def test_linear_system(self):
        """Check against the scipy solver."""

        model = Group()

        x = np.array([1, 2, -3])
        A = np.array([[5.0, -3.0, 2.0], [1.0, 7.0, -4.0], [1.0, 0.0, 8.0]])
        b = A.dot(x)

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

        lingrp = model.add_subsystem('lingrp', Group(), promotes=['*'])
        lingrp.add_subsystem('lin', LinearSystemComp(size=3, partial_type="matrix_free"))

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

        prob = Problem(model)
        prob.setup()

        lingrp.linear_solver = ScipyKrylov()

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

        assert_rel_error(self, prob['lin.x'], x, .0001)
        assert_rel_error(self, prob.model._residuals.get_norm(), 0.0, 1e-10)
Example #2
0
    def test_includes_and_excludes(self):
        prob = Problem()
        prob.root = ConvergeDiverge()
        prob.driver.add_recorder(self.recorder)
        self.recorder.options['includes'] = ['comp1.*']
        self.recorder.options['excludes'] = ["*.y2"]
        self.recorder.options['record_params'] = True
        self.recorder.options['record_resids'] = True
        prob.setup(check=False)
        t0, t1 = run_problem(prob)
        prob.cleanup()  # closes recorders

        coordinate = [0, 'Driver', (1,)]

        expected_params = [
            ("comp1.x1", 2.0)
        ]
        expected_unknowns = [
            ("comp1.y1", 8.0)
        ]
        expected_resids = [
            ("comp1.y1", 0.0)
        ]

        self.assertIterationDataRecorded(((coordinate, (t0, t1), expected_params, expected_unknowns, expected_resids),), self.eps)
Example #3
0
    def test_only_unknowns_recorded(self):
        prob = Problem()
        prob.root = ConvergeDiverge()
        prob.driver.add_recorder(self.recorder)
        prob.setup(check=False)

        t0, t1 = run_problem(prob)
        prob.cleanup()  # closes recorders

        coordinate = [0, 'Driver', (1, )]

        expected_unknowns = [
            ("comp1.y1", 8.0),
            ("comp1.y2", 6.0),
            ("comp2.y1", 4.0),
            ("comp3.y1", 21.0),
            ("comp4.y1", 46.0),
            ("comp4.y2", -93.0),
            ("comp5.y1", 36.8),
            ("comp6.y1", -46.5),
            ("comp7.y1", -102.7),
            ("p.x", 2.0)
        ]

        self.assertIterationDataRecorded(((coordinate, (t0, t1), None, expected_unknowns, None),), self.eps)
    def test_fd_options_form_precedence(self):
        class MyComp(Component):
            def __init__(self):
                super(MyComp, self).__init__()

                # Params
                self.add_param("x1", 3.0)
                self.add_param("x2", 3.0, form="central")

                # Unknowns
                self.add_output("y", 5.5)

            def solve_nonlinear(self, params, unknowns, resids):
                """ Doesn't do much. """
                unknowns["y"] = 7.0 * params["x1"] ** 2 + 7.0 * params["x2"] ** 2

        prob = Problem()
        prob.root = Group()
        comp = prob.root.add("comp", MyComp())
        prob.root.add("p1", IndepVarComp([("x1", 3.0), ("x2", 3.0)]))
        prob.root.connect("p1.x1", "comp.x1")
        prob.root.connect("p1.x2", "comp.x2")

        comp.fd_options["force_fd"] = True
        comp.fd_options["form"] = "forward"

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

        J = prob.calc_gradient(["p1.x1", "p1.x2"], ["comp.y"], return_format="dict")
        x1_err = J["comp.y"]["p1.x1"] - 42.0
        x2_err = J["comp.y"]["p1.x2"] - 42.0

        assert_rel_error(self, x1_err, 7e-6, 1e-1)
        assert_rel_error(self, x2_err, 5.4e-10, 1e-1)
Example #5
0
    def test_only_params_recorded(self):
        prob = Problem()
        prob.root = ConvergeDiverge()
        prob.driver.add_recorder(self.recorder)
        self.recorder.options['record_params'] = True
        self.recorder.options['record_resids'] = False
        self.recorder.options['record_unknowns'] = False
        prob.setup(check=False)

        t0, t1 = run_problem(prob)
        prob.cleanup()  # closes recorders

        coordinate = [0, 'Driver', (1,)]
        expected_params = [
            ("comp1.x1", 2.0),
            ("comp2.x1", 8.0),
            ("comp3.x1", 6.0),
            ("comp4.x1", 4.0),
            ("comp4.x2", 21.0),
            ("comp5.x1", 46.0),
            ("comp6.x1", -93.0),
            ("comp7.x1", 36.8),
            ("comp7.x2", -46.5)
        ]

        self.assertIterationDataRecorded(((coordinate, (t0, t1), expected_params, None, None),), self.eps)
Example #6
0
    def test_simple(self):
        prob = Problem(Group(), impl=impl)

        size = 5
        A1 = prob.root.add('A1', IndepVarComp('a', np.zeros(size, float)))
        B1 = prob.root.add('B1', IndepVarComp('b', np.zeros(size, float)))
        B2 = prob.root.add('B2', IndepVarComp('b', np.zeros(size, float)))
        S1 = prob.root.add('S1', IndepVarComp('s', ''))
        L1 = prob.root.add('L1', IndepVarComp('l', []))

        C1 = prob.root.add('C1', ABCDArrayComp(size))
        C2 = prob.root.add('C2', ABCDArrayComp(size))

        prob.root.connect('A1.a', 'C1.a')
        prob.root.connect('B1.b', 'C1.b')
        # prob.root.connect('S1:s', 'C1.in_string')
        # prob.root.connect('L1:l', 'C1.in_list')

        prob.root.connect('C1.c', 'C2.a')
        prob.root.connect('B2.b', 'C2.b')
        # prob.root.connect('C1.out_string', 'C2.in_string')
        # prob.root.connect('C1.out_list',   'C2.in_list')

        prob.setup(check=False)

        prob['A1.a'] = np.ones(size, float) * 3.0
        prob['B1.b'] = np.ones(size, float) * 7.0
        prob['B2.b'] = np.ones(size, float) * 5.0

        prob.run()

        self.assertTrue(all(prob['C2.a'] == np.ones(size, float)*10.))
        self.assertTrue(all(prob['C2.b'] == np.ones(size, float)*5.))
        self.assertTrue(all(prob['C2.c'] == np.ones(size, float)*15.))
        self.assertTrue(all(prob['C2.d'] == np.ones(size, float)*5.))
Example #7
0
    def test_only_resids_recorded(self):
        prob = Problem()
        prob.root = ConvergeDiverge()
        prob.driver.add_recorder(self.recorder)
        self.recorder.options['record_params'] = False
        self.recorder.options['record_unknowns'] = False
        self.recorder.options['record_resids'] = True
        prob.setup(check=False)

        t0, t1 = run_problem(prob)
        prob.cleanup()  # closes recorders

        coordinate = [0, 'Driver', (1, )]

        expected_resids = [
            ("comp1.y1", 0.0),
            ("comp1.y2", 0.0),
            ("comp2.y1", 0.0),
            ("comp3.y1", 0.0),
            ("comp4.y1", 0.0),
            ("comp4.y2", 0.0),
            ("comp5.y1", 0.0),
            ("comp6.y1", 0.0),
            ("comp7.y1", 0.0),
            ("p.x", 0.0)
        ]

        self.assertIterationDataRecorded(((coordinate, (t0, t1), None, None, expected_resids),), self.eps)
Example #8
0
    def test_parallel_diamond(self):
        size = 3
        prob = Problem(Group(), impl=impl)
        root = prob.root
        root.add('P1', IndepVarComp('x', np.ones(size, float) * 1.1))
        G1 = root.add('G1', ParallelGroup())
        G1.add('C1', ABCDArrayComp(size))
        G1.add('C2', ABCDArrayComp(size))
        root.add('C3', ABCDArrayComp(size))

        root.connect('P1.x', 'G1.C1.a')
        root.connect('P1.x', 'G1.C2.b')
        root.connect('G1.C1.c', 'C3.a')
        root.connect('G1.C2.d', 'C3.b')

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

        if not MPI or self.comm.rank == 0:
            assert_rel_error(self, prob.root.G1.C1.unknowns['c'],
                             np.ones(size)*2.1, 1.e-10)
            assert_rel_error(self, prob.root.G1.C1.unknowns['d'],
                             np.ones(size)*.1, 1.e-10)
            assert_rel_error(self, prob.root.C3.params['a'],
                             np.ones(size)*2.1, 1.e-10)
            assert_rel_error(self, prob.root.C3.params['b'],
                             np.ones(size)*-.1, 1.e-10)

        if not MPI or self.comm.rank == 1:
            assert_rel_error(self, prob.root.G1.C2.unknowns['c'],
                             np.ones(size)*2.1, 1.e-10)
            assert_rel_error(self, prob.root.G1.C2.unknowns['d'],
                             np.ones(size)*-.1, 1.e-10)
Example #9
0
    def test_multiple_problems(self):
        if MPI:
            # split the comm and run an instance of the Problem in each subcomm
            subcomm = self.comm.Split(self.comm.rank)
            prob = Problem(Group(), impl=impl, comm=subcomm)

            size = 5
            value = self.comm.rank + 1
            values = np.ones(size)*value

            A1 = prob.root.add('A1', IndepVarComp('x', values))
            C1 = prob.root.add('C1', ABCDArrayComp(size))

            prob.root.connect('A1.x', 'C1.a')
            prob.root.connect('A1.x', 'C1.b')

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

            # check the first output array and store in result
            self.assertTrue(all(prob['C1.c'] == np.ones(size)*(value*2)))
            result = prob['C1.c']

            # gather the results from the separate processes/problems and check
            # for expected values
            results = self.comm.allgather(result)
            self.assertEqual(len(results), self.comm.size)

            for n in range(self.comm.size):
                expected = np.ones(size)*2*(n+1)
                self.assertTrue(all(results[n] == expected))
Example #10
0
    def test_parab_FD(self):

        model = Problem(impl=impl)
        root = model.root = Group()
        par = root.add('par', ParallelGroup())

        par.add('c1', Parab1D(root=2.0))
        par.add('c2', Parab1D(root=3.0))

        root.add('p1', IndepVarComp('x', val=0.0))
        root.add('p2', IndepVarComp('x', val=0.0))
        root.connect('p1.x', 'par.c1.x')
        root.connect('p2.x', 'par.c2.x')

        root.add('sumcomp', ExecComp('sum = x1+x2'))
        root.connect('par.c1.y', 'sumcomp.x1')
        root.connect('par.c2.y', 'sumcomp.x2')

        driver = model.driver = pyOptSparseDriver()
        driver.options['optimizer'] = OPTIMIZER
        driver.options['print_results'] = False
        driver.add_desvar('p1.x', lower=-100, upper=100)
        driver.add_desvar('p2.x', lower=-100, upper=100)
        driver.add_objective('sumcomp.sum')

        root.fd_options['force_fd'] = True

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

        if not MPI or self.comm.rank == 0:
            assert_rel_error(self, model['p1.x'], 2.0, 1.e-6)
            assert_rel_error(self, model['p2.x'], 3.0, 1.e-6)
Example #11
0
    def test_parab_subbed_Pcomps(self):

        model = Problem(impl=impl)
        root = model.root = Group()
        root.ln_solver = lin_solver()

        par = root.add('par', ParallelGroup())

        par.add('s1', MP_Point(root=2.0))
        par.add('s2', MP_Point(root=3.0))

        root.add('sumcomp', ExecComp('sum = x1+x2'))
        root.connect('par.s1.c.y', 'sumcomp.x1')
        root.connect('par.s2.c.y', 'sumcomp.x2')

        driver = model.driver = pyOptSparseDriver()
        driver.options['optimizer'] = OPTIMIZER
        driver.options['print_results'] = False
        driver.add_desvar('par.s1.p.x', lower=-100, upper=100)
        driver.add_desvar('par.s2.p.x', lower=-100, upper=100)
        driver.add_objective('sumcomp.sum')

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

        if not MPI or self.comm.rank == 0:
            assert_rel_error(self, model['par.s1.p.x'], 2.0, 1.e-6)

        if not MPI or self.comm.rank == 1:
            assert_rel_error(self, model['par.s2.p.x'], 3.0, 1.e-6)
Example #12
0
    def test_driver_records_unknown_types_metadata(self):

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

        # Need an optimization problem to test to make sure
        #   the is_desvar, is_con, is_obj metadata is being
        #   recorded for the Unknowns
        root.add('p1', IndepVarComp('x', 50.0))
        root.add('p2', IndepVarComp('y', 50.0))
        root.add('comp', Paraboloid())

        root.connect('p1.x', 'comp.x')
        root.connect('p2.y', 'comp.y')

        prob.driver = ScipyOptimizer()
        prob.driver.options['optimizer'] = 'SLSQP'
        prob.driver.add_desvar('p1.x', lower=-50.0, upper=50.0)
        prob.driver.add_desvar('p2.y', lower=-50.0, upper=50.0)

        prob.driver.add_objective('comp.f_xy')
        prob.driver.options['disp'] = False

        prob.driver.add_recorder(self.recorder)
        self.recorder.options['record_metadata'] = True
        prob.setup(check=False)
        prob.cleanup() # close recorders

        expected_params = list(iteritems(prob.root.params))
        expected_unknowns = list(iteritems(prob.root.unknowns))
        expected_resids = list(iteritems(prob.root.resids))

        self.assertMetadataRecorded((expected_params, expected_unknowns, expected_resids))
Example #13
0
    def test_root_derivs_array(self):
        prob = Problem()
        prob.root = SellarDerivativesGrouped()

        prob.driver = ScipyOptimizer()
        prob.driver.options['optimizer'] = 'SLSQP'
        prob.driver.options['tol'] = 1.0e-8
        prob.driver.options['disp'] = False

        prob.driver.add_desvar('z', lower=np.array([-10.0, 0.0]),
                             upper=np.array([10.0, 10.0]))
        prob.driver.add_desvar('x', lower=0.0, upper=10.0)

        prob.driver.add_objective('obj')
        prob.driver.add_constraint('con1', upper=0.0)
        prob.driver.add_constraint('con2', upper=0.0)

        prob.driver.add_recorder(self.recorder)
        self.recorder.options['record_metadata'] = False
        self.recorder.options['record_derivs'] = True
        prob.setup(check=False)

        prob.run()

        prob.cleanup()

        sout = open(self.filename)
        lines = sout.readlines()

        self.assertEqual(lines[12].rstrip(), 'Derivatives:')
        self.assertTrue('9.61' in lines[13])
        self.assertTrue('0.784' in lines[14])
        self.assertTrue('1.077' in lines[15])
    def test_alloc_jacobian(self):
        # Testing the helper function

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

        root.add('comp1', ExecComp(["y[0]=x[0]*2.0+x[1]*7.0",
                                    "y[1]=x[0]*5.0-x[1]*3.0+x[2]*1.5"],
                                    x=np.zeros(3), y=np.zeros(2)))
        root.add('comp2', SimpleImplicitComp())

        root.ln_solver.options['maxiter'] = 2
        p.setup(check=False)

        # Explciit
        J = root.comp1.alloc_jacobian()

        self.assertTrue(len(J) == 1)
        self.assertTrue(('y', 'x') in J)
        self.assertTrue(J[('y', 'x')].shape == (2,3))

        # Implicit
        J = root.comp2.alloc_jacobian()

        self.assertTrue(len(J) == 4)
        self.assertTrue(('y', 'x') in J)
        self.assertTrue(('y', 'z') in J)
        self.assertTrue(('z', 'x') in J)
        self.assertTrue(('z', 'z') in J)
        self.assertTrue(J[('y', 'x')].shape == (1, 1))
        self.assertTrue(J[('y', 'z')].shape == (1, 1))
        self.assertTrue(J[('z', 'x')].shape == (1, 1))
        self.assertTrue(J[('z', 'z')].shape == (1, 1))

        p.run()
Example #15
0
    def test_problem_deriv_test(self):

        prob = Problem()
        prob.root = Group()
        prob.root.add('comp', SimpleCompWrongDeriv())
        prob.root.add('p1', IndepVarComp('x', 2.0))
        prob.root.connect('p1.x', 'comp.x')

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

        data = prob.check_partial_derivatives(out_stream=None)

        # suppress printed output from problem_derivatives_check()
        sysout = sys.stdout
        devnull = open(os.devnull, 'w')

        try:
            sys.stdout = devnull
            problem_derivatives_check(self, prob)
        except AssertionError as err:
            sys.stdout = sysout
            self.assertIn("not less than or equal to 1e-05", err.args[0])
        finally:
            sys.stdout = sysout
Example #16
0
    def test_mult_conns(self):

        class SubGroup(Group):
            def setup(self):
                self.add_subsystem('c1', ExecComp('y = 2*x', x=np.ones(4), y=2*np.ones(4)),
                                   promotes=['y', 'x'])
                self.add_subsystem('c2', ExecComp('z = 2*y', y=np.ones(4), z=2*np.ones(4)),
                                   promotes=['z', 'y'])

        prob = Problem()
        indeps = prob.model.add_subsystem('indeps', IndepVarComp(), promotes=['*'])
        indeps.add_output('x', 10*np.ones(4))
        indeps.add_output('y', np.ones(4))

        prob.model.add_subsystem('sub', SubGroup())

        prob.model.connect('x', 'sub.x')
        prob.model.connect('y', 'sub.y')

        with self.assertRaises(Exception) as context:
            prob.setup()

        self.assertEqual(str(context.exception),
                         "The following inputs have multiple connections: "
                         "sub.c2.y from ['indeps.y', 'sub.c1.y']")
