How to use openmdao - 10 common examples

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 / test_examples / test_circuit_analysis.py View on Github external
def test_circuit_advanced_newton(self):
        from openmdao.api import ArmijoGoldsteinLS, Problem, IndepVarComp

        from openmdao.test_suite.scripts.circuit_analysis import Circuit

        p = Problem()
        model = p.model

        model.add_subsystem('ground', IndepVarComp('V', 0., units='V'))
        model.add_subsystem('source', IndepVarComp('I', 0.1, units='A'))
        model.add_subsystem('circuit', Circuit())

        model.connect('source.I', 'circuit.I_in')
        model.connect('ground.V', 'circuit.Vg')

        p.setup()

        # you can change the NewtonSolver settings in circuit after setup is called
        newton = p.model.circuit.nonlinear_solver
        newton.options['iprint'] = 2
        newton.options['maxiter'] = 10
        newton.options['solve_subsystems'] = True
        newton.linesearch = ArmijoGoldsteinLS()
        newton.linesearch.options['maxiter'] = 10
        newton.linesearch.options['iprint'] = 2
github WISDEM / WISDEM / test / rotorse / test_rotor_structure_gradients.py View on Github external
def test_BladeCurvature():

    data = {}
    data['r'] = np.array([1.5375, 1.84056613137, 1.93905987557, 2.03755361977, 2.14220322299, 2.24069696719, 2.33919071139, 2.90419974, 3.04095863882, 3.13945238302, 5.637500205, 7.04226699698, 8.370800055, 11.8494282928, 13.8375, 14.7182548841, 15.887499795, 18.5537233505, 19.9875, 22.0564071286, 24.087500205, 26.16236509, 28.187499795, 32.2875, 33.5678634821, 36.387500205, 38.5725768593, 40.487499795, 40.6967540173, 40.7964789782, 40.8975, 42.6919644014, 44.5875, 52.787499795, 56.204199945, 58.937499795, 61.67080026, 63.0375])
    data['precurve'] = np.array([0.0, 0.043324361025, 0.0573893371698, 0.0714469497372, 0.0863751069858, 0.100417566593, 0.114452695996, 0.194824077331, 0.214241777459, 0.228217752953, 0.580295739194, 0.776308800624, 0.960411633829, 1.4368012564, 1.7055214864, 1.823777005, 1.98003324362, 2.32762426752, 2.50856911855, 2.76432512112, 3.0113656418, 3.26199245912, 3.50723775206, 4.0150233695, 4.17901272929, 4.55356019347, 4.85962948702, 5.14086873143, 5.17214747287, 5.18708601127, 5.20223968442, 5.47491847385, 5.77007321175, 7.12818875977, 7.7314427824, 8.22913789456, 8.73985955154, 9.0])
    data['presweep'] = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
    data['precone'] = 2.5
    npts = np.size(data['r'])

    prob = Problem()
    prob.root = Group()
    prob.root.add('comp', BladeCurvature(npts), promotes=['*'])
    prob = init_IndepVar_add(prob, data)
    prob.setup(check=False)
    prob = init_IndepVar_set(prob, data)

    check_gradient_unit_test(prob, tol=5e-5)
github WISDEM / WISDEM / test / rotorse / test_rotor_aeropower_gradients.py View on Github external
data['rated_Omega_in'] = 12.
    data['rated_pitch_in'] = 0.0
    data['rated_T_in'] = 714206.5321080858
    data['rated_Q_in'] = 3978873.5772973835
    data['hub_diameter_in'] = 3.075
    data['diameter_in'] = 125.95500453593273
    data['max_chord_in'] = 3.0459289459935825
    data['V_extreme_in'] = 70.0
    data['T_extreme_in'] = 0.0
    data['Q_extreme_in'] = 0.0
    data['Rtip_in'] = 63.0375
    data['precurveTip_in'] = 0.0
    data['precsweepTip_in'] = 0.0

    prob = Problem()
    prob.root = Group()
    prob.root.add('comp', OutputsAero(len(data['P_in'])), promotes=['*'])
    prob = init_IndepVar_add(prob, data)
    prob.root.comp.deriv_options['check_step_calc'] = 'relative' 
    prob.setup(check=False)
    prob = init_IndepVar_set(prob, data)

    check_gradient_unit_test(prob)
