Ejemplo n.º 1
0
    def test_specify_subgroup_solvers(self):
        from openmdao.api import Problem, NewtonSolver, ScipyIterativeSolver, DirectSolver, NonlinearBlockGS, LinearBlockGS
        from openmdao.test_suite.components.double_sellar import DoubleSellar

        prob = Problem()
        model = prob.model = DoubleSellar()

        # each SubSellar group converges itself
        g1 = model.get_subsystem('g1')
        g1.nonlinear_solver = NewtonSolver()
        g1.linear_solver = DirectSolver()  # used for derivatives

        g2 = model.get_subsystem('g2')
        g2.nonlinear_solver = NewtonSolver()
        g2.linear_solver = DirectSolver()

        # Converge the outer loop with Gauss Seidel, with a looser tolerance.
        model.nonlinear_solver = NonlinearBlockGS()
        model.nonlinear_solver.options['rtol'] = 1.0e-5
        model.linear_solver = ScipyIterativeSolver()
        model.linear_solver.precon = LinearBlockGS()

        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)
Ejemplo n.º 2
0
    def test_with_subsolves(self):
        prob = Problem()
        model = prob.model = DoubleSellar()

        g1 = model.g1
        g1.nonlinear_solver = NewtonSolver()
        g1.nonlinear_solver.options['rtol'] = 1.0e-5
        g1.linear_solver = DirectSolver()

        g2 = model.g2
        g2.nonlinear_solver = NewtonSolver()
        g2.nonlinear_solver.options['rtol'] = 1.0e-5
        g2.linear_solver = DirectSolver()

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

        model.nonlinear_solver.options['solve_subsystems'] = True
        model.nonlinear_solver.options['max_sub_solves'] = 4
        ls = model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(
            bound_enforcement='vector')

        # This is pretty bogus, but it ensures that we get a few LS iterations.
        ls.options['c'] = 100.0

        prob.set_solver_print(level=0)

        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)
Ejemplo n.º 3
0
    def test_specify_precon(self):
        import numpy as np

        from openmdao.api import Problem, Group, IndepVarComp, ScipyKrylov, 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.nonlinear_solver = NewtonSolver()
        model.linear_solver = ScipyKrylov()

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

        prob.setup()
        prob.run_model()

        assert_rel_error(self, prob['y1'], 25.58830273, .00001)
        assert_rel_error(self, prob['y2'], 12.05848819, .00001)
Ejemplo n.º 4
0
    def test_feature_boundscheck_basic(self):
        import numpy as np

        from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyIterativeSolver, BoundsEnforceLS
        from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays

        top = Problem()
        top.model = Group()
        top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1))))
        top.model.add_subsystem('comp', ImplCompTwoStatesArrays())
        top.model.connect('px.x', 'comp.x')

        top.model.nonlinear_solver = NewtonSolver()
        top.model.nonlinear_solver.options['maxiter'] = 10
        top.model.linear_solver = ScipyIterativeSolver()

        top.model.nonlinear_solver.linesearch = BoundsEnforceLS()

        top.setup(check=False)

        # Test lower bounds: should go to the lower bound and stall
        top['px.x'] = 2.0
        top['comp.y'] = 0.
        top['comp.z'] = 1.6
        top.run_model()

        assert_rel_error(self, top['comp.z'][0], [1.5], 1e-8)
        assert_rel_error(self, top['comp.z'][1], [1.5], 1e-8)
        assert_rel_error(self, top['comp.z'][2], [1.5], 1e-8)
Ejemplo n.º 5
0
    def test_feature_boundscheck_scalar(self):
        top = Problem()
        top.model = Group()
        top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1))))
        top.model.add_subsystem('comp', ImplCompTwoStatesArrays())
        top.model.connect('px.x', 'comp.x')

        top.model.nonlinear_solver = NewtonSolver()
        top.model.nonlinear_solver.options['maxiter'] = 10
        top.model.linear_solver = ScipyIterativeSolver()

        ls = top.model.nonlinear_solver.linesearch = BoundsEnforceLS()
        ls.options['bound_enforcement'] = 'scalar'

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

        # Test lower bounds: should stop just short of the lower bound
        top['px.x'] = 2.0
        top['comp.y'] = 0.
        top['comp.z'] = 1.6
        top.run_model()

        print(top['comp.z'][0])
        print(top['comp.z'][1])
        print(top['comp.z'][2])
