コード例 #1
0
def prepare_ocp(biorbd_model_path, final_time, number_shooting_points, min_g, max_g, target_g):
    # --- Options --- #
    biorbd_model = biorbd.Model(biorbd_model_path)
    tau_min, tau_max, tau_init = -30, 30, 0
    n_q = biorbd_model.nbQ()
    n_qdot = biorbd_model.nbQdot()
    n_tau = biorbd_model.nbGeneralizedTorque()

    # Add objective functions
    objective_functions = ObjectiveOption(Objective.Lagrange.MINIMIZE_TORQUE, weight=10)

    # Dynamics
    dynamics = DynamicsTypeOption(DynamicsType.TORQUE_DRIVEN)

    # Path constraint
    x_bounds = BoundsOption(QAndQDotBounds(biorbd_model))
    x_bounds[:, [0, -1]] = 0
    x_bounds[1, -1] = 3.14

    # Initial guess
    x_init = InitialGuessOption([0] * (n_q + n_qdot))

    # Define control path constraint
    u_bounds = BoundsOption([[tau_min] * n_tau, [tau_max] * n_tau])
    u_bounds[1, :] = 0

    u_init = InitialGuessOption([tau_init] * n_tau)

    # Define the parameter to optimize
    # Give the parameter some min and max bounds
    parameters = ParameterList()
    bound_gravity = Bounds(min_bound=min_g, max_bound=max_g, interpolation=InterpolationType.CONSTANT)
    # and an initial condition
    initial_gravity = InitialGuess((min_g + max_g) / 2)
    parameter_objective_functions = ObjectiveOption(
        my_target_function, weight=10, quadratic=True, custom_type=Objective.Parameter, target=target_g
    )
    parameters.add(
        "gravity_z",  # The name of the parameter
        my_parameter_function,  # The function that modifies the biorbd model
        initial_gravity,  # The initial guess
        bound_gravity,  # The bounds
        size=1,  # The number of elements this particular parameter vector has
        penalty_list=parameter_objective_functions,  # Objective of constraint for this particular parameter
        extra_value=1,  # You can define as many extra arguments as you want
    )

    return OptimalControlProgram(
        biorbd_model,
        dynamics,
        number_shooting_points,
        final_time,
        x_init,
        u_init,
        x_bounds,
        u_bounds,
        objective_functions,
        parameters=parameters,
    )
コード例 #2
0
def prepare_ocp(biorbd_model_path, ode_solver=OdeSolver.RK):
    # --- Options --- #
    # Model path
    biorbd_model = biorbd.Model(biorbd_model_path)

    # Problem parameters
    number_shooting_points = 30
    final_time = 2
    tau_min, tau_max, tau_init = -100, 100, 0

    # Add objective functions
    objective_functions = ObjectiveOption(Objective.Lagrange.MINIMIZE_TORQUE,
                                          weight=100)

    # Dynamics
    dynamics = DynamicsTypeOption(DynamicsType.TORQUE_DRIVEN)

    # Constraints
    constraints = ConstraintList()
    constraints.add(custom_func_align_markers,
                    node=Node.START,
                    first_marker_idx=0,
                    second_marker_idx=1)
    constraints.add(custom_func_align_markers,
                    node=Node.END,
                    first_marker_idx=0,
                    second_marker_idx=2)

    # Path constraint
    x_bounds = BoundsOption(QAndQDotBounds(biorbd_model))
    x_bounds[1:6, [0, -1]] = 0
    x_bounds[2, -1] = 1.57

    # Initial guess
    x_init = InitialGuessOption([0] *
                                (biorbd_model.nbQ() + biorbd_model.nbQdot()))

    # Define control path constraint
    u_bounds = BoundsOption([[tau_min] * biorbd_model.nbGeneralizedTorque(),
                             [tau_max] * biorbd_model.nbGeneralizedTorque()])

    u_init = InitialGuessOption([tau_init] *
                                biorbd_model.nbGeneralizedTorque())

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

    return OptimalControlProgram(
        biorbd_model,
        dynamics,
        number_shooting_points,
        final_time,
        x_init,
        u_init,
        x_bounds,
        u_bounds,
        objective_functions,
        constraints,
        ode_solver=ode_solver,
    )
