Пример #1
0
    def test_specify_newton_linear_solver_in_system(self):

        my_newton = NewtonSolver()
        my_newton.linear_solver = DirectSolver()

        prob = Problem(model=SellarDerivatives(nonlinear_solver=my_newton))

        prob.setup()

        self.assertIsInstance(prob.model.nonlinear_solver.linear_solver, DirectSolver)

        prob.run_model()

        assert_rel_error(self, prob['y1'], 25.58830273, .00001)
        assert_rel_error(self, prob['y2'], 12.05848819, .00001)
Пример #2
0
    def test_err_on_maxiter(self):
        # Raise AnalysisError when it fails to converge

        prob = Problem()
        nlsolver = NewtonSolver()
        prob.model = SellarDerivatives(nonlinear_solver=nlsolver, linear_solver=LinearBlockGS())

        nlsolver.options['err_on_maxiter'] = True
        nlsolver.options['maxiter'] = 1

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

        with self.assertRaises(AnalysisError) as context:
            prob.run_driver()

        msg = "Solver 'NL: Newton' on system '' failed to converge."
        self.assertEqual(str(context.exception), msg)
Пример #3
0
    def test_sellar_derivs(self):
        # Test top level Sellar (i.e., not grouped).
        # Also, piggybacked testing that makes sure we only call apply_nonlinear
        # on the head component behind the cycle break.

        prob = Problem()
        prob.model = SellarDerivatives(nonlinear_solver=NewtonSolver(), linear_solver=LinearBlockGS())

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

        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.model.nonlinear_solver._iter_count, 8)
Пример #4
0
    def test_feature_err_on_maxiter(self):
        import numpy as np

        from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, LinearBlockGS, ExecComp, AnalysisError
        from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives

        prob = Problem()
        model = prob.model

        model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x'])
        model.add_subsystem('pz',
                            IndepVarComp('z', np.array([5.0, 2.0])),
                            promotes=['z'])

        model.add_subsystem('d1',
                            SellarDis1withDerivatives(),
                            promotes=['x', 'z', 'y1', 'y2'])
        model.add_subsystem('d2',
                            SellarDis2withDerivatives(),
                            promotes=['z', 'y1', 'y2'])

        model.add_subsystem('obj_cmp',
                            ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',
                                     z=np.array([0.0, 0.0]),
                                     x=0.0),
                            promotes=['obj', 'x', 'z', 'y1', 'y2'])

        model.add_subsystem('con_cmp1',
                            ExecComp('con1 = 3.16 - y1'),
                            promotes=['con1', 'y1'])
        model.add_subsystem('con_cmp2',
                            ExecComp('con2 = y2 - 24.0'),
                            promotes=['con2', 'y2'])

        model.linear_solver = DirectSolver()

        nlgbs = model.nonlinear_solver = NewtonSolver()
        nlgbs.options['maxiter'] = 1
        nlgbs.options['err_on_maxiter'] = True

        prob.setup()

        try:
            prob.run_model()
        except AnalysisError:
            pass
Пример #5
0
    def setup(self):
        g = self.group

        with g.create_group('sys') as group:
            group.create_indep_var('a', val=1)
            group.create_indep_var('b', val=-4)
            group.create_indep_var('c', val=3)
        a = g.declare_input('a')
        b = g.declare_input('b')
        c = g.declare_input('c')

        x = g.create_implicit_output('x')
        y = a * x**2 + b * x + c

        x.define_residual(y)
        self.linear_solver = ScipyKrylov()
        self.nonlinear_solver = NewtonSolver(solve_subsystems=False)
    def test_feature_vector(self):
        import numpy as np
        from numpy.testing import assert_almost_equal

        from openmdao.api import Problem, Group, ExecComp, NewtonSolver, DirectSolver, DenseJacobian, BalanceComp

        n = 100

        prob = Problem(model=Group())

        exec_comp = ExecComp('y=b*x+c',
                             b={'value': np.random.uniform(0.01,100, size=n)},
                             c={'value': np.random.rand(n)},
                             x={'value': np.zeros(n)},
                             y={'value': np.ones(n)})

        prob.model.add_subsystem(name='exec', subsys=exec_comp)

        prob.model.add_subsystem(name='balance', subsys=BalanceComp('x', val=np.ones(n)))

        prob.model.connect('balance.x', 'exec.x')
        prob.model.connect('exec.y', 'balance.lhs:x')

        prob.model.linear_solver = DirectSolver()

        prob.model.nonlinear_solver = NewtonSolver()
        prob.model.nonlinear_solver.options['maxiter'] = 100
        prob.model.nonlinear_solver.options['iprint'] = 0

        prob.model.jacobian = DenseJacobian()

        prob.setup(check=False)

        prob['balance.x'] = np.random.rand(n)

        prob.run_model()

        b = prob['exec.b']
        c = prob['exec.c']

        assert_almost_equal(prob['balance.x'], -c/b, decimal=6)

        print('solution')
        print(prob['balance.x'])
        print('expected')
        print(-c/b)