Ejemplo n.º 6
0
    def test_feature_boundscheck_wall(self):
        top = Problem()
        top.model = Group()
        top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1))))
        top.model.add_subsystem('comp', ImplCompTwoStatesArrays())
        top.model.connect('px.x', 'comp.x')

        top.model.nonlinear_solver = NewtonSolver()
        top.model.nonlinear_solver.options['maxiter'] = 10
        top.model.linear_solver = ScipyIterativeSolver()

        ls = top.model.nonlinear_solver.linesearch = BoundsEnforceLS()
        ls.options['bound_enforcement'] = 'wall'

        top.setup(check=False)

        # Test upper bounds: should go to the upper bound and stall
        top['px.x'] = 0.5
        top['comp.y'] = 0.
        top['comp.z'] = 2.4
        top.run_model()

        assert_rel_error(self, top['comp.z'][0], [2.6], 1e-8)
        assert_rel_error(self, top['comp.z'][1], [2.5], 1e-8)
        assert_rel_error(self, top['comp.z'][2], [2.65], 1e-8)
Ejemplo n.º 7
0
    def test_feature_specification(self):
        from openmdao.api import Problem, IndepVarComp, NewtonSolver, BoundsEnforceLS
        from openmdao.api import DirectSolver
        from openmdao.solvers.linesearch.tests.test_backtracking import CompAtan

        prob = Problem()
        model = prob.model

        model.add_subsystem('px', IndepVarComp('x', -100.0))
        model.add_subsystem('comp', CompAtan())

        model.connect('px.x', 'comp.x')

        prob.setup()

        # Initial value for the state:
        prob['comp.y'] = 12.0

        # You can change the NewtonSolver settings after setup is called
        newton = prob.model.nonlinear_solver = NewtonSolver()
        prob.model.linear_solver = DirectSolver()
        newton.options['iprint'] = 2
        newton.options['rtol'] = 1e-8
        newton.options['solve_subsystems'] = True

        newton.linesearch = BoundsEnforceLS()
        newton.linesearch.options['iprint'] = 2

        prob.run_model()

        assert_rel_error(self, prob['comp.y'], 19.68734033, 1e-6)
Ejemplo n.º 8
0
    def test_feature_armijo_boundscheck_scalar(self):
        import numpy as np

        from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, ArmijoGoldsteinLS
        from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays

        top = Problem()
        top.model = Group()
        top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1))))
        top.model.add_subsystem('comp', ImplCompTwoStatesArrays())
        top.model.connect('px.x', 'comp.x')

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

        ls = top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(
            bound_enforcement='scalar')
        ls.options['bound_enforcement'] = 'scalar'

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

        # Test lower bounds: should stop just short of the lower bound
        top['px.x'] = 2.0
        top['comp.y'] = 0.
        top['comp.z'] = 1.6
        top.run_model()

        print(top['comp.z'][0])
        print(top['comp.z'][1])
        print(top['comp.z'][2])
Ejemplo n.º 9
0
    def test_specify_precon(self):
        import numpy as np

        from openmdao.api import Problem, ScipyKrylov, NewtonSolver, LinearBlockGS, \
             DirectSolver

        from openmdao.test_suite.components.double_sellar import DoubleSellar

        prob = Problem(model=DoubleSellar())
        model = prob.model

        model.nonlinear_solver = NewtonSolver()
        model.nonlinear_solver.linesearch = BoundsEnforceLS()
        model.linear_solver = ScipyKrylov()
        model.g1.linear_solver = DirectSolver()
        model.g2.linear_solver = DirectSolver()

        model.linear_solver.precon = LinearBlockGS()
        # TODO: This should work with 1 iteration.
        #model.linear_solver.precon.options['maxiter'] = 1

        prob.setup()
        prob.set_solver_print(level=2)
        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)
