def exercise1c():
    """describe how fiber length influences the force-length curve. Compare 
    a muscle comprised of short muscle fibers to a muscle comprised of 
    long muscle fibers. Change the parameter, you can use 
    system_parameters.py::MuscleParameters before instantiating the muscle
    No more than 2 plots are required.
    """

    # Defination of muscles
    parameters = MuscleParameters()
    pylog.warning("Loading default muscle parameters")
    pylog.info(parameters.showParameters())
    pylog.info("Use the parameters object to change the muscle parameters")

    # Create muscle object
    muscle = Muscle(parameters)

    pylog.warning("Isometric muscle contraction to be completed")

    # Instatiate isometric muscle system
    sys = IsometricMuscleSystem()

    # Add the muscle to the system
    sys.add_muscle(muscle)

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.L_OPT # To get the muscle optimal length
    muscle_lengths = np.arange(.1, .26, .03)

    max_muscle_active_forces = []
    max_muscle_passive_forces = []
    max_total_force = []
    max_force_stretch = []

    # Evalute for a single muscle stretch
    for muscle_length in muscle_lengths:

        parameters.l_opt = muscle_length
        muscle = Muscle(parameters)

        pylog.warning("Isometric muscle contraction to be completed")

        # Instatiate isometric muscle system
        sys = IsometricMuscleSystem()

        # Add the muscle to the system
        sys.add_muscle(muscle)

        if muscle_length < .16:
            start_stretch_length = .16
        else:
            start_stretch_length = muscle_length

        muscle_stretches = np.arange(
            start_stretch_length, 1.2 * muscle_length + .16,
            (1.2 * muscle_length + .16 - start_stretch_length) / 40)

        muscle_active_forces = []
        muscle_passive_forces = []
        total_force = []

        # Evalute for a single muscle stretch
        for muscle_stretch in muscle_stretches:

            # Evalute for a single muscle stimulation
            muscle_stimulation = 1.

            # Set the initial condition
            x0 = [0.0, sys.muscle.L_OPT]
            # x0[0] --> muscle stimulation intial value
            # x0[1] --> muscle contracticle length initial value

            # Set the time for integration
            t_start = 0.0
            t_stop = 0.3
            time_step = 0.001

            time = np.arange(t_start, t_stop, time_step)

            # Run the integration
            result = sys.integrate(x0=x0,
                                   time=time,
                                   time_step=time_step,
                                   stimulation=muscle_stimulation,
                                   muscle_length=muscle_stretch)

            muscle_active_forces.append(result.active_force[-1])
            muscle_passive_forces.append(result.passive_force[-1])
            total_force.append(result.active_force[-1] +
                               result.passive_force[-1])

        max_muscle_active_forces.append(max(muscle_active_forces))

        active_max_index = muscle_active_forces.index(
            max(muscle_active_forces))
        max_muscle_passive_forces.append(
            muscle_passive_forces[active_max_index])
        max_total_force.append(total_force[active_max_index])
        max_force_stretch.append(muscle_stretches[active_max_index])

        # Plotting max force for each muscle length over different stretch values. Uncomment to see (adds ~8 plots)
        #        plt.figure('Isometric muscle experiment. L_opt = %.2f'%(muscle_length))
        #        plt.plot(muscle_stretches, muscle_active_forces, label='active')
        #        plt.plot(muscle_stretches, muscle_passive_forces, label='passive')
        #        plt.plot(muscle_stretches, total_force, label='total')
        #        plt.title('Isometric muscle experiment 1C, L_opt = %.2f'%(muscle_length))
        #        plt.xlabel('Stretch Length [m]')
        #        plt.ylabel('Muscle Force [N]')
        #        plt.legend(loc='upper left')
        #        plt.grid()

        # Plotting active on its own
        plt.figure('Isometric muscle experiment, Active Force')
        plt.plot(muscle_stretches,
                 muscle_active_forces,
                 label=('L_opt = %.2f' % (muscle_length)))
        plt.title('Isometric muscle experiment: Active Force vs L_Opt')
        plt.xlabel('Stretch Length [m]')
        plt.ylabel('Active Muscle Force [N]')
        plt.legend(loc='upper left')
        plt.grid()

        # Plotting passive on its own
        plt.figure('Isometric muscle experiment, Passive Force')
        plt.plot(muscle_stretches,
                 muscle_passive_forces,
                 label=('L_opt = %.2f' % (muscle_length)))
        plt.title('Isometric muscle experiment: Passive Force vs L_Opt')
        plt.xlabel('Stretch Length [m]')
        plt.ylabel('Passive Muscle Force [N]')
        plt.legend(loc='upper left')
        plt.grid()

    # Plot max vals
    plt.figure('Isometric muscle experiment max Force')
    plt.plot(muscle_lengths, max_muscle_active_forces, label='active')
    #plt.plot(muscle_lengths, max_muscle_passive_forces, label='passive')
    #plt.plot(muscle_lengths, max_total_force, label='total')
    plt.title('Isometric muscle experiment 1C, Max')
    plt.xlabel('Muscle Optimal Length [m]')
    plt.ylabel('Max Muscle Force [N]')
    plt.legend(loc='upper left')
    plt.grid()

    #    print(max_muscle_active_forces)
    # Plot max stretch lengths of max vals
    plt.figure('Isometric muscle experiment max Force stretch')
    plt.plot(muscle_lengths, max_force_stretch, label='active')
    #plt.plot(muscle_lengths, max_muscle_passive_forces, label='passive')
    #plt.plot(muscle_lengths, max_total_force, label='total')
    plt.title('Isometric muscle experiment 1C, Max Stretch')
    plt.xlabel('Muscle Optimal Length [m]')
    plt.ylabel('Muscle Stretch of Max Force [m]')
    plt.legend(loc='upper left')
    plt.grid()
