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.

ARCHITECTURES

bliss.py

class openmdao.lib.architectures.bliss.BLISS[source]

Bases: openmdao.main.arch.Architecture

Bi-Level Integrated Systems Synthesis architecture

configure()[source]

bliss2000.py

Implementation of the BLISS2000 optimization architecture based on the work described in the following journal article:

J. Sobieszczanski-Sobieski, T. Altus, M. Phillips, and Sandu, Bilevel Integrated System Synthesis for Concurrent and Distributed Processing, AIAA journal, vol. 41, no. 10, pp. 1996-2003, 2003.

class openmdao.lib.architectures.bliss2000.BLISS2000(*args, **kwargs)[source]

Bases: openmdao.main.arch.Architecture

configure()[source]

setup and BLISS2000 architecture inside this assembly.

class openmdao.lib.architectures.bliss2000.Broadcast(doc=None, directory='')[source]

Bases: openmdao.main.component.Component

Used to create outputs in the SubSytemOpt assembly.

Float input
  • default: ‘0.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float output
  • default: ‘0.0’
  • iotype: ‘out’
  • vartypename: ‘Float’
execute()[source]
class openmdao.lib.architectures.bliss2000.SubSystemObj(num_vars)[source]

Bases: openmdao.main.component.Component

Component which adds the weight factors for each output state variable for a given subsystem.

Float f_wy

subsystem objective

  • default: ‘0.0’
  • iotype: ‘out’
  • vartypename: ‘Float’
configure()[source]
execute()[source]
class openmdao.lib.architectures.bliss2000.SubSystemOpt(component, global_params, local_params, couple_deps, couple_indeps, constraints)[source]

Bases: openmdao.main.assembly.Assembly

Assembly which takes global inputs, coupling indeps, and weight factors as inputs and runs a local optimization on the local des vars.

configure()[source]

co.py

Implementation of the Collaborative Optimization Architecture

class openmdao.lib.architectures.co.CO(*args, **kwargs)[source]

Bases: openmdao.main.arch.Architecture

configure()[source]

ego.py

class openmdao.lib.architectures.ego.EGO(*args, **kwargs)[source]

Bases: openmdao.main.arch.Architecture

Enum EI_PI

switch to decide between EI or PI for infill criterion

  • default: ‘PI’
  • iotype: ‘in’
  • values: [‘EI’, ‘PI’]
  • vartypename: ‘Enum’
Int initial_DOE_size

number of initial training points to use

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

EI or PI to use for stopping condition of optimization

  • default: ‘0.001’
  • iotype: ‘in’
  • vartypename: ‘Float’
Int sample_iterations

number of adaptively sampled points to use

  • default: ‘10’
  • iotype: ‘in’
cleanup()[source]
configure()[source]

idf.py

class openmdao.lib.architectures.idf.IDF(*args, **kwargs)[source]

Bases: openmdao.main.arch.Architecture

Architecture that uses a single top level optimizer, enforcing consistency with equality constraints.

configure()[source]

Setup an IDF architecture inside this assembly.

mdao_test_suite.py

Script to run all Architectures in openmdao.lib.architectures against all OptProblems in openmdao.lib.optproblems.

openmdao.lib.architectures.mdao_test_suite.build_arch_list(include=[], exclude=[])[source]

Builds a list of architectures.

include: list of architecture names
The names of the architectures to test. Only architectures in this list will be tested. Each name should be just the class name (e.g. ‘MDF’, ‘CO’). Must be set to None, if excludes is specified
exclude: list of architecture names
The names of the architectures not to test. All architectures from openmdao.lib.architectures will be tested, except for the ones in this list. Each name should be just the class name (e.g., ‘MDF’, ‘CO’). Must be set to None, if includes is specified.
openmdao.lib.architectures.mdao_test_suite.build_optproblem_list(include=[], exclude=[])[source]

builds a list of optproblems

include: (optional) list of optproblems names
The names of the optproblems to test. Only optproblems in this list will be tested. Each name should be just the class name (e.g., ‘SellarProblem’). Must be set to None, if excludes is specified. If not specified, all OptProblems, except those in exclude are used.
exclude: (optional) list of optproblems names
The names of the optproblems not to test. All optproblems from openmdao.lib.optproblems will be tested, except for the ones in this list. Each name should just be the class name (e.g. ‘SellarProblem’). Must be set to None, if includes is specified.
openmdao.lib.architectures.mdao_test_suite.cli_arch_test_suite(parser=None, options=None, args=None)[source]

Runs all the architectures against all the test problems. A console script runs this function.

openmdao.lib.architectures.mdao_test_suite.run_arch_test_suite(arch=[], optproblems=[])[source]

Runs the architectures against optproblems and records the results.

arch: list of Architectures
The architectures to test.
optproblems: list of OptProblems
The OptProblems to use for testing the Architectures.

mdf.py

class openmdao.lib.architectures.mdf.MDF(*args, **kwargs)[source]

Bases: openmdao.main.arch.Architecture

configure()[source]

Setup an MDF architecture inside this assembly.

CASEHANDLERS

api.py

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

case_db_to_dict

caseiter_to_caseset

CSVCaseIterator

CSVCaseRecorder

CaseArray

CaseSet

DBCaseIterator

DBCaseRecorder

DumpCaseRecorder

ExprCaseFilter

ListCaseIterator

ListCaseRecorder

SequenceCaseFilter

SliceCaseFilter

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.

close()[source]

Does nothing.

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

Record the given Case.

remove(case)[source]

Remove the given Case from this CaseArray.

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.

