Package openmdao.lib

This package contains the OpenMDAO Standard Library. It’s intended to contain all of the plugins that are officially supported and released as part of openmdao.

CASEHANDLERS

api.py

A central place to access all of the OpenMDAO case recorders and case iterators in the standard library.

case_db_to_dict

caseiter_to_caseset

CaseArray

CaseSet

DBCaseIterator

DBCaseRecorder

DumpCaseRecorder

ListCaseIterator

ListCaseRecorder

caseset.py

class openmdao.lib.casehandlers.caseset.CaseArray(obj=None, parent_uuid=None, names=None)[source]

Bases: object

A CaseRecorder/CaseIterator containing Cases having the same set of input/output strings but different data. Cases are not necessarily unique.

clear()[source]

Remove all case values from this container, but leave list of variables intact.

get_iter()[source]
pop(idx=-1)[source]
record(case)[source]

Record the given Case.

update(*case_containers)[source]

Add Cases from other CaseSets or CaseArrays to this one.

class openmdao.lib.casehandlers.caseset.CaseSet(obj=None, parent_uuid=None, names=None)[source]

Bases: openmdao.lib.casehandlers.caseset.CaseArray

A CaseRecorder/CaseIterator containing Cases having the same set of input/output strings but different data. All Cases in the set are unique.

clear()[source]

Remove all case values from this CaseSet, but leave list of variables intact.

difference(*case_sets)[source]

Return a new CaseSet with Cases in this that are not in the others.

intersection(*case_sets)[source]

Return a new CaseSet with Cases that are common to this and all others.

isdisjoint(case_set)[source]

Return True if this CaseSet has no Cases in common with the given CaseSet.

issubset(case_set)[source]

Return True if every Case in this one is in the given CaseSet.

issuperset(case_set)[source]

Return True if every Case in the given CaseSet is in this one.

pop(idx=-1)[source]
symmetric_difference(case_set)[source]

Return a new CaseSet with Cases in either this one or the other but not both.

union(*case_sets)[source]

Return a new CaseSet with Cases from this one and all others.

openmdao.lib.casehandlers.caseset.caseiter_to_caseset(caseiter, varnames=None, include_errors=False)[source]

Retrieve the values of specified variables from cases in a CaseIterator.

Returns a CaseSet containing cases with the specified varnames.

Cases in the case iterator that do not have all of the specified varnames are ignored.

caseiter: CaseIterator
A CaseIterator containing the cases of interest.
varnames: iterator returning strs (optional) [None]
Iterator of names of variables to be retrieved. If None, the list of varnames in the first Case without errors returned from the case iterator will be used.
include_errors: bool (optional) [False]
If True, include data from cases that reported an error.

db.py

class openmdao.lib.casehandlers.db.DBCaseIterator(dbfile=':memory:', selectors=None, connection=None)[source]

Bases: object

Pulls Cases from a relational DB (sqlite). It doesn’t support general sql queries, but it does allow for a series of boolean selectors, e.g., ‘x<=y’, that are ANDed together.

get_iter()[source]
dbfile[source]

The name of the database. This can be a filename or :memory: for an in-memory database.

class openmdao.lib.casehandlers.db.DBCaseRecorder(dbfile=':memory:', model_id='', append=False)[source]

Bases: object

Records Cases to a relational DB (sqlite). Values other than floats, ints or strings are pickled and are opaque to SQL queries.

get_iterator()[source]

Return a DBCaseIterator that points to our current DB.

record(case)[source]

Record the given Case.

dbfile[source]

The name of the database. This can be a filename or :memory: for an in-memory database.

openmdao.lib.casehandlers.db.case_db_to_dict(dbname, varnames, case_sql='', var_sql='', include_errors=False)[source]

Retrieve the values of specified variables from a sqlite DB containing Case data.

Returns a dict containing a list of values for each entry, keyed on variable name.

Only data from cases containing ALL of the specified variables will be returned so that all data values with the same index will correspond to the same case.

dbname: str
The name of the sqlite DB file.
varnames: list[str]
Iterator of names of variables to be retrieved.
case_sql: str (optional)
SQL syntax that will be placed in the WHERE clause for Case retrieval.
var_sql: str (optional)
SQL syntax that will be placed in the WHERE clause for variable retrieval.
include_errors: bool (optional) [False]
If True, include data from cases that reported an error.
openmdao.lib.casehandlers.db.cmdlineXYplot()[source]

Based on command line options, display an XY plot using data from a sqlite Case DB.

openmdao.lib.casehandlers.db.displayXY(dbname, xnames, ynames, case_sql=None, var_sql=None, title='', grid=False, xlabel='', ylabel='')[source]

Display an XY plot using Case data from a sqlite DB.

dbname: str
Name of the database file.
xnames: list[str]
Names of X variables.
ynames: list[str]
Names of Y variables.
case_sql: str (optional)
SQL syntax that will be placed in the WHERE clause for Case retrieval.
var_sql: str (optional)
SQL syntax that will be placed in the WHERE clause for variable retrieval.
title: str (optional)
Plot title.
grid: bool (optional)
If True, a grid is drawn on the plot.
xlabel: str (optional)
X axis label.
ylabel: str (optional)
Y axis label.
openmdao.lib.casehandlers.db.list_db_vars(dbname)[source]

Return the set of the names of the variables found in the specified case DB file.

dbname: str
The name of the sqlite DB file.

dumpcaserecorder.py

class openmdao.lib.casehandlers.dumpcaserecorder.DumpCaseRecorder(out=<open file '<stdout>', mode 'w' at 0x01A70070>)[source]

Bases: object

Dumps cases in a “pretty” form to a file-like object called “out” (defaults to sys.stdout). If out is None, cases will be ignored.

record(case)[source]

Dump the given Case in a “pretty” form.

listcaseiter.py

class openmdao.lib.casehandlers.listcaseiter.ListCaseIterator(cases)[source]

Bases: enthought.traits.has_traits.HasTraits

An iterator that returns Case objects from a passed-in iterator of cases. This can be useful for runtime-generated cases from an optimizer, etc.

get_iter()[source]

listcaserecorder.py

class openmdao.lib.casehandlers.listcaserecorder.ListCaseRecorder[source]

Bases: object

Stores cases in a list.

get_iterator()[source]
record(case)[source]

Store the case in our internal list.

COMPONENTS

api.py

Psudo package providing a central place to access all of the OpenMDAO components standard library.

DeMux

ExpectedImprovement

ExternalCode

MetaModel

MultiObjExpectedImprovement

Mux

ParetoFilter

ProbIntersect

dynwrapper.py

expected_improvement.py

Expected Improvement calculation for one or more objectives.

class openmdao.lib.components.expected_improvement.ExpectedImprovement(doc=None, directory='')[source]

Bases: openmdao.main.component.Component

Instance (ICaseIterator) best_case

CaseIterator which contains a single case, representing the criteria value.

  • default: ‘None’
  • iotype: ‘in’
  • copy: ‘deep’
  • required: True
Str criteria

Name of the variable to maximize the expected improvement around. Must be a NormalDistrubtion type.

  • default: ‘’
  • iotype: ‘in’
Instance (NormalDistribution) predicted_value

the Normal Distribution of the predicted value for some function at some point where you wish to calculate the EI.

  • default: ‘None’
  • iotype: ‘in’
  • copy: ‘deep’
Float EI

The expected improvement of the predicted_value

  • default: ‘0.0’
  • iotype: ‘out’
Float PI

The probability of improvement of the predicted_value

  • default: ‘0.0’
  • iotype: ‘out’
execute()[source]

Calculates the expected improvement of the model at a given point.

expected_improvement_multiobj.py

Expected Improvement calculation for one or more objectives

class openmdao.lib.components.expected_improvement_multiobj.MultiObjExpectedImprovement(*args, **kwargs)[source]

Bases: openmdao.main.component.Component

Instance (ICaseIterator) best_cases

CaseIterator which contains only Pareto optimal cases according to criteria

  • default: ‘None’
  • iotype: ‘in’
  • copy: ‘deep’
Array criteria

Names of responses to maximize expected improvement around. Must be NormalDistribution type.

  • default: ‘[]’
  • iotype: ‘in’
  • comparison_mode: 1
Array predicted_values

CaseIterator which contains NormalDistributions for each response at a location where you wish to calculate EI.

  • default: ‘[]’
  • iotype: ‘in’
  • comparison_mode: 1
Float EI

The expected improvement of the next_case

  • default: ‘0.0’
  • iotype: ‘out’
Float PI

The probability of improvement of the next_case

  • default: ‘0.0’
  • iotype: ‘out’
execute()[source]

Calculates the expected improvement of the model at a given point.

get_y_star()[source]

external_code.py

Base class for an external application that needs to be executed.

class openmdao.lib.components.external_code.ExternalCode(*args, **kwargs)[source]

Bases: openmdao.main.component_with_derivatives.ComponentWithDerivatives

Run an external code as a component.

Dict env_vars

Environment variables required by the command.

  • default: ‘{}’
  • iotype: ‘in’
Float poll_delay

