def test_add_new_plot(): # Load graphs_one_phase from bioptim.examples.torque_driven_ocp import track_markers_with_torque_actuators as ocp_module bioptim_folder = os.path.dirname(ocp_module.__file__) ocp = ocp_module.prepare_ocp( biorbd_model_path=bioptim_folder + "/models/cube.bioMod", n_shooting=20, final_time=0.5, ) solver = Solver.IPOPT() solver.set_maximum_iterations(1) sol = ocp.solve(solver) # Saving/loading files reset the plot settings to normal save_name = "test_plot.bo" ocp.save(sol, save_name) # Test 1 - Working plot ocp.add_plot("My New Plot", lambda t, x, u, p: x[0:2, :]) sol.graphs(automatically_organize=False) # Test 2 - Combine using combine_to is not allowed ocp, sol = OptimalControlProgram.load(save_name) with pytest.raises(RuntimeError): ocp.add_plot("My New Plot", lambda t, x, u, p: x[0:2, :], combine_to="NotAllowed") # Test 3 - Create a completely new plot ocp, sol = OptimalControlProgram.load(save_name) ocp.add_plot("My New Plot", lambda t, x, u, p: x[0:2, :]) ocp.add_plot("My Second New Plot", lambda t, x, p, u: x[0:2, :]) sol.graphs(automatically_organize=False) # Test 4 - Combine to the first using fig_name ocp, sol = OptimalControlProgram.load(save_name) ocp.add_plot("My New Plot", lambda t, x, u, p: x[0:2, :]) ocp.add_plot("My New Plot", lambda t, x, u, p: x[0:2, :]) sol.graphs(automatically_organize=False) # Add the plot of objectives and constraints to this mess ocp.add_plot_penalty(CostType.ALL) sol.graphs(automatically_organize=False) # Delete the saved file os.remove(save_name)
def main(): """ Create and solve a program. Then it saves it using the .bo method, and then using te stand_alone option. """ ocp = prepare_ocp(biorbd_model_path="models/pendulum.bioMod", final_time=1, n_shooting=100, n_threads=4) # --- Solve the program --- # sol = ocp.solve(show_online_optim=False) print(f"Time to solve : {sol.real_time_to_optimize}sec") # --- Print objective cost --- # print(f"Final objective value : {np.nansum(sol.cost)} \n") sol.print() # --- Save the optimal control program and the solution with stand_alone = False --- # ocp.save(sol, "pendulum.bo") # you don't have to specify the extension ".bo" # --- Load the optimal control program and the solution --- # ocp_load, sol_load = OptimalControlProgram.load("pendulum.bo") # --- Show results --- # sol_load.animate() sol_load.graphs() # --- Save the optimal control program and the solution with stand_alone = True --- # ocp.save(sol, f"pendulum_sa.bo", stand_alone=True) # --- Load the solution saved with stand_alone = True --- # with open(f"pendulum_sa.bo", "rb") as file: states, controls, parameters = pickle.load(file)
def save_and_load(sol, ocp, test_solve_of_loaded=False): file_path = "test.bo" ocp.save(sol, file_path) ocp_load, sol_load = OptimalControlProgram.load(file_path) TestUtils.deep_assert(sol, sol_load) TestUtils.deep_assert(sol_load, sol) if test_solve_of_loaded: sol_from_load = ocp_load.solve() TestUtils.deep_assert(sol, sol_from_load) TestUtils.deep_assert(sol_from_load, sol) TestUtils.deep_assert(ocp_load, ocp) TestUtils.deep_assert(ocp, ocp_load) os.remove(file_path) file_path_bob = "test.bob" ocp.save_get_data(sol, file_path_bob, interpolate_nb_frames=-1, concatenate=True) data = Data.get_data(ocp, sol, file_path_bob, interpolate_nb_frames=-1, concatenate=True) with open(file_path_bob, "rb") as file: data_load = pickle.load(file)["data"] TestUtils.deep_assert(data, data_load) TestUtils.deep_assert(data_load, data) os.remove(file_path_bob)
def test_add_new_plot(): # Load graphs_one_phase PROJECT_FOLDER = Path(__file__).parent / ".." spec = importlib.util.spec_from_file_location( "align_markers", str(PROJECT_FOLDER) + "/examples/torque_driven_ocp/align_markers_with_torque_actuators.py") graphs_one_phase = importlib.util.module_from_spec(spec) spec.loader.exec_module(graphs_one_phase) ocp = graphs_one_phase.prepare_ocp( biorbd_model_path=str(PROJECT_FOLDER) + "/examples/torque_driven_ocp/cube.bioMod", number_shooting_points=20, final_time=0.5, ) sol = ocp.solve(solver_options={"max_iter": 1}) # Saving/loading files reset the plot settings to normal save_name = "test_plot.bo" ocp.save(sol, save_name) # Test 1 - Working plot ocp.add_plot("My New Plot", lambda x, u, p: x[0:2, :]) ShowResult(ocp, sol).graphs(automatically_organize=False) # Test 2 - Combine using combine_to is not allowed ocp, sol = OptimalControlProgram.load(save_name) with pytest.raises(RuntimeError): ocp.add_plot("My New Plot", lambda x, u, p: x[0:2, :], combine_to="NotAllowed") # Test 3 - Create a completely new plot ocp, sol = OptimalControlProgram.load(save_name) ocp.add_plot("My New Plot", lambda x, u, p: x[0:2, :]) ocp.add_plot("My Second New Plot", lambda x, p, u: x[0:2, :]) ShowResult(ocp, sol).graphs(automatically_organize=False) # Test 4 - Combine to the first using fig_name ocp, sol = OptimalControlProgram.load(save_name) ocp.add_plot("My New Plot", lambda x, u, p: x[0:2, :]) ocp.add_plot("My New Plot", lambda x, u, p: x[0:2, :]) ShowResult(ocp, sol).graphs(automatically_organize=False) # Delete the saved file os.remove(save_name)
def test_add_new_plot(): # Load graphs_one_phase bioptim_folder = TestUtils.bioptim_folder() graphs = TestUtils.load_module( bioptim_folder + "/examples/torque_driven_ocp/track_markers_with_torque_actuators.py") ocp = graphs.prepare_ocp( biorbd_model_path=bioptim_folder + "/examples/torque_driven_ocp/cube.bioMod", n_shooting=20, final_time=0.5, ) sol = ocp.solve(solver_options={"max_iter": 1}) # Saving/loading files reset the plot settings to normal save_name = "test_plot.bo" ocp.save(sol, save_name) # Test 1 - Working plot ocp.add_plot("My New Plot", lambda x, u, p: x[0:2, :]) sol.graphs(automatically_organize=False) # Test 2 - Combine using combine_to is not allowed ocp, sol = OptimalControlProgram.load(save_name) with pytest.raises(RuntimeError): ocp.add_plot("My New Plot", lambda x, u, p: x[0:2, :], combine_to="NotAllowed") # Test 3 - Create a completely new plot ocp, sol = OptimalControlProgram.load(save_name) ocp.add_plot("My New Plot", lambda x, u, p: x[0:2, :]) ocp.add_plot("My Second New Plot", lambda x, p, u: x[0:2, :]) sol.graphs(automatically_organize=False) # Test 4 - Combine to the first using fig_name ocp, sol = OptimalControlProgram.load(save_name) ocp.add_plot("My New Plot", lambda x, u, p: x[0:2, :]) ocp.add_plot("My New Plot", lambda x, u, p: x[0:2, :]) sol.graphs(automatically_organize=False) # Delete the saved file os.remove(save_name)
def solve(self, limit_memory_max_iter, exact_max_iter, load_path=None, force_no_graph=False): def warm_start_nmpc(ocp, sol): state, ctrl, param = sol.states, sol.controls, sol.parameters u_init_guess = InitialGuessList() x_init_guess = InitialGuessList() for i in range(ocp.n_phases): u_init_guess.add(ctrl[i]["all"][:, :-1], interpolation=InterpolationType.EACH_FRAME) x_init_guess.add(state[i]["all"], interpolation=InterpolationType.EACH_FRAME) time_init_guess = InitialGuess(param["time"], name="time") ocp.update_initial_guess(x_init=x_init_guess, u_init=u_init_guess, param_init=time_init_guess) ocp.solver.set_lagrange_multiplier(sol) # Run optimizations if load_path: _, sol = OptimalControlProgram.load(load_path) return sol else: sol = None if limit_memory_max_iter > 0: sol = self.ocp.solve( show_online_optim=exact_max_iter == 0 and not force_no_graph, solver_options={ "linear_solver": "ma57", "hessian_approximation": "limited-memory", "max_iter": limit_memory_max_iter, }, ) if limit_memory_max_iter > 0 and exact_max_iter > 0: warm_start_nmpc(self.ocp, sol) if exact_max_iter > 0: sol = self.ocp.solve( show_online_optim=True and not force_no_graph, solver_options={ "linear_solver": "ma57", "hessian_approximation": "exact", "max_iter": exact_max_iter, "warm_start_init_point": "yes", }, ) return sol
def save_and_load(sol, ocp, test_solve_of_loaded=False): file_path = "test.bo" ocp.save(sol, file_path) ocp_load, sol_load = OptimalControlProgram.load(file_path) TestUtils.deep_assert(sol, sol_load) TestUtils.deep_assert(sol_load, sol) if test_solve_of_loaded: sol_from_load = ocp_load.solve() TestUtils.deep_assert(sol, sol_from_load) TestUtils.deep_assert(sol_from_load, sol) TestUtils.deep_assert(ocp_load, ocp) TestUtils.deep_assert(ocp, ocp_load) os.remove(file_path)
def save_and_load(sol, ocp, test_solve_of_loaded=False): file_path = "test" ocp.save(sol, f"{file_path}.bo") ocp_load, sol_load = OptimalControlProgram.load(f"{file_path}.bo") TestUtils.deep_assert(sol, sol_load) TestUtils.deep_assert(sol_load, sol) if test_solve_of_loaded: sol_from_load = ocp_load.solve() TestUtils.deep_assert(sol, sol_from_load) TestUtils.deep_assert(sol_from_load, sol) TestUtils.deep_assert(ocp_load, ocp) TestUtils.deep_assert(ocp, ocp_load) ocp.save(sol, f"{file_path}_sa.bo", stand_alone=True) with open(f"{file_path}_sa.bo", "rb") as file: states, controls, parameters = pickle.load(file) TestUtils.deep_assert(states, sol.states) TestUtils.deep_assert(controls, sol.controls) TestUtils.deep_assert(parameters, sol.parameters) os.remove(f"{file_path}.bo") os.remove(f"{file_path}_sa.bo")
sns.set() from casadi import MX, Function, vertcat, jacobian from matplotlib import pyplot as plt import csv from bioptim import ( OptimalControlProgram, Data, ShowResult, PlotType, ) # --- Load OCP --- # biorbd_model = biorbd.Model( "/home/amedeo/Documents/programmation/Article_Colombe/arm_Belaise_buchanan_de_groote.bioMod" ) ocp, sol, param = OptimalControlProgram.load( "/home/amedeo/Documents/programmation/Article_Colombe/results/Q_tracking_with_residual_torque2020-08-06 15:32:25.127113.bo" ) states, controls, params = Data.get_data(ocp, sol["x"], get_parameters=True) print(params["shape_factor"]) q = states["q"] qdot = states["q_dot"] u = states["muscles"] x = vertcat(states["q"], states["q_dot"], states["muscles"]) e = controls["muscles"] nlp = ocp.nlp[0] # --- Casadi stuff ---# symbolic_states = MX.sym("x", nlp["nbQ"] + nlp["nbQdot"] + nlp["nbMuscle"], 1) symbolic_controls = MX.sym("e", nlp["nbMuscle"], 1) symbolic_length = MX.sym("l", nlp["nbMuscle"], 1)
import time import sys import pickle from bioptim import OptimalControlProgram, ShowResult, Data, Simulate from up_and_down_bow import xia_model_dynamic, xia_model_configuration, xia_model_fibers, xia_initial_fatigue_at_zero file_path = "results/xia 5 phases/2020_7_25_upDown.bo" if len(sys.argv) > 1: file_path = str(sys.argv[1]) if not isinstance(file_path, str): t = time.localtime(time.time()) file_path = f"results/{t.tm_year}_{t.tm_mon}_{t.tm_mday}_upDown.bo" ocp, sol = OptimalControlProgram.load(file_path) d = Data.get_data(ocp, Simulate.from_solve(ocp, sol, single_shoot=True)) dict = {"data": d} with open(file_path[:-3] + "_single.bob", "wb") as file: pickle.dump(dict, file)
if __name__ == "__main__": """ Create and solve a program. Then it saves it using the .bob and .bo method """ ocp = prepare_ocp(biorbd_model_path="pendulum.bioMod", final_time=3, n_shooting=100, n_threads=4) # --- Solve the program --- # tic = time() sol = ocp.solve(show_online_optim=True) toc = time() - tic print(f"Time to solve : {toc}sec") # --- Print objective cost --- # print(f"Final objective value : {np.nansum(sol.cost)} \n") sol.print() # --- Save the optimal control program and the solution --- # ocp.save(sol, "pendulum.bo") # you don't have to specify the extension ".bo" # --- Load the optimal control program and the solution --- # ocp_load, sol_load = OptimalControlProgram.load("pendulum.bo") # --- Show results --- # sol_load.animate()
sol = ocp.solve( solver=Solver.IPOPT, show_online_optim=False, solver_options={ "tol": 1e-4, "dual_inf_tol": 1e-4, "constr_viol_tol": 1e-4, "compl_inf_tol": 1e-4, "linear_solver": "ma57", "max_iter": 500, "hessian_approximation": "exact", }, ) if os.path.isfile( f"solutions/sim_ip_{int(T*1000)}ms_{Ns}sn_{motion}.bo"): ocp.save(sol, f"solutions/sim_ip_{int(T*1000)}ms_{Ns}sn_{motion}_1.bo") else: ocp.save(sol, f"solutions/sim_ip_{int(T*1000)}ms_{Ns}sn_{motion}.bo") if use_BO: ocp, sol = OptimalControlProgram.load( f"solutions/sim_ip_{int(T*1000)}ms_{Ns}sn_{motion}.bo") # --- Show results --- # result = ShowResult(ocp, sol) result.graphs() result.animate()