def __init__(self, params=None, responses=None, nfi=1): super(MultiFiMetaModel, self).__init__(params, responses) self.nfi = nfi if self.nfi > 1: self._param_data = [[] for i in np.arange(self.nfi)] for name in responses: self._response_data[name] = [[] for i in np.arange(self.nfi)] self.add('default_surrogate', Slot(IMultiFiSurrogate, allow_none=True, desc="This surrogate will be used for all outputs that don't " "have a specific surrogate assigned to them in their sur_<name> slot.")) # Add params.<invar>_fi<n> for name in params: for n in np.arange(nfi): if n > 0: input_tree = self.get('params') name_with_fi = "%s_fi%d" % (name, n+1) self.add(name_with_fi, Float(0.0, iotype='in', desc='metamodel param')) input_tree.add(name_with_fi, List([], desc='training param')) # Add responses.<outvar>_fi<n> for name in responses: for n in np.arange(nfi): if n > 0: output_tree = self.get('responses') name_with_fi = "%s_fi%d" % (name, n+1) self.add(name_with_fi, Float(0.0, iotype='out', desc='metamodel response')) output_tree.add(name_with_fi, List([], desc='training response')) self.surrogates[name] = None
class VarComponent(Component): """Contains some vars""" boolvar = Bool(False, iotype='in') intvar = Int(333, iotype='in') floatvar = Float(-16.54, iotype='in') expvar1 = Float(1.2, iotype='in') expvar2 = Float(1.2, iotype='in') textvar = Str("This", iotype='in') arrayvar = Array(iotype='in') arrayvarsplit = Array(iotype='in') arrayvarsplit2 = Array(iotype='in') arrayvarzerod = Array(zeros(shape=(0, 0)), iotype='in') arrayvartwod = Array(zeros(shape=(1, 3)), iotype='in') arraysmall = Array(iotype='in') arrayshorthand = Array(iotype='in') single = Array(iotype='in') singleint = Array(iotype='in', dtype=numpy_int32) singlebool = Array(iotype='in', dtype=bool) stringarray = List([], iotype='in') listenumvar = List(Enum(1, (1, 2, 3)), iotype='in') listenumvar2 = List(Enum(1.5, (1.5, 2.4, 3.3)), iotype='in') listenumvar3 = List(Enum('a', ('a', 'b', 'c')), iotype='in') listenumvar4 = List(Enum(True, (True, False)), iotype='in') varcontainer = VarTree(VarContainer(), iotype='in')
class VarComponent(Component): """Contains some vars""" boolvar = Bool(False, iotype='in') intvar = Int(333, iotype='in') floatvar = Float(-16.54, iotype='in') expvar1 = Float(1.2, iotype='in') expvar2 = Float(1.2, iotype='in') textvar = Str("This", iotype='in') arrayvar = Array(iotype='in') arrayvarsplit = Array(iotype='in') arrayvarsplit2 = Array(iotype='in') arrayvarzerod = Array(zeros(shape=(0, 0)), iotype='in') arrayvartwod = Array(zeros(shape=(1, 3)), iotype='in') arraysmall = Array(iotype='in') arrayshorthand = Array(iotype='in') single = Array(iotype='in') singleint = Array(iotype='in', dtype=numpy_int32) singlebool = Array(iotype='in', dtype=bool) stringarray = List([], iotype='in') listenumvar = List(Enum(1, (1, 2, 3)), iotype='in') listenumvar2 = List(Enum(1.5, (1.5, 2.4, 3.3)), iotype='in') listenumvar3 = List(Enum('a', ('a', 'b', 'c')), iotype='in') listenumvar4 = List(Enum(True, (True, False)), iotype='in') def __init__(self, directory=''): super(VarComponent, self).__init__(directory) # Variable Containers self.add('varcontainer', VarContainer())
class ABCDArrayComp(Component): delay = Float(0.01, iotype='in') in_string = Str(iotype='in') out_string = Str(iotype='out') in_list = List(iotype='in') out_list = List(iotype='out') def __init__(self, arr_size=9): super(ABCDArrayComp, self).__init__() self.add_trait('a', Array(np.ones(arr_size, float), iotype='in')) self.add_trait('b', Array(np.ones(arr_size, float), iotype='in')) self.add_trait('c', Array(np.ones(arr_size, float), iotype='out')) self.add_trait('d', Array(np.ones(arr_size, float), iotype='out')) def execute(self): time.sleep(self.delay) self.c = self.a + self.b self.d = self.a - self.b self.out_string = self.in_string + '_' + self.name self.out_list = self.in_list[:] + [1.5] #self.dump() def dump(self): print self.name, ':' print "%s.a = %s" % (self.name, self.a) print "%s.b = %s" % (self.name, self.b) print "%s.c = %s" % (self.name, self.c) print "%s.d = %s" % (self.name, self.d)
class ParetoFilter(ParetoFilterBase): """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. """ # pylint: disable-msg=E1101 criteria = List(Str, iotype="in", desc="List of outputs from the case to consider for " "filtering. Note that only case outputs are allowed as " "criteria.") #case_set = Slot(ICaseIterator, # desc="CaseIterator with the cases to be filtered to " # "Find the pareto optimal subset.") case_sets = List(Slot(ICaseIterator), value=[], iotype="in", desc="CaseSet with the cases to be filtered to " "find the pareto optimal subset.") pareto_set = Slot(CaseSet, desc="Resulting collection of pareto optimal cases.", copy="shallow") dominated_set = Slot(CaseSet, desc="Resulting collection of dominated cases.", copy="shallow")
class Generator(Component): """ Generates cases to be evaluated. """ x = List(iotype='out') y = List(iotype='out') def execute(self): """ Generate some cases to be evaluated. """ self.x = [numpy_random.normal(size=4) for i in range(10)] self.y = [numpy_random.normal(size=10) for i in range(10)]
class Builder(Component): x0 = Float(iotype='in') y0 = Float(iotype='in') x = List(iotype='out') y = List(iotype='out') def execute(self): self.x = list(linspace(self.x0 - 2, self.x0 + 2, 5)) self.y = list(linspace(self.y0 - 2, self.y0 + 2, 5))
def __init__(self, *args, **kwargs): super(TopObj, self).__init__(*args, **kwargs) self.add('subobj', SubObj(iotype=kwargs['iotype'])) self.add('tob', Bool(True)) self.add('tof', Float(0.5, units='inch')) self.add('toi', Int(42)) self.add('tos', Str('Hello')) self.add( 'tofe', Enum(values=(2.781828, 3.14159), aliases=('e', 'pi'), desc='Float enum', units='m')) self.add('toie', Enum(values=(9, 8, 7, 1), desc='Int enum')) self.add('tose', Enum(values=('cold', 'hot', 'nice'), desc='Str enum')) self.add( 'tof1d', Array(dtype=float, desc='1D float array', units='cm', default_value=[1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5], low=0, high=10)) self.add( 'tof2d', Array(dtype=float, desc='2D float array', units='mm', default_value=[[1.5, 2.5, 3.5, 4.5], [5.5, 6.5, 7.5, 8.5]])) self.add( 'tof3d', Array(dtype=float, desc='3D float array', default_value=[[[1.5, 2.5, 3.5], [4.5, 5.5, 6.5], [7.5, 8.5, 9.5]], [[10.5, 20.5, 30.5], [40.5, 50.5, 60.5], [70.5, 80.5, 90.5]]])) self.add( 'toi1d', Array(dtype=int, desc='1D int array', default_value=[1, 2, 3, 4, 5, 6, 7, 8, 9])) self.add( 'tos1d', List(Str, desc='1D string array', value=['Hello', 'from', 'TestComponent.tos1d'])) self.add('toflst', List(Float, desc='Float list')) self.add('toilst', List(Int, desc='Int list'))
class Paraboloidish(Component): x = List(iotype='in') y = List(iotype='in') f_xy = Float(iotype='out') def execute(self): x_mean = mean(asarray(self.x)) y_mean = mean(asarray(self.y)) self.f_xy = (x_mean - 3.0)**2 + x_mean * y_mean + (y_mean + 4.0)**2 - 3.0 print self.name, x_mean, y_mean, self.f_xy
def __init__(self, params=None, responses=None, constraints=None): super(ParetoFilter, self).__init__() # Make params optional. if params is None: params = tuple() # Make constraints optional. if constraints is None: constraints = tuple() if not isinstance(params, tuple): msg = "ParetoFilter optional params argument needs to be a " + \ "tuple of variable names." self.raise_exception(msg, ValueError) if not isinstance(constraints, tuple): msg = 'ParetoFilter optional constraints argument '\ 'needs to be a tuple of constraint variable names.' self.raise_exception(msg, ValueError) if responses is None or not isinstance(responses, tuple): msg = "ParetoFilter responses argument needs to be a tuple of " + \ "variable names." self.raise_exception(msg, ValueError) # Add our inputs and outputs to the vartrees. input_tree = self.get('params') self._param_data = [] for name in params: input_tree.add(name, List([], desc='ParetoFilter input', noflat=True)) output_tree = self.get('responses') self._response_data = {} for name in responses: output_tree.add( name, List([], desc='ParetoFilter response', noflat=True)) constraint_tree = self.get('constraints') self._constraint_data = [] for name in constraints: constraint_tree.add( name, List([], desc='ParetoFilter constraint', noflat=True)) self._param_names = params self._response_names = responses self._constraint_names = constraints self.pareto_inputs = zeros((1, len(params))) self.pareto_outputs = zeros((1, len(responses))) self.pareto_outcons = zeros((1, len(constraints)))
class SubGroup(Container): """ For checking subcontainer access. """ b = Bool(iotype='in', default_value=True, desc='A boolean') f = Float(iotype='in', default_value=0.5, desc='A float') i = Int(iotype='in', default_value=7, desc='An int') s = Str(iotype='in', default_value='Hello World! ( & < > )', desc='A string') fe = Enum(iotype='in', values=(2.781828, 3.14159), aliases=('e', 'pi'), desc='Float enum', units='m') ie = Enum(iotype='in', values=(9, 8, 7, 1), desc='Int enum') se = Enum(iotype='in', values=('cold', 'hot', 'nice'), desc='Str enum') f1d = Array(dtype=float, iotype='in', desc='1D float array', units='cm', default_value=[1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5], low=0, high=10) f2d = Array(dtype=float, iotype='in', desc='2D float array', units='mm', default_value=[[1.5, 2.5, 3.5, 4.5], [5.5, 6.5, 7.5, 8.5]]) f3d = Array(dtype=float, iotype='in', desc='3D float array', default_value=[[[1.5, 2.5, 3.5], [4.5, 5.5, 6.5], [7.5, 8.5, 9.5]], [[10.5, 20.5, 30.5], [40.5, 50.5, 60.5], [70.5, 80.5, 90.5]]]) i1d = Array(dtype=int, iotype='in', desc='1D int array', default_value=[1, 2, 3, 4, 5, 6, 7, 8, 9]) s1d = List(Str, iotype='in', desc='1D string array', value=['Hello', 'from', 'TestComponent.SubGroup']) flst = List(Float, iotype='in', desc='List of floats') ilst = List(Int, iotype='in', desc='List of ints')
class Verifier(Component): """ Verifies evaluated cases. """ x = List(iotype='in') y = List(iotype='in') rosen_suzuki = List(iotype='in') sum_y = List(iotype='in') def execute(self): """ Verify evaluated cases. """ for i in range(len(self.rosen_suzuki)): assert self.rosen_suzuki[i] == rosen_suzuki(self.x[i]) assert self.sum_y[i] == sum(self.y[i])
class DakotaMultidimStudy(DakotaBase): """ Multidimensional parameter study using DAKOTA. """ partitions = List(Int, low=1, iotype='in', desc='List giving # of partitions for each parameter') def configure_input(self): """ Configures input specification. """ if len(self.partitions) != self.total_parameters(): self.raise_exception( '#partitions (%s) != #parameters (%s)' % (len(self.partitions), self.total_parameters()), ValueError) partitions = [str(partition) for partition in self.partitions] objectives = self.get_objectives() self.input.method = [ 'multidim_parameter_study', ' output = %s' % self.output, ' partitions = %s' % ' '.join(partitions) ] self.set_variables(need_start=False) self.input.responses = [ 'objective_functions = %s' % len(objectives), 'no_gradients', 'no_hessians' ]
class C1_l(Component): l = List([], iotype='in') i = Int(0, iotype='in') val = Int(0, iotype='out') def execute(self): self.val = self.l[self.i]
class DistributionCaseDriver(CaseIterDriverBase): """ Driver for evaluating models at point distributions. """ implements(IHasParameters) distribution_generator = Slot( IDistributionGenerator, required=True, desc='Iterator supplying values of point distribitions.') case_outputs = List(Str, iotype='in', desc='A list of outputs to be saved with each case.') def get_case_iterator(self): """Returns a new iterator over the Case set.""" return self._get_cases() def _get_cases(self): """Iterator over the cases""" for row in self.distribution_generator: case = self.set_parameters(row, Case(parent_uuid=self._case_id)) case.add_outputs(self.case_outputs) yield case
class DeMux(Component): """ Takes one List input and splits it into *n* indvidual outputs. This is a logical demultiplexer. """ n = Int(2, low=2, iotype="in", desc="number of items in the array to be \ demultiplexed") inputs = List(iotype="in") def __init__(self, n=2): super(DeMux,self).__init__() self.n = n self._outputs = [] self._n_changed(n,n) def _n_changed(self,old,new): for name in self._outputs: if self.parent: self.parent.disconnect('.'.join([self.name,name])) self.remove_trait(name) self._outputs = [] for i in xrange(new): name = "output_%d"%(i+1) self.add(name, Any(iotype="out")) self._outputs.append(name) def execute(self): for data,out in zip(self.inputs,self._outputs): setattr(self,out,data)
class Mux(Component): """ Takes in *n* inputs and exports a length *n* List with the data. It is a logical multiplexer. """ n = Int(2, low=2, iotype="in",desc="number of inputs to be multiplexed") output = List(iotype="out") def __init__(self, n=2): super(Mux,self).__init__() self._inputs = [] self.n = n self._n_changed(n, n) #just to initialize it def _n_changed(self,old,new): for name in self._inputs: if self.parent: self.parent.disconnect('.'.join([self.name,name])) self.remove_trait(name) self._inputs = [] #build the inputs for i in xrange(new): name = "input_%d"%(i+1) self.add(name, Any(iotype="in")) self._inputs.append(name) def execute(self): self.output = [getattr(self,inp) for inp in self._inputs]
class SimpleListComp(Component): a = List(Int, iotype='in') b = List(Int, iotype='in') c = List(Int, iotype='out') d = List(Int, iotype='out') def __init__(self): super(SimpleListComp, self).__init__() self.a = [1, 2, 3] self.b = [4, 5, 6] self.c = [5, 7, 9] self.d = [-3, -3, -3] def execute(self): self.c = [a + b for a, b in zip(self.a, self.b)] self.d = [a - b for a, b in zip(self.a, self.b)]
class DummyComp(Component): r = Float(iotype='in') r2 = Float(iotype='in') r3 = Float(iotype='in', desc="some random variable", low=-1.0, high=1.0, other_meta_data="test") s = Str(iotype='in') rout = Float(iotype='out', units='ft') r2out = Float(iotype='out') sout = Str(iotype='out') slistout = List(Str, iotype='out') dummy_in = Slot(Component, iotype='in') dummy_out = Slot(Component, iotype='out') dummy_out_no_copy = Slot(Component, iotype='out', copy=None) def __init__(self): super(DummyComp, self).__init__() self.r = 1.0 self.r2 = -1.0 self.rout = 0.0 self.r2out = 0.0 self.s = 'a string' self.sout = '' # make a nested container with input and output ContainerVars self.add('dummy', Multiplier()) self.dummy_in = self.dummy self.dummy_out = self.dummy def execute(self): self.rout = self.r * 1.5 self.r2out = self.r2 + 10.0 self.sout = self.s[::-1] # pylint: disable-msg=E1101 self.dummy.execute()
class TestComponent2(Component): vtlist = List(trait=Vars, value=[], iotype='in') f_out = Float(iotype='out') def execute(self): self.f_out = self.vtlist[0].f1 + self.vtlist[0].f2
def add_parameter(self, target, low=None, high=None, scaler=None, adder=None, start=None, fd_step=None, name=None, scope=None): """Adds a parameter or group of parameters to the driver.""" super(HasVarTreeParameters, self).add_parameter( target, low, high, scaler, adder, start, fd_step, name, scope) if name is not None: path = name elif isinstance(target, basestring): path = target elif isinstance(target, Parameter): path = target.name or target.target else: path = target[0] path = make_legal_path(path) obj = self.parent names = ['case_inputs'] + path.split('.') for name in names[:-1]: if obj.get_trait(name): val = obj.get(name) else: val = VariableTree() obj.add_trait(name, VarTree(val, iotype='in')) obj = val name = names[-1] obj.add_trait(name, List(iotype='in'))
class Broadcaster(Component): """Takes inputs and passes them directly to outputs to be broadcast out to other components.""" names = List( Str, iotype="in", desc="Names of the variables you want to broadcast from this component." ) types = Dict( {'default': Float}, iotype="in", desc= "Name/type pairs describing the variable types of each broadcast variable; " "'default' name is used if no other type is set explicitly.") def __init__(self, names, types=None): """names: ListSrt, list of the variable names you would like the broadcaster to create for you. All inputs will be named with an '_in' added. Outputs will follow the name given. types: Dict, dictionary of the name/type pairs describing which types you would like to broadcast. If given, the name 'default' indicates the default variable type to use.""" super(Broadcaster, self).__init__() self._vars = [] if types is not None: self.types = types self.names = names def _types_changed(self, old, new): if self.names: self._names_changed(self.names, self.names) #code to create inputs and outputs when names is changed def _names_changed(self, old, new): for in_var, out_var in self._vars: if self.parent: self.parent.disconnect('.'.join([self.name, in_var])) self.parent.disconnect('.'.join([self.name, out_var])) self.remove_trait(in_var) self.remove_trait(out_var) self._vars = [] for name in new: if name in self.types: traits = self.types[name] elif 'default' in self.types: traits = self.types['default'] else: self.raise_exception( 'No type was provided for "%s" and no "default" type was provided. ' 'Specify at least one of these.' % name, ValueError) in_var = "%s_in" % name out_var = name self.add_trait(in_var, Float(iotype="in", low=-9e99, high=9e99)) self.add_trait(out_var, Float(iotype="out")) self._vars.append((in_var, out_var)) def execute(self, *args, **kwargs): for in_var, out_var in self._vars: setattr(self, out_var, getattr(self, in_var))
class MyNoDefComp(Component): f_in = Float(iotype='in') f_out = Float(iotype='out') arr_in = Array(iotype='in') list_in = List(iotype='in') def execute(self): self.f_out = self.f_in + 1.
class MyDefComp(Component): f_in = Float(3.14, iotype='in') f_out = Float(iotype='out') arr_in = Array([1., 2., 3.], iotype='in') list_in = List(value=['a', 'b', 'c'], iotype='in') def execute(self): self.f_out = self.f_in + 1.
class Dummy(Component): x = Array([[-1, 1], [-2, 2]], iotype='in', shape=(2, 2)) xlist = List([1, 2], iotype='in') xdict = Dict({'a': 'b'}, iotype='in') def execute(self): self.y = self.x
class Dummy(Component): x = Float(0.0, low=-10, high=10, iotype='in') y = Float(0.0, low=0, high=10, iotype='in') lst = List([1, 2, 3, 4, 5], iotype='in') i = Int(0, low=-10, high=10, iotype='in') j = Int(0, low=0, high=10, iotype='in') enum_i = Enum(values=(1, 5, 8), iotype='in') enum_f = Enum(values=(1.1, 5.5, 8.8), iotype='in')
class ConnectA(Assembly): i1 = List([], iotype='in') o1 = List(iotype='out') def __init__(self, sequential): self.sequential = sequential super(ConnectA, self).__init__() def configure(self): self.add('c', ConnectC()) self.add('driver', CaseIteratorDriver()) self.driver.sequential = self.sequential self.driver.workflow.add('c') self.driver.add_parameter('c.i1') self.driver.add_response('c.o1') self.connect('i1', 'driver.case_inputs.c.i1') self.connect('driver.case_outputs.c.o1', 'o1')
class VarContainer(VariableTree): """Contains some vars""" boolvar = Bool(True) intvar = Int(7777) floatvar = Float(2.14543) textvar = Str("Hey") listenumvar = List(Enum(1, (1, 2, 3)))
class TopObj(VariableTree): """ Top-level object variable. """ tob = Bool(True) tof = Float(0.5, units='inch') toi = Int(42) tos = Str('Hello') tofe = Enum(values=(2.781828, 3.14159), aliases=('e', 'pi'), desc='Float enum', units='m') toie = Enum(values=(9, 8, 7, 1), desc='Int enum') tose = Enum(values=('cold', 'hot', 'nice'), desc='Str enum') tof1d = Array(dtype=float, desc='1D float array', units='cm', default_value=[1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5], low=0, high=10) tof2d = Array(dtype=float, desc='2D float array', units='mm', default_value=[[1.5, 2.5, 3.5, 4.5], [5.5, 6.5, 7.5, 8.5]]) tof3d = Array(dtype=float, desc='3D float array', default_value=[[[1.5, 2.5, 3.5], [4.5, 5.5, 6.5], [7.5, 8.5, 9.5]], [[10.5, 20.5, 30.5], [40.5, 50.5, 60.5], [70.5, 80.5, 90.5]]]) toi1d = Array(dtype=int, desc='1D int array', default_value=[1, 2, 3, 4, 5, 6, 7, 8, 9]) tos1d = List(Str, desc='1D string array', value=['Hello', 'from', 'TestComponent.tos1d']) toflst = List(Float, desc='Float list') toilst = List(Int, desc='Int list') subobj = VarTree(SubObj())
class Complex_Comp(Component): ''' Basic building block''' list_str = List(Str, iotype='in') string = Str('Testing', iotype='out') def execute(self): ''' pretty simple''' pass
def __init__(self, iotype, client, rpath, typ): ProxyMixin.__init__(self, client, rpath) self._type = typ default = self._value = [typ(val.strip(' "')) for val in self._valstr.split(',')] desc = client.get(rpath+'.description') if typ == float: as_units = client.get(rpath+'.units') if as_units: om_units = get_translation(as_units) else: om_units = None if typ != str: if client.get(rpath+'.hasUpperBound') == 'true': high = typ(client.get(rpath+'.upperBound')) else: high = None if client.get(rpath+'.hasLowerBound') == 'true': low = typ(client.get(rpath+'.lowerBound')) else: low = None if typ == float: List.__init__(self, trait=Float, iotype=iotype, desc=desc, value=default, low=low, high=high, units=om_units) elif typ == int: List.__init__(self, trait=Int, iotype=iotype, desc=desc, value=default, low=low, high=high) else: List.__init__(self, trait=Str, iotype=iotype, desc=desc, value=default)