Exemple #1
0
    def test_allow_different_variables(self):
        p1 = om.Problem()
        ivc = p1.model.add_subsystem('ivc', om.IndepVarComp(), promotes_outputs=['*'])
        ivc.add_output('a', val=0.0)
        ivc.add_output('b', val=1.0)
        ivc.add_output('c', val=2.0)
        ivc.add_output('x', val=3.0)
        p1.add_recorder(om.SqliteRecorder('p1.db'))
        p1.setup()

        p2 = om.Problem()
        ivc = p2.model.add_subsystem('ivc', om.IndepVarComp(), promotes_outputs=['*'])
        ivc.add_output('x', val=3.0)
        ivc.add_output('y', val=4.0)
        ivc.add_output('z', val=5.0)
        p2.add_recorder(om.SqliteRecorder('p2.db'))
        p2.setup()

        p1.run_model()
        p2.run_model()

        p1.record('final')
        p1.cleanup()

        p2.record('final')
        p2.cleanup()

        c1 = om.CaseReader('p1.db').get_case('final')
        c2 = om.CaseReader('p2.db').get_case('final')

        assert_cases_equal(c1, c2, require_same_vars=False)
Exemple #2
0
    def test_ex_two_burn_orbit_raise_connected(self):
        optimizer = 'IPOPT'

        p = two_burn_orbit_raise_problem(transcription='gauss-lobatto', transcription_order=3,
                                         compressed=False, optimizer=optimizer,
                                         show_output=False, connected=True)

        if p.model.traj.phases.burn2 in p.model.traj.phases._subsystems_myproc:
            assert_near_equal(p.get_val('traj.burn2.states:deltav')[0], 0.3995,
                              tolerance=4.0E-3)

        case1 = om.CaseReader('dymos_solution.db').get_case('final')
        sim_case1 = om.CaseReader('dymos_simulation.db').get_case('final')

        # Run again without an actual optimzier
        p = two_burn_orbit_raise_problem(transcription='gauss-lobatto', transcription_order=3,
                                         compressed=False, optimizer=None,
                                         show_output=False, restart='dymos_solution.db',
                                         connected=True)

        case2 = om.CaseReader('dymos_solution.db').get_case('final')
        sim_case2 = om.CaseReader('dymos_simulation.db').get_case('final')

        # Verify that the second case has the same inputs and outputs
        assert_cases_equal(case1, case2)
        assert_cases_equal(sim_case1, sim_case2)
    def test_timeseries_units_radau(self):
        double_integrator_direct_collocation(dm.Radau, compressed=True)

        sol_case = om.CaseReader('dymos_solution.db').get_case('final')
        sim_case = om.CaseReader('dymos_simulation.db').get_case('final')

        t_sol = sol_case.get_val('traj.phase0.timeseries.time')
        t_sim = sim_case.get_val('traj.phase0.timeseries.time')

        for var in ['states:x', 'states:v', 'state_rates:x']:
            sol = sol_case.get_val(f'traj.phase0.timeseries.{var}')
            sim = sim_case.get_val(f'traj.phase0.timeseries.{var}')
            assert_timeseries_near_equal(t_sol, sol, t_sim, sim, tolerance=1.0E-3)
Exemple #4
0
    def run_asserts(self):

        for db in ['dymos_solution.db', 'dymos_simulation.db']:
            p = om.CaseReader(db).get_case('final')

            t_initial = p.get_val('traj0.phase0.timeseries.time')[0]
            tf = p.get_val('traj0.phase0.timeseries.time')[-1]

            x0 = p.get_val('traj0.phase0.timeseries.states:x')[0]
            xf = p.get_val('traj0.phase0.timeseries.states:x')[-1]

            y0 = p.get_val('traj0.phase0.timeseries.states:y')[0]
            yf = p.get_val('traj0.phase0.timeseries.states:y')[-1]

            v0 = p.get_val('traj0.phase0.timeseries.states:v')[0]
            vf = p.get_val('traj0.phase0.timeseries.states:v')[-1]

            g = p.get_val('traj0.phase0.timeseries.parameters:g')[0]

            thetaf = p.get_val('traj0.phase0.timeseries.controls:theta')[-1]

            assert_near_equal(t_initial, 0.0)
            assert_near_equal(x0, 0.0)
            assert_near_equal(y0, 10.0)
            assert_near_equal(v0, 0.0)

            assert_near_equal(tf, 1.8016, tolerance=0.01)
            assert_near_equal(xf, 10.0, tolerance=0.01)
            assert_near_equal(yf, 5.0, tolerance=0.01)
            assert_near_equal(vf, 9.902, tolerance=0.01)
            assert_near_equal(g, 9.80665, tolerance=0.01)

            assert_near_equal(thetaf, 100.12, tolerance=0.01)
