Beispiel #1
0
        def test_sellar_state_connection_densejac(self):
            # Test derivatives across a converged Sellar model.

            prob = Problem()
            prob.model = SellarStateConnection(
                linear_solver=self.linear_solver_class(), nl_atol=1e-12)

            prob.set_solver_print(level=0)

            prob.setup(check=False, mode='fwd')

            prob.model.sub.d1.jacobian = DenseJacobian()
            prob.model.sub.d2.jacobian = DenseJacobian()
            prob.model.sub.state_eq_group.state_eq.jacobian = DenseJacobian()
            prob.model.obj_cmp.jacobian = DenseJacobian()
            prob.model.con_cmp1.jacobian = DenseJacobian()
            prob.model.con_cmp2.jacobian = DenseJacobian()

            prob.run_model()

            # Just make sure we are at the right answer
            assert_rel_error(self, prob['y1'], 25.58830273, .00001)
            assert_rel_error(self, prob['d2.y2'], 12.05848819, .00001)

            wrt = ['x', 'z']
            of = ['obj', 'con1', 'con2']

            Jbase = {}
            Jbase['con1', 'x'] = [[-0.98061433]]
            Jbase['con1', 'z'] = np.array([[-9.61002285, -0.78449158]])
            Jbase['con2', 'x'] = [[0.09692762]]
            Jbase['con2', 'z'] = np.array([[1.94989079, 1.0775421]])
            Jbase['obj', 'x'] = [[2.98061392]]
            Jbase['obj', 'z'] = np.array([[9.61001155, 1.78448534]])

            J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')
            for key, val in iteritems(Jbase):
                assert_rel_error(self, J[key], val, .00001)

            prob = Problem()
            prob.model = SellarStateConnection(
                linear_solver=self.linear_solver_class(), nl_atol=1e-12)

            prob.set_solver_print(level=0)

            prob.setup(check=False, mode='rev')

            prob.model.sub.d1.jacobian = DenseJacobian()
            prob.model.sub.d2.jacobian = DenseJacobian()
            prob.model.sub.state_eq_group.state_eq.jacobian = DenseJacobian()
            prob.model.obj_cmp.jacobian = DenseJacobian()
            prob.model.con_cmp1.jacobian = DenseJacobian()
            prob.model.con_cmp2.jacobian = DenseJacobian()

            prob.run_model()

            J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')
            for key, val in iteritems(Jbase):
                assert_rel_error(self, J[key], val, .00001)
Beispiel #2
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_model_viewer_has_correct_data_from_sqlite(self):
        """
        Verify that the correct data exists when a model structure is recorded
        and then pulled out of a sqlite db file and compared to the expected
        structure.  Uses the SellarStateConnection model.
        """
        p = om.Problem(model=SellarStateConnection())

        r = SqliteRecorder(self.sqlite_db_filename)
        p.driver.add_recorder(r)

        p.setup()
        p.final_setup()
        r.shutdown()

        model_viewer_data = _get_viewer_data(self.sqlite_db_filename)

        with open(os.path.join(self.parent_dir,
                               'sellar_tree.json')) as json_file:
            expected_tree = json.load(json_file)

        # check expected model tree
        self.check_model_viewer_data(
            model_viewer_data, expected_tree, self.expected_pathnames,
            self.expected_conns, self.expected_abs2prom,
            self.expected_declare_partials, self.expected_driver_name,
            self.expected_design_vars_names, self.expected_responses_names)
    def test_n2_from_sqlite(self):
        """
        Test that an n2 html file is generated from a sqlite file.
        """
        p = om.Problem()
        p.model = SellarStateConnection()
        r = SqliteRecorder(self.sqlite_db_filename2)
        p.driver.add_recorder(r)
        p.setup()
        p.final_setup()
        r.shutdown()
        n2(p, outfile=self.compare_html_filename, show_browser=DEBUG_BROWSER)
        n2(self.sqlite_db_filename2,
           outfile=self.sqlite_html_filename,
           show_browser=DEBUG_BROWSER)

        # Check that the html file has been created and has something in it.
        self.assertTrue(os.path.isfile(self.sqlite_html_filename),
                        (self.sqlite_html_filename + " is not a valid file."))
        self.assertGreater(os.path.getsize(self.sqlite_html_filename), 100)

        # Check that there are no errors when running from the command line with a recording.
        check_call('openmdao n2 --no_browser %s' % self.sqlite_db_filename2)

        # Compare models from the files generated from the Problem and the recording
        sqlite_model_data = self._extract_compressed_model(
            self.sqlite_html_filename)
        compare_model_data = self._extract_compressed_model(
            self.compare_html_filename)

        self.assertTrue(
            sqlite_model_data == compare_model_data,
            'Model data from sqlite does not match data from Problem.')
