def __init__(self, iotype, client, rpath): ProxyMixin.__init__(self, client, rpath) default = self._value = float(self._valstr) desc = client.get(rpath+'.description') as_units = client.get(rpath+'.units') if as_units: om_units = get_translation(as_units) else: om_units = None if client.get(rpath+'.hasUpperBound') == 'true': high = float(client.get(rpath+'.upperBound')) else: high = None if client.get(rpath+'.hasLowerBound') == 'true': low = float(client.get(rpath+'.lowerBound')) else: low = None Float.__init__(self, default_value=default, iotype=iotype, desc=desc, low=low, high=high, units=om_units)
class TestAsm(Assembly): f_in = Float(iotype='in') def configure(self): self.add('c2', TestComponent2()) self.driver.workflow.add('c2') # Construct list with only one element for demo purposes self.c2.vtlist = [Vars()] self.connect('f_in', 'c2.vtlist[0].f1') self.c2.vtlist[0].f2 = 90 self.create_passthrough('c2.f_out')
def __init__(self, num_elem=10): super(SysCLTar, self).__init__() # Inputs self.add('fuel_w', Array(np.zeros((num_elem+1, )), iotype='in', desc = 'Fuel Weight')) self.add('Gamma', Array(np.zeros((num_elem+1, )), iotype='in', desc = 'Flight path angle')) self.add('CT_tar', Array(np.zeros((num_elem+1, )), iotype='in', desc = 'Thrust Coefficient')) self.add('rho', Array(np.zeros((num_elem+1, )), iotype='in', desc = 'Density')) self.add('v', Array(np.zeros((num_elem+1, )), iotype='in', desc = 'Speed')) self.add('alpha', Array(np.zeros((num_elem+1, )), iotype='in', desc = 'Angle of attack')) self.add('S', Float(0.0, iotype='in', desc = 'Wing Area')) self.add('ac_w', Float(0.0, iotype='in', desc = 'Weight of aircraft + payload')) # Outputs self.add('CL', Array(np.zeros((num_elem+1, )), iotype='out', desc = 'Lift Coefficient'))
class Simple(Component): a = Float(iotype='in') b = Float(iotype='in') c = Float(iotype='out') d = Float(iotype='out') def __init__(self): super(Simple, self).__init__() self.a = 1 self.b = 2 self.c = 3 self.d = -1 def execute(self): self.c = self.a + self.b self.d = self.a - self.b def list_deriv_vars(self): return ('a', 'b'), ('c', 'd') def provideJ(self): der = 1.0 return np.array([[der, der], [der, der]])
class MyCompDerivs(Component): x1 = Float(1.0, iotype='in') x2 = Float(1.0, iotype='in') y = Float(3.3, iotype='out') def execute(self): ''' Simple eq ''' self.y = 2.0 * self.x1 * self.x1 + 2.0 * self.x2 * self.x2 def provideJ(self): ''' Simple eq ''' self.J = np.array([[4.0 * self.x1, 4.0 * self.x2]]) return self.J def list_deriv_vars(self): input_keys = ('x1', 'x2') output_keys = ('y', ) return input_keys, output_keys
class Discipline2(Component): """Component containing Discipline 2.""" # pylint: disable-msg=E1101 z1 = Float(0.0, iotype='in', desc='Global Design Variable.') z2 = Float(0.0, iotype='in', desc='Global Design Variable.') y1 = Float(1.0, iotype='in', desc='Disciplinary Coupling.') y2 = Float(iotype='out', desc='Output of this Discipline.') def execute(self): """Evaluates the equation y2 = y1**(.5) + z1 + z2""" z1 = self.z1 z2 = self.z2 # Note: this may cause some issues. However, y1 is constrained to be # above 3.16, so lets just let it converge, and the optimizer will # throw it out y1 = abs(self.y1) self.y2 = y1**(.5) + z1 + z2
class Model_A2d(Component): """ Wrapper for M4 Model_A2d. """ x = Float(0., iotype='in', desc='X input value.') y = Float(0., iotype='in', desc='Y input value.') z1 = Float(0., iotype='out', desc='exp(x) + exp(y)') z2 = Float(0., iotype='out', desc='10.0*(x-2.0)**2 + 10.0*(y-1.5)**2 + 10.0') #name='Model_A2d', def __init__(self): super(Model_A2d, self).__init__() self._m4_comp = mool.Optimization.Models_test.Model_A2d() def execute(self): """ Run M4 component. """ vec = [self.x, self.y] self.z1 = self._m4_comp.RunModel(vec, 0) self.z2 = self._m4_comp.RunModel(vec, 1) self._logger.debug('function(%f, %f) = %f, %f', self.x, self.y, self.z1, self.z2)
class MyFAST_component(FAST_component): """ An openMDAO component implementing an interface to compute rotor power as a function of wind speed and rotorspeed""" TMax = Float(30.0, iotype='in', desc='length of analysis') TStart = Float(0.0, iotype='in', desc='start of analysis') Vhub = Float(10.0, iotype='in', desc='hub height wind speed in mps') RotSpeed = Float(15.0, iotype='in', desc='rotor speed') RotPwr = Float(0, iotype='out', desc='generato power in Watts') def __init__(self, fst_exe, fst_dir, fst_file, run_dir): super(MyFAST_component, self).__init__(fst_exe, fst_dir, fst_file, run_dir) def execute(self): fstDict = {} fstDict['Vhub'] = self.Vhub fstDict['RotSpeed'] = self.RotSpeed fstDict['TMax'] = self.TMax fstDict['TStart'] = self.TStart self.myfast.setOutputs(['RotPwr']) self.myfast.fstDict = fstDict self.myfast.execute() self.RotPwr = max(self.myfast.getOutputValue("RotPwr"))
def __init__(self, num_elem=10): super(SysFuelObj, self).__init__() # Inputs self.add( 'fuel_w', Array(np.zeros((num_elem + 1, )), iotype='in', desc='Fuel Weight')) # Outputs self.add( 'fuelburn', Float(0.0, iotype='out', desc='Objective fuel burn (initial fuel carried)'))
class ABCDArrayComp(Component): delay = Float(0.01, iotype='in') 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
def _setup_move_rename(self): asm = set_as_top(Assembly()) asm.add('sub', Assembly()) asm.add('comp1', Simple()) asm.sub.add('comp2', Simple()) asm.sub.add('comp3', Simple()) asm.add('comp4', Simple()) asm.driver.workflow.add(['comp1', 'sub', 'comp4']) asm.sub.driver.workflow.add(['comp2', 'comp3']) asm.sub.add('a2', Float(iotype='in')) asm.sub.add('c3', Float(iotype='out')) asm.connect('comp1.c', 'sub.a2') asm.connect('sub.c3', 'comp4.a') asm.sub.connect('a2', 'comp2.a') asm.sub.connect('comp2.c', 'comp3.a') asm.sub.connect('comp3.c', 'c3') #asm.connect('comp1.d', 'sub.comp2.b') # autopassthrough #asm.connect('sub.comp3.d', 'comp4.b') # autopassthrough connections = asm.list_connections(show_passthrough=True) self.assertEqual( set(connections), set([ ('comp1.c', 'sub.a2'), # ('comp1.d', 'sub.comp2.b'), # ('sub.comp3.d', 'comp4.b'), ('sub.c3', 'comp4.a') ])) sub_connections = asm.sub.list_connections(show_passthrough=True) self.assertEqual( set(sub_connections), set([('comp3.c', 'c3'), ('a2', 'comp2.a'), ('comp2.c', 'comp3.a')])) self.assertEqual([c.name for c in asm.driver.workflow], ['comp1', 'sub', 'comp4']) self.assertEqual([c.name for c in asm.sub.driver.workflow], ['comp2', 'comp3']) return asm
class MyComp_Explicit(Component): ''' Single implicit component with 3 states and residuals. For c=2.0, (x,y,z) = (1.0, -2.333333, -2.1666667) ''' # External inputs c = Float( 2.0, iotype="in", fd_step=.00001, desc= "arbitrary constant that is not iterated on but does affect the results" ) # States x = Float(0.0, iotype="in") y = Float(0.0, iotype="in") z = Float(0.0, iotype="in") # Residuals res = Array(np.zeros((3)), iotype="out") # Outputs y_out = Float(iotype='out') def execute(self): """run a single step to calculate the residual values for the given state var values""" c, x, y, z = self.c, self.x, self.y, self.z self.res[0] = self.c * (3 * x + 2 * y - z) - 1 self.res[1] = 2 * x - 2 * y + 4 * z + 2 self.res[2] = -x + y / 2. - z self.y_out = c + x + y + z
class PrescribedLoad(VariableTree): y = Float(9.9999, desc='Point load location') pointZ = Float(0.15 * 9.8, desc='N') pointM = Float(0, desc='Nm') distributedX = Float(0, desc='N/m') distributedZ = Float(0, desc='N/m') distributedM = Float(0, desc='Nm/m')
class DummyCompVarTree(Component): ins = VarTree(TreeWithFloat(), iotype="in") y = Float(iotype="out") def execute(self): self.y = self.ins.x1 def provideJ(self): return array([[1]]) def list_deriv_vars(self): return ("ins.x1", ), ("y", )
class next_data(Component): """ for assigning new values from axod output """ hpower = Float(iotype='in', units='hp', desc='input power') def __init_(self, directory=''): """Constructor for temp_data component""" super(next_data, self).__init__(directory) self.hpower = 100.0 def execute(self): """ execute """ self._logger.debug('running')
class Dis12Linear(Component): """ Linear model of one a sellar model or system. """ z1 = Float(0., iotype='in') z2 = Float(0., iotype='in') z_store = Array([0., 0.], iotype='in') ssa_F = Array([0.0], iotype='in') ssa_G = Array([0.0, 0.0], iotype='in') ssa_dF = Array([0.0, 0.0], iotype='in') ssa_dG = Array([[0.0, 0.0], [0.0, 0.0]], iotype='in') obj = Float(0.0, iotype='out') con1 = Float(0.0, iotype='out') con2 = Float(0.0, iotype='out') def execute(self): self.obj = self.ssa_F[0] + self.ssa_dF[0]*(self.z_store[0] - self.z1) + \ self.ssa_dF[1]*(self.z_store[1] - self.z2) self.con1 = self.ssa_G[0] + self.ssa_dG[0][0]*(self.z_store[0] - self.z1) + \ self.ssa_dG[0][1]*(self.z_store[1] - self.z2) self.con2 = self.ssa_G[1] + self.ssa_dG[1][0]*(self.z_store[0] - self.z1) + \ self.ssa_dG[1][1]*(self.z_store[1] - self.z2)
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))
class Thrust(Component): #Aerocalc Inputs yN = Array(iotype="in") ycmax = Float(iotype="in") Cl = Array(iotype="in") c = Array(iotype="in") rho = Float(iotype="in") Omega = Float(iotype="in") #Aerocalc intermediate values Ns = Int(iotype="in") dr = Array(iotype="in") r = Array(iotype="in") dT = Array(iotype="out") chordFrac = Array(iotype="out") def execute(self): self.chordFrac = np.ones(self.Ns) self.dT = np.zeros(self.Ns) for index, element in enumerate(self.yN): if element < self.ycmax: sTrans = index self.chordFrac[sTrans] = self.yN[sTrans + 1] self.chordFrac[sTrans] -= self.ycmax self.chordFrac[sTrans] /= (self.yN[sTrans + 1] - self.yN[sTrans]) self.dT += self.chordFrac self.dT *= 0.5 self.dT *= self.rho self.dT *= (self.Omega * self.r)**2 self.dT *= self.Cl self.dT *= self.c self.dT *= self.dr
class AccessRoads(Component): terrain = Enum('FLAT_TO_ROLLING', ('FLAT_TO_ROLLING', 'RIDGE_TOP', 'MOUNTAINOUS'), iotype='in', desc='terrain options') layout = Enum('SIMPLE', ('SIMPLE', 'COMPLEX'), iotype='in', desc='layout options') nTurbines = Int(iotype='in', desc='number of turbines') diameter = Float(iotype='in', units='m', desc='rotor diameter') constructionTime = Int(iotype='in', units='mo', desc='construction time') accessRoadEntrances = Int(iotype='in', desc='access road entrances') cost = Float(iotype='out', units='USD', desc='access roads and site improvement cost') def execute(self): self.cost = _landbos.accessRoadsCost(Enum2Int(self, 'terrain'), Enum2Int(self, 'layout'), self.nTurbines, self.diameter, self.constructionTime, self.accessRoadEntrances)
def build_trait(self, ref_name, iotype=None, trait=None): if iotype is None: iostat = 'in' else: iostat = iotype if trait is None: if ref_name.startswith('f'): trait = Float(0.0, iotype=iostat, ref_name=ref_name) elif ref_name.startswith('i'): trait = Int(0, iotype=iostat, ref_name=ref_name) else: self.raise_exception("can't determine type of variable '%s'" % ref_name, RuntimeError) return trait
def configure_lcoe_with_landbos(assembly): """ if with_landbos additional inputs: voltage distInter terrain layout soil """ #assembly.replace('bos_a', NREL_Land_BOSSE()) assembly.add('voltage', Float(iotype='in', units='kV', desc='interconnect voltage')) assembly.add('distInter', Float(iotype='in', units='mi', desc='distance to interconnect')) assembly.add('terrain', Enum('FLAT_TO_ROLLING', ('FLAT_TO_ROLLING', 'RIDGE_TOP', 'MOUNTAINOUS'), iotype='in', desc='terrain options')) assembly.add('layout', Enum('SIMPLE', ('SIMPLE', 'COMPLEX'), iotype='in', desc='layout options')) assembly.add('soil', Enum('STANDARD', ('STANDARD', 'BOUYANT'), iotype='in', desc='soil options')) assembly.add('transportDist',Float(0.0, iotype='in', units='mi', desc='transportation distance')) # TODO: add rest of land-bos connections # connections to bos assembly.connect('machine_rating', 'bos_a.machine_rating') assembly.connect('rotor.diameter', 'bos_a.rotor_diameter') assembly.connect('rotor.hubHt', 'bos_a.hub_height') assembly.connect('turbine_number', 'bos_a.turbine_number') assembly.connect('rotor.mass_all_blades + hub.hub_system_mass + nacelle.nacelle_mass', 'bos_a.RNA_mass') assembly.connect('voltage', 'bos_a.voltage') assembly.connect('distInter', 'bos_a.distInter') assembly.connect('terrain', 'bos_a.terrain') assembly.connect('layout', 'bos_a.layout') assembly.connect('soil', 'bos_a.soil') assembly.connect('transportDist','bos_a.transportDist')
class WeibullCDF(CDFBase): """Weibull cumulative distribution function""" A = Float(iotype='in', desc='scale factor') k = Float(iotype='in', desc='shape or form factor') def execute(self): self.F = 1.0 - np.exp(-(self.x / self.A)**self.k) def list_deriv_vars(self): inputs = ('x', ) outputs = ('F', ) return inputs, outputs def provideJ(self): x = self.x A = self.A k = self.k J = np.diag(np.exp(-(x / A)**k) * (x / A)**(k - 1) * k / A) return J
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 = Instance(Component, iotype='in') dummy_out = Instance(Component, iotype='out') dummy_out_no_copy = Instance(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 DrivenComponent(Component): """ Just something to be driven and compute results. """ x = Array([1., 1., 1., 1.], iotype='in') y = Array([1., 1., 1., 1.], iotype='in') raise_error = Bool(False, iotype='in') sleep = Float(0., iotype='in') rosen_suzuki = Float(0., iotype='out') sum_y = Float(0., iotype='out') def __init__(self): super(DrivenComponent, self).__init__() def execute(self): """ Compute results from input vector. """ self._logger.critical('execute x %s, y %s, raise_error %s', self.x, self.y, self.raise_error) if self.sleep: time.sleep(self.sleep) self.rosen_suzuki = rosen_suzuki(self.x) self.sum_y = sum(self.y) if self.raise_error: self.raise_exception('Forced error', RuntimeError)
def configure_lcoe_with_turb_costs(assembly): """ tcc_a inputs: advanced_blade = Bool offshore = Bool assemblyCostMultiplier = Float overheadCostMultiplier = Float profitMultiplier = Float transportMultiplier = Float """ assembly.replace('tcc_a', nrel_csm_tcc_2015()) # Turbine Cost and Mass Inputs # parameters / high level inputs assembly.add('machine_rating', Float(iotype='in', units='kW', desc='machine rating')) assembly.add('blade_number', Int(iotype='in', desc='number of rotor blades')) assembly.add('offshore', Bool(iotype='in', desc='flag for offshore project')) assembly.add('crane', Bool(iotype='in', desc='flag for presence of onboard crane')) assembly.add('bearing_number', Int(2, iotype='in', desc='number of main bearings []') )#number of main bearings- defaults to 2 assembly.add('rotor_diameter', Float(units = 'm', iotype='in', desc= 'rotor diameter of the machine')) assembly.add('turbine_class', Enum('I', ('I', 'II/III', 'User Exponent'), iotype = 'in', desc='turbine class')) assembly.add('blade_has_carbon', Bool(False, iotype='in', desc= 'does the blade have carbon?')) #default to doesn't have carbon #assembly.add('rotor_torque', Float(iotype='in', units='N * m', desc = 'torque from rotor at rated power')) #JMF do we want this default? assembly.add('hub_height', Float(units = 'm', iotype='in', desc= 'hub height of wind turbine above ground / sea level')) assembly.connect('machine_rating','tcc_a.machine_rating') assembly.connect('blade_number',['tcc_a.blade_number']) assembly.connect('offshore',['tcc_a.offshore']) assembly.connect('crane',['tcc_a.crane']) assembly.connect('bearing_number',['tcc_a.bearing_number']) assembly.connect('rotor_diameter','tcc_a.rotor_diameter') assembly.connect('turbine_class','tcc_a.turbine_class') assembly.connect('blade_has_carbon','tcc_a.blade_has_carbon') #assembly.connect('rotor_torque','tcc_a.rotor_torque') #TODO - fix assembly.connect('hub_height','tcc_a.hub_height')
class SortingComp(Component): """ Used to test alphanumeric sorting of inputs & outputs. """ stress_i1 = Float(iotype='in') stress_i2 = Float(iotype='in') stress_i10 = Float(iotype='in') stress_o1 = Float(iotype='out') stress_o2 = Float(iotype='out') stress_o10 = Float(iotype='out')
def __init__(self, num_elem=10): super(SysSFC, self).__init__() # Inputs self.add( 'h', Array(np.zeros((num_elem + 1, )), iotype='in', desc='Altitude')) self.add('SFCSL', Float(0.0, iotype='in', desc='sea-level SFC value')) # Outputs self.add( 'SFC', Array(np.zeros((num_elem + 1, )), iotype='out', desc='Specific Fuel Consumption'))
def test_transform_just_scale_or_add(self): self.top.comp.v1 = 15. self.top.comp.add_trait( 'v1', Float(0.0, low=-100.0, high=100.0, iotype='in')) self.top.driver.add_parameter('comp.v1', high=12.0, scaler=1.5) self.top.driver2.add_parameter('comp.v1', low=-6.0, adder=-2.) params = self.top.driver.get_parameters() params2 = self.top.driver2.get_parameters() d1val = params['comp.v1'].evaluate()[0] d2val = params2['comp.v1'].evaluate()[0] self.assertEqual(d1val, 10.0) self.assertEqual(d2val, 17.0)
def __init__(self, num_elem=10): """ scaling: 1e4 """ super(SysBlockTime, self).__init__() # Inputs self.add('v', Array(np.zeros((num_elem+1, )), iotype='in', desc = 'airspeed')) self.add('x', Array(np.zeros((num_elem+1, )), iotype='in', desc = 'distance')) self.add('Gamma', Array(np.zeros((num_elem+1, )), iotype='in', desc = 'flight path angle')) # Outputs self.add('time', Float(0.0, iotype='out', desc = 'Initial Mach number point'))
def __init__(self, num_elem=10): super(SysTmax, self).__init__() # Inputs self.add( 'tau', Array(np.zeros((num_elem + 1, )), iotype='in', desc='Throttle setting')) # Outputs self.add('Tmax', Float(0.0, iotype='out', desc='Maximum Thrust Constraint')) self.max = 1.0 self.rho = 100
class TPmassprops(VariableTree): """Basic Inertial and Geometric Properties of TP additional mass for towerSE""" mass = Float(units='kg', desc='TP lumped mass') #TP mass [kg] I = Array( np.zeros(6), dtype=np.float, units='kg*m**2', desc= 'TP lumped mass [IXX,IYY,IZZ,IXY,IXZ,IYZ] @deck height (=tower-base flange)' ) CMoff = Array( np.zeros(3), dtype=np.float, units=None, desc= 'TP lumped mass CM [x/DTP,y/DTP,z/TPlength] offset from deck height')
def __init__(self, **metadata): self._vals = {} Float.__init__(self, **metadata) self._metadata['type'] = 'property' # Just to show correct type.