Пример #7
0
    def test_feature_iprint_0(self):

        prob = Problem()
        prob.model = SellarDerivatives()
        newton = prob.model.nonlinear_solver = NewtonSolver()
        scipy = prob.model.linear_solver = ScipyIterativeSolver()

        newton.options['maxiter'] = 1
        prob.setup(check=False)

        prob['y1'] = 10000
        prob['y2'] = -26

        newton.options['iprint'] = 0
        scipy.options['iprint'] = 0

        prob.run_model()
Пример #8
0
    def test_scalar(self):

        n = 1

        prob = Problem(model=Group())

        bal = BalanceComp()

        bal.add_balance('x')

        tgt = IndepVarComp(name='y_tgt', val=4)

        exec_comp = ExecComp('y=x**2', x={'value': 1}, y={'value': 1})

        prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt'])

        prob.model.add_subsystem(name='exec', subsys=exec_comp)

        prob.model.add_subsystem(name='balance', subsys=bal)

        prob.model.connect('y_tgt', 'balance.rhs:x')
        prob.model.connect('balance.x', 'exec.x')
        prob.model.connect('exec.y', 'balance.lhs:x')

        prob.model.linear_solver = DirectSolver()

        prob.model.nonlinear_solver = NewtonSolver()
        prob.model.nonlinear_solver.options['maxiter'] = 100
        prob.model.nonlinear_solver.options['iprint'] = 0

        prob.model.jacobian = DenseJacobian()

        prob.setup()

        prob['balance.x'] = np.random.rand(n)

        prob.run_model()

        assert_almost_equal(prob['balance.x'], 2.0, decimal=7)

        np.set_printoptions(linewidth=1024)

        cpd = prob.check_partials()

        for (of, wrt) in cpd['balance']:
            assert_almost_equal(cpd['balance'][of, wrt]['abs error'], 0.0, decimal=5)
Пример #9
0
    def test_feature_post_setup_solver_configure(self):
        from openmdao.api import Problem, Group, ImplicitComponent, NewtonSolver, ScipyIterativeSolver, NonlinearBlockGS

        class ImplSimple(ImplicitComponent):
            def setup(self):
                self.add_input('a', val=1.)
                self.add_output('x', val=0.)

            def apply_nonlinear(self, inputs, outputs, residuals):
                residuals['x'] = np.exp(outputs['x']) - \
                    inputs['a']**2 * outputs['x']**2

            def linearize(self, inputs, outputs, jacobian):
                jacobian['x', 'x'] = np.exp(outputs['x']) - \
                    2 * inputs['a']**2 * outputs['x']
                jacobian['x', 'a'] = -2 * inputs['a'] * outputs['x']**2

        class Sub(Group):
            def setup(self):
                self.add_subsystem('comp', ImplSimple())

                # This will not solve it
                self.nonlinear_solver = NonlinearBlockGS()

            def configure(self):
                # This will not solve it either.
                self.nonlinear_solver = NonlinearBlockGS()

        class Super(Group):
            def setup(self):
                self.add_subsystem('sub', Sub())

        top = Problem()
        top.model = Super()

        top.setup(check=False)

        # This will solve it.
        top.model.sub.nonlinear_solver = NewtonSolver()
        top.model.sub.linear_solver = ScipyIterativeSolver()

        self.assertTrue(
            isinstance(top.model.sub.nonlinear_solver, NewtonSolver))
        self.assertTrue(
            isinstance(top.model.sub.linear_solver, ScipyIterativeSolver))
Пример #10
0
    def setUp(self):

        thermo = Thermo(janaf, constants.AIR_MIX)

        self.prob = Problem()

        self.prob.model.add_subsystem(
            'flow_start', FlowStart(thermo_data=janaf, elements=AIR_MIX))
        self.prob.model.add_subsystem(
            'compressor',
            Compressor(map_data=AXI5,
                       design=False,
                       elements=AIR_MIX,
                       map_extrap=False))

        self.prob.model.set_input_defaults('compressor.s_PR', val=1.)
        self.prob.model.set_input_defaults('compressor.s_eff', val=1.)
        self.prob.model.set_input_defaults('compressor.s_Wc', val=1.)
        self.prob.model.set_input_defaults('compressor.s_Nc', val=1.)
        self.prob.model.set_input_defaults('compressor.map.alphaMap', val=0.)
        self.prob.model.set_input_defaults('compressor.Nmech', 0., units='rpm')
        self.prob.model.set_input_defaults('flow_start.P', 17., units='psi')
        self.prob.model.set_input_defaults('flow_start.T', 500., units='degR')
        self.prob.model.set_input_defaults('flow_start.W', 0., units='lbm/s')
        self.prob.model.set_input_defaults('compressor.area',
                                           50.,
                                           units='inch**2')

        connect_flow(self.prob.model, "flow_start.Fl_O", "compressor.Fl_I")

        newton = self.prob.model.nonlinear_solver = NewtonSolver()
        newton.options['atol'] = 1e-8
        newton.options['rtol'] = 1e-8
        newton.options['iprint'] = 2
        newton.options['maxiter'] = 10
        newton.options['solve_subsystems'] = True
        newton.options['max_sub_solves'] = 10
        newton.linesearch = BoundsEnforceLS()
        newton.linesearch.options['bound_enforcement'] = 'scalar'
        newton.linesearch.options['iprint'] = -1

        self.prob.model.linear_solver = DirectSolver(assemble_jac=True)

        self.prob.set_solver_print(level=-1)
        self.prob.setup(check=False)