Delay between polling for command completion. A value of zero will use an internally computed default.

  • default: ‘0.0’
  • iotype: ‘in’
  • units: ‘s’
  • low: 0.0
Dict resources

Resources required to run this component.

  • default: ‘{}’
  • iotype: ‘in’
Float timeout

Maximum time to wait for command completion. A value of zero implies an infinite wait.

  • default: ‘0.0’
  • iotype: ‘in’
  • units: ‘s’
  • low: 0.0
Int return_code

Return code from the command.

  • default: ‘0’
  • iotype: ‘out’
Bool timed_out

True if the command timed-out.

  • default: ‘False’
  • iotype: ‘out’
Str command

The command to be executed.

  • default: ‘’
copy_inputs(inputs_dir, patterns)[source]

Copy inputs from inputs_dir that match patterns.

inputs_dir: string
Directory to copy files from. Relative paths are evaluated from the component’s execution directory.
patterns: list or string
One or more glob patterns to match against.

This can be useful for resetting problem state.

copy_results(results_dir, patterns)[source]

Copy files from results_dir that match patterns.

results_dir: string
Directory to copy files from. Relative paths are evaluated from the component’s execution directory.
patterns: list or string
One or more glob patterns to match against.

This can be useful for workflow debugging when the external code takes a long time to execute.

execute()[source]

Runs the specified command.

First removes existing output (but not in/out) files. Then if resources have been specified, an appropriate server is allocated and the command is run on that server. Otherwise the command is run locally.

get_access_controller()[source]

Return AccessController for this object.

set(path, value, index=None, src=None, force=False)[source]

Don’t allow setting of ‘command’ by remote client.

stop()[source]

Stop the external code.

metamodel.py

Metamodel provides basic Meta Modeling capability

class openmdao.lib.components.metamodel.MetaModel(*args, **kwargs)[source]

Bases: openmdao.main.component.Component

A component that provides general Meta Modeling capability.

See the Standard Library Reference for additional information on the MetaModel component.

Instance (Component) model

Socket for the Component or Assembly being encapsulated.

  • default: ‘None’
  • copy: ‘deep’
Instance (ICaseRecorder) recorder

Records training cases

  • default: ‘None’
  • copy: ‘deep’
List excludes

A list of names of variables to be excluded from the public interface.

  • default: ‘[]’
  • iotype: ‘in’
  • copy: ‘deep’
List includes

A list of names of variables to be included in the public interface.

  • default: ‘[]’
  • iotype: ‘in’
  • copy: ‘deep’
Instance (ICaseIterator) warm_start_data

CaseIterator containing cases to use as initial training data. When this is set, all previous training data is cleared, and replaced with data from this CaseIterator

  • default: ‘None’
  • iotype: ‘in’
  • copy: ‘deep’
Dict surrogate

An dictionary provides a mapping between variables and surrogate models for each output. The “default” key must be given. It is the default surrogate model for all outputs. Any specific surrogate models can be specifed by a key with the desired variable name.

  • default: ‘{}’
  • allow_none: True
  • key_train: <class ‘enthought.traits.trait_types.Str’>
child_invalidated(childname, outs=None, force=False)[source]
exec_counts(compnames)[source]
execute()[source]

If the training flag is set, train the metamodel. Otherwise, predict outputs.

invalidate_deps(compname=None, varnames=None, force=False)[source]
list_inputs_to_model()[source]

Return the list of names of public inputs that correspond to model inputs.

list_outputs_from_model()[source]

Return the list of names of public outputs that correspond to model outputs.

update_inputs(compname, varnames)[source]
update_model(oldmodel, newmodel)[source]

called whenever the model variable is set.

update_model_inputs()[source]

Copy the values of the MetaModel’s inputs into the inputs of the model. Returns the values of the inputs.

update_outputs_from_model()[source]

Copy output values from the model into the MetaModel’s outputs, and if training, save the output associated with surrogate.

mux.py

class openmdao.lib.components.mux.DeMux(n=2, *args, **kwargs)[source]

Bases: openmdao.main.component.Component

Takes one List input and splits it into n indvidual outputs. This is a logical demultiplexer.

List inputs
  • default: ‘[]’
  • iotype: ‘in’
  • copy: ‘deep’
Int n

number of items in the array to be demultiplexed

  • default: ‘2’
  • iotype: ‘in’
  • low: 2
execute()[source]
class openmdao.lib.components.mux.Mux(n=2, *args, **kwargs)[source]

Bases: openmdao.main.component.Component

Takes in n inputs and exports a length n List with the data. It is a logical multiplexer.

Int n

number of inputs to be multiplexed

  • default: ‘2’
  • iotype: ‘in’
  • low: 2
List output
  • default: ‘[]’
  • iotype: ‘out’
  • copy: ‘deep’
execute()[source]

nastran.py

nastran.py defines NastranComponent.

class openmdao.lib.components.nastran.nastran.NastranComponent(*args, **kwargs)[source]

Bases: openmdao.lib.components.external_code.ExternalCode

All Nastran-capable components should be subclasses of NastranComponent.

By subclassing NastranComponent, any component should have easy access to NastranMaker, NastranReplacer, and NastranParser. Your subclass must specify how to handle the input and output variables to NastranComponent by specifying nastran-specific attributes on the traits. All of these attributes are described further in the MSC NastranComponent docs.

Note: This component does nothing with external_files. If you want to deal with that, then do so in your subclass.

Bool delete_tmp_files

Should I delete the temporary files?

  • default: ‘True’
  • iotype: ‘in’
Bool keep_first_iteration

If I am deleting temporary files, should I keep the first one?

  • default: ‘True’
  • iotype: ‘in’
Bool keep_last_iteration

If I am deleting temporary files, should I keep the last one?

  • default: ‘True’
  • iotype: ‘in’
Str nastran_command

Location of nastran executable.

  • default: ‘’
  • iotype: ‘in’
Str nastran_command_args

Arguments to the nastran command.

  • default: ‘’
  • iotype: ‘in’
Str nastran_filename

Input filename with placeholder variables.

  • default: ‘’
  • iotype: ‘in’
Str output_tempdir_dir

Directory in which to put the output temp dir.

  • default: ‘c:userstgrzinciappdatalocaltemp3’
  • iotype: ‘in’
Str output_filename

Output filename.

  • default: ‘’
  • iotype: ‘out’
execute()[source]

Runs the NastranComponent.

We are overiding ExternalCode’s execute function. First, we setup the input file (by running NastranReplacer and then NastranMaker). Next, we run Nastran by calling our parent’s execute function. Finally, we parse the data and set the output variables given to us.

RuntimeError
The component relies on ExternalCode which can throw all sorts of RuntimeError-like exceptions (RunStopped, RunInterrupted also included).
Filesystem-type Errors
NastranComponent makes a temporary directory with mkdtemp in the temp module. If that fails, the error just propagates up.

While there are no explicit parameters or return values for this function, it gets all the input it needs from the design variables that are connected to the subclass of NastranComponent. This should be described pretty well in the documentation.

nastran_maker_hook(maker)[source]

A subclass can override this function to dynamically add variables to NastranMaker.

maker: NastranMaker object
This NastranMaker object already has all the variables that were specified in the traits.

The return will be ignored. Right after this function exits, the Nastran input file will be written out to a file.

nastran_maker.py

Defines NastranMaker, an intelligent bulk data replacer for Nastran files.

class openmdao.lib.components.nastran.nastran_maker.NastranMaker(text)[source]

Bases: object

A object that performs specified replacements conforming to the Nastran format.

The goal of NastranMaker is to output a Nastran file with a set of variables replaced. It takes an existing Nastran file and variables. In order to retain as much data as possible, it replaces the variables in long format, allowing for 16 characters, instead of 8.

set(name, cid, fieldnum, value)[source]

Records what should be replaced where.

Instead of doing the replacing as we are given the variables to replace, we’d like to do all the replacing at one time. Therefore, this function just records what should be replaced.

name: str

cid: int or str Specifies the id of the card.

fieldnum: int
What field should we modify?
value: thing that can be passed to str
What value should we put in?
write_to_file(file_handler, unique_int=10001)[source]

After specifying the substitutions that should be made, write out the finished product.

file_handler: file-like object
Should provide a write and close function.
unique_int: int
Should be unique within the entire input file for Nastran to work.

This changes self.text and then prints self.text to a file. So, calling write_to_file more than once is unnecessary, although it shouldn’t actually change anything. Also note that the unique_int should be unique within the entire file.

nastran_parser.py

Defines NastranParser, an object that provides a way of parsing and accessing the data in the grids in Nastran’s output.

class openmdao.lib.components.nastran.nastran_parser.NastranParser(text)[source]

Bases: object

Provides access to the grids of Nastran output.

get(header, subcase, constraints, column_names, row_width=1)[source]

Get some data from the grid that we parsed previously.

You specify the grid you want with the header and a subcase. If you don’t care about the subcase, set it to None. You can also give it a dictionary of constraints and also specify which columns you’d liked returned. The row_width optional attribute is useful if you have something that looks like:

ELEMENT ID PRICES
1 4.00
5.00
2 38.30
60.00

