def make_graph(nodes=(), connections=()): scope = set_as_top(Assembly()) sub = scope.add('sub',Assembly()) dep = ExprMapper(sub) for name in nodes: if name.startswith('parent.'): scope.add(name.split('.',1)[1], Simple()) else: sub.add(name, Simple()) #dep.add(name) for src,dest in connections: if '.' not in src and not sub.contains(src): if dest.startswith('parent.'): iotype='out' else: iotype='in' sub.add(src, Int(1, iotype=iotype)) if '.' not in dest and not sub.contains(dest): if src.startswith('parent.'): iotype='in' else: iotype='out' sub.add(dest, Int(1, iotype=iotype)) dep.connect(ExprEvaluator(src,sub), ExprEvaluator(dest,sub), sub) return dep, sub
class Erection(Component): rating = Float(iotype='in', units='kW', desc='machine rating') hubHeight = Float(iotype='in', units='m', desc='hub height') nTurbines = Int(iotype='in', desc='number of turbines') weatherDelayDays = Int(iotype='in', units='d', desc='weather delay days') craneBreakdowns = Int(iotype='in', desc='crane breakdowns') deliveryAssistRequired = Bool(iotype='in', desc='delivery assist required') cost = Float(iotype='out', units='USD', desc='erection cost') def execute(self): self.cost = _landbos.erectionCost(self.rating, self.hubHeight, self.nTurbines, self.weatherDelayDays, self.craneBreakdowns, self.deliveryAssistRequired) def list_deriv_vars(self): inputs = ('hubHeight', ) outputs = ('cost', ) return inputs, outputs def provideJ(self): dhubHt = _landbos.deriv_erectionCost(self.nTurbines) J = np.array([[dhubHt]]) return J
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 BenchMark(Component): # set up interface to the framework # pylint: disable=E1101 x1 = Int(10, iotype='in', desc='The variable x1') x2 = Int(10, iotype='in', desc='The variable x2') x3 = Int(10, iotype='in', desc='The variable x2') f_x = Float(iotype='out', desc='f(x)') g1_x = Float(iotype='out', desc='g(x)') h1_x = Float(iotype='out', desc='h(x)') def execute(self): x1 = self.x1 x2 = self.x2 x3 = self.x3 #print "WAHHHH: ", self.x1 self.f_x = -x1 * x2 * x3 self.g1_x = x1 + 2. * x2 + 2. * x3 - 72.0 self.h1_x = -x1 - 2. * x2 - 2. * x3
class showBPMtext(Component): """ Shows the estimated BPM in the image frame """ ready = Bool(False, iotype="in") bpm = Float(iotype="in") x = Int(iotype="in") y = Int(iotype="in") fps = Float(iotype="in") size = Float(iotype="in") n = Int(iotype="in") def __init__(self): super(showBPMtext, self).__init__() self.add("frame_in", Array(iotype="in")) self.add("frame_out", Array(iotype="out")) self.bpms = [] def execute(self): self.bpms.append([time.time(), self.bpm]) if self.ready: col = (0, 255, 0) text = "%0.1f bpm" % self.bpm tsize = 2 else: col = (100, 255, 100) gap = (self.n - self.size) / self.fps text = "(estimate: %0.1f bpm, wait %0.0f s)" % (self.bpm, gap) tsize = 1 cv2.putText(self.frame_in, text, (self.x, self.y), cv2.FONT_HERSHEY_PLAIN, tsize, col) self.frame_out = self.frame_in
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]
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 DakotaGlobalSAStudy(DakotaBase): """ Global sensitivity analysis using DAKOTA. """ sample_type = Enum('lhs', iotype='in', values=('random', 'lhs'), desc='Type of sampling') seed = Int(52983, iotype='in', desc='Seed for random number generator') samples = Int(100, iotype='in', low=1, desc='# of samples to evaluate') def configure_input(self): """ Configures input specification. """ objectives = self.get_objectives() self.input.method = [ 'sampling', ' output = %s' % self.output, ' sample_type = %s' % self.sample_type, ' seed = %s' % self.seed, ' samples = %s' % self.samples ] self.set_variables(need_start=False, uniform=True) names = ['%r' % name for name in objectives.keys()] self.input.responses = [ 'num_response_functions = %s' % len(objectives), 'response_descriptors = %s' % ' '.join(names), 'no_gradients', 'no_hessians' ]
class IterateUntil(Driver): """ A simple driver to run a workflow until some stop condition is met. """ max_iterations = Int(10, iotype="in", desc="Maximum number of iterations.") iteration = Int(0, iotype="out", desc="Current iteration counter.") run_at_least_once = Bool(True, iotype="in", desc="If True, driver will" " ignore stop conditions for the first iteration" " and run at least one iteration.") def start_iteration(self): """ Code executed before the iteration. """ self.iteration = 0 def continue_iteration(self): """ Convergence check.""" if self.iteration < 1 and self.run_at_least_once: self.iteration += 1 return True if self.should_stop(): return False if self.iteration < self.max_iterations: self.iteration += 1 return True return False
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
class LatinHypercube(Container): """IDOEgenerator which provides a Latin hypercube DOE sample set. """ implements(IDOEgenerator) num_samples = Int(20, desc="Number of sample points in the DOE sample set.") num_parameters = Int(2, desc="Number of parameters, or dimensions, for the DOE.") def __init__(self, num_samples=None, ): super(LatinHypercube,self).__init__() if num_samples is not None: self.num_samples = num_samples def __iter__(self): """Return an iterator over our sets of input values.""" return self._get_input_values() def _get_input_values(self): rand_doe = rand_latin_hypercube(self.num_samples, self.num_parameters) for row in rand_doe: yield row
class FullFactorial(Container): """ DOEgenerator that performs a full-factorial Design of Experiments. Plugs into the DOEgenerator socket on a DOEdriver.""" implements(IDOEgenerator) # pylint: disable-msg=E1101 num_parameters = Int(0, iotype="in", desc="Number of independent " "parameters in the DOE.") num_levels = Int(0, iotype="in", desc="Number of levels of values for " "each parameter.") def __init__(self, num_levels=0, *args, **kwargs): super(FullFactorial, self).__init__(*args, **kwargs) self.num_levels = num_levels def __iter__(self): """Return an iterator over our sets of input values.""" return product(*[ linspace(0., 1., self.num_levels) for i in range(self.num_parameters) ])
class OptLatinHypercube(Container): """IDOEgenerator which provides a Latin hypercube DOE sample set. The Morris-Mitchell sampling criterion of the DOE is optimzied using an evolutionary algorithm. """ implements(IDOEgenerator) num_samples = Int(20, desc="Number of sample points in the DOE sample set.") num_parameters = Int( 2, desc="Number of parameters, or dimensions, for the DOE.") population = Int( 20, desc="Size of the population used in the evolutionary optimization.") generations = Int( 2, desc="Number of generations the optimization will evolve over.") norm_method = Enum( ["1-norm", "2-norm"], desc= "Vector norm calculation method. '1-norm' is faster but less accurate." ) seed = Int(None, iotype="in", desc="Random seed for the optimizer. Set to a specific value " "for repeatable results; otherwise leave as None for truly " "random seeding.") def __init__(self, num_samples=None, population=None, generations=None): super(OptLatinHypercube, self).__init__() self.qs = [1, 2, 5, 10, 20, 50, 100] #list of qs to try for Phi_q optimization if num_samples is not None: self.num_samples = num_samples if population is not None: self.population = population if generations is not None: self.generations = generations def __iter__(self): """Return an iterator over our sets of input values.""" if self.seed is not None: seed(self.seed) return self._get_input_values() def _get_input_values(self): rand_doe = rand_latin_hypercube(self.num_samples, self.num_parameters) best_lhc = LHC_indivudal(rand_doe, q=1, p=_norm_map[self.norm_method]) for q in self.qs: lh = LHC_indivudal(rand_doe, q, _norm_map[self.norm_method]) lh_opt = _mmlhs(lh, self.population, self.generations) if lh_opt.mmphi() < best_lhc.mmphi(): best_lhc = lh_opt for row in best_lhc: yield row
def __init__(self, Ns): super(ActuatorDiskInducedVelocity, self).__init__() # inputs self.add('Ns', Int(0, iotype='in', desc='number of elements')) self.add( 'r', Array(np.zeros(Ns), iotype='in', desc='radial location of each element')) self.add( 'dr', Array(np.zeros(Ns), iotype='in', desc='length of each element')) self.add('R', Float(0., iotype='in', desc='rotor radius')) self.add('b', Int(0, iotype='in', desc='number of blades')) self.add('h', Float(0., iotype='in', desc='height of rotor')) self.add('vc', Float(0., iotype='in', desc='vertical velocity')) self.add('rho', Float(0., iotype='in', desc='air density')) self.add('dT', Array(np.zeros((Ns, 1)), iotype='in', desc='thrust')) # outputs self.add( 'vi', Array(np.zeros(Ns), iotype='out', desc='induced downwash distribution'))
class ActuatorDiskInducedVelocity(Component): ''' Compute induced velocity using annual-ring actuator disk theory ''' # inputs Ns = Int(iotype='in', desc='number of elements') r = Array(iotype='in', desc='radial location of each element') dr = Array(iotype='in', desc='length of each element') R = Float(iotype='in', desc='rotor radius') b = Int(iotype='in', desc='number of blades') h = Float(iotype='in', desc='height of rotor') vc = Float(iotype='in', desc='vertical velocity') rho = Float(iotype='in', desc='air density') dT = Array(iotype='in', desc='thrust') # outputs vi = Array(iotype='out', desc='induced downwash distribution') def execute(self): self.vi = np.zeros((self.Ns, 1)) for s in range(self.Ns): sq = 0.25 * self.vc**2 + \ 0.25 * self.b * self.dT[s] / (np.pi * self.rho * self.r[s] * self.dr[s]) self.vi[s] = -0.5*self.vc + np.sqrt(sq) # Add ground effect Cheesemen & Benett's self.vi /= (1. + (self.R / self.h / 4.) ** 2)
class TwrGeoOutputs(VariableTree): """Basic Geometric Outputs needed to build Tower of Jacket.""" TwrObj = Instance(Klass=Tube, desc='Object of Class Tube for Tower portion of Jacket') Twr2RNAObj = Instance( Klass=RigidMember, desc='Object of Class RigidMember for Rigid Tower portion') joints = Array(np.array([]), units='m', dtype=np.float, desc='Pile Joint (with legs) Coordinates (3,nlegs=nfaces)') nodes = Array(np.empty((3, 10)), units='m', dtype=np.float, desc='Tower ALL Nodes' ' Coordinates (3,nNodes)') nNodes = Int(0, units=None, desc='Number of Tower Nodes INCLUDING joint at TP') nElems = Int(0, units=None, desc='Number of of elements in the flexible portion of tower') mass = Float(units='kg', desc='Tower Mass') TopMass = Array( np.zeros([10]), dtype=np.float, desc= 'Tower Top mass, Ixx, Iyy, Izz,Ixy,Ixz,Iyz,CMxoff,CMyoff,CMzoff from RNA properties in input' ) TopMass_yaw = Array( np.zeros([10]), dtype=np.float, desc= 'Tower Top mass, Ixx, Iyy, Izz,Ixy,Ixz,Iyz,CMxoff,CMyoff,CMzoff from RNA properties in input including yaw angle w.r.t. Global XYZ' ) TwrlumpedMass = Array( np.zeros([1, 11]), dtype=np.float, desc='Concentrated masses along tower: first column z' 's from base of tower; 2nd through 11th column: mass and Ixx,Iyy,Izz,Ixy,Ixz,Iyz,CMxoff,CMyoff,CMzoff values' ) HH = Float(units='m', desc='Hub-Height') Htwr = Float(units='m', desc='Tower Length') Htwr2 = Float(units='m', desc='Tower at constant cross section Length') Thoff_yaw = Array( np.zeros([3]), units='m', dtype=np.float, desc= 'Tower-top to Hub-center vector in yawed coordinate system (TO BE MOVED SOMEWHERE ELSE at one point)' ) rna_yawedcm = Array( np.zeros([3]), dtype=np.float, desc= 'Tower Top mass CMxoff,CMyoff,CMzoff in yawed coordinate system(TO BE MOVED SOMEWHERE ELSE at one point)' )
class PGrafComponent(Assembly): num = Int(iotype='in') inputs = Slot(PGrafObject) result = Int(iotype='out') def execute(self): print "comp execute" self.result = self.inputs.num + self.inputs.num
class PGrafComponent(Component): num = Int(iotype='in') obj = Slot(PGrafObject) result = Int(iotype='out') def execute(self): self.result = self.num + self.obj.num
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 Dummy(Component): a = Float(iotype="in") b = Float(iotype="in") x = Float(iotype="out") y = Float(iotype="out") i = Int(iotype="in") j = Int(iotype="out") farr = Array([1.1, 2.2, 3.3]) iarr = Array([1, 2, 3]) en = Enum(values=['foo', 'bar', 'baz'], iotype='in')
class PGrafComponent(Component): num = Int(iotype='in') # BAN - changed obj to an Instance with iotype defined in order to make obj # visible in the mpi-enabled framework. #obj = Slot(PGrafObject) obj = Instance(PGrafObject, iotype='in') result = Int(iotype='out') def execute(self): self.result = self.num + self.obj.num
class bos_csm_assembly(Assembly): # Variables machine_rating = Float(iotype='in', units='kW', desc='turbine machine rating') rotor_diameter = Float(iotype='in', units='m', desc='rotor diameter') hub_height = Float(iotype='in', units='m', desc='hub height') RNA_mass = Float(iotype='in', units='kg', desc='Rotor Nacelle Assembly mass') turbine_cost = Float(iotype='in', units='USD', desc='Single Turbine Capital _costs') # Parameters turbine_number = Int(iotype='in', desc='number of turbines in project') sea_depth = Float(20.0, units='m', iotype='in', desc='sea depth for offshore wind plant') year = Int(2009, iotype='in', desc='year for project start') month = Int(12, iotype='in', desc='month for project start') multiplier = Float(1.0, iotype='in') # Outputs bos_breakdown = VarTree(BOSVarTree(), iotype='out', desc='BOS cost breakdown') bos_costs = Float( iotype='out', desc= 'Overall wind plant balance of station/system costs up to point of comissioning' ) def configure(self): super(bos_csm_assembly, self).configure() configure_extended_bos(self) self.replace('bos', bos_csm_component()) self.connect('machine_rating', 'bos.machine_rating') self.connect('rotor_diameter', 'bos.rotor_diameter') self.connect('hub_height', 'bos.hub_height') self.connect('RNA_mass', 'bos.RNA_mass') self.connect('turbine_cost', 'bos.turbine_cost') self.connect('turbine_number', 'bos.turbine_number') self.connect('sea_depth', 'bos.sea_depth') self.connect('year', 'bos.year') self.connect('month', 'bos.month') self.connect('multiplier', 'bos.multiplier')
class Results(Component): # inputs b = Int(iotype='in', desc='number of blades') Ns = Int(iotype='in', desc='number of elements') yN = Array(iotype='in', desc='node locations') yE = Array(iotype='in', desc='') cE = Array(iotype='in', desc='chord of each element') Cl = Array(iotype='in', desc='lift coefficient distribution') q = Array(iotype='in', desc='deformation') phi = Array(iotype='in', desc='') collective = Float(iotype='in', desc='collective angle in radians') fblade = VarTree(Fblade(), iotype='in') Mtot = Float(0.0, iotype='in', desc='total mass') # outputs di = Array(iotype='out', desc='dihedral angle') alphaJig = Array(iotype='out', desc='aerodynamic jig angle') Ttot = Float(iotype='out', desc='total thrust') Qtot = Float(iotype='out', desc='total torque') MomRot = Float(iotype='out', desc='total moment') Ptot = Float(iotype='out', desc='total powers') def execute(self): # Compute aerodynamic jig angle self.alphaJig = np.zeros(self.cE.shape) qq = np.zeros((6, self.Ns + 1)) for s in range(1, self.Ns + 1): qq[:, s] = self.q[s * 6:s * 6 + 6].T Clalpha = 2 * pi for s in range(0, len(self.yN) - 1): self.alphaJig[s] = self.Cl[s] / Clalpha \ - (qq[4, s] + qq[4, s+1]) / 2 \ + self.phi[s] - self.collective # Compute dihedral angle self.di = np.zeros((self.Ns, 1)) for s in range(0, self.Ns): self.di[s] = arctan2(qq[2, s + 1] - qq[2, s], self.yN[s + 1] - self.yN[s]) # Compute totals # (Note: reshaping is due to numpy vs MATLAB 1D array shapes.. should scrub this) self.Ttot = np.sum( self.fblade.Fz.reshape(-1, 1) * np.cos(self.di)) * self.b * 4 self.MomRot = np.sum( self.fblade.Fz.reshape(-1, 1) * self.yE.reshape(-1, 1)) self.Qtot = np.sum(self.fblade.Q) * self.b * 4 Pitot = np.sum(self.fblade.Pi) * self.b * 4 Pptot = np.sum(self.fblade.Pp) * self.b * 4 self.Ptot = Pptot + Pitot # non-covered centre
class TestComponent(Component): """ Component which tracks it's total executions and can request that the run be stopped. """ dummy_input = Int(0, iotype='in') set_stop = Bool(False, iotype='in') total_executions = Int(0, iotype='out') def execute(self): self.total_executions += 1 if self.set_stop: self.parent.driver.stop()
class SiteCompound(Component): constructionTime = Int(iotype='in', units='mo', desc='construction time') accessRoadEntrances = Int(iotype='in', desc='access road entrances') farmSize = Float(iotype='in', units='MW', desc='wind farm size') cost = Float(iotype='out', units='USD', desc='site compound and security cost') def execute(self): self.cost = _landbos.siteCompoundCost(self.accessRoadEntrances, self.constructionTime, self.farmSize)
class MyEvComp(Component): doit = Event(desc='Do It!') doit2 = Event(desc='Do It Again!') doit_count = Int(0, iotype='out') doit2_count = Int(0, iotype='out') some_int = Int(0, iotype='in') def _doit_fired(self): self.doit_count += 1 def _doit2_fired(self): self.doit2_count += 1 def execute(self): pass
def __init__(self, iotype, client, rpath): ProxyMixin.__init__(self, client, rpath) default = self._value = int(self._valstr) desc = client.get(rpath+'.description') if client.get(rpath+'.hasUpperBound') == 'true': high = int(client.get(rpath+'.upperBound')) else: high = None if client.get(rpath+'.hasLowerBound') == 'true': low = int(client.get(rpath+'.lowerBound')) else: low = None Int.__init__(self, default_value=default, iotype=iotype, desc=desc, low=low, high=high)
class FComp(Component): infile = File(iotype='in', local_path='input') outfile = File(FileRef('output'), iotype='out') outval = Int(iotype='out') def execute(self): """ Runs code and sets `outfile`. """ with open(self.infile.abspath()) as f: s = f.read().strip() val = int(s.split()[1]) self.outval = val + 1 fname = self.outfile.abspath() print "about to open", fname sys.stdout.flush() with open(fname, 'w') as f: print "writing %s %d %d to %s" % (self.name, self.outval, MPI.COMM_WORLD.rank, fname) sys.stdout.flush() f.write("%s %d %d\n" % (self.name, self.outval, MPI.COMM_WORLD.rank)) print "wrote %s %d %d to %s" % (self.name, self.outval, MPI.COMM_WORLD.rank, fname) sys.stdout.flush()
class Summer(Driver): """Sums the objective over some number of iterations, feeding its current sum back into the specified parameter.""" max_iterations = Int(1, iotype='in') sum = Float(iotype='out') def __init__(self): super(Summer, self).__init__() self.itercount = 0 def continue_iteration(self): return self.itercount < self.max_iterations def start_iteration(self): self.itercount = 0 self.sum = 0.001 def pre_iteration(self): self.set_parameters([self.sum]) def post_iteration(self): self.sum += self.eval_objective() self.itercount += 1 def execute(self): global exec_order exec_order.append(self.name) super(Summer, self).execute()
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]