Пример #11
0
    def test_feature_scalar_with_default_mult(self):
        from numpy.testing import assert_almost_equal
        from openmdao.api import Problem, Group, IndepVarComp, ExecComp, NewtonSolver, \
            DirectSolver, DenseJacobian, BalanceComp

        prob = Problem(model=Group())

        bal = BalanceComp()

        bal.add_balance('x', use_mult=True, mult_val=2.0)

        tgt = IndepVarComp(name='y_tgt', val=4)

        exec_comp = ExecComp('y=x**2', x={'value': 1}, y={'value': 1})

        prob.model.add_subsystem(name='target',
                                 subsys=tgt,
                                 promotes_outputs=['y_tgt'])

        prob.model.add_subsystem(name='exec', subsys=exec_comp)

        prob.model.add_subsystem(name='balance', subsys=bal)

        prob.model.connect('y_tgt', 'balance.rhs:x')
        prob.model.connect('balance.x', 'exec.x')
        prob.model.connect('exec.y', 'balance.lhs:x')

        prob.model.linear_solver = DirectSolver()

        prob.model.nonlinear_solver = NewtonSolver()
        prob.model.nonlinear_solver.options['maxiter'] = 100
        prob.model.nonlinear_solver.options['iprint'] = 0

        prob.model.jacobian = DenseJacobian()

        prob.setup(check=False)

        # A reasonable initial guess to find the positive root.
        prob['balance.x'] = 1.0

        prob.run_model()

        print('x = ', prob['balance.x'])

        assert_almost_equal(prob['balance.x'], np.sqrt(2), decimal=7)
Пример #12
0
    def test_feature_atol(self):
        import numpy as np

        from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, LinearBlockGS, ExecComp
        from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives

        prob = Problem()
        model = prob.model

        model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x'])
        model.add_subsystem('pz',
                            IndepVarComp('z', np.array([5.0, 2.0])),
                            promotes=['z'])

        model.add_subsystem('d1',
                            SellarDis1withDerivatives(),
                            promotes=['x', 'z', 'y1', 'y2'])
        model.add_subsystem('d2',
                            SellarDis2withDerivatives(),
                            promotes=['z', 'y1', 'y2'])

        model.add_subsystem('obj_cmp',
                            ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',
                                     z=np.array([0.0, 0.0]),
                                     x=0.0),
                            promotes=['obj', 'x', 'z', 'y1', 'y2'])

        model.add_subsystem('con_cmp1',
                            ExecComp('con1 = 3.16 - y1'),
                            promotes=['con1', 'y1'])
        model.add_subsystem('con_cmp2',
                            ExecComp('con2 = y2 - 24.0'),
                            promotes=['con2', 'y2'])

        model.linear_solver = DirectSolver()

        nlgbs = model.nonlinear_solver = NewtonSolver()
        nlgbs.options['atol'] = 1e-4

        prob.setup()

        prob.run_model()

        assert_rel_error(self, prob['y1'], 25.5882856302, .00001)
        assert_rel_error(self, prob['y2'], 12.05848819, .00001)