Example #17
0
    def test_calc_gradient_multiple_params(self):
        prob = Problem()
        prob.root = FanIn()
        prob.setup(check=False)
        prob.run()

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

        # check that calc_gradient returns proper dict value when mode is 'fwd'
        J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')
        assert_almost_equal(J['comp3.y']['p2.x2'], np.array([[35.]]))
        assert_almost_equal(J['comp3.y']['p1.x1'], np.array([[-6.]]))

        # check that calc_gradient returns proper array value when mode is 'fwd'
        J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='array')
        assert_almost_equal(J, np.array([[-6., 35.]]))

        # check that calc_gradient returns proper dict value when mode is 'rev'
        J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')
        assert_almost_equal(J['comp3.y']['p2.x2'], np.array([[35.]]))
        assert_almost_equal(J['comp3.y']['p1.x1'], np.array([[-6.]]))

        # check that calc_gradient returns proper array value when mode is 'rev'
        J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='array')
        assert_almost_equal(J, np.array([[-6., 35.]]))

        # check that calc_gradient returns proper dict value when mode is 'fd'
        J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='dict')
        assert_almost_equal(J['comp3.y']['p2.x2'], np.array([[35.]]))
        assert_almost_equal(J['comp3.y']['p1.x1'], np.array([[-6.]]))

        # check that calc_gradient returns proper array value when mode is 'fd'
        J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='array')
        assert_almost_equal(J, np.array([[-6., 35.]]))
Example #18
0
    def test_inp_inp_promoted_w_explicit_src(self):
        p = Problem(model=Group())
        root = p.model

        G1 = root.add_subsystem("G1", Group())
        G2 = G1.add_subsystem("G2", Group(), promotes=['x'])
        G2.add_subsystem("C1", ExecComp('y=x*2.0'))
        G2.add_subsystem("C2", IndepVarComp('x', 1.0), promotes=['x'])

        G3 = root.add_subsystem("G3", Group())
        G4 = G3.add_subsystem("G4", Group(), promotes=['x'])
        C3 = G4.add_subsystem("C3", ExecComp('y=x*2.0'), promotes=['x'])
        C4 = G4.add_subsystem("C4", ExecComp('y=x*2.0'), promotes=['x'])

        p.model.connect('G1.x', 'G3.x')
        p.setup(check=False)
        p.set_solver_print(level=0)

        # setting promoted name will set the value into the outputs, but will
        # not propagate it to the inputs. That will happen during run_model().
        p['G1.x'] = 999.

        p.run_model()
        self.assertEqual(C3._inputs['x'], 999.)
        self.assertEqual(C4._inputs['x'], 999.)
Example #19
0
    def test_unit_conv_message(self):
        raise unittest.SkipTest("no units yet")
        prob = Problem(model=Group())
        root = prob.model

        root.add_subsystem("C1", ExecComp('y=x*2.0', units={'x': 'ft'}), promotes=['x'])
        root.add_subsystem("C2", ExecComp('y=x*2.0', units={'x': 'inch'}), promotes=['x'])
        root.add_subsystem("C3", ExecComp('y=x*2.0', units={'x': 'm'}), promotes=['x'])

        try:
            prob.setup(check=False)
        except Exception as err:
            msg = "The following connected inputs are promoted to 'x', but have different units: " \
                  "[('C1.x', 'ft'), ('C2.x', 'inch'), ('C3.x', 'm')]. " \
                  "Connect 'x' to a source (such as an IndepVarComp) with defined units."
            self.assertTrue(msg in str(err))
        else:
            self.fail("Exception expected")

        # Remedy the problem with an Indepvarcomp

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

        root.add_subsystem("C1", ExecComp('y=x*2.0', units={'x': 'ft'}), promotes=['x'])
        root.add_subsystem("C2", ExecComp('y=x*2.0', units={'x': 'inch'}), promotes=['x'])
        root.add_subsystem("C3", ExecComp('y=x*2.0', units={'x': 'm'}), promotes=['x'])
        root.add_subsystem('p', IndepVarComp('x', 1.0, units='cm'), promotes=['x'])

        prob.setup(check=False)
    def test_fan_out_parallel_sets_fwd(self):

        prob = Problem(impl=impl)
        prob.root = FanOutGrouped()
        prob.root.ln_solver = LinearGaussSeidel()
        prob.root.sub.ln_solver = LinearGaussSeidel()

        prob.root.ln_solver.options['mode'] = 'fwd'
        prob.root.sub.ln_solver.options['mode'] = 'fwd'

        prob.driver.add_desvar('p.x')
        prob.driver.add_constraint('c2.y', upper=0.0)
        prob.driver.add_constraint('c3.y', upper=0.0)
        prob.driver.parallel_derivs(['c2.y', 'c3.y'])  # ignored in fwd

        if MPI:
            expected = [('c2.y', 'c3.y')]
        else:
            expected = [('c2.y',), ('c3.y',)]

        self.assertEqual(prob.driver.outputs_of_interest(),
                         expected)

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

        unknown_list = ['c2.y', 'c3.y']
        indep_list = ['p.x']

        J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')
        assert_rel_error(self, J['c2.y']['p.x'][0][0], -6.0, 1e-6)
        assert_rel_error(self, J['c3.y']['p.x'][0][0], 15.0, 1e-6)
    def test_fan_out_parallel_sets_rev(self):

        prob = Problem(impl=impl)
        prob.root = FanOutGrouped()
        prob.root.ln_solver = LinearGaussSeidel()
        prob.root.sub.ln_solver = LinearGaussSeidel()

        # need to set mode to rev before setup. Otherwise the sub-vectors
        # for the parallel set vars won't get allocated.
        prob.root.ln_solver.options['mode'] = 'rev'
        prob.root.sub.ln_solver.options['mode'] = 'rev'

        prob.driver.add_desvar('p.x')
        prob.driver.add_constraint('c2.y', upper=0.0)
        prob.driver.add_constraint('c3.y', upper=0.0)
        prob.driver.parallel_derivs(['c2.y', 'c3.y'])

        if MPI:
            expected = [('c2.y', 'c3.y')]
        else:
            expected = [('c2.y',), ('c3.y',)]

        self.assertEqual(prob.driver.outputs_of_interest(),
                         expected)

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

        unknown_list = ['c2.y', 'c3.y']
        indep_list = ['p.x']

        J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')
        assert_rel_error(self, J['c2.y']['p.x'][0][0], -6.0, 1e-6)
        assert_rel_error(self, J['c3.y']['p.x'][0][0], 15.0, 1e-6)
    def setUp(self):

        r0 = 10.0
        depth = 30.0
        G = 140e6
        nu = 0.4
        rigid = [False, False, False, False, False, False]

        prob = Problem()
        root = prob.root = Group()
        root.add('p1', IndepVarComp('r0', r0))
        root.add('p2', IndepVarComp('depth', depth))
        root.add('p', TowerSoil())

        root.connect('p1.r0', 'p.r0')
        root.connect('p2.depth', 'p.depth')

        prob.driver.add_objective('p.k', scaler=1E-6)

        prob.driver.add_desvar('p1.r0', lower=0, upper=1000, scaler=1E-6)
        prob.driver.add_desvar('p2.depth', lower=0, upper=1000, scaler=1E-6)

        prob.setup()

        prob['p.G'] = G
        prob['p.nu'] = nu
        prob['p.rigid'] = rigid

        prob.run()

        self.J = prob.check_total_derivatives(out_stream=None)

        print self.J
Example #23
0
    def test_too_few_procs(self):
        size = 3
        group = Group()
        group.add('P', IndepVarComp('x', numpy.ones(size)))
        group.add('C1', DistribExecComp(['y=2.0*x'], arr_size=size,
                                        x=numpy.zeros(size),
                                        y=numpy.zeros(size)))
        group.add('C2', ExecComp(['z=3.0*y'],
                                 y=numpy.zeros(size),
                                 z=numpy.zeros(size)))

        prob = Problem(impl=impl)
        prob.root = group
        prob.root.ln_solver = LinearGaussSeidel()
        prob.root.connect('P.x', 'C1.x')
        prob.root.connect('C1.y', 'C2.y')

        try:
            prob.setup(check=False)
        except Exception as err:
            self.assertEqual(str(err),
                             "This problem was given 1 MPI processes, "
                             "but it requires between 2 and 2.")
        else:
            if MPI:
                self.fail("Exception expected")
Example #24
0
    def test_pbo_desvar_slsqp_scipy(self):
        top = Problem()

        root = top.root = Group()

        root.add('p1', IndepVarComp('x', u'var_x', pass_by_obj=True))
        root.add('p2', IndepVarComp('y', -4.0))
        root.add('p', PassByObjParaboloid())

        root.connect('p1.x', 'p.x')
        root.connect('p2.y', 'p.y')

        top.driver = ScipyOptimizer()
        top.driver.options['optimizer'] = 'SLSQP'

        top.driver.add_desvar('p1.x')
        top.driver.add_desvar('p2.y')
        top.driver.add_objective('p.f_xy')

        try:
            top.setup(check=False)
        except Exception as err:
            self.assertEqual(str(err), "Parameter 'p1.x' is a 'pass_by_obj' variable and "
                             "can't be used with a gradient based driver of type 'SLSQP'.")
        else:
            self.fail("Exception expected")
Example #25
0
    def test_src_indices_error(self):
        size = 3
        group = Group()
        group.add('P', IndepVarComp('x', numpy.ones(size)))
        group.add('C1', DistribExecComp(['y=2.0*x'], arr_size=size,
                                        x=numpy.zeros(size),
                                        y=numpy.zeros(size)))
        group.add('C2', ExecComp(['z=3.0*y'],
                                 y=numpy.zeros(size),
                                 z=numpy.zeros(size)))

        prob = Problem(impl=impl)
        prob.root = group
        prob.root.ln_solver = LinearGaussSeidel()
        prob.root.connect('P.x', 'C1.x')
        prob.root.connect('C1.y', 'C2.y')

        prob.driver.add_desvar('P.x')
        prob.driver.add_objective('C1.y')

        try:
            prob.setup(check=False)
        except Exception as err:
            self.assertEqual(str(err), "'C1.y' is a distributed variable"
                                       " and may not be used as a design var,"
                                       " objective, or constraint.")
        else:
            if MPI:
                self.fail("Exception expected")
Example #26
0
    def test_file_diamond(self):
        # connect a source FileRef to two target FileRefs on
        # components running in parallel, and connect the outputs
        # of those components to a common sink component.  All filenames
        # are different, so files will actually be copied for each connection.
        if MPI:
            num = self.N_PROCS
        else:
            num = 1

        prob = Problem(Group(), impl=impl)

        src = prob.root.add("src", FileSrc('src'))
        par = prob.root.add('par', ParallelGroup())
        sink = prob.root.add("sink", FileSink('sink', num))

        for i in range(num):
            par.add("mid%d"%i, FileMid('mid%d'%i,'mid%d'%i))
            prob.root.connect('src.fout', 'par.mid%d.fin'%i)
            prob.root.connect('par.mid%d.fout'%i, 'sink.fin%d'%i)

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

        for i in range(num):
            with sink.params['fin%d'%i].open('r') as f:
                self.assertEqual(f.read(), "src\npar.mid%d\n"%i)
Example #27
0
    def test_specify_subgroup_solvers(self):
        from openmdao.api import Problem, NewtonSolver, ScipyKrylov, DirectSolver, NonlinearBlockGS, LinearBlockGS
        from openmdao.test_suite.components.double_sellar import DoubleSellar

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

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

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

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

        prob.setup()
        prob.run_model()

        assert_rel_error(self, prob['g1.y1'], 0.64, .00001)
        assert_rel_error(self, prob['g1.y2'], 0.80, .00001)
        assert_rel_error(self, prob['g2.y1'], 0.64, .00001)
        assert_rel_error(self, prob['g2.y2'], 0.80, .00001)
Example #28
0
    def test_two_simple(self):
        size = 3
        group = Group()
        group.add('P', IndepVarComp('x', numpy.ones(size)))
        group.add('C1', DistribExecComp(['y=2.0*x'], arr_size=size,
                                        x=numpy.zeros(size),
                                        y=numpy.zeros(size)))
        group.add('C2', ExecComp(['z=3.0*y'],
                                 y=numpy.zeros(size),
                                 z=numpy.zeros(size)))

        prob = Problem(impl=impl)
        prob.root = group
        prob.root.ln_solver = LinearGaussSeidel()
        prob.root.connect('P.x', 'C1.x')
        prob.root.connect('C1.y', 'C2.y')

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

        J = prob.calc_gradient(['P.x'], ['C2.z'], mode='fwd', return_format='dict')
        assert_rel_error(self, J['C2.z']['P.x'], numpy.eye(size)*6.0, 1e-6)

        J = prob.calc_gradient(['P.x'], ['C2.z'], mode='rev', return_format='dict')
        assert_rel_error(self, J['C2.z']['P.x'], numpy.eye(size)*6.0, 1e-6)
Example #29
0
    def test_basic(self):
        prob = Problem()
        model = prob.model

        n_cp = 80
        n_point = 160

        t = np.linspace(0, 3.0*np.pi, n_cp)
        x = np.sin(t)

        model.add_subsystem('px', IndepVarComp('x', val=x))
        model.add_subsystem('interp', BsplinesComp(num_control_points=n_cp,
                                                   num_points=n_point,
                                                   in_name='h_cp',
                                                   out_name='h',
                                                   distribution='uniform'))

        model.connect('px.x', 'interp.h_cp')

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

        xx = prob['interp.h'].flatten()
        tt = np.linspace(0, 3.0*np.pi, n_point)

        x_expected = np.sin(tt)
        delta = xx - x_expected

        # Here we test that we don't have crazy interpolation error.
        self.assertLess(max(delta), .15)
        # And that it gets middle points a little better.
        self.assertLess(max(delta[15:-15]), .06)
    def test_fan_in_parallel_sets_rev(self):

        prob = Problem(impl=impl)
        prob.root = FanInGrouped()
        prob.root.ln_solver = LinearGaussSeidel()
        prob.root.sub.ln_solver = LinearGaussSeidel()
        prob.root.ln_solver.options['mode'] = 'rev'
        prob.root.sub.ln_solver.options['mode'] = 'rev'

        prob.driver.add_desvar('p1.x1')
        prob.driver.add_desvar('p2.x2')
        prob.driver.add_desvar('p3.x3')
        prob.driver.add_objective('comp3.y')

        prob.driver.parallel_derivs(['p1.x1', 'p2.x2'])

        if MPI:
            expected = [('p1.x1', 'p2.x2'), ('p3.x3',)]
        else:
            expected = [('p1.x1',), ('p2.x2',), ('p3.x3',)]

        self.assertEqual(prob.driver.desvars_of_interest(),
                         expected)

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

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

        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)
Example #31
0
"""
This is not a real run_file. It is only used to make the n2
diagram for the notional aerostructural problem used for demonstration in the docs.
"""

from openmdao.api import Problem, Group, ExecComp, IndepVarComp, view_model, ImplicitComponent

p = Problem()
dvs = p.model.add_subsystem('design_vars', IndepVarComp(), promotes=['*'])
dvs.add_output('x_aero')
dvs.add_output('x_struct')
aerostruct = p.model.add_subsystem('aerostruct_cycle', Group(), promotes=['*'])
#note the equations don't matter... just need a simple way to get inputs and outputs there
aerostruct.add_subsystem(
    'aero',
    ExecComp(['w = u+x_aero', 'Cl=u+x_aero', 'Cd = u + x_aero']),
    promotes=['*'])
aerostruct.add_subsystem('struct',
                         ExecComp(['u = w+x_struct', 'mass=x_struct']),
                         promotes=['*'])

p.model.add_subsystem('objective', ExecComp('f=mass+Cl/Cd'), promotes=['*'])
p.model.add_subsystem('constraint', ExecComp('g=Cl'), promotes=['*'])

p.setup()

view_model(p,
           outfile='aerostruct_n2.html',
           embeddable=True,
           show_browser=False)
Example #32
0
pb.driver.options['run_parallel'] = options.parallel

case_recorder_filename = 'lanceur_prop_solide_without_trajectory_version2_doe.sqlite'        
recorder = SqliteRecorder(case_recorder_filename)
pb.driver.add_recorder(recorder)
pb.model.nonlinear_solver.options['err_on_non_converge'] = True


pb.model.add_design_var('Mnozzle', lower=-sys.float_info.max, upper=sys.float_info.max)


pb.model.add_objective('F_T')
pb.model.add_objective('Isp')
pb.model.add_objective('Lconv')
pb.model.add_objective('Ldiv')
pb.model.add_objective('Lfairing')
pb.model.add_objective('Linterstage')
pb.model.add_objective('Mavionics')
pb.model.add_objective('Mf')
pb.model.add_objective('Mfairing')
pb.model.add_objective('Mi')
pb.model.add_objective('Minterstage')
pb.model.add_objective('Mpad')
pb.model.add_objective('M_EPS')
pb.model.add_objective('M_PLA')
pb.model.add_objective('prop_m')

pb.setup()  
pb.run_driver()        

