Пример #1
0
    def test_betz_derivatives(self):
        from openmdao.api import Problem, IndepVarComp

        from openmdao.test_suite.test_examples.test_betz_limit import ActuatorDisc

        prob = Problem()

        prob.model.add_subsystem('a_disk', ActuatorDisc())

        prob.setup()

        prob.check_partials(compact_print=True)
Пример #2
0
    def test_check_partials_for_docs(self):

        from openmdao.api import Problem
        from openmdao.test_suite.components.quad_implicit import QuadraticComp

        p = Problem()

        p.model.add_subsystem('quad', QuadraticComp())

        p.setup()

        p.check_partials(compact_print=True)
Пример #3
0
    def test_scalar_example(self):

        prob = Problem(model=Group())

        bal = BalanceComp()

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

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

        exec_comp = 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()

        for (of, wrt) in cpd['balance']:
            assert_almost_equal(cpd['balance'][of, wrt]['abs error'], 0.0, decimal=5)

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

        prob.setup()

        prob.run_model()

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

        np.set_printoptions(linewidth=1024)

        cpd = prob.check_partials()

        for (of, wrt) in cpd['balance']:
            assert_almost_equal(cpd['balance'][of, wrt]['abs error'], 0.0, decimal=5)
Пример #4
0
    def test_compute_jacvec_product_inputs_read_only_reset(self):
        class BadComp(RectangleJacVec):
            def compute_jacvec_product(self, inputs, d_inputs, d_outputs, mode):
                super(BadComp, self).compute_jacvec_product(inputs, d_inputs, d_outputs, mode)
                raise AnalysisError("It's just a scratch.")

        prob = Problem(BadComp())
        prob.setup()
        prob.run_model()

        with self.assertRaises(AnalysisError):
            prob.check_partials()

        # verify read_only status is reset after AnalysisError
        prob['length'] = 111.
Пример #5
0
    def test_compute_partials_inputs_read_only_reset(self):
        class BadComp(TestExplCompSimpleDense):
            def compute_partials(self, inputs, partials):
                super(BadComp, self).compute_partials(inputs, partials)
                raise AnalysisError("It's just a scratch.")

        prob = Problem(BadComp())
        prob.setup()
        prob.run_model()

        with self.assertRaises(AnalysisError):
            prob.check_partials()

        # verify read_only status is reset after AnalysisError
        prob['length'] = 111.
Пример #6
0
    def test_vectorized(self):
        prob = Problem()
        prob.model = model = Group()

        x = np.zeros((3, 5))
        x[0, :] = np.array([3.0, 5.0, 11.0, 13.0, 17.0])
        x[1, :] = np.array([13.0, 11.0, 5.0, 17.0, 3.0])*2
        x[2, :] = np.array([11.0, 3.0, 17.0, 5.0, 13.0])*3

        model.add_subsystem('px', IndepVarComp(name="x", val=x))
        model.add_subsystem('ks', KSComp(width=5, vec_size=3))
        model.connect('px.x', 'ks.g')

        model.add_design_var('px.x')
        model.add_constraint('ks.KS', upper=0.0)

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

        assert_rel_error(self, prob['ks.KS'][0], 17.0)
        assert_rel_error(self, prob['ks.KS'][1], 34.0)
        assert_rel_error(self, prob['ks.KS'][2], 51.0)

        partials = prob.check_partials(includes=['ks'], out_stream=None)

        for (of, wrt) in partials['ks']:
            assert_rel_error(self, partials['ks'][of, wrt]['abs error'][0], 0.0, 1e-6)
Пример #7
0
    def test_sellar_idf(self):
        prob = Problem(SellarIDF())
        prob.driver = ScipyOptimizeDriver(optimizer='SLSQP', disp=False)
        prob.setup()

        # check derivatives
        prob['dv.y1'] = 100
        prob['equal.rhs:y1'] = 1

        prob.run_model()

        cpd = prob.check_partials(out_stream=None)

        for (of, wrt) in cpd['equal']:
            assert_almost_equal(cpd['equal'][of, wrt]['abs error'], 0.0, decimal=5)

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

        # check results
        prob.run_driver()

        assert_rel_error(self, prob['dv.x'], 0., 1e-5)
        assert_rel_error(self, prob['dv.z'], [1.977639, 0.], 1e-5)

        assert_rel_error(self, prob['obj_cmp.obj'], 3.18339395045, 1e-5)

        assert_almost_equal(prob['dv.y1'], 3.16)
        assert_almost_equal(prob['d1.y1'], 3.16)

        assert_almost_equal(prob['dv.y2'], 3.7552778)
        assert_almost_equal(prob['d2.y2'], 3.7552778)

        assert_almost_equal(prob['equal.y1'], 0.0)
        assert_almost_equal(prob['equal.y2'], 0.0)
Пример #8
0
    def test_vectorized_rhs_val(self):
        prob = Problem()
        model = prob.model

        n = 100

        # find where x^2 == 4, vectorized
        model.add_subsystem('indep', IndepVarComp('x', val=np.ones(n)))
        model.add_subsystem('f', ExecComp('y=x**2', x=np.ones(n), y=np.ones(n)))
        model.add_subsystem('equal', EQConstraintComp('y', val=np.ones(n),
                            rhs_val=np.ones(n)*4., use_mult=True, mult_val=2.))
        model.add_subsystem('obj_cmp', ExecComp('obj=sum(y)', y=np.zeros(n)))

        model.connect('indep.x', 'f.x')

        model.connect('indep.x', 'equal.lhs:y')
        model.connect('f.y', 'obj_cmp.y')

        model.add_design_var('indep.x', lower=np.zeros(n), upper=np.ones(n)*10.)
        model.add_constraint('equal.y', equals=0.)
        model.add_objective('obj_cmp.obj')

        prob.setup(mode='fwd')
        prob.driver = ScipyOptimizeDriver(disp=False)
        prob.run_driver()

        assert_rel_error(self, prob['equal.y'], np.zeros(n), 1e-6)
        assert_rel_error(self, prob['indep.x'], np.ones(n)*2., 1e-6)
        assert_rel_error(self, prob['f.y'], np.ones(n)*4., 1e-6)

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

        # find where x^2 == 4
        model.add_subsystem('indep', IndepVarComp('x', val=1.))
        model.add_subsystem('f', ExecComp('y=x**2', x=1.))
        model.add_subsystem('equal', EQConstraintComp('y', rhs_val=4.))

        model.connect('indep.x', 'f.x')
        model.connect('f.y', 'equal.lhs:y')

        model.add_design_var('indep.x', lower=0., upper=10.)
        model.add_constraint('equal.y', equals=0.)
        model.add_objective('f.y')

        prob.setup(mode='fwd')
        prob.driver = ScipyOptimizeDriver(disp=False)
        prob.run_driver()

        assert_rel_error(self, prob['equal.y'], 0., 1e-6)
        assert_rel_error(self, prob['indep.x'], 2., 1e-6)
        assert_rel_error(self, prob['f.y'], 4., 1e-6)

        cpd = prob.check_partials(out_stream=None)

        for (of, wrt) in cpd['equal']:
            assert_almost_equal(cpd['equal'][of, wrt]['abs error'], 0.0, decimal=5)

        assert_check_partials(cpd, atol=1e-5, rtol=1e-5)
    def test_detailed(self):
        """ This is a longer version of the previous method, with plotting. """

        # Load in default lifting surfaces to setup the comparison
        surfaces = get_default_surfaces()

        # Instantiate an OpenMDAO problem and add the component we want to test
        # as asubsystem, giving that component a default lifting surface
        prob = Problem()
        prob.model.add_subsystem('tube', SectionPropertiesTube(surface=surfaces[0]))

        # Set up the problem and ensure it uses complex arrays so we can check
        # the derivatives using complex step
        prob.setup(force_alloc_complex=True)

        # Actually run the model, which is just a component in this case, then
        # check the derivatives and store the results in the `check` dict
        prob.run_model()
        check = prob.check_partials(compact_print=False)

        # Loop through this `check` dictionary and visualize the approximated
        # and computed derivatives
        for key, subjac in iteritems(check[list(check.keys())[0]]):
            print()
            print(key)
            view_mat(subjac['J_fd'],subjac['J_fwd'],key)

        # Loop through the `check` dictionary and perform assert that the
        # approximated deriv must be very close to the computed deriv
        for key, subjac in iteritems(check[list(check.keys())[0]]):
            if subjac['magnitude'].fd > 1e-6:
                assert_almost_equal(
                    subjac['rel error'].forward, 0., err_msg='deriv of %s wrt %s' % key)
                assert_almost_equal(
                    subjac['rel error'].reverse, 0., err_msg='deriv of %s wrt %s' % key)
