def __init__(self, resid_scaler=1.0):
        super(SellarStateConnection, self).__init__()

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

        sub = self.add('sub', Group(), promotes=['x', 'z', 'y1', 'state_eq.y2_actual',
                                                 'state_eq.y2_command', 'd1.y2', 'd2.y2'])
        sub.ln_solver = ScipyGMRES()

        subgrp = sub.add('state_eq_group', Group(), promotes=['state_eq.y2_actual',
                                                              'state_eq.y2_command'])
        subgrp.ln_solver = ScipyGMRES()
        subgrp.add('state_eq', StateConnection(resid_scaler=resid_scaler))

        sub.add('d1', SellarDis1withDerivatives(), promotes=['x', 'z', 'y1'])
        sub.add('d2', SellarDis2withDerivatives(), promotes=['z', 'y1'])

        self.connect('state_eq.y2_command', 'd1.y2')
        self.connect('d2.y2', 'state_eq.y2_actual')

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

        self.add('con_cmp1', ExecComp('con1 = 3.16 - y1'), promotes=['con1', 'y1'])
        self.add('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2'])
        self.connect('d2.y2', 'con_cmp2.y2')

        self.nl_solver = Newton()
Esempio n. 2
0
    def test_sellar_specify_linear_solver(self):

        prob = Problem()
        prob.root = SellarStateConnection()
        prob.root.nl_solver = Newton()

        # Use bad settings for this one so that problem doesn't converge.
        # That way, we test that we are really using Newton's Lin Solver
        # instead.
        prob.root.ln_solver = ScipyGMRES()
        prob.root.ln_solver.options['maxiter'] = 1

        # The good solver
        prob.root.nl_solver.ln_solver = ScipyGMRES()

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

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

        # Make sure we aren't iterating like crazy
        self.assertLess(prob.root.nl_solver.iter_count, 8)
        self.assertEqual(prob.root.ln_solver.iter_count, 0)
        self.assertGreater(prob.root.nl_solver.ln_solver.iter_count, 0)
    def test_overrides(self):

        prob = Problem()
        prob.root = Group()
        prob.root.ln_solver = ScipyGMRES()
        prob.root.add('comp', SimpleImplicitComp())
        prob.root.add('p1', IndepVarComp('x', 0.5))

        prob.root.connect('p1.x', 'comp.x')
        prob.root.comp.deriv_options['check_type'] = 'fd'
        prob.root.comp.deriv_options['check_step_size'] = 1e25

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

        # This should override the bad stepsize.
        opts = {'check_step_size' : 1e-6}
        mystream = StringIO()
        data = prob.check_partial_derivatives(out_stream=mystream, global_options=opts)

        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)

        prob = Problem()
        prob.root = Group()
        prob.root.ln_solver = ScipyGMRES()
        prob.root.add('comp', SimpleImplicitComp())
        prob.root.add('p1', IndepVarComp('x', 0.5))

        prob.root.connect('p1.x', 'comp.x')
        prob.root.comp.deriv_options['check_type'] = 'fd'
        prob.root.comp.deriv_options['check_step_size'] = 1e25

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

        mystream = StringIO()
        opts = {'check_form' : 'central'}
        data = prob.check_partial_derivatives(out_stream=mystream, global_options=opts,
                                              compact_print=True)
        text = mystream.getvalue()
        self.assertTrue('fd:central' in text)
        self.assertTrue('complex_step' not in text)

        mystream = StringIO()
        opts = {'check_type' : 'cs'}
        data = prob.check_partial_derivatives(out_stream=mystream, global_options=opts,
                                              compact_print=True)
        text = mystream.getvalue()
        self.assertTrue('fd:central' not in text)
        self.assertTrue('complex step' in text)
Esempio n. 4
0
    def test_run_apply(self):
        # This test makes sure that we correctly apply the "run_apply" flag
        # to all targets in the "broken" connection, even when they are
        # nested in Groups.

        prob = Problem()
        root = prob.root = Group()

        sub1 = root.add('sub1', Group())
        sub2 = root.add('sub2', Group())

        sub1.add('p1', Paraboloid())
        sub1.add('p2', Paraboloid())
        sub2.add('p1', Paraboloid())
        sub2.add('p2', Paraboloid())

        root.connect('sub1.p1.f_xy', 'sub2.p1.x')
        root.connect('sub1.p2.f_xy', 'sub2.p1.y')
        root.connect('sub1.p1.f_xy', 'sub2.p2.x')
        root.connect('sub1.p2.f_xy', 'sub2.p2.y')
        root.connect('sub2.p1.f_xy', 'sub1.p1.x')
        root.connect('sub2.p2.f_xy', 'sub1.p1.y')
        root.connect('sub2.p1.f_xy', 'sub1.p2.x')
        root.connect('sub2.p2.f_xy', 'sub1.p2.y')

        root.nl_solver = NLGaussSeidel()
        root.ln_solver = ScipyGMRES()

        prob.setup(check=False)

        # Will be True in one group and False in the other, depending on
        # where it cuts.
        self.assertTrue(root.sub1.p1._run_apply != root.sub2.p1._run_apply)
        self.assertTrue(root.sub1.p2._run_apply != root.sub2.p2._run_apply)
