コード例 #1
0
    def test_partials(self):
        self.p.setup(force_alloc_complex=True)

        v0 = 100.0
        gam0 = np.radians(30.0)
        t_duration = 10.0

        phase = self.p.model.phase0

        self.p['phase0.t_initial'] = 0.0
        self.p['phase0.t_duration'] = t_duration

        self.p['phase0.states:r'] = phase.interpolate(
            ys=[0, v0 * np.cos(gam0) * t_duration], nodes='state_disc')
        self.p['phase0.states:h'] = phase.interpolate(ys=[0, 0],
                                                      nodes='state_input')
        self.p['phase0.states:v'] = phase.interpolate(ys=[v0, v0],
                                                      nodes='state_input')
        self.p['phase0.states:gam'] = phase.interpolate(ys=[gam0, -gam0],
                                                        nodes='state_input')

        self.p.run_model()

        cpd = self.p.check_partials(compact_print=True, method='cs')

        assert_check_partials(cpd)
コード例 #2
0
ファイル: test_rk_stepsize_comp.py プロジェクト: daoos/dymos
    def test_rk_stepsize_comp_nonuniform(self):
        p = om.Problem(model=om.Group())

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

        ivc.add_output('t_duration', shape=(1, ), units='s')

        p.model.add_subsystem(
            'c',
            RungeKuttaStepsizeComp(num_segments=4,
                                   seg_rel_lengths=[1, 1, 0.5, 0.25],
                                   time_units='s'))

        p.model.connect('t_duration', 'c.t_duration')

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

        p['t_duration'] = 5.5

        np.set_printoptions(linewidth=1024)

        p.run_model()

        expected = np.array([2.0, 2.0, 1.0, 0.5])

        assert_near_equal(p.get_val('c.h'), expected, tolerance=1.0E-9)

        cpd = p.check_partials(method='cs', out_stream=None)
        assert_check_partials(cpd)
コード例 #3
0
    def test_brachistochrone_partials(self):
        import numpy as np
        import openmdao.api as om
        from dymos.utils.testing_utils import assert_check_partials
        from dymos.examples.brachistochrone.brachistochrone_ode import BrachistochroneODE

        num_nodes = 5

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

        ivc = p.model.add_subsystem('vars', om.IndepVarComp())
        ivc.add_output('v', shape=(num_nodes,), units='m/s')
        ivc.add_output('theta', shape=(num_nodes,), units='deg')

        p.model.add_subsystem('ode', BrachistochroneODE(num_nodes=num_nodes, static_gravity=True))

        p.model.connect('vars.v', 'ode.v')
        p.model.connect('vars.theta', 'ode.theta')

        p.setup(force_alloc_complex=True)

        p.set_val('vars.v', 10*np.random.random(num_nodes))
        p.set_val('vars.theta', 10*np.random.uniform(1, 179, num_nodes))

        p.run_model()
        cpd = p.check_partials(method='cs', compact_print=True)
        assert_check_partials(cpd)
コード例 #4
0
    def test_state_interp_comp_lobatto_vectorized_different_orders(self):

        segends = np.array([0.0, 3.0, 10.0])

        gd = GridData(num_segments=2,
                      transcription_order=[3, 5],
                      segment_ends=segends,
                      transcription='gauss-lobatto')

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

        states = {'pos': {'units': 'm', 'shape': (2,)}}

        X_ivc = om.IndepVarComp()
        p.model.add_subsystem('X_ivc', X_ivc, promotes=['state_disc:pos'])

        X_ivc.add_output('state_disc:pos',
                         val=np.zeros((gd.subset_num_nodes['state_disc'], 2)), units='m')

        F_ivc = om.IndepVarComp()
        p.model.add_subsystem('F_ivc', F_ivc, promotes=['staterate_disc:pos'])

        F_ivc.add_output('staterate_disc:pos',
                         val=np.zeros((gd.subset_num_nodes['state_disc'], 2)),
                         units='m/s')

        dt_dtau_ivc = om.IndepVarComp()
        p.model.add_subsystem('dt_dstau_ivc', dt_dtau_ivc, promotes=['dt_dstau'])

        dt_dtau_ivc.add_output('dt_dstau', val=0.0*np.zeros(gd.subset_num_nodes['col']), units='s')

        p.model.add_subsystem('state_interp_comp',
                              subsys=StateInterpComp(transcription='gauss-lobatto',
                                                     grid_data=gd,
                                                     state_options=states,
                                                     time_units='s'))

        p.model.connect('state_disc:pos', 'state_interp_comp.state_disc:pos')
        p.model.connect('staterate_disc:pos', 'state_interp_comp.staterate_disc:pos')
        p.model.connect('dt_dstau', 'state_interp_comp.dt_dstau')

        p.setup(force_alloc_complex=True)

        segends_disc = np.array((0, 3, 3, 6.5, 10))

        p['state_disc:pos'][:, 0] = [x(t) for t in segends_disc]  # [0.0, 25.0, 25.0, 100.0]
        p['staterate_disc:pos'][:, 0] = [f_x(t) for t in segends_disc]

        p['state_disc:pos'][:, 1] = [v(t) for t in segends_disc]
        p['staterate_disc:pos'][:, 1] = [f_v(t) for t in segends_disc]

        p['dt_dstau'] = [3.0/2., 7.0/2, 7.0/2]

        p.run_model()

        cpd = p.check_partials(compact_print=True, method='cs')
        assert_check_partials(cpd, atol=5.0E-5)
コード例 #5
0
 def test_partials(self):
     n = 10
     p = om.Problem(model=om.Group())
     p.model.add_subsystem(name='kappa_comp', subsys=KappaComp(num_nodes=n))
     p.setup()
     p.set_val('kappa_comp.mach', np.linspace(0, 1.8, n))
     p.run_model()
     cpd = p.check_partials(compact_print=False, out_stream=None)
     assert_check_partials(cpd, atol=1.0E-5, rtol=1.0E-4)