Пример #13
0
    def test_scalar_with_guess_func(self):

        n = 1

        model = Group(assembled_jac_type='dense')

        def guess_function(inputs, outputs, residuals):
            outputs['x'] = np.sqrt(inputs['rhs:x'])

        bal = BalanceComp(
            'x', guess_func=guess_function)  # test guess_func as kwarg

        tgt = IndepVarComp(name='y_tgt', val=4)

        exec_comp = ExecComp('y=x**2', x={'value': 1}, y={'value': 1})

        model.add_subsystem(name='target',
                            subsys=tgt,
                            promotes_outputs=['y_tgt'])
        model.add_subsystem(name='exec', subsys=exec_comp)
        model.add_subsystem(name='balance', subsys=bal)

        model.connect('y_tgt', 'balance.rhs:x')
        model.connect('balance.x', 'exec.x')
        model.connect('exec.y', 'balance.lhs:x')

        model.linear_solver = DirectSolver(assemble_jac=True)
        model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0)

        prob = Problem(model)
        prob.setup()

        prob['balance.x'] = np.random.rand(n)
        prob.run_model()

        assert_almost_equal(prob['balance.x'], 2.0, decimal=7)

        # should converge with no iteration due to the guess function
        self.assertEqual(model.nonlinear_solver._iter_count, 1)

        cpd = prob.check_partials(out_stream=None)
        for (of, wrt) in cpd['balance']:
            assert_almost_equal(cpd['balance'][of, wrt]['abs error'],
                                0.0,
                                decimal=5)
Пример #14
0
    def test_raise_error_on_singular_with_densejac(self):
        prob = Problem()
        model = prob.model

        comp = IndepVarComp()
        comp.add_output('dXdt:TAS', val=1.0)
        comp.add_output('accel_target', val=2.0)
        model.add_subsystem('des_vars', comp, promotes=['*'])

        teg = model.add_subsystem('thrust_equilibrium_group', subsys=Group())
        teg.add_subsystem('dynamics',
                          ExecComp('z = 2.0*thrust'),
                          promotes=['*'])

        thrust_bal = BalanceComp()
        thrust_bal.add_balance(name='thrust',
                               val=1207.1,
                               lhs_name='dXdt:TAS',
                               rhs_name='accel_target',
                               eq_units='m/s**2',
                               lower=-10.0,
                               upper=10000.0)

        teg.add_subsystem(name='thrust_bal',
                          subsys=thrust_bal,
                          promotes_inputs=['dXdt:TAS', 'accel_target'],
                          promotes_outputs=['thrust'])

        teg.linear_solver = DirectSolver(assemble_jac=True)
        teg.options['assembled_jac_type'] = 'dense'

        teg.nonlinear_solver = NewtonSolver()
        teg.nonlinear_solver.options['solve_subsystems'] = True
        teg.nonlinear_solver.options['max_sub_solves'] = 1
        teg.nonlinear_solver.options['atol'] = 1e-4

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

        with self.assertRaises(RuntimeError) as cm:
            prob.run_model()

        expected_msg = "Singular entry found in 'thrust_equilibrium_group' for column associated with state/residual 'thrust'."

        self.assertEqual(expected_msg, str(cm.exception))
Пример #15
0
    def test_feature_iprint_neg1(self):

        prob = Problem()
        prob.model = SellarDerivatives()
        newton = prob.model.nonlinear_solver = NewtonSolver()
        scipy = prob.model.linear_solver = ScipyIterativeSolver()

        newton.options['maxiter'] = 2
        prob.setup(check=False)

        # use a real bad initial guess
        prob['y1'] = 10000
        prob['y2'] = -26

        newton.options['iprint'] = -1
        scipy.options['iprint'] = -1
        prob.run_model()
        print('done')
Пример #16
0
    def setUp(self):

        p = Problem()

        p.model = Group()
        p.model.cite = "foobar model"
        p.model.nonlinear_solver.cite = "foobar nonlinear_solver"
        p.model.linear_solver.cite = "foobar linear_solver"

        indeps = p.model.add_subsystem('indeps', IndepVarComp('x', 10), promotes=['*'])
        indeps.linear_solver = LinearRunOnce()

        ec = p.model.add_subsystem('ec', ExecComp('y = 2+3*x'), promotes=['*'])
        # note using newton here makes no sense in reality, but its fine for this test since we never run the model
        ec.nonlinear_solver = NewtonSolver()
        ec.cite = "foobar exec comp"

        self.prob = p
Пример #17
0
def define_analysis(n_int_per_seg):
    """
    This function sets up the problem with all DVs and constraints necessary to perform analysis only (drives throttle residuals and BFL residuals to zero).
    This does NOT ensure that the airplane has enough fuel capacity or gross weight to fly the mission.
    """
    prob = Problem()
    prob.model = TotalAnalysis(n_int_per_seg=n_int_per_seg)

    prob.model.options['assembled_jac_type'] = 'csc'
    prob.model.nonlinear_solver = NewtonSolver()
    prob.model.linear_solver = DirectSolver(assemble_jac=True)
    prob.model.nonlinear_solver.options['solve_subsystems'] = True
    prob.model.nonlinear_solver.options['maxiter'] = 10
    prob.model.nonlinear_solver.options['atol'] = 1e-6
    prob.model.nonlinear_solver.options['rtol'] = 1e-6

    prob.driver = ScipyOptimizeDriver()
    return prob
