How to use the openmdao.api.Component 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 / OpenMDAO1 / mpitest / test_mpi.py View on Github external
self.add_output('d', np.ones(arr_size, float))
        self.add_output('out_string', '')
        self.add_output('out_list', [])

        self.delay = delay

    def solve_nonlinear(self, params, unknowns, resids):
        time.sleep(self.delay)

        unknowns['c'] = params['a'] + params['b']
        unknowns['d'] = params['a'] - params['b']

        unknowns['out_string'] = params['in_string'] + '_' + self.name
        unknowns['out_list']   = params['in_list'] + [1.5]

class PBOComp(Component):

    def __init__(self):
        super(PBOComp, self).__init__()
        self.add_param('a', [0.,0.,0.,0.,0.])
        self.add_param('b', [1.,2.,3.,4.,5.])

        self.add_output('c', [1.,2.,3.,4.,5.])
        self.add_output('d', [-1.,-2.,-3.,-4.,-5.])

    def solve_nonlinear(self, params, unknowns, resids):
        for i in range(5):
            unknowns['c'][i] = params['a'][i] + params['b'][i]
            unknowns['d'][i] = params['a'][i] - params['b'][i]

class PBOTestCase(MPITestCase):
    N_PROCS=1
github OpenMDAO / OpenMDAO1 / mpitest / test_par_less_procs.py View on Github external
import sys
import numpy
import time

from openmdao.api import Problem, IndepVarComp, Group, ParallelGroup, \
                         Component
from openmdao.test.exec_comp_for_test import ExecComp4Test
from openmdao.core.mpi_wrap import MPI
from openmdao.test.mpi_util import MPITestCase
if MPI:
    from openmdao.core.petsc_impl import PetscImpl as impl
else:
    from openmdao.api import BasicImpl as impl

class Adder(Component):
    def __init__(self, n):
        super(Adder, self).__init__()
        for i in range(1,n+1):
            self.add_param("x%d"%i, 0.0)
        self.add_output("sum", 0.0)

    def solve_nonlinear(self, params, unknowns, resids):
        unknowns["sum"] = sum(params[n] for n in self._init_params_dict)

class NDiamondPar(Group):
    """ Topology one - n - one."""

    def __init__(self, n, expr="y=2.0*x", req_procs=(1,1)):
        super(NDiamondPar, self).__init__()

        self.add('src', IndepVarComp('x', 2.0))
github OpenMDAO / OpenMDAO1 / mpitest / test_mpi.py View on Github external
import numpy as np

from openmdao.api import Problem, Group, ParallelGroup, Component, IndepVarComp
from openmdao.core.mpi_wrap import MPI, FakeComm
from openmdao.test.mpi_util import MPITestCase

if MPI:
    from openmdao.core.petsc_impl import PetscImpl as impl
else:
    from openmdao.api import BasicImpl as impl

from openmdao.test.util import assert_rel_error


class ABCDArrayComp(Component):

    def __init__(self, arr_size=9, delay=0.01):
        super(ABCDArrayComp, self).__init__()
        self.add_param('a', np.ones(arr_size, float))
        self.add_param('b', np.ones(arr_size, float))
        self.add_param('in_string', '')
        self.add_param('in_list', [])

        self.add_output('c', np.ones(arr_size, float))
        self.add_output('d', np.ones(arr_size, float))
        self.add_output('out_string', '')
        self.add_output('out_list', [])

        self.delay = delay

    def solve_nonlinear(self, params, unknowns, resids):
github mdolab / OpenAeroStruct / vlm.py View on Github external
super(TotalLift, self).__init__()

        self.add_param('CL1', val=0.)
        self.add_output('CL', val=0.)
        self.CL0 = surface['CL0']

    def solve_nonlinear(self, params, unknowns, resids):
        unknowns['CL'] = params['CL1'] + self.CL0

    def linearize(self, params, unknowns, resids):
        jac = self.alloc_jacobian()
        jac['CL', 'CL1'] = 1.
        return jac


class TotalDrag(Component):
    """ Calculate total drag in force units.

    Parameters
    ----------
    CDi : float
        Induced coefficient of drag (CD) for the lifting surface.
    CDv : float
        Calculated viscous drag for the lifting surface..

    Returns
    -------
    CD : float
        Total coefficient of drag (CD) for the lifting surface.

    """
github abdullah2891 / solar_energy_calculator / lib / basic.py View on Github external
import warnings
warnings.filterwarnings("ignore")

from openmdao.api import Component, Group, Problem, IndepVarComp

import numpy as np

from parser import parse_data

from solar import Panels, Batteries, DataSource, Costs
from make_plot import make_plot

class BasicLoads(Component):
    """
    A very basic PV solar load component. Has constant power draws, and direct loading.
    """
    def __init__(self, n):
        super(BasicLoads, self).__init__()
        self.n = n

        self.add_param("P_constant", 0.0, units="W")
        self.add_param("P_direct", 0.0, units="W")
        self.add_param("P_daytime", 0.0, units="W")
        self.add_param("P_nighttime", 0.0, units="W") 
        self.add_param("switch_temp", 0.0, units="degF")

        self.add_param("P_generated", np.zeros(self.n), units="W")
        self.add_param("cell_temperature", np.zeros(self.n), units="degF")
        self.add_param("ambient_temperature", np.zeros(self.n), units="degF")