コード例 #6
0
ファイル: test_rk_k_comp.py プロジェクト: wright/dymos
    def test_rk_k_comp_rk4_scalar(self):
        state_options = {'y': {'shape': (1, ), 'units': 'm'}}

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

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

        ivc.add_output('h', shape=(4, ), units='s')
        ivc.add_output('f:y', shape=(4, 4, 1), units='m/s')

        p.model.add_subsystem(
            'c',
            RungeKuttaKComp(num_segments=4,
                            method='RK4',
                            state_options=state_options,
                            time_units='s'))

        p.model.connect('f:y', 'c.f:y')
        p.model.connect('h', 'c.h')

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

        p['h'] = [0.5, 0.5, 0.5, 0.5]
        p['f:y'] = np.array([[[1.50000000], [1.81250000], [1.89062500],
                              [2.19531250]],
                             [[2.17513021], [2.40641276], [2.46423340],
                              [2.65724691]],
                             [[2.63960266], [2.73700333], [2.76135349],
                              [2.77027941]],
                             [[2.75681897], [2.63352371], [2.60269990],
                              [2.30816892]]])

        np.set_printoptions(linewidth=1024)

        p.run_model()

        expected = np.array([[[0.75000000], [0.90625000], [0.94531250],
                              [1.09765625]],
                             [[1.087565104166667], [1.203206380208333],
                              [1.232116699218750], [1.328623453776042]],
                             [[1.319801330566406], [1.368501663208008],
                              [1.380676746368408], [1.385139703750610]],
                             [[1.378409485022227], [1.316761856277783],
                              [1.301349949091673], [1.154084459568063]]])

        assert_near_equal(p.get_val('c.k:y'), expected, tolerance=1.0E-9)

        p.model.list_outputs(print_arrays=True)

        cpd = p.check_partials(method='cs', out_stream=None)
        assert_check_partials(cpd)
コード例 #7
0
    def test_rk_state_advance_comp_rk4_matrix(self):
        state_options = {'y': {'shape': (2, 2), 'units': 'm'}}

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

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

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

        p.model.add_subsystem(
            'c',
            RungeKuttaStatePredictComp(num_segments=1,
                                       method='RK4',
                                       state_options=state_options))

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

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

        p['y0'] = [[[0.5, 1.425130208333333],
                    [2.639602661132812, 4.006818970044454]]]

        p['k:y'] = np.array([[[[0.75, 1.087565104166667],
                               [1.319801330566406, 1.378409485022227]],
                              [[0.90625, 1.203206380208333],
                               [1.368501663208008, 1.316761856277783]],
                              [[0.9453125, 1.23211669921875],
                               [1.380676746368408, 1.301349949091673]],
                              [[1.09765625, 1.328623453776042],
                               [1.385139703750610, 1.154084459568063]]]])

        p.run_model()

        p.model.list_outputs(print_arrays=True)

        assert_near_equal(p.get_val('c.predicted_states:y'),
                          [[[0.5, 1.425130208333333],
                            [2.639602661132812, 4.006818970044454]],
                           [[0.875, 1.968912760416667],
                            [3.299503326416016, 4.696023712555567]],
                           [[0.953125, 2.0267333984375],
                            [3.323853492736816, 4.665199898183346]],
                           [[1.4453125, 2.657246907552083],
                            [4.020279407501221, 5.308168919136127]]])

        np.set_printoptions(linewidth=1024)
        cpd = p.check_partials(method='cs', out_stream=None)
        assert_check_partials(cpd)
コード例 #8
0
    def test_partials(self):
        np.set_printoptions(linewidth=1024, edgeitems=1e1000)

        p = self.make_prob('radau-ps', n_segs=2, order=5, compressed=False)
        cpd = p.check_partials(compact_print=True, method='fd')
        del cpd['state_indep']
        assert_check_partials(cpd)

        p = self.make_prob('radau-ps', n_segs=2, order=5, compressed=True)
        cpd = p.check_partials(compact_print=True, method='fd')
        del cpd['state_indep']
        assert_check_partials(cpd)

        p = self.make_prob('gauss-lobatto',
                           n_segs=3,
                           order=5,
                           compressed=False)
        cpd = p.check_partials(compact_print=True, method='fd')
        del cpd['state_indep']
        assert_check_partials(cpd)

        p = self.make_prob('gauss-lobatto', n_segs=4, order=3, compressed=True)
        cpd = p.check_partials(compact_print=True, method='fd')
        del cpd['state_indep']
        assert_check_partials(cpd)
コード例 #9
0
    def test_robertson_problem_for_docs(self):

        import openmdao.api as om
        from dymos.utils.testing_utils import assert_check_partials
        from openmdao.utils.assert_utils import assert_near_equal
        import matplotlib.pyplot as plt

        num_nodes = 3

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

        p.model.add_subsystem('ode', RobertsonODE(num_nodes=num_nodes), promotes=['*'])

        p.setup(force_alloc_complex=True)

        p.set_val('x', [10., 100., 1000.])
        p.set_val('y', [1, 0.1, 0.01])
        p.set_val('z', [1., 2., 3.])

        p.run_model()
        cpd = p.check_partials(method='cs', compact_print=True)

        assert_check_partials(cpd)

        assert_near_equal(p.get_val('xdot'), [9999.6, 1996., 260.])
        assert_near_equal(p.get_val('ydot'), [-3.00099996E7, -3.01996E5, -3.26E3])
        assert_near_equal(p.get_val('zdot'), [3.0E7, 3.0E5, 3.0E3])

        # just set up the problem, test it elsewhere
        p = self.robertson_problem(t_final=40)

        p.run_model()

        p_sim = p.model.traj.simulate(method='LSODA')

        assert_near_equal(p_sim.get_val('traj.phase0.timeseries.states:x0')[-1], 0.71583161, tolerance=1E-5)
        assert_near_equal(p_sim.get_val('traj.phase0.timeseries.states:y0')[-1], 9.18571144e-06, tolerance=1E-1)
        assert_near_equal(p_sim.get_val('traj.phase0.timeseries.states:z0')[-1], 0.2841592, tolerance=1E-5)

        t_sim = p_sim.get_val('traj.phase0.timeseries.time')

        states = ['x0', 'y0', 'z0']
        fig, axes = plt.subplots(len(states), 1)
        for i, state in enumerate(states):
            axes[i].plot(t_sim, p_sim.get_val(f'traj.phase0.timeseries.states:{state}'), '-')
            axes[i].set_ylabel(state[0])
        axes[-1].set_xlabel('time (s)')
        plt.tight_layout()
        plt.show()