Exemple #5
0
        def run_parallel():
            # process cases.sql in parallel
            cr = om.CaseReader("cases.sql")

            cases = cr.list_cases()
            self.assertEqual(len(cases), 9)

            my_idxs = list(range(len(cases)))[rank::size]
            my_cases = [cases[i] for i in my_idxs]
            self.assertEqual(my_cases, [
                'rank0:DOEDriver_FullFactorial|0',
                'rank0:DOEDriver_FullFactorial|2',
                'rank0:DOEDriver_FullFactorial|4',
                'rank0:DOEDriver_FullFactorial|6',
                'rank0:DOEDriver_FullFactorial|8'
            ] if rank == 0 else [
                'rank0:DOEDriver_FullFactorial|1',
                'rank0:DOEDriver_FullFactorial|3',
                'rank0:DOEDriver_FullFactorial|5',
                'rank0:DOEDriver_FullFactorial|7'
            ])

            my_responses = [cr.get_case(case_id)['f_xy'] for case_id in my_cases]
            self.assertEqual(my_responses, [22., 17., 23.75, 31., 27.] if rank == 0 else
                                           [19.25, 26.25, 21.75, 28.75])
Exemple #6
0
def read_results():
    """
    Read the sql file.

    Returns
    -------
    None.

    """
    # Read recorded options
    path = './'
    cr = om.CaseReader(path + 'Driver_recorder.sql')
    # driver_cases = cr.list_cases('driver') (If  multiple recorders)

    cases = cr.get_cases()

    # Initiates dictionnaries
    case1 = cr.get_case(0)
    obj = case1.get_objectives()
    des = case1.get_design_vars()
    const = case1.get_constraints()
    print(const)

    for case in cases[0::]:
        for key, val in case.get_objectives().items():
            obj[key] = np.append(obj[key], val)

        for key, val in case.get_design_vars().items():
            des[key] = np.append(des[key], val)
Exemple #7
0
    def test_cases_driver_recurseFalse(self):
        cr = om.CaseReader('cases.sql')

        # when calling list_cases() with the default out_stream, the notebook
        # should get an HTML table and no results should be written to stdout.
        sysout = sys.stdout
        try:
            capture_stdout = StringIO()
            sys.stdout = capture_stdout
            cases = cr.list_cases('driver', recurse=False)
        finally:
            sys.stdout = sysout

        # we should still get the expected return value
        for i, expected_case in enumerate(self.expected_cases):
            self.assertEqual(cases[i], expected_case)

        # no results should have been written to stdout
        captured_output = capture_stdout.getvalue()
        for source in self.expected_sources:
            self.assertFalse(source in captured_output)
        for case in self.expected_cases:
            self.assertFalse(case in captured_output)

        # generated HTML should be a table and have all expected sources and cases
        captured_HTML = self.html_stream.getvalue()
        self.assertTrue(captured_HTML.startswith('<table>'))
        self.assertTrue(captured_HTML.endswith('</table>'))
        self.assertEqual(captured_HTML.count('<tr><td'),
                         len(self.expected_cases))
        for source in self.expected_sources:
            self.assertEqual(captured_HTML.count(source),
                             1)  # header occurs only once
        for case in self.expected_cases:
            self.assertTrue(case in captured_HTML)  # all case rows are there