Пример #11
0
    def test_complex_step(self):
        prob = Problem()
        model = prob.model

        # find where 2*x == x^2
        model.add_subsystem('indep', IndepVarComp('x', val=1.))
        model.add_subsystem('multx', IndepVarComp('m', val=2.))
        model.add_subsystem('f', ExecComp('y=x**2', x=1.))
        model.add_subsystem('equal', EQConstraintComp('y', use_mult=True))

        model.connect('indep.x', 'f.x')

        model.connect('indep.x', 'equal.lhs:y')
        model.connect('multx.m', 'equal.mult:y')
        model.connect('f.y', 'equal.rhs:y')

        model.add_design_var('indep.x', lower=0., upper=10.)
        model.add_constraint('equal.y', equals=0.)
        model.add_objective('f.y')

        prob.setup(mode='fwd', force_alloc_complex=True)
        prob.driver = ScipyOptimizeDriver(disp=False)
        prob.run_driver()

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

        assert_check_partials(cpd, atol=1e-10, rtol=1e-10)
Пример #12
0
    def test_create_on_init_no_normalization(self):

        prob = Problem(model=Group())

        bal = BalanceComp('x', val=1.0, normalize=False)

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

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

        prob.model.linear_solver = DirectSolver()
        prob.model.nonlinear_solver = NewtonSolver(iprint=0)

        prob.setup()

        prob.run_model()

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

        assert_almost_equal(prob.model.balance._scale_factor, 1.0)

        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)
Пример #13
0
    def test_rhs_val(self):
        """ Test solution with a default RHS value and no connected RHS variable. """

        n = 1

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

        bal = BalanceComp('x', rhs_val=4.0)

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

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

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

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

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

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

        prob.setup()

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

        prob.run_model()

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

        cpd = prob.check_partials(out_stream=None)

        for (of, wrt) in cpd['balance']:
            assert_almost_equal(cpd['balance'][of, wrt]['abs error'], 0.0, decimal=5)
Пример #14
0
    def test_rk_with_time_invariant(self):
        np.random.seed(1)

        indeps = IndepVarComp()
        rktest = RKTest(NTIME)

        indeps.add_output('yi', np.random.random((2, 3)))
        indeps.add_output('yv', np.random.random((2, NTIME)))
        indeps.add_output('x0', np.random.random((2,)))

        prob = Problem()

        prob.model.add_subsystem('indeps', indeps, promotes=['*'])
        prob.model.add_subsystem('rktest', rktest, promotes=['*'])

        prob.setup()
        prob.run_model()

        # check partials
        partials = prob.check_partials(out_stream=None)
        assert_check_partials(partials, atol=6e-5, rtol=6e-5)

        # check totals
        inputs = ['yi', 'yv', 'x0']
        outputs = ['x']

        J = prob.check_totals(of=outputs, wrt=inputs, out_stream=None)

        for outp in outputs:
            for inp in inputs:
                Jn = J[outp, inp]['J_fd']
                Jf = J[outp, inp]['J_fwd']
                diff = abs(Jf - Jn)
                assert_rel_error(self, diff.max(), 0.0, 6e-5)
Пример #15
0
    def test_exec_comp_jac(self, f):
        test_data = _ufunc_test_data[f]

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

        if len(test_data['args']) > 1:
            ivc = model.add_subsystem(name='ivc', subsys=IndepVarComp())
            for arg_name, arg_value in iteritems(test_data['args']):
                if arg_name == 'f':
                    continue
                ivc.add_output(name=arg_name, val=arg_value['value'])
                model.connect('ivc.{0}'.format(arg_name),
                              '{0}_comp.{1}'.format(f, arg_name))

        model.add_subsystem('{0}_comp'.format(f),
                            ExecComp(test_data['str'], **test_data['args']),
                            promotes_outputs=['f'])
        prob.setup()
        prob.run_model()

        if 'check_val' not in test_data:
            cpd = prob.check_partials(compact_print=True)

            for comp in cpd:
                for (var, wrt) in cpd[comp]:
                    np.testing.assert_almost_equal(cpd[comp][var, wrt]['abs error'], 0, decimal=4)
Пример #16
0
    def test_solve_linear(self):
        """Check against solve_linear."""

        x = np.array([1, 2, -3])
        A = np.array([[1., 1., 1.], [1., 2., 3.], [0., 1., 3.]])
        b = A.dot(x)
        b_T = A.T.dot(x)

        lin_sys_comp = LinearSystemComp(size=3)

        prob = Problem()

        prob.model.add_subsystem('p1', IndepVarComp('A', A))
        prob.model.add_subsystem('p2', IndepVarComp('b', b))

        lingrp = prob.model.add_subsystem('lingrp', Group(), promotes=['*'])
        lingrp.add_subsystem('lin', lin_sys_comp)

        prob.model.connect('p1.A', 'lin.A')
        prob.model.connect('p2.b', 'lin.b')

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

        prob.run_model()
        prob.model.run_linearize()

        # Compare against calculated derivs
        Ainv = np.array([[3., -2., 1.],
                         [-3., 3., -2.],
                         [1., -1., 1.]])

        dx_dA = np.outer(Ainv, -x).reshape(3, 9)
        dx_db = Ainv

        d_inputs, d_outputs, d_residuals = lingrp.get_linear_vectors()

        # Forward mode with RHS of self.b
        d_residuals['lin.x'] = b
        lingrp.run_solve_linear(['linear'], 'fwd')
        sol = d_outputs['lin.x']
        assert_rel_error(self, sol, x, .0001)

        # Reverse mode with RHS of self.b_T
        d_outputs['lin.x'] = b_T
        lingrp.run_solve_linear(['linear'], 'rev')
        sol = d_residuals['lin.x']
        assert_rel_error(self, sol, x, .0001)

        J = prob.compute_totals(['lin.x'], ['p1.A', 'p2.b', 'lin.x'], return_format='flat_dict')
        assert_rel_error(self, J['lin.x', 'p1.A'], dx_dA, .0001)
        assert_rel_error(self, J['lin.x', 'p2.b'], dx_db, .0001)

        data = prob.check_partials(out_stream=None)

        abs_errors = data['lingrp.lin'][('x', 'x')]['abs error']
        self.assertTrue(len(abs_errors) > 0)
        for match in abs_errors:
            abs_error = float(match)
            self.assertTrue(abs_error < 1.e-6)
Пример #17
0
    def test_compute_partials_inputs_read_only(self):
        class BadComp(TestExplCompSimpleDense):
            def compute_partials(self, inputs, partials):
                super(BadComp, self).compute_partials(inputs, partials)
                inputs['length'] = 0.  # should not be allowed

        prob = Problem(BadComp())
        prob.setup()
        prob.run_model()

        with self.assertRaises(ValueError) as cm:
            prob.check_partials()

        self.assertEqual(str(cm.exception),
                         "Attempt to set value of 'length' in input vector "
                         "when it is read only.")
Пример #18
0
    def test_compute_jacvec_product_inputs_read_only(self):
        class BadComp(RectangleJacVec):
            def compute_jacvec_product(self, inputs, d_inputs, d_outputs, mode):
                super(BadComp, self).compute_jacvec_product(inputs, d_inputs, d_outputs, mode)
                inputs['length'] = 0.  # should not be allowed

        prob = Problem(BadComp())
        prob.setup()
        prob.run_model()

        with self.assertRaises(ValueError) as cm:
            prob.check_partials()

        self.assertEqual(str(cm.exception),
                         "Attempt to set value of 'length' in input vector "
                         "when it is read only.")
Пример #19
0
    def test_assert_check_partials_no_exception_expected(self):
        import numpy as np
        from openmdao.api import Problem, ExplicitComponent
        from openmdao.utils.assert_utils import assert_check_partials

        class MyComp(ExplicitComponent):
            def setup(self):
                self.add_input('x1', 3.0)
                self.add_input('x2', 5.0)

                self.add_output('y', 5.5)

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

            def compute(self, inputs, outputs):
                outputs['y'] = 3.0 * inputs['x1'] + 4.0 * inputs['x2']

            def compute_partials(self, inputs,     partials):
                """Correct derivative."""
                J = partials
                J['y', 'x1'] = np.array([3.0])
                J['y', 'x2'] = np.array([4.0])

        prob = Problem()
        prob.model = MyComp()

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

        data = prob.check_partials(out_stream=None)
        atol = 1.e-6
        rtol = 1.e-6
        assert_check_partials(data, atol, rtol)