Ejemplo n.º 10
0
    def test_promoted_connections_newton_solver(self):
        p = Problem()

        p.model = model = Group()
        model.linear_solver = DirectSolver()
        model.nonlinear_solver = NewtonSolver(solve_subsystems=False)
        model.add_subsystem('c1',
                            IndepVarComp('x', 1.0),
                            promotes_outputs=['x'])
        model.add_subsystem('c2',
                            ReconfComp1(),
                            promotes_inputs=['x'],
                            promotes_outputs=['y'])
        model.add_subsystem('c3',
                            ReconfComp2(),
                            promotes_inputs=['y'],
                            promotes_outputs=['f'])
        p.setup()
        p['x'] = 3.

        # First run the model once; counter = 1, size of y = 1
        p.run_model()
        self.assertEqual(len(p['y']), 1)

        # Run the model again, which will trigger reconfiguration; counter = 2, size of y = 2
        p.run_model()
        self.assertEqual(len(p['y']), 2)
        assert_rel_error(self, p['y'], [6., 6.])
Ejemplo n.º 11
0
    def test_feature_print_bound_enforce(self):
        import numpy as np

        from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, BoundsEnforceLS
        from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays

        top = Problem()
        top.model = Group()
        top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1))))
        top.model.add_subsystem('comp', ImplCompTwoStatesArrays())
        top.model.connect('px.x', 'comp.x')

        newt = top.model.nonlinear_solver = NewtonSolver()
        top.model.nonlinear_solver.options['maxiter'] = 2
        top.model.linear_solver = ScipyKrylov()

        ls = newt.linesearch = BoundsEnforceLS(bound_enforcement='vector')
        ls.options['print_bound_enforce'] = True

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

        # Test lower bounds: should go to the lower bound and stall
        top['px.x'] = 2.0
        top['comp.y'] = 0.
        top['comp.z'] = 1.6
        top.run_model()

        assert_rel_error(self, top['comp.z'][0], [1.5], 1e-8)
        assert_rel_error(self, top['comp.z'][1], [1.5], 1e-8)
        assert_rel_error(self, top['comp.z'][2], [1.5], 1e-8)
Ejemplo n.º 12
0
    def test_feature_armijo_boundscheck_wall(self):
        import numpy as np

        from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, ArmijoGoldsteinLS
        from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays

        top = Problem()
        top.model = Group()
        top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1))))
        top.model.add_subsystem('comp', ImplCompTwoStatesArrays())
        top.model.connect('px.x', 'comp.x')

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

        ls = top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(
            bound_enforcement='wall')
        ls.options['bound_enforcement'] = 'wall'

        top.setup(check=False)

        # Test upper bounds: should go to the upper bound and stall
        top['px.x'] = 0.5
        top['comp.y'] = 0.
        top['comp.z'] = 2.4
        top.run_model()

        assert_rel_error(self, top['comp.z'][0], [2.6], 1e-8)
        assert_rel_error(self, top['comp.z'][1], [2.5], 1e-8)
        assert_rel_error(self, top['comp.z'][2], [2.65], 1e-8)