Пример #18
0
    def setup_solvers(self, phase):
        """
        Add a NewtonSolver to converge continuity errors in the state between steps.

        Parameters
        ----------
        phase
            The phase to which this transcription instance applies.

        Returns
        -------

        """
        phase.nonlinear_solver = NewtonSolver()
        phase.nonlinear_solver.options['iprint'] = -1
        phase.nonlinear_solver.options['solve_subsystems'] = True
        phase.nonlinear_solver.options['err_on_maxiter'] = True
        phase.nonlinear_solver.linesearch = BoundsEnforceLS()
Пример #19
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 = Problem(model=SellarStateConnection(
            nonlinear_solver=NewtonSolver()))

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

        prob.setup(check=False)
        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)
Пример #20
0
        def runs_successfully(use_scal, coeffs):
            prob = Problem(model=Group())
            prob.model.add_subsystem('row1', ScalingTestComp(row=1, coeffs=coeffs,
                                                             use_scal=use_scal))
            prob.model.add_subsystem('row2', ScalingTestComp(row=2, coeffs=coeffs,
                                                             use_scal=use_scal))
            prob.model.connect('row1.y', 'row2.x')
            prob.model.connect('row2.y', 'row1.x')
            prob.model.nonlinear_solver = NewtonSolver(maxiter=2, atol=1e-5, rtol=0)
            prob.model.nonlinear_solver.linear_solver = ScipyKrylov(maxiter=1)

            prob.set_solver_print(level=0)

            prob.setup(check=False)
            result = prob.run_model()

            success = not result[0]
            return success
Пример #21
0
    def test_complex_step(self):

        n = 1

        prob = Problem(model=Group(assembled_jac_type='dense'))

        bal = BalanceComp()

        bal.add_balance('x')

        tgt = IndepVarComp(name='y_tgt', val=4)

        exec_comp = ExecComp('y=x**2', x={'value': 1}, y={'value': 1})

        prob.model.add_subsystem(name='target',
                                 subsys=tgt,
                                 promotes_outputs=['y_tgt'])

        prob.model.add_subsystem(name='exec', subsys=exec_comp)

        prob.model.add_subsystem(name='balance', subsys=bal)

        prob.model.connect('y_tgt', 'balance.rhs:x')
        prob.model.connect('balance.x', 'exec.x')
        prob.model.connect('exec.y', 'balance.lhs:x')

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

        prob.model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0)

        prob.setup(force_alloc_complex=True)

        prob['balance.x'] = np.random.rand(n)

        prob.run_model()

        with warnings.catch_warnings():
            warnings.filterwarnings(action="error", category=np.ComplexWarning)
            cpd = prob.check_partials(out_stream=None, method='cs')

        for (of, wrt) in cpd['balance']:
            assert_almost_equal(cpd['balance'][of, wrt]['abs error'],
                                0.0,
                                decimal=10)
Пример #22
0
    def test_vectorized_with_default_mult(self):
        """
        solve:  2 * x**2 = 4
        expected solution:  x=sqrt(2)
        """

        n = 100

        prob = Problem(model=Group(assembled_jac_type='dense'))

        bal = BalanceComp('x', val=np.ones(n), use_mult=True, mult_val=2.0)

        tgt = IndepVarComp(name='y_tgt', val=4 * np.ones(n))

        exec_comp = ExecComp('y=x**2', x={'value': np.ones(n)}, y={'value': np.ones(n)})

        prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt'])

        prob.model.add_subsystem(name='exec', subsys=exec_comp)

        prob.model.add_subsystem(name='balance', subsys=bal)

        prob.model.connect('y_tgt', 'balance.rhs:x')
        prob.model.connect('balance.x', 'exec.x')
        prob.model.connect('exec.y', 'balance.lhs:x')

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

        prob.model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0)

        prob.setup()

        prob['balance.x'] = np.random.rand(n)

        prob.run_model()

        assert_almost_equal(prob['balance.x'], np.sqrt(2), decimal=7)

        with printoptions(linewidth=1024):

            cpd = prob.check_partials()

            for (of, wrt) in cpd['balance']:
                assert_almost_equal(cpd['balance'][of, wrt]['abs error'], 0.0, decimal=5)