copy()[source]
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]
remove(case)[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.

csvcase.py

A CaseRecorder and CaseIterator that store the cases in a CSV file.

class openmdao.lib.casehandlers.csvcase.CSVCaseIterator(filename='cases.csv', headers=None)[source]

Bases: object

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.

Current limitations:

Quote character in the input CSV file should be ' or ". Other choices don’t seem to get identified by csv.Sniffer.

All string data must be contained inside of quotes. This includes field headers.

get_attributes(io_only=True)[source]

We need a custom get_attributes because we aren’t using Traits to manage our changeable settings. This is unfortunate, and should be changed to something that automates this somehow.

filename[source]

Get the name of the CSV file.

class openmdao.lib.casehandlers.csvcase.CSVCaseRecorder(filename='cases.csv', append=False, delimiter=', ', quotechar='"')[source]

Bases: object

Stores cases in a csv file. Defaults to cases.csv.

close()[source]

Closes the file.

get_attributes(io_only=True)[source]

We need a custom get_attributes because we aren’t using Traits to manage our changeable settings. This is unfortunate, and should be changed to something that automates this somehow.

get_iterator()[source]

Return CSVCaseIterator that points to our current file

record(case)[source]

Store the case in a csv file. The format for a line of data follows:

Field 1 - label Field 2 - [Empty] Field 3 - Input 1 ... Field i+2 - Input i Field i+3 - [Empty] Field i+4 - Output 1 ... Field i+j+4 - Output j Field i+j+5 - [Empty] Field i+j+6 - retries Field i+j+7 - max_retries Field i+j+8 - parent_uuid Field i+j+9 - msg

filename[source]

Get the name of the CSV file.

dbcase.py

A CaseRecorder and CaseIterator that store the cases in a relational DB (Python’s sqlite.)

class openmdao.lib.casehandlers.dbcase.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_attributes(io_only=True)[source]

We need a custom get_attributes because we aren’t using Traits to manage our changeable settings. This is unfortunate, and should be changed to something that automates this somehow.

dbfile[source]

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

class openmdao.lib.casehandlers.dbcase.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.

close()[source]

Commit and close DB connection if not using :memory:.

get_attributes(io_only=True)[source]

We need a custom get_attributes because we aren’t using Traits to manage our changeable settings. This is unfortunate, and should be changed to something that automates this somehow.

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.dbcase.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.dbcase.cmdlineXYplot()[source]

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

openmdao.lib.casehandlers.dbcase.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.dbcase.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.

dumpcase.py

class openmdao.lib.casehandlers.dumpcase.DumpCaseRecorder(out=<open file '<stdout>', mode 'w' at 0x259078>)[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.

close()[source]

Closes out unless it’s sys.stdout or sys.stderr. Note that a closed recorder will do nothing in record().

get_attributes(io_only=True)[source]

We need a custom get_attributes because we aren’t using Traits to manage our changeable settings. This is unfortunate, and should be changed to something that automates this somehow.

record(case)[source]

Dump the given Case in a “pretty” form.

filters.py

Case filters provide a means to select cases based on their index in the sequence of cases or the case data values.

class openmdao.lib.casehandlers.filters.ExprCaseFilter(expr)[source]

Bases: object

Select based on a boolean Python expression of the case data or seqno. Case data is accessed by case['name']

expr: string
Boolean expression referring to the case data or seqno.
Examples:
  • select failed cases 'case.msg'.
  • select first 3 cases: 'seqno < 3'.
  • select case with ‘param’ between 2 and 2.5: 'case["param"] > 2 and case["param"] < 2.5'.
select(seqno, case)[source]

Return True if case should be used.

seqno: int
Case sequence number.
case: Case
Case to be checked.
expr[source]

The expression to be evaluated.

class openmdao.lib.casehandlers.filters.IteratorCaseFilter(iterator)[source]

Bases: object

Select based on an iterator of case numbers.

iterator: iterator
Provides case numbers, assumed to be in increasing order.
select(seqno, case)[source]

Return True if case should be used.

seqno: int
Case sequence number.
case: Case
Case to be checked.
class openmdao.lib.casehandlers.filters.SequenceCaseFilter(indices)[source]

Bases: openmdao.lib.casehandlers.filters.IteratorCaseFilter

Select based on a sequence of case numbers.

indices: sequence(int)
Sequence of case numbers, assumed to be in increasing order.
class openmdao.lib.casehandlers.filters.SliceCaseFilter(start=0, stop=2147483647, step=1)[source]

Bases: openmdao.lib.casehandlers.filters.IteratorCaseFilter

Select based on start, stop, and step of case numbers.

start: int
Starting case number.
stop: int
Ending case number.
step: int
Step between case numbers.

listcase.py

A Case Iterator and CaseRecorder that stores the cases in a list.

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

Bases: list

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_attributes(io_only=True)[source]

We need a custom get_attributes because we aren’t using Traits to manage our changeable settings. This is unfortunate, and should be changed to something that automates this somehow.

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

Bases: object

Stores cases in a list.

close()[source]

Does nothing.

get_attributes(io_only=True)[source]

We need a custom get_attributes because we aren’t using Traits to manage our changeable settings. This is unfortunate, and should be changed to something that automates this somehow.

get_iterator()[source]

Return ListCaseIterator that uses our current list.

record(case)[source]

Store the case in our internal list.

COMPONENTS

api.py

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

Broadcaster

DeMux

ExecComp

ExecCompWithDerivatives

ExpectedImprovement

ExternalCode

MetaModel

MultiObjExpectedImprovement

Mux

ParetoFilter

broadcaster.py

class openmdao.lib.components.broadcaster.Broadcaster(names, types=None)[source]

Bases: openmdao.main.component.Component

Takes inputs and passes them directly to outputs to be broadcast out to other components.

List names

Names of the variables you want to broadcast from this component.

  • default: ‘[]’
  • iotype: ‘in’
  • copy: ‘deep’
Dict types

Name/type pairs describing the variable types of each broadcast variable; ‘default’ name is used if no other type is set explicitly.

  • default: ‘{‘default’: <class ‘openmdao.main.datatypes.float.Float’>}’
  • iotype: ‘in’
execute(*args, **kwargs)[source]

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

Slot (CaseSet) best_case

CaseSet which contains a single case representing the criteria value.

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

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

  • default: ‘’
  • iotype: ‘in’
  • vartypename: ‘Str’
Slot (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’
  • vartypename: ‘Slot’
Float EI

The expected improvement of the predicted_value.

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

The probability of improvement of the predicted_value.

  • default: ‘0.0’
  • iotype: ‘out’
  • vartypename: ‘Float’
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

Slot (CaseSet) best_cases

CaseIterator which contains only Pareto optimal cases according to criteria.

  • default: None
  • iotype: ‘in’
  • copy: ‘deep’
  • vartypename: ‘Slot’
Enum calc_switch

Switch to use either probability (PI) or expected (EI) improvement.

  • default: ‘PI’
  • iotype: ‘in’
  • values: [‘PI’, ‘EI’]
  • vartypename: ‘Enum’
Array criteria

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

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

Number of Monte Carlo Samples with which to calculate probability of improvement.

  • default: ‘1000’
  • iotype: ‘in’
Array predicted_values

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

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

The expected improvement of the next_case.

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

The probability of improvement of the next_case.

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

Calculates the expected improvement or probability of improvement of a candidate point given by a normal distribution.

get_y_star()[source]

external_code.py

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

Bases: openmdao.main.component_with_derivatives.ComponentWithDerivatives

Run an external code as a component. The component can be configured to run the code on a remote server. See execute().

Default stdin is the ‘null’ device, default stdout is the console, and default stderr is error.out.

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’
  • vartypename: ‘Bool’
List command

The command to be executed.

  • default: ‘[]’
  • copy: ‘deep’
check_files(inputs)[source]

Check that all ‘specific’ input or output external files exist. If an external file path specifies a pattern, it is not checked.

inputs: bool
If True, check inputs; otherwise outputs.
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.

  1. Existing output (but not in/out) files are removed.
  2. Checks that all external input files exist.
  3. Runs the command.
  4. Checks that all external output files exist.

If a subclass generates outputs (such as postprocessing results), then it should set attribute check_external_outputs False and call check_files() itself.

If resources have been specified, an appropriate server is allocated and the command is run on that server. Otherwise the command is run locally.

When running remotely, the following resources are set:

Key Value
job_name self.get_pathname()
remote_command self.command (first item)
args self.command (2nd through last items)
job_environment self.env_vars
input_path self.stdin
output_path self.stdout
error_path self.stderr (if != STDOUT)
join_files If self.stderr == STDOUT
wallclock_time self.timeout (if non-zero)

Note

Input files to be sent to the remote server are defined by FileMetadata entries in the external_files list with input True. Similarly, output files to be retrieved from the remote server are defined by entries with output True.

Warning

Any file not labeled with binary True will undergo newline translation if the local and remote machines have different newline representations. Newline translation will corrupt a file which is binary but hasn’t been labeled as such.

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’ or ‘resources’ by a remote client.

stop()[source]

Stop the external code.

DEV_NULL = '/dev/null'
PIPE = -1
STDOUT = -2

metamodel.py

MetaModel

MetaModel is a class which supports generalized meta modeling capabilities. It has two slots, one for surrogate model generators and a second for the model that is being approximated. The first slot, named surrogate, must always be filled before anything else is done. This slot gets filled with a dictionary that specifies which surrogate model generator should be used for which outputs. The keys of the dictionary are the variable names, and the values are the particular surrogate model generators which adhere to the ISurrogate interface. A special key, 'default', can be used to indicate a surrogate model generator to be used if no specific one is given for a particular variable. Any specified variables will override the default. OpenMDAO provides some surrogate modelers in openmdao.lib.surrogatemodels.

from openmdao.main.api import Assembly
from openmdao.lib.components.api import MetaModel
from openmdao.lib.surrogatemodels.api import KrigingSurrogate,LogisticRegression

class Simulation(Assembly):
    def configure(self):

        self.add('meta_model',MetaModel())
        #using KriginSurrogate for all outputs
        self.meta_model.surrogate = {'default':KrigingSurrogate()}

        #alternately, overiding the default for a specific variable
        self.meta_model.surrogate = {'default':LogisticRegression(),
                                     'f_xy':KrigingSurrogate()}

Once the surrogate dictionary has been specified, the model slot, called model, can be filled with a component. As soon as a component is put in the slot, MetaModel will automatically mirror the inputs and outputs of that component. In other words, MetaModel will have the same inputs and outputs as whatever component is put into the model slot.

from openmdao.main.api import Assembly
from openmdao.lib.components.api import MetaModel
from openmdao.lib.surrogatemodels.api import KrigingSurrogate
from openmdao.lib.optproblems.branin import BraninComponent

class Simulation(Assembly):
    def configure(self):

        self.add('meta_model',MetaModel())
        self.meta_model.surrogate = {'default':KrigingSurrogate()}

        #component has two inputs: x,y
        self.meta_model.model = BraninComponent()

        #meta_model now has two inputs: x,y
        self.meta_model.x = 9
        self.meta_model.y = 9

Depending on the component being approximated, you may not want to generate approximations for all the outputs. Alternatively, you may want to exclude some of the inputs from consideration when the surrogate models are generated if the inputs are going to be held constant for a given study. MetaModel provides two I/O-Traits to handle this situation: includes and excludes. Only one of these traits can be used at a time, and both inputs and outputs are specified at the same time.

If you are specifying the includes, then only the I/O-Traits in that list will be used. If you are specifying the excludes, then everything but the I/O-Traits in the list will be mirrored by MetaModel.

from openmdao.main.api import Assembly
from openmdao.lib.components.api import MetaModel
from openmdao.lib.surrogatemodels.api import KrigingSurrogate
from openmdao.lib.optproblems.branin import BraninComponent

class Simulation(Assembly):
    def configure(self):

        self.add('meta_model',MetaModel())
        self.meta_model.surrogate = {'default':KrigingSurrogate()}

        #component has two inputs: x,y
        self.meta_model.model = BraninComponent()

        #exclude the x input
        self.meta_model.excludes=['x']

or

from openmdao.main.api import Assembly
from openmdao.lib.components.api import MetaModel
from openmdao.lib.surrogatemodels.api import KrigingSurrogate
from openmdao.lib.optproblems.branin import BraninComponent

class Simulation(Assembly):

    def configure(self):

        self.add('meta_model',MetaModel())
        self.meta_model.surrogate = {'default': KrigingSurrogate()}

        #component has two inputs: x,y
        self.meta_model.model = BraninComponent()

        #include only the y input
        self.meta_model.includes=['y']

MetaModel treats inputs and outputs a little differently. All the inputs, regardless of which ones are being included/excluded, will be mirrored by a MetaModel. But if inputs are excluded, then MetaModel won’t pass down their values to the surrogate models as inputs to training cases.

When outputs are excluded, they no longer get mirrored by MetaModel. They won’t get surrogate models fit to them, and consequently, they won’t be available to the simulation from MetaModel.

Now you have set up your MetaModel with a specific surrogate model, and you have put a model into the model slot. The input and output inclusions/exclusions have been specified. The next step is to actually start training and executing the MetaModel in simulations.

MetaModel has two operating modes: training and prediction. When run in training mode, MetaModel passes its given inputs down to the model in the model slot and runs it. Then it stores the outputs from the model to use for generating a surrogate model later. When run in predict mode, MetaModel will check for any new training data and, if present, will generate a surrogate model for each model output with the data. Then it will make a prediction of the model outputs for the given inputs. A MetaModel instance must always be run in training mode before executing it in predict mode.

To put an instance of MetaModel into the training mode, you must set the train_next event trait before executing the component. This event trait automatically resets itself after the execution, so it must be set again before each training case. An event trait is just a trigger mechanism, and it will trigger its behavior regardless of the value you set it to.

from openmdao.main.api import Assembly
from openmdao.lib.components.api import MetaModel
from openmdao.lib.surrogatemodels.api import KrigingSurrogate
from openmdao.lib.optproblems.branin import BraninComponent

class Simulation(Assembly):
    def configure(self):

        self.add('meta_model',MetaModel())
        self.meta_model.surrogate = {'default':KrigingSurrogate()}

        #component has two inputs: x,y
        self.meta_model.model = BraninComponent()

        self.meta_model.train_next = True
        self.meta_model.x = 2
        self.meta_model.y = 3

        self.meta_model.execute()

In a typical iteration hierarchy, a Driver is responsible for setting the train_next event when appropriate. This is accomplished via the IHasEvents Driver sub-interface. The train_next event is added to a Driver, which will then automatically set train_next prior to each iteration of the model. A simple code snippet is presented below, while a more detailed example can be found in the single_objective_ei example under the openmdao.examples.expected_improvement package.

from openmdao.main.api import Assembly
from openmdao.lib.drivers.api import DOEdriver
from openmdao.lib.components.api import MetaModel
from openmdao.lib.surrogatemodels.api import KrigingSurrogate
from openmdao.lib.optproblems.branin import BraninComponent

class Simulation(Assembly):
    def configure(self):

        self.add('meta_model',MetaModel())
        self.meta_model.surrogate = {'default':KrigingSurrogate()}

        #component has two inputs: x,y
        self.meta_model.model = BraninComponent()

        self.add('driver',DOEdriver())
        self.driver.workflow.add('meta_model')
        self.driver.add_event('meta_model.train_next')

When the train_next event is not set, MetaModel automatically runs in predict mode. When in predict mode, the outputs provided are the result of predicted outputs from the surrogate model inside of MetaModel.

Before being able to predict the surrogate model response for any of the outputs of MetaModel, the surrogate model must be trained with the recorded training data. This will happen automatically whenever MetaModel is run in predict mode and new training data is available. This makes MetaModel more efficient, because it is not trying to retrain the model constantly when running large sets of training cases. Instead, the actual surrogate model training is only done when a prediction is needed and new training data is available.

Source Documentation for metamodel.py

Metamodel provides basic Meta Modeling capability.

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

Bases: openmdao.main.component.Component

Slot (IComponent) model

Slot for the Component or Assembly being encapsulated.

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

Records training cases

  • default: None
  • copy: ‘deep’
  • vartypename: ‘Slot’
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’
Bool report_errors

If True, metamodel will report errors reported from the component. If False, metamodel will swallow the errors but log that they happened and exclude the casefrom the training set

  • default: ‘True’
  • iotype: ‘in’
  • vartypename: ‘Bool’
Slot (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’
  • vartypename: ‘Slot’
Dict surrogate

Dictionary that 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
Dict surrogate_args

Dictionary that provides mapping between variables and arguments that should be passed to the surrogate model. Keys should match those in the surrogate dictionary. Values can be a list of ordered arguments, a dictionary of named arguments, or a two-tuple of a list and a dictionary.

  • default: ‘{}’
  • allow_none: True
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 or when includes/excludes change.

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]

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

CaseSet 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’
Slot (CaseSet) dominated_set

Resulting collection of dominated cases.

  • default: None
  • iotype: ‘out’
  • copy: ‘shallow’
  • vartypename: ‘Slot’
Slot (CaseSet) pareto_set

Resulting collection of pareto optimal cases.

  • default: None
  • iotype: ‘out’
  • copy: ‘shallow’
  • vartypename: ‘Slot’
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.

DIFFERENTIATORS

analytic.py

Differentiates a driver’s workflow using an analytic method.

class openmdao.lib.differentiators.analytic.Analytic[source]

Bases: openmdao.lib.differentiators.chain_rule.ChainRule

Differentiates a driver’s workflow using one of the analytic methods.

Enum approach

approach for assembling the problem. functional - convert all comps to functional formresidual - convert all comps to residual formhybrid - no conversion, each comps uses what it has

  • default: ‘functional’
  • iotype: ‘in’
  • values: [‘functional’, ‘residual’, ‘hybrid’]
  • vartypename: ‘Enum’
Enum mode

Choose forward or adjoint mode

  • default: ‘direct’
  • iotype: ‘in’
  • values: [‘direct’, ‘adjoint’]
  • vartypename: ‘Enum’
Bool sparse

Set to True for sparse storage of matrices.

  • default: ‘False’
  • iotype: ‘in’
  • vartypename: ‘Bool’
calc_gradient()[source]

Calculates the gradient vectors for all outputs in this Driver’s workflow.

get_derivative(output_name, wrt)[source]

Returns the derivative of output_name with respect to wrt.

output_name: string
Name of the output in the local OpenMDAO hierarchy.
wrt: string
Name of the input in the local OpenMDAO hierarchy. The derivative is with respect to this variable.
get_gradient(output_name=None)[source]

Returns the gradient of the given output with respect to all parameters.

output_name: string
Name of the output in the local OpenMDAO hierarchy.
setup()[source]

Determine problem dimension and allocate arrays. (unless sparse)

api.py

Pseudo package providing a central place to access all of the OpenMDAO differentiators in the standard library.

Analytic

ChainRule

FiniteDifference

chain_rule.py

A differentiator is a special object that can be used by a driver to calculate the first or second derivatives of a workflow. The derivatives are calculated from the parameter inputs to the objective and constraint outputs. Any driver that has been derived from the DriverUsesDerivatives base class contains a Slot called Differentiator. This slot can take a Differentiator object.

ChainRule

The ChainRule differentiator calculates the gradient of a Drivers’s workflow using forward automatic differentiation (i.e., successive application of the chainrule from the Parameters to the Objectives and Constraints.)

This differentiator is under construction. At present, it works for any workflow that contains Assemblies or Components for which derivatives have been specified for all connected components. Work is underway to include finite differencing of subsections of the model, and to support nested drivers. If your model requires any of these features, then you should use the FiniteDifference differentiator.

Source Documentation for chain_rule.py

Differentiates a driver’s workflow using the Chain Rule with Numerical Derivatives (CRND) method.

class openmdao.lib.differentiators.chain_rule.ChainRule[source]

Bases: openmdao.main.container.Container

Differentiates a driver’s workflow using the Chain Rule with Numerical Derivatives (CRND) method.

Float default_stepsize

Default finite difference step size.

  • default: ‘1e-06’
  • iotype: ‘in’
  • vartypename: ‘Float’
calc_gradient()[source]

Calculates the gradient vectors for all outputs in this Driver’s workflow.

calc_hessian(reuse_first=False)[source]

Returns the Hessian matrix for all outputs in the Driver’s workflow.

This method is not implemented yet.

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 and calls calc_gradient before calc_hessian.
get_2nd_derivative(output_name, wrt)[source]

Returns the 2nd derivative of output_name with respect to both vars in the tuple wrt.

output_name: string
Name of the output in the local OpenMDAO hierarchy.
wrt: tuple containing two strings
Names of the inputs in the local OpenMDAO hierarchy. The derivative is with respect to these 2 variables.
get_Hessian(output_name=None)[source]

Returns the Hessian matrix of the given output with respect to all parameters.

output_name: string
Name of the output in the local OpenMDAO hierarchy.
get_derivative(output_name, wrt)[source]

Returns the derivative of output_name with respect to wrt.

output_name: string
Name of the output in the local OpenMDAO hierarchy.
wrt: string
Name of the input in the local OpenMDAO hierarchy. The derivative is with respect to this variable.
get_gradient(output_name=None)[source]

Returns the gradient of the given output with respect to all parameters.

output_name: string
Name of the output in the local OpenMDAO hierarchy.
raise_exception(msg, exception_class=<type 'exceptions.Exception'>)[source]

Raise an exception.

reset_state()[source]

Local finite differences do not leave comps in a clean state. If you require one, then run this method.

setup()[source]

Sets some dimensions.

fd_helper.py

Object that can take a subsection of a model and perform finite difference on it.

class openmdao.lib.differentiators.fd_helper.FDhelper(model, comps, wrt, outs, stepsize=1e-06, order=1, form='CENTRAL')[source]

Bases: object

An object that takes a subsection of a model and performs a finite difference. The cases are run with a point distribution generator. Thus, we can take advantage of multiprocessing if it is available.

list_outs()[source]

Returns a list of variable paths that we are differencing.

list_wrt()[source]

Returns a list of variable paths that we are differencing with respect to.

run(input_dict, output_dict)[source]

Performs finite difference of our submodel with respect to wrt. Variables are intialized with init_vals.

input_dict: dict( string : value )
Dictionary of baseline values for input paramters
input_dict: dict( string : value )
Dictionary of baseline values for desired outputs

finite_difference.py

A differentiator is a special object that can be used by a driver to calculate the first or second derivatives of a workflow. The derivatives are calculated from the parameter inputs to the objective and constraint outputs. Any driver that has been derived from the DriverUsesDerivatives base class contains a Slot called Differentiator. This slot can take a Differentiator object.

FiniteDifference

The FiniteDifference differentiator provides the gradient vector and Hessian matrix of the workflow using the finite difference method. For first derivatives, you have a choice of forward, backward, or central differencing. Second derivatives are calculated using the standard three-point difference for both on-diagonal and off-diagonal terms.

The FiniteDifference differentiator also supports Finite Difference with Analytical Derivatives (FDAD), wherein a component’s analytical derivatives can be used to speed up that component under finite difference.

The FiniteDifference differentiator can be used with any optimizer that can usegradients, including the CONMIN, NEWSUMT, and SLSQP drivers. optimizer by plugging it into the differentiator socket.

from openmdao.main.api import Assembly
from openmdao.lib.drivers.api import NEWSUMTdriver
from openmdao.lib.differentiators.finite_difference import FiniteDifference
from openmdao.examples.simple.paraboloid import Paraboloid

class OptimizationConstrained(Assembly):
    """Constrained optimization of the Paraboloid."""

    def configure(self):

        # Create Paraboloid component instances
        self.add('paraboloid', Paraboloid_Derivative())

        # Create Optimizer instance
        self.add('driver', NEWSUMTdriver())

        # Driver process definition
        self.driver.workflow.add('paraboloid')

        # Differentiator
        self.driver.differentiator = FiniteDifference()
        self.driver.differentiator.form = 'central'
        self.driver.differentiator.default_stepsize = .0001

        # Objective
        self.driver.add_objective('paraboloid.f_xy')

        # Design Variables
        self.driver.add_parameter('paraboloid.x', low=-50., high=50., fd_step=.01)
        self.driver.add_parameter('paraboloid.y', low=-50., high=50.)

        # Constraints
        self.driver.add_constraint('paraboloid.x-paraboloid.y >= 15.0')

The only argument that FiniteDifference takes is the driver you are plugging into.

FiniteDifference has two additional control variables. The form parameter is used to declare which difference the first derivative will use. (The default is 'central'.) The default_stepsize parameter is used to set a default finite difference step size. Note that you can declare a separate finite difference step size for each parameter in the call to add_parameter. Here, the finite difference step size for the input 'x' to paraboloid is set to .01. If you don’t specify fd_step for a parameter, then the default step size is used.

Source Documentation for finite_difference.py

Differentiates a driver’s workflow using the Finite Difference with Analytical Derivatives (FDAD) method.

A variety of difference types are available for both first and second order.

class openmdao.lib.differentiators.finite_difference.FiniteDifference[source]

Bases: openmdao.main.container.Container

Differentiates a driver’s workflow using the Finite Difference with Analytical Derivatives (FDAD) 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’
  • vartypename: ‘Float’
Enum form

Finite difference form (central, forward, backward)

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

Calculates the gradient vectors for all outputs in this Driver’s workflow.

calc_hessian(reuse_first=False)[source]

Returns the Hessian matrix for all outputs in the 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, and calls calc_gradient before calc_hessian.
get_2nd_derivative(output_name, wrt)[source]

Returns the 2nd derivative of output_name with respect to both vars in the tuple wrt.

output_name: string
Name of the output in the local OpenMDAO hierarchy.
wrt: tuple containing two strings
Names of the inputs in the local OpenMDAO hierarchy. The derivative is with respect to these 2 variables.
get_Hessian(output_name=None)[source]

Returns the Hessian matrix of the given output with respect to all parameters.

output_name: string
Name of the output in the local OpenMDAO hierarchy.
get_derivative(output_name, wrt)[source]

Returns the derivative of output_name with respect to wrt.

output_name: string
Name of the output in the local OpenMDAO hierarchy.
wrt: string
Name of the input in the local OpenMDAO hierarchy. The derivative is with respect to this variable.
get_gradient(output_name=None)[source]

Returns the gradient of the given output with respect to all parameters.

output_name: string
Name of the output in the local OpenMDAO hierarchy.
raise_exception(msg, exception_class=<type 'exceptions.Exception'>)[source]

Raise an exception.

reset_state()[source]

Finite Difference does not leave the model in a clean state. If you require one, then run this method.

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

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

CSVFile

CentralComposite

FullFactorial

LatinHypercube

OptLatinHypercube

Uniform

central_composite.py

DOEgenerator that performs a central composite Design of Experiments. Plugs into the DOEgenerator socket on a DOEdriver.

class openmdao.lib.doegenerators.central_composite.CentralComposite(type='Face-Centered', *args, **kwargs)[source]

Bases: openmdao.main.container.Container

DOEgenerator that performs a central composite Design of Experiments. Plugs into the DOEgenerator socket on a DOEdriver.

Int num_parameters

Number of independent parameters in the DOE.

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

Type of central composite design

  • default: ‘Face-Centered’
  • iotype: ‘in’
  • values: [‘Face-Centered’, ‘Inscribed’]
  • vartypename: ‘Enum’

csvfile.py

class openmdao.lib.doegenerators.csvfile.CSVFile(doe_filename='doe_inputs.csv', *args, **kwargs)[source]

Bases: openmdao.main.container.Container

DOEgenerator that returns rows in a CSV file. Plugs into the DOEgenerator socket on a DOEdriver.

Str doe_filename

Name of CSV file.

  • default: ‘’
  • iotype: ‘in’
  • vartypename: ‘Str’
Int num_parameters

Expected number of parameters in the DOE

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

full_factorial.py

The FullFactorial DOEgenerator implements a full factorial Design of Experiments; that is, it generates a set of design points that fully span the range of the parameters at the requested resolution. It plugs into the DOEgenerator socket on a DOEdriver.

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

Bases: openmdao.main.container.Container

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

The OptLatinHypercube component implements an algorithm that produces an optimal Latin hypercube based on an evolutionary optimization of its Morris-Mitchell sampling criterion.

class openmdao.lib.doegenerators.optlh.LHC_indivudal(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.LatinHypercube(num_samples=None)[source]

Bases: openmdao.main.container.Container

IDOEgenerator which provides a Latin hypercube DOE sample set.

Int num_parameters

Number of parameters, or dimensions, for the DOE.

  • default: ‘2’
Int num_samples

Number of sample points in the DOE sample set.

  • default: ‘20’
class openmdao.lib.doegenerators.optlh.OptLatinHypercube(num_samples=None, population=None, generations=None)[source]

Bases: openmdao.main.container.Container

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’]
  • vartypename: ‘Enum’
Int num_parameters

Number of parameters, or dimensions, for the DOE.

  • default: ‘2’
Int num_samples

Number of sample points in the DOE sample set.

  • default: ‘20’
Int population

Size of the population used in the evolutionary optimization.

  • default: ‘20’
openmdao.lib.doegenerators.optlh.is_latin_hypercube(lh)[source]

Returns True if the given array is a Latin hypercube. The given array is assumed to be a numpy array.

openmdao.lib.doegenerators.optlh.rand_latin_hypercube(n, k, edges=False)[source]

Calculates a random Latin hypercube set of n points in k dimensions within [0,1]^k hypercube.

n: int
Desired number of points.
k: int
Number of design variables (dimensions).
edges: bool (optional)
If Edges=True, the extreme bins will have their centres on the edges of the domain; otherwise the bins will be entirely contained within the domain (default setting).

Returns an n by k numpy array.

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: openmdao.main.container.Container

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

broydensolver.py

BroydenSolver

The BroydenSolver can be used to solve for the set of inputs (independents) that are needed to to make a model satisfy an equation (the dependent equation) that is a function of model outputs. BroydenSolver is based on the quasi-Newton-Raphson algorithms found in SciPy’s nonlinear solver library. As the name implies, a Broyden update is used to approximate the Jacobian matrix. In fact, no Jacobian is evaluated with these algorithms, so they are quicker than a full Newton solver, but they may not be suitable for all problems.

To see how to use the BroydenSolver, consider a problem where we’d like to solve for the intersection of a line and a parabola. We can implement this as a single component.

from openmdao.lib.datatypes.api import Float
from openmdao.main.api import Component


class MIMOSystem(Component):
    """ Two equations, two unknowns """

    x = Float(10.0, iotype="in", doc="Input 1")
    y = Float(10.0, iotype="in", doc="Input 2")

    f_xy = Float(0.0, iotype="out", doc="Output 1")
    g_xy = Float(0.0, iotype="out", doc="Output 2")

    def execute(self):
        """ Evaluate:
        f_xy = 2.0*x**2 - y + 2.0
        g_xy = 2.0*x - y - 4.0
        """

        x = self.x
        y = self.y

        self.f_xy = 2.0*x**2 - y + 2.0
        self.g_xy = 2.0*x - y + 4.0

Notice that this is a two-input problem – the variables are x and y. There are also two equations that need to be satisfied: the equation for the line and the equation for the parabola. There are actually two solutions to this set of equations. The solver will return the first one that it finds. You can usually find other solutions by starting the solution from different initial points. We start at (10, 10), as designated by the default values for the variables x and y.

Next, we build a model that uses the BroydenSolver to find a root for the equations defined in MIMOSystem.

from openmdao.lib.drivers.api import BroydenSolver
from openmdao.main.api import Assembly

class SolutionAssembly(Assembly):
    """ Solves for the root of MIMOSystem. """

    def configure(self):

        self.add('driver', BroydenSolver())
        self.add('problem', MIMOSystem())

        self.driver.workflow.add('problem')

        self.driver.add_parameter('problem.x', low=-1.0e99, high=1.0e99)
        self.driver.add_parameter('problem.y', low=-1.0e99, high=1.0e99)

        self.driver.add_constraint('problem.f_xy = 0.0')
        self.driver.add_constraint('problem.g_xy = 0.0')
        self.driver.itmax = 20
        self.driver.alpha = .4
        self.driver.tol = .000000001

The parameters are the independent variables that the solver is allowed to vary. The method add_parameter is used to define these. Broyden does not utilize the low and high arguments, so they are set to some large arbitrary negative and positive values.

The equations that we want to satisfy are added as equality constraints using the add_constraint method. We want to find x and y that satisfy f_xy=0 and g_xy=0, so these two equations are added to the solver.

Both the add_parameter and add_constraint methods are presented in more detail in MDAO Architectures.

The resulting solution should yield:

>>> top = SolutionAssembly()
>>> top.run()
>>> print top.problem.x, top.problem.y
1.61... 7.23...

Five parameters control the solution process in the BroydenSolver.

algorithm
SciPy’s nonlinear package contained several algorithms for solving a set of nonlinear equations. Three of these methods were considered by their developers to be of good quality, so those three were implemented as part of the BroydenSolver. The variable algorithm is an Enum where the following values represent the algorithms that follow.
  • broyden2: Broyden’s second method – the same as broyden1 but updates the inverse Jacobian directly

  • broyden3: Broyden’s third 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 default value for algorithm is "broyden2".

    self.driver.algorithm = "broyden2"
    
itmax

This parameter specifies the maximum number of iterations before BroydenSolver terminates. The default value is 10.

self.driver.itmax = 10
alpha

This parameter specifies the mixing coefficient for the algorithm. The mixing coefficient is a linear scale factor applied to the update of the parameters, so increasing it can lead to quicker convergence but can also lead to instability. The default value is 0.4. If you use the excitingmixing algorithm, you should try a lower value, such as 0.1.

self.driver.alpha = 0.1
tol

Convergence tolerance for the solution. Iteration ends when the constraint equation is satisfied within this tolerance. The default value is 0.00001.

self.driver.tol = 0.00001
alphamax

This parameter is only used for the excitingmixing algorithm where the mixing coefficient is adaptively adjusted. It specifies the maximum allowable mixing coefficient for adaptation. The default value is 1.0.

self.driver.alphamax = 1.0

Source Documentation for broyensolver.py

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

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’]
  • vartypename: ‘Enum’
Float alpha

Mixing Coefficient.

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

Maximum Mixing Coefficient (only used with excitingmixing.)

  • default: ‘1.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
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’
  • vartypename: ‘Float’
add_constraint(expr_string, scaler=1.0, adder=0.0, name=None, scope=None)

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).
name: str (optional)
Name to be used to refer to the constraint rather than its expression string.
scope: object (optional)
The object to be used as the scope when evaluating the expression.
add_existing_constraint(cnst, name=None)

Adds an existing Constraint object to the driver.

cnst: Constraint object

name: str (optional)
Name to be used to refer to the constraint rather than its expression string.
add_parameter(target, low=None, high=None, scaler=None, adder=None, start=None, fd_step=None, name=None, scope=None)

Adds a parameter or group of parameters to the driver.

target: string or iter of strings or Parameter
What the driver should vary during execution. A target is an expression that can reside on the left-hand side of an assignment statement, so typically it will be the name of a variable or possibly a subscript expression indicating an entry within an array variable, e.g., x[3]. If an iterator of targets is given, then the driver will set all targets given to the same value whenever it varies this parameter during execution. If a Parameter instance is given, then that instance is copied into the driver with any other arguments specified, overiding the values in the given parameter.
low: float (optional)
Minimum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
high: float (optional)
Maximum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
scaler: float (optional)
Value to multiply the possibly offset parameter value by.
adder: float (optional)
Value to add to parameter prior to possible scaling.
start: any (optional)
Value to set into the target or targets of a parameter before starting any executions. If not given, analysis will start with whatever values are in the target or targets at that time.
fd_step: float (optional)
Step-size to use for finite difference calculation. If no value is given, the differentitator will use its own default.
name: str (optional)
Name used to refer to the parameter in place of the name of the variable referred to in the parameter string. This is sometimes useful if, for example, multiple entries in the same array variable are declared as parameters.
scope: object (optional)
The object to be used as the scope when evaluating the expression.

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.

allows_constraint_types(types)

Returns True if types is [‘eq’].

clear_constraints()

Removes all constraints.

clear_parameters()

Removes all parameters.

copy_constraints()

Returns a copy of our constraints dict.

eval_eq_constraints(scope=None)

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.

init_parameters()

Sets all parameters to their start value, if a start value is given

list_constraints()

Return a list of strings containing constraint expressions.

list_param_targets()

Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter and ParameterGroup objects since ParameterGroups have multiple targets.

remove_constraint(key)

Removes the constraint with the given string.

remove_parameter(name)

Removes the parameter with the given name.

set_parameter_by_name(name, value, case=None, scope=None)

Sets a single parameter by its name attribute.

name: str
Name of the parameter. This is either the name alias given when the parameter was added, or the variable path of the parameter’s target if no name was given.
value: object (typically a float)
Value of the parameter to be set.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.
set_parameters(values, case=None, scope=None)

Pushes the values in the iterator ‘values’ into the corresponding variables in the model. If the ‘case’ arg is supplied, the values will be set into the case and not into the model.

values: iterator
Iterator of input values with an order defined to match the order of parameters returned by the get_parameters method. ‘values’ must support the len() function.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.

caseiterdriver.py

CaseIteratorDriver

The CaseIteratorDriver provides the capability to evaluate one or more cases on a workflow. These evaluations can be performed either sequentially (the default) or concurrently (subject to computational resources available).

During sequential execution, each case is evaluated by applying the inputs to the workflow, executing the workflow, retrieving the outputs, and recording the evaluated case.

For concurrent execution, a modified form of the assembly is packaged into an egg, which is a file which can be sent to a remote server for execution. The modifications consist of replacing the assembly’s driver with a default driver, and setting that driver’s workflow to the CaseIteratorDriver’s workflow. After the egg is created, the ResourceAllocationManager (RAM) is used to allocate servers to evaluate the cases concurrently. Servers are selected based on egg requirements (Python version, installed packages, etc.).

Ordinarily, the model (modified form of the assembly) is loaded into a server prior to each evaluation. Since loading takes some time, this reloading process can be skipped if reload_model is set False. Some models require reloading (typically due to limitations of certain components used), so always reloading is the safe default. Note that during sequential execution no reloading takes place.

Source Documentation for 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’)
  • vartypename: ‘Enum’
Dict extra_resources

Extra resource requirements (unusual).

  • default: ‘{}’
  • iotype: ‘in’
Bool ignore_egg_requirements

If True, no distribution or orphan requirements will be included in the generated egg.

  • default: ‘False’
  • iotype: ‘in’
  • vartypename: ‘Bool’
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’
  • vartypename: ‘Bool’
Bool sequential

If True, evaluate cases sequentially.

  • default: ‘True’
  • iotype: ‘in’
  • vartypename: ‘Bool’
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.

Slot (ICaseFilter) filter

Filter used to select cases to evaluate.

  • default: None
  • iotype: ‘in’
  • copy: ‘deep’
  • vartypename: ‘Slot’
Slot (ICaseIterator) iterator

Iterator supplying Cases to evaluate.

  • default: None
  • iotype: ‘in’
  • copy: ‘deep’
  • vartypename: ‘Slot’
Slot (ICaseIterator) evaluated

Iterator supplying evaluated Cases.

  • default: None
  • iotype: ‘out’
  • copy: ‘deep’
  • vartypename: ‘Slot’
execute()[source]

Evaluate cases from iterator and place in evaluated.

get_case_iterator()[source]

Returns a new iterator over the Case set.

cobyladriver.py

cobyladriver.py - Contains a driver that wraps the cobyla optimizer as used in pyOpt:

Minimize a function using the Constrained Optimization BY Linear Approximation (COBYLA) method

COBYLA is gradient-free and can handle inequality constraints.

class openmdao.lib.drivers.cobyladriver.COBYLAdriver(*args, **kwargs)[source]

Bases: openmdao.main.driver.Driver

Minimize a function using the Constrained Optimization BY Linear Approximation (COBYLA) method.

COBYLA is gradient-free and can handle inequality constraints.

Note: constraints should be added using the OpenMDAO convention (positive = violated)

Int iout

Fortran output unit. Leave this at 6 for STDOUT

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

Controls the frequency of output: 0 (no output),1,2,3

  • default: ‘1’
  • iotype: ‘in’
  • values: [0, 1, 2, 3]
  • vartypename: ‘Enum’
Int maxfun

Maximum number of function evaluations.

  • default: ‘1000’
  • iotype: ‘in’
Str output_filename

Name of output file (if iout not 6).

  • default: ‘cobyla.out’
  • iotype: ‘in’
  • vartypename: ‘Str’
Float rhobeg

Reasonable initial changes to the variables.

  • default: ‘1.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float rhoend

Final accuracy in the optimization (not precisely guaranteed).

  • default: ‘0.0001’
  • iotype: ‘in’
  • vartypename: ‘Float’
Int error_code

Error code returned from COBYLA.

  • default: ‘0’
  • iotype: ‘out’
add_constraint(expr_string, scaler=1.0, adder=0.0, name=None, scope=None)

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).
name: str (optional)
Name to be used to refer to the constraint rather than its expression string.
scope: object (optional)
The object to be used as the scope when evaluating the expression.
add_existing_constraint(cnst, name=None)

Adds an existing Constraint object to the driver.

cnst: Constraint object

name: str (optional)
Name to be used to refer to the constraint rather than its expression string.
add_objective(expr, name=None, scope=None)

Adds an objective to the driver.

expr: string
String containing the objective expression.
name: string (optional)
Name to be used to refer to the objective in place of the expression string.
scope: object (optional)
The object to be used as the scope when evaluating the expression.
add_objectives(obj_iter, scope=None)

Takes an iterator of objective strings and creates objectives for them in the driver.

add_parameter(target, low=None, high=None, scaler=None, adder=None, start=None, fd_step=None, name=None, scope=None)

Adds a parameter or group of parameters to the driver.

target: string or iter of strings or Parameter
What the driver should vary during execution. A target is an expression that can reside on the left-hand side of an assignment statement, so typically it will be the name of a variable or possibly a subscript expression indicating an entry within an array variable, e.g., x[3]. If an iterator of targets is given, then the driver will set all targets given to the same value whenever it varies this parameter during execution. If a Parameter instance is given, then that instance is copied into the driver with any other arguments specified, overiding the values in the given parameter.
low: float (optional)
Minimum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
high: float (optional)
Maximum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
scaler: float (optional)
Value to multiply the possibly offset parameter value by.
adder: float (optional)
Value to add to parameter prior to possible scaling.
start: any (optional)
Value to set into the target or targets of a parameter before starting any executions. If not given, analysis will start with whatever values are in the target or targets at that time.
fd_step: float (optional)
Step-size to use for finite difference calculation. If no value is given, the differentitator will use its own default.
name: str (optional)
Name used to refer to the parameter in place of the name of the variable referred to in the parameter string. This is sometimes useful if, for example, multiple entries in the same array variable are declared as parameters.
scope: object (optional)
The object to be used as the scope when evaluating the expression.

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.

allows_constraint_types(typ)

Returns True if types is [‘ineq’].

clear_constraints()

Removes all constraints.

clear_objectives()

Removes all objectives.

clear_parameters()

Removes all parameters.

copy_constraints()

Returns a copy of our constraints dict.

eval_ineq_constraints(scope=None)

Returns a list of constraint values

eval_objective()

Returns a list of values of the evaluated objectives.

eval_objectives()

Returns a list of values of the evaluated objectives.

get_ineq_constraints()

Returns an ordered dict of inequality constraint objects.

get_objectives()

Returns an OrderedDict of objective expressions.

get_parameters()

Returns an ordered dict of parameter objects.

init_parameters()

Sets all parameters to their start value, if a start value is given

list_constraints()

Return a list of strings containing constraint expressions.

list_param_targets()

Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter and ParameterGroup objects since ParameterGroups have multiple targets.

remove_constraint(key)

Removes the constraint with the given string.

remove_objective(expr)

Removes the specified objective expression. Spaces within the expression are ignored.

remove_parameter(name)

Removes the parameter with the given name.

run_iteration()[source]

Note: cobyla controls the looping.

set_parameter_by_name(name, value, case=None, scope=None)

Sets a single parameter by its name attribute.

name: str
Name of the parameter. This is either the name alias given when the parameter was added, or the variable path of the parameter’s target if no name was given.
value: object (typically a float)
Value of the parameter to be set.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.
set_parameters(values, case=None, scope=None)

Pushes the values in the iterator ‘values’ into the corresponding variables in the model. If the ‘case’ arg is supplied, the values will be set into the case and not into the model.

values: iterator
Iterator of input values with an order defined to match the order of parameters returned by the get_parameters method. ‘values’ must support the len() function.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.
start_iteration()[source]

Perform initial setup before iteration loop begins.

conmindriver.py

CONMINDriver

CONMIN is a Fortran program written as a subroutine to solve linear or nonlinear constrained optimization problems. The basic optimization algorithm is the Method of Feasible Directions. If analytic gradients of the objective or constraint functions are not available (i.e., if a Differentiator is not plugged into the differentiator socket), then the gradients are calculated by CONMIN’s internal finite difference code. While the program is intended primarily for efficient solution of constrained problems, unconstrained function minimization problems may also be solved. The conjugate direction method of Fletcher and Reeves is used for this purpose.

More information on CONMIN can be found in the CONMIN User’s Manual.

CONMIN has been included in the OpenMDAO standard library to provide users with a basic gradient-based optimization algorithm.

Basic Interface

The CONMIN code contains a number of different parameters and switches that are useful for controlling the optimization process. These can be subdivided into those parameters that will be used in a typical optimization problem and those that are more likely to be used by an expert user.

For the simplest possible unconstrained optimization problem, CONMIN just needs an objective function and one or more decision variables (parameters.) The basic interface conforms to OpenMDAO’s driver API.

The OpenMDAO CONMIN driver can be imported from openmdao.lib.drivers.api.

from openmdao.lib.drivers.api import CONMINdriver

Typically, CONMIN will be used as a driver in the top level assembly, though it also can be used in a subassembly as part of a nested driver scheme. Using the OpenMDAO script interface, a simple optimization problem can be set up as follows:

from openmdao.main.api import Assembly
from openmdao.examples.enginedesign.vehicle import Vehicle
from openmdao.lib.drivers.api import CONMINdriver

class EngineOptimization(Assembly):
    """ Top level assembly for optimizing a vehicle. """

    def configure(self):

        # Create CONMIN Optimizer instance
        self.add('driver', CONMINdriver())

        # Create Vehicle instance
        self.add('vehicle', Vehicle())

        # add Vehicle to optimizer workflow
        self.driver.workflow.add('vehicle')

        # CONMIN Flags
        self.driver.iprint = 0
        self.driver.itmax = 30

        # CONMIN Objective
        self.driver.add_objective('vehicle.fuel_burn')

        # CONMIN Design Variables
        self.driver.add_parameter('vehicle.spark_angle', low=-50. , high=10.)
        self.driver.add_parameter('vehicle.bore', low=65. , high=100.)

This first section of code defines an assembly called EngineOptimization. This assembly contains a DrivingSim component and a CONMINdriver, both of which are created and added inside the __init__ function with add. The DrivingSim component is also added to the driver’s workflow. The objective function, design variables, constraints, and any CONMIN parameters are also assigned in the __init__ function.

Controlling the Optimization

It is often necessary to control the convergence criteria for an optimization. The CONMIN driver allows control over both the number of iterations before termination as well as the convergence tolerance (both absolute and relative).

The maximum number of iterations is specified by setting the itmax parameter. The default value is 10.

self.driver.itmax = 30

The convergence tolerance is controlled with dabfun and delfun. Dabfun is the absolute change in the objective function to indicate convergence (i.e., if the objective function changes by less than dabfun, then the problem is converged). Similarly, delfun is the relative change of the objective function with respect to the value at the previous step. Note that delfun has a hard-wired minimum of 1e-10 in the Fortran code, and dabfun has a minimum of 0.0001.

self.driver.dabfun = .001
self.driver.delfun = .1

All of these convergence checks are always active during optimization. The tests are performed in the following sequence:

  1. Check number of iterations
  2. Check absolute change in objective
  3. Check relative change in objective
  4. Reduce constraint thickness for slow convergence

The number of successive iterations that the convergence tolerance should be checked before terminating the loop can also be specified with the itrm parameter, whose default value is 3.

self.driver.itrm = 3

CONMIN can calculate the gradient of both the objective functions and of the constraints using a finite difference approximation. This is the default behavior if no Differentiator is plugged into the differentiator socket. Two parameters control the step size used for numerically estimating the local gradient: fdch and fdchm. The fdchm parameter is the minimum absolute step size that the finite difference will use, and fdch is the step size relative to the design variable.

self.driver.fdch = .0001
self.driver.fdchm = .0001

Note

The default values of fdch and fdchm are set to 0.01. This may be too large for some problems and will manifest itself by converging to a value that is not the minimum. It is important to evaluate the scale of the objective function around the optimum so that these can be chosen well.

You can also replace CONMIN’s finite difference with OpenMDAO’s built-in capability by inserting a differentiator into the Differentiator slot in the driver.

For certain problems, it is desirable to scale the inputs. Several scaling options are available, as summarized here:

Value Result
nscal < 0 User-defined scaling with the vector in scal
nscal = 0 No scaling of the design variables
nscal > 0 Scale the design variables every NSCAL iteration. Please see the CONMIN User’s Manual for additional notes about using this option.

If your problem uses linear constraints, you can improve the efficiency of the optimization process by designating those that are linear functions of the design variables as follows:

map(self.driver.add_constraint, ['vehicle.stroke < vehicle.bore',
                           'vehicle.stroke * vehicle.bore > 1.0'])
self.driver.cons_is_linear = [1, 0]

Here, the first constraint is linear, and the second constraint is nonlinear. If cons_is_linear is not specified, then all the constraints are assumed to be nonlinear. Note that the original CONMIN parameter for this is ISC. If your constraint includes some framework output in the equation, then it is probably not a linear function of the design variables.

Finally, the iprint parameter can be used to display diagnostic messages inside of CONMIN. These messages are currently sent to the standard output.

self.driver.iprint = 0

Higher positive values of iprint turn on the display of more levels of output, as summarized below. To make it easier to swap drivers, and iprint of -1 also suppresses all output.

Value Result
iprint = 0 All output is suppressed
iprint = 1 Print initial and final function information
iprint = 2 Debug level 1: All of the above plus control parameters
iprint = 3 Debug level 2: All of the above plus all constraint values, number of active/violated constraints, direction vectors, move parameters, and miscellaneous information
iprint = 4 Complete debug: All of the above plus objective function gradients, active and violated constraint gradients, and miscellaneous information
iprint = 5 All of above plus each proposed design vector, objective and constraints during the one-dimensional search
iprint = 101 All of above plus a dump of the arguments passed to subroutine CONMIN

Advanced Options

The following options exercise some of the more advanced capabilities of CONMIN. The details given here briefly summarize the effects of these parameters; more information is available in the CONMIN User’s Manual.

icndir
Conjugate direction restart parameter. For an unconstrained problem (no side constraints either), Fletcher-Reeves conjugate direction method will be restarted with the steepest descent direction every ICNDIR iterations. If ICNDIR = 1, only the steepest descent will be used. Default value is the number of design variables + 1.
Constraint Thickness
CONMIN gives four parameters for controlling the thickness of constraints – ct, ctmin, ctl, and ctlmin. Using these parameters essentially puts a tolerance around a constraint surface. Note that ct is used for general constraints, and ctl is used only for linear constraints. A wide initial value of the constraint thickness is desirable for highly nonlinear problems so that when a constraint becomes active, it tends to remain active, thus reducing the zigzagging problem. The values of ct and ctl adapt as the problem converges, so the minima can be set with ctl and ctlmin.
theta
Mean value of the push-off factor in the method of feasible directions. A larger value of theta is desirable if the constraints are known to be highly nonlinear, and a smaller value may be used if all constraints are known to be nearly linear. The actual value of the push-off factor used in the program is a quadratic function of each constraint (G(J)), varying from 0.0 for G(J) = ct to 4.0*theta for G(J) = ABS(ct). A value of theta = 0.0 is used in the program for constraints which are identified by the user to be strictly linear. Theta is called a push-off factor because it pushes the design away from the active constraints into the feasible region. The default value is usually adequate. This is used only for constrained problems.
phi
Participation coefficient, used if a design is infeasible (i.e., one or more violated constraints). Phi is a measure of how hard the design will be “pushed” towards the feasible region and is, in effect, a penalty parameter. If in a given problem, a feasible solution cannot be obtained with the default value, phi should be increased, and the problem run again. If a feasible solution cannot be obtained with phi = 100, it is probable that no feasible solution exists. The default value of 5.0 is usually adequate. Phi is used only for constrained problems.
linobj
Set this to 1 if the objective function is known to be linear.

Source Documentation for conmindriver.py

conmindriver.py - Driver for the CONMIN optimizer.

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 function 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(*args, **kwargs)[source]

Bases: openmdao.main.driver_uses_derivatives.DriverUsesDerivatives

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’
  • vartypename: ‘Float’
Float ctl

Constraint thickness parameter for linear and side constraints.

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

Minimum absolute value of ctl used in optimization.

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

Minimum absolute value of ct used in optimization.

  • default: ‘0.004’
  • iotype: ‘in’
  • vartypename: ‘Float’
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.0
Float fdch

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

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

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

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

Conjugate gradient restart. parameter.

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

Print information during CONMIN solution. Higher values are more verbose. 0 suppresses all output.

  • default: ‘0’
  • iotype: ‘in’
  • values: [0, 1, 2, 3, 4, 5, 101]
  • vartypename: ‘Enum’
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’
  • vartypename: ‘Bool’
Float phi

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

  • default: ‘5.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float theta

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

  • default: ‘1.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
add_constraint(expr_string, scaler=1.0, adder=0.0, name=None, scope=None)

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).
name: str (optional)
Name to be used to refer to the constraint rather than its expression string.
scope: object (optional)
The object to be used as the scope when evaluating the expression.
add_existing_constraint(cnst, name=None)

Adds an existing Constraint object to the driver.

cnst: Constraint object

name: str (optional)
Name to be used to refer to the constraint rather than its expression string.
add_objective(expr, name=None, scope=None)

Adds an objective to the driver.

expr: string
String containing the objective expression.
name: string (optional)
Name to be used to refer to the objective in place of the expression string.
scope: object (optional)
The object to be used as the scope when evaluating the expression.
add_objectives(obj_iter, scope=None)

Takes an iterator of objective strings and creates objectives for them in the driver.

add_parameter(target, low=None, high=None, scaler=None, adder=None, start=None, fd_step=None, name=None, scope=None)

Adds a parameter or group of parameters to the driver.

target: string or iter of strings or Parameter
What the driver should vary during execution. A target is an expression that can reside on the left-hand side of an assignment statement, so typically it will be the name of a variable or possibly a subscript expression indicating an entry within an array variable, e.g., x[3]. If an iterator of targets is given, then the driver will set all targets given to the same value whenever it varies this parameter during execution. If a Parameter instance is given, then that instance is copied into the driver with any other arguments specified, overiding the values in the given parameter.
low: float (optional)
Minimum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
high: float (optional)
Maximum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
scaler: float (optional)
Value to multiply the possibly offset parameter value by.
adder: float (optional)
Value to add to parameter prior to possible scaling.
start: any (optional)
Value to set into the target or targets of a parameter before starting any executions. If not given, analysis will start with whatever values are in the target or targets at that time.
fd_step: float (optional)
Step-size to use for finite difference calculation. If no value is given, the differentitator will use its own default.
name: str (optional)
Name used to refer to the parameter in place of the name of the variable referred to in the parameter string. This is sometimes useful if, for example, multiple entries in the same array variable are declared as parameters.
scope: object (optional)
The object to be used as the scope when evaluating the expression.

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.

allows_constraint_types(typ)

Returns True if types is [‘ineq’].

clear_constraints()

Removes all constraints.

clear_objectives()

Removes all objectives.

clear_parameters()

Removes all parameters.

continue_iteration()[source]

Returns True if iteration should continue.

copy_constraints()

Returns a copy of our constraints dict.

eval_ineq_constraints(scope=None)

Returns a list of constraint values

eval_objective()

Returns a list of values of the evaluated objectives.

eval_objectives()

Returns a list of values of the evaluated objectives.

get_ineq_constraints()

Returns an ordered dict of inequality constraint objects.

get_objectives()

Returns an OrderedDict of objective expressions.

get_parameters()

Returns an ordered dict of parameter objects.

init_parameters()

Sets all parameters to their start value, if a start value is given

list_constraints()

Return a list of strings containing constraint expressions.

list_param_targets()

Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter and ParameterGroup objects since ParameterGroups have multiple targets.

post_iteration()[source]

Checks CONMIN’s return status and writes out cases.

pre_iteration()[source]

Checks for RunStopped.

remove_constraint(key)

Removes the constraint with the given string.

remove_objective(expr)

Removes the specified objective expression. Spaces within the expression are ignored.

remove_parameter(name)

Removes the parameter with the given name.

run_iteration()[source]

The CONMIN driver iteration.

set_parameter_by_name(name, value, case=None, scope=None)

Sets a single parameter by its name attribute.

name: str
Name of the parameter. This is either the name alias given when the parameter was added, or the variable path of the parameter’s target if no name was given.
value: object (typically a float)
Value of the parameter to be set.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.
set_parameters(values, case=None, scope=None)

Pushes the values in the iterator ‘values’ into the corresponding variables in the model. If the ‘case’ arg is supplied, the values will be set into the case and not into the model.

values: iterator
Iterator of input values with an order defined to match the order of parameters returned by the get_parameters method. ‘values’ must support the len() function.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.
start_iteration()[source]

Perform initial setup before iteration loop begins.

distributioncasedriver.py

distributioncasedriver.py – Driver that executes
cases for distributions of points in the neighborhood of a given point.
class openmdao.lib.drivers.distributioncasedriver.DistributionCaseDriver(*args, **kwargs)[source]

Bases: openmdao.lib.drivers.caseiterdriver.CaseIterDriverBase

Driver for evaluating models at point distributions.

List case_outputs

A list of outputs to be saved with each case.

  • default: ‘[]’
  • iotype: ‘in’
  • copy: ‘deep’
Slot (IDistributionGenerator) distribution_generator

Iterator supplying values of point distribitions.

  • default: None
  • iotype: ‘in’
  • copy: ‘deep’
  • required: True
  • vartypename: ‘Slot’
add_parameter(target, low=None, high=None, scaler=None, adder=None, start=None, fd_step=None, name=None, scope=None)

Adds a parameter or group of parameters to the driver.

target: string or iter of strings or Parameter
What the driver should vary during execution. A target is an expression that can reside on the left-hand side of an assignment statement, so typically it will be the name of a variable or possibly a subscript expression indicating an entry within an array variable, e.g., x[3]. If an iterator of targets is given, then the driver will set all targets given to the same value whenever it varies this parameter during execution. If a Parameter instance is given, then that instance is copied into the driver with any other arguments specified, overiding the values in the given parameter.
low: float (optional)
Minimum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
high: float (optional)
Maximum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
scaler: float (optional)
Value to multiply the possibly offset parameter value by.
adder: float (optional)
Value to add to parameter prior to possible scaling.
start: any (optional)
Value to set into the target or targets of a parameter before starting any executions. If not given, analysis will start with whatever values are in the target or targets at that time.
fd_step: float (optional)
Step-size to use for finite difference calculation. If no value is given, the differentitator will use its own default.
name: str (optional)
Name used to refer to the parameter in place of the name of the variable referred to in the parameter string. This is sometimes useful if, for example, multiple entries in the same array variable are declared as parameters.
scope: object (optional)
The object to be used as the scope when evaluating the expression.

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.

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.