コード例 #3
0
def prepare_ocp(biorbd_model_path, problem_type_custom=True, ode_solver=OdeSolver.RK, use_SX=False):
    # --- Options --- #
    # Model path
    biorbd_model = biorbd.Model(biorbd_model_path)

    # Problem parameters
    number_shooting_points = 30
    final_time = 2
    tau_min, tau_max, tau_init = -100, 100, 0

    # Add objective functions
    objective_functions = ObjectiveList()
    objective_functions.add(Objective.Mayer.MINIMIZE_STATE, weight=1000, states_idx=[0, 1], target=np.array([[1., 2.]]).T)
    objective_functions.add(Objective.Mayer.MINIMIZE_STATE, weight=10000, states_idx=[2], target=np.array([[3.]]))
    objective_functions.add(Objective.Lagrange.MINIMIZE_TORQUE, weight=1,)

    # Dynamics
    dynamics = DynamicsTypeList()
    if problem_type_custom:
        dynamics.add(custom_configure, dynamic_function=custom_dynamic)
    else:
        dynamics.add(DynamicsType.TORQUE_DRIVEN, dynamic_function=custom_dynamic)


    # Path constraint
    x_bounds = BoundsOption(QAndQDotBounds(biorbd_model))
    x_bounds[:, 0] = 0

    # Initial guess
    x_init = InitialGuessOption([0] * (biorbd_model.nbQ() + biorbd_model.nbQdot()))

    # Define control path constraint
    u_bounds = BoundsOption(
        [[tau_min] * biorbd_model.nbGeneralizedTorque(), [tau_max] * biorbd_model.nbGeneralizedTorque()]
    )

    u_init = InitialGuessOption([tau_init] * biorbd_model.nbGeneralizedTorque())

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

    return OptimalControlProgram(
        biorbd_model,
        dynamics,
        number_shooting_points,
        final_time,
        x_init,
        u_init,
        x_bounds,
        u_bounds,
        objective_functions,
        ode_solver=ode_solver,
        use_SX=use_SX
    )
コード例 #4
0
def test_accessors_on_bounds_option():
    x_min = [-100] * 6
    x_max = [100] * 6
    x_bounds = BoundsOption([x_min, x_max], interpolation=InterpolationType.CONSTANT)
    x_bounds[:3] = 0
    x_bounds.min[3:] = -10
    x_bounds.max[1:3] = 10

    # Check accessor and min/max values to be equal
    np.testing.assert_almost_equal(x_bounds[:], (x_bounds.min[:], x_bounds.max[:]))

    # Check min and max have the right value
    np.testing.assert_almost_equal(x_bounds.min[:], np.array([[0], [0], [0], [-10], [-10], [-10]]))
    np.testing.assert_almost_equal(x_bounds.max[:], np.array([[0], [10], [10], [100], [100], [100]]))
コード例 #5
0
def prepare_ocp(biorbd_model_path, final_time, number_shooting_points,
                time_min, time_max):
    # --- Options --- #
    biorbd_model = biorbd.Model(biorbd_model_path)
    tau_min, tau_max, tau_init = -100, 100, 0
    n_q = biorbd_model.nbQ()
    n_qdot = biorbd_model.nbQdot()
    n_tau = biorbd_model.nbGeneralizedTorque()

    # Add objective functions
    objective_functions = ObjectiveOption(Objective.Lagrange.MINIMIZE_TORQUE)

    # Dynamics
    dynamics = DynamicsTypeOption(DynamicsType.TORQUE_DRIVEN)

    # Constraints
    constraints = ConstraintOption(Constraint.TIME_CONSTRAINT,
                                   node=Node.END,
                                   min_bound=time_min,
                                   max_bound=time_max)

    # Path constraint
    x_bounds = BoundsOption(QAndQDotBounds(biorbd_model))
    x_bounds[:, [0, -1]] = 0
    x_bounds[n_q - 1, -1] = 3.14

    # Initial guess
    x_init = InitialGuessOption([0] * (n_q + n_qdot))

    # Define control path constraint
    u_bounds = BoundsOption([[tau_min] * n_tau, [tau_max] * n_tau])
    u_bounds[n_tau - 1, :] = 0

    u_init = InitialGuessOption([tau_init] * n_tau)

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

    return OptimalControlProgram(
        biorbd_model,
        dynamics,
        number_shooting_points,
        final_time,
        x_init,
        u_init,
        x_bounds,
        u_bounds,
        objective_functions,
        constraints,
    )