Exemple #8
0
    def test_list_cases_problem(self):
        cr = om.CaseReader(self.filename)

        # when calling list_cases() with the default out_stream, the notebook
        # should get an HTML table and no results should be written to stdout.
        sysout = sys.stdout
        try:
            capture_stdout = StringIO()
            sys.stdout = capture_stdout
            cases = cr.list_cases('problem')
        finally:
            sys.stdout = sysout

        # we should still get the expected return value
        self.assertEqual(cases, ['final'])

        # no results should have been written to stdout
        captured_output = capture_stdout.getvalue()
        self.assertFalse('problem' in captured_output)
        self.assertFalse('final' in captured_output)

        # generated HTML should be a table and have all expected sources and cases
        captured_HTML = self.html_stream.getvalue()
        self.assertTrue(captured_HTML.startswith('<table>'))
        self.assertTrue(captured_HTML.endswith('</table>'))
        self.assertEqual(captured_HTML.count('<tr><td'), 1)
        self.assertTrue('problem' in captured_HTML)  # table header
        self.assertTrue('final' in captured_HTML)  # row value
Exemple #9
0
def convert_sqlite_to_csv(sqlite_filename, basename):
    cr = om.CaseReader(sqlite_filename)
    driver_cases = cr.list_cases("driver", out_stream=None)
    design_vars = sorted(cr.get_case(driver_cases[0]).get_design_vars())
    driver_name, cases, statuses = load_sqlite_file(sqlite_filename)
    all_vars = [v["varname"] for v in cases]
    out_vars = sorted(list(set(all_vars) - set(design_vars)))

    fieldnames = []
    values = {}
    nb_cases = len(statuses)
    for name in design_vars + out_vars:
        for case in cases:
            if name == case["varname"]:
                if case["coord_index"] == -1:
                    fieldnames.append(name)
                    values[name] = case["values"]
                else:
                    name_i = f"{name}[{case['coord_index']}]"
                    fieldnames.append(name_i)
                    values[name_i] = case["values"]

    outfile = f"{basename}.csv"
    with open(outfile, "w") as f:
        writer = csv.writer(f, delimiter=";", lineterminator="\n")
        writer.writerow(["success"] + fieldnames)

        for i in range(nb_cases):
            data = [statuses[i]]
            for var in fieldnames:
                data.append(values[var][i])
            writer.writerow(data)
    log(f"Convert {nb_cases} cases ({driver_name}) to {outfile}")
Exemple #10
0
    def compute(self, inputs, outputs):

        folder_output = self.options["opt_options"]["general"]["folder_output"]
        optimization_log = os.path.join(folder_output, self.options["opt_options"]["recorder"]["file_name"])
        if MPI:
            rank = MPI.COMM_WORLD.Get_rank()
        else:
            rank = 0
        if os.path.exists(optimization_log) and rank == 0:

            cr = om.CaseReader(optimization_log)
            cases = cr.list_cases()
            rec_data = {}
            iterations = []
            for i, casei in enumerate(cases):
                iterations.append(i)
                it_data = cr.get_case(casei)

                # parameters = it_data.get_responses()
                for parameters in [it_data.get_responses(), it_data.get_design_vars()]:
                    for j, param in enumerate(parameters.keys()):
                        if i == 0:
                            rec_data[param] = []
                        rec_data[param].append(parameters[param])

            for param in rec_data.keys():
                if param != "tower.layer_thickness" and param != "tower.diameter":
                    fig, ax = plt.subplots(1, 1, figsize=(5.3, 4))
                    ax.plot(iterations, rec_data[param])
                    ax.set(xlabel="Number of Iterations", ylabel=param)
                    fig_name = "Convergence_trend_" + param + ".png"
                    fig.savefig(os.path.join(folder_output, fig_name))
                    plt.close(fig)