コード例 #10
0
    def test_rk_state_predict_comp_rk4_3seg(self):
        num_seg = 3
        state_options = {'y': {'shape': (1, ), 'units': 'm'}}

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

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

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

        p.model.add_subsystem(
            'c',
            RungeKuttaStatePredictComp(num_segments=num_seg,
                                       method='RK4',
                                       state_options=state_options))

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

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

        p['y0'] = np.array([[0.5, 1.425130208333333, 2.639602661132812]]).T
        p['k:y'] = np.array([[[0.75000000], [0.90625000], [0.94531250],
                              [1.09765625]],
                             [[1.087565104166667], [1.203206380208333],
                              [1.232116699218750], [1.328623453776042]],
                             [[1.319801330566406], [1.368501663208008],
                              [1.380676746368408], [1.385139703750610]]])

        p.run_model()

        p.model.list_outputs(print_arrays=True)

        expected = np.array([[0.50000000], [0.87500000], [0.953125],
                             [1.4453125], [1.425130208333333],
                             [1.968912760416667], [2.026733398437500],
                             [2.657246907552083], [2.639602661132812],
                             [3.299503326416016], [3.323853492736816],
                             [4.020279407501221]])

        assert_near_equal(p.get_val('c.predicted_states:y'), expected)

        cpd = p.check_partials(method='cs', out_stream=None)
        assert_check_partials(cpd)
コード例 #11
0
    def test_rk_state_advance_comp_rk4_scalar(self):
        state_options = {'y': {'shape': (1, ), 'units': 'm'}}

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

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

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

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

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

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

        p['y0'] = np.array(
            [[0.5, 1.425130208333333, 2.639602661132812, 4.006818970044454]]).T
        p['k:y'] = np.array([[[0.75000000], [0.90625000], [0.94531250],
                              [1.09765625]],
                             [[1.08756510], [1.20320638], [1.23211670],
                              [1.32862345]],
                             [[1.31980133], [1.36850166], [1.38067675],
                              [1.38513970]],
                             [[1.37840949], [1.31676186], [1.30134995],
                              [1.15408446]]])

        p.run_model()

        assert_near_equal(p.get_val('c.final_states:y'),
                          np.array([[1.425130208333333], [2.639602661132812],
                                    [4.006818970044454], [5.301605229265987]]),
                          tolerance=1.0E-9)

        np.set_printoptions(linewidth=1024)
        cpd = p.check_partials(method='cs', out_stream=None)
        assert_check_partials(cpd)
コード例 #12
0
ファイル: test_dynamic_pressure.py プロジェクト: Rlmuniz/toa
    def test_partials(self):
        n = 5
        p = om.Problem()
        tas = np.linspace(0, 100, n)

        ivc = p.model.add_subsystem('ivc',
                                    subsys=om.IndepVarComp(),
                                    promotes_outputs=['*'])
        ivc.add_output(name='tas', val=tas, units='m/s')
        ivc.add_output(name='h', val=0.0, units='m')
        p.model.add_subsystem('atmos', subsys=USatm1976Comp(num_nodes=1))
        p.model.add_subsystem(name='dyn_press',
                              subsys=DynamicPressureComp(num_nodes=n))

        p.model.connect('tas', 'dyn_press.tas')
        p.model.connect('h', 'atmos.h')
        p.model.connect('atmos.rho', 'dyn_press.rho')
        p.setup()
        p.run_model()

        cpd = p.check_partials(compact_print=False, out_stream=None)
        assert_check_partials(cpd, atol=1.0E-5, rtol=1.0E-4)
コード例 #13
0
ファイル: test_cla_comp.py プロジェクト: wright/dymos
    def test_partials(self):

        n = 10

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

        ivc = om.IndepVarComp()

        ivc.add_output(name='mach', units=None, val=np.zeros(n))

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

        p.model.add_subsystem(name='cla_comp', subsys=CLaComp(num_nodes=n))

        p.model.connect('mach', 'cla_comp.mach')

        p.setup()

        p['mach'] = np.linspace(0, 1.8, n)

        p.run_model()

        cpd = p.check_partials(compact_print=False, out_stream=None)
        assert_check_partials(cpd, atol=1.0E-3, rtol=1.0E-4)