コード例 #6
0
def prepare_ocp(
    biorbd_model_path,
    number_shooting_points,
    final_time,
    x_init,
    u_init,
    x0,
):
    biorbd_model = biorbd.Model(biorbd_model_path)
    n_tau = biorbd_model.nbGeneralizedTorque()
    tau_min, tau_max, tau_init = -100, 100, 0

    objective_functions = ObjectiveList()
    objective_functions.add(Objective.Lagrange.MINIMIZE_TORQUE, idx=0)
    objective_functions.add(Objective.Lagrange.ALIGN_SEGMENT_WITH_CUSTOM_RT,
                            weight=100,
                            segment_idx=Bow.segment_idx,
                            rt_idx=violin.rt_on_string,
                            idx=1)

    dynamics = DynamicsTypeOption(DynamicsType.TORQUE_DRIVEN)

    x_bounds = BoundsOption(QAndQDotBounds(biorbd_model))
    x_bounds[:, 0] = x0
    x_init = InitialGuessOption(x_init,
                                interpolation=InterpolationType.EACH_FRAME)

    u_bounds = BoundsOption([[tau_min] * n_tau, [tau_max] * n_tau])
    u_init = InitialGuessOption(u_init,
                                interpolation=InterpolationType.EACH_FRAME)

    return OptimalControlProgram(
        biorbd_model,
        dynamics,
        number_shooting_points,
        final_time,
        x_init,
        u_init,
        x_bounds,
        u_bounds,
        objective_functions=objective_functions,
    ), x_bounds
コード例 #7
0
def test_accessors_on_bounds_option_multidimensional():
    x_min = [[-100, -50, 0] for i in range(6)]
    x_max = [[100, 150, 200] for i in range(6)]
    x_bounds = BoundsOption([x_min, x_max], interpolation=InterpolationType.CONSTANT_WITH_FIRST_AND_LAST_DIFFERENT)
    x_bounds[:3, 0] = 0
    x_bounds.min[1:5, 1:] = -10
    x_bounds.max[1:5, 1:] = 10

    # Check accessor and min/max values to be equal
    np.testing.assert_almost_equal(x_bounds[:], (x_bounds.min[:], x_bounds.max[:]))

    # Check min and max have the right value
    np.testing.assert_almost_equal(
        x_bounds.min[:],
        np.array([[0, -50, 0], [0, -10, -10], [0, -10, -10], [-100, -10, -10], [-100, -10, -10], [-100, -50, 0]]),
    )
    np.testing.assert_almost_equal(
        x_bounds.max[:],
        np.array([[0, 150, 200], [0, 10, 10], [0, 10, 10], [100, 10, 10], [100, 10, 10], [100, 150, 200]]),
    )
コード例 #8
0
ファイル: test_penalty.py プロジェクト: vennand/BiorbdOptim
def prepare_test_ocp(with_muscles=False, with_contact=False):
    PROJECT_FOLDER = Path(__file__).parent / ".."
    if with_muscles and with_contact:
        raise RuntimeError(
            "With muscles and with contact together is not defined")
    elif with_muscles:
        biorbd_model = biorbd.Model(
            str(PROJECT_FOLDER) + "/examples/muscle_driven_ocp/arm26.bioMod")
        dynamics = DynamicsTypeList()
        dynamics.add(DynamicsType.MUSCLE_ACTIVATIONS_AND_TORQUE_DRIVEN)
        nx = biorbd_model.nbQ() + biorbd_model.nbQdot()
        nu = biorbd_model.nbGeneralizedTorque() + biorbd_model.nbMuscles()
    elif with_contact:
        biorbd_model = biorbd.Model(
            str(PROJECT_FOLDER) +
            "/examples/muscle_driven_with_contact/2segments_4dof_2contacts_1muscle.bioMod"
        )
        dynamics = DynamicsTypeList()
        dynamics.add(DynamicsType.TORQUE_DRIVEN_WITH_CONTACT)
        nx = biorbd_model.nbQ() + biorbd_model.nbQdot()
        nu = biorbd_model.nbGeneralizedTorque()
    else:
        biorbd_model = biorbd.Model(
            str(PROJECT_FOLDER) + "/examples/align/cube_and_line.bioMod")
        dynamics = DynamicsTypeList()
        dynamics.add(DynamicsType.TORQUE_DRIVEN)
        nx = biorbd_model.nbQ() + biorbd_model.nbQdot()
        nu = biorbd_model.nbGeneralizedTorque()
    x_init = InitialGuessOption(np.zeros((nx, 1)))
    u_init = InitialGuessOption(np.zeros((nu, 1)))
    x_bounds = BoundsOption([np.zeros((nx, 1)), np.zeros((nx, 1))])
    u_bounds = BoundsOption([np.zeros((nu, 1)), np.zeros((nu, 1))])
    ocp = OptimalControlProgram(biorbd_model, dynamics, 10, 1.0, x_init,
                                u_init, x_bounds, u_bounds)
    ocp.nlp[0].J = [list()]
    ocp.nlp[0].g = [list()]
    ocp.nlp[0].g_bounds = [list()]
    return ocp
