r = radii(mesh) mesh = mesh.reshape(-1, mesh.shape[-1]) aero_ind = numpy.atleast_2d(numpy.array([num_x, num_y])) fem_ind = [num_y] aero_ind, fem_ind = get_inds(aero_ind, fem_ind) num_thickness = num_twist t = r/10 # Define the aircraft properties execfile('CRM.py') # Define the material properties execfile('aluminum.py') # Create the top-level system root = Group() tot_n_fem = numpy.sum(fem_ind[:, 0]) num_surf = fem_ind.shape[0] jac_twist = get_bspline_mtx(num_twist, num_y) jac_thickness = get_bspline_mtx(num_thickness, tot_n_fem-num_surf) # Define the independent variables indep_vars = [ ('span', span), ('twist_cp', numpy.zeros(num_twist)), ('thickness_cp', numpy.ones(num_thickness)*numpy.max(t)), ('v', v), ('alpha', alpha), ('rho', rho), ('r', r), ('t', t),
parser.add_argument('--run', action='store_true') parser.add_argument('mfile', nargs=1) args = parser.parse_args() c = MatlabWrapper(args.mfile[0]) print((json.dumps({ 'params': c._init_params_dict, 'unknowns': c._init_unknowns_dict }))) if args.run: from openmdao.api import IndepVarComp, Problem, Group top = Problem() root = top.root = Group() root.add('p1', IndepVarComp('x', 3.0)) root.add('p2', IndepVarComp('y', -4.0)) root.add('c', c) root.connect('p1.x', 'c.a') root.connect('p2.y', 'c.b') root.connect('p2.y', 'c.c') top.setup() top.run() print(root.c.unknowns['m'])
def test_values(self): n = 1 p = Problem(model=Group()) # Only need to add output to variables that impact the test case # Need to test other component also ivc = IndepVarComp() ivc.add_output('rpm', 4000 * np.ones(n), units='rpm', desc='Rotation speed') ivc.add_output('I_peak', 50 * np.ones(n), units='A', desc='Peak current') ivc.add_output('resistivity_wire', 1.724e-8, units='ohm*m', desc='resisitivity of Cu at 20 degC') ivc.add_output('stack_length', 0.0345, units='m', desc='axial length of the motor') ivc.add_output('n_slots', 24, desc='Number of Slots') ivc.add_output('n_turns', 12, desc='Number of wire turns') ivc.add_output('T_coeff_cu', 0.00393, desc='temperature coeff of copper') ivc.add_output('I', 34.5, units='A', desc='RMS Current') ivc.add_output('T_windings', 150, units='C', desc='operating temperature of windings') ivc.add_output('r_strand', 0.0001605, units='m', desc='28 AWG radius of one strand of litz wire') ivc.add_output('n_m', 20, desc='Number of magnets') ivc.add_output('mu_o', 1.2566e-6, units='H/m', desc='permeability of free space') ivc.add_output( 'mu_r', 1.0, units='H/m', desc='relative magnetic permeability of ferromagnetic materials') ivc.add_output('n_strands', 41, desc='number of strands in hand for litz wire') ivc.add_output('alpha_stein', 1.286, desc='Alpha coefficient for steinmetz, constant') ivc.add_output('B_pk', 2.4, units='T', desc='Peak flux density for Hiperco-50') ivc.add_output( 'beta_stein', 1.76835, desc='Beta coefficient for steinmentz, dependent on freq') ivc.add_output('k_stein', 0.0044, desc='k constant for steinmentz') ivc.add_output('motor_mass')
def test_debug_print_option(self): prob = Problem() model = prob.model = Group() model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) prob.set_solver_print(level=0) prob.driver = ScipyOptimizeDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = False prob.driver.options['debug_print'] = [ 'desvars', 'ln_cons', 'nl_cons', 'objs' ] model.add_design_var('x', lower=-50.0, upper=50.0) model.add_design_var('y', lower=-50.0, upper=50.0) model.add_objective('f_xy') model.add_constraint('c', upper=-15.0) prob.setup(check=False) stdout = sys.stdout strout = StringIO() sys.stdout = strout try: prob.run_driver() finally: sys.stdout = stdout output = strout.getvalue().split('\n') self.assertTrue( output.count("Design Vars") > 1, "Should be more than one design vars header printed") self.assertTrue( output.count("Nonlinear constraints") > 1, "Should be more than one nonlinear constraint header printed") self.assertTrue( output.count("Linear constraints") > 1, "Should be more than one linear constraint header printed") self.assertTrue( output.count("Objectives") > 1, "Should be more than one objective header printed") self.assertTrue( len([s for s in output if s.startswith('p1.x')]) > 1, "Should be more than one p1.x printed") self.assertTrue( len([s for s in output if s.startswith('p2.y')]) > 1, "Should be more than one p2.y printed") self.assertTrue( len([s for s in output if s.startswith('con.c')]) > 1, "Should be more than one con.c printed") self.assertTrue( len([s for s in output if s.startswith('comp.f_xy')]) > 1, "Should be more than one comp.f_xy printed")
def setUp(self): p1 = self.prob = Problem(model=Group()) p1.model.add_subsystem('sizing', subsys=HeatPipeSizeGroup(num_nodes=1)) p1.setup(force_alloc_complex=True) p1.run_model()
def min_time_climb_problem(num_seg=3, transcription_order=5, transcription='gauss-lobatto', top_level_densejacobian=True): p = Problem(model=Group()) p.driver = pyOptSparseDriver() p.driver.options['optimizer'] = 'SNOPT' p.driver.opt_settings['Major iterations limit'] = 500 p.driver.opt_settings['Iterations limit'] = 1000000000 p.driver.opt_settings['iSumm'] = 6 p.driver.opt_settings['Major feasibility tolerance'] = 1.0E-10 p.driver.opt_settings['Major optimality tolerance'] = 1.0E-10 p.driver.opt_settings['Verify level'] = 1 p.driver.opt_settings['Function precision'] = 1.0E-6 p.driver.opt_settings['Linesearch tolerance'] = .1 p.driver.opt_settings['Major step limit'] = .1 p.driver.options['dynamic_simul_derivs'] = True phase = Phase(transcription, ode_class=MinTimeClimbODE, num_segments=num_seg, transcription_order=transcription_order) p.model.add_subsystem('phase', phase) phase.set_time_options(opt_initial=False, duration_bounds=(50, 1e8), duration_ref=100.0) phase.set_state_options('r', fix_initial=True, lower=0, upper=1.0E8, scaler=1.0E-4, defect_scaler=1.0E-3, units='m') phase.set_state_options('h', fix_initial=True, lower=0, upper=20000.0, scaler=1.0E-3, defect_scaler=1.0E-3, units='m') phase.set_state_options('v', fix_initial=True, lower=10.0, upper=500., scaler=1.0E-2, defect_scaler=1.0E-2, units='m/s') phase.set_state_options('gam', fix_initial=True, lower=-1.5, upper=1.5, ref=1.0, defect_scaler=1.0, units='rad') phase.set_state_options('m', fix_initial=True, lower=10.0, upper=1.0E5, scaler=1.0E-3, defect_scaler=1.0E-3, units='kg') phase.add_control('alpha', units='deg', lower=-8.0, upper=8.0, scaler=1.0, rate_continuity=True) phase.add_design_parameter('S', val=49.2386, units='m**2', opt=False) # phase.add_design_parameter('throttle', val=1.0, opt=False) phase.add_control('throttle', val=1.0, opt=True, lower=0., upper=1., rate_continuity=False) phase.add_boundary_constraint('h', loc='final', equals=100., scaler=1.0E-3, units='m') # phase.add_boundary_constraint('aero.mach', loc='final', equals=1., units=None) # phase.add_boundary_constraint('gam', loc='final', equals=0.0, units='rad') phase.add_boundary_constraint('r', loc='final', equals=1e6, units='m') phase.add_path_constraint(name='h', lower=100.0, upper=20000, ref=20000) phase.add_path_constraint(name='aero.mach', lower=0.1, upper=1.8) phase.add_path_constraint(name='prop.m_dot', upper=0.) # phase.add_path_constraint(name='flight_dynamics.r_dot', lower=0.) # Minimize time at the end of the phase # phase.add_objective('time', loc='final', ref=100.0) phase.add_objective('m', loc='final', ref=-1000.0) p.model.linear_solver = DirectSolver(assemble_jac=True) p.model.options['assembled_jac_type'] = 'csc' p.setup(mode='fwd', check=True) p['phase.t_initial'] = 0.0 p['phase.t_duration'] = 2000. p['phase.states:r'] = phase.interpolate(ys=[0.0, 1e6], nodes='state_input') p['phase.states:h'] = phase.interpolate(ys=[100.0, 1e4], nodes='state_input') p['phase.states:v'] = phase.interpolate(ys=[135.964, 283.159], nodes='state_input') p['phase.states:gam'] = phase.interpolate(ys=[0.0, 0.0], nodes='state_input') p['phase.states:m'] = phase.interpolate(ys=[30e3, 29e3], nodes='state_input') # p['phase.controls:alpha'] = phase.interpolate(ys=[0.50, 0.50], nodes='all') return p
from openmdao.api import Problem, Group, IndepVarComp, NonlinearBlockGS from engine_hours_comp import EngineHoursComp from tooling_hours_comp import ToolingHoursComp from mfg_hours_comp import MfgHoursComp from quality_hours_comp import QualityHoursComp from devel_support_comp import DevelSupportComp from flight_test_cost_comp import FlightTestCostComp from mfg_material_cost_comp import MfgMaterialCostComp from rdte_fly_cost_comp import RdteFlyCostComp prob = Problem() 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=['*', '*'])
v = a * M span = 58.7630524 # baseline CRM alpha = 1. rho = 1.225 E = 200.e9 G = 30.e9 stress = 20.e6 mrho = 3.e3 r = radii(mesh) # t = 0.05 * numpy.ones(num_y-1) t = 0.05 * numpy.ones(num_y-1) t = r/10 root = Group() des_vars = [ ('span', span), ('twist', numpy.zeros(num_y)), ('v', v), ('alpha', alpha), ('rho', rho), ('r', r), ('t', t), ] root.add('des_vars', IndepVarComp(des_vars), promotes=['*'])
def setup(self): E = self.metadata['E'] L = self.metadata['L'] b = self.metadata['b'] volume = self.metadata['volume'] num_elements = self.metadata['num_elements'] num_nodes = num_elements + 1 num_cp = self.metadata['num_cp'] num_load_cases = self.metadata['num_load_cases'] inputs_comp = IndepVarComp() inputs_comp.add_output('h_cp', shape=num_cp) self.add_subsystem('inputs_comp', inputs_comp) comp = BsplinesComp(num_control_points=num_cp, num_points=num_elements, in_name='h_cp', out_name='h') self.add_subsystem('interp', comp) I_comp = MomentOfInertiaComp(num_elements=num_elements, b=b) self.add_subsystem('I_comp', I_comp) comp = LocalStiffnessMatrixComp(num_elements=num_elements, E=E, L=L) self.add_subsystem('local_stiffness_matrix_comp', comp) comp = GlobalStiffnessMatrixComp(num_elements=num_elements) self.add_subsystem('global_stiffness_matrix_comp', comp) # Parallel Subsystem for load cases. par = self.add_subsystem('parallel', ParallelGroup()) # Determine how to split cases up over the available procs. nprocs = self.comm.size divide = divide_cases(num_load_cases, nprocs) obj_srcs = [] for j, this_proc in enumerate(divide): num_rhs = len(this_proc) name = 'sub_%d' % j sub = par.add_subsystem(name, Group()) # Load is a sinusoidal distributed force of varying spatial frequency. force_vector = np.zeros((2 * num_nodes, num_rhs)) for i, k in enumerate(this_proc): end = 1.5 * np.pi if num_load_cases > 1: end += k * 0.5 * np.pi / (num_load_cases - 1) x = np.linspace(0, end, num_nodes) f = -np.sin(x) force_vector[0:-1:2, i] = f comp = MultiStatesComp(num_elements=num_elements, force_vector=force_vector, num_rhs=num_rhs) sub.add_subsystem('states_comp', comp) comp = MultiDisplacementsComp(num_elements=num_elements, num_rhs=num_rhs) sub.add_subsystem('displacements_comp', comp) comp = MultiComplianceComp(num_elements=num_elements, force_vector=force_vector, num_rhs=num_rhs) sub.add_subsystem('compliance_comp', comp) self.connect('global_stiffness_matrix_comp.K', 'parallel.%s.states_comp.K' % name) for k in range(num_rhs): sub.connect('states_comp.d_%d' % k, 'displacements_comp.d_%d' % k) sub.connect('displacements_comp.displacements_%d' % k, 'compliance_comp.displacements_%d' % k) obj_srcs.append('parallel.%s.compliance_comp.compliance_%d' % (name, k)) comp = VolumeComp(num_elements=num_elements, b=b, L=L) self.add_subsystem('volume_comp', comp) comp = ExecComp([ 'obj = ' + ' + '.join(['compliance_%d' % i for i in range(num_load_cases)]) ]) self.add_subsystem('obj_sum', comp) for j, src in enumerate(obj_srcs): self.connect(src, 'obj_sum.compliance_%d' % j) self.connect('inputs_comp.h_cp', 'interp.h_cp') self.connect('interp.h', 'I_comp.h') self.connect('I_comp.I', 'local_stiffness_matrix_comp.I') self.connect('local_stiffness_matrix_comp.K_local', 'global_stiffness_matrix_comp.K_local') self.connect('interp.h', 'volume_comp.h') self.add_design_var('inputs_comp.h_cp', lower=1e-2, upper=10.) self.add_constraint('volume_comp.volume', equals=volume) self.add_objective('obj_sum.obj')
def test_steady_aircraft_for_docs(self): import matplotlib.pyplot as plt from openmdao.api import Problem, Group, pyOptSparseDriver, IndepVarComp from openmdao.utils.assert_utils import assert_rel_error import dymos as dm from dymos.examples.aircraft_steady_flight.aircraft_ode import AircraftODE from dymos.examples.plotting import plot_results from dymos.utils.lgl import lgl p = Problem(model=Group()) p.driver = pyOptSparseDriver() p.driver.options['optimizer'] = 'SLSQP' p.driver.options['dynamic_simul_derivs'] = True num_seg = 15 seg_ends, _ = lgl(num_seg + 1) traj = p.model.add_subsystem('traj', dm.Trajectory()) phase = traj.add_phase( 'phase0', dm.Phase(ode_class=AircraftODE, transcription=dm.Radau(num_segments=num_seg, segment_ends=seg_ends, order=3, compressed=False))) # Pass Reference Area from an external source assumptions = p.model.add_subsystem('assumptions', IndepVarComp()) assumptions.add_output('S', val=427.8, units='m**2') assumptions.add_output('mass_empty', val=1.0, units='kg') assumptions.add_output('mass_payload', val=1.0, units='kg') phase.set_time_options(initial_bounds=(0, 0), duration_bounds=(300, 10000), duration_ref=5600) phase.set_state_options('range', units='NM', fix_initial=True, fix_final=False, ref=1e-3, defect_ref=1e-3, lower=0, upper=2000) phase.set_state_options('mass_fuel', units='lbm', fix_initial=True, fix_final=True, upper=1.5E5, lower=0.0, ref=1e2, defect_ref=1e2) phase.set_state_options('alt', units='kft', fix_initial=True, fix_final=True, lower=0.0, upper=60, ref=1e-3, defect_ref=1e-3) phase.add_control('climb_rate', units='ft/min', opt=True, lower=-3000, upper=3000, rate_continuity=True, rate2_continuity=False) phase.add_control('mach', units=None, opt=False) phase.add_input_parameter('S', units='m**2') phase.add_input_parameter('mass_empty', units='kg') phase.add_input_parameter('mass_payload', units='kg') phase.add_path_constraint('propulsion.tau', lower=0.01, upper=2.0, shape=(1, )) p.model.connect('assumptions.S', 'traj.phase0.input_parameters:S') p.model.connect('assumptions.mass_empty', 'traj.phase0.input_parameters:mass_empty') p.model.connect('assumptions.mass_payload', 'traj.phase0.input_parameters:mass_payload') phase.add_objective('range', loc='final', ref=-1.0e-4) p.setup() p['traj.phase0.t_initial'] = 0.0 p['traj.phase0.t_duration'] = 3600.0 p['traj.phase0.states:range'][:] = phase.interpolate( ys=(0, 724.0), nodes='state_input') p['traj.phase0.states:mass_fuel'][:] = phase.interpolate( ys=(30000, 1e-3), nodes='state_input') p['traj.phase0.states:alt'][:] = 10.0 p['traj.phase0.controls:mach'][:] = 0.8 p['assumptions.S'] = 427.8 p['assumptions.mass_empty'] = 0.15E6 p['assumptions.mass_payload'] = 84.02869 * 400 p.run_driver() assert_rel_error(self, p.get_val('traj.phase0.timeseries.states:range', units='NM')[-1], 726.85, tolerance=1.0E-2) exp_out = traj.simulate() plot_results([('traj.phase0.timeseries.states:range', 'traj.phase0.timeseries.states:alt', 'range (NM)', 'altitude (kft)'), ('traj.phase0.timeseries.time', 'traj.phase0.timeseries.states:mass_fuel', 'time (s)', 'fuel mass (lbm)')], title='Commercial Aircraft Optimization', p_sol=p, p_sim=exp_out) plt.show()
structure_problem_params = StaticStructureProblemParams( node_id, node_id_all) aero_problem_params = AeroProblemParams() na = aero_problem_dimensions.na network_info = aero_problem_dimensions.network_info node_coord = structure_problem_params.node_coord node_coord_all = structure_problem_params.node_coord_all t = structure_problem_params.t m = structure_problem_params.m apoints_coord = aero_problem_params.apoints_coord top = Problem() top.root = root = Group() # top.root.deriv_options['type'] = 'fd' # top.root.deriv_options['step_size'] = 1.0e-1 #Add independent variables root.add('wing_area', IndepVarComp('Sw', Sw), promotes=['*']) root.add('airspeed', IndepVarComp('V', V), promotes=['*']) root.add('sigma_y', IndepVarComp('sigma_y', sigma_y), promotes=['*']) root.add('stress_ref', IndepVarComp('s0', s0), promotes=['*']) root.add('air_density', IndepVarComp('rho_a', rho_a), promotes=['*']) root.add('Mach_number', IndepVarComp('Mach', Mach), promotes=['*']) root.add('young_module', IndepVarComp('E', E), promotes=['*']) root.add('weight', IndepVarComp('W', W), promotes=['*']) root.add('mat_density', IndepVarComp('rho_s', rho_s), promotes=['*']) root.add('poisson', IndepVarComp('nu', nu), promotes=['*']) root.add('angle_of_attack', IndepVarComp('alpha', 0.), promotes=['*']) root.add('wing_span', IndepVarComp('b', b), promotes=['*'])
def test_simple_list_vars_options(self): from openmdao.api import Group, Problem, IndepVarComp class QuadraticComp(ImplicitComponent): """ A Simple Implicit Component representing a Quadratic Equation. R(a, b, c, x) = ax^2 + bx + c Solution via Quadratic Formula: x = (-b + sqrt(b^2 - 4ac)) / 2a """ def setup(self): self.add_input('a', val=1., units='ft') self.add_input('b', val=1., units='inch') self.add_input('c', val=1., units='ft') self.add_output('x', val=0., lower=1.0, upper=100.0, ref=1.1, ref0=2.1, units='inch') self.declare_partials(of='*', wrt='*') def apply_nonlinear(self, inputs, outputs, residuals): a = inputs['a'] b = inputs['b'] c = inputs['c'] x = outputs['x'] residuals['x'] = a * x**2 + b * x + c def solve_nonlinear(self, inputs, outputs): a = inputs['a'] b = inputs['b'] c = inputs['c'] outputs['x'] = (-b + (b**2 - 4 * a * c)**0.5) / (2 * a) group = Group() comp1 = group.add_subsystem('comp1', IndepVarComp()) comp1.add_output('a', 1.0, units='ft') comp1.add_output('b', 1.0, units='inch') comp1.add_output('c', 1.0, units='ft') 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() # list_inputs test stream = cStringIO() inputs = prob.model.list_inputs(values=False, out_stream=stream) text = stream.getvalue() self.assertEqual(sorted(inputs), [ ('sub.comp2.a', {}), ('sub.comp2.b', {}), ('sub.comp2.c', {}), ('sub.comp3.a', {}), ('sub.comp3.b', {}), ('sub.comp3.c', {}), ]) self.assertEqual(1, text.count("6 Input(s) in 'model'")) self.assertEqual(1, text.count("top")) self.assertEqual(1, text.count(" sub")) self.assertEqual(1, text.count(" comp2")) self.assertEqual(2, text.count(" a")) num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()]) self.assertEqual(num_non_empty_lines, 14) # list_outputs tests # list implicit outputs outputs = prob.model.list_outputs(explicit=False, out_stream=None) text = stream.getvalue() self.assertEqual(sorted(outputs), [('sub.comp2.x', { 'value': [3.] }), ('sub.comp3.x', { 'value': [3.] })]) # list explicit outputs stream = cStringIO() outputs = prob.model.list_outputs(implicit=False, out_stream=None) self.assertEqual(sorted(outputs), [ ('comp1.a', { 'value': [1.] }), ('comp1.b', { 'value': [-4.] }), ('comp1.c', { 'value': [3.] }), ])
def test_guess_nonlinear_feature(self): from openmdao.api import Problem, Group, ImplicitComponent, IndepVarComp, NewtonSolver, ScipyKrylov class ImpWithInitial(ImplicitComponent): def setup(self): self.add_input('a', val=1.) self.add_input('b', val=1.) self.add_input('c', val=1.) self.add_output('x', val=0.) self.declare_partials(of='*', wrt='*') def apply_nonlinear(self, inputs, outputs, residuals): a = inputs['a'] b = inputs['b'] c = inputs['c'] x = outputs['x'] residuals['x'] = a * x**2 + b * x + c def solve_nonlinear(self, inputs, outputs): a = inputs['a'] b = inputs['b'] c = inputs['c'] outputs['x'] = (-b + (b**2 - 4 * a * c)**0.5) / 2 / a def linearize(self, inputs, outputs, partials): a = inputs['a'] b = inputs['b'] c = inputs['c'] x = outputs['x'] partials['x', 'a'] = x**2 partials['x', 'b'] = x partials['x', 'c'] = 1.0 partials['x', 'x'] = 2 * a * x + b self.inv_jac = 1.0 / (2 * a * x + b) def solve_nonlinear(self, inputs, outputs): """ Do nothing. """ pass def guess_nonlinear(self, inputs, outputs, resids): # Solution at 1 and 3. Default value takes us to -1 solution. Here # we set it to a value that will tke us to the 3 solution. outputs['x'] = 5.0 prob = Problem() model = prob.model = Group() model.add_subsystem('pa', IndepVarComp('a', 1.0)) model.add_subsystem('pb', IndepVarComp('b', 1.0)) model.add_subsystem('pc', IndepVarComp('c', 1.0)) model.add_subsystem('comp2', ImpWithInitial()) model.connect('pa.a', 'comp2.a') model.connect('pb.b', 'comp2.b') model.connect('pc.c', 'comp2.c') model.nonlinear_solver = NewtonSolver() model.nonlinear_solver.options['solve_subsystems'] = True model.nonlinear_solver.options['max_sub_solves'] = 1 model.linear_solver = ScipyKrylov() prob.setup(check=False) prob['pa.a'] = 1. prob['pb.b'] = -4. prob['pc.c'] = 3. prob.run_model() assert_rel_error(self, prob['comp2.x'], 3.)
# (in particular COBYLA) seem to totally ignore the design variable lower and upper bounds # Jonathan's work-around is to set additional constraints # Interesting article: http://openmdao.org/forum/questions/342/slsqpdriver-not-respecting-paramaters-low-and-high-contraints sub.driver.add_constraint('indep2.rProp', lower=30.0, upper=200.0) sub.driver.add_constraint('indep3.cruiseSpeed', lower=45.5, upper=80.0) sub.driver.add_constraint('indep4.batteryMass', lower=1.0, upper=99.90) sub.driver.add_constraint('indep5.motorMass', lower=0.10, upper=99.90) sub.driver.add_constraint('indep6.mtom', lower=1.0, upper=99.990) # SubProblem: set design constraints sub.driver.add_constraint('con1.c1', lower=0.0) sub.driver.add_constraint('con2.c2', lower=0.0) sub.driver.add_constraint('con3.c3', lower=0.0) # TopProblem: define a Problem to set up different optimization cases top = Problem(root=Group()) # TopProblem: add independent variables top.root.add('indep1', IndepVarComp('range', 50.0)) top.root.add('indep2', IndepVarComp('rProp', 100.0)) top.root.add('indep3', IndepVarComp('cruiseSpeed', 50.0)) top.root.add('indep4', IndepVarComp('batteryMass', 11.70)) top.root.add('indep5', IndepVarComp('motorMass', 3.00)) top.root.add('indep6', IndepVarComp('mtom', 6.500)) top.root.add('indep7', IndepVarComp( 'vehicle', 'tiltwing')) # 1st get this working with just the tiltwing # TopProblem: add the SubProblem top.root.add('subprob', SubProblem(sub, params=['indep1.range', 'indep2.rProp', \ 'indep3.cruiseSpeed', 'indep4.batteryMass', \ 'indep5.motorMass', 'indep6.mtom'],
self.add_output('f_x', shape=1) def solve_nonlinear(self, params, unknowns, resids): ''' f(x) = (x-3)^2 - 3 ''' x = params['x'] unknowns['f_x'] = (x - 3.0)**2 - 3.0 if __name__ == '__main__': # Instantiate a Problem 'sub' # Instantiate a Group and add it to sub sub = Problem() sub.root = Group() # Add the 'Parabola' Component to sub's root Group. sub.root.add('Parabola', Parabola()) # Initialize x_init as a IndepVarComp and add it to sub's root group as 'p1.x_init' # p1.x_init is initialized to 0.0 because the OpenMETA Design Variable 'x' has a range of -50 to +50 sub.root.add('p1', IndepVarComp('x_init', 0.0)) # Connect the IndepVarComp p1.x to Parabola.x sub.root.connect('p1.x_init', 'Parabola.x') # Add driver sub.driver = ScipyOptimizer() # Modify the optimization driver's settings
def test_brachistochrone_quick_start(self): import numpy as np from openmdao.api import Problem, Group, ScipyOptimizeDriver import dymos as dm import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt # # Define the OpenMDAO problem # p = Problem(model=Group()) # # Define a Trajectory object # traj = dm.Trajectory() p.model.add_subsystem('traj', subsys=traj) # # Define a Dymos Phase object with GaussLobatto Transcription # phase = dm.Phase(ode_class=BrachistochroneODE, transcription=dm.GaussLobatto(num_segments=10, order=3)) traj.add_phase(name='phase0', phase=phase) # # Set the time options # Time has no targets in our ODE. # We fix the initial time so that the it is not a design variable in the optimization. # The duration of the phase is allowed to be optimized, but is bounded on [0.5, 10]. # phase.set_time_options(fix_initial=True, duration_bounds=(0.5, 10.0), units='s') # # Set the time options # Initial values of positions and velocity are all fixed. # The final value of position are fixed, but the final velocity is a free variable. # The equations of motion are not functions of position, so 'x' and 'y' have no targets. # The rate source points to the output in the ODE which provides the time derivative of the # given state. phase.set_state_options('x', fix_initial=True, fix_final=True, units='m', rate_source='xdot') phase.set_state_options('y', fix_initial=True, fix_final=True, units='m', rate_source='ydot') phase.set_state_options('v', fix_initial=True, fix_final=False, units='m/s', rate_source='vdot', targets=['v']) # Define theta as a control. phase.add_control(name='theta', units='rad', lower=0, upper=np.pi, targets=['theta']) # Minimize final time. phase.add_objective('time', loc='final') # Set the driver. p.driver = ScipyOptimizeDriver() # Allow OpenMDAO to automatically determine our sparsity pattern. # Doing so can significant speed up the execution of Dymos. p.driver.options['dynamic_simul_derivs'] = True # Setup the problem p.setup(check=True) # Now that the OpenMDAO problem is setup, we can set the values of the states. p.set_val('traj.phase0.states:x', phase.interpolate(ys=[0, 10], nodes='state_input'), units='m') p.set_val('traj.phase0.states:y', phase.interpolate(ys=[10, 5], nodes='state_input'), units='m') p.set_val('traj.phase0.states:v', phase.interpolate(ys=[0, 5], nodes='state_input'), units='m/s') p.set_val('traj.phase0.controls:theta', phase.interpolate(ys=[90, 90], nodes='control_input'), units='deg') # Run the driver to solve the problem p.run_driver() # Check the validity of our results by using scipy.integrate.solve_ivp to # integrate the solution. sim_out = traj.simulate() # Plot the results fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 4.5)) axes[0].plot(p.get_val('traj.phase0.timeseries.states:x'), p.get_val('traj.phase0.timeseries.states:y'), 'ro', label='solution') axes[0].plot(sim_out.get_val('traj.phase0.timeseries.states:x'), sim_out.get_val('traj.phase0.timeseries.states:y'), 'b-', label='simulation') axes[0].set_xlabel('x (m)') axes[0].set_ylabel('y (m/s)') axes[0].legend() axes[0].grid() axes[1].plot(p.get_val('traj.phase0.timeseries.time'), p.get_val('traj.phase0.timeseries.controls:theta', units='deg'), 'ro', label='solution') axes[1].plot(sim_out.get_val('traj.phase0.timeseries.time'), sim_out.get_val('traj.phase0.timeseries.controls:theta', units='deg'), 'b-', label='simulation') axes[1].set_xlabel('time (s)') axes[1].set_ylabel(r'$\theta$ (deg)') axes[1].legend() axes[1].grid() plt.show()
# Connects Pod Geometry outputs to downstream components self.connect('pod_geometry.A_pod', 'pod_mach.A_pod') self.connect('pod_geometry.D_pod', ['pod_mass.podgeo_d', 'levitation_group.d_pod']) self.connect('pod_geometry.BF', 'pod_mass.BF') # Connects Levitation outputs to downstream components # Connects Pod Mass outputs to downstream components self.connect('pod_mass.pod_mass', 'levitation_group.m_pod') if __name__ == "__main__": prob = Problem() root = prob.root = Group() root.add('Pod', PodGroup()) params = (('comp_inlet_area', 2.3884, { 'units': 'm**2' }), ('comp_PR', 6.0, { 'units': 'unitless' }), ('PsE', 0.05588, { 'units': 'psi' }), ('des_time', 1.0), ('time_of_flight', 1.0, { 'units': 'h' }), ('motor_max_current', 800.0), ('motor_LD_ratio', 0.83), ('motor_oversize_factor', 1.0), ('inverter_efficiency', 1.0), ('battery_cross_section_area', 15000.0, { 'units': 'cm**2' }), ('n_passengers', 28.0), ('A_payload',
in_name = self.options['in_name'] out_name = self.options['out_name'] partials[out_name, in_name] = 1.0 - ( (1.0 / np.tanh(inputs[in_name]))**2).flatten() if __name__ == "__main__": from openmdao.api import Problem, IndepVarComp, Group n = 100 val = np.random.rand(n) indeps = IndepVarComp() indeps.add_output( 'x', val=val, shape=(n, ), ) prob = Problem() prob.model = Group() prob.model.add_subsystem( 'indeps', indeps, promotes=['*'], ) prob.model.add_subsystem( 'coth', CotanhComp(in_name='x', out_name='y', shape=(n, )), promotes=['*'], ) prob.setup() prob.check_partials(compact_print=True)
def create_problem(inverter): root = Group() prob = Problem(root) prob.root.add('comp', inverter) return prob
def test_algorithm_coverage_olhc(self): prob = Problem(impl=impl) root = prob.root = Group() root.add('p1', IndepVarComp('x', 50.0), promotes=['*']) root.add('p2', IndepVarComp('y', 50.0), promotes=['*']) root.add('comp', Paraboloid(), promotes=['*']) prob.driver = OptimizedLatinHypercubeDriver(100, population=5, num_par_doe=self.N_PROCS) prob.driver.add_desvar('x', lower=-50.0, upper=50.0) prob.driver.add_desvar('y', lower=-50.0, upper=50.0) prob.driver.add_objective('f_xy') prob.setup(check=False) prob.run() if MPI: runList = prob.driver._distrib_build_runlist() expected_runs = 25 else: runList = prob.driver._build_runlist() expected_runs = 100 # Ensure generated run list is a generator self.assertTrue((type(runList) == GeneratorType), "_build_runlist did not return a generator.") # Add run list to dictionaries xSet = [] ySet = [] countRuns = 0 for inputLine in runList: countRuns += 1 x, y = dict(inputLine).values() xSet.append(np.floor(x)) ySet.append(np.floor(y)) # Assert we had the correct number of runs self.assertTrue( countRuns == expected_runs, "Incorrect number of runs generated. expected %d but got %d" % (expected_runs, countRuns)) # Assert all input values in range [-50,50] valuesInRange = True for value in xSet + ySet: if value < (-50) or value > 49: valuesInRange = False self.assertTrue( valuesInRange, "One of the input values was outside the given range.") # Assert a single input in each interval [n,n+1] for n = [-50,49] self.assertTrue( len(xSet) == expected_runs, "One of the intervals wasn't covered.") self.assertTrue( len(ySet) == expected_runs, "One of the intervals wasn't covered.")
def test_case1(self): prob = Problem() model = prob.model = Group() n_init = np.array([ 3.23319258e-04, 1.00000000e-10, 1.10131241e-05, 1.00000000e-10, 1.63212420e-10, 6.18813039e-09, 1.00000000e-10, 2.69578835e-02, 1.00000000e-10, 7.23198770e-03 ]) model.add_subsystem('des_var1', IndepVarComp('Fl_I:tot:P', 100.0, units='lbf/inch**2'), promotes=["*"]) model.add_subsystem('des_var2', IndepVarComp('Fl_I:tot:h', 100.0, units='Btu/lbm'), promotes=["*"]) model.add_subsystem('des_var3', IndepVarComp('Fl_I:stat:W', 100.0, units='lbm/s'), promotes=["*"]) model.add_subsystem('des_var4', IndepVarComp('Fl_I:FAR', 0.0), promotes=["*"]) model.add_subsystem('des_var5', IndepVarComp('MN', 0.5), promotes=["*"]) model.add_subsystem('des_var6', IndepVarComp('Fl_I:tot:n', n_init), promotes=["*"]) model.add_subsystem('combustor', Combustor(), promotes=["*"]) prob.set_solver_print(level=2) prob.setup(check=False) # 6 cases to check against for i, data in enumerate(ref_data): # input flowstation prob['Fl_I:tot:P'] = data[h_map['Fl_I.Pt']] prob['Fl_I:tot:h'] = data[h_map['Fl_I.ht']] prob['Fl_I:stat:W'] = data[h_map['Fl_I.W']] prob['Fl_I:FAR'] = data[h_map['FAR']] prob['MN'] = data[h_map['Fl_O.MN']] prob.run_model() # check outputs tol = 1.0e-2 npss = data[h_map['Fl_O.Pt']] pyc = prob['Fl_O:tot:P'] rel_err = abs(npss - pyc) / npss print('Pt out:', npss, pyc, rel_err) self.assertLessEqual(rel_err, tol) npss = data[h_map['Fl_O.Tt']] pyc = prob['Fl_O:tot:T'] rel_err = abs(npss - pyc) / npss print('Tt out:', npss, pyc, rel_err) self.assertLessEqual(rel_err, tol) npss = data[h_map['Fl_O.ht']] pyc = prob['Fl_O:tot:h'] rel_err = abs(npss - pyc) / npss print('ht out:', npss, pyc, rel_err) self.assertLessEqual(rel_err, tol) npss = data[h_map['Fl_O.Ps']] pyc = prob['Fl_O:stat:P'] rel_err = abs(npss - pyc) / npss print('Ps out:', npss, pyc, rel_err) self.assertLessEqual(rel_err, tol) npss = data[h_map['Fl_O.Ts']] pyc = prob['Fl_O:stat:T'] rel_err = abs(npss - pyc) / npss print('Ts out:', npss, pyc, rel_err) self.assertLessEqual(rel_err, tol) npss = data[h_map['Wfuel']] pyc = prob['Fl_I:stat:W'] * (prob['Fl_I:FAR']) rel_err = abs(npss - pyc) / npss print('Wfuel:', npss, pyc, rel_err) self.assertLessEqual(rel_err, tol) print('') check_element_partials(self, prob, tol=1e-4)
def test_fan_out_grouped(self): prob = Problem(impl=impl) prob.root = root = Group() root.add('p', IndepVarComp('x', 1.0)) root.add('comp1', ExecComp(['y=3.0*x'])) sub = root.add('sub', ParallelGroup()) sub.add('comp2', ExecComp(['y=-2.0*x'])) sub.add('comp3', ExecComp(['y=5.0*x'])) root.add('c2', ExecComp(['y=-x'])) root.add('c3', ExecComp(['y=3.0*x'])) root.connect('sub.comp2.y', 'c2.x') root.connect('sub.comp3.y', 'c3.x') root.connect("comp1.y", "sub.comp2.x") root.connect("comp1.y", "sub.comp3.x") root.connect("p.x", "comp1.x") prob.root.ln_solver = LinearGaussSeidel() prob.root.sub.ln_solver = LinearGaussSeidel() prob.setup(check=False) prob.run() param = 'p.x' unknown_list = ['sub.comp2.y', "sub.comp3.y"] J = prob.calc_gradient([param], unknown_list, mode='fwd', return_format='dict') assert_rel_error(self, J[unknown_list[0]][param][0][0], -6.0, 1e-6) assert_rel_error(self, J[unknown_list[1]][param][0][0], 15.0, 1e-6) J = prob.calc_gradient([param], unknown_list, mode='rev', return_format='dict') assert_rel_error(self, J[unknown_list[0]][param][0][0], -6.0, 1e-6) assert_rel_error(self, J[unknown_list[1]][param][0][0], 15.0, 1e-6) unknown_list = ['c2.y', "c3.y"] J = prob.calc_gradient([param], unknown_list, mode='fwd', return_format='dict') assert_rel_error(self, J[unknown_list[0]][param][0][0], 6.0, 1e-6) assert_rel_error(self, J[unknown_list[1]][param][0][0], 45.0, 1e-6) J = prob.calc_gradient([param], unknown_list, mode='rev', return_format='dict') assert_rel_error(self, J[unknown_list[0]][param][0][0], 6.0, 1e-6) assert_rel_error(self, J[unknown_list[1]][param][0][0], 45.0, 1e-6)
def test_add_input_output_dupes(self): class Comp(ExplicitComponent): def setup(self): self.add_input('x', val=3.0) self.add_input('x', val=3.0) self.add_output('y', val=3.0) prob = Problem() model = prob.model = Group() model.add_subsystem('px', IndepVarComp('x', val=3.0)) model.add_subsystem('comp', Comp()) model.connect('px.x', 'comp.x') msg = "Variable name 'x' already exists." with assertRaisesRegex(self, ValueError, msg): prob.setup(check=False) class Comp(ExplicitComponent): def setup(self): self.add_input('x', val=3.0) self.add_output('y', val=3.0) self.add_output('y', val=3.0) prob = Problem() model = prob.model = Group() model.add_subsystem('px', IndepVarComp('x', val=3.0)) model.add_subsystem('comp', Comp()) model.connect('px.x', 'comp.x') msg = "Variable name 'y' already exists." with assertRaisesRegex(self, ValueError, msg): prob.setup(check=False) class Comp(ExplicitComponent): def setup(self): self.add_input('x', val=3.0) self.add_output('x', val=3.0) self.add_output('y', val=3.0) prob = Problem() model = prob.model = Group() model.add_subsystem('px', IndepVarComp('x', val=3.0)) model.add_subsystem('comp', Comp()) model.connect('px.x', 'comp.x') msg = "Variable name 'x' already exists." with assertRaisesRegex(self, ValueError, msg): prob.setup(check=False) # Make sure we can reconfigure. class Comp(ExplicitComponent): def setup(self): self.add_input('x', val=3.0) self.add_output('y', val=3.0) prob = Problem() model = prob.model = Group() model.add_subsystem('px', IndepVarComp('x', val=3.0)) model.add_subsystem('comp', Comp()) model.connect('px.x', 'comp.x') prob.setup(check=False) # pretend we reconfigured prob.setup(check=False)
self.connect('ambient.Ts', 'balance.rhs:Tt') self.connect('balance.Pt', 'fs.P') self.connect('balance.Tt', 'fs.T') self.connect('Fl_O:stat:P', 'balance.lhs:Pt') self.connect('Fl_O:stat:T', 'balance.lhs:Tt') # self.set_order(['ambient', 'subgroup']) if __name__ == "__main__": from openmdao.core.problem import Problem, IndepVarComp p1 = Problem() p1.model = Group() des_vars = p1.model.add_subsystem('des_vars', IndepVarComp()) des_vars.add_output('W', 0.0, units='lbm/s') des_vars.add_output('alt', 1., units='ft') des_vars.add_output('MN', 0.5) des_vars.add_output('dTs', 0.0, units='degR') fc = p1.model.add_subsystem("fc", FlightConditions()) p1.model.connect('des_vars.W', 'fc.W') p1.model.connect('des_vars.alt', 'fc.alt') p1.model.connect('des_vars.MN', 'fc.MN') p1.model.connect('des_vars.dTs', 'fc.dTs') p1.setup()
def create_problem(compressor): root = Group() prob = Problem(root) prob.root.add('comp', compressor) return prob
def solve_nonlinear(self, params, unknowns, resids): ''' f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3 ''' x = params['x'] y = params['y'] unknowns['f_xy'] = (x - 3.0)**2 + x * y + (y + 4.0)**2 - 3.0 if __name__ == '__main__': # Instantiate a sub-level Problem 'sub'. # Instantiate a Group and add it to sub sub = Problem() sub.root = Group() # Add the 'Paraboloid Component' to sub's root Group. Alternatively, I could have placed the 'Paraboloid' Component within a group sub.root.add('P', Paraboloid()) # Initialize x and y values in seperate IndepVarComps and add them to sub's root group sub.root.add('p1', IndepVarComp('x', 13.0)) sub.root.add('p2', IndepVarComp('y', -14.0)) # Define a constraint equation and add it to top's root Group sub.root.add('con', ExecComp('c = x - y')) # Connect 'p1.x' and 'p2.y' to 'con.x' and 'con.y' respectively sub.root.connect('p1.x', 'con.x') sub.root.connect('p2.y', 'con.y')
def setUp(self): self.nn = 3 self.p = Problem(model=Group()) self.ivc = DictIndepVarComp(data_dict=data) self.ivc.add_output(name='a', shape=(self.nn,)) self.ivc.add_output(name='b', shape=(self.nn,))
def setUp(self): p = Problem() p.root = Group() p.root.add('comp', CompTest(), promotes=['a','x','n','b','c']) p.root.nl_solver = Brent() self.prob = p
from UAM_team_optimization.components.Economics.mfghr_comp import MfgHrComp from UAM_team_optimization.components.Economics.toolhr_comp import ToolHrComp from UAM_team_optimization.components.Economics.qchr_comp import QcHrComp from UAM_team_optimization.components.Economics.laborcost_comp import LaborCostComp from UAM_team_optimization.components.Economics.develcost_comp import DevelCostComp from UAM_team_optimization.components.Economics.fltcost_comp import FltCostComp from UAM_team_optimization.components.Economics.mfgcost_comp import MfgCostComp from UAM_team_optimization.components.Economics.batterycost_comp import BatteryCostComp from UAM_team_optimization.components.Economics.motorcost_comp import MotorCostComp from UAM_team_optimization.components.Economics.avionicscost_comp import AvionicsCostComp from UAM_team_optimization.components.Economics.structcost_comp import StructCostComp from UAM_team_optimization.components.Economics.ac_comp import AcComp from UAM_team_optimization.components.Economics.fare_comp import FareComp prob = Problem() model = Group() comp = IndepVarComp() # Initial values for optimization: # Adding Input variables which are the outputs of input_comp # Atmospheric inital values: comp.add_output('v_inf', val=60) comp.add_output('q', val=250) # Wing inital values: comp.add_output('wing_alpha', val=0.1) comp.add_output('wing_CLa', val=2 * np.pi) comp.add_output('wing_CL0', val=0.2) comp.add_output('wing_CD0', val=0.015)
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 p.final_setup() 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 p.final_setup() 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')) msg = '\'Variable name "{}" not found.\'' inputs, outputs, residuals = g.get_nonlinear_vectors() # inputs with self.assertRaisesRegex(KeyError, msg.format('x')): inputs['x'] = 5.0 with self.assertRaisesRegex(KeyError, msg.format('x')): inputs['x'] with self.assertRaisesRegex(KeyError, msg.format('g.c.x')): inputs['g.c.x'] = 5.0 with self.assertRaisesRegex(KeyError, msg.format('g.c.x')): inputs['g.c.x'] # outputs with self.assertRaisesRegex(KeyError, msg.format('y')): outputs['y'] = 5.0 with self.assertRaisesRegex(KeyError, msg.format('y')): outputs['y'] with self.assertRaisesRegex(KeyError, msg.format('g.c.y')): outputs['g.c.y'] = 5.0 with self.assertRaisesRegex(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 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']