本文整理汇总了Python中openmdao.api.IndepVarComp类的典型用法代码示例。如果您正苦于以下问题:Python IndepVarComp类的具体用法?Python IndepVarComp怎么用?Python IndepVarComp使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了IndepVarComp类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_const_jacobian
def test_const_jacobian(self):
model = Group()
comp = IndepVarComp()
for name, val in (('x', 1.), ('y1', np.ones(2)), ('y2', np.ones(2)),
('y3', np.ones(2)), ('z', np.ones((2, 2)))):
comp.add_output(name, val)
model.add_subsystem('input_comp', comp, promotes=['x', 'y1', 'y2', 'y3', 'z'])
problem = Problem(model=model)
problem.set_solver_print(level=0)
model.linear_solver = ScipyKrylov()
model.jacobian = COOJacobian()
model.add_subsystem('simple', SimpleCompConst(),
promotes=['x', 'y1', 'y2', 'y3', 'z', 'f', 'g'])
problem.setup(check=False)
problem.run_model()
totals = problem.compute_totals(['f', 'g'],
['x', 'y1', 'y2', 'y3', 'z'])
jacobian = {}
jacobian['f', 'x'] = [[1.]]
jacobian['f', 'z'] = np.ones((1, 4))
jacobian['f', 'y1'] = np.zeros((1, 2))
jacobian['f', 'y2'] = np.zeros((1, 2))
jacobian['f', 'y3'] = np.zeros((1, 2))
jacobian['g', 'y1'] = [[1, 0], [1, 0], [0, 1], [0, 1]]
jacobian['g', 'y2'] = [[1, 0], [0, 1], [1, 0], [0, 1]]
jacobian['g', 'y3'] = [[1, 0], [1, 0], [0, 1], [0, 1]]
jacobian['g', 'x'] = [[1], [0], [0], [1]]
jacobian['g', 'z'] = np.zeros((4, 4))
assert_rel_error(self, totals, jacobian)
示例2: setUp
def setUp(self):
self.nn = 100
self.p = Problem(model=Group())
ivc = IndepVarComp()
ivc.add_output(name='a', shape=(self.nn, 4))
ivc.add_output(name='b', shape=(self.nn, 4))
self.p.model.add_subsystem(name='ivc',
subsys=ivc,
promotes_outputs=['a', 'b'])
self.p.model.add_subsystem(name='dot_prod_comp',
subsys=DotProductComp(vec_size=self.nn, length=4))
self.p.model.connect('a', 'dot_prod_comp.a')
self.p.model.connect('b', 'dot_prod_comp.b')
self.p.setup()
self.p['a'] = np.random.rand(self.nn, 4)
self.p['b'] = np.random.rand(self.nn, 4)
self.p.run_model()
示例3: setUp
def setUp(self):
self.nn = 5
self.p = Problem(model=Group())
ivc = IndepVarComp()
ivc.add_output(name='A', shape=(self.nn, 6, 4))
ivc.add_output(name='x', shape=(self.nn, 4))
self.p.model.add_subsystem(name='ivc',
subsys=ivc,
promotes_outputs=['A', 'x'])
self.p.model.add_subsystem(name='mat_vec_product_comp',
subsys=MatrixVectorProductComp(vec_size=self.nn,
A_shape=(6, 4)))
self.p.model.connect('A', 'mat_vec_product_comp.A')
self.p.model.connect('x', 'mat_vec_product_comp.x')
self.p.setup(force_alloc_complex=True)
self.p['A'] = np.random.rand(self.nn, 6, 4)
self.p['x'] = np.random.rand(self.nn, 4)
self.p.run_model()
示例4: setup
def setup(self):
surface = self.options['surface']
mesh = surface['mesh']
nx = mesh.shape[0]
ny = mesh.shape[1]
# Add independent variables that do not belong to a specific component
indep_var_comp = IndepVarComp()
# Add structural components to the surface-specific group
self.add_subsystem('indep_vars',
indep_var_comp,
promotes=['*'])
if 'struct' in surface['type']:
self.add_subsystem('radius_comp',
RadiusComp(surface=surface),
promotes_inputs=['mesh', 't_over_c'],
promotes_outputs=['radius'])
if 'thickness_cp' in surface.keys():
n_cp = len(surface['thickness_cp'])
# Add bspline components for active bspline geometric variables.
self.add_subsystem('thickness_bsp', BsplinesComp(
in_name='thickness_cp', out_name='thickness', units='m',
num_control_points=n_cp, num_points=int(ny-1),
bspline_order=min(n_cp, 4), distribution='uniform'),
promotes_inputs=['thickness_cp'], promotes_outputs=['thickness'])
indep_var_comp.add_output('thickness_cp', val=surface['thickness_cp'], units='m')
self.add_subsystem('tube',
SectionPropertiesTube(surface=surface),
promotes_inputs=['thickness', 'radius'],
promotes_outputs=['A', 'Iy', 'Iz', 'J'])
示例5: test_speed
def test_speed(self):
from openmdao.api import Problem, Group, IndepVarComp, ExecComp
from openmdao.core.tests.test_units import SpeedComp
comp = IndepVarComp()
comp.add_output('distance', val=1., units='m')
comp.add_output('time', val=1., units='s')
prob = Problem(model=Group())
prob.model.add_subsystem('c1', comp)
prob.model.add_subsystem('c2', SpeedComp())
prob.model.add_subsystem('c3', ExecComp('f=speed',speed={'units': 'm/s'}))
prob.model.connect('c1.distance', 'c2.distance')
prob.model.connect('c1.time', 'c2.time')
prob.model.connect('c2.speed', 'c3.speed')
prob.setup()
prob.run_model()
assert_rel_error(self, prob['c1.distance'], 1.) # units: m
assert_rel_error(self, prob['c2.distance'], 1.e-3) # units: km
assert_rel_error(self, prob['c1.time'], 1.) # units: s
assert_rel_error(self, prob['c2.time'], 1./3600.) # units: h
assert_rel_error(self, prob['c2.speed'], 3.6) # units: km/h
assert_rel_error(self, prob['c3.f'], 1.0) # units: km/h
示例6: setUp
def setUp(self):
self.nn = 5
self.p = Problem(model=Group())
ivc = IndepVarComp()
ivc.add_output(name='a', shape=(self.nn, 3, 1))
ivc.add_output(name='b', shape=(self.nn, 3, 1))
self.p.model.add_subsystem(name='ivc',
subsys=ivc,
promotes_outputs=['a', 'b'])
self.p.model.add_subsystem(name='cross_prod_comp',
subsys=CrossProductComp(vec_size=self.nn))
self.p.model.connect('a', 'cross_prod_comp.a')
self.p.model.connect('b', 'cross_prod_comp.b')
self.p.setup(force_alloc_complex=True)
self.p['a'] = np.random.rand(self.nn, 3, 1)
self.p['b'] = np.random.rand(self.nn, 3, 1)
self.p['a'][:, 0, 0] = 2.0
self.p['a'][:, 1, 0] = 3.0
self.p['a'][:, 2, 0] = 4.0
self.p['b'][:, 0, 0] = 5.0
self.p['b'][:, 1, 0] = 6.0
self.p['b'][:, 2, 0] = 7.0
self.p.run_model()
示例7: test_sparse_jacobian
def test_sparse_jacobian(self):
import numpy as np
from openmdao.api import Problem, Group, IndepVarComp, ExplicitComponent
class SparsePartialComp(ExplicitComponent):
def setup(self):
self.add_input('x', shape=(4,))
self.add_output('f', shape=(2,))
self.declare_partials(of='f', wrt='x', rows=[0, 1, 1, 1], cols=[0, 1, 2, 3])
def compute_partials(self, inputs, partials):
# Corresponds to the [(0,0), (1,1), (1,2), (1,3)] entries.
partials['f', 'x'] = [1., 2., 3., 4.]
model = Group()
comp = IndepVarComp()
comp.add_output('x', np.ones(4))
model.add_subsystem('input', comp)
model.add_subsystem('example', SparsePartialComp())
model.connect('input.x', 'example.x')
problem = Problem(model=model)
problem.setup(check=False)
problem.run_model()
totals = problem.compute_totals(['example.f'], ['input.x'])
assert_rel_error(self, totals['example.f', 'input.x'], [[1., 0., 0., 0.], [0., 2., 3., 4.]])
示例8: setup
def setup(self, compname, inputs, state0):
# create instance of component type
try:
comp = eval('%s(NTIME)' % compname)
except TypeError:
try:
comp = eval('%s()' % compname)
except TypeError:
comp = eval('%s(NTIME, 300)' % compname)
# collect metadata for component inputs
prob = Problem(comp)
prob.setup()
prob.final_setup()
self.inputs_dict = {}
for name, meta in prob.model.list_inputs(units=True, out_stream=None):
self.inputs_dict[name.split('.')[-1]] = meta
# create independent vars for each input, initialized with random values
indep = IndepVarComp()
for item in inputs + state0:
shape = self.inputs_dict[item]['value'].shape
units = self.inputs_dict[item]['units']
indep.add_output(item, np.random.random(shape), units=units)
# setup problem for test
self.prob = Problem()
self.prob.model.add_subsystem('indep', indep, promotes=['*'])
self.prob.model.add_subsystem('comp', comp, promotes=['*'])
self.prob.setup()
示例9: test_raise_no_error_on_singular
def test_raise_no_error_on_singular(self):
prob = Problem()
model = prob.model
comp = IndepVarComp()
comp.add_output('dXdt:TAS', val=1.0)
comp.add_output('accel_target', val=2.0)
model.add_subsystem('des_vars', comp, promotes=['*'])
teg = model.add_subsystem('thrust_equilibrium_group', subsys=Group())
teg.add_subsystem('dynamics', ExecComp('z = 2.0*thrust'), promotes=['*'])
thrust_bal = BalanceComp()
thrust_bal.add_balance(name='thrust', val=1207.1, lhs_name='dXdt:TAS',
rhs_name='accel_target', eq_units='m/s**2', lower=-10.0, upper=10000.0)
teg.add_subsystem(name='thrust_bal', subsys=thrust_bal,
promotes_inputs=['dXdt:TAS', 'accel_target'],
promotes_outputs=['thrust'])
teg.linear_solver = DirectSolver(assemble_jac=False)
teg.nonlinear_solver = NewtonSolver()
teg.nonlinear_solver.options['solve_subsystems'] = True
teg.nonlinear_solver.options['max_sub_solves'] = 1
teg.nonlinear_solver.options['atol'] = 1e-4
prob.setup(check=False)
prob.set_solver_print(level=0)
teg.linear_solver.options['err_on_singular'] = False
prob.run_model()
示例10: test_iimplicit
def test_iimplicit(self):
# Testing that our scale/unscale contexts leave the output vector in the correct state when
# linearize is called on implicit components.
prob = Problem()
model = prob.model
inputs_comp = IndepVarComp()
inputs_comp.add_output('x1_u', val=1.0)
model.add_subsystem('p', inputs_comp)
mycomp = model.add_subsystem('comp', MyImplicitComp())
model.connect('p.x1_u', 'comp.x2_u')
model.linear_solver = DirectSolver()
model.nonlinear_solver = NewtonSolver()
model.nonlinear_solver.options['atol'] = 1e-12
model.nonlinear_solver.options['rtol'] = 1e-12
model.add_design_var('p.x1_u', lower=-11, upper=11)
model.add_constraint('p.x1_u', upper=3.3)
model.add_objective('comp.x3_u')
model.add_objective('comp.x3_s')
prob.setup()
prob.run_model()
totals = prob.check_totals(compact_print=True, out_stream=None)
for (of, wrt) in totals:
assert_rel_error(self, totals[of, wrt]['abs error'][0], 0.0, 1e-7)
示例11: setUp
def setUp(self):
self.nn = 5
self.p = Problem(model=Group())
ivc = IndepVarComp()
ivc.add_output(name='a', shape=(self.nn, 3))
ivc.add_output(name='b', shape=(self.nn, 3))
self.p.model.add_subsystem(name='ivc',
subsys=ivc,
promotes_outputs=['a', 'b'])
adder=self.p.model.add_subsystem(name='add_subtract_comp',
subsys=AddSubtractComp())
adder.add_equation('adder_output',['input_a','input_b'],vec_size=self.nn,length=3)
self.p.model.connect('a', 'add_subtract_comp.input_a')
self.p.model.connect('b', 'add_subtract_comp.input_b')
self.p.setup()
self.p['a'] = np.random.rand(self.nn, 3)
self.p['b'] = np.random.rand(self.nn, 3)
self.p.run_model()
示例12: setUp
def setUp(self):
self.nn = 10
self.p = Problem(model=Group())
ivc = IndepVarComp()
ivc.add_output(name='a', shape=(self.nn,))
ivc.add_output(name='b', shape=(self.nn,))
self.p.model.add_subsystem(name='ivc',
subsys=ivc,
promotes_outputs=['a', 'b'])
demux_comp = self.p.model.add_subsystem(name='demux_comp',
subsys=DemuxComp(vec_size=self.nn))
demux_comp.add_var('a', shape=(self.nn,))
demux_comp.add_var('b', shape=(self.nn,))
self.p.model.connect('a', 'demux_comp.a')
self.p.model.connect('b', 'demux_comp.b')
self.p.setup(force_alloc_complex=True)
self.p['a'] = np.random.rand(self.nn)
self.p['b'] = np.random.rand(self.nn)
self.p.run_model()
示例13: test_structural_weight_loads
def test_structural_weight_loads(self):
surface = get_default_surfaces()[0]
comp = StructureWeightLoads(surface=surface)
group = Group()
indep_var_comp = IndepVarComp()
ny = surface['mesh'].shape[1]
#carefully chosen "random" values that give non-uniform derivatives outputs that are good for testing
nodesval = np.array([[1., 2., 4.],
[20., 22., 7.],
[8., 17., 14.],
[13., 14., 16.]],dtype=complex)
element_weights_val = np.arange(ny-1)+1
indep_var_comp.add_output('nodes', val=nodesval,units='m')
indep_var_comp.add_output('element_weights', val=element_weights_val,units='N')
group.add_subsystem('indep_var_comp', indep_var_comp, promotes=['*'])
group.add_subsystem('load', comp, promotes=['*'])
p = run_test(self, group, complex_flag=True, compact_print=True)
示例14: test
def test(self):
# Create a dictionary to store options about the surface
mesh_dict = {'num_y' : 7,
'wing_type' : 'CRM',
'symmetry' : True,
'num_twist_cp' : 5}
mesh, twist_cp = generate_mesh(mesh_dict)
surf_dict = {
# Wing definition
'name' : 'wing', # name of the surface
'symmetry' : True, # if true, model one half of wing
# reflected across the plane y = 0
'fem_model_type' : 'tube',
'mesh' : mesh,
'radius_cp' : np.ones((5)) * 0.5,
# Structural values are based on aluminum 7075
'E' : 70.e9, # [Pa] Young's modulus of the spar
'G' : 30.e9, # [Pa] shear modulus of the spar
'yield' : 500.e6 / 2.5, # [Pa] yield stress divided by 2.5 for limiting case
'mrho' : 3.e3, # [kg/m^3] material density
'fem_origin' : 0.35, # normalized chordwise location of the spar
't_over_c_cp' : np.array([0.15]), # maximum airfoil thickness
'thickness_cp' : np.ones((3)) * .1,
'wing_weight_ratio' : 2.,
'struct_weight_relief' : False, # True to add the weight of the structure to the loads on the structure
'distributed_fuel_weight' : False,
'exact_failure_constraint' : False,
}
# Create the problem and assign the model group
prob = Problem()
ny = surf_dict['mesh'].shape[1]
indep_var_comp = IndepVarComp()
indep_var_comp.add_output('loads', val=np.ones((ny, 6)) * 2e5, 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)
# Set up the problem
prob.setup()
prob.run_model()
assert_rel_error(self, prob['wing.structural_mass'][0], 117819.798089, 1e-4)
示例15: setup
def setup(self):
E = self.metadata['E']
L = self.metadata['L']
b = self.metadata['b']
volume = self.metadata['volume']
num_elements = self.metadata['num_elements']
num_nodes = num_elements + 1
force_vector = np.zeros(2 * num_nodes)
force_vector[-2] = -1.
inputs_comp = IndepVarComp()
inputs_comp.add_output('h', shape=num_elements)
self.add_subsystem('inputs_comp', inputs_comp)
I_comp = MomentOfInertiaComp(num_elements=num_elements, b=b)
self.add_subsystem('I_comp', I_comp)
comp = LocalStiffnessMatrixComp(num_elements=num_elements, E=E, L=L)
self.add_subsystem('local_stiffness_matrix_comp', comp)
comp = GlobalStiffnessMatrixComp(num_elements=num_elements)
self.add_subsystem('global_stiffness_matrix_comp', comp)
comp = StatesComp(num_elements=num_elements, force_vector=force_vector)
self.add_subsystem('states_comp', comp)
comp = DisplacementsComp(num_elements=num_elements)
self.add_subsystem('displacements_comp', comp)
comp = ComplianceComp(num_elements=num_elements, force_vector=force_vector)
self.add_subsystem('compliance_comp', comp)
comp = VolumeComp(num_elements=num_elements, b=b, L=L)
self.add_subsystem('volume_comp', comp)
self.connect('inputs_comp.h', 'I_comp.h')
self.connect('I_comp.I', 'local_stiffness_matrix_comp.I')
self.connect(
'local_stiffness_matrix_comp.K_local',
'global_stiffness_matrix_comp.K_local')
self.connect(
'global_stiffness_matrix_comp.K',
'states_comp.K')
self.connect(
'states_comp.d',
'displacements_comp.d')
self.connect(
'displacements_comp.displacements',
'compliance_comp.displacements')
self.connect(
'inputs_comp.h',
'volume_comp.h')
self.add_design_var('inputs_comp.h', lower=1e-2, upper=10.)
self.add_objective('compliance_comp.compliance')
self.add_constraint('volume_comp.volume', equals=volume)