def test_basic_run(self): prob = Problem(root=ExampleGroup()) prob.setup(check=False) prob.run() self.assertAlmostEqual(prob['G3.C4.y'], 40.)
def test_byobj_run(self): prob = Problem(root=ExampleByObjGroup()) prob.setup(check=False) prob.run() self.assertEqual(prob['G3.C4.y'], 'fooC2C3C4')
def test_driver_records_metadata(self): size = 3 prob = Problem(Group(), impl=impl) G1 = prob.root.add('G1', ParallelGroup()) G1.add('P1', IndepVarComp('x', np.ones(size, float) * 1.0)) G1.add('P2', IndepVarComp('x', np.ones(size, float) * 2.0)) prob.root.add('C1', ABCDArrayComp(size)) prob.root.connect('G1.P1.x', 'C1.a') prob.root.connect('G1.P2.x', 'C1.b') prob.driver.add_recorder(self.recorder) self.recorder.options['record_metadata'] = True prob.setup(check=False) prob.cleanup() expected = ( list(prob.root.params.iteritems()), list(prob.root.unknowns.iteritems()), list(prob.root.resids.iteritems()), ) self.assertMetadataRecorded(expected)
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) self.recorder.close() coordinate = ['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_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) self.recorder.close() 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_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) self.recorder.close() coordinate = ['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_auto_order(self): # this tests the auto ordering when we have a cycle that is smaller # than the full graph. p = Problem(root=Group()) root = p.root C5 = root.add("C5", ExecComp("y=x*2.0")) C6 = root.add("C6", ExecComp("y=x*2.0")) C1 = root.add("C1", ExecComp("y=x*2.0")) C2 = root.add("C2", ExecComp("y=x*2.0")) C3 = root.add("C3", ExecComp(["y=x*2.0", "y2=x2+1.0"])) C4 = root.add("C4", ExecComp(["y=x*2.0", "y2=x2+1.0"])) P1 = root.add("P1", ParamComp("x", 1.0)) root.connect("P1.x", "C1.x") root.connect("C1.y", "C2.x") root.connect("C2.y", "C4.x") root.connect("C4.y", "C5.x") root.connect("C5.y", "C6.x") root.connect("C5.y", "C3.x2") root.connect("C6.y", "C3.x") root.connect("C3.y", "C4.x2") p.setup(check=False) self.assertEqual(p.root.list_auto_order(), ["P1", "C1", "C2", "C4", "C5", "C6", "C3"])
def test_metadata_recorded(self): prob = Problem(impl=impl) prob.root = FanInGrouped() rec = DumpRecorder(out=self.filename) rec.options['record_metadata'] = True rec.options['includes'] = ['p1.x1', 'p2.x2', 'comp3.y'] prob.driver.add_recorder(rec) prob.setup(check=False) rec.close() with open(self.expected_filename, 'r') as dumpfile: params = iteritems(prob.root.params) unknowns = iteritems(prob.root.unknowns) self.assertEqual("Metadata:\n", dumpfile.readline()) self.assertEqual("Params:\n", dumpfile.readline()) for name, metadata in params: fmat = " {0}: {1}\n".format(name, metadata) self.assertEqual(fmat, dumpfile.readline()) self.assertEqual("Unknowns:\n", dumpfile.readline()) for name, metadata in unknowns: fmat = " {0}: {1}\n".format(name, metadata) self.assertEqual(fmat, dumpfile.readline())
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) self.recorder.close() coordinate = ['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_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: # pragma: no cover self.fail("Exception expected")
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_direct_solver_group(self): """ Test the direct solver on a group. """ prob = Problem(model=TestImplicitGroup(lnSolverClass=DirectSolver)) prob.setup(check=False) # Conclude setup but don't run model. prob.final_setup() prob.model.run_linearize() d_inputs, d_outputs, d_residuals = prob.model.get_linear_vectors() d_residuals.set_const(1.0) d_outputs.set_const(0.0) prob.model.run_solve_linear(['linear'], 'fwd') result = d_outputs._data assert_rel_error(self, result[1], prob.model.expected_solution[0], 1e-15) assert_rel_error(self, result[5], prob.model.expected_solution[1], 1e-15) d_outputs.set_const(1.0) d_residuals.set_const(0.0) prob.model.run_solve_linear(['linear'], 'rev') result = d_residuals._data assert_rel_error(self, result[1], prob.model.expected_solution[0], 1e-15) assert_rel_error(self, result[5], prob.model.expected_solution[1], 1e-15)
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) self.recorder.close() coordinate = ['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_noncontiguous_idxs(self): # take even input indices in 0 rank and odd ones in 1 rank size = 11 p = Problem(root=Group(), impl=impl) top = p.root top.add("C1", InOutArrayComp(size)) top.add("C2", DistribNoncontiguousComp(size)) top.add("C3", DistribGatherComp(size)) top.connect('C1.outvec', 'C2.invec') top.connect('C2.outvec', 'C3.invec') p.setup(check=False) top.C1.params['invec'] = np.array(range(size), float) p.run() if MPI: if self.comm.rank == 0: self.assertTrue(all(top.C2.unknowns['outvec'] == np.array(list(take_nth(0, 2, range(size))), 'f')*4)) else: self.assertTrue(all(top.C2.unknowns['outvec'] == np.array(list(take_nth(1, 2, range(size))), 'f')*4)) full_list = list(take_nth(0, 2, range(size))) + list(take_nth(1, 2, range(size))) self.assertTrue(all(top.C3.unknowns['outvec'] == np.array(full_list, 'f')*4)) else: self.assertTrue(all(top.C2.unknowns['outvec']==top.C1.unknowns['outvec']*2.)) self.assertTrue(all(top.C3.unknowns['outvec']==top.C2.unknowns['outvec']))
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: # pragma: no cover self.fail("Exception expected")
def test_conflicting_connections(self): # verify we get an error if we have conflicting implicit and explicit connections root = Group() # promoting G1.x will create an implicit connection to G3.x # this is a conflict because G3.x (aka G3.C4.x) is already connected # to G3.C3.x G2 = root.add('G2', Group(), promotes=['x']) # BAD PROMOTE G2.add('C1', ParamComp('x', 5.), promotes=['x']) G1 = G2.add('G1', Group(), promotes=['x']) G1.add('C2', ExecComp('y=x*2.0'), promotes=['x']) G3 = root.add('G3', Group(), promotes=['x']) G3.add('C3', ExecComp('y=x*2.0')) G3.add('C4', ExecComp('y=x*2.0'), promotes=['x']) root.connect('G2.G1.C2.y', 'G3.C3.x') G3.connect('C3.y', 'x') prob = Problem(root) try: prob.setup(check=False) except Exception as error: msg = "Target 'G3.C4.x' is connected to multiple unknowns: ['G2.C1.x', 'G3.C3.y']" self.assertEqual(text_type(error), msg) else: self.fail("Error expected")
def test_auto_order(self): # this tests the auto ordering when we have a cycle that is smaller # than the full graph. p = Problem(root=Group()) root = p.root C5 = root.add("C5", ExecComp('y=x*2.0')) C6 = root.add("C6", ExecComp('y=x*2.0')) C1 = root.add("C1", ExecComp('y=x*2.0')) C2 = root.add("C2", ExecComp('y=x*2.0')) C3 = root.add("C3", ExecComp(['y=x*2.0','y2=x2+1.0'])) C4 = root.add("C4", ExecComp(['y=x*2.0','y2=x2+1.0'])) P1 = root.add("P1", IndepVarComp('x', 1.0)) root.connect('P1.x', 'C1.x') root.connect('C1.y', 'C2.x') root.connect('C2.y', 'C4.x') root.connect('C4.y', 'C5.x') root.connect('C5.y', 'C6.x') root.connect('C5.y', 'C3.x2') root.connect('C6.y', 'C3.x') root.connect('C3.y', 'C4.x2') p.setup(check=False) self.assertEqual(p.root.list_auto_order(), ['P1','C1','C2','C4','C5','C6','C3'])
class CycleComponentTestCase(unittest.TestCase): def setUp(self): '''Initialization function called before every test function''' self.g = Group() self.comp1 = DummyComp() self.comp2 = DummyComp() self.g.add('comp1', self.comp1) self.g.add('comp2', self.comp2) self.p = Problem(root=self.g) self.p.setup() def tearDown(self): '''Function called after every test function''' self.g = None self.p = None def test_copy_flow(self): self.comp1.params['flow:in:W'] = 100.0 self.comp1.params['flow:in:Tt'] = 518.0 self.comp1.params['flow:in:Pt'] = 15.0 CycleComponent.copy_from(self.comp1, 'flow', self.comp2, 'flow') self.p.run() TOL = 0.0001 assert_rel_error(self, self.comp2.unknowns['flow:out:Tt'], 518.0, TOL) assert_rel_error(self, self.comp2.unknowns['flow:out:Pt'], 15.0, TOL)
def test_cycle(self): prob = Problem(root=Group()) root = prob.root G1 = root.add("G1", Group()) G2 = G1.add("G2", Group()) C1 = G2.add("C1", ExecComp("y=x*2.0")) C2 = G2.add("C2", ExecComp("y=x*2.0")) C3 = G2.add("C3", ExecComp("y=x*2.0")) G2.connect("C1.y", "C3.x") G2.connect("C3.y", "C2.x") G2.connect("C2.y", "C1.x") # force wrong order G2.set_order(["C1", "C2", "C3"]) stream = cStringIO() checks = prob.setup(out_stream=stream) auto = G2.list_auto_order() self.assertTrue(auto == ["C1", "C3", "C2"] or auto == ["C3", "C2", "C1"] or auto == ["C2", "C1", "C3"]) self.assertTrue("Group 'G1.G2' has the following cycles: [['C1', 'C2', 'C3']]" in stream.getvalue()) oo = checks["out_of_order"] self.assertEqual(oo[0][0], "G1.G2") expected = {("C2", "C3"): "C1", ("C3",): "C2", ("C2",): "C1"} for node, afters in oo[0][1]: self.assertEqual(node, expected[tuple(afters)])
def test_model_viewer_has_correct_data_from_problem(self): """ Verify that the correct model structure data exists when stored as compared to the expected structure, using the SellarStateConnection model. """ p = Problem(model=SellarStateConnection()) p.setup(check=False) model_viewer_data = _get_viewer_data(p) # check expected model tree self.assertDictEqual(model_viewer_data['tree'], self.expected_tree) # check expected system pathnames pathnames = model_viewer_data['sys_pathnames_list'] self.assertListEqual(sorted(pathnames), self.expected_pathnames) # check expected connections, after mapping cycle_arrows indices back to pathnames connections = model_viewer_data['connections_list'] for conn in connections: if 'cycle_arrows' in conn: cycle_arrows = [] for src, tgt in conn['cycle_arrows']: cycle_arrows.append(' '.join([pathnames[src], pathnames[tgt]])) conn['cycle_arrows'] = sorted(cycle_arrows) self.assertListEqual(connections, self.expected_conns) # check expected abs2prom map self.assertDictEqual(model_viewer_data['abs2prom'], self.expected_abs2prom)
def test_conflicting_promotions(self): # verify we get an error if we have conflicting promotions root = Group() # promoting G1.x will create an implicit connection to G3.x # this is a conflict because G3.x (aka G3.C4.x) is already connected # to G3.C3.x G2 = root.add('G2', Group()) G2.add('C1', ParamComp('x', 5.), promotes=['x']) G1 = G2.add('G1', Group(), promotes=['x']) G1.add('C2', ExecComp('y=x*2.0'), promotes=['x']) G3 = root.add('G3', Group(), promotes=['x']) G3.add('C3', ExecComp('y=x*2.0'), promotes=['y']) # promoting y G3.add('C4', ExecComp('y=x*2.0'), promotes=['x', 'y']) # promoting y again.. BAD prob = Problem(root) try: prob.setup(check=False) except Exception as error: msg = "Promoted name 'G3.y' matches multiple unknowns: ['G3.C3.y', 'G3.C4.y']" self.assertEqual(text_type(error), msg) else: self.fail("Error expected")
def test_inp_inp_promoted_w_explicit_src(self): p = Problem(root=Group()) root = p.root G1 = root.add("G1", Group()) G2 = G1.add("G2", Group(), promotes=['x']) C1 = G2.add("C1", ExecComp('y=x*2.0')) C2 = G2.add("C2", ParamComp('x', 1.0), promotes=['x']) G3 = root.add("G3", Group()) G4 = G3.add("G4", Group(), promotes=['x']) C3 = G4.add("C3", ExecComp('y=x*2.0'), promotes=['x']) C4 = G4.add("C4", ExecComp('y=x*2.0'), promotes=['x']) p.root.connect('G1.x', 'G3.x') p.setup(check=False) self.assertEqual(p._dangling['G1.G2.C1.x'], set(['G1.G2.C1.x'])) self.assertEqual(len(p._dangling), 1) # setting promoted name will set the value into the unknowns, but will # not propagate it to the params. That will happen during run(). p['G1.x'] = 999. self.assertEqual(p.root.G3.G4.C3.params['x'], 0.) self.assertEqual(p.root.G3.G4.C4.params['x'], 0.) p.run() self.assertEqual(p.root.G3.G4.C3.params['x'], 999.) self.assertEqual(p.root.G3.G4.C4.params['x'], 999.)
def test_inp_inp_promoted_no_src(self): p = Problem(root=Group()) root = p.root G1 = root.add("G1", Group()) G2 = G1.add("G2", Group()) C1 = G2.add("C1", ExecComp('y=x*2.0')) C2 = G2.add("C2", ExecComp('y=x*2.0')) G3 = root.add("G3", Group()) G4 = G3.add("G4", Group()) C3 = G4.add("C3", ExecComp('y=x*2.0'), promotes=['x']) C4 = G4.add("C4", ExecComp('y=x*2.0'), promotes=['x']) stream = cStringIO() checks = p.setup(out_stream=stream) self.assertEqual(checks['dangling_params'], ['G1.G2.C1.x', 'G1.G2.C2.x', 'G3.G4.x']) self.assertEqual(checks['no_connect_comps'], ['G1.G2.C1', 'G1.G2.C2', 'G3.G4.C3', 'G3.G4.C4']) self.assertEqual(p._dangling['G3.G4.x'], set(['G3.G4.C3.x','G3.G4.C4.x'])) # setting promoted name should set both params mapped to that name since the # params are dangling. p['G3.G4.x'] = 999. self.assertEqual(p.root.G3.G4.C3.params['x'], 999.) self.assertEqual(p.root.G3.G4.C4.params['x'], 999.)
def test_simple(self): prob = Problem(Group(), impl=impl) size = 5 A1 = prob.root.add('A1', ParamComp('a', np.zeros(size, float))) B1 = prob.root.add('B1', ParamComp('b', np.zeros(size, float))) B2 = prob.root.add('B2', ParamComp('b', np.zeros(size, float))) S1 = prob.root.add('S1', ParamComp('s', '')) L1 = prob.root.add('L1', ParamComp('l', [])) C1 = prob.root.add('C1', ABCDArrayComp(size)) C2 = prob.root.add('C2', ABCDArrayComp(size)) prob.root.connect('A1.a', 'C1.a') prob.root.connect('B1.b', 'C1.b') # prob.root.connect('S1:s', 'C1.in_string') # prob.root.connect('L1:l', 'C1.in_list') prob.root.connect('C1.c', 'C2.a') prob.root.connect('B2.b', 'C2.b') # prob.root.connect('C1.out_string', 'C2.in_string') # prob.root.connect('C1.out_list', 'C2.in_list') prob.setup(check=False) prob['A1.a'] = np.ones(size, float) * 3.0 prob['B1.b'] = np.ones(size, float) * 7.0 prob['B2.b'] = np.ones(size, float) * 5.0 prob.run() self.assertTrue(all(prob['C2.a']==np.ones(size, float)*10.)) self.assertTrue(all(prob['C2.b']==np.ones(size, float)*5.)) self.assertTrue(all(prob['C2.c']==np.ones(size, float)*15.)) self.assertTrue(all(prob['C2.d']==np.ones(size, float)*5.))
def test_parallel_diamond(self): size = 3 prob = Problem(Group(), impl=impl) root = prob.root root.add('P1', ParamComp('x', np.ones(size, float) * 1.1)) G1 = root.add('G1', ParallelGroup()) G1.add('C1', ABCDArrayComp(size)) G1.add('C2', ABCDArrayComp(size)) root.add('C3', ABCDArrayComp(size)) root.connect('P1.x', 'G1.C1.a') root.connect('P1.x', 'G1.C2.b') root.connect('G1.C1.c', 'C3.a') root.connect('G1.C2.d', 'C3.b') prob.setup(check=False) prob.run() if not MPI or self.comm.rank == 0: assert_rel_error(self, prob.root.G1.C1.unknowns['c'], np.ones(size)*2.1, 1.e-10) assert_rel_error(self, prob.root.G1.C1.unknowns['d'], np.ones(size)*.1, 1.e-10) assert_rel_error(self, prob.root.C3.params['a'], np.ones(size)*2.1, 1.e-10) assert_rel_error(self, prob.root.C3.params['b'], np.ones(size)*-.1, 1.e-10) if not MPI or self.comm.rank == 1: assert_rel_error(self, prob.root.G1.C2.unknowns['c'], np.ones(size)*2.1, 1.e-10) assert_rel_error(self, prob.root.G1.C2.unknowns['d'], np.ones(size)*-.1, 1.e-10)
def test_direct_solver_group(self): """ Test the direct solver on a group. """ prob = Problem(model=TestImplicitGroup(lnSolverClass=DirectSolver)) prob.setup(check=False) # Set this to False because we have matrix-free component(s). prob.model.linear_solver.options['assemble_jac'] = False # Conclude setup but don't run model. prob.final_setup() prob.model.run_linearize() d_inputs, d_outputs, d_residuals = prob.model.get_linear_vectors() d_residuals.set_const(1.0) d_outputs.set_const(0.0) prob.model.run_solve_linear(['linear'], 'fwd') result = d_outputs._data assert_rel_error(self, result, prob.model.expected_solution, 1e-15) d_outputs.set_const(1.0) d_residuals.set_const(0.0) prob.model.run_solve_linear(['linear'], 'rev') result = d_residuals._data assert_rel_error(self, result, prob.model.expected_solution, 1e-15)
def test_driver_records_metadata(self): size = 3 prob = Problem(Group(), impl=impl) G1 = prob.root.add("G1", ParallelGroup()) G1.add("P1", IndepVarComp("x", np.ones(size, float) * 1.0)) G1.add("P2", IndepVarComp("x", np.ones(size, float) * 2.0)) prob.root.add("C1", ABCDArrayComp(size)) prob.root.connect("G1.P1.x", "C1.a") prob.root.connect("G1.P2.x", "C1.b") prob.driver.add_recorder(self.recorder) self.recorder.options["record_metadata"] = True prob.setup(check=False) self.recorder.close() expected = ( list(prob.root.params.iteritems()), list(prob.root.unknowns.iteritems()), list(prob.root.resids.iteritems()), ) self.assertMetadataRecorded(expected)
def test_root_solver_doesnt_record_metadata(self): prob = Problem() prob.root = ConvergeDiverge() prob.root.nl_solver.add_recorder(self.recorder) self.recorder.options['record_metadata'] = False prob.setup(check=False) self.recorder.close() self.assertMetadataRecorded(None)
def test_subsolver_doesnt_record_metadata(self): prob = Problem() prob.root = ExampleGroup() prob.root.G2.G1.nl_solver.add_recorder(self.recorder) self.recorder.options['record_metadata'] = False prob.setup(check=False) self.recorder.close() self.assertMetadataRecorded(None)
def test_array(self): prob = Problem(root=Group()) C1 = prob.root.add('C1', ExecComp('y=x[1]', x=np.array([1.,2.,3.]), y=0.0)) self.assertTrue('x' in C1._params_dict) self.assertTrue('y' in C1._unknowns_dict) prob.setup(check=False) prob.run() assert_rel_error(self, C1.unknowns['y'], 2.0, 0.00001)
def test_unconnected_param_access_with_promotes(self): prob = Problem(root=Group()) G1 = prob.root.add('G1', Group()) G2 = G1.add('G2', Group(), promotes=['x']) C1 = G2.add('C1', ExecComp(['y=2.0*x', 'z=x*x-2.0']), promotes=['x']) C2 = G2.add('C2', ExecComp(['y=2.0*x', 'z=x*x-2.0'])) G2.connect('C1.y', 'C2.x') # ignore warning about the unconnected param with warnings.catch_warnings(record=True) as w: warnings.simplefilter("ignore") prob.setup(check=False) prob.run() # still must use absolute naming to find params even if they're # promoted. Promoted names for params can refer to more than one param. C1.params['x'] = 2. self.assertEqual(prob['G1.x'], 2.0) self.assertEqual(prob.root.G1.G2.C1.params['x'], 2.0) prob['G1.x'] = 99. self.assertEqual(C1.params['x'], 99.) prob['G1.x'] = 12. self.assertEqual(C1.params['x'], 12.) prob['G1.x'] = 17. self.assertEqual(prob.root.G1.G2.C1.params['x'], 17.0) prob.run()
def test_index_error_messages_con(self): prob = Problem() prob.root = Group() prob.root.fd_options['force_fd'] = True prob.root.ln_solver.options['mode'] = 'auto' prob.root.add('myparams', ParamComp('x', np.zeros(4))) prob.root.add('rosen', Rosenbrock(4)) prob.root.connect('myparams.x', 'rosen.x') prob.driver = MySimpleDriver() prob.driver.add_param('myparams.x') prob.driver.add_constraint('rosen.xxx', indices=[4]) prob.setup(check=False) # Make sure we can't do this with self.assertRaises(IndexError) as cm: prob.run() msg = "Index for constraint 'rosen.xxx' is out of bounds. " msg += "Requested index: [4], " msg += "Parameter shape: (4,)." raised_error = str(cm.exception) raised_error = raised_error.replace('(4L,', '(4,') self.assertEqual(msg, raised_error)
def test_fd_skip_keys(self): prob = Problem() root = prob.root = Group() comp = Component() comp.add_param('x', 0.) comp.add_param('y', 0.) comp.add_output('z', 0.) comp.solve_nonlinear = lambda p, u, r: u.__setitem__('z', 1.) comp._get_fd_params = lambda: ['x'] comp.jacobian = lambda a, b, c: {('z', 'x'): 0.} root.add('comp', comp, promotes=['x', 'y']) root.add('px', ParamComp('x', 0.), promotes=['*']) root.add('py', ParamComp('y', 0.), promotes=['*']) prob.setup(check=False) prob.run() try: prob.check_partial_derivatives(out_stream=None) except KeyError as err: self.fail('KeyError raised: {0}'.format(str(err)))
def test_direct_solver_comp(self): """ Test the direct solver on a component. """ for jac in [None, 'csc', 'dense']: prob = Problem(model=ImplComp4Test()) prob.model.nonlinear_solver = NewtonSolver(solve_subsystems=False) if jac in ('csc', 'dense'): prob.model.options['assembled_jac_type'] = jac prob.model.linear_solver = DirectSolver(assemble_jac=jac in ('csc','dense')) prob.set_solver_print(level=0) prob.setup() prob.run_model() assert_near_equal(prob['y'], [-1., 1.]) d_inputs, d_outputs, d_residuals = prob.model.get_linear_vectors() d_residuals.set_val(2.0) d_outputs.set_val(0.0) prob.model.run_solve_linear(['linear'], 'fwd') result = d_outputs._data assert_near_equal(result, [-2., 2.]) d_outputs.set_val(2.0) d_residuals.set_val(0.0) prob.model.run_solve_linear(['linear'], 'rev') result = d_residuals._data assert_near_equal(result, [2., -2.])
def test_model_viewer_has_correct_data_from_problem(self): """ Verify that the correct model structure data exists when stored as compared to the expected structure, using the SellarStateConnection model. """ p = Problem() p.model = SellarStateConnection() p.setup(check=False) model_viewer_data = _get_viewer_data(p) tree_json = json.dumps(model_viewer_data['tree']) conns_json = json.dumps(model_viewer_data['connections_list']) self.assertEqual(self.expected_tree_json, tree_json) self.assertEqual(self.expected_conns_json, conns_json)
def test_variable_access(self): prob = Problem(root=ExampleGroup()) # set with a different shaped array try: prob['G2.C1.x'] except Exception as err: msg = "'unknowns' has not been initialized, setup() must be called before 'G2.C1.x' can be accessed" self.assertEqual(text_type(err), msg) else: self.fail('Exception expected') prob.setup(check=False) self.assertEqual(prob['G2.C1.x'], 5.) # default output from ParamComp self.assertEqual(prob['G2.G1.C2.y'], 5.5) # output from ExecComp self.assertEqual(prob.root.G3.C3.params['x'], 0.) # initial value for a parameter self.assertEqual(prob.root.G2.G1.C2.params['x'], 0.) # initial value for a parameter prob = Problem(root=ExampleGroupWithPromotes()) prob.setup(check=False) self.assertEqual(prob.root.G2.G1.C2.params['x'], 0.) # initial value for a parameter # __setitem__ prob['G2.G1.C2.y'] = 99. self.assertEqual(prob['G2.G1.C2.y'], 99.)
def test_fd_params(self): # tests retrieval of a list of any internal params whose source is either # a ParamComp or is outside of the Group prob = Problem(root=ExampleGroup()) prob.setup(check=False) root = prob.root self.assertEqual(root._get_fd_params(), ['G2.G1.C2.x']) self.assertEqual(root.G2._get_fd_params(), ['G1.C2.x']) self.assertEqual(root.G2.G1._get_fd_params(), ['C2.x']) self.assertEqual(root.G3._get_fd_params(), ['C3.x']) self.assertEqual(root.G3.C3._get_fd_params(), ['x']) self.assertEqual(root.G2.G1.C2._get_fd_params(), ['x'])
def test_solver_debug_print(self, name, solver): 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() nl = model.circuit.nonlinear_solver = solver() nl.options['debug_print'] = True # suppress solver output for test nl.options['iprint'] = model.circuit.linear_solver.options['iprint'] = -1 # For Broydensolver, don't calc Jacobian try: nl.options['compute_jacobian'] = False except KeyError: pass # set some poor initial guesses so that we don't converge p['circuit.n1.V'] = 10. p['circuit.n2.V'] = 1e-3 opts = {} # formatting has changed in numpy 1.14 and beyond. if LooseVersion(np.__version__) >= LooseVersion("1.14"): opts["legacy"] = '1.13' with printoptions(**opts): # run the model and check for expected output file output = run_model(p) expected_output = '\n'.join([ self.expected_data, "Inputs and outputs at start of iteration " "have been saved to '%s'.\n" % self.filename ]) self.assertEqual(output, expected_output) with open(self.filename, 'r') as f: self.assertEqual(f.read(), self.expected_data)
def test_solver_record(self): prob = Problem() prob.root = ConvergeDiverge() prob.root.nl_solver.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) self.recorder.close() coordinate = ['Driver', (1,), "root", (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) ] 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) ] 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), expected_params, expected_unknowns, expected_resids),), self.eps)
def test_invalid_unit(self): prob = Problem() prob.root = Group() prob.root.add( 'uc', UnitComp(shape=1, param_name='in', out_name='out', units='junk')) prob.root.add('pc', ParamComp('x', 0., units='ft')) prob.root.connect('pc.x', 'uc.in') with self.assertRaises(ValueError) as cm: prob.setup(check=False) expected_msg = "no unit named 'junk' is defined" self.assertEqual(expected_msg, str(cm.exception))
def test_auto_order2(self): # this tests the auto ordering when we have a cycle that is the full graph. p = Problem(root=Group()) root = p.root C1 = root.add("C1", ExecComp('y=x*2.0')) C2 = root.add("C2", ExecComp('y=x*2.0')) C3 = root.add("C3", ExecComp('y=x*2.0')) root.connect('C1.y', 'C3.x') root.connect('C3.y', 'C2.x') root.connect('C2.y', 'C1.x') p.setup(check=False) self.assertEqual(p.root.list_auto_order(), ['C1', 'C3', 'C2'])
def test_incompatible_units(self): prob = Problem() prob.root = Group() prob.root.add( 'uc', UnitComp(shape=1, param_name='in', out_name='out', units='degC')) prob.root.add('pc', ParamComp('x', 0., units='ft')) prob.root.connect('pc.x', 'uc.in') with self.assertRaises(TypeError) as cm: prob.setup(check=False) expected_msg = "Unit 'ft' in source 'pc.x' is incompatible with unit 'degC' in target 'uc.in'." self.assertEqual(expected_msg, str(cm.exception))
def test_fd_unknowns(self): # tests retrieval of a list of any internal unknowns with ParamComp # variables filtered out. prob = Problem(root=ExampleGroup()) prob.setup(check=False) root = prob.root self.assertEqual(root._get_fd_unknowns(), ['G2.G1.C2.y', 'G3.C3.y', 'G3.C4.y']) self.assertEqual(root.G2._get_fd_unknowns(), ['G1.C2.y']) self.assertEqual(root.G2.G1._get_fd_unknowns(), ['C2.y']) self.assertEqual(root.G3._get_fd_unknowns(), ['C3.y', 'C4.y']) self.assertEqual(root.G3.C3._get_fd_unknowns(), ['y']) self.assertEqual(root.G2.G1.C2._get_fd_unknowns(), ['y'])
def test_model_viewer_has_correct_data_from_problem(self): """ Verify that the correct model structure data exists when stored as compared to the expected structure, using the SellarStateConnection model. """ p = Problem() p.model = SellarStateConnection() p.setup(check=False) model_viewer_data = _get_viewer_data(p) self.assertDictEqual(model_viewer_data['tree'], self.expected_tree) self.assertListEqual(model_viewer_data['connections_list'], self.expected_conns) self.assertDictEqual(model_viewer_data['abs2prom'], self.expected_abs2prom)
def test_direct_solver_comp(self): """ Test the direct solver on a component. """ for jac in ['dict', 'coo', 'csr', 'csc', 'dense']: prob = Problem(model=ImplComp4Test()) prob.model.nonlinear_solver = NewtonSolver() prob.model.linear_solver = DirectSolver() prob.set_solver_print(level=0) if jac == 'dict': pass elif jac == 'csr': prob.model.jacobian = CSRJacobian() elif jac == 'csc': prob.model.jacobian = CSCJacobian() elif jac == 'coo': prob.model.jacobian = COOJacobian() elif jac == 'dense': prob.model.jacobian = DenseJacobian() prob.setup(check=False) if jac == 'coo': with self.assertRaises(Exception) as context: prob.run_model() self.assertEqual( str(context.exception), "Direct solver is not compatible with matrix type COOMatrix in system ''." ) continue prob.run_model() assert_rel_error(self, prob['y'], [-1., 1.]) d_inputs, d_outputs, d_residuals = prob.model.get_linear_vectors() d_residuals.set_const(2.0) d_outputs.set_const(0.0) prob.model.run_solve_linear(['linear'], 'fwd') result = d_outputs.get_data() assert_rel_error(self, result, [-2., 2.]) d_outputs.set_const(2.0) d_residuals.set_const(0.0) prob.model.run_solve_linear(['linear'], 'rev') result = d_residuals.get_data() assert_rel_error(self, result, [2., -2.])
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) self.recorder.close() 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_too_many_procs(self): prob = Problem(Group(), impl=impl) size = 5 A1 = prob.root.add('A1', ParamComp('a', np.zeros(size, float))) C1 = prob.root.add('C1', ABCDArrayComp(size)) try: prob.setup(check=False) except Exception as err: self.assertEqual( str(err), "This problem was given 2 MPI processes, " "but it requires between 1 and 1.") else: if MPI: self.fail("Exception expected")
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.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) param_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(param_list, unknown_list, mode='fwd', return_format='dict') print(J) #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(param_list, unknown_list, mode='rev', return_format='dict') print(J) #for key1, val1 in Jbase.items(): #for key2, val2 in val1.items(): #assert_rel_error(self, J[key1][key2], val2, .00001) prob.root.fd_options['form'] = 'central' J = prob.calc_gradient(param_list, unknown_list, mode='fd', return_format='dict') print(J) for key1, val1 in Jbase.items(): for key2, val2 in val1.items(): assert_rel_error(self, J[key1][key2], val2, .00001)
def test_record_derivs_lists(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() hdf = h5py.File(self.filename, 'r') deriv_group = hdf['rank0:SLSQP|1']['Derivs'] self.assertEqual(deriv_group.attrs['success'], 1) self.assertEqual(deriv_group.attrs['msg'], '') J1 = deriv_group['Derivatives'] assert_rel_error(self, J1[0][0], 9.61001155, .00001) assert_rel_error(self, J1[0][1], 1.78448534, .00001) assert_rel_error(self, J1[0][2], 2.98061392, .00001) assert_rel_error(self, J1[1][0], -9.61002285, .00001) assert_rel_error(self, J1[1][1], -0.78449158, .00001) assert_rel_error(self, J1[1][2], -0.98061433, .00001) assert_rel_error(self, J1[2][0], 1.94989079, .00001) assert_rel_error(self, J1[2][1], 1.0775421, .00001) assert_rel_error(self, J1[2][2], 0.09692762, .00001) hdf.close()
def test_view_model_set_title(self): """ Test that an n2 html file is generated from a Problem. """ p = Problem() p.model = SellarStateConnection() p.setup() view_model(p, outfile=self.problem_html_filename, show_browser=DEBUG, title="Sellar State Connection") # Check that the html file has been created and has something in it. self.assertTrue(os.path.isfile(self.problem_html_filename), (self.problem_html_filename + " is not a valid file.")) self.assertTrue( 'OpenMDAO Model Hierarchy and N2 diagram: Sellar State Connection' \ in open(self.problem_html_filename).read() )
def test_solver_record(self): size = 3 prob = Problem(Group(), impl=impl) G1 = prob.root.add('G1', ParallelGroup()) G1.add('P1', IndepVarComp('x', np.ones(size, float) * 1.0)) G1.add('P2', IndepVarComp('x', np.ones(size, float) * 2.0)) prob.root.add('C1', ABCDArrayComp(size)) prob.root.connect('G1.P1.x', 'C1.a') prob.root.connect('G1.P2.x', 'C1.b') prob.root.nl_solver.add_recorder(self.recorder) self.recorder.options['record_params'] = True self.recorder.options['record_resids'] = True prob.setup(check=False) t0, t1 = run(prob) self.recorder.close() coordinate = ['Driver', (1, ), "root", (1, )] expected_params = [ ("C1.a", [1.0, 1.0, 1.0]), ("C1.b", [2.0, 2.0, 2.0]), ] expected_unknowns = [ ("G1.P1.x", np.array([1.0, 1.0, 1.0])), ("G1.P2.x", np.array([2.0, 2.0, 2.0])), ("C1.c", np.array([3.0, 3.0, 3.0])), ("C1.d", np.array([-1.0, -1.0, -1.0])), ("C1.out_string", "_C1"), ("C1.out_list", [1.5]), ] expected_resids = [ ("G1.P1.x", np.array([0.0, 0.0, 0.0])), ("G1.P2.x", np.array([0.0, 0.0, 0.0])), ("C1.c", np.array([0.0, 0.0, 0.0])), ("C1.d", np.array([0.0, 0.0, 0.0])), ("C1.out_string", ""), ("C1.out_list", []), ] self.assertIterationDataRecorded( ((coordinate, (t0, t1), expected_params, expected_unknowns, expected_resids), ), self.eps, prob.root)
def setup_sellar_grouped_model(self): self.prob = Problem() model = self.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']) mda = model.add_subsystem('mda', Group(), promotes=['x', 'z', 'y1', 'y2']) mda.linear_solver = ScipyIterativeSolver() mda.add_subsystem('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1', 'y2']) mda.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, y1=0.0, y2=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']) mda.nonlinear_solver = NonlinearBlockGS() model.linear_solver = ScipyIterativeSolver() 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)
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_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_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_simple_array_comp(self): prob = Problem() root = prob.root = Group() root.add('p1', ParamComp('x', np.zeros([2])), promotes=['*']) root.add('comp', SimpleArrayComp(), promotes=['*']) root.add('con', ExecComp('c = y - 20.0', c=np.array([0.0, 0.0]), y=np.array([0.0, 0.0])), promotes=['*']) root.add('obj', ExecComp('o = y[0]', y=np.array([0.0, 0.0])), promotes=['*']) prob.driver = pyOptSparseDriver() prob.driver.add_param('x', low=-50.0, high=50.0) prob.driver.add_objective('o') prob.driver.add_constraint('c', ctype='eq') prob.setup(check=False) prob.run() obj = prob['o'] assert_rel_error(self, obj, 20.0, 1e-6)
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_simple_array_comp2D(self): prob = Problem() root = prob.root = Group() root.add('p1', ParamComp('x', np.zeros((2, 2))), promotes=['*']) root.add('comp', ArrayComp2D(), promotes=['*']) root.add('con', ExecComp('c = y - 20.0', c=np.zeros((2, 2)), y=np.zeros((2, 2))), promotes=['*']) root.add('obj', ExecComp('o = y[0, 0]', y=np.zeros((2, 2))), promotes=['*']) prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.add_param('x', low=-50.0, high=50.0) prob.driver.add_objective('o') prob.driver.add_constraint('c', ctype='eq') prob.driver.options['disp'] = False prob.setup(check=False) prob.run() obj = prob['o'] assert_rel_error(self, obj, 20.0, 1e-6)
def test_metadata_recorded(self): prob = Problem(impl=impl) prob.root = FanInGrouped() rec = DumpRecorder(out=self.filename) rec.options['record_metadata'] = True rec.options['includes'] = ['p1.x1', 'p2.x2', 'comp3.y'] prob.driver.add_recorder(rec) prob.setup(check=False) prob.cleanup() with open(self.expected_filename, 'r') as dumpfile: params = iteritems(prob.root.params) unknowns = iteritems(prob.root.unknowns) self.assertEqual("Metadata:\n", dumpfile.readline()) self.assertEqual("Params:\n", dumpfile.readline()) for name, metadata in params: fmat = " {0}: {1}\n".format(name, metadata) self.assertEqual(fmat, dumpfile.readline()) self.assertEqual("Unknowns:\n", dumpfile.readline()) for name, metadata in unknowns: fmat = " {0}: {1}\n".format(name, metadata) self.assertEqual(fmat, dumpfile.readline())
def test_simple_paraboloid_equality(self): prob = Problem() root = prob.root = Group() root.add('p1', ParamComp('x', 50.0), promotes=['*']) root.add('p2', ParamComp('y', 50.0), promotes=['*']) root.add('comp', Paraboloid(), promotes=['*']) root.add('con', ExecComp('c = 15.0 - x + y'), promotes=['*']) prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1.0e-8 prob.driver.add_param('x', low=-50.0, high=50.0) prob.driver.add_param('y', low=-50.0, high=50.0) prob.driver.add_objective('f_xy') prob.driver.add_constraint('c', ctype='ineq') prob.driver.options['disp'] = False prob.setup(check=False) prob.run() # Minimum should be at (7.166667, -7.833334) assert_rel_error(self, prob['x'], 7.16667, 1e-6) assert_rel_error(self, prob['y'], -7.833334, 1e-6)