Beispiel #1
0
    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 = ["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)
Beispiel #2
0
    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 = ["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)
Beispiel #3
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 = ["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)
Beispiel #4
0
    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()
Beispiel #5
0
    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)
Beispiel #6
0
    def test_2Darray_write(self):

        top = Problem()
        top.root = Group()
        top.root.add('my_comp', VarComponent())

        top.setup(check=False)
        top.run()

        sb = Namelist(top.root.my_comp)

        top['my_comp.arrayvar'] = zeros([3, 2], dtype=numpy_float32)
        top['my_comp.arrayvar'][0, 1] = 3.7
        top['my_comp.arrayvar'][2, 0] = 7.88

        sb.set_filename(self.filename)
        sb.add_group('Test')
        sb.add_var("arrayvar")

        sb.generate()

        f = open(self.filename, 'r')
        contents = f.read()

        compare = "\n" + \
                  "&Test\n" + \
                  "  arrayvar(1,1) = 0.0,  3.700000047683716, \n" + \
                  "arrayvar(1,2) = 0.0,  0.0, \n" + \
                  "arrayvar(1,3) = 7.880000114440918,  0.0, \n" + \
                  "/\n"

        self.assertEqual(contents, compare)
Beispiel #7
0
    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)]

        g1_expected = (g1_expected_params, g1_expected_unknowns, g1_expected_resids)

        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_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', IndepVarComp('x', np.zeros(4)))
            prob.root.add('rosen', Rosenbrock(4))

            prob.root.connect('myparams.x', 'rosen.x')

            prob.driver = MySimpleDriver()
            prob.driver.add_desvar('myparams.x')
            prob.driver.add_constraint('rosen.xxx', upper=0.0, 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 += "shape: (4,)."
            raised_error = str(cm.exception)
            raised_error = raised_error.replace('(4L,', '(4,')
            self.assertEqual(msg, raised_error)
Beispiel #9
0
    def test_unsupported_array(self):

        top = Problem()
        top.root = Group()
        top.root.add('my_comp', VarComponent())

        top.setup(check=False)
        top.run()

        sb = Namelist(top.root.my_comp)

        top['my_comp.arrayvar'] = zeros([2, 2, 2], dtype=numpy_float32)

        sb.set_filename(self.filename)
        sb.add_group('Test')
        sb.add_var("arrayvar")

        try:
            sb.generate()
        except RuntimeError as err:
            self.assertEqual(str(err),
                             "Don't know how to handle array of" + \
                                           " 3 dimensions")
        else:
            self.fail('RuntimeError expected')
Beispiel #10
0
    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")
Beispiel #11
0
    def test_sublevel_record(self):

        prob = Problem()
        prob.root = ExampleGroup()
        prob.root.G2.G1.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)
        prob.cleanup() # closes recorders

        coordinate = [0, 'Driver', (1,), "root", (1,), "G2", (1,), "G1", (1,)]

        expected_params = [
            ("C2.x", 5.0)
        ]
        expected_unknowns = [
            ("C2.y", 10.0)
        ]
        expected_resids = [
            ("C2.y", 0.0)
        ]

        self.assertIterationDataRecorded(((coordinate, (t0, t1), expected_params,
                                expected_unknowns, expected_resids),), self.eps)
Beispiel #12
0
    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.)
Beispiel #13
0
    def test_calc_gradient_multiple_params(self):
        prob = Problem()
        prob.root = FanIn()
        prob.setup(check=False)
        prob.run()

        param_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(param_list, unknown_list, mode='fwd', return_format='dict')
        np.testing.assert_almost_equal(J['comp3.y']['p2.x2'], np.array([[ 35.]]))
        np.testing.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(param_list, unknown_list, mode='fwd', return_format='array')
        np.testing.assert_almost_equal(J, np.array([[-6., 35.]]))

        # check that calc_gradient returns proper dict value when mode is 'rev'
        J = prob.calc_gradient(param_list, unknown_list, mode='rev', return_format='dict')
        np.testing.assert_almost_equal(J['comp3.y']['p2.x2'], np.array([[ 35.]]))
        np.testing.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(param_list, unknown_list, mode='rev', return_format='array')
        np.testing.assert_almost_equal(J, np.array([[-6., 35.]]))

        # check that calc_gradient returns proper dict value when mode is 'fd'
        J = prob.calc_gradient(param_list, unknown_list, mode='fd', return_format='dict')
        np.testing.assert_almost_equal(J['comp3.y']['p2.x2'], np.array([[ 35.]]))
        np.testing.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(param_list, unknown_list, mode='fd', return_format='array')
        np.testing.assert_almost_equal(J, np.array([[-6., 35.]]))