As you can see, each element has two prices. In this case, if we had a constraint that selected only the second element, we would want both prices returned. Therefore, we would set row_width to 2.

header: str
This can be the actual header or a part of the header you want to select.
subcase: None or int
If None, then just take the first one you see.
constraints: { row_name: value }
A dictionary of constraints. str: str
column_names: [ column_name ] or “*”
Specify a list of column names or the asterisk character for all of them.
row_width: int
Optional. Sometimes there are two values per item – in different rows. In that case, row_width=2. If you specify the row_width, the constraints won’t get rid of good data.
parse()[source]

Parse the information!

Try to parse grids and headers from the outfile that was given to us beforehand. The basic idea is that we split the entire file by pages. Nastran conveniently labels sections of the output by pages. Each of these pages is expected to have one grid. We parse it by trying to find location of the columns. This is done completely heuristically because of the inconsistency in Nastran’s output specification.

openmdao.lib.components.nastran.nastran_parser.readable_header(line)[source]

Convert a header to something sane.

nastran_replacer.py

Defines NastranReplacer, an object which provides a crude and simple search and replace function.

class openmdao.lib.components.nastran.nastran_replacer.NastranReplacer(text)[source]

Bases: object

A kind of dummy object that just replaces variables in a text with their corresponding values.

replace(input_variables)[source]

Replace the input_variables in the text with the corresponding values.

input_variables: {variable_name: value}
We want to replace the instances of variable_name with a value. variable_name should be a string; value should be a stringafiable object. Note that although the actual variables are specified, like %varname in the Nastran file, the variable name here should just be varname.

Changes self.text. Running this twice should probably error out since it wouldn’t find the variables it was meant to replace.

nastran_util.py

Defines helpful functions that are used in conjunction with NastranComponent.

openmdao.lib.components.nastran.nastran_util.nastran_replace_inline(big_string, old_string, new_string)[source]

Find a string and replace it with another in one big string.

In big_string (probably a line), find old_string and replace it with new_string. Because a lot of Nastran is based on 8-character blocks, this will find the 8-character block currently occupied by old_string and replace that entire block with new_string.

big_string, old_string, new_string: str

openmdao.lib.components.nastran.nastran_util.stringify(thing, length=8)[source]

Convert thing to a string of a certain length.

This function tries to make the best use of space. For integers and floaters, it will try to get the most signicant digits while staying within length. For everything else, we just try to stick in a string.

thing: anything
What we want to convert to a string.

pareto_filter.py

Pareto Filter – finds non-dominated cases.

class openmdao.lib.components.pareto_filter.ParetoFilter(doc=None, directory='')[source]

Bases: openmdao.main.component.Component

Takes a set of cases and filters out the subset of cases which are pareto optimal. Assumes that smaller values for model responses are better, so all problems must be posed as minimization problems.

List case_sets

CaseIterator with the cases to be filtered to Find the pareto optimal subset.

  • default: ‘[]’
  • iotype: ‘in’
  • copy: ‘deep’
List criteria

List of outputs from the case to consider for filtering. Note that only case outputs are allowed as criteria.

  • default: ‘[]’
  • iotype: ‘in’
  • copy: ‘deep’
Instance (ICaseIterator) dominated_set

Resulting collection of dominated cases.

  • default: ‘None’
  • iotype: ‘out’
  • copy: ‘shallow’
Instance (ICaseIterator) pareto_set

Resulting collection of pareto optimal cases.

  • default: ‘None’
  • iotype: ‘out’
  • copy: ‘shallow’
execute()[source]

Finds and removes pareto optimal points in the given case set. Returns a list of pareto optimal points. Smaller is better for all criteria.

prob_intersect.py

class openmdao.lib.components.prob_intersect.ProbIntersect(*args, **kwargs)[source]

Bases: openmdao.main.component.Component

Computes the probability that any given point from the primary concept will interesect the pareto frontiers of some other concepts.

List criteria

Names of responses to maximize expected improvement around. Must be NormalDistribution type.

  • default: ‘[]’
  • iotype: ‘in’
  • dtype: ‘str’
  • copy: ‘deep’
List global_pareto

List of CaseIterators containing competing local Pareto points

  • default: ‘[]’
  • iotype: ‘in’
  • copy: ‘deep’
Array predicted_values

CaseIterator which contains a NormalDistribution for each response at a location where you wish to calculate EI.

  • default: ‘[]’
  • iotype: ‘in’
  • comparison_mode: 1
Instance (ICaseIterator) primary_pareto

CaseIterator which contains only Pareto optimal cases belonging to the same model as predicted_values

  • default: ‘None’
  • iotype: ‘in’
  • copy: ‘deep’
Float PInt

The probability that a candidate point is close to Pareto intersection

  • default: ‘0.0’
  • iotype: ‘out’
execute()[source]

Calculates the probability that a new point is close to the intersection of Pareto frontiers.

get_y_stars()[source]

DIFFERENTIATORS

finite_difference.py

Differentiates a driver’s workflow using the finite difference method. A variety of difference types are available for both first and second order.

class openmdao.lib.differentiators.finite_difference.FiniteDifference(parent)[source]

Bases: enthought.traits.has_traits.HasTraits

Differentiates a driver’s workflow using the finite difference method. A variety of difference types are available for both first and second order.

Float default_stepsize

Default finite difference step size.

  • default: ‘1e-06’
  • iotype: ‘in’
Enum form

Finite difference form (central, forward, backward)

  • default: ‘central’
  • iotype: ‘in’
  • values: [‘central’, ‘forward’, ‘backward’]
calc_gradient()[source]

Returns the gradient vectors for this Driver’s workflow.

calc_hessian(reuse_first=False)[source]

Returns the Hessian matrix for this Driver’s workflow.

reuse_first: bool
Switch to reuse some data from the gradient calculation so that we don’t have to re-run some points we already ran (namely the baseline, +eps, and -eps cases.) Obviously you do this when the driver needs gradient and hessian information at the same point.
raise_exception(msg, exception_class=<type 'exceptions.Exception'>)[source]

Raise an exception.

setup()[source]

Sets some dimensions.

openmdao.lib.differentiators.finite_difference.diff_1st_central(fp, fm, eps)[source]

Evaluates a first order central difference.

openmdao.lib.differentiators.finite_difference.diff_1st_fwrdbwrd(fp, fm, eps)[source]

Evaluates a first order forward or backward difference.

openmdao.lib.differentiators.finite_difference.diff_2nd_xx(fp, f0, fm, eps)[source]

Evaluates an on-diagonal 2nd derivative term

openmdao.lib.differentiators.finite_difference.diff_2nd_xy(fpp, fpm, fmp, fmm, eps1, eps2)[source]

Evaluates an off-diagonal 2nd derivative term

DOEGENERATORS

api.py

Psudo package providing a central place to access all of the OpenMDAO doegenerators standard library.

FullFactorial

OptLatinHypercube

Uniform

full_factorial.py

DOEgenerator that performs a full-factorial Design of Experiments. Plugs into the DOEgenerator socket on a DOEdriver.

class openmdao.lib.doegenerators.full_factorial.FullFactorial(num_levels=None, *args, **kwargs)[source]

Bases: enthought.traits.has_traits.HasTraits

DOEgenerator that performs a full-factorial Design of Experiments. Plugs into the DOEgenerator socket on a DOEdriver.

Int num_levels

Number of levels of values for each parameter.

  • default: ‘0’
  • iotype: ‘in’
Int num_parameters

Number of independent parameters in the DOE.

  • default: ‘0’
  • iotype: ‘in’

optlh.py

class openmdao.lib.doegenerators.optlh.LatinHypercube(doe, q=2, p=1)[source]

Bases: object

mmphi()[source]

Returns the Morris-Mitchell sampling criterion for this Latin hypercube.

perturb(mutation_count)[source]

Interchanges pairs of randomly chosen elements within randomly chosen columns of a doe a number of times. The result of this operation will also be a Latin hypercube.

shape[source]

Size of the LatinHypercube doe (rows,cols).

class openmdao.lib.doegenerators.optlh.OptLatinHypercube(num_samples=None, population=None, generations=None)[source]

Bases: enthought.traits.has_traits.HasTraits

IDOEgenerator which provides a Latin hypercube DOE sample set. The Morris-Mitchell sampling criterion of the DOE is optimzied using an evolutionary algorithm.

Int generations

Number of generations the optimization will evolve over.

  • default: ‘2’
Enum norm_method

Vector norm calculation method. ‘1-norm’ is faster, but less accurate.

  • default: ‘1-norm’
  • values: [‘1-norm’, ‘2-norm’]
Int num_parameters

Number of parameters, or dimensions, for the DOE.

  • default: ‘2’
Int num_sample_points

Number of sample points in the DOE sample set.

  • default: ‘20’
Int population

Size of the population used in the evolutionary optimization.

  • default: ‘20’

uniform.py

DOEgenerator that performs a uniform space-filling Design of Experiments. Plugs into the DOEgenerator socket on a DOEdriver.

class openmdao.lib.doegenerators.uniform.Uniform(num_samples=None, *args, **kwargs)[source]