Esempio n. 5
0
    def __init__(self):
        super(SellarDerivatives, self).__init__()

        # params will be provided by parent group
        self.add('px', IndepVarComp('x', 1.0), promotes=['x'])
        self.add('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])

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

        self.add('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'])

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

        self.nl_solver = NLGaussSeidel()
        self.ln_solver = ScipyGMRES()
Esempio n. 6
0
    def __init__(self):
        super(SellarStateConnection, self).__init__()

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

        self.add('state_eq', StateConnection())
        self.add('d1', SellarDis1(), promotes=['x', 'z', 'y1'])
        self.add('d2', SellarDis2(), promotes=['z', 'y1'])
        self.connect('state_eq.y2_command', 'd1.y2')
        self.connect('d2.y2', 'state_eq.y2_actual')

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

        self.add('con_cmp1',
                 ExecComp('con1 = 3.16 - y1'),
                 promotes=['con1', 'y1'])
        self.add('con_cmp2', ExecComp('con2 = y2 - 24.0'), promotes=['con2'])
        self.connect('d2.y2', 'con_cmp2.y2')

        self.nl_solver = Newton()
        self.ln_solver = ScipyGMRES()
Esempio n. 7
0
    def test_fan_in_grouped(self):

        prob = Problem()
        prob.root = FanInGrouped()
        prob.root.ln_solver = ScipyGMRES()

        indep_list = ['p1.x1', 'p2.x2']
        unknown_list = ['comp3.y']

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

        J = prob.calc_gradient(indep_list,
                               unknown_list,
                               mode='fwd',
                               return_format='dict')
        assert_rel_error(self, J['comp3.y']['p1.x1'][0][0], -6.0, 1e-6)
        assert_rel_error(self, J['comp3.y']['p2.x2'][0][0], 35.0, 1e-6)

        J = prob.calc_gradient(indep_list,
                               unknown_list,
                               mode='rev',
                               return_format='dict')
        assert_rel_error(self, J['comp3.y']['p1.x1'][0][0], -6.0, 1e-6)
        assert_rel_error(self, J['comp3.y']['p2.x2'][0][0], 35.0, 1e-6)
Esempio n. 8
0
    def test_relevance_issue(self):

        p = Problem()
        p.root = Group()

        dvars = (('a', 3.), ('b', 10.))
        p.root.add('desvars', IndepVarComp(dvars), promotes=['a', 'b'])

        sg = p.root.add('sg', Group(), promotes=["*"])
        sg.add('si', SimpleImplicit(), promotes=['a', 'b', 'x'])

        p.root.add('func', ExecComp('f = 2*x0+a'), promotes=['f', 'x0', 'a'])
        p.root.connect('x', 'x0', src_indices=[1])

        p.root.ln_solver = ScipyGMRES()
        p.root.ln_solver.preconditioner = LinearGaussSeidel()

        p.driver.add_objective('f')
        p.driver.add_desvar('a')

        p.setup(check=False)
        p.run_once()

        # Make sure we don't get a KeyError
        p.check_total_derivatives(out_stream=None)
Esempio n. 9
0
    def test_double_arraycomp(self):
        # Mainly testing a bug in the array return for multiple arrays

        group = Group()
        group.add('x_param1', IndepVarComp('x1', np.ones((2))), promotes=['*'])
        group.add('x_param2', IndepVarComp('x2', np.ones((2))), promotes=['*'])
        group.add('mycomp', DoubleArrayComp(), promotes=['*'])

        prob = Problem()
        prob.root = group
        prob.root.ln_solver = ScipyGMRES()
        prob.setup(check=False)
        prob.run()

        Jbase = group.mycomp.JJ

        J = prob.calc_gradient(['x1', 'x2'], ['y1', 'y2'], mode='fwd',
                               return_format='array')
        diff = np.linalg.norm(J - Jbase)
        assert_rel_error(self, diff, 0.0, 1e-8)

        J = prob.calc_gradient(['x1', 'x2'], ['y1', 'y2'], mode='fd',
                               return_format='array')
        diff = np.linalg.norm(J - Jbase)
        assert_rel_error(self, diff, 0.0, 1e-8)

        J = prob.calc_gradient(['x1', 'x2'], ['y1', 'y2'], mode='rev',
                               return_format='array')
        diff = np.linalg.norm(J - Jbase)
        assert_rel_error(self, diff, 0.0, 1e-8)