Exemple #11
0
    def test_load_case_unchanged_grid(self):
        import openmdao.api as om
        from openmdao.utils.assert_utils import assert_near_equal
        import dymos as dm

        p = setup_problem(dm.GaussLobatto(num_segments=10))

        # Solve for the optimal trajectory
        dm.run_problem(p)

        # Load the solution
        case = om.CaseReader('dymos_solution.db').get_case('final')

        # Initialize the system with values from the case.
        # We unnecessarily call setup again just to make sure we obliterate the previous solution
        p.setup()

        # Load the values from the previous solution
        dm.load_case(p, case)

        # Run the model to ensure we find the same output values as those that we recorded
        p.run_driver()

        outputs = dict([
            (o[0], o[1])
            for o in case.list_outputs(units=True, shape=True, out_stream=None)
        ])

        assert_near_equal(
            p['phase0.controls:theta'],
            outputs['phase0.control_group.indep_controls.controls:theta']
            ['value'])
    def test_cannonball_matrix_state_radau(self):

        tx = dm.Radau(num_segments=10, order=3, solve_segments=False)

        p = self._make_problem(tx)

        dm.run_problem(p, simulate=True)

        assert_near_equal(p.get_val('traj.phase.timeseries.time')[-1],
                          2.03873598,
                          tolerance=1E-5)
        assert_near_equal(p.get_val('traj.phase.timeseries.states:z')[-1, 0,
                                                                      1],
                          0.0,
                          tolerance=1E-5)
        assert_near_equal(p.get_val('traj.phase.timeseries.states:z')[-1, 0,
                                                                      0],
                          20.3873598,
                          tolerance=1E-5)

        c = om.CaseReader('dymos_simulation.db').get_case('final')

        assert_near_equal(c.get_val('traj.phase.timeseries.time')[-1],
                          2.03873598,
                          tolerance=1E-5)
        assert_near_equal(c.get_val('traj.phase.timeseries.states:z')[-1, 0,
                                                                      1],
                          0.0,
                          tolerance=1E-5)
        assert_near_equal(c.get_val('traj.phase.timeseries.states:z')[-1, 0,
                                                                      0],
                          20.3873598,
                          tolerance=1E-5)
Exemple #13
0
    def test_load_case_rk4_to_lgl(self):
        import openmdao.api as om
        import dymos as dm
        from openmdao.utils.assert_utils import assert_near_equal

        p = setup_problem(dm.RungeKutta(num_segments=50))

        # Solve for the optimal trajectory
        dm.run_problem(p)

        # Load the solution
        case = om.CaseReader('dymos_solution.db').get_case('final')

        # create a problem with a different transcription with a different number of variables
        q = setup_problem(dm.GaussLobatto(num_segments=10))

        # Load the values from the previous solution
        dm.load_case(q, case)

        # Run the model to ensure we find the same output values as those that we recorded
        q.run_driver()

        outputs = dict([
            (o[0], o[1])
            for o in case.list_outputs(units=True, shape=True, out_stream=None)
        ])

        time_val = outputs['phase0.timeseries.time']['value']
        theta_val = outputs['phase0.timeseries.controls:theta']['value']

        assert_near_equal(q['phase0.timeseries.controls:theta'],
                          q.model.phase0.interpolate(xs=time_val,
                                                     ys=theta_val,
                                                     nodes='all'),
                          tolerance=1.0E-1)
 def test_get_vars(self):
     cr = om.CaseReader('parab_record.sql')
     case_names = cr.list_cases(out_stream=None)
     inputs = _get_vars(cr, case_names=case_names, var_types='inputs')
     outputs = _get_vars(cr, case_names=case_names, var_types='outputs')
     self.assertSetEqual(set(inputs), {'x', 'y'})
     self.assertSetEqual(set(outputs), {'const.g', 'parab.f_xy'})
Exemple #15
0
def run_problem(problem, refine_method='hp', refine_iteration_limit=0, run_driver=True,
                simulate=False, restart=None):
    """
    A Dymos-specific interface to execute an OpenMDAO problem containing Dymos Trajectories or
    Phases.  This function can iteratively call run_driver to perform grid refinement, and automatically
    call simulate following a run to check the validity of a result.

    Parameters
    ----------
    problem : om.Problem
        The OpenMDAO problem object to be run.
    refine : bool
        If True, perform grid refinement on the Phases found in the Problem.
    refine_method : String
        The choice of refinement algorithm to use for grid refinement
    refine_iteration_limit : int
        The number of passes through the grid refinement algorithm to be made.
    run_driver : bool
        If True, run the driver (optimize the problem), otherwise just run the model one time.
    no_iterate : bool
        If True, run the driver but do not iterate.
    simulate : bool
        If True, perform a simulation of Trajectories found in the Problem after the driver
        has been run and grid refinement is complete.
    """
    if 'dymos_solution.db' not in [rec._filepath for rec in iter(problem._rec_mgr)]:
        problem.add_recorder(om.SqliteRecorder('dymos_solution.db'))

    problem.final_setup()  # make sure command line option hook has a chance to run

    if restart is not None:
        case = om.CaseReader(restart).get_case('final')
        load_case(problem, case)