コード例 #14
0
    def test_control_interp_matrix_2x2(self, transcription='gauss-lobatto', compressed=True):

        segends = np.array([0.0, 3.0, 10.0])

        gd = GridData(num_segments=2,
                      transcription_order=5,
                      segment_ends=segends,
                      transcription=transcription,
                      compressed=compressed)

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

        controls = {'a': {'units': 'm', 'shape': (2, 2), 'dynamic': True}}

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

        ivc.add_output('controls:a', val=np.zeros((gd.subset_num_nodes['control_input'], 2, 2)),
                       units='m')
        ivc.add_output('t_initial', val=0.0, units='s')
        ivc.add_output('t_duration', val=10.0, units='s')

        p.model.add_subsystem('time_comp',
                              subsys=TimeComp(num_nodes=gd.num_nodes, node_ptau=gd.node_ptau,
                                              node_dptau_dstau=gd.node_dptau_dstau, units='s'),
                              promotes_inputs=['t_initial', 't_duration'],
                              promotes_outputs=['time', 'dt_dstau'])

        p.model.add_subsystem('control_interp_comp',
                              subsys=ControlInterpComp(grid_data=gd,
                                                       control_options=controls,
                                                       time_units='s'),
                              promotes_inputs=['controls:*'])

        p.model.connect('dt_dstau', 'control_interp_comp.dt_dstau')

        p.setup(force_alloc_complex=True)

        p['t_initial'] = 0.0
        p['t_duration'] = 3.0

        p.run_model()

        t = p['time']
        control_input_idxs = gd.subset_node_indices['control_input']
        p['controls:a'][:, 0, 0] = f_a(t[control_input_idxs])
        p['controls:a'][:, 0, 1] = f_b(t[control_input_idxs])
        p['controls:a'][:, 1, 0] = f_c(t[control_input_idxs])
        p['controls:a'][:, 1, 1] = f_d(t[control_input_idxs])

        p.run_model()

        a0_value_expected = f_a(t)
        a1_value_expected = f_b(t)
        a2_value_expected = f_c(t)
        a3_value_expected = f_d(t)

        a0_rate_expected = f1_a(t)
        a1_rate_expected = f1_b(t)
        a2_rate_expected = f1_c(t)
        a3_rate_expected = f1_d(t)

        a0_rate2_expected = f2_a(t)
        a1_rate2_expected = f2_b(t)
        a2_rate2_expected = f2_c(t)
        a3_rate2_expected = f2_d(t)

        assert_almost_equal(p['control_interp_comp.control_values:a'][:, 0, 0],
                            a0_value_expected)

        assert_almost_equal(p['control_interp_comp.control_values:a'][:, 0, 1],
                            a1_value_expected)

        assert_almost_equal(p['control_interp_comp.control_values:a'][:, 1, 0],
                            a2_value_expected)

        assert_almost_equal(p['control_interp_comp.control_values:a'][:, 1, 1],
                            a3_value_expected)

        assert_almost_equal(p['control_interp_comp.control_rates:a_rate'][:, 0, 0],
                            a0_rate_expected)

        assert_almost_equal(p['control_interp_comp.control_rates:a_rate'][:, 0, 1],
                            a1_rate_expected)

        assert_almost_equal(p['control_interp_comp.control_rates:a_rate'][:, 1, 0],
                            a2_rate_expected)

        assert_almost_equal(p['control_interp_comp.control_rates:a_rate'][:, 1, 1],
                            a3_rate_expected)

        assert_almost_equal(p['control_interp_comp.control_rates:a_rate2'][:, 0, 0],
                            a0_rate2_expected)

        assert_almost_equal(p['control_interp_comp.control_rates:a_rate2'][:, 0, 1],
                            a1_rate2_expected)

        assert_almost_equal(p['control_interp_comp.control_rates:a_rate2'][:, 1, 0],
                            a2_rate2_expected)

        assert_almost_equal(p['control_interp_comp.control_rates:a_rate2'][:, 1, 1],
                            a3_rate2_expected)

        with np.printoptions(linewidth=100000, edgeitems=100000):
            cpd = p.check_partials(compact_print=True, method='cs')

        assert_check_partials(cpd)
コード例 #15
0
 def test_partials(self):
     np.set_printoptions(linewidth=1024, edgeitems=1000)
     cpd = self.p.check_partials(out_stream=None)
     assert_check_partials(cpd)
コード例 #16
0
 def test_partials(self):
     np.set_printoptions(linewidth=1024, edgeitems=1000)
     cpd = self.p.check_partials(method='cs')
     assert_check_partials(cpd)
コード例 #17
0
    def test_continuity_comp_connected_scalar_no_iteration_fwd(self):
        num_seg = 4
        state_options = {
            'y': {
                'shape': (1, ),
                'units': 'm',
                'targets': ['y'],
                'defect_scaler': None,
                'defect_ref': None,
                'lower': None,
                'upper': None,
                'connected_initial': True
            }
        }

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

        ivc = p.model.add_subsystem('ivc',
                                    om.IndepVarComp(),
                                    promotes_outputs=['*'])
        ivc.add_output('initial_states:y', units='m', shape=(1, 1))

        p.model.add_subsystem('continuity_comp',
                              RungeKuttaStateContinuityComp(
                                  num_segments=num_seg,
                                  state_options=state_options),
                              promotes_inputs=['*'],
                              promotes_outputs=['*'])

        p.model.nonlinear_solver = om.NonlinearRunOnce()
        p.model.linear_solver = om.DirectSolver()

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

        p['initial_states:y'] = 0.5

        p['states:y'] = np.array([[0.50000000], [1.425130208333333],
                                  [2.639602661132812], [4.006818970044454],
                                  [5.301605229265987]])

        p['state_integrals:y'] = np.array([[1.0], [1.0], [1.0], [1.0]])

        p.run_model()
        p.model.run_apply_nonlinear()

        # Test that the residuals of the states are the expected values
        outputs = p.model.list_outputs(print_arrays=True,
                                       residuals=True,
                                       out_stream=None)

        y_f = p['states:y'][1:, ...]
        y_i = p['states:y'][:-1, ...]
        dy_given = y_f - y_i
        dy_computed = p['state_integrals:y']

        expected_resids = np.zeros((num_seg + 1, 1))
        expected_resids[1:, ...] = dy_given - dy_computed

        op_dict = dict([op for op in outputs])
        assert_near_equal(op_dict['continuity_comp.states:y']['resids'],
                          expected_resids)

        # Test the partials
        cpd = p.check_partials(method='cs')
        assert_check_partials(cpd)