Esempio n. 10
0
    def __init__(self):
        super(SellarDerivatives, self).__init__()

        self.add('px', IndepVarComp('x1', 1.0), promotes=['x1'])
        self.add('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])

        self.add('d1', SellarDisc1(), promotes=['z', 'x1', 'y1', 'y2'])
        self.add('d2', SellarDisc2(), promotes=['z', 'y1', 'y2'])

        self.add('obj_cmp',
                 ExecComp('obj = x1**2 + z[1] + y1 + exp(-y2)',
                          z=np.array([5.0, 2.0]),
                          x1=1.0,
                          y1=0.0,
                          y2=0.0),
                 promotes=['obj', 'x1', 'z', 'y1', 'y2'])
        self.add('con_cmp1',
                 ExecComp('con1 = -y1 + 3.16', y1=0.0),
                 promotes=['y1', 'con1'])
        self.add('con_cmp2',
                 ExecComp('con2 = y2 - 24.0', y2=0.0),
                 promotes=['y2', 'con2'])

        self.n1_solver = NLGaussSeidel()
        self.n1_solver.options['atol'] = 1.0e-12

        self.ln_solver = ScipyGMRES()
    def test_simple_implicit_check_options(self):

        prob = Problem()
        prob.root = Group()
        prob.root.ln_solver = ScipyGMRES()
        prob.root.add('comp', SimpleImplicitComp())
        prob.root.add('p1', IndepVarComp('x', 0.5))

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

        # Not using this
        prob.root.deriv_options['step_size'] = 1e4

        # Using these
        prob.root.deriv_options['check_form'] = 'central'
        prob.root.deriv_options['check_step_size'] = 1e-3

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

        data = prob.check_total_derivatives(out_stream=None)

        for key, val in iteritems(data):
            assert_rel_error(self, val['abs error'][0], 0.0, 1e-5)
            assert_rel_error(self, val['abs error'][1], 0.0, 1e-5)
            assert_rel_error(self, val['abs error'][2], 0.0, 1e-5)
            assert_rel_error(self, val['rel error'][0], 0.0, 1e-5)
            assert_rel_error(self, val['rel error'][1], 0.0, 1e-5)
            assert_rel_error(self, val['rel error'][2], 0.0, 1e-5)
Esempio n. 12
0
    def test_single_diamond_grouped(self):

        prob = Problem()
        prob.root = SingleDiamondGrouped()
        prob.root.ln_solver = ScipyGMRES()
        prob.setup(check=False)
        prob.run()

        indep_list = ['p.x']
        unknown_list = ['comp4.y1', 'comp4.y2']

        J = prob.calc_gradient(indep_list,
                               unknown_list,
                               mode='fwd',
                               return_format='dict')
        assert_rel_error(self, J['comp4.y1']['p.x'][0][0], 25, 1e-6)
        assert_rel_error(self, J['comp4.y2']['p.x'][0][0], -40.5, 1e-6)

        J = prob.calc_gradient(indep_list,
                               unknown_list,
                               mode='rev',
                               return_format='dict')
        assert_rel_error(self, J['comp4.y1']['p.x'][0][0], 25, 1e-6)
        assert_rel_error(self, J['comp4.y2']['p.x'][0][0], -40.5, 1e-6)

        J = prob.calc_gradient(indep_list,
                               unknown_list,
                               mode='fd',
                               return_format='dict')
        assert_rel_error(self, J['comp4.y1']['p.x'][0][0], 25, 1e-6)
        assert_rel_error(self, J['comp4.y2']['p.x'][0][0], -40.5, 1e-6)
    def test_simple_implicit_run_once(self):
        class SIC2(SimpleImplicitComp):
            def solve_nonlinear(self, params, unknowns, resids):
                """ Simple iterative solve. (Babylonian method)."""

                super(SIC2, self).solve_nonlinear(params, unknowns, resids)

                # This mimics a problem with residuals that aren't up-to-date
                # with the solve
                resids['z'] = 999.999

        prob = Problem()
        prob.root = Group()
        prob.root.ln_solver = ScipyGMRES()
        prob.root.add('comp', SIC2())
        prob.root.add('p1', IndepVarComp('x', 0.5))

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

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

        data = prob.check_partial_derivatives(out_stream=None)

        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)