コード例 #9
0
def prepare_ocp(biorbd_model_path, final_time, number_shooting_points):
    # --- Options --- #
    biorbd_model = biorbd.Model(biorbd_model_path)
    torque_min, torque_max, torque_init = -100, 100, 0
    n_q = biorbd_model.nbQ()
    n_qdot = biorbd_model.nbQdot()
    n_tau = biorbd_model.nbGeneralizedTorque()

    # Dynamics
    dynamics = DynamicsTypeOption(DynamicsType.TORQUE_DRIVEN)

    # Path constraint
    x_bounds = BoundsOption(QAndQDotBounds(biorbd_model))
    x_bounds[:, [0, -1]] = 0
    x_bounds[1, -1] = 3.14

    # Initial guess
    x_init = InitialGuessOption([0] * (n_q + n_qdot))

    # Define control path constraint
    u_bounds = BoundsOption([[torque_min] * n_tau, [torque_max] * n_tau])
    u_bounds[n_tau - 1, :] = 0

    u_init = InitialGuessOption([torque_init] * n_tau)

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

    return OptimalControlProgram(
        biorbd_model,
        dynamics,
        number_shooting_points,
        final_time,
        x_init,
        u_init,
        x_bounds,
        u_bounds,
    )
コード例 #10
0
            # [0] * 6 + [0.4] * 3 + [0] * 10
        ]

    ocp = prepare_ocp(biorbd_model=biorbd_model, final_time=T, x0=x0, nbGT=nbGT, number_shooting_points=Ns, use_SX=True)

    for co in range(len(excitations_init)):
    # for co in range(2, 4):
        u_i = excitations_init[co]
        u_mi = excitations_min[co]
        u_ma = excitations_max

        u_init = InitialGuessOption(np.tile(u_i, (ocp.nlp[0].ns, 1)).T, interpolation=InterpolationType.EACH_FRAME)
        x_init = InitialGuessOption(np.tile(x0, (ocp.nlp[0].ns+1, 1)).T, interpolation=InterpolationType.EACH_FRAME)
        ocp.update_initial_guess(x_init, u_init=u_init)

        u_bounds = BoundsOption([u_mi, u_ma], interpolation=InterpolationType.CONSTANT)
        ocp.update_bounds(u_bounds=u_bounds)

        objectives = ObjectiveList()
        objectives.add(Objective.Lagrange.MINIMIZE_MUSCLES_CONTROL, weight=1000)

        objectives.add(
            Objective.Lagrange.TRACK_STATE,
            weight=100000,
            target=states[:biorbd_model.nbQ(), :],
            states_idx=np.array(range(nbQ))
        )

        objectives.add(
            Objective.Lagrange.MINIMIZE_STATE, weight=100, states_idx=np.array(range(nbQ * 2, nbQ * 2 + nbMT))
        )