def system_init():
    """Initialize default system."""
    ########## PENDULUM ##########
    # Define and Setup your pendulum model here
    # Check Pendulum.py for more details on Pendulum class
    P_params = PendulumParameters()  # Instantiate pendulum parameters
    P_params.L = 1.0  # To change the default length of the pendulum
    P_params.m = 0.25  # To change the default mass of the pendulum
    pendulum = PendulumSystem(P_params)  # Instantiate Pendulum object
    #### CHECK OUT Pendulum.py to ADD PERTURBATIONS TO THE MODEL #####
    pylog.info('Pendulum model initialized \n {}'.format(
        pendulum.parameters.showParameters()))

    ########## MUSCLES ##########
    # Define and Setup your muscle model here
    # Check MuscleSystem.py for more details on MuscleSystem class
    m1_param = MuscleParameters()  # Instantiate Muscle 1 parameters
    m1_param.f_max = 200.  # To change Muscle 1 max force
    m1_param.l_opt = 0.4
    m1_param.l_slack = 0.45
    m2_param = MuscleParameters()  # Instantiate Muscle 2 parameters
    m2_param.f_max = 200.  # To change Muscle 2 max force
    m2_param.l_opt = 0.4
    m2_param.l_slack = 0.45
    m1 = Muscle('m1', m1_param)  # Instantiate Muscle 1 object
    m2 = Muscle('m2', m2_param)  # Instantiate Muscle 2 object
    # Use the MuscleSystem Class to define your muscles in the system
    # Instantiate Muscle System with two muscles
    muscles = MuscleSystem(m1, m2)
    pylog.info('Muscle system initialized \n {} \n {}'.format(
        m1.parameters.showParameters(), m2.parameters.showParameters()))
    # Define Muscle Attachment points
    m1_origin = np.asarray([0.0, 0.9])  # Origin of Muscle 1
    m1_insertion = np.asarray([0.0, 0.15])  # Insertion of Muscle 1

    m2_origin = np.asarray([0.0, 0.8])  # Origin of Muscle 2
    m2_insertion = np.asarray([0.0, -0.3])  # Insertion of Muscle 2
    # Attach the muscles
    muscles.attach(np.asarray([m1_origin, m1_insertion]),
                   np.asarray([m2_origin, m2_insertion]))

    ########## ADD SYSTEMS ##########
    # Create a system with Pendulum and Muscles using the System Class
    # Check System.py for more details on System class
    sys = System()  # Instantiate a new system
    sys.add_pendulum_system(pendulum)  # Add the pendulum model to the system
    sys.add_muscle_system(muscles)  # Add the muscle model to the system

    ########## INITIALIZATION ##########
    t_max = 2  # Maximum simulation time
    time = np.arange(0., t_max, 0.001)  # Time vector
    ##### Model Initial Conditions #####
    x0_P = np.asarray([np.pi / 2, 0.0])  # Pendulum initial condition
    # Muscle Model initial condition
    l_ce_0 = sys.muscle_sys.initialize_muscle_length(np.pi / 2)
    x0_M = np.asarray([0.05, l_ce_0[0], 0.05, l_ce_0[1]])
    x0 = np.concatenate((x0_P, x0_M))  # System initial conditions

    ########## System Simulation ##########
    sim = SystemSimulation(sys)  # Instantiate Simulation object
    # Simulate the system for given time
    sim.initalize_system(x0, time)  # Initialize the system state
    return sim