コード例 #18
0
ファイル: test_rk_k_iter_group.py プロジェクト: wright/dymos
    def test_rk4_scalar_nonlinearblockgs(self):
        num_seg = 4
        num_stages = 4
        state_options = {'y': {'shape': (1, ), 'units': 'm', 'targets': ['y']}}

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

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

        ivc.add_output('initial_states_per_seg:y',
                       shape=(num_seg, 1),
                       units='m')
        ivc.add_output('h', shape=(num_seg, 1), units='s')
        ivc.add_output('t', shape=(num_seg * num_stages, 1), units='s')

        p.model.add_subsystem(
            'k_iter_group',
            RungeKuttaKIterGroup(num_segments=num_seg,
                                 method='RK4',
                                 state_options=state_options,
                                 time_units='s',
                                 ode_class=TestODE,
                                 ode_init_kwargs={},
                                 solver_class=om.NonlinearBlockGS,
                                 solver_options={'iprint': 2}))

        p.model.connect('t', 'k_iter_group.ode.t')
        p.model.connect('h', 'k_iter_group.h')
        p.model.connect('initial_states_per_seg:y',
                        'k_iter_group.initial_states_per_seg:y')

        src_idxs = np.arange(16, dtype=int).reshape((num_seg, num_stages, 1))
        p.model.connect('k_iter_group.ode.ydot',
                        'k_iter_group.k_comp.f:y',
                        src_indices=src_idxs,
                        flat_src_indices=True)

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

        p['t'] = np.array([[
            0.00, 0.25, 0.25, 0.50, 0.50, 0.75, 0.75, 1.00, 1.00, 1.25, 1.25,
            1.50, 1.50, 1.75, 1.75, 2.00
        ]]).T

        p['h'] = np.array([[0.5, 0.5, 0.5, 0.5]]).T

        p['initial_states_per_seg:y'] = np.array([[0.50000000],
                                                  [1.425130208333333],
                                                  [2.639602661132812],
                                                  [4.006818970044454]])

        # Start k with a terrible guess
        p['k_iter_group.k_comp.k:y'][...] = 0

        p.run_model()

        # Test that the residuals of k are zero (we started k at the expected converged value)
        outputs = p.model.list_outputs(print_arrays=True,
                                       residuals=True,
                                       out_stream=False)
        op_dict = dict([op for op in outputs])
        assert_almost_equal(op_dict['k_iter_group.k_comp.k:y']['resids'], 0.0)

        # Test the partials
        cpd = p.check_partials(method='cs', out_stream=None)
        assert_check_partials(cpd)
コード例 #19
0
    def test_polynomial_control_group_scalar_gl(self):
        transcription = 'gauss-lobatto'
        compressed = True

        segends = np.array([0.0, 3.0, 10.0])

        gd = GridData(num_segments=2,
                      transcription_order=5,
                      segment_ends=segends,
                      transcription=transcription,
                      compressed=compressed)

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

        controls = {
            'a': PolynomialControlOptionsDictionary(),
            'b': PolynomialControlOptionsDictionary()
        }

        controls['a']['units'] = 'm'
        controls['a']['order'] = 3
        controls['a']['shape'] = (1, )
        controls['a']['opt'] = True

        controls['b']['units'] = 'm'
        controls['b']['order'] = 3
        controls['b']['shape'] = (1, )
        controls['b']['opt'] = True

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

        ivc.add_output('t_initial', val=0.0, units='s')
        ivc.add_output('t_duration', val=10.0, units='s')

        p.model.add_subsystem('time_comp',
                              subsys=TimeComp(
                                  num_nodes=gd.num_nodes,
                                  node_ptau=gd.node_ptau,
                                  node_dptau_dstau=gd.node_dptau_dstau,
                                  units='s'),
                              promotes_inputs=['t_initial', 't_duration'],
                              promotes_outputs=['time', 'dt_dstau'])

        polynomial_control_group = PolynomialControlGroup(
            grid_data=gd, polynomial_control_options=controls, time_units='s')

        p.model.add_subsystem('polynomial_control_group',
                              subsys=polynomial_control_group,
                              promotes_inputs=['*'],
                              promotes_outputs=['*'])

        p.setup(force_alloc_complex=True)

        p['t_initial'] = 0.0
        p['t_duration'] = 3.0

        p.run_model()

        control_nodes_ptau, _ = lgl(controls['a']['order'] + 1)

        t_control_input = p['t_initial'] + 0.5 * (control_nodes_ptau +
                                                  1) * p['t_duration']
        t_all = p['time']

        p['polynomial_controls:a'][:, 0] = f_a(t_control_input)
        p['polynomial_controls:b'][:, 0] = f_b(t_control_input)

        p.run_model()

        a_value_expected = f_a(t_all)
        b_value_expected = f_b(t_all)

        a_rate_expected = f1_a(t_all)
        b_rate_expected = f1_b(t_all)

        a_rate2_expected = f2_a(t_all)
        b_rate2_expected = f2_b(t_all)

        assert_almost_equal(p['polynomial_control_values:a'],
                            np.atleast_2d(a_value_expected).T)

        assert_almost_equal(p['polynomial_control_values:b'],
                            np.atleast_2d(b_value_expected).T)

        assert_almost_equal(p['polynomial_control_rates:a_rate'],
                            np.atleast_2d(a_rate_expected).T)

        assert_almost_equal(p['polynomial_control_rates:b_rate'],
                            np.atleast_2d(b_rate_expected).T)

        assert_almost_equal(p['polynomial_control_rates:a_rate2'],
                            np.atleast_2d(a_rate2_expected).T)

        assert_almost_equal(p['polynomial_control_rates:b_rate2'],
                            np.atleast_2d(b_rate2_expected).T)

        np.set_printoptions(linewidth=1024)
        cpd = p.check_partials(compact_print=False,
                               out_stream=None,
                               method='cs')
        assert_check_partials(cpd)