Bases: enthought.traits.has_traits.HasTraits

DOEgenerator that performs a space-filling Design of Experiments with uniform distributions on all design variables. Plugs into the DOEgenerator socket on a DOEdriver.

Int num_parameters

number of independent parameters in the DOE

  • default: ‘0’
  • iotype: ‘in’
Int num_samples

number of total samples in the DOE

  • default: ‘0’
  • iotype: ‘in’
next()[source]

DRIVERS

api.py

Psudo package providing a central place to access all of the OpenMDAO drivers standard library.

BroydenSolver

CONMINdriver

CaseIteratorDriver

DOEdriver

FixedPointIterator

Genetic

IterateUntil

NEWSUMTdriver

broydensolver.py

solver.py – Solver based on the nonlinear solvers found in Scipy.Optimize.

See the Standard Library Reference for additional information on the BroydenSolver.

class openmdao.lib.drivers.broydensolver.BroydenSolver[source]

Bases: openmdao.main.driver.Driver

MIMO Newton-Raphson Solver with Broyden approximation to the Jacobian. Algorithms are based on those found in scipy.optimize.

Nonlinear solvers

These solvers find x for which F(x)=0. Both x and F are multidimensional.

All solvers have the parameter iter (the number of iterations to compute); some of them have other parameters of the solver. See the particular solver for details.

A collection of general-purpose nonlinear multidimensional solvers.

  • broyden2: Broyden’s second method – the same as broyden1 but updates the inverse Jacobian directly
  • broyden3: Broyden’s second method – the same as broyden2 but instead of directly computing the inverse Jacobian, it remembers how to construct it using vectors. When computing inv(J)*F, it uses those vectors to compute this product, thus avoiding the expensive NxN matrix multiplication.
  • excitingmixing: The excitingmixing algorithm. J=-1/alpha

The broyden2 is the best. For large systems, use broyden3; excitingmixing is also very effective. The remaining nonlinear solvers from SciPy are, in their own words, of “mediocre quality,” so they were not implemented.

Enum algorithm

Algorithm to use. Choose from broyden2, broyden3, and excitingmixing.

  • default: ‘broyden2’
  • iotype: ‘in’
  • values: [‘broyden2’, ‘broyden3’, ‘excitingmixing’]
Float alpha

Mixing Coefficient.

  • default: ‘0.4’
  • iotype: ‘in’
Float alphamax

Maximum Mixing Coefficient (only used with excitingmixing.)

  • default: ‘1.0’
  • iotype: ‘in’
Int itmax

Maximum number of iterations before termination.

  • default: ‘10’
  • iotype: ‘in’
Float tol

Convergence tolerance. If the norm of the independent vector is lower than this, then terminate successfully.

  • default: ‘1e-05’
  • iotype: ‘in’
add_constraint(expr_string, scaler=1.0, adder=0.0)

Adds a constraint in the form of a boolean expression string to the driver.

Parameters:

expr_string: str
Expression string containing the constraint.
scaler: float (optional)
Multiplicative scale factor applied to both sides of the constraint’s boolean expression. It should be a positive nonzero value. Default is unity (1.0).
adder: float (optional)
Additive scale factor applied to both sides of the constraint’s boolean expression. Default is no additive shift (0.0).
add_eq_constraint(lhs, rhs, scaler, adder)

Adds an equality constraint as two strings, a left-hand side and a right-hand side.

add_parameter(name, low=None, high=None, fd_step=None)

Adds a parameter to the driver.

name: string
Name of the variable the driver should vary during execution.
low: float (optional)
Minimum allowed value of the parameter.
high: float (optional)
Maximum allowed value of the parameter.
fd_step: float (optional)
Step-size to use for finite difference calculation. If no value is given, the differentitator will use its own default

If neither “low” nor “high” is specified, the min and max will default to the values in the metadata of the variable being referenced. If they are not specified in the metadata and not provided as arguments, a ValueError is raised.

add_parameters(param_iter)

Takes an iterator of tuples of the form (param_name, low, high) and adds the parameters to the driver.

clear_constraints()

Removes all constraints.

clear_parameters()

Removes all parameters.

eval_eq_constraints()

Returns a list of tuples of the form (lhs, rhs, comparator, is_violated).

execute()[source]

Solver execution.

execute_broyden2()[source]

From SciPy, Broyden’s second method.

Updates inverse Jacobian by an optimal formula. There is NxN matrix multiplication in every iteration.

The best norm(F(x))=0.003 achieved in ~20 iterations.

execute_broyden3()[source]

from scipy, Broyden’s second (sic) method.

Updates inverse Jacobian by an optimal formula. The NxN matrix multiplication is avoided.

The best norm(F(x))=0.003 achieved in ~20 iterations.

execute_excitingmixing()[source]

from scipy, The excitingmixing method.

J=-1/alpha

The best norm(F(x))=0.005 achieved in ~140 iterations.

Note: SciPy uses 0.1 as the default value for alpha for this algorithm. Ours is set at 0.4, which is appropriate for Broyden2 and Broyden3, so adjust it accordingly if there are problems.

get_eq_constraints()

Returns an ordered dict of constraint objects.

get_parameters()

Returns an ordered dict of parameter objects.

list_constraints()

Return a list of strings containing constraint expressions.

list_parameters()

Returns an alphabetized list of parameter names.

remove_constraint(expr_string)

Removes the constraint with the given string.

remove_parameter(name)

Removes the parameter with the given name.

set_parameters(values)

Pushes the values in the iterator ‘values’ into the corresponding variables in the model.

values: iterator
Iterator of input values with an order defined to match the order of parameters returned by the list_parameter method. ‘values’ must support the len() function.

caseiterdriver.py

class openmdao.lib.drivers.caseiterdriver.CaseIterDriverBase(*args, **kwargs)[source]

Bases: openmdao.main.driver.Driver

A base class for Drivers that run sets of cases in a manner similar to the ROSE framework. Concurrent evaluation is supported, with the various evaluations executed across servers obtained from the ResourceAllocationManager.

Enum error_policy

If ABORT, any error stops the evaluation of the whole set of cases.

  • default: ‘ABORT’
  • iotype: ‘in’
  • values: (‘ABORT’, ‘RETRY’)
Int max_retries

Maximum number of times to retry a failed case.

  • default: ‘1’
  • iotype: ‘in’
  • low: 0
Bool reload_model

If True, reload the model between executions.

  • default: ‘True’
  • iotype: ‘in’
Bool sequential

If True, evaluate cases sequentially.

  • default: ‘True’
  • iotype: ‘in’
execute()[source]

Runs all cases and records results in recorder. Uses setup() and resume() with default arguments.

get_case_iterator()[source]

Returns a new iterator over the Case set.

resume(remove_egg=True)[source]

Resume execution.

remove_egg: bool
If True, then the egg file created for concurrent evaluation is removed at the end of the run. Re-using the egg file can eliminate a lot of startup overhead.
setup(replicate=True)[source]

Setup to begin new run.

replicate: bool
If True, then replicate the model and save to an egg file first (for concurrent evaluation).
step()[source]

Evaluate the next case.

stop()[source]

Stop evaluating cases.

class openmdao.lib.drivers.caseiterdriver.CaseIteratorDriver(*args, **kwargs)[source]

Bases: openmdao.lib.drivers.caseiterdriver.CaseIterDriverBase

Run a set of cases provided by an ICaseIterator. Concurrent evaluation is supported, with the various evaluations executed across servers obtained from the ResourceAllocationManager.

Instance (ICaseIterator) iterator

Iterator supplying Cases to evaluate.

  • default: ‘None’
  • iotype: ‘in’
  • copy: ‘deep’
get_case_iterator()[source]

Returns a new iterator over the Case set.

conmindriver.py

conmindriver.py - Driver for the CONMIN optimizer.

See the Standard Library Reference for additional information on the CONMINDriver.

The CONMIN driver can be a good example of how to wrap another Driver for OpenMDAO. However, there are some things to keep in mind.

1. This implementation of the CONMIN Fortran driver is interruptable, in that control is returned every time an objective or constraint evaluation is needed. Most external optimizers just expect a functions to be passed for these, so they require a slightly different driver implementation than this.

2. The CONMIN driver is a direct wrap, and all inputs are passed using Numpy arrays. This means there are a lot of locally stored variables that you might not need for a pure Python optimizer.

Ultimately, if you are wrapping a new optimizer for OpenMDAO, you should endeavour to understand the purpose for each statement, so that your implementation doesn’t do any unneccessary or redundant calculation.

class openmdao.lib.drivers.conmindriver.CONMINdriver(doc=None)[source]

Bases: openmdao.main.driver.Driver

Driver wrapper of Fortran version of CONMIN.

Note on self.cnmn1.igoto, which reports CONMIN’s operation state:
0: Initial and final state 1: Initial evaluation of objective and constraint values 2: Evalute gradients of objective and constraints (internal only) 3: Evalute gradients of objective and constraints 4: One-dimensional search on unconstrained function 5: Solve 1D search problem for unconstrained function
Array cons_is_linear