Beispiel #14
0
    def test_byobj_run(self):
        prob = Problem(root=ExampleByObjGroup())

        prob.setup(check=False)
        prob.run()

        self.assertEqual(prob['G3.C4.y'], 'fooC2C3C4')
Beispiel #15
0
    def test_basic_run(self):
        prob = Problem(root=ExampleGroup())

        prob.setup(check=False)
        prob.run()

        self.assertAlmostEqual(prob['G3.C4.y'], 40.)
Beispiel #16
0
    def test_mode_auto(self):
        # Make sure mode=auto chooses correctly for all prob sizes as well
        # as for abs/rel/etc paths

        prob = Problem()
        root = prob.root = Group()

        root.add('p1', ParamComp('a', 1.0), promotes=['*'])
        root.add('p2', ParamComp('b', 1.0), promotes=['*'])
        root.add('comp', ExecComp(['x = 2.0*a + 3.0*b', 'y=4.0*a - 1.0*b']), promotes=['*'])

        root.ln_solver.options['mode'] = 'auto'
        prob.setup(check=False)
        prob.run()

        mode = prob._mode('auto', ['a'], ['x'])
        self.assertEqual(mode, 'fwd')

        mode = prob._mode('auto', ['a', 'b'], ['x'])
        self.assertEqual(mode, 'rev')

        # make sure _check function does it too

        #try:
            #mode = prob._check_for_matrix_matrix(['a'], ['x'])
        #except Exception as err:
            #msg  = "Group '' must have the same mode as root to use Matrix Matrix."
            #self.assertEqual(text_type(err), msg)
        #else:
            #self.fail('Exception expected')

        root.ln_solver.options['mode'] = 'fwd'
        mode = prob._check_for_matrix_matrix(['a', 'b'], ['x'])
        self.assertEqual(mode, 'fwd')
Beispiel #17
0
    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()
        except KeyError as err:
            self.fail('KeyError raised: {0}'.format(str(err)))
Beispiel #18
0
    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")
Beispiel #19
0
    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)
Beispiel #20
0
    def test_splitterW(self):
        g = Group()
        p = Problem(root=g)
        comp = g.add('comp', SplitterW())
        p.setup(check=False)
        
        comp.params['W1_des'] = 1.08
        comp.params['MNexit1_des'] = 1.0
        comp.params['MNexit2_des'] = 1.0
        comp.params['design'] = True

        comp.params['flow_in:in:W'] = 3.48771299
        comp.params['flow_in:in:Tt'] = 630.74523
        comp.params['flow_in:in:Pt'] = 0.0271945
        comp.params['flow_in:in:Mach'] = 1.0
        p.run()
        self.check(comp)

        comp.params['design'] = False
        comp.params['flow_out_1:in:is_super'] = True
        comp.params['flow_out_2:in:is_super'] = True
        p.run()
        self.check(comp)

        comp.params['flow_in:in:W'] *= 0.95
        comp.params['flow_out_1:in:is_super'] = False
        comp.params['flow_out_2:in:is_super'] = False
        p.run()
        TOL = 0.001
        assert_rel_error(self, comp.unknowns['flow_out_1:out:Mach'], 0.76922, TOL)
        assert_rel_error(self, comp.unknowns['flow_out_2:out:Mach'], 0.76922, TOL)