Ejemplo n.º 13
0
    def test_direct_solver_comp(self):
        """
        Test the direct solver on a component.
        """
        for jac in [None, 'csc', 'dense']:
            prob = Problem(model=ImplComp4Test())
            prob.model.nonlinear_solver = NewtonSolver()
            if jac in ('csc', 'dense'):
                prob.model.options['assembled_jac_type'] = jac
            prob.model.linear_solver = DirectSolver(assemble_jac=jac in ('csc','dense'))
            prob.set_solver_print(level=0)

            prob.setup(check=False)

            prob.run_model()
            assert_rel_error(self, prob['y'], [-1., 1.])

            d_inputs, d_outputs, d_residuals = prob.model.get_linear_vectors()

            d_residuals.set_const(2.0)
            d_outputs.set_const(0.0)
            prob.model.run_solve_linear(['linear'], 'fwd')
            result = d_outputs.get_data()
            assert_rel_error(self, result, [-2., 2.])

            d_outputs.set_const(2.0)
            d_residuals.set_const(0.0)
            prob.model.run_solve_linear(['linear'], 'rev')
            result = d_residuals.get_data()
            assert_rel_error(self, result, [2., -2.])
    def test_direct_solver_comp(self):
        """
        Test the direct solver on a component.
        """
        for jac in [None, 'csc', 'dense']:
            prob = Problem(model=ImplComp4Test())
            prob.model.nonlinear_solver = NewtonSolver(solve_subsystems=False)
            if jac in ('csc', 'dense'):
                prob.model.options['assembled_jac_type'] = jac
            prob.model.linear_solver = DirectSolver(assemble_jac=jac in ('csc','dense'))
            prob.set_solver_print(level=0)

            prob.setup()

            prob.run_model()
            assert_near_equal(prob['y'], [-1., 1.])

            d_inputs, d_outputs, d_residuals = prob.model.get_linear_vectors()

            d_residuals.set_val(2.0)
            d_outputs.set_val(0.0)
            prob.model.run_solve_linear('fwd')
            result = d_outputs.asarray()
            assert_near_equal(result, [-2., 2.])

            d_outputs.set_val(2.0)
            d_residuals.set_val(0.0)
            prob.model.run_solve_linear('rev')
            result = d_residuals.asarray()
            assert_near_equal(result, [2., -2.])
Ejemplo n.º 15
0
    def test_read_only_bug(self):
        # this tests for a bug in which guess_nonlinear failed due to the output
        # vector being left in a read only state after the AnalysisError

        top = Problem()
        top.model = Group()
        top.model.add_subsystem('px', IndepVarComp('x', 7.0))

        sub = top.model.add_subsystem('sub', Group())
        sub.add_subsystem('comp', ImplCompTwoStatesGuess())

        top.model.connect('px.x', 'sub.comp.x')

        top.model.nonlinear_solver = NewtonSolver()
        top.model.nonlinear_solver.options['maxiter'] = 2
        top.model.nonlinear_solver.options['solve_subsystems'] = True
        top.model.linear_solver = ScipyKrylov()

        sub.nonlinear_solver = NewtonSolver()
        sub.nonlinear_solver.options['maxiter'] = 2
        sub.linear_solver = ScipyKrylov()

        ls = top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(
            bound_enforcement='wall')
        ls.options['maxiter'] = 5
        ls.options['alpha'] = 10.0
        ls.options['retry_on_analysis_error'] = True
        ls.options['c'] = 10000.0

        top.setup(check=False)
        top.set_solver_print(level=2)

        stdout = sys.stdout
        strout = StringIO()

        sys.stdout = strout
        try:
            top.run_model()
        finally:
            sys.stdout = stdout

        output = strout.getvalue().split('\n')
        self.assertTrue(output[26].startswith('|  LS: AG 3'))