Exemple #16
0
def test_unconstrained_dtlz1(recording_path):
    recorder = om.SqliteRecorder(recording_path)

    pymop_problem = pymop.DTLZ1(n_var=3, n_obj=3)

    prob = om.Problem()
    prob.model = PymopGroup(problem=pymop_problem)
    prob.model.add_recorder(recorder)
    prob.driver = Nsga3Driver(generation_count=500, random_seed=0)

    try:
        prob.setup()
        prob.run_driver()
    finally:
        prob.cleanup()

    cases = case_dataset(om.CaseReader(recording_path))
    pareto_cases = pareto_subset(cases)

    distance_function = "euclidean"
    ref_dirs = uniform_reference_points(pymop_problem.n_obj, p=4)
    ideal_pareto_front = pymop_problem.pareto_front(ref_dirs)
    min_pareto_point_distance = sp.spatial.distance.pdist(
        ideal_pareto_front, distance_function
    ).min()

    distances = sp.spatial.distance.cdist(
        pareto_cases["problem.obj"].values, ideal_pareto_front, distance_function
    )
    distances_to_ideal = np.min(distances, axis=0)

    assert distances_to_ideal.max() <= min_pareto_point_distance * 0.75
Exemple #17
0
    def test_list_cases(self):
        cr = om.CaseReader(self.filename)

        # when calling list_cases() with the default out_stream, the notebook
        # should get an HTML table and no results should be written to stdout.
        sysout = sys.stdout
        try:
            capture_stdout = StringIO()
            sys.stdout = capture_stdout
            cases = cr.list_cases()
        finally:
            sys.stdout = sysout

        # we should still get the expected return value
        for i, line in enumerate(self.expected_cases):
            self.assertEqual(cases[i], line, f'case not found "{line}"')

        # no results should have been written to stdout
        captured_output = capture_stdout.getvalue()
        for source in self.expected_headers:
            self.assertFalse(source in captured_output)
        for case in self.expected_cases:
            self.assertFalse(case in captured_output)

        # generated HTML should be a table and have all expected sources and cases
        captured_HTML = self.html_stream.getvalue()
        self.assertTrue(captured_HTML.startswith('<table>'))
        self.assertTrue(captured_HTML.endswith('</table>'))
        self.assertEqual(captured_HTML.count('<tr><td'),
                         len(self.expected_cases))
        for source in self.expected_headers:
            self.assertTrue(source in captured_HTML)
        for case in self.expected_cases:
            self.assertTrue(case in captured_HTML)
Exemple #18
0
    def test_ex_brachistochrone_no_solve(self):
        print('test_ex_brachistochrone_no_solve')
        with patch.object(sys, 'argv', self.base_args + ['--no_solve']):
            command_line.dymos_cmd()

        self.assertTrue(os.path.exists('dymos_solution.db'))
        cr = om.CaseReader('dymos_solution.db')
        self.assertTrue(len(cr.list_cases()) == 1)
Exemple #19
0
    def test_proc_per_model(self):
        # Test that we can run a GA on a distributed component without lockups.
        prob = om.Problem()
        model = prob.model

        model.add_subsystem('p', om.IndepVarComp('x', 3.0), promotes=['x'])

        model.add_subsystem('d1', D1(), promotes=['*'])
        model.add_subsystem('d2', D2(), promotes=['*'])

        model.add_subsystem('obj_comp', Summer(), promotes_outputs=['*'])
        model.promotes('obj_comp', inputs=['*'], src_indices=om.slicer[:])
        model.nonlinear_solver = om.NewtonSolver(solve_subsystems=True)
        model.linear_solver = om.LinearBlockGS()

        model.add_design_var('x', lower=-0.5, upper=0.5)
        model.add_objective('obj')

        driver = prob.driver = om.DifferentialEvolutionDriver()
        driver.options['pop_size'] = 4
        driver.options['max_gen'] = 3
        driver.options['run_parallel'] = True
        driver.options['procs_per_model'] = 2

        # also check that parallel recording works
        driver.add_recorder(om.SqliteRecorder("cases.sql"))

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

        failed, output = run_driver(prob)

        self.assertFalse(failed)

        # we will have run 2 models in parallel on our 4 procs
        num_models = prob.comm.size // driver.options['procs_per_model']
        self.assertEqual(num_models, 2)

        # a separate case file should have been written by rank 0 of each parallel model
        # (the top two global ranks)
        rank = prob.comm.rank
        filename = "cases.sql_%d" % rank

        if rank < num_models:
            expect_msg = "Cases from rank %d are being written to %s." % (
                rank, filename)
            self.assertTrue(expect_msg in output)

            cr = om.CaseReader(filename)
            cases = cr.list_cases('driver')

            # check that cases were recorded on this proc
            num_cases = len(cases)
            self.assertTrue(num_cases > 0)
        else:
            self.assertFalse("Cases from rank %d are being written" %
                             rank in output)
            self.assertFalse(os.path.exists(filename))