def exercise2():
    """ Main function to run for Exercise 2.

    Parameters
    ----------
        None

    Returns
    -------
        None
        
    """
    '''
    sim = system_init()

    # Add muscle activations to the simulation
    # Here you can define your muscle activation vectors
    # that are time dependent

    act1 = np.ones((len(sim.time), 1)) * 0.05
    act2 = np.ones((len(sim.time), 1)) * 0.05

    activations = np.hstack((act1, act2))

    # Method to add the muscle activations to the simulation

    sim.add_muscle_stimulations(activations)

    #: If you would like to perturb the pedulum model then you could do
    # so by
    sim.sys.pendulum_sys.parameters.PERTURBATION = True
    # The above line sets the state of the pendulum model to zeros between
    # time interval 1.2 < t < 1.25. You can change this and the type of
    # perturbation in
    # pendulum_system.py::pendulum_system function

    # Integrate the system for the above initialized state and time
    sim.simulate()

    # Obtain the states of the system after integration
    # res is np.asarray [time, states]
    # states vector is in the same order as x0
    res = sim.results()

    # In order to obtain internal states of the muscle
    # you can access the results attribute in the muscle class
    muscle_1_results = sim.sys.muscle_sys.muscle_1.results
    muscle_2_results = sim.sys.muscle_sys.muscle_2.results

    # Plotting the results
    plt.figure('Pendulum')
    plt.title('Pendulum Phase')
    plt.plot(res[:, 1], res[:, 2])
    plt.xlabel('Position [rad]')
    plt.ylabel('Velocity [rad.s]')
    plt.grid()
    '''

    ###########################################################
    ###########################################################
    ###########################################################
    ###########################################################
    ###########################################################
    ### code for 2a
    pylog.info("2a")

    theta = np.arange(np.pi / 4, np.pi * 3 / 4, 0.001)

    temp_a1 = 0.35
    ratios = [
        0.2,
        0.5,
        1.,
        2.,
        5.,
    ]

    L2_s = []
    h2_s = []

    for temp_ratio in ratios:
        temp_a2 = temp_a1 * temp_ratio
        temp_L2 = np.sqrt(temp_a1 * temp_a1 + temp_a2 * temp_a2 +
                          2 * temp_a1 * temp_a2 * np.cos(theta))
        temp_h2 = (temp_a1 * temp_a2 * np.sin(theta)) / temp_L2

        L2_s = L2_s + [temp_L2]
        h2_s = h2_s + [temp_h2]

    plt.figure(
        '2a. Relationship between muscle length and pendulum angular position')
    plt.title(
        'Relationship between  muscle length and pendulum angular position')
    for i in range(len(ratios)):
        plt.plot(theta, L2_s[i])
    plt.xlabel('Angular Position [rad]')
    plt.ylabel('Muscle Length [m]')
    temp_legends = [
        'ratio of a2/a1 = ' + format((temp_ratio), '.2f')
        for temp_ratio in ratios
    ]
    plt.legend(temp_legends)
    plt.grid()
    plt.show()

    plt.figure(
        '2a. Relationship between moment arm and pendulum angular position')
    plt.title('Relationship between moment arm and pendulum angular position')
    for i in range(len(ratios)):
        plt.plot(theta, h2_s[i])
    plt.xlabel('Angular Position [rad]')
    plt.ylabel('Moment Arm [m]')
    temp_legends = [
        'ratio of a2/a1 = ' + format((temp_ratio), '.2f')
        for temp_ratio in ratios
    ]
    plt.legend(temp_legends)
    plt.grid()
    plt.show()

    ###########################################################
    ###########################################################
    ###########################################################
    ###########################################################
    ###########################################################
    ### code for 2b
    pylog.info("2b")

    #initialization
    P_params = PendulumParameters()  # Instantiate pendulum parameters
    P_params.L = 1.0  # To change the default length of the pendulum
    P_params.m = 0.25  # To change the default mass of the pendulum
    pendulum = PendulumSystem(P_params)  # Instantiate Pendulum object
    #### CHECK OUT Pendulum.py to ADD PERTURBATIONS TO THE MODEL #####
    pylog.info('Pendulum model initialized \n {}'.format(
        pendulum.parameters.showParameters()))

    ########## MUSCLES ##########
    # Define and Setup your muscle model here
    # Check MuscleSystem.py for more details on MuscleSystem class
    m1_param = MuscleParameters()  # Instantiate Muscle 1 parameters
    m1_param.f_max = 200.  # To change Muscle 1 max force
    m1_param.l_opt = 0.4
    m1_param.l_slack = 0.45
    m2_param = MuscleParameters()  # Instantiate Muscle 2 parameters
    m2_param.f_max = 200.  # To change Muscle 2 max force
    m2_param.l_opt = 0.4
    m2_param.l_slack = 0.45
    m1 = Muscle('m1', m1_param)  # Instantiate Muscle 1 object
    m2 = Muscle('m2', m2_param)  # Instantiate Muscle 2 object
    # Use the MuscleSystem Class to define your muscles in the system
    # Instantiate Muscle System with two muscles
    muscles = MuscleSystem(m1, m2)
    pylog.info('Muscle system initialized \n {} \n {}'.format(
        m1.parameters.showParameters(), m2.parameters.showParameters()))
    # Define Muscle Attachment points
    m1_origin = np.asarray([0.0, 0.9])  # Origin of Muscle 1
    m1_insertion = np.asarray([0.0, 0.15])  # Insertion of Muscle 1

    m2_origin = np.asarray([0.0, 0.8])  # Origin of Muscle 2
    m2_insertion = np.asarray([0.0, -0.3])  # Insertion of Muscle 2
    # Attach the muscles
    muscles.attach(np.asarray([m1_origin, m1_insertion]),
                   np.asarray([m2_origin, m2_insertion]))

    ########## ADD SYSTEMS ##########
    # Create a system with Pendulum and Muscles using the System Class
    # Check System.py for more details on System class
    sys = System()  # Instantiate a new system
    sys.add_pendulum_system(pendulum)  # Add the pendulum model to the system
    sys.add_muscle_system(muscles)  # Add the muscle model to the system

    ########## INITIALIZATION ##########
    t_max = 2  # Maximum simulation time
    time = np.arange(0., t_max, 0.001)  # Time vector
    ##### Model Initial Conditions #####
    x0_P = np.asarray([np.pi / 2, 0.0])  # Pendulum initial condition
    # Muscle Model initial condition
    l_ce_0 = sys.muscle_sys.initialize_muscle_length(np.pi / 2)
    x0_M = np.asarray([0.05, l_ce_0[0], 0.05, l_ce_0[1]])
    x0 = np.concatenate((x0_P, x0_M))  # System initial conditions

    ########## System Simulation ##########
    sim = SystemSimulation(sys)  # Instantiate Simulation object
    # Simulate the system for given time
    sim.initalize_system(x0, time)  # Initialize the system state

    omega = 1.5
    sin_act_1 = np.sin(2 * np.pi * omega * time).reshape(len(time), 1)
    sin_act_1[sin_act_1 < 0] = 0
    #sin_act_2=np.sin(2*np.pi*omega*time+np.pi/2).reshape(len(time),1)
    sin_act_2 = -np.sin(2 * np.pi * omega * time).reshape(len(time), 1)
    sin_act_2[sin_act_2 < 0] = 0
    activations = np.hstack((sin_act_1, sin_act_2))

    plt.figure('2b. Activation wave')
    plt.title('Activation wave')
    plt.plot(time, sin_act_1, label='Activation 1')
    plt.plot(time, sin_act_2, label='Activation 2')
    plt.xlabel('Time [s]')
    plt.ylabel('Activation')
    plt.grid()
    plt.legend()

    # without pertubation
    sim.add_muscle_stimulations(activations)
    sim.initalize_system(x0, time)
    sim.sys.pendulum_sys.parameters.PERTURBATION = False
    sim.simulate()
    res = sim.results()
    muscle1_results = sim.sys.muscle_sys.muscle_1.results
    muscle2_results = sim.sys.muscle_sys.muscle_2.results

    plt.figure('2b. Limit cycle without pertubation')
    plt.title('Pendulum Phase without pertubation')
    plt.plot(
        res[:, 1],
        res[:, 2],
    )
    plt.xlabel('Position [rad]')
    plt.ylabel('Velocity [rad/s]')
    plt.grid()
    plt.legend()

    # with pertubation
    sim.add_muscle_stimulations(activations)
    sim.initalize_system(x0, time)
    sim.sys.pendulum_sys.parameters.PERTURBATION = True
    sim.simulate()
    res = sim.results()
    muscle1_results = sim.sys.muscle_sys.muscle_1.results
    muscle2_results = sim.sys.muscle_sys.muscle_2.results

    plt.figure('2b. Limit cycle with pertubation')
    plt.title('Pendulum Phase with pertubation')
    plt.plot(
        res[:, 1],
        res[:, 2],
    )
    plt.xlabel('Position [rad]')
    plt.ylabel('Velocity [rad/s]')
    plt.grid()
    plt.legend()

    ###########################################################
    ###########################################################
    ###########################################################
    ###########################################################
    ###########################################################
    ### code for 2c
    pylog.info("2c")

    # different frequencies
    omegas = 1.5 * np.array([0.5, 2.])

    positions = []
    vels = []

    for temp_omega in omegas:

        sin_act_1 = np.sin(2 * np.pi * temp_omega * time).reshape(len(time), 1)
        sin_act_1[sin_act_1 < 0] = 0
        sin_act_2 = -np.sin(2 * np.pi * temp_omega * time).reshape(
            len(time), 1)
        sin_act_2[sin_act_2 < 0] = 0
        activations = np.hstack((sin_act_1, sin_act_2))

        sim.add_muscle_stimulations(activations)
        sim.initalize_system(x0, time)
        sim.sys.pendulum_sys.parameters.PERTURBATION = False
        sim.simulate()
        res = sim.results()
        muscle1_results = sim.sys.muscle_sys.muscle_1.results
        muscle2_results = sim.sys.muscle_sys.muscle_2.results

        positions = positions + [res[:, 1]]
        vels = vels + [res[:, 2]]

    plt.figure('2c.Pendulum phase plane with stimulation frequencies')
    plt.title('Pendulum phase plane with stimulation frequencies')
    for i in range(len(omegas)):
        plt.plot(positions[i], vels[i])
    plt.xlabel('Angular Position [rad]')
    plt.ylabel('Velocity [rad/s]')
    temp_legends = [
        'ratio of frequency = ' + format((temp_omega / 1.5), '.2f')
        for temp_omega in omegas
    ]
    plt.legend(temp_legends)
    plt.grid()
    plt.show()
    '''
    # different frequencies
    omegas=1.5*np.array([0.2,0.5,1.,2.,5.])
    
    positions=[]
    vels=[]
    
    for temp_omega in omegas:
        
        sin_act_1=np.sin(2*np.pi*temp_omega*time).reshape(len(time),1)
        sin_act_1[sin_act_1<0]=0
        sin_act_2=np.sin(2*np.pi*temp_omega*(np.pi/6+time)).reshape(len(time),1)
        sin_act_2[sin_act_2<0]=0
        activations = np.hstack((sin_act_1,sin_act_2)) 
        
        sim.add_muscle_stimulations(activations)
        sim.initalize_system(x0, time)
        sim.sys.pendulum_sys.parameters.PERTURBATION = False
        sim.simulate()
        res = sim.results()
        muscle1_results = sim.sys.muscle_sys.muscle_1.results
        muscle2_results = sim.sys.muscle_sys.muscle_2.results
        
        positions=positions+[res[:, 1]]
        vels=vels+[res[:,2]]
    
    
    plt.figure('2c.Pendulum phase plane with stimulation frequencies')    
    plt.title('Pendulum phase plane with stimulation frequencies')
    for i in range(len(ratios)):
        plt.plot(positions[i], vels[i])
    plt.xlabel('Angular Position [rad]')
    plt.ylabel('Muscle Length [m]')
    temp_legends=['ratio of frequency = '+ format((temp_omega/1.5),'.2f') for temp_omega in omegas]
    plt.legend(temp_legends)
    plt.grid()
    plt.show()
    '''

    # To animate the model, use the SystemAnimation class
    # Pass the res(states) and systems you wish to animate
    simulation = SystemAnimation(res, sim.sys.pendulum_sys, sim.sys.muscle_sys)
    if not DEFAULT["save_figures"]:
        # To start the animation
        simulation.animate()
        plt.show()
    else:
        figures = plt.get_figlabels()
        pylog.debug("Saving figures:\n{}".format(figures))
        for fig in figures:
            plt.figure(fig)
            save_figure(fig)
            plt.close(fig)
