Example #1
0
    def test_feature_newton_basic(self):
        """ Feature test for slotting a Newton solver and using it to solve
        Sellar.
        """
        import openmdao.api as om
        from openmdao.test_suite.components.sellar import SellarDerivatives

        prob = om.Problem(model=SellarDerivatives(
            nonlinear_solver=om.NewtonSolver()))

        prob.setup()
        prob.run_model()

        assert_rel_error(self, prob['y1'], 25.58830273, .00001)
        assert_rel_error(self, prob['y2'], 12.05848819, .00001)
Example #2
0
    def test_sellar_grouped(self):
        # Tests basic Newton solution on Sellar in a subgroup

        prob = om.Problem(model=SellarDerivativesGrouped(
            nonlinear_solver=om.NewtonSolver()))

        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['y2'], 12.05848819, .00001)

        # Make sure we aren't iterating like crazy
        self.assertLess(prob.model.nonlinear_solver._iter_count, 8)
Example #3
0
    def test_specify_newton_linear_solver_in_system(self):

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

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

        prob.setup()

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

        prob.run_model()

        assert_rel_error(self, prob['y1'], 25.58830273, .00001)
        assert_rel_error(self, prob['y2'], 12.05848819, .00001)
Example #4
0
    def test_error_specify_solve_subsystems(self):
        # Raise AnalysisError when it fails to converge

        prob = om.Problem()
        model = prob.model

        model.nonlinear_solver = om.NewtonSolver()

        prob.setup()

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

        msg = "NewtonSolver in <model> <class Group>: solve_subsystems must be set by the user."
        self.assertEqual(str(context.exception), msg)
Example #5
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)
Example #6
0
    def test_solve_subsystems_assembled_jac_top_csc(self):
        prob = om.Problem(model=DoubleSellar())
        model = prob.model

        g1 = model.g1
        g1.nonlinear_solver = om.NewtonSolver(solve_subsystems=False,
                                              rtol=1.0e-5)
        g1.linear_solver = om.DirectSolver()

        g2 = model.g2
        g2.nonlinear_solver = om.NewtonSolver(solve_subsystems=False,
                                              rtol=1.0e-5)
        g2.linear_solver = om.DirectSolver()

        model.nonlinear_solver = om.NewtonSolver(solve_subsystems=True)
        model.linear_solver = om.ScipyKrylov(assemble_jac=True)

        prob.setup()
        prob.run_model()

        assert_near_equal(prob['g1.y1'], 0.64, .00001)
        assert_near_equal(prob['g1.y2'], 0.80, .00001)
        assert_near_equal(prob['g2.y1'], 0.64, .00001)
        assert_near_equal(prob['g2.y2'], 0.80, .00001)
Example #7
0
    def test_feature_newton_basic(self):
        """ Feature test for slotting a Newton solver and using it to solve
        Sellar.
        """
        import openmdao.api as om
        from openmdao.test_suite.components.sellar import SellarDerivatives

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

        prob.setup()
        prob.run_model()

        assert_near_equal(prob.get_val('y1'), 25.58830273, .00001)
        assert_near_equal(prob.get_val('y2'), 12.05848819, .00001)
Example #8
0
    def setUp(self):
        top = om.Problem()
        top.model.add_subsystem('px', om.IndepVarComp('x', np.ones((3, 1))))
        top.model.add_subsystem('comp', ImplCompTwoStatesArrays())
        top.model.connect('px.x', 'comp.x')

        top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)
        top.model.nonlinear_solver.options['maxiter'] = 10
        top.model.linear_solver = om.ScipyKrylov()

        top.set_solver_print(level=0)
        top.setup()

        self.top = top
        self.ub = np.array([2.6, 2.5, 2.65])
    def setup(self):
        indeps = self.add_subsystem('indeps', om.IndepVarComp(), promotes=['*'])
        indeps.add_output('l', 0.01)
        indeps.add_output('w', 0.01)
        
        cycle = self.add_subsystem('cycle', om.Group(), promotes=['*'])
        cycle.add_subsystem('d1', Structures(), promotes_inputs=['l', 'F'], promotes_outputs=['theta'])
        cycle.add_subsystem('d2', Aerodynamics(), promotes_inputs=['l', 'w','theta'], promotes_outputs=['F'])

        ns = cycle.nonlinear_solver = om.NewtonSolver(solve_subsystems=True) 
        ns.options['maxiter'] = 500   

        self.add_subsystem('obj_cmp', om.ExecComp('obj = (theta - 0.250)**2'), promotes=['theta','obj'])       
        self.add_subsystem('con_cmp1', om.ExecComp('con1 = F - 7'), promotes=['con1', 'F'])
        self.add_subsystem('con_cmp2', om.ExecComp('con2 = l*w - 0.01'), promotes=['con2', 'l','w'])
