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())
示例#2
0
class GradientOptions(VariableTree):
    ''' Options for calculation of the gradient by the driver's workflow. '''

    # Finite Difference
    fd_form = Enum('forward', ['forward', 'backward', 'central'],
                   desc='Finite difference mode (forward, backward, central',
                   framework_var=True)
    fd_step = Float(1.0e-6,
                    desc='Default finite difference stepsize',
                    framework_var=True)
    fd_step_type = Enum('absolute', ['absolute', 'relative', 'bounds_scaled'],
                        desc='Set to absolute, relative, '
                        'or scaled to the bounds ( high-low) step sizes',
                        framework_var=True)

    force_fd = Bool(False,
                    desc="Set to True to force finite difference " +
                    "of this driver's entire workflow in a" + "single block.",
                    framework_var=True)

    # KTM - story up for this one.
    #fd_blocks = List([], desc='User can specify nondifferentiable blocks ' + \
    #                          'by adding sets of component names.')

    # Analytic solution with GMRES
    gmres_tolerance = Float(1.0e-9,
                            desc='Tolerance for GMRES',
                            framework_var=True)
    gmres_maxiter = Int(100,
                        desc='Maximum number of iterations for GMRES',
                        framework_var=True)
def configure_lcoe_with_landbos(assembly):
    """
    if with_landbos additional inputs:
        voltage
        distInter
        terrain
        layout
        soil
    """

    assembly.replace('bos_a', LandBOS())

    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'))

    # 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')
