def test_incompatible_connections(self): class BadComp(Component): def __init__(self): super(BadComp, self).__init__() self.add_param('x2', 100.0, units='m') self.add_output('x3', 100.0) # Explicit Connection prob = Problem() prob.root = Group() prob.root.add('src', SrcComp()) prob.root.add('dest', BadComp()) prob.root.connect('src.x2', 'dest.x2') with self.assertRaises(TypeError) as cm: prob.setup(check=False) expected_msg = "Unit 'degC' in source 'src.x2' is incompatible with unit 'm' in target 'dest.x2'." self.assertEqual(str(cm.exception), expected_msg) # Implicit Connection prob = Problem() prob.root = Group() prob.root.add('src', SrcComp(), promotes=['x2']) prob.root.add('dest', BadComp(),promotes=['x2']) with self.assertRaises(TypeError) as cm: prob.setup(check=False) expected_msg = "Unit 'degC' in source 'x2' is incompatible with unit 'm' in target 'x2'." self.assertEqual(str(cm.exception), expected_msg)
def test_error_change_after_setup(self): # Tests error messages for the 5 options that we should never change # after setup is called. top = Problem() top.root = SellarStateConnection() top.setup(check=False) # Not permitted to change this with self.assertRaises(RuntimeError) as err: top.root.fd_options['form'] = 'complex_step' expected_msg = "The 'form' option cannot be changed after setup." self.assertEqual(str(err.exception), expected_msg) top = Problem() top.root = SellarStateConnection() top.setup(check=False) # Not permitted to change this with self.assertRaises(RuntimeError) as err: top.root.fd_options['extra_check_partials_form'] = 'complex_step' expected_msg = "The 'extra_check_partials_form' option cannot be changed after setup." self.assertEqual(str(err.exception), expected_msg) top = Problem() top.root = SellarStateConnection() top.setup(check=False) # Not permitted to change this with self.assertRaises(RuntimeError) as err: top.root.fd_options['force_fd'] = True expected_msg = "The 'force_fd' option cannot be changed after setup." self.assertEqual(str(err.exception), expected_msg) top = Problem() top.root = SellarStateConnection() top.setup(check=False) # Not permitted to change this with self.assertRaises(RuntimeError) as err: top.root.ln_solver.options['mode'] = 'rev' expected_msg = "The 'mode' option cannot be changed after setup." self.assertEqual(str(err.exception), expected_msg) top = Problem() top.root = SellarStateConnection() top.setup(check=False) # Not permitted to change this with self.assertRaises(RuntimeError) as err: top.root.ln_solver.options['single_voi_relevance_reduction'] = True expected_msg = "The 'single_voi_relevance_reduction' option cannot be changed after setup." self.assertEqual(str(err.exception), expected_msg)
def test_explicit_connection_errors(self): class A(Component): def __init__(self): super(A, self).__init__() self.add_state('x', 0) class B(Component): def __init__(self): super(B, self).__init__() self.add_param('x', 0) prob = Problem() prob.root = Group() prob.root.ln_solver = ScipyGMRES() prob.root.add('A', A()) prob.root.add('B', B()) prob.root.connect('A.x', 'B.x') prob.setup(check=False) prob = Problem() prob.root = Group() prob.root.add('A', A()) prob.root.add('B', B()) prob.root.connect('A.y', 'B.x') with self.assertRaises(Exception) as cm: prob.setup(check=False) expected = ("Source 'A.y' cannot be connected to target 'B.x': " "'A.y' does not exist.") self.assertEqual(str(cm.exception), expected) prob = Problem() prob.root = Group() prob.root.add('A', A()) prob.root.add('B', B()) prob.root.connect('A.x', 'B.y') with self.assertRaises(Exception) as cm: prob.setup(check=False) expected = ("Source 'A.x' cannot be connected to target 'B.y': " "'B.y' does not exist.") self.assertEqual(str(cm.exception), expected) prob = Problem() prob.root = Group() prob.root.add('A', A()) prob.root.add('B', B()) prob.root.connect('A.x', 'A.x') with self.assertRaises(Exception) as cm: prob.setup(check=False) expected = ("Source 'A.x' cannot be connected to target 'A.x': " "Target must be a parameter but 'A.x' is an unknown.") self.assertEqual(str(cm.exception), expected)
def test_iprint(self): top = Problem() top.root = SellarStateConnection() top.setup(check=False) base_stdout = sys.stdout try: ostream = cStringIO() sys.stdout = ostream top.run() finally: sys.stdout = base_stdout printed = ostream.getvalue() self.assertEqual(printed, '') # Turn on all iprints top.print_all_convergence() try: ostream = cStringIO() sys.stdout = ostream top.run() finally: sys.stdout = base_stdout printed = ostream.getvalue() self.assertEqual(printed.count('NEWTON'), 3) self.assertEqual(printed.count('GMRES'), 4) self.assertTrue('[root] NL: NEWTON 0 | ' in printed) self.assertTrue(' [root.sub] LN: GMRES 1 | ' in printed) # Now, test out level = 1 top = Problem() top.root = SellarStateConnection() top.setup(check=False) base_stdout = sys.stdout top.print_all_convergence(level=1) try: ostream = cStringIO() sys.stdout = ostream top.run() finally: sys.stdout = base_stdout printed = ostream.getvalue() self.assertEqual(printed.count('NEWTON'), 2) self.assertEqual(printed.count('GMRES'), 4) self.assertTrue('[root] NL: NEWTON 0 | ' not in printed) self.assertTrue(' [root.sub] LN: GMRES 1 | ' not in printed)
def test_bad_size(self): class BadComp(SimpleArrayComp): def linearize(self, params, unknowns, resids): """Analytical derivatives""" J = {} J[('y', 'x')] = np.zeros((3, 3)) return J prob = Problem() prob.root = Group() prob.root.add('comp', BadComp()) prob.root.add('p1', IndepVarComp('x', np.ones([2]))) prob.root.connect('p1.x', 'comp.x') prob.setup(check=False) prob.run() try: data = prob.check_partial_derivatives(out_stream=None) except Exception as err: msg = "derivative in component 'comp' of 'y' wrt 'x' is the wrong size. It should be (2, 2), but got (3, 3)" # Good ole Numpy raised_error = str(err) raised_error = raised_error.replace('3L', '3') self.assertEqual(raised_error, msg) else: self.fail("Error expected")
def test_includes_and_excludes(self): prob = Problem() prob.root = ConvergeDiverge() prob.driver.add_recorder(self.recorder) self.recorder.options['includes'] = ['comp1.*'] self.recorder.options['excludes'] = ["*.y2"] self.recorder.options['record_params'] = True self.recorder.options['record_resids'] = True prob.setup(check=False) t0, t1 = run_problem(prob) prob.cleanup() # closes recorders coordinate = [0, 'Driver', (1,)] expected_params = [ ("comp1.x1", 2.0) ] expected_unknowns = [ ("comp1.y1", 8.0) ] expected_resids = [ ("comp1.y1", 0.0) ] self.assertIterationDataRecorded(((coordinate, (t0, t1), expected_params, expected_unknowns, expected_resids),), self.eps)
def test_src_indices_error(self): size = 3 group = Group() group.add('P', IndepVarComp('x', numpy.ones(size))) group.add('C1', DistribExecComp(['y=2.0*x'], arr_size=size, x=numpy.zeros(size), y=numpy.zeros(size))) group.add('C2', ExecComp(['z=3.0*y'], y=numpy.zeros(size), z=numpy.zeros(size))) prob = Problem(impl=impl) prob.root = group prob.root.ln_solver = LinearGaussSeidel() prob.root.connect('P.x', 'C1.x') prob.root.connect('C1.y', 'C2.y') prob.driver.add_desvar('P.x') prob.driver.add_objective('C1.y') try: prob.setup(check=False) except Exception as err: self.assertEqual(str(err), "'C1.y' is a distributed variable" " and may not be used as a design var," " objective, or constraint.") else: if MPI: self.fail("Exception expected")
def test_driver_param_indices(self): """ Test driver param indices with pyOptSparse and force_fd=False """ prob = Problem() prob.root = SellarStateConnection() prob.root.fd_options['force_fd'] = False prob.driver = pyOptSparseDriver() prob.driver.options['optimizer'] = OPTIMIZER prob.driver.options['print_results'] = False prob.driver.add_desvar('z', lower=np.array([-10.0]), upper=np.array([10.0]), indices=[0]) prob.driver.add_desvar('x', lower=0.0, upper=10.0) prob.driver.add_objective('obj') prob.driver.add_constraint('con1', upper=0.0) prob.driver.add_constraint('con2', upper=0.0) prob.setup(check=False) prob['z'][1] = 0.0 prob.run() assert_rel_error(self, prob['z'][0], 1.9776, 1e-3) assert_rel_error(self, prob['z'][1], 0.0, 1e-3) assert_rel_error(self, prob['x'], 0.0, 1e-3)
def test_two_simple(self): size = 3 group = Group() group.add('P', IndepVarComp('x', numpy.ones(size))) group.add('C1', DistribExecComp(['y=2.0*x'], arr_size=size, x=numpy.zeros(size), y=numpy.zeros(size))) group.add('C2', ExecComp(['z=3.0*y'], y=numpy.zeros(size), z=numpy.zeros(size))) prob = Problem(impl=impl) prob.root = group prob.root.ln_solver = LinearGaussSeidel() prob.root.connect('P.x', 'C1.x') prob.root.connect('C1.y', 'C2.y') prob.setup(check=False) prob.run() J = prob.calc_gradient(['P.x'], ['C2.z'], mode='fwd', return_format='dict') assert_rel_error(self, J['C2.z']['P.x'], numpy.eye(size)*6.0, 1e-6) J = prob.calc_gradient(['P.x'], ['C2.z'], mode='rev', return_format='dict') assert_rel_error(self, J['C2.z']['P.x'], numpy.eye(size)*6.0, 1e-6)
def test_too_few_procs(self): size = 3 group = Group() group.add('P', IndepVarComp('x', numpy.ones(size))) group.add('C1', DistribExecComp(['y=2.0*x'], arr_size=size, x=numpy.zeros(size), y=numpy.zeros(size))) group.add('C2', ExecComp(['z=3.0*y'], y=numpy.zeros(size), z=numpy.zeros(size))) prob = Problem(impl=impl) prob.root = group prob.root.ln_solver = LinearGaussSeidel() prob.root.connect('P.x', 'C1.x') prob.root.connect('C1.y', 'C2.y') try: prob.setup(check=False) except Exception as err: self.assertEqual(str(err), "This problem was given 1 MPI processes, " "but it requires between 2 and 2.") else: if MPI: self.fail("Exception expected")
def test_fan_out_parallel_sets_fwd(self): prob = Problem(impl=impl) prob.root = FanOutGrouped() prob.root.ln_solver = LinearGaussSeidel() prob.root.sub.ln_solver = LinearGaussSeidel() prob.root.ln_solver.options['mode'] = 'fwd' prob.root.sub.ln_solver.options['mode'] = 'fwd' prob.driver.add_desvar('p.x') prob.driver.add_constraint('c2.y', upper=0.0) prob.driver.add_constraint('c3.y', upper=0.0) prob.driver.parallel_derivs(['c2.y', 'c3.y']) # ignored in fwd if MPI: expected = [('c2.y', 'c3.y')] else: expected = [('c2.y',), ('c3.y',)] self.assertEqual(prob.driver.outputs_of_interest(), expected) prob.setup(check=False) prob.run() unknown_list = ['c2.y', 'c3.y'] indep_list = ['p.x'] J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict') assert_rel_error(self, J['c2.y']['p.x'][0][0], -6.0, 1e-6) assert_rel_error(self, J['c3.y']['p.x'][0][0], 15.0, 1e-6)
def test_fan_in_parallel_sets_rev(self): prob = Problem(impl=impl) prob.root = FanInGrouped() prob.root.ln_solver = LinearGaussSeidel() prob.root.sub.ln_solver = LinearGaussSeidel() prob.root.ln_solver.options['mode'] = 'rev' prob.root.sub.ln_solver.options['mode'] = 'rev' prob.driver.add_desvar('p1.x1') prob.driver.add_desvar('p2.x2') prob.driver.add_desvar('p3.x3') prob.driver.add_objective('comp3.y') prob.driver.parallel_derivs(['p1.x1', 'p2.x2']) if MPI: expected = [('p1.x1', 'p2.x2'), ('p3.x3',)] else: expected = [('p1.x1',), ('p2.x2',), ('p3.x3',)] self.assertEqual(prob.driver.desvars_of_interest(), expected) prob.setup(check=False) prob.run() indep_list = ['p1.x1', 'p2.x2'] unknown_list = ['comp3.y'] J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict') assert_rel_error(self, J['comp3.y']['p1.x1'][0][0], -6.0, 1e-6) assert_rel_error(self, J['comp3.y']['p2.x2'][0][0], 35.0, 1e-6)
def test_calc_gradient_multiple_params(self): prob = Problem() prob.root = FanIn() prob.setup(check=False) prob.run() indep_list = ['p1.x1', 'p2.x2'] unknown_list = ['comp3.y'] # check that calc_gradient returns proper dict value when mode is 'fwd' J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict') assert_almost_equal(J['comp3.y']['p2.x2'], np.array([[35.]])) assert_almost_equal(J['comp3.y']['p1.x1'], np.array([[-6.]])) # check that calc_gradient returns proper array value when mode is 'fwd' J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='array') assert_almost_equal(J, np.array([[-6., 35.]])) # check that calc_gradient returns proper dict value when mode is 'rev' J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict') assert_almost_equal(J['comp3.y']['p2.x2'], np.array([[35.]])) assert_almost_equal(J['comp3.y']['p1.x1'], np.array([[-6.]])) # check that calc_gradient returns proper array value when mode is 'rev' J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='array') assert_almost_equal(J, np.array([[-6., 35.]])) # check that calc_gradient returns proper dict value when mode is 'fd' J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='dict') assert_almost_equal(J['comp3.y']['p2.x2'], np.array([[35.]])) assert_almost_equal(J['comp3.y']['p1.x1'], np.array([[-6.]])) # check that calc_gradient returns proper array value when mode is 'fd' J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='array') assert_almost_equal(J, np.array([[-6., 35.]]))
def test_fan_out_parallel_sets_rev(self): prob = Problem(impl=impl) prob.root = FanOutGrouped() prob.root.ln_solver = LinearGaussSeidel() prob.root.sub.ln_solver = LinearGaussSeidel() # need to set mode to rev before setup. Otherwise the sub-vectors # for the parallel set vars won't get allocated. prob.root.ln_solver.options['mode'] = 'rev' prob.root.sub.ln_solver.options['mode'] = 'rev' prob.driver.add_desvar('p.x') prob.driver.add_constraint('c2.y', upper=0.0) prob.driver.add_constraint('c3.y', upper=0.0) prob.driver.parallel_derivs(['c2.y', 'c3.y']) if MPI: expected = [('c2.y', 'c3.y')] else: expected = [('c2.y',), ('c3.y',)] self.assertEqual(prob.driver.outputs_of_interest(), expected) prob.setup(check=False) prob.run() unknown_list = ['c2.y', 'c3.y'] indep_list = ['p.x'] J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict') assert_rel_error(self, J['c2.y']['p.x'][0][0], -6.0, 1e-6) assert_rel_error(self, J['c3.y']['p.x'][0][0], 15.0, 1e-6)
def test_root_derivs_array(self): prob = Problem() prob.root = SellarDerivativesGrouped() prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1.0e-8 prob.driver.options['disp'] = False prob.driver.add_desvar('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0])) prob.driver.add_desvar('x', lower=0.0, upper=10.0) prob.driver.add_objective('obj') prob.driver.add_constraint('con1', upper=0.0) prob.driver.add_constraint('con2', upper=0.0) prob.driver.add_recorder(self.recorder) self.recorder.options['record_metadata'] = False self.recorder.options['record_derivs'] = True prob.setup(check=False) prob.run() prob.cleanup() sout = open(self.filename) lines = sout.readlines() self.assertEqual(lines[12].rstrip(), 'Derivatives:') self.assertTrue('9.61' in lines[13]) self.assertTrue('0.784' in lines[14]) self.assertTrue('1.077' in lines[15])
def test_problem_deriv_test(self): prob = Problem() prob.root = Group() prob.root.add('comp', SimpleCompWrongDeriv()) prob.root.add('p1', IndepVarComp('x', 2.0)) prob.root.connect('p1.x', 'comp.x') prob.setup(check=False) prob.run() data = prob.check_partial_derivatives(out_stream=None) # suppress printed output from problem_derivatives_check() sysout = sys.stdout devnull = open(os.devnull, 'w') try: sys.stdout = devnull problem_derivatives_check(self, prob) except AssertionError as err: sys.stdout = sysout self.assertIn("not less than or equal to 1e-05", err.args[0]) finally: sys.stdout = sysout
def test_only_resids_recorded(self): prob = Problem() prob.root = ConvergeDiverge() prob.driver.add_recorder(self.recorder) self.recorder.options['record_params'] = False self.recorder.options['record_unknowns'] = False self.recorder.options['record_resids'] = True prob.setup(check=False) t0, t1 = run_problem(prob) prob.cleanup() # closes recorders coordinate = [0, 'Driver', (1, )] expected_resids = [ ("comp1.y1", 0.0), ("comp1.y2", 0.0), ("comp2.y1", 0.0), ("comp3.y1", 0.0), ("comp4.y1", 0.0), ("comp4.y2", 0.0), ("comp5.y1", 0.0), ("comp6.y1", 0.0), ("comp7.y1", 0.0), ("p.x", 0.0) ] self.assertIterationDataRecorded(((coordinate, (t0, t1), None, None, expected_resids),), self.eps)
def test_only_unknowns_recorded(self): prob = Problem() prob.root = ConvergeDiverge() prob.driver.add_recorder(self.recorder) prob.setup(check=False) t0, t1 = run_problem(prob) prob.cleanup() # closes recorders coordinate = [0, 'Driver', (1, )] expected_unknowns = [ ("comp1.y1", 8.0), ("comp1.y2", 6.0), ("comp2.y1", 4.0), ("comp3.y1", 21.0), ("comp4.y1", 46.0), ("comp4.y2", -93.0), ("comp5.y1", 36.8), ("comp6.y1", -46.5), ("comp7.y1", -102.7), ("p.x", 2.0) ] self.assertIterationDataRecorded(((coordinate, (t0, t1), None, expected_unknowns, None),), self.eps)
def test_only_params_recorded(self): prob = Problem() prob.root = ConvergeDiverge() prob.driver.add_recorder(self.recorder) self.recorder.options['record_params'] = True self.recorder.options['record_resids'] = False self.recorder.options['record_unknowns'] = False prob.setup(check=False) t0, t1 = run_problem(prob) prob.cleanup() # closes recorders coordinate = [0, 'Driver', (1,)] expected_params = [ ("comp1.x1", 2.0), ("comp2.x1", 8.0), ("comp3.x1", 6.0), ("comp4.x1", 4.0), ("comp4.x2", 21.0), ("comp5.x1", 46.0), ("comp6.x1", -93.0), ("comp7.x1", 36.8), ("comp7.x2", -46.5) ] self.assertIterationDataRecorded(((coordinate, (t0, t1), expected_params, None, None),), self.eps)
def test_beam_tutorial_viewtree(self): top = Problem() top.root = BeamTutorial() top.driver = ScipyOptimizer() top.driver.options['optimizer'] = 'SLSQP' top.driver.options['tol'] = 1.0e-8 top.driver.options['maxiter'] = 10000 #maximum number of solver iterations top.driver.options['disp'] = False #room length and width bounds top.driver.add_desvar('ivc_rlength.room_length', lower=5.0*12.0, upper=50.0*12.0) #domain: 1in <= length <= 50ft top.driver.add_desvar('ivc_rwidth.room_width', lower=5.0*12.0, upper=30.0*12.0) #domain: 1in <= width <= 30ft top.driver.add_objective('d_neg_area.neg_room_area') #minimize negative area (or maximize area) top.driver.add_constraint('d_len_minus_wid.length_minus_width', lower=0.0) #room_length >= room_width top.driver.add_constraint('d_deflection.deflection', lower=720.0) #deflection >= 720 top.driver.add_constraint('d_bending.bending_stress_ratio', upper=0.5) #bending < 0.5 top.driver.add_constraint('d_shear.shear_stress_ratio', upper=1.0/3.0) #shear < 1/3 top.setup(check=False) from openmdao.api import view_tree view_tree(top, show_browser=False) import os.path self.assertTrue(os.path.isfile('partition_tree_n2.html')) os.remove('partition_tree_n2.html')
def test_fd_options_form_precedence(self): class MyComp(Component): def __init__(self): super(MyComp, self).__init__() # Params self.add_param("x1", 3.0) self.add_param("x2", 3.0, form="central") # Unknowns self.add_output("y", 5.5) def solve_nonlinear(self, params, unknowns, resids): """ Doesn't do much. """ unknowns["y"] = 7.0 * params["x1"] ** 2 + 7.0 * params["x2"] ** 2 prob = Problem() prob.root = Group() comp = prob.root.add("comp", MyComp()) prob.root.add("p1", IndepVarComp([("x1", 3.0), ("x2", 3.0)])) prob.root.connect("p1.x1", "comp.x1") prob.root.connect("p1.x2", "comp.x2") comp.fd_options["force_fd"] = True comp.fd_options["form"] = "forward" prob.setup(check=False) prob.run() J = prob.calc_gradient(["p1.x1", "p1.x2"], ["comp.y"], return_format="dict") x1_err = J["comp.y"]["p1.x1"] - 42.0 x2_err = J["comp.y"]["p1.x2"] - 42.0 assert_rel_error(self, x1_err, 7e-6, 1e-1) assert_rel_error(self, x2_err, 5.4e-10, 1e-1)
def test_double_arraycomp(self): # Mainly testing a bug in the array return for multiple arrays group = Group() group.add('x_param1', IndepVarComp('x1', np.ones((2))), promotes=['*']) group.add('x_param2', IndepVarComp('x2', np.ones((2))), promotes=['*']) group.add('mycomp', DoubleArrayComp(), promotes=['*']) prob = Problem(impl=impl) prob.root = group prob.root.ln_solver = PetscKSP() prob.setup(check=False) prob.run() Jbase = group.mycomp.JJ J = prob.calc_gradient(['x1', 'x2'], ['y1', 'y2'], mode='fwd', return_format='array') diff = np.linalg.norm(J - Jbase) assert_rel_error(self, diff, 0.0, 1e-8) J = prob.calc_gradient(['x1', 'x2'], ['y1', 'y2'], mode='fd', return_format='array') diff = np.linalg.norm(J - Jbase) assert_rel_error(self, diff, 0.0, 1e-8) J = prob.calc_gradient(['x1', 'x2'], ['y1', 'y2'], mode='rev', return_format='array') diff = np.linalg.norm(J - Jbase) assert_rel_error(self, diff, 0.0, 1e-8)
def test_double_diamond_model_complex_step(self): prob = Problem() prob.root = ConvergeDivergeGroups() prob.root.sub1.comp1.fd_options['form'] = 'complex_step' prob.root.sub1.sub2.comp2.fd_options['form'] = 'complex_step' prob.root.sub1.sub2.comp3.fd_options['form'] = 'complex_step' prob.root.sub1.comp4.fd_options['form'] = 'complex_step' prob.root.sub3.comp5.fd_options['form'] = 'complex_step' prob.root.sub3.comp6.fd_options['form'] = 'complex_step' prob.root.comp7.fd_options['form'] = 'complex_step' prob.setup(check=False) prob.run() data = prob.check_partial_derivatives(out_stream=None) for key1, val1 in iteritems(data): for key2, val2 in iteritems(val1): assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5) assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5) assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5) assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5) assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5) assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)
def test_driver_param_indices_force_fd_shift(self): """ Test driver param indices with shifted indices and force_fd=True """ prob = Problem() prob.root = SellarStateConnection() prob.root.fd_options['force_fd'] = True prob.driver.add_desvar('z', lower=np.array([-10.0, -10.0]), upper=np.array([10.0, 10.0]), indices=[1]) prob.driver.add_desvar('x', lower=0.0, upper=10.0) prob.driver.add_objective('obj') prob.driver.add_constraint('con1', upper=0.0) prob.driver.add_constraint('con2', upper=0.0) #prob.driver.options['disp'] = False prob.setup(check=False) prob['z'][1] = 0.0 prob.run() J = prob.calc_gradient(['x', 'z'], ['obj'], mode='fd', return_format='array') assert_rel_error(self, J[0][1], 1.78402, 1e-3)
def test_simple_implicit_complex_step(self): prob = Problem() prob.root = Group() prob.root.ln_solver = ScipyGMRES() prob.root.add('comp', SimpleImplicitComp()) prob.root.add('p1', IndepVarComp('x', 0.5)) prob.root.connect('p1.x', 'comp.x') prob.root.comp.fd_options['step_size'] = 1.0e4 prob.root.comp.fd_options['form'] = 'complex_step' prob.setup(check=False) prob.run() data = prob.check_partial_derivatives(out_stream=None) for key1, val1 in iteritems(data): for key2, val2 in iteritems(val1): assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5) assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5) assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5) assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5) assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5) assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)
def test_Sellar_state_SLSQP(self): """ Baseline Sellar test case without specifying indices. """ prob = Problem() prob.root = SellarStateConnection() prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1.0e-8 prob.driver.add_desvar('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0])) prob.driver.add_desvar('x', lower=0.0, upper=10.0) prob.driver.add_objective('obj') prob.driver.add_constraint('con1', upper=0.0) prob.driver.add_constraint('con2', upper=0.0) prob.driver.options['disp'] = False prob.setup(check=False) prob.run() assert_rel_error(self, prob['z'][0], 1.9776, 1e-3) assert_rel_error(self, prob['z'][1], 0.0, 1e-3) assert_rel_error(self, prob['x'], 0.0, 1e-3)
def test_driver_param_indices_slsqp_force_fd(self): """ Test driver param indices with ScipyOptimizer SLSQP and force_fd=True """ prob = Problem() prob.root = SellarStateConnection() prob.root.fd_options['force_fd'] = True prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1.0e-8 prob.driver.options['disp'] = False prob.driver.add_desvar('z', lower=np.array([-10.0]), upper=np.array([10.0]), indices=[0]) prob.driver.add_desvar('x', lower=0.0, upper=10.0) prob.driver.add_objective('obj') prob.driver.add_constraint('con1', upper=0.0) prob.driver.add_constraint('con2', upper=0.0) #prob.driver.options['disp'] = False prob.setup(check=False) prob['z'][1] = 0.0 prob.run() assert_rel_error(self, prob['z'][0], 1.9776, 1e-3) assert_rel_error(self, prob['z'][1], 0.0, 1e-3) assert_rel_error(self, prob['x'], 0.0, 1e-3)
def test_simple_implicit_run_once(self): class SIC2(SimpleImplicitComp): def solve_nonlinear(self, params, unknowns, resids): """ Simple iterative solve. (Babylonian method).""" super(SIC2, self).solve_nonlinear(params, unknowns, resids) # This mimics a problem with residuals that aren't up-to-date # with the solve resids['z'] = 999.999 prob = Problem() prob.root = Group() prob.root.ln_solver = ScipyGMRES() prob.root.add('comp', SIC2()) prob.root.add('p1', IndepVarComp('x', 0.5)) prob.root.connect('p1.x', 'comp.x') prob.setup(check=False) prob.run_once() data = prob.check_partial_derivatives(out_stream=None) for key1, val1 in iteritems(data): for key2, val2 in iteritems(val1): assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5) assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5) assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5) assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5) assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5) assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)
def test_simple_deriv_xfer(self): prob = Problem(impl=impl) prob.root = FanInGrouped() prob.setup(check=False) prob.root.comp3.dpmat[None]['x1'] = 7. prob.root.comp3.dpmat[None]['x2'] = 11. prob.root._transfer_data(mode='rev', deriv=True) if not MPI or self.comm.rank == 0: self.assertEqual(prob.root.sub.comp1.dumat[None]['y'], 7.) if not MPI or self.comm.rank == 1: self.assertEqual(prob.root.sub.comp2.dumat[None]['y'], 11.) prob.root.comp3.dpmat[None]['x1'] = 0. prob.root.comp3.dpmat[None]['x2'] = 0. self.assertEqual(prob.root.comp3.dpmat[None]['x1'], 0.) self.assertEqual(prob.root.comp3.dpmat[None]['x2'], 0.) prob.root._transfer_data(mode='fwd', deriv=True) self.assertEqual(prob.root.comp3.dpmat[None]['x1'], 7.) self.assertEqual(prob.root.comp3.dpmat[None]['x2'], 11.)
def test_converge_diverge_compfd(self): prob = Problem(impl=impl) prob.root = ConvergeDivergePar() prob.root.ln_solver = PetscKSP() # fd comp2 and comp5. each is under a par group prob.root.par1.comp2.fd_options['force_fd'] = True prob.root.par2.comp5.fd_options['force_fd'] = True prob.setup(check=False) prob.run() # Make sure value is fine. assert_rel_error(self, prob['comp7.y1'], -102.7, 1e-6) indep_list = ['p.x'] unknown_list = ['comp7.y1'] J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict') assert_rel_error(self, J['comp7.y1']['p.x'][0][0], -40.75, 1e-6) J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict') assert_rel_error(self, J['comp7.y1']['p.x'][0][0], -40.75, 1e-6) J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='dict') assert_rel_error(self, J['comp7.y1']['p.x'][0][0], -40.75, 1e-6)
def test_pull_size_from_source(self): class Src(Component): def __init__(self): super(Src, self).__init__() self.add_param('x', 2.0) self.add_output('y1', np.zeros((3, ))) self.add_output('y2', shape=((3, ))) def solve_nonlinear(self, params, unknowns, resids): """ counts up. """ x = params['x'] unknowns['y1'] = x * np.array([1.0, 2.0, 3.0]) unknowns['y2'] = x * np.array([1.0, 2.0, 3.0]) class Tgt(Component): def __init__(self): super(Tgt, self).__init__() self.add_param('x1') self.add_param('x2') self.add_output('y1', 0.0) self.add_output('y2', 0.0) def solve_nonlinear(self, params, unknowns, resids): """ counts up. """ x1 = params['x1'] x2 = params['x2'] unknowns['y1'] = np.sum(x1) unknowns['y2'] = np.sum(x2) top = Problem() top.root = Group() top.root.add('src', Src()) top.root.add('tgt', Tgt()) top.root.connect('src.y1', 'tgt.x1') top.root.connect('src.y2', 'tgt.x2') top.setup(check=False) top.run() self.assertEqual(top['tgt.y1'], 12.0) self.assertEqual(top['tgt.y2'], 12.0)
def test_basic_input_input(self): prob = Problem() prob.root = Group() prob.root.add('src', SrcComp()) prob.root.add('tgtF', TgtCompF()) prob.root.add('tgtC', TgtCompC()) prob.root.add('tgtK', TgtCompK()) prob.root.add('px1', IndepVarComp('x1', 100.0), promotes=['x1']) prob.root.connect('x1', 'src.x1') prob.root.connect('src.x2', 'tgtC.x2') prob.root.connect('tgtC.x2', 'tgtF.x2') prob.root.connect('tgtC.x2', 'tgtK.x2') prob.setup(check=False) prob.run() assert_rel_error(self, prob['src.x2'], 100.0, 1e-6) assert_rel_error(self, prob['tgtF.x3'], 212.0, 1e-6) assert_rel_error(self, prob['tgtC.x3'], 100.0, 1e-6) assert_rel_error(self, prob['tgtK.x3'], 373.15, 1e-6) # Make sure we don't convert equal units self.assertEqual(prob.root.params.metadata('tgtC.x2').get('unit_conv'), None) indep_list = ['x1'] unknown_list = ['tgtF.x3', 'tgtC.x3', 'tgtK.x3'] J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict') assert_rel_error(self, J['tgtF.x3']['x1'][0][0], 1.8, 1e-6) assert_rel_error(self, J['tgtC.x3']['x1'][0][0], 1.0, 1e-6) assert_rel_error(self, J['tgtK.x3']['x1'][0][0], 1.0, 1e-6) J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict') assert_rel_error(self, J['tgtF.x3']['x1'][0][0], 1.8, 1e-6) assert_rel_error(self, J['tgtC.x3']['x1'][0][0], 1.0, 1e-6) assert_rel_error(self, J['tgtK.x3']['x1'][0][0], 1.0, 1e-6) J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='dict') assert_rel_error(self, J['tgtF.x3']['x1'][0][0], 1.8, 1e-6) assert_rel_error(self, J['tgtC.x3']['x1'][0][0], 1.0, 1e-6) assert_rel_error(self, J['tgtK.x3']['x1'][0][0], 1.0, 1e-6)
def test_unit_conversion(self): prob = Problem() prob.root = Group() prob.root.add('src', SrcComp()) prob.root.add('tgtF', TgtCompF()) prob.root.add('tgtC', TgtCompC()) prob.root.add('tgtK', TgtCompK()) prob.root.add('px1', IndepVarComp('x1', 100.0), promotes=['x1']) prob.root.connect('x1', 'src.x1') prob.root.connect('src.x2', 'tgtF.x2') prob.root.connect('src.x2', 'tgtC.x2') prob.root.connect('src.x2', 'tgtK.x2') prob.root.fd_options['force_fd'] = True prob.root.fd_options['form'] = 'complex_step' prob.setup(check=False) prob.run() indep_list = ['x1'] unknown_list = ['tgtF.x3', 'tgtC.x3', 'tgtK.x3'] J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict') assert_rel_error(self, J['tgtF.x3']['x1'][0][0], 1.8, 1e-6) assert_rel_error(self, J['tgtC.x3']['x1'][0][0], 1.0, 1e-6) assert_rel_error(self, J['tgtK.x3']['x1'][0][0], 1.0, 1e-6) J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict') assert_rel_error(self, J['tgtF.x3']['x1'][0][0], 1.8, 1e-6) assert_rel_error(self, J['tgtC.x3']['x1'][0][0], 1.0, 1e-6) assert_rel_error(self, J['tgtK.x3']['x1'][0][0], 1.0, 1e-6) J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='dict') assert_rel_error(self, J['tgtF.x3']['x1'][0][0], 1.8, 1e-6) assert_rel_error(self, J['tgtC.x3']['x1'][0][0], 1.0, 1e-6) assert_rel_error(self, J['tgtK.x3']['x1'][0][0], 1.0, 1e-6)
def test_sellar_derivs_grouped(self): prob = Problem() prob.root = SellarDerivativesGrouped() prob.root.ln_solver = LinearGaussSeidel() prob.root.ln_solver.options['maxiter'] = 15 #prob.root.ln_solver.options['iprint'] = 1 prob.root.mda.nl_solver.options['atol'] = 1e-12 prob.setup(check=False) prob.run() # Just make sure we are at the right answer assert_rel_error(self, prob['y1'], 25.58830273, .00001) assert_rel_error(self, prob['y2'], 12.05848819, .00001) indep_list = ['x', 'z'] unknown_list = ['obj', 'con1', 'con2'] Jbase = {} Jbase['con1'] = {} Jbase['con1']['x'] = -0.98061433 Jbase['con1']['z'] = np.array([-9.61002285, -0.78449158]) Jbase['con2'] = {} Jbase['con2']['x'] = 0.09692762 Jbase['con2']['z'] = np.array([1.94989079, 1.0775421 ]) Jbase['obj'] = {} Jbase['obj']['x'] = 2.98061392 Jbase['obj']['z'] = np.array([9.61001155, 1.78448534]) J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict') for key1, val1 in Jbase.items(): for key2, val2 in val1.items(): assert_rel_error(self, J[key1][key2], val2, .00001) J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict') for key1, val1 in Jbase.items(): for key2, val2 in val1.items(): assert_rel_error(self, J[key1][key2], val2, .00001) # Cheat a bit so I can twiddle mode OptionsDictionary.locked = False prob.root.fd_options['form'] = 'central' J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='dict') for key1, val1 in Jbase.items(): for key2, val2 in val1.items(): assert_rel_error(self, J[key1][key2], val2, .00001)
def test_multilevel_record(self): prob = Problem() prob.root = ExampleGroup() prob.root.G2.G1.nl_solver.add_recorder(self.recorder) prob.driver.add_recorder(self.recorder) self.recorder.options['record_params'] = True self.recorder.options['record_resids'] = True prob.setup(check=False) t0, t1 = run_problem(prob) prob.cleanup() # closes recorders solver_coordinate = ['Driver', (1,), "root", (1,), "G2", (1,), "G1", (1,)] g1_expected_params = [ ("C2.x", 5.0) ] g1_expected_unknowns = [ ("C2.y", 10.0) ] g1_expected_resids = [ ("C2.y", 0.0) ] driver_coordinate = ['Driver', (1,)] driver_expected_params = [ ("G3.C3.x", 10.0) ] driver_expected_unknowns = [ ("G2.C1.x", 5.0), ("G2.G1.C2.y", 10.0), ("G3.C3.y", 20.0), ("G3.C4.y", 40.0), ] driver_expected_resids = [ ("G2.C1.x", 0.0), ("G2.G1.C2.y", 0.0), ("G3.C3.y", 0.0), ("G3.C4.y", 0.0), ] expected = [] expected.append((solver_coordinate, (t0, t1), g1_expected_params, g1_expected_unknowns, g1_expected_resids)) expected.append((driver_coordinate, (t0, t1), driver_expected_params, driver_expected_unknowns, driver_expected_resids)) self.assertIterationDataRecorded(expected, self.eps)
def test_sub_unsupported(self): prob = Problem() prob.root = SellarDerivativesGrouped() # We don't support submodel cs yet. prob.root.mda.fd_options['force_fd'] = True prob.root.mda.fd_options['form'] = 'complex_step' with self.assertRaises(RuntimeError) as cm: prob.setup(check=False) msg = "Complex step is currently not supported for groups" msg += " other than root." self.assertTrue(msg in str(cm.exception))
def test_brent_converge_index(self): p = Problem() p.root = Group() p.root.add('comp', IndexCompTest(), promotes=['a', 'x', 'n', 'b', 'c']) p.root.nl_solver = Brent() p.root.nl_solver.options['state_var'] = 'x' p.root.nl_solver.options['state_var_idx'] = 2 p.root.ln_solver = ScipyGMRES() p.setup(check=False) p.run() assert_rel_error(self, p.root.unknowns['x'][2], 2.06720359226, .0001) assert_rel_error(self, p.root.resids['x'][2], 0, .0001)
def test_CSMDrivetrain(aeroPower, ratedPower): data = {} data['aeroPower'] = aeroPower data['ratedPower'] = ratedPower data['drivetrainType'] = DRIVETRAIN_TYPE['GEARED'] prob = Problem() prob.root = Group() prob.root.add('comp', CSMDrivetrain(len(aeroPower)), promotes=['*']) prob = init_IndepVar_add(prob, data) prob.root.comp.deriv_options['check_form'] = 'central' prob.root.comp.deriv_options['check_step_calc'] = 'relative' prob.setup(check=False) prob = init_IndepVar_set(prob, data) check_gradient_unit_test(prob, tol=6e-4)
def test_sellar_analysis_error(self): prob = Problem() prob.root = SellarNoDerivatives() prob.root.nl_solver = NLGaussSeidel() prob.root.nl_solver.options['maxiter'] = 2 prob.root.nl_solver.options['err_on_maxiter'] = True prob.setup(check=False) try: prob.run() except AnalysisError as err: self.assertEqual(str(err), "Solve in '': NLGaussSeidel FAILED to converge after 2 iterations") else: self.fail("expected AnalysisError")
def test_sellar_derivs_with_Lin_GS(self): prob = Problem() prob.root = SellarDerivatives() prob.root.nl_solver = Newton() prob.root.ln_solver = LinearGaussSeidel() prob.root.ln_solver.options['maxiter'] = 2 prob.setup(check=False) prob.run() assert_rel_error(self, prob['y1'], 25.58830273, .00001) assert_rel_error(self, prob['y2'], 12.05848819, .00001) # Make sure we aren't iterating like crazy self.assertLess(prob.root.nl_solver.iter_count, 8)
def test_simple_matvec(self): group = Group() group.add('x_param', IndepVarComp('x', 1.0), promotes=['*']) group.add('mycomp', SimpleCompDerivMatVec(), promotes=['x', 'y']) prob = Problem() prob.root = group prob.root.ln_solver = LinearGaussSeidel() prob.setup(check=False) prob.run() J = prob.calc_gradient(['x'], ['y'], mode='fwd', return_format='dict') assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6) J = prob.calc_gradient(['x'], ['y'], mode='rev', return_format='dict') assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6)
def test_TotalLoads(inputs_str, inputs_aeroloads): npts = np.size(inputs_str['r']) prob = Problem() prob.root = Group() prob.root.add('comp', TotalLoads(npts), promotes=['*']) prob = init_IndepVar_add(prob, inputs_str) prob = init_IndepVar_add(prob, inputs_aeroloads) prob.root.comp.deriv_options['check_step_calc'] = 'relative' prob.root.comp.deriv_options['check_form'] = 'central' prob.setup(check=False) prob = init_IndepVar_set(prob, inputs_str) prob = init_IndepVar_set(prob, inputs_aeroloads) check_gradient_unit_test(prob, tol=.01, display=False)
def test_GustETM(): data = {} data['V_mean'] = 10.0 data['V_hub'] = 11.7733866478 data['std'] = 3 data['turbulence_class'] = TURBULENCE_CLASS['B'] prob = Problem() prob.root = Group() prob.root.add('comp', GustETM(), promotes=['*']) prob = init_IndepVar_add(prob, data) prob.setup(check=False) prob = init_IndepVar_set(prob, data) check_gradient_unit_test(prob)
def test_simple_jac(self): group = Group() group.add('x_param', IndepVarComp('x', 1.0), promotes=['*']) group.add('mycomp', ExecComp(['y=2.0*x']), promotes=['x', 'y']) prob = Problem(impl=impl) prob.root = group prob.root.ln_solver = PetscKSP() prob.setup(check=False) prob.run() J = prob.calc_gradient(['x'], ['y'], mode='fwd', return_format='dict') assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6) J = prob.calc_gradient(['x'], ['y'], mode='rev', return_format='dict') assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6)
def test1(self): xbar = 6.0 x = np.array([3.0, 3.08805770406, 3.17611540812, 3.26417311218, 3.35223081624, 3.4402885203, 3.52834622436, 3.61640392842, 3.70446163248, 3.79251933654, 3.8805770406, 3.96863474466, 4.05669244872, 4.14475015278, 4.23280785684, 4.3208655609, 4.40892326496, 4.49698096902, 4.58503867308, 4.67309637714, 4.7611540812, 4.84921178526, 4.93726948932, 5.02532719338, 5.11338489744, 5.2014426015, 5.28950030556, 5.37755800962, 5.46561571369, 5.55367341775, 5.64173112181, 5.72978882587, 5.81784652993, 5.90590423399, 5.99396193805, 6.08201964211, 6.17007734617, 6.25813505023, 6.34619275429, 6.43425045835, 6.52230816241, 6.61036586647, 6.69842357053, 6.78648127459, 6.87453897865, 6.96259668271, 7.05065438677, 7.13871209083, 7.22676979489, 7.31482749895, 7.40288520301, 7.49094290707, 7.57900061113, 7.66705831519, 7.75511601925, 7.84317372331, 7.93123142737, 8.01928913143, 8.10734683549, 8.19540453955, 8.28346224361, 8.37151994767, 8.45957765173, 8.54763535579, 8.63569305985, 8.72375076391, 8.81180846797, 8.89986617203, 8.98792387609, 9.07598158015, 9.16403928421, 9.25209698827, 9.34015469233, 9.42821239639, 9.51627010045, 9.60432780451, 9.69238550857, 9.78044321263, 9.86850091669, 9.95655862075, 10.0446163248, 10.1326740289, 10.2207317329, 10.308789437, 10.3968471411, 10.4849048451, 10.5729625492, 10.6610202532, 10.7490779573, 10.8371356614, 10.9251933654, 11.0132510695, 11.1013087735, 11.1893664776, 11.2774241817, 11.3654818857, 11.4535395898, 11.5415972938, 11.6296549979, 11.717712702, 11.8505355749, 11.9833584479, 12.1161813209, 12.2490041939, 12.3818270669, 12.5146499398, 12.6474728128, 12.7802956858, 12.9131185588, 13.0459414318, 13.1787643047, 13.3115871777, 13.4444100507, 13.5772329237, 13.7100557967, 13.8428786696, 13.9757015426, 14.1085244156, 14.2413472886, 14.3741701616, 14.5069930345, 14.6398159075, 14.7726387805, 14.9054616535, 15.0382845265, 15.1711073994, 15.3039302724, 15.4367531454, 15.5695760184, 15.7023988914, 15.8352217644, 15.9680446373, 16.1008675103, 16.2336903833, 16.3665132563, 16.4993361293, 16.6321590022, 16.7649818752, 16.8978047482, 17.0306276212, 17.1634504942, 17.2962733671, 17.4290962401, 17.5619191131, 17.6947419861, 17.8275648591, 17.960387732, 18.093210605, 18.226033478, 18.358856351, 18.491679224, 18.6245020969, 18.7573249699, 18.8901478429, 19.0229707159, 19.1557935889, 19.2886164618, 19.4214393348, 19.5542622078, 19.6870850808, 19.8199079538, 19.9527308267, 20.0855536997, 20.2183765727, 20.3511994457, 20.4840223187, 20.6168451916, 20.7496680646, 20.8824909376, 21.0153138106, 21.1481366836, 21.2809595565, 21.4137824295, 21.5466053025, 21.6794281755, 21.8122510485, 21.9450739215, 22.0778967944, 22.2107196674, 22.3435425404, 22.4763654134, 22.6091882864, 22.7420111593, 22.8748340323, 23.0076569053, 23.1404797783, 23.2733026513, 23.4061255242, 23.5389483972, 23.6717712702, 23.8045941432, 23.9374170162, 24.0702398891, 24.2030627621, 24.3358856351, 24.4687085081, 24.6015313811, 24.734354254, 24.867177127, 25.0]) prob = Problem() prob.root = Group() prob.root.add('comp', RayleighCDF(), promotes=['*']) prob.root.add('xbar', IndepVarComp('xbar', 0.0), promotes=['*']) prob.root.add('x', IndepVarComp('x', np.zeros(len(x))), promotes=['*']) prob.setup(check=False) prob['xbar'] = xbar prob['x'] = x check_gradient_unit_test(self, prob, tol=2e-6)
def test_complex_step_around_newton_error(self): prob = Problem() prob.root = SellarDerivativesGrouped() prob.root.deriv_options['type'] = 'cs' prob.root.mda.nl_solver = Newton() with self.assertRaises(RuntimeError) as cm: prob.setup(check=False) msg = "The solver in 'mda' requires derivatives. We " msg += "currently do not support complex step around it." self.assertTrue(msg in str(cm.exception))
def test_message_no_connections(self): p = Problem() p.root = Group() c = p.root.add('comp', Paraboloid()) p.setup(check=False) p.run_once() mystream = StringIO() p.check_partial_derivatives(out_stream=mystream) text = mystream.getvalue() expected = 'Skipping because component has no connected inputs.' self.assertTrue(expected in text)
def test_fd_options_form(self): prob = Problem() prob.root = Group() comp = prob.root.add('comp', Paraboloid()) prob.root.add('p1', IndepVarComp('x', 15.0)) prob.root.add('p2', IndepVarComp('y', 15.0)) prob.root.connect('p1.x', 'comp.x') prob.root.connect('p2.y', 'comp.y') comp.fd_options['force_fd'] = True comp.fd_options['form'] = 'forward' indep_list = ['p1.x'] unknowns_list = ['comp.f_xy'] prob.setup(check=False) prob.run() J = prob.calc_gradient(indep_list, unknowns_list, return_format='dict') assert_rel_error(self, J['comp.f_xy']['p1.x'][0][0], 39.0, 1e-6) # Make sure it gives good result with small stepsize comp.fd_options['form'] = 'backward' J = prob.calc_gradient(['p1.x'], ['comp.f_xy'], return_format='dict') assert_rel_error(self, J['comp.f_xy']['p1.x'][0][0], 39.0, 1e-6) # Make sure it gives good result with small stepsize comp.fd_options['form'] = 'central' J = prob.calc_gradient(['p1.x'], ['comp.f_xy'], return_format='dict') assert_rel_error(self, J['comp.f_xy']['p1.x'][0][0], 39.0, 1e-6) # Now, Make sure we really are going foward and backward comp.fd_options['form'] = 'forward' comp.fd_options['step_size'] = 1e3 J = prob.calc_gradient(['p1.x'], ['comp.f_xy'], return_format='dict') self.assertGreater(J['comp.f_xy']['p1.x'][0][0], 0.0) comp.fd_options['form'] = 'backward' J = prob.calc_gradient(['p1.x'], ['comp.f_xy'], return_format='dict') self.assertLess(J['comp.f_xy']['p1.x'][0][0], 0.0) # Central should get pretty close even for the bad stepsize comp.fd_options['form'] = 'central' J = prob.calc_gradient(['p1.x'], ['comp.f_xy'], return_format='dict') assert_rel_error(self, J['comp.f_xy']['p1.x'][0][0], 39.0, 1e-1)
def test_beam_tutorial_viewmodel_using_data_from_sqlite_case_recorder_file( self): top = Problem() top.root = BeamTutorial() top.driver = ScipyOptimizer() top.driver.options['optimizer'] = 'SLSQP' top.driver.options['tol'] = 1.0e-8 top.driver.options[ 'maxiter'] = 10000 #maximum number of solver iterations top.driver.options['disp'] = False #room length and width bounds top.driver.add_desvar('ivc_rlength.room_length', lower=5.0 * 12.0, upper=50.0 * 12.0) #domain: 1in <= length <= 50ft top.driver.add_desvar('ivc_rwidth.room_width', lower=5.0 * 12.0, upper=30.0 * 12.0) #domain: 1in <= width <= 30ft top.driver.add_objective('d_neg_area.neg_room_area' ) #minimize negative area (or maximize area) top.driver.add_constraint('d_len_minus_wid.length_minus_width', lower=0.0) #room_length >= room_width top.driver.add_constraint('d_deflection.deflection', lower=720.0) #deflection >= 720 top.driver.add_constraint('d_bending.bending_stress_ratio', upper=0.5) #bending < 0.5 top.driver.add_constraint('d_shear.shear_stress_ratio', upper=1.0 / 3.0) #shear < 1/3 tempdir = mkdtemp() case_recorder_filename = "tmp.sql" filename = os.path.join(tempdir, case_recorder_filename) recorder = SqliteRecorder(filename) top.driver.add_recorder(recorder) top.setup(check=False) top.run() view_model(filename, show_browser=False) self.assertTrue(os.path.isfile('partition_tree_n2.html')) os.remove('partition_tree_n2.html')
def test_root_derivs_dict(self): if OPT is None: raise unittest.SkipTest("pyoptsparse is not installed") if OPTIMIZER is None: raise unittest.SkipTest( "pyoptsparse is not providing SNOPT or SLSQP") prob = Problem() prob.root = SellarDerivativesGrouped() prob.driver = pyOptSparseDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.opt_settings['ACC'] = 1e-9 prob.driver.options['print_results'] = False self.recorder.options['record_unknowns'] = True prob.driver.add_desvar('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0])) prob.driver.add_desvar('x', lower=0.0, upper=10.0) prob.driver.add_objective('obj') prob.driver.add_constraint('con1', upper=0.0) prob.driver.add_constraint('con2', upper=0.0) prob.driver.add_recorder(self.recorder) self.recorder.options['record_metadata'] = False self.recorder.options['record_derivs'] = True prob.setup(check=False) prob.run() prob.cleanup() sout = open(self.filename) lines = sout.readlines() self.assertEqual(lines[14].rstrip(), 'Derivatives:') self.assertTrue(' con1 wrt x:' in lines[15]) self.assertTrue(' con1 wrt z:' in lines[16]) self.assertTrue(' con2 wrt x:' in lines[17]) self.assertTrue(' con2 wrt z:' in lines[18]) self.assertTrue(' obj wrt x:' in lines[19]) self.assertTrue(' obj wrt z:' in lines[20]) self.assertTrue('1.784' in lines[20])
def test_simple_implicit_apply(self): prob = Problem() prob.root = Group() prob.root.ln_solver = ScipyGMRES() prob.root.add('comp', SimpleImplicitCompApply()) prob.root.add('p1', IndepVarComp('x', 0.5)) prob.root.connect('p1.x', 'comp.x') prob.setup(check=False) prob.run() # Correct total derivatives (we can do this one manually) J = prob.calc_gradient(['p1.x'], ['comp.y'], mode='fd') assert_rel_error(self, J[0][0], -2.5555511, 1e-6) J = prob.calc_gradient(['p1.x'], ['comp.y'], mode='rev') assert_rel_error(self, J[0][0], -2.5555511, 1e-6) J = prob.calc_gradient(['p1.x'], ['comp.y'], mode='fd') assert_rel_error(self, J[0][0], -2.5555511, 1e-6) # Clean up old FD prob.run() # Partials data = prob.check_partial_derivatives(out_stream=None) #data = prob.check_partial_derivatives() for key1, val1 in iteritems(data): for key2, val2 in iteritems(val1): assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5) assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5) assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5) assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5) assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5) assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5) assert_rel_error(self, data['comp'][('y', 'x')]['J_fwd'][0][0], 1.0, 1e-6) assert_rel_error(self, data['comp'][('y', 'z')]['J_fwd'][0][0], 2.0, 1e-6) assert_rel_error(self, data['comp'][('z', 'x')]['J_fwd'][0][0], 2.66666667, 1e-6) assert_rel_error(self, data['comp'][('z', 'z')]['J_fwd'][0][0], 1.5, 1e-6)
def test_pull_size_from_source(self): raise unittest.SkipTest("setting input size based on src size not supported yet") class Src(ExplicitComponent): def initialize_variables(self): self.add_input('x', 2.0) self.add_output('y1', np.zeros((3, ))) self.add_output('y2', shape=((3, ))) def solve_nonlinear(self, inputs, outputs, resids): x = inputs['x'] outputs['y1'] = x * np.array( [1.0, 2.0, 3.0]) outputs['y2'] = x * np.array( [1.0, 2.0, 3.0]) class Tgt(ExplicitComponent): def initialize_variables(self): self.add_input('x1') self.add_input('x2') self.add_output('y1', 0.0) self.add_output('y2', 0.0) def solve_nonlinear(self, inputs, outputs, resids): x1 = inputs['x1'] x2 = inputs['x2'] outputs['y1'] = np.sum(x1) outputs['y2'] = np.sum(x2) p = Problem() p.root = Group() p.root.add_subsystem('src', Src()) p.root.add_subsystem('tgt', Tgt()) p.root.connect('src.y1', 'tgt.x1') p.root.connect('src.y2', 'tgt.x2') p.setup(check=False) p.run() self.assertEqual(p['tgt.y1'], 12.0) self.assertEqual(p['tgt.y2'], 12.0)
def test_SetupPCModVarSpeed(): data = {} data['control_tsr'] = 8.0 data['control_pitch'] = 1.0 data['Vrated'] = 12.0 data['R'] = 63.0 data['Vfactor'] = 0.7 prob = Problem() prob.root = Group() prob.root.add('comp', SetupPCModVarSpeed(), promotes=['*']) prob = init_IndepVar_add(prob, data) prob.setup(check=False) prob = init_IndepVar_set(prob, data) check_gradient_unit_test(prob)
def test_unsupported_multiple_obj(self): prob = Problem() prob.root = SellarDerivatives() prob.driver = MySimpleDriver() prob.driver.add_desvar('z', lower=-100.0, upper=100.0) prob.driver.add_objective('obj') # Add duplicate objective with self.assertRaises(RuntimeError) as cm: prob.driver.add_objective('x') msg = "Attempted to add multiple objectives to a driver that does not " \ "support multiple objectives." raised_error = str(cm.exception) self.assertEqual(msg, raised_error)
def test_krig_sin(self): prob = Problem() prob.root = TrigMM() prob.setup(check=False) #traning data is just set manually. No connected input needed, since # we're assuming the data is pre-existing prob['sin_mm.train:x'] = np.linspace(0, 10, 20) prob['sin_mm.train:f_x:float'] = np.sin(prob['sin_mm.train:x']) prob['sin_mm.train:f_x:norm_dist'] = np.cos(prob['sin_mm.train:x']) prob['sin_mm.x'] = 2.1 #prediction happens at this value prob.run() assert_rel_error(self, prob['sin_mm.f_x:float'], 0.8632, 1e-3) assert_rel_error(self, prob['sin_mm.f_x:norm_dist'][0], -0.5048, 1e-3)
def test_deriv_options_type_ambiguous(self): prob = Problem() prob.root = Group() comp = prob.root.add('comp', FDpropsComp(type='fd'), promotes=['x2']) comp2 = prob.root.add('comp2', FDpropsComp(type='cs'), promotes=['x2']) prob.root.add('p1', IndepVarComp([('x1', 3.0), ('x2', 3.0)])) prob.root.connect('p1.x1', 'comp.x1') comp.deriv_options['step_size'] = 1.0e-4 try: prob.setup(check=False) except Exception as err: self.assertTrue("The following parameters have the same promoted name, " "'x2', but different 'type' values: [('comp.x2', 'fd'), " "('comp2.x2', 'cs')]" in str(err))
def test_simple_choose_different_alg(self): group = Group() group.add('x_param', IndepVarComp('x', 1.0), promotes=['*']) group.add('mycomp', SimpleCompDerivMatVec(), promotes=['x', 'y']) prob = Problem(impl=impl) prob.root = group prob.root.ln_solver = PetscKSP() prob.root.ln_solver.options['ksp_type'] = 'gmres' prob.setup(check=False) prob.run() J = prob.calc_gradient(['x'], ['y'], mode='fwd', return_format='dict') assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6) J = prob.calc_gradient(['x'], ['y'], mode='rev', return_format='dict') assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6)
def test_plot(self): top = Problem() top.root = Basic() top.setup(check=False) top['loads.P_constant'] = 10 top['des_vars.array_power'] = 300 top['des_vars.power_capacity'] = 420 top.run() fig = make_plot(top) fig.savefig("test_fig.png", format="png", bbox_inches='tight', pad_inches=0) assert os.path.exists("test_fig.png")
def test_double_diamond_model(self): prob = Problem() prob.root = ConvergeDivergeGroups() prob.setup(check=False) prob.run() data = prob.check_total_derivatives(out_stream=None) for key, val in iteritems(data): assert_rel_error(self, val['abs error'][0], 0.0, 1e-5) assert_rel_error(self, val['abs error'][1], 0.0, 1e-5) assert_rel_error(self, val['abs error'][2], 0.0, 1e-5) assert_rel_error(self, val['rel error'][0], 0.0, 1e-5) assert_rel_error(self, val['rel error'][1], 0.0, 1e-5) assert_rel_error(self, val['rel error'][2], 0.0, 1e-5)
def test_sellar_derivs_grouped_precon(self): prob = Problem(impl=impl) prob.root = SellarDerivativesGrouped() prob.root.mda.nl_solver.options['atol'] = 1e-12 prob.root.ln_solver = PetscKSP() prob.root.ln_solver.preconditioner = LinearGaussSeidel() prob.root.mda.ln_solver = DirectSolver() prob.setup(check=False) prob.run() # Just make sure we are at the right answer assert_rel_error(self, prob['y1'], 25.58830273, .00001) assert_rel_error(self, prob['y2'], 12.05848819, .00001) indep_list = ['x', 'z'] unknown_list = ['obj', 'con1', 'con2'] Jbase = {} Jbase['con1'] = {} Jbase['con1']['x'] = -0.98061433 Jbase['con1']['z'] = np.array([-9.61002285, -0.78449158]) Jbase['con2'] = {} Jbase['con2']['x'] = 0.09692762 Jbase['con2']['z'] = np.array([1.94989079, 1.0775421]) Jbase['obj'] = {} Jbase['obj']['x'] = 2.98061392 Jbase['obj']['z'] = np.array([9.61001155, 1.78448534]) J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict') for key1, val1 in Jbase.items(): for key2, val2 in val1.items(): assert_rel_error(self, J[key1][key2], val2, .00001) J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict') for key1, val1 in Jbase.items(): for key2, val2 in val1.items(): assert_rel_error(self, J[key1][key2], val2, .00001)