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 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 Connectable(Component): b_in = Bool(iotype='in') e_in = Enum(values=(1, 2, 3), iotype='in') f_in = Float(iotype='in') i_in = Int(iotype='in') s_in = Str(iotype='in') x_in = Float(iotype='in') w_in = Float(iotype='in', units='g') b_out = Bool(iotype='out') e_out = Enum(values=(1, 2, 3), iotype='out') f_out = Float(iotype='out') i_out = Int(iotype='out') s_out = Str(iotype='out') x_out = Float(iotype='out') w_out = Float(5.0, iotype='out', units='kg') def execute(self): self.b_out = self.b_in self.e_out = self.e_in self.f_out = self.f_in self.i_out = self.i_in self.s_out = self.s_in self.x_out = self.x_in
def __init__(self, iotype, client, rpath): ProxyMixin.__init__(self, client, rpath) default = self._valstr desc = client.get(rpath+'.description') Str.__init__(self, default_value=default, iotype=iotype, desc=desc)
class Case(Container): title1 = Str() title2 = Str() oline = Str() def __init__(self): super(Case, self).__init__() self._stages = [] def read(self, stream): """ Read from `stream`. Returns: - 1 if read OK and more to go. - 0 if read OK and end of data. - -1 if end-of-file or read error. """ #read title1 line = stream.readline() if not line: return False self.title1 = line line = stream.readline() if not line: return False self.title2 = line # stage loop pos = stream.tell() line = stream.readline() while line and '&DATAIN' in line: stagein = Datain() if stagein.read(stream): stage_num = len(self._stages) + 1 self.add('Stage%d' % stage_num, stagein) self._stages.append(stagein) if stagein.endjob: return 0 if stagein.endstg: return 1 else: return -1 pos = stream.tell() line = stream.readline() if line: stream.seek(os.SEEK_SET, pos) return 1 def write(self, stream): stream.write(self.title1) stream.write(self.title2) #print ' .before going to write() .. self.nstages =', len(self._stages) for stagein in self._stages: stagein.write(stream)
class PrintEnvironment(ExternalCode, ASMixin): allocator = Str('LocalHost', iotype='in') env_str = Str(iotype='out') def execute(self): self._logger.critical('execute: allocator %s', self.allocator) self.resources = dict(allocator=self.allocator) self.command = ['printenv'] self.stdout = 'printenv.out' super(PrintEnvironment, self).execute() with open('printenv.out', 'r') as inp: self.env_str = inp.read() self._logger.critical('done %s', len(self.env_str))
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 SubObj(VariableTree): """ Sub-object under TopObject. """ sob = Bool(False) sof = Float(0.284, units='lb/inch**3') soi = Int(3) sos = Str('World')
def test_single_bogus(self): code = "self.top.driver.add_parameter('comp.bogus', 0., 1.e99)" assert_raises( self, code, globals(), locals(), AttributeError, "driver: Can't add parameter 'comp.bogus' because" " it doesn't exist.") code = "self.top.driver.add_parameter('zr()', 0., 1.e99)" assert_raises( self, code, globals(), locals(), ValueError, "driver: Can't add parameter: 'zr()' is not a" " valid parameter expression") code = "self.top.driver.add_parameter('comp.x', 0., 1.e99, scope='bogus')" assert_raises( self, code, globals(), locals(), TypeError, "driver: Can't add parameter: cannot create weak" " reference to 'str' object") self.top.comp.add_trait('vstr', Str('Hey', iotype='in')) code = "self.top.driver.add_parameter('comp.vstr', 0., 1.e99)" assert_raises( self, code, globals(), locals(), ValueError, "driver: The value of parameter 'comp.vstr' must" " be a real or integral type, but its type is 'str'.")
class CSVFile(Container): """ DOEgenerator that returns rows in a CSV file. Plugs into the DOEgenerator socket on a DOEdriver. """ implements(IDOEgenerator) num_parameters = Int(0, iotype='in', desc='Expected number of parameters in the DOE') doe_filename = Str('', iotype='in', desc='Name of CSV file.') def __init__(self, doe_filename='doe_inputs.csv', *args, **kwargs): super(CSVFile, self).__init__(*args, **kwargs) self.doe_filename = doe_filename def __iter__(self): """ Return an iterator over our sets of input values. """ return self._next_row() def _next_row(self): """ Generate float values from CSV file. """ inp = open(self.doe_filename, 'rb') num_params = self.num_parameters for i, row in enumerate(csv.reader(inp)): if len(row) != num_params: raise RuntimeError( '%s line %d: expected %d parameters, got %d' % (self.doe_filename, i + 1, num_params, len(row))) yield [float(val) for val in row]
class MyAsm(Assembly): ModulesInstallPath = Str('C:/work/IMOO2/imoo/modules', desc='', iotype='in') def configure(self): self.add('propulsion', MyComp()) self.driver.workflow.add('propulsion') self.connect('ModulesInstallPath', 'propulsion.ModulesInstallPath')
def setUp(self): self.startdir = os.getcwd() self.tempdir = tempfile.mkdtemp(prefix='test_csv-') os.chdir(self.tempdir) self.top = top = set_as_top(Assembly()) driver = top.add('driver', SimpleCaseIterDriver()) top.add('comp1', ExecComp(exprs=['z=x+y'])) top.add('comp2', ExecComp(exprs=['z=x+1'])) top.connect('comp1.z', 'comp2.x') top.comp1.add('a_string', Str("Hello',;','", iotype='out')) top.comp1.add('a_array', Array(array([1.0, 3.0, 5.5]), iotype='out')) top.comp1.add('x_array', Array(array([1.0, 1.0, 1.0]), iotype='in')) top.comp1.add('b_bool', Bool(False, iotype='in')) top.comp1.add('vt', VarTree(DumbVT(), iotype='out')) top.driver.workflow.add(['comp1', 'comp2']) # now create some Cases outputs = ['comp1.z', 'comp2.z', 'comp1.a_string', 'comp1.a_array[2]'] cases = [] for i in range(10): i = float(i) inputs = [('comp1.x', i + 0.1), ('comp1.y', i * 2 + .1), ('comp1.x_array[1]', 99.88), ('comp1.b_bool', True)] cases.append(Case(inputs=inputs, outputs=outputs)) Case.set_vartree_inputs(driver, cases) driver.add_responses(sorted(outputs)) self.filename = "openmdao_test_csv_case_iterator.csv"
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 OptRosenSuzukiComponent(Component): """ From the CONMIN User's Manual: EXAMPLE 1 - CONSTRAINED ROSEN-SUZUKI FUNCTION. NO GRADIENT INFORMATION. MINIMIZE OBJ = X(1)**2 - 5*X(1) + X(2)**2 - 5*X(2) + 2*X(3)**2 - 21*X(3) + X(4)**2 + 7*X(4) + 50 Subject to: G(1) = X(1)**2 + X(1) + X(2)**2 - X(2) + X(3)**2 + X(3) + X(4)**2 - X(4) - 8 .LE.0 G(2) = X(1)**2 - X(1) + 2*X(2)**2 + X(3)**2 + 2*X(4)**2 - X(4) - 10 .LE.0 G(3) = 2*X(1)**2 + 2*X(1) + X(2)**2 - X(2) + X(3)**2 - X(4) - 5 .LE.0 This problem is solved beginning with an initial X-vector of X = (1.0, 1.0, 1.0, 1.0) The optimum design is known to be OBJ = 6.000 and the corresponding X-vector is X = (0.0, 1.0, 2.0, -1.0) """ x = Array(iotype='in', low=-10, high=99) g = Array([1., 1., 1.], iotype='out') result = Float(iotype='out') obj_string = Str(iotype='out') opt_objective = Float(iotype='out') # pylint: disable=C0103 def __init__(self): super(OptRosenSuzukiComponent, self).__init__() self.x = array([1., 1., 1., 1.], dtype=float) self.result = 0. self.opt_objective = 6. self.opt_design_vars = [0., 1., 2., -1.] def execute(self): """calculate the new objective value""" x = self.x self.result = (x[0]**2 - 5. * x[0] + x[1]**2 - 5. * x[1] + 2. * x[2]**2 - 21. * x[2] + x[3]**2 + 7. * x[3] + 50) self.obj_string = "Bad" # cast constraint vector according to input type # to deal with complex inputs self.g = zeros(3, dtype=self.x.dtype) self.g[0] = (x[0]**2 + x[0] + x[1]**2 - x[1] + x[2]**2 + x[2] + x[3]**2 - x[3] - 8) self.g[1] = (x[0]**2 - x[0] + 2. * x[1]**2 + x[2]**2 + 2. * x[3]**2 - x[3] - 10) self.g[2] = (2 * x[0]**2 + 2 * x[0] + x[1]**2 - x[1] + x[2]**2 - x[3] - 5)
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 Complex_Comp(Component): ''' Basic building block''' list_str = List(Str, iotype='in') string = Str('Testing', iotype='out') def execute(self): ''' pretty simple''' pass
def _add_str(vartree, member, props): """ Helper for :meth:`_populate_from_xml`. """ name = member.attrib['name'] args = {} args['default_value'] = member.text.decode('string_escape') desc = props.get('description') if desc: args['desc'] = desc.decode('string_escape') vartree.add(name, Str(**args))
class TracedComponent(Component): """ Used to check iteration coordinates. """ inp = Int(iotype='in') itername = Str(iotype='out') def execute(self): """ Record iteration coordinate. """ self.itername = self.get_itername()
class Source(Component): """ Produces files. """ text_data = Str('Hello world', iotype='in') text_file = File('source.txt', iotype='out') def execute(self): """ Write test data to files. """ with open(self.text_file.path, 'w') as out: out.write(self.text_data)
class Sink(Component): """ Consumes files. """ text_data = Str(iotype='out') text_file = File(iotype='in') def execute(self): """ Read test data from files. """ with self.text_file.open() as inp: self.text_data = inp.read()
class ReadAirfoilBase(Component): """Read airfoil data from a file""" # inputs fileIn = Str(iotype='in', desc='name of file') # outputs afOut = VarTree(AirfoilDataVT(), iotype='out', desc='tabulated airfoil data')
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 Sink(Component): """ Consumes files. """ bogus_path = Str('', iotype='in') text_data = Str(iotype='out') binary_data = List([1.0], iotype='out') text_file = File(iotype='in') binary_file = File(iotype='in') def execute(self): """ Read test data from files. """ if self.bogus_path: self.text_file.path = self.bogus_path inp = self.text_file.open() self.text_data = inp.read() inp.close() inp = self.binary_file.open() self.binary_data = cPickle.load(inp) inp.close()
class AirfoilDataVT(VariableTree): """ airfoil data at a specific Reynolds number over of range of angles of attack """ desc = Str(desc='Description of data, i.e. airfoil name, flow conditions (clean/rough) etc') Re = Float(desc='Reynolds number') alpha = Array(units='deg', desc='angles of attack') cl = Array(desc='corresponding lift coefficients') cd = Array(desc='corresponding drag coefficients') cm = Array(desc='corresponding pitching moment coefficients')
class FUSEDIECBase(Assembly): """base class for simulation codes running an IEC load basis""" inputs = VarTree(IECRunCaseBaseVT(), iotype='in', desc='') outputs = VarTree(IECOutputsBaseVT(), iotype='out', desc='') results_dir = Str('all_runs', iotype='in', desc='Directory for simulation results files') def __init__(self): super(FUSEDIECBase, self).__init__() # TODO KLD not using for now '''self.results_dir = os.path.join(os.getcwd(), self.results_dir)
class AirfoilDatasetVT(VariableTree): """ List of AirfoilDataVT datasets The ``interpolator`` parameter can be used to characterize the list of data in terms of e.g. Reynolds number, relative thickness, TE flap angle, roughness ratio etc, and should have the same length as the number of polars. """ desc = Str(desc='Description of dataset') interpolator = Array(desc='The interpolator could characterize e.g. TE flap angle, roughness ratio etc') polars = List(AirfoilDataVT, desc='List of AirfoilDataVT')
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 ExpectedImprovement(Component): best_case = Slot(CaseSet, iotype="in", desc="CaseSet which contains a single case " "representing the criteria value.", required=True) criteria = Str(iotype="in", desc="Name of the variable to maximize the expected " "improvement around. Must be a NormalDistrubtion type.") predicted_value = Slot( NormalDistribution, iotype="in", desc="The Normal Distribution of the predicted value " "for some function at some point where you wish to" " calculate the EI.") EI = Float(0.0, iotype="out", desc="The expected improvement of the predicted_value.") PI = Float(0.0, iotype="out", desc="The probability of improvement of the predicted_value.") def execute(self): """ Calculates the expected improvement of the model at a given point. """ mu = self.predicted_value.mu sigma = self.predicted_value.sigma best_case = self.best_case[0] try: target = best_case[self.criteria] except KeyError: self.raise_exception( "best_case did not have an output which " "matched the criteria, '%s'" % self.criteria, ValueError) try: self.PI = 0.5 + 0.5 * erf((1 / 2**.5) * (target - mu / sigma)) T1 = (target - mu) * .5 * (1. + erf( (target - mu) / (sigma * 2.**.5))) T2 = sigma * ((1. / ((2. * pi)**.05)) * exp(-0.5 * ( (target - mu) / sigma)**2.)) self.EI = abs(T1 + T2) except (ValueError, ZeroDivisionError): self.EI = 0 self.PI = 0
class Flags(VariableTree): Opt = Int(1, desc='0 - single run, 1 - optimization') ConFail = Int( 0, desc='1 - use structural failure as a constraint on optimization') ConWireCont = Int( 0, desc= '1 - use wire length continuity as a constraint to set appropriate wire forces in multi-point optimizations' ) ConJigCont = Int(0, desc='1 - use jig continuity') ConDef = Int(0, desc='1 - constraints on maximum deformation of the rotor') MultiPoint = Int( 4, desc= '0 - single point optimization, 1 - 4 point optimization (h=0.5, h=3, wind case, gravity load)' ) Quad = Int(1, desc='0 - prop drive, 1 - quad rotor') FreeWake = Int(1, desc='0 - momentum theory, 1 - free vortex ring wake') PlotWake = Int(0, desc='0 - dont plot wake, 1 - plot wake ') DynamicClimb = Int( 0, desc= '0 - vc imposes downward velocity, 1 - vc represents climb (final altitude depends on Nw)' ) Cover = Int(0, desc='0 - no cover over root rotor blades, 1 - cover') Load = Int( 0, desc= '0 - normal run, 1 - gravity forces only, 2 - prescribed load from pLoad' ) Cdfit = Int( 1, desc= '0 - analytic model for drag coefficient, 1 - curve fit on BE airfoils' ) GWing = Int( 1, desc= '0 - Daedalus style wing, 1 - Gossamer style wing (changes amount of laminar flow)' ) AeroStr = Int( 1, desc='0 - Assume flat wing, 1 - take deformation into account') Movie = Int(0, desc='0 - dont save animation, 1 - save animation') wingWarp = Int( 0, desc='0 - no twist constraint, >0 - twist constraint at wingWarp') CFRPType = Str('NCT301-1X HS40 G150 33 +/-2%RW', desc='type of carbon fibre reinforced polymer') WireType = Enum('Pianowire', ('Pianowire', 'Vectran'), desc='Material to be used for lift wire')
class ExprComp(Component): """Evaluates an expression based on the input x and assigns it to f_x""" x = Float(iotype='in') f_x = Float(iotype='out') expr = Str('x', iotype='in') def __init__(self, expr='x'): super(ExprComp, self).__init__() self.expr = expr def execute(self): global exec_order exec_order.append(self.name) self.f_x = eval(self.expr, globals(), self.__dict__)