Esempio n. 14
0
    def test_fan_out_all_grouped(self):

        prob = Problem()
        prob.root = FanOutAllGrouped()
        prob.root.ln_solver = ScipyGMRES()

        prob.root.ln_solver.preconditioner = LinearGaussSeidel()
        prob.root.sub1.ln_solver = DirectSolver()
        prob.root.sub2.ln_solver = DirectSolver()
        prob.root.sub3.ln_solver = DirectSolver()

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

        indep_list = ['p.x']
        unknown_list = ['sub2.comp2.y', "sub3.comp3.y"]

        J = prob.calc_gradient(indep_list,
                               unknown_list,
                               mode='fwd',
                               return_format='dict')
        assert_rel_error(self, J['sub2.comp2.y']['p.x'][0][0], -6.0, 1e-6)
        assert_rel_error(self, J['sub3.comp3.y']['p.x'][0][0], 15.0, 1e-6)

        J = prob.calc_gradient(indep_list,
                               unknown_list,
                               mode='rev',
                               return_format='dict')
        assert_rel_error(self, J['sub2.comp2.y']['p.x'][0][0], -6.0, 1e-6)
        assert_rel_error(self, J['sub3.comp3.y']['p.x'][0][0], 15.0, 1e-6)
Esempio n. 15
0
    def test_generate_numpydocstring(self):
        group = Group()
        group.add('x_param', IndepVarComp('x', 1.0), promotes=['*'])
        group.add('mycomp', SimpleCompDerivMatVec(), promotes=['x', 'y'])

        prob = Problem()
        prob.root = group
        prob.root.ln_solver = ScipyGMRES()

        test_string = prob.root.ln_solver.generate_docstring()

        original_string = \
"""    \"\"\"

    Options
    -------
    options['atol'] : float(1e-12)
        Absolute convergence tolerance.
    options['err_on_maxiter'] : bool(False)
        If True, raise an AnalysisError if not converged at maxiter.
    options['iprint'] : int(0)
        Set to 0 to disable printing, set to 1 to print the residual to stdout each iteration, set to 2 to print subiteration residuals as well.
    options['maxiter'] : int(1000)
        Maximum number of iterations.
    options['mode'] : str('auto')
        Derivative calculation mode, set to 'fwd' for forward mode, 'rev' for reverse mode, or 'auto' to let OpenMDAO determine the best mode.
    options['restart'] : int(20)
        Number of iterations between restarts. Larger values increase iteration cost, but may be necessary for convergence

    \"\"\"
"""
        for sorig, stest in zip(original_string.split('\n'),
                                test_string.split('\n')):
            self.assertEqual(sorig, stest)
Esempio n. 16
0
    def test_analysis_error(self):

        prob = Problem()
        prob.root = ConvergeDiverge()
        prob.root.ln_solver = ScipyGMRES()
        prob.root.ln_solver.options['maxiter'] = 2
        prob.root.ln_solver.options['err_on_maxiter'] = True

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

        indep_list = ['p.x']
        unknown_list = ['comp7.y1']

        prob.run()

        # Make sure value is fine.
        assert_rel_error(self, prob['comp7.y1'], -102.7, 1e-6)

        try:
            J = prob.calc_gradient(indep_list,
                                   unknown_list,
                                   mode='fwd',
                                   return_format='dict')
        except AnalysisError as err:
            self.assertEqual(
                str(err),
                "Solve in '': ScipyGMRES failed to converge after 2 iterations"
            )
        else:
            self.fail("expected AnalysisError")
    def test_simple_implicit_complex_step(self):

        prob = Problem()
        prob.root = Group()
        prob.root.ln_solver = ScipyGMRES()
        prob.root.add('comp', SimpleImplicitComp())
        prob.root.add('p1', IndepVarComp('x', 0.5))

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

        prob.root.comp.fd_options['step_size'] = 1.0e4
        prob.root.comp.fd_options['form'] = 'complex_step'

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

        data = prob.check_partial_derivatives(out_stream=None)

        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)
Esempio n. 18
0
    def test_auto_order(self):
        # this tests the auto ordering when we have a cycle that is smaller
        # than the full graph.
        p = Problem(root=Group())
        root = p.root
        root.ln_solver = ScipyGMRES()

        C5 = root.add("C5", ExecComp('y=x*2.0'))
        C6 = root.add("C6", ExecComp('y=x*2.0'))
        C1 = root.add("C1", ExecComp('y=x*2.0'))
        C2 = root.add("C2", ExecComp('y=x*2.0'))
        C3 = root.add("C3", ExecComp(['y=x*2.0', 'y2=x2+1.0']))
        C4 = root.add("C4", ExecComp(['y=x*2.0', 'y2=x2+1.0']))
        P1 = root.add("P1", IndepVarComp('x', 1.0))

        root.connect('P1.x', 'C1.x')
        root.connect('C1.y', 'C2.x')
        root.connect('C2.y', 'C4.x')
        root.connect('C4.y', 'C5.x')
        root.connect('C5.y', 'C6.x')
        root.connect('C5.y', 'C3.x2')
        root.connect('C6.y', 'C3.x')
        root.connect('C3.y', 'C4.x2')

        p.setup(check=False)

        self.assertEqual(p.root.list_auto_order()[0],
                         ['P1', 'C1', 'C2', 'C4', 'C5', 'C6', 'C3'])