Пример #20
0
    def test_derivatives(self):
        mm = MetaModelUnStructured()
        mm.add_input('x', 0.)
        mm.add_output('f', 0.)
        mm.default_surrogate = FloatKrigingSurrogate()

        prob = Problem()
        prob.model.add_subsystem('p', IndepVarComp('x', 0.),
                                 promotes_outputs=['x'])
        prob.model.add_subsystem('mm', mm,
                                 promotes_inputs=['x'])
        prob.setup()

        mm.metadata['train:x'] = [0., .25, .5, .75, 1.]
        mm.metadata['train:f'] = [1., .75, .5, .25, 0.]

        prob['x'] = 0.125
        prob.run_model()

        data = prob.check_partials()

        Jf = data['mm'][('f', 'x')]['J_fwd']
        Jr = data['mm'][('f', 'x')]['J_rev']

        assert_rel_error(self, Jf[0][0], -1., 1.e-3)
        assert_rel_error(self, Jr[0][0], -1., 1.e-3)

        # TODO: complex step not currently supported in check_partial_derivs
        # data = prob.check_partials(global_options={'method': 'cs'})

        abs_errors = data['mm'][('f', 'x')]['abs error']
        self.assertTrue(len(abs_errors) > 0)
        for match in abs_errors:
            abs_error = float(match)
            self.assertTrue(abs_error < 1.e-6)
Пример #21
0
    def test_create_on_init(self):

        prob = Problem(model=Group())

        bal = BalanceComp('x', val=1.0)

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

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

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

        prob.setup()

        prob.run_model()

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

        np.set_printoptions(linewidth=1024)

        cpd = prob.check_partials()

        for (of, wrt) in cpd['balance']:
            assert_almost_equal(cpd['balance'][of, wrt]['abs error'], 0.0, decimal=5)
Пример #22
0
    def test_basic_fd_comps(self):

        prob = Problem()
        prob.model = Group()
        prob.model.add_subsystem('px1', IndepVarComp('x1', 100.0), promotes=['x1'])
        prob.model.add_subsystem('src', SrcCompFD())
        prob.model.add_subsystem('tgtF', TgtCompFFD())
        prob.model.add_subsystem('tgtC', TgtCompCFD())
        prob.model.add_subsystem('tgtK', TgtCompKFD())
        prob.model.connect('x1', 'src.x1')
        prob.model.connect('src.x2', 'tgtF.x2')
        prob.model.connect('src.x2', 'tgtC.x2')
        prob.model.connect('src.x2', 'tgtK.x2')

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

        assert_rel_error(self, prob['src.x2'], 100.0, 1e-6)
        assert_rel_error(self, prob['tgtF.x3'], 212.0, 1e-6)
        assert_rel_error(self, prob['tgtC.x3'], 100.0, 1e-6)
        assert_rel_error(self, prob['tgtK.x3'], 373.15, 1e-6)

        indep_list = ['x1']
        unknown_list = ['tgtF.x3', 'tgtC.x3', 'tgtK.x3']
        J = prob.compute_totals(of=unknown_list, wrt=indep_list, return_format='dict')

        assert_rel_error(self, J['tgtF.x3']['x1'][0][0], 1.8, 1e-6)
        assert_rel_error(self, J['tgtC.x3']['x1'][0][0], 1.0, 1e-6)
        assert_rel_error(self, J['tgtK.x3']['x1'][0][0], 1.0, 1e-6)

        prob.setup(check=False, mode='rev')
        prob.run_model()
        J = prob.compute_totals(of=unknown_list, wrt=indep_list, return_format='dict')

        assert_rel_error(self, J['tgtF.x3']['x1'][0][0], 1.8, 1e-6)
        assert_rel_error(self, J['tgtC.x3']['x1'][0][0], 1.0, 1e-6)
        assert_rel_error(self, J['tgtK.x3']['x1'][0][0], 1.0, 1e-6)

        prob.model.approx_totals(method='fd')
        prob.setup(check=False, mode='rev')
        prob.run_model()
        J = prob.compute_totals(of=unknown_list, wrt=indep_list, return_format='dict')

        assert_rel_error(self, J['tgtF.x3']['x1'][0][0], 1.8, 1e-6)
        assert_rel_error(self, J['tgtC.x3']['x1'][0][0], 1.0, 1e-6)
        assert_rel_error(self, J['tgtK.x3']['x1'][0][0], 1.0, 1e-6)

        # Make sure check partials handles conversion
        data = prob.check_partials()

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-6)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-6)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-6)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-6)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-6)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-6)
Пример #23
0
class TestCrossProductCompNx3x1(unittest.TestCase):

    def setUp(self):
        self.nn = 5

        self.p = Problem(model=Group())

        ivc = IndepVarComp()
        ivc.add_output(name='a', shape=(self.nn, 3, 1))
        ivc.add_output(name='b', shape=(self.nn, 3, 1))

        self.p.model.add_subsystem(name='ivc',
                                   subsys=ivc,
                                   promotes_outputs=['a', 'b'])

        self.p.model.add_subsystem(name='cross_prod_comp',
                                   subsys=CrossProductComp(vec_size=self.nn))

        self.p.model.connect('a', 'cross_prod_comp.a')
        self.p.model.connect('b', 'cross_prod_comp.b')

        self.p.setup(force_alloc_complex=True)

        self.p['a'] = np.random.rand(self.nn, 3, 1)
        self.p['b'] = np.random.rand(self.nn, 3, 1)

        self.p['a'][:, 0, 0] = 2.0
        self.p['a'][:, 1, 0] = 3.0
        self.p['a'][:, 2, 0] = 4.0

        self.p['b'][:, 0, 0] = 5.0
        self.p['b'][:, 1, 0] = 6.0
        self.p['b'][:, 2, 0] = 7.0

        self.p.run_model()

    def test_results(self):

        for i in range(self.nn):
            a_i = self.p['a'][i, :, 0]
            b_i = self.p['b'][i, :, 0]
            c_i = self.p['cross_prod_comp.c'][i, :]
            expected_i = np.cross(a_i, b_i)

            np.testing.assert_almost_equal(c_i, expected_i)

    def test_partials(self):
        cpd = self.p.check_partials(out_stream=None, method='cs')

        for comp in cpd:
            for (var, wrt) in cpd[comp]:
                np.testing.assert_almost_equal(actual=cpd[comp][var, wrt]['J_fwd'],
                                               desired=cpd[comp][var, wrt]['J_fd'],
                                               decimal=6)
Пример #24
0
    def test_exec_comp_value(self, f):
        test_data = _ufunc_test_data[f]

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

        if len(test_data['args']) > 1:
            ivc = model.add_subsystem(name='ivc', subsys=IndepVarComp())
            for arg_name, arg_value in iteritems(test_data['args']):
                if arg_name == 'f':
                    continue
                ivc.add_output(name=arg_name, val=arg_value['value'])
                model.connect('ivc.{0}'.format(arg_name), 'comp.{0}'.format(arg_name))

        model.add_subsystem('comp', ExecComp(test_data['str'], **test_data['args']),
                            promotes_outputs=['f'])
        prob.setup()
        prob.run_model()

        if 'check_func' in test_data:
            check_args = []
            try:
                check_args.append(test_data['args']['x']['value'])
            except Exception:
                pass
            try:
                check_args.append(test_data['args']['y']['value'])
            except Exception:
                pass
            check_args = tuple(check_args)

            expected = test_data['check_func'](*check_args)
        else:
            expected = test_data['check_val']
        np.testing.assert_almost_equal(prob['f'], expected)

        if 'check_val' not in test_data:
            try:
                prob.check_partials(compact_print=True)
            except TypeError as e:
                print(f, 'does not support complex-step differentiation')
Пример #25
0
    def test_renamed_vars(self):

        n = 1

        prob = Problem(model=Group())

        bal = BalanceComp()

        bal.add_balance('x', use_mult=True, mult_name='MUL', lhs_name='XSQ', rhs_name='TARGETXSQ')

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

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

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

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

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

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

        prob.model.connect('y_tgt', 'balance.TARGETXSQ')
        prob.model.connect('mult', 'balance.MUL')
        prob.model.connect('balance.x', 'exec.x')
        prob.model.connect('exec.y', 'balance.XSQ')

        prob.model.linear_solver = DirectSolver()

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

        prob.model.jacobian = DenseJacobian()

        prob.setup()

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

        prob.run_model()

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

        np.set_printoptions(linewidth=1024)

        cpd = prob.check_partials()

        for (of, wrt) in cpd['balance']:
            assert_almost_equal(cpd['balance'][of, wrt]['abs error'], 0.0, decimal=5)
Пример #26
0
    def test_scalar_with_guess_func_additional_input(self):

        n = 1

        prob = Problem(model=Group())

        bal = BalanceComp()

        bal.add_balance('x', guess_func=lambda inputs, resids: inputs['guess_x'])
        bal.add_input('guess_x', val=0.0)

        ivc = IndepVarComp()
        ivc.add_output(name='y_tgt', val=4)
        ivc.add_output(name='guess_x', val=2.5)

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

        prob.model.add_subsystem(name='ivc', subsys=ivc, promotes_outputs=['y_tgt', 'guess_x'])

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

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

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

        prob.model.linear_solver = DirectSolver()

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

        prob.model.jacobian = DenseJacobian()

        prob.setup()

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

        prob.run_model()

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

        np.set_printoptions(linewidth=1024)

        cpd = prob.check_partials()

        for (of, wrt) in cpd['balance']:
            assert_almost_equal(cpd['balance'][of, wrt]['abs error'], 0.0, decimal=5)
