def generate_results(prob): """Create all results from the routine. Extract the data that has been retrieved by OpenMDAO and use them to generate, plot and save results. Args: prob (om.Problem object): Current problem that is being defined """ if Rt.use_aeromap and Rt.type == 'DoE': dct.add_am_to_dict(optim_var_dict, am_dict) ## Generate N2 scheme ## om.n2(optim_dir_path + '/circuit.sqlite', optim_dir_path + '/circuit.html', False) ## Recap of the problem inputs/outputs ## prob.model.list_inputs() prob.model.list_outputs() ## Results processing ## tls.plot_results(optim_dir_path, '', optim_var_dict) tls.save_results(optim_dir_path, optim_var_dict) wkf.copy_module_to_module(Rt.modules[-1], 'out', 'Optimisation', 'out')
def test_oad_process(cleanup): """ Test for the overall aircraft design process. """ configurator = FASTOADProblemConfigurator(pth.join(DATA_FOLDER_PATH, "oad_process.yml")) # Create inputs ref_inputs = pth.join(DATA_FOLDER_PATH, "CeRAS01_legacy.xml") configurator.write_needed_inputs(ref_inputs) # Create problems with inputs problem = configurator.get_problem(read_inputs=True) problem.setup() problem.run_model() problem.write_outputs() if not pth.exists(RESULTS_FOLDER_PATH): os.mkdir(RESULTS_FOLDER_PATH) om.view_connections( problem, outfile=pth.join(RESULTS_FOLDER_PATH, "connections.html"), show_browser=False ) om.n2(problem, outfile=pth.join(RESULTS_FOLDER_PATH, "n2.html"), show_browser=False) # Check that weight-performances loop correctly converged _check_weight_performance_loop(problem)
def routine_launcher(Opt): """Run an optimisation routine or DoE using the OpenMDAO library. This function launches the setup for the routine by setting up the problem with the OpenMDAO component, creating of reading a file containing all the problem parameters and launching the driver. It also specifies where to save the case recordings and launches the results plotting at the end of the routine. Args: Opt (class) : Indicates which modules to use and the routine type (Optim or DoE). Returns: None. """ global counter, optim_var_dict, Rt counter = 0 Rt = opf.Routine() Rt.type = Opt.optim_method Rt.modules = Opt.module_optim ## Initialize CPACS file and problem dictionary ## create_routine_folder() opf.first_run(Rt.modules) Rt.get_user_inputs(opf.CPACS_OPTIM_PATH) optim_var_dict = opf.create_variable_library(Rt, optim_dir_path) ## Instantiate components and subsystems ## prob = om.Problem() ivc = om.IndepVarComp() ## Add subsystems to problem ## add_subsystems(prob, ivc) ## Defining problem parameters ## add_parameters(prob, ivc) ## Setting up the problem options ## driver_setup(prob) ## Setup the model hierarchy for OpenMDAO ## prob.setup() ## Run the model ## prob.run_driver() ## Recap of the problem inputs/outputs ## prob.model.list_inputs() prob.model.list_outputs() ## Results processing ## tls.plot_results(optim_dir_path, '') tls.save_results(optim_dir_path) ## Generate N2 scheme ## om.n2(optim_dir_path + '/circuit.sqlite', optim_dir_path + '/circuit.html', False)
def write_n2(configuration_file_path: str, n2_file_path: str = None, overwrite: bool = False): """ Write the N2 diagram of the problem in file n2.html :param configuration_file_path: :param n2_file_path: :param overwrite: """ if not n2_file_path: n2_file_path = pth.join(pth.dirname(configuration_file_path), "n2.html") n2_file_path = pth.abspath(n2_file_path) if not overwrite and pth.exists(n2_file_path): raise FastFileExistsError( "N2-diagram file %s not written because it already exists. " "Use overwrite=True to bypass." % n2_file_path, n2_file_path, ) make_parent_dir(n2_file_path) problem = FASTOADProblemConfigurator(configuration_file_path).get_problem() problem.setup() problem.final_setup() om.n2(problem, outfile=n2_file_path, show_browser=False) _LOGGER.info("N2 diagram written in %s", n2_file_path)
def write_n2(configuration_file_path: str, n2_file_path: str = "n2.html", overwrite: bool = False): """ Write the N2 diagram of the problem in file n2.html :param configuration_file_path: :param n2_file_path: :param overwrite: """ if not overwrite and pth.exists(n2_file_path): raise FastFileExistsError( "N2-diagram file %s not written because it already exists. " "Use overwrite=True to bypass." % n2_file_path, n2_file_path, ) make_parent_dir(n2_file_path) conf = FASTOADProblemConfigurator(configuration_file_path) conf._set_configuration_modifier(_PROBLEM_CONFIGURATOR) problem = conf.get_problem() problem.setup() problem.final_setup() om.n2(problem, outfile=n2_file_path, show_browser=False) clear_output() _LOGGER.info("N2 diagram written in %s", pth.abspath(n2_file_path))
def test_oad_process(cleanup): """ Test for the overall aircraft design process. """ problem = FASTOADProblemConfigurator(pth.join(INPUT_FOLDER_PATH, "oad_process.toml")).get_problem() problem.model.aicraft.set_input_defaults('data:geometry:horizontal_tail:sweep_25', val=10., units='deg') ref_inputs = pth.join(INPUT_FOLDER_PATH, XML_NAME) get_problem_after_setup(problem).write_needed_inputs(ref_inputs, VariableXmlStandardFormatter()) problem.read_inputs() print('\n') problem.setup(check=True) problem.set_solver_print(level=2) with Timer(name="Mass-performance loop:"): problem.run_model() problem.write_outputs() if not pth.exists(RESULTS_FOLDER_PATH): os.mkdir(RESULTS_FOLDER_PATH) om.view_connections( problem, outfile=pth.join(RESULTS_FOLDER_PATH, "connections.html"), show_browser=False ) om.n2(problem, outfile=pth.join(RESULTS_FOLDER_PATH, "n2.html"), show_browser=False) # Check that weight-performances loop correctly converged assert_allclose( problem["data:weight:aircraft:OWE"], problem["data:weight:airframe:mass"] + problem["data:weight:propulsion:mass"] + problem["data:weight:systems:mass"] + problem["data:weight:furniture:mass"], rtol=5e-2, ) assert_allclose( problem["data:weight:aircraft:MZFW"], problem["data:weight:aircraft:OWE"] + problem["data:weight:aircraft:max_payload"], rtol=5e-2, ) assert_allclose( problem["data:weight:aircraft:MTOW"], problem["data:weight:aircraft:OWE"] + problem["data:weight:aircraft:max_payload"] + problem["data:mission:sizing:fuel"], rtol=5e-2, ) assert_allclose(problem.get_val("data:mission:sizing:fuel", units="kg"), 203.65, atol=1) # noinspection PyTypeChecker assert_allclose(problem.get_val("data:weight:aircraft:max_payload", units="kg"), 400.0, atol=1) # noinspection PyTypeChecker assert_allclose(problem["data:handling_qualities:static_margin"], 0.08515, atol=1e-2) # noinspection PyTypeChecker assert_allclose(problem.get_val("data:weight:aircraft:MTOW", units="kg"), 1650.24, atol=1) # noinspection PyTypeChecker assert_allclose(problem.get_val("data:weight:aircraft:payload", units="kg"), 360., atol=1) # noinspection PyTypeChecker assert_allclose(problem.get_val("data:weight:aircraft:OWE", units="kg"), 1046.61, atol=1) # noinspection PyTypeChecker assert_allclose(problem.get_val("data:mission:sizing:main_route:cruise:fuel", units="kg"), 166.405, atol=1)
def test_serialize_n2(self): p = om.Problem() p.model.add_subsystem('foo', BadOptionComp(bad=object())) p.setup() p.final_setup() om.n2(p, show_browser=False)
def store_model_view(self, open_in_browser=False): # type: (bool) -> None """Implementation of the view_model() function for storage and (optionally) viewing in the browser. Parameters ---------- open_in_browser : bool Setting whether to attempt to automatically open the model view in the browser. """ if self._setup_status == 0: self.setup() n2(self, outfile=self.model_view_path, show_browser=open_in_browser)
def test_oad_process(cleanup): """ Test for the overall aircraft design process. """ configurator = FASTOADProblemConfigurator( pth.join(DATA_FOLDER_PATH, "oad_process.toml")) # Create inputs ref_inputs = pth.join(DATA_FOLDER_PATH, "CeRAS01_legacy.xml") configurator.write_needed_inputs(ref_inputs) # Create problems with inputs problem = configurator.get_problem(read_inputs=True) problem.setup() problem.run_model() problem.write_outputs() if not pth.exists(RESULTS_FOLDER_PATH): os.mkdir(RESULTS_FOLDER_PATH) om.view_connections(problem, outfile=pth.join(RESULTS_FOLDER_PATH, "connections.html"), show_browser=False) om.n2(problem, outfile=pth.join(RESULTS_FOLDER_PATH, "n2.html"), show_browser=False) # Check that weight-performances loop correctly converged assert_allclose( problem["data:weight:aircraft:OWE"], problem["data:weight:airframe:mass"] + problem["data:weight:propulsion:mass"] + problem["data:weight:systems:mass"] + problem["data:weight:furniture:mass"] + problem["data:weight:crew:mass"], atol=1, ) assert_allclose( problem["data:weight:aircraft:MZFW"], problem["data:weight:aircraft:OWE"] + problem["data:weight:aircraft:max_payload"], atol=1, ) assert_allclose( problem["data:weight:aircraft:MTOW"], problem["data:weight:aircraft:OWE"] + problem["data:weight:aircraft:payload"] + problem["data:mission:sizing:needed_block_fuel"], atol=1, )
def test_oad_process(cleanup): """ Test for the overall aircraft design process. """ problem = FASTOADProblemConfigurator( pth.join(DATA_FOLDER_PATH, "oad_process.toml")).get_problem() ref_inputs = pth.join(DATA_FOLDER_PATH, "beechcraft_76.xml") get_problem_after_setup(problem).write_needed_inputs( ref_inputs, VariableXmlStandardFormatter()) problem.read_inputs() print('\n') problem.setup(check=True) problem.set_solver_print(level=2) problem.run_model() problem.write_outputs() if not pth.exists(RESULTS_FOLDER_PATH): os.mkdir(RESULTS_FOLDER_PATH) om.view_connections(problem, outfile=pth.join(RESULTS_FOLDER_PATH, "connections.html"), show_browser=False) om.n2(problem, outfile=pth.join(RESULTS_FOLDER_PATH, "n2.html"), show_browser=False) # Check that weight-performances loop correctly converged assert_allclose( problem["data:weight:aircraft:OWE"], problem["data:weight:airframe:mass"] + problem["data:weight:propulsion:mass"] + problem["data:weight:systems:mass"] + problem["data:weight:furniture:mass"], rtol=5e-2, ) assert_allclose( problem["data:weight:aircraft:MZFW"], problem["data:weight:aircraft:OWE"] + problem["data:weight:aircraft:max_payload"], rtol=5e-2, ) assert_allclose( problem["data:weight:aircraft:MTOW"], problem["data:weight:aircraft:OWE"] + problem["data:weight:aircraft:max_payload"] + problem["data:mission:sizing:fuel"], rtol=5e-2, )
def run_738_analysis(plots=False): num_nodes = 11 global NUM_X, NUM_Y NUM_X = 3 NUM_Y = 7 prob = configure_problem(num_nodes) prob.setup(check=False, mode='fwd') set_values(prob, num_nodes) prob.run_model() om.n2(prob, show_browser=False) show_outputs(prob, plots=plots) print( f"Wing weight = {prob.get_val('ac|weights|W_wing', units='lb')[0]} lb") print( f"Raymer wing weight = {prob.get_val('ac|weights|orig_W_wing', units='lb')[0]} lb" ) print(f"2.5g failure = {prob.get_val('2_5g_KS_failure')}") print(f"Climb failure = {prob.get_val('climb.ac|struct|failure')}") print(f"Cruise failure = {prob.get_val('cruise.ac|struct|failure')}") print(f"Descent failure = {prob.get_val('descent.ac|struct|failure')}") return prob
def test_broadcast_scalar_connection(self): """ OpenMDAO should allow promotion to an input that appears to have a certain shape. Users should be allowed to connect an arbitrary variable with compatible src_indices to that input. """ p = om.Problem() g1 = om.Group() # c1 contains scalar calculations ivc = om.IndepVarComp() ivc.add_output('y', val=5.0*np.ones(4,)) ivc.add_output('x', val=np.linspace(0.0, 3.0, 4)) p.model.add_subsystem('ivc', ivc) # c2 is vectorized calculations c2 = om.ExecComp('z = a * y', z={'shape': (4,)}, y={'shape': (4,)}, a={'shape': (4,)}) p.model.add_subsystem('g1', g1) g1.add_subsystem('g1', c2) # The ultimate source of a and y may be scalar, or have some other arbitrary shape g1.promotes('g1', inputs=['a', 'y'], src_indices=[0, 0, 0, 0], src_shape=(1,)) p.model.connect('ivc.y', 'g1.y') # Now connect only a portion of some other output to a, which appears as a scalar input # (This currently breaks because we're specifying the src_indices of an input twice.) p.model.connect('ivc.x', 'g1.a', src_indices=[-1]) p.setup() p.run_model() om.n2(p.model)
def test_multiple_inputs_different_src_indices(self): """ When different variables get promoted to the same name, but have different src_indices, this should be supported as long as the src_shape of the different promotions is compatible or made so by the set_input_defaults call. """ p = om.Problem() g1 = om.Group() g2 = om.Group() # c1 contains scalar calculations c1 = om.ExecComp('y = a0 + b', y={'shape': (1,)}, a0={'shape': (1,)}, b={'shape': (1,)}) # c2 is vectorized calculations c2 = om.ExecComp('z = a * y', z={'shape': (4,)}, y={'shape': (4,)}, a={'shape': (4,)}) p.model.add_subsystem('g1', g1, promotes_inputs=['a', 'b']) g1.add_subsystem('c1', c1, promotes_inputs=[('a0', 'a'), 'b'], promotes_outputs=['y']) g2.add_subsystem('c2', c2, promotes_inputs=['a', 'y']) g1.add_subsystem('g2', g2) g1.promotes('g2', inputs=['y'], src_indices=[0, 0, 0, 0], src_shape=(1,)) g1.promotes('g2', inputs=['a'], src_indices=[0, 0, 0, 0], src_shape=(1,)) p.model.promotes('g1', inputs=['a'], src_indices=[0], src_shape=(1,)) p.setup() p.run_model() om.n2(p.model)
def write_n2(configuration_file_path: str, n2_file_path: str = None, overwrite: bool = False): """ Write the N2 diagram of the problem in file n2.html :param configuration_file_path: :param n2_file_path: if None, will default to `n2.html` :param overwrite: :return: path of generated file. :raise FastFileExistsError: if overwrite==False and n2_file_path already exists """ if not n2_file_path: n2_file_path = "n2.html" n2_file_path = pth.abspath(n2_file_path) if not overwrite and pth.exists(n2_file_path): raise FastFileExistsError( "N2-diagram file %s not written because it already exists. " "Use overwrite=True to bypass." % n2_file_path, n2_file_path, ) make_parent_dir(n2_file_path) conf = FASTOADProblemConfigurator(configuration_file_path) conf._set_configuration_modifier(_PROBLEM_CONFIGURATOR) problem = conf.get_problem() problem.setup() problem.final_setup() om.n2(problem, outfile=n2_file_path, show_browser=False) if InteractiveShell.initialized(): clear_output() _LOGGER.info("N2 diagram written in %s", pth.abspath(n2_file_path)) return n2_file_path
# Setup problem and add design variables, constraint, and objective prob.model.add_design_var('wing.thickness_cp', lower=0.01, upper=0.5, ref=1e-1) prob.model.add_constraint('wing.failure', upper=0.) prob.model.add_constraint('wing.thickness_intersects', upper=0.) # Add design variables, constraisnt, and objective on the problem prob.model.add_objective('wing.structural_mass', scaler=1e-5) ## Part-4: Set up and run the optimization problem # Set up the problem prob.setup(force_alloc_complex=False) # prob.run_model() # prob.check_partials(compact_print=False, method='fd') # exit() prob.run_driver() print('wing.radius:', prob['wing.radius']) print('Structural_mass (obj):', prob['wing.structural_mass'][0]) print('Thickness_cp (x):', prob['wing.thickness_cp']) # Part-5: Generate N2 diagram from openmdao.api import n2 n2(prob) # Part-6: visualization from openaerostruct.utils.plot_wing import disp_plot args = [[], []] args[1] = 'struct.db' disp_plot(args=args)
p['phase.t_initial'] = 0.0 p['phase.t_duration'] = 10. for cell in np.arange(cells): p['phase.states:T_cell_{}'.format(cell)] = phase.interpolate( ys=[293.15, 333.15], nodes='state_input') p['phase.states:T_cell_1'] = phase.interpolate(ys=[373.15, 333.15], nodes='state_input') p.run_driver() p.model.list_inputs(prom_name=True) p.model.list_outputs(prom_name=True) time_opt = p.get_val('phase.timeseries.time', units='s') om.view_connections(p) om.n2(p) for j in np.arange(cells): T_cell = p.get_val('phase.timeseries.states:T_cell_{}'.format(j), units='K') plt.plot(time_opt, T_cell, label='cell {}'.format(j)) plt.xlabel('time, s') plt.ylabel('T_cell, K') plt.legend() plt.show()
class LanceurPropSolideFactory(LanceurPropSolideFactoryBase): """ A factory to create disciplines of LanceurPropSolide analysis """ pass if __name__ == "__main__": parser = OptionParser() parser.add_option("-n", "--no-n2", action="store_false", dest='n2_view', default=True, help="display N2 openmdao viewer") (options, args) = parser.parse_args() problem = Problem() problem.model = LanceurPropSolide() problem.setup() problem.final_setup() if options.n2_view: from packaging import version if version.parse(OPENMDAO_VERSION) < version.parse("2.10.0"): from openmdao.api import view_model as n2 else: from openmdao.visualization.n2_viewer.n2_viewer import n2 n2(problem)
p.set_val('traj.phase0.controls:phi', value=phase0.interpolate(ys=[80, 90], nodes='control_input'), units='deg') p.set_val('traj.phase1.t_initial', value=1.0) p.set_val('traj.phase1.t_duration', value=1.0) p.set_val('traj.phase1.states:y', value=phase1.interpolate(ys=[0, 0], nodes='state_input')) p.set_val('traj.phase1.states:x', value=phase1.interpolate(ys=[0, 1], nodes='state_input')) p.set_val('traj.phase1.controls:phi', value=phase1.interpolate(ys=[90, 100], nodes='control_input'), units='deg') p.set_val('traj.design_parameters:v', value=2.0) # # Solve the problem # phase0.refine_options['refine'] = True phase0.refine_options['tolerance'] = 1.0E-6 phase0.refine_options['max_order'] = 11 p.final_setup() om.n2(p.model) # # Simulate the problem using the optimized control time history # exp_out = traj.simulate(record_file='donner_sub_simulation.sql') print('Max y:', p.get_val('traj.phase0.timeseries.states:y').ravel()[-1])
fem_origin, SBEIG, num_dt), promotes=['*']) # Components after the time loop root.add_subsystem('vlm_funcs', UVLMFunctionals(num_x, num_y_sym, CL0, CD0, num_dt), promotes=['*']) ################### # Run the program # ################### prob = om.Problem() prob.model = root prob.set_solver_print() # Setup data recording # name_data = '%s_v%.2f_ndt%.0f_damp%.2f_alpha%.1f_w%.0f'%(wing, v, num_dt, zeta, alpha, num_w) # db_name = 'results/flutter/db/%s'%(name_data) # prob.driver.add_recorder(om.SqliteRecorder(db_name)) prob.setup() om.n2(prob, outfile="aerostruct_for_loop.html", show_browser=False) st = time() prob.run_model() print("run time", time() - st) print("number of steps =", num_dt) print("dt =", prob['dt']) print("CL =", prob['CL'], "; CD =", prob['CD'])
def test_oad_process(cleanup): """ Test the overall aircraft design process without and with optimization. """ test = FASTOADProblemConfigurator( pth.join(INPUT_FOLDER_PATH, "oad_process.toml")) problem = FASTOADProblemConfigurator( pth.join(INPUT_FOLDER_PATH, "oad_process.toml")).get_problem() recorder = om.SqliteRecorder("cases.sql") ref_inputs = pth.join(INPUT_FOLDER_PATH, XML_NAME) get_problem_after_setup(problem).write_needed_inputs( ref_inputs, VariableXmlStandardFormatter()) problem.read_inputs() print('\n') problem.setup(check=True) solver = problem.model.nonlinear_solver solver.add_recorder(recorder) problem.run_model() problem.write_outputs() if not pth.exists(RESULTS_FOLDER_PATH): os.mkdir(RESULTS_FOLDER_PATH) om.view_connections(problem, outfile=pth.join(RESULTS_FOLDER_PATH, "connections.html"), show_browser=False) om.n2(problem, outfile=pth.join(RESULTS_FOLDER_PATH, "n2.html"), show_browser=False) # Check that weight-performances loop correctly converged assert_allclose( problem["data:weight:aircraft:OWE"], problem["data:weight:airframe:mass"] + problem["data:weight:propulsion:mass"] + problem["data:weight:systems:mass"] + problem["data:weight:furniture:mass"], rtol=5e-2, ) assert_allclose( problem["data:weight:aircraft:MZFW"], problem["data:weight:aircraft:OWE"] + problem["data:weight:aircraft:max_payload"], rtol=5e-2, ) assert_allclose( problem["data:weight:aircraft:MTOW"], problem["data:weight:aircraft:OWE"] + problem["data:weight:aircraft:payload"] + problem["data:mission:sizing:fuel"], rtol=5e-2, ) if XML_NAME == "cirrus_sr22.xml": assert_allclose(problem.get_val("data:mission:sizing:fuel", units="kg"), 258.831, atol=1) # noinspection PyTypeChecker assert_allclose( problem["data:handling_qualities:stick_fixed_static_margin"], 0.0728, atol=1e-2) # noinspection PyTypeChecker assert_allclose(problem.get_val("data:weight:aircraft:MTOW", units="kg"), 1629.7406025, atol=1) # noinspection PyTypeChecker assert_allclose(problem.get_val("data:weight:aircraft:OWE", units="kg"), 1030.9167, atol=1) else: assert_allclose(problem.get_val("data:mission:sizing:fuel", units="kg"), 228.624, atol=1) # noinspection PyTypeChecker assert_allclose( problem["data:handling_qualities:stick_fixed_static_margin"], 0.0252, atol=1e-2) # noinspection PyTypeChecker assert_allclose(problem.get_val("data:weight:aircraft:MTOW", units="kg"), 1678.863295, atol=1) # noinspection PyTypeChecker assert_allclose(problem.get_val("data:weight:aircraft:OWE", units="kg"), 1090.2524, atol=1)
def test_n2_parallel(self): """ Verify that allgather() is called from all ranks and doesn't sit there blocking. """ om.n2(self.p, show_browser=False, outfile=OUTFILE)
def _build_problem(self): func(self) # setup internal problem g = self.group _remove_nonresiduals(g._root) # Collect residual expressions and their corresponding inputs # and outputs for res_expr in g._root.dependencies: if isinstance(res_expr, Subsystem) == False and isinstance( res_expr, ExplicitOutput) == False: # inputs for this residual only in_exprs = set(collect_input_exprs([], res_expr, res_expr)) # output corresponding to this residual out_name = self.group.res_out_map[res_expr.name] # accumulate inputs and outputs to set values self.all_inputs[out_name] = in_exprs self.all_outputs = self.all_outputs.union({out_name}) # add component output # output is an input to internal problem self.add_output( out_name, shape=res_expr.shape, val=res_expr.val, ) # add inputs, declare partials (out wrt in) for in_expr in in_exprs: if in_expr.name != out_name: self.add_input( in_expr.name, shape=in_expr.shape, val=in_expr.val, ) self.declare_partials( of=out_name, wrt=in_expr.name, ) # residual wrt output self.declare_partials( of=out_name, wrt=out_name, ) # set response and design variables to compute derivatives # treat inputs and output as inputs to internal model # treat residual as output of internal model self.prob.model.add_constraint(res_expr.name) for in_expr in in_exprs: in_name = in_expr.name if in_name in self.prob.model._design_vars or in_name in self.prob.model._static_design_vars: pass else: self.prob.model.add_design_var(in_name) if out_name in self.prob.model._design_vars or out_name in self.prob.model._static_design_vars: pass else: self.prob.model.add_design_var(out_name) self.prob.setup() # set initial values for inputs and output for res_expr in self.group._root.dependencies: if isinstance(res_expr, Subsystem) == False and isinstance( res_expr, ExplicitOutput) == False: out_name = self.group.res_out_map[res_expr.name] if len(self.group.out_vals) == 0: self.prob[out_name] = 1 else: self.prob[out_name] = self.group.out_vals[out_name] for in_expr in self.all_inputs[out_name]: self.prob[in_expr.name] = in_expr.val # create n2 diagram of internal model for debugging if self.n2 == True: self.prob.run_model() self.prob.model.list_inputs() self.prob.model.list_outputs() from openmdao.api import n2 n2(self.prob)
""" This is not a real run_file. It is only used to make the n2 diagram for the notional aerostructural problem used for demonstration in the docs. """ import openmdao.api as om p = om.Problem() dvs = p.model.add_subsystem('design_vars', om.IndepVarComp(), promotes=['*']) dvs.add_output('x_aero') dvs.add_output('x_struct') aerostruct = p.model.add_subsystem('aerostruct_cycle', om.Group(), promotes=['*']) #note the equations don't matter... just need a simple way to get inputs and outputs there aerostruct.add_subsystem( 'aero', om.ExecComp(['w = u+x_aero', 'Cl=u+x_aero', 'Cd = u + x_aero']), promotes=['*']) aerostruct.add_subsystem('struct', om.ExecComp(['u = w+x_struct', 'mass=x_struct']), promotes=['*']) p.model.add_subsystem('objective', om.ExecComp('f=mass+Cl/Cd'), promotes=['*']) p.model.add_subsystem('constraint', om.ExecComp('g=Cl'), promotes=['*']) p.setup() om.n2(p, outfile='aerostruct_n2.html', embeddable=True, show_browser=False)
def setup(self): out_name = self.options['out_name'] condition = self.options['condition'] if isinstance(condition, Input): raise TypeError("Condition must not be an Input object") expr_true = self.options['expr_true'] if isinstance(expr_true, Input): raise TypeError( "Variable object to evaluate when condition is TRUE must not be an Input object" ) expr_false = self.options['expr_false'] if isinstance(expr_false, Input): raise TypeError( "Variable object to evaluate when condition is FALSE must not be an Input object" ) if expr_true.shape != expr_false.shape: raise ValueError( "Variable shapes must be the same for Variable objects for both branches of execution" ) self.add_output( out_name, shape=expr_true.shape, val=expr_true.val, ) # collect input expressions for all three problems self.in_exprs_condition = set( collect_input_exprs([], condition, condition)) self.in_exprs_true = set(collect_input_exprs([], expr_true, expr_true)) self.in_exprs_false = set( collect_input_exprs([], expr_false, expr_false)) # TODO: enable multiple outputs # self.all_inputs[out_name] = in_exprs # self.all_outputs = self.all_outputs.union({out_name}) # add inputs, declare partials (out wrt in) for in_expr in set(self.in_exprs_condition, self.in_exprs_true, self.in_exprs_false): if in_expr.name != out_name: self.add_input( in_expr.name, shape=in_expr.shape, val=in_expr.val, ) self.declare_partials( of=out_name, wrt=in_expr.name, ) # setup response variables self.condition.model.add_constraint(condition.name) self.ptrue.model.add_constraint(expr_true.name) self.pfalse.model.add_constraint(expr_false.name) # setup input variables for in_expr in self.in_exprs_condition: in_name = in_expr.name if in_name in self.condition.model._design_vars or in_name in self.condition.model._static_design_vars: pass else: self.condition.model.add_design_var(in_name) for in_expr in self.in_exprs_true: in_name = in_expr.name if in_name in self.ptrue.model._design_vars or in_name in self.ptrue.model._static_design_vars: pass else: self.ptrue.model.add_design_var(in_name) for in_expr in self.in_exprs_false: in_name = in_expr.name if in_name in self.pfalse.model._design_vars or in_name in self.pfalse.model._static_design_vars: pass else: self.pfalse.model.add_design_var(in_name) # setup internal problems self.condition.model._root = deepcopy(condition) self.condition.setup() self.ptrue.model._root = deepcopy(expr_true) self.ptrue.setup() self.pfalse.model._root = deepcopy(expr_false) self.pfalse.setup() # create n2 diagram of internal model for debugging if self.options['n2'] == True: self.ptrue.run_model() self.ptrue.model.list_inputs() self.ptrue.model.list_outputs() self.pfalse.run_model() self.pfalse.model.list_inputs() self.pfalse.model.list_outputs() from openmdao.api import n2 # TODO: check that two n2 diagrams are created, make sure # both show up in docs n2(self.ptrue) n2(self.pfalse)
prob.model.add_constraint('AS_point_0.L_equals_W', equals=0.) # Instead of using an equality constraint here, we have to give it a little # wiggle room to make SLSQP work correctly. prob.model.add_constraint('AS_point_0.CM', lower=-0.001, upper=0.001) prob.model.add_constraint('wing.twist_cp', lower=np.array([-1e20, -1e20, 5.]), upper=np.array([1e20, 1e20, 5.])) # We're trying to minimize fuel burn prob.model.add_objective('AS_point_0.fuelburn', scaler=.1) # Set up the problem prob.setup() om.n2(prob) # Use this if you just want to run analysis and not optimization # prob.run_model() # # Actually run the optimization problem prob.run_driver() print("alpha = ", prob['alpha']) print("sweep = ", prob['wing.sweep']) print("twist_cp = ", prob['wing.twist_cp']) print("thickness_cp = ", prob['wing.thickness_cp']) print("CL = ", prob['AS_point_0.wing_perf.CL']) print("CD = ", prob['AS_point_0.wing_perf.CD']) print("fuelburn = ", prob['AS_point_0.fuelburn'])