How to use the openmdao.api.ExplicitComponent function in openmdao

To help you get started, we’ve selected a few openmdao examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github OpenMDAO / OpenMDAO / openmdao / test_suite / components / simple_comps.py View on Github external
outputs['y1'] = self.JJ[0:2, 0:2].dot(inputs['x1']) + \
                        self.JJ[0:2, 2:4].dot(inputs['x2'])
        outputs['y2'] = self.JJ[2:4, 0:2].dot(inputs['x1']) + \
                        self.JJ[2:4, 2:4].dot(inputs['x2'])

    def compute_partials(self, inputs, partials):
        """
        Analytical derivatives.
        """
        partials[('y1', 'x1')] = self.JJ[0:2, 0:2]
        partials[('y1', 'x2')] = self.JJ[0:2, 2:4]
        partials[('y2', 'x1')] = self.JJ[2:4, 0:2]
        partials[('y2', 'x2')] = self.JJ[2:4, 2:4]


class NonSquareArrayComp(om.ExplicitComponent):
    """
    A fairly simple array component.
    """

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

        self.JJ = np.array([[1.0, 3.0, -2.0, 7.0],
                            [6.0, 2.5, 2.0, 4.0],
                            [-1.0, 0.0, 8.0, 1.0],
                            [1.0, 4.0, -5.0, 6.0]])

        self.declare_partials('*', '*')

    def setup(self):
        # Params
github OpenMDAO / OpenMDAO / openmdao / test_suite / components / unit_conv.py View on Github external
""" Some models used in unit conversion tests."""

import numpy as np

import openmdao.api as om


class SrcComp(om.ExplicitComponent):
    """Source provides degrees Celsius."""

    def setup(self):
        self.add_input('x1', 100.0)
        self.add_output('x2', 100.0, units='degC')

        self.declare_partials('*', '*')

    def compute(self, inputs, outputs):
        """ Pass through."""
        outputs['x2'] = inputs['x1']

    def compute_partials(self, inputs, partials):
        """ Derivative is 1.0"""
        partials['x2', 'x1'] = 1.0
github OpenMDAO / pyCycle / pycycle / elements / duct.py View on Github external
outputs['s_dPqP'] = inputs['dPqP'] / inputs['MN_in']**expMN
        else:
            outputs['dPqP'] = inputs['s_dPqP'] * inputs['MN_in']**expMN

    def compute_partials(self, inputs, J):
        design = self.options['design']
        expMN = self.options['expMN']

        if design:
            J['s_dPqP', 'dPqP'] = 1.0 / inputs['MN_in']**expMN
            J['s_dPqP', 'MN_in'] = -expMN * inputs['dPqP'] * inputs['MN_in']**(-expMN-1.0)
        else:
            J['dPqP', 's_dPqP'] = inputs['MN_in']**expMN
            J['dPqP', 'MN_in'] = expMN * inputs['s_dPqP'] * inputs['MN_in']**(expMN-1.0)

class PressureLoss(om.ExplicitComponent):
    """
    Calculates pressure loss across the duct.
    """

    def setup(self):
        # inputs
        self.add_input('dPqP', val = 0.0,
                       desc='pressure differential as a fraction of incoming pressure')
        self.add_input('Pt_in', val=5.0, units='lbf/inch**2', desc='Inlet total pressure')

        # outputs
        self.add_output('Pt_out', val=14.696, units='lbf/inch**2', desc='Exit total pressure', lower=1e-3)

        self.declare_partials('Pt_out', '*')

    def compute(self, inputs, outputs):
github mdolab / openconcept / openconcept / analysis / takeoff.py View on Github external
self.declare_partials(['climb|gamma'], ['weight','thrust_v2','drag_v2'])

    def compute(self, inputs, outputs):
        g = 9.80665 #m/s^2
        outputs['climb|gamma'] = np.arcsin((inputs['thrust_v2']-inputs['drag_v2'])/inputs['weight']/g)

    def compute_partials(self, inputs, J):
        g = 9.80665 #m/s^2
        interior_qty = (inputs['thrust_v2']-inputs['drag_v2'])/inputs['weight']/g
        d_arcsin = 1/np.sqrt(1-interior_qty**2)
        J['climb|gamma','thrust_v2'] = d_arcsin/inputs['weight']/g
        J['climb|gamma','drag_v2'] = -d_arcsin/inputs['weight']/g
        J['climb|gamma','weight'] = -d_arcsin*(inputs['thrust_v2']-inputs['drag_v2'])/inputs['weight']**2/g