class TestUnits(unittest.TestCase):

    def setUp(self):
        self.nn = 5

        self.p = Problem(model=Group())

        ivc = IndepVarComp()
        ivc.add_output(name='A', shape=(self.nn, 3, 3), units='ft')
        ivc.add_output(name='x', shape=(self.nn, 3), units='lbf')

        self.p.model.add_subsystem(name='ivc',
                                   subsys=ivc,
                                   promotes_outputs=['A', 'x'])

        self.p.model.add_subsystem(name='mat_vec_product_comp',
                                   subsys=MatrixVectorProductComp(vec_size=self.nn,
                                                                  A_units='m', x_units='N',
                                                                  b_units='N*m'))

        self.p.model.connect('A', 'mat_vec_product_comp.A')
        self.p.model.connect('x', 'mat_vec_product_comp.x')

        self.p.setup(force_alloc_complex=True)

        self.p['A'] = np.random.rand(self.nn, 3, 3)
        self.p['x'] = np.random.rand(self.nn, 3)

        self.p.run_model()

    def test_results(self):

        for i in range(self.nn):
            A_i = self.p['A'][i, :, :]
            x_i = self.p['x'][i, :]
            b_i = self.p.get_val('mat_vec_product_comp.b', units='ft*lbf')[i, :]

            expected_i = np.dot(A_i, x_i)
            np.testing.assert_almost_equal(b_i, expected_i)

    def test_partials(self):
        np.set_printoptions(linewidth=1024)
        cpd = self.p.check_partials(out_stream=None, method='cs')

        for comp in cpd:
            for (var, wrt) in cpd[comp]:
                np.testing.assert_almost_equal(actual=cpd[comp][var, wrt]['J_fwd'],
                                               desired=cpd[comp][var, wrt]['J_fd'],
                                               decimal=6)
Пример #28
0
class TestUnits(unittest.TestCase):

    def setUp(self):
        self.nn = 5

        self.p = Problem(model=Group())

        ivc = IndepVarComp()
        ivc.add_output(name='a', shape=(self.nn, 3), units='lbf')
        ivc.add_output(name='b', shape=(self.nn, 3), units='ft/s')

        self.p.model.add_subsystem(name='ivc',
                                   subsys=ivc,
                                   promotes_outputs=['a', 'b'])

        self.p.model.add_subsystem(name='dot_prod_comp',
                                   subsys=DotProductComp(vec_size=self.nn,
                                                         a_units='N', b_units='m/s',
                                                         c_units='W'))

        self.p.model.connect('a', 'dot_prod_comp.a')
        self.p.model.connect('b', 'dot_prod_comp.b')

        self.p.setup()

        self.p['a'] = np.random.rand(self.nn, 3)
        self.p['b'] = np.random.rand(self.nn, 3)

        self.p.run_model()

    def test_results(self):

        for i in range(self.nn):
            a_i = self.p['a'][i, :]
            b_i = self.p['b'][i, :]
            c_i = self.p.get_val('dot_prod_comp.c', units='hp')[i]
            expected_i = np.dot(a_i, b_i) / 550.0

            np.testing.assert_almost_equal(c_i, expected_i)

    def test_partials(self):
        np.set_printoptions(linewidth=1024)
        cpd = self.p.check_partials(compact_print=True)

        for comp in cpd:
            for (var, wrt) in cpd[comp]:
                np.testing.assert_almost_equal(actual=cpd[comp][var, wrt]['J_fwd'],
                                               desired=cpd[comp][var, wrt]['J_fd'],
                                               decimal=6)
Пример #29
0
    def test_vectorized_with_default_mult(self):
        """
        solve:  2 * x**2 = 4
        expected solution:  x=sqrt(2)
        """

        n = 100

        prob = Problem(model=Group())

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

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

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

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

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

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

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

        prob.model.linear_solver = DirectSolver()

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

        prob.model.jacobian = DenseJacobian()

        prob.setup()

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

        prob.run_model()

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

        np.set_printoptions(linewidth=1024)

        cpd = prob.check_partials()

        for (of, wrt) in cpd['balance']:
            assert_almost_equal(cpd['balance'][of, wrt]['abs error'], 0.0, decimal=5)
Пример #30
0
    def test_assert_check_partials_exception_expected(self):
        class MyComp(ExplicitComponent):
            def setup(self):
                self.add_input('x1', 3.0)
                self.add_input('x2', 5.0)

                self.add_output('y', 5.5)

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

            def compute(self, inputs, outputs):
                outputs['y'] = 3.0 * inputs['x1'] + 4.0 * inputs['x2']

            def compute_partials(self, inputs, partials):
                """Intentionally incorrect derivative."""
                J = partials
                J['y', 'x1'] = np.array([4.0])
                J['y', 'x2'] = np.array([40])

        prob = Problem()
        prob.model = MyComp()

        prob.set_solver_print(level=0)

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

        data = prob.check_partials(out_stream=None)

        atol = 1.e-6
        rtol = 1.e-6
        try:
            assert_check_partials(data, atol, rtol)
        except ValueError as err:
            err_string = str(err)
            self.assertEqual(err_string.count('Assert Check Partials failed for the following Components'), 1)
            self.assertEqual(err_string.count('1e-06'), 2)
            self.assertEqual(err_string.count('Component:'), 1)
            self.assertEqual(err_string.count('< output > wrt < variable >'), 1)
            self.assertEqual(err_string.count('norm'), 2)
            self.assertEqual(err_string.count('y wrt x1'), 4)
            self.assertEqual(err_string.count('y wrt x2'), 4)
            self.assertEqual(err_string.count('abs'), 6)
            self.assertEqual(err_string.count('rel'), 6)
            self.assertEqual(err_string.count('fwd-fd'), 4)
            self.assertEqual(err_string.count('rev-fd'), 4)
        else:
            self.fail('Exception expected.')
Пример #31
0
    def test_basic(self):
        """Test that output values and total derivatives are correct."""
        prob = Problem(model=UnitConvGroup())

        # Check the outputs after running to test the unit conversions
        prob.setup(check=False, mode='fwd')
        prob.run_model()

        assert_rel_error(self, prob['src.x2'], 100.0, 1e-6)
        assert_rel_error(self, prob['tgtF.x3'], 212.0, 1e-6)
        assert_rel_error(self, prob['tgtC.x3'], 100.0, 1e-6)
        assert_rel_error(self, prob['tgtK.x3'], 373.15, 1e-6)

        # Check the total derivatives in forward mode
        wrt = ['px1.x1']
        of = ['tgtF.x3', 'tgtC.x3', 'tgtK.x3']
        J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')

        assert_rel_error(self, J['tgtF.x3', 'px1.x1'][0][0], 1.8, 1e-6)
        assert_rel_error(self, J['tgtC.x3', 'px1.x1'][0][0], 1.0, 1e-6)
        assert_rel_error(self, J['tgtK.x3', 'px1.x1'][0][0], 1.0, 1e-6)

        # Check the total derivatives in reverse mode
        prob.setup(check=False, mode='rev')
        prob.run_model()
        J = prob.compute_totals(of=of, wrt=wrt, return_format='flat_dict')

        assert_rel_error(self, J['tgtF.x3', 'px1.x1'][0][0], 1.8, 1e-6)
        assert_rel_error(self, J['tgtC.x3', 'px1.x1'][0][0], 1.0, 1e-6)
        assert_rel_error(self, J['tgtK.x3', 'px1.x1'][0][0], 1.0, 1e-6)

        # Make sure check partials handles conversion
        data = prob.check_partials()

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-6)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-6)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-6)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-6)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-6)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-6)
Пример #32
0
    def test_create_on_init_add_constraint(self):
        prob = Problem()
        model = prob.model

        # find intersection of two non-parallel lines
        model.add_subsystem('indep', IndepVarComp('x', val=0.))
        model.add_subsystem('f', ExecComp('y=3*x-3', x=0.))
        model.add_subsystem('g', ExecComp('y=2.3*x+4', x=0.))
        model.add_subsystem('equal', EQConstraintComp('y',
                                                      add_constraint=True))

        model.connect('indep.x', 'f.x')
        model.connect('indep.x', 'g.x')

        model.connect('f.y', 'equal.lhs:y')
        model.connect('g.y', 'equal.rhs:y')

        model.add_design_var('indep.x', lower=0., upper=20.)
        model.add_objective('f.y')

        prob.setup(mode='fwd')

        # verify that the constraint has been added as requested
        self.assertTrue('equal.y' in model.get_constraints())

        prob.driver = ScipyOptimizeDriver(disp=False)

        prob.run_driver()

        assert_almost_equal(prob['equal.y'], 0.)
        assert_almost_equal(prob['indep.x'], 10.)
        assert_almost_equal(prob['f.y'], 27.)
        assert_almost_equal(prob['g.y'], 27.)

        cpd = prob.check_partials(out_stream=None)

        for (of, wrt) in cpd['equal']:
            assert_almost_equal(cpd['equal'][of, wrt]['abs error'],
                                0.0,
                                decimal=5)

        assert_check_partials(cpd, atol=1e-5, rtol=1e-5)
    def test_detailed(self):
        """ This is a longer version of the previous method, with plotting. """

        # Load in default lifting surfaces to setup the comparison
        surfaces = get_default_surfaces()

        # Instantiate an OpenMDAO problem and add the component we want to test
        # as asubsystem, giving that component a default lifting surface
        prob = Problem()
        prob.model.add_subsystem('tube',
                                 SectionPropertiesTube(surface=surfaces[0]))

        # Set up the problem and ensure it uses complex arrays so we can check
        # the derivatives using complex step
        prob.setup(force_alloc_complex=True)

        # Actually run the model, which is just a component in this case, then
        # check the derivatives and store the results in the `check` dict
        prob.run_model()
        check = prob.check_partials(compact_print=False)

        # Loop through this `check` dictionary and visualize the approximated
        # and computed derivatives
        for key, subjac in iteritems(check[list(check.keys())[0]]):
            print()
            print(key)
            print('Approximated derivative (either fd or cs):')
            view_mat(subjac['J_fd'])

            print('Computed derivative set by user:'******'J_fwd'])

        # Loop through the `check` dictionary and perform assert that the
        # approximated deriv must be very close to the computed deriv
        for key, subjac in iteritems(check[list(check.keys())[0]]):
            if subjac['magnitude'].fd > 1e-6:
                assert_almost_equal(subjac['rel error'].forward,
                                    0.,
                                    err_msg='deriv of %s wrt %s' % key)
                assert_almost_equal(subjac['rel error'].reverse,
                                    0.,
                                    err_msg='deriv of %s wrt %s' % key)