Beispiel #5
0
    def test_n2_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()
        p.final_setup()
        r.shutdown()
        n2(p, outfile=self.compare_html_filename, show_browser=DEBUG_BROWSER)
        n2(self.sqlite_db_filename2,
           outfile=self.sqlite_html_filename,
           show_browser=DEBUG_BROWSER)

        # Check that the html file has been created and has something in it.
        self.assertTrue(os.path.isfile(self.sqlite_html_filename),
                        (self.sqlite_html_filename + " is not a valid file."))
        self.assertGreater(os.path.getsize(self.sqlite_html_filename), 100)

        # Check that there are no errors when running from the command line with a recording.
        check_call('openmdao n2 --no_browser %s' % self.sqlite_db_filename2)

        # Compare the sizes of the files generated from the Problem and the recording
        size1 = os.path.getsize(self.sqlite_html_filename)
        size2 = os.path.getsize(self.compare_html_filename)
        self.assertTrue(
            size1 == size2, 'File size of ' + self.sqlite_html_filename +
            ' is ' + str(size1) + ', but size of ' +
            self.compare_html_filename + ' is ' + str(size2))
Beispiel #6
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 = om.Problem(model=SellarStateConnection())
        p.setup()
        p.final_setup()

        model_viewer_data = _get_viewer_data(p)

        with open(os.path.join(self.parent_dir, 'sellar_tree.json')) as json_file:
            expected_tree = json.load(json_file)

        # check expected model tree
        self.check_model_viewer_data(
            model_viewer_data,
            expected_tree,
            self.expected_pathnames,
            self.expected_conns,
            self.expected_abs2prom,
            self.expected_declare_partials,
            self.expected_driver_name,
            self.expected_design_vars_names,
            self.expected_responses_names
        )
    def test_viewer_data_from_subgroup(self):
        """
        Test error message when asking for viewer data for a subgroup.
        """
        p = om.Problem(model=SellarStateConnection())
        p.setup()

        msg = "Viewer data is not available for sub-Group 'sub'."
        with assert_warning(UserWarning, msg):
            _get_viewer_data(p.model.sub)
Beispiel #8
0
    def test_view_model_from_problem(self):
        """
        Test that an n2 html file is generated from a Problem.
        """
        p = Problem()
        p.model = SellarStateConnection()
        p.setup(check=False)
        view_model(p, outfile=self.problem_filename, show_browser=False)

        # 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.assertGreater(os.path.getsize(self.problem_html_filename), 100)
Beispiel #9
0
    def test_n2_from_model(self):
        """
        Test that an n2 html file is generated from a model.
        """
        p = om.Problem()
        p.model = SellarStateConnection()
        p.setup()
        n2(p.model, outfile=self.problem_html_filename, show_browser=DEBUG_BROWSER)

        # 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.assertGreater(os.path.getsize(self.problem_html_filename), 100)
Beispiel #10
0
    def test_sellar_state_connection(self):
        # Sellar model closes loop with state connection instead of a cycle.

        prob = Problem(model=SellarStateConnection(nonlinear_solver=NewtonSolver()))

        prob.set_solver_print(level=0)
        prob.setup(check=False)
        prob.run_model()

        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.model.nonlinear_solver._iter_count, 8)
Beispiel #11
0
    def test_sellar_state_connection(self):
        # Sellar model closes loop with state connection instead of a cycle.

        prob = om.Problem(model=SellarStateConnection(nonlinear_solver=om.NewtonSolver(solve_subsystems=False)))

        prob.set_solver_print(level=0)
        prob.setup()
        prob.run_model()

        assert_near_equal(prob.get_val('y1'), 25.58830273, .00001)
        assert_near_equal(prob['state_eq.y2_command'], 12.05848819, .00001)

        # Make sure we aren't iterating like crazy
        self.assertLess(prob.model.nonlinear_solver._iter_count, 8)
    def test_viewer_data_from_None(self):
        """
        Test error message when asking for viewer data for an invalid source.
        """
        p = om.Problem(model=SellarStateConnection())
        p.setup()

        msg = "Viewer data is not available for 'None'." + \
              "The source must be a Problem, model or the filename of a recording."

        with self.assertRaises(TypeError) as cm:
            _get_viewer_data(None)

        self.assertEquals(str(cm.exception), msg)