Esempio n. 4
0
def system_init():
    """ Use this function to create a new default system. """
    ########## PENDULUM ##########
    # Define and Setup your pendulum model here
    # Check Pendulum.py for more details on Pendulum class
    P_params = PendulumParameters()  # Instantiate pendulum parameters
    P_params.L = 1.0  # To change the default length of the pendulum
    P_params.m = 0.25  # To change the default mass of the pendulum
    pendulum = PendulumSystem(P_params)  # Instantiate Pendulum object

    #### CHECK OUT Pendulum.py to ADD PERTURBATIONS TO THE MODEL #####

    pylog.info('Pendulum model initialized \n {}'.format(
        pendulum.parameters.showParameters()))

    ########## MUSCLES ##########
    # Define and Setup your muscle model here
    # Check MuscleSystem.py for more details on MuscleSystem class
    m1_param = MuscleParameters()  # Instantiate Muscle 1 parameters
    m1_param.f_max = 200.  # To change Muscle 1 max force
    m1_param.l_opt = 0.4
    m1_param.l_slack = 0.45
    m2_param = MuscleParameters()  # Instantiate Muscle 2 parameters
    m2_param.f_max = 200.  # To change Muscle 2 max force
    m2_param.l_opt = 0.4
    m2_param.l_slack = 0.45
    m1 = Muscle('m1', m1_param)  # Instantiate Muscle 1 object
    m2 = Muscle('m2', m2_param)  # Instantiate Muscle 2 object
    # Use the MuscleSystem Class to define your muscles in the system
    # Instantiate Muscle System with two muscles
    muscles = MuscleSystem(m1, m2)
    pylog.info('Muscle system initialized \n {} \n {}'.format(
        m1.parameters.showParameters(), m2.parameters.showParameters()))
    # Define Muscle Attachment points
    m1_origin = np.asarray([0.0, 0.9])  # Origin of Muscle 1
    m1_insertion = np.asarray([0.0, 0.15])  # Insertion of Muscle 1

    m2_origin = np.asarray([0.0, 0.8])  # Origin of Muscle 2
    m2_insertion = np.asarray([0.0, -0.3])  # Insertion of Muscle 2
    # Attach the muscles
    muscles.attach(np.asarray([m1_origin, m1_insertion]),
                   np.asarray([m2_origin, m2_insertion]))

    ########## Network ##########
    # The network consists of four neurons
    N_params = NetworkParameters()  # Instantiate default network parameters
    N_params.D = 1  # To change a network parameter
    # Similarly to change w -> N_params.w = (4x4) array
    N_params.tau = [0.02, 0.02, 0.1, 0.1]
    N_params.w = [[0, -5, 5, -5], [-5, 0, -5, 5], [-5, 0, 0, 0], [0, -5, 0, 0]]
    N_params.b = [3.0, 3.0, -3.0, -3.0]
    N_params.w = np.transpose(N_params.w)
    # Create a new neural network with above parameters
    neural_network = NeuralSystem(N_params)
    pylog.info('Neural system initialized \n {}'.format(
        N_params.showParameters()))

    ########## ADD SYSTEMS ##########
    # Create system of Pendulum, Muscles and neural network using SystemClass
    # Check System.py for more details on System class
    sys = System()  # Instantiate a new system
    sys.add_pendulum_system(pendulum)  # Add the pendulum model to the system
    sys.add_muscle_system(muscles)  # Add the muscle model to the system
    # Add the neural network to the system
    sys.add_neural_system(neural_network)

    ##### Time #####
    t_max = 2.5  # Maximum simulation time
    time = np.arange(0., t_max, 0.001)  # Time vector

    ##### Model Initial Conditions #####
    x0_P = np.asarray([np.pi / 2, 0.])  # Pendulum initial condition

    # Muscle Model initial condition
    l_ce_0 = sys.muscle_sys.initialize_muscle_length(np.pi / 2)
    x0_M = np.asarray([0.05, l_ce_0[0], 0.05, l_ce_0[1]])

    x0_N = np.asarray([-0.5, 1, 0.5, 1])  # Neural Network Initial Conditions

    x0 = np.concatenate((x0_P, x0_M, x0_N))  # System initial conditions

    ##### System Simulation #####
    # For more details on System Simulation check SystemSimulation.py
    # SystemSimulation is used to initialize the system and integrate
    # over time
    sim = SystemSimulation(sys)  # Instantiate Simulation object
    sim.initalize_system(x0, time)  # Initialize the system state
    return sim