Пример #34
0
 def test_quadratic_three_phase_units_equal_dt_count_all(self):
     n_int_per_seg = self.num_intervals
     nn_tot = (n_int_per_seg*2 + 1)
     x1 = np.linspace(0, nn_tot-1, nn_tot)
     x2 = np.linspace(nn_tot-1, 2*(nn_tot-1), nn_tot)
     x3 = np.linspace(2*(nn_tot-1), 3*(nn_tot-1), nn_tot)
     x = np.concatenate([x1, x2, x3])
     fprime = 4 * x **2 - 8*x + 5
     f = 4 * x ** 3 / 3 - 8 * x ** 2 / 2 + 5*x
     prob = Problem(MultiPhaseIntegratorTestGroup(segment_names=['climb','cruise','descent'],
                                                  segments_to_count=['climb','cruise','descent'],
                                                  num_intervals=self.num_intervals, integrator=self.integrator,
                                                  quantity_units='kg', diff_units='s'))
     prob.setup(check=True, force_alloc_complex=True)
     prob['iv.rate_to_integrate'] = fprime
     prob.run_model()
     assert_rel_error(self, prob.get_val('integral.q', units='kg'), f, tolerance=1e-14)
     assert_rel_error(self, prob.get_val('integral.q_final', units='kg'), f[-1], tolerance=1e-14)
     partials = prob.check_partials(method='cs',compact_print=True)
     assert_check_partials(partials, atol=1e-8, rtol=1e0)
Пример #35
0
    def test_auto_names(self):
        num_nodes = self.num_nodes
        nn_tot = num_nodes
        x = np.linspace(0, nn_tot - 1, nn_tot)
        fprime = 4 * x**2 - 8 * x + 5
        f = 4 * x**3 / 3 - 8 * x**2 / 2 + 5 * x

        prob = Problem(
            IntegratorTestGroup(test_auto_names=True,
                                num_nodes=self.num_nodes,
                                integrator=self.integrator))
        prob.setup(check=True, force_alloc_complex=True)
        prob['iv.rate_to_integrate'] = fprime
        prob.run_model()
        assert_near_equal(prob['integral.q'], f, tolerance=1e-14)
        assert_near_equal(prob.get_val('integral.q_final', units=None),
                          f[-1],
                          tolerance=1e-14)
        partials = prob.check_partials(method='cs', compact_print=True)
        assert_check_partials(partials, atol=1e-8, rtol=1e0)
Пример #36
0
class GroundspeedsTestCase(unittest.TestCase):
    def setUp(self):
        self.prob = Problem(GroundspeedsTestGroup(num_nodes=15))
        self.prob.setup(check=True, force_alloc_complex=True)
        self.prob.run_model()

    def test_level_flight(self):
        assert_near_equal(self.prob['fltcond|groundspeed'][0],50,tolerance=1e-10)
        assert_near_equal(self.prob['fltcond|cosgamma'][0],1.,tolerance=1e-10)
        assert_near_equal(self.prob['fltcond|singamma'][0],0.,tolerance=1e-10)

    def test_climb_flight(self):
        gs = np.sqrt(50**2 - 3**2)
        assert_near_equal(self.prob['fltcond|groundspeed'][-1],gs,tolerance=1e-10)
        assert_near_equal(self.prob['fltcond|cosgamma'][-1],gs/50.,tolerance=1e-10)
        assert_near_equal(self.prob['fltcond|singamma'][-1],3./50.,tolerance=1e-10)

    def test_partials(self):
        partials = self.prob.check_partials(method='cs', out_stream=None)
        assert_check_partials(partials)
class ClimbAngleTestCase_Scalar(unittest.TestCase):
    def setUp(self):
        self.prob = Problem(ClimbAngleCompTestGroup(num_nodes=1))
        self.prob.setup(check=True, force_alloc_complex=True)
        self.prob.run_model()

    def test_level_flight(self):
        assert_rel_error(self, self.prob['gamma'][0], 0, tolerance=1e-10)

    def test_climb_flight(self):
        self.prob['thrust'] = np.ones((1, )) * 1200
        self.prob.run_model()
        assert_rel_error(self,
                         self.prob['gamma'][0],
                         np.arcsin(200 / 1000 / g),
                         tolerance=1e-10)

    def test_partials(self):
        partials = self.prob.check_partials(method='cs', out_stream=None)
        assert_check_partials(partials)
Пример #38
0
class ScalarAtmosTestCase(unittest.TestCase):
    def setUp(self):
        self.prob = Problem(AtmosTestGroup(num_nodes=1))
        self.prob.setup(check=True, force_alloc_complex=True)
        self.prob.run_model()

    def test_sea_level(self):
        assert_near_equal(self.prob['fltcond|rho'][0], 1.225, tolerance=1e-4)
        assert_near_equal(self.prob['fltcond|p'][0], 101325, tolerance=1e-3)
        assert_near_equal(self.prob['fltcond|T'][0], 288.15, tolerance=1e-3)
        assert_near_equal(self.prob['fltcond|Utrue'][0],
                          61.7333,
                          tolerance=1e-3)
        assert_near_equal(self.prob['fltcond|q'][0], 2334.2398, tolerance=1e-3)
        assert_near_equal(self.prob['fltcond|M'][0], 0.1814, tolerance=1e-3)
        assert_near_equal(self.prob['fltcond|a'][0], 340.294, tolerance=1e-3)

    def test_partials(self):
        partials = self.prob.check_partials(method='cs', out_stream=None)
        assert_check_partials(partials)
    def test_scalex(self):
        symmetry = False
        mesh = get_mesh(symmetry)

        prob = Problem()
        group = prob.model

        val = np.random.random(NY)

        comp = ScaleX(val=val, mesh_shape=mesh.shape)
        group.add_subsystem('comp', comp)

        prob.setup()

        prob['comp.in_mesh'] = mesh

        prob.run_model()

        check = prob.check_partials(compact_print=True, abs_err_tol=1e-5, rel_err_tol=1e-5)
        assert_check_partials(check, atol=1e-6, rtol=1e-6)
    def test_rk_state_advance_comp_rk4_vector(self):
        state_options = {'y': {'shape': (2, ), 'units': 'm'}}

        p = Problem(model=Group())

        ivc = p.model.add_subsystem('ivc',
                                    IndepVarComp(),
                                    promotes_outputs=['*'])

        ivc.add_output('k:y', shape=(2, 4, 2), units='m')
        ivc.add_output('y0', shape=(2, 2), units='m')

        p.model.add_subsystem(
            'c',
            RungeKuttaStateAdvanceComp(num_segments=2,
                                       method='RK4',
                                       state_options=state_options))

        p.model.connect('k:y', 'c.k:y')
        p.model.connect('y0', 'c.initial_states_per_seg:y')

        p.setup(check=True, force_alloc_complex=True)

        p['y0'] = [[0.5, 1.425130208333333],
                   [2.639602661132812, 4.006818970044454]]
        p['k:y'][0, :, 0] = [0.75, 0.90625, 0.9453125, 1.09765625]
        p['k:y'][0, :, 1] = [1.08756510, 1.20320638, 1.23211670, 1.32862345]
        p['k:y'][1, :, 0] = [1.31980133, 1.36850166, 1.38067675, 1.38513970]
        p['k:y'][1, :, 1] = [1.37840949, 1.31676186, 1.30134995, 1.15408446]

        p.run_model()

        assert_rel_error(test_case=self,
                         actual=p.get_val('c.final_states:y'),
                         desired=[[1.425130208333333, 2.639602661132812],
                                  [4.006818970044454, 5.301605229265987]],
                         tolerance=1.0E-9)

        np.set_printoptions(linewidth=1024)
        cpd = p.check_partials(method='cs', out_stream=None)
        assert_check_partials(cpd)