Esempio n. 19
0
    def test_intersect_parabola_line(self):

        top = Problem()
        root = top.root = Group()
        root.add('line', Line())
        root.add('parabola', Parabola())
        root.add('bal', Balance())

        root.connect('line.y', 'bal.y1')
        root.connect('parabola.y', 'bal.y2')
        root.connect('bal.x', 'line.x')
        root.connect('bal.x', 'parabola.x')

        root.nl_solver = Newton()
        root.ln_solver = ScipyGMRES()

        top.setup(check=False)

        # Positive solution
        top['bal.x'] = 7.0
        top.run()
        assert_rel_error(self, top['bal.x'], 1.430501, 1e-5)
        assert_rel_error(self, top['line.y'], 1.1389998, 1e-5)

        # Negative solution
        top['bal.x'] = -7.0
        top.run()
        assert_rel_error(self, top['bal.x'], -2.097168, 1e-5)
        assert_rel_error(self, top['line.y'], 8.194335, 1e-5)
Esempio n. 20
0
    def test_nested(self):

        top = Problem()
        root = top.root = Group()
        sub = root.add('sub', Group(), promotes=['x', 'z', 'y1', 'y2'])

        sub.add('comp', SellarInABox(), promotes=['x', 'z', 'y1', 'y2'])
        sub.add('px', IndepVarComp('x', 1.0), promotes=['x'])
        sub.add('pz', IndepVarComp('z', np.array([5.0, 2.0])), promotes=['z'])

        root.nl_solver = Newton()
        root.ln_solver = ScipyGMRES()
        root.ln_solver.preconditioner = LinearGaussSeidel()

        top.setup(check=False)

        # Turn on all iprints
        top.print_all_convergence()

        base_stdout = sys.stdout

        try:
            ostream = cStringIO()
            sys.stdout = ostream
            top.run()
        finally:
            sys.stdout = base_stdout

        assert_rel_error(self, top['y1'], 25.58830273, .00001)
        assert_rel_error(self, top['y2'], 12.05848819, .00001)

        self.assertGreater(top.root.sub.comp.count_solve_linear, 0)

        printed = ostream.getvalue()
        self.assertTrue('PRECON:' in printed)
Esempio n. 21
0
    def test_data_pass_bounds_idx(self):

        p = Problem()
        p.root = Group()

        p.root.add('lower', ExecComp('low = 2*a'), promotes=['low', 'a'])
        p.root.add('upper', ExecComp('high = 2*b'), promotes=['high', 'b'])

        sub = p.root.add('sub', Group(), promotes=['x', 'low', 'high'])
        sub.add('comp', IndexCompTest(), promotes=['a', 'x', 'n', 'b', 'c'])
        sub.add('dummy1', ExecComp('d=low'), promotes=['low'])
        sub.add('dummy2', ExecComp('d=high'), promotes=['high'])
        sub.nl_solver = Brent()

        sub.nl_solver.options['state_var'] = 'x'
        sub.nl_solver.options['state_var_idx'] = 2
        sub.nl_solver.options['var_lower_bound'] = 'low'
        sub.nl_solver.options['var_upper_bound'] = 'high'
        sub.ln_solver = ScipyGMRES()

        p.setup(check=False)
        p['a'] = -5.
        p['b'] = 55.
        p.run()

        assert_rel_error(self, p.root.unknowns['x'][2], 110, .0001)
Esempio n. 22
0
    def test_converge_diverge_groups(self):

        prob = Problem()
        prob.root = ConvergeDivergeGroups()
        prob.root.ln_solver = ScipyGMRES()
        prob.root.ln_solver.options['precondition'] = True

        prob.root.sub1.ln_solver = DirectSolver()
        prob.root.sub3.ln_solver = DirectSolver()

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

        # Make sure value is fine.
        assert_rel_error(self, prob['comp7.y1'], -102.7, 1e-6)

        indep_list = ['p.x']
        unknown_list = ['comp7.y1']

        J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')
        assert_rel_error(self, J['comp7.y1']['p.x'][0][0], -40.75, 1e-6)

        J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')
        assert_rel_error(self, J['comp7.y1']['p.x'][0][0], -40.75, 1e-6)

        J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='dict')
        assert_rel_error(self, J['comp7.y1']['p.x'][0][0], -40.75, 1e-6)