Exemple #20
0
    def test_list_outputs(self):
        """
        Confirm that includes/excludes has the same result between System.list_inputs() and
        Case.list_inputs(), and between System.list_outputs() and Case.list_outputs().
        """

        prob = ParaboloidProblem()
        rec = om.SqliteRecorder('test_list_outputs.db')
        prob.model.add_recorder(rec)

        prob.setup()
        prob.run_model()

        read_p = om.CaseReader('test_list_outputs.db').get_case(-1)

        prob_out = io.StringIO()
        rec_out = io.StringIO()

        # Test list_inputs() with includes
        prob.model.list_inputs(val=False, includes="comp*", out_stream=prob_out)
        read_p.list_inputs(val=False, includes="comp*", out_stream=rec_out)

        prob_out_str = prob_out.getvalue()
        rec_out_str = rec_out.getvalue()
        self.assertEqual(prob_out_str, rec_out_str)

        prob_out.flush()
        rec_out.flush()        

        # Test list_outputs() with includes
        prob.model.list_outputs(val=False, includes="p*", out_stream=prob_out)
        read_p.list_outputs(val=False, includes="p*", out_stream=rec_out)

        prob_out_str = prob_out.getvalue()
        rec_out_str = rec_out.getvalue()
        self.assertEqual(prob_out_str, rec_out_str)

        prob_out.flush()
        rec_out.flush()

        # Test list_inputs() with excludes
        prob.model.list_inputs(val=False, excludes="comp*", out_stream=prob_out)
        read_p.list_inputs(val=False, excludes="comp*", out_stream=rec_out)

        prob_out_str = prob_out.getvalue()
        rec_out_str = rec_out.getvalue()
        self.assertEqual(prob_out_str, rec_out_str)

        prob_out.flush()
        rec_out.flush()

        # Test list_outputs() with excludes
        prob.model.list_outputs(val=False, excludes="p*", out_stream=prob_out)
        read_p.list_outputs(val=False, excludes="p*", out_stream=rec_out)

        prob_out_str = prob_out.getvalue()
        rec_out_str = rec_out.getvalue()
        self.assertEqual(prob_out_str, rec_out_str)