Пример #41
0
    def test_create_on_init(self):

        prob = Problem(model=Group())

        bal = BalanceComp('x', val=1.0)

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

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

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

        prob.setup()

        prob.run_model()

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

        # Assert that normalization is happening
        assert_almost_equal(prob.model.balance._scale_factor, 1.0 / np.abs(2))

        with printoptions(linewidth=1024):
            cpd = prob.check_partials()

            for (of, wrt) in cpd['balance']:
                assert_almost_equal(cpd['balance'][of, wrt]['abs error'],
                                    0.0,
                                    decimal=5)
Пример #42
0
class TestSplitMultipleSystems(unittest.TestCase):
    def setUp(self):
        self.nn = 5
        self.p = Problem(model=Group())
        ivc = IndepVarComp()
        ivc.add_output(name='input_to_split', shape=(self.nn * 2 + 2, 3))

        self.p.model.add_subsystem(name='ivc',
                                   subsys=ivc,
                                   promotes_outputs=['input_to_split'])

        splitter = self.p.model.add_subsystem(name='vector_split_comp',
                                              subsys=VectorSplitComp())
        splitter.add_relation(['output_a', 'output_b', 'output_c'],
                              'input_to_split',
                              vec_sizes=[self.nn, self.nn, 2],
                              length=3)

        self.p.model.connect('input_to_split',
                             'vector_split_comp.input_to_split')
        self.p.setup(force_alloc_complex=True)
        self.p['input_to_split'] = np.random.rand(self.nn * 2 + 2, 3)
        self.p.run_model()

    def test_results(self):
        input_to_split = self.p['input_to_split']
        out_a = self.p['vector_split_comp.output_a']
        out_b = self.p['vector_split_comp.output_b']
        out_c = self.p['vector_split_comp.output_c']

        expected_a = input_to_split[0:self.nn, :]
        expected_b = input_to_split[self.nn:2 * self.nn, :]
        expected_c = input_to_split[2 * self.nn:2 * self.nn + 2, :]

        assert_near_equal(out_a, expected_a, 1e-16)
        assert_near_equal(out_b, expected_b, 1e-16)
        assert_near_equal(out_c, expected_c, 1e-16)

    def test_partials(self):
        partials = self.p.check_partials(method='cs', out_stream=None)
        assert_check_partials(partials)
Пример #43
0
    def test_three_inputs(self):
        nn = 5
        p = Problem()
        p.model.add_subsystem('selector',
                              SelectorComp(num_nodes=nn,
                                           input_names=['A', 'B', 'C'],
                                           units='g'),
                              promotes=['*'])
        p.setup(check=True, force_alloc_complex=True)
        p.set_val('A', np.array([5.7, 2.3, -10., 2., 77.]), units='g')
        p.set_val('B', np.array([-1., -1., -1., -1., -2.]), units='kg')
        p.set_val('C', 42. * np.ones(nn), units='g')
        p.set_val('selector', np.array([0, 1, 2, 0, 2]))
        p.run_model()
        assert_near_equal(p['result'], np.array([5.7, -1000., 42., 2., 42.]))

        partials = p.check_partials(method='cs', compact_print=True)
        assert_check_partials(partials)

        p.set_val('A', 5. * np.ones(nn), units='g')
        p.set_val('B', 6. * np.ones(nn), units='g')
        p.set_val('C', 7. * np.ones(nn), units='g')
        p.set_val('selector', np.zeros(nn))
        p.run_model()
        assert_near_equal(p['result'], 5. * np.ones(nn))

        p.set_val('selector', np.ones(nn))
        p.run_model()
        assert_near_equal(p['result'], 6. * np.ones(nn))

        p.set_val('selector', 2. * np.ones(nn))
        p.run_model()
        assert_near_equal(p['result'], 7. * np.ones(nn))

        p.set_val('selector', np.array([-1, 1, 0, 2, 0]))
        with self.assertRaises(RuntimeWarning):
            p.run_model()

        p.set_val('selector', np.array([0, 1, -1, 2, 3]))
        with self.assertRaises(RuntimeWarning):
            p.run_model()
Пример #44
0
    def test_simple_explicit_apply(self):
        prob = Problem(Group())

        prob.model.add_subsystem('px', IndepVarComp('x', 1.0))
        prob.model.add_subsystem('py', IndepVarComp('y', 1.0))
        prob.model.add_subsystem('comp', ParaboloidApply())

        prob.model.connect('px.x', 'comp.x')
        prob.model.connect('py.y', 'comp.y')
        prob.model.linear_solver = ScipyGMRES()
        prob.set_solver_print(level=0)

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

        assert_rel_error(self, prob['comp.f_xy'], 27.0, 1e-6)

        J = prob.compute_totals(of=['comp.f_xy'], wrt=['px.x', 'py.y'])
        assert_rel_error(self, J[('comp.f_xy', 'px.x')][0][0], -3.0, 1e-5)
        assert_rel_error(self, J[('comp.f_xy', 'py.y')][0][0], 11.0, 1e-5)

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

        assert_rel_error(self, prob['comp.f_xy'], 27.0, 1e-6)

        J = prob.compute_totals(of=['comp.f_xy'], wrt=['px.x', 'py.y'])
        assert_rel_error(self, J[('comp.f_xy', 'px.x')][0][0], -3.0, 1e-5)
        assert_rel_error(self, J[('comp.f_xy', 'py.y')][0][0], 11.0, 1e-5)

        # Check partials
        data = prob.check_partials()

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)
Пример #45
0
    def test_renamed_vars(self):
        prob = Problem()
        model = prob.model

        # find intersection of two non-parallel lines, fx_y and gx_y
        equal = EQConstraintComp('y',
                                 lhs_name='fx_y',
                                 rhs_name='gx_y',
                                 add_constraint=True)

        model.add_subsystem('indep', IndepVarComp('x', val=0.))
        model.add_subsystem('f', ExecComp('y=3*x-3', x=0.))
        model.add_subsystem('g', ExecComp('y=2.3*x+4', x=0.))
        model.add_subsystem('equal', equal)

        model.connect('indep.x', 'f.x')
        model.connect('indep.x', 'g.x')

        model.connect('f.y', 'equal.fx_y')
        model.connect('g.y', 'equal.gx_y')

        model.add_design_var('indep.x', lower=0., upper=20.)
        model.add_objective('f.y')

        prob.setup(mode='fwd')
        prob.driver = ScipyOptimizeDriver(disp=False)
        prob.run_driver()

        assert_almost_equal(prob['equal.y'], 0.)
        assert_almost_equal(prob['indep.x'], 10.)
        assert_almost_equal(prob['f.y'], 27.)
        assert_almost_equal(prob['g.y'], 27.)

        cpd = prob.check_partials(out_stream=None)

        for (of, wrt) in cpd['equal']:
            assert_almost_equal(cpd['equal'][of, wrt]['abs error'],
                                0.0,
                                decimal=5)

        assert_check_partials(cpd, atol=1e-5, rtol=1e-5)
Пример #46
0
def run_test(test_obj, comp, complex_flag=False, compact_print=True, method='fd', step=1e-6, atol=1e-5, rtol=1e-5, view=False):
    prob = Problem()
    prob.model.add_subsystem('comp', comp)
    prob.setup(force_alloc_complex=complex_flag)

    prob.run_model()

    if method=='cs':
        step = 1e-40

    check = prob.check_partials(compact_print=compact_print, method=method, step=step)

    if view:
        # Loop through this `check` dictionary and visualize the approximated
        # and computed derivatives
        for key, subjac in iteritems(check[list(check.keys())[0]]):
            view_mat(subjac['J_fd'],subjac['J_fwd'],key)

    assert_check_partials(check, atol=atol, rtol=rtol)

    return prob