Пример #23
0
    def test_error_under_cs(self):
        """Verify that PETScKrylov abides by the 'maxiter' option."""
        prob = Problem()
        model = prob.model = Group()

        model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x'])
        model.add_subsystem('pz',
                            IndepVarComp('z', np.array([5.0, 2.0])),
                            promotes=['z'])

        model.add_subsystem('d1',
                            SellarDis1withDerivatives(),
                            promotes=['x', 'z', 'y1', 'y2'])
        model.add_subsystem('d2',
                            SellarDis2withDerivatives(),
                            promotes=['z', 'y1', 'y2'])

        model.add_subsystem('obj_cmp',
                            ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',
                                     z=np.array([0.0, 0.0]),
                                     x=0.0),
                            promotes=['obj', 'x', 'z', 'y1', 'y2'])

        model.add_subsystem('con_cmp1',
                            ExecComp('con1 = 3.16 - y1'),
                            promotes=['con1', 'y1'])
        model.add_subsystem('con_cmp2',
                            ExecComp('con2 = y2 - 24.0'),
                            promotes=['con2', 'y2'])

        model.nonlinear_solver = NewtonSolver()
        model.linear_solver = PETScKrylov()

        model.approx_totals(method='cs')

        prob.setup(mode='fwd')
        prob.set_solver_print(level=0)
        prob.run_model()

        with self.assertRaises(RuntimeError) as cm:
            J = prob.compute_totals(of=['obj'], wrt=['z'])

        msg = 'PETScKrylov solver is not supported under complex step.'
        self.assertEqual(str(cm.exception), msg)
Пример #24
0
    def test_post_setup_solver_configure(self):
        # Test that we can change solver settings after we have instantiated our model.

        class ImplSimple(ImplicitComponent):
            def setup(self):
                self.add_input('a', val=1.)
                self.add_output('x', val=0.)

            def apply_nonlinear(self, inputs, outputs, residuals):
                residuals['x'] = np.exp(outputs['x']) - \
                    inputs['a']**2 * outputs['x']**2

            def linearize(self, inputs, outputs, jacobian):
                jacobian['x', 'x'] = np.exp(outputs['x']) - \
                    2 * inputs['a']**2 * outputs['x']
                jacobian['x', 'a'] = -2 * inputs['a'] * outputs['x']**2

        class Sub(Group):
            def setup(self):
                self.add_subsystem('comp', ImplSimple())

                # This solver will get over-ridden below
                self.nonlinear_solver = NonlinearBlockGS()

            def configure(self):
                # This solver will get over-ridden below
                self.nonlinear_solver = NonlinearBlockGS()

        class Super(Group):
            def setup(self):
                self.add_subsystem('sub', Sub())

        top = Problem()
        top.model = Super()

        top.setup(check=False)

        # These solvers override the ones set in the setup method of the 'sub' groups
        top.model.sub.nonlinear_solver = NewtonSolver()
        top.model.sub.linear_solver = ScipyKrylov()

        self.assertTrue(
            isinstance(top.model.sub.nonlinear_solver, NewtonSolver))
        self.assertTrue(isinstance(top.model.sub.linear_solver, ScipyKrylov))
Пример #25
0
    def test_derivs(self):
        n = 1
        p = Problem(model=Group())

        ivc = IndepVarComp()
        ivc.add_output('gap', val=.001, units='m')
        ivc.add_output('w_slot', val=.01508251, units='m')
        ivc.add_output('w_t', val=.0047909798, units='m')
        ivc.add_output('t_mag', val=.0044, units='m')
        ivc.add_output('Br_20', val=1.39, units='T')
        ivc.add_output('T_coef_rem_mag', val=.00393)
        ivc.add_output('T_mag', val=100, units='C')
        ivc.add_output('k_sat', val=1)
        ivc.add_output('mu_r', val=1, units='H/m')
        ivc.add_output('n_m', val=20)
        ivc.add_output('n_turns', val=12)
        ivc.add_output('I', val=34.35, units='A')
        ivc.add_output('rot_or', val=.06841554332, units='m')
        ivc.add_output('P_shaft', val=14.0, units='kW')
        ivc.add_output('rpm', val=2000, units='rpm')
        ivc.add_output('stack_length', val=.0345, units='m')
        ivc.add_output('P_wire', val=396, units='W')
        ivc.add_output('P_steinmetz', val=260, units='W')

        p.model.add_subsystem('ivc', ivc, promotes_outputs=['*'])
        p.model.add_subsystem(name='em', subsys=EmGroup(num_nodes=n))

        p.model.connect('P_shaft', 'em.P_shaft')
        p.model.connect('P_wire', 'em.P_wire')
        p.model.connect('P_steinmetz', 'em.P_steinmetz')

        p.model.linear_solver = DirectSolver()
        p.model.nonlinear_solver = NewtonSolver()

        p.setup(force_alloc_complex=True)

        p['P_shaft'] = 10

        p.run_model()

        data = p.check_partials(method='cs',
                                compact_print=True,
                                show_only_incorrect=True)
        assert_check_partials(data, atol=1e-6, rtol=1e-6)