Beispiel #21
0
    def test_2Darray_read(self):

        namelist1 = "Testing\n" + \
                    "$GROUP\n" + \
                    "  arrayvartwod(1,1) = 12, 24, 36\n" + \
                    "  arrayvartwod(1,2) = 33, 66, 99\n" + \
                    "$END\n"

        outfile = open(self.filename, 'w')
        outfile.write(namelist1)
        outfile.close()

        top = Problem()
        top.root = Group()
        top.root.add('my_comp', VarComponent())

        top.setup(check=False)
        top.run()

        sb = Namelist(top.root.my_comp)
        sb.set_filename(self.filename)

        sb.parse_file()

        sb.load_model()

        # Unchanged
        self.assertEqual(top['my_comp.arrayvartwod'][0][0], 12)
        self.assertEqual(top['my_comp.arrayvartwod'][1][2], 99)
Beispiel #22
0
    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']))
Beispiel #23
0
    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_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_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_array2D_index_connection(self):
        group = Group()
        group.add('x_param', IndepVarComp('x', np.ones((2, 2))), promotes=['*'])
        sub = group.add('sub', Group(), promotes=['*'])
        sub.add('mycomp', ArrayComp2D(), promotes=['x', 'y'])
        group.add('obj', ExecComp('b = a'))
        group.connect('y', 'obj.a',  src_indices=[3])

        prob = Problem()
        prob.root = group
        prob.root.ln_solver = LinearGaussSeidel()
        prob.setup(check=False)
        prob.run()

        J = prob.calc_gradient(['x'], ['obj.b'], mode='fwd', return_format='dict')
        Jbase = prob.root.sub.mycomp._jacobian_cache
        assert_rel_error(self, Jbase[('y', 'x')][3][0], J['obj.b']['x'][0][0], 1e-8)
        assert_rel_error(self, Jbase[('y', 'x')][3][1], J['obj.b']['x'][0][1], 1e-8)
        assert_rel_error(self, Jbase[('y', 'x')][3][2], J['obj.b']['x'][0][2], 1e-8)
        assert_rel_error(self, Jbase[('y', 'x')][3][3], J['obj.b']['x'][0][3], 1e-8)

        J = prob.calc_gradient(['x'], ['obj.b'], mode='rev', return_format='dict')
        Jbase = prob.root.sub.mycomp._jacobian_cache
        assert_rel_error(self, Jbase[('y', 'x')][3][0], J['obj.b']['x'][0][0], 1e-8)
        assert_rel_error(self, Jbase[('y', 'x')][3][1], J['obj.b']['x'][0][1], 1e-8)
        assert_rel_error(self, Jbase[('y', 'x')][3][2], J['obj.b']['x'][0][2], 1e-8)
        assert_rel_error(self, Jbase[('y', 'x')][3][3], J['obj.b']['x'][0][3], 1e-8)
    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_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.add_desvar('z', low=np.array([-10.0]),
                              high=np.array([10.0]),indices=[0])
        prob.driver.add_desvar('x', low=0.0, high=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_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', low=np.array([-10.0, 0.0]),
                             high=np.array([10.0, 10.0]))
        prob.driver.add_desvar('x', low=0.0, high=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)
Beispiel #30
0
    def test_read3(self):
        # Parse a single group in a deck with non-unique group names

        namelist1 = "Testing\n" + \
                    "$GROUP\n" + \
                    "  intvar = 99\n" + \
                    "$END\n" + \
                    "$GROUP\n" + \
                    "  floatvar = 3.5e-23\n" + \
                    "$END\n"

        outfile = open(self.filename, 'w')
        outfile.write(namelist1)
        outfile.close()

        top = Problem()
        top.root = Group()
        top.root.add('my_comp', VarComponent())

        top.setup(check=False)
        top.run()

        sb = Namelist(top.root.my_comp)
        sb.set_filename(self.filename)

        sb.parse_file()

        sb.load_model(single_group=1)

        # Unchanged
        self.assertEqual(top['my_comp.intvar'], 333)
        # Changed
        self.assertEqual(top['my_comp.floatvar'], 3.5e-23)
Beispiel #31
0
    def test_simplest_run(self):

        prob = Problem(root=Group())
        root = prob.root

        root.add('x_param', ParamComp('x', 7.0))
        root.add('mycomp', ExecComp('y=x*2.0'))

        root.connect('x_param.x', 'mycomp.x')

        prob.setup(check=False)
        prob.run()
        result = root.unknowns['mycomp.y']
        self.assertAlmostEqual(14.0, result, 3)
Beispiel #32
0
    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'])
