Esempio n. 1
0
 def test_input_input_explicit_conns_w_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')
     root.connect('p1.x', 'c2.x')
     prob.setup(check=False)
     prob.run()
     self.assertEqual(root.connections['c1.x'], 'p1.x')
     self.assertEqual(root.connections['c2.x'], 'p1.x')
     self.assertEqual(len(root.connections), 2)
Esempio n. 2
0
    def test_sellar_derivs_grouped(self):

        prob = Problem()
        prob.root = SellarDerivativesGrouped()

        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')
        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')
        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')
        for key1, val1 in Jbase.items():
            for key2, val2 in val1.items():
                assert_rel_error(self, J[key1][key2], val2, .00001)
Esempio n. 3
0
    def setup(self, check=False):
        """
        Creates the containing `Problem` and performs needed initializations.

        Parameters
        ----------
        check : bool
            If setup should run checks.
        """
        args = self.args

        group = MODELS[self._group_type](**args)

        local_vec_class = args.get('local_vector_class', 'default')
        if local_vec_class == 'default':
            vec_class = DefaultVector
        elif local_vec_class == 'petsc':
            vec_class = PETScVector
            if PETScVector is None:
                raise SkipTest('PETSc not available.')
        else:
            raise RuntimeError("Unrecognized local_vector_class '%s'" %
                               local_vec_class)

        self.problem = prob = Problem(group)

        if args['assembled_jac']:

            jacobian_type = args.get('jacobian_type', 'dense')
            if jacobian_type == 'dense':
                prob.model.jacobian = DenseJacobian()
            elif jacobian_type == 'sparse-coo':
                prob.model.jacobian = COOJacobian()
            elif jacobian_type == 'sparse-csr':
                prob.model.jacobian = CSRJacobian()
            elif jacobian_type == 'sparse-csc':
                prob.model.jacobian = CSCJacobian()

        prob.model.linear_solver = self.linear_solver_class(
            **self.linear_solver_options)

        prob.model.nonlinear_solver = self.solver_class(**self.solver_options)

        prob.set_solver_print(level=0)

        prob.setup(check=check, local_vector_class=vec_class)

        fail, rele, abse = prob.run_model()
        if fail:
            raise RuntimeError('Problem run failed: re %f ; ae %f' %
                               (rele, abse))
Esempio n. 4
0
    def test_group_fd(self):
        class SimpleComp(Component):
            """ A simple component that provides derivatives. """
            def __init__(self):
                super(SimpleComp, self).__init__()

                # Params
                self.add_param('x', 2.0)

                # Unknowns
                self.add_output('y', 0.0)

            def solve_nonlinear(self, params, unknowns, resids):
                """ Doesn't do much.  Just multiply by 3"""
                unknowns['y'] = 3.0 * params['x']

            def jacobian(self, params, unknowns, resids):
                """Analytical derivatives."""

                J = {}
                J[('y', 'x')] = 3.0
                return J

        class Model(Group):
            """ Simple model to experiment with finite difference."""
            def __init__(self):
                super(Model, self).__init__()

                self.add('px', ParamComp('x', 2.0))

                self.add('comp1', SimpleComp())
                sub = self.add('sub', Group())
                sub.add('comp2', SimpleComp())
                sub.add('comp3', SimpleComp())
                self.add('comp4', SimpleComp())

                self.connect('px.x', 'comp1.x')
                self.connect('comp1.y', 'sub.comp2.x')
                self.connect('sub.comp2.y', 'sub.comp3.x')
                self.connect('sub.comp3.y', 'comp4.x')

                self.sub.fd_options['force_fd'] = True

        prob = Problem()
        prob.root = Model()

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

        J = prob.calc_gradient(['px.x'], ['comp4.y'])
        assert_rel_error(self, J[0][0], 81.0, 1e-6)
Esempio n. 5
0
    def test_basic(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_params'] = True
        self.recorder.options['record_resids'] = True

        prob.setup(check=False)

        t0, t1 = run(prob)
        prob.cleanup()

        coordinate = ['Driver', (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 test_sellar(self):

        prob = Problem()
        prob.root = SellarNoDerivatives()
        prob.root.nl_solver = NLGaussSeidel()

        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)
Esempio n. 7
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)
Esempio n. 8
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)
Esempio n. 9
0
    def test_root_solver_records_metadata(self):
        prob = Problem()
        prob.root = ConvergeDiverge()
        prob.root.nl_solver.add_recorder(self.recorder)
        self.recorder.options['record_metadata'] = True
        prob.setup(check=False)
        self.recorder.close()

        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))
Esempio n. 10
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 = [0, '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 = [0, '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)
Esempio n. 11
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))
Esempio n. 12
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'])
Esempio n. 13
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)
        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)