Пример #26
0
    def test_scalar(self):

        n = 1

        prob = Problem(model=Group(assembled_jac_type='dense'))

        bal = BalanceComp()

        bal.add_balance('x')

        tgt = IndepVarComp(name='y_tgt', val=4)

        exec_comp = ExecComp('y=x**2', x={'value': 1}, y={'value': 1})

        prob.model.add_subsystem(name='target',
                                 subsys=tgt,
                                 promotes_outputs=['y_tgt'])

        prob.model.add_subsystem(name='exec', subsys=exec_comp)

        prob.model.add_subsystem(name='balance', subsys=bal)

        prob.model.connect('y_tgt', 'balance.rhs:x')
        prob.model.connect('balance.x', 'exec.x')
        prob.model.connect('exec.y', 'balance.lhs:x')

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

        prob.model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0)

        prob.setup()

        prob['balance.x'] = np.random.rand(n)

        prob.run_model()

        assert_almost_equal(prob['balance.x'], 2.0, decimal=7)

        cpd = prob.check_partials(out_stream=None)

        for (of, wrt) in cpd['balance']:
            assert_almost_equal(cpd['balance'][of, wrt]['abs error'],
                                0.0,
                                decimal=5)
Пример #27
0
    def test_guess_nonlinear_transfer_subbed2(self):
        # Test that data is transfered to a component before calling guess_nonlinear.

        class ImpWithInitial(ImplicitComponent):

            def setup(self):
                self.add_input('x', 3.0)
                self.add_output('y', 4.0)

            def solve_nonlinear(self, inputs, outputs):
                """ Do nothing. """
                pass

            def apply_nonlinear(self, inputs, outputs, resids):
                """ Do nothing. """
                resids['y'] = 1.0e-6
                pass

            def guess_nonlinear(self, inputs, outputs, resids):
                # Passthrough
                outputs['y'] = inputs['x']


        group = Group()
        sub = Group()

        group.add_subsystem('px', IndepVarComp('x', 77.0))
        sub.add_subsystem('comp1', ImpWithInitial())
        sub.add_subsystem('comp2', ImpWithInitial())
        group.connect('px.x', 'sub.comp1.x')
        group.connect('sub.comp1.y', 'sub.comp2.x')

        group.add_subsystem('sub', sub)

        sub.nonlinear_solver = NewtonSolver()
        sub.nonlinear_solver.options['maxiter'] = 1

        prob = Problem(model=group)
        prob.set_solver_print(level=0)
        prob.setup(check=False)

        prob.run_model()
        assert_rel_error(self, prob['sub.comp2.y'], 77., 1e-5)
Пример #28
0
    def test_feature_scalar(self):
        from numpy.testing import assert_almost_equal
        from openmdao.api import Problem, Group, IndepVarComp, ExecComp, NewtonSolver, \
            DirectSolver, BalanceComp

        prob = Problem(model=Group(assembled_jac_type='dense'))

        bal = BalanceComp()

        bal.add_balance('x', use_mult=True)

        tgt = IndepVarComp(name='y_tgt', val=4)

        mult_ivc = IndepVarComp(name='mult', val=2.0)

        exec_comp = ExecComp('y=x**2', x={'value': 1}, y={'value': 1})

        prob.model.add_subsystem(name='target', subsys=tgt, promotes_outputs=['y_tgt'])
        prob.model.add_subsystem(name='mult_comp', subsys=mult_ivc, promotes_outputs=['mult'])

        prob.model.add_subsystem(name='exec', subsys=exec_comp)

        prob.model.add_subsystem(name='balance', subsys=bal)

        prob.model.connect('y_tgt', 'balance.rhs:x')
        prob.model.connect('mult', 'balance.mult:x')
        prob.model.connect('balance.x', 'exec.x')
        prob.model.connect('exec.y', 'balance.lhs:x')

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

        prob.model.nonlinear_solver = NewtonSolver(maxiter=100, iprint=0)

        prob.setup(check=False)

        # A reasonable initial guess to find the positive root.
        prob['balance.x'] = 1.0

        prob.run_model()

        print('x = ', prob['balance.x'])

        assert_almost_equal(prob['balance.x'], np.sqrt(2), decimal=7)