コード例 #20
0
ファイル: test_propulsion_group.py プロジェクト: wright/dymos
 def test_partials(self):
     cpd = self.p.check_partials(method='cs', out_stream=None)
     assert_check_partials(cpd)
コード例 #21
0
    def test_state_interp_comp_lobatto(self):

        segends = np.array([0.0, 3.0, 10.0])

        gd = GridData(num_segments=2,
                      transcription_order=3,
                      segment_ends=segends,
                      transcription='gauss-lobatto')

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

        states = {'x': {'units': 'm', 'shape': (1,)},
                  'v': {'units': 'm/s', 'shape': (1,)}}

        X_ivc = om.IndepVarComp()
        p.model.add_subsystem('X_ivc', X_ivc, promotes=['state_disc:x', 'state_disc:v'])

        X_ivc.add_output('state_disc:x', val=np.zeros(gd.subset_num_nodes['state_disc']),
                         units='m')

        X_ivc.add_output('state_disc:v', val=np.zeros(gd.subset_num_nodes['state_disc']),
                         units='m/s')

        F_ivc = om.IndepVarComp()
        p.model.add_subsystem('F_ivc', F_ivc, promotes=['staterate_disc:x', 'staterate_disc:v'])

        F_ivc.add_output('staterate_disc:x',
                         val=np.zeros(gd.subset_num_nodes['state_disc']),
                         units='m/s')

        F_ivc.add_output('staterate_disc:v',
                         val=np.zeros(gd.subset_num_nodes['state_disc']),
                         units='m/s**2')

        dt_dtau_ivc = om.IndepVarComp()
        p.model.add_subsystem('dt_dstau_ivc', dt_dtau_ivc, promotes=['dt_dstau'])

        dt_dtau_ivc.add_output('dt_dstau', val=0.0*np.zeros(gd.subset_num_nodes['col']), units='s')

        p.model.add_subsystem('state_interp_comp',
                              subsys=StateInterpComp(transcription='gauss-lobatto',
                                                     grid_data=gd,
                                                     state_options=states,
                                                     time_units='s'))

        p.model.connect('state_disc:x', 'state_interp_comp.state_disc:x')
        p.model.connect('state_disc:v', 'state_interp_comp.state_disc:v')
        p.model.connect('staterate_disc:x', 'state_interp_comp.staterate_disc:x')
        p.model.connect('staterate_disc:v', 'state_interp_comp.staterate_disc:v')
        p.model.connect('dt_dstau', 'state_interp_comp.dt_dstau')

        p.setup(force_alloc_complex=True)

        segends_disc = segends[np.array((0, 1, 1, 2), dtype=int)]

        p['state_disc:x'] = [x(t) for t in segends_disc]
        p['staterate_disc:x'] = [f_x(t) for t in segends_disc]

        p['state_disc:v'] = [v(t) for t in segends_disc]
        p['staterate_disc:v'] = [f_v(t) for t in segends_disc]

        p['dt_dstau'] = (segends[1:] - segends[:-1]) / 2.0

        p.run_model()

        t_disc = segends_disc
        t_col = (segends[1:] + segends[:-1]) / 2.0

        if SHOW_PLOTS:  # pragma: no cover
            f, ax = plt.subplots(2, 1)

            t = np.linspace(0, 10, 100)
            x1 = x(t)
            xdot1 = f_x(t)

            x2 = v(t)
            xdot2 = f_v(t)

            ax[0].plot(t, x1, 'b-', label='$x$')
            ax[0].plot(t, xdot1, 'b--', label=r'$\dot{x}$')
            ax[0].plot(t_disc, p['state_disc:x'], 'bo', label='$X_d:x$')
            ax[0].plot(t_col, p['state_interp_comp.state_col:x'], 'bv', label='$X_c:x$')
            ax[0].plot(t_col, p['state_interp_comp.staterate_col:x'], marker='v', color='None',
                       mec='b', label='$Xdot_c:x$')

            ax[1].plot(t, x2, 'r-', label='$v$')
            ax[1].plot(t, xdot2, 'r--', label=r'$\dot{v}$')
            ax[1].plot(t_disc, p['state_disc:v'], 'ro', label='$X_d:v$')
            ax[1].plot(t_col, p['state_interp_comp.state_col:v'], 'rv', label='$X_c:v$')
            ax[1].plot(t_col, p['state_interp_comp.staterate_col:v'], marker='v', color='None',
                       mec='r', label='$Xdot_c:v$')

            ax[0].legend(loc='upper left', ncol=3)
            ax[1].legend(loc='upper left', ncol=3)

            plt.show()

        # Test 1
        assert_almost_equal(
            p['state_interp_comp.state_col:x'][:, 0], x(t_col))
        assert_almost_equal(
            p['state_interp_comp.staterate_col:x'][:, 0], f_x(t_col))

        # Test 2
        assert_almost_equal(
            p['state_interp_comp.state_col:v'][:, 0], v(t_col))
        assert_almost_equal(
            p['state_interp_comp.staterate_col:v'][:, 0], f_v(t_col))

        cpd = p.check_partials(compact_print=True, method='cs')
        assert_check_partials(cpd, atol=5.0E-5)
コード例 #22
0
 def test_partials(self):
     cpd = self.p.check_partials(out_stream=None)
     assert_check_partials(cpd)
