class Top(Assembly): Src = VarTree(VTINputs(), iotype='in') Targ = VarTree(VTINputs(), iotype='out') def configure(self): pass
class MyComp(Component): ins = VarTree(tree(), iotype='in') outs = VarTree(tree(), iotype='out') def execute(self): self.outs = self.ins.copy() self.outs.z = 2.0*self.ins.x
class TstComponent(Component): dummy_data = VarTree(TstContainer(), iotype='in') dummy_data_out = VarTree(TstContainer(), iotype='out') dummyin = Float(iotype='in') def execute(self): self.dummy_data_out = self.dummy_data.copy()
class CompWithVarTreeSubTree(Component): ins = VarTree(TreeWithSubTree(), iotype="in") outs = VarTree(TreeWithFloat2(), iotype="out") outs2 = VarTree(TreeWithSubTree(), iotype="out") z = Float(iotype='out') def execute(self): self.outs.z = 2 * self.ins.x.x1 + 3 * self.ins.x.x2 + 4 * self.ins.y self.z = self.outs.z def provideJ(self): self.J = ones((2, 3)) self.J[:, 0] *= 2 self.J[:, 1] *= 3 self.J[:, 2] *= 4 return self.J def list_deriv_vars(self): ins = ('ins.x.x1', 'ins.x.x2', 'ins.y') outs = ('outs.z', 'z') return ins, outs
class VTComp(Component): vtree_in = VarTree(TstVtree(), iotype='in') vtree_out = VarTree(TstVtree(), iotype='out') def execute(self): self.vtree_out.floatval = self.vtree_in.floatval self.vtree_out.floatval2 = self.vtree_in.floatval2
class CompWithVarTreeSubTree(Component): ins = VarTree(TreeWithSubTree(), iotype="in") outs = VarTree(TreeWithSubTree(), iotype="out") def execute(self): self.outs.x = 2.0 * self.ins.x + 3.0 * self.ins.sub.x self.outs.sub.x = 4.0 * self.ins.x + 1.0 * self.ins.sub.x
def common_io(assembly, varspeed, varpitch): regulated = varspeed or varpitch # add inputs assembly.add('npts_coarse_power_curve', Int(20, iotype='in', desc='number of points to evaluate aero analysis at')) assembly.add('npts_spline_power_curve', Int(200, iotype='in', desc='number of points to use in fitting spline to power curve')) assembly.add('AEP_loss_factor', Float(1.0, iotype='in', desc='availability and other losses (soiling, array, etc.)')) if varspeed: assembly.add('control', VarTree(VarSpeedMachine(), iotype='in', desc='control parameters')) else: assembly.add('control', VarTree(FixedSpeedMachine(), iotype='in', desc='control parameters')) # add slots (must replace) assembly.add('geom', Slot(GeomtrySetupBase)) assembly.add('analysis', Slot(AeroBase)) assembly.add('dt', Slot(DrivetrainLossesBase)) assembly.add('cdf', Slot(CDFBase)) # add outputs assembly.add('AEP', Float(iotype='out', units='kW*h', desc='annual energy production')) assembly.add('V', Array(iotype='out', units='m/s', desc='wind speeds (power curve)')) assembly.add('P', Array(iotype='out', units='W', desc='power (power curve)')) assembly.add('diameter', Float(iotype='out', units='m', desc='rotor diameter')) if regulated: assembly.add('ratedConditions', VarTree(RatedConditions(), iotype='out'))
class BEMPerf(Component): """collects data from set of BladeElements and calculates aggregate values""" r = Float(.8, iotype="in", desc="tip radius of the rotor", units="m") rpm = Float(2100, iotype="in", desc="rotations per minute", low=0, units="min**-1") free_stream = VarTree(FlowConditions(), iotype="in") data = VarTree(BEMPerfData(), iotype="out") #this lets the size of the arrays vary for different numbers of elements def __init__(self, n=10): super(BEMPerf, self).__init__() #array size based on number of elements self.add( 'delta_Ct', Array(iotype='in', desc='thrusts from %d different blade elements' % n, default_value=np.ones((n, )), shape=(n, ), dtype=Float, units="N")) self.add( 'delta_Cp', Array(iotype='in', desc='Cp integrant points from %d different blade elements' % n, default_value=np.ones((n, )), shape=(n, ), dtype=Float)) self.add( 'lambda_r', Array(iotype='in', desc='lambda_r from %d different blade elements' % n, default_value=np.ones((n, )), shape=(n, ), dtype=Float)) def execute(self): self.data = BEMPerfData() # empty the variable tree V_inf = self.free_stream.V rho = self.free_stream.rho norm = (.5 * rho * (V_inf**2) * (pi * self.r**2)) self.data.Ct = np.trapz(self.delta_Ct, x=self.lambda_r) self.data.net_thrust = self.data.Ct * norm self.data.Cp = np.trapz(self.delta_Cp, x=self.lambda_r) * 8. / self.lambda_r.max()**2 self.data.net_power = self.data.Cp * norm * V_inf self.data.J = V_inf / (self.rpm / 60.0 * 2 * self.r)
class InandOutTree(Component): zzz = Float(iotype='out', desc='nonvartree', units='ft') ins = VarTree(InVtree(), iotype='in') outs = VarTree(OutVtree(), iotype='out') def execute(self): self.outs.x = 2 * self.ins.a self.outs.y = 2 * self.ins.a + self.ins.b
class SimpleComp(Component): cont_in = VarTree(DumbVT(), iotype='in') cont_out = VarTree(DumbVT(), iotype='out') def execute(self): self.cont_out.v1 = self.cont_in.v1 + 1.0 self.cont_out.v2 = self.cont_in.v2 + 1.0 self.cont_out.vt2.x = self.cont_in.vt2.x + 1.0 self.cont_out.vt2.y = self.cont_in.vt2.y + 1.0 self.cont_out.vt2.vt3.a = self.cont_in.vt2.vt3.a self.cont_out.vt2.vt3.b = self.cont_in.vt2.vt3.b if self.cont_in.data is not None: with self.cont_in.data.open() as inp: filename = '%s.data.vt' % self.name with open(filename, 'w') as out: out.write(inp.read()) self.cont_out.data = FileRef(filename, self) if self.cont_in.vt2.data is not None: with self.cont_in.vt2.data.open() as inp: filename = '%s.data.vt2' % self.name with open(filename, 'w') as out: out.write(inp.read()) self.cont_out.vt2.data = FileRef(filename, self) if self.cont_in.vt2.vt3.data is not None: with self.cont_in.vt2.vt3.data.open() as inp: filename = '%s.data.vt3' % self.name with open(filename, 'w') as out: out.write(inp.read()) self.cont_out.vt2.vt3.data = FileRef(filename, self) def get_vals(self, iotype): if iotype == 'in': cont = self.cont_in else: cont = self.cont_out return [ cont.v1, cont.v2, cont.vt2.x, cont.vt2.y, cont.vt2.vt3.a, cont.vt2.vt3.b, ] def get_files(self, iotype): if iotype == 'in': cont = self.cont_in else: cont = self.cont_out return [ cont.data, cont.vt2.data, cont.vt2.vt3.data, ]
class MEflows(VariableTree): """Container of variables defining the flow properties of the mixer-ejector nozzle""" gamma = Float(1.4, desc='Ratio of specific heats') Pstatic = Float(2116.8, units='lbf/ft**2', desc='Freestream static pressure') # alt = Float(0.0, units='ft', desc='Altitude') # Mach = Float(0.0, desc='Freestream Mach number') pri = VarTree(Stream()) sec = VarTree(Stream())
class InandOutTree(Component): ins = VarTree(InVtree(), iotype="in") outs = VarTree(OutVtree(), iotype="out") def execute(self): self.outs.x = 2*self.ins.a self.outs.y = 2*self.ins.a+self.ins.b
class AeroHydroLoads(Component): windLoads = VarTree(FluidLoads(), iotype='in', desc='wind loads in inertial coordinate system') waveLoads = VarTree(FluidLoads(), iotype='in', desc='wave loads in inertial coordinate system') z = Array(iotype='in', desc='locations along tower') yaw = Float(0.0, iotype='in', units='deg', desc='yaw angle') outloads = VarTree(FluidLoads(), iotype='in', desc='combined wind and wave loads') Px = Array(iotype='out', units='N/m', desc='force per unit length in x-direction') Py = Array(iotype='out', units='N/m', desc='force per unit length in y-direction') Pz = Array(iotype='out', units='N/m', desc='force per unit length in z-direction') qdyn = Array(iotype='out', units='N/m**2', desc='dynamic pressure') def execute(self): # aero/hydro loads wind = self.windLoads wave = self.waveLoads hubHt = self.z[-1] # top of tower betaMain = np.interp( hubHt, self.z, wind.beta) # wind coordinate system defined relative to hub height windLoads = DirectionVector( wind.Px, wind.Py, wind.Pz).inertialToWind(betaMain).windToYaw(self.yaw) waveLoads = DirectionVector( wave.Px, wave.Py, wave.Pz).inertialToWind(betaMain).windToYaw(self.yaw) self.outloads.Px = np.interp(self.z, wind.z, windLoads.x) + np.interp( self.z, wave.z, waveLoads.x) self.outloads.Py = np.interp(self.z, wind.z, windLoads.y) + np.interp( self.z, wave.z, waveLoads.y) self.outloads.Pz = np.interp(self.z, wind.z, windLoads.z) + np.interp( self.z, wave.z, waveLoads.z) self.outloads.qdyn = np.interp(self.z, wind.z, wind.qdyn) + np.interp( self.z, wave.z, wave.qdyn) self.outloads.z = self.z #The following are redundant, at one point we will consolidate them to something that works for both tower (not using vartrees) and jacket (still using vartrees) self.Px = self.outloads.Px self.Py = self.outloads.Py self.Pz = self.outloads.Pz self.qdyn = self.outloads.qdyn
def __init__(self, Ns): super(Switch, self).__init__() # inputs self.add('fblade_initial', VarTree(Fblade(Ns), iotype='in')) self.add('fblade_updated', VarTree(Fblade(Ns), iotype='in')) # outputs self.add('fblade', VarTree(Fblade(Ns), iotype='out')) self.initial = True self.force_execute = True
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 Top(Assembly): Pileinputs = VarTree(PileGeoInputs(), iotype='in', desc="Pile Input Data") SPIstiffness = VarTree(PileGeoInputs(), iotype='out', desc="Pile Input Data") def configure(self): self.connect('Pileinputs.Lp', 'SPIstiffness.Lp') self.disconnect('Pileinputs.Lp', 'SPIstiffness.Lp') self.add('comp', MyComp()) self.driver.workflow.add('comp') self.connect('Pileinputs.Lp', 'comp.x')
class CompWithArrayVarTree(Component): ins = VarTree(TreeWithArray(), iotype="in") outs = VarTree(TreeWithArray(), iotype="out") def execute(self): self.outs.x[0] = 2*self.ins.x[0] + 6*self.ins.x[1] self.outs.x[1] = 4*self.ins.x[0] + 6*self.ins.x[1] def provideJ(self): self.J = array([[2., 6.], [4., 6.]]) return self.J def list_deriv_vars(self): return ('ins.x',), ('outs.x',)
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 TestComponent(Component): dummy_data = VarTree(TestContainer(), iotype='in') x = Float(iotype='out') def execute(self): self.x = (self.dummy_data.dummy1 - 3)**2 - self.dummy_data.dummy2
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 CompWithVarTree(Component): x1 = Float(iotype="in") ins = VarTree(TreeWithFloat2(), iotype="in") outs = VarTree(TreeWithFloat2(), iotype="out") z = Float(iotype="out") def execute(self): self.outs.z = 2*self.ins.z + 6*self.x1 self.z = 4*self.ins.z + 6*self.x1 def provideJ(self): self.J = array([[2., 6.], [4., 6.]]) return self.J def list_deriv_vars(self): return ('ins.z', 'x1'), ('outs.z', 'z')
class VarTreeSink2(Component): invar = VarTree(DumbVTSubVarReq(), iotype="in") outvar = Float(1.5, iotype="out") def execute(self): pass
class VarTreeSink(Component): invar = VarTree(DumbVT(), iotype="in", required=True) outvar = Float(1.5, iotype="out") def execute(self): pass
class VarTreeSource(Component): invar = Float(2.0, iotype="in") outvar = VarTree(DumbVT(), iotype="out") def execute(self): pass
class C1_vt(Component): vt = VarTree(V(), iotype='in') i = Int(0, iotype='in') val = Int(0, iotype='out') def execute(self): self.val = self.vt.l[self.i]
class AComp(Component): inp = Float(iotype='in') out = VarTree(OutputVT(), iotype='out') def execute(self): self.out.a = 2 * self.inp
class GeomComponent(Component): x = Float(1.0, iotype='in') geom_out = VarTree(GeomData(2, 1), iotype='out') def list_deriv_vars(self): return ('x'), ('geom_out.points', ) def provideJ(self): self.J = np.array([[2, 0, 1], [0, 2, 1]], dtype=np.float) def apply_deriv(self, arg, result): result['geom_out.points'][0, :] += self.J[0, :] * arg['x'] result['geom_out.points'][1, :] += self.J[1, :] * arg['x'] def apply_derivT(self, arg, result): result['x'] += np.sum(self.J.T[:, 0] * arg['geom_out.points'][0, :]) result['x'] += np.sum(self.J.T[:, 1] * arg['geom_out.points'][1, :]) def execute(self): x = self.x J = np.array([[2, 0, 1], [0, 2, 1]]) self.geom_out.points[0, :] = J[0, :] * x self.geom_out.points[1, :] = J[1, :] * x
class AeroBase(Component): """A base component for a rotor aerodynamics code.""" run_case = Enum('power', ('power', 'loads'), iotype='in') # --- use these if (run_case == 'power') --- # inputs Uhub = Array(np.array([1.0]), iotype='in', units='m/s', desc='hub height wind speed') Omega = Array(np.array([0.0]), iotype='in', units='rpm', desc='rotor rotation speed') pitch = Array(np.array([0.0]), iotype='in', units='deg', desc='blade pitch setting') # outputs T = Array(np.array([0.0]), iotype='out', units='N', desc='rotor aerodynamic thrust') Q = Array(np.array([0.0]), iotype='out', units='N*m', desc='rotor aerodynamic torque') P = Array(np.array([0.0]), iotype='out', units='W', desc='rotor aerodynamic power') # --- use these if (run_case == 'loads') --- # if you only use rotoraero.py and not rotor.py # (i.e., only care about power curves, and not structural loads) # then these second set of inputs/outputs are not needed # inputs V_load = Float(iotype='in', units='m/s', desc='hub height wind speed') Omega_load = Float(iotype='in', units='rpm', desc='rotor rotation speed') pitch_load = Float(iotype='in', units='deg', desc='blade pitch setting') azimuth_load = Float(iotype='in', units='deg', desc='blade azimuthal location') # outputs loads = VarTree(AeroLoads(), iotype='out', desc='loads in blade-aligned coordinate system')
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 SetupRunVarSpeed(Component): """determines approriate conditions to run AeroBase code across the power curve""" control = VarTree(VarSpeedMachine(), iotype='in', desc='control parameters') R = Float(iotype='in', units='m', desc='rotor radius') npts = Int(20, iotype='in', desc='number of points to evalute aero code to generate power curve') # outputs Uhub = Array(iotype='out', units='m/s', desc='freestream velocities to run') Omega = Array(iotype='out', units='rpm', desc='rotation speeds to run') pitch = Array(iotype='out', units='deg', desc='pitch angles to run') missing_deriv_policy = 'assume_zero' def execute(self): ctrl = self.control n = self.npts R = self.R # # attempt to distribute points mostly before rated # cpguess = 0.5 # Vr0 = (ctrl.ratedPower/(cpguess*0.5*rho*pi*R**2))**(1.0/3) # Vr0 *= 1.20 # V1 = np.linspace(Vin, Vr0, 15) # V2 = np.linspace(Vr0, Vout, 6) # V = np.concatenate([V1, V2[1:]]) # velocity sweep V = np.linspace(ctrl.Vin, ctrl.Vout, n) # corresponding rotation speed Omega_d = ctrl.tsr*V/R*RS2RPM Omega, dOmega_dOmegad, dOmega_dmaxOmega = smooth_min(Omega_d, ctrl.maxOmega, pct_offset=0.01) # store values self.Uhub = V self.Omega = Omega self.pitch = ctrl.pitch*np.ones_like(V) # gradients dV = np.zeros((n, 3)) dOmega_dtsr = dOmega_dOmegad * V/R*RS2RPM dOmega_dR = dOmega_dOmegad * -ctrl.tsr*V/R**2*RS2RPM dOmega = hstack([dOmega_dtsr, dOmega_dR, dOmega_dmaxOmega]) dpitch = np.zeros((n, 3)) self.J = vstack([dV, dOmega, dpitch]) def list_deriv_vars(self): inputs = ('control.tsr', 'R', 'control.maxOmega') outputs = ('Uhub', 'Omega', 'pitch') return inputs, outputs def provideJ(self): return self.J