Пример #29
0
    def test_simple_implicit_apply(self):

        prob = Problem(Group())
        prob.model.add_subsystem('p1', IndepVarComp('x', 0.5))
        prob.model.add_subsystem('comp', SimpleImplicitCompApply())

        prob.model.linear_solver = ScipyGMRES()
        prob.model.nonlinear_solver = NewtonSolver()
        prob.set_solver_print(level=0)

        prob.model.connect('p1.x', 'comp.x')

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

        assert_rel_error(self, prob['comp.z'], 2.666, 1e-3)
        self.assertLess(prob.model.nonlinear_solver._iter_count, 5)

        J = prob.compute_totals(of=['comp.y', 'comp.z'], wrt=['p1.x'])
        assert_rel_error(self, J[('comp.y', 'p1.x')][0][0], -2.5555511, 1e-5)
        assert_rel_error(self, J[('comp.z', 'p1.x')][0][0], -1.77777777, 1e-5)

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

        assert_rel_error(self, prob['comp.z'], 2.666, 1e-3)
        self.assertLess(prob.model.nonlinear_solver._iter_count, 5)

        J = prob.compute_totals(of=['comp.y', 'comp.z'], wrt=['p1.x'])
        assert_rel_error(self, J[('comp.y', 'p1.x')][0][0], -2.5555511, 1e-5)
        assert_rel_error(self, J[('comp.z', 'p1.x')][0][0], -1.77777777, 1e-5)

        # Check partials
        data = prob.check_partials()

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)
Пример #30
0
    def test_specify_precon_left(self):

        prob = Problem()
        model = prob.model = Group()

        model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x'])
        model.add_subsystem('pz',
                            IndepVarComp('z', np.array([5.0, 2.0])),
                            promotes=['z'])

        model.add_subsystem('d1',
                            SellarDis1withDerivatives(),
                            promotes=['x', 'z', 'y1', 'y2'])
        model.add_subsystem('d2',
                            SellarDis2withDerivatives(),
                            promotes=['z', 'y1', 'y2'])

        model.add_subsystem('obj_cmp',
                            ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',
                                     z=np.array([0.0, 0.0]),
                                     x=0.0),
                            promotes=['obj', 'x', 'z', 'y1', 'y2'])

        model.add_subsystem('con_cmp1',
                            ExecComp('con1 = 3.16 - y1'),
                            promotes=['con1', 'y1'])
        model.add_subsystem('con_cmp2',
                            ExecComp('con2 = y2 - 24.0'),
                            promotes=['con2', 'y2'])

        model.nonlinear_solver = NewtonSolver()
        model.linear_solver = PetscKSP()

        model.linear_solver.precon = DirectSolver()
        model.linear_solver.options['precon_side'] = 'left'
        model.linear_solver.options['ksp_type'] = 'richardson'

        prob.setup()
        prob.run_model()

        assert_rel_error(self, prob['y1'], 25.58830273, .00001)
        assert_rel_error(self, prob['y2'], 12.05848819, .00001)
Пример #31
0
    def test_jacobian_changed_group(self):
        prob = Problem()
        model = prob.model = Group()

        model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x'])
        model.add_subsystem('pz',
                            IndepVarComp('z', np.array([5.0, 2.0])),
                            promotes=['z'])

        model.add_subsystem('d1',
                            SellarDis1withDerivatives(),
                            promotes=['x', 'z', 'y1', 'y2'])
        model.add_subsystem('d2',
                            SellarDis2withDerivatives(),
                            promotes=['z', 'y1', 'y2'])

        model.add_subsystem('obj_cmp',
                            ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',
                                     z=np.array([0.0, 0.0]),
                                     x=0.0),
                            promotes=['obj', 'x', 'z', 'y1', 'y2'])

        model.add_subsystem('con_cmp1',
                            ExecComp('con1 = 3.16 - y1'),
                            promotes=['con1', 'y1'])
        model.add_subsystem('con_cmp2',
                            ExecComp('con2 = y2 - 24.0'),
                            promotes=['con2', 'y2'])

        model.nonlinear_solver = NewtonSolver()
        model.linear_solver = ScipyKrylov()

        prob.model.jacobian = DenseJacobian()

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

        prob.model.jacobian = DenseJacobian()

        msg = ": jacobian has changed and setup was not called."
        with assertRaisesRegex(self, Exception, msg):
            prob.run_model()
Пример #32
0
    def test_component_assembled_jac(self):
        prob = Problem()
        model = prob.model = Group()

        model.add_subsystem('px', IndepVarComp('x', 1.0), promotes=['x'])
        model.add_subsystem('pz',
                            IndepVarComp('z', np.array([5.0, 2.0])),
                            promotes=['z'])

        model.add_subsystem('d1',
                            SellarDis1withDerivatives(),
                            promotes=['x', 'z', 'y1', 'y2'])
        model.add_subsystem('d2',
                            SellarDis2withDerivatives(),
                            promotes=['z', 'y1', 'y2'])

        model.add_subsystem('obj_cmp',
                            ExecComp('obj = x**2 + z[1] + y1 + exp(-y2)',
                                     z=np.array([0.0, 0.0]),
                                     x=0.0),
                            promotes=['obj', 'x', 'z', 'y1', 'y2'])

        model.add_subsystem('con_cmp1',
                            ExecComp('con1 = 3.16 - y1'),
                            promotes=['con1', 'y1'])
        model.add_subsystem('con_cmp2',
                            ExecComp('con2 = y2 - 24.0'),
                            promotes=['con2', 'y2'])

        model.nonlinear_solver = NewtonSolver()
        model.linear_solver = ScipyKrylov()

        d1 = prob.model.d1

        d1.jacobian = DenseJacobian()
        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['y2'], 12.05848819, .00001)