示例#4
0
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
示例#5
0
class ElecInstallation(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')
    farmSize = Float(iotype='in', units='MW', desc='wind farm size')
    diameter = Float(iotype='in', units='m', desc='rotor diameter')
    nTurbines = Int(iotype='in', desc='number of turbines')
    rockTrenchingLength = Float(
        10.0,
        iotype='in',
        desc='rock trenching required (% of collector cable length)')
    overheadCollector = Float(0.0,
                              iotype='in',
                              units='mi',
                              desc='MV overhead collector')

    cost = Float(iotype='out',
                 units='USD',
                 desc='MV electrical materials cost')

    def execute(self):
        self.cost = _landbos.electricalInstallationCost(
            Enum2Int(self, 'terrain'), Enum2Int(self, 'layout'), self.farmSize,
            self.diameter, self.nTurbines, self.rockTrenchingLength,
            self.overheadCollector)
示例#6
0
class ElecMaterials(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')
    farmSize = Float(iotype='in', units='MW', desc='wind farm size')
    diameter = Float(iotype='in', units='m', desc='rotor diameter')
    nTurbines = Int(iotype='in', desc='number of turbines')
    padMountTransformer = Bool(True,
                               iotype='in',
                               desc='pad mount transformer required')
    thermalBackfill = Float(0.0,
                            iotype='in',
                            units='mi',
                            desc='MV thermal backfill')

    cost = Float(iotype='out',
                 units='USD',
                 desc='MV electrical materials cost')

    def execute(self):
        self.cost = _landbos.electricalMaterialsCost(Enum2Int(self, 'terrain'),
                                                     Enum2Int(self, 'layout'),
                                                     self.farmSize,
                                                     self.diameter,
                                                     self.nTurbines,
                                                     self.padMountTransformer,
                                                     self.thermalBackfill)
示例#7
0
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 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')
示例#9
0
    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'))
示例#10
0
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('rated_power', 'bos_a.machine_rating')
    assembly.connect('rotor_diameter', 'bos_a.rotor_diameter')
    assembly.connect('hub_height', 'bos_a.hub_height')
    assembly.connect('turbine_number', 'bos_a.turbine_number')
    assembly.connect(
        'blade_number * blade_design.blade_mass + 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')
示例#11
0
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')
示例#12
0
class GradientOptions(VariableTree):
    ''' Options for calculation of the gradient by the driver's workflow. '''

    # Finite Difference
    fd_form = Enum('forward', ['forward', 'backward', 'central', 'complex_step'],
                   desc="Finite difference mode. (forward, backward, central) "
                        "You can also set to 'complex_step' to peform the complex "
                        "step method if your components support it.",
                   framework_var=True)
    fd_step = Float(1.0e-6, desc='Default finite difference stepsize',
                    framework_var=True)
    fd_step_type = Enum('absolute',
                        ['absolute', 'relative', 'bounds_scaled'],
                        desc='Set to absolute, relative, '
                             'or scaled to the bounds (high-low) step sizes',
                        framework_var=True)

    force_fd = Bool(False, desc="Set to True to force finite difference "
                                "of this driver's entire workflow in a"
                                "single block.",
                    framework_var=True)

    directional_fd = Bool(False, desc="Set to True to do a directional "
                                      "finite difference for each GMRES "
                                      "iteration instead of pre-computing "
                                      "the full fd space.",
                          framework_var=True)

    fd_blocks = List([], desc="List of lists that contain comps which "
                              "should be finite-differenced together.",
                     framework_var=True)

    # KTM - story up for this one.
    # fd_blocks = List([], desc='User can specify nondifferentiable blocks '
    #                          'by adding sets of component names.')

    # Analytic solution with GMRES
    gmres_tolerance = Float(1.0e-9, desc='Tolerance for GMRES',
                            framework_var=True)
    gmres_maxiter = Int(100, desc='Maximum number of iterations for GMRES',
                        framework_var=True)
    derivative_direction = Enum('auto',
                                ['auto', 'forward', 'adjoint'],
                                desc="Direction for derivative calculation. "
                                     "Can be 'forward', 'adjoint', or 'auto'. "
                                     "Auto is the default setting. "
                                     "When set to auto, OpenMDAO automatically "
                                     "figures out the best direction based on the "
                                     "number of parameters and responses. "
                                     "When the number of parameters and responses "
                                     "are equal, then forward direction is used.",
                                framework_var=True)
示例#13
0
class Foundations(Component):

    rating = Float(iotype='in', units='kW', desc='machine rating')
    diameter = Float(iotype='in', units='m', desc='rotor diameter')
    topMass = Float(iotype='in', units='kg', desc='tower top mass (tonnes)')
    hubHeight = Float(iotype='in', units='m', desc='hub height')
    soil = Enum('STANDARD', ('STANDARD', 'BOUYANT'),
                iotype='in',
                desc='soil options')
    nTurbines = Int(iotype='in', desc='number of turbines')

    cost = Float(iotype='out', units='USD', desc='foundations cost')

    def execute(self):
        self.cost = _landbos.foundationCost(self.rating, self.diameter,
                                            self.topMass / 1000.0,
                                            self.hubHeight,
                                            Enum2Int(self,
                                                     'soil'), self.nTurbines)

    def list_deriv_vars(self):

        inputs = ('diameter', 'topMass', 'hubHeight')
        outputs = ('cost', )

        return inputs, outputs

    def provideJ(self):

        ddiameter, dtopMass, dhubHt = _landbos.deriv_foundationCost(
            self.rating, self.diameter, self.topMass / 1000.0, self.nTurbines)

        J = np.array([[ddiameter, dtopMass / 1000.0, dhubHt]])

        return J
示例#14
0
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')
示例#15
0
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'
        ]
示例#16
0
def _add_enum(vartree, member, props):
    """ Helper for :meth:`_populate_from_xml`. """
    name = member.attrib['name']
    typ = member.attrib['type']
    cvt = {'double': float, 'long': int, 'string': str}[typ]
    args = {}
    if typ == 'string':
        args['default_value'] = member.text.decode('string_escape')
    else:
        args['default_value'] = cvt(member.text)
    desc = props.get('description')
    if desc:
        args['desc'] = desc.decode('string_escape')
    values = props.get('enumValues')
    if values:
        if typ == 'string':
            values = values.decode('string_escape')
        args['values'] = [cvt(val.strip(' "')) for val in values.split(',')]
    aliases = props.get('enumAliases')
    if aliases:
        aliases = aliases.decode('string_escape')
        args['aliases'] = [val.strip(' "') for val in aliases.split(',')]
    units = props.get('units')
    if units:
        args['units'] = get_translation(units)
    vartree.add(name, Enum(**args))
示例#17
0
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
示例#18
0
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 SomeComp(Component):
            """Arbitrary component with a few variables, but which does not
            really do any calculations"""

            w = Float(0.0, low=-10, high=0.0, iotype="in")
            x = Float(0.0, low=0.0, high=100.0, iotype="in")
            y = Int(10, low=10, high=100, iotype="in")
            z = Enum([-10, -5, 0, 7], iotype="in")
示例#20
0
class TopObj(VariableTree):
    """ Top-level object variable. """

    tob = Bool(True)
    tof = Float(0.5, units='inch')
    toi = Int(42)
    tos = Str('Hello')
    tofe = Enum(values=(2.781828, 3.14159),
                aliases=('e', 'pi'),
                desc='Float enum',
                units='m')
    toie = Enum(values=(9, 8, 7, 1), desc='Int enum')
    tose = Enum(values=('cold', 'hot', 'nice'), desc='Str enum')

    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)

    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]])

    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]]])

    toi1d = Array(dtype=int,
                  desc='1D int array',
                  default_value=[1, 2, 3, 4, 5, 6, 7, 8, 9])

    tos1d = List(Str,
                 desc='1D string array',
                 value=['Hello', 'from', 'TestComponent.tos1d'])

    toflst = List(Float, desc='Float list')
    toilst = List(Int, desc='Int list')

    subobj = VarTree(SubObj())