Example #10
0
    def test_solve_subsystems_basic_csc(self):
        prob = om.Problem(model=DoubleSellar())
        model = prob.model

        g1 = model.g1
        g1.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5)
        g1.options['assembled_jac_type'] = 'dense'
        g1.linear_solver = om.DirectSolver(assemble_jac=True)

        g2 = model.g2
        g2.nonlinear_solver = om.NewtonSolver(rtol=1.0e-5)
        g2.linear_solver = om.DirectSolver(assemble_jac=True)
        g2.options['assembled_jac_type'] = 'dense'

        model.nonlinear_solver = om.NewtonSolver(solve_subsystems=True)
        model.linear_solver = om.ScipyKrylov(assemble_jac=True)

        prob.setup()
        prob.run_model()

        assert_rel_error(self, prob['g1.y1'], 0.64, .00001)
        assert_rel_error(self, prob['g1.y2'], 0.80, .00001)
        assert_rel_error(self, prob['g2.y1'], 0.64, .00001)
        assert_rel_error(self, prob['g2.y2'], 0.80, .00001)
Example #11
0
    def test_vectorized_no_normalization(self):

        n = 100

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

        bal = om.BalanceComp()

        bal.add_balance('x', val=np.ones(n), normalize=False)

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

        exec_comp = om.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 = om.DirectSolver(assemble_jac=True)

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

        prob.setup()

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

        prob.run_model()

        assert_almost_equal(prob['balance.x'], np.sqrt(1.7), 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)
Example #12
0
    def test_error_handling(self):
        # Make sure the debug_print doesn't bomb out.

        class Bad(om.ExplicitComponent):
            def setup(self):
                self.add_input('x', val=0.0)
                self.add_input('y', val=0.0)

                self.add_output('f_xy', val=0.0, upper=1.0)

                self.declare_partials(of='*', wrt='*')
                self.count = 0

            def compute(self, inputs, outputs):
                if self.count < 1:
                    x = inputs['x']
                    y = inputs['y']
                    outputs['f_xy'] = (x - 3.0)**2 + x * y + (y + 4.0)**2 - 3.0
                else:
                    outputs['f_xy'] = np.inf

                self.count += 1

            def compute_partials(self, inputs, partials):
                x = inputs['x']
                y = inputs['y']

                partials['f_xy', 'x'] = 2.0 * x - 6.0 + y
                partials['f_xy', 'y'] = 2.0 * y + 8.0 + x

        top = om.Problem()
        top.model.add_subsystem('px', om.IndepVarComp('x', 1.0))
        top.model.add_subsystem('comp', ImplCompTwoStates())
        top.model.add_subsystem('par', Bad())
        top.model.connect('px.x', 'comp.x')
        top.model.connect('comp.z', 'par.x')

        top.model.nonlinear_solver = om.NewtonSolver()
        top.model.nonlinear_solver.options['maxiter'] = 3

        top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(
            bound_enforcement='vector')
        top.set_solver_print(level=0)

        top.setup()

        # Make sure we don't raise an error when we reach the final debug print.
        top.run_model()
