Skip to content

Instantly share code, notes, and snippets.

@Kenneth-T-Moore
Created April 21, 2022 14:31
Show Gist options
  • Save Kenneth-T-Moore/9160a9df5ba7f5953ab037effaa042db to your computer and use it in GitHub Desktop.
Save Kenneth-T-Moore/9160a9df5ba7f5953ab037effaa042db to your computer and use it in GitHub Desktop.
Pyoptsparse linear constraint bug.
"""
Equivalent OpenMDAO example.
import numpy as np
import openmdao.api as om
prob = om.Problem()
model = prob.model
model.add_subsystem('comp', om.ExecComp(['y=2.0*x + 100', 'y2=3.0*x', 'obj=sum(-3.0*x**2)']))
model.add_design_var('comp.x', lower=0.01, upper=4.0)
model.add_objective('comp.obj')
model.add_constraint('comp.y', upper=2.0, linear=True)
model.add_constraint('comp.y2', upper=7.0)
prob.driver = om.pyOptSparseDriver(optimizer='SNOPT')
prob.setup()
prob.set_val('comp.x', 0)
prob.run_driver()
"""
import numpy as np
from pyoptsparse import SNOPT, Optimization
LINEAR = True
def objfunc(xdict):
"""Evaluates these equations:
obj = -3.0 * x**2
con1 = 2.0 * x + 100
con2 = 3.0 * x
"""
x = xdict["x"]
funcs = {}
funcs["obj"] = -3.0 * x**2
funcs["con2"] = 3.0 * x
if not LINEAR:
funcs["con1"] = 2.0 * x + 100
fail = False
return funcs, fail
def sens(xdict, funcs):
"""Derivatives"""
x = xdict["x"]
funcsSens = {}
funcsSens['obj'] = {"x": -6.0 * x}
funcsSens['con2'] = {"x": 3.0}
if not LINEAR:
funcsSens['con1'] = {"x": 2.0}
fail = False
return funcsSens, fail
# Optimization Object
optProb = Optimization("Test1", objfunc)
# Design Variables
optProb.addVarGroup("x", 1, varType="c", lower=0.1, upper=4.0, value=0.0)
# Objective
optProb.addObj("obj")
# Constraint
optProb.addConGroup("con2", 1, upper=7.0, wrt=["x"], linear=False)
# Linear Constraint
if LINEAR:
jac = {"x": 2.0}
optProb.addConGroup("con1", 1, upper=2.0, wrt=["x"], linear=LINEAR, jac=jac)
else:
optProb.addConGroup("con1", 1, upper=2.0, linear=False)
opt = SNOPT()
sol = opt(optProb, sens=sens)
print(sol)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment