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.
Bases: openmdao.main.arch.Architecture
Bi-Level Integrated Systems Synthesis architecture
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.
Bases: openmdao.main.component.Component
Used to create outputs in the SubSytemOpt assembly.
Bases: openmdao.main.component.Component
Component which adds the weight factors for each output state variable for a given subsystem.
subsystem objective
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.
Implementation of the Collaborative Optimization Architecture
Bases: openmdao.main.arch.Architecture
Switch to decide between EI or PI for infill criterion.
Number of initial training points to use.
EI or PI to use for stopping condition of optimization.
Number of adaptively sampled points to use.
Bases: openmdao.main.arch.Architecture
Architecture that uses a single top level optimizer, enforcing consistency with equality constraints.
Script to run all Architectures in openmdao.lib.architectures against all OptProblems in openmdao.lib.optproblems.
Builds a list of architectures.
Builds a list of optproblems.
Runs all the architectures against all the test problems. A console script runs this function.
Runs the architectures against optproblems and records the results.
A central place to access all of the OpenMDAO case recorders, case iterators, and case filters in the standard library.
Bases: object
A CaseRecorder/CaseIterator containing Cases having the same set of input/output strings but different data. Cases are not necessarily unique.
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.
Return a new CaseSet with Cases that are common to this and all others.
Return True if this CaseSet has no Cases in common with the given CaseSet.
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.
Post-processing function that takes a case_data_set and outputs a csv file
Post-processing function that takes a case_data_set and outputs a csv file. Should be able to pass tests of current csv case recorder (column ordering, meta column, etc...) Assume query by case (not variable).
Inputs:
data - results of fetch on Query object
A CaseRecorder and CaseIterator that store the cases in a CSV file.
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.
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.
Bases: object
Stores cases in a csv file. Defaults to cases.csv.
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.
Store the case in a csv file. The format for a line of data follows:
Field 1 - timestamp 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 - uuid Field i+j+7 - parent_uuid Field i+j+8 - msg
A CaseRecorder and CaseIterator that store the cases in a relational DB (Python’s sqlite.)
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.
Bases: object
Records Cases to a relational DB (sqlite). Values other than floats, ints or strings are pickled and are opaque to SQL queries.
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.
Based on command line options, display an XY plot using data from a sqlite Case DB.
Display an XY plot using Case data from a sqlite DB.
Bases: object
Dumps cases in a “pretty” form to out, which may be a string or a file-like object (defaults to stdout). If out is stdout or stderr, then that standard stream is used. Otherwise, if out is a string, then a file with that name will be opened in the current directory. If out is None, cases will be ignored.
Closes out unless it’s sys.stdout or sys.stderr. Note that a closed recorder will do nothing in record().
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.
Doesn’t really make sense to have a case iterator for dump files, so just return None.
Case filters provide a means to select cases based on their index in the sequence of cases or the case data values.
Bases: object
Select based on a boolean Python expression of the case data or seqno. Case data is accessed by case['name']
Bases: object
Select based on an iterator of case numbers.
Bases: openmdao.lib.casehandlers.filters.IteratorCaseFilter
Select based on a sequence of case numbers.
Bases: openmdao.lib.casehandlers.filters.IteratorCaseFilter
Select based on start, stop, and step of case numbers.
JSON/BSON Case Recording.
Bases: openmdao.lib.casehandlers.jsoncase._BaseRecorder
Dumps a run in BSON form to out, which may be a string or a file-like object. If out is a string, then a file with that name will be opened in the current directory. If out is None, cases will be ignored.
The resulting file can be read by code similar to this:
from bson import loads
from pprint import pprint
from struct import unpack
import sys
sep = '-'*60
with open(sys.argv[1], 'rb') as inp:
reclen = unpack('<L', inp.read(4))[0]
data = inp.read(reclen)
obj = loads(data) # simulation_info
pprint(obj)
print sep
data = inp.read(4)
while data:
reclen = unpack('<L', data)[0]
data = inp.read(reclen)
obj = loads(data) # driver_info or iteration_case
pprint(obj)
print sep
data = inp.read(4)
Bases: openmdao.lib.casehandlers.jsoncase._BaseRecorder
Dumps a run in JSON form to out, which may be a string or a file-like object (defaults to stdout). If out is stdout or stderr, then that standard stream is used. Otherwise, if out is a string, then a file with that name will be opened in the current directory. If out is None, cases will be ignored.
A Case Iterator and CaseRecorder that stores the cases in a list.
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.
Bases: object
Stores cases in a list.
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.
Bases: object
Reads case data from filename and allows queries on it. format should be bson or json, indicating a BSONCaseRecorder file or JSONCaseRecorder file respectively.
To get all case data:
cds = CaseDataset('recorded.json', 'json')
cases = cds.data.fetch()
To get names of columns returned:
names = cds.data.var_names().fetch()
To select a specific set of variables:
cases = cds.data.vars(['top.sub.comp.x, top.sub.comp.y']).fetch()
To get a case and all its child cases:
cases = cds.data.parent_case(parent_id).fetch()
To get cases for a particular driver:
cases = cds.data.driver(driver_name).fetch()
To get cases for a particular run of a particular driver:
cases = cds.data.parent_case(parent_id).driver(driver_name).fetch()
or:
cases = cds.data.driver(driver_name).parent_case(parent_id).fetch()
Other possibilities exist, see Query.
To restore from the last recorded case:
cds.restore(assembly, cds.data.fetch()[-1]['_id'])
Bases: list
List that can be indexed by index or ‘var_name’.
Bases: list
Simply a list that allows us to save a reference to the original CaseDataSet.
Bases: object
Retains query information for a CaseDataset. All methods other than fetch() and write() return self, so operations are easily chained. If the same method is called more than once, only the last call has an effect.
Have fetch() return data as [var][case] rather than the default of [case][var].
Restrict the variables returned to only those in the specific driver’s local set. This means that if there are cases from more than one driver, variables not local to that driver will be set to NaN.
Write filtered CaseDataset to out, a filename or file-like object. Default format is the format of the original data file.
Pseudo package providing a central place to access all of the OpenMDAO components in the standard library.
Bases: openmdao.main.component.Component
Takes inputs and passes them directly to outputs to be broadcast out to other components.
Names of the variables you want to broadcast from this component.
Name/type pairs describing the variable types of each broadcast variable; ‘default’ name is used if no other type is set explicitly.
Expected Improvement calculation for single objective.
Bases: openmdao.main.component.Component
Expected Improvement calculation for single objective.
The Normal Distribution of the predicted value for some function at some point where you wish to calculate the EI.
Current objective minimum.
The expected improvement of the predicted_value in current.
The probability of improvement of the predicted_value in current.
Expected Improvement calculation for multiple objectives.
Bases: openmdao.main.component.Component
Expected Improvement calculation for multiple objectives.
Switch to use either probability (PI) or expected (EI) improvement.
The NormalDistributions for each response at a location where you wish to calculate EI.
Number of Monte Carlo Samples with which to calculate probability of improvement.
Array of Pareto-optimal cases.
The expected improvement of the next_case.
The probability of improvement of the next_case.
Bases: openmdao.main.component.Component
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.
Environment variables required by the command.
Delay between polling for command completion. A value of zero will use an internally computed default.
Resources required to run this component.
Maximum time to wait for command completion. A value of zero implies an infinite wait.
Return code from the command.
True if the command timed-out.
The command to be executed.
Check that all ‘specific’ input or output external files exist. If an external file path specifies a pattern, it is not checked.
Copy inputs from inputs_dir that match patterns.
This can be useful for resetting problem state.
Copy files from results_dir that match patterns.
This can be useful for workflow debugging when the external code takes a long time to execute.
Runs the specified command.
- Checks that all external input files exist.
- Runs the command.
- 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.
Don’t allow setting of ‘command’ or ‘resources’ by a remote client.
Bases: openmdao.main.component.Component
Slot for a parametric geometry.
When set to True, component will automatically execute whenever any input values are changed
Bases: openmdao.main.component.Component
Takes two Float inputs and provides n Float outputs with a linear variation between them. Units can be optionally provided. If use_array is True (default), then the output is an array. Otherwise, the output will be a set of separate variables
MetaModel is a class which supports generalized meta modeling (a.k.a. surrogate modeling) capabilities. The Metamodel can be used to create a reduced order (and faster) respresentation of any input-output relationship in your model. The inputs to a metamodel are called params, and the outputs are called responses. When you instantiate a metamodel, you give it a tuple of params and a tuple of responses that you want it to model.
Let’s start by creating an assembly with a component (the BraninComponent) and a metamodel of its response with respect to its two inputs.
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):
#component has two inputs (x, y) and one output (f_xy)
self.add('model', BraninComponent())
self.model.x = 9.
self.model.y = 9.
#create meta_model for f_xy as the response
self.add('meta_model', MetaModel(params=('x', 'y'),
responses=('f_xy')))
Metamodel contains a slot, called default_surrogate, which can be filled with a surrogate model generator instance. Copies of this default surrogate model generator will be used for any outputs that don’t have a specific surrogate model generator associated with them.
You can also associate a surrogate model generator with a specific output by finding that output’s key in the dictionary named surrogates and assigning the specific surrogate model there. All surrogate model generators must implement the ISurrogate interface. OpenMDAO provides some surrogate model generators in the openmdao.lib.surrogatemodels directory.
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):
#component has two inputs (x, y) and one output (f_xy)
self.add('model', BraninComponent())
self.model.x = 9
self.model.y = 9
#create meta_model for f_xy as the response
self.add('meta_model', MetaModel(params=('x', 'y'),
responses=('f_xy')))
#The meta_model contains a dictionary named 'surrogates' whose keys are
#the variable names, and whose values are slots where a surrogate
#model instance can be filled. In this case we'll just put
#another KrigingSurrogate in there, just to show how it's done.
#Since the default_surrogate is also a KrigingSurrogate, this
#will give us the same results we would have had if we'd only
#used the default_surrogate.
# use Kriging for the f_xy output
self.meta_model.surrogates['f_xy'] = KrigingSurrogate()
Now you have set up your MetaModel with a specific surrogate model, and you have put a model into the model slot. The next step is to actually start training and executing the MetaModel in simulations.
When you create a MetaModel instance, a selection of input and output variables are created based on the names you give it in the params and responses tuples. These variables allow you to operate the metamodel in training and prediction.
For training, a Metamodel is created with two variables trees params and responses, which contain inputs for all of the params and responses that were specified when instantiated. You can connect these variables to some other component (like a DOEDriver) that provides a list of training points. Each training point in the list is a list of the values of all the params or responses.
For prediction, a Metamodel is also created with input and output variables that match the params and responses that were specified. Once a MetaModel has been trained, it will run in predict mode, and predict its outputs based on what is passed into the input variables.
from openmdao.main.api import Assembly
from openmdao.lib.components.api import MetaModel
from openmdao.lib.doegenerators.api import FullFactorial
from openmdao.lib.drivers.api import DOEdriver
from openmdao.lib.optproblems.branin import BraninComponent
from openmdao.lib.surrogatemodels.api import KrigingSurrogate
class Simulation(Assembly):
def configure(self):
#component has two inputs (x, y) and one output (f_xy)
self.add('model', BraninComponent())
self.model.x = 9
self.model.y = 9
#create meta_model for f_xy as the response
self.add('meta_model', MetaModel(params=('x', 'y'),
responses=('f_xy')))
# use Kriging for the f_xy output
self.meta_model.surrogates['f_xy'] = KrigingSurrogate()
# Generate training data for the meta_model
self.add("DOE_Trainer", DOEdriver())
self.DOE_Trainer.DOEgenerator = FullFactorial()
self.DOE_Trainer.DOEgenerator.num_levels = 25
self.DOE_Trainer.add_parameter("model.x", low=0, high=20)
self.DOE_Trainer.add_parameter("model.y", low=0, high=20)
self.DOE_Trainer.add_response('model.f_x')
# Pass training data to the meta model.
self.connect('DOE_Trainer.case_inputs.model.x', 'meta_model.params.x')
self.connect('DOE_Trainer.case_inputs.model.y', 'meta_model.params.y')
self.connect('DOE_Trainer.case_outputs.model.f_x', 'meta_model.responses.f_x')
# Iteration Hierarchy
self.driver.workflow.add(['DOE_Trainer','model'])
self.DOE_Trainer.workflow.add('model')
The first time a MetaModel runs, it trains using the data in the params and responses variable trees, and then predicts a new response. Thereafter, it always predicts. However, if new training data is passed in, then it will train on the new data, and predict. 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.
Metamodel provides basic Meta Modeling capability.
Bases: openmdao.main.component.Component
Class that creates a reduced order model for a tuple of outputs from a tuple of inputs. Accepts surrogate models that adhere to ISurrogate. Multiple surrogate models can be used. Training inputs and outputs should be provided in the params and responses variable trees.
For a Float variable, the training data is an array of length m.
This surrogate will be used for all outputs that don’t have a specific surrogate assigned to them in their sur_<name> slot.
Records training cases
When set to False (default), the metamodel retrains with the new dataset whenever the training data values are changed. When set to True, the new data is appended to the old data and all of the data is used to train.
surrogates for output variables
Bases: openmdao.main.component.Component
Takes one List input and splits it into n indvidual outputs. This is a logical demultiplexer.
number of items in the array to be demultiplexed
Bases: openmdao.main.component.Component
Takes in n inputs and exports a length n List with the data. It is a logical multiplexer.
number of inputs to be multiplexed
Pareto Filter – finds non-dominated cases.
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.
You must pass a tuple of responses into the constructor. You can also optionally pass a tuple of params if you want ParetoFilter to keep track of the inputs for the nondominated responses.
VarTree of minus-definition constraints (<=0 means constaint satisfied) used to filter cases following the rule that satifisfied is better than unsatisfied and small unstatisfied constraint value is better than greater one, regardless of objective function values.Optional if None
Array of input values in the Pareto frontier
Array of constraints values in the Pareto frontier
Array of response values in the Pareto frontier
well. Sleep.
Useful for slowing down a simulation to see what is happening
Bases: openmdao.main.component.Component
Sleep for a given number of secons
The number of seconds to sleep
Pseudo package providing a central place to access all of the OpenMDAO doegenerators in the standard library.
DOEgenerator that performs a central composite Design of Experiments. Plugs into the DOEgenerator socket on a DOEdriver.
Bases: openmdao.main.container.Container
DOEgenerator that performs a central composite Design of Experiments. Plugs into the DOEgenerator socket on a DOEdriver.
Number of independent parameters in the DOE.
Type of central composite design
Bases: openmdao.main.container.Container
DOEgenerator that returns rows in a CSV file. Plugs into the DOEgenerator socket on a DOEdriver.
Name of CSV file.
Expected number of parameters in the DOE
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.
Bases: openmdao.main.container.Container
DOEgenerator that performs a full-factorial Design of Experiments. Plugs into the DOEgenerator socket on a DOEdriver.
Number of levels of values for each parameter.
Number of independent parameters in the DOE.
The OptLatinHypercube component implements an algorithm that produces an optimal Latin hypercube based on an evolutionary optimization of its Morris-Mitchell sampling criterion.
Bases: object
Bases: openmdao.main.container.Container
IDOEgenerator which provides a Latin hypercube DOE sample set.
Random seed for the optimizer. Set to a specific value for repeatable results; otherwise leave as None for truly random seeding.
Number of parameters, or dimensions, for the DOE.
Number of sample points in the DOE sample set.
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.
Random seed for the optimizer. Set to a specific value for repeatable results; otherwise leave as None for truly random seeding.
Number of generations the optimization will evolve over.
Vector norm calculation method. ‘1-norm’ is faster but less accurate.
Number of parameters, or dimensions, for the DOE.
Number of sample points in the DOE sample set.
Size of the population used in the evolutionary optimization.
Returns True if the given array is a Latin hypercube. The given array is assumed to be a numpy array.
Calculates a random Latin hypercube set of n points in k dimensions within [0,1]^k hypercube.
Returns an n by k numpy array.
DOEgenerator that performs a uniform space-filling Design of Experiments. Plugs into the DOEgenerator socket on a DOEdriver.
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.
Number of independent parameters in the DOE.
Number of total samples in the DOE.
The AdaptiveSampleDriver behaves like a DOEDriver for the first iteration and a CaseIteratorDriver thereafter.
Bases: openmdao.lib.drivers.doedriver.DOEdriver
Solver based on scipy.optimize.brentq
Bases: openmdao.main.driver.Driver
Root finding using Brent’s method.
user supplied function to handle resizing bracket. Form of function is: lower_new, upper_new, continue = f_resize_bracket(lower, upper, iteration) inputs include the current lower and upper bracket and the current iteration count starting from 1. Outputs include a new lower and upper bracket, and a boolean flag on whether or not to terminate calling resize bracket
user supplied value to handle what value should be returned when a suitable bracket cannot be found. sets the “zero” as a linear combination of the lower and upper brackets. Must be between 0 and 1 or an error will be thrown. root = lower + invalid_bracket_return*(upper-lower)
Set to 1 to print out itercount and residual.
lower bound for the root search
if convergence is not achieved in maxiter iterations, and error is raised. Must be >= 0.
The routine converges when a root is known to lie within rtol times the value returned of the value returned. Should be >= 0. Defaults to np.finfo(float).eps * 2.
upper bound for the root search
The routine converges when a root is known to lie within xtol of the value return. Should be >= 0. The routine modifies this to take into account the relative precision of doubles.
Adds a constraint in the form of a boolean expression string to the driver.
Adds an existing Constraint object to the driver.
constraint: Constraint object
Adds a parameter or group of parameters to the driver.
If neither “low” nor “high” is specified, the min and max will default to the values in the metadata of the variable being referenced.
Removes all constraints.
Removes all parameters.
Reconfigure parameters from potentially changed targets.
Returns a copy of our constraints dict.
Returns a list of constraint values.
Return evaluated parameter values.
Returns an ordered dict of constraint objects
Returns an ordered dict of constraint objects.
Return fd_step values, they may include None.
Return lower bound values.
Returns an ordered dict of parameter objects.
Return upper bound values.
Sets all parameters to their start value if a start value is given
Return a list of strings containing constraint expressions.
Returns a list of outputs suitable for calc_gradient().
Returns a list of tuples that contain the targets for each parameter group.
Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter, ParameterGroup, and ArrayParameter objects since ParameterGroup instances have multiple targets.
Removes the constraint with the given string.
Removes the parameter with the given name.
Sets a single parameter by its name attribute.
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.
Returns the total number of constraint values.
Returns the total number of values to be set.
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", desc="Input 1")
y = Float(10.0, iotype="in", desc="Input 2")
f_xy = Float(0.0, iotype="out", desc="Output 1")
g_xy = Float(0.0, iotype="out", desc="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.
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"
This parameter specifies the maximum number of iterations before BroydenSolver terminates. The default value is 10.
self.driver.itmax = 10
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
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
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
Solver based on the nonlinear solvers found in Scipy.Optimize.
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.
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.
Algorithm to use. Choose from broyden2, broyden3, and excitingmixing.
Mixing Coefficient.
Maximum Mixing Coefficient (only used with excitingmixing.)
Maximum number of iterations before termination.
Convergence tolerance. If the norm of the independent vector is lower than this, then terminate successfully.
Adds a constraint in the form of a boolean expression string to the driver.
Adds an existing Constraint object to the driver.
constraint: Constraint object
Adds a parameter or group of parameters to the driver.
If neither “low” nor “high” is specified, the min and max will default to the values in the metadata of the variable being referenced.
Removes all constraints.
Removes all parameters.
Reconfigure parameters from potentially changed targets.
Returns a copy of our constraints dict.
Returns a list of constraint values.
Return evaluated parameter values.
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.
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.
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.
Returns an ordered dict of constraint objects
Returns an ordered dict of constraint objects.
Return fd_step values, they may include None.
Return lower bound values.
Returns an ordered dict of parameter objects.
Return upper bound values.
Sets all parameters to their start value if a start value is given
Return a list of strings containing constraint expressions.
Returns a list of outputs suitable for calc_gradient().
Returns a list of tuples that contain the targets for each parameter group.
Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter, ParameterGroup, and ArrayParameter objects since ParameterGroup instances have multiple targets.
Removes the constraint with the given string.
Removes the parameter with the given name.
Sets a single parameter by its name attribute.
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.
Returns the total number of constraint values.
Returns the total number of values to be set.
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.
Bases: openmdao.main.driver.Driver
A base class for Drivers that run sets of cases. Concurrent evaluation is supported, with the various evaluations executed across servers obtained from the ResourceAllocationManager.
If ABORT, any error stops the evaluation of the whole set of cases.
Extra resource requirements (unusual).
If True, no distribution or orphan requirements will be included in the generated egg.
Maximum number of times to retry a failed case.
If True, reload the model between executions.
If True, evaluate cases sequentially.
Adds a parameter or group of parameters to the driver.
Adds a response to the driver.
Takes an iterator of response strings and creates responses for them in the driver.
Removes all parameters.
Removes all responses.
Reconfigure parameters from potentially changed targets.
Return evaluated parameter values.
Returns the value of response name.
Returns a list of values of the evaluated responses.
Runs all cases and records results in recorder. Uses setup() and resume() with default arguments.
Return fd_step values, they may include None.
Return lower bound values.
Returns an ordered dict of parameter objects.
Returns an OrderedDict of response expressions.
Return upper bound values.
Sets all parameters to their start value if a start value is given
Initializes response storage in the driver.
Returns a list of tuples that contain the targets for each parameter group.
Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter, ParameterGroup, and ArrayParameter objects since ParameterGroup instances have multiple targets.
Returns a list of outputs suitable for calc_gradient().
Removes the parameter with the given name.
Removes the specified response expression. Spaces within the expression are ignored.
Sets a single parameter by its name attribute.
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.
Returns the total number of values to be set.
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.
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).
Fortran output unit. Leave this at 6 for STDOUT.
Controls the frequency of output: 0 (no output),1,2,3.
Maximum number of function evaluations.
Name of output file (if iout not 6).
Reasonable initial changes to the variables.
Final accuracy in the optimization (not precisely guaranteed).
Error code returned from COBYLA.
Adds a constraint in the form of a boolean expression string to the driver.
Adds an existing Constraint object to the driver.
constraint: Constraint object
Adds an objective to the driver.
Takes an iterator of objective strings and creates objectives for them in the driver.
Adds a parameter or group of parameters to the driver.
If neither “low” nor “high” is specified, the min and max will default to the values in the metadata of the variable being referenced.
Removes all constraints.
Removes all objectives.
Removes all parameters.
Reconfigure parameters from potentially changed targets.
Returns a copy of our constraints dict.
Returns a list of constraint values.
Returns the value of objective name.
Returns a list of values of the evaluated objectives.
Returns a list of values of the evaluated objectives.
Return evaluated parameter values.
Returns an ordered dict of constraint objects
Return fd_step values, they may include None.
Returns an ordered dict of inequality constraint objects.
Return lower bound values.
Returns an OrderedDict of objective expressions.
Returns an ordered dict of parameter objects.
Return upper bound values.
Sets all parameters to their start value if a start value is given
Return a list of strings containing constraint expressions.
Returns a list of outputs suitable for calc_gradient().
Returns a list of outputs suitable for calc_gradient().
Returns a list of tuples that contain the targets for each parameter group.
Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter, ParameterGroup, and ArrayParameter objects since ParameterGroup instances have multiple targets.
Removes the constraint with the given string.
Removes the specified objective expression. Spaces within the expression are ignored.
Removes the parameter with the given name.
Sets a single parameter by its name attribute.
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.
Returns the total number of inequality constraint values.
Returns the total number of values to be set.
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, or you do not wish to use OpenMDAO’s gradient calculation, then you can use CONMIN’s internal finite difference code to calculate the gradient. 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:
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
By default, OpenMDAO calculates the gradient and provides it to CONMIN. However, you may want to use CONMIN’s internal finite-difference to calculate the gradient. This can be done by setting the conmin_diff flag to True.
self.conmin_diff = True
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.
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, an 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.
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.
Bases: openmdao.main.driver.Driver
Driver wrapper of Fortran version of CONMIN.
0: Initial and final state
1: Initial evaluation of objective and constraint values
2: Evaluate gradients of objective and constraints (internal only)
3: Evaluate gradients of objective and constraints
4: One-dimensional search on unconstrained function
5: Solve 1D search problem for unconstrained function
Set to True to let CONMINcalculate the gradient.
Array designating whether each constraint is linear.
Constraint thickness parameter.
Constraint thickness parameter for linear and side constraints.
Minimum absolute value of ctl used in optimization.
Minimum absolute value of ct used in optimization.
Absolute convergence tolerance.
Relative convergence tolerance.
Relative change in parameters when calculating finite difference gradients (only when CONMIN calculates gradient).
Minimum absolute step in finite difference gradient calculations (only when CONMIN calculates gradient).
Conjugate gradient restart. parameter.
Print information during CONMIN solution. Higher values are more verbose. 0 suppresses all output.
Maximum number of iterations before termination.
Number of consecutive iterations to indicate convergence (relative or absolute).
Linear objective function flag. Set to True if objective is linear.
Participation coefficient - penalty parameter that pushes designs towards the feasible region.
Mean value of the push-off factor in the method of feasible directions.
Adds a constraint in the form of a boolean expression string to the driver.
Adds an existing Constraint object to the driver.
constraint: Constraint object
Adds an objective to the driver.
Takes an iterator of objective strings and creates objectives for them in the driver.
Adds a parameter or group of parameters to the driver.
If neither “low” nor “high” is specified, the min and max will default to the values in the metadata of the variable being referenced.
Removes all constraints.
Removes all objectives.
Removes all parameters.
Reconfigure parameters from potentially changed targets.
Returns a copy of our constraints dict.
Returns a list of constraint values.
Returns the value of objective name.
Returns a list of values of the evaluated objectives.
Returns a list of values of the evaluated objectives.
Return evaluated parameter values.
Returns an ordered dict of constraint objects
Return fd_step values, they may include None.
Returns an ordered dict of inequality constraint objects.
Return lower bound values.
Returns an OrderedDict of objective expressions.
Returns an ordered dict of parameter objects.
Return upper bound values.
Sets all parameters to their start value if a start value is given
Return a list of strings containing constraint expressions.
Returns a list of outputs suitable for calc_gradient().
Returns a list of outputs suitable for calc_gradient().
Returns a list of tuples that contain the targets for each parameter group.
Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter, ParameterGroup, and ArrayParameter objects since ParameterGroup instances have multiple targets.
Removes the constraint with the given string.
Removes the specified objective expression. Spaces within the expression are ignored.
Removes the parameter with the given name.
Sets a single parameter by its name attribute.
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.
Returns the total number of inequality constraint values.
Returns the total number of values to be set.
Bases: openmdao.lib.drivers.caseiterdriver.CaseIteratorDriver
Driver for evaluating models at point distributions.
Iterator supplying values of point distribitions.
Bases: openmdao.main.container.Container
Generate the input cases for finite differences.
Form of finite difference used
Order of the finite differences
Set to True to skip running the baseline case.
The DOEdriver provides the capability to execute a DOE on a workflow. This Driver supports the IHasParameters and the IHasResponses interfaces. 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.) self.driver.add_response('branin.f_xy') #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.
doedriver.py – Driver that executes a Design of Experiments.
Bases: openmdao.lib.drivers.caseiterdriver.CaseIteratorDriver
Driver for Design of Experiments.
Iterator supplying normalized DOE values.
Name of CSV file to record to (default is <driver-name>.csv).
Record normalized DOE values to CSV file.
Bases: openmdao.lib.drivers.caseiterdriver.CaseIteratorDriver
Driver for Design of Experiments within a specified neighborhood around a point.
Iterator supplying normalized DOE values.
Multiplicative factor for neighborhood DOE Driver.
Another factor for neighborhood DOE Driver.
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"
A simple Pyevolve-based driver for OpenMDAO.
Bases: openmdao.main.driver.Driver
Genetic algorithm for the OpenMDAO framework, based on the Pyevolve Genetic algorithm module.
The genome with the best score from the optimization.
The crossover rate used when two parent genomes reproduce to form a child genome.
Controls the use of elitism in the creation of new generations.
The maximum number of generations the algorithm will evolve to before stopping.
The mutation rate applied to population members.
Sets the optimization to either minimize or maximize the objective function.
The size of the population in each generation.
Random seed for the optimizer. Set to a specific value for repeatable results; otherwise leave as None for truly random seeding.
The selection method used to pick population members who will survive for breeding into the next generation.
Adds an objective to the driver.
Takes an iterator of objective strings and creates objectives for them in the driver.
Adds a parameter or group of parameters to the driver.
If neither “low” nor “high” is specified, the min and max will default to the values in the metadata of the variable being referenced.
Removes all objectives.
Removes all parameters.
Reconfigure parameters from potentially changed targets.
Returns the value of objective name.
Returns a list of values of the evaluated objectives.
Returns a list of values of the evaluated objectives.
Return evaluated parameter values.
Return fd_step values, they may include None.
Return lower bound values.
Returns an OrderedDict of objective expressions.
Returns an ordered dict of parameter objects.
Return upper bound values.
Sets all parameters to their start value if a start value is given
Returns a list of outputs suitable for calc_gradient().
Returns a list of tuples that contain the targets for each parameter group.
Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter, ParameterGroup, and ArrayParameter objects since ParameterGroup instances have multiple targets.
Removes the specified objective expression. Spaces within the expression are ignored.
Removes the parameter with the given name.
Sets a single parameter by its name attribute.
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.
Returns the total number of values to be set.
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", desc="Input is x")
y = Float(iotype="out", desc="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.
This is a simple iteration driver that 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.
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.
Maximum number of iterations before termination.
Absolute convergence tolerance between iterations.
For multivariable iteration, type of norm to use to test convergence.
Adds a constraint in the form of a boolean expression string to the driver.
Adds an existing Constraint object to the driver.
constraint: Constraint object
Adds a parameter or group of parameters to the driver.
If neither “low” nor “high” is specified, the min and max will default to the values in the metadata of the variable being referenced.
Removes all constraints.
Removes all parameters.
Removes all stop conditions.
Reconfigure parameters from potentially changed targets.
Returns a copy of our constraints dict.
Returns a list of constraint values.
Return evaluated parameter values.
Returns a list of evaluated stop conditions.
Returns an ordered dict of constraint objects
Returns an ordered dict of constraint objects.
Return fd_step values, they may include None.
Return lower bound values.
Returns an ordered dict of parameter objects.
Returns a list of stop condition strings.
Return upper bound values.
Sets all parameters to their start value if a start value is given
Return a list of strings containing constraint expressions.
Returns a list of outputs suitable for calc_gradient().
Returns a list of tuples that contain the targets for each parameter group.
Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter, ParameterGroup, and ArrayParameter objects since ParameterGroup instances have multiple targets.
Removes the constraint with the given string.
Removes the parameter with the given name.
Removes the stop condition matching the given string.
Sets a single parameter by its name attribute.
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.
Return True if any of the stopping conditions evaluate to True.
Returns the total number of constraint values.
Returns the total number of values to be set.
Bases: openmdao.main.driver.Driver
A simple driver to run a workflow until some stop condition is met.
Maximum number of iterations.
If True, driver will ignore stop conditions for the first iteration and run at least one iteration.
Current iteration counter.
Removes all stop conditions.
Returns a list of evaluated stop conditions.
Returns a list of stop condition strings.
Removes the stop condition matching the given string.
Return True if any of the stopping conditions evaluate to True.
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, although it can also 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 NEWSUMTdriver
class EngineOptimization(Assembly):
""" Top level assembly for optimizing a vehicle. """
def configure(self):
""" Creates a new Assembly for vehicle performance optimization."""
# Create NEWSUMT Optimizer instance
self.add('driver', NEWSUMTdriver())
# Create Vehicle instance
self.add('vehicle', Vehicle())
# add Vehicle to optimizer workflow
self.driver.workflow.add('vehicle')
# NEWSUMT Flags
self.driver.iprint = 0
self.driver.itmax = 30
# NEWSUMT Objective
self.driver.add_objective('vehicle.fuel_burn')
# NEWSUMT 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. Presently, OpenMDAO’s built-in differentiation capability does not support second derivatives, so NEWSUMT’s gradient and Hessian calculation is the only available option.
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 |
newsumtdriver.py - Driver for the NEWSUMT optimizer.
Bases: openmdao.main.driver.Driver
Driver wrapper of Fortran version of NEWSUMT.
Todo
Check to see if this itmax variable is needed. NEWSUMT might handle it for us.
Default finite difference stepsize. Parameters with specified values override this.
Convergence criteria of the golden section algorithm used for the one dimensional minimization.
Convergence criteria of the unconstrained minimization.
Convergence criteria for the overall process.
Initial value of the transition parameter.
Array designating whether each constraint is linear.
Print information during NEWSUMT solution. Higher values are more verbose. If 0,print initial and final designs only.
Maximum number of iterations before termination.
Set to 1 if linear objective function.
Maximum allowable number of golden section iterations used for 1D minimization.
Maximum allowable number of one dimensional minimizations.
Maximum allowable number of unconstrained minimizations.
Flag for penalty multiplier. If 0, initial value computed by NEWSUMT. If 1, initial value set by ra.
Set to True to let NEWSUMTcalculate the gradient.
Penalty multiplier. Required if mflag=1
Penalty multiplier decrease ratio. Required if mflag=1.
Lower bound of penalty multiplier. Required if mflag=1.
Maximum bound imposed on the initial step size of the one-dimensional minimization.
Adds a constraint in the form of a boolean expression string to the driver.
Adds an existing Constraint object to the driver.
constraint: Constraint object
Adds an objective to the driver.
Takes an iterator of objective strings and creates objectives for them in the driver.
Adds a parameter or group of parameters to the driver.
If neither “low” nor “high” is specified, the min and max will default to the values in the metadata of the variable being referenced.
Removes all constraints.
Removes all objectives.
Removes all parameters.
Reconfigure parameters from potentially changed targets.
Returns a copy of our constraints dict.
Returns a list of constraint values.
Returns the value of objective name.
Returns a list of values of the evaluated objectives.
Returns a list of values of the evaluated objectives.
Return evaluated parameter values.
Returns an ordered dict of constraint objects
Return fd_step values, they may include None.
Returns an ordered dict of inequality constraint objects.
Return lower bound values.
Returns an OrderedDict of objective expressions.
Returns an ordered dict of parameter objects.
Return upper bound values.
Sets all parameters to their start value if a start value is given
Return a list of strings containing constraint expressions.
Returns a list of outputs suitable for calc_gradient().
Returns a list of outputs suitable for calc_gradient().
Returns a list of tuples that contain the targets for each parameter group.
Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter, ParameterGroup, and ArrayParameter objects since ParameterGroup instances have multiple targets.
Removes the constraint with the given string.
Removes the specified objective expression. Spaces within the expression are ignored.
Removes the parameter with the given name.
Sets a single parameter by its name attribute.
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.
Returns the total number of inequality constraint values.
Returns the total number of values to be set.
Newton solver based around Scipy’s fsolve method. More methods can be added.
Bases: openmdao.main.driver.Driver
Wrapper for some Newton style solvers. Currently supports fsolve from scipy.optimize.
Maximum number of iterations
Solution method (currently only fsolve from scipy optimize)
Global convergence tolerance
Adds a constraint in the form of a boolean expression string to the driver.
Adds an existing Constraint object to the driver.
constraint: Constraint object
Adds a parameter or group of parameters to the driver.
If neither “low” nor “high” is specified, the min and max will default to the values in the metadata of the variable being referenced.
Removes all constraints.
Removes all parameters.
Reconfigure parameters from potentially changed targets.
Returns a copy of our constraints dict.
Returns a list of constraint values.
Return evaluated parameter values.
Returns an ordered dict of constraint objects
Returns an ordered dict of constraint objects.
Return fd_step values, they may include None.
Return lower bound values.
Returns an ordered dict of parameter objects.
Return upper bound values.
Sets all parameters to their start value if a start value is given
Return a list of strings containing constraint expressions.
Returns a list of outputs suitable for calc_gradient().
Returns a list of tuples that contain the targets for each parameter group.
Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter, ParameterGroup, and ArrayParameter objects since ParameterGroup instances have multiple targets.
Removes the constraint with the given string.
Removes the parameter with the given name.
Sets a single parameter by its name attribute.
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.
Returns the total number of constraint values.
Returns the total number of values to be set.
sensitivity.py – Driver to calculate the gradient of a workflow and return it as a driver output. OpenMDAO’s gradient capability is utilized.
Bases: openmdao.main.driver.Driver
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 requires OpenMDAO to calculate a gradient. Fake Finite Difference is supported.
Objective baseline values where sensitivity is evaluated.
Constraint baseline values where sensitivity is evaluated.
Sensitivity of the objectives with respect to the parameters. Index 1 is the objective output, while index 2 is the parameter input.
Objective names that correspond to our array indices.
Sensitivity of the constraints with respect to the parameters. Index 1 is the constraint output, while index 2 is the parameter input.
Constraint names that correspond to our array indices.
Parameter names that correspond to our array indices.
Parameter baseline values where sensitivity is evaluated.
Adds a constraint in the form of a boolean expression string to the driver.
Adds an existing Constraint object to the driver.
constraint: Constraint object
Adds an objective to the driver.
Takes an iterator of objective strings and creates objectives for them in the driver.
Adds a parameter or group of parameters to the driver.
If neither “low” nor “high” is specified, the min and max will default to the values in the metadata of the variable being referenced.
Removes all constraints.
Removes all objectives.
Removes all parameters.
Reconfigure parameters from potentially changed targets.
Returns a list of constraint values.
Returns a list of constraint values.
Returns a list of constraint values.
Returns the value of objective name.
Returns a list of values of the evaluated objectives.
Return evaluated parameter values.
Returns an ordered dict of constraint objects
Returns an ordered dict of equality constraint objects.
Return fd_step values, they may include None.
Returns an ordered dict of inequality constraint objects.
Return lower bound values.
Returns an OrderedDict of objective expressions.
Returns an ordered dict of parameter objects.
Return upper bound values.
Sets all parameters to their start value if a start value is given
Returns a list of outputs suitable for calc_gradient().
Return a list of strings containing constraint expressions.
Returns a list of outputs suitable for calc_gradient().
Returns a list of outputs suitable for calc_gradient().
Returns a list of outputs suitable for calc_gradient().
Returns a list of tuples that contain the targets for each parameter group.
Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter, ParameterGroup, and ArrayParameter objects since ParameterGroup instances have multiple targets.
Removes the constraint with the given string.
Removes the specified objective expression. Spaces within the expression are ignored.
Removes the parameter with the given name.
Sets a single parameter by its name attribute.
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.
Returns the total number of constraint values.
Returns the total number of equality constraint values.
Returns the total number of inequality constraint values.
Returns the total number of values to be set.
A simple driver that runs cases from a CaseIterator and records them with a CaseRecorder.
Bases: openmdao.main.driver.Driver
A Driver that sequentially runs each parameter set. This is intended for test cases or very simple models only. For a more full-featured Driver with similar functionality, see CaseIteratorDriver.
Adds a parameter or group of parameters to the driver.
Adds a response to the driver.
Takes an iterator of response strings and creates responses for them in the driver.
Removes all parameters.
Removes all responses.
Reconfigure parameters from potentially changed targets.
Return evaluated parameter values.
Returns the value of response name.
Returns a list of values of the evaluated responses.
Return fd_step values, they may include None.
Return lower bound values.
Returns an ordered dict of parameter objects.
Returns an OrderedDict of response expressions.
Return upper bound values.
Sets all parameters to their start value if a start value is given
Initializes response storage in the driver.
Returns a list of tuples that contain the targets for each parameter group.
Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter, ParameterGroup, and ArrayParameter objects since ParameterGroup instances have multiple targets.
Returns a list of outputs suitable for calc_gradient().
Removes the parameter with the given name.
Removes the specified response expression. Spaces within the expression are ignored.
Sets a single parameter by its name attribute.
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.
Returns the total number of values to be set.
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.
Bases: openmdao.main.driver.Driver
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).
Convergence accuracy
Fortran output unit. Leave this at 6 for STDOUT.
Controls the frequency of output: 0 (no output),1,2,3.
Maximum number of iterations.
Name of output file (if iout not 6).
Error code returned from SLSQP.
Adds a constraint in the form of a boolean expression string to the driver.
Adds an existing Constraint object to the driver.
constraint: Constraint object
Adds an objective to the driver.
Takes an iterator of objective strings and creates objectives for them in the driver.
Adds a parameter or group of parameters to the driver.
If neither “low” nor “high” is specified, the min and max will default to the values in the metadata of the variable being referenced.
Removes all constraints.
Removes all objectives.
Removes all parameters.
Reconfigure parameters from potentially changed targets.
Returns a list of constraint values.
Returns a list of constraint values.
Returns a list of constraint values.
Returns the value of objective name.
Returns a list of values of the evaluated objectives.
Returns a list of values of the evaluated objectives.
Return evaluated parameter values.
Returns an ordered dict of constraint objects
Returns an ordered dict of equality constraint objects.
Return fd_step values, they may include None.
Returns an ordered dict of inequality constraint objects.
Return lower bound values.
Returns an OrderedDict of objective expressions.
Returns an ordered dict of parameter objects.
Return upper bound values.
Sets all parameters to their start value if a start value is given
Returns a list of outputs suitable for calc_gradient().
Return a list of strings containing constraint expressions.
Returns a list of outputs suitable for calc_gradient().
Returns a list of outputs suitable for calc_gradient().
Returns a list of outputs suitable for calc_gradient().
Returns a list of tuples that contain the targets for each parameter group.
Returns a list of parameter targets. Note that this list may contain more entries than the list of Parameter, ParameterGroup, and ArrayParameter objects since ParameterGroup instances have multiple targets.
Removes the constraint with the given string.
Removes the specified objective expression. Spaces within the expression are ignored.
Removes the parameter with the given name.
Sets a single parameter by its name attribute.
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.
Returns the total number of constraint values.
Returns the total number of equality constraint values.
Returns the total number of inequality constraint values.
Returns the total number of values to be set.
Bases: object
A static (non-parametric) box geometry.
Bases: openmdao.main.geom.ParametricGeometry
A simple parametric geometry (a box)
Bases: object
FFD class for solid bodies which only have one surface
Bases: object
transforms points from Cartesian space to cylindrical space and vice versa
Bases: object
FFD class for shell bodies which have two connected surfaces
Bases: object
Manages the points extracted from an STL file
Bases: object
deforms the geometry applying the new locations for the control points, given by body name
Bases: openmdao.main.component.Component
Bases: openmdao.main.problem_formulation.OptProblem
Branin Test Problem Definition
Bases: openmdao.main.component.Component
Single polynomial component. Constructs and evaluates a polynomial constructed from variables sampled from the input array, X The variables sampled from X can be set on instancing (by setting the indices into X in the list idx). Otherwise, they will be selected randomly.
For example, if idx = [0,1], than the output F of this component is:
F = (X[0]-roots[0]) + (X[1]-roots[1]) + (X[0]-roots[0])*(X[1]-roots[1])
and will take the value of zero if the values of X match the corresponding root values.
Bases: openmdao.main.assembly.Assembly
Multivariable polynomial test problem
m : number of variables (also the number of components)
X : vector of variables. will be set by the solver
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.
Bases: openmdao.lib.optproblems.scalable.Discipline_No_Deriv
Add derivatives to the scalable problem.
Bases: openmdao.main.component.Component
Single discipline for the scalable problem.
Coefficient for the output variables.
Bases: openmdao.main.problem_formulation.OptProblem
Model that contains N scalable discipline. Output is scaled so that the values are 1.0
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.
Bases: openmdao.main.component.Component
Component containing Discipline 1.
Local Design Variable.
Disciplinary Coupling.
Global Design Variable.
Global Design Variable.
Output of this Discipline.
Bases: openmdao.main.component.Component
Component containing Discipline 1.
Local Design Variable.
Disciplinary Coupling.
Global Design Variable.
Global Design Variable.
Output of this Discipline.
Bases: openmdao.main.component.Component
Component containing Discipline 2.
Disciplinary Coupling.
Global Design Variable.
Global Design Variable.
Output of this Discipline.
Bases: openmdao.main.component.Component
Component containing Discipline 2.
Disciplinary Coupling.
Global Design Variable.
Global Design Variable.
Output of this Discipline.
Bases: openmdao.main.problem_formulation.OptProblem
Sellar test problem definition.
Bases: openmdao.main.problem_formulation.OptProblem
Sellar test problem definition using components analytical derivatives.
Pseudo package providing a central place to access all of the OpenMDAO surrogatemodels in the standard library.
Surrogate model based on Kriging.
Bases: openmdao.lib.surrogatemodels.kriging_surrogate.KrigingSurrogate
Surrogate model based on the simple Kriging interpolation. Predictions are returned as floats, which are the mean of the NormalDistribution predicted by the model.
Bases: openmdao.main.container.Container
Surrogate Modeling method based on the simple Kriging interpolation. Predictions are returned as a NormalDistribution instance.
Returns a NormalDistribution centered around the value, with a standard deviation of 0.
Surrogate Model based on a logistic regression model, with regularization to adjust for overfitting. Based on work from Python logistic regression.
Bases: openmdao.main.container.Container
L2 regularization strength.
Returns the value iself. Logistic regressions don’t have uncertainty.
Surrogate Model based on second order response surface equations.
Bases: openmdao.main.container.Container
Returns the value iself. Response surface equations don’t have uncertainty.
Pseudo package providing a central place to access all of the OpenMDAO datatypes in the standard library.
Bases: object
A DomainObj represents a (possibly multi-zoned) mesh and data related to that mesh.
Add zones from other to self, retaining names where possible.
Add a Zone. Returns the added zone.
Construct a new DomainObj from zones extended according to zone_args. Existing zone names are used for the new domain’s zones.
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.
Test if self and other are equivalent.
Convert to Cartesian coordinate system.
Convert to cylindrical coordinate system.
Remove a zone. Returns the removed zone.
Rename a zone.
Translate coordinates.
Bases: object
Contains solution variables for a Zone. All variables have the same shape and grid location.
Add a numpy.ndarray of scalar data and bind to name. Returns the added array.
Add a Vector and bind to name. Returns the added vector.
Construct a new FlowSolution by replication. The existing ghosts/rind planes specification is retained.
Construct a new FlowSolution from data extracted from the specified region.
Test if self and other are equivalent.
Convert to Cartesian coordinate system.
Convert to cylindrical coordinate system.
Number of ghost cells for each index direction.
Position at which data is located; must be one of (‘Vertex’, ‘CellCenter’)
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.
Construct a new GridCoordinates by linear extrapolation. The existing ghosts/rind planes specification is retained.
Construct a new GridCoordinates from data extracted from the specified region.
Test if self and other are equivalent.
Convert to Cartesian coordinate system.
Convert to cylindrical coordinate system.
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.
Bases: object
Computes area of mesh surface.
Bases: object
Computes corrected mass flow across a mesh surface.
Bases: object
Computes length of mesh curve.
Bases: object
Computes mass flow across a mesh surface.
Bases: object
Computes weighted static pressure for a mesh region.
Bases: object
Computes weighted static temperature for a mesh region.
Bases: object
Computes weighted total pressure for a mesh region.
Bases: object
Computes weighted total temperature for a mesh region.
Bases: object
Computes volume of mesh volume.
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.
Register a metric calculation class.
Functions to read and write a DomainObj in Plot3D format. Many function arguments are common:
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.
Returns a DomainObj initialized from Plot3D grid_file and f_file. Variables are assigned to names of the form f_N.
Returns a DomainObj initialized from Plot3D grid_file.
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’.
Returns a list of zone dimensions from Plot3D grid_file.
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.
Writes domain to grid_file in Plot3D format. Ghost data is not written.
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.
Support for calculating one or more scalar averages across one or more regions in a domain.
Calculate metrics on mesh regions. Currently only supports structured grids.
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.
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.
Construct a new Vector by replication.
Construct a new Vector from data extracted from the specified region.
Test if self and other are equivalent.
Convert to Cartesian coordinate system.
Convert to cylindrical coordinate system.
Number of ghost/rind planes for each index direction.
Bases: object
One zone in a possibly multi-zone DomainObj.
Construct a new Zone by linearly extending the grid and replicating the flow. Symmetry data is copied.
Construct a new Zone from grid and flow data extracted from the specified region. Symmetry data is copied.
Test if self and other are equivalent.
Convert to Cartesian coordinate system.
Convert to cylindrical coordinate system.
Translate coordinates.
Coordinate system in use.