class TakeoffTransition(ExplicitComponent):
    """
    Computes distance and altitude at end of circular transition.

    This is a helper function for the main TOFL analysis group `TakeoffTotalDistance`
    and shoudln't be instantiated in the top-level model directly.

    Based on TO distance analysis method in Raymer book.
    Obstacle clearance height set for GA / Part 23 aircraft
    Override for analyzing Part 25 aircraft

    Inputs
    ------
    fltcond|Utrue_vtrans
        Transition true airspeed (generally avg of vr and v2) (scalar, m/s)
    climb|gamma : float
        Climb out flight path angle (scalar, rad)
github mdolab / openconcept / examples / methods / weights_twin_hybrid.py View on Github external
# # #Wh_raymer = 0.016 * (n_ult*inputs['ac|weights|MTOW'])**0.414 * inputs['ac|q_cruise']**0.168 * inputs['ac|geom|hstab|S_ref']**0.896 * (100 * 0.18)**-0.12 * (inputs['AR_h'])**0.043 * 0.7**-0.02
        # # Wv = 98.5 * ((inputs['ac|weights|MTOW']*n_ult/1e5)**0.87 * (inputs['ac|geom|vstab|S_ref']/100)**1.2 * 0.289 * (bv/inputs['troot_v'])**0.5)**0.458

        # # Wemp_USAF = Wh + Wv

        #Torenbeek, Roskam PVC5p73eq5.16
        Wemp_Torenbeek = 0.04 * (n_ult * (inputs['ac|geom|vstab|S_ref'] + inputs['ac|geom|hstab|S_ref'])**2)**0.75
        outputs['W_empennage'] = Wemp_Torenbeek

    def compute_partials(self, inputs, J):
        n_ult = self.options['n_ult']
        J['W_empennage','ac|geom|vstab|S_ref'] = 0.75* 0.04 * (n_ult * (inputs['ac|geom|vstab|S_ref'] + inputs['ac|geom|hstab|S_ref'])**2)**(0.75-1)*(n_ult * 2* (inputs['ac|geom|vstab|S_ref'] + inputs['ac|geom|hstab|S_ref']))
        J['W_empennage','ac|geom|hstab|S_ref'] = 0.75* 0.04 * (n_ult * (inputs['ac|geom|vstab|S_ref'] + inputs['ac|geom|hstab|S_ref'])**2)**(0.75-1)*(n_ult * 2* (inputs['ac|geom|vstab|S_ref'] + inputs['ac|geom|hstab|S_ref']))


class FuselageWeight_SmallTurboprop(ExplicitComponent):
    def initialize(self):
        #self.options.declare('num_nodes', default=1, desc='Number of flight/control conditions')
        #define configuration parameters
        self.options.declare('n_ult', default=3.8*1.5, desc='Ultimate load factor (dimensionless)')


    def setup(self):
        #nn = self.options['num_nodes']
        self.add_input('ac|weights|MTOW', units='lb', desc='Maximum rated takeoff weight')
        self.add_input('ac|geom|fuselage|length', units='ft', desc='Fuselage length (not counting nacelle')
        self.add_input('ac|geom|fuselage|height', units='ft', desc='Fuselage height')
        self.add_input('ac|geom|fuselage|width', units='ft', desc='Fuselage weidth')
        #self.add_input('V_C', units='kn', desc='Indicated cruise airspeed (KEAS)')
        #self.add_input('V_MO', units='kn', desc='Max operating speed (indicated)')
        self.add_input('ac|geom|fuselage|S_wet', units='ft**2', desc='Fuselage shell area')
        self.add_input('ac|geom|hstab|c4_to_wing_c4', units='ft', desc='Horiz tail arm')
github OpenMDAO / dymos / dymos / glm / ozone / components / explicit_tm_step_comp.py View on Github external
import numpy as np
from six import iteritems
import scipy.sparse

from openmdao.api import ExplicitComponent

from dymos.glm.ozone.utils.var_names import get_name
from dymos.glm.ozone.utils.units import get_rate_units


class ExplicitTMStepComp(ExplicitComponent):

    def initialize(self):
        self.options.declare('states', types=dict)
        self.options.declare('time_units', types=str, allow_none=True)
        self.options.declare('num_stages', types=int)
        self.options.declare('num_step_vars', types=int)
        self.options.declare('glm_B', types=np.ndarray)
        self.options.declare('glm_V', types=np.ndarray)
        self.options.declare('i_step', types=int)

    def setup(self):
        time_units = self.options['time_units']
        num_stages = self.options['num_stages']
        num_step_vars = self.options['num_step_vars']
        i_step = self.options['i_step']
        glm_B = self.options['glm_B']
github OpenMDAO / OpenMDAO / benchmark / benchmark_multipoint.py View on Github external
from __future__ import print_function
import unittest
from six.moves import range
import numpy as np

import time
from openmdao.api import Problem, Group, ExplicitComponent, IndepVarComp, ExecComp


class Plus(ExplicitComponent):
    def __init__(self, adder):
        super(Plus, self).__init__()
        self.adder = float(adder)

    def setup(self):
        self.add_input('x', np.random.random())
        self.add_output('f1', shape=1)

    def compute(self, inputs, outputs):
        outputs['f1'] = inputs['x'] + self.adder

class Times(ExplicitComponent):
    def __init__(self, scalar):
        super(Times, self).__init__()
        self.scalar = float(scalar)
github OpenMDAO / dymos / dymos / phases / simulation / simulation_phase_control_interp_comp.py View on Github external
_, Daa_block = lagrange_matrices(tau_s_given, tau_s_given)

        L_blocks.append(L_block)
        D_blocks.append(D_block)
        Daa_blocks.append(Daa_block)

    L_ae = block_diag(*L_blocks)
    D_ae = block_diag(*D_blocks)

    D_aa = block_diag(*Daa_blocks)
    D2_ae = np.dot(D_ae, D_aa)

    return L_ae, D_ae, D2_ae


class SimulationPhaseControlInterpComp(ExplicitComponent):
    """
    Compute the approximated control values and rates given the values of a control at an arbitrary
    set of points (known a priori) given the values at all nodes.

    Notes
    -----
    .. math::

        u = \\left[ L \\right] u_d

        \\dot{u} = \\frac{d\\tau_s}{dt} \\left[ D \\right] u_d

        \\ddot{u} = \\left( \\frac{d\\tau_s}{dt} \\right)^2 \\left[ D_2 \\right] u_d

    where
    :math:`u_d` are the values of the control at the control discretization nodes,