Esempio n. 23
0
    def test_ubcs(self):
        p = Problem(root=Group())
        root = p.root
        root.ln_solver = ScipyGMRES()

        self.P1 = root.add("P1", IndepVarComp('x', 1.0))
        self.C1 = root.add("C1", ExecComp('y=x1*2.0+x2*3.0', x2=1.0))
        self.C2 = root.add("C2", ExecComp('y=x1*2.0+x2'))
        self.C3 = root.add("C3", ExecComp('y=x*2.0'))
        self.C4 = root.add("C4", ExecComp('y=x1*2.0 + x2*5.0'))
        self.C5 = root.add("C5", ExecComp('y=x1*2.0 + x2*7.0'))

        root.connect("P1.x", "C1.x1")
        root.connect("C1.y", ("C2.x1", "C3.x"))
        root.connect("C2.y", "C4.x1")
        root.connect("C3.y", "C4.x2")

        # input-input connection
        root.connect("C1.x2", "C5.x2")

        # create a cycle
        root.connect("C4.y", "C1.x2")

        # set a bogus value for C4.y
        self.C4._init_unknowns_dict['y']['val'] = -999.

        p.setup(check=False)

        ubcs = p._get_ubc_vars(root.connections)

        self.assertEqual(ubcs, ['C1.x2'])

        p.run()
    def test_simple_implicit(self):

        prob = Problem()
        prob.root = Group()
        prob.root.ln_solver = ScipyGMRES()
        prob.root.add('comp', SimpleImplicitComp())
        prob.root.add('p1', IndepVarComp('x', 0.5))

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

        prob.root.comp.deriv_options['check_type'] = 'cs'

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

        # Correct total derivatives (we can do this one manually)
        J = prob.calc_gradient(['p1.x'], ['comp.y'], mode='fwd')
        assert_rel_error(self, J[0][0], -2.5555511, 1e-5)

        J = prob.calc_gradient(['p1.x'], ['comp.y'], mode='rev')
        assert_rel_error(self, J[0][0], -2.5555511, 1e-5)

        J = prob.calc_gradient(['p1.x'], ['comp.y'], mode='fd')
        assert_rel_error(self, J[0][0], -2.5555511, 1e-5)

        # Clean up old FD
        prob.run()

        # Partials
        data = prob.check_partial_derivatives(out_stream=None)
        #data = prob.check_partial_derivatives()

        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)

        assert_rel_error(self, data['comp'][('y', 'x')]['J_fwd'][0][0], 1.0, 1e-6)
        assert_rel_error(self, data['comp'][('y', 'z')]['J_fwd'][0][0], 2.0, 1e-6)
        assert_rel_error(self, data['comp'][('z', 'x')]['J_fwd'][0][0], 2.66666667, 1e-6)
        assert_rel_error(self, data['comp'][('z', 'z')]['J_fwd'][0][0], 1.5, 1e-6)

        # Clean up old FD
        prob.run()

        # Make sure check_totals works too
        data = prob.check_total_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            assert_rel_error(self, val1['abs error'][0], 0.0, 1e-5)
            assert_rel_error(self, val1['abs error'][1], 0.0, 1e-5)
            assert_rel_error(self, val1['abs error'][2], 0.0, 1e-5)
            assert_rel_error(self, val1['rel error'][0], 0.0, 1e-5)
            assert_rel_error(self, val1['rel error'][1], 0.0, 1e-5)
            assert_rel_error(self, val1['rel error'][2], 0.0, 1e-5)
Esempio n. 25
0
    def __init__(self,
                 nTurbines,
                 direction_id=0,
                 datasize=0,
                 differentiable=True,
                 use_rotor_components=False,
                 nSamples=0,
                 wake_model=floris_wrapper,
                 wake_model_options=None):

        super(RotorSolveGroup, self).__init__()

        if wake_model_options is None:
            wake_model_options = {
                'differentiable': differentiable,
                'use_rotor_components': use_rotor_components,
                'nSamples': nSamples
            }

        from openmdao.core.mpi_wrap import MPI

        # set up iterative solvers
        epsilon = 1E-6
        if MPI:
            self.ln_solver = PetscKSP()
        else:
            self.ln_solver = ScipyGMRES()
        self.nl_solver = NLGaussSeidel()
        self.ln_solver.options['atol'] = epsilon

        self.add('CtCp',
                 CPCT_Interpolate_Gradients_Smooth(nTurbines,
                                                   direction_id=direction_id,
                                                   datasize=datasize),
                 promotes=[
                     'gen_params:*',
                     'yaw%i' % direction_id,
                     'wtVelocity%i' % direction_id, 'Cp_out'
                 ])

        # TODO refactor the model component instance
        self.add('floris',
                 wake_model(nTurbines,
                            direction_id=direction_id,
                            wake_model_options=wake_model_options),
                 promotes=([
                     'model_params:*', 'wind_speed', 'axialInduction',
                     'turbineXw', 'turbineYw', 'rotorDiameter',
                     'yaw%i' % direction_id, 'hubHeight',
                     'wtVelocity%i' % direction_id
                 ] if (nSamples == 0) else [
                     'model_params:*', 'wind_speed', 'axialInduction',
                     'turbineXw', 'turbineYw', 'rotorDiameter',
                     'yaw%i' % direction_id, 'hubHeight',
                     'wtVelocity%i' %
                     direction_id, 'wsPositionX', 'wsPositionY', 'wsPositionZ',
                     'wsArray%i' % direction_id
                 ]))
        self.connect('CtCp.Ct_out', 'floris.Ct')