コード例 #23
0
 def test_partials(self):
     cpd = self.p.check_partials(out_stream=None, method='fd', step=1.0E-6)
     assert_check_partials(cpd, atol=5.0E-3, rtol=2.0)
コード例 #24
0
 def test_partials(self):
     np.set_printoptions(linewidth=1024)
     cpd = self.p.check_partials(compact_print=False,
                                 method='fd',
                                 out_stream=None)
     assert_check_partials(cpd)
コード例 #25
0
    def test_control_interp_scalar(self):
        param_list = itertools.product(
            ['gauss-lobatto', 'radau-ps'],  # transcription
            [True, False],  # compressed
        )
        for transcription, compressed in param_list:
            with self.subTest():
                segends = np.array([0.0, 3.0, 10.0])

                gd = GridData(num_segments=2,
                              transcription_order=5,
                              segment_ends=segends,
                              transcription=transcription,
                              compressed=compressed)

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

                controls = {
                    'a': {
                        'units': 'm',
                        'shape': (1, ),
                        'dynamic': True
                    },
                    'b': {
                        'units': 'm',
                        'shape': (1, ),
                        'dynamic': True
                    }
                }

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

                ivc.add_output('controls:a',
                               val=np.zeros(
                                   (gd.subset_num_nodes['control_input'], 1)),
                               units='m')

                ivc.add_output('controls:b',
                               val=np.zeros(
                                   (gd.subset_num_nodes['control_input'], 1)),
                               units='m')

                ivc.add_output('t_initial', val=0.0, units='s')
                ivc.add_output('t_duration', val=10.0, units='s')

                p.model.add_subsystem(
                    'time_comp',
                    subsys=TimeComp(num_nodes=gd.num_nodes,
                                    node_ptau=gd.node_ptau,
                                    node_dptau_dstau=gd.node_dptau_dstau,
                                    units='s'),
                    promotes_inputs=['t_initial', 't_duration'],
                    promotes_outputs=['time', 'dt_dstau'])

                p.model.add_subsystem('control_interp_comp',
                                      subsys=ControlInterpComp(
                                          grid_data=gd,
                                          control_options=controls,
                                          time_units='s'),
                                      promotes_inputs=['controls:*'])

                p.model.connect('dt_dstau', 'control_interp_comp.dt_dstau')

                p.setup(force_alloc_complex=True)

                p['t_initial'] = 0.0
                p['t_duration'] = 3.0

                p.run_model()

                t = p['time']
                p['controls:a'][:, 0] = f_a(
                    t[gd.subset_node_indices['control_input']])
                p['controls:b'][:, 0] = f_b(
                    t[gd.subset_node_indices['control_input']])

                p.run_model()

                a_value_expected = f_a(t)
                b_value_expected = f_b(t)

                a_rate_expected = f1_a(t)
                b_rate_expected = f1_b(t)

                a_rate2_expected = f2_a(t)
                b_rate2_expected = f2_b(t)

                assert_almost_equal(p['control_interp_comp.control_values:a'],
                                    np.atleast_2d(a_value_expected).T)

                assert_almost_equal(p['control_interp_comp.control_values:b'],
                                    np.atleast_2d(b_value_expected).T)

                assert_almost_equal(
                    p['control_interp_comp.control_rates:a_rate'],
                    np.atleast_2d(a_rate_expected).T)

                assert_almost_equal(
                    p['control_interp_comp.control_rates:b_rate'],
                    np.atleast_2d(b_rate_expected).T)

                assert_almost_equal(
                    p['control_interp_comp.control_rates:a_rate2'],
                    np.atleast_2d(a_rate2_expected).T)

                assert_almost_equal(
                    p['control_interp_comp.control_rates:b_rate2'],
                    np.atleast_2d(b_rate2_expected).T)

                np.set_printoptions(linewidth=1024)
                cpd = p.check_partials(compact_print=False, method='cs')
                assert_check_partials(cpd)
コード例 #26
0
 def test_partials(self):
     cpd = self.p.check_partials(compact_print=True, method='cs')
     assert_check_partials(cpd)
コード例 #27
0
 def test_partials(self):
     cpd = self.p.check_partials(compact_print=True,
                                 method='cs',
                                 out_stream=None)
     assert_check_partials(cpd)