Array designating whether each constraint is linear.

  • default: ‘[]’
  • iotype: ‘in’
  • comparison_mode: 1
Float ct

Constraint thickness parameter.

  • default: ‘-0.1’
  • iotype: ‘in’
Float ctl

Constraint thickness parameter for linear and side constraints.

  • default: ‘-0.01’
  • iotype: ‘in’
Float ctlmin

Minimum absolute value of ctl used in optimization.

  • default: ‘0.001’
  • iotype: ‘in’
Float ctmin

Minimum absolute value of ct used in optimization.

  • default: ‘0.004’
  • iotype: ‘in’
Float dabfun

Absolute convergence tolerance.

  • default: ‘0.001’
  • iotype: ‘in’
  • low: 1e-10
Float delfun

Relative convergence tolerance.

  • default: ‘0.001’
  • iotype: ‘in’
  • low: 0.0001
Float fdch

Relative change in parameters when calculating finite difference gradients. (only when CONMIN calculates gradient)

  • default: ‘0.01’
  • iotype: ‘in’
Float fdchm

Minimum absolute step in finite difference gradient calculations. (only when CONMIN calculates gradient)

  • default: ‘0.01’
  • iotype: ‘in’
Float icndir

Conjugate gradient restart parameter.

  • default: ‘0.0’
  • iotype: ‘in’
Enum iprint

Print information during CONMIN solution. Higher values are more verbose.

  • default: ‘0’
  • iotype: ‘in’
  • values: [0, 1, 2, 3, 4, 5, 101]
Int itmax

Maximum number of iterations before termination.

  • default: ‘10’
  • iotype: ‘in’
Int itrm

Number of consecutive iterations to indicate convergence (relative or absolute).

  • default: ‘3’
  • iotype: ‘in’
Bool linobj

Linear objective function flag. Set to True if objective is linear

  • default: ‘False’
  • iotype: ‘in’
Float nscal

Scaling control parameter – controls scaling of decision variables.

  • default: ‘0.0’
  • iotype: ‘in’
Float phi

Participation coefficient - penalty parameter that pushes designs towards the feasible region.

  • default: ‘5.0’
  • iotype: ‘in’
List printvars

List of extra variables to output in the recorder.

  • default: ‘[]’
  • iotype: ‘in’
  • copy: ‘deep’
Array scal

Array of scaling factors for the parameters.

  • default: ‘[]’
  • iotype: ‘in’
  • comparison_mode: 1
Float theta

Mean value of the push-off factor in the method of feasible directions.

  • default: ‘1.0’
  • iotype: ‘in’
add_constraint(expr_string, scaler=1.0, adder=0.0)

Adds a constraint in the form of a boolean expression string to the driver.

expr_string: str
Expression string containing the constraint.
scaler: float (optional)
Multiplicative scale factor applied to both sides of the constraint’s boolean expression. It should be a positive nonzero value. Default is unity (1.0).
adder: float (optional)
Additive scale factor applied to both sides of the constraint’s boolean expression. Default is no additive shift (0.0).
add_ineq_constraint(lhs, rel, rhs, scaler, adder)

Adds an inequality constraint as three strings; a left-hand side, a comparator (‘<’,’>’,’<=’, or ‘>=’), and a right-hand side.

add_objective(expr)

Sets the objective of this driver to be the specified expression. If there is a preexisting objective in this driver, it is replaced.

expr: string
String containing the objective expression.
add_parameter(name, low=None, high=None, fd_step=None)

Adds a parameter to the driver.

name: string
Name of the variable the driver should vary during execution.
low: float (optional)
Minimum allowed value of the parameter.
high: float (optional)
Maximum allowed value of the parameter.
fd_step: float (optional)
Step-size to use for finite difference calculation. If no value is given, the differentitator will use its own default

If neither “low” nor “high” is specified, the min and max will default to the values in the metadata of the variable being referenced. If they are not specified in the metadata and not provided as arguments, a ValueError is raised.

add_parameters(param_iter)

Takes an iterator of tuples of the form (param_name, low, high) and adds the parameters to the driver.

check_gradients()

Run check_derivatives on our workflow.

clear_constraints()

Removes all constraints.

clear_parameters()

Removes all parameters.

continue_iteration()[source]

Returns True if iteration should continue.

eval_ineq_constraints()

Returns a list of constraint values

eval_objective()

Returns the value of the evaluated objective.

get_ineq_constraints()

Returns an ordered dict of inequality constraint objects.

get_parameters()

Returns an ordered dict of parameter objects.

list_constraints()

Return a list of strings containing constraint expressions.

list_objective()

Returns the expression string for the objective.

list_parameters()

Returns an alphabetized list of parameter names.

post_iteration()[source]

Checks CONMIN’s return status and writes out cases.

pre_iteration()[source]

Checks for RunStopped

remove_constraint(expr_string)

Removes the constraint with the given string.

remove_parameter(name)

Removes the parameter with the given name.

run_iteration()[source]

The CONMIN driver iteration.

set_parameters(values)

Pushes the values in the iterator ‘values’ into the corresponding variables in the model.

values: iterator
Iterator of input values with an order defined to match the order of parameters returned by the list_parameter method. ‘values’ must support the len() function.
start_iteration()[source]

Perform initial setup before iteration loop begins.

doedriver.py

doedriver.py – Driver that executes a Design of Experiments.

See the Standard Library Reference for additional information on the DOEdriver.

class openmdao.lib.drivers.doedriver.DOEdriver(*args, **kwargs)[source]

Bases: openmdao.lib.drivers.caseiterdriver.CaseIterDriverBase

Driver for Design of Experiments

Instance (IDOEgenerator) DOEgenerator

Iterator supplying normalized DOE values.

  • default: ‘None’
  • iotype: ‘in’
  • copy: ‘deep’
  • required: True
List case_outputs

A list of outputs to be saved with each case.

  • default: ‘[]’
  • iotype: ‘in’
  • copy: ‘deep’
add_parameter(name, low=None, high=None, fd_step=None)

Adds a parameter to the driver.

name: string
Name of the variable the driver should vary during execution.
low: float (optional)
Minimum allowed value of the parameter.
high: float (optional)
Maximum allowed value of the parameter.
fd_step: float (optional)
Step-size to use for finite difference calculation. If no value is given, the differentitator will use its own default

If neither “low” nor “high” is specified, the min and max will default to the values in the metadata of the variable being referenced. If they are not specified in the metadata and not provided as arguments, a ValueError is raised.

add_parameters(param_iter)

Takes an iterator of tuples of the form (param_name, low, high) and adds the parameters to the driver.

clear_parameters()

Removes all parameters.

get_case_iterator()[source]

Returns a new iterator over the Case set.

get_parameters()

Returns an ordered dict of parameter objects.

list_parameters()

Returns an alphabetized list of parameter names.

remove_parameter(name)

Removes the parameter with the given name.

set_parameters(values)

Pushes the values in the iterator ‘values’ into the corresponding variables in the model.

values: iterator
Iterator of input values with an order defined to match the order of parameters returned by the list_parameter method. ‘values’ must support the len() function.

genetic.py

A simple Pyevolve-based driver for OpenMDAO.

See the Standard Library Reference for additional information on the Genetic driver.

class openmdao.lib.drivers.genetic.Genetic(doc=None)[source]

Bases: openmdao.main.driver.Driver

Genetic algorithm for the OpenMDAO framework, based on the Pyevolve Genetic algorithm module.

Float crossover_rate

The crossover rate used when two parent genomes reproduce to form a child genome.

  • default: ‘0.9’
  • iotype: ‘in’
  • low: 0.0
  • high: 1.0
Bool elitism

Controls the use of elitism in the creation of new generations.

  • default: ‘False’
  • iotype: ‘in’
Int generations

The maximum number of generations the algorithm will evolve to before stopping.

  • default: ‘100’
  • iotype: ‘in’
Float mutation_rate

The mutation rate applied to population members.

  • default: ‘0.02’
  • iotype: ‘in’
  • low: 0.0
  • high: 1.0
Enum opt_type

Sets the optimization to either minimize or maximize the objective function.

  • default: ‘minimize’
  • iotype: ‘in’
  • values: [‘minimize’, ‘maximize’]
Int population_size

The size of the population in each generation.

  • default: ‘80’
  • iotype: ‘in’
Int seed

Random seed for the optimizer. Set to a specific value for repeatable results; otherwise leave as None for truly random seeding.

  • default: ‘0’
  • iotype: ‘in’
Enum selection_method

The selection method used to pick population members who will survive for breeding into the next generation.

  • default: ‘roulette_wheel’
  • iotype: ‘in’
  • values: (‘roulette_wheel’, ‘tournament’, ‘rank’, ‘uniform’)
Instance (GenomeBase) best_individual

The genome with the best score from the optimization.

  • default: ‘None’
  • iotype: ‘out’
  • copy: ‘deep’
add_objective(expr)

Sets the objective of this driver to be the specified expression. If there is a preexisting objective in this driver, it is replaced.

expr: string
String containing the objective expression.
add_parameter(name, low=None, high=None, fd_step=None)

Adds a parameter to the driver.