Esempio n. 26
0
    def test_explicit_connection_errors(self):
        class A(Component):
            def __init__(self):
                super(A, self).__init__()
                self.add_state('x', 0)

        class B(Component):
            def __init__(self):
                super(B, self).__init__()
                self.add_param('x', 0)

        prob = Problem()
        prob.root = Group()
        prob.root.ln_solver = ScipyGMRES()
        prob.root.add('A', A())
        prob.root.add('B', B())

        prob.root.connect('A.x', 'B.x')
        prob.setup(check=False)

        prob = Problem()
        prob.root = Group()
        prob.root.add('A', A())
        prob.root.add('B', B())
        prob.root.connect('A.y', 'B.x')

        with self.assertRaises(ConnectError) as cm:
            prob.setup(check=False)

        expected = ("Source 'A.y' cannot be connected to target 'B.x': "
                    "'A.y' does not exist.")
        self.assertEqual(str(cm.exception), expected)

        prob = Problem()
        prob.root = Group()
        prob.root.add('A', A())
        prob.root.add('B', B())
        prob.root.connect('A.x', 'B.y')

        with self.assertRaises(ConnectError) as cm:
            prob.setup(check=False)

        expected = ("Source 'A.x' cannot be connected to target 'B.y': "
                    "'B.y' does not exist.")
        self.assertEqual(str(cm.exception), expected)

        prob = Problem()
        prob.root = Group()
        prob.root.add('A', A())
        prob.root.add('B', B())
        prob.root.connect('A.x', 'A.x')

        with self.assertRaises(ConnectError) as cm:
            prob.setup(check=False)

        expected = ("Source 'A.x' cannot be connected to target 'A.x': "
                    "Target must be a parameter but 'A.x' is an unknown.")
        self.assertEqual(str(cm.exception), expected)
Esempio n. 27
0
    def __init__(self):
        super(TubeGroup, self).__init__()

        # Adding in components to Tube Group
        self.add('Vacuum', Vacuum(), promotes=['tube_area',
        									                     'tube_length',
                          									   'electricity_price',
                          									   'pressure_initial',
                                               'pwr',
                                               'speed',
                                               'time_down',
                                               'gamma',
                                               'pump_weight'])

        self.add('Temp',TubeTemp(), promotes=['nozzle_air_W',
                                              'nozzle_air_Tt',
                                              'num_pods',
                                              'temp_boundary',
                                              'tube_thickness'])

        self.add('Struct', TubeAndPylon(), promotes=['h', 'p_tunnel', 'm_pod', 'r_pylon'])
        
        self.add('PropMech', PropulsionMechanics(), promotes=['vf',
                                                              'v0',
                                                              'Cd',
                                                              'S',
                                                              'D_mag',
                                                              'nozzle_thrust',
                                                              'ram_drag'])
        
        self.add('TubePower', TubePower(), promotes=['num_thrust',
                                                     'time_thrust'])

        self.add('SteadyStateVacuum', SteadyStateVacuum(), promotes = ['fl_start.W', 'comp.power', 'pod_period', 'L_pod'])

        self.add('SubmergedTube', SubmergedTube(), promotes = ['depth'])

        # Connects tube group level variables to downstream components
        self.connect('tube_area', ['Temp.tube_area', 'Struct.tube_area', 'SubmergedTube.A_tube', 'SteadyStateVacuum.A_tube'])
        self.connect('tube_length', 'Temp.length_tube')
        self.connect('p_tunnel', ['PropMech.p_tube', 'Vacuum.pressure_final', 'SteadyStateVacuum.fl_start.P', 'SubmergedTube.p_tube'])
        self.connect('electricity_price', 'TubePower.elec_price')
        self.connect('tube_thickness', 'Struct.t')
        self.connect('m_pod', 'PropMech.m_pod')

        # Connects vacuum outputs to downstream components
        self.connect('Vacuum.weight_tot', 'Struct.vac_weight')
        self.connect('Vacuum.pwr_tot', 'TubePower.vac_power')
        self.connect('Vacuum.energy_tot', 'TubePower.vac_energy_day')

        # Connects tube_wall_temp outputs to downstream components
        self.connect('temp_boundary', ['TubePower.tube_temp', 'SteadyStateVacuum.fl_start.T','PropMech.T_ambient'])

        # Connects propulsion_mechanics outputs to downstream components
        self.connect('PropMech.pwr_req', 'TubePower.prop_power')

        self.ln_solver = ScipyGMRES()