コード例 #28
0
    def test_state_interp_comp_radau(self):

        gd = GridData(num_segments=1,
                      transcription_order=3,
                      segment_ends=np.array([0, 10]),
                      transcription='radau-ps')

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

        states = {'x': {'units': 'm', 'shape': (1,)},
                  'v': {'units': 'm/s', 'shape': (1,)}}

        X_ivc = om.IndepVarComp()
        p.model.add_subsystem('X_ivc', X_ivc, promotes=['state_disc:x', 'state_disc:v'])

        X_ivc.add_output('state_disc:x', val=np.zeros(gd.subset_num_nodes['state_disc']),
                         units='m')

        X_ivc.add_output('state_disc:v', val=np.zeros(gd.subset_num_nodes['state_disc']),
                         units='m/s')

        dt_dtau_ivc = om.IndepVarComp()
        dt_dtau_ivc.add_output('dt_dstau', val=0.0*np.zeros(gd.subset_num_nodes['col']), units='s')

        p.model.add_subsystem('dt_dstau_ivc', dt_dtau_ivc, promotes=['dt_dstau'])

        p.model.add_subsystem('state_interp_comp',
                              subsys=StateInterpComp(transcription='radau-ps',
                                                     grid_data=gd,
                                                     state_options=states,
                                                     time_units='s'))

        p.model.connect('state_disc:x', 'state_interp_comp.state_disc:x')
        p.model.connect('state_disc:v', 'state_interp_comp.state_disc:v')
        p.model.connect('dt_dstau', 'state_interp_comp.dt_dstau')

        p.setup(force_alloc_complex=True)

        lgr_nodes, lgr_weights = lgr(3, include_endpoint=True)
        t_disc = (lgr_nodes + 1.0) * 5.0
        t_col = t_disc[:-1]

        # Test 1:  Let x = t**2, f = 2*t
        p['state_disc:x'] = t_disc**2

        # Test 1:  Let v = t**3-10*t**2, f = 3*t**2 - 20*t
        p['state_disc:v'] = t_disc**3-10*t_disc**2

        p['dt_dstau'] = 10/2.0

        p.run_model()

        if SHOW_PLOTS:  # pragma: no cover
            f, ax = plt.subplots(2, 1)

            t_disc = np.array([0, 5, 10])
            t_col = np.array([2.5, 7.5])

            t = np.linspace(0, 10, 100)
            x1 = t**2
            xdot1 = 2*t

            x2 = t**3 - 10*t**2
            xdot2 = 3*t**2 - 20*t

            ax[0].plot(t, x1, 'b-', label='$x$')
            ax[0].plot(t, xdot1, 'b--', label='$\dot{x}$')
            ax[0].plot(t_disc, p['state_disc:x'], 'bo', label='$X_d:x$')
            ax[0].plot(t_col, p['state_interp_comp.state_col:x'], 'bv', label='$X_c:x$')
            ax[0].plot(t_col, p['state_interp_comp.staterate_col:x'], marker='v', color='None',
                       mec='b', label='$Xdot_c:x$')

            ax[1].plot(t, x2, 'r-', label='$v$')
            ax[1].plot(t, xdot2, 'r--', label='$\dot{v}$')
            ax[1].plot(t_disc, p['state_disc:v'], 'ro', label='$X_d:v$')
            ax[1].plot(t_col, p['state_interp_comp.state_col:v'], 'rv', label='$X_c:v$')
            ax[1].plot(t_col, p['state_interp_comp.staterate_col:v'], marker='v', color='None',
                       mec='r', label='$Xdot_c:v$')

            ax[0].legend(loc='upper left', ncol=3)
            ax[1].legend(loc='upper left', ncol=3)

            plt.show()

        # Test 1
        assert_almost_equal(
            p['state_interp_comp.staterate_col:x'][:, 0], 2*t_col)

        # Test 2
        assert_almost_equal(
            p['state_interp_comp.staterate_col:v'][:, 0], 3*t_col**2 - 20*t_col)

        cpd = p.check_partials(compact_print=True, method='cs')
        assert_check_partials(cpd, atol=1.0E-5)
コード例 #29
0
 def assert_partials(self, p):
     with printoptions(linewidth=1024, edgeitems=100):
         cpd = p.check_partials(method='cs', compact_print=True)
     assert_check_partials(cpd)
コード例 #30
0
ファイル: test_rk_k_iter_group.py プロジェクト: wright/dymos
    def test_rk4_scalar_no_iteration(self):
        num_seg = 4
        num_stages = 4
        state_options = {'y': {'shape': (1, ), 'units': 'm', 'targets': ['y']}}

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

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

        ivc.add_output('initial_states_per_seg:y',
                       shape=(num_seg, 1),
                       units='m')
        ivc.add_output('h', shape=(num_seg, 1), units='s')
        ivc.add_output('t', shape=(num_seg * num_stages, 1), units='s')

        p.model.add_subsystem(
            'k_iter_group',
            RungeKuttaKIterGroup(num_segments=num_seg,
                                 method='RK4',
                                 state_options=state_options,
                                 time_units='s',
                                 ode_class=TestODE,
                                 ode_init_kwargs={},
                                 solver_class=om.NonlinearRunOnce))

        p.model.connect('t', 'k_iter_group.ode.t')
        p.model.connect('h', 'k_iter_group.h')
        p.model.connect('initial_states_per_seg:y',
                        'k_iter_group.initial_states_per_seg:y')

        src_idxs = np.arange(16, dtype=int).reshape((num_seg, num_stages, 1))
        p.model.connect('k_iter_group.ode.ydot',
                        'k_iter_group.k_comp.f:y',
                        src_indices=src_idxs,
                        flat_src_indices=True)

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

        p['t'] = np.array([[
            0.00, 0.25, 0.25, 0.50, 0.50, 0.75, 0.75, 1.00, 1.00, 1.25, 1.25,
            1.50, 1.50, 1.75, 1.75, 2.00
        ]]).T

        p['h'] = np.array([[0.5, 0.5, 0.5, 0.5]]).T

        p['initial_states_per_seg:y'] = np.array([[0.50000000],
                                                  [1.425130208333333],
                                                  [2.639602661132812],
                                                  [4.006818970044454]])

        p['k_iter_group.k_comp.k:y'] = np.array([[[0.75000000], [0.90625000],
                                                  [0.94531250], [1.09765625]],
                                                 [[1.087565104166667],
                                                  [1.203206380208333],
                                                  [1.232116699218750],
                                                  [1.328623453776042]],
                                                 [[1.319801330566406],
                                                  [1.368501663208008],
                                                  [1.380676746368408],
                                                  [1.385139703750610]],
                                                 [[1.378409485022227],
                                                  [1.316761856277783],
                                                  [1.301349949091673],
                                                  [1.154084459568063]]])

        p.run_model()

        # Test that the residuals of k are zero (we started k at the expected converged value)
        outputs = p.model.list_outputs(print_arrays=True,
                                       residuals=True,
                                       out_stream=False)
        op_dict = dict([op for op in outputs])
        assert_almost_equal(op_dict['k_iter_group.k_comp.k:y']['resids'], 0.0)

        # Test the partials
        cpd = p.check_partials(method='cs', out_stream=None)
        assert_check_partials(cpd)