def test_incompatible_connections(self): class BadComp(ExplicitComponent): def setup(self): self.add_input('x2', 100.0, units='m') self.add_output('x3', 100.0) # Explicit Connection prob = Problem() prob.model = Group() prob.model.add_subsystem('src', SrcComp()) prob.model.add_subsystem('dest', BadComp()) prob.model.connect('src.x2', 'dest.x2') with self.assertRaises(Exception) as cm: prob.setup(check=False) expected_msg = "Output units of 'degC' for 'src.x2' are incompatible with input units of 'm' for 'dest.x2'." self.assertEqual(expected_msg, str(cm.exception)) # Implicit Connection prob = Problem() prob.model = Group() prob.model.add_subsystem('src', SrcComp(), promotes=['x2']) prob.model.add_subsystem('dest', BadComp(),promotes=['x2']) with self.assertRaises(Exception) as cm: prob.setup(check=False) expected_msg = "Output units of 'degC' for 'src.x2' are incompatible with input units of 'm' for 'dest.x2'." self.assertEqual(expected_msg, str(cm.exception))
def test_sellar_opt(self): from openmdao.api import Problem, ScipyOptimizeDriver, ExecComp, IndepVarComp, DirectSolver from openmdao.test_suite.components.sellar_feature import SellarMDA prob = Problem() prob.model = SellarMDA() prob.driver = ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' # prob.driver.options['maxiter'] = 100 prob.driver.options['tol'] = 1e-8 prob.model.add_design_var('x', lower=0, upper=10) prob.model.add_design_var('z', lower=0, upper=10) prob.model.add_objective('obj') prob.model.add_constraint('con1', upper=0) prob.model.add_constraint('con2', upper=0) prob.setup() prob.set_solver_print(level=0) # Ask OpenMDAO to finite-difference across the model to compute the gradients for the optimizer prob.model.approx_totals() prob.run_driver() print('minimum found at') assert_rel_error(self, prob['x'][0], 0., 1e-5) assert_rel_error(self, prob['z'], [1.977639, 0.], 1e-5) print('minumum objective') assert_rel_error(self, prob['obj'][0], 3.18339395045, 1e-5)
def test_diamond(self): prob = Problem() prob.model = Diamond() prob.setup(vector_class=PETScVector, check=False, mode='fwd') prob.set_solver_print(level=0) prob.run_model() assert_rel_error(self, prob['c4.y1'], 46.0, 1e-6) assert_rel_error(self, prob['c4.y2'], -93.0, 1e-6) indep_list = ['iv.x'] unknown_list = ['c4.y1', 'c4.y2'] J = prob.compute_totals(of=unknown_list, wrt=indep_list) assert_rel_error(self, J['c4.y1', 'iv.x'][0][0], 25, 1e-6) assert_rel_error(self, J['c4.y2', 'iv.x'][0][0], -40.5, 1e-6) prob.setup(vector_class=PETScVector, check=False, mode='rev') prob.run_model() assert_rel_error(self, prob['c4.y1'], 46.0, 1e-6) assert_rel_error(self, prob['c4.y2'], -93.0, 1e-6) J = prob.compute_totals(of=unknown_list, wrt=indep_list) assert_rel_error(self, J['c4.y1', 'iv.x'][0][0], 25, 1e-6) assert_rel_error(self, J['c4.y2', 'iv.x'][0][0], -40.5, 1e-6)
def test_converge_diverge(self): prob = Problem() prob.model = ConvergeDiverge() prob.setup(vector_class=PETScVector, check=False, mode='fwd') prob.set_solver_print(level=0) prob.run_model() assert_rel_error(self, prob['c7.y1'], -102.7, 1e-6) indep_list = ['iv.x'] unknown_list = ['c7.y1'] J = prob.compute_totals(of=unknown_list, wrt=indep_list) assert_rel_error(self, J['c7.y1', 'iv.x'][0][0], -40.75, 1e-6) prob.setup(vector_class=PETScVector, check=False, mode='rev') prob.run_model() assert_rel_error(self, prob['c7.y1'], -102.7, 1e-6) J = prob.compute_totals(of=unknown_list, wrt=indep_list) assert_rel_error(self, J['c7.y1', 'iv.x'][0][0], -40.75, 1e-6) assert_rel_error(self, prob['c7.y1'], -102.7, 1e-6)
def test_api_iter_on_model(self): prob = Problem() prob.model = SellarDerivatives() prob.model.nonlinear_solver = NonlinearBlockGS() prob.model.add_design_var('x', lower=-100, upper=100) prob.model.add_design_var('z', lower=range(-101, -99), upper=range(99, 101), indices=range(2)) prob.model.add_objective('obj') prob.model.add_constraint('con1') prob.model.add_constraint('con2') prob.setup(check=False) des_vars = prob.model.get_design_vars() obj = prob.model.get_objectives() constraints = prob.model.get_constraints() self.assertEqual(set(des_vars.keys()), {'px.x', 'pz.z'}) self.assertEqual(set(obj.keys()), {'obj_cmp.obj',}) self.assertEqual(set(constraints.keys()), {'con_cmp1.con1', 'con_cmp2.con2'})
def test_feature_print_bound_enforce(self): import numpy as np from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, BoundsEnforceLS from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays top = Problem() top.model = Group() top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') newt = top.model.nonlinear_solver = NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 2 top.model.linear_solver = ScipyKrylov() ls = newt.linesearch = BoundsEnforceLS(bound_enforcement='vector') ls.options['print_bound_enforce'] = True top.set_solver_print(level=2) top.setup() # Test lower bounds: should go to the lower bound and stall top['px.x'] = 2.0 top['comp.y'] = 0. top['comp.z'] = 1.6 top.run_model() assert_rel_error(self, top['comp.z'][0], [1.5], 1e-8) assert_rel_error(self, top['comp.z'][1], [1.5], 1e-8) assert_rel_error(self, top['comp.z'][2], [1.5], 1e-8)
def test_feature_boundscheck_scalar(self): import numpy as np from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, BoundsEnforceLS from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays top = Problem() top.model = Group() top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') top.model.nonlinear_solver = NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 10 top.model.linear_solver = ScipyKrylov() ls = top.model.nonlinear_solver.linesearch = BoundsEnforceLS() ls.options['bound_enforcement'] = 'scalar' top.setup(check=False) top.run_model() # Test lower bounds: should stop just short of the lower bound top['px.x'] = 2.0 top['comp.y'] = 0. top['comp.z'] = 1.6 top.run_model() print(top['comp.z'][0]) print(top['comp.z'][1]) print(top['comp.z'][2])
def test_concurrent_eval_padded(self): # This test only makes sure we don't lock up if we overallocate our integer desvar space # to the next power of 2. class GAGroup(Group): def setup(self): self.add_subsystem('p1', IndepVarComp('x', 1.0)) self.add_subsystem('p2', IndepVarComp('y', 1.0)) self.add_subsystem('p3', IndepVarComp('z', 1.0)) self.add_subsystem('comp', ExecComp(['f = x + y + z'])) self.add_design_var('p1.x', lower=-100, upper=100) self.add_design_var('p2.y', lower=-100, upper=100) self.add_design_var('p3.z', lower=-100, upper=100) self.add_objective('comp.f') prob = Problem() prob.model = GAGroup() driver = prob.driver = SimpleGADriver() driver.options['max_gen'] = 5 driver.options['pop_size'] = 40 driver.options['run_parallel'] = True prob.setup() # No meaningful result from a short run; just make sure we don't hang. prob.run_driver()
def test_fan_in_grouped(self): prob = Problem() prob.model = FanInGrouped2() prob.setup(vector_class=PETScVector, check=False, mode='fwd') prob.set_solver_print(level=0) prob.run_model() indep_list = ['p1.x', 'p2.x'] unknown_list = ['c3.y'] assert_rel_error(self, prob['c3.y'], 29.0, 1e-6) J = prob.compute_totals(of=unknown_list, wrt=indep_list) assert_rel_error(self, J['c3.y', 'p1.x'][0][0], -6.0, 1e-6) assert_rel_error(self, J['c3.y', 'p2.x'][0][0], 35.0, 1e-6) assert_rel_error(self, prob['c3.y'], 29.0, 1e-6) prob.setup(vector_class=PETScVector, check=False, mode='rev') prob.run_model() assert_rel_error(self, prob['c3.y'], 29.0, 1e-6) J = prob.compute_totals(of=unknown_list, wrt=indep_list) assert_rel_error(self, J['c3.y', 'p1.x'][0][0], -6.0, 1e-6) assert_rel_error(self, J['c3.y', 'p2.x'][0][0], 35.0, 1e-6) assert_rel_error(self, prob['c3.y'], 29.0, 1e-6)
def test_objective_affine_mapping(self): prob = Problem() prob.model = SellarDerivatives() prob.model.nonlinear_solver = NonlinearBlockGS() prob.model.add_design_var('x', lower=-100, upper=100) prob.model.add_design_var('z', lower=-100, upper=100) prob.model.add_objective('obj', ref0=1000, ref=1010) prob.model.add_objective('con2') prob.setup(check=False) objectives = prob.model.get_objectives() obj_ref0 = objectives['obj_cmp.obj']['ref0'] obj_ref = objectives['obj_cmp.obj']['ref'] obj_scaler = objectives['obj_cmp.obj']['scaler'] obj_adder = objectives['obj_cmp.obj']['adder'] self.assertAlmostEqual( obj_scaler*(obj_ref0 + obj_adder), 0.0, places=12) self.assertAlmostEqual( obj_scaler*(obj_ref + obj_adder), 1.0, places=12)
def test_debug_print_option_totals_color(self): prob = Problem() prob.model = FanInGrouped() prob.model.linear_solver = LinearBlockGS() prob.model.sub.linear_solver = LinearBlockGS() prob.model.add_design_var('iv.x1', parallel_deriv_color='par_dv') prob.model.add_design_var('iv.x2', parallel_deriv_color='par_dv') prob.model.add_design_var('iv.x3') prob.model.add_objective('c3.y') prob.driver.options['debug_print'] = ['totals'] prob.setup(check=False, mode='fwd') prob.set_solver_print(level=0) prob.run_driver() indep_list = ['iv.x1', 'iv.x2', 'iv.x3'] unknown_list = ['c3.y'] stdout = sys.stdout strout = StringIO() sys.stdout = strout try: _ = prob.compute_totals(unknown_list, indep_list, return_format='flat_dict', debug_print=not prob.comm.rank) finally: sys.stdout = stdout output = strout.getvalue() if not prob.comm.rank: self.assertTrue('Solving color: par_dv (iv.x1, iv.x2)' in output) self.assertTrue('Solving variable: iv.x3' in output)
def test_constraint_invalid_indices(self): prob = Problem() prob.model = SellarDerivatives() prob.model.nonlinear_solver = NonlinearBlockGS() with self.assertRaises(ValueError) as context: prob.model.add_constraint('con1', lower=0.0, upper=5.0, indices='foo') self.assertEqual(str(context.exception), 'If specified, indices must ' 'be a sequence of integers.') with self.assertRaises(ValueError) as context: prob.model.add_constraint('con1', lower=0.0, upper=5.0, indices=1) self.assertEqual(str(context.exception), 'If specified, indices must ' 'be a sequence of integers.') with self.assertRaises(ValueError) as context: prob.model.add_constraint('con1', lower=0.0, upper=5.0, indices=[1, 'k']) self.assertEqual(str(context.exception), 'If specified, indices must ' 'be a sequence of integers.') # passing an iterator for indices should be valid prob.model.add_constraint('con1', lower=0.0, upper=5.0, indices=range(2))
def test_constraint_affine_mapping(self): prob = Problem() prob.model = SellarDerivatives() prob.model.nonlinear_solver = NonlinearBlockGS() prob.model.add_design_var('x', lower=-100, upper=100) prob.model.add_design_var('z', lower=-100, upper=100) prob.model.add_objective('obj') prob.model.add_constraint('con1', lower=-100, upper=100, ref0=-100.0, ref=100) prob.model.add_constraint('con2') prob.setup(check=False) constraints = prob.model.get_constraints() con1_ref0 = constraints['con_cmp1.con1']['ref0'] con1_ref = constraints['con_cmp1.con1']['ref'] con1_scaler = constraints['con_cmp1.con1']['scaler'] con1_adder = constraints['con_cmp1.con1']['adder'] self.assertAlmostEqual( con1_scaler*(con1_ref0 + con1_adder), 0.0, places=12) self.assertAlmostEqual( con1_scaler*(con1_ref + con1_adder), 1.0, places=12)
def test_desvar_affine_mapping(self): prob = Problem() prob.model = SellarDerivatives() prob.model.nonlinear_solver = NonlinearBlockGS() prob.model.add_design_var('x', lower=-100, upper=100, ref0=-100.0, ref=100) prob.model.add_design_var('z', lower=-100, upper=100) prob.model.add_objective('obj') prob.model.add_constraint('con1') prob.model.add_constraint('con2') prob.setup(check=False) des_vars = prob.model.get_design_vars() x_ref0 = des_vars['px.x']['ref0'] x_ref = des_vars['px.x']['ref'] x_scaler = des_vars['px.x']['scaler'] x_adder = des_vars['px.x']['adder'] self.assertAlmostEqual( x_scaler*(x_ref0 + x_adder), 0.0, places=12) self.assertAlmostEqual( x_scaler*(x_ref + x_adder), 1.0, places=12)
def test_converge_diverge_groups(self): # Test derivatives for converge-diverge-groups topology. prob = Problem() prob.model = ConvergeDivergeGroups() prob.model.linear_solver = LinearRunOnce() prob.set_solver_print(level=0) g1 = prob.model.g1 g2 = g1.g2 g3 = prob.model.g3 g1.linear_solver = LinearRunOnce() g2.linear_solver = LinearRunOnce() g3.linear_solver = LinearRunOnce() prob.setup(check=False, mode='fwd') prob.run_model() wrt = ['iv.x'] of = ['c7.y1'] # Make sure value is fine. assert_rel_error(self, prob['c7.y1'], -102.7, 1e-6) J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict') assert_rel_error(self, J['c7.y1', 'iv.x'][0][0], -40.75, 1e-6) prob.setup(check=False, mode='rev') prob.run_model() J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict') assert_rel_error(self, J['c7.y1', 'iv.x'][0][0], -40.75, 1e-6)
def test_feature_boundscheck_wall(self): import numpy as np from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, BoundsEnforceLS from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays top = Problem() top.model = Group() top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') top.model.nonlinear_solver = NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 10 top.model.linear_solver = ScipyKrylov() ls = top.model.nonlinear_solver.linesearch = BoundsEnforceLS() ls.options['bound_enforcement'] = 'wall' top.setup(check=False) # Test upper bounds: should go to the upper bound and stall top['px.x'] = 0.5 top['comp.y'] = 0. top['comp.z'] = 2.4 top.run_model() assert_rel_error(self, top['comp.z'][0], [2.6], 1e-8) assert_rel_error(self, top['comp.z'][1], [2.5], 1e-8) assert_rel_error(self, top['comp.z'][2], [2.65], 1e-8)
def test_rev_mode_bug(self): prob = Problem() prob.model = SellarDerivatives(nonlinear_solver=NewtonSolver(), linear_solver=DirectSolver()) prob.setup(check=False, mode='rev') prob.set_solver_print(level=0) prob.run_model() assert_rel_error(self, prob['y1'], 25.58830273, .00001) assert_rel_error(self, prob['y2'], 12.05848819, .00001) wrt = ['x', 'z'] of = ['obj', 'con1', 'con2'] Jbase = {} Jbase['con1', 'x'] = [[-0.98061433]] Jbase['con1', 'z'] = np.array([[-9.61002285, -0.78449158]]) Jbase['con2', 'x'] = [[0.09692762]] Jbase['con2', 'z'] = np.array([[1.94989079, 1.0775421]]) Jbase['obj', 'x'] = [[2.98061392]] Jbase['obj', 'z'] = np.array([[9.61001155, 1.78448534]]) J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict') for key, val in iteritems(Jbase): assert_rel_error(self, J[key], val, .00001) # In the bug, the solver mode got switched from fwd to rev when it shouldn't # have been, causing a singular matrix and NaNs in the output. prob.run_model() assert_rel_error(self, prob['y1'], 25.58830273, .00001) assert_rel_error(self, prob['y2'], 12.05848819, .00001)
def test_sellar_state_connection(self): # Test derivatives across a converged Sellar model. prob = Problem() prob.model = SellarStateConnection(linear_solver=self.linear_solver_class(), nl_atol=1e-12) prob.set_solver_print(level=0) prob.setup(check=False, mode='fwd') prob.run_model() # Just make sure we are at the right answer assert_rel_error(self, prob['y1'], 25.58830273, .00001) assert_rel_error(self, prob['d2.y2'], 12.05848819, .00001) wrt = ['x', 'z'] of = ['obj', 'con1', 'con2'] Jbase = {} Jbase['con1', 'x'] = [[-0.98061433]] Jbase['con1', 'z'] = np.array([[-9.61002285, -0.78449158]]) Jbase['con2', 'x'] = [[0.09692762]] Jbase['con2', 'z'] = np.array([[1.94989079, 1.0775421]]) Jbase['obj', 'x'] = [[2.98061392]] Jbase['obj', 'z'] = np.array([[9.61001155, 1.78448534]]) J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict') for key, val in iteritems(Jbase): assert_rel_error(self, J[key], val, .00001) prob.setup(check=False, mode='rev') prob.run_model() J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict') for key, val in iteritems(Jbase): assert_rel_error(self, J[key], val, .00001)
def ttest_reconf_comp(self): p = Problem() p.model = Group() p.model.add_subsystem('c1', IndepVarComp('x', 1.0), promotes_outputs=['x']) p.model.add_subsystem('c2', ReconfComp(), promotes_inputs=['x'], promotes_outputs=['y']) p.model.add_subsystem('c3', Comp(), promotes_inputs=['x'], promotes_outputs=['z']) p.setup() p['x'] = 3. # First run the model once; counter = 1, size of y = 1 p.run_model() totals = p.compute_totals(wrt=['x'], of=['y']) assert_rel_error(self, p['x'], 3.0) assert_rel_error(self, p['y'], 6.0) assert_rel_error(self, p['z'], 9.0) assert_rel_error(self, totals['y', 'x'], 2.0) print(p['x'], p['y'], p['z'], totals['y', 'x'].flatten()) # Run the model again, which will trigger reconfiguration; counter = 2, size of y = 2 p.run_model() totals = p.compute_totals(wrt=['x'], of=['y']) assert_rel_error(self, p['x'], 3.0) assert_rel_error(self, p['y'], 6.0 * np.ones(2)) assert_rel_error(self, p['z'], 9.0) assert_rel_error(self, totals['y', 'x'], 2.0 * np.ones(2, 1))
def test_feature_armijogoldsteinls_basic(self): import numpy as np from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, ArmijoGoldsteinLS from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays top = Problem() top.model = Group() top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') top.model.nonlinear_solver = NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 10 top.model.linear_solver = ScipyKrylov() top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS() top.setup(check=False) # Test lower bounds: should go to the lower bound and stall top['px.x'] = 2.0 top['comp.y'] = 0. top['comp.z'] = 1.6 top.run_model() assert_rel_error(self, top['comp.z'][0], [1.5], 1e-8) assert_rel_error(self, top['comp.z'][1], [1.5], 1e-8) assert_rel_error(self, top['comp.z'][2], [1.5], 1e-8)
def test_assert_check_partials_no_exception_expected(self): import numpy as np from openmdao.api import Problem, ExplicitComponent from openmdao.utils.assert_utils import assert_check_partials class MyComp(ExplicitComponent): def setup(self): self.add_input('x1', 3.0) self.add_input('x2', 5.0) self.add_output('y', 5.5) self.declare_partials(of='*', wrt='*') def compute(self, inputs, outputs): outputs['y'] = 3.0 * inputs['x1'] + 4.0 * inputs['x2'] def compute_partials(self, inputs, partials): """Correct derivative.""" J = partials J['y', 'x1'] = np.array([3.0]) J['y', 'x2'] = np.array([4.0]) prob = Problem() prob.model = MyComp() prob.set_solver_print(level=0) prob.setup(check=False) prob.run_model() data = prob.check_partials(out_stream=None) atol = 1.e-6 rtol = 1.e-6 assert_check_partials(data, atol, rtol)
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(self): p = Problem() p.model = Group() p.model.add_subsystem('c1', IndepVarComp('x', 1.0), promotes_outputs=['x']) p.model.add_subsystem('c2', ReconfComp(), promotes_inputs=['x'], promotes_outputs=['y']) p.model.add_subsystem('c3', Comp(), promotes_inputs=['x'], promotes_outputs=['z']) # First run the usual setup method on Problem; size of y = 1 p.setup() p['x'] = 2 p.run_model() totals = p.compute_totals(wrt=['x'], of=['y']) assert_rel_error(self, p['x'], 2.0) assert_rel_error(self, p['y'], 4.0) assert_rel_error(self, p['z'], 6.0) assert_rel_error(self, totals['y', 'x'], [[2.0]]) # Now run the setup method on the root system; size of y = 2 p.model.resetup() p['x'] = 3 p.run_model() totals = p.compute_totals(wrt=['x'], of=['y']) assert_rel_error(self, p['x'], 3.0) assert_rel_error(self, p['y'], 6.0 * np.ones(2)) assert_rel_error(self, p['z'], 9.0) assert_rel_error(self, totals['y', 'x'], 2.0 * np.ones((2, 1))) # Now reconfigure from c2 and update in root; size of y = 3; the value of x is preserved p.model.c2.resetup('reconf') p.model.resetup('update') p.run_model() totals = p.compute_totals(wrt=['x'], of=['y']) assert_rel_error(self, p['x'], 3.0) assert_rel_error(self, p['y'], 6.0 * np.ones(3)) assert_rel_error(self, p['z'], 9.0) assert_rel_error(self, totals['y', 'x'], 2.0 * np.ones((3, 1))) # Now reconfigure from c3 and update in root; size of y = 3; the value of x is preserved p.model.c3.resetup('reconf') p.model.resetup('update') p.run_model() totals = p.compute_totals(wrt=['x'], of=['y']) assert_rel_error(self, p['x'], 3.0) assert_rel_error(self, p['y'], 6.0 * np.ones(3)) assert_rel_error(self, p['z'], 9.0) assert_rel_error(self, totals['y', 'x'], 2.0 * np.ones((3, 1))) # Finally, setup reconf from root; size of y = 4 # Since we are at the root, calling setup('full') and setup('reconf') have the same effect. # In both cases, variable values are lost so we have to set x=3 again. p.model.resetup('reconf') p['x'] = 3 p.run_model() totals = p.compute_totals(wrt=['x'], of=['y']) assert_rel_error(self, p['x'], 3.0) assert_rel_error(self, p['y'], 6.0 * np.ones(4)) assert_rel_error(self, p['z'], 9.0) assert_rel_error(self, totals['y', 'x'], 2.0 * np.ones((4, 1)))
def test_assert_no_approx_partials_exception_not_expected(self): prob = Problem() prob.model = DoubleSellar() prob.setup(check=False) assert_no_approx_partials(prob.model, include_self=True, recurse=True)
def test_pull_size_from_source_with_indices(self): raise unittest.SkipTest("setting input size based on src size not supported yet") class Src(ExplicitComponent): def setup(self): self.add_input('x', 2.0) self.add_output('y1', np.zeros((3, ))) self.add_output('y2', shape=((3, ))) self.add_output('y3', 3.0) def solve_nonlinear(self, inputs, outputs, resids): """ counts up. """ x = inputs['x'] outputs['y1'] = x * np.array([1.0, 2.0, 3.0]) outputs['y2'] = x * np.array([1.0, 2.0, 3.0]) outputs['y3'] = x * 4.0 class Tgt(ExplicitComponent): def setup(self): self.add_input('x1') self.add_input('x2') self.add_input('x3') self.add_output('y1', 0.0) self.add_output('y2', 0.0) self.add_output('y3', 0.0) def solve_nonlinear(self, inputs, outputs, resids): """ counts up. """ x1 = inputs['x1'] x2 = inputs['x2'] x3 = inputs['x3'] outputs['y1'] = np.sum(x1) outputs['y2'] = np.sum(x2) outputs['y3'] = np.sum(x3) top = Problem() top.model = Group() top.model.add_subsystem('src', Src()) top.model.add_subsystem('tgt', Tgt()) top.model.connect('src.y1', 'tgt.x1', src_indices=(0, 1)) top.model.connect('src.y2', 'tgt.x2', src_indices=(0, 1)) top.model.connect('src.y3', 'tgt.x3') top.setup(check=False) top.run_model() self.assertEqual(top['tgt.y1'], 6.0) self.assertEqual(top['tgt.y2'], 6.0) self.assertEqual(top['tgt.y3'], 8.0)
def test_basic_fd_comps(self): prob = Problem() prob.model = Group() prob.model.add_subsystem('px1', IndepVarComp('x1', 100.0), promotes=['x1']) prob.model.add_subsystem('src', SrcCompFD()) prob.model.add_subsystem('tgtF', TgtCompFFD()) prob.model.add_subsystem('tgtC', TgtCompCFD()) prob.model.add_subsystem('tgtK', TgtCompKFD()) prob.model.connect('x1', 'src.x1') prob.model.connect('src.x2', 'tgtF.x2') prob.model.connect('src.x2', 'tgtC.x2') prob.model.connect('src.x2', 'tgtK.x2') prob.setup(check=False) prob.run_model() assert_rel_error(self, prob['src.x2'], 100.0, 1e-6) assert_rel_error(self, prob['tgtF.x3'], 212.0, 1e-6) assert_rel_error(self, prob['tgtC.x3'], 100.0, 1e-6) assert_rel_error(self, prob['tgtK.x3'], 373.15, 1e-6) indep_list = ['x1'] unknown_list = ['tgtF.x3', 'tgtC.x3', 'tgtK.x3'] J = prob.compute_totals(of=unknown_list, wrt=indep_list, return_format='dict') assert_rel_error(self, J['tgtF.x3']['x1'][0][0], 1.8, 1e-6) assert_rel_error(self, J['tgtC.x3']['x1'][0][0], 1.0, 1e-6) assert_rel_error(self, J['tgtK.x3']['x1'][0][0], 1.0, 1e-6) prob.setup(check=False, mode='rev') prob.run_model() J = prob.compute_totals(of=unknown_list, wrt=indep_list, return_format='dict') assert_rel_error(self, J['tgtF.x3']['x1'][0][0], 1.8, 1e-6) assert_rel_error(self, J['tgtC.x3']['x1'][0][0], 1.0, 1e-6) assert_rel_error(self, J['tgtK.x3']['x1'][0][0], 1.0, 1e-6) prob.model.approx_totals(method='fd') prob.setup(check=False, mode='rev') prob.run_model() J = prob.compute_totals(of=unknown_list, wrt=indep_list, return_format='dict') assert_rel_error(self, J['tgtF.x3']['x1'][0][0], 1.8, 1e-6) assert_rel_error(self, J['tgtC.x3']['x1'][0][0], 1.0, 1e-6) assert_rel_error(self, J['tgtK.x3']['x1'][0][0], 1.0, 1e-6) # Make sure check partials handles conversion data = prob.check_partials() for key1, val1 in iteritems(data): for key2, val2 in iteritems(val1): assert_rel_error(self, val2['abs error'][0], 0.0, 1e-6) assert_rel_error(self, val2['abs error'][1], 0.0, 1e-6) assert_rel_error(self, val2['abs error'][2], 0.0, 1e-6) assert_rel_error(self, val2['rel error'][0], 0.0, 1e-6) assert_rel_error(self, val2['rel error'][1], 0.0, 1e-6) assert_rel_error(self, val2['rel error'][2], 0.0, 1e-6)
def test_distrib_record_solver(self): prob = Problem() prob.model = Group() try: prob.model.nonlinear_solver.add_recorder(self.recorder) except RuntimeError as err: self.assertEqual(str(err), "Recording of Solvers when running parallel code is not supported yet") else: self.fail('RuntimeError expected.')
def test_distrib_record_system(self): prob = Problem() prob.model = Group() try: prob.model.add_recorder(self.recorder) except RuntimeError as err: msg = "Recording of Systems when running parallel code is not supported yet" self.assertEqual(str(err), msg) else: self.fail('RuntimeError expected.')
def test_sellar(self): prob = Problem() prob.model = SellarMDA() prob.setup(check=False) prob.run_model() assert_rel_error(self, prob['y1'], 25.58830273, .00001) assert_rel_error(self, prob['y2'], 12.05848819, .00001) # Make sure we aren't iterating like crazy self.assertLess(prob.model.nonlinear_solver._iter_count, 8)
def test_objective_invalid_name(self): prob = Problem() prob.model = SellarDerivatives() prob.model.nonlinear_solver = NonlinearBlockGS() with self.assertRaises(TypeError) as context: prob.model.add_objective(42, ref0=-100.0, ref=100) self.assertEqual(str(context.exception), 'The name argument should ' 'be a string, got 42')
def compute_partials(self, inputs, partials): in_name = self.options['in_name'] out_name = self.options['out_name'] partials[out_name, in_name] = -np.sin(inputs[in_name]).flatten() if __name__ == "__main__": from openmdao.api import Problem, IndepVarComp, Group n = 100 val = np.random.rand(n) indeps = IndepVarComp() indeps.add_output( 'x', val=val, shape=(n, ), ) prob = Problem() prob.model = Group() prob.model.add_subsystem( 'indeps', indeps, promotes=['*'], ) prob.model.add_subsystem( 'cos', CosComp(in_name='x', out_name='y', shape=(n, )), promotes=['*'], ) prob.setup() prob.check_partials(compact_print=True)
class ExampleMultipleMatrixAlong0(Group): def setup(self): n = 3 m = 6 # Declare a matrix of shape 3x6 as input M1 = self.declare_input('M1', val=np.arange(n * m).reshape((n, m))) # Declare another matrix of shape 3x6 as input M2 = self.declare_input('M2', val=np.arange(n * m, 2 * n * m).reshape( (n, m))) # Output the elementwise average of the axiswise average of matrices M1 ad M2 along the columns self.register_output('multiple_matrix_average_along_0', ot.average(M1, M2, axes=(0, ))) prob = Problem() prob.model = ExampleMultipleMatrixAlong0() prob.setup(force_alloc_complex=True) prob.run_model() print('M1', prob['M1'].shape) print(prob['M1']) print('M2', prob['M2'].shape) print(prob['M2']) print('multiple_matrix_average_along_0', prob['multiple_matrix_average_along_0'].shape) print(prob['multiple_matrix_average_along_0'])
def test_deep_analysis_error_iprint(self): class ImplCompTwoStatesAE(ImplicitComponent): def setup(self): self.add_input('x', 0.5) self.add_output('y', 0.0) self.add_output('z', 2.0, lower=1.5, upper=2.5) self.maxiter = 10 self.atol = 1.0e-12 self.declare_partials(of='*', wrt='*') self.counter = 0 def apply_nonlinear(self, inputs, outputs, residuals): """ Don't solve; just calculate the residual. """ x = inputs['x'] y = outputs['y'] z = outputs['z'] residuals['y'] = y - x - 2.0 * z residuals['z'] = x * z + z - 4.0 self.counter += 1 if self.counter > 5 and self.counter < 11: raise AnalysisError('catch me') def linearize(self, inputs, outputs, jac): """ Analytical derivatives. """ # Output equation jac[('y', 'x')] = -1.0 jac[('y', 'y')] = 1.0 jac[('y', 'z')] = -2.0 # State equation jac[('z', 'z')] = -inputs['x'] + 1.0 jac[('z', 'x')] = -outputs['z'] top = Problem() top.model = Group() top.model.add_subsystem('px', IndepVarComp('x', 7.0)) sub = top.model.add_subsystem('sub', Group()) sub.add_subsystem('comp', ImplCompTwoStatesAE()) top.model.connect('px.x', 'sub.comp.x') top.model.nonlinear_solver = NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 2 top.model.nonlinear_solver.options['solve_subsystems'] = True top.model.linear_solver = ScipyKrylov() sub.nonlinear_solver = NewtonSolver() sub.nonlinear_solver.options['maxiter'] = 2 sub.linear_solver = ScipyKrylov() ls = top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS( bound_enforcement='wall') ls.options['maxiter'] = 5 ls.options['alpha'] = 10.0 ls.options['retry_on_analysis_error'] = True ls.options['c'] = 10000.0 top.setup(check=False) top.set_solver_print(level=2) stdout = sys.stdout strout = StringIO() sys.stdout = strout try: top.run_model() finally: sys.stdout = stdout output = strout.getvalue().split('\n') self.assertTrue(output[26].startswith('| LS: AG 5'))
# Initialize, read initial FAST files to avoid doing it iteratively fast = InputReader_OpenFAST(FAST_ver=FASTpref['FAST_ver'], dev_branch=FASTpref['dev_branch']) fast.FAST_InputFile = FASTpref['FAST_InputFile'] fast.FAST_directory = FASTpref['FAST_directory'] fast.execute() fst_vt = fast.fst_vt else: fst_vt = {} # Initialize and execute OpenMDAO problem with input data prob_ref = Problem() prob_ref.model=Optimize_MonopileTurbine(RefBlade=blade, Nsection_Tow = Nsection_Tow, VerbosityCosts = False, folder_output = folder_output, FASTpref = FASTpref) prob_ref.setup() prob_ref = Init_MonopileTurbine(prob_ref, blade, Nsection_Tow = Nsection_Tow, Analysis_Level = Analysis_Level, fst_vt = fst_vt) prob_ref['drive.shaft_angle'] = np.radians(6.) prob_ref['overhang'] = 8.5 prob_ref['drive.distance_hub2mb'] = 3.5 prob_ref['significant_wave_height'] = 4.52 prob_ref['significant_wave_period'] = 9.45 prob_ref['monopile'] = True prob_ref['foundation_height'] = -30. prob_ref['water_depth'] = 30. prob_ref['suctionpile_depth'] = 45. prob_ref['wind_reference_height'] = 150. prob_ref['hub_height'] = 150. prob_ref['tower_section_height'] = np.array([10., 10., 10., 10., 10., 12.5, 12.5, 12.5, 12.5, 12.5, 12.5, 12.5, 12.5, 12.5, 13.6679])
vec = self.declare_input('a', val=a) # Shape of Tensor shape3 = (2, 4, 3) c = np.arange(24).reshape(shape3) # Declaring tensor tens = self.declare_input('c', val=c) # Inner Product of a tensor and a vector self.register_output( 'einsum_inner2', ot.einsum_new_api( tens, vec, operation=[('rows', 0, 1), (0, ), ('rows', 1)], )) prob = Problem() prob.model = ExampleInnerTensorVector() prob.setup(force_alloc_complex=True) prob.run_model() print('a', prob['a'].shape) print(prob['a']) print('c', prob['c'].shape) print(prob['c']) print('einsum_inner2', prob['einsum_inner2'].shape) print(prob['einsum_inner2'])
def test_feature_cache_linear(self): import numpy as np from scipy.sparse.linalg import gmres from openmdao.api import ImplicitComponent, Group, IndepVarComp, Problem class QuadraticComp(ImplicitComponent): """ A Simple Implicit Component representing a Quadratic Equation. R(a, b, c, x) = ax^2 + bx + c Solution via Quadratic Formula: x = (-b + sqrt(b^2 - 4ac)) / 2a """ def setup(self): self.add_input('a', val=1.) self.add_input('b', val=1.) self.add_input('c', val=1.) self.add_output('states', val=[0, 0]) self.declare_partials(of='*', wrt='*') def apply_nonlinear(self, inputs, outputs, residuals): a = inputs['a'] b = inputs['b'] c = inputs['c'] x = outputs['states'][0] y = outputs['states'][1] residuals['states'][0] = a * x**2 + b * x + c residuals['states'][1] = a * y + b def solve_nonlinear(self, inputs, outputs): a = inputs['a'] b = inputs['b'] c = inputs['c'] outputs['states'][0] = (-b + (b**2 - 4 * a * c)**0.5) / (2 * a) outputs['states'][1] = -b / a def linearize(self, inputs, outputs, partials): a = inputs['a'][0] b = inputs['b'][0] c = inputs['c'][0] x = outputs['states'][0] y = outputs['states'][1] partials['states', 'a'] = [[x**2], [y]] partials['states', 'b'] = [[x], [1]] partials['states', 'c'] = [[1.0], [0]] partials['states', 'states'] = [[2 * a * x + b, 0], [0, a]] self.state_jac = np.array([[2 * a * x + b, 0], [0, a]]) def solve_linear(self, d_outputs, d_residuals, mode): if mode == 'fwd': print("incoming initial guess", d_outputs['states']) d_outputs['states'] = gmres(self.state_jac, d_residuals['states'], x0=d_outputs['states'])[0] elif mode == 'rev': d_residuals['states'] = gmres(self.state_jac, d_outputs['states'], x0=d_residuals['states'])[0] p = Problem() p.model = Group() indeps = p.model.add_subsystem('indeps', IndepVarComp(), promotes_outputs=['a', 'b', 'c']) indeps.add_output('a', 1.) indeps.add_output('b', 4.) indeps.add_output('c', 1.) p.model.add_subsystem('quad', QuadraticComp(), promotes_inputs=['a', 'b', 'c'], promotes_outputs=['states']) p.model.add_design_var('a', cache_linear_solution=True) p.model.add_constraint('states', upper=10) p.setup(mode='fwd') p.run_model() assert_rel_error(self, p['states'], [-0.26794919, -4.], 1e-6) derivs = p.compute_totals(of=['states'], wrt=['a']) assert_rel_error(self, derivs['states', 'a'], [[-0.02072594], [4.]], 1e-6) p['a'] = 4 derivs = p.compute_totals(of=['states'], wrt=['a']) assert_rel_error(self, derivs['states', 'a'], [[-0.02072594], [4.]], 1e-6)
from openmdao.api import Problem from omtools.api import Group import omtools.api as ot import numpy as np class ExampleSingleMatrixAlong1(Group): def setup(self): n = 3 m = 6 # Declare a matrix of shape 3x6 as input M1 = self.declare_input('M1', val=np.arange(n * m).reshape((n, m))) # Output the axiswise average of matrix M1 along the columns self.register_output('single_matrix_average_along_1', ot.average(M1, axes=(1, ))) prob = Problem() prob.model = ExampleSingleMatrixAlong1() prob.setup(force_alloc_complex=True) prob.run_model() print('M1', prob['M1'].shape) print(prob['M1']) print('single_matrix_average_along_1', prob['single_matrix_average_along_1'].shape) print(prob['single_matrix_average_along_1'])
def compute_partials(self, inputs, J, discrete_inputs): J = self.J class Finance(Group): def setup(self): self.add_subsystem('plantfinancese', PlantFinance(verbosity = True), promotes=['*']) if __name__ == "__main__": # Initialize OpenMDAO problem and FloatingSE Group prob = Problem() prob.model=Finance() # runs script prob.setup() prob['machine_rating'] = 2.32 * 1.e+003 # kW prob['tcc_per_kW'] = 1093 # USD/kW prob['turbine_number'] = 87. prob['opex_per_kW'] = 43.56 # USD/kW/yr Source: 70 $/kW/yr, updated from report, (70 is on the high side) prob['fixed_charge_rate'] = 0.079216644 # 7.9 % confirmed from report prob['bos_per_kW'] = 517. # USD/kW from appendix of report prob['wake_loss_factor'] = 0.15 # confirmed from report prob['turbine_aep'] = 9915.95 * 1.e+003 # confirmed from report prob.run_driver()
self.connect("cycle.beam0.sigma", ["con0.sigma"]) self.connect("cycle.beam1.sigma", ["con1.sigma"]) self.connect("cycle.beam2.sigma", ["con2.sigma"]) self.connect("cycle.beam3.sigma", ["con3.sigma"]) self.connect("cycle.beam4.sigma", ["con4.sigma"]) self.connect("indeps.A0", ["cycle.beam0.A", "obj_cmp.A0"]) self.connect("indeps.A1", ["cycle.beam1.A", "obj_cmp.A1"]) self.connect("indeps.A2", ["cycle.beam2.A", "obj_cmp.A2"]) self.connect("indeps.A3", ["cycle.beam3.A", "obj_cmp.A3"]) self.connect("indeps.A4", ["cycle.beam4.A", "obj_cmp.A4"]) if __name__ == "__main__": prob = Problem() prob.model = Truss_Analysis() prob.driver = ScipyOptimizeDriver() prob.driver.options["optimizer"] = "SLSQP" prob.model.add_design_var("indeps.A0", lower=0.001, upper=100) prob.model.add_design_var("indeps.A1", lower=0.001, upper=100) prob.model.add_design_var("indeps.A2", lower=0.001, upper=100) prob.model.add_design_var("indeps.A3", lower=0.001, upper=100) prob.model.add_design_var("indeps.A4", lower=0.001, upper=100) prob.model.add_objective("obj_cmp.obj") prob.model.add_constraint("con0.con", lower=0) prob.model.add_constraint("con1.con", lower=0) prob.model.add_constraint("con2.con", lower=0) prob.model.add_constraint("con3.con", lower=0) prob.model.add_constraint("con4.con", lower=0)
dq_dt[0, :] = -np.sin(antAngle / 2.) / 2. dq_dt[1, :] = np.cos(antAngle / 2.) / rt2 / 2. dq_dt[2, :] = -np.cos(antAngle / 2.) / rt2 / 2. dq_dt[3, :] = 0.0 partials['q_A', 'antAngle'] = dq_dt.flatten() if __name__ == '__main__': import numpy as np from openmdao.api import Problem, IndepVarComp, Group group = Group() comp = IndepVarComp() num_times = 3 comp.add_output('antAngle', val=1.0, units='rad') group.add_subsystem('Inputcomp', comp, promotes=['*']) group.add_subsystem('antenna_angle', AntRotationComp(num_times=num_times), promotes=['*']) prob = Problem() prob.model = group prob.setup(check=True) prob.run_model() prob.model.list_outputs() prob.check_partials(compact_print=True)
cycle.nonlinear_solver = NonlinearBlockGS() self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0)) self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1')) self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0')) self.connect('indeps.x', ['cycle.d1.x', 'obj_cmp.x']) self.connect('indeps.z', ['cycle.d1.z', 'cycle.d2.z', 'obj_cmp.z']) self.connect('cycle.d1.y1', ['obj_cmp.y1', 'con_cmp1.y1']) self.connect('cycle.d2.y2', ['obj_cmp.y2', 'con_cmp2.y2']) prob = Problem() prob.model = SellarMDAConnect() prob.driver = ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' # prob.driver.options['maxiter'] = 100 prob.driver.options['tol'] = 1e-8 prob.model.add_design_var('indeps.x', lower=0, upper=10) prob.model.add_design_var('indeps.z', lower=0, upper=10) prob.model.add_objective('obj_cmp.obj') prob.model.add_constraint('con_cmp1.con1', upper=0) prob.model.add_constraint('con_cmp2.con2', upper=0) prob.setup() prob['indeps.x'] = 2.
class ExampleMultipleMatrix(Group): def setup(self): n = 3 m = 6 # Declare a matrix of shape 3x6 as input M1 = self.declare_input('M1', val=np.arange(n * m).reshape((n, m))) # Declare another matrix of shape 3x6 as input M2 = self.declare_input('M2', val=np.arange(n * m, 2 * n * m).reshape( (n, m))) # Output the elementwise sum of matrices M1 and M2 self.register_output('multiple_matrix_sum', ot.sum(M1, M2)) prob = Problem() prob.model = ExampleMultipleMatrix() prob.setup(force_alloc_complex=True) prob.run_model() print('M1', prob['M1'].shape) print(prob['M1']) print('M2', prob['M2'].shape) print(prob['M2']) print('multiple_matrix_sum', prob['multiple_matrix_sum'].shape) print(prob['multiple_matrix_sum'])
model.add_subsystem('inputs_comp', comp, promotes=['*']) comp = CLComp() model.add_subsystem('cl_comp', comp, promotes=['*']) comp = CDiComp(e=0.7) model.add_subsystem('cdi_comp', comp, promotes=['*']) comp = ExecComp('CD = CD0 + CDi') model.add_subsystem('cd_comp', comp, promotes=['*']) comp = ExecComp('LD = CL/CD') comp.add_objective('LD', scaler=-1.) model.add_subsystem('ld_comp', comp, promotes=['*']) prob.model = model prob.driver = ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-15 prob.driver.options['disp'] = True prob.setup() prob.run_model() prob.run_driver() prob.check_partials(compact_print=True) print('alpha', prob['alpha']) print('CL0', prob['CL0']) print('CL', prob['CL'])
# --- constraints --- min_d_to_t = 120.0 max_taper = 0.2 # --------------- # # V_max = 80.0 # tip speed # # D = 126.0 # # .freq1p = V_max / (D/2) / (2*pi) # convert to Hz nPoints = len(d_param) nFull = 5*(nPoints-1) + 1 wind = 'PowerWind' nLC = 2 prob = Problem() prob.model = TowerSE(nLC=nLC, nPoints=nPoints, nFull=nFull, wind=wind, topLevelFlag=True, monopile=monopile) prob.setup() if wind=='PowerWind': prob['shearExp'] = shearExp # assign values to params # --- geometry ---- prob['hub_height'] = h_param.sum() prob['foundation_height'] = 0.0 prob['tower_section_height'] = h_param prob['tower_outer_diameter'] = d_param prob['tower_wall_thickness'] = t_param prob['tower_buckling_length'] = L_reinforced prob['tower_outfitting_factor'] = Koutfitting
a = np.arange(4) vec = self.declare_input('a', val=a) # Shape of Tensor shape3 = (2, 4, 3) c = np.arange(24).reshape(shape3) # Declaring tensor tens = self.declare_input('c', val=c) # Outer Product of a tensor and a vector self.register_output('einsum_outer2', ot.einsum( tens, vec, subscripts='hij,k->hijk', )) prob = Problem() prob.model = ExampleOuterTensorVector() prob.setup(force_alloc_complex=True) prob.run_model() print('a', prob['a'].shape) print(prob['a']) print('c', prob['c'].shape) print(prob['c']) print('einsum_outer2', prob['einsum_outer2'].shape) print(prob['einsum_outer2'])
num_nodes=nn, aircraft_model=ElectricTBM850Model, extra_states=extra_states_tuple, transition_method='ode'), promotes_inputs=['*'], promotes_outputs=['*']) self.connect('T_motor_initial', 'v0v1.propmodel.motorheatsink.T_initial') self.connect('T_res_initial', 'v0v1.propmodel.reservoir.T_initial') if __name__ == "__main__": num_nodes = 11 prob = Problem() prob.model = ElectricTBMAnalysisGroup() prob.model.nonlinear_solver = NewtonSolver(iprint=2) prob.model.options['assembled_jac_type'] = 'csc' prob.model.linear_solver = DirectSolver(assemble_jac=True) prob.model.nonlinear_solver.options['solve_subsystems'] = True prob.model.nonlinear_solver.options['maxiter'] = 20 prob.model.nonlinear_solver.options['atol'] = 1e-8 prob.model.nonlinear_solver.options['rtol'] = 1e-8 prob.model.nonlinear_solver.linesearch = BoundsEnforceLS( bound_enforcement='scalar', print_bound_enforce=False) prob.model.add_design_var('mission_range', lower=100, upper=300, scaler=1e-2)
class ExampleReorderTensorSparse(Group): def setup(self): # Shape of Tensor shape3 = (2, 4, 3) c = np.arange(24).reshape(shape3) # Declaring tensor tens = self.declare_input('c', val=c) self.register_output( 'einsum_reorder2_sparse_derivs', ot.einsum( tens, subscripts='ijk->kji', partial_format='sparse', )) prob = Problem() prob.model = ExampleReorderTensorSparse() prob.setup(force_alloc_complex=True) prob.run_model() print('c', prob['c'].shape) print(prob['c']) print('einsum_reorder2_sparse_derivs', prob['einsum_reorder2_sparse_derivs'].shape) print(prob['einsum_reorder2_sparse_derivs'])
class PlanesIntersection(Group): def setup(self): self.add_subsystem('p3', Plane3()) self.add_subsystem('p1', Plane1()) self.add_subsystem('p2', Plane2()) self.connect('p1.y', 'p2.y') self.connect('p1.y', 'p3.y') self.connect('p2.x', 'p3.x') self.connect('p2.x', 'p1.x') self.connect('p3.z', 'p1.z') self.connect('p3.z', 'p2.z') prob = Problem() from openmdao.api import LinearRunOnce prob.model = PlanesIntersection() # a = prob.model.nonlinear_solver = NewtonSolver() a = prob.model.linear_solver = LinearRunOnce() a.options['maxiter'] = 10 prob.setup() # view_model(prob) prob.run_model() print(prob['p1.y'], prob['p1.x'], prob['p1.z'])
def test_array_list_vars_options(self): class ArrayAdder(ExplicitComponent): """ Just a simple component that has array inputs and outputs """ def __init__(self, size): super(ArrayAdder, self).__init__() self.size = size def setup(self): self.add_input('x', val=np.zeros(self.size), units='inch') self.add_output('y', val=np.zeros(self.size), units='ft') def compute(self, inputs, outputs): outputs['y'] = inputs['x'] + 10.0 size = 100 # how many items in the array prob = Problem() prob.model = Group() prob.model.add_subsystem('des_vars', IndepVarComp('x', np.ones(size), units='inch'), promotes=['x']) prob.model.add_subsystem('mult', ArrayAdder(size), promotes=['x', 'y']) prob.setup(check=False) prob['x'] = np.ones(size) prob.run_driver() # logging inputs # out_stream - not hierarchical - extras - no print_arrays stream = cStringIO() prob.model.list_inputs(values=True, units=True, hierarchical=False, print_arrays=False, out_stream=stream) text = stream.getvalue() self.assertEqual(1, text.count("1 Input(s) in 'model'")) self.assertEqual(1, text.count('mult.x')) num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()]) self.assertEqual(5, num_non_empty_lines) # out_stream - hierarchical - extras - no print_arrays stream = cStringIO() prob.model.list_inputs(values=True, units=True, hierarchical=True, print_arrays=False, out_stream=stream) text = stream.getvalue() self.assertEqual(1, text.count("1 Input(s) in 'model'")) num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()]) self.assertEqual(7, num_non_empty_lines) self.assertEqual(1, text.count('top')) self.assertEqual(1, text.count(' mult')) self.assertEqual(1, text.count(' x')) # logging outputs # out_stream - not hierarchical - extras - no print_arrays stream = cStringIO() prob.model.list_outputs(values=True, units=True, shape=True, bounds=True, residuals=True, scaling=True, hierarchical=False, print_arrays=False, out_stream=stream) text = stream.getvalue() self.assertEqual(text.count('2 Explicit Output'), 1) # make sure they are in the correct order self.assertTrue(text.find("des_vars.x") < text.find('mult.y')) num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()]) self.assertEqual(8, num_non_empty_lines) # Promoted names - no print arrays stream = cStringIO() prob.model.list_outputs(values=True, prom_name=True, print_arrays=False, out_stream=stream) text = stream.getvalue() self.assertEqual(text.count(' x |10.0| x'), 1) self.assertEqual(text.count(' y |110.0| y'), 1) num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()]) self.assertEqual(num_non_empty_lines, 11) # Hierarchical - no print arrays stream = cStringIO() prob.model.list_outputs(values=True, units=True, shape=True, bounds=True, residuals=True, scaling=True, hierarchical=True, print_arrays=False, out_stream=stream) text = stream.getvalue() self.assertEqual(text.count('top'), 1) self.assertEqual(text.count(' des_vars'), 1) self.assertEqual(text.count(' x'), 1) self.assertEqual(text.count(' mult'), 1) self.assertEqual(text.count(' y'), 1) num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()]) self.assertEqual(num_non_empty_lines, 11) # Need to explicitly set this to make sure all ways of running this test # result in the same format of the output. When running this test from the # top level via testflo, the format comes out different than if the test is # run individually opts = { 'edgeitems': 3, 'infstr': 'inf', 'linewidth': 75, 'nanstr': 'nan', 'precision': 8, 'suppress': False, 'threshold': 1000, } from distutils.version import LooseVersion if LooseVersion(np.__version__) >= LooseVersion("1.14"): opts['legacy'] = '1.13' with printoptions(**opts): # logging outputs # out_stream - not hierarchical - extras - print_arrays stream = cStringIO() prob.model.list_outputs(values=True, units=True, shape=True, bounds=True, residuals=True, scaling=True, hierarchical=False, print_arrays=True, out_stream=stream) text = stream.getvalue() self.assertEqual(text.count('2 Explicit Output'), 1) self.assertEqual(text.count('value:'), 2) self.assertEqual(text.count('resids:'), 2) self.assertEqual(text.count('['), 4) # make sure they are in the correct order self.assertTrue(text.find("des_vars.x") < text.find('mult.y')) num_non_empty_lines = sum( [1 for s in text.splitlines() if s.strip()]) self.assertEqual(37, num_non_empty_lines) # Hierarchical stream = cStringIO() prob.model.list_outputs(values=True, units=True, shape=True, bounds=True, residuals=True, scaling=True, hierarchical=True, print_arrays=True, out_stream=stream) text = stream.getvalue() self.assertEqual(text.count('2 Explicit Output'), 1) self.assertEqual(text.count('value:'), 2) self.assertEqual(text.count('resids:'), 2) self.assertEqual(text.count('['), 4) self.assertEqual(text.count('top'), 1) self.assertEqual(text.count(' des_vars'), 1) self.assertEqual(text.count(' x'), 1) self.assertEqual(text.count(' mult'), 1) self.assertEqual(text.count(' y'), 1) num_non_empty_lines = sum( [1 for s in text.splitlines() if s.strip()]) self.assertEqual(num_non_empty_lines, 40)
def setup(self): m = 3 # Shape of the vectors vec_shape = (m, ) # Values for the two vectors vec1 = np.arange(m) vec2 = np.arange(m, 2 * m) # Adding the vectors to omtools vec1 = self.declare_input('vec1', val=vec1) vec2 = self.declare_input('vec2', val=vec2) # Vector-Vector Outer Product self.register_output('VecVecOuter', ot.outer(vec1, vec2)) prob = Problem() prob.model = ExampleVectorVector() prob.setup(force_alloc_complex=True) prob.run_model() print('vec1', prob['vec1'].shape) print(prob['vec1']) print('vec2', prob['vec2'].shape) print(prob['vec2']) print('VecVecOuter', prob['VecVecOuter'].shape) print(prob['VecVecOuter'])
from openmdao.api import Problem from omtools.api import Group import numpy as np class ExampleSimple(Group): def setup(self): z = self.create_indep_var('z', val=10) prob = Problem() prob.model = ExampleSimple() prob.setup(force_alloc_complex=True) prob.run_model() print('z', prob['z'].shape) print(prob['z'])
super(Mda, self).setup() def create_structure(self): return Structure(self.scalers) def create_aerodynamics(self): return Aerodynamics(self.scalers) def create_propulsion(self): return Propulsion(self.scalers) if __name__ == "__main__": parser = OptionParser() parser.add_option("-n", "--no-n2", action="store_false", dest='n2_view', default=True, help="display N2 openmdao viewer") (options, args) = parser.parse_args() problem = Problem() problem.model = Mda() problem.setup() problem.final_setup() if options.n2_view: view_model(problem)
from openmdao.api import Problem from omtools.api import Group import omtools.api as ot import numpy as np class ErrorTypeNotPositive(Group): def setup(self): # Shape of the tensor shape = (2, 3, 4, 5) # Number of elements in the tensor num_of_elements = np.prod(shape) # Creating a numpy tensor with the desired shape and size tensor = np.arange(num_of_elements).reshape(shape) # Declaring in1 as input tensor in1 = self.declare_input('in1', val=tensor) # Computing the 6-norm on in1 without specifying an axis self.register_output('axis_free_pnorm', ot.pnorm(in1, pnorm_type=-2)) prob = Problem() prob.model = ErrorTypeNotPositive() prob.setup(force_alloc_complex=True) prob.run_model()
self.connect('totals.h','exit_static.ht') self.connect('totals.S','exit_static.S') self.connect('Fl_O:tot:P','exit_static.guess:Pt') self.connect('totals.gamma', 'exit_static.guess:gamt') if __name__ == "__main__": from collections import OrderedDict from openmdao.api import Problem, IndepVarComp # np.seterr(all='raise') p = Problem() p.model = FlowStart() # p.root.add('init_prod', IndepVarComp('init_prod_amounts', p.root.totals.thermo.init_prod_amounts), promotes=['*']) p.model.add_subsystem('temp', IndepVarComp('T', 4000., units="degR"), promotes=["*"]) p.model.add_subsystem('pressure', IndepVarComp('P', 1.0342, units="bar"), promotes=["*"]) # p.root.add('MN', IndepVarComp('MN_target', .3), promotes=["*"]) p.model.add_subsystem('W', IndepVarComp('W', 100.0), promotes=['*']) p.setup() def find_order(group): subs = OrderedDict() for s in group.subsystems(): if isinstance(s, Group): subs[s.name] = find_order(s) else:
# self.nonlinear_solver.options['maxiter'] = 20 # self.linear_solver = DirectSolver() def setup(self): super(Trajectoire, self).setup() class TrajectoireFactory(TrajectoireFactoryBase): """ A factory to create disciplines of Trajectoire analysis """ pass if __name__ == "__main__": parser = OptionParser() parser.add_option("-n", "--no-n2", action="store_false", dest='n2_view', default=True, help="display N2 openmdao viewer") (options, args) = parser.parse_args() problem = Problem() problem.model = Trajectoire() problem.setup() problem.final_setup() if options.n2_view: from packaging import version if version.parse(OPENMDAO_VERSION) < version.parse("2.10.0"): from openmdao.api import view_model as n2 else: from openmdao.visualization.n2_viewer.n2_viewer import n2 n2(problem)
from omtools.api import Group import omtools.api as ot import numpy as np class ExampleMultipleVector(Group): def setup(self): n = 3 # Declare a vector of length 3 as input v1 = self.declare_input('v1', val=np.arange(n)) # Declare another vector of length 3 as input v2 = self.declare_input('v2', val=np.arange(n, 2 * n)) # Output the elementwise average of vectors v1 and v2 self.register_output('multiple_vector_average', ot.average(v1, v2)) prob = Problem() prob.model = ExampleMultipleVector() prob.setup(force_alloc_complex=True) prob.run_model() print('v1', prob['v1'].shape) print(prob['v1']) print('v2', prob['v2'].shape) print(prob['v2']) print('multiple_vector_average', prob['multiple_vector_average'].shape) print(prob['multiple_vector_average'])
print("Not enough power to charge battery") Mi *= exp(-DVi/(I_sp*g0)) #Current Total Mass t += t_c+t_dc ShadeTime = max(GetDarkTime(R_0),GetDarkTime(R_f)) outputs['M_batt,min'] = P_req*ShadeTime/(E_sp*eta_dis) #linear overshoot correction t -= (t_c+t_dc)*(Ri-R_f)/(Ri-Rimin1) #Outputs print(M_st) outputs['M_d'] = M_0-(M_u+M_ps+M_p+M_st) outputs['t_tot']= t outputs['M_p'] = M_p if __name__ == '__main__': from openmdao.api import Group, Problem import time start_time = time.time() p = Problem() p.model = Group() p.model.add_subsystem('test1',MBOne(Sat='H2Sat1'),promotes=['*']) p.setup() p['M_sa'] = 100 p['M_batt'] = 20 p.run_model() print(p['M_d']) print("total orbit transfer time in days",p['t_tot']/(3600*24)) print("Mbattmin is",p['M_batt,min']) print(f"executed in {(time.time()-start_time)} seconds")
def test_for_docs_array_list_vars_options(self): import numpy as np from openmdao.api import Problem, Group, IndepVarComp, ExplicitComponent class ArrayAdder(ExplicitComponent): """ Just a simple component that has array inputs and outputs """ def __init__(self, size): super(ArrayAdder, self).__init__() self.size = size def setup(self): self.add_input('x', val=np.zeros(self.size), units='inch') self.add_output('y', val=np.zeros(self.size), units='ft') def compute(self, inputs, outputs): outputs['y'] = inputs['x'] + 10.0 size = 30 prob = Problem() prob.model = Group() prob.model.add_subsystem('des_vars', IndepVarComp('x', np.ones(size), units='inch'), promotes=['x']) prob.model.add_subsystem('mult', ArrayAdder(size), promotes=['x', 'y']) prob.setup(check=False) prob['x'] = np.arange(size) prob.run_driver() prob.model.list_inputs(values=True, units=True, hierarchical=True, print_arrays=True) with printoptions(edgeitems=3, infstr='inf', linewidth=75, nanstr='nan', precision=8, suppress=False, threshold=1000, formatter=None): prob.model.list_outputs(values=True, implicit=False, units=True, shape=True, bounds=True, residuals=True, scaling=True, hierarchical=False, print_arrays=True) prob.model.list_outputs(values=True, implicit=False, units=True, shape=True, bounds=True, residuals=True, scaling=True, hierarchical=True, print_arrays=True)
import numpy as np import matplotlib.pylab as plt from openmdao.api import Problem from openmdao.api import SqliteRecorder, ScipyOptimizeDriver #, pyOptSparseDriver from ssbj_idf_mda import SSBJ_IDF_MDA from ssbj_mda import init_ssbj_mda # pylint: disable=C0103 # Optimization problem scalers = init_ssbj_mda() print(scalers) prob = Problem() prob.model = SSBJ_IDF_MDA(scalers) # Optimizer options prob.driver = ScipyOptimizeDriver() # prob.driver = pyOptSparseDriver() optimizer = 'SLSQP' prob.driver.options['optimizer'] = optimizer #prob.driver.options['tol'] = 1e-3 #prob.driver.options['debug_print'] = ['desvars','ln_cons','nl_cons','objs'] #Design variables prob.model.add_design_var('z', lower=np.array([0.2, 0.666, 0.875, 0.45, 0.72, 0.5]), upper=np.array([1.8, 1.333, 1.125, 1.45, 1.27, 1.5])) prob.model.add_design_var('x_str', lower=np.array([0.4, 0.75]),