Ejemplo n.º 16
0
    def test_debug_after_raised_error(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()

        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
        teg.nonlinear_solver.options['debug_print'] = True

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

        stdout = sys.stdout
        strout = StringIO()
        sys.stdout = strout

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

        sys.stdout = stdout

        output = strout.getvalue()
        target = "'thrust_equilibrium_group.thrust_bal.thrust'"
        self.assertTrue(target in output, msg=target + "NOT FOUND IN" + output)

        # Make sure exception is unchanged.
        expected_msg = "Singular entry found in 'thrust_equilibrium_group' for row associated with state/residual 'thrust'."
        self.assertEqual(expected_msg, str(cm.exception))
Ejemplo n.º 17
0
    def __init__(self, units=None, scaling=None, **kwargs):
        super(DoubleSellarImplicit, self).__init__(**kwargs)

        self.add_subsystem('g1', SubSellar(units=units, scaling=scaling))
        self.add_subsystem('g2', SubSellar(units=units, scaling=scaling))

        self.connect('g1.y2', 'g2.x')
        self.connect('g2.y2', 'g1.x')

        # Converge the outer loop with Gauss Seidel, with a looser tolerance.
        self.nonlinear_solver = NewtonSolver()
        self.linear_solver = DirectSolver()
Ejemplo n.º 18
0
 def initialize(self):
     self.metadata.declare('nonlinear_solver', default=NewtonSolver(),
                           desc='Nonlinear solver for Sellar MDA')
     self.metadata.declare('nl_atol', default=None,
                           desc='User-specified atol for nonlinear solver.')
     self.metadata.declare('nl_maxiter', default=None,
                           desc='Iteration limit for nonlinear solver.')
     self.metadata.declare('linear_solver', default=ScipyKrylov(),
                           desc='Linear solver')
     self.metadata.declare('ln_atol', default=None,
                           desc='User-specified atol for linear solver.')
     self.metadata.declare('ln_maxiter', default=None,
                           desc='Iteration limit for linear solver.')
Ejemplo n.º 19
0
    def test_error_handling(self):
        # Make sure the debug_print doen't bomb out.

        class Bad(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 = Problem()
        top.model = Group()
        top.model.add_subsystem('px', 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 = NewtonSolver()
        top.model.nonlinear_solver.options['maxiter'] = 3

        ls = top.model.nonlinear_solver.linesearch = BoundsEnforceLS(
            bound_enforcement='vector')
        ls.options['maxiter'] = 10
        top.set_solver_print(level=0)

        top.setup(check=False)

        # Make sure we don't raise an error when we reach the final debug print.
        top.run_model()
Ejemplo n.º 20
0
    def setUp(self):
        top = Problem()
        top.model = Group()
        top.model.add_subsystem('px', IndepVarComp('x', 1.0))
        top.model.add_subsystem('comp', ImplCompTwoStates())
        top.model.connect('px.x', 'comp.x')

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

        top.setup(check=False)

        self.top = top
    def test_direct_solver_comp(self):
        """
        Test the direct solver on a component.
        """
        for jac in ['dict', 'coo', 'csr', 'csc', 'dense']:
            prob = Problem(model=ImplComp4Test())
            prob.model.nonlinear_solver = NewtonSolver()
            prob.model.linear_solver = DirectSolver()
            prob.set_solver_print(level=0)

            if jac == 'dict':
                pass
            elif jac == 'csr':
                prob.model.jacobian = CSRJacobian()
            elif jac == 'csc':
                prob.model.jacobian = CSCJacobian()
            elif jac == 'coo':
                prob.model.jacobian = COOJacobian()
            elif jac == 'dense':
                prob.model.jacobian = DenseJacobian()

            prob.setup(check=False)

            if jac == 'coo':
                with self.assertRaises(Exception) as context:
                    prob.run_model()
                self.assertEqual(
                    str(context.exception),
                    "Direct solver is not compatible with matrix type COOMatrix in system ''."
                )
                continue

            prob.run_model()
            assert_rel_error(self, prob['y'], [-1., 1.])

            d_inputs, d_outputs, d_residuals = prob.model.get_linear_vectors()

            d_residuals.set_const(2.0)
            d_outputs.set_const(0.0)
            prob.model.run_solve_linear(['linear'], 'fwd')
            result = d_outputs.get_data()
            assert_rel_error(self, result, [-2., 2.])

            d_outputs.set_const(2.0)
            d_residuals.set_const(0.0)
            prob.model.run_solve_linear(['linear'], 'rev')
            result = d_residuals.get_data()
            assert_rel_error(self, result, [2., -2.])
Ejemplo n.º 22
0
    def setUp(self):
        top = Problem()
        top.model = Group()
        top.model.add_subsystem('px', IndepVarComp('x', np.ones((3, 1))))
        top.model.add_subsystem('comp', ImplCompTwoStatesArrays())
        top.model.connect('px.x', 'comp.x')

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

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

        self.top = top
        self.ub = np.array([2.6, 2.5, 2.65])
Ejemplo n.º 23
0
    def test_specify_solver(self):
        prob = Problem()
        model = prob.model = SellarDerivatives()

        model.nonlinear_solver = newton = NewtonSolver()

        # using a different linear solver for Newton with a looser tolerance
        newton.linear_solver = ScipyIterativeSolver()
        newton.linear_solver.options['atol'] = 1e-4

        # used for analytic derivatives
        model.linear_solver = DirectSolver()

        prob.setup()
        prob.run_model()

        assert_rel_error(self, prob['y1'], 25.58830273, .00001)
        assert_rel_error(self, prob['y2'], 12.05848819, .00001)
Ejemplo n.º 24
0
    def test_solver_debug_print_feature(self):
        from distutils.version import LooseVersion
        import numpy as np
        from openmdao.api import Problem, IndepVarComp, NewtonSolver, AnalysisError
        from openmdao.test_suite.scripts.circuit_analysis import Circuit
        from openmdao.utils.general_utils import printoptions

        p = Problem()
        model = p.model

        model.add_subsystem('ground', IndepVarComp('V', 0., units='V'))
        model.add_subsystem('source', IndepVarComp('I', 0.1, units='A'))
        model.add_subsystem('circuit', Circuit())

        model.connect('source.I', 'circuit.I_in')
        model.connect('ground.V', 'circuit.Vg')

        p.setup()

        nl = model.circuit.nonlinear_solver = NewtonSolver()

        nl.options['iprint'] = 2
        nl.options['debug_print'] = True
        nl.options['err_on_maxiter'] = 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 AnalysisError:
                pass

        with open('rank0_root_0_NLRunOnce_0_circuit_0.dat', 'r') as f:
            self.assertEqual(f.read(), self.expected_data)
Ejemplo n.º 25
0
    def test_specify_solver(self):
        from openmdao.api import Problem, NewtonSolver, ScipyKrylov, DirectSolver
        from openmdao.test_suite.components.sellar import SellarDerivatives

        prob = Problem()
        model = prob.model = SellarDerivatives()

        model.nonlinear_solver = newton = NewtonSolver()

        # using a different linear solver for Newton with a looser tolerance
        newton.linear_solver = ScipyKrylov(atol=1e-4)

        # used for analytic derivatives
        model.linear_solver = DirectSolver()

        prob.setup()
        prob.run_model()

        assert_rel_error(self, prob['y1'], 25.58830273, .00001)
        assert_rel_error(self, prob['y2'], 12.05848819, .00001)
Ejemplo n.º 26
0
    def test_feature_specification(self):
        top = Problem()
        top.model = Group()
        top.model.add_subsystem('px', IndepVarComp('x', 1.0))
        top.model.add_subsystem('comp', ImplCompTwoStates())
        top.model.connect('px.x', 'comp.x')

        top.model.nonlinear_solver = NewtonSolver()
        top.model.nonlinear_solver.options['maxiter'] = 10
        top.model.linear_solver = ScipyIterativeSolver()

        ls = top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS()
        ls.options['maxiter'] = 10

        top.setup(check=False)

        top['px.x'] = 2.0
        top['comp.y'] = 0.0
        top['comp.z'] = 1.6
        top.run_model()
        assert_rel_error(self, top['comp.z'], 1.5, 1e-8)
Ejemplo n.º 27
0
    def setUp(self):
        top = Problem()
        top.model = Group()
        top.model.add_subsystem('px', IndepVarComp('x', 1.0))
        top.model.add_subsystem('comp', ImplCompTwoStates())
        top.model.add_subsystem('par', ParaboloidAE())
        top.model.connect('px.x', 'comp.x')
        top.model.connect('comp.z', 'par.x')

        top.model.nonlinear_solver = NewtonSolver()
        top.model.nonlinear_solver.options['maxiter'] = 1
        top.model.linear_solver = ScipyKrylov()

        ls = top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(
            bound_enforcement='vector')
        ls.options['maxiter'] = 10
        ls.options['alpha'] = 1.0
        top.set_solver_print(level=0)

        self.top = top
        self.ls = ls
Ejemplo n.º 28
0
    def test_specify_precon(self):
        import numpy as np

        from openmdao.api import Problem, Group, ScipyKrylov, NewtonSolver, LinearBlockGS, \
             DirectSolver, ExecComp, PETScKrylov

        from openmdao.test_suite.components.quad_implicit import QuadraticComp

        prob = Problem()
        model = prob.model

        sub1 = model.add_subsystem('sub1', Group())
        sub1.add_subsystem('q1', QuadraticComp())
        sub1.add_subsystem('z1', ExecComp('y = -6.0 + .01 * x'))
        sub2 = model.add_subsystem('sub2', Group())
        sub2.add_subsystem('q2', QuadraticComp())
        sub2.add_subsystem('z2', ExecComp('y = -6.0 + .01 * x'))

        model.connect('sub1.q1.x', 'sub1.z1.x')
        model.connect('sub1.z1.y', 'sub2.q2.c')
        model.connect('sub2.q2.x', 'sub2.z2.x')
        model.connect('sub2.z2.y', 'sub1.q1.c')

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

        prob.setup()

        model.sub1.linear_solver = DirectSolver()
        model.sub2.linear_solver = DirectSolver()

        model.linear_solver.precon = LinearBlockGS()

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

        assert_rel_error(self, prob['sub1.q1.x'], 1.996, .0001)
        assert_rel_error(self, prob['sub2.q2.x'], 1.996, .0001)
Ejemplo n.º 29
0
    def test_feature_specification(self):
        from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, ScipyKrylov, ArmijoGoldsteinLS
        from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStates

        top = Problem()
        top.model = Group()
        top.model.add_subsystem('px', IndepVarComp('x', 1.0))
        top.model.add_subsystem('comp', ImplCompTwoStates())
        top.model.connect('px.x', 'comp.x')

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

        ls = top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS()
        ls.options['maxiter'] = 10

        top.setup(check=False)

        top['px.x'] = 2.0
        top['comp.y'] = 0.0
        top['comp.z'] = 1.6
        top.run_model()
        assert_rel_error(self, top['comp.z'], 1.5, 1e-8)
Ejemplo n.º 30
0
    def test_deep_analysis_error_iprint(self):
        class ImplCompTwoStatesAE(ImplicitComponent):
            def setup(self):
                self.add_input('x', 0.5)
                self.add_output('y', 0.0)
                self.add_output('z', 2.0, lower=1.5, upper=2.5)

                self.maxiter = 10
                self.atol = 1.0e-12

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

                self.counter = 0

            def apply_nonlinear(self, inputs, outputs, residuals):
                """
                Don't solve; just calculate the residual.
                """

                x = inputs['x']
                y = outputs['y']
                z = outputs['z']

                residuals['y'] = y - x - 2.0 * z
                residuals['z'] = x * z + z - 4.0

                self.counter += 1
                if self.counter > 5 and self.counter < 11:
                    raise AnalysisError('catch me')

            def linearize(self, inputs, outputs, jac):
                """
                Analytical derivatives.
                """

                # Output equation
                jac[('y', 'x')] = -1.0
                jac[('y', 'y')] = 1.0
                jac[('y', 'z')] = -2.0

                # State equation
                jac[('z', 'z')] = -inputs['x'] + 1.0
                jac[('z', 'x')] = -outputs['z']

        top = Problem()
        top.model = Group()
        top.model.add_subsystem('px', IndepVarComp('x', 7.0))

        sub = top.model.add_subsystem('sub', Group())
        sub.add_subsystem('comp', ImplCompTwoStatesAE())

        top.model.connect('px.x', 'sub.comp.x')

        top.model.nonlinear_solver = NewtonSolver()
        top.model.nonlinear_solver.options['maxiter'] = 2
        top.model.nonlinear_solver.options['solve_subsystems'] = True
        top.model.linear_solver = ScipyKrylov()

        sub.nonlinear_solver = NewtonSolver()
        sub.nonlinear_solver.options['maxiter'] = 2
        sub.linear_solver = ScipyKrylov()

        ls = top.model.nonlinear_solver.linesearch = ArmijoGoldsteinLS(
            bound_enforcement='wall')
        ls.options['maxiter'] = 5
        ls.options['alpha'] = 10.0
        ls.options['retry_on_analysis_error'] = True
        ls.options['c'] = 10000.0

        top.setup(check=False)
        top.set_solver_print(level=2)

        stdout = sys.stdout
        strout = StringIO()

        sys.stdout = strout
        try:
            top.run_model()
        finally:
            sys.stdout = stdout

        output = strout.getvalue().split('\n')
        self.assertTrue(output[26].startswith('|  LS: AG 5'))