示例#21
0
def configure_lcoe_with_csm_aep(assembly):
    """
    aep inputs
        power_curve    = Array([], iotype='in', desc='wind turbine power curve')
        array_losses = Float
        other_losses = Float
        A = Float
        k = Float
    """

    # Variables
    #machine_rating = Float(units = 'kW', iotype='in', desc= 'rated machine power in kW')
    assembly.add('max_tip_speed', Float(units = 'm/s', iotype='in', desc= 'maximum allowable tip speed for the rotor'))
    #rotor_diameter = Float(units = 'm', iotype='in', desc= 'rotor diameter of the machine') 
    assembly.add('max_power_coefficient', Float(iotype='in', desc= 'maximum power coefficient of rotor for operation in region 2'))
    assembly.add('opt_tsr', Float(iotype='in', desc= 'optimum tip speed ratio for operation in region 2'))
    assembly.add('cut_in_wind_speed', Float(units = 'm/s', iotype='in', desc= 'cut in wind speed for the wind turbine'))
    assembly.add('cut_out_wind_speed', Float(units = 'm/s', iotype='in', desc= 'cut out wind speed for the wind turbine'))
    assembly.add('hub_height', Float(units = 'm', iotype='in', desc= 'hub height of wind turbine above ground / sea level'))
    assembly.add('altitude', Float(units = 'm', iotype='in', desc= 'altitude of wind plant'))
    assembly.add('air_density', Float(0.0, units = 'kg / (m * m * m)', iotype='in', desc= 'air density at wind plant site')) # default air density value is 0.0 - forces aero csm to calculate air density in model
    assembly.add('drivetrain_design', Enum('geared', ('geared', 'single_stage', 'multi_drive', 'pm_direct_drive'), iotype='in'))
    assembly.add('shear_exponent', Float(iotype='in', desc= 'shear exponent for wind plant')) #TODO - could use wind model here
    assembly.add('wind_speed_50m', Float(iotype='in', units = 'm/s', desc='mean annual wind speed at 50 m height'))
    assembly.add('weibull_k', Float(iotype='in', desc = 'weibull shape factor for annual wind speed distribution'))
    assembly.add('soiling_losses', Float(iotype='in', desc = 'energy losses due to blade soiling for the wind plant - average across turbines'))
    assembly.add('array_losses', Float(iotype='in', desc = 'energy losses due to turbine interactions - across entire plant'))
    #assembly.add('availability', Float(iotype='in', desc = 'average annual availbility of wind turbines at plant'))
    #turbine_number = Int(iotype='in', desc = 'total number of wind turbines at the plant')
    assembly.add('thrust_coefficient', Float(iotype='in', desc='thrust coefficient at rated power'))
    assembly.add('max_efficiency', Float(iotype='in', desc = 'maximum efficiency of rotor and drivetrain - at rated power')) # TODO: should come from drivetrain

    assembly.add('capacity_factor', Float(iotype='out'))

    assembly.connect('rotor_diameter','aep_a.rotor_diameter')
    assembly.connect('machine_rating','aep_a.machine_rating')
    assembly.connect('turbine_number','aep_a.turbine_number')
    
    assembly.connect('max_tip_speed','aep_a.max_tip_speed')
    assembly.connect('max_power_coefficient','aep_a.max_power_coefficient')
    assembly.connect('opt_tsr','aep_a.opt_tsr')
    assembly.connect('cut_in_wind_speed','aep_a.cut_in_wind_speed')
    assembly.connect('cut_out_wind_speed','aep_a.cut_out_wind_speed')
    assembly.connect('hub_height','aep_a.hub_height')
    assembly.connect('altitude','aep_a.altitude')
    assembly.connect('air_density','aep_a.air_density')
    assembly.connect('drivetrain_design','aep_a.drivetrain_design')
    assembly.connect('shear_exponent','aep_a.shear_exponent')
    assembly.connect('wind_speed_50m','aep_a.wind_speed_50m')
    assembly.connect('weibull_k','aep_a.weibull_k')
    assembly.connect('soiling_losses','aep_a.soiling_losses')
    assembly.connect('array_losses','aep_a.array_losses')
    #assembly.connect('availability','aep_a.availability')
    assembly.connect('thrust_coefficient','aep_a.thrust_coefficient')
    assembly.connect('max_efficiency','aep_a.max_efficiency')
    assembly.connect('aep_a.capacity_factor','capacity_factor')