name: string
Name of the variable the driver should vary during execution.
low: float (optional)
Minimum allowed value of the parameter.
high: float (optional)
Maximum allowed value of the parameter.
fd_step: float (optional)
Step-size to use for finite difference calculation. If no value is given, the differentitator will use its own default

If neither “low” nor “high” is specified, the min and max will default to the values in the metadata of the variable being referenced. If they are not specified in the metadata and not provided as arguments, a ValueError is raised.

add_parameters(param_iter)

Takes an iterator of tuples of the form (param_name, low, high) and adds the parameters to the driver.

clear_parameters()

Removes all parameters.

eval_objective()

Returns the value of the evaluated objective.

execute()[source]

Perform the optimization

get_parameters()

Returns an ordered dict of parameter objects.

list_objective()

Returns the expression string for the objective.

list_parameters()

Returns an alphabetized list of parameter names.

remove_parameter(name)

Removes the parameter with the given name.

set_parameters(values)

Pushes the values in the iterator ‘values’ into the corresponding variables in the model.

values: iterator
Iterator of input values with an order defined to match the order of parameters returned by the list_parameter method. ‘values’ must support the len() function.

iterate.py

A simple iteration driver. Basically runs a workflow, passing the output to the input for the next iteration. Relative change and number of iterations are used as termination criteria.

class openmdao.lib.drivers.iterate.FixedPointIterator(doc=None)[source]

Bases: openmdao.main.driver.Driver

A simple fixed point iteration driver, which runs a workflow and passes the value from the output to the input for the next iteration. Relative change and number of iterations are used as termination criterea.

Int max_iteration

Maximum number of iterations before termination.

  • default: ‘25’
  • iotype: ‘in’
Float tolerance

Absolute convergence tolerance between iterations.

  • default: ‘1e-05’
  • iotype: ‘in’
Str x_out

loop output to pass to input.

  • default: ‘’
  • iotype: ‘in’
Str x_in

loop input, taken from the input.

  • default: ‘’
  • iotype: ‘out’
execute()[source]

Perform the iteration.

class openmdao.lib.drivers.iterate.IterateUntil(doc=None)[source]

Bases: openmdao.main.driver.Driver

Int max_iterations

maximun number of iterations

  • default: ‘10’
  • iotype: ‘in’
Int iteration

current iteration counter

  • default: ‘0’
  • iotype: ‘out’
add_stop_condition(exprstr)
clear_stop_conditions()

Removes all stop conditions.

continue_iteration()[source]
eval_stop_conditions()

Returns a list of evaluated stop conditions.

get_stop_conditions()

Returns a list of stop condition strings.

remove_stop_condition(expr_string)

Removes the stop condition matching the given string.

should_stop()

Return True if any of the stopping conditions evaluate to True.

start_iteration()[source]

newsumtdriver.py

newsumtdriver.py - Driver for the NEWSUMT optimizer.

(See the Standard Library Reference for additional information on the NEWSUMTDriver.)

class openmdao.lib.drivers.newsumtdriver.NEWSUMTdriver(doc=None)[source]

Bases: openmdao.main.driver.Driver

Driver wrapper of Fortran version of NEWSUMT.

Todo

Check to see if this itmax variable is needed. NEWSUMT might handle it for us.

Float default_fd_stepsize

Default finite difference stepsize. Parameters with specified values override this.

  • default: ‘0.01’
  • iotype: ‘in’
Float epsgsn

Convergence criteria of the golden section algorithm used for the one dimensional minimization.

  • default: ‘0.001’
  • iotype: ‘in’
Float epsodm

Convergence criteria of the unconstrained minimization.

  • default: ‘0.001’
  • iotype: ‘in’
Float epsrsf

Convergence criteria for the overall process.

  • default: ‘0.001’
  • iotype: ‘in’
Float g0

Initial value of the transition parameter.

  • default: ‘0.1’
  • iotype: ‘in’
Array ilin

Array designating whether each constraint is linear.

  • default: ‘[]’
  • iotype: ‘in’
  • comparison_mode: 1
Int itmax

Maximum number of iterations before termination.

  • default: ‘10’
  • iotype: ‘in’
Int jprint

Print information during NEWSUMT solution. Higher values are more verbose. If 0, print initial and final designs only.

  • default: ‘0’
  • iotype: ‘in’
  • low: -1
  • high: 3
  • exclude_high: False
  • exclude_low: False
Int lobj

Set to 1 if linear objective function.

  • default: ‘0’
  • iotype: ‘in’
Int maxgsn

Maximum allowable number of golden section iterations used for 1D minimization.

  • default: ‘20’
  • iotype: ‘in’
Int maxodm

Maximum allowable number of one dimensional minimizations.

  • default: ‘6’
  • iotype: ‘in’
Int maxrsf

Maximum allowable number of unconstrained minimizations.

  • default: ‘15’
  • iotype: ‘in’
Int mflag

Flag for penalty multiplier. If 0, initial value computed by NEWSUMT. If 1, initial value set by ra.

  • default: ‘0’
  • iotype: ‘in’
Float ra

Penalty multiplier. Required if mflag=1

  • default: ‘1.0’
  • iotype: ‘in’
Float racut

Penalty multiplier decrease ratio. Required if mflag=1.

  • default: ‘0.1’
  • iotype: ‘in’
Float ramin

Lower bound of penalty multiplier. Required if mflag=1.

  • default: ‘1e-13’
  • iotype: ‘in’
Float stepmx

Maximum bound imposed on the initial step size of the one-dimensional minimization.

  • default: ‘2.0’
  • iotype: ‘in’
add_constraint(expr_string, scaler=1.0, adder=0.0)

Adds a constraint in the form of a boolean expression string to the driver.

expr_string: str
Expression string containing the constraint.
scaler: float (optional)
Multiplicative scale factor applied to both sides of the constraint’s boolean expression. It should be a positive nonzero value. Default is unity (1.0).
adder: float (optional)
Additive scale factor applied to both sides of the constraint’s boolean expression. Default is no additive shift (0.0).
add_ineq_constraint(lhs, rel, rhs, scaler, adder)

Adds an inequality constraint as three strings; a left-hand side, a comparator (‘<’,’>’,’<=’, or ‘>=’), and a right-hand side.

add_objective(expr)

Sets the objective of this driver to be the specified expression. If there is a preexisting objective in this driver, it is replaced.

expr: string
String containing the objective expression.
add_parameter(name, low=None, high=None, fd_step=None)

Adds a parameter to the driver.

name: string
Name of the variable the driver should vary during execution.
low: float (optional)
Minimum allowed value of the parameter.
high: float (optional)
Maximum allowed value of the parameter.
fd_step: float (optional)
Step-size to use for finite difference calculation. If no value is given, the differentitator will use its own default

If neither “low” nor “high” is specified, the min and max will default to the values in the metadata of the variable being referenced. If they are not specified in the metadata and not provided as arguments, a ValueError is raised.

add_parameters(param_iter)

Takes an iterator of tuples of the form (param_name, low, high) and adds the parameters to the driver.

check_gradients()

Run check_derivatives on our workflow.

check_hessians()

Run check_derivatives on our workflow.

clear_constraints()

Removes all constraints.

clear_parameters()

Removes all parameters.

continue_iteration()[source]

Returns True if iteration should continue.

eval_ineq_constraints()

Returns a list of constraint values

eval_objective()

Returns the value of the evaluated objective.

get_ineq_constraints()

Returns an ordered dict of inequality constraint objects.

get_parameters()

Returns an ordered dict of parameter objects.

list_constraints()

Return a list of strings containing constraint expressions.

list_objective()

Returns the expression string for the objective.

list_parameters()

Returns an alphabetized list of parameter names.

pre_iteration()[source]

Checks or RunStopped and evaluates objective.

remove_constraint(expr_string)

Removes the constraint with the given string.

remove_parameter(name)

Removes the parameter with the given name.

run_iteration()[source]

The NEWSUMT driver iteration.

set_parameters(values)

Pushes the values in the iterator ‘values’ into the corresponding variables in the model.

values: iterator
Iterator of input values with an order defined to match the order of parameters returned by the list_parameter method. ‘values’ must support the len() function.
start_iteration()[source]

Perform the optimization.

simplecid.py

A simple driver that runs cases from a CaseIterator and records them with a CaseRecorder

class openmdao.lib.drivers.simplecid.SimpleCaseIterDriver(*args, **kwargs)[source]

Bases: openmdao.main.driver.Driver

A Driver that sequentially runs a set of cases provided by an ICaseIterator and records the results in a CaseRecorder. This is intended for test cases or very simple models only. For a more full-featured Driver with similar functionality, see CaseIteratorDriver.

  • The iterator socket provides the cases to be evaluated.
  • The recorder socket is used to record results.

For each case coming from the iterator, the workflow will be executed once.

Instance (ICaseIterator) iterator

Source of Cases.

  • default: ‘None’
  • required: True
  • copy: ‘deep’
execute()[source]

Run each case in iterator and record results in recorder.

SURROGATEMODELS

api.py

Psudo package providing a central place to access all of the OpenMDAO surrogatemodels standard library.