コード例 #11
0
def test_update_bounds_and_init_with_param():
    def my_parameter_function(biorbd_model, value, extra_value):
        biorbd_model.setGravity(biorbd.Vector3d(0, 0, value + extra_value))

    def my_target_function(ocp, value, target_value):
        return value + target_value

    PROJECT_FOLDER = Path(__file__).parent / ".."
    biorbd_model = biorbd.Model(
        str(PROJECT_FOLDER) + "/examples/align/cube_and_line.bioMod")
    nq = biorbd_model.nbQ()
    ns = 10
    g_min, g_max, g_init = -10, -6, -8

    dynamics = DynamicsTypeList()
    dynamics.add(DynamicsType.TORQUE_DRIVEN)

    parameters = ParameterList()
    bounds_gravity = Bounds(min_bound=g_min,
                            max_bound=g_max,
                            interpolation=InterpolationType.CONSTANT)
    initial_gravity = InitialGuess(g_init)
    parameter_objective_functions = ObjectiveOption(
        my_target_function,
        weight=10,
        quadratic=True,
        custom_type=Objective.Parameter,
        target_value=-8)
    parameters.add(
        "gravity_z",
        my_parameter_function,
        initial_gravity,
        bounds_gravity,
        size=1,
        penalty_list=parameter_objective_functions,
        extra_value=1,
    )

    ocp = OptimalControlProgram(biorbd_model,
                                dynamics,
                                ns,
                                1.0,
                                parameters=parameters)

    x_bounds = BoundsOption([-np.ones((nq * 2, 1)), np.ones((nq * 2, 1))])
    u_bounds = BoundsOption([-2.0 * np.ones((nq, 1)), 2.0 * np.ones((nq, 1))])
    ocp.update_bounds(x_bounds, u_bounds)

    expected = np.append(
        np.tile(np.append(-np.ones((nq * 2, 1)), -2.0 * np.ones((nq, 1))), ns),
        -np.ones((nq * 2, 1)))
    np.testing.assert_almost_equal(
        ocp.V_bounds.min,
        np.append([g_min], expected).reshape(129, 1))
    expected = np.append(
        np.tile(np.append(np.ones((nq * 2, 1)), 2.0 * np.ones((nq, 1))), ns),
        np.ones((nq * 2, 1)))
    np.testing.assert_almost_equal(
        ocp.V_bounds.max,
        np.append([[g_max]], expected).reshape(129, 1))

    x_init = InitialGuessOption(0.5 * np.ones((nq * 2, 1)))
    u_init = InitialGuessOption(-0.5 * np.ones((nq, 1)))
    ocp.update_initial_guess(x_init, u_init)
    expected = np.append(
        np.tile(np.append(0.5 * np.ones((nq * 2, 1)), -0.5 * np.ones((nq, 1))),
                ns), 0.5 * np.ones((nq * 2, 1)))
    np.testing.assert_almost_equal(
        ocp.V_init.init,
        np.append([g_init], expected).reshape(129, 1))