Example #13
0
    def test_feature_linear_solver(self):
        import numpy as np

        import openmdao.api as om
        from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, \
             SellarDis2withDerivatives

        prob = om.Problem()
        model = prob.model

        model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])
        model.add_subsystem('pz',
                            om.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',
                            om.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',
                            om.ExecComp('con1 = 3.16 - y1'),
                            promotes=['con1', 'y1'])
        model.add_subsystem('con_cmp2',
                            om.ExecComp('con2 = y2 - 24.0'),
                            promotes=['con2', 'y2'])

        model.linear_solver = om.LinearBlockGS()

        newton = model.nonlinear_solver = om.NewtonSolver(
            solve_subsystems=False)

        newton.linear_solver = om.DirectSolver()

        prob.setup()

        prob.run_model()

        assert_rel_error(self, prob['y1'], 25.58830273, .00001)
        assert_rel_error(self, prob['y2'], 12.05848819, .00001)
Example #14
0
    def configure_solvers(self, phase):
        """
        Configure the solvers.

        Parameters
        ----------
        phase : dymos.Phase
            The phase object to which this transcription instance applies.
        """
        if self.any_solved_segs or self.any_connected_opt_segs:
            newton = phase.nonlinear_solver = om.NewtonSolver()
            newton.options['solve_subsystems'] = True
            newton.options['maxiter'] = 100
            newton.options['iprint'] = -1
            newton.linesearch = om.BoundsEnforceLS()
            phase.linear_solver = om.DirectSolver()
Example #15
0
    def test_specify_newton_linear_solver_in_system(self):

        my_newton = om.NewtonSolver(solve_subsystems=False)
        my_newton.linear_solver = om.DirectSolver()

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

        prob.setup()

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

        prob.run_model()

        assert_near_equal(prob.get_val('y1'), 25.58830273, .00001)
        assert_near_equal(prob.get_val('y2'), 12.05848819, .00001)
Example #16
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=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)
Example #17
0
    def test_comm_warning(self):

        rank = MPI.COMM_WORLD.rank if MPI is not None else 0

        prob = om.Problem(model=SellarDerivatives(nonlinear_solver=om.NewtonSolver()))

        prob.setup()

        msg = 'Deprecation warning: In V 3.0, the default Newton solver setup will change ' + \
              'to use the BoundsEnforceLS line search.'
        if rank == 0:
            with assert_warning(DeprecationWarning, msg):
                prob.final_setup()
        else:
            with assert_no_warning(DeprecationWarning, msg):
                prob.final_setup()
Example #18
0
    def test_feature_err_on_non_converge(self):
        import numpy as np

        import openmdao.api as om
        from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, SellarDis2withDerivatives

        prob = om.Problem()
        model = prob.model

        model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])
        model.add_subsystem('pz',
                            om.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',
                            om.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',
                            om.ExecComp('con1 = 3.16 - y1'),
                            promotes=['con1', 'y1'])
        model.add_subsystem('con_cmp2',
                            om.ExecComp('con2 = y2 - 24.0'),
                            promotes=['con2', 'y2'])

        model.linear_solver = om.DirectSolver()

        newton = model.nonlinear_solver = om.NewtonSolver(
            solve_subsystems=False)
        newton.options['maxiter'] = 1
        newton.options['err_on_non_converge'] = True

        prob.setup()

        try:
            prob.run_model()
        except om.AnalysisError:
            pass
Example #19
0
    def test_vectorized_with_default_mult(self):
        """
        solve:  2 * x**2 = 4
        expected solution:  x=sqrt(2)
        """

        n = 100

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

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

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

        exec_comp = om.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 = om.DirectSolver(assemble_jac=True)

        prob.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False,
                                                      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)

        cpd = prob.check_partials(out_stream=None)

        assert_check_partials(cpd, atol=1e-5, rtol=1e-5)
