def setup(self): self.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) self.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) self.mda = mda = self.add_subsystem('mda', Group(), promotes=['x', 'z', 'y1', 'y2']) mda.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) mda.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0, y1=0.0, y2=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) nl = self.options['nonlinear_solver'] self.nonlinear_solver = nl() if inspect.isclass(nl) else nl if self.options['nl_atol']: self.nonlinear_solver.options['atol'] = self.options['nl_atol'] if self.options['nl_maxiter']: self.nonlinear_solver.options['maxiter'] = self.options['nl_maxiter'] ln = self.options['linear_solver'] self.linear_solver = ln() if inspect.isclass(ln) else ln if self.options['ln_atol']: self.linear_solver.options['atol'] = self.options['ln_atol'] if self.options['ln_maxiter']: self.linear_solver.options['maxiter'] = self.options['ln_maxiter']
def setup(self): self.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) self.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) self.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) self.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) self.nonlinear_solver = self.metadata['nonlinear_solver'] if self.metadata['nl_atol']: self.nonlinear_solver.options['atol'] = self.metadata['nl_atol'] if self.metadata['nl_maxiter']: self.nonlinear_solver.options['maxiter'] = self.metadata['nl_maxiter'] self.linear_solver = self.metadata['linear_solver'] if self.metadata['ln_atol']: self.linear_solver.options['atol'] = self.metadata['ln_atol'] if self.metadata['ln_maxiter']: self.linear_solver.options['maxiter'] = self.metadata['ln_maxiter']
def setUp(self): model = Group() ivc = IndepVarComp() mapdata = SampleMap() params = mapdata.param_data x, y, z = params outs = mapdata.output_data z = outs[0] ivc.add_output('x', x['default'], units=x['units']) ivc.add_output('y', y['default'], units=y['units']) ivc.add_output('z', z['default'], units=z['units']) model.add_subsystem('des_vars', ivc, promotes=["*"]) comp = MetaModelStructured(method='slinear', extrapolate=True) for param in params: comp.add_input(param['name'], param['default'], param['values']) for out in outs: comp.add_output(out['name'], out['default'], out['values']) model.add_subsystem('comp', comp, promotes=["*"]) self.prob = Problem(model) self.prob.setup() self.prob['x'] = 1.0 self.prob['y'] = 0.75 self.prob['z'] = -1.7
def setup(self): self.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) self.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) cycle = self.add_subsystem('cycle', Group(), promotes=['x', 'z', 'y1', 'y2']) cycle.add_subsystem('d1', SellarDis1(), promotes=['x', 'z', 'y1', 'y2']) cycle.add_subsystem('d2', SellarDis2(), promotes=['z', 'y1', 'y2']) self.add_subsystem('obj_cmp', 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', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) self.nonlinear_solver = NonlinearBlockGS() self.nonlinear_solver = self.options['nonlinear_solver'] if self.options['nl_atol']: self.nonlinear_solver.options['atol'] = self.options['nl_atol'] if self.options['nl_maxiter']: self.nonlinear_solver.options['maxiter'] = self.options[ 'nl_maxiter']
def get_cd_trim(cl): ivc = IndepVarComp() ivc.add_output( "data:aerodynamics:aircraft:cruise:CL", 150 * [cl] ) # needed because size of input array is fixed problem = run_system(CdTrim(), ivc) return problem["data:aerodynamics:aircraft:cruise:CD:trim"][0]
def setup(self): self.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) self.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) sub = self.add_subsystem('sub', Group(), promotes=[ 'x', 'z', 'y1', 'state_eq.y2_actual', 'state_eq.y2_command', 'd1.y2', 'd2.y2' ]) subgrp = sub.add_subsystem( 'state_eq_group', Group(), promotes=['state_eq.y2_actual', 'state_eq.y2_command']) subgrp.add_subsystem('state_eq', StateConnection()) sub.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1']) sub.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1']) self.connect('state_eq.y2_command', 'd1.y2') self.connect('d2.y2', 'state_eq.y2_actual') self.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0, y1=0.0, y2=0.0), promotes=['x', 'z', 'y1', 'obj']) self.connect('d2.y2', 'obj_cmp.y2') self.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) self.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2']) self.connect('d2.y2', 'con_cmp2.y2') nl = self.options['nonlinear_solver'] self.nonlinear_solver = nl() if inspect.isclass(nl) else nl if self.options['nl_atol']: self.nonlinear_solver.options['atol'] = self.options['nl_atol'] if self.options['nl_maxiter']: self.nonlinear_solver.options['maxiter'] = self.options[ 'nl_maxiter'] ln = self.options['linear_solver'] self.linear_solver = ln() if inspect.isclass(ln) else ln if self.options['ln_atol']: self.linear_solver.options['atol'] = self.options['ln_atol'] if self.options['ln_maxiter']: self.linear_solver.options['maxiter'] = self.options['ln_maxiter']
def test_compute(): """ Tests a simple XFOIL run""" if pth.exists(XFOIL_RESULTS): shutil.rmtree(XFOIL_RESULTS) ivc = IndepVarComp() ivc.add_output("xfoil:unit_reynolds", 18000000) ivc.add_output("xfoil:mach", 0.80) ivc.add_output("data:geometry:wing:thickness_ratio", 0.1284) ivc.add_output("xfoil:length", 1.0, units="m") xfoil_comp = XfoilPolar(alpha_start=15.0, alpha_end=25.0, iter_limit=20, xfoil_exe_path=xfoil_path) problem = run_system(xfoil_comp, ivc) assert problem["xfoil:CL_max_2D"] == pytest.approx(1.9, 1e-2) assert not pth.exists(XFOIL_RESULTS) # Deactivate warnings for wished crash of xfoil warnings.simplefilter("ignore") xfoil_comp = XfoilPolar( alpha_start=12.0, alpha_end=20.0, iter_limit=20, xfoil_exe_path=xfoil_path) # will stop before real max CL problem = run_system(xfoil_comp, ivc) assert problem["xfoil:CL_max_2D"] == pytest.approx(1.9, 1e-2) assert not pth.exists(XFOIL_RESULTS) xfoil_comp = XfoilPolar(alpha_start=50.0, alpha_end=55.0, iter_limit=2, xfoil_exe_path=xfoil_path) # will not converge problem = run_system(xfoil_comp, ivc) assert problem["xfoil:CL_max_2D"] == pytest.approx(DEFAULT_2D_CL_MAX, 1e-2) assert not pth.exists(XFOIL_RESULTS) # Reactivate warnings warnings.simplefilter("default") xfoil_comp = XfoilPolar(iter_limit=20, result_folder_path=XFOIL_RESULTS, xfoil_exe_path=xfoil_path) problem = run_system(xfoil_comp, ivc) assert problem["xfoil:CL_max_2D"] == pytest.approx(1.9, 1e-2) assert pth.exists(XFOIL_RESULTS) assert pth.exists(pth.join(XFOIL_RESULTS, "polar_result.txt")) # remove folder if pth.exists(XFOIL_RESULTS): shutil.rmtree(XFOIL_RESULTS)
def __init__(self): super(FanIn, self).__init__() self.add_subsystem('p1', IndepVarComp('x1', 1.0)) self.add_subsystem('p2', IndepVarComp('x2', 1.0)) self.add_subsystem('comp1', ExecComp(['y=-2.0*x'])) self.add_subsystem('comp2', ExecComp(['y=5.0*x'])) self.add_subsystem('comp3', ExecComp(['y=3.0*x1+7.0*x2'])) self.connect("comp1.y", "comp3.x1") self.connect("comp2.y", "comp3.x2") self.connect("p1.x1", "comp1.x") self.connect("p2.x2", "comp2.x")
def test_solver_debug_print(self, name, solver): p = Problem() model = p.model model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') model.connect('ground.V', 'circuit.Vg') p.setup() nl = model.circuit.nonlinear_solver = solver() nl.options['debug_print'] = True # suppress solver output for test nl.options['iprint'] = model.circuit.linear_solver.options['iprint'] = -1 # For Broydensolver, don't calc Jacobian try: nl.options['compute_jacobian'] = False except KeyError: pass # set some poor initial guesses so that we don't converge p['circuit.n1.V'] = 10. p['circuit.n2.V'] = 1e-3 opts = {} # formatting has changed in numpy 1.14 and beyond. if LooseVersion(np.__version__) >= LooseVersion("1.14"): opts["legacy"] = '1.13' with printoptions(**opts): # run the model and check for expected output file output = run_model(p) expected_output = '\n'.join([ self.expected_data, "Inputs and outputs at start of iteration " "have been saved to '%s'.\n" % self.filename ]) self.assertEqual(output, expected_output) with open(self.filename, 'r') as f: self.assertEqual(f.read(), self.expected_data)
def __init__(self): super(ConvergeDivergeFlat, self).__init__() self.add_subsystem('iv', IndepVarComp('x', 2.0)) self.add_subsystem('c1', ExecComp(['y1 = 2.0*x1**2', 'y2 = 3.0*x1'])) self.add_subsystem('c2', ExecComp('y1 = 0.5*x1')) self.add_subsystem('c3', ExecComp('y1 = 3.5*x1')) self.add_subsystem( 'c4', ExecComp(['y1 = x1 + 2.0*x2', 'y2 = 3.0*x1 - 5.0*x2'])) self.add_subsystem('c5', ExecComp('y1 = 0.8*x1')) self.add_subsystem('c6', ExecComp('y1 = 0.5*x1')) self.add_subsystem('c7', ExecComp('y1 = x1 + 3.0*x2')) # make connections self.connect('iv.x', 'c1.x1') self.connect('c1.y1', 'c2.x1') self.connect('c1.y2', 'c3.x1') self.connect('c2.y1', 'c4.x1') self.connect('c3.y1', 'c4.x2') self.connect('c4.y1', 'c5.x1') self.connect('c4.y2', 'c6.x1') self.connect('c5.y1', 'c7.x1') self.connect('c6.y1', 'c7.x2')
def __init__(self): super(ConvergeDivergeGroups, self).__init__() self.add_subsystem('iv', IndepVarComp('x', 2.0)) g1 = self.add_subsystem('g1', ParallelGroup()) g1.add_subsystem('c1', ExecComp(['y1 = 2.0*x1**2', 'y2 = 3.0*x1'])) g2 = g1.add_subsystem('g2', ParallelGroup()) g2.add_subsystem('c2', ExecComp('y1 = 0.5*x1')) g2.add_subsystem('c3', ExecComp('y1 = 3.5*x1')) g1.add_subsystem( 'c4', ExecComp(['y1 = x1 + 2.0*x2', 'y2 = 3.0*x1 - 5.0*x2'])) g3 = self.add_subsystem('g3', ParallelGroup()) g3.add_subsystem('c5', ExecComp('y1 = 0.8*x1')) g3.add_subsystem('c6', ExecComp('y1 = 0.5*x1')) self.add_subsystem('c7', ExecComp('y1 = x1 + 3.0*x2')) # make connections self.connect('iv.x', 'g1.c1.x1') g1.connect('c1.y1', 'g2.c2.x1') g1.connect('c1.y2', 'g2.c3.x1') self.connect('g1.g2.c2.y1', 'g1.c4.x1') self.connect('g1.g2.c3.y1', 'g1.c4.x2') self.connect('g1.c4.y1', 'g3.c5.x1') self.connect('g1.c4.y2', 'g3.c6.x1') self.connect('g3.c5.y1', 'c7.x1') self.connect('g3.c6.y1', 'c7.x2')
def __init__(self): super(Diamond, self).__init__() self.add_subsystem('iv', IndepVarComp('x', 2.0)) self.add_subsystem('c1', ExecComp([ 'y1 = 2.0*x1**2', 'y2 = 3.0*x1' ])) sub = self.add_subsystem('sub', ParallelGroup()) sub.add_subsystem('c2', ExecComp('y1 = 0.5*x1')) sub.add_subsystem('c3', ExecComp('y1 = 3.5*x1')) self.add_subsystem('c4', ExecComp([ 'y1 = x1 + 2.0*x2', 'y2 = 3.0*x1 - 5.0*x2' ])) # make connections self.connect('iv.x', 'c1.x1') self.connect('c1.y1', 'sub.c2.x1') self.connect('c1.y2', 'sub.c3.x1') self.connect('sub.c2.y1', 'c4.x1') self.connect('sub.c3.y1', 'c4.x2')
def __init__(self): super(FanInGrouped2, self).__init__() p1 = self.add_subsystem('p1', IndepVarComp('x', 1.0)) p2 = self.add_subsystem('p2', IndepVarComp('x', 1.0)) self.sub = self.add_subsystem('sub', ParallelGroup()) self.sub.add_subsystem('c1', ExecComp(['y=-2.0*x'])) self.sub.add_subsystem('c2', ExecComp(['y=5.0*x'])) self.add_subsystem('c3', ExecComp(['y=3.0*x1+7.0*x2'])) self.connect("sub.c1.y", "c3.x1") self.connect("sub.c2.y", "c3.x2") self.connect("p1.x", "sub.c1.x") self.connect("p2.x", "sub.c2.x")
def test_meta_model_structured_deprecated(self): # run same test as above, only with the deprecated component, # to ensure we get the warning and the correct answer. # self-contained, to be removed when class name goes away. import numpy as np from openmdao.api import Group, Problem, IndepVarComp from openmdao.components.meta_model_structured_comp import MetaModelStructured # deprecated import warnings with warnings.catch_warnings(record=True) as w: xor_interp = MetaModelStructured(method='slinear') self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[0].category, DeprecationWarning)) self.assertEqual(str(w[0].message), "'MetaModelStructured' has been deprecated. Use " "'MetaModelStructuredComp' instead.") # set up inputs and outputs xor_interp.add_input('x', 0.0, training_data=np.array([0.0, 1.0]), units=None) xor_interp.add_input('y', 1.0, training_data=np.array([0.0, 1.0]), units=None) xor_interp.add_output('xor', 1.0, training_data=np.array([[0.0, 1.0], [1.0, 0.0]]), units=None) # Set up the OpenMDAO model model = Group() ivc = IndepVarComp() ivc.add_output('x', 0.0) ivc.add_output('y', 1.0) model.add_subsystem('ivc', ivc, promotes=["*"]) model.add_subsystem('comp', xor_interp, promotes=["*"]) prob = Problem(model) prob.setup() # Now test out a 'fuzzy' XOR prob['x'] = 0.9 prob['y'] = 0.001242 prob.run_model() computed = prob['xor'] actual = 0.8990064 assert_almost_equal(computed, actual) # we can verify all gradients by checking against finite-difference prob.check_partials(compact_print=True)
def test_compute_with_provided_path(): """ Test that option "use_exe_path" works """ ivc = IndepVarComp() ivc.add_output("xfoil:unit_reynolds", 18000000) ivc.add_output("xfoil:mach", 0.20) ivc.add_output("data:geometry:wing:thickness_ratio", 0.1284) ivc.add_output("xfoil:length", 1.0, units="m") xfoil_comp = XfoilPolar(alpha_start=18.0, alpha_end=21.0, iter_limit=20) xfoil_comp.options["xfoil_exe_path"] = "Dummy" # bad name with pytest.raises(ValueError): _ = run_system(xfoil_comp, ivc) xfoil_comp.options["xfoil_exe_path"] = ( xfoil_path if xfoil_path else pth.join( pth.dirname(__file__), pth.pardir, "xfoil699", "xfoil.exe")) problem = run_system(xfoil_comp, ivc) assert problem["xfoil:CL_max_2D"] == pytest.approx(1.85, 1e-2)
def setup(self): sub = self.add_subsystem('sub', ParallelGroup()) sub1 = sub.add_subsystem('sub1', Group()) sub2 = sub.add_subsystem('sub2', Group()) sub1.add_subsystem('p1', IndepVarComp('x', 3.0)) sub2.add_subsystem('p2', IndepVarComp('x', 5.0)) sub1.add_subsystem('c1', ExecComp(['y = 2.0*x'])) sub2.add_subsystem('c2', ExecComp(['y = 4.0*x'])) sub1.connect('p1.x', 'c1.x') sub2.connect('p2.x', 'c2.x') self.add_subsystem('sum', 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')
def setup(self): self.add_subsystem('px', IndepVarComp('x', 1.0)) self.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0]))) self.add_subsystem('d1', SellarDis1withDerivatives()) self.add_subsystem('d2', SellarDis2withDerivatives()) 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('px.x', ['d1.x', 'obj_cmp.x']) self.connect('pz.z', ['d1.z', 'd2.z', 'obj_cmp.z']) self.connect('d1.y1', ['d2.y1', 'obj_cmp.y1', 'con_cmp1.y1']) self.connect('d2.y2', ['d1.y2', 'obj_cmp.y2', 'con_cmp2.y2']) self.nonlinear_solver = NonlinearBlockGS() self.linear_solver = ScipyKrylov()
def __init__(self): super(FanOut, self).__init__() self.add_subsystem('p', IndepVarComp('x', 1.0)) self.add_subsystem('comp1', ExecComp(['y=3.0*x'])) self.add_subsystem('comp2', ExecComp(['y=-2.0*x'])) self.add_subsystem('comp3', ExecComp(['y=5.0*x'])) self.connect("p.x", "comp1.x") self.connect("comp1.y", "comp2.x") self.connect("comp1.y", "comp3.x")
def test_xor(self): import numpy as np from openmdao.api import Group, Problem, IndepVarComp from openmdao.components.meta_model_structured import MetaModelStructured # Create regular grid interpolator instance xor_interp = MetaModelStructured(method='slinear') # set up inputs and outputs xor_interp.add_input('x', 0.0, np.array([0.0, 1.0]), units=None) xor_interp.add_input('y', 1.0, np.array([0.0, 1.0]), units=None) xor_interp.add_output('xor', 1.0, np.array([[0.0, 1.0], [1.0, 0.0]]), units=None) # Set up the OpenMDAO model model = Group() ivc = IndepVarComp() ivc.add_output('x', 0.0) ivc.add_output('y', 1.0) model.add_subsystem('ivc', ivc, promotes=["*"]) model.add_subsystem('comp', xor_interp, promotes=["*"]) prob = Problem(model) prob.setup() # Now test out a 'fuzzy' XOR prob['x'] = 0.9 prob['y'] = 0.001242 prob.run_model() computed = prob['xor'] actual = 0.8990064 assert_almost_equal(computed, actual) # we can verify all gradients by checking against finit-difference prob.check_partials(compact_print=True)
def test_raise_out_of_bounds_error(self): model = Group() ivc = IndepVarComp() mapdata = SampleMap() params = mapdata.param_data x, y, z = params outs = mapdata.output_data z = outs[0] ivc.add_output('x', x['default'], units=x['units']) ivc.add_output('y', y['default'], units=y['units']) ivc.add_output('z', z['default'], units=z['units']) model.add_subsystem('des_vars', ivc, promotes=["*"]) # Need to make sure extrapolate is False for bounds to be checked comp = MetaModelStructured(method='slinear', extrapolate=False) for param in params: comp.add_input(param['name'], param['default'], param['values']) for out in outs: comp.add_output(out['name'], out['default'], out['values']) model.add_subsystem('comp', comp, promotes=["*"]) self.prob = Problem(model) self.prob.setup() self.prob['x'] = 1.0 self.prob['y'] = 0.75 self.prob['z'] = 9.0 # intentionally set to be out of bounds # The interpolating output name is given as a regexp because the exception could # happen with f or g first. The order those are evaluated comes from the keys of # dict so no guarantee on the order except for Python 3.6 ! msg = "Error interpolating output '[f|g]' in 'comp' " + "because input 'comp.z' was " \ "out of bounds \('.*', '.*'\) with value '9.0'" with assertRaisesRegex(self, ValueError, msg): self.run_and_check_derivs(self.prob)
def test_compute_with_provided_path(): """ Test that option "use_exe_path" works """ ivc = IndepVarComp() ivc.add_output("xfoil:reynolds", 1e6) ivc.add_output("xfoil:mach", 0.20) # Clear saved polar results if pth.exists( pth.join(resources.__path__[0], _DEFAULT_AIRFOIL_FILE.replace('af', 'csv'))): os.remove( pth.join(resources.__path__[0], _DEFAULT_AIRFOIL_FILE.replace('af', 'csv'))) if pth.exists( pth.join(resources.__path__[0], _DEFAULT_AIRFOIL_FILE.replace('.af', '_sym.csv'))): os.remove( pth.join(resources.__path__[0], _DEFAULT_AIRFOIL_FILE.replace('.af', '_sym.csv'))) xfoil_comp = XfoilPolar(alpha_start=0.0, alpha_end=20.0, iter_limit=20) xfoil_comp.options["xfoil_exe_path"] = "Dummy" # bad name with pytest.raises(ValueError): _ = run_system(xfoil_comp, ivc) xfoil_comp.options["xfoil_exe_path"] = ( xfoil_path if xfoil_path else pth.join( pth.dirname(__file__), pth.pardir, "xfoil699", "xfoil.exe")) problem = run_system(xfoil_comp, ivc) assert problem["xfoil:CL_max_2D"] == pytest.approx(1.48, 1e-2)
def setUp(self): model = Group() ivc = IndepVarComp() mapdata = SampleMap() params = mapdata.param_data x, y, z = params outs = mapdata.output_data z = outs[0] ivc.add_output('x', x['default'], units=x['units']) ivc.add_output('y', y['default'], units=y['units']) ivc.add_output('z', z['default'], units=z['units']) model.add_subsystem('des_vars', ivc, promotes=["*"]) comp = MetaModelStructured(method='slinear', extrapolate=True) for param in params: comp.add_input(param['name'], param['default'], param['values']) for out in outs: comp.add_output(out['name'], out['default'], out['values']) model.add_subsystem('comp', comp, promotes=["*"]) self.prob = Problem(model) self.prob.setup() self.prob['x'] = 1.0 self.prob['y'] = 0.75 self.prob['z'] = -1.7
def get_cd_compressibility(mach, cl): ivc = IndepVarComp() ivc.add_output("data:aerodynamics:aircraft:cruise:CL", 150 * [cl]) # needed because size of input array is fixed ivc.add_output("data:TLAR:cruise_mach", mach) problem = run_system(CdCompressibility(), ivc) return problem["data:aerodynamics:aircraft:cruise:CD:compressibility"][ 0]
def test_xor(self): import numpy as np from openmdao.api import Group, Problem, IndepVarComp from openmdao.components.meta_model_structured import MetaModelStructured # Create regular grid interpolator instance xor_interp = MetaModelStructured(method='slinear') # set up inputs and outputs xor_interp.add_input('x', 0.0, np.array([0.0, 1.0]), units=None) xor_interp.add_input('y', 1.0, np.array([0.0, 1.0]), units=None) xor_interp.add_output('xor', 1.0, np.array([[0.0, 1.0], [1.0, 0.0]]), units=None) # Set up the OpenMDAO model model = Group() ivc = IndepVarComp() ivc.add_output('x', 0.0) ivc.add_output('y', 1.0) model.add_subsystem('ivc', ivc, promotes=["*"]) model.add_subsystem('comp', xor_interp, promotes=["*"]) prob = Problem(model) prob.setup() # Now test out a 'fuzzy' XOR prob['x'] = 0.9 prob['y'] = 0.001242 prob.run_model() computed = prob['xor'] actual = 0.8990064 assert_almost_equal(computed, actual) # we can verify all gradients by checking against finit-difference prob.check_partials(compact_print=True)
def test_solver_debug_print_feature(self): from openmdao.api import Problem, IndepVarComp, NewtonSolver from openmdao.test_suite.test_examples.test_circuit_analysis import Circuit p = Problem() model = p.model model.add_subsystem('ground', IndepVarComp('V', 0., units='V')) model.add_subsystem('source', IndepVarComp('I', 0.1, units='A')) model.add_subsystem('circuit', Circuit()) model.connect('source.I', 'circuit.I_in') model.connect('ground.V', 'circuit.Vg') p.setup() nl = model.circuit.nonlinear_solver = NewtonSolver() nl.options['iprint'] = 2 nl.options['debug_print'] = True # set some poor initial guesses so that we don't converge p['circuit.n1.V'] = 10. p['circuit.n2.V'] = 1e-3 opts = {} # formatting has changed in numpy 1.14 and beyond. if LooseVersion(np.__version__) >= LooseVersion("1.14"): opts["legacy"] = '1.13' with printoptions(**opts): # run the model p.run_model() with open('rank0_root_0_NLRunOnce_0_circuit_0.dat', 'r') as f: self.assertEqual(f.read(), self.expected_data)
def test_compute(): """ Tests a simple XFOIL run""" if pth.exists(XFOIL_RESULTS): shutil.rmtree(XFOIL_RESULTS) ivc = IndepVarComp() ivc.add_output("xfoil:reynolds", 18000000) ivc.add_output("xfoil:mach", 0.20) ivc.add_output("data:geometry:wing:thickness_ratio", 0.1284) # Base test ---------------------------------------------------------------- xfoil_comp = XfoilPolar(alpha_start=15.0, alpha_end=25.0, iter_limit=20, xfoil_exe_path=xfoil_path) problem = run_system(xfoil_comp, ivc) assert problem["xfoil:CL_max_2D"] == pytest.approx(1.94, 1e-2) assert not pth.exists(XFOIL_RESULTS) # Test that will stop before real max CL ----------------------------------- xfoil_comp = XfoilPolar(alpha_start=12.0, alpha_end=20.0, iter_limit=20, xfoil_exe_path=xfoil_path) problem = run_system(xfoil_comp, ivc) assert problem["xfoil:CL_max_2D"] == pytest.approx(1.92, 1e-2) assert not pth.exists(XFOIL_RESULTS) # Test that will not converge ---------------------------------------------- xfoil_comp = XfoilPolar(alpha_start=50.0, alpha_end=55.0, iter_limit=2, xfoil_exe_path=xfoil_path) problem = run_system(xfoil_comp, ivc) assert problem["xfoil:CL_max_2D"] == pytest.approx(DEFAULT_2D_CL_MAX, 1e-2) assert not pth.exists(XFOIL_RESULTS) # Test that will output results in provided folder ------------------------- xfoil_comp = XfoilPolar(iter_limit=20, result_folder_path=XFOIL_RESULTS, xfoil_exe_path=xfoil_path) problem = run_system(xfoil_comp, ivc) assert problem["xfoil:CL_max_2D"] == pytest.approx(1.94, 1e-2) assert pth.exists(XFOIL_RESULTS) assert pth.exists(pth.join(XFOIL_RESULTS, "polar_result.txt"))
def test_training_gradient(self): model = Group() ivc = IndepVarComp() mapdata = SampleMap() params = mapdata.param_data outs = mapdata.output_data ivc.add_output('x', np.array([-0.3, 0.7, 1.2])) ivc.add_output('y', np.array([0.14, 0.313, 1.41])) ivc.add_output('z', np.array([-2.11, -1.2, 2.01])) ivc.add_output('f_train', outs[0]['values']) ivc.add_output('g_train', outs[1]['values']) comp = MetaModelStructuredComp(training_data_gradients=True, method='cubic', num_nodes=3) for param in params: comp.add_input(param['name'], param['default'], param['values']) for out in outs: comp.add_output(out['name'], out['default'], out['values']) model.add_subsystem('ivc', ivc, promotes=["*"]) model.add_subsystem('comp', comp, promotes=["*"]) prob = Problem(model) prob.setup() prob.run_model() val0 = np.array([ 50.26787317, 49.76106232, 19.66117913]) val1 = np.array([-32.62094041, -31.67449135, -27.46959668]) tol = 1e-5 assert_rel_error(self, prob['f'], val0, tol) assert_rel_error(self, prob['g'], val1, tol) self.run_and_check_derivs(prob)
def setup(self): self.add_subsystem("compute_low_speed_aero", ComputeAerodynamicsLowSpeed(), promotes=["*"]) ivc = IndepVarComp("data:aerodynamics:aircraft:takeoff:mach", val=0.2) self.add_subsystem("mach_low_speed", ivc, promotes=["*"]) self.add_subsystem( "compute_oswald_coeff", OswaldCoefficient(low_speed_aero=True), promotes=["*"] ) self.add_subsystem("comp_re", ComputeReynolds(low_speed_aero=True), promotes=["*"]) self.add_subsystem("initialize_cl", InitializeClPolar(low_speed_aero=True), promotes=["*"]) self.add_subsystem("cd0_wing", Cd0Wing(low_speed_aero=True), promotes=["*"]) self.add_subsystem("cd0_fuselage", Cd0Fuselage(low_speed_aero=True), promotes=["*"]) self.add_subsystem("cd0_ht", Cd0HorizontalTail(low_speed_aero=True), promotes=["*"]) self.add_subsystem("cd0_vt", Cd0VerticalTail(low_speed_aero=True), promotes=["*"]) self.add_subsystem( "cd0_nac_pylons", Cd0NacelleAndPylons(low_speed_aero=True), promotes=["*"] ) self.add_subsystem("cd0_total", Cd0Total(low_speed_aero=True), promotes=["*"]) self.add_subsystem("cd_trim", CdTrim(low_speed_aero=True), promotes=["*"]) self.add_subsystem("get_polar", ComputePolar(type=PolarType.LOW_SPEED), promotes=["*"])
def __init__(self): super(FanInGrouped, self).__init__() iv = self.add_subsystem('iv', IndepVarComp()) iv.add_output('x1', 1.0) iv.add_output('x2', 1.0) iv.add_output('x3', 1.0) self.sub = self.add_subsystem('sub', ParallelGroup()) self.sub.add_subsystem('c1', ExecComp(['y=-2.0*x'])) self.sub.add_subsystem('c2', ExecComp(['y=5.0*x'])) self.add_subsystem('c3', ExecComp(['y=3.0*x1+7.0*x2'])) self.connect("sub.c1.y", "c3.x1") self.connect("sub.c2.y", "c3.x2") self.connect("iv.x1", "sub.c1.x") self.connect("iv.x2", "sub.c2.x")
def __init__(self): super(FanOutGroupedVarSets, self).__init__() self.add_subsystem('iv', IndepVarComp('x', 1.0)) self.add_subsystem('c1', ExecComp('y=3.0*x', x={'var_set': 2})) self.sub = self.add_subsystem('sub', ParallelGroup()) self.sub.add_subsystem('c2', ExecComp('y=-2.0*x', x={'var_set': 2})) self.sub.add_subsystem('c3', ExecComp('y=5.0*x', x={'var_set': 3})) self.add_subsystem('c2', ExecComp('y=x', x={'var_set': 2})) self.add_subsystem('c3', ExecComp('y=x', x={'var_set': 3})) self.connect('iv.x', 'c1.x') self.connect('c1.y', 'sub.c2.x') self.connect('c1.y', 'sub.c3.x') self.connect('sub.c2.y', 'c2.x') self.connect('sub.c3.y', 'c3.x')
def test_training_gradient(self): model = Group() ivc = IndepVarComp() mapdata = SampleMap() params = mapdata.param_data outs = mapdata.output_data ivc.add_output('x', np.array([-0.3, 0.7, 1.2])) ivc.add_output('y', np.array([0.14, 0.313, 1.41])) ivc.add_output('z', np.array([-2.11, -1.2, 2.01])) ivc.add_output('f_train', outs[0]['values']) ivc.add_output('g_train', outs[1]['values']) comp = MetaModelStructured(training_data_gradients=True, method='cubic', num_nodes=3) for param in params: comp.add_input(param['name'], param['default'], param['values']) for out in outs: comp.add_output(out['name'], out['default'], out['values']) model.add_subsystem('ivc', ivc, promotes=["*"]) model.add_subsystem('comp', comp, promotes=["*"]) prob = Problem(model) prob.setup() prob.run_model() val0 = np.array([ 50.26787317, 49.76106232, 19.66117913]) val1 = np.array([-32.62094041, -31.67449135, -27.46959668]) tol = 1e-5 assert_rel_error(self, prob['f'], val0, tol) assert_rel_error(self, prob['g'], val1, tol) self.run_and_check_derivs(prob)
def test_compute(): """ Tests a simple XFOIL run""" if pth.exists(XFOIL_RESULTS): shutil.rmtree(XFOIL_RESULTS) ivc = IndepVarComp() ivc.add_output("xfoil:reynolds", 1e6, units="m**-1") ivc.add_output("xfoil:mach", 0.60) xfoil_comp = XfoilPolar(alpha_start=0.0, alpha_end=15.0, iter_limit=100, symmetrical=True, xfoil_exe_path=xfoil_path) problem = run_system(xfoil_comp, ivc) assert problem["xfoil:CL_max_2D"] == pytest.approx(1.31, 1e-2) assert problem["xfoil:CL_min_2D"] == pytest.approx(-0.59, 1e-2) assert not pth.exists(XFOIL_RESULTS) # Deactivate warnings for wished crash of xfoil warnings.simplefilter("ignore") xfoil_comp = XfoilPolar(alpha_start=50.0, alpha_end=60.0, iter_limit=2, xfoil_exe_path=xfoil_path) # will not converge problem = run_system(xfoil_comp, ivc) assert problem["xfoil:CL_max_2D"] == pytest.approx(DEFAULT_2D_CL_MAX, 1e-2) assert problem["xfoil:CL_min_2D"] == pytest.approx(DEFAULT_2D_CL_MIN, 1e-2) assert not pth.exists(XFOIL_RESULTS) # Reactivate warnings warnings.simplefilter("default") xfoil_comp = XfoilPolar(iter_limit=20, result_folder_path=XFOIL_RESULTS, xfoil_exe_path=xfoil_path) run_system(xfoil_comp, ivc) assert pth.exists(XFOIL_RESULTS) assert pth.exists(pth.join(XFOIL_RESULTS, "polar_result.txt")) # remove folder if pth.exists(XFOIL_RESULTS): shutil.rmtree(XFOIL_RESULTS)
def test_raise_out_of_bounds_error(self): model = Group() ivc = IndepVarComp() mapdata = SampleMap() params = mapdata.param_data x, y, z = params outs = mapdata.output_data z = outs[0] ivc.add_output('x', x['default'], units=x['units']) ivc.add_output('y', y['default'], units=y['units']) ivc.add_output('z', z['default'], units=z['units']) model.add_subsystem('des_vars', ivc, promotes=["*"]) # Need to make sure extrapolate is False for bounds to be checked comp = MetaModelStructured(method='slinear', extrapolate=False) for param in params: comp.add_input(param['name'], param['default'], param['values']) for out in outs: comp.add_output(out['name'], out['default'], out['values']) model.add_subsystem('comp', comp, promotes=["*"]) self.prob = Problem(model) self.prob.setup() self.prob['x'] = 1.0 self.prob['y'] = 0.75 self.prob['z'] = 9.0 # intentionally set to be out of bounds # The interpolating output name is given as a regexp because the exception could # happen with f or g first. The order those are evaluated comes from the keys of # dict so no guarantee on the order except for Python 3.6 ! msg = "Error interpolating output '[f|g]' in 'comp' " + "because input 'comp.z' was " \ "out of bounds \('.*', '.*'\) with value '9.0'" with assertRaisesRegex(self, ValueError, msg): self.run_and_check_derivs(self.prob)
2, 2, 2, var_factory=lambda: numpy.zeros(vec_size)) cname = "C%d" % (num_comps - 1) self.add_objective("%s.o0" % cname) self.add_constraint("%s.o1" % cname, lower=0.0) p = Problem() g = p.model if 'gmres' in sys.argv: from openmdao.solvers.linear.scipy_iter_solver import ScipyKrylov g.linear_solver = ScipyKrylov() g.add_subsystem("P", IndepVarComp('x', numpy.ones(vec_size))) g.add_design_var("P.x") par = g.add_subsystem("par", ParallelGroup()) for pt in range(pts): ptname = "G%d" % pt ptg = par.add_subsystem(ptname, SubGroup()) #create_dyncomps(ptg, num_comps, 2, 2, 2, #var_factory=lambda: numpy.zeros(vec_size)) g.connect("P.x", "par.%s.C0.i0" % ptname) #cname = ptname + '.' + "C%d"%(num_comps-1) #g.add_objective("par.%s.o0" % cname) #g.add_constraint("par.%s.o1" % cname, lower=0.0)
Optimal solution (minimum): x = 6.6667; y = -7.3333 """ x = inputs['x'] y = inputs['y'] outputs['f_xy'] = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0 if __name__ == "__main__": from openmdao.core.problem import Problem from openmdao.core.group import Group from openmdao.core.indepvarcomp import IndepVarComp model = Group() ivc = IndepVarComp() ivc.add_output('x', 3.0) ivc.add_output('y', -4.0) model.add_subsystem('des_vars', ivc) model.add_subsystem('parab_comp', Paraboloid()) model.connect('des_vars.x', 'parab_comp.x') model.connect('des_vars.y', 'parab_comp.y') prob = Problem(model) prob.setup() prob.run_model() print(prob['parab_comp.f_xy']) prob['des_vars.x'] = 5.0 prob['des_vars.y'] = -2.0