Beispiel #33
0
    def test_sellar_state_connection(self):

        prob = Problem()
        prob.root = SellarStateConnection()
        prob.root.nl_solver = Newton()

        prob.setup(check=False)
        prob.run()

        assert_rel_error(self, prob['y1'], 25.58830273, .00001)
        assert_rel_error(self, prob['state_eq.y2_command'], 12.05848819, .00001)

        # Make sure we aren't iterating like crazy
        self.assertLess(prob.root.nl_solver.iter_count, 8)
Beispiel #34
0
    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.add('A', A())
        prob.root.add('B', B())

        prob.root.connect('A.x', 'B.x')
        prob.setup(check=False)

        expected_error_message = (
            "Source 'A.y' cannot be connected to target 'B.x': "
            "'A.y' does not exist.")
        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(ConnectError) as cm:
            prob.setup(check=False)

        self.assertEqual(str(cm.exception), expected_error_message)

        expected_error_message = (
            "Source 'A.x' cannot be connected to target 'B.y': "
            "'B.y' does not exist.")
        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(ConnectError) as cm:
            prob.setup(check=False)

        self.assertEqual(str(cm.exception), expected_error_message)

        expected_error_message = (
            "Source 'A.x' cannot be connected to target 'A.x': "
            "Target must be a parameter but 'A.x' is an unknown.")
        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(ConnectError) as cm:
            prob.setup(check=False)

        self.assertEqual(str(cm.exception), expected_error_message)
Beispiel #35
0
    def test_sellar_derivs(self):

        prob = Problem()
        prob.root = SellarDerivatives()
        prob.root.nl_solver = Newton()

        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)
Beispiel #36
0
    def test_subsolver_records_metadata(self):
        prob = Problem()
        prob.root = ExampleGroup()
        prob.root.G2.G1.nl_solver.add_recorder(self.recorder)
        self.recorder.options['record_metadata'] = True
        prob.setup(check=False)
        prob.cleanup()  # closes recorders

        expected_params = list(iteritems(prob.root.params))
        expected_unknowns = list(iteritems(prob.root.unknowns))
        expected_resids = list(iteritems(prob.root.resids))

        self.assertMetadataRecorded(
            (expected_params, expected_unknowns, expected_resids))
Beispiel #37
0
    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)
        prob.cleanup() # closes recorders

        coordinate = [0, '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)
Beispiel #38
0
    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)
Beispiel #39
0
    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_sellar_group(self):

        prob = Problem()
        prob.root = SellarDerivativesGrouped()
        prob.root.nl_solver = NLGaussSeidel()
        prob.root.nl_solver.options['atol'] = 1e-9
        prob.root.mda.nl_solver.options['atol'] = 1e-3
        prob.root.nl_solver.options[
            'iprint'] = 1  # so that print_norm is in coverage

        prob.setup(check=False)
        prob.run()

        assert_rel_error(self, prob['y1'], 25.58830273, .00001)
        assert_rel_error(self, prob['y2'], 12.05848819, .00001)
Beispiel #41
0
    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))
Beispiel #42
0
    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))
Beispiel #43
0
    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)
Beispiel #44
0
    def test_input_input_explicit_conns_no_conn(self):
        prob = Problem(root=Group())
        root = prob.root
        root.add('p1', ParamComp('x', 1.0))
        root.add('c1', ExecComp('y = x*2.0'))
        root.add('c2', ExecComp('y = x*3.0'))
        root.connect('c1.x', 'c2.x')

        # ignore warning about the unconnected params
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("ignore")
            prob.setup(check=False)

        prob.run()
        self.assertEqual(root.connections, {})
Beispiel #45
0
    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_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.])
Beispiel #47
0
    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)
