class FstWrapper(FstExternalCode): FSTexe = Str(io_type='in', desc='Path to executable') FSTInputFile = Str(iotype='in', desc='FAST input file (ext=.fst)') fst_directory = Str(iotype='in', desc='Path to fst directory files') def __init__(self): super(FstWrapper, self).__init__() def execute(self): print "Executing FAST" self.input_file = os.path.join(self.fst_directory, self.FSTInputFile) if (not os.path.exists(self.FSTexe)): sys.stderr.write("Can't find FAST executable: {:}\n".format( self.FSTexe)) return 0 print "calling ", self.FSTexe print "input file=", self.input_file self.command.append(self.FSTexe) self.command.append(self.input_file) super(FstWrapper, self).execute()
class SubCounterComp(Component): # --- Initialize counter variable --- config = Str('', iotype='out', desc='full ID string') case = Str('', iotype='in', desc='current DOE case number') power_level = Int(100, iotype='in', desc='% thrust setting') reset_iteration = Event() def _reset_iteration_fired(self): self._iteration = 0 def __init__(self, *args, **kwargs): # --------------------------------------------- # --- Constructor for the counter component --- # --------------------------------------------- super(SubCounterComp, self).__init__(*args, **kwargs) # --- Edit this line to override default numbering # --- If restarting, should equal the subiteration number of the last successful case + 1 # --- Needs to be 0 if starting a new case self._iteration = 7 self.force_execute = True def execute(self): self.config = '%s_%s_%s' % (self.case, str( self._iteration), str(self.power_level)) self._iteration += 1 print '--------------------------------------------------' print 'Starting Simulation ', self.config print '--------------------------------------------------'
class HAWC2ConstraintFix23(VariableTree): con_type = Str() mbdy = Str(desc='Main_body name to which the next main_body is fixed') dof = Array(np.zeros(3), desc='Direction in global coo that is fixed in rotation' '0: free, 1: fixed')
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 HAWC2Constraint(VariableTree): con_name = Str() con_type = Enum('free', ('fixed', 'fixed_to_body', 'free', 'prescribed_angle'), desc='Constraint type') body1 = Str(desc='Main body name to which the body is attached') DOF = Array(np.zeros(6), desc='Degrees of freedom')
def __init__(self, excelFile, xmlFile): super(ExcelWrapper, self).__init__() self.xmlFile = xmlFile try: tree = ET.parse(self.xmlFile) except: if not os.path.exists(self.xmlFile): print 'Cannot find the xml file at ' + self.xmlFile self.variables = tree.findall("Variable") for v in self.variables: name = v.attrib['name'] kwargs = dict([(key, v.attrib[key]) for key in ('iotype', 'desc', 'units') if key in v.attrib]) if v.attrib['iotype'] == 'in': if v.attrib['type'] == 'Float': self.add(v.attrib['name'], Float(float(v.attrib['value']), **kwargs)) elif v.attrib['type'] == 'Int': self.add(v.attrib['name'], Int(int(v.attrib['value']), **kwargs)) elif v.attrib['type'] == 'Bool': self.add( v.attrib['name'], Bool(ast.literal_eval(v.attrib['value']), **kwargs)) elif v.attrib['type'] == 'Str': self.add(v.attrib['name'], Str(v.attrib['value'], **kwargs)) else: if v.attrib['type'] == 'Float': self.add(v.attrib['name'], Float(**kwargs)) elif v.attrib['type'] == 'Int': self.add(v.attrib['name'], Int(**kwargs)) elif v.attrib['type'] == 'Bool': self.add(v.attrib['name'], Bool(**kwargs)) elif v.attrib['type'] == 'Str': self.add(v.attrib['name'], Str(**kwargs)) self.excelFile = excelFile self.xlInstance = None self.workbook = None self.ExcelConnectionIsValid = True if not os.path.exists(self.excelFile): print "Invalid file given" self.ExcelConnectionIsValid = False else: self.excelFile = os.path.abspath(self.excelFile) xl = self.openExcel() if xl is None: print "Connection to Excel failed." self.ExcelConnectionIsValid = False else: self.xlInstance = xl self.workbook = xl.Workbooks.Open(self.excelFile)
class Texture(XMLContainer): """ XML parameters for a texture/image applied to a surface. """ XMLTAG = 'Applied_Texture' texture_name = Str('Default_Name', iotype='in', xmltag='Name', desc='Name of texture.') texture_filename = Str('Default_Name', iotype='in', xmltag='Texture_Name', desc='Filename for texture data (.jpg or .tga)') all_surf_flag = Bool(False, iotype='in', xmltag='All_Surf_Flag', desc='If True, apply to all surfaces of component.') surf_id = Int(0, iotype='in', xmltag='Surf_ID', desc='ID of surface to apply to.') u = Float(0.5, iotype='in', xmltag='U', desc='Position along U axis.') w = Float(0.5, iotype='in', xmltag='W', desc='Position along W axis.') scale_u = Float(1.0, iotype='in', xmltag='Scale_U', desc='Scaling in U direction.') scale_w = Float(1.0, iotype='in', xmltag='Scale_W', desc='Scaling in W direction.') wrap_u = Bool(False, iotype='in', xmltag='Wrap_U_Flag', desc='') wrap_w = Bool(False, iotype='in', xmltag='Wrap_W_Flag', desc='') repeat = Bool(False, iotype='in', xmltag='Repeat_Flag', desc='Repeat texture over surface.') bright = Float(1.0, low=0., high=1., iotype='in', xmltag='Bright', desc='Brightness.') alpha = Float(1.0, low=0., high=1., iotype='in', xmltag='Alpha', desc='Transparency.') flip_u = Bool(False, iotype='in', xmltag='Flip_U_Flag', desc='') flip_w = Bool(False, iotype='in', xmltag='Flip_W_Flag', desc='') refl_flip_u = Bool(False, iotype='in', xmltag='Refl_Flip_U_Flag', desc='') refl_flip_w = Bool(False, iotype='in', xmltag='Refl_Flip_W_Flag', desc='') def __init__(self): super(Texture, self).__init__(self.XMLTAG)
class BCIntM_recv(Container): """ :class:`BCIntM` receiving block definition. """ lblk1rr = Int(low=1, desc='Receiving block.') lface1 = Str(desc='Grid plane (I, J, or K).') ldir1 = Str(desc='Direction into flowfield (P or M).') l1lim = Int(low=1, desc='Grid index of surface.') m1lim1 = Int(low=1, desc='Initial 1st coord index.') m1lim2 = Int(low=1, desc='Initial 2nd coord index.') n1lim1 = Int(low=1, desc='Final 1st coord index.') n1lim2 = Int(low=1, desc='Final 2nd coord index.') def read(self, inp): """ Read from stream `inp`. """ tokens = inp.readline().upper().split() if len(tokens) != 8: self.raise_exception('line %d: expecting 8 fields, got %d.' \ % (inp.lineno(), len(tokens)), ValueError) for i, attr in enumerate(('lblk1rr', 'lface1', 'ldir1', 'l1lim', 'm1lim1', 'm1lim2', 'n1lim1', 'n1lim2')): if attr == 'lface1' or attr == 'ldir1': value = tokens[i] else: try: value = int(tokens[i]) except ValueError: self.raise_exception('line %d: %s (%s) must be an integer.' \ % (inp.lineno(), attr, tokens[i]), ValueError) setattr(self, attr, value) def check_config(self): """ Check sanity of current configuration. """ #TODO: check indices against mesh dimensions, etc. if self.lface1 not in ('I', 'J', 'K'): self.raise_exception('lface1 (%s) must be I, J, or K.' \ % self.lface1, ValueError) if self.ldir1 not in ('P', 'M'): self.raise_exception('ldir1 (%s) must be P or M.' \ % self.ldir1, ValueError) if self.m1lim2 <= self.m1lim1: self.raise_exception('m1lim2 (%d) must be > m1lim1 (%d).' \ % (self.m1lim2, self.m1lim1), ValueError) if self.n1lim2 < self.n1lim1: self.raise_exception('n1lim2 (%d) must be >= n1lim1 (%d).' \ % (self.n1lim2, self.n1lim1), ValueError) def write(self, out): """ Write to stream `out`. """ out.write(' %d %s %s %d %d %d %d %d\n' \ % (self.lblk1rr, self.lface1, self.ldir1, self.l1lim, self.m1lim1, self.m1lim2, self.n1lim1, self.n1lim2))
class WingParms(XMLContainer): """ XML parameters specific to a Wing. """ XMLTAG = 'Mwing_Parms' num_pnts = Int(iotype='in', xmltag='Num_Pnts', desc='') driver = Int(iotype='in', xmltag='Driver', desc='') aspect_ratio = Float(iotype='in', xmltag='Aspect_Ratio', desc='') taper_ratio = Float(iotype='in', xmltag='Taper_Ratio', desc='') area = Float(iotype='in', xmltag='Area', desc='') span = Float(iotype='in', xmltag='Span', desc='') tip_chord = Float(iotype='in', xmltag='Tip_Chord', desc='') root_chord = Float(iotype='in', xmltag='Root_Chord', desc='') sweep = Float(iotype='in', xmltag='Sweep', desc='') sweep_loc = Float(iotype='in', xmltag='Sweep_Loc', desc='') twist_loc = Float(iotype='in', xmltag='Twist_Loc', desc='') in_twist = Float(iotype='in', xmltag='In_Twist', desc='') in_dihed = Float(iotype='in', xmltag='In_Dihed', desc='') mid_twist = Float(iotype='in', xmltag='Mid_Twist', desc='') mid_dihed = Float(iotype='in', xmltag='Mid_Dihed', desc='') out_twist = Float(iotype='in', xmltag='Out_Twist', desc='') out_dihed = Float(iotype='in', xmltag='Out_Dihed', desc='') strake_sweep = Float(iotype='in', xmltag='Strake_Sweep', desc='') strake_span_per = Float(iotype='in', xmltag='Strake_Span_Per', desc='') aft_ext_sweep = Float(iotype='in', xmltag='Aft_Ext_Sweep', desc='') aft_ext_span_per = Float(iotype='in', xmltag='Aft_Ext_Span_Per', desc='') all_move_flag = Bool(iotype='in', xmltag='All_Move_Flag', desc='') in_flap_type = Int(iotype='in', xmltag='In_Flap_Type', desc='') out_flap_type = Int(iotype='in', xmltag='Out_Flap_Type', desc='') in_slat_type = Int(iotype='in', xmltag='In_Slat_Type', desc='') out_slat_type = Int(iotype='in', xmltag='Out_Slat_Type', desc='') in_flap_span_in = Float(iotype='in', xmltag='In_Flap_Span_In', desc='') in_flap_span_out = Float(iotype='in', xmltag='In_Flap_Span_Out', desc='') in_flap_chord = Float(iotype='in', xmltag='In_Flap_Chord', desc='') out_flap_span_in = Float(iotype='in', xmltag='Out_Flap_Span_In', desc='') out_flap_span_out = Float(iotype='in', xmltag='Out_Flap_Span_Out', desc='') out_flap_chord = Float(iotype='in', xmltag='Out_Flap_Chord', desc='') in_slat_span_in = Float(iotype='in', xmltag='In_Slat_Span_In', desc='') in_slat_span_out = Float(iotype='in', xmltag='In_Slat_Span_Out', desc='') in_slat_chord = Float(iotype='in', xmltag='In_Slat_Chord', desc='') out_slat_span_in = Float(iotype='in', xmltag='Out_Slat_Span_In', desc='') out_slat_span_out = Float(iotype='in', xmltag='Out_Slat_Span_Out', desc='') out_slat_chord = Float(iotype='in', xmltag='Out_Slat_Chord', desc='') deflect_on_off = Bool(iotype='in', xmltag='Deflect_On_Off', desc='') deflect_name = Str(iotype='in', xmltag='Deflect_Name', desc='') deflect_scale = Float(iotype='in', xmltag='Deflect_Scale', desc='') deflect_twist_scale = Float(iotype='in', xmltag='Deflect_Twist_Scale', desc='') strake_aft_flag = Bool(iotype='in', xmltag='Strake_Aft_Flag', desc='') # TODO: handle array. deflect_pnts = Str(iotype='in', xmltag='Deflect_Pnts', desc='') def __init__(self): super(WingParms, self).__init__(self.XMLTAG)
class HAWC2Simulation(VariableTree): time_stop = Float(300, desc='Simulation stop time') solvertype = Int(1, desc='Solver type. Default Newmark') convergence_limits = List([1.0e3, 1.0, 0.7], desc='Sovler convergence limits') on_no_convergence = Str() max_iterations = Int(100, desc='Maximum iterations') newmark_deltat = Float(0.02, desc='Newmark time step') eig_out = Bool(False) logfile = Str('hawc2_case.log')
class BasicTurbineVT(VariableTree): turbine_name = Str('FUSED-Wind turbine', desc='Wind turbine name') docs = Str(desc='Human readable description of wind turbine') nblades = Int(3, desc='number of blades') orientation = Str('upwind') rotor_diameter = Float(units='m', desc='Rotor Diameter') hub_height = Float(units='m', desc='Hub height') drivetrain_config = Enum(1, (1, 2, 3, 4, 'x'), desc='Drive train configuration') iec_class = Str(desc='Primary IEC classification of the turbine') controls = VarTree(ControlsVT(), desc='control specifications VT')
class Layer(VariableTree): """ A layer represents a stack of multidirectional plies and is assigned an apparent set of material properties based on the properties of the constituent materials, pre-computed using simple micromechanics equations and classical lamination theory. Layers are stacked in a region """ thickness = Float() angle = Float() materialname = Str() plyname = Str()
class BCPRR_send(Container): """ :class:`BCPRR` sending block definition. """ lblock2b = Int(low=1, desc='Sending block.') lface2b = Str(desc='Grid plane (I, J, or K).') ldir2b = Str(desc='Direction into flowfield (P or M).') l2limb = Int(low=1, desc='Grid index of surface.') m2lim1b = Int(low=1, desc='Initial 1st coord index.') m2lim2b = Int(low=1, desc='Initial 2nd coord index.') n2lim1b = Int(low=1, desc='Final 1st coord index.') n2lim2b = Int(low=1, desc='Final 2nd coord index.') def read(self, inp): """ Read from stream `inp`. """ tokens = inp.readline().upper().split() if len(tokens) != 8: self.raise_exception('line %d: expecting 8 fields, got %d.' \ % (inp.lineno(), len(tokens)), ValueError) for i, attr in enumerate(('lblock2b', 'lface2b', 'ldir2b', 'l2limb', 'm2lim1b', 'm2lim2b', 'n2lim1b', 'n2lim2b')): if attr == 'lface2b' or attr == 'ldir2b': value = tokens[i] else: try: value = int(tokens[i]) except ValueError: self.raise_exception('line %d: %s (%s) must be an integer.' \ % (inp.lineno(), attr, tokens[i]), ValueError) setattr(self, attr, value) def check_config(self): """ Check sanity of current configuration. """ #TODO: check indices against mesh dimensions, etc. if self.lface2b not in ('I', 'J', 'K'): self.raise_exception('lface2b (%s) must be I, J, or K.' \ % self.lface2b, ValueError) if self.ldir2b not in ('P', 'M'): self.raise_exception('ldir2b (%s) must be P or M.' \ % self.ldir2b, ValueError) def write(self, out): """ Write to stream `out`. """ out.write(' %d %s %s %d %d %d %d %d\n' \ % (self.lblock2b, self.lface2b, self.ldir2b, self.l2limb, self.m2lim1b, self.m2lim2b, self.n2lim1b, self.n2lim2b))
class LoadVector(VariableTree): """ Point load vector containing forces and moments """ case_id = Str('dlcx.x', desc='Case identifier') s = Float(desc='Running length of blade') Fx = Float(units='N', desc='Force in x-direction') Fy = Float(units='N', desc='Force in y-direction') Fz = Float(units='N', desc='Force in z-direction') Fres = Float(units='N', desc='Resulting transverse force') Mx = Float(units='N*m', desc='Moment in x-direction') My = Float(units='N*m', desc='Moment in y-direction') Mz = Float(units='N*m', desc='Moment in z-direction') Mres = Float(units='N*m', desc='Resulting bending moment') def _toarray(self): return np.array([ self.s, self.Fx, self.Fy, self.Fz, self.Fres, self.Mx, self.My, self.Mz, self.Mres ]) def _fromarray(self, d): self.s = d[0] self.Fx = d[1] self.Fy = d[2] self.Fz = d[3] self.Fres = d[4] self.Mx = d[5] self.My = d[6] self.Mz = d[7] self.Mres = d[8]
class HAWC2ConstraintFix4(VariableTree): con_type = Str() mbdy1 = List(desc='Main_body name to which the next main_body is fixed') mbdy2 = List( desc='Main_body name of the main_body that is fixed to main_body1') time = Float(2., desc='Time for the pre-stress process. Default=2 sec')
class IECRunCaseBaseVT(VariableTree): # General conditions needed case_name = Str( 'IEC_case', desc='Name of the specific case passed to the aeroelastic code') simulation = VarTree( AeroElasticSimulationSetup(), desc='Basic simulation input settings' ) # 4/28/2015 kld: should move elsewhere but leaving in for debugging environment = VarTree(OffshoreTurbineEnvironmentVT(), desc='Inflow conditions to the turbine simulation') basic_turbine = VarTree( BasicTurbineVT(), desc='Basic turbine variables already defined in fusedwind') rotor = VarTree(RotorOperationalData(), desc='Rotor variables already defined in fusedwind') pitch = VarTree( FixedSpeedFixedPitch(), desc='Pitch already defined in fusedwind') # should probably move init_conditions = VarTree(FASTInitialConditions(), desc='Initial conditions needed to run FAST') simulation_specs = VarTree( FASTSimulationSpecs(), desc='Basic simulation input settings') #mb: also shouldn't be here aero_inputs = VarTree(AerodynInputs(), desc='Wind and airfoil files to run Aerodyn') fst_inputs = VarTree(FASTInputs(), desc='FAST model variables') ptfm_inputs = VarTree(PtfmInputs(), desc='Platform model variables')
class HAWC2ConstraintFix1(VariableTree): con_type = Str() mbdy1 = List(desc='Main_body name to which the next main_body is fixed') mbdy2 = List( desc='Main_body name of the main_body that is fixed to main_body1') disable_at = Float(desc='Time at which constraint can be disabled')
class DOECounterComp(Component): # --- Initialize counter variable --- config = Str('', iotype='out', desc='current design configuration number') def __init__(self, *args, **kwargs): # --------------------------------------------- # --- Constructor for the counter component --- # --------------------------------------------- super(DOECounterComp, self).__init__(*args, **kwargs) self.case_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] start_case = 2 end_case = 4 # --- Edit this line to define DOE case number self.case = 2 #[self.case_list.append(case_number) for case_number in range(start_case, end_case)] self.force_execute = True def execute(self): self.config = str(self.case_list[self.case]) self.case += 1
class CSVFile(HasTraits): """ 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=None, *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 MeshSurface(Vis3DObject): """ I, J, or K surface of mesh. """ block = Int(low=1) plane = Str() value = Int(low=1) min2 = Int(low=1) max2 = Int(low=1) min3 = Int(low=1) max3 = Int(low=1) def __init__(self, block, plane, value, min2, max2, min3, max3): super(MeshSurface, self).__init__() self.block = block self.plane = plane self.value = value self.min2 = min2 self.max2 = max2 self.min3 = min3 self.max3 = max3 def clone(self, offset): """ Return a copy of ourselves, adjusting for block `offset`. """ obj = Vis3DObject.clone(self, offset) obj.block += offset return obj def write_ensight(self, stream): """ Writes Ensight commands to `stream`. """ stream.write(""" # MeshSurface %(name)s clip: select_default part: modify_begin clip: tool ijk part: modify_end clip: select_default part: modify_begin clip: mesh_plane %(plane)s clip: tool ijk part: modify_end part: select_begin %(block)d part: select_end clip: begin clip: value %(value)d clip: domain intersect clip: tool ijk clip: dimension2 %(min2)d %(max2)d clip: dimension3 %(min3)d %(max3)d clip: end clip: create part: select_lastcreatedpart part: modify_begin part: description %(name)s part: modify_end """ % {'block':self.block, 'plane':self.plane, 'value':self.value, 'min2':self.min2, 'max2':self.max2, 'min3':self.min3, 'max3':self.max3, 'name':self.vis_name}) super(MeshSurface, self).write_ensight(stream)
class VSPComponent(XMLContainer): """ Base XML parameters for a VSP component/part. """ XMLTAG = 'Component' type = Str(iotype='out', xmltag='Type', desc='Type name for this component.') def __init__(self): super(VSPComponent, self).__init__(self.XMLTAG) self.add('general_parms', GeneralParms()) def read(self, this): """ Read parameters from XML tree element `this`. """ super(VSPComponent, self).read(this) parms = this.find('General_Parms') if parms is not None: # No general parameters for 'User' component. self.general_parms.read(parms) def write(self, parent, nesting=0): """ Write parameters to XML tree under `parent`. Returns tree element. """ this = super(VSPComponent, self).write(parent, nesting) if self.type != 'User': self.general_parms.write(this, nesting + 1) return this
class WTPC(GenericWindTurbinePowerCurveVT): """ A GenericWindTurbinePowerCurveVT with a name, position and wind rose """ # GenericWindTurbineVT hub_height = Float(desc='Machine hub height', units='m') rotor_diameter = Float(desc='Machine rotor diameter', units='m') power_rating = Float(desc='Machine power rating', units='W') # GenericWindTurbinePowerCurveVT c_t_curve = Array(desc='Machine thrust coefficients by wind speed at hub') power_curve = Array(desc='Machine power output [W] by wind speed at hub') cut_in_wind_speed = Float(4., desc='The cut-in wind speed of the wind turbine', units='m/s') cut_out_wind_speed = Float( 25., desc='The cut-out wind speed of the wind turbine', units='m/s') rated_wind_speed = Float(desc='The rated wind speed of the wind turbine', units='m/s') air_density = Float(desc='The air density the power curve are valid for', units='kg/(m*m*m)') # WTPC name = Str(desc='The wind turbine name') position = Array(shape=(2, ), desc='The UTM position of the turbine', units='m') wind_rose = VarTree(GenericWindRoseVT(), desc='The wind turbine wind rose') def __init__(self, **kwargs): """Initialise the variable tree with the right inputs""" super(WTPC, self).__init__() for k, v in kwargs.iteritems(): if k in self.list_vars(): setattr(self, k, v)
def __init__(self, Ns): super(SparProperties, self).__init__() # inputs self.add( 'yN', Array(np.zeros(Ns + 1), iotype='in', desc='node locations for each element along the span')) self.add('d', Array(np.zeros(Ns), iotype='in', desc='diameter')) self.add('theta', Array(np.zeros(Ns), iotype='in', desc='wrap angle')) self.add( 'nTube', Array(np.zeros(Ns), iotype='in', desc='number of tube layers')) self.add('nCap', Array(np.zeros(Ns), iotype='in', desc='number of cap strips')) self.add('lBiscuit', Array(np.zeros(Ns), iotype='in', desc='')) self.add('CFRPType', Str('', iotype='in', desc='')) # outputs self.add('EIx', Array(np.zeros(Ns), iotype='out', desc='')) self.add('EIz', Array(np.zeros(Ns), iotype='out', desc='')) self.add('EA', Array(np.zeros(Ns), iotype='out', desc='')) self.add('GJ', Array(np.zeros(Ns), iotype='out', desc='')) self.add('mSpar', Array(np.zeros(Ns), iotype='out', desc='')) self.add('dy', Array(np.zeros(Ns), iotype='out', desc=''))
class BladePlanformWriter(Component): filebase = Str('blade') pf = VarTree(BladePlanformVT(), iotype='in') def execute(self): name = self.filebase + self.itername + '.pfd' try: if '-fd' in self.itername or '-fd' in self.parent.itername: name = self.filebase + '.pfd' except: pass data = np.array([ self.pf.x, self.pf.y, self.pf.z, self.pf.rot_x, self.pf.rot_y, self.pf.rot_z, self.pf.chord, self.pf.rthick, self.pf.p_le ]).T fid = open(name, 'w') header = [ 'main_axis_x', 'main_axis_y', 'main_axis_z', 'rot_x', 'rot_y', 'rot_z', 'chord', 'rthick', 'p_le' ] exp_prec = 10 # exponential precesion col_width = exp_prec + 8 # column width required for exp precision header_full = '# ' + ''.join([(hh + ' [%i]').center(col_width + 2) % i for i, hh in enumerate(header)]) + '\n' fid.write(header_full) np.savetxt(fid, data, fmt='%' + ' %i.%ie' % (col_width, exp_prec)) fid.close()
class FUSEDFSTCaseRunner(FUSEDIECBase): FSTexe = Str(iotype='in', desc='Path to executable') def __init__(self): #, file_locs): super(FUSEDFSTCaseRunner, self).__init__() #self.filedict = parse_key_val_file_all(file_locs) def configure(self): self.force_execute = True self.add('reader', FstInputReader()) self.driver.workflow.add('reader') #self.connect('fst_infile_vt', 'reader.fst_infile_vt') #OC3 Example #FAST_DIR = os.path.dirname(os.path.realpath(__file__)) FAST_DIR = "C:/Python27/NREL-Models/WISDEM/AeroelasticSE/src/AeroelasticSE/ModelFiles" #print self.filedict #FAST_DIR = self.filedict['fst_dir'] #self.reader.fst_infile = os.path.join(FAST_DIR,self.filedict['fst_file']) #replace with master fast file self.reader.fst_infile = 'NRELOffshrBsline5MW_Monopile_RF.fst' #replace with master fast file self.reader.fst_directory = os.path.join(FAST_DIR,"OC3_Files") #self.reader.fst_directory = FAST_DIR self.reader.ad_file_type = 1 ### TODO: peter graf, automate which type self.reader.fst_file_type = 1 self.reader.read_input_file() self.add('builder', FUSEDWindInputBuilder()) self.driver.workflow.add('builder') #self.connect('reader.fst_vt', 'builder.fstIn') #TODO: why can't these be connected like a normal workflow? #self.builder.force_execute = True self.connect('inputs', 'builder.inputs') self.builder.fstIn = self.reader.fst_vt.copy() self.builder.initialize_inputs() self.builder.execute() self.builder.force_execute = True self.add('writer', FstInputWriter()) self.driver.workflow.add('writer') self.writer.fst_infile = 'FAST_Model.fst' self.writer.fst_directory = os.path.join(FAST_DIR,self.inputs.case_name) if not os.path.isdir(self.writer.fst_directory): os.mkdir(self.writer.fst_directory) self.connect('builder.fstOut', 'writer.fst_vt') #TODO; why can't i do direct connect? self.connect('inputs.case_name', ['writer.case_id']) self.writer.force_execute = True self.add('wrapper', FstWrapper()) self.driver.workflow.add('wrapper') #self.connect('FSTexe', 'wrapper.FSTexe') #TODO: why isn't connect working? # Set up input files self.wrapper.FSTexe = 'C:/Models/FAST/FAST.exe' #self.wrapper.FSTexe = self.filedict['fst_exe'] self.connect('writer.fst_directory', 'wrapper.fst_directory') self.connect('writer.fst_file', 'wrapper.FSTInputFile')
class BaseSource(XMLContainer): """ Base class for CFD meshing source objects. """ XMLTAG = 'CFD_Mesh_Source' source_name = Str('Default_Name', iotype='in', xmltag='Name', desc='Name of this source.') type = Int(iotype='in', xmltag='Type', desc='Type of meshing source.') radius = Float(0.0, iotype='in', xmltag='Rad', desc='Radius of influence.') length = Float(0.0, iotype='in', xmltag='Len', desc='Target edge length.') def __init__(self): super(BaseSource, self).__init__(self.XMLTAG) @staticmethod def create(element): """ Create a source object of the type specified in `element`. """ typ = int(element.findtext('Type')) if typ == _POINT_SOURCE: return PointSource() elif typ == _LINE_SOURCE: return LineSource() elif typ == _BOX_SOURCE: return BoxSource() raise ValueError("Invalid source type '%s'" % typ)
class DOEdriver(CaseIterDriverBase): """ Driver for Design of Experiments. """ # pylint: disable-msg=E1101 DOEgenerator = Slot(IDOEgenerator, iotype='in', required=True, desc='Iterator supplying normalized DOE values.') record_doe = Bool(True, iotype='in', desc='Record normalized DOE values to CSV file.') doe_filename = Str('', iotype='in', desc='Name of CSV file to record to' ' (default is <driver-name>.csv)') case_outputs = ListStr([], iotype='in', desc='A list of outputs to be saved with each case.') case_filter = Slot(ICaseFilter, iotype='in', desc='Selects cases to be run.') def execute(self): """Generate and evaluate cases.""" self._csv_file = None try: super(DOEdriver, self).execute() finally: if self._csv_file is not None: self._csv_file.close() def get_case_iterator(self): """Returns a new iterator over the Case set.""" return self._get_cases() def _get_cases(self): """Generate each case.""" params = self.get_parameters().values() self.DOEgenerator.num_parameters = len(params) record_doe = self.record_doe events = self.get_events() outputs = self.case_outputs case_filter = self.case_filter if record_doe: if not self.doe_filename: self.doe_filename = '%s.csv' % self.name self._csv_file = open(self.doe_filename, 'wb') csv_writer = csv.writer(self._csv_file) for i, row in enumerate(self.DOEgenerator): if record_doe: csv_writer.writerow(['%.16g' % val for val in row]) vals = [p.low+(p.high-p.low)*val for p,val in zip(params,row)] case = self.set_parameters(vals, Case(parent_uuid=self._case_id)) # now add events for varname in events: case.add_input(varname, True) case.add_outputs(outputs) if case_filter is None or case_filter.select(i, case): yield case
class HAWC2Mann(VariableTree): create_turb = Bool(True) L = Float(29.4) alfaeps = Float(1.0) gamma = Float(3.7) seed = Float() highfrq_compensation = Float(1.) turb_base_name = Str('mann_turb') turb_directory = Str('turb') box_nu = Int(8192) box_nv = Int(32) box_nw = Int(32) box_du = Float(0.8056640625) box_dv = Float(5.6) box_dw = Float(5.6) std_scaling = Array([1.0, 0.7, 0.5])
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 HAWC2AirfoilPolar(VariableTree): """A single airfoil polar""" desc = Str() rthick = Float() aoa = Array() cl = Array() cd = Array() cm = Array()