def exercise3():
    """ Main function to run for Exercise 3.

    Parameters
    ----------
        None

    Returns
    -------
        None
    """
    '''
    # Create system
    sim = system_init()

    # Add external inputs to neural network
    sim.add_external_inputs_to_network(np.ones((len(sim.time), 4)))

    # Integrate the system for the above initialized state and time
    sim.simulate()

    # Obtain the states of the system after integration
    # res is np.asarray [time, states]
    # states vector is in the same order as x0
    res = sim.results()

    # Obtain the states of the system after integration
    # res is np.asarray [time, states]
    # states vector is in the same order as x0
    res = sim.results()

    # In order to obtain internal states of the muscle
    # you can access the results attribute in the muscle class
    muscle_1_results = sim.sys.muscle_sys.muscle_1.results
    muscle_2_results = sim.sys.muscle_sys.muscle_2.results

    # Plotting the results
    plt.figure('Pendulum')
    plt.title('Pendulum Phase')
    plt.plot(res[:, 1], res[:, 2])
    plt.xlabel('Position [rad]')
    plt.ylabel('Velocity [rad.s]')
    plt.grid()
    '''

    ######################################################
    #  initialization

    ########## PENDULUM ##########
    P_params = PendulumParameters()
    P_params.L = 1.0
    P_params.m = 0.25
    pendulum = PendulumSystem(P_params)

    pylog.info('Pendulum model initialized \n {}'.format(
        pendulum.parameters.showParameters()))

    ########## MUSCLES ##########
    m1_param = MuscleParameters()
    m1_param.f_max = 200.
    m1_param.l_opt = 0.4
    m1_param.l_slack = 0.45
    m2_param = MuscleParameters()
    m2_param.f_max = 200.
    m2_param.l_opt = 0.4
    m2_param.l_slack = 0.45
    m1 = Muscle('m1', m1_param)
    m2 = Muscle('m2', m2_param)
    muscles = MuscleSystem(m1, m2)

    pylog.info('Muscle system initialized \n {} \n {}'.format(
        m1.parameters.showParameters(), m2.parameters.showParameters()))

    ######## Define Muscle Attachment points
    m1_origin = np.asarray([0.0, 0.9])
    m1_insertion = np.asarray([0.0, 0.15])
    m2_origin = np.asarray([0.0, 0.8])
    m2_insertion = np.asarray([0.0, -0.3])
    muscles.attach(np.asarray([m1_origin, m1_insertion]),
                   np.asarray([m2_origin, m2_insertion]))

    ##### Time #####
    t_max = 2.5
    time = np.arange(0., t_max, 0.001)

    ###########################################################
    ###########################################################
    ###########################################################
    ###########################################################
    ###########################################################
    ### code for 3a
    pylog.info("3a")

    d = 1.
    tau = np.array([0.02, 0.02, 0.1, 0.1])
    b = np.array([3., 3., -3., -3.])
    w = np.zeros((4, 4))
    w[0, 1] = w[0, 3] = w[1, 0] = w[1, 2] = -5
    w[0, 2] = w[1, 3] = 5
    w[2, 0] = w[3, 1] = -5
    w = w.T

    N_params = NetworkParameters()
    N_params.D = d
    N_params.tau = tau
    N_params.b = b
    N_params.w = w
    neural_network = NeuralSystem(N_params)

    sys = System()
    sys.add_pendulum_system(pendulum)
    sys.add_muscle_system(muscles)
    sys.add_neural_system(neural_network)

    x0_P = np.asarray([np.pi / 2, 0.])
    l_ce_0 = sys.muscle_sys.initialize_muscle_length(np.pi / 2)
    x0_M = np.asarray([0.05, l_ce_0[0], 0.05, l_ce_0[1]])
    x0_N = np.asarray([-0.5, 1, 0.5, 1])
    x0 = np.concatenate((x0_P, x0_M, x0_N))

    sim = SystemSimulation(sys)
    sim.initalize_system(x0, time)
    sim.simulate()
    res = sim.results()

    positions = res[:, 1]
    vels = res[:, 2]

    plt.figure('3a. Activation with time ')
    plt.title('Activation with time')
    plt.plot(res[:, 0], res[:, 3], label="Activation 1")
    plt.plot(res[:, 0], res[:, 5], label="Activation 2")
    plt.xlabel('Time [s]')
    plt.ylabel('Activation')
    plt.legend()
    plt.grid()
    plt.show()

    # Plotting the results
    plt.figure('3a. Pendulum state with time')
    plt.title('Pendulum state with time')
    plt.plot(res[:, 0], positions)
    plt.xlabel('Time [s]')
    plt.ylabel('Position [rad]')
    plt.grid()
    plt.show()

    # Plotting the results
    plt.figure('3a. Pendulum phase plot')
    plt.title('Pendulum phase plot')
    plt.plot(positions, vels)
    plt.xlabel('Position [rad]')
    plt.ylabel('Velocity [rad/s]')
    plt.grid()
    plt.show()

    ###########################################################
    ###########################################################
    ###########################################################
    ###########################################################
    ###########################################################
    ### code for 3b
    pylog.info("3b")

    all_positions = []
    all_vels = []
    all_time = []
    all_act_1 = []
    all_act_2 = []

    external_drives = np.array([0, 0.2, 0.5, 1., 2., 5.])
    for temp_drive in external_drives:
        sim = SystemSimulation(sys)
        sim.initalize_system(x0, time)
        sim.add_external_inputs_to_network(
            np.ones((len(sim.time), 4)) * temp_drive)
        sim.simulate()
        res = sim.results()

        all_time = all_time + [res[:, 0]]
        all_positions = all_positions + [res[:, 1]]
        all_vels = all_vels + [res[:, 2]]
        all_act_1 = all_act_1 + [res[:, 3]]
        all_act_2 = all_act_2 + [res[:, 5]]

    plt.figure('3a. Activation with time by different external drives')
    plt.title('Activation with time by different external drives')
    for i in range(len(external_drives)):
        plt.plot(all_time[i], all_act_1[i])
        plt.plot(all_time[i], all_act_2[i])
    plt.xlabel('Time [s]')
    plt.ylabel('Activation')
    temp_legends = [
        'external drive: ' + format((temp_drive), '.2f')
        for temp_drive in external_drives
    ]
    plt.legend(temp_legends)
    plt.grid()
    plt.show()

    plt.figure('3b. Pendulum state with time by different external drives')
    plt.title('Pendulum state with time by different external drives')
    for i in range(len(external_drives)):
        plt.plot(all_time[i], all_positions[i])
    plt.xlabel('Time [s]')
    plt.ylabel('Position [rad]')
    temp_legends = [
        'external drive: ' + format((temp_drive), '.2f')
        for temp_drive in external_drives
    ]
    plt.legend(temp_legends)
    plt.grid()
    plt.show()

    plt.figure('3a. Pendulum phase plot by different external drives')
    plt.title('Pendulum phase plot by different external drives')
    for i in range(len(external_drives)):
        plt.plot(all_positions[i], all_vels[i])
    plt.xlabel('Position [rad]')
    plt.ylabel('Velocity [rad/s]')
    temp_legends = [
        'external drive: ' + format((temp_drive), '.2f')
        for temp_drive in external_drives
    ]
    plt.legend(temp_legends)
    plt.grid()
    plt.show()

    # To animate the model, use the SystemAnimation class
    # Pass the res(states) and systems you wish to animate
    simulation = SystemAnimation(res, sim.sys.pendulum_sys, sim.sys.muscle_sys,
                                 sim.sys.neural_sys)

    if DEFAULT["save_figures"] is False:
        # To start the animation
        simulation.animate()
        plt.show()
    else:
        figures = plt.get_figlabels()
        pylog.debug("Saving figures:\n{}".format(figures))
        for fig in figures:
            plt.figure(fig)
            save_figure(fig)
            plt.close(fig)