示例#22
0
    def __init__(self, iotype, client, rpath, typ, valstrs):
        ProxyMixin.__init__(self, client, rpath)

        om_units = None
        if typ == 'PHXDouble':
            self._from_string = float
            self._to_string = _float2str
            as_units = client.get(rpath + '.units')
            if as_units:
                om_units = get_translation(as_units)
        elif typ == 'PHXLong':
            self._from_string = int
            self._to_string = str
        elif typ == 'PHXString':
            self._from_string = self._null
            self._to_string = self._null
        else:
            raise NotImplementedError('EnumProxy for %r' % typ)

        default = self._from_string(self._valstr)
        desc = client.get(rpath + '.description')

        enum_values = []
        for valstr in valstrs.split(','):
            enum_values.append(self._from_string(valstr.strip(' "')))

        enum_aliases = []
        aliases = self._client.get(rpath + '.enumAliases')
        if aliases:
            for alias in aliases.split(','):
                enum_aliases.append(alias.strip(' "'))
        if enum_aliases:
            if len(enum_aliases) != len(enum_values):
                raise ValueError("Aliases %r don't match values %r" %
                                 (enum_aliases, enum_values))

        Enum.__init__(self,
                      default_value=default,
                      iotype=iotype,
                      desc=desc,
                      values=enum_values,
                      aliases=enum_aliases,
                      units=om_units)
示例#23
0
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 SphereFunction(Component):
    total = Float(0., iotype='out')
    x = Float(0, low=-5.12,high=5.13, iotype="in")
    y = Enum([-10,0,1,2,3,4,5], iotype="in")
    z = Int(0, low=-5,high=5, iotype="in")

    def __init__(self):
        super(SphereFunction, self).__init__()

    def execute(self):
        """ calculate the sume of the squares for the list of numbers """
        self.total = self.x**2+self.y**2+self.z**2
示例#25
0
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 list_deriv_vars(self):

        inputs = ('diameter', )
        outputs = ('cost', )

        return inputs, outputs

    def provideJ(self):

        ddiameter = _landbos.deriv_accessRoadsCost(Enum2Int(self, 'terrain'),
                                                   Enum2Int(self, 'layout'),
                                                   self.nTurbines)
        J = np.array([[ddiameter]])

        return J
示例#26
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')
示例#27
0
    def __init__(self, iotype, client, rpath, typ, valstrs):
        ProxyMixin.__init__(self, client, rpath)

        om_units = None
        if typ == 'PHXDouble':
            self._from_string = float
            self._to_string = _float2str
            as_units = client.get(rpath+'.units')
            if as_units:
                om_units = get_translation(as_units)
        elif typ == 'PHXLong':
            self._from_string = int
            self._to_string = str
        elif typ == 'PHXString':
            self._from_string = self._null
            self._to_string = self._null
        else:
            raise NotImplementedError('EnumProxy for %r' % typ)

        default = self._value = self._from_string(self._valstr)
        desc = client.get(rpath+'.description')

        enum_values = []
        for valstr in valstrs.split(','):
            enum_values.append(self._from_string(valstr.strip(' "')))

        enum_aliases = []
        aliases = self._client.get(rpath+'.enumAliases')
        if aliases:
            for alias in aliases.split(','):
                enum_aliases.append(alias.strip(' "'))
        if enum_aliases:
            if len(enum_aliases) != len(enum_values):
                raise ValueError("Aliases %r don't match values %r"
                                 % (enum_aliases, enum_values))

        Enum.__init__(self, default_value=default, iotype=iotype, desc=desc,
                      values=enum_values, aliases=enum_aliases, units=om_units)