Beispiel #13
0
    def test_error_need_direct_solver(self):
        # Test top level Sellar (i.e., not grouped).

        prob = Problem()
        model = prob.model = SellarStateConnection(
            nonlinear_solver=BroydenSolver(), linear_solver=LinearRunOnce())

        prob.setup(check=False)

        with self.assertRaises(ValueError) as context:
            prob.run_model()

        msg = "Linear solver must be DirectSolver when solving the full model."
        self.assertEqual(str(context.exception), msg)
Beispiel #14
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)
Beispiel #15
0
    def test_linsearch_3_deprecation(self):
        prob = om.Problem()
        model = prob.model = SellarStateConnection(
            nonlinear_solver=om.BroydenSolver(),
            linear_solver=om.LinearRunOnce())
        prob.setup()

        model.nonlinear_solver.options['state_vars'] = ['state_eq.y2_command']
        model.nonlinear_solver.options['compute_jacobian'] = False

        msg = 'Deprecation warning: In V 3.0, the default Broyden solver setup will change ' + \
              'to use the BoundsEnforceLS line search.'

        with assert_warning(DeprecationWarning, msg):
            prob.final_setup()
    def test_n2_set_title(self):
        """
        Test that an n2 html file is generated from a Problem.
        """
        p = Problem()
        p.model = SellarStateConnection()
        p.setup()
        n2(p, outfile=self.title_html_filename, show_browser=DEBUG_BROWSER,
           title="Sellar State Connection")

        # Check that the html file has been created and has something in it.
        self.assertTrue(os.path.isfile(self.title_html_filename),
                        (self.title_html_filename + " is not a valid file."))
        self.assertTrue('OpenMDAO Model Hierarchy and N2 diagram: Sellar State Connection'
                        in open(self.title_html_filename).read())
Beispiel #17
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 #18
0
    def test_error_badname(self):
        # Test top level Sellar (i.e., not grouped).

        prob = Problem()
        model = prob.model = SellarStateConnection(
            nonlinear_solver=BroydenSolver(), linear_solver=LinearRunOnce())

        prob.setup(check=False)

        model.nonlinear_solver.options['state_vars'] = ['junk']

        with self.assertRaises(ValueError) as context:
            prob.run_model()

        msg = "The following variable names were not found: junk"
        self.assertEqual(str(context.exception), msg)
Beispiel #19
0
    def test_simple_sellar(self):
        # Test top level Sellar (i.e., not grouped).

        prob = om.Problem()
        model = prob.model = SellarStateConnection(nonlinear_solver=om.BroydenSolver(),
                                                   linear_solver=om.LinearRunOnce())

        prob.setup()

        model.nonlinear_solver.options['state_vars'] = ['state_eq.y2_command']
        model.nonlinear_solver.options['compute_jacobian'] = False

        prob.run_model()

        assert_near_equal(prob['y1'], 25.58830273, .00001)
        assert_near_equal(prob['state_eq.y2_command'], 12.05848819, .00001)
    def test_sellar_state_connection_fd_system(self):
        # Sellar model closes loop with state connection instead of a cycle.
        # This test is just fd.
        prob = om.Problem(model=SellarStateConnection(nonlinear_solver=om.NewtonSolver()))

        prob.model.approx_totals(method='fd')

        prob.setup()
        prob.set_solver_print(level=0)
        prob.run_model()

        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.model.nonlinear_solver._iter_count, 6)
Beispiel #21
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)
Beispiel #22
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()
        p.final_setup()

        model_viewer_data = _get_viewer_data(p)

        # check expected model tree
        self.check_model_viewer_data(
            model_viewer_data, self.expected_tree, self.expected_pathnames,
            self.expected_conns, self.expected_abs2prom,
            self.expected_declare_partials, self.expected_driver_name,
            self.expected_design_vars_names, self.expected_responses_names)
Beispiel #23
0
    def test_model_viewer_has_correct_data_from_sqlite(self):
        """
        Verify that the correct data exists when a model structure is recorded
        and then pulled out of a sqlite db file and compared to the expected
        structure.  Uses the SellarStateConnection model.
        """
        p = Problem(model=SellarStateConnection())

        r = SqliteRecorder(self.sqlite_db_filename)
        p.driver.add_recorder(r)

        p.setup()
        p.final_setup()
        r.shutdown()

        model_viewer_data = _get_viewer_data(self.sqlite_db_filename)
        print(model_viewer_data['tree'])

        # 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 = sorted(model_viewer_data['connections_list'],
                             key=lambda x: (x['tgt'], x['src']))
        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.assertEqual(len(connections), len(self.expected_conns))
        for c, ex in zip(connections, self.expected_conns):
            self.assertEqual(c['src'], ex['src'])
            self.assertEqual(c['tgt'], ex['tgt'])
            self.assertEqual(c.get('cycle_arrows', []),
                             ex.get('cycle_arrows', []))

        # check expected abs2prom map
        self.assertDictEqual(model_viewer_data['abs2prom'],
                             self.expected_abs2prom)