Пример #47
0
    def test_feature_assert_check_partials_exception_expected(self):
        import numpy as np
        from openmdao.api import ExplicitComponent, Problem
        from openmdao.utils.assert_utils import assert_check_partials

        class MyComp(ExplicitComponent):
            def setup(self):
                self.add_input('x1', 3.0)
                self.add_input('x2', 5.0)

                self.add_output('y', 5.5)

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

            def compute(self, inputs, outputs):
                """ Compute outputs. """
                outputs['y'] = 3.0 * inputs['x1'] + 4.0 * inputs['x2']

            def compute_partials(self, inputs, partials):
                """Intentionally incorrect derivative."""
                J = partials
                J['y', 'x1'] = np.array([4.0])
                J['y', 'x2'] = np.array([40])

        prob = Problem()
        prob.model = MyComp()

        prob.set_solver_print(level=0)

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

        data = prob.check_partials(out_stream=None)

        atol = 1.e-6
        rtol = 1.e-6
        try:
            assert_check_partials(data, atol, rtol)
        except ValueError as err:
            print(str(err))
Пример #48
0
class TestElementMultiplyDivideCompNx3(unittest.TestCase):
    def setUp(self):
        self.nn = 5

        self.p = Problem(model=Group())

        ivc = IndepVarComp()
        ivc.add_output(name='a', shape=(self.nn, 3))
        ivc.add_output(name='b', shape=(self.nn, 3))

        self.p.model.add_subsystem(name='ivc',
                                   subsys=ivc,
                                   promotes_outputs=['a', 'b'])

        multi = self.p.model.add_subsystem(name='multiply_divide_comp',
                                           subsys=ElementMultiplyDivideComp())
        multi.add_equation('multdiv_output', ['input_a', 'input_b'],
                           vec_size=self.nn,
                           length=3)

        self.p.model.connect('a', 'multiply_divide_comp.input_a')
        self.p.model.connect('b', 'multiply_divide_comp.input_b')

        self.p.setup()

        self.p['a'] = np.random.uniform(low=1, high=2, size=(self.nn, 3))
        self.p['b'] = np.random.uniform(low=1, high=2, size=(self.nn, 3))

        self.p.run_model()

    def test_results(self):
        a = self.p['a']
        b = self.p['b']
        out = self.p['multiply_divide_comp.multdiv_output']
        expected = a * b
        assert_near_equal(out, expected, 1e-16)

    def test_partials(self):
        partials = self.p.check_partials(method='fd', out_stream=None)
        assert_check_partials(partials)
Пример #49
0
class TestAddSubtractCompNx3(unittest.TestCase):
    def setUp(self):
        self.nn = 5

        self.p = Problem(model=Group())

        ivc = IndepVarComp()
        ivc.add_output(name='a', shape=(self.nn, 3))
        ivc.add_output(name='b', shape=(self.nn, 3))

        self.p.model.add_subsystem(name='ivc',
                                   subsys=ivc,
                                   promotes_outputs=['a', 'b'])

        adder = self.p.model.add_subsystem(name='add_subtract_comp',
                                           subsys=AddSubtractComp())
        adder.add_equation('adder_output', ['input_a', 'input_b'],
                           vec_size=self.nn,
                           length=3)

        self.p.model.connect('a', 'add_subtract_comp.input_a')
        self.p.model.connect('b', 'add_subtract_comp.input_b')

        self.p.setup()

        self.p['a'] = np.random.rand(self.nn, 3)
        self.p['b'] = np.random.rand(self.nn, 3)

        self.p.run_model()

    def test_results(self):
        a = self.p['a']
        b = self.p['b']
        out = self.p['add_subtract_comp.adder_output']
        expected = a + b
        assert_rel_error(self, out, expected, 1e-16)

    def test_partials(self):
        partials = self.p.check_partials(method='fd', out_stream=None)
        assert_check_partials(partials)
Пример #50
0
    def test_rhs_val(self):
        """ Test solution with a default RHS value and no connected RHS variable. """

        n = 1

        prob = Problem(model=Group())

        bal = BalanceComp('x', rhs_val=4.0)

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

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

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

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

        prob.model.linear_solver = DirectSolver()

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

        prob.model.jacobian = DenseJacobian()

        prob.setup()

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

        prob.run_model()

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

        np.set_printoptions(linewidth=1024)

        cpd = prob.check_partials()

        for (of, wrt) in cpd['balance']:
            assert_almost_equal(cpd['balance'][of, wrt]['abs error'], 0.0, decimal=5)
Пример #51
0
class TestSplitNx3Units(unittest.TestCase):
    def setUp(self):
        self.nn = 5
        self.p = Problem(model=Group())
        ivc = IndepVarComp()
        ivc.add_output(name='input_to_split',
                       shape=(self.nn * 2, 3),
                       units='m')

        self.p.model.add_subsystem(name='ivc',
                                   subsys=ivc,
                                   promotes_outputs=['input_to_split'])

        splitter = self.p.model.add_subsystem(name='vector_split_comp',
                                              subsys=VectorSplitComp())
        splitter.add_relation(['output_a', 'output_b'],
                              'input_to_split',
                              vec_sizes=[self.nn, self.nn],
                              length=3,
                              units='m')

        self.p.model.connect('input_to_split',
                             'vector_split_comp.input_to_split')
        self.p.setup()
        self.p['input_to_split'] = np.random.rand(self.nn * 2, 3)
        self.p.run_model()

    def test_results(self):
        input_to_split = self.p['input_to_split']
        out_a = self.p['vector_split_comp.output_a']
        out_b = self.p['vector_split_comp.output_b']

        expected_a = input_to_split[0:self.nn, :]
        expected_b = input_to_split[self.nn:2 * self.nn, :]
        assert_rel_error(self, out_a, expected_a, 1e-16)
        assert_rel_error(self, out_b, expected_b, 1e-16)

    def test_partials(self):
        partials = self.p.check_partials(method='fd', out_stream=None)
        assert_check_partials(partials)
Пример #52
0
 def test_nondefault_settings(self):
     prob = Problem(
         MotorTestGroup(
             vec_size=10,
             use_defaults=False,
             efficiency=0.95,
             weight_inc=1 / 3000,
             weight_base=2,
             cost_inc=1 / 500,
             cost_base=3,
         ))
     prob.setup(check=True, force_alloc_complex=True)
     prob.run_model()
     assert_rel_error(self,
                      prob.get_val('motor.shaft_power_out', units='kW'),
                      np.ones(10) * 90 * 0.95,
                      tolerance=1e-15)
     assert_rel_error(self,
                      prob.get_val('motor.elec_load', units='kW'),
                      np.ones(10) * 90,
                      tolerance=1e-15)
     assert_rel_error(self,
                      prob.get_val('motor.heat_out', units='kW'),
                      np.ones(10) * 90 * 0.05,
                      tolerance=1e-15)
     assert_rel_error(self,
                      prob.get_val('motor.component_sizing_margin'),
                      np.ones(10) * 0.90,
                      tolerance=1e-15)
     assert_rel_error(self,
                      prob.get_val('motor.component_cost', units='USD'),
                      203,
                      tolerance=1e-15)
     assert_rel_error(self,
                      prob.get_val('motor.component_weight', units='kg'),
                      35.333333333333333333,
                      tolerance=1e-10)
     partials = prob.check_partials(method='cs', compact_print=True)
     assert_check_partials(partials)
Пример #53
0
    def test_vectorized(self):
        nn = 5
        p = Problem()
        p.model = CFM56(num_nodes=nn)

        p.setup(force_alloc_complex=True)

        p.set_val('throttle', np.linspace(0.0001, 1., nn))
        p.set_val('fltcond|h', np.linspace(0, 40e3, nn), units='ft')
        p.set_val('fltcond|M', np.linspace(0.1, 0.9, nn))

        p.run_model()

        assert_near_equal(p.get_val('thrust', units='lbf'), np.array([1445.41349482, 3961.46624224,
                            5278.43191982, 5441.44404298, 6479.00525867]), tolerance=5e-3)
        assert_near_equal(p.get_val('fuel_flow', units='kg/s'), np.array([0.17032429, 0.25496437,
                            0.35745638, 0.40572545, 0.4924194]), tolerance=5e-3)
        assert_near_equal(p.get_val('T4', units='degK'), np.array([1005.38911171, 1207.57548728,
                            1381.94820904, 1508.07901676, 1665.37063872]), tolerance=5e-3)

        partials = p.check_partials(method='cs',compact_print=True)
        assert_check_partials(partials)