示例#28
0
class Oneinp(Component):
    """ A simple input component    """

    ratio1 = Float(2., iotype='in', desc='Float   Variable')
    ratio2 = Int(2, iotype='in', desc='Int Variable')
    ratio3 = Bool(False, iotype='in', desc='Float Variable')
    ratio4 = Float(1.03, iotype='in', desc='Float variable ', units='ft')
    ratio5 = Str('01234', iotype='in', desc='string variable')
    ratio6 = Enum(0, (0, 3, 11, 27), iotype='in', desc='some enum')
    unit = Float(0.0, units='ft', iotype='in')
    no_unit = Float(0.0, iotype='in')

    arrinp = Array(dtype=float, default_value=[42, 13, 0], iotype='in')

    def execute(self):
        """                                                                    
示例#29
0
class Oneout(Component):
    """ A simple output component    """

    ratio1 = Float(3.54, iotype='out', desc='Float Variable')
    ratio2 = Int(9, iotype='out', desc='Integer variable')
    ratio3 = Bool(True, iotype='out', desc='Boolean Variable')
    ratio4 = Float(1.03, iotype='out', desc='Float variable ', units='cm')
    ratio5 = Str('05678', iotype='out', desc='string variable')
    ratio6 = Enum(27, (0, 3, 9, 27), iotype='out', desc='some enum')
    unit = Float(12.0, units='inch', iotype='out')
    no_unit = Float(12.0, iotype='out')

    arrout = Array(dtype=float, default_value=[1, 2, 3], iotype='out')

    def execute(self):
        """                                                                    
示例#30
0
class CentralComposite(Container):
    """ DOEgenerator that performs a central composite 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.")
    type = Enum("Face-Centered", ["Face-Centered", "Inscribed"],
                iotype="in",
                desc="Type of central composite design")

    def __init__(self, type="Face-Centered", *args, **kwargs):

        super(CentralComposite, self).__init__(*args, **kwargs)

        self.type = type

    def __iter__(self):
        """Return an iterator over our sets of input values."""

        # Set the number of center points and the alpha parameter based on the type of central composite design
        num_center_points = 1
        if self.type == "Face-Centered":
            alpha = 1.0
        if self.type == "Inscribed":
            alpha = self.num_parameters**0.5  # Based on recommendation from "Response Surface Methodology" by R.H. Myers and D.C. Montgomery

        # Form the iterator for the corner points using a 2 level full factorial
        low_corner_val = 0.5 - 0.5 / alpha
        high_corner_val = 0.5 + 0.5 / alpha
        corner_points = product(*[[low_corner_val, high_corner_val]
                                  for i in range(self.num_parameters)])

        # Form iterators for the face centered points (one for low value faces, one for high value faces)
        center_list = (self.num_parameters - 1) * [0.5]
        low_face_points = set(permutations([0.0] + center_list))
        high_face_points = set(permutations([1.0] + center_list))

        # Form iterator for center point(s)
        center_points = num_center_points * [self.num_parameters * [0.5]]

        # Chain case lists together to get complete iterator
        return chain(corner_points, low_face_points, high_face_points,
                     center_points)
示例#31
0
class Foundations(Component):

    rating = Float(iotype='in', units='kW', desc='machine rating')
    diameter = Float(iotype='in', units='m', desc='rotor diameter')
    topMass = Float(iotype='in', units='kg', desc='tower top mass (tonnes)')
    hubHeight = Float(iotype='in', units='m', desc='hub height')
    soil = Enum('STANDARD', ('STANDARD', 'BOUYANT'),
                iotype='in',
                desc='soil options')
    nTurbines = Int(iotype='in', desc='number of turbines')

    cost = Float(iotype='out', units='USD', desc='foundations cost')

    def execute(self):
        self.cost = _landbos.foundationCost(self.rating, self.diameter,
                                            self.topMass / 1000.0,
                                            self.hubHeight,
                                            Enum2Int(self,
                                                     'soil'), self.nTurbines)