KrigingSurrogate

LogisticRegression

kriging_surrogate.py

Surrogate model based on Kriging.

class openmdao.lib.surrogatemodels.kriging_surrogate.KrigingSurrogate(X=None, Y=None)[source]

Bases: enthought.traits.has_traits.HasTraits

get_uncertain_value(value)[source]

Returns a NormalDistribution centered around the value, with a standard deviation of 0.

predict(new_x)[source]

Calculates a predicted value of the response based on the current trained model for the supplied list of inputs.

train(X, Y)[source]

Train the surrogate model with the given set of inputs and outputs.

logistic_regression.py

Surrogate Model based on a logistic regression model, with regularization to adjust for overfitting. Based on work from http://blog.smellthedata.com/2009/06/python-logistic-regression-with-l2.html

class openmdao.lib.surrogatemodels.logistic_regression.LogisticRegression(X=None, Y=None, alpha=0.10000000000000001)[source]

Bases: enthought.traits.has_traits.HasTraits

Float alpha

L2 regularization strength

  • default: ‘0.1’
  • iotype: ‘in’
  • low: 0.0
get_uncertain_value(value)[source]

Returns the value iself. Logistic regressions don’t have uncertainty

lik(betas)[source]

Likelihood of the data under the current settings of parameters.

predict(new_x)[source]

Calculates a predicted value of the response based on the current trained model for the supplied list of inputs.

train(X, Y)[source]

Define the gradient and hand it off to a scipy gradient-based optimizer.

openmdao.lib.surrogatemodels.logistic_regression.sigmoid(x)[source]

DATATYPES

api.py

Psudo package providing a central place to access all of the OpenMDAO datatypes standard library.

implements

on_trait_change

Any

Array

Bool

CBool

Complex

Dict

Enum

Event

File

Float

Instance

Int

Interface

List

Python

Str

TraitError

array.py

Trait for numpy array variables, with optional units.

class openmdao.lib.datatypes.array.Array(default_value=None, dtype=None, shape=None, iotype=None, desc=None, units=None, **metadata)[source]

Bases: enthought.traits.trait_numeric.Array

A variable wrapper for a numpy array with optional units. The unit applies to the entire array.

error(obj, name, value)[source]

Returns an informative and descriptive error string.

get_val_wrapper(value)[source]

Return a TraitValWrapper object. Its value attribute will be filled in by the caller.

validate(obj, name, value)[source]

Validates that a specified value is valid for this trait. Units are converted as needed.

domain.py

class openmdao.lib.datatypes.domain.domain.DomainObj[source]

Bases: object

A DomainObj represents a (possibly multi-zoned) mesh and data related to that mesh.

add_domain(other, prefix='', make_copy=False)[source]

Add zones from other to self, retaining names where possible.

other: DomainObj
Source for new zone data.
prefix: string
String prepended to zone names.
make_copy: bool
If True, then a deep copy of each zone is made rather than just referring to a shared instance.
add_zone(name, zone, prefix='', make_copy=False)[source]

Add a Zone. Returns the added zone.

name: string
Name for the zone. If None or blank, then a default of the form zone_N is used.
prefix: string
String prepended to the zone name.
make_copy: bool
If True, then a deep copy of each zone is made rather than just referring to a shared instance.
copy()[source]

Returns a deep copy of self.

deallocate()[source]

Deallocate resources.

is_equivalent(other, logger=None, tolerance=0.0)[source]

Test if self and other are equivalent.

other: DomainObj
The domain to check against.
logger: Logger or None
Used to log debug messages that will indicate what if anything is not equivalent.
tolerance: float
The maximum relative difference in array values to be considered equivalent.
make_cartesian(axis='z')[source]

Convert to Cartesian coordinate system.

axis: string
Specifies which is the cylinder axis (‘z’ or ‘x’).
make_cylindrical(axis='z')[source]

Convert to cylindrical coordinate system.

axis: string
Specifies which is the cylinder axis (‘z’ or ‘x’).
make_left_handed()[source]

Convert to left-handed coordinate system.

make_right_handed()[source]

Convert to right-handed coordinate system.

remove_zone(zone)[source]

Remove a zone. Returns the removed zone.

zone: string or DomainObj
Zone to be removed.
rename_zone(name, zone)[source]

Rename a zone.

name: string
New name for the zone.
zone: DomainObj
Zone to be renamed.
rotate_about_x(deg)[source]

Rotate about the X axis.

deg: float (degrees)
Amount of rotation.
rotate_about_y(deg)[source]

Rotate about the Y axis.

deg: float (degrees)
Amount of rotation.
rotate_about_z(deg)[source]

Rotate about the Z axis.

deg: float (degrees)
Amount of rotation.
translate(delta_x, delta_y, delta_z)[source]

Translate coordinates.

delta_x, delta_y, delta_z: float
Amount of translation along the corresponding axis.
zone_name(zone)[source]

Return name that a zone is bound to.

zone: DomainObj
Zone whose name is to be returned.
extent[source]

List of coordinate ranges for each zone.

shape[source]

List of coordinate index limits for each zone.

enum.py

Trait for enumerations, with optional alias list.

class openmdao.lib.datatypes.enum.Enum(default_value=None, values=(), iotype=None, aliases=(), desc=None, **metadata)[source]

Bases: openmdao.main.variable.Variable

A variable wrapper for an enumeration, which is a variable that can assume one value from a set of specified values.

error(obj, name, value)[source]

Returns a general error string for Enum.

validate(obj, name, value)[source]

Validates that a specified value is valid for this trait.

file.py

Support for files, either as File or external files.

class openmdao.lib.datatypes.file.File(default_value=None, iotype=None, desc=None, **metadata)[source]

Bases: openmdao.main.variable.Variable

A trait wrapper for a FileRef object. For input files legal_types may be set to a list of expected ‘content_type’ strings. Then upon assignment the actual ‘content_type’ must match one of the legal_types strings. Also for input files, if local_path is set, then upon assignent the associated file will be copied to that path.

post_setattr(obj, name, value)[source]

If ‘local_path’ is set on an input, then copy the source FileRef’s file to that path.

validate(obj, name, value)[source]

Verify that value is a FileRef of a legal type.

float.py

Trait for floating point variables, with optional min, max, and units.

class openmdao.lib.datatypes.float.Float(default_value=None, iotype=None, desc=None, low=None, high=None, exclude_low=False, exclude_high=False, units=None, **metadata)[source]

Bases: openmdao.main.variable.Variable

A Variable wrapper for floating point number valid within a specified range of values.

error(obj, name, value)[source]

Returns a descriptive error string.

get_val_wrapper(value)[source]

Return a TraitValWrapper object. Its value attribute will be filled in by the caller.

validate(obj, name, value)[source]

Validates that a specified value is valid for this trait. Units are converted as needed.

flow.py

class openmdao.lib.datatypes.domain.flow.FlowSolution[source]

Bases: object

Contains solution variables for a Zone. All variables have the same shape and grid location.

add_array(name, array)[source]

Add a numpy.ndarray of scalar data and bind to name. Returns the added array.

name: string
Name for the added array.
array: ndarray
Scalar data.
add_vector(name, vector)[source]

Add a Vector and bind to name. Returns the added vector.

name: string
Name for the added array.
vector: Vector
Vector data.
flip_z()[source]

Convert to other-handed coordinate system.

is_equivalent(other, logger, tolerance=0.0)[source]

Test if self and other are equivalent.

other: FlowSolution
The flowfield to check against.
logger: Logger or None
Used to log debug messages that will indicate what if anything is not equivalent.
tolerance: float
The maximum relative difference in array values to be considered equivalent.
make_cartesian(grid, axis='z')[source]

Convert to Cartesian coordinate system.

grid: GridCoordinates
Must be in cylindrical form.
axis: string
Specifies which is the cylinder axis (‘z’ or ‘x’).
make_cylindrical(grid, axis='z')[source]

Convert to cylindrical coordinate system.

grid: GridCoordinates
Must be in cylindrical form.
axis: string
Specifies which is the cylinder axis (‘z’ or ‘x’).
name_of_obj(obj)[source]

Return name of object or None if not found.

rotate_about_x(deg)[source]

Rotate about the X axis.

deg: float (degrees)
Amount of rotation.
rotate_about_y(deg)[source]

Rotate about the Y axis.

deg: float (degrees)
Amount of rotation.
rotate_about_z(deg)[source]

Rotate about the Z.

deg: float (degrees)
Amount of rotation.
arrays[source]

List of scalar data arrays.

ghosts

Number of ghost cells for each index direction.

grid_location

Position at which data is located.

vectors[source]

List of vector data.

grid.py

class openmdao.lib.datatypes.domain.grid.GridCoordinates[source]

Bases: openmdao.lib.datatypes.domain.vector.Vector

Coordinate data for a Zone.

is_equivalent(other, logger, tolerance=0.0)[source]

Test if self and other are equivalent.

other: GridCoordinates
The grid to check against.
logger: Logger or None
Used to log debug messages that will indicate what if anything is not equivalent.
tolerance: float
The maximum relative difference in array values to be considered equivalent.
make_cartesian(axis='z')[source]