Example #33
0
class TestCADRE(unittest.TestCase):
    def setup(self, compname, inputs, state0):
        # create instance of component type
        try:
            comp = eval('%s(NTIME)' % compname)
        except TypeError:
            try:
                comp = eval('%s()' % compname)
            except TypeError:
                comp = eval('%s(NTIME, 300)' % compname)

        # collect metadata for component inputs
        prob = Problem(comp)
        prob.setup()
        prob.final_setup()

        self.inputs_dict = {}
        for name, meta in prob.model.list_inputs(units=True, out_stream=None):
            self.inputs_dict[name.split('.')[-1]] = meta

        # create independent vars for each input, initialized with random values
        indep = IndepVarComp()
        for item in inputs + state0:
            shape = self.inputs_dict[item]['value'].shape
            units = self.inputs_dict[item]['units']
            indep.add_output(item, np.random.random(shape), units=units)

        # setup problem for test
        self.prob = Problem()
        self.prob.model.add_subsystem('indep', indep, promotes=['*'])
        self.prob.model.add_subsystem('comp', comp, promotes=['*'])

        self.prob.setup()

    def compare_derivatives(self, var_in, var_out, rel_error=False):
        # check totals
        J = self.prob.check_totals(of=var_out, wrt=var_in, out_stream=None)

        for outp in var_out:
            for inp in var_in:
                Jn = J[outp, inp]['J_fd']
                Jf = J[outp, inp]['J_fwd']
                if rel_error:
                    diff = np.nan_to_num(abs(Jf - Jn) / Jn)
                else:
                    diff = abs(Jf - Jn)
                assert_rel_error(self, diff.max(), 0.0, 1e-3)

        # check partials
        # FIXME: several components fail check_partials
        #partials = self.prob.check_partials()
        partials = self.prob.check_partials(compact_print=True, method='cs')
        #partials = self.prob.check_partials(out_stream=None)
        # Only check relative
        assert_check_partials(partials, atol=np.inf, rtol=5e-3)

    def test_Attitude_Angular(self):
        compname = 'Attitude_Angular'
        inputs = ['O_BI', 'Odot_BI']
        outputs = ['w_B']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Attitude_AngularRates(self):
        compname = 'Attitude_AngularRates'
        inputs = ['w_B']
        outputs = ['wdot_B']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Attitude_Attitude(self):
        compname = 'Attitude_Attitude'
        inputs = ['r_e2b_I']
        outputs = ['O_RI']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Attitude_Roll(self):
        compname = 'Attitude_Roll'
        inputs = ['Gamma']
        outputs = ['O_BR']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Attitude_RotationMtx(self):
        compname = 'Attitude_RotationMtx'
        inputs = ['O_BR', 'O_RI']
        outputs = ['O_BI']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Attitude_RotationMtxRates(self):
        compname = 'Attitude_RotationMtxRates'
        inputs = ['O_BI']
        outputs = ['Odot_BI']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Attitude_Sideslip(self):
        compname = 'Attitude_Sideslip'
        inputs = ['r_e2b_I', 'O_BI']
        outputs = ['v_e2b_B']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Attitude_Torque(self):
        compname = 'Attitude_Torque'
        inputs = ['w_B', 'wdot_B']
        outputs = ['T_tot']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_BatterySOC(self):
        compname = 'BatterySOC'
        inputs = ['P_bat', 'temperature']
        outputs = ['SOC']
        state0 = ['iSOC']

        self.setup(compname, inputs, state0)
        self.prob.model.comp.h = 0.01
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_BatteryPower(self):
        compname = 'BatteryPower'
        inputs = ['SOC', 'temperature', 'P_bat']
        outputs = ['I_bat']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_BatteryConstraints(self):
        compname = 'BatteryConstraints'
        inputs = ['I_bat', 'SOC']
        outputs = ['ConCh', 'ConDs', 'ConS0', 'ConS1']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_BsplineParameters(self):
        compname = 'BsplineParameters'
        inputs = ['CP_P_comm', 'CP_gamma', 'CP_Isetpt']
        outputs = ['P_comm', 'Gamma', 'Isetpt']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Comm_DataDownloaded(self):
        compname = 'Comm_DataDownloaded'
        inputs = ['Dr']
        outputs = ['Data']
        state0 = ['Data0']

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Comm_AntRotation(self):
        compname = 'Comm_AntRotation'
        inputs = ['antAngle']
        outputs = ['q_A']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Comm_AntRotationMtx(self):
        compname = 'Comm_AntRotationMtx'
        inputs = ['q_A']
        outputs = ['O_AB']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Comm_BitRate(self):
        compname = 'Comm_BitRate'
        inputs = ['P_comm', 'gain', 'GSdist', 'CommLOS']
        outputs = ['Dr']
        state0 = []

        np.random.seed(1001)

        self.setup(compname, inputs, state0)

        # These need to be a certain magnitude so it doesn't blow up
        shape = self.inputs_dict['P_comm']['value'].shape
        self.prob['P_comm'] = np.ones(shape)
        shape = self.inputs_dict['GSdist']['value'].shape
        self.prob['GSdist'] = np.random.random(shape) * 1e3

        self.prob.run_model()

        self.compare_derivatives(inputs + state0, outputs)

    def test_Comm_Distance(self):
        compname = 'Comm_Distance'
        inputs = ['r_b2g_A']
        outputs = ['GSdist']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Comm_EarthsSpin(self):
        compname = 'Comm_EarthsSpin'
        inputs = ['t']
        outputs = ['q_E']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Comm_EarthsSpinMtx(self):
        compname = 'Comm_EarthsSpinMtx'
        inputs = ['q_E']
        outputs = ['O_IE']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Comm_GainPattern(self):
        compname = 'Comm_GainPattern'
        inputs = ['azimuthGS', 'elevationGS']
        outputs = ['gain']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Comm_GSposEarth(self):
        compname = 'Comm_GSposEarth'
        inputs = ['lon', 'lat', 'alt']
        outputs = ['r_e2g_E']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Comm_GSposECI(self):
        compname = 'Comm_GSposECI'
        inputs = ['O_IE', 'r_e2g_E']
        outputs = ['r_e2g_I']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Comm_LOS(self):
        compname = 'Comm_LOS'
        inputs = ['r_b2g_I', 'r_e2g_I']
        outputs = ['CommLOS']
        state0 = []

        self.setup(compname, inputs, state0)

        # needs to be negative to test not trivial branch.
        self.prob['r_e2g_I'] = -self.prob['r_e2g_I']

        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Comm_VectorAnt(self):
        compname = 'Comm_VectorAnt'
        inputs = ['r_b2g_B', 'O_AB']
        outputs = ['r_b2g_A']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Comm_VectorBody(self):
        compname = 'Comm_VectorBody'
        inputs = ['r_b2g_I', 'O_BI']
        outputs = ['r_b2g_B']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Comm_VectorECI(self):
        compname = 'Comm_VectorECI'
        inputs = ['r_e2g_I', 'r_e2b_I']
        outputs = ['r_b2g_I']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Comm_VectorSpherical(self):
        compname = 'Comm_VectorSpherical'
        inputs = ['r_b2g_A']
        outputs = ['azimuthGS', 'elevationGS']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Orbit_Dynamics(self):
        compname = 'Orbit_Dynamics'
        inputs = ['r_e2b_I0']
        outputs = ['r_e2b_I']
        state0 = []

        self.setup(compname, inputs, state0)

        self.prob.model.comp.h = 0.01
        self.prob['r_e2b_I0'][:3] = np.random.random((3)) * 1e6
        self.prob['r_e2b_I0'][3:] = np.random.random((3)) * 1e5

        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Orbit_Initial(self):
        compname = 'Orbit_Initial'
        inputs = [
            'altPerigee', 'altApogee', 'RAAN', 'Inc', 'argPerigee',
            'trueAnomaly'
        ]
        outputs = ['r_e2b_I0']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Power_CellVoltage(self):
        compname = 'Power_CellVoltage'
        inputs = ['LOS', 'temperature', 'exposedArea', 'Isetpt']
        outputs = ['V_sol']
        state0 = []

        self.setup(compname, inputs, state0)

        shape = self.inputs_dict['temperature']['value'].shape
        self.prob['temperature'] = np.random.random(shape) * 40 + 240

        shape = self.inputs_dict['exposedArea']['value'].shape
        self.prob['exposedArea'] = np.random.random(shape) * 1e-4

        shape = self.inputs_dict['Isetpt']['value'].shape
        self.prob['Isetpt'] = np.random.random(shape) * 1e-2

        self.prob.run_model()
        self.compare_derivatives(inputs, outputs, rel_error=True)

    def test_Power_SolarPower(self):
        compname = 'Power_SolarPower'
        inputs = ['V_sol', 'Isetpt']
        outputs = ['P_sol']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Power_Total(self):
        compname = 'Power_Total'
        inputs = ['P_sol', 'P_comm', 'P_RW']
        outputs = ['P_bat']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_ReactionWheel_Motor(self):
        compname = 'ReactionWheel_Motor'
        inputs = ['T_RW', 'w_B', 'w_RW']
        outputs = ['T_m']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_ReactionWheel_Power(self):
        compname = 'ReactionWheel_Power'
        inputs = ['w_RW', 'T_RW']
        outputs = ['P_RW']
        state0 = []

        np.random.seed(1001)

        self.setup(compname, inputs, state0)

        self.prob['T_RW'] = np.random.random(self.prob['T_RW'].shape) * 1e-1
        self.prob['w_RW'] = np.random.random(self.prob['w_RW'].shape) * 1e-1

        self.prob.run_model()
        self.compare_derivatives(inputs, outputs, rel_error=True)

    def test_ReactionWheel_Torque(self):
        compname = 'ReactionWheel_Torque'
        inputs = ['T_tot']
        outputs = ['T_RW']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_ReactionWheel_Dynamics(self):
        compname = 'ReactionWheel_Dynamics'
        inputs = ['w_B', 'T_RW']
        outputs = ['w_RW']

        # keep these at zeros
        state0 = []  # ['w_RW0']

        self.setup(compname, inputs, state0)
        self.prob.model.comp.h = 0.01

        shape = self.inputs_dict['w_B']['value'].shape
        self.prob['w_B'] = np.random.random(shape) * 1e-4
        shape = self.inputs_dict['T_RW']['value'].shape
        self.prob['T_RW'] = np.random.random(shape) * 1e-9

        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Solar_ExposedArea(self):
        compname = 'Solar_ExposedArea'
        inputs = ['finAngle', 'azimuth', 'elevation']
        outputs = ['exposedArea']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Sun_LOS(self):
        np.random.seed(1001)

        compname = 'Sun_LOS'
        inputs = ['r_e2b_I', 'r_e2s_I']
        outputs = ['LOS']
        state0 = []

        self.setup(compname, inputs, state0)

        # needs to be negative to test not trivial branch.
        self.prob['r_e2s_I'] -= 5800
        self.prob['r_e2b_I'] += 5800

        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Sun_PositionBody(self):
        compname = 'Sun_PositionBody'
        inputs = ['O_BI', 'r_e2s_I']
        outputs = ['r_e2s_B']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Sun_PositionECI(self):
        compname = 'Sun_PositionECI'
        inputs = ['t', 'LD']
        outputs = ['r_e2s_I']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_Sun_PositionSpherical(self):
        compname = 'Sun_PositionSpherical'
        inputs = ['r_e2s_B']
        outputs = ['azimuth', 'elevation']
        state0 = []

        self.setup(compname, inputs, state0)
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)

    def test_ThermalTemperature(self):
        compname = 'ThermalTemperature'
        inputs = ['exposedArea', 'cellInstd', 'LOS', 'P_comm']
        outputs = ['temperature']
        state0 = ['T0']

        self.setup(compname, inputs, state0)
        self.prob.model.comp.h = 0.01
        self.prob.run_model()
        self.compare_derivatives(inputs + state0, outputs)
Example #34
0
if __name__ == '__main__':
    top = Problem()
    root = top.root = Group()

    params = (('M_pod', .8), ('gam', 1.4))

    root.add('input_vars', IndepVarComp(params))
    root.add('p', PodMach())

    root.connect('input_vars.M_pod', 'p.M_pod')
    root.connect('input_vars.gam', 'p.gam')

    root.deriv_options['type'] = 'fd'
    root.deriv_options['form'] = 'central'
    root.deriv_options['step_size'] = 1.0e-8

    top.setup()

    top.run()

    print('\n')
    print('Pod Mach number is %f' % top['p.M_pod'])
    print('Area of the tube is %f m^2' % top['p.A_tube'])
    print('Compressor power is %f W' % top['p.pwr_comp'])
    print('Area of the inlet is %f m^2' % top['p.A_inlet'])
    print('Area after diffuser is %f m^2' % top['p.A_diff'])
    print('Bypass area is %f m^2' % top['p.A_bypass'])
    print('Effective duct area is %f m^2' % top['p.A_duct_eff'])
    print('Reynolds number is %f' % top['p.Re'])
Example #35
0
    class AddedTurbModel1(AbstractWakeAddedTurbulence):
        def compute(self, inputs, outputs):
            TI_amb = inputs['TI_amb']
            ct = inputs['ct']
            u_inf = inputs['u_inf']
            d = inputs['d']

            outputs['TI_eff'] = TI_amb * ct + u_inf / d

    model = Group()
    ivc = IndepVarComp()

    ivc.add_output('TI_amb', 0.12)
    ivc.add_output('ct', 0.6)
    ivc.add_output('u_inf', 8.0)
    ivc.add_output('d', 460.0)

    model.add_subsystem('indep', ivc)
    model.add_subsystem('added1', AddedTurbModel1())

    model.connect('indep.TI_amb', 'added1.TI_amb')
    model.connect('indep.ct', 'added1.ct')
    model.connect('indep.u_inf', 'added1.u_inf')
    model.connect('indep.d', 'added1.d')

    prob = Problem(model)
    prob.setup()
    prob.run_model()
    print(prob['added1.TI_eff'])
Example #36
0
    def test_apply_linear_adjoint(self):
        # Make sure we can index into dparams

        class Attitude_Angular(Component):
            """ Calculates angular velocity vector from the satellite's orientation
            matrix and its derivative.
            """

            def __init__(self, n=2):
                super(Attitude_Angular, self).__init__()

                self.n = n

                # Inputs
                self.add_param('O_BI', np.zeros((3, 3, n)), units="ft",
                               desc="Rotation matrix from body-fixed frame to Earth-centered "
                               "inertial frame over time")

                self.add_param('Odot_BI', np.zeros((3, 3, n)), units="km",
                               desc="First derivative of O_BI over time")

                # Outputs
                self.add_output('w_B', np.zeros((3, n)), units="1/s",
                                desc="Angular velocity vector in body-fixed frame over time")

                self.dw_dOdot = np.zeros((n, 3, 3, 3))
                self.dw_dO = np.zeros((n, 3, 3, 3))

            def solve_nonlinear(self, params, unknowns, resids):
                """ Calculate output. """

                O_BI = params['O_BI']
                Odot_BI = params['Odot_BI']
                w_B = unknowns['w_B']

                for i in range(0, self.n):
                    w_B[0, i] = np.dot(Odot_BI[2, :, i], O_BI[1, :, i])
                    w_B[1, i] = np.dot(Odot_BI[0, :, i], O_BI[2, :, i])
                    w_B[2, i] = np.dot(Odot_BI[1, :, i], O_BI[0, :, i])

            def linearize(self, params, unknowns, resids):
                """ Calculate and save derivatives. (i.e., Jacobian) """

                O_BI = params['O_BI']
                Odot_BI = params['Odot_BI']

                for i in range(0, self.n):
                    self.dw_dOdot[i, 0, 2, :] = O_BI[1, :, i]
                    self.dw_dO[i, 0, 1, :] = Odot_BI[2, :, i]

                    self.dw_dOdot[i, 1, 0, :] = O_BI[2, :, i]
                    self.dw_dO[i, 1, 2, :] = Odot_BI[0, :, i]

                    self.dw_dOdot[i, 2, 1, :] = O_BI[0, :, i]
                    self.dw_dO[i, 2, 0, :] = Odot_BI[1, :, i]

            def apply_linear(self, params, unknowns, dparams, dunknowns, dresids, mode):
                """ Matrix-vector product with the Jacobian. """

                dw_B = dresids['w_B']

                if mode == 'fwd':
                    for k in range(3):
                        for i in range(3):
                            for j in range(3):
                                if 'O_BI' in dparams:
                                    dw_B[k, :] += self.dw_dO[:, k, i, j] * \
                                        dparams['O_BI'][i, j, :]
                                if 'Odot_BI' in dparams:
                                    dw_B[k, :] += self.dw_dOdot[:, k, i, j] * \
                                        dparams['Odot_BI'][i, j, :]

                else:

                    for k in range(3):
                        for i in range(3):
                            for j in range(3):

                                if 'O_BI' in dparams:
                                    dparams['O_BI'][i, j, :] += self.dw_dO[:, k, i, j] * \
                                        dw_B[k, :]

                                if 'Odot_BI' in dparams:
                                    dparams['Odot_BI'][i, j, :] -= -self.dw_dOdot[:, k, i, j] * \
                                        dw_B[k, :]

        prob = Problem()
        root = prob.root = Group()
        prob.root.add('comp', Attitude_Angular(n=5), promotes=['*'])
        prob.root.add('p1', IndepVarComp('O_BI', np.ones((3, 3, 5))), promotes=['*'])
        prob.root.add('p2', IndepVarComp('Odot_BI', np.ones((3, 3, 5))), promotes=['*'])

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

        indep_list = ['O_BI', 'Odot_BI']
        unknown_list = ['w_B']
        Jf = prob.calc_gradient(indep_list, unknown_list, mode='fwd',
                                return_format='dict')

        indep_list = ['O_BI', 'Odot_BI']
        unknown_list = ['w_B']
        Jr = prob.calc_gradient(indep_list, unknown_list, mode='rev',
                                return_format='dict')

        for key, val in iteritems(Jr):
            for key2 in val:
                diff = abs(Jf[key][key2] - Jr[key][key2])
                assert_rel_error(self, diff, 0.0, 1e-10)
