def test_simple_Jacobian(self): # Tests that we can correctly handle user-defined Jacobians. empty = {} params = {'x': 0.0} unknowns = {'y': 0.0} mycomp = ExecComp(['y=2.0*x']) mycomp._jacobian_cache = mycomp.linearize(params, unknowns, empty) # Forward dparams = {} dparams['x'] = np.array([3.1]) dresids = {} dresids['y'] = np.array([0.0]) mycomp.apply_linear(empty, empty, dparams, empty, dresids, 'fwd') self.assertEqual(dresids['y'], 6.2) # Reverse dparams = {} dparams['x'] = np.array([0.0]) dresids = {} dresids['y'] = np.array([3.1]) mycomp.apply_linear(empty, empty, dparams, empty, dresids, 'rev') self.assertEqual(dparams['x'], 6.2)
def test_mode_auto(self): # Make sure mode=auto chooses correctly for all prob sizes as well # as for abs/rel/etc paths prob = Problem() root = prob.root = Group() root.add('p1', IndepVarComp('a', 1.0), promotes=['*']) root.add('p2', IndepVarComp('b', 1.0), promotes=['*']) root.add('comp', ExecComp(['x = 2.0*a + 3.0*b', 'y=4.0*a - 1.0*b']), promotes=['*']) root.ln_solver.options['mode'] = 'auto' prob.setup(check=False) prob.run() mode = prob._mode('auto', ['a'], ['x']) self.assertEqual(mode, 'fwd') mode = prob._mode('auto', ['a', 'b'], ['x']) self.assertEqual(mode, 'rev') # make sure _check function does it too #try: #mode = prob._check_for_parallel_derivs(['a'], ['x'], False, False) #except Exception as err: #msg = "Group '' must have the same mode as root to use Matrix Matrix." #self.assertEqual(text_type(err), msg) #else: #self.fail('Exception expected') # Cheat a bit so I can twiddle mode OptionsDictionary.locked = False root.ln_solver.options['mode'] = 'fwd' mode = prob._check_for_parallel_derivs(['a', 'b'], ['x'], False, False) self.assertEqual(mode, 'fwd')
def test_raise_no_error_on_singular(self): prob = Problem() model = prob.model comp = IndepVarComp() comp.add_output('dXdt:TAS', val=1.0) comp.add_output('accel_target', val=2.0) model.add_subsystem('des_vars', comp, promotes=['*']) teg = model.add_subsystem('thrust_equilibrium_group', subsys=Group()) teg.add_subsystem('dynamics', ExecComp('z = 2.0*thrust'), promotes=['*']) thrust_bal = BalanceComp() thrust_bal.add_balance(name='thrust', val=1207.1, lhs_name='dXdt:TAS', rhs_name='accel_target', eq_units='m/s**2', lower=-10.0, upper=10000.0) teg.add_subsystem(name='thrust_bal', subsys=thrust_bal, promotes_inputs=['dXdt:TAS', 'accel_target'], promotes_outputs=['thrust']) teg.linear_solver = DirectSolver(assemble_jac=False) teg.nonlinear_solver = NewtonSolver() teg.nonlinear_solver.options['solve_subsystems'] = True teg.nonlinear_solver.options['max_sub_solves'] = 1 teg.nonlinear_solver.options['atol'] = 1e-4 prob.setup(check=False) prob.set_solver_print(level=0) teg.linear_solver.options['err_on_singular'] = False prob.run_model()
def test_relevancy_for_newton(self): class TestImplCompSimple(ImplicitComponent): def setup(self): self.add_input('a', val=1.) self.add_output('x', val=0.) self.declare_partials(of='*', wrt='*') def apply_nonlinear(self, inputs, outputs, residuals): residuals['x'] = np.exp(outputs['x']) - \ inputs['a']**2 * outputs['x']**2 def linearize(self, inputs, outputs, jacobian): jacobian['x', 'x'] = np.exp(outputs['x']) - \ 2 * inputs['a']**2 * outputs['x'] jacobian['x', 'a'] = -2 * inputs['a'] * outputs['x']**2 prob = Problem() model = prob.model model.add_subsystem('p1', IndepVarComp('x', 3.0)) model.add_subsystem('icomp', TestImplCompSimple()) model.add_subsystem('ecomp', ExecComp('y = x*p', p=1.0)) model.connect('p1.x', 'ecomp.x') model.connect('icomp.x', 'ecomp.p') model.add_design_var('p1.x', 3.0) model.add_objective('ecomp.y') model.nonlinear_solver = NewtonSolver() model.linear_solver = ScipyKrylov() prob.setup(check=False) prob.run_model() J = prob.compute_totals() assert_rel_error(self, J['ecomp.y', 'p1.x'][0][0], -0.703467422498, 1e-6)
def __init__(self): super(DFIG_Opt, self).__init__() self.add('machine_rating', IndepVarComp('machine_rating', val=0.0), promotes=['*']) self.add('n_nom', IndepVarComp('n_nom', val=0.0), promotes=['*']) self.add('highSpeedSide_cm', IndepVarComp('highSpeedSide_cm', val=np.array([0.0, 0.0, 0.0])), promotes=['*']) self.add('highSpeedSide_length', IndepVarComp('highSpeedSide_length', val=0.0), promotes=['*']) self.add('Gearbox_efficiency', IndepVarComp('Gearbox_efficiency', val=0.0), promotes=['*']) self.add('r_s', IndepVarComp('r_s', val=0.0), promotes=['*']) self.add('l_s', IndepVarComp('l_s', val=0.0), promotes=['*']) self.add('h_s', IndepVarComp('h_s', val=0.0), promotes=['*']) self.add('h_r', IndepVarComp('h_r', val=0.0), promotes=['*']) self.add('S_Nmax', IndepVarComp('S_Nmax', val=0.0), promotes=['*']) self.add('B_symax', IndepVarComp('B_symax', val=0.0), promotes=['*']) self.add('I_0', IndepVarComp('I_0', val=0.0), promotes=['*']) self.add('rho_Fe', IndepVarComp('rho_Fe', 0.0), promotes=['*']) self.add('rho_Copper', IndepVarComp('rho_Copper', 0.0), promotes=['*']) # add DFIG component, create constraint equations self.add('DFIG', DFIG(), promotes=['*']) self.add('TC', ExecComp('TC =TC2-TC1'), promotes=['*']) # add DFIG_Cost component self.add('DFIG_Cost', DFIG_Cost(), promotes=['*']) self.add('C_Cu', IndepVarComp('C_Cu', val=0.0), promotes=['*']) self.add('C_Fe', IndepVarComp('C_Fe', val=0.0), promotes=['*']) self.add('C_Fes', IndepVarComp('C_Fes', val=0.0), promotes=['*'])
def test_create_on_init(self): prob = Problem(model=Group()) bal = BalanceComp('x', val=1.0) tgt = IndepVarComp(name='y_tgt', val=2) exec_comp = ExecComp('y=x**2') prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt']) prob.model.add_subsystem(name='exec', subsys=exec_comp) prob.model.add_subsystem(name='balance', subsys=bal) prob.model.connect('y_tgt', 'balance.rhs:x') prob.model.connect('balance.x', 'exec.x') prob.model.connect('exec.y', 'balance.lhs:x') prob.model.linear_solver = DirectSolver() prob.model.nonlinear_solver = NewtonSolver() prob.setup() prob.run_model() assert_almost_equal(prob['balance.x'], np.sqrt(2), decimal=7) # Assert that normalization is happening assert_almost_equal(prob.model.balance._scale_factor, 1.0 / np.abs(2)) cpd = prob.check_partials(out_stream=None) for (of, wrt) in cpd['balance']: assert_almost_equal(cpd['balance'][of, wrt]['abs error'], 0.0, decimal=5)
def test_rhs_val(self): """ Test solution with a default RHS value and no connected RHS variable. """ n = 1 prob = Problem(model=Group()) bal = BalanceComp('x', rhs_val=4.0) exec_comp = ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) prob.model.add_subsystem(name='exec', subsys=exec_comp) prob.model.add_subsystem(name='balance', subsys=bal) prob.model.connect('balance.x', 'exec.x') prob.model.connect('exec.y', 'balance.lhs:x') prob.model.linear_solver = DirectSolver() prob.model.nonlinear_solver = NewtonSolver() prob.model.nonlinear_solver.options['maxiter'] = 100 prob.model.nonlinear_solver.options['iprint'] = 0 prob.model.jacobian = DenseJacobian() prob.setup() prob['balance.x'] = np.random.rand(n) prob.run_model() assert_almost_equal(prob['balance.x'], 2.0, decimal=7) np.set_printoptions(linewidth=1024) cpd = prob.check_partials() for (of, wrt) in cpd['balance']: assert_almost_equal(cpd['balance'][of, wrt]['abs error'], 0.0, decimal=5)
def test_complex_step2_colons(self): prob = Problem(Group()) comp = prob.root.add('comp', ExecComp('foo:y=foo:x*foo:x + foo:x*2.0')) prob.root.add('p1', IndepVarComp('x', 2.0)) prob.root.connect('p1.x', 'comp.foo:x') comp.deriv_options['type'] = 'user' prob.setup(check=False) prob.run() J = prob.calc_gradient(['p1.x'], ['comp.foo:y'], mode='fwd', return_format='dict') assert_rel_error(self, J['comp.foo:y']['p1.x'], np.array([6.0]), 0.00001) J = prob.calc_gradient(['p1.x'], ['comp.foo:y'], mode='rev', return_format='dict') assert_rel_error(self, J['comp.foo:y']['p1.x'], np.array([6.0]), 0.00001)
def test_common_shape_with_values(self): p = Problem() model = p.model model.add_subsystem('indep', IndepVarComp('x', val=np.ones(5))) model.add_subsystem( 'comp', ExecComp('y=3.0*x + 2.5', shape=(5, ), x={'value': np.zeros(5)}, y={'value': np.zeros(5)})) model.connect('indep.x', 'comp.x') p.setup() p.run_model() J = p.compute_totals(of=['comp.y'], wrt=['indep.x'], return_format='array') assert_almost_equal(J, np.eye(5) * 3., decimal=6)
def setup(self): shape = self.options['shape'] # comp = IndepVarComp() # comp.add_output('hover_wing_angular_speed') # # if design variable, add as output in IVC # self.add_subsystem('inputs_comp', comp, promotes = ['*']) # make connections in run_group (aero_geom_group to this one for wing_span) # r = b/2/(cos(sweep)) comp = ExecComp('radius = wing_span/2/(cos(sweep*pi/180))', shape=shape) self.add_subsystem('radius_comp', comp, promotes=['*']) # ExecComp defines the equation and calculates given the equation/inputs # Need to connect sweep/wingspan to this Group and then can compute the # hover velocity below # V = 2pi*RPM/60*.75*radius or V = 2pi*RPM/60*.75* b/2/(cos(sweep)) # V = omega * r comp = PowerCombinationComp(shape=shape, coeff=.75, out_name='hover_drag_velocity', powers_dict=dict( hover_wing_angular_speed=1., radius=1., )) self.add_subsystem('hover_drag_velocity_comp', comp, promotes=['*']) comp = PowerCombinationComp(shape=shape, coeff=.5, out_name='hover_torque_velocity', powers_dict=dict( hover_wing_angular_speed=1., wing_span=1., )) self.add_subsystem('hover_torque_velocity_comp', comp, promotes=['*'])
def test_multi_dim_src_indices(self): prob = Problem() model = prob.model size = 5 model.add_subsystem( 'indeps', IndepVarComp('x', np.arange(5).reshape((1, size, 1)))) model.add_subsystem( 'comp', ExecComp('y = x * 2.', x=np.zeros((size, )), y=np.zeros((size, )))) src_indices = [[0, i, 0] for i in range(size)] model.connect('indeps.x', 'comp.x', src_indices=src_indices) model.linear_solver = DirectSolver() prob.setup() prob.run_model() J = prob.compute_totals(wrt=['indeps.x'], of=['comp.y'], return_format='array') np.testing.assert_almost_equal(J, np.eye(size) * 2.)
def test_setup_bad_mode_direction_fwd(self): prob = Problem() prob.model.add_subsystem("indep", IndepVarComp("x", np.ones(99))) prob.model.add_subsystem("C1", ExecComp("y=2.0*x", x=np.zeros(10), y=np.zeros(10))) prob.model.connect("indep.x", "C1.x", src_indices=list(range(10))) prob.model.add_design_var("indep.x") prob.model.add_objective("C1.y") prob.setup(mode='fwd') with warnings.catch_warnings(record=True) as w: prob.final_setup() self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[0].category, RuntimeWarning)) self.assertEqual(str(w[0].message), "Inefficient choice of derivative mode. " "You chose 'fwd' for a problem with 99 design variables and 10 " "response variables (objectives and constraints).")
def test_raised_error_sensfunc(self): # Component fails hard this time during gradient eval, so we expect # pyoptsparse to raise. prob = Problem() model = prob.model = Group() model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) comp = model.add_subsystem('comp', ParaboloidAE(), promotes=['*']) model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) prob.driver = pyOptSparseDriver() # SNOPT has a weird cleanup problem when this fails, so we use SLSQP. For the # regular failure, it doesn't matter which opt we choose since they all fail through. prob.driver.options['optimizer'] = 'SLSQP' prob.driver.opt_settings['ACC'] = 1e-9 prob.driver.options['print_results'] = False model.add_design_var('x', lower=-50.0, upper=50.0) model.add_design_var('y', lower=-50.0, upper=50.0) model.add_objective('f_xy') model.add_constraint('c', upper=-15.0) comp.fail_hard = True comp.grad_fail_at = 2 comp.eval_fail_at = 100 prob.setup(check=False) with self.assertRaises(Exception) as err: prob.run_driver() # pyopt's failure message differs by platform and is not informative anyway del prob
def setup(self): # Outer diameter is fixed (mm) od_fixed = 139.7 # Convert to radius (m) or_fixed = od_fixed * 0.5 * .001 # Build model indeps = self.add_subsystem('p', IndepVarComp(), promotes=['*']) indeps.add_output('ID_OD_ratio', 0.5) indeps.add_output('outer_radius', or_fixed, units='m') self.add_subsystem('calc_inner_radius', ExecComp( ['inner_radius = ID_OD_ratio * outer_radius']), promotes=['*']) self.add_subsystem('motor', DoubleHalbachMotorComp(overlap=True), promotes=['*'])
def test_remote_voi(self): prob = Problem() par = prob.model.add_subsystem('par', ParallelGroup()) prob.model.par.add_subsystem('G1', Mygroup()) prob.model.par.add_subsystem('G2', Mygroup()) prob.model.add_subsystem('Obj', ExecComp('obj=y1+y2')) prob.model.connect('par.G1.y', 'Obj.y1') prob.model.connect('par.G2.y', 'Obj.y2') prob.model.add_objective('Obj.obj') prob.driver = pyOptSparseDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.setup() self.assertEqual('par.G1', par.G1.pathname) self.assertEqual('par.G2', par.G2.pathname) prob.run_driver() J = prob.compute_totals(of=['Obj.obj', 'par.G1.c', 'par.G2.c'], wrt=['par.G1.x', 'par.G2.x']) assert_rel_error(self, J['Obj.obj', 'par.G1.x'], np.array([[2.0]]), 1e-6) assert_rel_error(self, J['Obj.obj', 'par.G2.x'], np.array([[2.0]]), 1e-6) assert_rel_error(self, J['par.G1.c', 'par.G1.x'], np.array([[1.0]]), 1e-6) assert_rel_error(self, J['par.G1.c', 'par.G2.x'], np.array([[0.0]]), 1e-6) assert_rel_error(self, J['par.G2.c', 'par.G1.x'], np.array([[0.0]]), 1e-6) assert_rel_error(self, J['par.G2.c', 'par.G2.x'], np.array([[1.0]]), 1e-6)
def test_abs_complex_step(self): prob = Problem(model=Group()) C1 = prob.model.add_subsystem('C1', ExecComp('y=2.0*abs(x)', x=-2.0)) prob.setup(check=False) prob.set_solver_print(level=0) prob.run_model() assert_rel_error(self, C1._outputs['y'], 4.0, 0.00001) # any positive C1.x should give a 2.0 derivative for dy/dx C1._inputs['x'] = 1.0e-10 C1._linearize() assert_rel_error(self, C1._jacobian['y', 'x'], [[2.0]], 0.00001) C1._inputs['x'] = -3.0 C1._linearize() assert_rel_error(self, C1._jacobian['y', 'x'], [[-2.0]], 0.00001) C1._inputs['x'] = 0.0 C1._linearize() assert_rel_error(self, C1._jacobian['y', 'x'], [[2.0]], 0.00001)
def test_create_on_init(self): prob = Problem(model=Group()) bal = BalanceComp('x', val=1.0) tgt = IndepVarComp(name='y_tgt', val=2) exec_comp = ExecComp('y=x**2') prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt']) prob.model.add_subsystem(name='exec', subsys=exec_comp) prob.model.add_subsystem(name='balance', subsys=bal) prob.model.connect('y_tgt', 'balance.rhs:x') prob.model.connect('balance.x', 'exec.x') prob.model.connect('exec.y', 'balance.lhs:x') prob.model.linear_solver = DirectSolver() prob.model.nonlinear_solver = NewtonSolver() prob.setup() prob.run_model() assert_almost_equal(prob['balance.x'], np.sqrt(2), decimal=7) np.set_printoptions(linewidth=1024) cpd = prob.check_partials() for (of, wrt) in cpd['balance']: assert_almost_equal(cpd['balance'][of, wrt]['abs error'], 0.0, decimal=5)
def test_no_derivatives(self): prob = Problem() prob.root = Group() comp = prob.root.add('comp', ExecComp('y=x*2.0')) prob.root.add('p1', IndepVarComp('x', 2.0)) prob.root.connect('p1.x', 'comp.x') comp.fd_options['force_fd'] = True prob.setup(check=False) prob.run() J = prob.calc_gradient(['p1.x'], ['comp.y'], mode='fwd', return_format='dict') assert_rel_error(self, J['comp.y']['p1.x'][0][0], 2.0, 1e-6) J = prob.calc_gradient(['p1.x'], ['comp.y'], mode='rev', return_format='dict') assert_rel_error(self, J['comp.y']['p1.x'][0][0], 2.0, 1e-6)
def test_duplicate_src_indices(self): size = 10 root = Group() root.add('P1', IndepVarComp('x', np.zeros(size // 2))) root.add('C1', ExecComp('y = x**2', y=np.zeros(size), x=np.zeros(size))) root.connect('P1.x', "C1.x", src_indices=2 * list(range(size // 2))) prob = Problem(root) prob.setup(check=False) prob["P1.x"] = np.arange(5, dtype=float) prob.run() r = np.arange(5, dtype=float)**2 expected = np.concatenate((r, r)) assert_almost_equal(prob["C1.y"], expected, decimal=7)
def test_one_src_2_tgts_csc_error(self): size = 10 prob = Problem() indeps = prob.model.add_subsystem('indeps', IndepVarComp('x', np.ones(size))) G1 = prob.model.add_subsystem('G1', Group()) G1.add_subsystem('C1', ExecComp('z=2.0*y+3.0*x', x=np.zeros(size), y=np.zeros(size), z=np.zeros(size))) prob.model.linear_solver = DirectSolver(assemble_jac=True) prob.model.add_objective('G1.C1.z') prob.model.add_design_var('indeps.x') prob.model.connect('indeps.x', 'G1.C1.x') prob.model.connect('indeps.x', 'G1.C1.y') prob.setup(mode='fwd') prob.run_model() J = prob.compute_totals(of=['G1.C1.z'], wrt=['indeps.x']) assert_near_equal(J['G1.C1.z', 'indeps.x'], np.eye(10)*5.0, .0001)
def test_connect_incompatible_shapes(self): p = Problem() p.model.add_subsystem('indep', IndepVarComp('x', val=np.arange(10)[np.newaxis, :, np.newaxis, np.newaxis])) p.model.add_subsystem('C1', ExecComp('y=5*x', x={'value': np.zeros((5, 2))}, y={'value': np.zeros((5, 2))})) p.model.connect('indep.x', 'C1.x') expected = "Group (<model>): The source and target shapes do not match or are " + \ "ambiguous for the connection 'indep.x' to 'C1.x'. The source shape is " + \ "(1, 10, 1, 1) but the target shape is (5, 2)." with self.assertRaises(Exception) as context: p.setup() self.assertEqual(str(context.exception), expected) p.model._raise_connection_errors = False with assert_warning(UserWarning, expected): p.setup()
def test_vectorize_error(self): p = Problem() model = p.model model.add_subsystem('indep', IndepVarComp('x', val=np.ones(3))) model.add_design_var('indep.x') mat = np.arange(15).reshape((3, 5)) model.add_subsystem( 'comp', ExecComp('y=A.dot(x)', vectorize=True, A=mat, x=np.ones(5), y=np.ones(3))) model.connect('indep.x', 'comp.x') with self.assertRaises(Exception) as context: p.setup() self.assertEqual( str(context.exception), "comp: vectorize is True but partial(y, A) is not square (shape=(3, 15))." )
def test_feature_scalar_with_default_mult(self): from numpy.testing import assert_almost_equal from openmdao.api import Problem, Group, IndepVarComp, ExecComp, NewtonSolver, \ DirectSolver, BalanceComp prob = Problem(model=Group(assembled_jac_type='dense')) bal = BalanceComp() bal.add_balance('x', use_mult=True, mult_val=2.0) tgt = IndepVarComp(name='y_tgt', val=4) exec_comp = ExecComp('y=x**2', x={'value': 1}, y={'value': 1}) prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt']) prob.model.add_subsystem(name='exec', subsys=exec_comp) prob.model.add_subsystem(name='balance', subsys=bal) prob.model.connect('y_tgt', 'balance.rhs:x') prob.model.connect('balance.x', 'exec.x') prob.model.connect('exec.y', 'balance.lhs:x') prob.model.linear_solver = DirectSolver(assemble_jac=True) prob.model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) prob.setup(check=False) # A reasonable initial guess to find the positive root. prob['balance.x'] = 1.0 prob.run_model() print('x = ', prob['balance.x']) assert_almost_equal(prob['balance.x'], np.sqrt(2), decimal=7)
def test_basic(self): import numpy as np from openmdao.api import Problem, IndepVarComp, ExecComp from openmdao.components.ks import KSComponent prob = Problem() model = prob.model model.add_subsystem('px', IndepVarComp('x', val=np.array([5.0, 4.0]))) model.add_subsystem( 'comp', ExecComp('y = 3.0*x', x=np.zeros((2, )), y=np.zeros( (2, )))) model.add_subsystem('ks', KSComponent(width=2)) model.connect('px.x', 'comp.x') model.connect('comp.y', 'ks.g') prob.setup() prob.run_model() assert_rel_error(self, prob['ks.KS'], 15.0)
def test_repeated_src_indices_dense(self): size = 2 p = Problem() indeps = p.model.add_subsystem('indeps', IndepVarComp('x', np.ones(size))) p.model.add_subsystem( 'C1', ExecComp('z=3.0*x[0]**3 + 2.0*x[1]**2', x=np.zeros(size))) p.model.options['assembled_jac_type'] = 'dense' p.model.linear_solver = DirectSolver(assemble_jac=True) p.model.connect('indeps.x', 'C1.x', src_indices=[1, 1]) p.setup() p.run_model() J = p.compute_totals(of=['C1.z'], wrt=['indeps.x'], return_format='array') np.testing.assert_almost_equal( p.model._assembled_jac._int_mtx._matrix, np.array([[-1., 0., 0.], [0., -1., 0.], [0., 13., -1.]]))
def test_diff_conn_input_units_w_src(self): raise unittest.SkipTest("no compatability checking of connected inputs yet") p = Problem() root = p.model num_comps = 50 root.add_subsystem("desvars", IndepVarComp('dvar1', 1.0)) # add a bunch of comps for i in range(num_comps): if i % 2 == 0: units = "ft" else: units = "m" root.add_subsystem("C%d" % i, ExecComp('y=x*2.0', units={'x': units})) # connect all of their inputs (which have different units) for i in range(1, num_comps): root.connect("C%d.x" % (i-1), "C%d.x" % i) try: p.setup() except Exception as err: self.assertTrue("The following connected inputs have no source and different units" in str(err)) else: self.fail("Exception expected") # now, connect a source and the error should go away p.cleanup() root.connect('desvars.dvar1', 'C10.x') p.setup()
def test_two_simple(self): size = 3 group = Group() # import pydevd # pydevd.settrace('localhost', port=10000+MPI.COMM_WORLD.rank, # stdoutToServer=True, stderrToServer=True) group.add_subsystem('P', IndepVarComp('x', numpy.arange(size))) group.add_subsystem( 'C1', DistribExecComp(['y=2.0*x', 'y=3.0*x'], arr_size=size, x=numpy.zeros(size), y=numpy.zeros(size))) group.add_subsystem( 'C2', ExecComp(['z=3.0*y'], y=numpy.zeros(size), z=numpy.zeros(size))) prob = Problem() prob.model = group prob.model.linear_solver = LinearBlockGS() prob.model.connect('P.x', 'C1.x') prob.model.connect('C1.y', 'C2.y') prob.setup(check=False, mode='fwd') prob.run_model() J = prob.compute_totals(['C2.z'], ['P.x']) assert_rel_error(self, J['C2.z', 'P.x'], numpy.diag([6.0, 6.0, 9.0]), 1e-6) prob.setup(check=False, mode='rev') prob.run_model() J = prob.compute_totals(['C2.z'], ['P.x']) assert_rel_error(self, J['C2.z', 'P.x'], numpy.diag([6.0, 6.0, 9.0]), 1e-6)
def test_simple_array_comp2D_dbl_sided_con(self): prob = Problem() model = prob.model = Group() model.add_subsystem('p1', IndepVarComp('widths', np.zeros((2, 2))), promotes=['*']) model.add_subsystem('comp', TestExplCompArrayDense(), promotes=['*']) model.add_subsystem('obj', ExecComp('o = areas[0, 0]', areas=np.zeros( (2, 2))), promotes=['*']) prob.set_solver_print(level=0) prob.driver = ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False model.add_design_var('widths', lower=-50.0, upper=50.0) model.add_objective('o') model.add_constraint('areas', lower=np.array([24.0, 21.0, 3.5, 17.5]), upper=np.array([24.0, 21.0, 3.5, 17.5])) prob.setup(check=False) failed = prob.run_driver() self.assertFalse( failed, "Optimization failed, result =\n" + str(prob.driver.result)) con = prob['areas'] assert_rel_error(self, con, np.array([[24.0, 21.0], [3.5, 17.5]]), 1e-6)
def test_list_inputs_before_final_setup(self): class SpeedComp(ExplicitComponent): def setup(self): self.add_input('distance', val=1.0, units='km') self.add_input('time', val=1.0, units='h') self.add_output('speed', val=1.0, units='km/h') def compute(self, inputs, outputs): outputs['speed'] = inputs['distance'] / inputs['time'] prob = Problem() prob.model.add_subsystem('c1', SpeedComp(), promotes=['*']) prob.model.add_subsystem('c2', ExecComp('f=speed',speed={'units': 'm/s'}), promotes=['*']) prob.setup() msg = ("Calling `list_inputs` before `final_setup` will only " "display the default values of variables and will not show the result of " "any `set_val` calls.") with assert_warning(UserWarning, msg): prob.model.list_inputs(units=True, prom_name=True)
def test_one_src_2_tgts_with_src_indices_densejac(self): size = 4 prob = Problem(model=Group(assembled_jac_type='dense')) indeps = prob.model.add_subsystem('indeps', IndepVarComp('x', np.ones(size))) G1 = prob.model.add_subsystem('G1', Group()) G1.add_subsystem('C1', ExecComp('z=2.0*y+3.0*x', x=np.zeros(size//2), y=np.zeros(size//2), z=np.zeros(size//2))) prob.model.linear_solver = DirectSolver(assemble_jac=True) prob.model.add_objective('G1.C1.z') prob.model.add_design_var('indeps.x') prob.model.connect('indeps.x', 'G1.C1.x', src_indices=[0,1]) prob.model.connect('indeps.x', 'G1.C1.y', src_indices=[2,3]) prob.setup() prob.run_model() J = prob.compute_totals(of=['G1.C1.z'], wrt=['indeps.x']) assert_near_equal(J['G1.C1.z', 'indeps.x'], np.array([[ 3., 0., 2., 0.], [-0., 3., 0., 2.]]), .0001)
def test_connect_src_indices_noflat(self): import numpy as np from openmdao.api import Problem, IndepVarComp, ExecComp p = Problem() p.model.add_subsystem('indep', IndepVarComp('x', np.arange(12).reshape((4, 3)))) p.model.add_subsystem('C1', ExecComp('y=sum(x)*2.0', x=np.zeros((2, 2)))) # connect C1.x to entries (0,0), (-1,1), (2,1), (1,1) of indep.x p.model.connect('indep.x', 'C1.x', src_indices=[[(0, 0), (-1, 1)], [(2, 1), (1, 1)]], flat_src_indices=False) p.set_solver_print(level=0) p.setup() p.run_model() assert_rel_error(self, p['C1.x'], np.array([[0., 10.], [7., 4.]])) assert_rel_error(self, p['C1.y'], 42.)