Example #1
0
class A(Component):
    f = Float(iotype='in')
    a1d = Array(array([1.0, 1.0, 2.0, 3.0]), iotype='in')
    a2d = Array(array([[1.0, 1.0], [2.0, 3.0]]), iotype='in')
    b1d = Array(array([1.0, 1.0, 2.0, 3.0]), iotype='out')
    b2d = Array(array([[1.0, 1.0], [2.0, 3.0]]), iotype='out')
    c1d = Array(array([0.0, 1.0, 2.0, 3.0]), iotype='in')
    c2d = Array(array([[0.0, 1.0], [2.0, 3.0]]), iotype='in')

    def some_funct(self, a, b, op='add'):
        if op == 'add':
            return a + b
        elif op == 'mult':
            return a * b
        elif op == 'sub':
            return a - b
        raise RuntimeError("bad input to some_funct")

    @property
    def some_prop(self):
        return 7
def configure_lcoe_with_csm_bos(assembly):
    """
    bos inputs:
    		bos_multiplier = Float
    """

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

    assembly.add('bos_multiplier', Float(1.0, iotype='in'))

    # 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('sea_depth', 'bos_a.sea_depth')
    assembly.connect('year', 'bos_a.year')
    assembly.connect('month', 'bos_a.month')
    assembly.connect('bos_multiplier','bos_a.multiplier')
    def test_solver_nested_under_double_nested_driver_boundary_var_no_deriv(
            self):

        model = set_as_top(Assembly())
        model.add('comp', MyComp_No_Deriv())
        model.add('bvar', Float(0.0, iotype='in'))
        model.add('driver', SimpleDriver())
        model.add('subdriver', SimpleDriver())

        model.driver.workflow.add('subdriver')
        model.subdriver.workflow.add('comp')

        model.subdriver.add_parameter('comp.c', low=-100, high=100)
        model.subdriver.add_objective('comp.y_out - bvar')

        model.driver.add_parameter('bvar', low=-100, high=100)
        model.driver.add_objective('bvar - comp.y_out')
        model.comp.eval_only = True
        model.run()

        J = model.driver.calc_gradient()
Example #4
0
 def _clone_trait(self, name):
     """ Return valid new trait for model trait `name`. """
     trait = self.model.trait(name)
     if hasattr(trait, 'get'):  # Property trait -- don't use normal clone.
         val = getattr(self.model, name)
         metadata = {}
         for attr in ('iotype', 'desc', 'low', 'high',
                      'exclude_low', 'exclude_high', 'units'):
             try:
                 metadata[attr] = getattr(trait, attr)
             except AttributeError:
                 pass
         if metadata['iotype'] == 'in':
             metadata['default_value'] = val
         if isinstance(val, float):
             trait = Float(**metadata)
         else:
             trait = Int(**metadata)
     else:
         trait = _clone_trait(trait)
     return trait
Example #5
0
    def build_trait(self, ref_name, iotype=None, trait=None):
        if iotype is None:
            iostat = 'in'
        else:
            iostat = iotype

        if isinstance(iostat, dict):
            metadata = iostat
        else:
            metadata = dict(iotype=iostat)
        metadata['ref_name'] = ref_name

        if trait is None:
            if ref_name.startswith('f'):
                trait = Float(0.0, **metadata)
            elif ref_name.startswith('i'):
                trait = Int(0, **metadata)
            else:
                self.raise_exception("can't determine type of variable '%s'"
                                         % ref_name, RuntimeError)
        return trait
Example #6
0
class WindInputs(VariableTree):
    """Basic Wind Inputs needed to calculate Jacket Loads"""
    # inputs
    al_shear = Float(0.14,
                     units=None,
                     desc='power law exponent wind from IEC 61400-3')
    psi = Float(
        45.,
        units='deg',
        desc=
        'Wind angle relative global CS. Positive according to RHR with positive z direction.'
    )
    rho = Float(
        1.225,
        units='kg*m**-3',
        desc=
        'Air Density. Set to 0 if no tower wind load is included (thrust from rotor still on)'
    )
    U50HH = Float(
        70.,
        units='m/s',
        desc=
        '50-yr return 3-s gust [m/s] :From IEC Class I-III or whatever gust to be associated with DLC under consideration (e.g. 30 m/s for DLC 1.6 under max thrust)'
    )
    HH = Float(units='m', desc='Hub-height above MSL')
    mu = Float(1.7934e-5, units='kg/(m*s)', desc='dynamic viscosity of air')
    Cdj = Float(
        iotype='in',
        units=None,
        desc=
        'User input drag coefficient for jacket members, if left blank it will be automatically calculated based on Cylinder Re'
    )
    Cdt = Float(
        iotype='in',
        units=None,
        desc=
        'User input drag coefficient for tower, if left blank it will be automatically calculated based on Cylinder Re'
    )
Example #7
0
    def setUp(self):
        """This sets up the following hierarchy of Containers:

                       root
                       /  \
                     c1    c2
                          /  \
                        c21  c22
                             /
                          c221
                          /
                        number
        """

        self.root = Container()
        self.root.add('c1', Container())
        self.root.add('c2', Container())
        self.root.c2.add('c21', Container())
        self.root.c2.add('c22', Container())
        self.root.c2.c22.add('c221', Container())
        self.root.c2.c22.c221.add('number', Float(3.14, iotype='in'))
