def _cite_cmd(options, user_args): """ Run the `openmdao cite` command. Parameters ---------- options : argparse Namespace Command line options. user_args : list of str Args to be passed to the user script. """ if options.outfile is None: out = sys.stdout else: out = open(options.outfile, 'w') if not options.classes: options.classes = None def _cite(prob): if not MPI or MPI.COMM_WORLD.rank == 0: print_citations(prob, classes=options.classes, out_stream=out) exit() hooks._register_hook('setup', 'Problem', post=_cite) ignore_errors(True) _load_and_exec(options.file[0], user_args)
def _n2_cmd(options, user_args): """ Process command line args and call n2 on the specified file. Parameters ---------- options : argparse Namespace Command line options. user_args : list of str Command line options after '--' (if any). Passed to user script. """ filename = _to_filename(options.file[0]) if filename.endswith('.py'): # the file is a python script, run as a post_setup hook def _noraise(prob): prob.model._raise_connection_errors = False if options.use_declare_partial_info: warn_deprecation("'--use_declare_partial_info' is now the" " default and the option is ignored.") def _viewmod(prob): n2(prob, outfile=options.outfile, show_browser=not options.no_browser, title=options.title, embeddable=options.embeddable) hooks._register_hook('setup', 'Problem', pre=_noraise, ncalls=1) hooks._register_hook('final_setup', 'Problem', post=_viewmod, exit=True) ignore_errors(True) _load_and_exec(options.file[0], user_args) else: # assume the file is a recording, run standalone n2(filename, outfile=options.outfile, title=options.title, show_browser=not options.no_browser, embeddable=options.embeddable)
def _timing_cmd(options, user_args): """ Implement the 'openmdao timing' command. Parameters ---------- options : argparse Namespace Command line options. user_args : list of str Args to be passed to the user script. """ if not options.funcs: options.funcs = _default_timer_methods.copy() filename = _to_filename(options.file[0]) if filename.endswith('.py'): hooks._register_hook('setup', 'Problem', pre=partial(_set_timer_setup_hook, options)) # register an atexit function to write out all of the timing data atexit.register(partial(_postprocess, options)) with timing_context(not options.use_context): _load_and_exec(options.file[0], user_args) else: # assume file is a pickle file if options.use_context: issue_warning( f"Since given file '{options.file[0]}' is not a python script, the " "'--use_context' option is ignored.") _show_view(options.file[0], options)
def _n2_cmd(options, user_args): """ Process command line args and call n2 on the specified file. Parameters ---------- options : argparse Namespace Command line options. user_args : list of str Command line options after '--' (if any). Passed to user script. """ filename = _to_filename(options.file[0]) if filename.endswith('.py'): # the file is a python script, run as a post_setup hook def _viewmod(prob): n2(prob, outfile=options.outfile, show_browser=not options.no_browser, title=options.title, embeddable=options.embeddable, use_declare_partial_info=options.use_declare_partial_info) exit() # could make this command line selectable later hooks._register_hook('final_setup', 'Problem', post=_viewmod) _load_and_exec(options.file[0], user_args) else: # assume the file is a recording, run standalone n2(filename, outfile=options.outfile, title=options.title, show_browser=not options.no_browser, embeddable=options.embeddable, use_declare_partial_info=options.use_declare_partial_info)
def _view_connections_cmd(options, user_args): """ Return the post_setup hook function for 'openmdao view_connections'. Parameters ---------- options : argparse Namespace Command line options. user_args : list of str Args to be passed to the user script. """ def _viewconns(prob): if options.title: title = options.title else: title = "Connections for %s" % os.path.basename(options.file[0]) view_connections(prob, outfile=options.outfile, show_browser=not options.no_browser, show_values=options.show_values, title=title) exit() # register the hook if options.show_values: funcname = 'final_setup' else: funcname = 'setup' hooks._register_hook(funcname, class_name='Problem', inst_id=options.problem, post=_viewconns) ignore_errors(True) _load_and_exec(options.file[0], user_args)
def _view_dyn_shapes_cmd(options, user_args): """ Return the post_setup hook function for 'openmdao view_dyn_shapes'. Parameters ---------- options : argparse Namespace Command line options. user_args : list of str Args to be passed to the user script. """ def _view_shape_graph(model): view_dyn_shapes(model, outfile=options.outfile, show=not options.no_display, title=options.title) exit() def _set_dyn_hook(prob): # we can't wait until the end of Problem.setup because we'll die in _setup_sizes # if there were any unresolved dynamic shapes, so put the hook immediately after # _setup_dynamic_shapes. inst_id is None here because no system's pathname will # have been set at the time this hook is triggered. hooks._register_hook('_setup_dynamic_shapes', class_name='Group', inst_id=None, post=_view_shape_graph) hooks._setup_hooks(prob.model) # register the hooks hooks._register_hook('setup', 'Problem', pre=_set_dyn_hook) ignore_errors(True) _load_and_exec(options.file[0], user_args)
def _xdsm_cmd(options, user_args): """ Process command line args and call xdsm on the specified file. Parameters ---------- options : argparse Namespace Command line options. user_args : list of str Command line options after '--' (if any). Passed to user script. """ filename = _to_filename(options.file[0]) kwargs = {} for name in ['box_stacking', 'box_width', 'box_lines', 'numbered_comps', 'number_alignment']: val = getattr(options, name) if val is not None: kwargs[name] = val if filename.endswith('.py'): # the file is a python script, run as a post_setup hook def _xdsm(prob): write_xdsm(prob, filename=options.outfile, model_path=options.model_path, recurse=options.recurse, include_external_outputs=not options.no_extern_outputs, out_format=options.format, include_solver=options.include_solver, subs=_CHAR_SUBS, show_browser=not options.no_browser, show_parallel=not options.no_parallel, add_process_conns=not options.no_process_conns, output_side=options.output_side, legend=options.legend, class_names=options.class_names, equations=options.equations, include_indepvarcomps=not options.no_indepvarcomps, **kwargs) exit() hooks._register_hook('setup', 'Problem', post=_xdsm) _load_and_exec(options.file[0], user_args) else: # assume the file is a recording, run standalone write_xdsm(options.file[0], filename=options.outfile, model_path=options.model_path, recurse=options.recurse, include_external_outputs=not options.no_extern_outputs, out_format=options.format, include_solver=options.include_solver, subs=_CHAR_SUBS, show_browser=not options.no_browser, show_parallel=not options.no_parallel, add_process_conns=not options.no_process_conns, output_side=options.output_side, legend=options.legend, class_names=options.class_names, equations=options.equations, **kwargs)
def _scaling_cmd(options, user_args): """ Return the post_setup hook function for 'openmdao driver_scaling'. Parameters ---------- options : argparse Namespace Command line options. user_args : list of str Args to be passed to the user script. """ def _set_flag(problem): global _run_driver_called _run_driver_called = True def _scaling_check(problem): if _run_driver_called: # If run_driver has been called, we know no more user changes are coming. _scaling(problem) def _scaling(problem): hooks._unregister_hook('final_setup', 'Problem') # avoid recursive loop hooks._unregister_hook('run_driver', 'Problem') driver = problem.driver if options.title: title = options.title else: title = "Driver scaling for %s" % os.path.basename(options.file[0]) view_driver_scaling(driver, outfile=options.outfile, show_browser=not options.no_browser, title=title, jac=not options.nojac) exit() # register the hooks hooks._register_hook('final_setup', class_name='Problem', inst_id=options.problem, post=_scaling_check) hooks._register_hook('run_driver', class_name='Problem', inst_id=options.problem, pre=_set_flag) # register an atexit function to check if scaling report was triggered during the script import atexit atexit.register(_exitfunc) ignore_errors(True) _load_and_exec(options.file[0], user_args)
def _cprof_exec(options, user_args): """ Gather profiling info. Parameters ---------- options : argparse Namespace Command line options. user_args : list of str Args to be passed to the user script. """ with profiling(options.outfile): _load_and_exec(options.file[0], user_args)
def upload_vars_init_cmd(self, py_filename, options): def upload_vars_init(prob): self.upload_vars_init(prob, options) sys.exit() d = os.path.dirname(py_filename) run_analysis_filename = os.path.join(d, "run_analysis.py") if not os.path.exists(run_analysis_filename): error( f"Can not get analysis init: script {run_analysis_filename} not found." ) hooks.use_hooks = True hooks._register_hook("final_setup", "Problem", post=upload_vars_init) _load_and_exec(run_analysis_filename, [])
def _config_summary_cmd(options, user_args): """ Return the post_setup hook function for 'openmdao summary'. Parameters ---------- options : argparse Namespace Command line options. user_args : list of str Args to be passed to the user script. """ hooks._register_hook('final_setup', 'Problem', post=config_summary, exit=True) ignore_errors(True) _load_and_exec(options.file[0], user_args)
def _check_config_cmd(options, user_args): """ Return the post_setup hook function for 'openmdao check'. Parameters ---------- options : argparse Namespace Command line options. user_args : list of str Args to be passed to the user script. Returns ------- function The post-setup hook function. """ def _check_config(prob): if not MPI or MPI.COMM_WORLD.rank == 0: if options.outfile is None: logger = get_logger('check_config', out_stream='stdout', out_file=None, use_format=True) else: logger = get_logger('check_config', out_file=options.outfile, use_format=True) if not options.checks: options.checks = sorted(_default_checks) elif 'all' in options.checks: options.checks = sorted(_all_checks) prob.check_config(logger, options.checks) exit() # register the hook _register_hook('final_setup', class_name='Problem', inst_id=options.problem, post=_check_config) ignore_errors(True) _load_and_exec(options.file[0], user_args)
def _tree_cmd(options, user_args): """ Return the post_setup hook function for 'openmdao tree'. Parameters ---------- options : argparse Namespace Command line options. user_args : list of str Args to be passed to the user script. """ if options.outfile is None: out = sys.stdout else: out = open(options.outfile, 'w') if options.attrs or options.vecvars: filt = _get_tree_filter(options.attrs, options.vecvars) else: filt = None def _tree(prob): tree(prob, show_colors=options.show_colors, show_sizes=options.show_sizes, show_approx=options.show_approx, filter=filt, max_depth=options.depth, rank=options.rank, stream=out) exit() # register the hook if options.vecvars or options.show_sizes or options.show_approx: funcname = 'final_setup' else: funcname = 'setup' hooks._register_hook(funcname, class_name='Problem', inst_id=options.problem, post=_tree) ignore_errors(True) _load_and_exec(options.file[0], user_args)
def push_mda_cmd(self, py_filename, options): def push_mda(prob): name = options["--name"] pbname = prob.model.__class__.__name__ if name and pbname != name: info("Analysis %s skipped" % pbname) # do not exit seeking for another problem (ie analysis) else: options["--pyfilename"] = py_filename xdsm = self.push_mda(prob, options) if options.get("--xdsm"): # show command # required to interrupt pb execution raise AnalysisPushedException(xdsm=xdsm) else: sys.exit() hooks.use_hooks = True hooks._register_hook("final_setup", "Problem", post=push_mda) _load_and_exec(py_filename, []) return push_mda
def _memtop_exec(options, user_args): """ Display the top memory usage. Parameters ---------- options : argparse Namespace Command line options. user_args : list of str Args to be passed to the user script. """ if options.outfile is None: out = sys.stdout else: out = open(options.outfile, 'w') tracemalloc.start() _load_and_exec(options.file[0], user_args) snapshot = tracemalloc.take_snapshot() display_top(snapshot, limit=options.limit, file=out)
def _dist_idxs_exec(options, user_args): """ Return the post_setup hook function for 'openmdao dump_idxs'. Parameters ---------- options : argparse Namespace Command line options. user_args : list of str Args to be passed to the user script. """ if options.outfile is None: out = sys.stdout else: out = open(options.outfile, 'w') def _dumpdist(prob): dump_dist_idxs(prob, full=options.full, stream=out) exit() _register_hook('final_setup', 'Problem', post=_dumpdist) ignore_errors(True) _load_and_exec(options.file[0], user_args)
def openmdao_cmd(): """ Run an 'openmdao' sub-command or list help info for 'openmdao' command or sub-commands. """ # pre-parse sys.argv to split between before and after '--' if '--' in sys.argv: idx = sys.argv.index('--') sys_args = sys.argv[:idx] user_args = sys.argv[idx + 1:] sys.argv[:] = sys_args else: user_args = [] parser = argparse.ArgumentParser( description='OpenMDAO Command Line Tools', epilog='Use -h after any sub-command for sub-command help.' ' If using a tool on a script that takes its own command line' ' arguments, place those arguments after a "--". For example:' ' openmdao n2 -o foo.html myscript.py -- -x --myarg=bar') parser.add_argument('--version', action='version', version=version) # setting 'dest' here will populate the Namespace with the active subparser name subs = parser.add_subparsers(title='Tools', metavar='', dest="subparser_name") for p, (parser_setup_func, executor, help_str) in sorted(_command_map.items()): subp = subs.add_parser(p, help=help_str) parser_setup_func(subp) subp.set_defaults(executor=executor) if pkg_resources is None: print( "\npkg_resources was not found, so no plugin entry points can be loaded.\n" ) else: # now add any plugin openmdao commands epdict = {} for ep in pkg_resources.iter_entry_points(group='openmdao_command'): cmd, module, target = split_ep(ep) # don't let plugins override the builtin commands if cmd in _command_map: raise RuntimeError( "openmdao plugin command '{}' defined in {} conflicts with " "builtin command '{}'.".format(cmd, module, cmd)) elif cmd in epdict: raise RuntimeError( "openmdao plugin command '{}' defined in {} conflicts with a " "another plugin command defined in {}.".format( cmd, module, epdict[cmd][1])) epdict[cmd] = (ep, module) # sort commands by module and then by command name so commands from plugins will # be grouped together. for cmd, (ep, module) in sorted(epdict.items(), key=lambda x: x[1][1] + x[0]): func = ep.load() parser_setup_func, executor, help_str = func() pkg = module.split('.', 1)[0] subp = subs.add_parser(cmd, help='(%s plugin) ' % pkg + help_str) parser_setup_func(subp) subp.set_defaults(executor=executor) # handle case where someone just runs `openmdao <script> [dashed-args]` args = [a for a in sys.argv[1:] if not a.startswith('-')] if not set(args).intersection( subs.choices) and len(args) == 1 and os.path.isfile(args[0]): _load_and_exec(args[0], user_args) else: hooks.use_hooks = True # we do a parse_known_args here instead of parse_args so that we can associate errors with # the correct subparser. Otherwise we would just get a top level error message without any # sub-command usage info. options, unknown = parser.parse_known_args() if unknown: msg = 'unrecognized arguments: ' + ', '.join(unknown) try: sub = subs.choices[options.subparser_name] except KeyError: parser.error(msg) else: print(sub.format_usage(), file=sys.stderr) print(msg, file=sys.stderr) parser.exit(2) if hasattr(options, 'executor'): options.executor(options, user_args) else: print("\nNothing to do.")
def _scaling_cmd(options, user_args): """ Return the post_setup hook function for 'openmdao driver_scaling'. Parameters ---------- options : argparse Namespace Command line options. user_args : list of str Args to be passed to the user script. """ def _set_run_driver_flag(problem): global _run_driver_called _run_driver_called.add(problem._name) def _set_run_model_start(problem): global _run_model_start _run_model_start.add(problem._name) def _set_run_model_done(problem): global _run_model_done _run_model_done.add(problem._name) def _scaling_check(problem): if problem._name in _run_driver_called: # If run_driver has been called, we know no more user changes are coming. if problem._name not in _run_model_start: problem.run_model() if problem._name in _run_model_done: _scaling(problem) def _scaling(problem): driver = problem.driver if options.title: title = options.title else: title = "Driver scaling for %s" % os.path.basename(options.file[0]) view_driver_scaling(driver, outfile=options.outfile, show_browser=not options.no_browser, title=title, jac=not options.nojac) exit() # register the hooks hooks._register_hook('final_setup', class_name='Problem', inst_id=options.problem, post=_scaling_check) hooks._register_hook('run_model', class_name='Problem', inst_id=options.problem, pre=_set_run_model_start, post=_set_run_model_done, ncalls=1) hooks._register_hook('run_driver', class_name='Problem', inst_id=options.problem, pre=_set_run_driver_flag, ncalls=1) # register an atexit function to check if scaling report was triggered during the script import atexit atexit.register(functools.partial(_exitfunc, options.problem)) ignore_errors(True) _load_and_exec(options.file[0], user_args)
def _meta_model_cmd(options, user_args): """ Return the post_setup hook function for 'openmdao meta_model'. Parameters ---------- options : argparse Namespace Command line options. user_args : list of str Args to be passed to the user script. """ def _view_metamodel(prob): if bokeh is None: print( "bokeh must be installed to view a MetaModel. Use the command:\n", " pip install bokeh") exit() hooks._unregister_hook('final_setup', 'Problem') mm_types = (MetaModelStructuredComp, MetaModelUnStructuredComp) pathname = options.pathname port_number = options.port_number resolution = options.resolution browser = options.browser if pathname: comp = prob.model._get_subsystem(pathname) if comp and isinstance(comp, mm_types): view_metamodel(comp, resolution, port_number, browser) exit() else: comp = None metamodels = { mm.pathname: mm for mm in prob.model.system_iter(include_self=True, typ=mm_types) } mm_names = list(metamodels.keys()) mm_count = len(mm_names) if mm_count == 0: print("No Metamodel components found in model.") elif mm_count == 1 and not pathname: comp = metamodels[mm_names[0]] view_metamodel(comp, resolution, port_number, browser) else: try_str = "Try one of the following: {}.".format(mm_names) if not pathname: print("\nMetamodel not specified. {}".format(try_str)) elif not comp: print("\nMetamodel '{}' not found.\n {}".format( pathname, try_str)) else: print("\n'{}' is not a Metamodel.\n {}".format( pathname, try_str)) exit() hooks._register_hook('final_setup', 'Problem', post=_view_metamodel) _load_and_exec(options.file[0], user_args)