Beispiel #48
0
    def test_implicit_component(self, m):
        self.setup_endpoints(m)
        from openmdao.core.tests.test_impl_comp import QuadraticLinearize, QuadraticJacVec
        group = Group()
        group.add_subsystem('comp1', IndepVarComp([('a', 1.0), ('b', 1.0), ('c', 1.0)]))
        group.add_subsystem('comp2', QuadraticLinearize())
        group.add_subsystem('comp3', QuadraticJacVec())
        group.connect('comp1.a', 'comp2.a')
        group.connect('comp1.b', 'comp2.b')
        group.connect('comp1.c', 'comp2.c')
        group.connect('comp1.a', 'comp3.a')
        group.connect('comp1.b', 'comp3.b')
        group.connect('comp1.c', 'comp3.c')

        prob = Problem(model=group)
        prob.setup(check=False)

        prob['comp1.a'] = 1.
        prob['comp1.b'] = -4.
        prob['comp1.c'] = 3.

        comp2 = prob.model.comp2  # ImplicitComponent

        comp2.recording_options['record_metadata'] = False
        comp2.add_recorder(self.recorder)

        t0, t1 = run_driver(prob)
        prob.cleanup()
        upload(self.filename, self._accepted_token)

        expected_inputs = [
            {'name': 'comp2.a', 'values': [1.0]},
            {'name': 'comp2.b', 'values': [-4.0]},
            {'name': 'comp2.c', 'values': [3.0]}
        ]
        expected_outputs = [{'name': 'comp2.x', 'values': [3.0]}]
        expected_residuals = [{'name': 'comp2.x', 'values': [0.0]}]

        system_iteration = json.loads(self.system_iterations)

        for i in expected_inputs:
            self.assert_array_close(i, system_iteration['inputs'])

        for r in expected_residuals:
            self.assert_array_close(r, system_iteration['residuals'])

        for o in expected_outputs:
            self.assert_array_close(o, system_iteration['outputs'])
Beispiel #49
0
    def test_view_model_from_sqlite(self):
        """
        Test that an n2 html file is generated from a sqlite file.
        """
        p = Problem()
        p.model = SellarStateConnection()
        r = SqliteRecorder(self.sqlite_db_filename2)
        p.driver.add_recorder(r)
        p.setup(check=False)
        p.final_setup()
        r.shutdown()
        view_model(self.sqlite_db_filename2, outfile=self.sqlite_filename, show_browser=False)

        # Check that the html file has been created and has something in it.
        self.assertTrue(os.path.isfile(self.sqlite_html_filename), (self.problem_html_filename + " is not a valid file."))
        self.assertGreater(os.path.getsize(self.sqlite_html_filename), 100)
    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_matvec(self):
        group = Group()
        group.add('x_param', ParamComp('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_simple_jac(self):
        group = Group()
        group.add('x_param', ParamComp('x', 1.0), promotes=['*'])
        group.add('mycomp', ExecComp(['y=2.0*x']), promotes=['x', 'y'])

        prob = Problem()
        prob.root = group
        prob.root.ln_solver = ScipyGMRES()
        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)
Beispiel #53
0
    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")
Beispiel #54
0
    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)
        prob.cleanup()

        if MPI:
            coord = [MPI.COMM_WORLD.rank, 'Driver', (1, ), "root", (1,)]
        else:
            coord = [0, '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(((coord, (t0, t1), expected_params, expected_unknowns, expected_resids),), self.eps, prob.root)
    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)
Beispiel #56
0
    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()
Beispiel #57
0
    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() )
Beispiel #58
0
    def test_distrib_idx_in_full_out(self):
        size = 11

        p = Problem(root=Group(), impl=impl)
        top = p.root
        top.add("C1", InOutArrayComp(size))
        top.add("C2", DistribInputComp(size))
        top.connect('C1.outvec', 'C2.invec')
        p.setup(check=False)

        top.C1.params['invec'] = np.array(range(size, 0, -1), float)

        p.run()

        self.assertTrue(
            all(top.C2.unknowns['outvec'] ==
                np.array(range(size, 0, -1), float) * 4))
    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)
Beispiel #60
0
    def test_distrib_full_in_out(self):
        size = 11

        p = Problem(root=Group(), impl=impl)
        top = p.root
        top.add("C1", InOutArrayComp(size))
        top.add("C2", DistribCompSimple(size))
        top.connect('C1.outvec', 'C2.invec')

        p.setup(check=False)

        top.C1.params['invec'] = np.ones(size, float) * 5.0

        p.run()

        self.assertTrue(
            all(top.C2.unknowns['outvec'] == np.ones(size, float) * 7.5))