Example #37
0
    def test_basic(self):

        prob = Problem()
        prob.root = Group()
        prob.root.add('src', SrcComp())
        prob.root.add('tgtF', TgtCompF())
        prob.root.add('tgtC', TgtCompC())
        prob.root.add('tgtK', TgtCompK())
        prob.root.add('px1', IndepVarComp('x1', 100.0), promotes=['x1'])
        prob.root.connect('x1', 'src.x1')
        prob.root.connect('src.x2', 'tgtF.x2')
        prob.root.connect('src.x2', 'tgtC.x2')
        prob.root.connect('src.x2', 'tgtK.x2')

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

        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)

        # Make sure we don't convert equal units
        self.assertEqual(prob.root.params.metadata('tgtC.x2').get('unit_conv'),
                         None)

        indep_list = ['x1']
        unknown_list = ['tgtF.x3', 'tgtC.x3', 'tgtK.x3']
        J = prob.calc_gradient(indep_list, unknown_list, mode='fwd',
                               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)

        J = prob.calc_gradient(indep_list, unknown_list, mode='rev',
                               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)

        J = prob.calc_gradient(indep_list, unknown_list, mode='fd',
                               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)

        # Need to clean up after FD gradient call, so just rerun.
        prob.run()

        # Make sure check partials handles conversion
        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-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)

        stream = cStringIO()
        conv = prob.root.list_unit_conv(stream=stream)
        self.assertTrue((('src.x2', 'tgtF.x2'), ('degC', 'degF')) in conv)
        self.assertTrue((('src.x2', 'tgtK.x2'), ('degC', 'degK')) in conv)
Example #38
0
def struct(loads, params):

    # Unpack variables
    mesh = params.get('mesh')
    num_x = params.get('num_x')
    num_y = params.get('num_y')
    span = params.get('span')
    twist_cp = params.get('twist_cp')
    thickness_cp = params.get('thickness_cp')
    v = params.get('v')
    alpha = params.get('alpha')
    rho = params.get('rho')
    r = params.get('r')
    t = params.get('t')
    aero_ind = params.get('aero_ind')
    fem_ind = params.get('fem_ind')
    num_thickness = params.get('num_thickness')
    num_twist = params.get('num_twist')
    sweep = params.get('sweep')
    taper = params.get('taper')
    disp = params.get('disp')
    dihedral = params.get('dihedral')
    E = params.get('E')
    G = params.get('G')
    stress = params.get('stress')
    mrho = params.get('mrho')
    tot_n_fem = params.get('tot_n_fem')
    num_surf = params.get('num_surf')
    jac_twist = params.get('jac_twist')
    jac_thickness = params.get('jac_thickness')
    check = params.get('check')
    out_stream = params.get('out_stream')

    # Define the design variables
    des_vars = [
        ('twist_cp', twist_cp),
        ('thickness_cp', thickness_cp),
        ('r', r),
        # ('dihedral', dihedral),
        # ('sweep', sweep),
        # ('span', span),
        # ('taper', taper),
        # ('v', v),
        # ('alpha', alpha),
        # ('rho', rho),
        # ('disp', disp),
        ('loads', loads)
    ]

    root = Group()

    root.add(
        'des_vars',
        IndepVarComp(des_vars),
        #  promotes=['thickness_cp','r','loads'])
        promotes=['*'])
    # root.add('twist_bsp',  # What is this doing?
    #          Bspline('twist_cp', 'twist', jac_twist),
    #          promotes=['*'])
    root.add('twist_bsp',
             Bspline('twist_cp', 'twist', jac_twist),
             promotes=['*'])
    root.add(
        'thickness_bsp',  # What is this doing?
        Bspline('thickness_cp', 'thickness', jac_thickness),
        #  promotes=['thickness'])
        promotes=['*'])
    root.add('mesh', GeometryMesh(mesh, aero_ind), promotes=['*'])
    root.add(
        'tube',
        MaterialsTube(fem_ind),
        #  promotes=['r','thickness','A','Iy','Iz','J'])
        promotes=['*'])
    root.add(
        'spatialbeamstates',
        SpatialBeamStates(aero_ind, fem_ind, E, G),
        #  promotes=[
        #     'mesh', # ComputeNodes
        #     'A','Iy','Iz','J','loads', # SpatialBeamFEM
        #     'disp' # SpatialBeamDisp
        #  ])
        promotes=['*'])
    root.add(
        'transferdisp',
        TransferDisplacements(aero_ind, fem_ind),
        #  promotes=['mesh','disp','def_mesh'])
        promotes=['*'])

    prob = Problem()
    prob.root = root
    prob.setup(check=check, out_stream=out_stream)
    prob.run()

    return prob['def_mesh']  # Output the def_mesh matrix
    def test(self):

        # Create a dictionary to store options about the surface
        mesh_dict = {
            'num_y': 11,
            'num_x': 3,
            'wing_type': 'CRM',
            'symmetry': False,
            'num_twist_cp': 5
        }

        mesh, twist_cp = generate_mesh(mesh_dict)

        surf_dict = {
            # Wing definition
            'name': 'wing',  # name of the surface
            'type': 'aero',
            'symmetry': False,  # if true, model one half of wing
            # reflected across the plane y = 0
            'S_ref_type': 'wetted',  # how we compute the wing area,
            # can be 'wetted' or 'projected'
            'mesh': mesh,
            'num_x': mesh.shape[0],
            'num_y': mesh.shape[1],
            'twist_cp': twist_cp,

            # Aerodynamic performance of the lifting surface at
            # an angle of attack of 0 (alpha=0).
            # These CL0 and CD0 values are added to the CL and CD
            # obtained from aerodynamic analysis of the surface to get
            # the total CL and CD.
            # These CL0 and CD0 values do not vary wrt alpha.
            'CL0': 0.0,  # CL of the surface at alpha=0
            'CD0': 0.0,  # CD of the surface at alpha=0

            # Airfoil properties for viscous drag calculation
            'k_lam': 0.05,  # percentage of chord with laminar
            # flow, used for viscous drag
            't_over_c_cp':
            np.array([0.15]),  # thickness over chord ratio (NACA0015)
            'c_max_t': .303,  # chordwise location of maximum (NACA0015)
            # thickness
            'with_viscous': True,  # if true, compute viscous drag
            'with_wave': True,  # if true, compute wave drag
        }

        surfaces = [surf_dict]

        # Create the problem and the model group
        prob = Problem()

        indep_var_comp = IndepVarComp()
        indep_var_comp.add_output('v', val=248.136, units='m/s')
        indep_var_comp.add_output('alpha', val=5., units='deg')
        indep_var_comp.add_output('M', val=0.84)
        indep_var_comp.add_output('re', val=1.e6, units='1/m')
        indep_var_comp.add_output('rho', val=0.38, units='kg/m**3')
        indep_var_comp.add_output('cg', val=np.zeros((3)), units='m')

        prob.model.add_subsystem('prob_vars', indep_var_comp, promotes=['*'])

        # Loop over each surface in the surfaces list
        for surface in surfaces:

            geom_group = Geometry(surface=surface)

            # Add tmp_group to the problem as the name of the surface.
            # Note that is a group and performance group for each
            # individual surface.
            prob.model.add_subsystem(surface['name'], geom_group)

        # Loop through and add a certain number of aero points
        for i in range(1):

            # Create the aero point group and add it to the model
            aero_group = AeroPoint(surfaces=surfaces)
            point_name = 'aero_point_{}'.format(i)
            prob.model.add_subsystem(point_name, aero_group)

            # Connect flow properties to the analysis point
            prob.model.connect('v', point_name + '.v')
            prob.model.connect('alpha', point_name + '.alpha')
            prob.model.connect('M', point_name + '.M')
            prob.model.connect('re', point_name + '.re')
            prob.model.connect('rho', point_name + '.rho')
            prob.model.connect('cg', point_name + '.cg')

            # Connect the parameters within the model for each aero point
            for surface in surfaces:

                name = surface['name']

                # Connect the mesh from the geometry component to the analysis point
                prob.model.connect(name + '.mesh',
                                   point_name + '.' + name + '.def_mesh')

                # Perform the connections with the modified names within the
                # 'aero_states' group.
                prob.model.connect(
                    name + '.mesh',
                    point_name + '.aero_states.' + name + '_def_mesh')

                prob.model.connect(
                    name + '.t_over_c',
                    point_name + '.' + name + '_perf.' + 't_over_c')

        from openmdao.api import ScipyOptimizeDriver
        prob.driver = ScipyOptimizeDriver()
        prob.driver.options['tol'] = 1e-9

        recorder = SqliteRecorder("aero_opt_wavedrag.db")
        prob.driver.add_recorder(recorder)
        prob.driver.recording_options['record_derivatives'] = True

        # Setup problem and add design variables, constraint, and objective
        prob.model.add_design_var('wing.twist_cp', lower=-10., upper=15.)
        prob.model.add_constraint(point_name + '.wing_perf.CL', equals=0.5)
        prob.model.add_objective(point_name + '.wing_perf.CD', scaler=1e4)

        # Set up the problem
        prob.setup()

        prob.run_driver()

        assert_rel_error(self, prob['aero_point_0.wing_perf.CL'][0], 0.5, 1e-6)
        assert_rel_error(self, prob['aero_point_0.wing_perf.CD'][0],
                         0.02257921, 1e-6)
        assert_rel_error(self, prob['aero_point_0.CM'][1], -0.179451279, 1e-6)
Example #40
0
def setup(num_inboard=2, num_outboard=3, check=False, out_stream=sys.stdout):
    ''' Setup the aerostruct mesh using OpenMDAO'''

    # Define the aircraft properties
    from CRM import span, v, alpha, rho

    # Define spatialbeam properties
    from aluminum import E, G, stress, mrho

    # Create the mesh with 2 inboard points and 3 outboard points.
    # This will be mirrored to produce a mesh with 7 spanwise points,
    # or 6 spanwise panels
    print(type(num_inboard))
    mesh = gen_crm_mesh(int(num_inboard), int(num_outboard), num_x=2)
    num_x, num_y = mesh.shape[:2]
    num_twist = numpy.max([int((num_y - 1) / 5), 5])
    r = radii(mesh)

    # Set the number of thickness control points and the initial thicknesses
    num_thickness = num_twist
    t = r / 10

    mesh = mesh.reshape(-1, mesh.shape[-1])
    aero_ind = numpy.atleast_2d(numpy.array([num_x, num_y]))
    fem_ind = [num_y]
    aero_ind, fem_ind = get_inds(aero_ind, fem_ind)

    # Set additional mesh parameters
    dihedral = 0.  # dihedral angle in degrees
    sweep = 0.  # shearing sweep angle in degrees
    taper = 1.  # taper ratio

    # Initial displacements of zero
    tot_n_fem = numpy.sum(fem_ind[:, 0])
    disp = numpy.zeros((tot_n_fem, 6))

    # Define Jacobians for b-spline controls
    tot_n_fem = numpy.sum(fem_ind[:, 0])
    num_surf = fem_ind.shape[0]
    jac_twist = get_bspline_mtx(num_twist, num_y)
    jac_thickness = get_bspline_mtx(num_thickness, tot_n_fem - num_surf)

    # Define ...
    twist_cp = numpy.zeros(num_twist)
    thickness_cp = numpy.ones(num_thickness) * numpy.max(t)

    # Define the design variables
    des_vars = [('twist_cp', twist_cp), ('dihedral', dihedral),
                ('sweep', sweep), ('span', span), ('taper', taper), ('v', v),
                ('alpha', alpha), ('rho', rho), ('disp', disp),
                ('aero_ind', aero_ind), ('fem_ind', fem_ind)]

    root = Group()

    root.add(
        'des_vars',
        IndepVarComp(des_vars),
        promotes=['twist_cp', 'span', 'v', 'alpha', 'rho', 'disp', 'dihedral'])
    root.add(
        'mesh',  # This component is needed, otherwise resulting loads matrix is NaN
        GeometryMesh(
            mesh,
            aero_ind),  # changes mesh given span, sweep, twist, and des_vars
        promotes=['span', 'sweep', 'dihedral', 'twist', 'taper', 'mesh'])
    root.add('def_mesh',
             TransferDisplacements(aero_ind, fem_ind),
             promotes=['mesh', 'disp', 'def_mesh'])

    prob = Problem()
    prob.root = root
    prob.setup(check=check, out_stream=out_stream)
    prob.run()

    # Output the def_mesh for the aero modules
    def_mesh = prob['def_mesh']

    # Other variables needed for aero and struct modules
    params = {
        'mesh': mesh,
        'num_x': num_x,
        'num_y': num_y,
        'span': span,
        'twist_cp': twist_cp,
        'thickness_cp': thickness_cp,
        'v': v,
        'alpha': alpha,
        'rho': rho,
        'r': r,
        't': t,
        'aero_ind': aero_ind,
        'fem_ind': fem_ind,
        'num_thickness': num_thickness,
        'num_twist': num_twist,
        'sweep': sweep,
        'taper': taper,
        'dihedral': dihedral,
        'E': E,
        'G': G,
        'stress': stress,
        'mrho': mrho,
        'tot_n_fem': tot_n_fem,
        'num_surf': num_surf,
        'jac_twist': jac_twist,
        'jac_thickness': jac_thickness,
        'out_stream': out_stream,
        'check': check
    }

    return (def_mesh, params)