github OpenMDAO / OpenMDAO-Framework / contrib / testmpi / test_distribcomp.py View on Github external
start, end, sizes, offsets = evenly_distrib_idxs(comm, self.arr_size)

        self.invec = np.ones(sizes[rank], dtype=float)
        self.outvec = np.ones(sizes[rank], dtype=float)

        print self.name,".outvec",self.outvec

        return {
            'invec': make_idx_array(start, end),
            'outvec': make_idx_array(start, end)
        }

    def get_req_cpus(self):
        return 2

class DistribNoncontiguousComp(Component):
    """Uses 2 procs and takes non-contiguous input var slices and has output
    var slices as well
    """
    def __init__(self, arr_size=11):
        super(DistribNoncontiguousComp, self).__init__()
        self.arr_size = arr_size
        self.add_trait('invec', Array(np.ones(arr_size, float), iotype='in'))
        self.add_trait('outvec', Array(np.ones(arr_size, float), iotype='out'))

    def execute(self):
        if self.mpi.comm == MPI.COMM_NULL:
            return

        for i,val in enumerate(self.invec):
            self.outvec[i] = 2*val
github OpenMDAO / OpenMDAO-Framework / contrib / testmpi / test_distribcomp.py View on Github external
class InOutArrayComp(Component):
    delay = Float(0.01, iotype='in')

    def __init__(self, arr_size=10):
        super(InOutArrayComp, self).__init__()
        self.mpi.requested_cpus = 2

        self.add_trait('invec', Array(np.ones(arr_size, float), iotype='in'))
        self.add_trait('outvec', Array(np.ones(arr_size, float), iotype='out'))

    def execute(self):
        time.sleep(self.delay)
        self.outvec = self.invec * 2.

class DistribCompSimple(Component):
    """Uses 2 procs but takes full input vars"""
    def __init__(self, arr_size=10):
        super(DistribCompSimple, self).__init__()
        self.mpi.requested_cpus = 2

        self.add_trait('invec', Array(np.ones(arr_size, float), iotype='in'))
        self.add_trait('outvec', Array(np.ones(arr_size, float), iotype='out'))

    def execute(self):
        if self.mpi.comm == MPI.COMM_NULL:
            return
        if self.mpi.comm != MPI.COMM_NULL:
            if self.mpi.comm.rank == 0:
                self.outvec = self.invec * 0.25
            elif self.mpi.comm.rank == 1:
                self.outvec = self.invec * 0.5
github OpenMDAO / OpenMDAO / openmdao / test_suite / scripts / circuit_analysis.py View on Github external
from openmdao.api import ArmijoGoldsteinLS, Problem, IndepVarComp, BalanceComp, ExecComp
    from openmdao.api import NewtonSolver, DirectSolver, NonlinearRunOnce, LinearRunOnce

    p = Problem()
    model = p.model

    model.add_subsystem('ground', IndepVarComp('V', 0., units='V'))

    # replacing the fixed current source with a BalanceComp to represent a fixed Voltage source
    # model.add_subsystem('source', IndepVarComp('I', 0.1, units='A'))
    model.add_subsystem('batt', IndepVarComp('V', 1.5, units='V'))
    bal = model.add_subsystem('batt_balance', BalanceComp())
    bal.add_balance('I', units='A', eq_units='V')

    model.add_subsystem('circuit', Circuit())
    model.add_subsystem('batt_deltaV', ExecComp('dV = V1 - V2', V1={'units':'V'}, V2={'units':'V'}, dV={'units':'V'}))

    # current into the circuit is now the output state from the batt_balance comp
    model.connect('batt_balance.I', 'circuit.I_in')
    model.connect('ground.V', ['circuit.Vg','batt_deltaV.V2'])
    model.connect('circuit.n1.V', 'batt_deltaV.V1')

    # set the lhs and rhs for the battery residual
    model.connect('batt.V', 'batt_balance.rhs:I')
    model.connect('batt_deltaV.dV', 'batt_balance.lhs:I')

    p.setup()

    ###################
    # Solver Setup
    ###################