Esempio n. 6
0
def isometric_experiment(muscle_stimulation=1.,
                         ce_stretch_max=1.5,
                         ce_stretch_min=0.5,
                         nb_pts=1000,
                         time_param=TimeParameters(),
                         l_opt=None):
    """ Runs a experiments in isometric mode for multiple stretches, returns the results
    Parameters:
        - muscle_stimulation: applied stimulation.
        - ce_stretch_max: the maximal stretch to apply to the contractile element.
        - ce_stretch_min: the minimal stretch to apply to the contractile element.
        - nb_pts: the number of times the experiment should be ran between the min and max stretch.
         (i.e number of points in the results)
        - time_param: A TimeParameters object to pass the intended time parameters for every experiment.
        - l_opt: The optimal length of the contractile element. If None the default one is taken
    Returns every parameters for the experiments.
    """

    # System definition
    parameters = MuscleParameters()
    if l_opt is not None:
        parameters.l_opt = l_opt
    muscle = Muscle(parameters)
    sys = IsometricMuscleSystem()
    sys.add_muscle(muscle)

    # Experiment parameters
    muscle_stretch_max = find_ce_stretch_iso(sys, ce_stretch_max, time_param)
    muscle_stretch_min = find_ce_stretch_iso(sys, ce_stretch_min, time_param)
    stretches = np.arange(muscle_stretch_min, muscle_stretch_max,
                          muscle_stretch_max / nb_pts)
    x0 = [0] * StatesIsometric.NB_STATES.value
    x0[StatesIsometric.STIMULATION.value] = 0
    x0[StatesIsometric.L_CE.value] = sys.muscle.L_OPT

    # Containers
    active_force = []
    passive_force = []
    total_force = []
    l_ce = []
    l_slack = []
    l_mtc = []

    # Experiences
    pylog.info(
        "Running isometric experiments for stretches (this might take a while)..."
    )

    for stretch in stretches:
        result = sys.integrate(x0=x0,
                               time=time_param.times,
                               time_step=time_param.t_step,
                               stimulation=muscle_stimulation,
                               muscle_length=stretch)
        active_force.append(result.active_force[-1])
        passive_force.append(result.passive_force[-1])
        total_force.append(result.tendon_force[-1])
        l_ce.append(result.l_ce[-1])
        l_mtc.append(result.l_mtc[-1])
        l_slack.append(result.l_mtc[-1] - result.l_ce[-1])

    return active_force, passive_force, total_force, l_ce, l_slack, l_mtc