Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_reentry(self):
import openmdao.api as om
from openmdao.utils.assert_utils import assert_near_equal
import dymos as dm
from dymos.examples.shuttle_reentry.shuttle_ode import ShuttleODE
from dymos.examples.plotting import plot_results
# Instantiate the problem, add the driver, and allow it to use coloring
p = om.Problem(model=om.Group())
p.driver = om.pyOptSparseDriver()
p.driver.declare_coloring()
p.driver.options['optimizer'] = 'SLSQP'
# Instantiate the trajectory and add a phase to it
traj = p.model.add_subsystem('traj', dm.Trajectory())
phase0 = traj.add_phase('phase0',
dm.Phase(ode_class=ShuttleODE,
transcription=dm.Radau(num_segments=15, order=3)))
phase0.set_time_options(fix_initial=True, units='s', duration_ref=200)
phase0.add_state('h', fix_initial=True, fix_final=True, units='ft', rate_source='hdot',
targets=['h'], lower=0, ref0=75000, ref=300000, defect_ref=1000)
phase0.add_state('gamma', fix_initial=True, fix_final=True, units='rad',
rate_source='gammadot', targets=['gamma'],
lower=-89. * np.pi / 180, upper=89. * np.pi / 180)
phase0.add_state('phi', fix_initial=True, fix_final=False, units='rad',
def test_betz(self):
from distutils.version import LooseVersion
import scipy
import openmdao.api as om
class ActuatorDisc(om.ExplicitComponent):
"""Simple wind turbine model based on actuator disc theory"""
def setup(self):
# Inputs
self.add_input('a', 0.5, desc="Induced Velocity Factor")
self.add_input('Area', 10.0, units="m**2", desc="Rotor disc area")
self.add_input('rho', 1.225, units="kg/m**3", desc="air density")
self.add_input('Vu', 10.0, units="m/s", desc="Freestream air velocity, upstream of rotor")
# Outputs
self.add_output('Vr', 0.0, units="m/s",
desc="Air velocity at rotor exit plane")
self.add_output('Vd', 0.0, units="m/s",
desc="Slipstream air velocity, downstream of rotor")
self.add_output('Ct', 0.0, desc="Thrust Coefficient")
E = 1.
L = 1.
b = 0.1
volume = 0.01
num_cp = 5
num_elements = 50
num_load_cases = 2
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 = om.Problem(model=model)
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()
assert_rel_error(self, prob['interp.h'][0],
[ 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,
0.13392808, 0.13105565, 0.1279617, 0.12471547, 0.1213954, 0.11808665,
0.11487828, 0.11185599, 0.10900669, 0.10621949, 0.10338308, 0.10039485,
0.09716531, 0.09362202, 0.08971275, 0.08540785, 0.08070168, 0.07561313,
0.0701851, 0.06448311, 0.05859294, 0.05261756, 0.0466733, 0.04088557,
def setup(self):
n_ins = self.options['n_ins']
for i in range(1,n_ins+1):
self.add_input('W_{}'.format(i), units='lbm/s')
self.add_output('W_cool', units='lbm/s')
self.declare_partials('W_cool', '*', val=1) #constant values
def compute(self, inputs, outputs):
W_cool = 0
for i in range(1, self.options['n_ins']+1):
W_cool += inputs['W_{}'.format(i)]
outputs['W_cool'] = W_cool
class CoolingCalcs(om.ExplicitComponent):
def initialize(self):
self.options.declare('n_stages', types=int, desc="number of stages in the turbine")
self.options.declare('i_row', types=int, desc="row number")
self.options.declare('T_safety', types=float, default=150., desc='safety factor applied') # units=degR
self.options.declare('T_metal', types=float, default=2460., desc='safety factor applied') # units=degR
def setup(self):
self.add_input('turb_pwr', val=1, units='Btu/s', desc='power produced by the whole turbine')
self.add_input('Pt_in', val=1, units='psi', desc='turbine inlet pressure') # note: NOT the pressure at the row. Across the whole turbine!
self.add_input('Pt_out', val=1, units='psi', desc='turbine exit pressure')
self.add_input('x_factor', val=1, desc='technology factor. 1 is current technology, lower is more advanced technology')
self.add_input('W_primary', val=1, units='lbm/s', desc="flow into the row")
self.add_input('Tt_primary', val=1, units='degR', desc='total temperature of primary flow coming into the row')
self.add_input('Tt_cool', val=1, units='degR', desc='total temperature of cooling flow coming into the row')
noz_names = ['nozz']
noz_full_names = [f'{pt}.{n}' for n in noz_names]
pyc.print_nozzle(prob, noz_full_names, file=file)
shaft_names = ['shaft']
shaft_full_names = [f'{pt}.{s}' for s in shaft_names]
pyc.print_shaft(prob, shaft_full_names, file=file)
if __name__ == "__main__":
import time
from openmdao.api import Problem, IndepVarComp
from openmdao.utils.units import convert_units as cu
prob = om.Problem()
des_vars = prob.model.add_subsystem('des_vars', IndepVarComp(), promotes=["*"])
# Design point inputs
des_vars.add_output('alt', 0.0, units='ft'),
des_vars.add_output('MN', 0.000001),
des_vars.add_output('T4max', 2370.0, units='degR'),
des_vars.add_output('Fn_des', 11800.0, units='lbf'),
des_vars.add_output('comp:PRdes', 13.5),
des_vars.add_output('comp:effDes', 0.83),
des_vars.add_output('burn:dPqP', 0.03),
des_vars.add_output('turb:effDes', 0.86),
des_vars.add_output('nozz:Cv', 0.99),
des_vars.add_output('shaft:Nmech', 8070.0, units='rpm'),
des_vars.add_output('inlet:MN_out', 0.60),
des_vars.add_output('comp:MN_out', 0.20),
lhs_name='P_pack',
units='A', eq_units='W', lower=0.0, upper=50.))
self.add_subsystem('battery', Battery(num_nodes=num_nodes, n_parallel=num_battery),
promotes_inputs=['SOC'],
promotes_outputs=['dXdt:SOC'])
self.add_subsystem('motors', Motors(num_nodes=num_nodes, n_parallel=num_motor))
self.connect('battery.P_pack', 'pwr_balance.P_pack')
self.connect('motors.power_in_motor', 'pwr_balance.pwr_out_batt')
self.connect('pwr_balance.I_Li', 'battery.I_Li')
self.connect('battery.I_pack', 'motors.current_in_motor')
self.nonlinear_solver = om.NewtonSolver(solve_subsystems=False, maxiter=20)
self.linear_solver = om.DirectSolver()
J['trq_in','eff'] = -inputs['trq_base'] * inputs['N_out'] / inputs['N_in']
J['trq_in','N_in'] = inputs['trq_base'] * inputs['eff'] * inputs['N_out'] / inputs['N_in']**2
J['trq_in','N_out'] = -inputs['trq_base'] * inputs['eff'] / inputs['N_in']
else:
J['trq_base','N_in'] = -inputs['gear_ratio']
J['trq_base','gear_ratio'] = -inputs['N_in']
J['trq_in','trq_base'] = -inputs['eff']*inputs['gear_ratio']
J['trq_in','eff'] = -outputs['trq_base']*inputs['gear_ratio']
J['trq_in','gear_ratio'] = -outputs['trq_base']*inputs['eff']
if __name__ == "__main__":
p = om.Problem()
inputs = p.model.add_subsystem('inputs',om.IndepVarComp(), promotes=['*'])
inputs.add_output('eff', 1.0)
inputs.add_output('N_in', 6772.0, units='rpm')
inputs.add_output('N_out', 2184.5, units='rpm')
inputs.add_output('trq_base', 23711.1, units='ft*lbf')
# inputs.add_output('gear_ratio', 0.322578263438, units=None)
p.model.add_subsystem('gearbox', Gearbox(design=True), promotes=['*'])
p.setup()
# p['trq_base'] = 23711.1
p.run_model()
p.check_partials(compact_print=True)
import numpy as np
import openmdao.api as om
class TrueAirspeedComp(om.ExplicitComponent):
""" Compute Mach number based on true airspeed and the local speed of sound. """
def initialize(self):
self.options.declare('num_nodes', types=int)
def setup(self):
nn = self.options['num_nodes']
self.add_input('sos', val=np.zeros(nn), desc='atmospheric speed of sound', units='m/s')
self.add_input('mach', val=np.zeros(nn), desc='Mach number', units=None)
self.add_output('TAS', val=np.zeros(nn), desc='true airspeed', units='m/s')
# Setup partials
ar = np.arange(self.options['num_nodes'])
self.declare_partials(of='TAS', wrt='mach', rows=ar, cols=ar)
self.declare_partials(of='TAS', wrt='sos', rows=ar, cols=ar)
def vanderpol(transcription='gauss-lobatto', num_segments=8, transcription_order=3,
compressed=True, optimizer='SLSQP', use_pyoptsparse=False, delay=None):
"""Dymos problem definition for optimal control of a Van der Pol oscillator"""
# define the OpenMDAO problem
p = om.Problem(model=om.Group())
if not use_pyoptsparse:
p.driver = om.ScipyOptimizeDriver()
else:
p.driver = om.pyOptSparseDriver()
p.driver.options['optimizer'] = optimizer
if use_pyoptsparse and optimizer == 'SNOPT':
p.driver.opt_settings['iSumm'] = 6 # show detailed SNOPT output
p.driver.declare_coloring()
# define a Trajectory object and add to model
traj = dm.Trajectory()
p.model.add_subsystem('traj', subsys=traj)
# define a Transcription
if transcription == 'gauss-lobatto':
t = dm.GaussLobatto(num_segments=num_segments,
order=transcription_order,
compressed=compressed)
elif transcription == 'radau-ps':
t = dm.Radau(num_segments=num_segments,
import openmdao.api as om
from .dynamic_pressure_comp import DynamicPressureComp
from .lift_drag_force_comp import LiftDragForceComp
from .cd0_comp import CD0Comp
from .kappa_comp import KappaComp
from .cla_comp import CLaComp
from .cl_comp import CLComp
from .cd_comp import CDComp
from .mach_comp import MachComp
class AeroGroup(om.Group):
"""
The purpose of the AeroGroup is to compute the aerodynamic forces on the
aircraft in the body frame.
Parameters
----------
v : float
air-relative velocity (m/s)
sos : float
local speed of sound (m/s)
rho : float
atmospheric density (kg/m**3)
alpha : float
angle of attack (rad)
S : float
aerodynamic reference area (m**2)