Example #20
0
    def test_scalar_example(self):

        prob = om.Problem()

        bal = om.BalanceComp()
        bal.add_balance('x', val=1.0)

        tgt = om.IndepVarComp(name='y_tgt', val=2)

        exec_comp = om.ExecComp('y=x**2')

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

        # do one test in an unconverged state, to capture accuracy of partials
        prob.setup()

        prob[
            'y_tgt'] = 100000  #set rhs and lhs to very different values. Trying to capture some derivatives wrt
        prob['exec.y'] = .001

        prob.run_model()

        cpd = prob.check_partials(out_stream=None)

        assert_check_partials(cpd, atol=2e-5, rtol=2e-5)

        # set an actual solver, and re-setup. Then check derivatives at a converged point
        prob.model.linear_solver = om.DirectSolver()
        prob.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)

        prob.setup()

        prob.run_model()

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

        cpd = prob.check_partials(out_stream=None)

        assert_check_partials(cpd, atol=1e-5, rtol=1e-5)
    def test_specify_precon_left(self):
        import numpy as np

        import openmdao.api as om
        from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, \
             SellarDis2withDerivatives

        prob = om.Problem()
        model = prob.model

        model.add_subsystem('px', om.IndepVarComp('x', 1.0), promotes=['x'])
        model.add_subsystem('pz',
                            om.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',
                            om.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',
                            om.ExecComp('con1 = 3.16 - y1'),
                            promotes=['con1', 'y1'])
        model.add_subsystem('con_cmp2',
                            om.ExecComp('con2 = y2 - 24.0'),
                            promotes=['con2', 'y2'])

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

        model.linear_solver.precon = om.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)
Example #22
0
    def test_scalar_with_guess_func(self):

        n = 1

        model = om.Group(assembled_jac_type='dense')

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

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

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

        exec_comp = om.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 = om.DirectSolver(assemble_jac=True)
        model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False,
                                                 maxiter=100,
                                                 iprint=0)

        prob = om.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)
Example #23
0
    def test_raise_error_on_singular_with_densejac(self):
        prob = om.Problem()
        model = prob.model

        comp = om.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=om.Group())
        teg.add_subsystem('dynamics',
                          om.ExecComp('z = 2.0*thrust'),
                          promotes=['*'])

        thrust_bal = om.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 = om.DirectSolver(assemble_jac=True)
        teg.options['assembled_jac_type'] = 'dense'

        teg.nonlinear_solver = om.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()
        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))
    def setup(self):
        nn = self.options['num_nodes']

        self.add_subsystem('aero',
                           subsys=AerodynamicsGroup(num_nodes=nn),
                           promotes_inputs=['alt'])

        self.add_subsystem('thrust_eq_comp',
                           subsys=ThrustEquilibriumComp(num_nodes=nn),
                           promotes_inputs=['q', 'S', 'gam', 'alpha', 'W_total'],
                           promotes_outputs=['CT'])

        self.add_subsystem('lift_eq_comp',
                           subsys=LiftEquilibriumComp(num_nodes=nn),
                           promotes_inputs=['q', 'S', 'gam', 'alpha', 'W_total', 'CT'],
                           promotes_outputs=['CL_eq'])

        bal = self.add_subsystem(name='alpha_eta_balance',
                                 subsys=om.BalanceComp(),
                                 promotes_outputs=['alpha', 'eta'])

        self.connect('alpha', ('aero.alpha'))
        self.connect('eta', ('aero.eta'))

        bal.add_balance('alpha', units='rad', eq_units=None, lhs_name='CL_eq',
                        rhs_name='CL', val=0.01*np.ones(nn), lower=-20, upper=30, res_ref=1.0)

        bal.add_balance('eta', units='rad', val=0.01*np.ones(nn), eq_units=None, lhs_name='CM',
                        lower=-30, upper=30, res_ref=1.0)

        self.connect('aero.CL', 'alpha_eta_balance.CL')
        self.connect('aero.CD', 'thrust_eq_comp.CD')
        self.connect('aero.CM', 'alpha_eta_balance.CM')
        self.connect('CL_eq', ('alpha_eta_balance.CL_eq'))

        self.linear_solver = om.DirectSolver()
        self.nonlinear_solver = om.NewtonSolver()
        self.nonlinear_solver.options['atol'] = 1e-14
        self.nonlinear_solver.options['rtol'] = 1e-14
        self.nonlinear_solver.options['solve_subsystems'] = True
        self.nonlinear_solver.options['err_on_non_converge'] = True
        self.nonlinear_solver.options['max_sub_solves'] = 10
        self.nonlinear_solver.options['maxiter'] = 150
        self.nonlinear_solver.options['iprint'] = -1
        self.nonlinear_solver.linesearch = om.BoundsEnforceLS()
        self.nonlinear_solver.linesearch.options['print_bound_enforce'] = True