Example #41
0
    def test_design_derivs(self):
        p = Problem()
        model = p.model
        nn = 1

        ind = model.add_subsystem('indeps', IndepVarComp(), promotes=['*'])

        ind.add_output('DES:P_shaft',
                       14.000,
                       units='kW',
                       desc='shaft power out of the motor')
        ind.add_output('OD:P_shaft',
                       1.000 * np.ones(nn),
                       units='kW',
                       desc='shaft power out of the motor')

        ind.add_output('DES:stack_length',
                       0.0345,
                       units='m',
                       desc='axial length of the motor')

        ind.add_output('DES:rpm', 5400, units='rpm', desc='Rotation speed')
        ind.add_output('OD:rpm',
                       1000 * np.ones(nn),
                       units='rpm',
                       desc='Rotation speed')

        ind.add_output('DES:I', 34.5, units='A', desc='RMS Current')
        ind.add_output('OD:I',
                       34.5 * np.ones(nn),
                       units='A',
                       desc='RMS Current')

        ind.add_output('radius_motor',
                       0.078225,
                       units='m',
                       desc='Motor outer radius')  # Ref motor = 0.078225

        ind.add_output('n_turns', 12, desc='Number of wire turns')
        ind.add_output('n_slots', 24, desc='Number of Slots')
        ind.add_output('n_m', 20, desc='Number of magnets')

        ind.add_output('t_mag',
                       .0044,
                       units='m',
                       desc='Radial magnet thickness')  # Ref motor = 0.0044
        ind.add_output('r_strand',
                       0.0001605,
                       units='m',
                       desc='28 AWG radius of one strand of litz wire')
        ind.add_output('n_strands',
                       41,
                       desc='number of strands in hand for litz wire')

        ind.add_output('T_windings',
                       150,
                       units='C',
                       desc='operating temperature of windings')
        ind.add_output('T_mag',
                       100,
                       units='C',
                       desc='operating temperature of the magnets')

        # -------------------------------------------------------------------------
        #                        Material Properties and Constants
        # -------------------------------------------------------------------------
        ind.add_output('Hc_20',
                       -1046,
                       units='kA/m',
                       desc='Intrinsic Coercivity at 20 degC')
        ind.add_output('Br_20',
                       1.39,
                       units='T',
                       desc='remnance flux density at 20 degC')
        ind.add_output(
            'k_sat',
            1,
            desc=
            'Saturation factor of the magnetic circuit due to the main (linkage) magnetic flux'
        )
        ind.add_output('mu_o',
                       1.2566e-6,
                       units='H/m',
                       desc='permeability of free space')
        ind.add_output(
            'mu_r',
            1.0,
            units='H/m',
            desc='relative magnetic permeability of ferromagnetic materials')
        ind.add_output('rho',
                       8110.2,
                       units='kg/m**3',
                       desc='Density of Hiperco-50')
        ind.add_output('rho_mag',
                       7500,
                       units='kg/m**3',
                       desc='Density of Magnets')
        # ind.add_output('rho_wire', 8940, units='kg/m**3', desc='Density of wire: Cu=8940')
        ind.add_output('resistivity_wire',
                       1.724e-8,
                       units='ohm*m',
                       desc='resisitivity of Cu at 20 degC')
        ind.add_output('T_coeff_cu',
                       0.00393,
                       desc='temperature coeff of copper')
        # ind.add_output('T_ref_wire', 20.0, units='C', desc='reference temperature at which winding resistivity is measured')
        ind.add_output('alpha_stein',
                       1.286,
                       desc='Alpha coefficient for steinmetz, constant')
        ind.add_output(
            'beta_stein',
            1.76835,
            desc='Beta coefficient for steinmetz, dependent on freq')
        ind.add_output('k_stein', 0.0044, desc='k constant for steinmetz')
        ind.add_output(
            'T_coef_rem_mag',
            -0.12,
            desc=
            ' Temperature coefficient of the remnance flux density for N48H magnets'
        )

        # -------------------------------------------------------------------------

        ind.add_output('b_ry', 3.0, units='T',
                       desc='Rotor yoke flux density')  # FEA
        ind.add_output('b_sy', 2.4, units='T',
                       desc='Stator yoke flux density')  # FEA
        ind.add_output('b_t', 3.0, units='T', desc='Tooth Flux Density')  # FEA
        ind.add_output('B_pk',
                       2.4,
                       units='T',
                       desc='Peak flux density for Hiperco-50')  # FEA
        ind.add_output('k_wb', 0.58,
                       desc='copper fill factor')  # Ref motor = 0.58

        # ind.add_output('l_slot_opening', .00325, units='m', desc='length of the slot opening')  # Ref motor = .00325
        ind.add_output('k', 0.94, desc='Stacking factor assumption')
        ind.add_output(
            'gap',
            0.0010,
            units='m',
            desc=
            'Air gap distance, Need to calculate effective air gap, using Carters Coeff'
        )

        p.model.add_subsystem('DESIGN', Motor(num_nodes=nn, design=True))

        motor_path = 'DESIGN'
        p.model.connect('radius_motor', f'{motor_path}.radius_motor')
        p.model.connect('rho', f'{motor_path}.rho')
        p.model.connect('rho_mag', f'{motor_path}.rho_mag')
        p.model.connect('b_ry', f'{motor_path}.b_ry')
        p.model.connect('b_sy', f'{motor_path}.b_sy')
        p.model.connect('b_t', f'{motor_path}.b_t')
        p.model.connect('k_wb', f'{motor_path}.k_wb')
        p.model.connect('k', f'{motor_path}.k')
        p.model.connect('B_pk', f'{motor_path}.B_pk')
        p.model.connect('Br_20', f'{motor_path}.Br_20')
        p.model.connect('n_turns', f'{motor_path}.n_turns')
        p.model.connect('n_slots', f'{motor_path}.n_slots')
        p.model.connect('n_m', f'{motor_path}.n_m')
        p.model.connect('t_mag', f'{motor_path}.t_mag')
        p.model.connect('r_strand', f'{motor_path}.r_strand')
        p.model.connect('n_strands', f'{motor_path}.n_strands')
        p.model.connect('T_windings', f'{motor_path}.T_windings')
        p.model.connect('T_mag', f'{motor_path}.T_mag')
        # -------------------------------------------------------------------------
        #                        Material Properties and Constants
        # -------------------------------------------------------------------------
        p.model.connect('k_sat', f'{motor_path}.k_sat')
        p.model.connect('mu_o', f'{motor_path}.mu_o')
        p.model.connect('mu_r', f'{motor_path}.mu_r')
        # p.model.connect('rho_wire', f'{motor_path}.rho_wire')
        p.model.connect('resistivity_wire', f'{motor_path}.resistivity_wire')
        p.model.connect('T_coeff_cu', f'{motor_path}.T_coeff_cu')
        # p.model.connect('T_ref_wire', f'{motor_path}.T_ref_wire')
        p.model.connect('alpha_stein', f'{motor_path}.alpha_stein')
        p.model.connect('beta_stein', f'{motor_path}.beta_stein')
        p.model.connect('k_stein', f'{motor_path}.k_stein')
        p.model.connect('T_coef_rem_mag', f'{motor_path}.T_coef_rem_mag')

        p.model.connect('gap', f'{motor_path}.gap')

        p.model.connect('DES:rpm', 'DESIGN.rpm')
        p.model.connect('DES:I', 'DESIGN.I')
        p.model.connect('DES:stack_length', 'DESIGN.stack_length')
        p.model.connect('DES:P_shaft', 'DESIGN.P_shaft')

        p.setup(force_alloc_complex=True)

        p['radius_motor'] = 0.086  # Set the desired radius of the motor, application specific
        p['DESIGN.rot_or'] = 6.8  # initial guess

        # p.run_model()
        # make new lines for each component

        data_size = p.check_partials(method='cs',
                                     compact_print=True,
                                     show_only_incorrect=True,
                                     includes='DESIGN.geometry.size')

        # can look at one component at a time with assert_check_partials
        assert_check_partials(data_size, atol=1e-6, rtol=1e-6)

        data = p.check_partials(method='cs',
                                compact_print=True,
                                show_only_incorrect=True,
                                includes='DESIGN.em_properties.carters')
        # can look at one component at a time with assert_check_partials
        assert_check_partials(data, atol=1e-6, rtol=1e-6)

        data = p.check_partials(method='cs',
                                compact_print=True,
                                show_only_incorrect=True,
                                includes='DESIGN.em_properties.equivalent_gap')
        # can look at one component at a time with assert_check_partials
        assert_check_partials(data, atol=1e-6, rtol=1e-6)

        data = p.check_partials(method='cs',
                                compact_print=True,
                                show_only_incorrect=True,
                                includes='DESIGN.em_properties.gap_fields')
        # can look at one component at a time with assert_check_partials
        assert_check_partials(data, atol=1e-6, rtol=1e-6)

        data = p.check_partials(method='cs',
                                compact_print=True,
                                show_only_incorrect=True,
                                includes='DESIGN.em_properties.torque')
        # can look at one component at a time with assert_check_partials
        assert_check_partials(data, atol=1e-6, rtol=1e-6)

        data = p.check_partials(
            method='cs',
            compact_print=True,
            show_only_incorrect=True,
            includes='DESIGN.em_properties.motor_efficiency')
        # can look at one component at a time with assert_check_partials
        assert_check_partials(data, atol=1e-6, rtol=1e-6)

        data = p.check_partials(
            method='cs',
            compact_print=True,
            show_only_incorrect=True,
            includes='DESIGN.thermal_properties.copperloss')
        # can look at one component at a time with assert_check_partials
        assert_check_partials(data, atol=1e-6, rtol=1e-6)

        data = p.check_partials(
            method='cs',
            compact_print=True,
            show_only_incorrect=True,
            includes='DESIGN.thermal_properties.steinmetzloss')
        # can look at one component at a time with assert_check_partials
        assert_check_partials(data, atol=1e-6, rtol=1e-6)
Example #42
0
def aero(def_mesh=None, params=None):

    if (params is None) or (def_mesh is None):
        tmpmesh, params = setup()
        if not def_mesh:
            def_mesh = tmpmesh

    # Unpack variables
    mesh = params.get('mesh')
    num_x = params.get('num_x')
    num_y = params.get('num_y')
    span = params.get('span')
    twist_cp = params.get('twist_cp')
    thickness_cp = params.get('thickness_cp')
    v = params.get('v')
    alpha = params.get('alpha')
    rho = params.get('rho')
    r = params.get('r')
    t = params.get('t')
    aero_ind = params.get('aero_ind')
    fem_ind = params.get('fem_ind')
    num_thickness = params.get('num_thickness')
    num_twist = params.get('num_twist')
    sweep = params.get('sweep')
    taper = params.get('taper')
    disp = params.get('disp')
    dihedral = params.get('dihedral')
    check = params.get('check')
    out_stream = params.get('out_stream')

    # Define Jacobians for b-spline controls
    tot_n_fem = numpy.sum(fem_ind[:, 0])
    num_surf = fem_ind.shape[0]
    jac_twist = get_bspline_mtx(num_twist, num_y)
    jac_thickness = get_bspline_mtx(num_thickness, tot_n_fem - num_surf)

    disp = numpy.zeros((num_y, 6))  # for display?

    # Define the design variables
    des_vars = [('twist_cp', numpy.zeros(num_twist)), ('dihedral', dihedral),
                ('sweep', sweep), ('span', span), ('taper', taper), ('v', v),
                ('alpha', alpha), ('rho', rho),
                ('disp', numpy.zeros((tot_n_fem, 6))), ('def_mesh', def_mesh)]

    root = Group()

    root.add('des_vars',
             IndepVarComp(des_vars),
             promotes=[
                 'twist_cp', 'span', 'v', 'alpha', 'rho', 'disp', 'dihedral',
                 'def_mesh'
             ])
    # root.add('twist_bsp',  # What is this doing?
    #          Bspline('twist_cp', 'twist', jac_twist),
    #          promotes=['*'])
    # root.add('thickness_bsp',    # What is this doing?
    #          Bspline('thickness_cp', 'thickness', jac_thickness),
    #          promotes=['*'])
    # root.add('tube',
    #          MaterialsTube(fem_ind),
    #          promotes=['*'])

    root.add(
        'VLMstates',
        VLMStates(aero_ind),
        promotes=[
            'def_mesh',
            'b_pts',
            'mid_b',
            'c_pts',
            'widths',
            'normals',
            'S_ref',  # VLMGeometry
            'alpha',
            'circulations',
            'v',  # VLMCirculations
            'rho',
            'sec_forces'  # VLMForces
        ])
    root.add('loads',
             TransferLoads(aero_ind, fem_ind),
             promotes=['def_mesh', 'sec_forces', 'loads'])

    prob = Problem()
    prob.root = root
    prob.setup(check=check, out_stream=out_stream)
    prob.run()

    return prob['loads']  # Output the Loads matrix
phase.add_boundary_constraint('h', loc='final', equals=20000, scaler=1.0E-3, units='m')
phase.add_boundary_constraint('aero.mach', loc='final', equals=1.0, shape=(1,))
phase.add_boundary_constraint('gam', loc='final', equals=0.0, units='rad')

phase.add_path_constraint(name='h', lower=100.0, upper=20000, ref=20000)
phase.add_path_constraint(name='aero.mach', lower=0.1, upper=1.8, shape=(1,))

# Minimize time at the end of the phase
phase.add_objective('time', loc='final', ref=1.0)

p.model.linear_solver = DirectSolver()

#
# Setup the problem and set the initial guess
#
p.setup(check=True)

p['traj.phase0.t_initial'] = 0.0
p['traj.phase0.t_duration'] = 500

p['traj.phase0.states:r'] = phase.interpolate(ys=[0.0, 50000.0], nodes='state_input')
p['traj.phase0.states:h'] = phase.interpolate(ys=[100.0, 20000.0], nodes='state_input')
p['traj.phase0.states:v'] = phase.interpolate(ys=[135.964, 283.159], nodes='state_input')
p['traj.phase0.states:gam'] = phase.interpolate(ys=[0.0, 0.0], nodes='state_input')
p['traj.phase0.states:m'] = phase.interpolate(ys=[19030.468, 10000.], nodes='state_input')
# p['traj.phase0.controls:alpha'] = phase.interpolate(ys=[0.0, 0.0], nodes='control_input')