Exemple #21
0
    def test_restart_from_sol(self):
        p = self._make_problem()
        dm.run_problem(p, run_driver=True, simulate=False)

        sol_results = om.CaseReader('dymos_solution.db').get_case('final')

        assert_near_equal(sol_results.get_val('traj.climb.timeseries.states:r')[-1], 2016, tolerance=0.01)

        dm.run_problem(p, run_driver=True, simulate=True, restart='dymos_solution.db')

        sol_results = om.CaseReader('dymos_solution.db').get_case('final')
        sim_results = om.CaseReader('dymos_simulation.db').get_case('final')

        assert_near_equal(sol_results.get_val('traj.climb.timeseries.states:r')[-1], 2016, tolerance=0.01)
        assert_near_equal(sim_results.get_val('traj.climb.timeseries.states:r')[-1], 2016, tolerance=0.01)

        assert_near_equal(sol_results.get_val('traj.rto.timeseries.states:r')[-1], 2016, tolerance=0.01)
        assert_near_equal(sim_results.get_val('traj.rto.timeseries.states:r')[-1], 2016, tolerance=0.01)
    def test_brachistochrone_recording(self):
        import matplotlib
        matplotlib.use('Agg')
        import openmdao.api as om
        from openmdao.utils.assert_utils import assert_near_equal
        import dymos as dm
        from dymos.examples.brachistochrone.brachistochrone_ode import BrachistochroneODE

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

        phase = dm.Phase(ode_class=BrachistochroneODE, transcription=dm.GaussLobatto(num_segments=10))

        p.model.add_subsystem('phase0', phase)

        phase.set_time_options(initial_bounds=(0, 0), duration_bounds=(.5, 10))

        phase.add_state('x', fix_initial=True, fix_final=True,
                        rate_source=BrachistochroneODE.states['x']['rate_source'])
        phase.add_state('y', fix_initial=True, fix_final=True,
                        rate_source=BrachistochroneODE.states['y']['rate_source'])
        phase.add_state('v', fix_initial=True,
                        rate_source=BrachistochroneODE.states['v']['rate_source'])

        phase.add_control('theta', units='deg',
                          rate_continuity=False, lower=0.01, upper=179.9)

        phase.add_parameter('g', units='m/s**2', opt=False, val=9.80665)

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

        p.model.linear_solver = om.DirectSolver()

        p.setup()

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

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

        # Solve for the optimal trajectory
        dm.run_problem(p)

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

        case = om.CaseReader('dymos_solution.db').get_case('final')

        outputs = dict([(o[0], o[1]) for o in case.list_outputs(units=True, shape=True,
                                                                out_stream=None)])

        assert_near_equal(p['phase0.controls:theta'],
                          outputs['phase0.control_group.indep_controls.controls:theta']['value'])
    def test_get_resids_val(self):
        cr = om.CaseReader('parab_record.sql')
        case_name = cr.list_cases(out_stream=None)[0]
        case = cr.get_case(case_name)

        g_resids = _get_resids_val(case, 'const.g')
        f_resids = _get_resids_val(case, 'parab.f_xy')

        assert_near_equal(g_resids, [0.])
        assert_near_equal(f_resids, [0.])
Exemple #24
0
    def _assert_correct_solution(self):
        # Fail if the recorded driver solution file does not exist (driver did not execute)
        self.assertTrue(os.path.exists('dymos_solution.db'))

        # Assert the results are what we expect.
        cr = om.CaseReader('dymos_solution.db')
        case = cr.get_case('final')

        # Make sure the driver converged
        self.assertTrue(case.success)
Exemple #25
0
    def test_ex_brachistochrone_set_solution_record_file(self):
        print('test_ex_brachistochrone_set_solution_record_file')
        with patch.object(
                sys, 'argv', self.base_args +
            ['--solution_record_file=solution_record_file.db']):
            command_line.dymos_cmd()

        self.assertTrue(os.path.exists('solution_record_file.db'))
        cr = om.CaseReader('solution_record_file.db')
        self.assertListEqual(['final'], cr.list_cases())
Exemple #26
0
    def test_ex_brachistochrone_stock_nosolve_nosim(self):
        """ Test to verify that the command line interface intercepts final_setup and
        does nothing if given `--no_solve` and not given `--simulate`. """
        print('test_ex_brachistochrone_stock_nosolve_nosim')
        with patch.object(sys, 'argv', self.base_args + ['--no_solve']):
            command_line.dymos_cmd()

        self.assertTrue(os.path.exists('dymos_solution.db'))
        cr = om.CaseReader('dymos_solution.db')
        self.assertTrue(len(cr.list_cases()) == 1)