コード例 #12
0
def test_double_update_bounds_and_init():
    PROJECT_FOLDER = Path(__file__).parent / ".."
    biorbd_model = biorbd.Model(
        str(PROJECT_FOLDER) + "/examples/align/cube_and_line.bioMod")
    nq = biorbd_model.nbQ()
    ns = 10

    dynamics = DynamicsTypeList()
    dynamics.add(DynamicsType.TORQUE_DRIVEN)
    ocp = OptimalControlProgram(biorbd_model, dynamics, ns, 1.0)

    x_bounds = BoundsOption([-np.ones((nq * 2, 1)), np.ones((nq * 2, 1))])
    u_bounds = BoundsOption([-2.0 * np.ones((nq, 1)), 2.0 * np.ones((nq, 1))])
    ocp.update_bounds(x_bounds, u_bounds)

    expected = np.append(
        np.tile(np.append(-np.ones((nq * 2, 1)), -2.0 * np.ones((nq, 1))), ns),
        -np.ones((nq * 2, 1)))
    np.testing.assert_almost_equal(ocp.V_bounds.min, expected.reshape(128, 1))
    expected = np.append(
        np.tile(np.append(np.ones((nq * 2, 1)), 2.0 * np.ones((nq, 1))), ns),
        np.ones((nq * 2, 1)))
    np.testing.assert_almost_equal(ocp.V_bounds.max, expected.reshape(128, 1))

    x_init = InitialGuessOption(0.5 * np.ones((nq * 2, 1)))
    u_init = InitialGuessOption(-0.5 * np.ones((nq, 1)))
    ocp.update_initial_guess(x_init, u_init)
    expected = np.append(
        np.tile(np.append(0.5 * np.ones((nq * 2, 1)), -0.5 * np.ones((nq, 1))),
                ns), 0.5 * np.ones((nq * 2, 1)))
    np.testing.assert_almost_equal(ocp.V_init.init, expected.reshape(128, 1))

    x_bounds = BoundsOption(
        [-2.0 * np.ones((nq * 2, 1)), 2.0 * np.ones((nq * 2, 1))])
    u_bounds = BoundsOption([-4.0 * np.ones((nq, 1)), 4.0 * np.ones((nq, 1))])
    ocp.update_bounds(x_bounds=x_bounds)
    ocp.update_bounds(u_bounds=u_bounds)

    expected = np.append(
        np.tile(
            np.append(-2.0 * np.ones((nq * 2, 1)), -4.0 * np.ones((nq, 1))),
            ns), -2.0 * np.ones((nq * 2, 1)))
    np.testing.assert_almost_equal(ocp.V_bounds.min, expected.reshape(128, 1))
    expected = np.append(
        np.tile(np.append(2.0 * np.ones((nq * 2, 1)), 4.0 * np.ones((nq, 1))),
                ns), 2.0 * np.ones((nq * 2, 1)))
    np.testing.assert_almost_equal(ocp.V_bounds.max, expected.reshape(128, 1))

    x_init = InitialGuessOption(0.25 * np.ones((nq * 2, 1)))
    u_init = InitialGuessOption(-0.25 * np.ones((nq, 1)))
    ocp.update_initial_guess(x_init, u_init)
    expected = np.append(
        np.tile(
            np.append(0.25 * np.ones((nq * 2, 1)), -0.25 * np.ones((nq, 1))),
            ns), 0.25 * np.ones((nq * 2, 1)))
    np.testing.assert_almost_equal(ocp.V_init.init, expected.reshape(128, 1))

    with pytest.raises(
            RuntimeError,
            match=
            "x_init should be built from a InitialGuessOption or InitialGuessList"
    ):
        ocp.update_initial_guess(x_bounds, u_bounds)
    with pytest.raises(
            RuntimeError,
            match="x_bounds should be built from a BoundsOption or BoundsList"
    ):
        ocp.update_bounds(x_init, u_init)
コード例 #13
0
def prepare_ocp(biorbd_model_path,
                number_shooting_points,
                final_time,
                loop_from_constraint,
                ode_solver=OdeSolver.RK):
    # --- Options --- #
    # Model path
    biorbd_model = biorbd.Model(biorbd_model_path)

    # Problem parameters
    tau_min, tau_max, tau_init = -100, 100, 0

    # Add objective functions
    objective_functions = ObjectiveOption(Objective.Lagrange.MINIMIZE_TORQUE,
                                          weight=100)

    # Dynamics
    dynamics = DynamicsTypeOption(DynamicsType.TORQUE_DRIVEN)

    # Constraints
    constraints = ConstraintList()
    constraints.add(Constraint.ALIGN_MARKERS,
                    node=Node.MID,
                    first_marker_idx=0,
                    second_marker_idx=2)
    constraints.add(Constraint.TRACK_STATE, node=Node.MID, index=2)
    constraints.add(Constraint.ALIGN_MARKERS,
                    node=Node.END,
                    first_marker_idx=0,
                    second_marker_idx=1)

    # Path constraint
    x_bounds = BoundsOption(QAndQDotBounds(biorbd_model))
    x_bounds[2:6, -1] = [1.57, 0, 0, 0]

    # Initial guess
    x_init = InitialGuessOption([0] *
                                (biorbd_model.nbQ() + biorbd_model.nbQdot()))

    # Define control path constraint
    u_bounds = BoundsOption([[tau_min] * biorbd_model.nbGeneralizedTorque(),
                             [tau_max] * biorbd_model.nbGeneralizedTorque()])

    u_init = InitialGuessOption([tau_init] *
                                biorbd_model.nbGeneralizedTorque())

    # ------------- #
    # A state transition loop constraint is treated as
    # hard penalty (constraint) if weight is <= 0 [or if no weight is provided], or
    # as a soft penalty (objective) otherwise
    state_transitions = StateTransitionList()
    if loop_from_constraint:
        state_transitions.add(StateTransition.CYCLIC, weight=0)
    else:
        state_transitions.add(StateTransition.CYCLIC, weight=10000)

    return OptimalControlProgram(
        biorbd_model,
        dynamics,
        number_shooting_points,
        final_time,
        x_init,
        u_init,
        x_bounds,
        u_bounds,
        objective_functions,
        constraints,
        ode_solver=ode_solver,
        state_transitions=state_transitions,
    )