Convert to Cartesian coordinate system.

axis: string
Specifies which is the cylinder axis (‘z’ or ‘x’).
make_cylindrical(axis='z')[source]

Convert to cylindrical coordinate system.

axis: string
Specifies which is the cylinder axis (‘z’ or ‘x’).
translate(delta_x, delta_y, delta_z)[source]

Translate coordinates.

delta_x, delta_y, delta_z: float
Amount of translation along the corresponding axis.
ghosts

Number of ghost cells for each index direction.

int.py

Trait for floating point variables, with optional min and max.

class openmdao.lib.datatypes.int.Int(default_value=None, iotype=None, desc=None, low=None, high=None, exclude_low=False, exclude_high=False, **metadata)[source]

Bases: openmdao.main.variable.Variable

A variable wrapper for an integer valid within a specified range of values.

error(obj, name, value)[source]

Returns a descriptive error string.

validate(obj, name, value)[source]

Validates that a specified value is valid for this trait.

plot3d.py

Functions to read and write a DomainObj in Plot3D format. Many function arguments are common:

multiblock: bool
If True, then the file is assumed to have a multiblock header.
dim: int
Specifies the expected dimensionality of the blocks.
blanking: bool
If True, then blanking data is expected.
planes: bool
If True, then the data is expected in planar, not whole, format.
binary: bool
If True, the data is in binary, not text, form.
big_endian: bool
If True, the data bytes are in ‘big-endian’ order. Only meaningful if binary.
single_precision: bool
If True, floating-point data is 32 bits, not 64. Only meaningful if binary.
unformatted: bool
If True, the data is surrounded by Fortran record length markers. Only meaningful if binary.
logger: Logger or None
Used to record progress.

Default argument values are set for a typical 3D multiblock single-precision Fortran unformatted file. When writing, zones are assumed in Cartesian coordinates with data located at the vertices.

openmdao.lib.datatypes.domain.plot3d.read_plot3d_f(grid_file, f_file, varnames=None, multiblock=True, dim=3, blanking=False, planes=False, binary=True, big_endian=False, single_precision=True, unformatted=True, logger=None)[source]

Returns a DomainObj initialized from Plot3D grid_file and f_file. Variables are assigned to names of the form f_N.

grid_file: string
Grid filename.
f_file: string
Function data filename.
openmdao.lib.datatypes.domain.plot3d.read_plot3d_grid(grid_file, multiblock=True, dim=3, blanking=False, planes=False, binary=True, big_endian=False, single_precision=True, unformatted=True, logger=None)[source]

Returns a DomainObj initialized from Plot3D grid_file.

grid_file: string
Grid filename.
openmdao.lib.datatypes.domain.plot3d.read_plot3d_q(grid_file, q_file, multiblock=True, dim=3, blanking=False, planes=False, binary=True, big_endian=False, single_precision=True, unformatted=True, logger=None)[source]

Returns a DomainObj initialized from Plot3D grid_file and q_file. Q variables are assigned to ‘density’, ‘momentum’, and ‘energy_stagnation_density’. Scalars are assigned to ‘mach’, ‘alpha’, ‘reynolds’, and ‘time’.

grid_file: string
Grid filename.
q_file: string
Q data filename.
openmdao.lib.datatypes.domain.plot3d.read_plot3d_shape(grid_file, multiblock=True, dim=3, binary=True, big_endian=False, unformatted=True, logger=None)[source]

Returns a list of zone dimensions from Plot3D grid_file.

grid_file: string
Grid filename.
openmdao.lib.datatypes.domain.plot3d.write_plot3d_f(domain, grid_file, f_file, varnames=None, planes=False, binary=True, big_endian=False, single_precision=True, unformatted=True, logger=None)[source]

Writes domain to grid_file and f_file in Plot3D format. If varnames is None, then all arrays and then all vectors are written.

domain: DomainObj
The domain to be written.
grid_file: string
Grid filename.
f_file: string
Function data filename.
openmdao.lib.datatypes.domain.plot3d.write_plot3d_grid(domain, grid_file, planes=False, binary=True, big_endian=False, single_precision=True, unformatted=True, logger=None)[source]

Writes domain to grid_file in Plot3D format.

domain: DomainObj
The domain to be written.
grid_file: string
Grid filename.
openmdao.lib.datatypes.domain.plot3d.write_plot3d_q(domain, grid_file, q_file, planes=False, binary=True, big_endian=False, single_precision=True, unformatted=True, logger=None)[source]

Writes domain to grid_file and q_file in Plot3D format. Requires ‘density’, ‘momentum’, and ‘energy_stagnation_density’ variables as well as ‘mach’, ‘alpha’, ‘reynolds’, and ‘time’ scalars.

domain: DomainObj
The domain to be written.
grid_file: string
Grid filename.
q_file: string
Q data filename.

probe.py

openmdao.lib.datatypes.domain.probe.register_surface_probe(name, function, integrate)[source]

Register a surface probe function.

name: string
The name of the metric calculated.
function: callable
The function to call. The passed arguments are (domain, surface, weights, reference_state).
integrate: bool
If True, then function values are integrated, not averaged.
openmdao.lib.datatypes.domain.probe.surface_probe(domain, surfaces, variables, weighting_scheme='area')[source]

Calculate metrics on mesh surfaces. Currently only supports 3D structured grids with cell-centered data.

domain: DomainObj
The domain to be processed.
surfaces: list
List of (zone_name, imin, imax, jmin, jmax, kmin, kmax) mesh surface specifications to be used for the calculation. Indices start at 0. Negative indices are relative to the end of the array.
variables: list
List of (metric_name, units) tuples. Legal metric names are ‘area’, ‘mass_flow’, ‘corrected_mass_flow’, ‘pressure’, ‘pressure_stagnation’, ‘temperature’, and ‘temperature_stagnation’.
weighting_scheme: string
Specifies how individual values are weighted. Legal values are ‘area’ for area averaging and ‘mass’ for mass averaging.

Returns a list of metric values in the order of the variables list.

vector.py

class openmdao.lib.datatypes.domain.vector.Vector[source]

Bases: object

Vector data for a FlowSolution. In Cartesian coordinates, array indexing order is x,y,z; so an ‘i-face’ is a y,z surface. In cylindrical coordinates, array indexing order is z,r,t; so an ‘i-face’ is an r,t surface.

flip_z()[source]

Convert to other-handed coordinate system.

is_equivalent(other, name, logger, tolerance=0.0)[source]

Test if self and other are equivalent.

other: Vector
The vector to check against.
name: string
Name of this vector, used for reporting differences.
logger: Logger or None
Used to log debug messages that will indicate what if anything is not equivalent.
tolerance: float
The maximum relative difference in array values to be considered equivalent.
make_cartesian(grid, axis='z')[source]

Convert to Cartesian coordinate system.

grid: GridCoordinates
Must be in cylindrical form.
axis: string
Specifies which is the cylinder axis (‘z’ or ‘x’).
make_cylindrical(grid, axis='z')[source]

Convert to cylindrical coordinate system.

grid: GridCoordinates
Must be in cylindrical form.
axis: string
Specifies which is the cylinder axis (‘z’ or ‘x’).
rotate_about_x(deg)[source]

Rotate about the X axis.

deg: float (degrees)
Amount of rotation.
rotate_about_y(deg)[source]

Rotate about the Y axis.

deg: float (degrees)
Amount of rotation.
rotate_about_z(deg)[source]

Rotate about the Z axis.

deg: float (degrees)
Amount of rotation.
extent[source]

Tuple of component ranges.

shape[source]

Tuple of index limits.

zone.py

class openmdao.lib.datatypes.domain.zone.Zone[source]

Bases: object

One zone in a possibly multi-zone DomainObj.

is_equivalent(other, logger, tolerance=0.0)[source]

Test if self and other are equivalent.

other: Zone
Zone to check against.
logger: Logger or None
Used to log debug messages that will indicate what if anything is not equivalent.
tolerance: float
The maximum relative difference in array values to be considered equivalent.
make_cartesian(axis='z')[source]

Convert to Cartesian coordinate system.

axis: string
Specifies which is the cylinder axis (‘z’ or ‘x’).
make_cylindrical(axis='z')[source]

Convert to cylindrical coordinate system.

axis: string
Specifies which is the cylinder axis (‘z’ or ‘x’).
make_left_handed()[source]

Convert to left-handed coordinate system.

make_right_handed()[source]

Convert to right-handed coordinate system.

rotate_about_x(deg)[source]

Rotate about the X axis.

deg: float (degrees)
Amount of rotation.
rotate_about_y(deg)[source]

Rotate about the Y axis.

deg: float (degrees)
Amount of rotation.
rotate_about_z(deg)[source]

Rotate about the Z axis.

deg: float (degrees)
Amount of rotation.
translate(delta_x, delta_y, delta_z)[source]

Translate coordinates.

delta_x, delta_y, delta_z: float
Amount of translation along the corresponding axis.
coordinate_system

Coordinate system in use.

extent[source]

Tuple of coordinate ranges.

shape[source]

Tuple of coordinate index limits.