Esempio n. 28
0
    def __init__(self):
        super(MotorGroup, self).__init__()

        self.add('motor',
                 Motor(),
                 promotes=['design_torque', 'motor_max_current',
                           'phase_current', 'phase_voltage', 'current',
                           'voltage', 'frequency', 'motor_power_input'])
        self.add('motor_size',
                 MotorSize(),
                 promotes=['motor_mass', 'design_torque', 'design_power',
                            'motor_max_current', 'motor_length', 'motor_diameter', 'motor_volume',
                           'motor_LD_ratio', 'motor_oversize_factor'])
        self.add('motor_balance',
                 MotorBalance(),
                 promotes=['current', 'voltage', 'motor_power_input'])

        self.connect('motor_size.max_torque', 'motor.max_torque')

        self.add('idp1',
                 IndepVarComp('n_phases', 3.0,
                              units='unitless'))
        self.connect('idp1.n_phases', ['motor_size.n_phases', 'motor.n_phases'])

        self.add('idp2',
                 IndepVarComp('pole_pairs', 6.0,
                              units='unitless'))

        self.connect('idp2.pole_pairs',
                     ['motor_size.pole_pairs', 'motor.pole_pairs'])

        #self.add('idp3',
        #         IndepVarComp('motor_max_current', 42.0,
        #                      units='A'),
        #         promotes=['motor_max_current'])

        # self.add('idp4',
        #          IndepVarComp('design_torque', 1.0,
        #                       units='N*m'),
        #          promotes=['design_torque'])

        self.connect('motor_size.power_iron_loss', 'motor.power_iron_loss')
        self.connect('motor_size.power_mech', 'motor.power_mech')
        self.connect('motor_size.power_windage_loss',
                     'motor.power_windage_loss')
        self.connect('motor_size.w_operating', 'motor.w_operating')
        self.connect('motor_size.winding_resistance',
                     'motor.winding_resistance')

        self.connect('motor_balance.I0', 'motor.I0')

        self.nl_solver = Newton()
        self.nl_solver.options['maxiter'] = 1000
        self.nl_solver.options['atol'] = 0.0001

        self.ln_solver = ScipyGMRES()
        self.ln_solver.options['maxiter'] = 100
Esempio n. 29
0
    def test_nested_relevancy_gmres(self):

        # This test is just to make sure that values in the dp vector from
        # higher scopes aren't sitting there converting themselves during sub
        # iterations.

        prob = Problem()
        root = prob.root = Group()
        root.add('p1', IndepVarComp('xx', 3.0))
        root.add('c1', ExecComp(['y1=0.5*x + 1.0*xx', 'y2=0.3*x - 1.0*xx'], units={'y2' : 'km'}))
        root.add('c2', ExecComp(['y=0.5*x']))
        sub = root.add('sub', Group())
        sub.add('cc1', ExecComp(['y=1.01*x1 + 1.01*x2'], units={'x1' : 'fm'}))
        sub.add('cc2', ExecComp(['y=1.01*x']))

        root.connect('p1.xx', 'c1.xx')
        root.connect('c1.y1', 'c2.x')
        root.connect('c2.y', 'c1.x')
        root.connect('c1.y2', 'sub.cc1.x1')
        root.connect('sub.cc1.y', 'sub.cc2.x')
        root.connect('sub.cc2.y', 'sub.cc1.x2')

        root.nl_solver = Newton()
        root.nl_solver.options['maxiter'] = 1
        root.ln_solver = ScipyGMRES()
        root.ln_solver.options['maxiter'] = 1

        sub.nl_solver = Newton()
        sub.ln_solver = ScipyGMRES()

        prob.driver.add_desvar('p1.xx')
        prob.driver.add_objective('sub.cc2.y')

        prob.setup(check=False)

        prob.run()

        # GMRES doesn't cause a successive build-up in the value of an out-of
        # scope param, but the linear solver doesn't converge. We can test to
        # make sure it does.
        iter_count = sub.ln_solver.iter_count
        self.assertTrue(iter_count < 20)
        self.assertTrue(not np.isnan(prob['sub.cc2.y']))
Esempio n. 30
0
    def test_implicit(self):
        top = Problem()
        root = top.root = Group()
        root.add('comp', SimpleImplicitComp())

        root.ln_solver = ScipyGMRES()
        top.setup(check=False)

        top.run()
        assert_rel_error(self, top['comp.z'], 2.666667, 1e-5)