コード例 #14
0
def prepare_ocp(
    biorbd_model_path,
    number_shooting_points,
    final_time,
    initial_guess=InterpolationType.CONSTANT,
):
    # --- Options --- #
    # Model path
    biorbd_model = biorbd.Model(biorbd_model_path)
    nq = biorbd_model.nbQ()
    nqdot = biorbd_model.nbQdot()
    ntau = biorbd_model.nbGeneralizedTorque()
    tau_min, tau_max, tau_init = -100, 100, 0

    # Add objective functions
    objective_functions = ObjectiveOption(Objective.Lagrange.MINIMIZE_TORQUE,
                                          weight=100)

    # Dynamics
    dynamics = DynamicsTypeOption(DynamicsType.TORQUE_DRIVEN)

    # Constraints
    constraints = ConstraintList()
    constraints.add(Constraint.ALIGN_MARKERS,
                    node=Node.START,
                    first_marker_idx=0,
                    second_marker_idx=1)
    constraints.add(Constraint.ALIGN_MARKERS,
                    node=Node.END,
                    first_marker_idx=0,
                    second_marker_idx=2)

    # Path constraint and control path constraints
    x_bounds = BoundsOption(QAndQDotBounds(biorbd_model))
    x_bounds[1:6, [0, -1]] = 0
    x_bounds[2, -1] = 1.57
    u_bounds = BoundsOption([[tau_min] * ntau, [tau_max] * ntau])

    # Initial guesses
    t = None
    extra_params_x = {}
    extra_params_u = {}
    if initial_guess == InterpolationType.CONSTANT:
        x = [0] * (nq + nqdot)
        u = [tau_init] * ntau
    elif initial_guess == InterpolationType.CONSTANT_WITH_FIRST_AND_LAST_DIFFERENT:
        x = np.array([[1.0, 0.0, 0.0, 0, 0, 0], [1.5, 0.0, 0.785, 0, 0, 0],
                      [2.0, 0.0, 1.57, 0, 0, 0]]).T
        u = np.array([[1.45, 9.81, 2.28], [0, 9.81, 0], [-1.45, 9.81,
                                                         -2.28]]).T
    elif initial_guess == InterpolationType.LINEAR:
        x = np.array([[1.0, 0.0, 0.0, 0, 0, 0], [2.0, 0.0, 1.57, 0, 0, 0]]).T
        u = np.array([[1.45, 9.81, 2.28], [-1.45, 9.81, -2.28]]).T
    elif initial_guess == InterpolationType.EACH_FRAME:
        x = np.random.random((nq + nqdot, number_shooting_points + 1))
        u = np.random.random((ntau, number_shooting_points))
    elif initial_guess == InterpolationType.SPLINE:
        # Bound spline assume the first and last point are 0 and final respectively
        t = np.hstack((0, np.sort(np.random.random(
            (3, )) * final_time), final_time))
        x = np.random.random((nq + nqdot, 5))
        u = np.random.random((ntau, 5))
    elif initial_guess == InterpolationType.CUSTOM:
        # The custom function refers to the one at the beginning of the file. It emulates a Linear interpolation
        x = custom_init_func
        u = custom_init_func
        extra_params_x = {
            "my_values": np.random.random((nq + nqdot, 2)),
            "nb_shooting": number_shooting_points
        }
        extra_params_u = {
            "my_values": np.random.random((ntau, 2)),
            "nb_shooting": number_shooting_points
        }
    else:
        raise RuntimeError("Initial guess not implemented yet")
    x_init = InitialGuessOption(x,
                                t=t,
                                interpolation=initial_guess,
                                **extra_params_x)

    u_init = InitialGuessOption(u,
                                t=t,
                                interpolation=initial_guess,
                                **extra_params_u)
    # ------------- #

    return OptimalControlProgram(
        biorbd_model,
        dynamics,
        number_shooting_points,
        final_time,
        x_init,
        u_init,
        x_bounds,
        u_bounds,
        objective_functions,
        constraints,
    )