def test_feature_numpyvec_setup(self): from openmdao.api import Problem, Group, IndepVarComp from openmdao.test_suite.components.paraboloid import Paraboloid prob = Problem() model = prob.model = Group() model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) model.add_subsystem('p2', IndepVarComp('y', 0.0), promotes=['y']) model.add_subsystem('comp', Paraboloid(), promotes=['x', 'y', 'f_xy']) prob.setup() prob['x'] = 2. prob['y'] = 10. prob.run_model() assert_rel_error(self, prob['f_xy'], 214.0, 1e-6) prob['x'] = 0. prob['y'] = 0. prob.run_model() assert_rel_error(self, prob['f_xy'], 22.0, 1e-6) # skip the setup error checking prob.setup(check=False) prob['x'] = 4 prob['y'] = 8. prob.run_model() assert_rel_error(self, prob['f_xy'], 174.0, 1e-6)
def test_feature_boundscheck_wall(self): top = Problem() top.model = Group() top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') top.model.nonlinear_solver = NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 10 top.model.linear_solver = ScipyIterativeSolver() ls = top.model.nonlinear_solver.linesearch = BoundsEnforceLS() ls.options['bound_enforcement'] = 'wall' top.setup(check=False) # Test upper bounds: should go to the upper bound and stall top['px.x'] = 0.5 top['comp.y'] = 0. top['comp.z'] = 2.4 top.run_model() assert_rel_error(self, top['comp.z'][0], [2.6], 1e-8) assert_rel_error(self, top['comp.z'][1], [2.5], 1e-8) assert_rel_error(self, top['comp.z'][2], [2.65], 1e-8)
def test_relevancy_for_newton(self): class TestImplCompSimple(ImplicitComponent): def setup(self): self.add_input('a', val=1.) self.add_output('x', val=0.) self.declare_partials(of='*', wrt='*') def apply_nonlinear(self, inputs, outputs, residuals): residuals['x'] = np.exp(outputs['x']) - \ inputs['a']**2 * outputs['x']**2 def linearize(self, inputs, outputs, jacobian): jacobian['x', 'x'] = np.exp(outputs['x']) - \ 2 * inputs['a']**2 * outputs['x'] jacobian['x', 'a'] = -2 * inputs['a'] * outputs['x']**2 prob = Problem() prob.model = model = Group() model.add_subsystem('p1', IndepVarComp('x', 3.0)) model.add_subsystem('icomp', TestImplCompSimple()) model.add_subsystem('ecomp', ExecComp('y = x*p', p=1.0)) model.connect('p1.x', 'ecomp.x') model.connect('icomp.x', 'ecomp.p') model.add_design_var('p1.x', 3.0) model.add_objective('ecomp.y') model.nonlinear_solver = NewtonSolver() model.linear_solver = ScipyIterativeSolver() prob.setup(check=False) prob.run_model() J = prob.compute_totals() assert_rel_error(self, J['ecomp.y', 'p1.x'][0][0], -0.703467422498, 1e-6)
def test_circuit_plain_newton_many_iter(self): from openmdao.api import Problem, IndepVarComp from openmdao.test_suite.test_examples.test_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['maxiter'] = 50 # set some initial guesses p['circuit.n1.V'] = 10. p['circuit.n2.V'] = 1e-3 p.run_model() assert_rel_error(self, p['circuit.n1.V'], 9.98744708, 1e-5) assert_rel_error(self, p['circuit.n2.V'], 8.73215484, 1e-5) #'Sanity check: shoudl sum to .1 Amps assert_rel_error(self, p['circuit.R1.I'] + p['circuit.D1.I'], 0.09987447, 1e-6)
def test_set_checks_shape(self): model = Group() indep = model.add_subsystem('indep', IndepVarComp()) indep.add_output('num') indep.add_output('arr', shape=(10, 1)) prob = Problem(model) prob.setup() msg = "Incompatible shape for '.*': Expected (.*) but got (.*)" # check valid scalar value new_val = -10. prob['indep.num'] = new_val assert_rel_error(self, prob['indep.num'], new_val, 1e-10) # check bad scalar value bad_val = -10 * np.ones((10)) prob['indep.num'] = bad_val with assertRaisesRegex(self, ValueError, msg): prob.final_setup() prob._initial_condition_cache = {} # check assign scalar to array arr_val = new_val * np.ones((10, 1)) prob['indep.arr'] = new_val prob.final_setup() assert_rel_error(self, prob['indep.arr'], arr_val, 1e-10) # check valid array value new_val = -10 * np.ones((10, 1)) prob['indep.arr'] = new_val assert_rel_error(self, prob['indep.arr'], new_val, 1e-10) # check bad array value bad_val = -10 * np.ones((10)) with assertRaisesRegex(self, ValueError, msg): prob['indep.arr'] = bad_val # check valid list value new_val = new_val.tolist() prob['indep.arr'] = new_val assert_rel_error(self, prob['indep.arr'], new_val, 1e-10) # check bad list value bad_val = bad_val.tolist() with assertRaisesRegex(self, ValueError, msg): prob['indep.arr'] = bad_val
def test_nolinesearch(self): top = self.top # Run without a line search at x=2.0 top['px.x'] = 2.0 top.run_model() assert_rel_error(self, top['comp.y'], 4.666666, 1e-4) assert_rel_error(self, top['comp.z'], 1.333333, 1e-4) # Run without a line search at x=0.5 top['px.x'] = 0.5 top.run_model() assert_rel_error(self, top['comp.y'], 5.833333, 1e-4) assert_rel_error(self, top['comp.z'], 2.666666, 1e-4)
def test_feature_print_bound_enforce(self): top = Problem() top.model = Group() top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1)))) top.model.add_subsystem('comp', ImplCompTwoStatesArrays()) top.model.connect('px.x', 'comp.x') newt = top.model.nonlinear_solver = NewtonSolver() top.model.nonlinear_solver.options['maxiter'] = 2 top.model.linear_solver = ScipyIterativeSolver() ls = newt.linesearch = BoundsEnforceLS(bound_enforcement='vector') ls.options['print_bound_enforce'] = True top.set_solver_print(level=2) top.setup() # Test lower bounds: should go to the lower bound and stall top['px.x'] = 2.0 top['comp.y'] = 0. top['comp.z'] = 1.6 top.run_model() assert_rel_error(self, top['comp.z'][0], [1.5], 1e-8) assert_rel_error(self, top['comp.z'][1], [1.5], 1e-8) assert_rel_error(self, top['comp.z'][2], [1.5], 1e-8)
def test_converge_diverge_groups(self): # Test derivatives for converge-diverge-groups topology. prob = Problem() prob.model = ConvergeDivergeGroups() prob.model.linear_solver = LinearRunOnce() prob.set_solver_print(level=0) g1 = prob.model.get_subsystem('g1') g2 = g1.get_subsystem('g2') g3 = prob.model.get_subsystem('g3') g1.linear_solver = LinearRunOnce() g2.linear_solver = LinearRunOnce() g3.linear_solver = LinearRunOnce() prob.setup(check=False, mode='fwd') prob.run_model() wrt = ['iv.x'] of = ['c7.y1'] # Make sure value is fine. assert_rel_error(self, prob['c7.y1'], -102.7, 1e-6) J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict') assert_rel_error(self, J['c7.y1', 'iv.x'][0][0], -40.75, 1e-6) prob.setup(check=False, mode='rev') prob.run_model() J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict') assert_rel_error(self, J['c7.y1', 'iv.x'][0][0], -40.75, 1e-6)
def test_basic_cs(self): class CompOne(ExplicitComponent): def setup(self): self.add_input('x', val=0.0) self.add_output('y', val=np.zeros(25)) self._exec_count = 0 def compute(self, inputs, outputs): x = inputs['x'] outputs['y'] = np.arange(25) * x self._exec_count += 1 class CompTwo(ExplicitComponent): def setup(self): self.add_input('y', val=np.zeros(25)) self.add_output('z', val=0.0) self._exec_count = 0 def compute(self, inputs, outputs): y = inputs['y'] outputs['z'] = np.sum(y) self._exec_count += 1 prob = Problem() model = prob.model = Group() model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) model.add_subsystem('comp1', CompOne(), promotes=['x', 'y']) comp2 = model.add_subsystem('comp2', CompTwo(), promotes=['y', 'z']) model.linear_solver = ScipyIterativeSolver() model.approx_totals(method='cs') prob.setup() prob.run_model() of = ['z'] wrt = ['x'] derivs = prob.compute_totals(of=of, wrt=wrt) assert_rel_error(self, derivs['z', 'x'], [[300.0]], 1e-6)
def test_tldr(self): from openmdao.api import Problem, ScipyOptimizer, ExecComp, IndepVarComp # build the model prob = Problem() indeps = prob.model.add_subsystem('indeps', IndepVarComp()) indeps.add_output('x', 3.0) indeps.add_output('y', -4.0) prob.model.add_subsystem('paraboloid', ExecComp('f = (x-3)**2 + x*y + (y+4)**2 - 3')) prob.model.connect('indeps.x', 'paraboloid.x') prob.model.connect('indeps.y', 'paraboloid.y') # setup the optimization prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.model.add_design_var('indeps.x', lower=-50, upper=50) prob.model.add_design_var('indeps.y', lower=-50, upper=50) prob.model.add_objective('paraboloid.f') prob.setup() prob.run_driver() # minimum value assert_rel_error(self, prob['paraboloid.f'], -27.33333, 1e-6) # location of the minimum assert_rel_error(self, prob['indeps.x'], 6.6667, 1e-4) assert_rel_error(self, prob['indeps.y'], -7.33333, 1e-4)
def test_connect_units_with_nounits(self): prob = Problem(Group()) prob.model.add_subsystem('px1', IndepVarComp('x1', 100.0)) prob.model.add_subsystem('src', ExecComp('x2 = 2 * x1')) prob.model.add_subsystem('tgt', ExecComp('y = 3 * x', x={'units': 'degC'})) prob.model.connect('px1.x1', 'src.x1') prob.model.connect('src.x2', 'tgt.x') prob.set_solver_print(level=0) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") prob.setup(check=False) self.assertEqual( str(w[-1].message), "Input 'tgt.x' with units of 'degC' is " "connected to output 'src.x2' which has no units.") prob.run_model() assert_rel_error(self, prob['tgt.y'], 600.)
def test_vector_inputs(self): mm = MetaModel() mm.add_input('x', np.zeros(4)) mm.add_output('y1', 0.) mm.add_output('y2', 0.) mm.default_surrogate = FloatKrigingSurrogate() prob = Problem() prob.model.add_subsystem('mm', mm) prob.setup(check=False) mm.metadata['train:x'] = [[1.0, 1.0, 1.0, 1.0], [2.0, 1.0, 1.0, 1.0], [1.0, 2.0, 1.0, 1.0], [1.0, 1.0, 2.0, 1.0], [1.0, 1.0, 1.0, 2.0]] mm.metadata['train:y1'] = [3.0, 2.0, 1.0, 6.0, -2.0] mm.metadata['train:y2'] = [1.0, 4.0, 7.0, -3.0, 3.0] prob['mm.x'] = [1.0, 2.0, 1.0, 1.0] prob.run_model() assert_rel_error(self, prob['mm.y1'], 1.0, .00001) assert_rel_error(self, prob['mm.y2'], 7.0, .00001)
def test_speed(self): comp = IndepVarComp() comp.add_output('distance', 1., units='km') comp.add_output('time', 1., units='h') group = Group() group.add_subsystem('c1', comp) group.add_subsystem('c2', SpeedComputationWithUnits()) group.connect('c1.distance', 'c2.distance') group.connect('c1.time', 'c2.time') prob = Problem(model=group) prob.setup(check=False) prob.set_solver_print(level=0) prob.run_model() assert_rel_error(self, prob['c1.distance'], 1.0) # units: km assert_rel_error(self, prob['c2.distance'], 1000.0) # units: m assert_rel_error(self, prob['c1.time'], 1.0) # units: h assert_rel_error(self, prob['c2.time'], 3600.0) # units: s assert_rel_error(self, prob['c2.speed'], 1.0) # units: km/h (i.e., kph)
def test_scaled_derivs(self): prob = Problem() prob.model = model = SellarDerivatives() model.add_design_var('z', ref=2.0, ref0=0.0) model.add_objective('obj', ref=1.0, ref0=0.0) model.add_constraint('con1', lower=0, ref=2.0, ref0=0.0) prob.set_solver_print(level=0) prob.setup(check=False) prob.run_model() base = prob.compute_totals(of=['obj', 'con1'], wrt=['z']) derivs = prob.driver._compute_totals( of=['obj_cmp.obj', 'con_cmp1.con1'], wrt=['pz.z'], return_format='dict') assert_rel_error(self, base[('con1', 'z')][0], derivs['con_cmp1.con1']['pz.z'][0], 1e-5) assert_rel_error(self, base[('obj', 'z')][0] * 2.0, derivs['obj_cmp.obj']['pz.z'][0], 1e-5)
def test_4_subs_with_mins_serial_plus_2_par(self): p = Problem() model = p.model model.add_subsystem('indep', IndepVarComp('x', 1.0)) par1 = model.add_subsystem('par1', ParallelGroup()) par2 = model.add_subsystem('par2', ParallelGroup()) par1.add_subsystem("C0", ExecComp("y=2.0*x"), min_procs=2) par1.add_subsystem("C1", ExecComp("y=2.0*x"), min_procs=1) par2.add_subsystem("C2", ExecComp("y=2.0*x"), min_procs=1) par2.add_subsystem("C3", ExecComp("y=2.0*x"), min_procs=2) s_sum = '+'.join(['x%d' % i for i in range(4)]) model.add_subsystem('objective', ExecComp("y=%s" % s_sum)) model.connect('indep.x', ['par1.C0.x', 'par1.C1.x', 'par2.C2.x', 'par2.C3.x']) for i in range(2): model.connect('par1.C%d.y' % i, 'objective.x%d' % i) for i in range(2,4): model.connect('par2.C%d.y' % i, 'objective.x%d' % i) model.add_design_var('indep.x') model.add_objective('objective.y') p.setup(vector_class=vector_class, check=False) p.final_setup() all_inds = _get_which_procs(p.model) self.assertEqual(all_inds, [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]) all_inds = _get_which_procs(p.model.par1) self.assertEqual(all_inds, [[0], [0], [1]]) all_inds = _get_which_procs(p.model.par2) self.assertEqual(all_inds, [[0], [1], [1]]) p.run_model() assert_rel_error(self, p['objective.y'], 8.0) J = p.compute_totals(['objective.y'], ['indep.x'], return_format='dict') assert_rel_error(self, J['objective.y']['indep.x'][0][0], 8.0, 1e-6)
def test_promote_src_indices_nonflat_to_scalars(self): class MyComp(ExplicitComponent): def setup(self): self.add_input('x', 1.0, src_indices=[(3, 1)], shape=(1, )) self.add_output('y', 1.0) def compute(self, inputs, outputs): outputs['y'] = inputs['x'] * 2.0 p = Problem() p.model.add_subsystem('indep', IndepVarComp('x', np.arange(12).reshape((4, 3))), promotes_outputs=['x']) p.model.add_subsystem('C1', MyComp(), promotes_inputs=['x']) p.set_solver_print(level=0) p.setup() p.run_model() assert_rel_error(self, p['C1.x'], 10.) assert_rel_error(self, p['C1.y'], 20.)
def test_training_gradient(self): model = Group() ivc = IndepVarComp() mapdata = SampleMap() params = mapdata.param_data outs = mapdata.output_data ivc.add_output('x', np.array([-0.3, 0.7, 1.2])) ivc.add_output('y', np.array([0.14, 0.313, 1.41])) ivc.add_output('z', np.array([-2.11, -1.2, 2.01])) ivc.add_output('f_train', outs[0]['values']) ivc.add_output('g_train', outs[1]['values']) comp = MetaModelStructured(training_data_gradients=True, method='cubic', num_nodes=3) for param in params: comp.add_input(param['name'], param['default'], param['values']) for out in outs: comp.add_output(out['name'], out['default'], out['values']) model.add_subsystem('ivc', ivc, promotes=["*"]) model.add_subsystem('comp', comp, promotes=["*"]) prob = Problem(model) prob.setup() prob.run_model() val0 = np.array([50.26787317, 49.76106232, 19.66117913]) val1 = np.array([-32.62094041, -31.67449135, -27.46959668]) tol = 1e-5 assert_rel_error(self, prob['f'], val0, tol) assert_rel_error(self, prob['g'], val1, tol) self.run_and_check_derivs(prob)
def test_snopt_maxit(self): prob = Problem() model = prob.model = SellarDerivativesGrouped() prob.driver = pyOptSparseDriver() prob.driver.options['optimizer'] = "SNOPT" prob.driver.opt_settings['Major iterations limit'] = 4 model.add_design_var('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0])) model.add_design_var('x', lower=0.0, upper=10.0) model.add_objective('obj') model.add_constraint('con1', upper=0.0) model.add_constraint('con2', upper=0.0) prob.set_solver_print(level=0) prob.setup(check=False, mode='rev') prob.run_driver() assert_rel_error(self, prob['z'][0], 1.9780247, 1e-3)
def test_promote_src_indices_nonflat(self): import numpy as np from openmdao.api import ExplicitComponent, Problem, IndepVarComp class MyComp(ExplicitComponent): def setup(self): # We want to pull the following 4 values out of the source: # [(0,0), (3,1), (2,1), (1,1)]. # Because our input is also non-flat we arrange the # source index tuples into an array having the same shape # as our input. If we didn't set flat_src_indices to False, # we could specify src_indices as a 1D array of indices into # the flattened source. self.add_input('x', np.ones((2, 2)), src_indices=[[(0, 0), (3, 1)], [(2, 1), (1, 1)]], flat_src_indices=False) self.add_output('y', 1.0) def compute(self, inputs, outputs): outputs['y'] = np.sum(inputs['x']) p = Problem() # by promoting the following output and inputs to 'x', they will # be automatically connected p.model.add_subsystem('indep', IndepVarComp('x', np.arange(12).reshape((4, 3))), promotes_outputs=['x']) p.model.add_subsystem('C1', MyComp(), promotes_inputs=['x']) p.set_solver_print(level=0) p.setup() p.run_model() assert_rel_error(self, p['C1.x'], np.array([[0., 10.], [7., 4.]])) assert_rel_error(self, p['C1.y'], 21.)
def test_sin_metamodel_rmse(self): # create MetaModelUnStructured with Kriging, using the rmse option sin_mm = MetaModelUnStructured() sin_mm.add_input('x', 0.) sin_mm.add_output('f_x', 0.) sin_mm.default_surrogate = KrigingSurrogate(eval_rmse=True) # add it to a Problem prob = Problem() prob.model.add_subsystem('sin_mm', sin_mm) prob.setup(check=False) # train the surrogate and check predicted value sin_mm.metadata['train:x'] = np.linspace(0,10,20) sin_mm.metadata['train:f_x'] = np.sin(sin_mm.metadata['train:x']) prob['sin_mm.x'] = 2.1 prob.run_model() assert_rel_error(self, prob['sin_mm.f_x'], np.sin(2.1), 1e-4) # mean self.assertTrue(self, sin_mm._metadata('f_x')['rmse'] < 1e-5) # std deviation
def test_simple_paraboloid_upper_indices(self): prob = Problem() model = prob.model = Group() size = 3 model.add_subsystem('p1', IndepVarComp('x', np.array([50.0]*size))) model.add_subsystem('p2', IndepVarComp('y', np.array([50.0]*size))) model.add_subsystem('comp', ExecComp('f_xy = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0', x=np.zeros(size), y=np.zeros(size), f_xy=np.zeros(size))) model.add_subsystem('con', ExecComp('c = - x + y', c=np.zeros(size), x=np.zeros(size), y=np.zeros(size))) model.connect('p1.x', 'comp.x') model.connect('p2.y', 'comp.y') model.connect('p1.x', 'con.x') model.connect('p2.y', 'con.y') prob.set_solver_print(level=0) prob.driver = pyOptSparseDriver() prob.driver.options['optimizer'] = OPTIMIZER if OPTIMIZER == 'SLSQP': prob.driver.opt_settings['ACC'] = 1e-9 prob.driver.options['print_results'] = False model.add_design_var('p1.x', indices=[1], lower=-50.0, upper=50.0) model.add_design_var('p2.y', indices=[1], lower=-50.0, upper=50.0) model.add_objective('comp.f_xy', index=1) model.add_constraint('con.c', indices=[1], upper=-15.0) prob.setup(check=False) prob.run_driver() # Minimum should be at (7.166667, -7.833334) assert_rel_error(self, prob['p1.x'], np.array([50., 7.16667, 50.]), 1e-6) assert_rel_error(self, prob['p2.y'], np.array([50., -7.833334, 50.]), 1e-6)
def test_guess_nonlinear_transfer(self): # Test that data is transfered to a component before calling guess_nonlinear. class ImpWithInitial(ImplicitComponent): def setup(self): self.add_input('x', 3.0) self.add_output('y', 4.0) def solve_nonlinear(self, inputs, outputs): """ Do nothing. """ pass def apply_nonlinear(self, inputs, outputs, resids): """ Do nothing. """ pass def guess_nonlinear(self, inputs, outputs, resids): # Passthrough outputs['y'] = inputs['x'] group = Group() group.add_subsystem('px', IndepVarComp('x', 77.0)) group.add_subsystem('comp1', ImpWithInitial()) group.add_subsystem('comp2', ImpWithInitial()) group.connect('px.x', 'comp1.x') group.connect('comp1.y', 'comp2.x') group.nonlinear_solver = NewtonSolver() group.nonlinear_solver.options['maxiter'] = 1 prob = Problem(model=group) prob.set_solver_print(level=0) prob.setup(check=False) prob.run_model() assert_rel_error(self, prob['comp2.y'], 77., 1e-5)
def test_feature_basic(self): prob = Problem() model = prob.model = Group() model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1e-9 prob.driver.options['disp'] = True model.add_design_var('x', lower=-50.0, upper=50.0) model.add_design_var('y', lower=-50.0, upper=50.0) model.add_objective('f_xy') prob.setup() prob.run_driver() assert_rel_error(self, prob['x'], 6.66666667, 1e-6) assert_rel_error(self, prob['y'], -7.3333333, 1e-6)
def test_fan_out_serial_sets_rev(self): prob = Problem() prob.model = FanOutGrouped() prob.model.linear_solver = LinearBlockGS() prob.model.sub.linear_solver = LinearBlockGS() prob.model.add_design_var('iv.x') prob.model.add_constraint('c2.y', upper=0.0) prob.model.add_constraint('c3.y', upper=0.0) prob.setup(vector_class=vector_class, check=False, mode='rev') prob.run_driver() unknown_list = ['c3.y', 'c2.y'] #['c2.y', 'c3.y'] indep_list = ['iv.x'] J = prob.compute_totals(unknown_list, indep_list, return_format='flat_dict') assert_rel_error(self, J['c2.y', 'iv.x'][0][0], -6.0, 1e-6) assert_rel_error(self, J['c3.y', 'iv.x'][0][0], 15.0, 1e-6)
def test_sparse_jacobian_const(self): class SparsePartialComp(ExplicitComponent): def setup(self): self.add_input('x', shape=(4, )) self.add_input('y', shape=(2, )) self.add_output('f', shape=(2, )) self.declare_partials(of='f', wrt='x', rows=[0, 1, 1, 1], cols=[0, 1, 2, 3], val=[1., 2., 3., 4.]) self.declare_partials(of='f', wrt='y', val=sp.sparse.eye(2, format='csc')) def compute_partials(self, inputs, partials): pass model = Group() comp = IndepVarComp() comp.add_output('x', np.ones(4)) comp.add_output('y', np.ones(2)) model.add_subsystem('input', comp) model.add_subsystem('example', SparsePartialComp()) model.connect('input.x', 'example.x') model.connect('input.y', 'example.y') problem = Problem(model=model) problem.setup(check=False) problem.run_model() totals = problem.compute_totals(['example.f'], ['input.x', 'input.y']) assert_rel_error(self, totals['example.f', 'input.x'], [[1., 0., 0., 0.], [0., 2., 3., 4.]]) assert_rel_error(self, totals['example.f', 'input.y'], [[1., 0.], [0., 1.]])
def test_fan_in_serial_sets_fwd(self): prob = Problem() prob.model = FanInGrouped() prob.model.linear_solver = LinearBlockGS() prob.model.sub.linear_solver = LinearBlockGS() prob.model.add_design_var('iv.x1') prob.model.add_design_var('iv.x2') prob.model.add_objective('c3.y') prob.setup(vector_class=vector_class, check=False, mode='fwd') prob.run_driver() indep_list = ['iv.x1', 'iv.x2'] unknown_list = ['c3.y'] J = prob.compute_totals(unknown_list, indep_list, return_format='flat_dict') assert_rel_error(self, J['c3.y', 'iv.x1'][0][0], -6.0, 1e-6) assert_rel_error(self, J['c3.y', 'iv.x2'][0][0], 35.0, 1e-6)
def test_serial_rev(self): asize = self.asize prob = self.setup_model() prob.model.add_design_var('Indep1.x') prob.model.add_design_var('Indep2.x') prob.model.add_constraint('Con1.y', upper=0.0) prob.model.add_constraint('Con2.y', upper=0.0) prob.setup(vector_class=vector_class, check=False, mode='rev') prob.run_driver() J = prob.compute_totals(['Con1.y', 'Con2.y'], ['Indep1.x', 'Indep2.x'], return_format='flat_dict') assert_rel_error( self, J['Con1.y', 'Indep1.x'], np.array([[15., 20., 25.], [15., 20., 25.], [15., 20., 25.]]), 1e-6) expected = np.zeros((asize, asize + 2)) expected[:, :asize] = np.eye(asize) * 8.0 assert_rel_error(self, J['Con2.y', 'Indep2.x'], expected, 1e-6)
def test_1d_2fi_cokriging(self): # Example from Forrester: Engineering design via surrogate modelling def f_expensive(x): return ((x * 6 - 2)**2) * sin((x * 6 - 2) * 2) def f_cheap(x): return 0.5 * ((x * 6 - 2)**2) * sin( (x * 6 - 2) * 2) + (x - 0.5) * 10. - 5 x = array([[[0.0], [0.4], [0.6], [1.0]], [[0.1], [0.2], [0.3], [0.5], [0.7], [0.8], [0.9], [0.0], [0.4], [0.6], [1.0]]]) y = array([[f_expensive(v) for v in array(x[0]).ravel()], [f_cheap(v) for v in array(x[1]).ravel()]]) cokrig = MultiFiCoKrigingSurrogate() cokrig.train_multifi(x, y) new_x = array([0.75]) mu, sigma = cokrig.predict(new_x) assert_rel_error(self, mu, [[f_expensive(new_x[0])]], 0.05) assert_rel_error(self, sigma, [[0.]], 0.02)
def test_full_model_fd(self): class DontCall(LinearRunOnce): def solve(self, vec_names, mode, rel_systems=None): raise RuntimeError("This solver should be ignored!") class Simple(ExplicitComponent): def setup(self): self.add_input('x', val=0.0) self.add_output('y', val=0.0) self.declare_partials('y', 'x') def compute(self, inputs, outputs): x = inputs['x'] outputs['y'] = 4.0 * x prob = Problem() model = prob.model = Group() model.add_subsystem('p1', IndepVarComp('x', 0.0), promotes=['x']) model.add_subsystem('comp', Simple(), promotes=['x', 'y']) model.linear_solver = DontCall() model.approx_totals() model.add_design_var('x') model.add_objective('y') prob.setup(check=False, mode='fwd') prob.set_solver_print(level=0) prob.run_model() of = ['comp.y'] wrt = ['p1.x'] derivs = prob.driver._compute_totals(of=of, wrt=wrt, return_format='dict') assert_rel_error(self, derivs['comp.y']['p1.x'], [[4.0]], 1e-6)
def test_sellar(self): # Basic sellar test. prob = self.prob = Problem() model = prob.model = Group() model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x']) model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z']) model.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) model.add_subsystem('d2', SellarDis2withDerivatives(), promotes=['z', 'y1', 'y2']) model.add_subsystem('obj_cmp', ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)', z=np.array([0.0, 0.0]), x=0.0), promotes=['obj', 'x', 'z', 'y1', 'y2']) model.add_subsystem('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1']) model.add_subsystem('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2', 'y2']) nlbgs = prob.model.nonlinear_solver = NonlinearBlockGS() model.approx_totals(method='fd', step=1e-5) prob.setup(check=False) prob.set_solver_print(level=0) prob.run_model() assert_rel_error(self, prob['y1'], 25.58830273, .00001) assert_rel_error(self, prob['y2'], 12.05848819, .00001) wrt = ['z'] of = ['obj'] J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict') assert_rel_error(self, J['obj', 'z'][0][0], 9.61001056, .00001) assert_rel_error(self, J['obj', 'z'][0][1], 1.78448534, .00001)