def configure_lcoe_with_openwind(assembly, ow_file='', ow_wkbook=''):
    """
    aep inputs
        power_curve    = Array([], iotype='in', desc='wind turbine power curve')
        rpm            = Array([], iotype='in', desc='wind turbine rpm curve')
        ct             = Array([], iotype='in', desc='wind turbine ct curve')
    """

    assembly.add(
        'other_losses',
        Float(0.0,
              iotype='in',
              desc='energy losses due to blade soiling, electrical, etc'))

    assembly.replace('aep_a', openwind_assembly(ow_file, ow_wkbook))

    assembly.connect('rotor.hubHt', 'aep_a.hub_height')
    assembly.connect('rotor.diameter', 'aep_a.rotor_diameter')
    assembly.connect('machine_rating', 'aep_a.machine_rating')
    assembly.connect('other_losses', 'aep_a.other_losses')
    '''assembly.add('zippy',zip_powercurve())
Example #9
0
class Example1FromManualComponent(Component):
    """ From the NEWSUMT User's Manual:

         EXAMPLE 1

         MINIMIZE OBJ = 10.0 * x(1) + X(2)

         Subject to:

              G(1) = 2.0 * X(1) - X(2) - 1.0 > 0
              G(2) = X(1) - 2.0 * X(2) + 1.0 > 0
              G(3) = - X(1)**2 + 2.0 * ( X(1) + X(2) ) - 1.0 > 0

    This problem is solved beginning with an initial X-vector of
         X = (2.0, 1.0)
    The optimum design is known to be
         OBJ = 5.5917
    and the corresponding X-vector is
         X = (0.5515, 0.1006)
    """

    x = Array(iotype='in')
    result = Float(iotype='out')

    # pylint: disable=C0103
    def __init__(self):
        """Initialize"""

        super(Example1FromManualComponent, self).__init__()
        # Initial guess
        self.x = numpy.array([2.0, 1.0], dtype=float)
        self.result = 0.0

        self.opt_objective = 5.5917
        self.opt_design_vars = [0.5515, 0.1006]

    def execute(self):
        """calculate the new objective value"""

        self.result = (10.0 * self.x[0] + self.x[1])
Example #10
0
class NetGain(Component):
    """
    Computes the sum of an inputted gain array.
    """
    net = Float(iotype="out")

    def __init__(self, n):
        super(NetGain, self).__init__()
        self.n = n
        self.add('gain', Array(np.zeros(n), iotype='in', shape=(n, )))

    def execute(self):
        self.net = sum(self.gain)

    def list_deriv_vars(self):
        input_keys = ('gain', )
        output_keys = ('net', )
        return input_keys, output_keys

    def apply_derivT(self, arg, result):
        if 'gain' in result and 'net' in arg:
            result['gain'] += arg['net'] * np.ones(self.n)
    def test_smart_low_high(self):

        top = Assembly()
        top.add('comp', MyComp())
        driver = top.add('driver', SimpleDriver())
        top.comp.add('x1', Float(1.0, iotype='in', low=-1.0, high=1.0))
        driver.add_objective('comp.y')
        driver.add_parameter('comp.x1', low=-1.0, high=1.0)
        driver.workflow.add('comp')

        top.driver.gradient_options.fd_form = 'central'
        top.driver.gradient_options.fd_step = 0.1

        top.comp.x1 = -0.95
        top.run()
        J = top.driver.workflow.calc_gradient()
        assert_rel_error(self, J[0, 0], -3.6, 0.001)

        top.comp.x1 = 0.95
        top.run()
        J = top.driver.workflow.calc_gradient()
        assert_rel_error(self, J[0, 0], 3.6, 0.001)
Example #12
0
class CompWithVarTreeSubTree(Component):
    ins = VarTree(TreeWithSubTree(), iotype="in")
    outs = VarTree(TreeWithFloat2(), iotype="out")
    outs2 = VarTree(TreeWithSubTree(), iotype="out")
    z = Float(iotype='out')

    def execute(self):
        self.outs.z = 2*self.ins.x.x1 + 3*self.ins.x.x2 + 4*self.ins.y
        self.z = self.outs.z

    def provideJ(self):
        self.J = ones((2, 3))
        self.J[:, 0] *= 2
        self.J[:, 1] *= 3
        self.J[:, 2] *= 4
        return self.J

    def list_deriv_vars(self):
        ins  = ('ins.x.x1', 'ins.x.x2', 'ins.y')
        outs = ('outs.z', 'z')

        return ins, outs
Example #13
0
class SolverCO(Assembly):
    """ solver using assmebly """

    x = Float(default_value=0, iotype='in', desc='test x')

    def configure(self):
        """config"""

        self.add('driver', SLSQPdriver())
        self.add('testdrv', SLSQPdriver())

        self.driver.workflow.add(['testdrv'])
        self.add('con', TestCon())
        self.testdrv.workflow.add(['con'])

        self.driver.add_parameter('x', low=-10, high=10)
        self.driver.add_constraint('(con.x1-x)**2 < 1e-3')
        self.driver.add_objective('x**2')

        self.testdrv.add_parameter('con.x1', low=-10, high=10)
        self.testdrv.add_objective('(con.x1-x)**2')
        self.testdrv.add_constraint('con.g1>=0')
Example #14
0
class Simple(Component):
    a = Float(iotype='in', units='inch')
    b = Float(iotype='in', units='inch')
    c = Float(iotype='out', units='ft')
    d = Float(iotype='out', units='ft')
    dist = Float(iotype='out', units='ft')
    time = Float(iotype='out', units='s')
    speed = Float(iotype='in', units='inch/s')
    arr = Array([1.,2.,3.], iotype='out', units='ft')

    def __init__(self):
        super(Simple, self).__init__()
        self.a = 1
        self.b = 2
        self.c = 3
        self.d = -1

    def execute(self):
        self.c = PhysicalQuantity(self.a + self.b, 'inch').in_units_of('ft').value
        self.d = PhysicalQuantity(self.a - self.b, 'inch').in_units_of('ft').value
Example #15
0
    def test_derivative_state_connection_external_solve_apply_deriv_not_implicit(
            self):

        model = set_as_top(Assembly())
        model.add('comp', MyComp_Explicit())
        model.comp.add('c', Float(2.0, iotype="in", fd_step=.001))

        model.add('comp2', ExecCompWithDerivatives(["y=2*x"], ["dy_dx=2"]))

        model.add('solver', BroydenSolver())
        model.solver.workflow.add(['comp'])
        model.driver.workflow.add(['solver', 'comp2'])
        model.connect('comp.z', 'comp2.x')

        model.solver.add_parameter('comp.x', low=-100, high=100)
        model.solver.add_parameter('comp.y', low=-100, high=100)
        model.solver.add_parameter('comp.z', low=-100, high=100)

        model.solver.add_constraint('comp.res[0] = 0')
        model.solver.add_constraint('comp.res[1] = 0')
        model.solver.add_constraint('comp.res[2] = 0')

        model.run()
        # print model.comp.x, model.comp.y, model.comp.z, model.comp.res
        J = model.driver.workflow.calc_gradient(inputs=['comp.c'],
                                                outputs=['comp2.y'])
        assert_rel_error(self, J[0][0], -0.1666, 1e-3)

        model.driver.workflow.config_changed()
        J = model.driver.workflow.calc_gradient(inputs=['comp.c'],
                                                outputs=['comp2.y'],
                                                mode='adjoint')
        assert_rel_error(self, J[0][0], -0.1666, 1e-3)

        model.driver.workflow.config_changed()
        J = model.driver.workflow.calc_gradient(inputs=['comp.c'],
                                                outputs=['comp2.y'],
                                                mode='fd')
        assert_rel_error(self, J[0][0], -0.1666, 1e-3)
Example #16
0
class RayleighCDF(CDFBase):
    """Rayleigh cumulative distribution function"""

    # Inputs
    xbar = Float(iotype='in', desc='mean value of distribution')
    x = Array(iotype='in', desc='input curve')

    # Outputs
    F = Array(iotype='out', desc='probabilities out')

    def __init__(self):

        super(RayleighCDF, self).__init__()

        #controls what happens if derivatives are missing
        self.missing_deriv_policy = 'assume_zero'

    def execute(self):

        self.F = 1.0 - np.exp(-np.pi / 4.0 * (self.x / self.xbar)**2)

        self.d_F_d_x = np.diag(
            -np.exp(-np.pi / 4.0 * (self.x / self.xbar)**2) *
            ((-np.pi / 2.0) * (self.x / self.xbar)) * (1.0 / self.xbar))
        self.d_F_d_xbar = -np.exp(-np.pi / 4.0 * (self.x / self.xbar)**2) * (
            (np.pi / 2.0) * (self.xbar / self.x)**(-3)) * (1.0 / self.x)

    def list_deriv_vars(self):

        inputs = ['x', 'xbar']
        outputs = ['F']

        return inputs, outputs

    def provideJ(self):

        self.J = hstack((self.d_F_d_x, self.d_F_d_xbar))

        return self.J
Example #17
0
class Markup(Component):

    transportationCost = Float(iotype='in',
                               units='USD',
                               desc='transportation cost')
    contingency = Float(3.0, iotype='in', desc='%')
    warranty = Float(0.02, iotype='in', desc='%')
    useTax = Float(0.0, iotype='in', desc='%')
    overhead = Float(5.0, iotype='in', desc='%')
    profitMargin = Float(5.0, iotype='in', desc='%')

    alpha = Float(iotype='out', desc='multiplier portion of markup cost')
    cost = Float(iotype='out',
                 units='USD',
                 desc='constant portion of markup cost')

    def execute(self):
        values = _landbos.markupMultiplierAndCost(self.transportationCost,
                                                  self.contingency,
                                                  self.warranty, self.useTax,
                                                  self.overhead,
                                                  self.profitMargin)
        self.alpha = values['alpha']
        self.cost = values['cost']
Example #18
0
    def test_derivative_state_connection_internal_solve_apply_deriv(self):

        model = set_as_top(Assembly())
        model.add('comp', MyComp_Deriv())
        model.comp.add('c', Float(2.0, iotype="in", fd_step=.001))

        model.add('comp2', ExecCompWithDerivatives(["y=2*x"], ["dy_dx=2"]))
        model.driver.workflow.add(['comp', 'comp2'])
        model.connect('comp.z', 'comp2.x')

        model.run()
        # print model.comp.x, model.comp.y, model.comp.z, model.comp.res
        J = model.driver.workflow.calc_gradient(inputs=['comp.c'],
                                                outputs=['comp2.y'])
        info = model.driver.workflow.get_implicit_info()
        # print info
        self.assertEqual(set(info[('comp.res', )]),
                         set(['comp.x', 'comp.y', 'comp.z']))
        self.assertEqual(len(info), 1)

        edges = model.driver.workflow._edges
        # print edges
        self.assertEqual(set(edges['@in0']), set(['comp.c']))
        self.assertEqual(set(edges['comp2.y']), set(['@out0']))

        assert_rel_error(self, J[0][0], -0.1666, 1e-3)

        model.driver.workflow.config_changed()
        J = model.driver.workflow.calc_gradient(inputs=['comp.c'],
                                                outputs=['comp2.y'],
                                                mode='adjoint')
        assert_rel_error(self, J[0][0], -0.1666, 1e-3)

        model.driver.workflow.config_changed()
        J = model.driver.workflow.calc_gradient(inputs=['comp.c'],
                                                outputs=['comp2.y'],
                                                mode='fd')
        assert_rel_error(self, J[0][0], -0.1666, 1e-3)
Example #19
0
 def __init__(self, exprs=[]):
     super(ExecComp, self).__init__()
     ins = set()
     outs = set()
     allvars = set()
     self.codes = [compile(expr, '<string>', 'exec') for expr in exprs]
     for expr in exprs:
         expreval = ExprEvaluator(expr, scope=self)
         exvars = expreval.get_referenced_varpaths()
         lhs, rhs = expr.split('=')
         lhs = lhs.strip()
         lhs = lhs.split(',')
         outs.update(lhs)
         allvars.update(exvars)
     ins = allvars - outs
     for var in allvars:
         if '.' not in var:  # if a varname has dots, it's outside of our scope,
             # so don't add a trait for it
             if var in outs:
                 iotype = 'out'
             else:
                 iotype = 'in'
             self.add(var, Float(iotype=iotype))
Example #20
0
    def __init__(self, num_elem=10):
        """ scaling: 1e4
        """
        super(SysBlockTime, self).__init__()

        # Inputs
        self.add(
            'v', Array(np.zeros((num_elem + 1, )),
                       iotype='in',
                       desc='airspeed'))
        self.add(
            'x', Array(np.zeros((num_elem + 1, )),
                       iotype='in',
                       desc='distance'))
        self.add(
            'Gamma',
            Array(np.zeros((num_elem + 1, )),
                  iotype='in',
                  desc='flight path angle'))

        # Outputs
        self.add('time',
                 Float(0.0, iotype='out', desc='Initial Mach number point'))
Example #21
0
    def __init__(self, Ns):
        super(Results, self).__init__()

        # inputs
        self.add('b', Int(0, iotype='in', desc='number of blades'))
        self.add('Ns', Int(0, iotype='in', desc='number of elements'))

        self.add('yN',
                 Array(np.zeros(Ns + 1), iotype='in', desc='node locations'))
        self.add('yE', Array(np.zeros(Ns), iotype='in', desc=''))
        self.add(
            'cE', Array(np.zeros(Ns),
                        iotype='in',
                        desc='chord of each element'))
        self.add(
            'Cl',
            Array(np.zeros(Ns),
                  iotype='in',
                  desc='lift coefficient distribution'))

        self.add(
            'q',
            Array(np.zeros((6 * (Ns + 1), 1)), iotype='in',
                  desc='deformation'))

        self.add('phi', Array(np.zeros(Ns), iotype='in', desc=''))

        self.add('collective',
                 Float(0., iotype='in', desc='collective angle in radians'))

        self.add('fblade', VarTree(Fblade(Ns), iotype='in'))

        self.add('Mtot', Float(0., iotype='in', desc='total mass'))

        # outputs
        self.add('di', Array(np.zeros(Ns), iotype='out',
                             desc='dihedral angle'))
        self.add(
            'alphaJig',
            Array(np.zeros(Ns), iotype='out', desc='aerodynamic jig angle'))

        self.add('Ttot', Float(0., iotype='out', desc='total thrust'))
        self.add('Qtot', Float(0., iotype='out', desc='total torque'))
        self.add('MomRot', Float(0., iotype='out', desc='total moment'))
        self.add('Ptot', Float(0., iotype='out', desc='total powers'))
    def test_broadcast_input_to_opaque_system(self):

        # This test replicates a bug when finite differencing a boundary variable that
        # broadcasts to multiple places.

        top = set_as_top(Assembly())
        top.add('comp1', ExecComp(['y=7.0*x1']))
        top.add('comp2', ExecComp(['y=5.0*x1 + 2.0*x2']))
        top.add('driver', SimpleDriver())
        top.driver.workflow.add(['comp1', 'comp2'])

        top.add('x1', Float(3.0, iotype='in'))
        top.connect('comp1.y', 'comp2.x2')
        top.connect('x1', 'comp1.x1')
        top.connect('x1', 'comp2.x1')

        top.run()

        J = top.driver.calc_gradient(inputs=['x1'],
                                     outputs=['comp2.y'],
                                     mode='forward')

        assert_rel_error(self, J[0, 0], 19.0, .001)
class SimpleUnits(Component):
    a = Float(iotype='in', units='inch')
    b = Float(iotype='in')
    kin = Float(iotype='in', units='K')
    c = Float(iotype='out', units='ft')
    d = Float(iotype='out')
    kout = Float(iotype='out', units='degK')

    def __init__(self):
        super(SimpleUnits, self).__init__()
        self.a = 4.
        self.b = 5.
        self.c = 7.
        self.d = 1.5

    def execute(self):
        self.c = self.a + self.b
        self.d = self.a - self.b
Example #24
0
    def __init__(self, exprs=(), sleep=0, trace=False):
        super(ExecComp, self).__init__()
        outs = set()
        allvars = set()
        self.exprs = exprs
        self.codes = [compile(expr, '<string>', 'exec') for expr in exprs]
        self.sleep = sleep
        self.trace = trace
        for expr in exprs:
            lhs, rhs = expr.split('=')
            lhs = lhs.strip()
            lhs = lhs.split(',')
            outs.update(lhs)
            expreval = ExprEvaluator(expr, scope=self)
            allvars.update(expreval.get_referenced_varpaths(copy=False))

        for var in allvars:
            if '.' not in var:  # if a varname has dots, it's outside of our scope,
                # so don't add a trait for it
                if var in outs:
                    iotype = 'out'
                else:
                    iotype = 'in'
                self.add(var, Float(0.0, iotype=iotype))
class DrivenComponent(Component):
    """ Just something to be driven and compute results. """

    a = Int(0, iotype='in')
    b = Int(0, iotype='in')
    v = Array(np.array([0, 1, 2, 3], dtype=np.int), iotype='in')
    x0 = Float(1., iotype='in')
    y0 = Float(1., iotype='in')  # used just to get ParameterGroup
    x1 = Float(1., iotype='in')
    x2 = Float(1., iotype='in')
    x3 = Float(1., iotype='in')
    rosen_suzuki = Float(0., iotype='out')
    raise_err = Bool(iotype='in')

    def execute(self):
        """ Compute results from input vector. """
        self.rosen_suzuki = rosen_suzuki(self.x0, self.x1, self.x2, self.x3)
        if self.raise_err:
            self.raise_exception('Forced error', RuntimeError)
class HollowSphere(Component):
    """ Simple component for testing. """

    radius = Float(1.0, low=0., exclude_low=True, iotype='in', units='cm')
    thickness = Float(0.05, iotype='in', units='cm')

    inner_volume = Float(iotype='out', units='cm**3')
    volume = Float(iotype='out', units='cm**3')
    solid_volume = Float(iotype='out', units='cm**3')
    surface_area = Float(iotype='out', units='cm**2')
    pid = Int(iotype='out')

    def __init__(self):
        super(HollowSphere, self).__init__()
        self.pid = os.getpid()

    def execute(self):
        self.surface_area = 4.0*pi*self.radius*self.radius
        self.inner_volume = 4.0/3.0*pi*self.radius**3
        self.volume = 4.0/3.0*pi*(self.radius+self.thickness)**3
        self.solid_volume = self.volume-self.inner_volume
Example #27
0
        class TestComponent(ImplicitComponent):

            # in
            a = Float(iotype='in')
            ap = Float(iotype='in')
            lambda_r = Float(iotype='in')

            # states
            phi = Float(iotype='state')

            # residuals
            residual = Float(iotype='residual')

            # outputs
            dummy = Float(iotype='out')

            eval_only = True

            def evaluate(self):

                self.residual = sin(self.phi)/(1-self.a) - cos(self.phi)/self.lambda_r/(1+self.ap)
                self.dummy = self.phi * 2
Example #28
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
Example #29
0
class SLSQPdriver(DriverUsesDerivatives):
    """Minimize a function using the Sequential Least SQuares Programming
    (SLSQP) method.

    SLSQP is a gradient optimizer that can handle both equality and
    inequality constraints.
    
    Note: Constraints should be added using the OpenMDAO convention
    (positive = violated).
    """
    
    implements(IHasParameters, IHasConstraints, IHasObjective)
    
    # pylint: disable-msg=E1101
    accuracy = Float(1.0e-6, iotype='in', 
                     desc = 'Convergence accuracy')

    maxiter = Int(50, iotype='in', 
                   desc = 'Maximum number of iterations.')

    iprint = Enum(0, [0, 1, 2, 3], iotype='in',
                  desc = 'Controls the frequency of output: 0 (no output),1,2,3.')
    
    iout = Int(6, iotype='in',
                  desc = 'Fortran output unit. Leave  this at 6 for STDOUT.')
    
    output_filename = Str('slsqp.out', iotype='in',
                          desc = 'Name of output file (if iout not 6).')
    
    error_code = Int(0, iotype='out',
                  desc = 'Error code returned from SLSQP.')
    
    
    def __init__(self, *args, **kwargs):
        
        super(SLSQPdriver, self).__init__(*args, **kwargs)
        
        self.error_messages = {
            -1 : "Gradient evaluation required (g & a)",
             1 : "Function evaluation required (f & c)",
             2 : "More equality constraints than independent variables",
             3 : "More than 3*n iterations in LSQ subproblem",
             4 : "Inequality constraints incompatible",
             5 : "Singular matrix E in LSQ subproblem",
             6 : "Singular matrix C in LSQ subproblem",
             7 : "Rank-deficient equality constraint subproblem HFTI",
             8 : "Positive directional derivative for linesearch",
             9 : "Iteration limit exceeded",        
        }
        
        self.x = zeros(0,'d')
        self.x_lower_bounds = zeros(0,'d')
        self.x_upper_bounds = zeros(0,'d')
        
        # We auto-fill the slot because the gradient is required
        # in this implementation
        self.differentiator = FiniteDifference()
        
    def start_iteration(self):
        """Perform initial setup before iteration loop begins."""
        
        if not self.differentiator:
            msg = 'A differentiator must be socketed for this driver.'
            self.raise_exception(msg, RuntimeError)

        self.nparam = len(self.get_parameters().values())
        self.ncon = len(self.get_constraints())
        self.neqcon = len(self.get_eq_constraints())
        
        # get the initial values of the parameters
        self.x = zeros(self.nparam,'d')
        params = self.get_parameters().values()
        for i, val in enumerate(params):
            self.x[i] = val.evaluate(self.parent)
            
        # create lower and upper bounds arrays
        self.x_lower_bounds = zeros(self.nparam)
        self.x_upper_bounds = zeros(self.nparam)
        for i, param in enumerate(params):
            self.x_lower_bounds[i] = param.low
            self.x_upper_bounds[i] = param.high        
            
        self.ff = 0
        self.nfunc = 0
        self.ngrad = 0

        self._continue = True
        
    def run_iteration(self):
        """ Note: slsqp controls the looping."""
        
        n = self.nparam
        m = self.ncon
        meq = self.neqcon
        
        la = max(m,1)
        self.gg = zeros([la], 'd')
        df = zeros([n+1], 'd')
        dg = zeros([la, n+1], 'd')
        
        mineq = m - meq + 2*(n+1)
        lsq = (n+1)*((n+1)+1) + meq*((n+1)+1) + mineq*((n+1)+1)
        lsi = ((n+1)-meq+1)*(mineq+2) + 2*mineq
        lsei = ((n+1)+mineq)*((n+1)-meq) + 2*meq + (n+1)
        slsqpb = (n+1)*(n/2) + 2*m + 3*n + 3*(n+1) + 1
        lw = lsq + lsi + lsei + slsqpb + n + m
        w = zeros([lw], 'd')
        ljw = max(mineq,(n+1)-meq)
        jw = zeros([ljw], 'i')
        
        try:
            dg, self.error_code, self.nfunc, self.ngrad = \
              slsqp(self.ncon, self.neqcon, la, self.nparam, \
                    self.x, self.x_lower_bounds, self.x_upper_bounds, \
                    self.ff, self.gg, df, dg, self.accuracy, self.maxiter, \
                    self.iprint-1, self.iout, self.output_filename, \
                    self.error_code, w, lw, jw, ljw, \
                    self.nfunc, self.ngrad, \
                    self._func, self._grad)
                    
            #slsqp(m,meq,la,n,xx,xl,xu,ff,gg,df,dg,acc,maxit,iprint,
            #      iout,ifile,mode,w,lw,jw,ljw,nfunc,ngrad,slfunc,slgrad)            
            
        except Exception, err:
            self._logger.error(str(err))
            raise       
        
        if self.iprint > 0 :
            closeunit(self.iout)

        # Log any errors
        if self.error_code != 0 :
            self._logger.warning(self.error_messages[self.error_code])

        # Iteration is complete
        self._continue = False
Example #30
0
class bos_csm_component(Component):

    # 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 __init__(self):
        """
        OpenMDAO component to wrap BOS model of the NREL _cost and Scaling Model (csmBOS.py)

        """
        #super(bos_csm_component, self).__init__() #update for FUSED - not recognizing bos_csm_component super due to decorator
        Component.__init__(self)

        #controls what happens if derivatives are missing
        self.missing_deriv_policy = 'assume_zero'

    def execute(self):
        """
        Executes BOS model of the NREL _cost and Scaling Model to estimate wind plant BOS costs.
        """

        # print "In {0}.execute()...".format(self.__class__)

        lPrmtsCostCoeff1 = 9.94E-04
        lPrmtsCostCoeff2 = 20.31
        oPrmtsCostFactor = 37.0  # $/kW (2003)
        scourCostFactor = 55.0  # $/kW (2003)
        ptstgCostFactor = 20.0  # $/kW (2003)
        ossElCostFactor = 260.0  # $/kW (2003) shallow
        ostElCostFactor = 290.0  # $/kW (2003) transitional
        ostSTransFactor = 25.0  # $/kW (2003)
        ostTTransFactor = 77.0  # $/kW (2003)
        osInstallFactor = 100.0  # $/kW (2003) shallow & trans
        suppInstallFactor = 330.0  # $/kW (2003) trans additional
        paiCost = 60000.0  # per turbine

        suretyBRate = 0.03  # 3% of ICC
        suretyBond = 0.0

        #set variables
        if self.sea_depth == 0:  # type of plant # 1: Land, 2: < 30m, 3: < 60m, 4: >= 60m
            iDepth = 1
        elif self.sea_depth < 30:
            iDepth = 2
        elif self.sea_depth < 60:
            iDepth = 3
        else:
            iDepth = 4

        # initialize self.ppi index calculator
        if iDepth == 1:
            ref_yr = 2002
            ref_mon = 9
        else:
            ref_yr = 2003
            ref_mon = 9
        ppi.ref_yr = ref_yr
        ppi.ref_mon = ref_mon
        ppi.curr_yr = self.year
        ppi.curr_mon = self.month

        self.d_foundation_d_diameter = 0.0
        self.d_foundation_d_hheight = 0.0
        self.d_foundation_d_rating = 0.0
        # foundation costs
        if (iDepth == 1):  # land
            fcCoeff = 303.23
            fcExp = 0.4037
            SweptArea = (self.rotor_diameter * 0.5)**2.0 * np.pi
            foundation_cost = fcCoeff * (self.hub_height * SweptArea)**fcExp
            fndnCostEscalator = ppi.compute('IPPI_FND')
            self.d_foundation_d_diameter = fndnCostEscalator * fcCoeff * fcExp * (
                (self.hub_height * (2.0 * 0.5 *
                                    (self.rotor_diameter * 0.5) * np.pi))
                **(fcExp - 1)) * self.hub_height
            self.d_foundation_d_hheight = fndnCostEscalator * fcCoeff * fcExp * (
                (self.hub_height * SweptArea)**(fcExp - 1)) * SweptArea
        elif (iDepth == 2):
            sscf = 300.0  # $/kW
            foundation_cost = sscf * self.machine_rating
            fndnCostEscalator = ppi.compute('IPPI_MPF')
            self.d_foundation_d_rating = fndnCostEscalator * sscf
        elif (iDepth == 3):
            sscf = 450.0  # $/kW
            foundation_cost = sscf * self.machine_rating
            fndnCostEscalator = ppi.compute('IPPI_OAI')
            self.d_foundation_d_rating = fndnCostEscalator * sscf
        elif (iDepth == 4):
            foundation_cost = 0.0
            fndnCostEscalator = 1.0

        foundation_cost *= fndnCostEscalator

        # cost calculations
        tpC1 = 0.00001581
        tpC2 = -0.0375
        tpInt = 54.7
        tFact = tpC1 * self.machine_rating * self.machine_rating + tpC2 * self.machine_rating + tpInt

        roadsCivil_costs = 0.0
        portStaging_costs = 0.0
        pai_costs = 0.0
        scour_costs = 0.0
        self.d_assembly_d_diameter = 0.0
        self.d_assembly_d_hheight = 0.0
        self.d_development_d_rating = 0.0
        self.d_preparation_d_rating = 0.0
        self.d_transport_d_rating = 0.0
        self.d_electrical_d_rating = 0.0
        self.d_assembly_d_rating = 0.0
        self.d_other_d_rating = 0.0
        if (iDepth == 1):
            engPermits_costs  = (lPrmtsCostCoeff1 * self.machine_rating * self.machine_rating) + \
                               (lPrmtsCostCoeff2 * self.machine_rating)
            ppi.ref_mon = 3
            engPermits_costs *= ppi.compute('IPPI_LPM')
            self.d_development_d_rating = ppi.compute('IPPI_LPM') * (
                2.0 * lPrmtsCostCoeff1 * self.machine_rating +
                lPrmtsCostCoeff2)
            ppi.ref_mon = 9

            elC1 = 3.49E-06
            elC2 = -0.0221
            elInt = 109.7
            eFact = elC1 * self.machine_rating * self.machine_rating + elC2 * self.machine_rating + elInt
            electrical_costs = self.machine_rating * eFact * ppi.compute(
                'IPPI_LEL')
            self.d_electrical_d_rating = ppi.compute('IPPI_LEL') * (3. * elC1*self.machine_rating**2. + \
                                    2. * elC2*self.machine_rating + elInt)

            rcC1 = 2.17E-06
            rcC2 = -0.0145
            rcInt = 69.54
            rFact = rcC1 * self.machine_rating * self.machine_rating + rcC2 * self.machine_rating + rcInt
            roadsCivil_costs = self.machine_rating * rFact * ppi.compute(
                'IPPI_RDC')
            self.d_preparation_d_rating = ppi.compute('IPPI_RDC') * (3. * rcC1 * self.machine_rating**2. + \
                                     2. * rcC2 * self.machine_rating + rcInt)

            iCoeff = 1.965
            iExp = 1.1736
            installation_costs = iCoeff * (
                (self.hub_height * self.rotor_diameter)**
                iExp) * ppi.compute('IPPI_LAI')
            self.d_assembly_d_diameter = iCoeff * (
                (self.hub_height * self.rotor_diameter)
                **(iExp - 1)) * self.hub_height * ppi.compute('IPPI_LAI')
            self.d_assembly_d_hheight = iCoeff * (
                (self.hub_height * self.rotor_diameter)
                **(iExp - 1)) * self.rotor_diameter * ppi.compute('IPPI_LAI')

            transportation_costs = self.machine_rating * tFact * ppi.compute(
                'IPPI_TPT')
            self.d_transport_d_rating = ppi.compute('IPPI_TPT') * (tpC1* 3. * self.machine_rating**2. + \
                                   tpC2* 2. * self.machine_rating + tpInt )

        elif (iDepth == 2):  # offshore shallow
            ppi.ref_yr = 2003
            pai_costs = paiCost * ppi.compute('IPPI_PAE')
            portStaging_costs = ptstgCostFactor * self.machine_rating * ppi.compute(
                'IPPI_STP')  # 1.415538133
            self.d_preparation_d_rating = ptstgCostFactor * ppi.compute(
                'IPPI_STP')
            engPermits_costs = oPrmtsCostFactor * self.machine_rating * ppi.compute(
                'IPPI_OPM')
            self.d_development_d_rating = oPrmtsCostFactor * ppi.compute(
                'IPPI_OPM')
            scour_costs = scourCostFactor * self.machine_rating * ppi.compute(
                'IPPI_STP')  # 1.415538133#
            self.d_other_d_rating = scourCostFactor * ppi.compute('IPPI_STP')
            installation_costs = osInstallFactor * self.machine_rating * ppi.compute(
                'IPPI_OAI')
            self.d_assembly_d_rating = osInstallFactor * ppi.compute(
                'IPPI_OAI')
            electrical_costs = ossElCostFactor * self.machine_rating * ppi.compute(
                'IPPI_OEL')
            self.d_electrical_d_rating = ossElCostFactor * ppi.compute(
                'IPPI_OEL')
            ppi.ref_yr = 2002
            transportation_costs = self.machine_rating * tFact * ppi.compute(
                'IPPI_TPT')
            self.d_transport_d_rating = ppi.compute('IPPI_TPT') * (tpC1* 3. * self.machine_rating**2. + \
                                   tpC2* 2. * self.machine_rating + tpInt )
            ppi.ref_yr = 2003

        elif (iDepth == 3):  # offshore transitional depth
            ppi.ref_yr = 2003
            turbInstall = osInstallFactor * self.machine_rating * ppi.compute(
                'IPPI_OAI')
            supportInstall = suppInstallFactor * self.machine_rating * ppi.compute(
                'IPPI_OAI')
            installation_costs = turbInstall + supportInstall
            self.d_assembly_d_rating = (
                osInstallFactor + suppInstallFactor) * ppi.compute('IPPI_OAI')
            pai_costs = paiCost * ppi.compute('IPPI_PAE')
            electrical_costs = ostElCostFactor * self.machine_rating * ppi.compute(
                'IPPI_OEL')
            self.d_electrical_d_rating = ossElCostFactor * ppi.compute(
                'IPPI_OEL')
            portStaging_costs = ptstgCostFactor * self.machine_rating * ppi.compute(
                'IPPI_STP')
            self.d_preparation_d_rating = ptstgCostFactor * ppi.compute(
                'IPPI_STP')
            engPermits_costs = oPrmtsCostFactor * self.machine_rating * ppi.compute(
                'IPPI_OPM')
            self.d_development_d_rating = oPrmtsCostFactor * ppi.compute(
                'IPPI_OPM')
            scour_costs = scourCostFactor * self.machine_rating * ppi.compute(
                'IPPI_STP')
            self.d_other_d_rating = scourCostFactor * ppi.compute('IPPI_STP')
            ppi.ref_yr = 2002
            turbTrans = ostTTransFactor * self.machine_rating * ppi.compute(
                'IPPI_TPT')
            self.d_transport_d_rating = ostTTransFactor * ppi.compute(
                'IPPI_TPT')
            ppi.ref_yr = 2003
            supportTrans = ostSTransFactor * self.machine_rating * ppi.compute(
                'IPPI_OAI')
            transportation_costs = self.turbTrans + self.supportTrans
            self.d_transport_d_rating += ostSTransFactor * ppi.compute(
                'IPPI_OAI')

        elif (iDepth == 4):  # offshore deep
            print "\ncsmBOS: Add costCat 4 code\n\n"

        bos_costs = foundation_cost + \
                    transportation_costs + \
                    roadsCivil_costs    + \
                    portStaging_costs   + \
                    installation_costs   + \
                    electrical_costs     + \
                    engPermits_costs    + \
                    pai_costs          + \
                    scour_costs

        self.d_other_d_tcc = 0.0
        if (self.sea_depth > 0.0):
            suretyBond = suretyBRate * (self.turbine_cost + bos_costs)
            self.d_other_d_tcc = suretyBRate
            d_surety_d_rating = suretyBRate * (self.d_development_d_rating + self.d_preparation_d_rating + self.d_transport_d_rating + \
                          self.d_foundation_d_rating + self.d_electrical_d_rating + self.d_assembly_d_rating + self.d_other_d_rating)
            self.d_other_d_rating += d_surety_d_rating
        else:
            suretyBond = 0.0

        self.bos_costs = self.turbine_number * (bos_costs + suretyBond)
        self.bos_costs *= self.multiplier  # TODO: add to gradients

        self.bos_breakdown.development_costs = engPermits_costs * self.turbine_number
        self.bos_breakdown.preparation_and_staging_costs = (
            roadsCivil_costs + portStaging_costs) * self.turbine_number
        self.bos_breakdown.transportation_costs = (transportation_costs *
                                                   self.turbine_number)
        self.bos_breakdown.foundation_and_substructure_costs = foundation_cost * self.turbine_number
        self.bos_breakdown.electrical_costs = electrical_costs * self.turbine_number
        self.bos_breakdown.assembly_and_installation_costs = installation_costs * self.turbine_number
        self.bos_breakdown.soft_costs = 0.0
        self.bos_breakdown.other_costs = (pai_costs + scour_costs +
                                          suretyBond) * self.turbine_number

        # derivatives
        self.d_development_d_rating *= self.turbine_number
        self.d_preparation_d_rating *= self.turbine_number
        self.d_transport_d_rating *= self.turbine_number
        self.d_foundation_d_rating *= self.turbine_number
        self.d_electrical_d_rating *= self.turbine_number
        self.d_assembly_d_rating *= self.turbine_number
        self.d_soft_d_rating = 0.0
        self.d_other_d_rating *= self.turbine_number
        self.d_cost_d_rating = self.d_development_d_rating + self.d_preparation_d_rating + self.d_transport_d_rating + \
                          self.d_foundation_d_rating + self.d_electrical_d_rating + self.d_assembly_d_rating + \
                          self.d_soft_d_rating + self.d_other_d_rating

        self.d_development_d_diameter = 0.0
        self.d_preparation_d_diameter = 0.0
        self.d_transport_d_diameter = 0.0
        #self.d_foundation_d_diameter
        self.d_electrical_d_diameter = 0.0
        #self.d_assembly_d_diameter
        self.d_soft_d_diameter = 0.0
        self.d_other_d_diameter = 0.0
        self.d_cost_d_diameter = self.d_development_d_diameter + self.d_preparation_d_diameter + self.d_transport_d_diameter + \
                          self.d_foundation_d_diameter + self.d_electrical_d_diameter + self.d_assembly_d_diameter + \
                          self.d_soft_d_diameter + self.d_other_d_diameter

        self.d_development_d_tcc = 0.0
        self.d_preparation_d_tcc = 0.0
        self.d_transport_d_tcc = 0.0
        self.d_foundation_d_tcc = 0.0
        self.d_electrical_d_tcc = 0.0
        self.d_assembly_d_tcc = 0.0
        self.d_soft_d_tcc = 0.0
        self.d_other_d_tcc *= self.turbine_number
        self.d_cost_d_tcc = self.d_development_d_tcc + self.d_preparation_d_tcc + self.d_transport_d_tcc + \
                          self.d_foundation_d_tcc + self.d_electrical_d_tcc + self.d_assembly_d_tcc + \
                          self.d_soft_d_tcc + self.d_other_d_tcc

        self.d_development_d_hheight = 0.0
        self.d_preparation_d_hheight = 0.0
        self.d_transport_d_hheight = 0.0
        #self.d_foundation_d_hheight
        self.d_electrical_d_hheight = 0.0
        #self.d_assembly_d_hheight
        self.d_soft_d_hheight = 0.0
        self.d_other_d_hheight = 0.0
        self.d_cost_d_hheight = self.d_development_d_hheight + self.d_preparation_d_hheight + self.d_transport_d_hheight + \
                          self.d_foundation_d_hheight + self.d_electrical_d_hheight + self.d_assembly_d_hheight + \
                          self.d_soft_d_hheight + self.d_other_d_hheight

        self.d_development_d_rna = 0.0
        self.d_preparation_d_rna = 0.0
        self.d_transport_d_rna = 0.0
        self.d_foundation_d_rna = 0.0
        self.d_electrical_d_rna = 0.0
        self.d_assembly_d_rna = 0.0
        self.d_soft_d_rna = 0.0
        self.d_other_d_rna = 0.0
        self.d_cost_d_rna = self.d_development_d_rna + self.d_preparation_d_rna + self.d_transport_d_rna + \
                          self.d_foundation_d_rna + self.d_electrical_d_rna + self.d_assembly_d_rna + \
                          self.d_soft_d_rna + self.d_other_d_rna

    def list_deriv_vars(self):

        inputs = [
            'machine_rating', 'rotor_diameter', 'turbine_cost', 'hub_height',
            'RNA_mass'
        ]
        outputs = ['bos_breakdown.development_costs', 'bos_breakdown.preparation_and_staging_costs',\
                   'bos_breakdown.transportation_costs', 'bos_breakdown.foundation_and_substructure_costs',\
                   'bos_breakdown.electrical_costs', 'bos_breakdown.assembly_and_installation_costs',\
                   'bos_breakdown.soft_costs', 'bos_breakdown.other_costs', 'bos_costs']

        return inputs, outputs

    def provideJ(self):

        self.J = np.array([[self.d_development_d_rating, self.d_development_d_diameter, self.d_development_d_tcc, self.d_development_d_hheight, self.d_development_d_rna],\
                           [self.d_preparation_d_rating, self.d_preparation_d_diameter, self.d_preparation_d_tcc, self.d_preparation_d_hheight, self.d_preparation_d_rna],\
                           [self.d_transport_d_rating, self.d_transport_d_diameter, self.d_transport_d_tcc, self.d_transport_d_hheight, self.d_transport_d_rna],\
                           [self.d_foundation_d_rating, self.d_foundation_d_diameter, self.d_foundation_d_tcc, self.d_foundation_d_hheight, self.d_foundation_d_rna],\
                           [self.d_electrical_d_rating, self.d_electrical_d_diameter, self.d_electrical_d_tcc, self.d_electrical_d_hheight, self.d_electrical_d_rna],\
                           [self.d_assembly_d_rating, self.d_assembly_d_diameter, self.d_assembly_d_tcc, self.d_assembly_d_hheight, self.d_assembly_d_rna],\
                           [self.d_soft_d_rating, self.d_soft_d_diameter, self.d_soft_d_tcc, self.d_soft_d_hheight, self.d_soft_d_rna],\
                           [self.d_other_d_rating, self.d_other_d_diameter, self.d_other_d_tcc, self.d_other_d_hheight, self.d_other_d_rna],\
                           [self.d_cost_d_rating, self.d_cost_d_diameter, self.d_cost_d_tcc, self.d_cost_d_hheight, self.d_cost_d_rna]])

        return self.J