Beispiel #24
0
    def test_sellar(self):
        from openmdao.api import Problem, LinearRunOnce, IndepVarComp, BroydenSolver
        from openmdao.test_suite.components.sellar import SellarStateConnection

        prob = Problem()
        model = prob.model = SellarStateConnection(nonlinear_solver=BroydenSolver(),
                                                   linear_solver=LinearRunOnce())

        prob.setup()

        model.nonlinear_solver.options['state_vars'] = ['state_eq.y2_command']
        model.nonlinear_solver.options['compute_jacobian'] = False

        prob.set_solver_print(level=2)
        prob.run_model()

        assert_rel_error(self, prob['y1'], 25.58830273, .00001)
        assert_rel_error(self, prob['state_eq.y2_command'], 12.05848819, .00001)
Beispiel #25
0
    def test_sellar(self):
        import openmdao.api as om
        from openmdao.test_suite.components.sellar import SellarStateConnection

        prob = om.Problem()
        model = prob.model = SellarStateConnection(nonlinear_solver=om.BroydenSolver(),
                                                   linear_solver=om.LinearRunOnce())

        prob.setup()

        model.nonlinear_solver.options['state_vars'] = ['state_eq.y2_command']
        model.nonlinear_solver.options['compute_jacobian'] = False

        prob.set_solver_print(level=2)
        prob.run_model()

        assert_near_equal(prob['y1'], 25.58830273, .00001)
        assert_near_equal(prob['state_eq.y2_command'], 12.05848819, .00001)
Beispiel #26
0
    def test_simple_sellar_full_jacobian(self):
        # Test top level Sellar (i.e., not grouped).

        prob = om.Problem()
        model = prob.model = SellarStateConnection(nonlinear_solver=om.BroydenSolver(),
                                                   linear_solver=om.LinearRunOnce())

        prob.setup()

        model.nonlinear_solver.linear_solver = om.DirectSolver()

        prob.run_model()

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

        # Normally takes about 5 iters, but takes around 4 if you calculate an initial
        # Jacobian.
        self.assertTrue(model.nonlinear_solver._iter_count < 5)
Beispiel #27
0
    def test_simple_sellar_jacobian_assembled(self):
        # Test top level Sellar (i.e., not grouped).

        prob = Problem()
        model = prob.model = SellarStateConnection(nonlinear_solver=BroydenSolver(),
                                                   linear_solver=LinearRunOnce())

        prob.setup(check=False)

        model.nonlinear_solver.linear_solver = DirectSolver(assemble_jac=True)

        prob.run_model()

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

        # Normally takes about 4 iters, but takes around 3 if you calculate an initial
        # Jacobian.
        self.assertTrue(model.nonlinear_solver._iter_count < 4)
Beispiel #28
0
    def test_model_viewer_has_correct_data_from_sqlite(self):
        """
        Verify that the correct data exists when a model structure is recorded
        and then pulled out of a sqlite db file and compared to the expected
        structure.  Uses the SellarStateConnection model.
        """
        p = Problem()
        p.model = SellarStateConnection()
        r = SqliteRecorder(self.sqlite_db_filename)
        p.driver.add_recorder(r)
        p.setup(check=False)
        p.final_setup()
        r.close()

        model_viewer_data = _get_viewer_data(self.sqlite_db_filename)
        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)
Beispiel #29
0
    def test_sellar_state_connection_fd_system(self):
        # Sellar model closes loop with state connection instead of a cycle.
        # This test is just fd.
        prob = om.Problem()
        model = prob.model = SellarStateConnection(nonlinear_solver=om.BroydenSolver(),
                                                   linear_solver=om.LinearRunOnce())
        prob.model.approx_totals(method='fd')

        prob.setup()

        model.nonlinear_solver.options['state_vars'] = ['state_eq.y2_command']
        model.nonlinear_solver.options['compute_jacobian'] = False

        prob.run_model()

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

        # Make sure we aren't iterating like crazy
        self.assertLess(prob.model.nonlinear_solver._iter_count, 6)
Beispiel #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()
        p.final_setup()
        r.shutdown()
        view_model(self.sqlite_db_filename2,
                   outfile=self.sqlite_html_filename,
                   show_browser=DEBUG)

        # 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)

        # Check that there are no errors when running from the command line with a recording.
        check_call('openmdao view_model --no_browser %s' %
                   self.sqlite_db_filename2)