Example #25
0
 def generate_model(self, nn):
     prob = om.Problem()
     iv = prob.model.add_subsystem('iv',
                                   om.IndepVarComp(),
                                   promotes_outputs=['*'])
     iv.add_output('q_in', val=np.linspace(2000, 5000, nn), units='W')
     iv.add_output('mdot_coolant', val=1 * np.ones((nn, )), units='kg/s')
     iv.add_output('T_in', val=25 * np.ones((nn, )), units='degC')
     iv.add_output('battery_weight', val=100., units='kg')
     prob.model.add_subsystem('test',
                              LiquidCooledBattery(num_nodes=nn,
                                                  quasi_steady=True),
                              promotes=['*'])
     prob.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=True)
     prob.model.linear_solver = om.DirectSolver()
     prob.setup(check=True, force_alloc_complex=True)
     return prob
Example #26
0
    def test_complex_step(self):

        n = 1

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

        bal = om.BalanceComp()

        bal.add_balance('x')

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

        exec_comp = om.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 = om.DirectSolver(assemble_jac=True)

        prob.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False,
                                                      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)
Example #27
0
        def runs_successfully(use_scal, coeffs):
            prob = om.Problem()
            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 = om.NewtonSolver(maxiter=2, atol=1e-5, rtol=0)
            prob.model.nonlinear_solver.linear_solver = om.ScipyKrylov(maxiter=1)

            prob.set_solver_print(level=0)

            prob.setup()
            prob.run_model()

            return np.linalg.norm(prob.model._residuals._data) < 1e-5
Example #28
0
    def test_specify_precon(self):
        import numpy as np

        import openmdao.api as om
        from openmdao.test_suite.components.sellar import SellarDis1withDerivatives, \
             SellarDis2withDerivatives

        prob = om.Problem()
        model = prob.model

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

        model.add_subsystem('obj_cmp',
                            om.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',
                            om.ExecComp('con1 = 3.16 - y1'),
                            promotes=['con1', 'y1'])
        model.add_subsystem('con_cmp2',
                            om.ExecComp('con2 = y2 - 24.0'),
                            promotes=['con2', 'y2'])

        model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)
        model.linear_solver = om.PETScKrylov()

        model.linear_solver.precon = om.LinearBlockGS()
        model.linear_solver.precon.options['maxiter'] = 2

        prob.setup()

        prob.set_val('x', 1.)
        prob.set_val('z', np.array([5.0, 2.0]))

        prob.run_model()

        assert_near_equal(prob.get_val('y1'), 25.58830273, .00001)
        assert_near_equal(prob.get_val('y2'), 12.05848819, .00001)
Example #29
0
    def test_solver_debug_print_feature(self):
        from distutils.version import LooseVersion
        import numpy as np

        import openmdao.api as om
        from openmdao.test_suite.scripts.circuit_analysis import Circuit
        from openmdao.utils.general_utils import printoptions

        p = om.Problem()
        model = p.model

        model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V'))
        model.add_subsystem('source', om.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 = om.NewtonSolver(
            solve_subsystems=False)

        nl.options['iprint'] = 2
        nl.options['debug_print'] = True
        nl.options['err_on_non_converge'] = True

        # 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
            try:
                p.run_model()
            except om.AnalysisError:
                pass

        with open(self.filename, 'r') as f:
            self.assertEqual(f.read(), self.expected_data)
Example #30
0
            def setup(self):
                self.set_input_defaults('x', 1.0)
                self.set_input_defaults('z', np.array([5.0, 2.0]))

                cycle = self.add_subsystem('cycle', om.Group(), promotes=['*'])
                cycle.add_subsystem('d1',
                                    SellarDis1withDerivatives(),
                                    promotes_inputs=['x', 'z', 'y2'],
                                    promotes_outputs=['y1'])
                cycle.add_subsystem('d2',
                                    SellarDis2withDerivatives(),
                                    promotes_inputs=['z', 'y1'],
                                    promotes_outputs=['y2'])

                cycle.linear_solver = om.ScipyKrylov()

                cycle.nonlinear_solver = om.NewtonSolver(
                    solve_subsystems=False)