p['traj.phase0.polynomial_controls:alpha'] = np.array([[4.86918595],
                                                        [1.30322324],
                                                        [1.41897019],
                                                        [1.10227365],
Example #44
0
class J79OffdesignDryTestCase(unittest.TestCase):
    def setUp(self):

        self.prob = Problem()

        des_vars = self.prob.model.add_subsystem('des_vars',
                                                 IndepVarComp(),
                                                 promotes=['*'])
        des_vars.add_output('OD_MN', 0.000001)
        des_vars.add_output('OD_alt', 0.0, units='ft')
        des_vars.add_output('OD_T4', 2370.0, units='degR')
        des_vars.add_output('OD_ab_FAR', 0.0)  # 0.031523391)
        des_vars.add_output('OD_Rline', 2.0)

        des_vars.add_output('duct1:dPqP', 0.02)
        des_vars.add_output('burn:dPqP', 0.03)
        des_vars.add_output('ab:dPqP', 0.06)
        des_vars.add_output('nozz:Cv', 0.99)
        des_vars.add_output('comp:cool1:frac_W', 0.0789)
        des_vars.add_output('comp:cool1:frac_P', 1.0)
        des_vars.add_output('comp:cool1:frac_work', 1.0)
        des_vars.add_output('comp:cool2:frac_W', 0.0383)
        des_vars.add_output('comp:cool2:frac_P', 1.0)
        des_vars.add_output('comp:cool2:frac_work', 1.0)
        des_vars.add_output('turb:cool1:frac_P', 1.0)
        des_vars.add_output('turb:cool2:frac_P', 0.0)

        des_vars.add_output('comp:s_PRdes', 2.97619047619)
        des_vars.add_output('comp:s_WcDes', 5.71447539197)
        des_vars.add_output('comp:s_effDes', 0.975323149236)
        des_vars.add_output('comp:s_NcDes', 8070.0)
        des_vars.add_output('turb:s_PRdes', 0.692263737296)
        des_vars.add_output('turb:s_WpDes', 0.259890960213)
        des_vars.add_output('turb:s_effDes', 0.927123760241)
        des_vars.add_output('turb:s_NpDes', 1.65767490056)

        des_vars.add_output('inlet:Fl_O:stat:area',
                            581.693962336,
                            units='inch**2')
        des_vars.add_output('duct1:Fl_O:stat:area',
                            593.565267689,
                            units='inch**2')
        des_vars.add_output('comp:Fl_O:stat:area',
                            148.263145086,
                            units='inch**2')
        des_vars.add_output('burner:Fl_O:stat:area',
                            224.924279335,
                            units='inch**2')
        des_vars.add_output('turb:Fl_O:stat:area',
                            504.741845228,
                            units='inch**2')
        des_vars.add_output('ab:Fl_O:stat:area',
                            536.954431167,
                            units='inch**2')

        self.prob.model.add_subsystem('OD', Turbojet(design=False,
                                                     statics=True))

        self.prob.model.connect('OD_alt', 'OD.fc.alt')
        self.prob.model.connect('OD_MN', 'OD.fc.MN')
        self.prob.model.connect('OD_T4', 'OD.balance.rhs:FAR')
        self.prob.model.connect('OD_Rline', 'OD.balance.rhs:W')
        self.prob.model.connect('OD_ab_FAR', 'OD.ab.Fl_I:FAR')

        self.prob.model.connect('duct1:dPqP', 'OD.duct1.dPqP')
        self.prob.model.connect('burn:dPqP', 'OD.burner.dPqP')
        self.prob.model.connect('ab:dPqP', 'OD.ab.dPqP')
        self.prob.model.connect('nozz:Cv', 'OD.nozz.Cv')

        self.prob.model.connect('comp:cool1:frac_W', 'OD.comp.cool1:frac_W')
        self.prob.model.connect('comp:cool1:frac_P', 'OD.comp.cool1:frac_P')
        self.prob.model.connect('comp:cool1:frac_work',
                                'OD.comp.cool1:frac_work')

        self.prob.model.connect('comp:cool2:frac_W', 'OD.comp.cool2:frac_W')
        self.prob.model.connect('comp:cool2:frac_P', 'OD.comp.cool2:frac_P')
        self.prob.model.connect('comp:cool2:frac_work',
                                'OD.comp.cool2:frac_work')

        self.prob.model.connect('turb:cool1:frac_P', 'OD.turb.cool1:frac_P')
        self.prob.model.connect('turb:cool2:frac_P', 'OD.turb.cool2:frac_P')

        self.prob.model.connect('comp:s_PRdes', 'OD.comp.s_PR')
        self.prob.model.connect('comp:s_WcDes', 'OD.comp.s_Wc')
        self.prob.model.connect('comp:s_effDes', 'OD.comp.s_eff')
        self.prob.model.connect('comp:s_NcDes', 'OD.comp.s_Nc')

        self.prob.model.connect('turb:s_PRdes', 'OD.turb.s_PR')
        self.prob.model.connect('turb:s_WpDes', 'OD.turb.s_Wp')
        self.prob.model.connect('turb:s_effDes', 'OD.turb.s_eff')
        self.prob.model.connect('turb:s_NpDes', 'OD.turb.s_Np')

        self.prob.model.connect('inlet:Fl_O:stat:area', 'OD.inlet.area')
        self.prob.model.connect('duct1:Fl_O:stat:area', 'OD.duct1.area')
        self.prob.model.connect('comp:Fl_O:stat:area', 'OD.comp.area')
        self.prob.model.connect('burner:Fl_O:stat:area', 'OD.burner.area')
        self.prob.model.connect('turb:Fl_O:stat:area', 'OD.turb.area')
        self.prob.model.connect('ab:Fl_O:stat:area', 'OD.ab.area')

        self.prob.set_solver_print(level=-1)
        self.prob.set_solver_print(level=2, depth=1)
        self.prob.setup(check=False)

        self.prob['OD.balance.W'] = 168.
        self.prob['OD.balance.FAR'] = 0.0175506829934
        self.prob['OD.balance.Nmech'] = 8070.0
        self.prob['OD.fc.balance.Pt'] = 14.6955113159
        self.prob['OD.fc.balance.Tt'] = 518.665288153
        self.prob['OD.turb.PR'] = 4.46138725662

        # from openmdao.api import view_model
        # view_model(self.prob)
        # exit()

    def benchmark_case1(self):
        # ADP Point
        np.seterr(divide='raise')

        self.prob.run_model()
        tol = 1e-3

        print()

        reg_data = 168.005
        pyc = self.prob['OD.inlet.Fl_O:stat:W'][0]
        print('W:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 13.500
        pyc = self.prob['OD.perf.OPR'][0]
        print('OPR:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 0.01755
        pyc = self.prob['OD.balance.FAR'][0]
        print('Main FAR:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 8070.00
        pyc = self.prob['OD.balance.Nmech'][0]
        print('HP Nmech:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 11800.0
        pyc = self.prob['OD.perf.Fg'][0]
        print('Fg:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 0.79415
        pyc = self.prob['OD.perf.TSFC'][0]
        print('TSFC:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 1190.18
        pyc = self.prob['OD.comp.Fl_O:tot:T'][0]
        print('Tt3:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        print()

    def benchmark_case2(self):
        np.seterr(divide='raise')
        self.prob['OD_MN'] = 0.8
        self.prob['OD_alt'] = 0.0
        self.prob['OD_T4'] = 2370.0
        self.prob['OD_ab_FAR'] = 0.0
        self.prob['OD_Rline'] = 2.0

        self.prob.run_model()
        tol = 1e-3

        print()

        reg_data = 225.917
        pyc = self.prob['OD.inlet.Fl_O:stat:W'][0]
        print('W:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 11.971
        pyc = self.prob['OD.perf.OPR'][0]
        print('OPR:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 0.01629
        pyc = self.prob['OD.balance.FAR'][0]
        print('Main FAR:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 8288.85
        pyc = self.prob['OD.balance.Nmech'][0]
        print('HP Nmech:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 17210.0
        pyc = self.prob['OD.perf.Fg'][0]
        print('Fg:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 1.06924
        pyc = self.prob['OD.perf.TSFC'][0]
        print('TSFC:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 1280.18
        pyc = self.prob['OD.comp.Fl_O:tot:T'][0]
        print('Tt3:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        print()

    def benchmark_case3(self):
        np.seterr(divide='raise')
        self.prob['OD_MN'] = 1.00001  # set to 1.00001 to get model to converge
        self.prob['OD_alt'] = 15000.0
        self.prob['OD_T4'] = 2370.0
        self.prob['OD_ab_FAR'] = 0.0
        self.prob['OD_Rline'] = 2.0

        self.prob.run_model()
        tol = 1e-3

        print()

        reg_data = 166.073
        pyc = self.prob['OD.inlet.Fl_O:stat:W'][0]
        print('W:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 12.526
        pyc = self.prob['OD.perf.OPR'][0]
        print('OPR:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 0.01680
        pyc = self.prob['OD.balance.FAR'][0]
        print('Main FAR:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 8197.38
        pyc = self.prob['OD.balance.Nmech'][0]
        print('HP Nmech:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 13881.2
        pyc = self.prob['OD.perf.Fg'][0]
        print('Fg:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 1.05281
        pyc = self.prob['OD.perf.TSFC'][0]
        print('TSFC:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 1243.86
        pyc = self.prob['OD.comp.Fl_O:tot:T'][0]
        print('Tt3:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        print()

    def benchmark_case4(self):
        np.seterr(divide='raise')
        self.prob['OD_MN'] = 1.2
        self.prob['OD_alt'] = 25000.0
        self.prob['OD_T4'] = 2370.0
        self.prob['OD_ab_FAR'] = 0.0
        self.prob['OD_Rline'] = 2.0

        self.prob.run_model()
        tol = 1e-3

        print()

        reg_data = 141.201
        pyc = self.prob['OD.inlet.Fl_O:stat:W'][0]
        print('W:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 12.636
        pyc = self.prob['OD.perf.OPR'][0]
        print('OPR:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 0.01689
        pyc = self.prob['OD.balance.FAR'][0]
        print('Main FAR:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 8181.03
        pyc = self.prob['OD.balance.Nmech'][0]
        print('HP Nmech:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 12589.2
        pyc = self.prob['OD.perf.Fg'][0]
        print('Fg:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 1.04755
        pyc = self.prob['OD.perf.TSFC'][0]
        print('TSFC:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 1237.20
        pyc = self.prob['OD.comp.Fl_O:tot:T'][0]
        print('Tt3:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        print()

    def benchmark_case5(self):
        np.seterr(divide='raise')
        self.prob['OD_MN'] = 0.6
        self.prob['OD_alt'] = 35000.0
        self.prob['OD_T4'] = 2370.0
        self.prob['OD_ab_FAR'] = 0.0
        self.prob['OD_Rline'] = 2.0

        self.prob['OD.balance.W'] = 60.

        self.prob.run_model()
        tol = 1e-3

        print()

        reg_data = 61.708
        pyc = self.prob['OD.inlet.Fl_O:stat:W'][0]
        print('W:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 16.956
        pyc = self.prob['OD.perf.OPR'][0]
        print('OPR:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 0.01873
        pyc = self.prob['OD.balance.FAR'][0]
        print('Main FAR:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 8902.24
        pyc = self.prob['OD.balance.Nmech'][0]
        print('HP Nmech:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 5109.4
        pyc = self.prob['OD.perf.Fg'][0]
        print('Fg:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 0.92067
        pyc = self.prob['OD.perf.TSFC'][0]
        print('TSFC:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 1105.24
        pyc = self.prob['OD.comp.Fl_O:tot:T'][0]
        print('Tt3:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        print()

    def benchmark_case6(self):
        np.seterr(divide='raise')
        self.prob['OD_MN'] = 1.6
        self.prob['OD_alt'] = 35000.0
        self.prob['OD_T4'] = 2370.0
        self.prob['OD_ab_FAR'] = 0.0
        self.prob['OD_Rline'] = 2.0

        self.prob.run_model()
        tol = 1e-3

        print()

        reg_data = 145.635
        pyc = self.prob['OD.inlet.Fl_O:stat:W'][0]
        print('W:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 11.765
        pyc = self.prob['OD.perf.OPR'][0]
        print('OPR:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 0.01608
        pyc = self.prob['OD.balance.FAR'][0]
        print('Main FAR:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 8326.59
        pyc = self.prob['OD.balance.Nmech'][0]
        print('HP Nmech:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 14061.9
        pyc = self.prob['OD.perf.Fg'][0]
        print('Fg:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 1.06142
        pyc = self.prob['OD.perf.TSFC'][0]
        print('TSFC:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 1294.80
        pyc = self.prob['OD.comp.Fl_O:tot:T'][0]
        print('Tt3:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        print()

    def benchmark_case7(self):
        np.seterr(divide='raise')
        self.prob['OD_MN'] = 1.6
        self.prob['OD_alt'] = 50000.0
        self.prob['OD_T4'] = 2370.0
        self.prob['OD_ab_FAR'] = 0.0
        self.prob['OD_Rline'] = 2.0

        self.prob.run_model()
        tol = 1e-3

        print()

        reg_data = 71.539
        pyc = self.prob['OD.inlet.Fl_O:stat:W'][0]
        print('W:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 11.876
        pyc = self.prob['OD.perf.OPR'][0]
        print('OPR:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 0.01620
        pyc = self.prob['OD.balance.FAR'][0]
        print('Main FAR:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 8306.00
        pyc = self.prob['OD.balance.Nmech'][0]
        print('HP Nmech:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 6930.5
        pyc = self.prob['OD.perf.Fg'][0]
        print('Fg:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 1.05654
        pyc = self.prob['OD.perf.TSFC'][0]
        print('TSFC:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 1286.85
        pyc = self.prob['OD.comp.Fl_O:tot:T'][0]
        print('Tt3:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        print()

    #TODO: there seems to be a regression here, but its the only one so I think we'll just skip it for now
    def _benchmark_case8(self):
        np.seterr(divide='raise')
        self.prob['OD_MN'] = 1.8
        self.prob['OD_alt'] = 70000.0
        self.prob['OD_T4'] = 2370.0
        self.prob['OD_ab_FAR'] = 0.0
        self.prob['OD_Rline'] = 2.0

        self.prob.run_model()
        tol = 1e-3

        print()

        reg_data = 33.347
        pyc = self.prob['OD.inlet.Fl_O:stat:W'][0]
        print('W:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 10.741
        pyc = self.prob['OD.perf.OPR'][0]
        print('OPR:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 0.01517
        pyc = self.prob['OD.balance.FAR'][0]
        print('Main FAR:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 8467.24
        pyc = self.prob['OD.balance.Nmech'][0]
        print('HP Nmech:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 3290.0
        pyc = self.prob['OD.perf.Fg'][0]
        print('Fg:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 1.08806
        pyc = self.prob['OD.perf.TSFC'][0]
        print('TSFC:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        reg_data = 1359.21
        pyc = self.prob['OD.comp.Fl_O:tot:T'][0]
        print('Tt3:', reg_data, pyc)
        assert_rel_error(self, pyc, reg_data, tol)

        print()
Example #45
0
    def test_relevance(self):
        p = Problem()
        model = p.model

        indep1 = model.add_subsystem("indep1", IndepVarComp('x', 1.0))
        G1 = model.add_subsystem('G1', Group())
        G1.add_subsystem('C1', ExecComp(['x=2.0*a', 'y=2.0*b', 'z=2.0*a']))
        G1.add_subsystem('C2', ExecComp(['x=2.0*a', 'y=2.0*b', 'z=2.0*b']))
        model.add_subsystem("C3", ExecComp(['x=2.0*a', 'y=2.0*b+3.0*c']))
        model.add_subsystem("C4", ExecComp(['x=2.0*a', 'y=2.0*b']))
        indep2 = model.add_subsystem("indep2", IndepVarComp('x', 1.0))
        G2 = model.add_subsystem('G2', Group())
        G2.add_subsystem('C5', ExecComp(['x=2.0*a', 'y=2.0*b+3.0*c']))
        G2.add_subsystem('C6', ExecComp(['x=2.0*a', 'y=2.0*b+3.0*c']))
        G2.add_subsystem('C7', ExecComp(['x=2.0*a', 'y=2.0*b']))
        model.add_subsystem("C8", ExecComp(['y=1.5*a+2.0*b']))
        model.add_subsystem("Unconnected", ExecComp('y=99.*x'))

        model.connect('indep1.x', 'G1.C1.a')
        model.connect('indep2.x', 'G2.C6.a')
        model.connect('G1.C1.x', 'G1.C2.b')
        model.connect('G1.C2.z', 'C4.b')
        model.connect('G1.C1.z', ('C3.b', 'C3.c', 'G2.C5.a'))
        model.connect('C3.y', 'G2.C5.b')
        model.connect('C3.x', 'C4.a')
        model.connect('G2.C6.y', 'G2.C7.b')
        model.connect('G2.C5.x', 'C8.b')
        model.connect('G2.C7.x', 'C8.a')

        p.setup(check=False, mode='rev')

        g = p.model.compute_sys_graph(comps_only=True)
        relevant = get_relevant_vars(g, ['indep1.x', 'indep2.x'],
                                     ['C8.y', 'Unconnected.y'],
                                     mode='rev')

        indep1_ins = set(
            ['C3.b', 'C3.c', 'C8.b', 'G1.C1.a', 'G2.C5.a', 'G2.C5.b'])
        indep1_outs = set(['C3.y', 'C8.y', 'G1.C1.z', 'G2.C5.x', 'indep1.x'])
        indep1_sys = set(
            ['C3', 'C8', 'G1.C1', 'G2.C5', 'indep1', 'G1', 'G2', ''])

        dct, systems = relevant['C8.y']['indep1.x']
        inputs = dct['input']
        outputs = dct['output']

        self.assertEqual(inputs, indep1_ins)
        self.assertEqual(outputs, indep1_outs)
        self.assertEqual(systems, indep1_sys)

        dct, systems = relevant['C8.y']['indep1.x']
        inputs = dct['input']
        outputs = dct['output']

        self.assertEqual(inputs, indep1_ins)
        self.assertEqual(outputs, indep1_outs)
        self.assertEqual(systems, indep1_sys)

        indep2_ins = set(['C8.a', 'G2.C6.a', 'G2.C7.b'])
        indep2_outs = set(['C8.y', 'G2.C6.y', 'G2.C7.x', 'indep2.x'])
        indep2_sys = set(['C8', 'G2.C6', 'G2.C7', 'indep2', 'G2', ''])

        dct, systems = relevant['C8.y']['indep2.x']
        inputs = dct['input']
        outputs = dct['output']

        self.assertEqual(inputs, indep2_ins)
        self.assertEqual(outputs, indep2_outs)
        self.assertEqual(systems, indep2_sys)

        dct, systems = relevant['C8.y']['indep2.x']
        inputs = dct['input']
        outputs = dct['output']

        self.assertEqual(inputs, indep2_ins)
        self.assertEqual(outputs, indep2_outs)
        self.assertEqual(systems, indep2_sys)

        dct, systems = relevant['C8.y']['@all']
        inputs = dct['input']
        outputs = dct['output']

        self.assertEqual(inputs, indep1_ins | indep2_ins)
        self.assertEqual(outputs, indep1_outs | indep2_outs)
        self.assertEqual(systems, indep1_sys | indep2_sys)
Example #46
0
        prob.model.connect('DESIGN.hpc.Fl_O:stat:area', pt+'.hpc.area')
        prob.model.connect('DESIGN.bld3.Fl_O:stat:area', pt+'.bld3.area')
        prob.model.connect('DESIGN.burner.Fl_O:stat:area', pt+'.burner.area')
        prob.model.connect('DESIGN.hpt.Fl_O:stat:area', pt+'.hpt.area')
        prob.model.connect('DESIGN.hpt_duct.Fl_O:stat:area', pt+'.hpt_duct.area')
        prob.model.connect('DESIGN.lpt.Fl_O:stat:area', pt+'.lpt.area')
        prob.model.connect('DESIGN.lpt_duct.Fl_O:stat:area', pt+'.lpt_duct.area')
        prob.model.connect('DESIGN.bypass_duct.Fl_O:stat:area', pt+'.bypass_duct.area')
        prob.model.connect('DESIGN.mixer.Fl_O:stat:area', pt+'.mixer.area')
        prob.model.connect('DESIGN.mixer.Fl_I1_calc:stat:area', pt+'.mixer.Fl_I1_stat_calc.area')
        prob.model.connect('DESIGN.mixer_duct.Fl_O:stat:area', pt+'.mixer_duct.area')
        prob.model.connect('DESIGN.afterburner.Fl_O:stat:area', pt+'.afterburner.area')


    # setup problem
    prob.setup(check=False)#True)

    # initial guesses
    prob['DESIGN.balance.FAR_core'] = 0.025
    prob['DESIGN.balance.FAR_ab'] = 0.025
    prob['DESIGN.balance.BPR'] = 1.0
    prob['DESIGN.balance.W'] = 100.
    prob['DESIGN.balance.lpt_PR'] = 3.5
    prob['DESIGN.balance.hpt_PR'] = 2.5
    prob['DESIGN.fc.balance.Pt'] = 5.2
    prob['DESIGN.fc.balance.Tt'] = 440.0
    prob['DESIGN.mixer.balance.P_tot']= 15

    for pt in od_pts:
        prob[pt+'.balance.FAR_core'] = 0.025
        prob[pt+'.balance.FAR_ab'] = 0.025
Example #47
0
 def test_simple(self):
     prob = Problem(RectangleComp())
     prob.setup(check=False)
     prob.run_model()
    def test(self):
        # Create a dictionary to store options about the surface
        mesh_dict = {
            'num_y': 5,
            'num_x': 2,
            'wing_type': 'CRM',
            'symmetry': True,
            'num_twist_cp': 5
        }

        mesh, twist_cp = generate_mesh(mesh_dict)

        surf_dict = {
            # Wing definition
            'name': 'wing',  # name of the surface
            'symmetry': True,  # if true, model one half of wing
            # reflected across the plane y = 0
            'S_ref_type': 'wetted',  # how we compute the wing area,
            # can be 'wetted' or 'projected'
            'fem_model_type': 'tube',
            'thickness_cp': np.array([.1, .2, .3]),
            'twist_cp': twist_cp,
            'mesh': mesh,

            # Aerodynamic performance of the lifting surface at
            # an angle of attack of 0 (alpha=0).
            # These CL0 and CD0 values are added to the CL and CD
            # obtained from aerodynamic analysis of the surface to get
            # the total CL and CD.
            # These CL0 and CD0 values do not vary wrt alpha.
            'CL0': 0.0,  # CL of the surface at alpha=0
            'CD0': 0.015,  # CD of the surface at alpha=0

            # Airfoil properties for viscous drag calculation
            'k_lam': 0.05,  # percentage of chord with laminar
            # flow, used for viscous drag
            't_over_c_cp':
            np.array([0.15]),  # thickness over chord ratio (NACA0015)
            'c_max_t': .303,  # chordwise location of maximum (NACA0015)
            # thickness
            'with_viscous': True,
            'with_wave': False,  # if true, compute wave drag

            # Structural values are based on aluminum 7075
            'E': 70.e9,  # [Pa] Young's modulus of the spar
            'G': 30.e9,  # [Pa] shear modulus of the spar
            'yield':
            500.e6 / 2.5,  # [Pa] yield stress divided by 2.5 for limiting case
            'mrho': 3.e3,  # [kg/m^3] material density
            'fem_origin': 0.35,  # normalized chordwise location of the spar
            'wing_weight_ratio': 2.,
            'struct_weight_relief':
            False,  # True to add the weight of the structure to the loads on the structure
            'distributed_fuel_weight': False,
            # Constraints
            'exact_failure_constraint': False,  # if false, use KS function
        }

        surfaces = [surf_dict]

        # Create the problem and assign the model group
        prob = Problem()

        # Add problem information as an independent variables component
        indep_var_comp = IndepVarComp()
        indep_var_comp.add_output('v', val=248.136, units='m/s')
        indep_var_comp.add_output('alpha', val=5., units='deg')
        indep_var_comp.add_output('Mach_number', val=0.84)
        indep_var_comp.add_output('re', val=1.e6, units='1/m')
        indep_var_comp.add_output('rho', val=0.38, units='kg/m**3')
        indep_var_comp.add_output('CT',
                                  val=grav_constant * 17.e-6,
                                  units='1/s')
        indep_var_comp.add_output('R', val=11.165e6, units='m')
        indep_var_comp.add_output('W0', val=0.4 * 3e5, units='kg')
        indep_var_comp.add_output('speed_of_sound', val=295.4, units='m/s')
        indep_var_comp.add_output('load_factor', val=1.)
        indep_var_comp.add_output('empty_cg', val=np.zeros((3)), units='m')

        prob.model.add_subsystem('prob_vars', indep_var_comp, promotes=['*'])

        # Loop over each surface in the surfaces list
        for surface in surfaces:

            # Get the surface name and create a group to contain components
            # only for this surface
            name = surface['name']

            aerostruct_group = AerostructGeometry(surface=surface)

            # Add tmp_group to the problem with the name of the surface.
            prob.model.add_subsystem(name, aerostruct_group)

        # Loop through and add a certain number of aero points
        for i in range(1):

            point_name = 'AS_point_{}'.format(i)
            # Connect the parameters within the model for each aero point

            # Create the aero point group and add it to the model
            AS_point = AerostructPoint(surfaces=surfaces)

            prob.model.add_subsystem(point_name, AS_point)

            # Connect flow properties to the analysis point
            prob.model.connect('v', point_name + '.v')
            prob.model.connect('alpha', point_name + '.alpha')
            prob.model.connect('Mach_number', point_name + '.Mach_number')
            prob.model.connect('re', point_name + '.re')
            prob.model.connect('rho', point_name + '.rho')
            prob.model.connect('CT', point_name + '.CT')
            prob.model.connect('R', point_name + '.R')
            prob.model.connect('W0', point_name + '.W0')
            prob.model.connect('speed_of_sound',
                               point_name + '.speed_of_sound')
            prob.model.connect('empty_cg', point_name + '.empty_cg')
            prob.model.connect('load_factor', point_name + '.load_factor')

            for surface in surfaces:

                com_name = point_name + '.' + name + '_perf'
                prob.model.connect(
                    name + '.local_stiff_transformed', point_name +
                    '.coupled.' + name + '.local_stiff_transformed')
                prob.model.connect(name + '.nodes',
                                   point_name + '.coupled.' + name + '.nodes')

                # Connect aerodyamic mesh to coupled group mesh
                prob.model.connect(name + '.mesh',
                                   point_name + '.coupled.' + name + '.mesh')

                # Connect performance calculation variables
                prob.model.connect(name + '.radius', com_name + '.radius')
                prob.model.connect(name + '.thickness',
                                   com_name + '.thickness')
                prob.model.connect(name + '.nodes', com_name + '.nodes')
                prob.model.connect(
                    name + '.cg_location',
                    point_name + '.' + 'total_perf.' + name + '_cg_location')
                prob.model.connect(
                    name + '.structural_mass', point_name + '.' +
                    'total_perf.' + name + '_structural_mass')
                prob.model.connect(name + '.t_over_c', com_name + '.t_over_c')

        # Set up the problem
        prob.setup()

        prob.run_model()

        assert_rel_error(self, prob['AS_point_0.fuelburn'][0], 276492.942161,
                         1e-4)
        assert_rel_error(self, prob['AS_point_0.CM'][1], -0.567558367647, 1e-5)
Example #49
0
    def test_array_list_vars_options(self):
        class ArrayAdder(ExplicitComponent):
            """
            Just a simple component that has array inputs and outputs
            """
            def __init__(self, size):
                super(ArrayAdder, self).__init__()
                self.size = size

            def setup(self):
                self.add_input('x', val=np.zeros(self.size), units='inch')
                self.add_output('y', val=np.zeros(self.size), units='ft')

            def compute(self, inputs, outputs):
                outputs['y'] = inputs['x'] + 10.0

        size = 100  # how many items in the array

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

        prob.model.add_subsystem('des_vars',
                                 IndepVarComp('x', np.ones(size),
                                              units='inch'),
                                 promotes=['x'])
        prob.model.add_subsystem('mult', ArrayAdder(size), promotes=['x', 'y'])

        prob.setup(check=False)

        prob['x'] = np.ones(size)

        prob.run_driver()

        # logging inputs
        # out_stream - not hierarchical - extras - no print_arrays
        stream = cStringIO()
        prob.model.list_inputs(values=True,
                               units=True,
                               hierarchical=False,
                               print_arrays=False,
                               out_stream=stream)
        text = stream.getvalue()
        self.assertEqual(1, text.count("1 Input(s) in 'model'"))
        self.assertEqual(1, text.count('mult.x'))
        num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()])
        self.assertEqual(5, num_non_empty_lines)

        # out_stream - hierarchical - extras - no print_arrays
        stream = cStringIO()
        prob.model.list_inputs(values=True,
                               units=True,
                               hierarchical=True,
                               print_arrays=False,
                               out_stream=stream)
        text = stream.getvalue()
        self.assertEqual(1, text.count("1 Input(s) in 'model'"))
        num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()])
        self.assertEqual(7, num_non_empty_lines)
        self.assertEqual(1, text.count('top'))
        self.assertEqual(1, text.count('  mult'))
        self.assertEqual(1, text.count('    x'))

        # logging outputs
        # out_stream - not hierarchical - extras - no print_arrays
        stream = cStringIO()
        prob.model.list_outputs(values=True,
                                units=True,
                                shape=True,
                                bounds=True,
                                residuals=True,
                                scaling=True,
                                hierarchical=False,
                                print_arrays=False,
                                out_stream=stream)
        text = stream.getvalue()
        self.assertEqual(text.count('2 Explicit Output'), 1)
        # make sure they are in the correct order
        self.assertTrue(text.find("des_vars.x") < text.find('mult.y'))
        num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()])
        self.assertEqual(8, num_non_empty_lines)

        # Hierarchical - no print arrays
        stream = cStringIO()
        prob.model.list_outputs(values=True,
                                units=True,
                                shape=True,
                                bounds=True,
                                residuals=True,
                                scaling=True,
                                hierarchical=True,
                                print_arrays=False,
                                out_stream=stream)
        text = stream.getvalue()
        self.assertEqual(text.count('top'), 1)
        self.assertEqual(text.count('  des_vars'), 1)
        self.assertEqual(text.count('    x'), 1)
        self.assertEqual(text.count('  mult'), 1)
        self.assertEqual(text.count('    y'), 1)
        num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()])
        self.assertEqual(num_non_empty_lines, 11)

        # Need to explicitly set this to make sure all ways of running this test
        #   result in the same format of the output. When running this test from the
        #   top level via testflo, the format comes out different than if the test is
        #   run individually
        np.set_printoptions(edgeitems=3,
                            infstr='inf',
                            linewidth=75,
                            nanstr='nan',
                            precision=8,
                            suppress=False,
                            threshold=1000,
                            formatter=None)
        # logging outputs
        # out_stream - not hierarchical - extras - print_arrays
        stream = cStringIO()
        prob.model.list_outputs(values=True,
                                units=True,
                                shape=True,
                                bounds=True,
                                residuals=True,
                                scaling=True,
                                hierarchical=False,
                                print_arrays=True,
                                out_stream=stream)
        text = stream.getvalue()
        self.assertEqual(text.count('2 Explicit Output'), 1)
        self.assertEqual(text.count('value:'), 2)
        self.assertEqual(text.count('resids:'), 2)
        self.assertEqual(text.count('['), 4)
        # make sure they are in the correct order
        self.assertTrue(text.find("des_vars.x") < text.find('mult.y'))
        num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()])
        self.assertEqual(37, num_non_empty_lines)

        # Hierarchical
        stream = cStringIO()
        prob.model.list_outputs(values=True,
                                units=True,
                                shape=True,
                                bounds=True,
                                residuals=True,
                                scaling=True,
                                hierarchical=True,
                                print_arrays=True,
                                out_stream=stream)
        text = stream.getvalue()
        self.assertEqual(text.count('2 Explicit Output'), 1)
        self.assertEqual(text.count('value:'), 2)
        self.assertEqual(text.count('resids:'), 2)
        self.assertEqual(text.count('['), 4)
        self.assertEqual(text.count('top'), 1)
        self.assertEqual(text.count('  des_vars'), 1)
        self.assertEqual(text.count('    x'), 1)
        self.assertEqual(text.count('  mult'), 1)
        self.assertEqual(text.count('    y'), 1)
        num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()])
        self.assertEqual(num_non_empty_lines, 40)
Example #50
0
    def test_compute_and_list(self):
        prob = Problem(RectangleGroup())
        prob.setup(check=False)

        msg = "Unable to list inputs until model has been run."
        try:
            prob.model.list_inputs()
        except Exception as err:
            self.assertTrue(msg == str(err))
        else:
            self.fail("Exception expected")

        msg = "Unable to list outputs until model has been run."
        try:
            prob.model.list_outputs()
        except Exception as err:
            self.assertTrue(msg == str(err))
        else:
            self.fail("Exception expected")

        prob['comp1.length'] = 3.
        prob['comp1.width'] = 2.
        prob.run_model()
        assert_rel_error(self, prob['comp2.area'], 6.)
        assert_rel_error(self, prob['comp3.area'], 6.)

        # total derivs
        total_derivs = prob.compute_totals(wrt=['comp1.length', 'comp1.width'],
                                           of=['comp2.area', 'comp3.area'])
        assert_rel_error(self, total_derivs['comp2.area', 'comp1.length'],
                         [[2.]])
        assert_rel_error(self, total_derivs['comp3.area', 'comp1.length'],
                         [[2.]])
        assert_rel_error(self, total_derivs['comp2.area', 'comp1.width'],
                         [[3.]])
        assert_rel_error(self, total_derivs['comp3.area', 'comp1.width'],
                         [[3.]])

        # list inputs
        inputs = prob.model.list_inputs(out_stream=None)
        self.assertEqual(sorted(inputs), [
            ('comp2.length', {
                'value': [3.]
            }),
            ('comp2.width', {
                'value': [2.]
            }),
            ('comp3.length', {
                'value': [3.]
            }),
            ('comp3.width', {
                'value': [2.]
            }),
        ])

        # list explicit outputs
        outputs = prob.model.list_outputs(implicit=False, out_stream=None)
        self.assertEqual(sorted(outputs), [
            ('comp1.length', {
                'value': [3.]
            }),
            ('comp1.width', {
                'value': [2.]
            }),
            ('comp2.area', {
                'value': [6.]
            }),
            ('comp3.area', {
                'value': [6.]
            }),
        ])

        # list states
        states = prob.model.list_outputs(explicit=False, out_stream=None)
        self.assertEqual(states, [])

        # list excluding both explicit and implicit components raises error
        msg = "You have excluded both Explicit and Implicit components."

        with assertRaisesRegex(self, RuntimeError, msg):
            prob.model.list_outputs(explicit=False, implicit=False)
Example #51
0
    def test_for_feature_docs_list_vars_options(self):

        from openmdao.api import IndepVarComp, Group, Problem, ExecComp

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

        model.add_subsystem(
            'p1',
            IndepVarComp(
                'x',
                12.0,
                lower=1.0,
                upper=100.0,
                ref=1.1,
                ref0=2.1,
                units='inch',
            ))
        model.add_subsystem(
            'p2',
            IndepVarComp(
                'y',
                1.0,
                lower=2.0,
                upper=200.0,
                ref=1.2,
                res_ref=2.2,
                units='ft',
            ))
        model.add_subsystem(
            'comp',
            ExecComp('z=x+y',
                     x={
                         'value': 0.0,
                         'units': 'inch'
                     },
                     y={
                         'value': 0.0,
                         'units': 'inch'
                     },
                     z={
                         'value': 0.0,
                         'units': 'inch'
                     }))
        model.connect('p1.x', 'comp.x')
        model.connect('p2.y', 'comp.y')

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

        inputs = prob.model.list_inputs(units=True)
        print(inputs)

        outputs = prob.model.list_outputs(implicit=False,
                                          values=True,
                                          units=True,
                                          shape=True,
                                          bounds=True,
                                          residuals=True,
                                          scaling=True,
                                          hierarchical=False,
                                          print_arrays=False)

        self.assertEqual(sorted(outputs), [
            ('comp.z', {
                'value': [24.],
                'resids': [0.],
                'units': 'inch',
                'shape': (1, ),
                'lower': None,
                'upper': None,
                'ref': 1.0,
                'ref0': 0.0,
                'res_ref': 1.0
            }),
            ('p1.x', {
                'value': [12.],
                'resids': [0.],
                'units': 'inch',
                'shape': (1, ),
                'lower': [1.],
                'upper': [100.],
                'ref': 1.1,
                'ref0': 2.1,
                'res_ref': 1.1
            }),
            ('p2.y', {
                'value': [1.],
                'resids': [0.],
                'units': 'ft',
                'shape': (1, ),
                'lower': [2.],
                'upper': [200.],
                'ref': 1.2,
                'ref0': 0.0,
                'res_ref': 2.2
            }),
        ])

        outputs = prob.model.list_outputs(implicit=False,
                                          values=True,
                                          units=True,
                                          shape=True,
                                          bounds=True,
                                          residuals=True,
                                          scaling=True,
                                          hierarchical=True,
                                          print_arrays=False)
Example #52
0
    def test_for_docs_array_list_vars_options(self):

        import numpy as np
        from openmdao.api import Problem, Group, IndepVarComp, ExplicitComponent

        class ArrayAdder(ExplicitComponent):
            """
            Just a simple component that has array inputs and outputs
            """
            def __init__(self, size):
                super(ArrayAdder, self).__init__()
                self.size = size

            def setup(self):
                self.add_input('x', val=np.zeros(self.size), units='inch')
                self.add_output('y', val=np.zeros(self.size), units='ft')

            def compute(self, inputs, outputs):
                outputs['y'] = inputs['x'] + 10.0

        size = 30

        prob = Problem()
        prob.model = Group()
        prob.model.add_subsystem('des_vars',
                                 IndepVarComp('x', np.ones(size),
                                              units='inch'),
                                 promotes=['x'])
        prob.model.add_subsystem('mult', ArrayAdder(size), promotes=['x', 'y'])

        prob.setup(check=False)
        prob['x'] = np.arange(size)
        prob.run_driver()

        prob.model.list_inputs(values=True,
                               units=True,
                               hierarchical=True,
                               print_arrays=True)

        np.set_printoptions(edgeitems=3,
                            infstr='inf',
                            linewidth=75,
                            nanstr='nan',
                            precision=8,
                            suppress=False,
                            threshold=1000,
                            formatter=None)

        prob.model.list_outputs(values=True,
                                implicit=False,
                                units=True,
                                shape=True,
                                bounds=True,
                                residuals=True,
                                scaling=True,
                                hierarchical=False,
                                print_arrays=True)

        prob.model.list_outputs(values=True,
                                implicit=False,
                                units=True,
                                shape=True,
                                bounds=True,
                                residuals=True,
                                scaling=True,
                                hierarchical=True,
                                print_arrays=True)
Example #53
0
class ErrorWrongAxis(Group):
    def setup(self):
        m = 3
        n = 4
        p = 5

        # Shape of the tensors
        ten_shape1 = (m, n, p)
        ten_shape2 = (m, n, p)

        # Number of elements in the tensors
        num_ten_elements1 = np.prod(ten_shape1)
        num_ten_elements2 = np.prod(ten_shape2)

        # Values for the two tensors
        ten1 = np.arange(num_ten_elements1).reshape(ten_shape1)
        ten2 = np.arange(num_ten_elements2,
                         2 * num_ten_elements2).reshape(ten_shape2)

        ten1 = self.declare_input('ten1', val=ten1)
        ten2 = self.declare_input('ten2', val=ten2)

        # Tensor-Tensor Dot Product specifying the first axis
        self.register_output('TenTenDotFirst', ot.dot(ten1, ten2, axis=1))


prob = Problem()
prob.model = ErrorWrongAxis()
prob.setup(force_alloc_complex=True)
prob.run_model()
Example #54
0
    def test_hierarchy_list_vars_options(self):

        prob = Problem()
        model = prob.model

        model.add_subsystem('pz', IndepVarComp('z', np.array([5.0, 2.0])))

        sub1 = model.add_subsystem('sub1', Group())
        sub2 = sub1.add_subsystem('sub2', Group())
        g1 = sub2.add_subsystem('g1', SubSellar())
        g2 = model.add_subsystem('g2', SubSellar())

        model.connect('pz.z', 'sub1.sub2.g1.z')
        model.connect('sub1.sub2.g1.y2', 'g2.x')
        model.connect('g2.y2', 'sub1.sub2.g1.x')

        model.nonlinear_solver = NewtonSolver()
        model.linear_solver = ScipyKrylov()
        model.nonlinear_solver.options['solve_subsystems'] = True
        model.nonlinear_solver.options['max_sub_solves'] = 0

        g1.nonlinear_solver = NewtonSolver()
        g1.linear_solver = LinearBlockGS()

        g2.nonlinear_solver = NewtonSolver()
        g2.linear_solver = ScipyKrylov()
        g2.linear_solver.precon = LinearBlockGS()
        g2.linear_solver.precon.options['maxiter'] = 2

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

        # logging inputs
        # out_stream - not hierarchical - extras - no print_arrays
        stream = cStringIO()
        prob.model.list_inputs(values=True,
                               units=True,
                               hierarchical=False,
                               print_arrays=False,
                               out_stream=stream)
        text = stream.getvalue()
        self.assertEqual(1, text.count("10 Input(s) in 'model'"))
        # make sure they are in the correct order
        self.assertTrue(
            text.find("sub1.sub2.g1.d1.z") < text.find('sub1.sub2.g1.d1.x') <
            text.find('sub1.sub2.g1.d1.y2') < text.find('sub1.sub2.g1.d2.z') <
            text.find('sub1.sub2.g1.d2.y1') < text.find('g2.d1.z') < text.find(
                'g2.d1.x') < text.find('g2.d1.y2') < text.find(
                    'g2.d2.z') < text.find('g2.d2.y1'))
        num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()])
        self.assertEqual(14, num_non_empty_lines)

        # out_stream - hierarchical - extras - no print_arrays
        stream = cStringIO()
        prob.model.list_inputs(values=True,
                               units=True,
                               hierarchical=True,
                               print_arrays=False,
                               out_stream=stream)
        text = stream.getvalue()
        self.assertEqual(1, text.count("10 Input(s) in 'model'"))
        num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()])
        self.assertEqual(23, num_non_empty_lines)
        self.assertEqual(1, text.count('top'))
        self.assertEqual(1, text.count('  sub1'))
        self.assertEqual(1, text.count('    sub2'))
        self.assertEqual(1, text.count('      g1'))
        self.assertEqual(1, text.count('        d1'))
        self.assertEqual(2, text.count('          z'))

        # logging outputs
        # out_stream - not hierarchical - extras - no print_arrays
        stream = cStringIO()
        prob.model.list_outputs(values=True,
                                units=True,
                                shape=True,
                                bounds=True,
                                residuals=True,
                                scaling=True,
                                hierarchical=False,
                                print_arrays=False,
                                out_stream=stream)
        text = stream.getvalue()
        self.assertEqual(text.count('5 Explicit Output'), 1)
        # make sure they are in the correct order
        self.assertTrue(text.find("pz.z") < text.find('sub1.sub2.g1.d1.y1') < text.find('sub1.sub2.g1.d2.y2') < \
                        text.find('g2.d1.y1') < text.find('g2.d2.y2'))
        num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()])
        self.assertEqual(11, num_non_empty_lines)

        # Hierarchical
        stream = cStringIO()
        prob.model.list_outputs(values=True,
                                units=True,
                                shape=True,
                                bounds=True,
                                residuals=True,
                                scaling=True,
                                hierarchical=True,
                                print_arrays=False,
                                out_stream=stream)
        text = stream.getvalue()
        self.assertEqual(text.count('top'), 1)
        self.assertEqual(text.count('          y1'), 1)
        self.assertEqual(text.count('  g2'), 1)
        num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()])
        self.assertEqual(num_non_empty_lines, 21)
Example #55
0
    def test_solve_linear_ksp_precon_left(self):
        """Solve implicit system with PETScKrylov using a preconditioner."""

        group = TestImplicitGroup(lnSolverClass=PETScKrylov)
        precon = group.linear_solver.precon = DirectSolver()
        group.linear_solver.options['precon_side'] = 'left'
        group.linear_solver.options['ksp_type'] = 'richardson'

        p = Problem(group)
        p.setup(vector_class=PETScVector, check=False)
        p.set_solver_print(level=0)

        # Conclude setup but don't run model.
        p.final_setup()

        d_inputs, d_outputs, d_residuals = group.get_linear_vectors()

        # forward
        d_residuals.set_const(1.0)
        d_outputs.set_const(0.0)
        group.run_linearize()
        group.run_solve_linear(['linear'], 'fwd')

        output = d_outputs._data
        assert_rel_error(self, output[1], group.expected_solution[0], 1e-15)
        assert_rel_error(self, output[5], group.expected_solution[1], 1e-15)

        # reverse
        d_outputs.set_const(1.0)
        d_residuals.set_const(0.0)
        group.run_linearize()
        group.run_solve_linear(['linear'], 'rev')

        output = d_residuals._data
        assert_rel_error(self, output[1], group.expected_solution[0], 3e-15)
        assert_rel_error(self, output[5], group.expected_solution[1], 3e-15)

        # test the direct solver and make sure KSP correctly recurses for _linearize
        precon = group.linear_solver.precon = DirectSolver()
        group.linear_solver.options['precon_side'] = 'left'
        group.linear_solver.options['ksp_type'] = 'richardson'

        p.setup(vector_class=PETScVector, check=False)

        # Conclude setup but don't run model.
        p.final_setup()

        d_inputs, d_outputs, d_residuals = group.get_linear_vectors()

        # forward
        d_residuals.set_const(1.0)
        d_outputs.set_const(0.0)
        group.linear_solver._linearize()
        group.run_solve_linear(['linear'], 'fwd')

        output = d_outputs._data
        assert_rel_error(self, output[1], group.expected_solution[0], 1e-15)
        assert_rel_error(self, output[5], group.expected_solution[1], 1e-15)

        # reverse
        d_outputs.set_const(1.0)
        d_residuals.set_const(0.0)
        group.linear_solver._linearize()
        group.run_solve_linear(['linear'], 'rev')

        output = d_residuals._data
        assert_rel_error(self, output[1], group.expected_solution[0], 3e-15)
        assert_rel_error(self, output[5], group.expected_solution[1], 3e-15)
Example #56
0
    def test_simple_list_vars_options(self):

        from openmdao.api import IndepVarComp, Group, Problem, ExecComp

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

        model.add_subsystem(
            'p1',
            IndepVarComp(
                'x',
                12.0,
                lower=1.0,
                upper=100.0,
                ref=1.1,
                ref0=2.1,
                units='inch',
            ))
        model.add_subsystem(
            'p2',
            IndepVarComp(
                'y',
                1.0,
                lower=2.0,
                upper=200.0,
                ref=1.2,
                res_ref=2.2,
                units='ft',
            ))
        model.add_subsystem(
            'comp',
            ExecComp('z=x+y',
                     x={
                         'value': 0.0,
                         'units': 'inch'
                     },
                     y={
                         'value': 0.0,
                         'units': 'inch'
                     },
                     z={
                         'value': 0.0,
                         'units': 'inch'
                     }))
        model.connect('p1.x', 'comp.x')
        model.connect('p2.y', 'comp.y')

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

        # list_inputs tests
        # Cannot do exact equality here because the units cause comp.y to be slightly different than 12.0
        stream = cStringIO()
        inputs = prob.model.list_inputs(units=True, out_stream=stream)
        tol = 1e-7
        for actual, expected in zip(sorted(inputs), [
            ('comp.x', {
                'value': [12.],
                'units': 'inch'
            }),
            ('comp.y', {
                'value': [12.],
                'units': 'inch'
            }),
        ]):
            self.assertEqual(expected[0], actual[0])
            self.assertEqual(expected[1]['units'], actual[1]['units'])
            assert_rel_error(self, expected[1]['value'], actual[1]['value'],
                             tol)
        text = stream.getvalue()
        self.assertEqual(1, text.count("Input(s) in 'model'"))
        self.assertEqual(1, text.count('varname'))
        self.assertEqual(1, text.count('value'))
        self.assertEqual(1, text.count('top'))
        self.assertEqual(1, text.count('  comp'))
        self.assertEqual(1, text.count('    x'))
        self.assertEqual(1, text.count('    y'))
        num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()])
        self.assertEqual(8, num_non_empty_lines)

        # list_outputs tests

        # list outputs for implicit comps - should get none
        outputs = prob.model.list_outputs(implicit=True,
                                          explicit=False,
                                          out_stream=None)
        self.assertEqual(outputs, [])

        # list outputs with out_stream - just check to see if it was logged to
        stream = cStringIO()
        outputs = prob.model.list_outputs(out_stream=stream)
        text = stream.getvalue()
        self.assertEqual(1, text.count('Explicit Output'))
        self.assertEqual(1, text.count('Implicit Output'))

        # list outputs with out_stream and all the optional display values True
        stream = cStringIO()
        outputs = prob.model.list_outputs(values=True,
                                          units=True,
                                          shape=True,
                                          bounds=True,
                                          residuals=True,
                                          scaling=True,
                                          hierarchical=False,
                                          print_arrays=False,
                                          out_stream=stream)

        self.assertEqual([
            ('comp.z', {
                'value': [24.],
                'resids': [0.],
                'units': 'inch',
                'shape': (1, ),
                'lower': None,
                'upper': None,
                'ref': 1.0,
                'ref0': 0.0,
                'res_ref': 1.0
            }),
            ('p1.x', {
                'value': [12.],
                'resids': [0.],
                'units': 'inch',
                'shape': (1, ),
                'lower': [1.],
                'upper': [100.],
                'ref': 1.1,
                'ref0': 2.1,
                'res_ref': 1.1
            }),
            ('p2.y', {
                'value': [1.],
                'resids': [0.],
                'units': 'ft',
                'shape': (1, ),
                'lower': [2.],
                'upper': [200.],
                'ref': 1.2,
                'ref0': 0.0,
                'res_ref': 2.2
            }),
        ], sorted(outputs))

        text = stream.getvalue()
        self.assertEqual(1, text.count('varname'))
        self.assertEqual(1, text.count('value'))
        self.assertEqual(1, text.count('resids'))
        self.assertEqual(1, text.count('units'))
        self.assertEqual(1, text.count('shape'))
        self.assertEqual(1, text.count('lower'))
        self.assertEqual(1, text.count('upper'))
        self.assertEqual(3, text.count('ref'))
        self.assertEqual(1, text.count('ref0'))
        self.assertEqual(1, text.count('res_ref'))
        self.assertEqual(1, text.count('p1.x'))
        self.assertEqual(1, text.count('p2.y'))
        self.assertEqual(1, text.count('comp.z'))
        num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()])
        self.assertEqual(9, num_non_empty_lines)
Example #57
0
    def test_brachistochrone_for_docs_runge_kutta_polynomial_controls(self):
        from openmdao.api import Problem, Group, ScipyOptimizeDriver, DirectSolver, SqliteRecorder
        from openmdao.utils.assert_utils import assert_rel_error
        import dymos as dm
        from dymos.examples.plotting import plot_results
        from dymos.examples.brachistochrone import BrachistochroneODE

        #
        # Initialize the Problem and the optimization driver
        #
        p = Problem(model=Group())
        p.driver = ScipyOptimizeDriver()
        p.driver.options['dynamic_simul_derivs'] = True

        #
        # Create a trajectory and add a phase to it
        #
        traj = p.model.add_subsystem('traj', dm.Trajectory())

        phase = traj.add_phase(
            'phase0',
            dm.Phase(ode_class=BrachistochroneODE,
                     transcription=dm.RungeKutta(num_segments=10)))

        #
        # Set the variables
        #
        phase.set_time_options(initial_bounds=(0, 0), duration_bounds=(.5, 10))
        phase.set_state_options('x', fix_initial=True)
        phase.set_state_options('y', fix_initial=True)
        phase.set_state_options('v', fix_initial=True)
        phase.add_polynomial_control('theta',
                                     units='deg',
                                     lower=0.01,
                                     upper=179.9,
                                     order=1)
        phase.add_design_parameter('g', units='m/s**2', opt=False, val=9.80665)

        #
        # Final state values are not optimization variables, so we must enforce final values
        # with boundary constraints, not simple bounds.
        #
        phase.add_boundary_constraint('x', loc='final', equals=10)
        phase.add_boundary_constraint('y', loc='final', equals=5)

        #
        # Minimize time at the end of the phase
        #
        phase.add_objective('time', loc='final', scaler=10)

        p.model.linear_solver = DirectSolver()

        #
        # Setup the Problem
        #
        p.setup()

        #
        # Set the initial values
        #
        p['traj.phase0.t_initial'] = 0.0
        p['traj.phase0.t_duration'] = 2.0

        p['traj.phase0.states:x'] = phase.interpolate(ys=[0, 10],
                                                      nodes='state_input')
        p['traj.phase0.states:y'] = phase.interpolate(ys=[10, 5],
                                                      nodes='state_input')
        p['traj.phase0.states:v'] = phase.interpolate(ys=[0, 9.9],
                                                      nodes='state_input')
        p['traj.phase0.polynomial_controls:theta'][:] = 5.0

        #
        # Solve for the optimal trajectory
        #
        p.run_driver()

        # Test the results
        assert_rel_error(self,
                         p.get_val('traj.phase0.timeseries.time')[-1],
                         1.8016,
                         tolerance=1.0E-3)

        # Generate the explicitly simulated trajectory
        exp_out = traj.simulate()

        plot_results(
            [('traj.phase0.timeseries.states:x',
              'traj.phase0.timeseries.states:y', 'x (m)', 'y (m)'),
             ('traj.phase0.timeseries.time',
              'traj.phase0.timeseries.polynomial_controls:theta', 'time (s)',
              'theta (deg)')],
            title=
            'Brachistochrone Solution\nRK4 Shooting and Polynomial Controls',
            p_sol=p,
            p_sim=exp_out)

        plt.show()
Example #58
0
    def test_list_auto_order(self):
        prob = Problem(self.root)
        prob.setup(check=False)

        self.assertEqual(self.root.list_auto_order(),
                         (['C1', 'C2', 'C3', 'C4'], []))
Example #59
0
    def test_simple_list_vars_options(self):
        from openmdao.api import Group, Problem, IndepVarComp

        class QuadraticComp(ImplicitComponent):
            """
            A Simple Implicit Component representing a Quadratic Equation.

            R(a, b, c, x) = ax^2 + bx + c

            Solution via Quadratic Formula:
            x = (-b + sqrt(b^2 - 4ac)) / 2a
            """

            def setup(self):
                self.add_input('a', val=1., units='ft')
                self.add_input('b', val=1., units='inch')
                self.add_input('c', val=1., units='ft')
                self.add_output('x', val=0.,
                                lower=1.0, upper=100.0,
                                ref=1.1, ref0=2.1,
                                units='inch')

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

            def apply_nonlinear(self, inputs, outputs, residuals):
                a = inputs['a']
                b = inputs['b']
                c = inputs['c']
                x = outputs['x']
                residuals['x'] = a * x ** 2 + b * x + c

            def solve_nonlinear(self, inputs, outputs):
                a = inputs['a']
                b = inputs['b']
                c = inputs['c']
                outputs['x'] = (-b + (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)

        group = Group()

        comp1 = group.add_subsystem('comp1', IndepVarComp())
        comp1.add_output('a', 1.0, units='ft')
        comp1.add_output('b', 1.0, units='inch')
        comp1.add_output('c', 1.0, units='ft')

        sub = group.add_subsystem('sub', Group())
        sub.add_subsystem('comp2', QuadraticComp())
        sub.add_subsystem('comp3', QuadraticComp())

        group.connect('comp1.a', 'sub.comp2.a')
        group.connect('comp1.b', 'sub.comp2.b')
        group.connect('comp1.c', 'sub.comp2.c')

        group.connect('comp1.a', 'sub.comp3.a')
        group.connect('comp1.b', 'sub.comp3.b')
        group.connect('comp1.c', 'sub.comp3.c')

        global prob
        prob = Problem(model=group)
        prob.setup()

        prob['comp1.a'] = 1.
        prob['comp1.b'] = -4.
        prob['comp1.c'] = 3.
        prob.run_model()

        # list_inputs test
        stream = cStringIO()
        inputs = prob.model.list_inputs(values=False, out_stream=stream)
        text = stream.getvalue()
        self.assertEqual(sorted(inputs), [
            ('sub.comp2.a', {}),
            ('sub.comp2.b', {}),
            ('sub.comp2.c', {}),
            ('sub.comp3.a', {}),
            ('sub.comp3.b', {}),
            ('sub.comp3.c', {}),
        ])
        self.assertEqual(1, text.count("6 Input(s) in 'model'"))
        self.assertEqual(1, text.count("top"))
        self.assertEqual(1, text.count("  sub"))
        self.assertEqual(1, text.count("    comp2"))
        self.assertEqual(2, text.count("      a"))
        num_non_empty_lines = sum([1 for s in text.splitlines() if s.strip()])
        self.assertEqual(num_non_empty_lines, 14)

        # list_outputs tests
        # list implicit outputs
        outputs = prob.model.list_outputs(explicit=False, out_stream=None)
        text = stream.getvalue()
        self.assertEqual(sorted(outputs), [
            ('sub.comp2.x', {'value': [3.]}),
            ('sub.comp3.x', {'value': [3.]})
        ])
        # list explicit outputs
        stream = cStringIO()
        outputs = prob.model.list_outputs(implicit=False, out_stream=None)
        self.assertEqual(sorted(outputs), [
            ('comp1.a', {'value': [1.]}),
            ('comp1.b', {'value': [-4.]}),
            ('comp1.c', {'value': [3.]}),
        ])
class FlightConditionsTestCase(unittest.TestCase):
    def setUp(self):
        self.prob = Problem()

        des_vars = self.prob.model.add_subsystem('des_vars',
                                                 IndepVarComp(),
                                                 promotes=['*'])
        des_vars.add_output('MN', 0.0)
        des_vars.add_output('alt', 0.0, units="ft")
        des_vars.add_output('dTs', 0.0, units='degR')

        self.prob.model.add_subsystem('fc', FlightConditions())

        self.prob.model.connect('MN', 'fc.MN')
        self.prob.model.connect('alt', 'fc.alt')
        self.prob.model.connect('dTs', 'fc.dTs')

        self.prob.setup(check=False)
        self.prob.set_solver_print(level=-1)

        # from openmdao.api import view_model
        # view_model(self.prob)
        # exit()

    def test_case1(self):

        # 6 cases to check against
        for i, data in enumerate(ref_data):
            self.prob['alt'] = data[h_map['alt']]
            self.prob['MN'] = data[h_map['MN']]
            self.prob['dTs'] = data[h_map['dTs']]

            if self.prob['MN'] < 1e-10:
                self.prob['MN'] += 1e-6

            # print(data[h_map['alt']], data[h_map['MN']], data[h_map['dTs']])

            # from openmdao.api import view_model
            # view_model(self.prob)
            # exit()

            self.prob.run_model()

            # check outputs
            Pt = data[h_map['Pt']]
            Pt_c = self.prob['fc.Fl_O:tot:P']

            Ps = data[h_map['Ps']]
            Ps_c = self.prob['fc.Fl_O:stat:P']

            Tt = data[h_map['Tt']]
            Tt_c = self.prob['fc.Fl_O:tot:T']

            Ts = data[h_map['Ts']]
            Ts_c = self.prob['fc.Fl_O:stat:T']

            # print('alt, MN, dts: ', self.prob['alt'], self.prob['MN'], self.prob['dTs'])
            # print('Pt:', Pt_c, Pt)
            # print('Ps:', Ps_c, Ps)
            # print('Tt:', Tt_c, Tt)
            # print('Ts:', Ts_c, Ts)
            # print()

            tol = 1e-4
            assert_rel_error(self, Pt_c, Pt, tol)
            assert_rel_error(self, Ps_c, Ps, tol)
            assert_rel_error(self, Tt_c, Tt, tol)
            assert_rel_error(self, Ps_c, Ps, tol)

            check_element_partials(self, self.prob, depth=3)