init_parameters()

Sets all parameters to their start value, if a start value is given

list_param_targets()

Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter and ParameterGroup objects since ParameterGroups have multiple targets.

remove_parameter(name)

Removes the parameter with the given name.

set_parameter_by_name(name, value, case=None, scope=None)

Sets a single parameter by its name attribute.

name: str
Name of the parameter. This is either the name alias given when the parameter was added, or the variable path of the parameter’s target if no name was given.
value: object (typically a float)
Value of the parameter to be set.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.
set_parameters(values, case=None, scope=None)

Pushes the values in the iterator ‘values’ into the corresponding variables in the model. If the ‘case’ arg is supplied, the values will be set into the case and not into the model.

values: iterator
Iterator of input values with an order defined to match the order of parameters returned by the get_parameters method. ‘values’ must support the len() function.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.
class openmdao.lib.drivers.distributioncasedriver.FiniteDifferenceGenerator(driver)[source]

Bases: openmdao.main.container.Container

Generate the input cases for finite differences.

Enum form

Form of finite difference used

  • default: ‘CENTRAL’
  • values: [‘CENTRAL’, ‘FORWARD’, ‘BACKWARD’]
  • vartypename: ‘Enum’
Int num_parameters

Number of parameters, or dimensions

  • default: ‘2’
Int order

Order of the finite differences

  • default: ‘1’
Bool skip_baseline

Set to True to skip running the baseline case.

  • default: ‘False’
  • vartypename: ‘Bool’

doedriver.py

DOEdriver

The DOEdriver provides the capability to execute a DOE on a workflow. This Driver supports the IHasParameters interface. At execution time, the driver will use the list of parameters added to it by the user to create a specific DOE and then iteratively execute the DOE cases on the workflow.

Users can pick from any of the DOEgenerators provided in the standard library or provide their own custom instance of a DOEgenerator. A DOEgenerator must be plugged into the DOEgenerator socket on the DOEdriver in order to operate.

from openmdao.main.api import Assembly
from openmdao.lib.drivers.api import DOEdriver
from openmdao.lib.doegenerators.api import FullFactorial

from openmdao.lib.optproblems.branin import BraninComponent

class Analysis(Assembly):
    def configure(self):

        self.add('branin', BraninComponent())
        self.add('driver', DOEdriver())
        self.driver.workflow.add('branin')

        self.driver.add_parameter('branin.x',low=-5.,high=10.)
        self.driver.add_parameter('branin.y',low=0.,high=15.)

        #use a full factorial DOE with 2 variables, and 3 levels
        #   for each variable
        self.driver.DOEgenerator = FullFactorial(num_levels=3)

The min and max metadata of the parameters are used to denote the range for each variable over which the DOE will span.

By default, the normalized parameter values are written to a CSV file in the driver’s execution directory, with a name of <driver-name>.csv. This can be used later to rerun all of the cases by using a CSVFile DOE generator. You can also select which cases should be run by filling the case_filter slot.

Source Documentation for doedriver.py

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

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

Bases: openmdao.lib.drivers.caseiterdriver.CaseIterDriverBase

Driver for Design of Experiments.

Slot (IDOEgenerator) DOEgenerator

Iterator supplying normalized DOE values.

  • default: None
  • iotype: ‘in’
  • copy: ‘deep’
  • required: True
  • vartypename: ‘Slot’
Slot (ICaseFilter) case_filter

Selects cases to be run.

  • default: None
  • iotype: ‘in’
  • copy: ‘deep’
  • vartypename: ‘Slot’
List case_outputs

A list of outputs to be saved with each case.

  • default: ‘[]’
  • iotype: ‘in’
  • copy: ‘deep’
Str doe_filename

Name of CSV file to record to (default is <driver-name>.csv)

  • default: ‘’
  • iotype: ‘in’
  • vartypename: ‘Str’
Bool record_doe

Record normalized DOE values to CSV file.

  • default: ‘True’
  • iotype: ‘in’
  • vartypename: ‘Bool’
add_parameter(target, low=None, high=None, scaler=None, adder=None, start=None, fd_step=None, name=None, scope=None)

Adds a parameter or group of parameters to the driver.

target: string or iter of strings or Parameter
What the driver should vary during execution. A target is an expression that can reside on the left-hand side of an assignment statement, so typically it will be the name of a variable or possibly a subscript expression indicating an entry within an array variable, e.g., x[3]. If an iterator of targets is given, then the driver will set all targets given to the same value whenever it varies this parameter during execution. If a Parameter instance is given, then that instance is copied into the driver with any other arguments specified, overiding the values in the given parameter.
low: float (optional)
Minimum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
high: float (optional)
Maximum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
scaler: float (optional)
Value to multiply the possibly offset parameter value by.
adder: float (optional)
Value to add to parameter prior to possible scaling.
start: any (optional)
Value to set into the target or targets of a parameter before starting any executions. If not given, analysis will start with whatever values are in the target or targets at that time.
fd_step: float (optional)
Step-size to use for finite difference calculation. If no value is given, the differentitator will use its own default.
name: str (optional)
Name used to refer to the parameter in place of the name of the variable referred to in the parameter string. This is sometimes useful if, for example, multiple entries in the same array variable are declared as parameters.
scope: object (optional)
The object to be used as the scope when evaluating the expression.

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.

clear_parameters()

Removes all parameters.

execute()[source]

Generate and evaluate cases.

get_case_iterator()[source]

Returns a new iterator over the Case set.

get_parameters()

Returns an ordered dict of parameter objects.

init_parameters()

Sets all parameters to their start value, if a start value is given

list_param_targets()

Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter and ParameterGroup objects since ParameterGroups have multiple targets.

remove_parameter(name)

Removes the parameter with the given name.

set_parameter_by_name(name, value, case=None, scope=None)

Sets a single parameter by its name attribute.

name: str
Name of the parameter. This is either the name alias given when the parameter was added, or the variable path of the parameter’s target if no name was given.
value: object (typically a float)
Value of the parameter to be set.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.
set_parameters(values, case=None, scope=None)

Pushes the values in the iterator ‘values’ into the corresponding variables in the model. If the ‘case’ arg is supplied, the values will be set into the case and not into the model.

values: iterator
Iterator of input values with an order defined to match the order of parameters returned by the get_parameters method. ‘values’ must support the len() function.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.
class openmdao.lib.drivers.doedriver.NeighborhoodDOEdriver(*args, **kwargs)[source]

Bases: openmdao.lib.drivers.caseiterdriver.CaseIterDriverBase

Driver for Design of Experiments within a specified neighborhood around a point.

Slot (IDOEgenerator) DOEgenerator

Iterator supplying normalized DOE values.

  • default: None
  • iotype: ‘in’
  • copy: ‘deep’
  • required: True
  • vartypename: ‘Slot’
Float alpha

Multiplicative factor for neighborhood DOE Driver.

  • default: ‘0.3’
  • iotype: ‘in’
  • low: 0.01
  • high: 1.0
  • vartypename: ‘Float’
Float beta

Another factor for neighborhood DOE Driver.

  • default: ‘0.01’
  • iotype: ‘in’
  • low: 0.001
  • high: 1.0
  • vartypename: ‘Float’
List case_outputs

A list of outputs to be saved with each case.

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

Adds a parameter or group of parameters to the driver.

target: string or iter of strings or Parameter
What the driver should vary during execution. A target is an expression that can reside on the left-hand side of an assignment statement, so typically it will be the name of a variable or possibly a subscript expression indicating an entry within an array variable, e.g., x[3]. If an iterator of targets is given, then the driver will set all targets given to the same value whenever it varies this parameter during execution. If a Parameter instance is given, then that instance is copied into the driver with any other arguments specified, overiding the values in the given parameter.
low: float (optional)
Minimum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
high: float (optional)
Maximum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
scaler: float (optional)
Value to multiply the possibly offset parameter value by.
adder: float (optional)
Value to add to parameter prior to possible scaling.
start: any (optional)
Value to set into the target or targets of a parameter before starting any executions. If not given, analysis will start with whatever values are in the target or targets at that time.
fd_step: float (optional)
Step-size to use for finite difference calculation. If no value is given, the differentitator will use its own default.
name: str (optional)
Name used to refer to the parameter in place of the name of the variable referred to in the parameter string. This is sometimes useful if, for example, multiple entries in the same array variable are declared as parameters.
scope: object (optional)
The object to be used as the scope when evaluating the expression.

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.

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.

init_parameters()

Sets all parameters to their start value, if a start value is given

list_param_targets()

Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter and ParameterGroup objects since ParameterGroups have multiple targets.

remove_parameter(name)

Removes the parameter with the given name.

set_parameter_by_name(name, value, case=None, scope=None)

Sets a single parameter by its name attribute.

name: str
Name of the parameter. This is either the name alias given when the parameter was added, or the variable path of the parameter’s target if no name was given.
value: object (typically a float)
Value of the parameter to be set.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.
set_parameters(values, case=None, scope=None)

Pushes the values in the iterator ‘values’ into the corresponding variables in the model. If the ‘case’ arg is supplied, the values will be set into the case and not into the model.

values: iterator
Iterator of input values with an order defined to match the order of parameters returned by the get_parameters method. ‘values’ must support the len() function.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.

genetic.py

Genetic

Genetic is a driver which performs optimization using a genetic algorithm based on Pyevolve. Genetic is a global optimizer and is ideal for optimizing problems with integer or discrete design variables because it is a non-derivative based optimization method.

Genetic can be used in any simulation by importing it from openmdao.lib.drivers.api:

from openmdao.lib.drivers.api import Genetic

Design Variables

IOtraits are added to Genetic and become optimization parameters. Genetic will vary the set of parameters to search for an optimum. Genetic supports three variable types: Float, Int, and Enum. These types can be used as parameters in any optimization.

You add design variables to Genetic using the add_parameter method.

from openmdao.main.api import Assembly, Component, set_as_top
from openmdao.lib.drivers.api import Genetic
from openmdao.lib.datatypes.api import Float, Int, Enum


class SomeComp(Component):
    """Arbitrary component with a few variables, but which does not really do
       any calculations
    """

    w = Float(0.0, low=-10, high=10, iotype="in")

    x = Float(0.0, low=0.0, high=100.0, iotype="in")
    y = Int(10, low=10, high=100, iotype="in")
    z = Enum([-10, -5, 0, 7], iotype="in")

class Simulation(Assembly):
    """Top Level Assembly used for simulation"""

    def configure(self):

        self.add('driver', Genetic())
        self.add('comp', SomeComp())

        # Driver process definition
        self.driver.workflow.add('comp')

        self.driver.add_parameter('comp.x')
        self.driver.add_parameter('comp.y')
        self.driver.add_parameter('comp.z')

top = set_as_top(Simulation())

In the above example, three parameters were added to the optimizer. The optimizer figures out for itself what type of variable it is and behaves appropriately. In all three cases, since no low or high arguments were provided, the optimizer will use the values from the metadata provided in the variable deceleration.

For comp.x the optimizer will try floats between 0.0 and 100.0. For comp.y the optimizer will try integers between 10 and 100. For comp.z the optimizer will pick from the list of allowed values: [-10,-5,0,7].

You can override the low and high values from the metadata if you want the optimizer to use a different range instead of the default.

top.driver.add_parameter('comp.w', low=5.0, high=7.0)

Now, for comp.x the optimizer will only try values between 5.0 and 7.0. Note that low and high are applicable only to Float and Int variables. For Enum variables, low and high are not applicable.

Configuration

When setting the objective you can specify a single variable name or a more complex function, such as

top.driver.add_objective("comp.x")

or

top.driver.clear_objectives()
top.driver.add_objective("2*comp.x + comp.y + 3*comp.z")

In the second example above, a more complex objective function was created where the overall objective was a weighted combination of comp.x, comp.y, and comp.z.

To set the optimizer to either minimize or maximize your objective, you set the opt_type variable of Genetic to "minimize" or "maximize.

top.driver.opt_type = "minimize"

You can control the size of the population in each generation and the maximum number of generations in your optimization with the population_size and generations variables.

top.driver.population_size = 80
top.driver.generations = 100

As you increase the population size, you are effectively adding diversity in to the gene pool of your optimization. A large population means that a larger number of individuals from a given generation will be chosen to provide genetic material for the next generation. So there is a better chance that weaker individuals will pass on their genes. This diversity helps to ensure that your optimization will find a true global optimum within the allowed design space. However, it also serves to slow down the optimization because of the increased number of function evaluations necessary for each generation.

Picking an appropriate value for the maximum number of generations will depend highly on the specifics of your problem. Setting this number too low will likely prevent the optimization from converging on a true optimum. Setting it too high will help you find the true optimum, but you may end up wasting the computation time on later generations where the optimum has been found.

You can further control the behavior of the genetic algorithm by setting the crossover_rate, mutation_rate, selection_method, and elitism variables. These settings will allow you to fine-tune the convergence of your optimization to achieve the desired result; however, for many optimizations the default values will work well and won’t need to be changed.

The crossover_rate controls the rate at which the crossover operator gets applied to the genome of a set of individuals who are reproducing. The allowed values are between 0.0 and 1.0. A higher rate will mean that more of the genes are swapped between parents. The result will be a more uniform population and better searching of the design space. If the rate is set too high, then it is likely that stronger individuals could be lost to churn.

top.driver.crossover_rate = 0.9

The mutation_rate controls how likely any particular gene is to experience a mutation. A low, but non-zero, mutation rate will help prevent stagnation in the gene pool by randomly moving the values of genes. If this rate is set too high, the algorithm basically degrades into a random search through the design space. The allowed values are between 0.0 and 1.0.

top.driver.mutation_rate = .02

In a pure genetic algorithm, it is possible that your best performing individual will not survive from one generation to the next due to competition, mutation, and crossover. If you want to ensure that the best individual survives intact from one generation to the next, then turn on the elitism flag for your optimization. This will ensure that the best individual is always copied to the next generation no matter what.

top.driver.elitism = True

A number of different commonly used selection algorithms are available. The default algorithm is the Roulette Wheel Algorithm, but Rank Selection, and Uniform Selection are also available. The selection_method variable allows you to select the algorithm; allowed values are: "roulette_wheel," "rank," and "uniform".

top.driver.selection_method="rank"

Source Documentation for genetic.py

A simple Pyevolve-based driver for OpenMDAO.

class openmdao.lib.drivers.genetic.Genetic(*args, **kwargs)[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
  • vartypename: ‘Float’
Bool elitism

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

  • default: ‘False’
  • iotype: ‘in’
  • vartypename: ‘Bool’
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
  • vartypename: ‘Float’
Enum opt_type

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

  • default: ‘minimize’
  • iotype: ‘in’
  • values: [‘minimize’, ‘maximize’]
  • vartypename: ‘Enum’
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’, ‘rank’, ‘uniform’)
  • vartypename: ‘Enum’
Slot (GenomeBase) best_individual

The genome with the best score from the optimization.

  • default: None
  • iotype: ‘out’
  • copy: ‘deep’
  • vartypename: ‘Slot’
add_objective(expr, name=None, scope=None)

Adds an objective to the driver.

expr: string
String containing the objective expression.
name: string (optional)
Name to be used to refer to the objective in place of the expression string.
scope: object (optional)
The object to be used as the scope when evaluating the expression.
add_objectives(obj_iter, scope=None)

Takes an iterator of objective strings and creates objectives for them in the driver.

add_parameter(target, low=None, high=None, scaler=None, adder=None, start=None, fd_step=None, name=None, scope=None)

Adds a parameter or group of parameters to the driver.

target: string or iter of strings or Parameter
What the driver should vary during execution. A target is an expression that can reside on the left-hand side of an assignment statement, so typically it will be the name of a variable or possibly a subscript expression indicating an entry within an array variable, e.g., x[3]. If an iterator of targets is given, then the driver will set all targets given to the same value whenever it varies this parameter during execution. If a Parameter instance is given, then that instance is copied into the driver with any other arguments specified, overiding the values in the given parameter.
low: float (optional)
Minimum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
high: float (optional)
Maximum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
scaler: float (optional)
Value to multiply the possibly offset parameter value by.
adder: float (optional)
Value to add to parameter prior to possible scaling.
start: any (optional)
Value to set into the target or targets of a parameter before starting any executions. If not given, analysis will start with whatever values are in the target or targets at that time.
fd_step: float (optional)
Step-size to use for finite difference calculation. If no value is given, the differentitator will use its own default.
name: str (optional)
Name used to refer to the parameter in place of the name of the variable referred to in the parameter string. This is sometimes useful if, for example, multiple entries in the same array variable are declared as parameters.
scope: object (optional)
The object to be used as the scope when evaluating the expression.

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.

clear_objectives()

Removes all objectives.

clear_parameters()

Removes all parameters.

eval_objective()

Returns a list of values of the evaluated objectives.

eval_objectives()

Returns a list of values of the evaluated objectives.

execute()[source]

Perform the optimization

get_objectives()

Returns an OrderedDict of objective expressions.

get_parameters()

Returns an ordered dict of parameter objects.

init_parameters()

Sets all parameters to their start value, if a start value is given

list_param_targets()

Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter and ParameterGroup objects since ParameterGroups have multiple targets.

remove_objective(expr)

Removes the specified objective expression. Spaces within the expression are ignored.

remove_parameter(name)

Removes the parameter with the given name.

set_parameter_by_name(name, value, case=None, scope=None)

Sets a single parameter by its name attribute.

name: str
Name of the parameter. This is either the name alias given when the parameter was added, or the variable path of the parameter’s target if no name was given.
value: object (typically a float)
Value of the parameter to be set.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.
set_parameters(values, case=None, scope=None)

Pushes the values in the iterator ‘values’ into the corresponding variables in the model. If the ‘case’ arg is supplied, the values will be set into the case and not into the model.

values: iterator
Iterator of input values with an order defined to match the order of parameters returned by the get_parameters method. ‘values’ must support the len() function.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.

iterate.py

FixedPointIterator

The FixedPointIterator is a simple solver that can solve a single-input single-output problem using fixed point iteration. It provides a way to iterate on a single input to match an output. In other words, fixed point iteration can be used to solve the equation x = f(x). By extension, FixedPointIterator can be used to close a loop in the data flow. The algorithm is useful for some problems, so it is included here. However, it may require more functional evaluations than the BroydenSolver.

As an example, let’s implement a component that can be run iteratively to produce the square root of a number.

from openmdao.lib.datatypes.api import Float
from openmdao.main.api import Component


class Babylonian(Component):
    """ The Babylonians had a neat way of calculating square
    roots using Fixed Point Iteration"""

    x = Float(1.0, iotype="in", doc="Input is x")
    y = Float(iotype="out", doc="Output is y")

    def execute(self):
        """ Iterate to find the square root of 2, the Babylonian way:
        """

        x = self.x
        self.y = 0.5*(2.0/x + x)

An assembly with this component and the FixedPointIterator would look like this.

from openmdao.lib.drivers.api import FixedPointIterator
from openmdao.main.api import Assembly

class SolutionAssembly(Assembly):
    """ Solves for the root of MIMOSystem. """

    def configure(self):
        """ Creates a new Assembly with this problem
        the answer should be 1.4142.....
        """

        self.add('driver', FixedPointIterator())
        self.add('problem', Babylonian())

        self.driver.workflow.add('problem')

        # Set our independent and dependent
        self.driver.add_parameter('problem.x', low=-9.e99, high=9.e99)
        self.driver.add_constraint('problem.y = problem.x')

The x input and the F(x) output equation are specified as string expressions using the add_parameter and add_constraint methods. The constraint contains the equation x = f(x), which we are trying to solve. Note that this is a single-input single-output method, so it is only valid to specify one constraint and one parameter.

>>> top = SolutionAssembly()
>>> top.run()
>>> print top.problem.x
1.4142...

Two additional parameters control the FixedPointIterator. The parameter tolerance sets the convergence tolerance for the comparison between value of x_out at the current iteration and the previous iteration. The default value for tolerance is 0.001. The parameter max_iteration specifies the number of iterations to run. The default value for max_iterations is 25.

A more useful example in which the FixedPointIterator is used to converge two coupled components is shown in MDAO Architectures.

Source Documentation for 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[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. This type of iteration is also known as Gauss-Seidel.

Int max_iteration

Maximum number of iterations before termination.

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

Absolute convergence tolerance between iterations.

  • default: ‘0.001’
  • iotype: ‘in’
  • vartypename: ‘Float’
Enum norm_order

For multivariable iteration, type of normto use to test convergence.

  • default: ‘Infinity’
  • values: [‘Infinity’, ‘Euclidean’]
  • vartypename: ‘Enum’
add_constraint(expr_string, scaler=1.0, adder=0.0, name=None, scope=None)

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).
name: str (optional)
Name to be used to refer to the constraint rather than its expression string.
scope: object (optional)
The object to be used as the scope when evaluating the expression.
add_existing_constraint(cnst, name=None)

Adds an existing Constraint object to the driver.

cnst: Constraint object

name: str (optional)
Name to be used to refer to the constraint rather than its expression string.
add_parameter(target, low=None, high=None, scaler=None, adder=None, start=None, fd_step=None, name=None, scope=None)

Adds a parameter or group of parameters to the driver.

target: string or iter of strings or Parameter
What the driver should vary during execution. A target is an expression that can reside on the left-hand side of an assignment statement, so typically it will be the name of a variable or possibly a subscript expression indicating an entry within an array variable, e.g., x[3]. If an iterator of targets is given, then the driver will set all targets given to the same value whenever it varies this parameter during execution. If a Parameter instance is given, then that instance is copied into the driver with any other arguments specified, overiding the values in the given parameter.
low: float (optional)
Minimum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
high: float (optional)
Maximum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
scaler: float (optional)
Value to multiply the possibly offset parameter value by.
adder: float (optional)
Value to add to parameter prior to possible scaling.
start: any (optional)
Value to set into the target or targets of a parameter before starting any executions. If not given, analysis will start with whatever values are in the target or targets at that time.
fd_step: float (optional)
Step-size to use for finite difference calculation. If no value is given, the differentitator will use its own default.
name: str (optional)
Name used to refer to the parameter in place of the name of the variable referred to in the parameter string. This is sometimes useful if, for example, multiple entries in the same array variable are declared as parameters.
scope: object (optional)
The object to be used as the scope when evaluating the expression.

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.

allows_constraint_types(types)

Returns True if types is [‘eq’].

clear_constraints()

Removes all constraints.

clear_parameters()

Removes all parameters.

copy_constraints()

Returns a copy of our constraints dict.

eval_eq_constraints(scope=None)

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

execute()[source]

Perform the iteration.

get_eq_constraints()

Returns an ordered dict of constraint objects.

get_parameters()

Returns an ordered dict of parameter objects.

init_parameters()

Sets all parameters to their start value, if a start value is given

list_constraints()

Return a list of strings containing constraint expressions.

list_param_targets()

Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter and ParameterGroup objects since ParameterGroups have multiple targets.

remove_constraint(key)

Removes the constraint with the given string.

remove_parameter(name)

Removes the parameter with the given name.

set_parameter_by_name(name, value, case=None, scope=None)

Sets a single parameter by its name attribute.

name: str
Name of the parameter. This is either the name alias given when the parameter was added, or the variable path of the parameter’s target if no name was given.
value: object (typically a float)
Value of the parameter to be set.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.
set_parameters(values, case=None, scope=None)

Pushes the values in the iterator ‘values’ into the corresponding variables in the model. If the ‘case’ arg is supplied, the values will be set into the case and not into the model.

values: iterator
Iterator of input values with an order defined to match the order of parameters returned by the get_parameters method. ‘values’ must support the len() function.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.
class openmdao.lib.drivers.iterate.IterateUntil(doc=None)[source]

Bases: openmdao.main.driver.Driver

A simple driver to run a workflow until some stop condition is met

Int max_iterations

maximun number of iterations

  • default: ‘10’
  • iotype: ‘in’
Bool run_at_least_once

If True, driver will ignore stop conditions for the first iteration, and run at least one iteration

  • default: ‘True’
  • iotype: ‘in’
  • vartypename: ‘Bool’
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]

Code executed before the iteration

newsumtdriver.py

NEWSUMTDriver

NEWSUMT is a Fortran subroutine for solving linear and nonlinear constrained or unconstrained function minimization problems. It has been included in the OpenMDAO standard library to provide users with a basic gradient-based optimization algorithm.

The minimization algorithm used in NEWSUMT is a sequence of unconstrained minimizations technique (SUMT) where the modified Newton’s method is used for unconstrained function minimizations.

If analytic gradients of the objective or constraint functions are not available, this information is calculated by finite difference.

NEWSUMT treats inequality constraints in a way that is especially well suited to engineering design applications.

More information on NEWSUMT can be found in the NEWSUMT Users Guide.

Basic Interface

The NEWSUMT code contains a number of different parameters and switches that are useful for controlling the optimization process. These can be subdivided into those parameters that will be used in a typical optimization problem and those that are more likely to be used by an expert user.

For the simplest possible unconstrained optimization problem, NEWSUMT just needs an objective function and one or more decision variables (parameters.) The basic interface conforms to OpenMDAO’s driver API.

The OpenMDAO NEWSUMT driver can be imported from openmdao.lib.drivers.api.

from openmdao.lib.drivers.api import NEWSUMTdriver

Typically, NEWSUMT will be used as a driver in the top level assembly, though it can be also used in a subassembly as part of a nested driver scheme. Using the OpenMDAO script interface, a simple optimization problem can be set up as follows:

from openmdao.main.api import Assembly
from openmdao.examples.enginedesign.vehicle import Vehicle
from openmdao.lib.drivers.api import CONMINdriver

class EngineOptimization(Assembly):
    """ Top level assembly for optimizing a vehicle. """

    def configure(self):
        """ Creates a new Assembly for vehicle performance optimization."""

        # Create CONMIN Optimizer instance
        self.add('driver', NEWSUMTdriver())

        # Create Vehicle instance
        self.add('vehicle', Vehicle())

        # add Vehicle to optimizer workflow
        self.driver.workflow.add('vehicle')

        # CONMIN Flags
        self.driver.iprint = 0
        self.driver.itmax = 30

        # CONMIN Objective
        self.driver.add_objective('vehicle.fuel_burn')

        # CONMIN Design Variables
        self.driver.add_parameter('vehicle.spark_angle', low=-50. , high=10.)
        self.driver.add_parameter('vehicle.bore', low=65. , high=100.)

This first section of code defines an assembly called EngineOptimization. This assembly contains a DrivingSim component and a NEWSUMTdriver, both of which are created and added inside the __init__ function with add. The DrivingSim component is also added to the driver’s workflow. The objective function, design variables, constraints, and any NEWSUMT parameters are also assigned in the __init__ function.

Basic Parameters

This section contains the basic parameters for NEWSUMT.

The default behavior for NEWSUMT is to calculate its own gradients and Hessians of the objective and constraints using a first-order forward finite difference. The second derivatives are approximated from the first order differences. You can replace NEWSUMT’s finite difference with OpenMDAO’s built-in capability by inserting a differentiator into the Differentiator slot in the driver.

If you want to use NEWSUMT for the finite difference calculation and want the same finite difference step size in all your variables, you can set the default_fd_stepsize parameter.

self.driver.default_fd_stepsize = .0025

The default step size will be used for all parameters for which you have not set the fd_step attribute.

When using NEWSUMT, if you have any linear constraints, it may be advantageous to specify them as such so that NEWSUMT can treat them differently. Use the integer array ilin to designate whether a constraint is linear. A value of 0 indicates that that constraint is non-linear, while a value of 1 indicates that that the constraint is linear. This parameter is optional, and when it is omitted, all constraints are assumed to be nonlinear.

map(self.driver.add_constraint, ['vehicle.stroke < vehicle.bore',
                           'vehicle.stroke * vehicle.bore > 1.0'])
self.driver.ilin_linear = [1, 0]

Similarly, NEWSUMT has a flag parameter to indicate whether the objective function is linear or nonlinear. Setting lobj to 1 indicates a linear objective function. Setting it to 0, which is the default value, indicates a nonlinear objective function.

self.driver.lobj = 0

The iprint parameter can be used to display diagnostic messages. These messages are currently sent to the standard output.

self.driver.iprint = 0

Higher positive values of iprint turn on the display of more levels of output, as summarized below.

Value Result
iprint = 0 All output is suppressed, including warnings
iprint = 1 Print initial and final designs only
iprint = 2 Print brief results of analysis for initial and final designs together with minimal intermediate information
iprint = 3 Detailed printing
iprint = 4 Debugging printing

Controlling the Optimization

NEWSUMT provides a variety of parameters to control the convergence criteria for an optimization.

The maximum number of iterations is specified by setting the itmax parameter. The default value is 10.

self.driver.itmax = 30

The convergence tolerance is controlled with six parameters. The following table summarizes these parameters.

Parameter Description Default
epsgsn Convergence criteria of the golden section algorithm used for the one-dimensional minimization 0.001
epsodm Convergence criteria of the unconstrained minimization 0.001
epsrsf Convergence criteria for the overall process 0.001
maxgsn Maximum allowable number of golden section iterations used for 1D minimization 20
maxodm Maximum allowable number of one-dimensional minimizations 6
maxrsf Maximum allowable number of unconstrained minimizations 15
self.driver.epsgsn = .000001
self.driver.maxgsn = 40

Advanced Options

There are additional options for advanced users. More information on these parameters can be found in the NEWSUMT Users Guide. (This doc is slow to load.)

Parameter Description Default
mflag Flag for penalty multiplier. If 0, initial value computed by NEWSUMT. If 1, initial value set by ra 0
ra Penalty multiplier. Required if mflag=1 1.0
racut Penalty multiplier decrease ratio. Required if mflag=1 0.1
ramin Lower bound of penalty multiplier. Required if mflag=1 1.0e-13
g0 Initial value of the transition parameter 0.1

Source Documentation for newsumtdriver.py

newsumtdriver.py - Driver for the NEWSUMT optimizer.

class openmdao.lib.drivers.newsumtdriver.NEWSUMTdriver(*args, **kwargs)[source]

Bases: openmdao.main.driver_uses_derivatives.DriverUsesDerivatives

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’
  • vartypename: ‘Float’
Float epsgsn

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

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

Convergence criteria of the unconstrained minimization.

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

Convergence criteria for the overall process.

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

Initial value of the transition parameter.

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

Array designating whether each constraint is linear.

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

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

  • default: ‘0’
  • iotype: ‘in’
  • low: 0
  • high: 4
  • vartypename: ‘Int’
  • exclude_low: False
  • exclude_high: False
Int itmax

Maximum number of iterations before termination.

  • default: ‘10’
  • iotype: ‘in’
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’
  • vartypename: ‘Float’
Float racut

Penalty multiplier decrease ratio. Required if mflag=1.

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

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

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

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

  • default: ‘2.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
add_constraint(expr_string, scaler=1.0, adder=0.0, name=None, scope=None)

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).
name: str (optional)
Name to be used to refer to the constraint rather than its expression string.
scope: object (optional)
The object to be used as the scope when evaluating the expression.
add_existing_constraint(cnst, name=None)

Adds an existing Constraint object to the driver.

cnst: Constraint object

name: str (optional)
Name to be used to refer to the constraint rather than its expression string.
add_objective(expr, name=None, scope=None)

Adds an objective to the driver.

expr: string
String containing the objective expression.
name: string (optional)
Name to be used to refer to the objective in place of the expression string.
scope: object (optional)
The object to be used as the scope when evaluating the expression.
add_objectives(obj_iter, scope=None)

Takes an iterator of objective strings and creates objectives for them in the driver.

add_parameter(target, low=None, high=None, scaler=None, adder=None, start=None, fd_step=None, name=None, scope=None)

Adds a parameter or group of parameters to the driver.

target: string or iter of strings or Parameter
What the driver should vary during execution. A target is an expression that can reside on the left-hand side of an assignment statement, so typically it will be the name of a variable or possibly a subscript expression indicating an entry within an array variable, e.g., x[3]. If an iterator of targets is given, then the driver will set all targets given to the same value whenever it varies this parameter during execution. If a Parameter instance is given, then that instance is copied into the driver with any other arguments specified, overiding the values in the given parameter.
low: float (optional)
Minimum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
high: float (optional)
Maximum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
scaler: float (optional)
Value to multiply the possibly offset parameter value by.
adder: float (optional)
Value to add to parameter prior to possible scaling.
start: any (optional)
Value to set into the target or targets of a parameter before starting any executions. If not given, analysis will start with whatever values are in the target or targets at that time.
fd_step: float (optional)
Step-size to use for finite difference calculation. If no value is given, the differentitator will use its own default.
name: str (optional)
Name used to refer to the parameter in place of the name of the variable referred to in the parameter string. This is sometimes useful if, for example, multiple entries in the same array variable are declared as parameters.
scope: object (optional)
The object to be used as the scope when evaluating the expression.

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.