github OpenMDAO / OpenMDAO / openmdao / test_suite / scripts / circle_coloring_needs_args.py View on Github external
import os
import sys

COLOR_TYPE = os.environ.get('COLOR_TYPE', 'auto')

from openmdao.api import ScipyOptimizeDriver
from openmdao.core.tests.test_coloring import run_opt

if __name__ == '__main__':

    if len(sys.argv) != 3 or sys.argv[1] != '-f':
        print("usage: python circle_coloring_needs_args.py -f bar")
        sys.exit(2)

    p_color = run_opt(ScipyOptimizeDriver, COLOR_TYPE, optimizer='SLSQP', disp=False,
                      dynamic_total_coloring=True, partial_coloring=False)
github mdolab / OpenAeroStruct / tests / test_v1_struct_opt.py View on Github external
'fem_origin' : 0.35,    # normalized chordwise location of the spar
                    't_over_c' : 0.15,      # maximum airfoil thickness
                    'thickness_cp' : np.ones((3)) * .0075,
                    'wing_weight_ratio' : 1.,

                    'exact_failure_constraint' : False,
                    }

        # Create the problem and assign the model group
        prob = Problem()

        ny = surf_dict['num_y']

        loads = np.zeros((ny, 6))
        loads[0, 2] = 1e4
        indep_var_comp = IndepVarComp()
        indep_var_comp.add_output('loads', val=loads, units='N')
        indep_var_comp.add_output('load_factor', val=1.)

        struct_group = SpatialBeamAlone(surface=surf_dict)

        # Add indep_vars to the structural group
        struct_group.add_subsystem('indep_vars',
             indep_var_comp,
             promotes=['*'])

        prob.model.add_subsystem(surf_dict['name'], struct_group)

        try:
            from openmdao.api import pyOptSparseDriver
            prob.driver = pyOptSparseDriver()
            prob.driver.options['optimizer'] = "SNOPT"
github OpenMDAO / OpenMDAO1 / mpitest / test_par_doe.py View on Github external
def test_doe_fail_analysis_error(self):
        problem = Problem(impl=impl)
        root = problem.root = Group()
        root.add('indep_var', IndepVarComp('x', val=1.0))
        root.add('const', IndepVarComp('c', val=2.0))

        if MPI:
            fail_rank = 1  # raise exception from this rank
            npardoe = self.N_PROCS
        else:
            fail_rank = 0
            npardoe = 1

        root.add('mult', ExecComp4Test("y=c*x", fail_rank=fail_rank,
                  fails=[3,4]))

        root.connect('indep_var.x', 'mult.x')
        root.connect('const.c', 'mult.c')

        num_levels = 25
        problem.driver = FullFactorialDriver(num_levels=num_levels,
github OpenMDAO / OpenMDAO / openmdao / test_suite / scripts / multipoint_beam_opt.py View on Github external
except ImportError:
    print("PETSc is not installed. Skipping beam optimization.")
    PETScVector = None


if __name__ == '__main__' and PETScVector is not None:
    E = 1.
    L = 1.
    b = 0.1
    volume = 0.01

    num_cp = 5
    num_elements = 50
    num_load_cases = 2

    prob = om.Problem(model=MultipointBeamGroup(E=E, L=L, b=b, volume=volume,
                                                num_elements=num_elements, num_cp=num_cp,
                                                num_load_cases=num_load_cases))

    prob.driver = om.ScipyOptimizeDriver()
    prob.driver.options['optimizer'] = 'SLSQP'
    prob.driver.options['tol'] = 1e-9
    prob.driver.options['disp'] = True

    prob.setup()

    prob.run_driver()

    h = prob['interp.h']
    expected = np.array([ 0.14122705,  0.14130706,  0.14154096,  0.1419107,   0.14238706,  0.14293095,
                          0.14349514,  0.14402636,  0.1444677,   0.14476123,  0.14485062,  0.14468388,
                          0.14421589,  0.1434107,   0.14224356,  0.14070252,  0.13878952,  0.13652104,