Esempio n. 14
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)
Esempio n. 15
0
    def setup(self, check=False):
        """
        Creates the containing `Problem` and performs needed initializations.

        Parameters
        ----------
        check : bool
            If setup should run checks.
        """
        args = self.args

        group = MODELS[self._group_type](**args)

        local_vec_class = args.get('local_vector_class', 'default')
        if local_vec_class == 'default':
            vec_class = DefaultVector
        elif local_vec_class == 'petsc':
            vec_class = PETScVector
            if PETScVector is None:
                raise SkipTest('PETSc not available.')
        else:
            raise RuntimeError("Unrecognized local_vector_class '%s'" %
                               local_vec_class)

        self.problem = prob = Problem(group)

        if args['assembled_jac']:
            jacobian_type = args.get('jacobian_type', 'dense')

            if jacobian_type == 'dense':
                self.linear_solver_options['assemble_jac'] = True
                prob.model.options['assembled_jac_type'] = 'dense'
            elif jacobian_type == 'sparse-csc':
                self.linear_solver_options['assemble_jac'] = True
                prob.model.options['assembled_jac_type'] = 'csc'
            elif jacobian_type != 'matvec':
                raise RuntimeError("Invalid assembled_jac: '%s'." %
                                   jacobian_type)

        prob.model.linear_solver = self.linear_solver_class(
            **self.linear_solver_options)

        prob.model.nonlinear_solver = self.solver_class(**self.solver_options)

        prob.set_solver_print(level=0)

        prob.setup(check=check, local_vector_class=vec_class)

        prob.run_model()
Esempio n. 16
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)
Esempio n. 17
0
    def test_variable_access(self):
        prob = Problem(root=ExampleGroup())

        # try accessing variable value before setup()
        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)

        # check that we can access values from unknowns (default) and params
        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

        # now try same thing in a Group with promotes
        prob = Problem(root=ExampleGroupWithPromotes())
        prob.setup(check=False)

        prob.root.G2.unknowns['x'] = 99.

        self.assertEqual(prob['G2.x'], 99.)
        self.assertEqual(prob.root.G2.G1.C2.params['x'],
                         0.)  # initial value for a parameter

        # and make sure we get the correct value after a transfer
        prob.root.G2._transfer_data('G1')
        self.assertEqual(prob.root.G2.G1.C2.params['x'],
                         99.)  # transferred value of parameter
Esempio n. 18
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'])
Esempio n. 19
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)
Esempio n. 20
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'])
Esempio n. 21
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))
Esempio n. 22
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))
Esempio n. 23
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, {})
Esempio n. 24
0
    def test_check_promotes(self):
        # verify we get an error at setup time if we have promoted a var that doesn't exist

        # valid case, no error
        prob = Problem(Group())
        G = prob.root.add('G', Group())
        C = G.add('C', SimpleComp(), promotes=['x*', 'y'])
        # ignore warning about the unconnected param
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("ignore")
            prob.setup(check=False)

        # promoting a non-existent variable should throw an error
        prob = Problem(Group())
        G = prob.root.add('G', Group())
        C = G.add('C', SimpleComp(), promotes=['spoon'])  # there is no spoon
        try:
            prob.setup(check=False)
        except Exception as error:
            msg = "'C' promotes 'spoon' but has no variables matching that specification"
            self.assertEqual(text_type(error), msg)
        else:
            self.fail("Error expected")

        # promoting a pattern with no matches should throw an error
        prob = Problem(Group())
        G = prob.root.add('G', Group())
        P = G.add('P', ParamComp('x', 5.),
                  promotes=['a*'])  # there is no match
        try:
            prob.setup(check=False)
        except Exception as error:
            msg = "'P' promotes 'a*' but has no variables matching that specification"
            self.assertEqual(text_type(error), msg)
        else:
            self.fail("Error expected")
Esempio n. 25
0
    def test_subsystem_access(self):
        prob = Problem(root=ExampleGroup())
        root = prob.root

        self.assertEqual(root.G2, prob.root.G2)
        self.assertEqual(root.G2.C1, prob.root.C1)
        self.assertEqual(root.G2.G1, prob.root.G1)
        self.assertEqual(root.G2.G1.C2, prob.root.C2)

        self.assertEqual(root.G3, prob.root.G3)
        self.assertEqual(root.G3.C3, prob.root.C3)
        self.assertEqual(root.G3.C4, prob.root.C4)

        prob = Problem(root=ExampleGroupWithPromotes())
        root = prob.root

        self.assertEqual(root.G2, prob.root.G2)
        self.assertEqual(root.G2.C1, prob.root.C1)
        self.assertEqual(root.G2.G1, prob.root.G1)
        self.assertEqual(root.G2.G1.C2, prob.root.C2)

        self.assertEqual(root.G3, prob.root.G3)
        self.assertEqual(root.G3.C3, prob.root.C3)
        self.assertEqual(root.G3.C4, prob.root.C4)
    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)
    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.])
Esempio n. 28
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'])
    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)
Esempio n. 30
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)