allows_constraint_types(typ)

Returns True if types is [‘ineq’].

clear_constraints()

Removes all constraints.

clear_objectives()

Removes all objectives.

clear_parameters()

Removes all parameters.

continue_iteration()[source]

Returns True if iteration should continue.

copy_constraints()

Returns a copy of our constraints dict.

eval_ineq_constraints(scope=None)

Returns a list of constraint values

eval_objective()

Returns a list of values of the evaluated objectives.

eval_objectives()

Returns a list of values of the evaluated objectives.

get_ineq_constraints()

Returns an ordered dict of inequality constraint objects.

get_objectives()

Returns an OrderedDict of objective expressions.

get_parameters()

Returns an ordered dict of parameter objects.

init_parameters()

Sets all parameters to their start value, if a start value is given

list_constraints()

Return a list of strings containing constraint expressions.

list_param_targets()

Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter and ParameterGroup objects since ParameterGroups have multiple targets.

pre_iteration()[source]

Checks or RunStopped and evaluates objective.

remove_constraint(key)

Removes the constraint with the given string.

remove_objective(expr)

Removes the specified objective expression. Spaces within the expression are ignored.

remove_parameter(name)

Removes the parameter with the given name.

run_iteration()[source]

The NEWSUMT driver iteration.

set_parameter_by_name(name, value, case=None, scope=None)

Sets a single parameter by its name attribute.

name: str
Name of the parameter. This is either the name alias given when the parameter was added, or the variable path of the parameter’s target if no name was given.
value: object (typically a float)
Value of the parameter to be set.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.
set_parameters(values, case=None, scope=None)

Pushes the values in the iterator ‘values’ into the corresponding variables in the model. If the ‘case’ arg is supplied, the values will be set into the case and not into the model.

values: iterator
Iterator of input values with an order defined to match the order of parameters returned by the get_parameters method. ‘values’ must support the len() function.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.
start_iteration()[source]

Perform the optimization.

sensitivity.py

sensitivity.py – Driver to calculate the gradient of a workflow and return it as a driver output.

SensitivityDriver includes a differentiator slot where the differentiation method can be plugged. Fake finite difference is supported.

class openmdao.lib.drivers.sensitivity.SensitivityDriver(*args, **kwargs)[source]

Bases: openmdao.main.driver_uses_derivatives.DriverUsesDerivatives

Driver to calculate the gradient of a workflow and return it as a driver output. The gradient is calculated from all inputs (Parameters) to all outputs (Objectives and Constraints).

SensitivityDriver includes a differentiator slot where the differentiation method can be plugged. Fake finite difference is supported.

Array F

Objective baseline values where sensitivity is evaluated.

  • default: ‘[]’
  • iotype: ‘out’
  • comparison_mode: 1
Array G

Constraint baseline values where sensitivity is evaluated.

  • default: ‘[]’
  • iotype: ‘out’
  • comparison_mode: 1
Array dF

Sensitivity of the objectives with respect to the parameters. Index 1 is the objective output, while index 2 is the parameter input.

  • default: ‘[]’
  • iotype: ‘out’
  • comparison_mode: 1
List dF_names

Objective names that correspond to our array indices.

  • default: ‘[]’
  • iotype: ‘out’
  • copy: ‘deep’
Array dG

Sensitivity of the constraints with respect to the parameters. Index 1 is the constraint output, while index 2 is the parameter input.

  • default: ‘[]’
  • iotype: ‘out’
  • comparison_mode: 1
List dG_names

Constraint names that correspond to our array indices.

  • default: ‘[]’
  • iotype: ‘out’
  • copy: ‘deep’
List dx_names

Parameter names that correspond to our array indices.

  • default: ‘[]’
  • iotype: ‘out’
  • copy: ‘deep’
Array x

Parameter baseline values where sensitivity is evaluated.

  • default: ‘[]’
  • iotype: ‘out’
  • comparison_mode: 1
add_constraint(expr_string, scaler=1.0, adder=0.0, name=None, scope=None)

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).
name: str (optional)
Name to be used to refer to the constraint rather than its expression string.
scope: object (optional)
The object to be used as the scope when evaluating the expression.
add_existing_constraint(cnst, name=None)

Adds an existing Constraint object to the driver.

cnst: Constraint object

name: str (optional)
Name to be used to refer to the constraint rather than its expression string.
add_objective(expr, name=None, scope=None)

Adds an objective to the driver.

expr: string
String containing the objective expression.
name: string (optional)
Name to be used to refer to the objective in place of the expression string.
scope: object (optional)
The object to be used as the scope when evaluating the expression.
add_objectives(obj_iter, scope=None)

Takes an iterator of objective strings and creates objectives for them in the driver.

add_parameter(target, low=None, high=None, scaler=None, adder=None, start=None, fd_step=None, name=None, scope=None)

Adds a parameter or group of parameters to the driver.

target: string or iter of strings or Parameter
What the driver should vary during execution. A target is an expression that can reside on the left-hand side of an assignment statement, so typically it will be the name of a variable or possibly a subscript expression indicating an entry within an array variable, e.g., x[3]. If an iterator of targets is given, then the driver will set all targets given to the same value whenever it varies this parameter during execution. If a Parameter instance is given, then that instance is copied into the driver with any other arguments specified, overiding the values in the given parameter.
low: float (optional)
Minimum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
high: float (optional)
Maximum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
scaler: float (optional)
Value to multiply the possibly offset parameter value by.
adder: float (optional)
Value to add to parameter prior to possible scaling.
start: any (optional)
Value to set into the target or targets of a parameter before starting any executions. If not given, analysis will start with whatever values are in the target or targets at that time.
fd_step: float (optional)
Step-size to use for finite difference calculation. If no value is given, the differentitator will use its own default.
name: str (optional)
Name used to refer to the parameter in place of the name of the variable referred to in the parameter string. This is sometimes useful if, for example, multiple entries in the same array variable are declared as parameters.
scope: object (optional)
The object to be used as the scope when evaluating the expression.

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.

allows_constraint_types(types)

Returns True if this Driver supports constraints of the given types.

types: list of str
Types of constraints supported. Valid values are: [‘eq’, ‘ineq’]
clear_constraints()

Removes all constraints.

clear_objectives()

Removes all objectives.

clear_parameters()

Removes all parameters.

copy_constraints()
eval_eq_constraints(scope=None)

Returns a list of tuples of the form (lhs, rhs, comparator, is_violated) from evalution of equality constraints.

eval_ineq_constraints(scope=None)

Returns a list of tuples of the form (lhs, rhs, comparator, is_violated) from evalution of inequality constraints.

eval_objectives()

Returns a list of values of the evaluated objectives.

execute()[source]

Calculate the gradient of the workflow.

get_constraints()

Return a list of constraint objects

get_eq_constraints()

Returns an ordered dict of equality constraint objects.

get_ineq_constraints()

Returns an ordered dict of inequality constraint objects.

get_objectives()

Returns an OrderedDict of objective expressions.

get_parameters()

Returns an ordered dict of parameter objects.

init_parameters()

Sets all parameters to their start value, if a start value is given

list_constraints()

Return a list of strings containing constraint expressions.

list_param_targets()

Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter and ParameterGroup objects since ParameterGroups have multiple targets.

remove_constraint(expr_string)

Removes the constraint with the given string.

remove_objective(expr)

Removes the specified objective expression. Spaces within the expression are ignored.

remove_parameter(name)

Removes the parameter with the given name.

set_parameter_by_name(name, value, case=None, scope=None)

Sets a single parameter by its name attribute.

name: str
Name of the parameter. This is either the name alias given when the parameter was added, or the variable path of the parameter’s target if no name was given.
value: object (typically a float)
Value of the parameter to be set.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.
set_parameters(values, case=None, scope=None)

Pushes the values in the iterator ‘values’ into the corresponding variables in the model. If the ‘case’ arg is supplied, the values will be set into the case and not into the model.

values: iterator
Iterator of input values with an order defined to match the order of parameters returned by the get_parameters method. ‘values’ must support the len() function.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.

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 optionally 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 recorders socket is used to record results. This is inherited from the Driver class.

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

Slot (ICaseIterator) iterator

Source of Cases.

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

Run each case in iterator and record results in recorder.

slsqpdriver.py

slsqpdriver.py - Contains a driver that wraps the SLSQP optimizer as used in pyOpt:

Minimize a function using Sequential Least SQuares Programming.

SLSQP is a gradient optimizer that can handle both equality and inequality constraints.

class openmdao.lib.drivers.slsqpdriver.SLSQPdriver(*args, **kwargs)[source]

Bases: openmdao.main.driver_uses_derivatives.DriverUsesDerivatives

Minimize a function using the Sequential Least SQuares Programming (SLSQP) method.

SLSQP is a gradient optimizer that can handle both equality and inequality constraints.

Note: Constraints should be added using the OpenMDAO convention (positive = violated).

Float accuracy

Convergence accuracy

  • default: ‘1e-06’
  • iotype: ‘in’
  • vartypename: ‘Float’
Int iout

Fortran output unit. Leave this at 6 for STDOUT.

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

Controls the frequency of output: 0 (no output),1,2,3.

  • default: ‘0’
  • iotype: ‘in’
  • values: [0, 1, 2, 3]
  • vartypename: ‘Enum’
Int maxiter

Maximum number of iterations.

  • default: ‘50’
  • iotype: ‘in’
Str output_filename

Name of output file (if iout not 6).

  • default: ‘slsqp.out’
  • iotype: ‘in’
  • vartypename: ‘Str’
Int error_code

Error code returned from SLSQP.

  • default: ‘0’
  • iotype: ‘out’
add_constraint(expr_string, scaler=1.0, adder=0.0, name=None, scope=None)

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).
name: str (optional)
Name to be used to refer to the constraint rather than its expression string.
scope: object (optional)
The object to be used as the scope when evaluating the expression.
add_existing_constraint(cnst, name=None)

Adds an existing Constraint object to the driver.

cnst: Constraint object

name: str (optional)
Name to be used to refer to the constraint rather than its expression string.
add_objective(expr, name=None, scope=None)

Adds an objective to the driver.

expr: string
String containing the objective expression.
name: string (optional)
Name to be used to refer to the objective in place of the expression string.
scope: object (optional)
The object to be used as the scope when evaluating the expression.
add_objectives(obj_iter, scope=None)

Takes an iterator of objective strings and creates objectives for them in the driver.

add_parameter(target, low=None, high=None, scaler=None, adder=None, start=None, fd_step=None, name=None, scope=None)

Adds a parameter or group of parameters to the driver.

target: string or iter of strings or Parameter
What the driver should vary during execution. A target is an expression that can reside on the left-hand side of an assignment statement, so typically it will be the name of a variable or possibly a subscript expression indicating an entry within an array variable, e.g., x[3]. If an iterator of targets is given, then the driver will set all targets given to the same value whenever it varies this parameter during execution. If a Parameter instance is given, then that instance is copied into the driver with any other arguments specified, overiding the values in the given parameter.
low: float (optional)
Minimum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
high: float (optional)
Maximum allowed value of the parameter. If scaler and/or adder are supplied, use the transformed value here.
scaler: float (optional)
Value to multiply the possibly offset parameter value by.
adder: float (optional)
Value to add to parameter prior to possible scaling.
start: any (optional)
Value to set into the target or targets of a parameter before starting any executions. If not given, analysis will start with whatever values are in the target or targets at that time.
fd_step: float (optional)
Step-size to use for finite difference calculation. If no value is given, the differentitator will use its own default.
name: str (optional)
Name used to refer to the parameter in place of the name of the variable referred to in the parameter string. This is sometimes useful if, for example, multiple entries in the same array variable are declared as parameters.
scope: object (optional)
The object to be used as the scope when evaluating the expression.

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.

allows_constraint_types(types)

Returns True if this Driver supports constraints of the given types.

types: list of str
Types of constraints supported. Valid values are: [‘eq’, ‘ineq’]
clear_constraints()

Removes all constraints.

clear_objectives()

Removes all objectives.

clear_parameters()

Removes all parameters.

copy_constraints()
eval_eq_constraints(scope=None)

Returns a list of tuples of the form (lhs, rhs, comparator, is_violated) from evalution of equality constraints.

eval_ineq_constraints(scope=None)

Returns a list of tuples of the form (lhs, rhs, comparator, is_violated) from evalution of inequality constraints.

eval_objective()

Returns a list of values of the evaluated objectives.

eval_objectives()

Returns a list of values of the evaluated objectives.

get_constraints()

Return a list of constraint objects

get_eq_constraints()

Returns an ordered dict of equality constraint objects.

get_ineq_constraints()

Returns an ordered dict of inequality constraint objects.

get_objectives()

Returns an OrderedDict of objective expressions.

get_parameters()

Returns an ordered dict of parameter objects.

init_parameters()

Sets all parameters to their start value, if a start value is given

list_constraints()

Return a list of strings containing constraint expressions.

list_param_targets()

Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter and ParameterGroup objects since ParameterGroups have multiple targets.

remove_constraint(expr_string)

Removes the constraint with the given string.

remove_objective(expr)

Removes the specified objective expression. Spaces within the expression are ignored.

remove_parameter(name)

Removes the parameter with the given name.

run_iteration()[source]

Note: slsqp controls the looping.

set_parameter_by_name(name, value, case=None, scope=None)

Sets a single parameter by its name attribute.

name: str
Name of the parameter. This is either the name alias given when the parameter was added, or the variable path of the parameter’s target if no name was given.
value: object (typically a float)
Value of the parameter to be set.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.
set_parameters(values, case=None, scope=None)

Pushes the values in the iterator ‘values’ into the corresponding variables in the model. If the ‘case’ arg is supplied, the values will be set into the case and not into the model.

values: iterator
Iterator of input values with an order defined to match the order of parameters returned by the get_parameters method. ‘values’ must support the len() function.
case: Case (optional)
If supplied, the values will be associated with their corresponding targets and added as inputs to the Case instead of being set directly into the model.
start_iteration()[source]

Perform initial setup before iteration loop begins.

OPTPROBLEMS

branin.py

class openmdao.lib.optproblems.branin.BraninComponent(doc=None, directory='')[source]

Bases: openmdao.main.component.Component

Float x
  • default: ‘0.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float y
  • default: ‘0.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float f_xy
  • default: ‘0.0’
  • iotype: ‘out’
  • vartypename: ‘Float’
execute()[source]
class openmdao.lib.optproblems.branin.BraninProblem(doc=None, directory='')[source]

Bases: openmdao.main.problem_formulation.OptProblem

Branin Test Problem Definition

configure()[source]

scalable.py

Scalable Test Optimization test problem proposed by Martins and Marriage.

J. R. R. A. Martins and C. Marriage, “An Object-Oriented Framework for Multidisciplinary Design Optimization,” 3rd AIAA Multidisciplinary Design Optimization Specialist Conference, 2007.

class openmdao.lib.optproblems.scalable.Discipline(prob_size=1)[source]

Bases: openmdao.main.component.Component

Float c_y_out

coefficient for the output variables

  • default: ‘1.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
execute()[source]
class openmdao.lib.optproblems.scalable.UnitScalableProblem(n_disciplines=3, prob_size=3)[source]

Bases: openmdao.main.problem_formulation.OptProblem

configure()[source]

sellar.py

Two discipline components. From Sellar’s analytic problem.

Sellar, R. S., Batill, S. M., and Renaud, J. E., “Response Surface Based, Concurrent Subspace Optimization for Multidisciplinary System Design,” Proceedings References 79 of the 34th AIAA Aerospace Sciences Meeting and Exhibit, Reno, NV, January 1996.
class openmdao.lib.optproblems.sellar.Discipline1(doc=None, directory='')[source]

Bases: openmdao.main.component.Component

Component containing Discipline 1.

Float x1

Local Design Variable.

  • default: ‘1.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float y2

Disciplinary Coupling.

  • default: ‘1.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float z1

Global Design Variable.

  • default: ‘0.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float z2

Global Design Variable.

  • default: ‘0.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float y1

Output of this Discipline.

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

Evaluates the equation y1 = z1**2 + z2 + x1 - 0.2*y2