Exemple #27
0
    def test_run_brachistochrone_problem_with_simulate(self):
        p = om.Problem(model=om.Group())
        p.driver = om.pyOptSparseDriver()
        p.driver.declare_coloring()
        p.driver.options['optimizer'] = 'SLSQP'

        traj = p.model.add_subsystem('traj', dm.Trajectory())
        phase0 = traj.add_phase(
            'phase0',
            dm.Phase(ode_class=BrachistochroneODE,
                     transcription=dm.Radau(num_segments=10, order=3)))
        phase0.set_time_options(fix_initial=True, fix_duration=False)
        phase0.add_state('x', fix_initial=True, fix_final=False)
        phase0.add_state('y', fix_initial=True, fix_final=False)
        phase0.add_state('v', fix_initial=True, fix_final=False)
        phase0.add_control('theta',
                           continuity=True,
                           rate_continuity=True,
                           units='deg',
                           lower=0.01,
                           upper=179.9)
        phase0.add_parameter('g', units='m/s**2', val=9.80665)

        phase0.add_boundary_constraint('x', loc='final', equals=10)
        phase0.add_boundary_constraint('y', loc='final', equals=5)
        # Minimize time at the end of the phase
        phase0.add_objective('time_phase', loc='final', scaler=10)

        phase0.set_refine_options(refine=True)

        p.model.linear_solver = om.DirectSolver()
        p.setup(check=True)

        p.set_val('traj.phase0.t_initial', 0.0)
        p.set_val('traj.phase0.t_duration', 2.0)

        p.set_val('traj.phase0.states:x',
                  phase0.interpolate(ys=[0, 10], nodes='state_input'))
        p.set_val('traj.phase0.states:y',
                  phase0.interpolate(ys=[10, 5], nodes='state_input'))
        p.set_val('traj.phase0.states:v',
                  phase0.interpolate(ys=[0, 9.9], nodes='state_input'))
        p.set_val('traj.phase0.controls:theta',
                  phase0.interpolate(ys=[5, 100], nodes='control_input'))
        p.set_val('traj.phase0.parameters:g', 9.80665)

        dm.run_problem(p, simulate=True)

        self.assertTrue(os.path.exists('dymos_solution.db'))
        # Assert the results are what we expect.
        cr = om.CaseReader('dymos_solution.db')
        case = cr.get_case('final')
        assert_almost_equal(case.outputs['traj.phase0.timeseries.time'].max(),
                            1.8016,
                            decimal=4)
Exemple #28
0
def run_problem(problem,
                refine_method='hp',
                refine_iteration_limit=0,
                run_driver=True,
                simulate=False,
                restart=None):
    """
    A Dymos-specific interface to execute an OpenMDAO problem containing Dymos Trajectories or
    Phases.  This function can iteratively call run_driver to perform grid refinement, and automatically
    call simulate following a run to check the validity of a result.

    Parameters
    ----------
    problem : om.Problem
        The OpenMDAO problem object to be run.
    refine : bool
        If True, perform grid refinement on the Phases found in the Problem.
    refine_method : String
        The choice of refinement algorithm to use for grid refinement
    refine_iteration_limit : int
        The number of passes through the grid refinement algorithm to be made.
    run_driver : bool
        If True, run the driver (optimize the problem), otherwise just run the model one time.
    no_iterate : bool
        If True, run the driver but do not iterate.
    simulate : bool
        If True, perform a simulation of Trajectories found in the Problem after the driver
        has been run and grid refinement is complete.
    """
    problem.final_setup(
    )  # make sure command line option hook has a chance to run

    if restart is not None:
        cr = om.CaseReader(restart)
        system_cases = cr.list_cases('root')
        case = cr.get_case(system_cases[-1])
        load_case(problem, case)

    if run_driver:
        problem.run_driver()
        _refine_iter(problem, refine_iteration_limit, refine_method)
    else:
        problem.run_model()
        if refine_iteration_limit > 0:
            warnings.warn(
                "Refinement not performed. Set run_driver to True to perform refinement."
            )

    problem.record('final')  # save case for potential restart

    if simulate:
        for subsys in problem.model.system_iter(include_self=True,
                                                recurse=True):
            if isinstance(subsys, Trajectory):
                subsys.simulate(record_file='dymos_simulation.db')
def load_OMsql(log):
    print('loading {}'.format(log))
    cr = om.CaseReader(log)
    rec_data = {}
    driver_cases = cr.list_cases('driver')
    cases = cr.get_cases('driver')
    for case in cases:
        for key in case.outputs.keys():
            if key not in rec_data:
                rec_data[key] = []
            rec_data[key].append(case[key])
Exemple #30
0
    def test_ex_brachistochrone_no_solve(self):
        print('test_ex_brachistochrone_no_solve')
        with patch.object(sys, 'argv', self.base_args + ['--no_solve']):
            command_line.dymos_cmd()

        # Until the problem recorder is fixed, the driver recorder shouldn't be
        # invoked by this test, and thus we won't get a dymos_solution.db file

        self.assertTrue(os.path.exists('dymos_solution.db'))
        cr = om.CaseReader('dymos_solution.db')
        self.assertTrue(len(cr.list_cases()) == 0)  # no case recorded