class TestVectorInitialAndFinalBoundaryValue(unittest.TestCase):

    def setUp(self):

        self.p = Problem(model=Group())

        ivp = self.p.model.add_subsystem('ivc', subsys=IndepVarComp(), promotes_outputs=['*'])

        ivp.add_output('pos', val=np.zeros((100, 3)))
        self.p.model.add_design_var('pos', lower=0, upper=100)

        bv_comp = self.p.model.add_subsystem('bv_comp', BoundaryConstraintComp())
        bv_comp._add_initial_constraint(name='pos', shape=(3,))
        bv_comp._add_final_constraint(name='pos', shape=(3,))

        src_idxs = np.array([[0, 1, 2],
                             [-3, -2, -1]])

        self.p.model.connect('pos', 'bv_comp.boundary_values:pos', src_indices=src_idxs,
                             flat_src_indices=True)

        self.p.setup(force_alloc_complex=True)

        self.p['pos'][:, 0] = np.arange(100)
        self.p['pos'][:, 1] = 100 + np.arange(100)
        self.p['pos'][:, 2] = 200 + np.arange(100)

        self.p.run_model()

    def test_results(self):

        assert_almost_equal(self.p['bv_comp.boundary_values:pos'][0, :], self.p['pos'][0, :])
        assert_almost_equal(self.p['bv_comp.boundary_values:pos'][1, :], self.p['pos'][-1, :])
        assert_almost_equal(self.p['bv_comp.initial_value:pos'], self.p['pos'][0, :])
        assert_almost_equal(self.p['bv_comp.final_value:pos'], self.p['pos'][-1, :])

    def test_partials(self):
        cpd = self.p.check_partials(compact_print=True, method='cs')
        assert_check_partials(cpd)
Пример #55
0
class TestConcatenateNx3(unittest.TestCase):
    def setUp(self):
        self.nn = 5
        self.length = 3
        self.p = Problem(model=Group())
        ivc = IndepVarComp()
        ivc.add_output(name='a', shape=(self.nn, self.length))
        ivc.add_output(name='b', shape=(self.nn, self.length))

        self.p.model.add_subsystem(name='ivc',
                                   subsys=ivc,
                                   promotes_outputs=['a', 'b'])

        combiner = self.p.model.add_subsystem(name='vector_concat_comp',
                                              subsys=VectorConcatenateComp())
        combiner.add_relation('concat_output', ['input_a', 'input_b'],
                              vec_sizes=[self.nn, self.nn],
                              length=self.length)

        self.p.model.connect('a', 'vector_concat_comp.input_a')
        self.p.model.connect('b', 'vector_concat_comp.input_b')

        self.p.setup(force_alloc_complex=False)

        self.p['a'] = np.random.rand(self.nn, self.length)
        self.p['b'] = np.random.rand(self.nn, self.length)

        self.p.run_model()

    def test_results(self):
        a = self.p['a']
        b = self.p['b']
        out = self.p['vector_concat_comp.concat_output']
        expected = np.concatenate((a, b))
        assert_near_equal(out, expected, 1e-16)

    def test_partials(self):
        partials = self.p.check_partials(method='fd', out_stream=None)
        assert_check_partials(partials)
Пример #56
0
    def run_partials_test(self):
        from openmdao.api import Problem

        ode_function = self.ode_function_class()
        initial_conditions, t0, t1 = ode_function.get_test_parameters()
        exact_solution = ode_function.get_exact_solution(initial_conditions, t0, t1)

        num = 10

        times = np.linspace(t0, t1, num)

        method_name = 'ImplicitMidpoint'
        formulation = 'solver-based'

        integrator = ODEIntegrator(ode_function, formulation, method_name,
            times=times, initial_conditions=initial_conditions,
        )

        prob = Problem(integrator)
        prob.setup()
        prob.run_model()

        jac = prob.check_partials(compact_print=True)
        for comp_name, jac_comp in iteritems(jac):
            for partial_name, jac_partial in iteritems(jac_comp):
                mag_fd = jac_partial['magnitude'].fd
                mag_fwd = jac_partial['magnitude'].forward
                mag_rev = jac_partial['magnitude'].reverse

                abs_fwd = jac_partial['abs error'].forward
                abs_rev = jac_partial['abs error'].reverse

                rel_fwd = jac_partial['rel error'].forward
                rel_rev = jac_partial['rel error'].reverse

                non_zero = np.max([mag_fd, mag_fwd, mag_rev]) > 1e-12
                if non_zero:
                    self.assertTrue(rel_fwd < 1e-3 or abs_fwd < 1e-3)
                    self.assertTrue(rel_rev < 1e-3 or abs_rev < 1e-3)
Пример #57
0
    def test_derivs_with_sideslip(self):
        surfaces = get_default_surfaces()

        # Use Tail since it is not symmetric.
        comp = LiftDrag(surface=surfaces[1])

        prob = Problem()
        prob.model.add_subsystem('comp', comp)
        prob.setup(force_alloc_complex=True)

        prob['comp.alpha'] = 3.0
        prob['comp.beta'] = 15.0
        prob['comp.sec_forces'] = 10.0 * np.random.random(
            prob['comp.sec_forces'].shape)

        prob.run_model()

        check = prob.check_partials(compact_print=True,
                                    method='cs',
                                    step=1e-40)

        assert_check_partials(check)
Пример #58
0
class TestSummationNx3AxisNone(unittest.TestCase):
    def setUp(self):
        self.nn = 5
        self.length = 3
        self.sf = -2
        self.p = Problem(model=Group())
        ivc = IndepVarComp()
        ivc.add_output(name='a', shape=(self.nn, self.length))

        self.p.model.add_subsystem(name='ivc',
                                   subsys=ivc,
                                   promotes_outputs=['a'])

        multi = self.p.model.add_subsystem(name='sum_comp',
                                           subsys=SumComp(axis=None))
        multi.add_equation('sum_output',
                           'sum_input',
                           vec_size=self.nn,
                           length=self.length,
                           scaling_factor=self.sf)

        self.p.model.connect('a', 'sum_comp.sum_input')

        self.p.setup(force_alloc_complex=True)

        self.p['a'] = np.random.rand(self.nn, self.length)

        self.p.run_model()

    def test_results(self):
        a = self.p['a']
        out = self.p['sum_comp.sum_output']
        expected = self.sf * np.sum(a, axis=None)
        expected = expected.reshape((1, ))
        assert_near_equal(out, expected, 1e-16)

    def test_partials(self):
        partials = self.p.check_partials(method='cs', out_stream=None)
        assert_check_partials(partials)
Пример #59
0
    def test_basic(self):
        xcp = np.array([1.0, 2.0, 4.0, 6.0, 10.0, 12.0])
        ycp = np.array([5.0, 12.0, 14.0, 16.0, 21.0, 29.0])
        ncp = len(xcp)
        n = 50
        x = np.linspace(1.0, 12.0, n)

        prob = Problem()

        comp = AkimaSplineComp(num_control_points=ncp, num_points=n,
                               name='chord', input_x=True, input_xcp=True)

        prob.model.add_subsystem('akima', comp)

        prob.setup(force_alloc_complex=True)

        prob['akima.chord:x_cp'] = xcp
        prob['akima.chord:y_cp'] = ycp.reshape((1, ncp))
        prob['akima.chord:x'] = x

        prob.run_model()

        y = np.array([[ 5.        ,  7.20902005,  9.21276849, 10.81097162, 11.80335574,
                        12.1278001 , 12.35869145, 12.58588536, 12.81022332, 13.03254681,
                        13.25369732, 13.47451633, 13.69584534, 13.91852582, 14.14281484,
                        14.36710105, 14.59128625, 14.81544619, 15.03965664, 15.26399335,
                        15.48853209, 15.7133486 , 15.93851866, 16.16573502, 16.39927111,
                        16.63928669, 16.8857123 , 17.1384785 , 17.39751585, 17.66275489,
                        17.93412619, 18.21156029, 18.49498776, 18.78433915, 19.07954501,
                        19.38053589, 19.68724235, 19.99959495, 20.31752423, 20.64096076,
                        20.96983509, 21.47630381, 22.33596028, 23.44002074, 24.67782685,
                        25.93872026, 27.11204263, 28.0871356 , 28.75334084, 29.        ]])


        assert_array_almost_equal(y, prob['akima.chord:y'])

        derivs = prob.check_partials(compact_print=True, method='cs')

        assert_check_partials(derivs, atol=1e-14, rtol=1e-14)
Пример #60
0
    def test_create_on_init_no_normalization(self):

        prob = Problem(model=Group())

        bal = BalanceComp('x', val=1.0, normalize=False)

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

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

        prob.model.linear_solver = DirectSolver()
        prob.model.nonlinear_solver = NewtonSolver(iprint=0)

        prob.setup()

        prob.run_model()

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

        assert_almost_equal(prob.model.balance._scale_factor, 1.0)

        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)