class openmdao.lib.optproblems.sellar.Discipline1_WithDerivatives[source]

Bases: openmdao.main.component_with_derivatives.ComponentWithDerivatives

Component containing Discipline 1.

Float x1

Local Design Variable.

  • default: ‘0.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float y2

Disciplinary Coupling.

  • default: ‘1.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float z1

Global Design Variable.

  • default: ‘0.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float z2

Global Design Variable.

  • default: ‘0.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float y1

Output of this Discipline.

  • default: ‘0.0’
  • iotype: ‘out’
  • vartypename: ‘Float’
calculate_first_derivatives()[source]

Analytical first derivatives

execute()[source]

Evaluates the equation y1 = z1**2 + z2 + x1 - 0.2*y2.

class openmdao.lib.optproblems.sellar.Discipline2(doc=None, directory='')[source]

Bases: openmdao.main.component.Component

Component containing Discipline 2.

Float y1

Disciplinary Coupling.

  • default: ‘1.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float z1

Global Design Variable.

  • default: ‘0.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float z2

Global Design Variable.

  • default: ‘0.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float y2

Output of this Discipline.

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

Evaluates the equation y2 = y1**(.5) + z1 + z2

class openmdao.lib.optproblems.sellar.Discipline2_WithDerivatives[source]

Bases: openmdao.main.component_with_derivatives.ComponentWithDerivatives

Component containing Discipline 2.

Float y1

Disciplinary Coupling.

  • default: ‘1.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float z1

Global Design Variable.

  • default: ‘0.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float z2

Global Design Variable.

  • default: ‘0.0’
  • iotype: ‘in’
  • vartypename: ‘Float’
Float y2

Output of this Discipline.

  • default: ‘0.0’
  • iotype: ‘out’
  • vartypename: ‘Float’
calculate_first_derivatives()[source]

Analytical first derivatives

execute()[source]

Evaluates the equation y2 = y1**(.5) + z1 + z2.

class openmdao.lib.optproblems.sellar.SellarProblem(doc=None, directory='')[source]

Bases: openmdao.main.problem_formulation.OptProblem

Sellar test problem definition.

configure()[source]

Optimal Design at (1.9776, 0, 0)

Optimal Objective = 3.18339

class openmdao.lib.optproblems.sellar.SellarProblemWithDeriv(doc=None, directory='')[source]

Bases: openmdao.main.problem_formulation.OptProblem

Sellar test problem definition using components analytical derivatives.

configure()[source]

Creates a new Assembly with this problem.

Optimal Design at (1.9776, 0, 0)

Optimal Objective = 3.18339

SURROGATEMODELS

api.py

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

KrigingSurrogate

LogisticRegression

ResponseSurface

kriging_surrogate.py

Surrogate model based on Kriging.

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

Bases: object

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 Python logistic regression.

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

Bases: openmdao.main.container.Container

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]

response_surface.py

Surrogate Model based on second order response surface equations.

class openmdao.lib.surrogatemodels.response_surface.ResponseSurface(X=None, Y=None)[source]

Bases: openmdao.main.container.Container

get_uncertain_value(value)[source]

Returns the value iself. Response surface equations don’t have uncertainty.

predict(new_x)[source]

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

train(X, Y)[source]

Calculate response surface equation coefficients using least squares regression.

DATATYPES

api.py

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

on_trait_change

Any

Array

Bool

Complex

Dict

Enum

Event

File

Float

Int

List

Python

Slot

Str

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.
zone: Zone
Zone to be added.
prefix: string
String prepended to the zone name.
make_copy: bool
If True, then a deep copy of zone is made rather than just referring to a shared instance.
copy()[source]

Returns a deep copy of self.

deallocate()[source]

Deallocate resources.

demote()[source]

Demote from N-dimensional to N-1 dimensional index space.

extend(zone_args)[source]

Construct a new DomainObj from zones extended according to zone_args. Existing zone names are used for the new domain’s zones.

zone_args: sequence
Sequence of argument tuples to be used to extend each zone. If an argument tuple is empty or None, then that zone is skipped.
extract(zone_args)[source]

Construct a new DomainObj from grid and flow data extracted from the specified regions of each zone. Existing zone names are used for the new domain’s zones.

zone_args: sequence
Sequence of argument tuples to be used to extract data from each zone. If an argument tuple is empty or None then that zone is skipped.
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.

promote()[source]

Promote from N-dimensional to N+1 dimensional index space.

remove_zone(zone)[source]

Remove a zone. Returns the removed zone.

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

Rename a zone.

name: string
New name for the zone.
zone: Zone
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: Zone
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.

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: numpy.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.
copy()[source]

Returns a deep copy of self.

demote()[source]

Demote from N-dimensional to N-1 dimensional index space.

extend(axis, delta, npoints)[source]

Construct a new FlowSolution by replication. The existing ghosts/rind planes specification is retained.

axis: ‘i’, ‘j’, or ‘k’
Index axis to extend.
delta: float.
Direction. A negative value adds points before the current zero-index of axis.
npoints: int > 0
Number of points to add in axis dimension.
extract(imin, imax, jmin=None, jmax=None, kmin=None, kmax=None, ghosts=None)[source]

Construct a new FlowSolution from data extracted from the specified region.

imin, imax, jmin, jmax, kmin, kmax: int
Specifies the region to extract neglecting ghost/rind planes. Negative values are relative to the size in that dimension, so -1 refers to the last element. For 2D zones omit kmin and kmax. For 1D zones omit jmin, jmax, kmin, and kmax.
ghosts: int[]
Number of ghost/rind planes for the new zone. If None the existing specification is used.
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.

promote()[source]

Promote from N-dimensional to N+1 dimensional index space.

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, must be one of (‘Vertex’, ‘CellCenter’)

real_shape[source]

Data index limits, including any ‘ghost/rind’ planes.

shape[source]

Data index limits, not including ‘ghost/rind’ planes.

vectors[source]

List of vector data.

grid.py

class openmdao.lib.datatypes.domain.grid.GridCoordinates(vec=None)[source]

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

Coordinate data for a Zone. Currently limited to structured grids. 1D spatial data must set ‘x’. 2D spatial data must set ‘x’, and ‘y’ or ‘r’ and ‘t’. 3D spatial data must set ‘x’, ‘y’, and ‘z’ or ‘r’, ‘t’, and ‘z’. Note that index dimension is not the same as spatial dimension. For example, a curve in 3D space is represented by 1D ‘x’, ‘y’, and ‘z’ arrays. It can also be represented by 2D or 3D arrays where only one index dimension varies.

copy()[source]

Returns a deep copy of self.

extend(axis, delta, npoints, normal=None)[source]

Construct a new GridCoordinates by linear extrapolation. The existing ghosts/rind planes specification is retained.

axis: ‘i’, ‘j’, or ‘k’
Index axis to extend.
delta: float
Fractional amount to move for each point. Multiplies the ‘edge’ delta in the axis direction or the appropriate component of normal. A negative value adds points before the current zero-index of axis.
npoints: int > 0
Number of points to add in axis dimension.
normal: float[]
For cases where only a single point exists in the axis direction, this specifies the direction to move. If not specified, an axis-aligned direction is selected based on minimum grid extent.
extract(imin, imax, jmin=None, jmax=None, kmin=None, kmax=None, ghosts=None)[source]

Construct a new GridCoordinates from data extracted from the specified region.

imin, imax, jmin, jmax, kmin, kmax: int
Specifies the region to extract neglecting ghost/rind planes. Negative values are relative to the size in that dimension, so -1 refers to the last element. For 2D zones omit kmin and kmax. Similarly, for 1D zones only specify imin and imax.
ghosts: int[]
Number of ghost/rind planes for the new zone. If None, the existing specification is used.
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’). Only used for 3D data.
make_cylindrical(axis='z')[source]

Convert to cylindrical coordinate system.

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

Translate coordinates.

delta_x, delta_y, delta_z: float
Amount of translation along the corresponding axis.
extent[source]

Coordinate ranges, not including ‘ghost/rind’ planes. If cartesian (xmin,xmax,ymin,ymax,zmin,zmax). Otherwise (rmin,rmax,tmin,tmax,zmin,zmax).

metrics.py

Predefined classes used by mesh_probe(). Some typical fluid flow metric calculation classes are included here. Others may be added via register_metric(). A list of available metrics is returned by list_metrics(). Note that the name a metric is registered under need not match its class name.

Metrics may be used with 1D, 2D, or 3D Cartesian coordinates. They may also be used with polar (2D) or cylindrical (3D) coordinates. calculate() should be prepared for this.

class openmdao.lib.datatypes.domain.metrics.Area(zone, zone_name, reference_state)[source]

Bases: object

Computes area of mesh surface.

calculate(loc, normal)[source]

Return metric value.

dimensionalize(value)[source]

Return dimensional value.

class openmdao.lib.datatypes.domain.metrics.CorrectedMassFlow(zone, zone_name, reference_state)[source]

Bases: object

Computes corrected mass flow across a mesh surface.

calculate(loc, normal)[source]

Return metric value.

dimensionalize(value)[source]

Dimensionalize value.

class openmdao.lib.datatypes.domain.metrics.Length(zone, zone_name, reference_state)[source]

Bases: object

Computes length of mesh curve.

calculate(loc, length)[source]

Return metric value.

dimensionalize(value)[source]

Return dimensional value.

class openmdao.lib.datatypes.domain.metrics.MassFlow(zone, zone_name, reference_state)[source]

Bases: object

Computes mass flow across a mesh surface.

calculate(loc, normal)[source]

Return metric value.

dimensionalize(value)[source]

Dimensionalize value.

class openmdao.lib.datatypes.domain.metrics.StaticPressure(zone, zone_name, reference_state)[source]

Bases: object

Computes weighted static pressure for a mesh region.

calculate(loc, geom)[source]

Return metric value.

dimensionalize(value)[source]

Dimensionalize value.

class openmdao.lib.datatypes.domain.metrics.StaticTemperature(zone, zone_name, reference_state)[source]

Bases: object

Computes weighted static temperature for a mesh region.

calculate(loc, geom)[source]

Return metric value.

dimensionalize(value)[source]

Dimensionalize value.

class openmdao.lib.datatypes.domain.metrics.TotalPressure(zone, zone_name, reference_state)[source]

Bases: object

Computes weighted total pressure for a mesh region.

calculate(loc, geom)[source]

Return metric value.

dimensionalize(value)[source]

Dimensionalize value.

class openmdao.lib.datatypes.domain.metrics.TotalTemperature(zone, zone_name, reference_state)[source]

Bases: object

Computes weighted total temperature for a mesh region.

calculate(loc, geom)[source]

Return metric value.

dimensionalize(value)[source]

Dimensionalize value.

class openmdao.lib.datatypes.domain.metrics.Volume(zone, zone_name, reference_state)[source]

Bases: object

Computes volume of mesh volume.

calculate(loc, volume)[source]

Return metric value.

dimensionalize(value)[source]

Return dimensional value.

openmdao.lib.datatypes.domain.metrics.create_scalar_metric(var_name)[source]

Creates a minimal metric calculation class for var_name and registers it. This can be used for averaging scalar flow variables without having to statically create a class and register it. The created class does not support dimensionalization.

openmdao.lib.datatypes.domain.metrics.get_metric(name)[source]

Return (cls, integrate, geometry).

openmdao.lib.datatypes.domain.metrics.list_metrics()[source]

Return list of valid metric names.

openmdao.lib.datatypes.domain.metrics.register_metric(name, cls, integrate, geometry='any')[source]

Register a metric calculation class.

name: string
The name of the metric calculated.
cls: class
Class used to calculate metric. It must contain calculate() and dimensionalize(). Constructor arguments are (zone, zone_name, reference_state). calculate() will be called with (loc, geom). loc contains indices into the zone variable arrays and geom is either the cell volume, a non-dimensional vector normal to the cell face with magnitude equal to its area, or the edge length; depending upon the type of region (volume, surface, or curve). dimensionalize() is called with the accumulated value. It should return a PhysicalQuantity for the dimensionalized value.
integrate: bool
If True, then calculated values are integrated, not averaged.
geometry: string (‘volume’, ‘surface’, ‘curve’, or ‘any’)
Specifies what type of geometry this metric is restricted to, if any.

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. Ghost data is not written.

domain: DomainObj or Zone
The domain or zone 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. Ghost data is not written.

domain: DomainObj or Zone
The domain or zone 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. Ghost data is not written.

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

probe.py

Support for calculating one or more scalar averages across one or more regions in a domain.

openmdao.lib.datatypes.domain.probe.mesh_probe(domain, regions, variables, weighting_scheme='area')[source]

Calculate metrics on mesh regions. Currently only supports structured grids.

domain: DomainObj
The domain to be processed.
regions: list
List of (zone_name, imin, imax[, jmin, jmax[, kmin, kmax]]) mesh region 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 pre-existing metric names can be obtained from list_metrics(). If units is None then no unit conversion is attempted. metric_name may also be the name of a flow solution scalar variable, if units is None. In this case a minimal metric calculator will be auto-generated.
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.

Note

The per-item averaging scheme is simplistic. For instance, all four vertices of a face get equal weight, or the two cells sharing a face get equal weight. This will lead to inaccuracies for highly irregular grids.

vector.py

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

Bases: object

Vector data for a FlowSolution, also the base for GridCoordinates. 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.

demote()[source]

Demote from N-dimensional to N-1 dimensional index space.

extend(axis, delta, npoints)[source]

Construct a new Vector by replication.

axis: ‘i’, ‘j’, or ‘k’
Index axis to extend.
delta: float.
Direction. A negative value adds points before the current zero-index of axis.
npoints: int > 0
Number of points to add in axis dimension.
extract(imin, imax, jmin=None, jmax=None, kmin=None, kmax=None, ghosts=None)[source]

Construct a new Vector from data extracted from the specified region.

imin, imax, jmin, jmax, kmin, kmax: int
Specifies the region to extract. Negative values are relative to the size in that dimension, so -1 refers to the last element. For 2D zones omit kmin and kmax. For 1D zones omit jmin, jmax, kmin, and kmax.
ghosts: int[]
Numer of ghost/rind planes for the new zone. If None the existing specification is used.
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’).
promote()[source]

Promote from N-dimensional to N+1 dimensional index space.

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.
ghosts

Number of ghost/rind planes for each index direction.

real_shape[source]

Data index limits, including any ‘ghost/rind’ planes.

shape[source]

Data index limits, not including ‘ghost/rind’ planes.

zone.py

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

Bases: object

One zone in a possibly multi-zone DomainObj.

copy()[source]

Returns a deep copy of self.

demote()[source]

Demote from N-dimensional to N-1 dimensional index space.

extend(axis, delta, grid_points, flow_points, normal=None)[source]

Construct a new Zone by linearly extending the grid and replicating the flow. Symmetry data is copied.

axis: ‘i’, ‘j’, or ‘k’
Index axis to extend.
delta: float.
Fractional amount to move for each point. Multiplies the ‘edge’ delta in the axis direction or the appropriate component of normal. A negative value adds points before the current zero-index of axis.
grid_points: int >= 0
Number of points to add in axis dimension.
flow_points: int >= 0
Number of points to add in axis dimension.
normal: float[]
For cases where only a single point exists in the axis direction, this specifies the direction to move. If not specified, an axis-aligned direction is selected based on minimum grid extent.
extract(imin, imax, jmin=None, jmax=None, kmin=None, kmax=None, grid_ghosts=None, flow_ghosts=None)[source]

Construct a new Zone from grid and flow data extracted from the specified region. Symmetry data is copied.

imin, imax, jmin, jmax, kmin, kmax: int
Specifies the region to extract neglecting ghost/rind planes. Negative values are relative to the size in that dimension, so -1 refers to the last element. For 2D zones omit kmin and kmax. For 1D zones omit jmin, jmax, kmin, and kmax.
grid_ghosts: int[]
The number of ghost/rind planes for the new zone’s grid. If None the grid’s existing specification is used.
flow_ghosts: int[]
The number of ghost/rind planes for the new zone’s flow solution. If None the flow’s existing specification is used.
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.

promote()[source]

Promote from N-dimensional to N+1 dimensional index space.

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]

Coordinate ranges, not including ‘ghost/rind’ planes.

shape[source]

Coordinate index limits, not including ‘ghost/rind’ planes.

OpenMDAO Home

Table Of Contents

Previous topic

Package openmdao.gui

Next topic

Package openmdao.main

This Page