Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
from openmdao.api import ArmijoGoldsteinLS, Problem, IndepVarComp, BalanceComp, ExecComp
from openmdao.api import NewtonSolver, DirectSolver, NonlinearRunOnce, LinearRunOnce
p = Problem()
model = p.model
model.add_subsystem('ground', IndepVarComp('V', 0., units='V'))
# replacing the fixed current source with a BalanceComp to represent a fixed Voltage source
# model.add_subsystem('source', IndepVarComp('I', 0.1, units='A'))
model.add_subsystem('batt', IndepVarComp('V', 1.5, units='V'))
bal = model.add_subsystem('batt_balance', BalanceComp())
bal.add_balance('I', units='A', eq_units='V')
model.add_subsystem('circuit', Circuit())
model.add_subsystem('batt_deltaV', ExecComp('dV = V1 - V2', V1={'units':'V'}, V2={'units':'V'}, dV={'units':'V'}))
# current into the circuit is now the output state from the batt_balance comp
model.connect('batt_balance.I', 'circuit.I_in')
model.connect('ground.V', ['circuit.Vg','batt_deltaV.V2'])
model.connect('circuit.n1.V', 'batt_deltaV.V1')
# set the lhs and rhs for the battery residual
model.connect('batt.V', 'batt_balance.rhs:I')
model.connect('batt_deltaV.dV', 'batt_balance.lhs:I')
p.setup()
###################
# Solver Setup
###################
'parallel.%s.states_comp.K_local' % name)
for k in range(num_rhs):
sub.connect(
'states_comp.d_%d' % k,
'displacements_comp.d_%d' % k)
sub.connect(
'displacements_comp.displacements_%d' % k,
'compliance_comp.displacements_%d' % k)
obj_srcs.append('parallel.%s.compliance_comp.compliance_%d' % (name, k))
comp = VolumeComp(num_elements=num_elements, b=b, L=L)
self.add_subsystem('volume_comp', comp)
comp = om.ExecComp(['obj = ' + ' + '.join(['compliance_%d' % i for i in range(num_load_cases)])])
self.add_subsystem('obj_sum', comp)
for j, src in enumerate(obj_srcs):
self.connect(src, 'obj_sum.compliance_%d' % j)
self.connect('inputs_comp.h_cp', 'interp.h_cp')
self.connect('interp.h', 'I_comp.h')
self.connect('I_comp.I', 'local_stiffness_matrix_comp.I')
self.connect('interp.h', 'volume_comp.h')
self.add_design_var('inputs_comp.h_cp', lower=1e-2, upper=10.)
self.add_constraint('volume_comp.volume', equals=volume)
self.add_objective('obj_sum.obj')
def setup(self):
indeps = self.add_subsystem('indeps', om.IndepVarComp(), promotes=['*'])
indeps.add_output('x', 1.0)
indeps.add_output('z', np.array([5.0, 2.0]))
cycle = self.add_subsystem('cycle', om.Group(), promotes=['*'])
cycle.add_subsystem('d1', SellarDis1(), promotes_inputs=['x', 'z', 'y2'],
promotes_outputs=['y1'])
cycle.add_subsystem('d2', SellarDis2(), promotes_inputs=['z', 'y1'],
promotes_outputs=['y2'])
# Nonlinear Block Gauss Seidel is a gradient free solver
cycle.nonlinear_solver =om. NonlinearBlockGS()
self.add_subsystem('obj_cmp', om.ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',
z=np.array([0.0, 0.0]), x=0.0),
promotes=['x', 'z', 'y1', 'y2', 'obj'])
self.add_subsystem('con_cmp1', om.ExecComp('con1 = 3.16 - y1'),
promotes=['con1', 'y1'])
self.add_subsystem('con_cmp2', om.ExecComp('con2 = y2 - 24.0'),
promotes=['con2', 'y2'])
def test_constrained(self):
import openmdao.api as om
# We'll use the component that was defined in the last tutorial
from openmdao.test_suite.components.paraboloid import Paraboloid
# build the model
prob = om.Problem()
indeps = prob.model.add_subsystem('indeps', om.IndepVarComp())
indeps.add_output('x', 3.0)
indeps.add_output('y', -4.0)
prob.model.add_subsystem('parab', Paraboloid())
# define the component whose output will be constrained
prob.model.add_subsystem('const', om.ExecComp('g = x + y'))
prob.model.connect('indeps.x', ['parab.x', 'const.x'])
prob.model.connect('indeps.y', ['parab.y', 'const.y'])
# setup the optimization
prob.driver = om.ScipyOptimizeDriver()
prob.driver.options['optimizer'] = 'COBYLA'
prob.model.add_design_var('indeps.x', lower=-50, upper=50)
prob.model.add_design_var('indeps.y', lower=-50, upper=50)
prob.model.add_objective('parab.f_xy')
# to add the constraint to the model
prob.model.add_constraint('const.g', lower=0, upper=10.)
# prob.model.add_constraint('const.g', equals=0.)
def test_paraboloid_optimize_constrained(self):
top = Problem()
root = top.root = Group()
root.add('p1', IndepVarComp('x', 3.0))
root.add('p2', IndepVarComp('y', -4.0))
root.add('p', ParaboloidOptCon())
# Constraint Equation
root.add('con', ExecComp('c = x-y'))
root.connect('p1.x', 'p.x')
root.connect('p2.y', 'p.y')
root.connect('p.x', 'con.x')
root.connect('p.y', 'con.y')
top.driver = ScipyOptimizer()
top.driver.options['optimizer'] = 'SLSQP'
top.driver.options['disp'] = False
top.driver.add_desvar('p1.x', lower=-50, upper=50)
top.driver.add_desvar('p2.y', lower=-50, upper=50)
top.driver.add_objective('p.f_xy')
top.driver.add_constraint('con.c', lower=15.0)
top.setup(check=False)
def setup(self):
sub = self.add_subsystem('sub', om.ParallelGroup())
sub1 = sub.add_subsystem('sub1', om.Group())
sub2 = sub.add_subsystem('sub2', om.Group())
sub1.add_subsystem('p1', om.IndepVarComp('x', 3.0))
sub2.add_subsystem('p2', om.IndepVarComp('x', 5.0))
sub1.add_subsystem('c1', om.ExecComp(['y = 2.0*x']))
sub2.add_subsystem('c2', om.ExecComp(['y = 4.0*x']))
sub1.connect('p1.x', 'c1.x')
sub2.connect('p2.x', 'c2.x')
self.add_subsystem('sum',om. ExecComp(['y = z1 + z2']))
self.connect('sub.sub1.c1.y', 'sum.z1')
self.connect('sub.sub2.c2.y', 'sum.z2')
self.sub.sub1.add_design_var('p1.x')
self.sub.sub2.add_design_var('p2.x')
self.add_objective('sum.y')
from openmdao.api import ParallelGroup, Group, Problem, IndepVarComp, \
ExecComp, LinearGaussSeidel
from openmdao.core.mpi_wrap import MPI
from openmdao.test.mpi_util import MPITestCase
from openmdao.test.util import assert_rel_error
from openmdao.util.array_util import evenly_distrib_idxs
if MPI:
from openmdao.core.petsc_impl import PetscImpl as impl
rank = MPI.COMM_WORLD.rank
else:
from openmdao.core.basic_impl import BasicImpl as impl
rank = 0
class DistribExecComp(ExecComp):
"""An ExecComp that uses 2 procs and
takes input var slices and has output var slices as well.
"""
def __init__(self, exprs, arr_size=11, **kwargs):
super(DistribExecComp, self).__init__(exprs, **kwargs)
self.arr_size = arr_size
def setup_distrib(self):
""" component declares the local sizes and sets initial values
for all distributed inputs and outputs. Returns a dict of
index arrays keyed to variable names.
"""
comm = self.comm
rank = comm.rank
sizes, offsets = evenly_distrib_idxs(comm.size, self.arr_size)
"""
import openmdao.api as om
p = om.Problem()
dvs = p.model.add_subsystem('design_vars', om.IndepVarComp(), promotes=['*'])
dvs.add_output('x_aero')
dvs.add_output('x_struct')
aerostruct = p.model.add_subsystem('aerostruct_cycle', om.Group(), promotes=['*'])
#note the equations don't matter... just need a simple way to get inputs and outputs there
aerostruct.add_subsystem('aero',
om.ExecComp(['w = u+x_aero', 'Cl=u+x_aero', 'Cd = u + x_aero']),
promotes=['*'])
aerostruct.add_subsystem('struct', om.ExecComp(['u = w+x_struct', 'mass=x_struct']),
promotes=['*'])
p.model.add_subsystem('objective', om.ExecComp('f=mass+Cl/Cd'), promotes=['*'])
p.model.add_subsystem('constraint', om.ExecComp('g=Cl'), promotes=['*'])
p.setup()
om.n2(p, outfile='aerostruct_n2.html', embeddable=True, show_browser=False)
elif genType.lower() == 'eesg':
mygen = EESG
elif genType.lower() == 'pmsg_arms':
mygen = PMSG_Arms
elif genType.lower() == 'pmsg_disc':
mygen = PMSG_Disc
self.add_subsystem('generator', mygen(), promotes=['*'])
self.add_subsystem('gen_cost', Generator_Cost(), promotes=['*'])
# Now add constraints
if genType.lower() in ['eesg', 'pmsg_arms', 'pmsg_disc']:
self.add_subsystem('con_uAs', ExecComp('con_uAs =u_all_s-u_As'),promotes=['*'])
self.add_subsystem('con_zAs', ExecComp('con_zAs =z_all_s-z_A_s'),promotes=['*'])
self.add_subsystem('con_yAs', ExecComp('con_yAs =y_all-y_As'),promotes=['*'])
self.add_subsystem('con_bst', ExecComp('con_bst =b_all_s-b_st',
b_st={'units':'m'}), promotes=['*'])
self.add_subsystem('con_uAr', ExecComp('con_uAr =u_all_r-u_Ar'),promotes=['*'])
self.add_subsystem('con_yAr', ExecComp('con_yAr =y_all-y_Ar'),promotes=['*'])
self.add_subsystem('con_TC2', ExecComp('con_TC2 =TC2-TC1'),promotes=['*'])
self.add_subsystem('con_TC3', ExecComp('con_TC3 =TC3-TC1'),promotes=['*'])
if genType.lower() in ['pmsg_arms', 'pmsg_disc']:
self.add_subsystem('con_Bsmax', ExecComp('con_Bsmax =B_g-B_smax'),promotes=['*'])
if genType.lower() in ['eesg', 'pmsg_arms']:
self.add_subsystem('con_zAr', ExecComp('con_zAr =z_all_r-z_A_r'),promotes=['*'])
self.add_subsystem('con_br', ExecComp('con_br =b_all_r-b_r',
b_r={'units':'m'}), promotes=['*'])
prob.model.connect('RTO.balance.hpt_chrg_cool_frac', 'TOC.bld3.bld_exit:frac_W')
prob.model.connect('RTO.balance.hpt_nochrg_cool_frac', 'TOC.bld3.bld_inlet:frac_W')
prob.model.connect('RTO.balance.hpt_chrg_cool_frac', 'SLS.bld3.bld_exit:frac_W')
prob.model.connect('RTO.balance.hpt_nochrg_cool_frac', 'SLS.bld3.bld_inlet:frac_W')
prob.model.connect('RTO.balance.hpt_chrg_cool_frac', 'CRZ.bld3.bld_exit:frac_W')
prob.model.connect('RTO.balance.hpt_nochrg_cool_frac', 'CRZ.bld3.bld_inlet:frac_W')
prob.model.connect('splitter:BPR', 'TOC.splitter.BPR')
prob.model.connect('TOC:W', 'TOC.fc.W')
prob.model.connect('CRZ:Fn_target', 'CRZ.balance.rhs:FAR')
prob.model.connect('SLS:Fn_target', 'SLS.balance.rhs:FAR')
prob.model.add_subsystem('T4_ratio',
om.ExecComp('TOC_T4 = RTO_T4*TR',
RTO_T4={'value': 3400.0, 'units':'degR'},
TOC_T4={'value': 3150.0, 'units':'degR'},
TR={'value': 0.926470588, 'units': None}))
prob.model.connect('RTO:T4max','T4_ratio.RTO_T4')
prob.model.connect('T4_ratio.TOC_T4', 'TOC.balance.rhs:FAR')
prob.model.connect('TR', 'T4_ratio.TR')
prob.model.set_order(['des_vars', 'T4_ratio', 'TOC', 'RTO', 'SLS', 'CRZ'])
newton = prob.model.nonlinear_solver = om.NewtonSolver()
newton.options['atol'] = 1e-6
newton.options['rtol'] = 1e-6
newton.options['iprint'] = 2
newton.options['maxiter'] = 20
newton.options['solve_subsystems'] = True
newton.options['max_sub_solves'] = 10