github mdolab / openconcept / examples / HybridTwin.py View on Github external
from openconcept.utilities.math import VectorConcatenateComp, VectorSplitComp
from openconcept.utilities.dict_indepvarcomp import DictIndepVarComp
from openconcept.analysis.takeoff import BalancedFieldLengthTakeoff, takeoff_check
from openconcept.analysis.mission import MissionAnalysis
from openconcept.utilities.linearinterp import LinearInterpolator
from openconcept.utilities.nodes import compute_num_nodes
#These imports are particular to this airplane
# If run from the root git  directory as 'python examples/script.py', these imports are found because the script's path is added to sys.path by default.

from methods.weights_twin_hybrid import TwinSeriesHybridEmptyWeight
from methods.costs_commuter import OperatingCost
from aircraft_data.KingAirC90GT import data as acdata
from aircraft_data.KingAirC90GT_mission import data as missiondata
from propulsion_layouts.simple_series_hybrid import TwinSeriesHybridElectricPropulsionSystem

class DummyPayload(ExplicitComponent):
    def setup(self):
        self.add_input('payload_DV', units='lb')
        self.add_output('payload_objective', units='lb')
        self.declare_partials(['payload_objective'], ['payload_DV'], val=1)
    def compute(self, inputs, outputs):
        outputs['payload_objective'] = inputs['payload_DV']

class AugmentedFBObjective(ExplicitComponent):
    def setup(self):
        self.add_input('fuel_burn', units='kg')
        self.add_input('ac|weights|MTOW', units='kg')
        self.add_output('mixed_objective', units='kg')
        self.declare_partials(['mixed_objective'], ['fuel_burn'], val=1)
        self.declare_partials(['mixed_objective'], ['ac|weights|MTOW'], val=1/100)
    def compute(self, inputs, outputs):
        outputs['mixed_objective'] = inputs['fuel_burn'] + inputs['ac|weights|MTOW']/100
github mdolab / OpenAeroStruct / openaerostruct / aerodynamics / components / mesh / vlm_ref_axis_comp.py View on Github external
from __future__ import print_function
import numpy as np

from openmdao.api import ExplicitComponent

from openaerostruct.utils.misc_utils import get_array_indices, get_airfoils, tile_sparse_jac


class VLMRefAxisComp(ExplicitComponent):

    def initialize(self):
        self.metadata.declare('num_nodes', types=int)
        self.metadata.declare('lifting_surfaces', types=list)

    def setup(self):
        num_nodes = self.metadata['num_nodes']
        lifting_surfaces = self.metadata['lifting_surfaces']

        for lifting_surface_name, lifting_surface_data in lifting_surfaces:
            num_points_x = lifting_surface_data.num_points_x
            num_points_z = 2 * lifting_surface_data.num_points_z_half - 1

            x_name = '{}_{}'.format(lifting_surface_name, 'sec_x')
            y_name = '{}_{}'.format(lifting_surface_name, 'sec_y')
            z_name = '{}_{}'.format(lifting_surface_name, 'sec_z')