github mdolab / OpenAeroStruct / vlm.py View on Github external
(self.d_over_q / 4 / chords + chords * cd_Re * re / 2.)
            jac['CDv', 'lengths'][0, 1:] += CDv_lengths
            jac['CDv', 'lengths'][0, :-1] += CDv_lengths
            jac['CDv', 'widths'][0, :] = self.d_over_q * FF / S_ref * 0.72
            jac['CDv', 'S_ref'] = - self.D_over_q / S_ref**2
            jac['CDv', 'cos_sweep'][0, :] = 0.28 * self.k_FF * self.d_over_q / S_ref / cos_sweep**0.72

            if self.surface['symmetry']:
                jac['CDv', 'lengths'][0, :] *=  2
                jac['CDv', 'widths'][0, :] *= 2
                jac['CDv', 'S_ref'] *=  2
                jac['CDv', 'cos_sweep'][0, :] *=  2

        return jac

class VLMCoeffs(Component):
    """ Compute lift and drag coefficients for each individual lifting surface.

    Parameters
    ----------
    S_ref : float
        The reference areas of the lifting surface.
    L : float
        Total lift for the lifting surface.
    D : float
        Total drag for the lifting surface.
    v : float
        Freestream air velocity in m/s.
    rho : float
        Air density in kg/m^3.

    Returns
github OpenMDAO / OpenMDAO1 / openmdao / examples / fd_model_example.py View on Github external
""" This example shows how to finite difference a single component."""

from __future__ import print_function

from openmdao.api import IndepVarComp, Component, Group, Problem

class SimpleComp(Component):
    """ A simple component that provides derivatives. """

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

        # Params
        self.add_param('x', 2.0)

        # Unknowns
        self.add_output('y', 0.0)

        self.print_output = True

    def solve_nonlinear(self, params, unknowns, resids):
        """ Doesn't do much.  Just multiply by 3"""
        unknowns['y'] = 3.0*params['x']
github mdolab / OpenAeroStruct / vlm.py View on Github external
tmp = np.array([-sina, 0, cosa])
        jac['L', 'sec_forces'] = \
            np.atleast_2d(np.tile(tmp, self.num_panels)) * symmetry_factor
        tmp = np.array([cosa, 0, sina])
        jac['D', 'sec_forces'] = \
            np.atleast_2d(np.tile(tmp, self.num_panels)) * symmetry_factor

        p180 = np.pi / 180.
        jac['L', 'alpha'] = p180 * symmetry_factor * \
            np.sum(-forces[:, :, 0] * cosa - forces[:, :, 2] * sina)
        jac['D', 'alpha'] = p180 * symmetry_factor * \
            np.sum(-forces[:, :, 0] * sina + forces[:, :, 2] * cosa)

        return jac

class ViscousDrag(Component):
    """
    Compute the skin friction drag if the with_viscous option is True.

    Parameters
    ----------
    re : float
        Dimensionalized (1/length) Reynolds number. This is used to compute the
        local Reynolds number based on the local chord length.
    M : float
        Mach number.
    S_ref : float
        The reference area of the lifting surface.
    sweep : float
        The angle (in degrees) of the wing sweep. This is used in the form
        factor calculation.
    widths[ny-1] : np array
github OpenMDAO / OpenMDAO1 / openmdao / examples / beam_tutorial.py View on Github external
unknowns['deflection'] = (E * I * 384.0) / (5.0 * ((0.5 * TOTAL_LOAD_PSI * room_width)  + BEAM_WEIGHT_LBS_PER_IN) * room_length**3)


    def linearize(self, params, unknowns, resids):
        J = {}

        room_width = params['room_width']
        room_length = params['room_length']

        J['deflection','room_width'] = (-192.0 * E * I * TOTAL_LOAD_PSI) / ((5.0 * room_length**3) * (TOTAL_LOAD_PSI * room_width/2.0 + BEAM_WEIGHT_LBS_PER_IN)**2)
        J['deflection','room_length'] = (-1152.0 * E * I) / (5.0 * ((TOTAL_LOAD_PSI * room_width)/2.0 + BEAM_WEIGHT_LBS_PER_IN) * room_length**4)

        return J


class BendingStress(Component):

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

        self.add_param('room_width', val=0.0)
        self.add_param('room_length', val=0.0)
        self.add_output('bending_stress_ratio', val=0.0)

    def solve_nonlinear(self, params, unknowns, resids):

        room_width = params['room_width']
        room_length = params['room_length']

        unknowns['bending_stress_ratio'] = (0.5*BEAM_HEIGHT_IN * ((0.5 * TOTAL_LOAD_PSI * room_width)  + BEAM_WEIGHT_LBS_PER_IN) * (room_length)**2) / (8.0 * YIELD_STRENGTH_PSI * I)

    def linearize(self, params, unknowns, resids):
github WISDEM / AirfoilPreppy / airfoilprep / fused_airfoilprep.py View on Github external
import numpy as np
from openmdao.api import Component, Group, ParallelGroup
from airfoilprep import Polar, Airfoil


class AirfoilPreppyPolarExtrapolator(Component):

    def __init__(self, config, sdim, nalpha):

        super(AirfoilPreppyPolarExtrapolator, self).__init__()

        # HAWC2 output requires:
        self.blend_var = config['AirfoilPrep']['blend_var']
        self.naero_coeffs = len(self.blend_var)

        # TODO: predict number of aoa for each airfoil or use same for all afs
        '''
        self.naoa = config['AirfoilPrep']['naoa']
        '''

        self.sdim = sdim
        self.nsec = sdim[1]