def test_feature_vectorized(self): import numpy as np from openmdao.api import Group, Problem, IndepVarComp from openmdao.api import LinearSystemComp, ScipyKrylov model = Group() A = np.array([[5.0, -3.0, 2.0], [1.0, 7.0, -4.0], [1.0, 0.0, 8.0]]) b = np.array([[2.0, -3.0, 4.0], [1.0, 0.0, -1.0]]) model.add_subsystem('p1', IndepVarComp('A', A)) model.add_subsystem('p2', IndepVarComp('b', b)) lingrp = model.add_subsystem('lingrp', Group(), promotes=['*']) lingrp.add_subsystem('lin', LinearSystemComp(size=3, vec_size=2)) model.connect('p1.A', 'lin.A') model.connect('p2.b', 'lin.b') prob = Problem(model) prob.setup() lingrp.linear_solver = ScipyKrylov() prob.run_model() assert_rel_error(self, prob['lin.x'], np.array([[ 0.10596026, -0.16556291, 0.48675497], [ 0.19205298, -0.11258278, -0.14900662]]), .0001)
def test_feature_vectorized_A(self): import numpy as np from openmdao.api import Group, Problem, IndepVarComp from openmdao.api import LinearSystemComp, ScipyKrylov model = Group() A = np.array([[[5.0, -3.0, 2.0], [1.0, 7.0, -4.0], [1.0, 0.0, 8.0]], [[2.0, 3.0, 4.0], [1.0, -1.0, -2.0], [3.0, 2.0, -2.0]]]) b = np.array([[-5.0, 2.0, 3.0], [-1.0, 1.0, -3.0]]) model.add_subsystem('p1', IndepVarComp('A', A)) model.add_subsystem('p2', IndepVarComp('b', b)) lingrp = model.add_subsystem('lingrp', Group(), promotes=['*']) lingrp.add_subsystem('lin', LinearSystemComp(size=3, vec_size=2, vectorize_A=True)) model.connect('p1.A', 'lin.A') model.connect('p2.b', 'lin.b') prob = Problem(model) prob.setup() lingrp.linear_solver = ScipyKrylov() prob.run_model() assert_rel_error(self, prob['lin.x'], np.array([[-0.78807947, 0.66887417, 0.47350993], [ 0.7 , -1.8 , 0.75 ]]), .0001)
def test(self): surface = get_default_surfaces()[0] group = Group() comp = VonMisesTube(surface=surface) indep_var_comp = IndepVarComp() ny = surface['mesh'].shape[1] # define the spar with y out the wing nodes = np.zeros((ny, 3)) nodes[:,0] = np.linspace(0,0.01,ny) nodes[:,1] = np.linspace(0,1,ny) radius = 0.01*np.ones((ny - 1)) disp = np.zeros((ny, 6)) for i in range(6): disp[:,i] = np.linspace(0,0.001,ny) indep_var_comp.add_output('nodes', val=nodes, units='m') indep_var_comp.add_output('radius', val=radius, units='m') indep_var_comp.add_output('disp', val=disp, units='m') group.add_subsystem('vm_comp', comp) group.add_subsystem('indep_var_comp', indep_var_comp) group.connect('indep_var_comp.nodes', 'vm_comp.nodes') group.connect('indep_var_comp.radius', 'vm_comp.radius') group.connect('indep_var_comp.disp', 'vm_comp.disp') run_test(self, group, complex_flag=True, compact_print=True, method='cs', step=1e-40, atol=2e-4, rtol=1e-8)
def test_feature_basic(self): import numpy as np from openmdao.api import Group, Problem, IndepVarComp from openmdao.api import LinearSystemComp, ScipyKrylov model = Group() A = np.array([[5.0, -3.0, 2.0], [1.0, 7.0, -4.0], [1.0, 0.0, 8.0]]) b = np.array([1.0, 2.0, -3.0]) model.add_subsystem('p1', IndepVarComp('A', A)) model.add_subsystem('p2', IndepVarComp('b', b)) lingrp = model.add_subsystem('lingrp', Group(), promotes=['*']) lingrp.add_subsystem('lin', LinearSystemComp(size=3)) model.connect('p1.A', 'lin.A') model.connect('p2.b', 'lin.b') prob = Problem(model) prob.setup() lingrp.linear_solver = ScipyKrylov() prob.run_model() assert_rel_error(self, prob['lin.x'], np.array([0.36423841, -0.00662252, -0.4205298 ]), .0001)
def test_simple_values(self): surface = get_default_surfaces()[0] surface['n_point_masses'] = 1 comp = ComputePointMassLoads(surface=surface) group = Group() indep_var_comp = IndepVarComp() ny = surface['mesh'].shape[1] nodesval = np.array([[0., 0., 0.], [0., 1., 0.], [0., 2., 0.], [0., 3., 0.]]) point_masses = np.array([[1/9.8]]) point_mass_locations = np.array([[.55012, 0.1, 0.]]) indep_var_comp.add_output('nodes', val=nodesval, units='m') indep_var_comp.add_output('point_masses', val=point_masses, units='kg') indep_var_comp.add_output('point_mass_locations', val=point_mass_locations, units='m') group.add_subsystem('indep_var_comp', indep_var_comp, promotes=['*']) group.add_subsystem('compute_point_mass_loads', comp, promotes=['*']) prob = run_test(self, group, complex_flag=True, step=1e-8, atol=1e-5, compact_print=True) truth_array = np.array([0, 0, -1., 0., 0.55012, 0.]) assert_rel_error(self, prob['comp.loads_from_point_masses'][0, :], truth_array, 1e-6)
def test_derivs(self): surface = get_default_surfaces()[0] surface['n_point_masses'] = 2 comp = ComputePointMassLoads(surface=surface) group = Group() indep_var_comp = IndepVarComp() ny = surface['mesh'].shape[1] nodesval = np.array([[0., 0., 0.], [0., 1., 0.], [0., 2., 0.], [0., 3., 0.]]) point_masses = np.array([[2., 1.]]) point_mass_locations = np.array([[2.1, 0.1, 0.2], [3.2, 1.2, 0.3]]) indep_var_comp.add_output('nodes', val=nodesval, units='m') indep_var_comp.add_output('point_masses', val=point_masses, units='kg') indep_var_comp.add_output('point_mass_locations', val=point_mass_locations, units='m') group.add_subsystem('indep_var_comp', indep_var_comp, promotes=['*']) group.add_subsystem('compute_point_mass_loads', comp, promotes=['*']) prob = run_test(self, group, complex_flag=True, step=1e-8, atol=1e-5, compact_print=True)
def test_double_arraycomp(self): # Mainly testing an old bug in the array return for multiple arrays group = Group() group.add_subsystem('x_param1', IndepVarComp('x1', np.ones((2))), promotes=['x1']) group.add_subsystem('x_param2', IndepVarComp('x2', np.ones((2))), promotes=['x2']) mycomp = group.add_subsystem('mycomp', DoubleArrayComp(), promotes=['x1', 'x2', 'y1', 'y2']) prob = Problem() model = prob.model = group model.linear_solver = self.linear_solver_class() prob.set_solver_print(level=0) prob.setup(check=False, mode='fwd') prob.run_model() Jbase = mycomp.JJ of = ['y1', 'y2'] wrt = ['x1', 'x2'] J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict') diff = np.linalg.norm(J['y1', 'x1'] - Jbase[0:2, 0:2]) assert_rel_error(self, diff, 0.0, 1e-8) diff = np.linalg.norm(J['y1', 'x2'] - Jbase[0:2, 2:4]) assert_rel_error(self, diff, 0.0, 1e-8) diff = np.linalg.norm(J['y2', 'x1'] - Jbase[2:4, 0:2]) assert_rel_error(self, diff, 0.0, 1e-8) diff = np.linalg.norm(J['y2', 'x2'] - Jbase[2:4, 2:4]) assert_rel_error(self, diff, 0.0, 1e-8)
def test_vectorized_A(self): """Check against the scipy solver.""" model = Group() x = np.array([[1, 2, -3], [2, -1, 4]]) A = np.array([[[5.0, -3.0, 2.0], [1.0, 7.0, -4.0], [1.0, 0.0, 8.0]], [[2.0, 3.0, 4.0], [1.0, -1.0, -2.0], [3.0, 2.0, -2.0]]]) b = np.einsum('ijk,ik->ij', A, x) model.add_subsystem('p1', IndepVarComp('A', A)) model.add_subsystem('p2', IndepVarComp('b', b)) lingrp = model.add_subsystem('lingrp', Group(), promotes=['*']) lingrp.add_subsystem('lin', LinearSystemComp(size=3, vec_size=2, vectorize_A=True)) model.connect('p1.A', 'lin.A') model.connect('p2.b', 'lin.b') prob = Problem(model) prob.setup() lingrp.linear_solver = ScipyKrylov() prob.set_solver_print(level=0) prob.run_model() assert_rel_error(self, prob['lin.x'], x, .0001) assert_rel_error(self, prob.model._residuals.get_norm(), 0.0, 1e-10) model.run_apply_nonlinear() with model._scaled_context_all(): val = model.lingrp.lin._residuals['x'] assert_rel_error(self, val, np.zeros((2, 3)), tolerance=1e-8)
def setUp(self): from openmdao.api import Group, Problem, IndepVarComp from openmdao.core.tests.test_impl_comp import QuadraticComp group = Group() comp1 = group.add_subsystem('comp1', IndepVarComp()) comp1.add_output('a', 1.0) comp1.add_output('b', 1.0) comp1.add_output('c', 1.0) sub = group.add_subsystem('sub', Group()) sub.add_subsystem('comp2', QuadraticComp()) sub.add_subsystem('comp3', QuadraticComp()) group.connect('comp1.a', 'sub.comp2.a') group.connect('comp1.b', 'sub.comp2.b') group.connect('comp1.c', 'sub.comp2.c') group.connect('comp1.a', 'sub.comp3.a') group.connect('comp1.b', 'sub.comp3.b') group.connect('comp1.c', 'sub.comp3.c') global prob prob = Problem(model=group) prob.setup() prob['comp1.a'] = 1. prob['comp1.b'] = -4. prob['comp1.c'] = 3. prob.run_model()
def test_structural_weight_loads(self): surface = get_default_surfaces()[0] comp = StructureWeightLoads(surface=surface) group = Group() indep_var_comp = IndepVarComp() ny = surface['mesh'].shape[1] #carefully chosen "random" values that give non-uniform derivatives outputs that are good for testing nodesval = np.array([[1., 2., 4.], [20., 22., 7.], [8., 17., 14.], [13., 14., 16.]],dtype=complex) element_weights_val = np.arange(ny-1)+1 indep_var_comp.add_output('nodes', val=nodesval,units='m') indep_var_comp.add_output('element_weights', val=element_weights_val,units='N') group.add_subsystem('indep_var_comp', indep_var_comp, promotes=['*']) group.add_subsystem('load', comp, promotes=['*']) p = run_test(self, group, complex_flag=True, compact_print=True)
def test_const_jacobian(self): import numpy as np from openmdao.api import Problem, Group, IndepVarComp, DirectSolver, DenseJacobian from openmdao.jacobians.tests.test_jacobian_features import SimpleCompConst model = Group() comp = IndepVarComp() for name, val in (('x', 1.), ('y1', np.ones(2)), ('y2', np.ones(2)), ('y3', np.ones(2)), ('z', np.ones((2, 2)))): comp.add_output(name, val) model.add_subsystem('input_comp', comp, promotes=['x', 'y1', 'y2', 'y3', 'z']) problem = Problem(model=model) model.suppress_solver_output = True model.linear_solver = DirectSolver() model.jacobian = DenseJacobian() model.add_subsystem('simple', SimpleCompConst(), promotes=['x', 'y1', 'y2', 'y3', 'z', 'f', 'g']) problem.setup(check=False) problem.run_model() totals = problem.compute_totals(['f', 'g'], ['x', 'y1', 'y2', 'y3', 'z']) assert_rel_error(self, totals['f', 'x'], [[1.]]) assert_rel_error(self, totals['f', 'z'], np.ones((1, 4))) assert_rel_error(self, totals['f', 'y1'], np.zeros((1, 2))) assert_rel_error(self, totals['f', 'y2'], np.zeros((1, 2))) assert_rel_error(self, totals['f', 'y3'], np.zeros((1, 2))) assert_rel_error(self, totals['g', 'x'], [[1], [0], [0], [1]]) assert_rel_error(self, totals['g', 'z'], np.zeros((4, 4))) assert_rel_error(self, totals['g', 'y1'], [[1, 0], [1, 0], [0, 1], [0, 1]]) assert_rel_error(self, totals['g', 'y2'], [[1, 0], [0, 1], [1, 0], [0, 1]]) assert_rel_error(self, totals['g', 'y3'], [[1, 0], [1, 0], [0, 1], [0, 1]])
def test_sparse_jacobian(self): import numpy as np from openmdao.api import Problem, Group, IndepVarComp, ExplicitComponent class SparsePartialComp(ExplicitComponent): def setup(self): self.add_input('x', shape=(4,)) self.add_output('f', shape=(2,)) self.declare_partials(of='f', wrt='x', rows=[0, 1, 1, 1], cols=[0, 1, 2, 3]) def compute_partials(self, inputs, partials): # Corresponds to the [(0,0), (1,1), (1,2), (1,3)] entries. partials['f', 'x'] = [1., 2., 3., 4.] model = Group() comp = IndepVarComp() comp.add_output('x', np.ones(4)) model.add_subsystem('input', comp) model.add_subsystem('example', SparsePartialComp()) model.connect('input.x', 'example.x') problem = Problem(model=model) problem.setup(check=False) problem.run_model() totals = problem.compute_totals(['example.f'], ['input.x']) assert_rel_error(self, totals['example.f', 'input.x'], [[1., 0., 0., 0.], [0., 2., 3., 4.]])
def test_linear_system(self): """Check against the scipy solver.""" model = Group() x = np.array([1, 2, -3]) A = np.array([[5.0, -3.0, 2.0], [1.0, 7.0, -4.0], [1.0, 0.0, 8.0]]) b = A.dot(x) model.add_subsystem('p1', IndepVarComp('A', A)) model.add_subsystem('p2', IndepVarComp('b', b)) lingrp = model.add_subsystem('lingrp', Group(), promotes=['*']) lingrp.add_subsystem('lin', LinearSystemComp(size=3, partial_type="matrix_free")) model.connect('p1.A', 'lin.A') model.connect('p2.b', 'lin.b') prob = Problem(model) prob.setup() lingrp.linear_solver = ScipyKrylov() prob.set_solver_print(level=0) prob.run_model() assert_rel_error(self, prob['lin.x'], x, .0001) assert_rel_error(self, prob.model._residuals.get_norm(), 0.0, 1e-10)
def test_const_jacobian(self): model = Group() comp = IndepVarComp() for name, val in (('x', 1.), ('y1', np.ones(2)), ('y2', np.ones(2)), ('y3', np.ones(2)), ('z', np.ones((2, 2)))): comp.add_output(name, val) model.add_subsystem('input_comp', comp, promotes=['x', 'y1', 'y2', 'y3', 'z']) problem = Problem(model=model) problem.set_solver_print(level=0) model.linear_solver = ScipyKrylov() model.jacobian = COOJacobian() model.add_subsystem('simple', SimpleCompConst(), promotes=['x', 'y1', 'y2', 'y3', 'z', 'f', 'g']) problem.setup(check=False) problem.run_model() totals = problem.compute_totals(['f', 'g'], ['x', 'y1', 'y2', 'y3', 'z']) jacobian = {} jacobian['f', 'x'] = [[1.]] jacobian['f', 'z'] = np.ones((1, 4)) jacobian['f', 'y1'] = np.zeros((1, 2)) jacobian['f', 'y2'] = np.zeros((1, 2)) jacobian['f', 'y3'] = np.zeros((1, 2)) jacobian['g', 'y1'] = [[1, 0], [1, 0], [0, 1], [0, 1]] jacobian['g', 'y2'] = [[1, 0], [0, 1], [1, 0], [0, 1]] jacobian['g', 'y3'] = [[1, 0], [1, 0], [0, 1], [0, 1]] jacobian['g', 'x'] = [[1], [0], [0], [1]] jacobian['g', 'z'] = np.zeros((4, 4)) assert_rel_error(self, totals, jacobian)
def test_shape(self): n = 100 bal = BalanceComp() bal.add_balance('x', shape=(n,)) tgt = IndepVarComp(name='y_tgt', val=4*np.ones(n)) exe = ExecComp('y=x**2', x=np.zeros(n), y=np.zeros(n)) model = Group() model.add_subsystem('tgt', tgt, promotes_outputs=['y_tgt']) model.add_subsystem('exe', exe) model.add_subsystem('bal', bal) model.connect('y_tgt', 'bal.rhs:x') model.connect('bal.x', 'exe.x') model.connect('exe.y', 'bal.lhs:x') model.linear_solver = DirectSolver(assemble_jac=True) model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0) prob = Problem(model) prob.setup() prob['bal.x'] = np.random.rand(n) prob.run_model() assert_almost_equal(prob['bal.x'], 2.0*np.ones(n), decimal=7)
def test_guess_nonlinear_resids_read_only(self): class ImpWithInitial(ImplicitComponent): def setup(self): self.add_input('x', 3.0) self.add_output('y', 4.0) def guess_nonlinear(self, inputs, outputs, resids): # inputs is read_only, should not be allowed resids['y'] = 0. group = Group() group.add_subsystem('px', IndepVarComp('x', 77.0)) group.add_subsystem('comp1', ImpWithInitial()) group.add_subsystem('comp2', ImpWithInitial()) group.connect('px.x', 'comp1.x') group.connect('comp1.y', 'comp2.x') group.nonlinear_solver = NewtonSolver() group.nonlinear_solver.options['maxiter'] = 1 prob = Problem(model=group) prob.set_solver_print(level=0) prob.setup(check=False) with self.assertRaises(ValueError) as cm: prob.run_model() self.assertEqual(str(cm.exception), "Attempt to set value of 'y' in residual vector " "when it is read only.")
def test_guess_nonlinear_inputs_read_only_reset(self): class ImpWithInitial(ImplicitComponent): def setup(self): self.add_input('x', 3.0) self.add_output('y', 4.0) def guess_nonlinear(self, inputs, outputs, resids): raise AnalysisError("It's just a scratch.") group = Group() group.add_subsystem('px', IndepVarComp('x', 77.0)) group.add_subsystem('comp1', ImpWithInitial()) group.add_subsystem('comp2', ImpWithInitial()) group.connect('px.x', 'comp1.x') group.connect('comp1.y', 'comp2.x') group.nonlinear_solver = NewtonSolver() group.nonlinear_solver.options['maxiter'] = 1 prob = Problem(model=group) prob.set_solver_print(level=0) prob.setup(check=False) with self.assertRaises(AnalysisError): prob.run_model() # verify read_only status is reset after AnalysisError prob['comp1.x'] = 111.
def test(self): surface = get_default_surfaces()[0] ny = surface['mesh'].shape[1] group = Group() ivc = IndepVarComp() ivc.add_output('nodes', val=np.random.random_sample((ny, 3))) comp = Weight(surface=surface) group.add_subsystem('ivc', ivc, promotes=['*']) group.add_subsystem('comp', comp, promotes=['*']) run_test(self, group, compact_print=False, complex_flag=True)
def test_group_nested_conn(self): """Example of adding subsystems and issuing connections with nested groups.""" g1 = Group() c1_1 = g1.add_subsystem('comp1', IndepVarComp('x', 5.0)) c1_2 = g1.add_subsystem('comp2', ExecComp('b=2*a')) g1.connect('comp1.x', 'comp2.a') g2 = Group() c2_1 = g2.add_subsystem('comp1', ExecComp('b=2*a')) c2_2 = g2.add_subsystem('comp2', ExecComp('b=2*a')) g2.connect('comp1.b', 'comp2.a') model = Group() model.add_subsystem('group1', g1) model.add_subsystem('group2', g2) model.connect('group1.comp2.b', 'group2.comp1.a') p = Problem(model=model) p.setup() c1_1 = p.model.group1.comp1 c1_2 = p.model.group1.comp2 c2_1 = p.model.group2.comp1 c2_2 = p.model.group2.comp2 self.assertEqual(c1_1.name, 'comp1') self.assertEqual(c1_2.name, 'comp2') self.assertEqual(c2_1.name, 'comp1') self.assertEqual(c2_2.name, 'comp2') c1_1 = p.model.group1.comp1 c1_2 = p.model.group1.comp2 c2_1 = p.model.group2.comp1 c2_2 = p.model.group2.comp2 self.assertEqual(c1_1.name, 'comp1') self.assertEqual(c1_2.name, 'comp2') self.assertEqual(c2_1.name, 'comp1') self.assertEqual(c2_2.name, 'comp2') s = p.model._get_subsystem('') self.assertEqual(s, None) p.set_solver_print(level=0) p.run_model() self.assertEqual(p['group1.comp1.x'], 5.0) self.assertEqual(p['group1.comp2.b'], 10.0) self.assertEqual(p['group2.comp1.b'], 20.0) self.assertEqual(p['group2.comp2.b'], 40.0)
def test(self): surfaces = get_default_surfaces() group = Group() comp = VLMGeometry(surface=surfaces[0]) indep_var_comp = IndepVarComp() indep_var_comp.add_output('def_mesh', val=surfaces[0]['mesh'], units='m') group.add_subsystem('geom', comp) group.add_subsystem('indep_var_comp', indep_var_comp) group.connect('indep_var_comp.def_mesh', 'geom.def_mesh') run_test(self, group)
def test2(self): surfaces = get_default_surfaces() group = Group() comp = MomentCoefficient(surfaces=surfaces) indep_var_comp = IndepVarComp() indep_var_comp.add_output('S_ref_total', val=1e4, units='m**2') group.add_subsystem('moment_calc', comp) group.add_subsystem('indep_var_comp', indep_var_comp) group.connect('indep_var_comp.S_ref_total', 'moment_calc.S_ref_total') run_test(self, group)
def test(self): surface = get_default_surfaces()[0] comp = ComputeTransformationMatrix(surface=surface) group = Group() indep_var_comp = IndepVarComp() ny = surface['mesh'].shape[1] disp = np.random.random_sample((ny, 6)) * 100. indep_var_comp.add_output('disp', val=disp, units='m') group.add_subsystem('indep_var_comp', indep_var_comp, promotes=['*']) group.add_subsystem('trans_mtx', comp, promotes=['*']) run_test(self, group, complex_flag=True, method='cs')
def test(self): surface = get_default_surfaces()[0] group = Group() comp = LoadTransfer(surface=surface) indep_var_comp = IndepVarComp() nx = surface['mesh'].shape[0] ny = surface['mesh'].shape[1] indep_var_comp.add_output('def_mesh', val=np.random.random((nx, ny, 3)), units='m') indep_var_comp.add_output('sec_forces', val=np.random.random((nx-1, ny-1, 3)), units='N') group.add_subsystem('indep_var_comp', indep_var_comp, promotes=['*']) group.add_subsystem('load_transfer', comp, promotes=['*']) run_test(self, group, complex_flag=True, compact_print=False)
def test_assert_no_dict_jacobians_exception_not_expected(self): model = Group(assembled_jac_type='dense') 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.model.linear_solver = DirectSolver(assemble_jac=True) prob.setup(check=False) assert_no_dict_jacobians(prob.model, include_self=True, recurse=True)
def test_fd_options(self): import numpy as np from openmdao.api import Problem, Group, IndepVarComp, ExplicitComponent class FDPartialComp(ExplicitComponent): def setup(self): self.add_input('x', shape=(4,)) self.add_input('y', shape=(2,)) self.add_input('y2', shape=(2,)) self.add_output('f', shape=(2,)) self.declare_partials('f', 'y*', method='fd', form='backward', step=1e-6) self.declare_partials('f', 'x', method='fd', form='central', step=1e-4) def compute(self, inputs, outputs): f = outputs['f'] x = inputs['x'] y = inputs['y'] f[0] = x[0] + y[0] f[1] = np.dot([0, 2, 3, 4], x) + y[1] model = Group() comp = IndepVarComp() comp.add_output('x', np.ones(4)) comp.add_output('y', np.ones(2)) model.add_subsystem('input', comp) model.add_subsystem('example', FDPartialComp()) model.connect('input.x', 'example.x') model.connect('input.y', 'example.y') problem = Problem(model=model) problem.setup(check=False) problem.run_model() totals = problem.compute_totals(['example.f'], ['input.x', 'input.y']) assert_rel_error(self, totals['example.f', 'input.x'], [[1., 0., 0., 0.], [0., 2., 3., 4.]], tolerance=1e-8) assert_rel_error(self, totals['example.f', 'input.y'], [[1., 0.], [0., 1.]], tolerance=1e-8)
def test(self): surfaces = get_default_surfaces() group = Group() comp = RadiusComp(surface=surfaces[0]) ny = surfaces[0]['mesh'].shape[1] indep_var_comp = IndepVarComp() indep_var_comp.add_output('mesh', val=surfaces[0]['mesh'], units='m') indep_var_comp.add_output('t_over_c', val=np.linspace(0.1,0.5,num=ny-1)) group.add_subsystem('radius', comp) group.add_subsystem('indep_var_comp', indep_var_comp) group.connect('indep_var_comp.mesh', 'radius.mesh') group.connect('indep_var_comp.t_over_c', 'radius.t_over_c') run_test(self, group)
def test(self): surface = get_default_surfaces()[0] group = Group() comp = StructuralCG(surface=surface) indep_var_comp = IndepVarComp() ny = surface['mesh'].shape[1] indep_var_comp.add_output('nodes', val=np.random.random((ny, 3)), units='m') indep_var_comp.add_output('structural_weight', val=1., units='N') indep_var_comp.add_output('element_weights', val=np.ones((ny-1)), units='N') group.add_subsystem('indep_var_comp', indep_var_comp, promotes=['*']) group.add_subsystem('structural_cg', comp, promotes=['*']) run_test(self, group, complex_flag=True, compact_print=False)
def test(self): surface = get_default_surfaces()[0] comp = DisplacementTransfer(surface=surface) group = Group() indep_var_comp = IndepVarComp() ny = surface['mesh'].shape[1] mesh = surface['mesh'] indep_var_comp.add_output('mesh', val=mesh, units='m') group.add_subsystem('indep_var_comp', indep_var_comp, promotes=['*']) group.add_subsystem('load', comp, promotes=['*']) run_test(self, group, complex_flag=True)
def test_pass_through(self): group = Group() group.add_subsystem('sys1', IndepVarComp('old_length', 1.0, units='mm', ref=1e5)) group.add_subsystem('sys2', PassThroughLength()) group.connect('sys1.old_length', 'sys2.old_length') prob = Problem(group) prob.setup(check=False) prob.set_solver_print(level=0) prob['sys1.old_length'] = 3.e5 prob.final_setup() assert_rel_error(self, prob['sys1.old_length'], 3.e5) assert_rel_error(self, prob.model._outputs['sys1.old_length'], 3.e5) prob.run_model() assert_rel_error(self, prob['sys2.new_length'], 3.e-1) assert_rel_error(self, prob.model._outputs['sys2.new_length'], 3.e-1)
def test_speed(self): comp = IndepVarComp() comp.add_output('distance', 1., units='km') comp.add_output('time', 1., units='h') group = Group() group.add_subsystem('c1', comp) group.add_subsystem('c2', SpeedComputationWithUnits()) group.connect('c1.distance', 'c2.distance') group.connect('c1.time', 'c2.time') prob = Problem(model=group) prob.setup(check=False) prob.set_solver_print(level=0) prob.run_model() assert_rel_error(self, prob['c1.distance'], 1.0) # units: km assert_rel_error(self, prob['c2.distance'], 1000.0) # units: m assert_rel_error(self, prob['c1.time'], 1.0) # units: h assert_rel_error(self, prob['c2.time'], 3600.0) # units: s assert_rel_error(self, prob['c2.speed'], 1.0) # units: km/h (i.e., kph)
def compute_partials(self, inputs, partials): v_m_s = inputs['v_m_s'] theta_rad = inputs['theta_rad'] partials['vy_m_s', 'v_m_s'] = np.sin(theta_rad) partials['vy_m_s', 'theta_rad'] = v_m_s * np.cos(theta_rad) if __name__ == '__main__': from openmdao.api import Problem, Group, IndepVarComp group = Group() comp = IndepVarComp() comp.add_output('v_m_s') comp.add_output('theta_rad') group.add_subsystem('comp1', comp) comp = VyComp() group.add_subsystem('comp2', comp) group.connect('comp1.v_m_s', 'comp2.v_m_s') group.connect('comp1.theta_rad', 'comp2.theta_rad') prob = Problem() prob.model = group prob.setup() prob.run_model() prob.model.list_outputs() prob.check_partials(compact_print=True)
def setup(self): surfaces = self.options['surfaces'] coupled = Group() for surface in surfaces: name = surface['name'] # Connect the output of the loads component with the FEM # displacement parameter. This links the coupling within the coupled # group that necessitates the subgroup solver. coupled.connect(name + '_loads.loads', name + '.loads') # Perform the connections with the modified names within the # 'aero_states' group. coupled.connect(name + '.normals', 'aero_states.' + name + '_normals') coupled.connect(name + '.def_mesh', 'aero_states.' + name + '_def_mesh') # Connect the results from 'coupled' to the performance groups coupled.connect(name + '.def_mesh', name + '_loads.def_mesh') coupled.connect('aero_states.' + name + '_sec_forces', name + '_loads.sec_forces') # Connect the results from 'aero_states' to the performance groups self.connect('coupled.aero_states.' + name + '_sec_forces', name + '_perf' + '.sec_forces') # Connection performance functional variables self.connect(name + '_perf.CL', 'total_perf.' + name + '_CL') self.connect(name + '_perf.CD', 'total_perf.' + name + '_CD') self.connect('coupled.aero_states.' + name + '_sec_forces', 'total_perf.' + name + '_sec_forces') self.connect('coupled.' + name + '.chords', name + '_perf.aero_funcs.chords') # Connect parameters from the 'coupled' group to the performance # groups for the individual surfaces. self.connect('coupled.' + name + '.disp', name + '_perf.disp') self.connect('coupled.' + name + '.S_ref', name + '_perf.S_ref') self.connect('coupled.' + name + '.widths', name + '_perf.widths') # self.connect('coupled.' + name + '.chords', name + '_perf.chords') self.connect('coupled.' + name + '.lengths', name + '_perf.lengths') self.connect('coupled.' + name + '.cos_sweep', name + '_perf.cos_sweep') # Connect parameters from the 'coupled' group to the total performance group. self.connect('coupled.' + name + '.S_ref', 'total_perf.' + name + '_S_ref') self.connect('coupled.' + name + '.widths', 'total_perf.' + name + '_widths') self.connect('coupled.' + name + '.chords', 'total_perf.' + name + '_chords') self.connect('coupled.' + name + '.b_pts', 'total_perf.' + name + '_b_pts') # Add components to the 'coupled' group for each surface. # The 'coupled' group must contain all components and parameters # needed to converge the aerostructural system. coupled_AS_group = CoupledAS(surface=surface) if surface['distributed_fuel_weight']: promotes = ['load_factor'] else: promotes = [] coupled.add_subsystem(name, coupled_AS_group, promotes_inputs=promotes) # Add a single 'aero_states' component for the whole system within the # coupled group. coupled.add_subsystem('aero_states', VLMStates(surfaces=surfaces), promotes_inputs=['v', 'alpha', 'rho']) # Explicitly connect parameters from each surface's group and the common # 'aero_states' group. for surface in surfaces: name = surface['name'] # Add a loads component to the coupled group coupled.add_subsystem(name + '_loads', LoadTransfer(surface=surface)) """ ### Change the solver settings here ### """ # Set solver properties for the coupled group # coupled.linear_solver = ScipyIterativeSolver() # coupled.linear_solver.precon = LinearRunOnce() coupled.nonlinear_solver = NonlinearBlockGS(use_aitken=True) coupled.nonlinear_solver.options['maxiter'] = 100 coupled.nonlinear_solver.options['atol'] = 1e-7 coupled.nonlinear_solver.options['rtol'] = 1e-30 # coupled.linear_solver = DirectSolver() coupled.linear_solver = DirectSolver(assemble_jac=True) coupled.options['assembled_jac_type'] = 'csc' # coupled.nonlinear_solver = NewtonSolver(solve_subsystems=True) # coupled.nonlinear_solver.options['maxiter'] = 50 coupled.nonlinear_solver.options['iprint'] = 2 """ ### End change of solver settings ### """ # Add the coupled group to the model problem self.add_subsystem('coupled', coupled, promotes_inputs=['v', 'alpha', 'rho']) for surface in surfaces: name = surface['name'] # Add a performance group which evaluates the data after solving # the coupled system perf_group = CoupledPerformance(surface=surface) self.add_subsystem(name + '_perf', perf_group, promotes_inputs=['rho', 'v', 'alpha', 're', 'Mach_number']) # Add functionals to evaluate performance of the system. # Note that only the interesting results are promoted here; not all # of the parameters. self.add_subsystem('total_perf', TotalPerformance(surfaces=surfaces, user_specified_Sref=self.options['user_specified_Sref'], internally_connect_fuelburn=self.options['internally_connect_fuelburn']), promotes_inputs=['v', 'rho', 'empty_cg', 'total_weight', 'CT', 'speed_of_sound', 'R', 'Mach_number', 'W0', 'load_factor', 'S_ref_total'], promotes_outputs=['L_equals_W', 'fuelburn', 'CL', 'CD', 'CM', 'cg'])
def test_nested_promotion_errors(self): """ Tests for error-handling for promoted input variable names. """ c1 = IndepVarComp('x') c2 = ExecComp('y=2*x') c3 = ExecComp('z=3*x') g = Group(assembled_jac_type='dense') g.add_subsystem('c2', c2, promotes=['*']) g.add_subsystem('c3', c3, promotes=['*']) g.linear_solver = DirectSolver(assemble_jac=True) model = Group() model.add_subsystem('c1', c1, promotes=['*']) model.add_subsystem('g', g) p = Problem(model) p.setup() # ------------------------------------------------------------------- msg1 = "The promoted name g.x is invalid because it refers to multiple inputs: " \ "[g.c2.x, g.c3.x] that are not connected to an output variable." # inputs (g.x is not connected) # with assertRaisesRegex(self, RuntimeError, msg1.format('g.x')): with self.assertRaises(Exception) as context: p['g.x'] = 5.0 p.final_setup() self.assertEqual(str(context.exception), msg1) # Repeat test for post final_setup when vectors are allocated. p = Problem(model) p.setup() p.final_setup() # ------------------------------------------------------------------- # inputs (g.x is not connected) with self.assertRaises(Exception) as context: p['g.x'] = 5.0 p.final_setup() self.assertEqual(str(context.exception), msg1) # Start from a clean state again p = Problem(model) p.setup() with self.assertRaises(Exception) as context: self.assertEqual(p['g.x'], 5.0) self.assertEqual(str(context.exception), msg1) msg2 = "The promoted name x is invalid because it refers to multiple inputs: " \ "[g.c2.x, g.c3.x] that are not connected to an output variable." jac = g.linear_solver._assembled_jac # d(outputs)/d(inputs) with self.assertRaises(Exception) as context: jac['y', 'x'] = 5.0 self.assertEqual(str(context.exception), msg2) with self.assertRaises(Exception) as context: self.assertEqual(jac['y', 'x'], 5.0) self.assertEqual(str(context.exception), msg2) # ------------------------------------------------------------------- # Repeat test for post final_setup when vectors are allocated. p = Problem(model) p.setup() p.final_setup() with self.assertRaises(Exception) as context: self.assertEqual(p['g.x'], 5.0) self.assertEqual(str(context.exception), msg1) # d(outputs)/d(inputs) with self.assertRaises(Exception) as context: jac['y', 'x'] = 5.0 self.assertEqual(str(context.exception), msg2) with self.assertRaises(Exception) as context: self.assertEqual(jac['y', 'x'], 5.0) self.assertEqual(str(context.exception), msg2) # ------------------------------------------------------------------- msg1 = "The promoted name g.x is invalid because it refers to multiple inputs: " \ "[g.c2.x ,g.c3.x]. Access the value from the connected output variable x instead." # From here, 'g.x' has a valid source. model.connect('x', 'g.x') p = Problem(model) p.setup() # inputs (g.x is connected to x) p['g.x'] = 5.0 with self.assertRaises(Exception) as context: p.final_setup() self.assertEqual(str(context.exception), msg1) # Repeat test for post final_setup when vectors are allocated. p = Problem(model) p.setup() p.final_setup() # inputs (g.x is connected to x) with self.assertRaises(Exception) as context: p['g.x'] = 5.0 self.assertEqual(str(context.exception), msg1) # Final test, the getitem p = Problem(model) p.setup() with self.assertRaises(Exception) as context: self.assertEqual(p['g.x'], 5.0) self.assertEqual(str(context.exception), msg1) # d(outputs)/d(inputs) with self.assertRaises(Exception) as context: jac['y', 'x'] = 5.0 self.assertEqual(str(context.exception), msg2) with self.assertRaises(Exception) as context: self.assertEqual(jac['y', 'x'], 5.0) # Start from a clean state again self.assertEqual(str(context.exception), msg2) # Repeat test for post final_setup when vectors are allocated. p = Problem(model) p.setup() p.final_setup() with self.assertRaises(Exception) as context: self.assertEqual(p['g.x'], 5.0) self.assertEqual(str(context.exception), msg1) # d(outputs)/d(inputs) with self.assertRaises(Exception) as context: jac['y', 'x'] = 5.0 self.assertEqual(str(context.exception), msg2) with self.assertRaises(Exception) as context: self.assertEqual(jac['y', 'x'], 5.0) self.assertEqual(str(context.exception), msg2)
from cost.fuel_comp import FuelComp from cost.main_comp import MainComp from cost.rdte_comp import RDTEComp from cost.mtow_comp import MTOWComp prob = Problem() model = Group() comp = IndepVarComp() comp.add_output('velocity_ms', val=466) comp.add_output('specific_fuel_consum', val=0.5) comp.add_output('We', val=187346) comp.add_output('Wfr', val=34300) model.add_subsystem('inputs_comp', comp, promotes=['*']) comp = IndepVarComp() comp.add_output('MHFH', val=10) ## Maintaince Hour Per Flight Hour comp.add_output('M_max', val=0.83) ## Engine max mach number comp.add_output('T_max', val=74400) ## Engine max Thrust comp.add_output('EN', val=500 * 2) ## Engine Number comp.add_output('FH', val=3500) ###FTA flight test comp.add_output('FTA', val=3) ###FTA flight test comp.add_output('Q', val=500) ### Less number production comp.add_output('Tinlet', val=3303) ## Turbine inlet temperature prob.model.add_subsystem('constants', comp, promotes=['*']) comp = FlyawayComp() model.add_subsystem('fl_comp', comp, promotes=['*'])
def test_recording_remote_voi(self): # Create a parallel model model = Group() model.add_subsystem('par', ParallelGroup()) model.par.add_subsystem('G1', Mygroup()) model.par.add_subsystem('G2', Mygroup()) model.connect('par.G1.y', 'Obj.y1') model.connect('par.G2.y', 'Obj.y2') model.add_subsystem('Obj', ExecComp('obj=y1+y2')) model.add_objective('Obj.obj') # Configure driver to record VOIs on both procs driver = ScipyOptimizeDriver(disp=False) driver.recording_options['record_desvars'] = True driver.recording_options['record_responses'] = True driver.recording_options['record_objectives'] = True driver.recording_options['record_constraints'] = True driver.recording_options['includes'] = ['par.G1.y', 'par.G2.y'] driver.add_recorder(self.recorder) # Create problem and run driver prob = Problem(model, driver) prob.setup() t0, t1 = run_driver(prob) prob.cleanup() # Since the test will compare the last case recorded, just check the # current values in the problem. This next section is about getting those values # These involve collective gathers so all ranks need to run this expected_outputs = prob.driver.get_design_var_values() expected_outputs.update(prob.driver.get_objective_values()) expected_outputs.update(prob.driver.get_constraint_values()) # includes for outputs are specified as promoted names but we need absolute names prom2abs = model._var_allprocs_prom2abs_list['output'] abs_includes = [ prom2abs[n][0] for n in prob.driver.recording_options['includes'] ] # Absolute path names of includes on this rank rrank = model.comm.rank rowned = model._owning_rank local_includes = [n for n in abs_includes if rrank == rowned[n]] # Get values for all vars on this rank inputs, outputs, residuals = model.get_nonlinear_vectors() # Get values for includes on this rank local_vars = {n: outputs[n] for n in local_includes} # Gather values for includes on all ranks all_vars = model.comm.gather(local_vars, root=0) if prob.comm.rank == 0: # Only on rank 0 do we have all the values. The all_vars variable is a list of # dicts from all ranks 0,1,... In this case, just ranks 0 and 1 dct = all_vars[-1] for d in all_vars[:-1]: dct.update(d) expected_includes = { 'par.G1.Cy.y': dct['par.G1.Cy.y'], 'par.G2.Cy.y': dct['par.G2.Cy.y'], } expected_outputs.update(expected_includes) coordinate = [0, 'ScipyOptimize_SLSQP', (driver.iter_count - 1, )] expected_data = ((coordinate, (t0, t1), expected_outputs, None), ) assertDriverIterDataRecorded(self, expected_data, self.eps)
interp.add_output('ct_over_cp',1.5,raymer_static_data) return interp def static_propeller_map_highpower(vec_size=1): #Factoring up the thrust of the Raymer static thrust data to match the high power data cp = np.linspace(0.0,1.0,41) factored_raymer_static_data = np.array([2.5,3.0,2.55,2.0,1.85,1.5,1.25,1.05,0.95,0.86,0.79,0.70,0.62,0.53,0.45,0.38,0.32,0.28,0.24,0.21,0.18,0.16,0.14,0.12,0.10,0.09,0.08,0.08,0.08,0.08,0.08,0.08,0.08,0.08,0.08,0.08,0.08,0.08,0.08,0.08,0.08]) factored_raymer_static_data[6:] = factored_raymer_static_data[6:]*1.2 interp = MetaModelStructuredComp(method='cubic',extrapolate=True,vec_size=vec_size) interp.add_input('cp',0.15,cp) interp.add_output('ct_over_cp',1.5,factored_raymer_static_data) return interp if __name__ == "__main__": interp = propeller_map() #interp = static_propeller_map() # Set up the OpenMDAO model model = Group() model.add_subsystem('comp', interp, promotes=["*"]) prob = Problem(model) prob.setup() # set inputs prob['J'] = 1.75 prob['cp'] = 0.017714165222329097 prob.run_model() computed = prob['eta_prop'] #computed = prob['ct_over_cp'] prob.check_partials(compact_print=True) # we can verify all gradients by checking against finit-difference
def _sort_expressions_and_build_components(self): """ User defined method to define expressions and add subsystems for model execution """ # The user-defined Group.setup() method func(self) # Create a record of all nodes in DAG self._root.register_nodes(self.nodes) # Ensure independent variables are at the top of n2 diagram for node in self.nodes.values(): for indep in self._root.dependencies: if isinstance(indep, Indep): if not isinstance(node, Indep): node.add_dependency_node(indep) # Clean up graph, removing dependencies that do not constrain # execution order for node in self.nodes.values(): remove_indirect_dependencies(node) # add forward edges self._root.add_fwd_edges() # remove unused expressions keys = [] for name, node in self.nodes.items(): if len(node.dependents) == 0: keys.append(name) for name in keys: del node[name] # Compute branch costs and sort branches to get desired sparsity # pattern in system jacobian self._root.compute_dag_cost() for node in self.nodes.values(): node.sort_dependency_branches( reverse_branch_sorting=self.reverse_branch_sorting) # Sort expressions, preventing unnecessary feedbacks (i.e. # feedbacks will only occur if there is coupling between # components) self.sorted_expressions = topological_sort(self._root) # Now that expressions are sorted, construct components for expr in reversed(self.sorted_expressions): # Check if outputs are defined if isinstance(expr, Output): if expr.defined == False: raise ValueError("Output not defined for " + repr(expr)) # Construct Component object corresponding to Variable # object, if applicable. # Input objects and root Variable object do not have # a build method defined. if expr.build is not None: sys = expr.build() pfx = 'comp_' promotes = ['*'] promotes_inputs = None promotes_outputs = None if isinstance(sys, OMGroup): pfx = '' promotes = expr.promotes promotes_inputs = expr.promotes_inputs promotes_outputs = expr.promotes_outputs OMGroup.add_subsystem( self, pfx + expr.name, sys, promotes=promotes, promotes_inputs=promotes_inputs, promotes_outputs=promotes_outputs, ) # Set initial values for inputs # if isinstance(expr, Input): # self.set_input_defaults(expr.name, val=expr.val) # Set design variables if isinstance(expr, Indep): if expr.dv == True: self.add_design_var(expr.name) # Cut down on memory consumption del expr
import numpy as np from openmdao.api import Problem, Group, IndepVarComp, ExecComp, ScipyOptimizeDriver from wingWeight import wingWeightComp prob = Problem() model = Group() comp = IndepVarComp() comp.add_output('W0', val=50000) comp.add_output('Swing', val=1000) comp.add_design_var('W0', lower=30000) model.add_subsystem('inputs_comp', comp, promotes=['*']) comp = wingWeightComp(N=3.,tc=0.3,AR=9.,sweep=30.) model.add_subsystem('wingWeight', comp, promotes=['*']) comp = ExecComp('totalWeight = Wwing') comp.add_objective('totalWeight', scaler=40000.) model.add_subsystem('total_comp', comp, promotes=['*']) prob.model = model prob.driver = ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP'
def test_no_promotion_errors(self): """ Tests for error-handling for invalid variable names and keys. """ g = Group(assembled_jac_type='dense') g.linear_solver = DirectSolver(assemble_jac=True) g.add_subsystem('c', ExecComp('y=2*x')) p = Problem() model = p.model model.add_subsystem('g', g) p.setup() # ------------------------------------------------------------------- msg = '\'Group (<model>): Variable "{}" not found.\'' # inputs with self.assertRaises(KeyError) as ctx: p['x'] = 5.0 self.assertEqual(str(ctx.exception), msg.format('x')) p._initial_condition_cache = {} with self.assertRaises(KeyError) as ctx: p['x'] self.assertEqual(str(ctx.exception), msg.format('x')) # outputs with self.assertRaises(KeyError) as ctx: p['y'] = 5.0 self.assertEqual(str(ctx.exception), msg.format('y')) p._initial_condition_cache = {} with self.assertRaises(KeyError) as ctx: p['y'] self.assertEqual(str(ctx.exception), msg.format('y')) p.final_setup() msg = "Group (g): Variable name '{}' not found." inputs, outputs, residuals = g.get_nonlinear_vectors() # inputs for vname in ['x', 'g.c.x']: with self.assertRaises(KeyError) as cm: inputs[vname] = 5.0 self.assertEqual(cm.exception.args[0], f"Group (g): Variable name '{vname}' not found.") with self.assertRaises(KeyError) as cm: inputs[vname] self.assertEqual(cm.exception.args[0], f"Group (g): Variable name '{vname}' not found.") # outputs for vname in ['y', 'g.c.y']: with self.assertRaises(KeyError) as cm: outputs[vname] = 5.0 self.assertEqual(cm.exception.args[0], f"Group (g): Variable name '{vname}' not found.") with self.assertRaises(KeyError) as cm: outputs[vname] self.assertEqual(cm.exception.args[0], f"Group (g): Variable name '{vname}' not found.") msg = r'Variable name pair \("{}", "{}"\) not found.' jac = g.linear_solver._assembled_jac # d(output)/d(input) with self.assertRaisesRegex(KeyError, msg.format('y', 'x')): jac['y', 'x'] = 5.0 with self.assertRaisesRegex(KeyError, msg.format('y', 'x')): jac['y', 'x'] # allow absolute keys now # with self.assertRaisesRegex(KeyError, msg.format('g.c.y', 'g.c.x')): # jac['g.c.y', 'g.c.x'] = 5.0 # with self.assertRaisesRegex(KeyError, msg.format('g.c.y', 'g.c.x')): # deriv = jac['g.c.y', 'g.c.x'] # d(output)/d(output) with self.assertRaisesRegex(KeyError, msg.format('y', 'y')): jac['y', 'y'] = 5.0 with self.assertRaisesRegex(KeyError, msg.format('y', 'y')): jac['y', 'y']
group = Group() # Adding all of the Explicit components to the main group comp = IndepVarComp() comp.add_output('We', val=4.) comp.add_output('V', val=83.) comp.add_output('Q', val=500.) comp.add_output('FTA', val=2.) comp.add_output('Re', val=86.0 * 1.530) comp.add_output('Rt', val=88.0 * 1.530) comp.add_output('Rq', val=81.0 * 1.530) comp.add_output('Rm', val=73.0 * 1.530) comp.add_output('Ceng', val=19.99) comp.add_output('Neng', val=2.0) comp.add_output('Cav', val=113.08) group.add_subsystem('ivc', comp, promotes=['*', '*']) group.add_subsystem('ehc', EngineHoursComp(), promotes=['*', '*']) group.add_subsystem('thc', ToolingHoursComp(), promotes=['*', '*']) group.add_subsystem('mhc', MfgHoursComp(), promotes=['*', '*']) group.add_subsystem('qhc', QualityHoursComp(), promotes=['*', '*']) group.add_subsystem('dsc', DevelSupportComp(), promotes=['*', '*']) group.add_subsystem('ftc', FlightTestCostComp(), promotes=['*', '*']) group.add_subsystem('mmc', MfgMaterialCostComp(), promotes=['*', '*']) group.add_subsystem('rdfc', RdteFlyCostComp(), promotes=['*', '*']) prob.model = group prob.setup() prob.run_model() print(prob['rdtef']) # prob.check_partials(compact_print=True)
for case in range(self.n_cases): farm_output = sum(inputs['ind_powers'][case][:n_turbines]) # Alternative without using n_turbines. ans = np.append(ans, farm_output) ans = ans.reshape(self.n_cases) outputs['farm_power'] = ans if __name__ == '__main__': from openmdao.api import Problem, Group, IndepVarComp, ExecComp class PowerFidelity1(AbstractPower): def compute(self, inputs, outputs): outputs['p'] = inputs['u'] ** 3.0 model = Group() ivc = IndepVarComp() ivc.add_output('u', 7.0) model.add_subsystem('indep', ivc) model.add_subsystem('pow', PowerFidelity1()) model.add_subsystem('equal', ExecComp('y=x+1')) model.connect('indep.u', 'pow.u') model.connect('pow.p', 'equal.x') prob = Problem(model) prob.setup() prob.run_model() print(prob['equal.y'])
for i in range(0, num_times): dGS_drot[i, :, i] = C[:, i] partials['GSdist', 'r_b2g_A'] = dGS_drot.flatten() if __name__ == '__main__': import numpy as np from openmdao.api import Problem, IndepVarComp, Group group = Group() comp = IndepVarComp() num_times = 4 comp.add_output('r_b2g_A', val=np.random.random((3, num_times)), units='km') group.add_subsystem('Inputcomp', comp, promotes=['*']) group.add_subsystem('distance', StationSatelliteDistanceComp(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)
def test_simple_external_code_implicit_comp(self): from openmdao.api import Group, NewtonSolver, Problem, IndepVarComp, DirectSolver, \ ExternalCodeImplicitComp class MachExternalCodeComp(ExternalCodeImplicitComp): def initialize(self): self.options.declare('super_sonic', types=bool) def setup(self): self.add_input('area_ratio', val=1.0, units=None) self.add_output('mach', val=1., units=None) self.declare_partials(of='mach', wrt='area_ratio', method='fd') self.input_file = 'mach_input.dat' self.output_file = 'mach_output.dat' # providing these are optional; the component will verify that any input # files exist before execution and that the output files exist after. self.options['external_input_files'] = [self.input_file] self.options['external_output_files'] = [self.output_file] self.options['command_apply'] = [ 'python', 'extcode_mach.py', self.input_file, self.output_file, ] self.options['command_solve'] = [ 'python', 'extcode_mach.py', self.input_file, self.output_file, ] def apply_nonlinear(self, inputs, outputs, residuals): with open(self.input_file, 'w') as input_file: input_file.write('residuals\n') input_file.write('{}\n'.format(inputs['area_ratio'][0])) input_file.write('{}\n'.format(outputs['mach'][0])) # the parent apply_nonlinear function actually runs the external code super(MachExternalCodeComp, self).apply_nonlinear(inputs, outputs, residuals) # parse the output file from the external code and set the value of mach with open(self.output_file, 'r') as output_file: mach = float(output_file.read()) residuals['mach'] = mach def solve_nonlinear(self, inputs, outputs): with open(self.input_file, 'w') as input_file: input_file.write('outputs\n') input_file.write('{}\n'.format(inputs['area_ratio'][0])) input_file.write('{}\n'.format( self.options['super_sonic'])) # the parent apply_nonlinear function actually runs the external code super(MachExternalCodeComp, self).solve_nonlinear(inputs, outputs) # parse the output file from the external code and set the value of mach with open(self.output_file, 'r') as output_file: mach = float(output_file.read()) outputs['mach'] = mach group = Group() group.add_subsystem('ar', IndepVarComp('area_ratio', 0.5)) mach_comp = group.add_subsystem('comp', MachExternalCodeComp(), promotes=['*']) prob = Problem(model=group) group.nonlinear_solver = NewtonSolver() group.nonlinear_solver.options['solve_subsystems'] = True group.nonlinear_solver.options['iprint'] = 0 group.nonlinear_solver.options['maxiter'] = 20 group.linear_solver = DirectSolver() prob.setup(check=False) area_ratio = 1.3 super_sonic = False prob['area_ratio'] = area_ratio mach_comp.options['super_sonic'] = super_sonic prob.run_model() assert_rel_error(self, prob['mach'], mach_solve(area_ratio, super_sonic=super_sonic), 1e-8) area_ratio = 1.3 super_sonic = True prob['area_ratio'] = area_ratio mach_comp.options['super_sonic'] = super_sonic prob.run_model() assert_rel_error(self, prob['mach'], mach_solve(area_ratio, super_sonic=super_sonic), 1e-8)
import numpy as np from openmdao.api import Problem, Group, IndepVarComp, ExecComp, ScipyOptimizeDriver from lsdo_aircraft.api import Atmosphere from thrust_comp import thrustComp from lift_comp import liftComp prob = Problem() model = Group() comp = IndepVarComp() comp.add_output('altitude_km', val=0.0, units='km') comp.add_output('BPR', val=5.0) comp.add_output('max_thrust', val=580, units='kN') #kN model.add_subsystem('inputs_comp', comp, promotes=['*']) comp = thrustComp() model.add_subsystem('thrust', comp, promotes=['*']) prob.model = model prob.driver = ScipyOptimizeDriver() prob.driver.options['debug_print'] = ['nl_cons', 'objs', 'desvars'] prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-15 prob.driver.options['disp'] = True # Setup problem and add design variables, constraint, and objective prob.model.add_design_var('altitude_km', lower=0, upper=5)
class AddedTurbModel1(AbstractWakeAddedTurbulence): def compute(self, inputs, outputs): TI_amb = inputs['TI_amb'] ct = inputs['ct'] u_inf = inputs['u_inf'] d = inputs['d'] outputs['TI_eff'] = TI_amb * ct + u_inf / d model = Group() ivc = IndepVarComp() ivc.add_output('TI_amb', 0.12) ivc.add_output('ct', 0.6) ivc.add_output('u_inf', 8.0) ivc.add_output('d', 460.0) model.add_subsystem('indep', ivc) model.add_subsystem('added1', AddedTurbModel1()) model.connect('indep.TI_amb', 'added1.TI_amb') model.connect('indep.ct', 'added1.ct') model.connect('indep.u_inf', 'added1.u_inf') model.connect('indep.d', 'added1.d') prob = Problem(model) prob.setup() prob.run_model() print(prob['added1.TI_eff'])
def test_set_checks_shape(self): indep = IndepVarComp() indep.add_output('a') indep.add_output('x', shape=(5, 1)) g1 = Group() g1.add_subsystem('Indep', indep, promotes=['a', 'x']) g2 = g1.add_subsystem('G2', Group(), promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a', 'b']) g2.add_subsystem('C2', ExecComp('y=2*x', x=np.zeros((5, 1)), y=np.zeros((5, 1))), promotes=['x', 'y']) model = Group() model.add_subsystem('G1', g1, promotes=['b', 'y']) model.add_subsystem('Sink', ExecComp(('c=2*b', 'z=2*y'), y=np.zeros((5, 1)), z=np.zeros((5, 1))), promotes=['b', 'y']) p = Problem(model=model) p.setup() p.set_solver_print(level=0) p.run_model() msg = "'.*' <class Group>: Failed to set value of '.*': could not broadcast input array from shape (.*) into shape (.*)." num_val = -10 arr_val = -10 * np.ones((5, 1)) bad_val = -10 * np.ones((10)) inputs, outputs, residuals = g2.get_nonlinear_vectors() # # set input # # assign array to scalar with self.assertRaisesRegex(ValueError, msg): inputs['C1.a'] = arr_val # assign scalar to array inputs['C2.x'] = num_val assert_near_equal(inputs['C2.x'], arr_val, 1e-10) # assign array to array inputs['C2.x'] = arr_val assert_near_equal(inputs['C2.x'], arr_val, 1e-10) # assign bad array shape to array with self.assertRaisesRegex(ValueError, msg): inputs['C2.x'] = bad_val # assign list to array inputs['C2.x'] = arr_val.tolist() assert_near_equal(inputs['C2.x'], arr_val, 1e-10) # assign bad list shape to array with self.assertRaisesRegex(ValueError, msg): inputs['C2.x'] = bad_val.tolist() # # set output # # assign array to scalar with self.assertRaisesRegex(ValueError, msg): outputs['C1.b'] = arr_val # assign scalar to array outputs['C2.y'] = num_val assert_near_equal(outputs['C2.y'], arr_val, 1e-10) # assign array to array outputs['C2.y'] = arr_val assert_near_equal(outputs['C2.y'], arr_val, 1e-10) # assign bad array shape to array with self.assertRaisesRegex(ValueError, msg): outputs['C2.y'] = bad_val # assign list to array outputs['C2.y'] = arr_val.tolist() assert_near_equal(outputs['C2.y'], arr_val, 1e-10) # assign bad list shape to array with self.assertRaisesRegex(ValueError, msg): outputs['C2.y'] = bad_val.tolist() # # set residual # # assign array to scalar with self.assertRaisesRegex(ValueError, msg): residuals['C1.b'] = arr_val # assign scalar to array residuals['C2.y'] = num_val assert_near_equal(residuals['C2.y'], arr_val, 1e-10) # assign array to array residuals['C2.y'] = arr_val assert_near_equal(residuals['C2.y'], arr_val, 1e-10) # assign bad array shape to array with self.assertRaisesRegex(ValueError, msg): residuals['C2.y'] = bad_val # assign list to array residuals['C2.y'] = arr_val.tolist() assert_near_equal(residuals['C2.y'], arr_val, 1e-10) # assign bad list shape to array with self.assertRaisesRegex(ValueError, msg): residuals['C2.y'] = bad_val.tolist()
def test_set_checks_shape(self): indep = IndepVarComp() indep.add_output('a') indep.add_output('x', shape=(5, 1)) g1 = Group() g1.add_subsystem('Indep', indep, promotes=['a', 'x']) g2 = g1.add_subsystem('G2', Group(), promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a', 'b']) g2.add_subsystem('C2', ExecComp('y=2*x', x=np.zeros((5, 1)), y=np.zeros((5, 1))), promotes=['x', 'y']) model = Group() model.add_subsystem('G1', g1, promotes=['b', 'y']) model.add_subsystem('Sink', ExecComp(('c=2*b', 'z=2*y'), y=np.zeros((5, 1)), z=np.zeros((5, 1))), promotes=['b', 'y']) p = Problem(model=model) p.setup() p.set_solver_print(level=0) p.run_model() msg = "Incompatible shape for '.*': Expected (.*) but got (.*)" num_val = -10 arr_val = -10 * np.ones((5, 1)) bad_val = -10 * np.ones((10)) inputs, outputs, residuals = g2.get_nonlinear_vectors() # # set input # # assign array to scalar with assertRaisesRegex(self, ValueError, msg): inputs['C1.a'] = arr_val # assign scalar to array inputs['C2.x'] = num_val assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) # assign array to array inputs['C2.x'] = arr_val assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) # assign bad array shape to array with assertRaisesRegex(self, ValueError, msg): inputs['C2.x'] = bad_val # assign list to array inputs['C2.x'] = arr_val.tolist() assert_rel_error(self, inputs['C2.x'], arr_val, 1e-10) # assign bad list shape to array with assertRaisesRegex(self, ValueError, msg): inputs['C2.x'] = bad_val.tolist() # # set output # # assign array to scalar with assertRaisesRegex(self, ValueError, msg): outputs['C1.b'] = arr_val # assign scalar to array outputs['C2.y'] = num_val assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) # assign array to array outputs['C2.y'] = arr_val assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) # assign bad array shape to array with assertRaisesRegex(self, ValueError, msg): outputs['C2.y'] = bad_val # assign list to array outputs['C2.y'] = arr_val.tolist() assert_rel_error(self, outputs['C2.y'], arr_val, 1e-10) # assign bad list shape to array with assertRaisesRegex(self, ValueError, msg): outputs['C2.y'] = bad_val.tolist() # # set residual # # assign array to scalar with assertRaisesRegex(self, ValueError, msg): residuals['C1.b'] = arr_val # assign scalar to array residuals['C2.y'] = num_val assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) # assign array to array residuals['C2.y'] = arr_val assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) # assign bad array shape to array with assertRaisesRegex(self, ValueError, msg): residuals['C2.y'] = bad_val # assign list to array residuals['C2.y'] = arr_val.tolist() assert_rel_error(self, residuals['C2.y'], arr_val, 1e-10) # assign bad list shape to array with assertRaisesRegex(self, ValueError, msg): residuals['C2.y'] = bad_val.tolist()
from demo.vpm.mdoComponent import * from demo.vpm.panelGeneration import * from openmdao.api import Problem, Group, IndepVarComp, ScipyOptimizeDriver FORCE_FILE = "/Users/gakki/Dropbox/thesis/surface_flow_sort.csv" airfoil = Airfoil(FORCE_FILE, chord_length=1, num_samples=12, angle_of_attack=0.0) airfoil.panelGeneration() model = Group() comp = IndepVarComp() comp.add_output('y', airfoil.boundaryPoints_Y) model.add_subsystem('input',comp) model.add_subsystem('arcComp',ArcLengthComp(x=airfoil.boundaryPoints_X, num_panel=airfoil.NUM_SAMPLES,aoa=airfoil.aoa)) model.connect('input.y','arcComp.y') model.add_subsystem('thetaComp',ThetaComp(x=airfoil.boundaryPoints_X,num_panel=airfoil.NUM_SAMPLES)) model.connect('input.y','thetaComp.y') model.add_subsystem('RHSComp',RHSComp(num_panel=airfoil.NUM_SAMPLES,aoa=airfoil.aoa)) model.connect('thetaComp.theta','RHSComp.theta') model.add_subsystem('AComp',AComp(x=airfoil.boundaryPoints_X, num_panel=airfoil.NUM_SAMPLES)) model.connect('thetaComp.theta','AComp.theta') model.connect('input.y','AComp.y') model.add_subsystem('BComp',BComp(x=airfoil.boundaryPoints_X, num_panel=airfoil.NUM_SAMPLES)) model.connect('input.y','BComp.y') model.add_subsystem('CComp',CComp(num_panel=airfoil.NUM_SAMPLES)) model.connect('thetaComp.theta','CComp.theta') model.add_subsystem('DComp',DComp(num_panel=airfoil.NUM_SAMPLES)) model.connect('thetaComp.theta','DComp.theta') model.add_subsystem('EComp',EComp(x=airfoil.boundaryPoints_X, num_panel=airfoil.NUM_SAMPLES)) model.connect('thetaComp.theta','EComp.theta') model.connect('input.y','EComp.y')
TestPoint_x = trajectory_x[29] TestPoint_y = trajectory_y[29] outputs['stance_dist'] = np.linalg.norm( [x - TestPoint_x, y - TestPoint_y]) if __name__ == '__main__': from openmdao.api import Problem, Group, IndepVarComp group = Group() comp = IndepVarComp() comp.add_output('l1') comp.add_output('l2') group.add_subsystem('i_comp', comp, promotes=['*']) comp = FkComp() group.add_subsystem('fk_comp', comp, promotes=['*']) comp = StancePointCon() group.add_subsystem('stance_con', comp, promotes=['*']) prob = Problem() prob.model = group prob.setup() prob.run_model() prob.model.list_outputs()
rotor_thrust, rna_mass): # Redefine method in subclass of AbstractSupportStructureDesign with specific model that has same inputs and outputs. pass if __name__ == '__main__': from openmdao.api import Problem, Group, IndepVarComp class TeamPlay(AbstractSupportStructureDesign): def compute(self, inputs, outputs): TI = inputs['TI'] depth = inputs['depth'] outputs['cost_support'] = TI * depth**3.0 model = Group() ivc = IndepVarComp() ivc.add_output('TI', 0.12) ivc.add_output('depth', 14.0) model.add_subsystem('indep', ivc) model.add_subsystem('teamplay', TeamPlay()) model.connect('indep.TI', 'teamplay.TI') model.connect('indep.depth', 'teamplay.depth') prob = Problem(model) prob.setup() prob.run_model() print(prob['teamplay.cost_support'])
def test_with_promotion_errors(self): """ Tests for error-handling for invalid variable names and keys. """ c1 = IndepVarComp('x') c2 = ExecComp('y=2*x') c3 = ExecComp('z=3*x') g = Group(assembled_jac_type='dense') g.add_subsystem('c1', c1, promotes=['*']) g.add_subsystem('c2', c2, promotes=['*']) g.add_subsystem('c3', c3, promotes=['*']) g.linear_solver = DirectSolver(assemble_jac=True) model = Group() model.add_subsystem('g', g, promotes=['*']) p = Problem(model) p.setup() # Conclude setup but don't run model. p.final_setup() # ------------------------------------------------------------------- msg1 = 'Variable name "{}" not found.' msg2 = "The promoted name x is invalid because it refers to multiple inputs: " \ "[g.c2.x ,g.c3.x]. Access the value from the connected output variable x instead." inputs, outputs, residuals = g.get_nonlinear_vectors() # inputs with self.assertRaises(Exception) as context: inputs['x'] = 5.0 self.assertEqual(str(context.exception), msg2) with self.assertRaises(Exception) as context: self.assertEqual(inputs['x'], 5.0) self.assertEqual(str(context.exception), msg2) with assertRaisesRegex(self, KeyError, msg1.format('g.c2.x')): inputs['g.c2.x'] = 5.0 with assertRaisesRegex(self, KeyError, msg1.format('g.c2.x')): self.assertEqual(inputs['g.c2.x'], 5.0) # outputs with assertRaisesRegex(self, KeyError, msg1.format('g.c2.y')): outputs['g.c2.y'] = 5.0 with assertRaisesRegex(self, KeyError, msg1.format('g.c2.y')): self.assertEqual(outputs['g.c2.y'], 5.0) msg1 = r'Variable name pair \("{}", "{}"\) not found.' jac = g.linear_solver._assembled_jac # d(outputs)/d(inputs) with self.assertRaises(Exception) as context: jac['y', 'x'] = 5.0 self.assertEqual(str(context.exception), msg2) with self.assertRaises(Exception) as context: self.assertEqual(jac['y', 'x'], 5.0) self.assertEqual(str(context.exception), msg2)
add_eq('eq_cr_V','Con_cr_V', 'cr_V -V') add_var('cr_RPM') #cruise RMP # add_eq('') add_var('hv_RPM') # hover RMP add_var('cr_P') # cruise power add_var('hv_P') # hover power add_var('cr_T') # cruise Thrust add_var('hv_T') # hover Thrust add_var('cr_Q') # cruise Torque? add_var('hv_Q') # hover Torque? group = Group() group.add_subsystem('indep_var_comp', indep_var_comp, promotes=['*']) group.add_subsystem('equations_group', equations_group, promotes=['*']) group.add_objective('x', scaler=1) #group.add_constraint('b',lower=0.5,upper = 1,) # this is how you add a contraint prob = Problem(model=group) prob.driver = ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.setup() prob.run_model() #print(prob['Con_q']) prob.run_driver()
def test_no_promotion_errors(self): """ Tests for error-handling for invalid variable names and keys. """ g = Group(assembled_jac_type='dense') g.linear_solver = DirectSolver(assemble_jac=True) g.add_subsystem('c', ExecComp('y=2*x')) p = Problem() model = p.model model.add_subsystem('g', g) p.setup() # ------------------------------------------------------------------- msg = 'Variable name "{}" not found.' # inputs with assertRaisesRegex(self, KeyError, msg.format('x')): p['x'] = 5.0 p.final_setup() p._initial_condition_cache = {} with assertRaisesRegex(self, KeyError, msg.format('x')): p['x'] # outputs with assertRaisesRegex(self, KeyError, msg.format('y')): p['y'] = 5.0 p.final_setup() p._initial_condition_cache = {} with assertRaisesRegex(self, KeyError, msg.format('y')): p['y'] msg = 'Variable name "{}" not found.' inputs, outputs, residuals = g.get_nonlinear_vectors() # inputs with assertRaisesRegex(self, KeyError, msg.format('x')): inputs['x'] = 5.0 with assertRaisesRegex(self, KeyError, msg.format('x')): inputs['x'] with assertRaisesRegex(self, KeyError, msg.format('g.c.x')): inputs['g.c.x'] = 5.0 with assertRaisesRegex(self, KeyError, msg.format('g.c.x')): inputs['g.c.x'] # outputs with assertRaisesRegex(self, KeyError, msg.format('y')): outputs['y'] = 5.0 with assertRaisesRegex(self, KeyError, msg.format('y')): outputs['y'] with assertRaisesRegex(self, KeyError, msg.format('g.c.y')): outputs['g.c.y'] = 5.0 with assertRaisesRegex(self, KeyError, msg.format('g.c.y')): outputs['g.c.y'] msg = r'Variable name pair \("{}", "{}"\) not found.' jac = g.linear_solver._assembled_jac # d(output)/d(input) with assertRaisesRegex(self, KeyError, msg.format('y', 'x')): jac['y', 'x'] = 5.0 with assertRaisesRegex(self, KeyError, msg.format('y', 'x')): jac['y', 'x'] # allow absolute keys now # with assertRaisesRegex(self, KeyError, msg.format('g.c.y', 'g.c.x')): # jac['g.c.y', 'g.c.x'] = 5.0 # with assertRaisesRegex(self, KeyError, msg.format('g.c.y', 'g.c.x')): # deriv = jac['g.c.y', 'g.c.x'] # d(output)/d(output) with assertRaisesRegex(self, KeyError, msg.format('y', 'y')): jac['y', 'y'] = 5.0 with assertRaisesRegex(self, KeyError, msg.format('y', 'y')): jac['y', 'y']
comp.add_output('Cla', val=0.11) comp.add_output('Cla_t', val=0.11) comp.add_output('d_fuse', val=10.) comp.add_output('d_fuse_t', val=2.) comp.add_output('b', val=150) comp.add_output('b_t', val=15) comp.add_output('W_0', val=18000) comp.add_output('q', val=46) comp.add_output('taper', val=0.4) ## wing taper ratio comp.add_output('thickness_ratio', val=0.12) comp.add_output('n', val=2) prob.model.add_subsystem('ivc', comp) ## AERODYNAMICS GROUP group = Group() group.add_subsystem('cla_wing', CLaWingComp()) group.add_subsystem('cla_tail', CLaTailComp()) prob.model.add_subsystem('Aerodynamics', group) ## WEIGHTS GROUP group = Group() group.add_subsystem('W_lg', LGWeightComp()) group.add_subsystem('W_tail', TailWeightComp()) group.add_subsystem('W_wing', WingWeightComp()) group.add_subsystem('W_wing_control', WingControlWeightComp()) prob.model.add_subsystem('Weights', group) prob.model.connect("ivc.AR", "Aerodynamics.cla_wing.AR") prob.model.connect("ivc.M", "Aerodynamics.cla_wing.M") prob.model.connect("ivc.Cla", "Aerodynamics.cla_wing.Cla") prob.model.connect("ivc.S", "Aerodynamics.cla_wing.S")
def setup(self): super(ExplicitTMIntegrator, self).setup() ode_function = self.options['ode_function'] method = self.options['method'] starting_coeffs = self.options['starting_coeffs'] has_starting_method = method.starting_method is not None is_starting_method = starting_coeffs is not None states = ode_function._states static_parameters = ode_function._static_parameters dynamic_parameters = ode_function._dynamic_parameters time_units = ode_function._time_options['units'] starting_norm_times, my_norm_times = self._get_meta() glm_A, glm_B, glm_U, glm_V, num_stages, num_step_vars = self._get_method( ) num_times = len(my_norm_times) num_stages = method.num_stages num_step_vars = method.num_values glm_A = method.A glm_B = method.B glm_U = method.U glm_V = method.V # ------------------------------------------------------------------------------------ integration_group = Group() self.add_subsystem('integration_group', integration_group) for i_step in range(len(my_norm_times) - 1): step_comp_old_name = 'integration_group.step_comp_%i' % (i_step - 1) step_comp_new_name = 'integration_group.step_comp_%i' % (i_step) for i_stage in range(num_stages): stage_comp_name = 'integration_group.stage_comp_%i_%i' % ( i_step, i_stage) ode_comp_name = 'integration_group.ode_comp_%i_%i' % (i_step, i_stage) if ode_function._time_options['targets']: self.connect('time_comp.stage_times', [ '.'.join((ode_comp_name, t)) for t in ode_function._time_options['targets'] ], src_indices=i_step * (num_stages) + i_stage) comp = ExplicitTMStageComp( states=states, time_units=time_units, num_stages=num_stages, num_step_vars=num_step_vars, glm_A=glm_A, glm_U=glm_U, i_stage=i_stage, i_step=i_step, ) integration_group.add_subsystem( stage_comp_name.split('.')[1], comp) self.connect('time_comp.h_vec', '%s.h' % stage_comp_name, src_indices=i_step) for j_stage in range(i_stage): ode_comp_tmp_name = 'integration_group.ode_comp_%i_%i' % ( i_step, j_stage) self._connect_multiple( self._get_state_names(ode_comp_tmp_name, 'rate_source'), self._get_state_names(stage_comp_name, 'F', i_step=i_step, i_stage=i_stage, j_stage=j_stage), ) comp = self._create_ode(1) integration_group.add_subsystem( ode_comp_name.split('.')[1], comp) self._connect_multiple( self._get_state_names(stage_comp_name, 'Y', i_step=i_step, i_stage=i_stage), self._get_state_names(ode_comp_name, 'targets'), ) if len(static_parameters) > 0: self._connect_multiple( self._get_static_parameter_names( 'static_parameter_comp', 'out'), self._get_static_parameter_names( ode_comp_name, 'targets'), ) if len(dynamic_parameters) > 0: src_indices_list = [] for parameter_name, value in iteritems(dynamic_parameters): size = np.prod(value['shape']) shape = value['shape'] arange = np.arange(((len(my_norm_times) - 1) * num_stages * size)).reshape((( len(my_norm_times) - 1, num_stages, ) + shape)) src_indices = arange[i_step, i_stage, :].reshape((1, ) + shape) src_indices_list.append(src_indices) self._connect_multiple( self._get_dynamic_parameter_names( 'dynamic_parameter_comp', 'out'), self._get_dynamic_parameter_names( ode_comp_name, 'targets'), src_indices_list, ) comp = ExplicitTMStepComp( states=states, time_units=time_units, num_stages=num_stages, num_step_vars=num_step_vars, glm_B=glm_B, glm_V=glm_V, i_step=i_step, ) integration_group.add_subsystem( step_comp_new_name.split('.')[1], comp) self.connect('time_comp.h_vec', '%s.h' % step_comp_new_name, src_indices=i_step) for j_stage in range(num_stages): ode_comp_tmp_name = 'integration_group.ode_comp_%i_%i' % ( i_step, j_stage) self._connect_multiple( self._get_state_names(ode_comp_tmp_name, 'rate_source'), self._get_state_names(step_comp_new_name, 'F', i_step=i_step, j_stage=j_stage), ) if i_step == 0: self._connect_multiple( self._get_state_names('starting_system', 'starting'), self._get_state_names(step_comp_new_name, 'y_old', i_step=i_step), ) for i_stage in range(num_stages): stage_comp_name = 'integration_group.stage_comp_%i_%i' % ( i_step, i_stage) self._connect_multiple( self._get_state_names('starting_system', 'starting'), self._get_state_names(stage_comp_name, 'y_old', i_step=i_step, i_stage=i_stage), ) else: self._connect_multiple( self._get_state_names(step_comp_old_name, 'y_new', i_step=i_step - 1), self._get_state_names(step_comp_new_name, 'y_old', i_step=i_step), ) for i_stage in range(num_stages): stage_comp_name = 'integration_group.stage_comp_%i_%i' % ( i_step, i_stage) self._connect_multiple( self._get_state_names(step_comp_old_name, 'y_new', i_step=i_step - 1), self._get_state_names(stage_comp_name, 'y_old', i_step=i_step, i_stage=i_stage), ) promotes_outputs = [] for state_name in states: out_state_name = get_name('state', state_name) starting_name = get_name('starting', state_name) promotes_outputs.append(out_state_name) if is_starting_method: promotes_outputs.append(starting_name) comp = TMOutputComp(states=states, num_starting_times=len(starting_norm_times), num_my_times=len(my_norm_times), num_step_vars=num_step_vars, starting_coeffs=starting_coeffs) self.add_subsystem('output_comp', comp, promotes_outputs=promotes_outputs) if has_starting_method: self._connect_multiple( self._get_state_names('starting_system', 'state'), self._get_state_names('output_comp', 'starting_state'), ) for i_step in range(len(my_norm_times)): if i_step == 0: self._connect_multiple( self._get_state_names('starting_system', 'starting'), self._get_state_names('output_comp', 'y', i_step=i_step), ) else: self._connect_multiple( self._get_state_names('integration_group.step_comp_%i' % (i_step - 1), 'y_new', i_step=i_step - 1), self._get_state_names('output_comp', 'y', i_step=i_step), )
if __name__ == '__main__': from openmdao.api import Problem, Group, IndepVarComp from numpy import sqrt class RSSMerge(AbstractWakeMerging): def compute(self, inputs, outputs): all_du = inputs['all_du'] add = 0.0 for du in all_du: add += du ** 2.0 root = sqrt(add) outputs['u'] = root model = Group() ivc = IndepVarComp() ivc.add_output('deficits', [0.16, 0.14, 0.15, 0.18]) model.add_subsystem('indep', ivc) model.add_subsystem('rms', RSSMerge(4)) model.connect('indep.deficits', 'rms.all_du') prob = Problem(model) prob.setup() prob.run_model() print(prob['rms.u'])
def run_open_mdao(): if USE_SCALING: # prepare scaling global offset_weight global offset_stress global scale_weight global scale_stress runner = MultiRun(use_calcu=not USE_ABA, use_aba=USE_ABA, non_liner=False, project_name_prefix=PROJECT_NAME_PREFIX, force_recalc=False) sur = Surrogate(use_abaqus=USE_ABA, pgf=False, show_plots=False, scale_it=False) res, surro = sur.auto_run(SAMPLE_HALTON, 16, SURRO_POLYNOM, run_validation=False) p = runner.new_project_r_t(range_rib[0], range_shell[0]) offset_weight = p.calc_wight() p = runner.new_project_r_t(range_rib[1], range_shell[1]) max_weight = p.calc_wight() offset_stress = surro.predict([range_rib[1], range_shell[1]]) max_stress = surro.predict([range_rib[0], range_shell[0]]) scale_weight = (max_weight - offset_weight) scale_stress = (max_stress - offset_stress) write_mdao_log('iter,time,ribs(float),ribs,shell,stress,weight') model = Group() indeps = IndepVarComp() indeps.add_output('ribs', (22 - offset_rib) / scale_rib) indeps.add_output('shell', (0.0024 - offset_shell) / scale_shell) model.add_subsystem('des_vars', indeps) model.add_subsystem('wing', WingStructureSurro()) model.connect('des_vars.ribs', ['wing.ribs', 'con_cmp1.ribs']) model.connect('des_vars.shell', 'wing.shell') # design variables, limits and constraints model.add_design_var('des_vars.ribs', lower=(range_rib[0] - offset_rib) / scale_rib, upper=(range_rib[1] - offset_rib) / scale_rib) model.add_design_var('des_vars.shell', lower=(range_shell[0] - offset_shell) / scale_shell, upper=(range_shell[1] - offset_shell) / scale_shell) # objective model.add_objective('wing.weight', scaler=0.0001) # constraint print('constrain stress: ' + str((max_shear_strength - offset_stress) / scale_stress)) model.add_constraint('wing.stress', upper=(max_shear_strength - offset_stress) / scale_stress) model.add_subsystem('con_cmp1', ExecComp('con1 = (ribs * '+str(scale_rib)+') - int(ribs[0] * '+str(scale_rib)+')')) model.add_constraint('con_cmp1.con1', upper=.5) prob = Problem(model) # setup the optimization if USE_PYOPTSPARSE: prob.driver = pyOptSparseDriver() prob.driver.options['optimizer'] = OPTIMIZER prob.driver.opt_settings['SwarmSize'] = 8 prob.driver.opt_settings['stopIters'] = 5 else: prob.driver = ScipyOptimizeDriver() prob.driver.options['optimizer'] = OPTIMIZER # ['Nelder-Mead', 'Powell', 'CG', 'BFGS', 'Newton-CG', 'L-BFGS-B', 'TNC', 'COBYLA', 'SLSQP'] prob.driver.options['tol'] = TOL prob.driver.options['disp'] = True prob.driver.options['maxiter'] = 1000 #prob.driver.opt_settings['etol'] = 100 prob.setup() prob.set_solver_print(level=0) prob.model.approx_totals() prob.setup(check=True, mode='fwd') prob.run_driver() print('done') print('ribs: ' + str((prob['wing.ribs'] * scale_rib) + offset_rib)) print('shell: ' + str((prob['wing.shell'] * scale_shell) + offset_shell) + ' m') print('weight= ' + str((prob['wing.weight'] * scale_weight) + offset_weight)) print('stress= ' + str((prob['wing.stress'] * scale_stress) + offset_stress) + ' ~ ' + str(prob['wing.stress'])) print('execution counts wing: ' + str(prob.model.wing.executionCounter))
# comp.add_output('xcg_y', val = 0.395) comp.add_output('xcg_y', val=0.1913) # # # for the Total W Xcg comp.add_output('mass_wing', val=0.447) # comp.add_output('mass_allminuswing', val =4.916) comp.add_output('mass_allminuswing', val=3.71) # This is for the Wing's X ac # comp.add_output('xac_y', val = .4286) comp.add_output('xac_y', val=.2143) group.add_subsystem('ivc', comp) comp = EmptyWeightFractionComp() group.add_subsystem('ewf', comp) comp = GrossWeightComp() group.add_subsystem('gw', comp) comp = BatteryRangeComp() # 'electric battery range' group.add_subsystem('r', comp) comp = PowerLoadingComp() group.add_subsystem('pw0', comp) comp = WingLoadingComp() group.add_subsystem('s', comp)
def test_vector_context_managers(self): g1 = Group() g1.add_subsystem('Indep', IndepVarComp('a', 5.0), promotes=['a']) g2 = g1.add_subsystem('G2', Group(), promotes=['*']) g2.add_subsystem('C1', ExecComp('b=2*a'), promotes=['a', 'b']) model = Group() model.add_subsystem('G1', g1, promotes=['b']) model.add_subsystem('Sink', ExecComp('c=2*b'), promotes=['b']) p = Problem(model=model) p.set_solver_print(level=0) # Test pre-setup errors with self.assertRaises(Exception) as cm: inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(str(cm.exception), "<class Group>: Cannot get vectors because setup has not yet been called.") with self.assertRaises(Exception) as cm: d_inputs, d_outputs, d_residuals = model.get_linear_vectors() self.assertEqual(str(cm.exception), "<class Group>: Cannot get vectors because setup has not yet been called.") p.setup() p.run_model() # Test inputs with original values inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'], 5.) inputs, outputs, residuals = g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'], 5.) # Test inputs after setting a new value inputs, outputs, residuals = g2.get_nonlinear_vectors() inputs['C1.a'] = -1. inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(inputs['G1.G2.C1.a'], -1.) inputs, outputs, residuals = g1.get_nonlinear_vectors() self.assertEqual(inputs['G2.C1.a'], -1.) # Test outputs with original values inputs, outputs, residuals = model.get_nonlinear_vectors() self.assertEqual(outputs['G1.G2.C1.b'], 10.) inputs, outputs, residuals = g2.get_nonlinear_vectors() # Test outputs after setting a new value inputs, outputs, residuals = model.get_nonlinear_vectors() outputs['G1.G2.C1.b'] = 123. self.assertEqual(outputs['G1.G2.C1.b'], 123.) inputs, outputs, residuals = g2.get_nonlinear_vectors() outputs['C1.b'] = 789. self.assertEqual(outputs['C1.b'], 789.) # Test residuals inputs, outputs, residuals = model.get_nonlinear_vectors() residuals['G1.G2.C1.b'] = 99.0 self.assertEqual(residuals['G1.G2.C1.b'], 99.0) # Test linear d_inputs, d_outputs, d_residuals = model.get_linear_vectors() d_outputs['G1.G2.C1.b'] = 10. self.assertEqual(d_outputs['G1.G2.C1.b'], 10.)
group = Group() comp = IndepVarComp() num_times = 1501 num_cp = 300 step_size = 95 * 60 / (num_times - 1) dd_dt = np.loadtxt('/home/lsdo/Cubesat/lsdo_cubesat/rundata/Bitrate.csv') # dd_dt.reshape((1, num_times)) print(dd_dt.shape) Data0 = 0 comp.add_output('num_times', val=num_times) comp.add_output('Download_rate', val=dd_dt) comp.add_output('Initial_Data', val=Data0) group.add_subsystem('Inputcomp', comp, promotes=['*']) group.add_subsystem('Statecomp_Implicit', DataDownloadComp(num_times=num_times, step_size=step_size), promotes=['*']) prob = Problem() prob.model = group prob.setup() prob.run_model() prob.model.list_outputs() print(prob['Data']) prob.check_partials(compact_print=True) # import matplotlib.pyplot as plt