Пример #1
0
def exercise2():
    """ Main function to run for Exercise 2.

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

    Returns
    -------
        None
    """

    # Define and Setup your pendulum model here
    # Check PendulumSystem.py for more details on Pendulum class
    pendulum_params = PendulumParameters()  # Instantiate pendulum parameters
    pendulum_params.L = 0.5  # To change the default length of the pendulum
    pendulum_params.m = 1.  # To change the default mass of the pendulum
    pendulum = PendulumSystem(pendulum_params)  # Instantiate Pendulum object

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

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

    # Define and Setup your pendulum model here
    # Check MuscleSytem.py for more details on MuscleSytem class
    M1_param = MuscleParameters()  # Instantiate Muscle 1 parameters
    M1_param.f_max = 1500  # To change Muscle 1 max force
    M2_param = MuscleParameters()  # Instantiate Muscle 2 parameters
    M2_param.f_max = 1500  # To change Muscle 2 max force
    M1 = Muscle(M1_param)  # Instantiate Muscle 1 object
    M2 = Muscle(M2_param)  # Instantiate Muscle 2 object
    # Use the MuscleSystem Class to define your muscles in the system
    muscles = MuscleSytem(M1, M2)  # Instantiate Muscle System with two muscles
    pylog.info('Muscle system initialized \n {} \n {}'.format(
        M1.parameters.showParameters(), M2.parameters.showParameters()))

    # Define Muscle Attachment points
    m1_origin = np.array([-0.17, 0.0])  # Origin of Muscle 1
    m1_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 1

    m2_origin = np.array([0.17, 0.0])  # Origin of Muscle 2
    m2_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 2

    # Attach the muscles
    muscles.attach(np.array([m1_origin, m1_insertion]),
                   np.array([m2_origin, m2_insertion]))

    # 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

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

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

    # Muscle Model initial condition
    x0_M = np.array([0., M1.L_OPT, 0., M2.L_OPT])

    x0 = np.concatenate((x0_P, x0_M))  # 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

    # Add muscle activations to the simulation
    # Here you can define your muscle activation vectors
    # that are time dependent
    sin_freq = 1  #hz
    ampl_sin = 1
    phase_difference_1_2 = np.pi
    act1 = np.ones((len(time), 1))
    act2 = np.ones((len(time), 1))
    for i in range(len(time)):
        act1[i, 0] = ampl_sin * (1 + np.sin(2 * np.pi * sin_freq * time[i]))
        act2[i, 0] = ampl_sin * (
            1 + np.sin(2 * np.pi * sin_freq * time[i] + phase_difference_1_2))
    activations = np.hstack((act1, act2))

    # Method to add the muscle activations to the simulation

    sim.add_muscle_activations(activations)

    # Simulate the system for given time

    sim.initalize_system(x0, time)  # Initialize the system state

    #: 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.array [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
    muscle1_results = sim.sys.muscle_sys.Muscle1.results
    muscle2_results = sim.sys.muscle_sys.Muscle2.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()
    plt.figure('Activations')
    plt.title('Sine wave activations for both muscles')
    plt.plot(time, act1)
    plt.plot(time, act2)
    plt.legend(("activation muscle1", "activation muscle2"))
    # To animate the model, use the SystemAnimation class
    # Pass the res(states) and systems you wish to animate
    simulation = SystemAnimation(res, pendulum, muscles)
    # To start the animation
    if DEFAULT["save_figures"] is False:
        simulation.animate()

    if not DEFAULT["save_figures"]:
        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)
Пример #2
0
def exercise2c():
    pendulum_params = PendulumParameters()  # Instantiate pendulum parameters
    pendulum_params.L = 0.5  # To change the default length of the pendulum
    pendulum_params.m = 1.  # To change the default mass of the pendulum
    pendulum = PendulumSystem(pendulum_params)  # Instantiate Pendulum object

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

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

    # Define and Setup your pendulum model here
    # Check MuscleSytem.py for more details on MuscleSytem class
    M1_param = MuscleParameters()  # Instantiate Muscle 1 parameters
    M1_param.f_max = 1500  # To change Muscle 1 max force
    M2_param = MuscleParameters()  # Instantiate Muscle 2 parameters
    M2_param.f_max = 1500  # To change Muscle 2 max force
    M1 = Muscle(M1_param)  # Instantiate Muscle 1 object
    M2 = Muscle(M2_param)  # Instantiate Muscle 2 object
    # Use the MuscleSystem Class to define your muscles in the system
    muscles = MuscleSytem(M1, M2)  # Instantiate Muscle System with two muscles
    pylog.info('Muscle system initialized \n {} \n {}'.format(
        M1.parameters.showParameters(), M2.parameters.showParameters()))

    # Define Muscle Attachment points
    m1_origin = np.array([-0.17, 0.0])  # Origin of Muscle 1
    m1_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 1

    m2_origin = np.array([0.17, 0.0])  # Origin of Muscle 2
    m2_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 2

    # Attach the muscles
    muscles.attach(np.array([m1_origin, m1_insertion]),
                   np.array([m2_origin, m2_insertion]))

    # 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

    ##### Model Initial Conditions #####
    x0_P = np.array([0, 0.])  # Pendulum initial condition

    # Muscle Model initial condition
    x0_M = np.array([0., M1.L_OPT, 0., M2.L_OPT])

    x0 = np.concatenate((x0_P, x0_M))  # 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

    #Frequency effect :

    stim_frequency = np.array([0.05, 0.1, 0.5, 1, 5, 10, 50, 100, 500])  #in Hz

    stim_amplitude = 1  # belongs to 0-1
    phase = np.pi

    frequency_pendelum = np.zeros(len(stim_frequency))
    amplitude_pendelum = np.zeros(len(stim_frequency))
    for j, frequency in enumerate(stim_frequency):
        t_max = 5 / frequency  # Maximum simulation time
        time_step = 0.001 * (1 / frequency)
        time = np.arange(0., t_max, time_step)  # Time vector

        act1 = np.zeros((len(time), 1))
        act2 = np.zeros((len(time), 1))
        act1[:,
             0] = stim_amplitude * (1 +
                                    np.sin(2 * np.pi * frequency * time)) / 2
        act2[:, 0] = stim_amplitude * (
            1 + np.sin(2 * np.pi * frequency * time + phase)) / 2
        activations = np.hstack((act1, act2))
        sim.add_muscle_activations(activations)
        sim.initalize_system(x0, time)  # Initialize the system state
        sim.simulate()
        res = sim.results()
        #computing the freuquency and amplitude
        angular_position = res[:, 1]
        #signal_stat = signal[index_start:len(signal)]
        start_index = int(len(angular_position) / 2)
        final_index = (len(angular_position))
        index_zeros = np.where(
            np.diff(np.sign(angular_position[start_index:final_index])))[
                0]  #np.where(signal_stat==0)[0]
        deltas = np.diff(index_zeros)
        delta = np.mean(deltas)

        frequency_pendelum[j] = 1 / (2 * delta * time_step)
        signal = angular_position[start_index:len(angular_position)]
        amplitude = (np.max(signal) - np.min(signal)) / 2
        amplitude_pendelum[j] = amplitude

    plt.figure()
    plt.subplot(121)
    plt.loglog(stim_frequency, frequency_pendelum)
    plt.grid()
    plt.xlabel('Stimulation Frequency [Hz]')
    plt.ylabel('Pendulum Oscillation Frequency [Hz]')
    plt.subplot(122)
    plt.loglog(stim_frequency, amplitude_pendelum)
    plt.grid()
    plt.xlabel('Stimulation Frequency [Hz]')
    plt.ylabel('Pendulum Oscillation Amplitude [rad]')
    plt.savefig('2c.png')
    plt.show()
    stim_frequency = 10  #in Hz
    stim_amplitude = np.arange(0, 1.1, 0.1)
    frequency_pendelum = np.zeros(len(stim_amplitude))
    amplitude_pendelum = np.zeros(len(stim_amplitude))

    for j, amplitude_ in enumerate(stim_amplitude):
        t_max = 5 / stim_frequency  # Maximum simulation time
        time_step = 0.001 * (1 / stim_frequency)
        time = np.arange(0., t_max, time_step)  # Time vector

        act1 = np.zeros((len(time), 1))
        act2 = np.zeros((len(time), 1))
        act1[:,
             0] = amplitude_ * (1 +
                                np.sin(2 * np.pi * stim_frequency * time)) / 2
        act2[:, 0] = amplitude_ * (
            1 + np.sin(2 * np.pi * stim_frequency * time + phase)) / 2
        activations = np.hstack((act1, act2))
        sim.add_muscle_activations(activations)
        sim.initalize_system(x0, time)  # Initialize the system state
        sim.simulate()
        res = sim.results()
        #computing the freuquency and amplitude
        angular_position = res[:, 1]
        #signal_stat = signal[index_start:len(signal)]
        start_index = int(len(angular_position) / 2)
        final_index = (len(angular_position))
        index_zeros = np.where(
            np.diff(np.sign(angular_position[start_index:final_index])))[
                0]  #np.where(signal_stat==0)[0]
        deltas = np.diff(index_zeros)
        delta = np.mean(deltas)

        frequency_pendelum[j] = 1 / (2 * delta * time_step)
        signal = angular_position[start_index:len(angular_position)]
        amplitude = (np.max(signal) - np.min(signal)) / 2
        amplitude_pendelum[j] = amplitude
    frequency_pendelum[0] = 0
    plt.figure()
    plt.subplot(121)
    plt.plot(stim_amplitude, frequency_pendelum)
    plt.grid()
    plt.xlabel('Stimulation Amplitude [rad]')
    plt.ylabel('Pendulum Oscillation Frequency [Hz]')
    plt.subplot(122)
    plt.plot(stim_amplitude, amplitude_pendelum)
    plt.grid()
    plt.xlabel('Stimulation Amplitude[rad]')
    plt.ylabel('Pendulum Oscillation Amplitude [rad]')
    plt.savefig('2c_amplitude.png')
    plt.show()
Пример #3
0
def exercise2c():
    """ Main function to run for Exercise 2c.

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

    Returns
    -------
        None
    """
    # Define and Setup your pendulum model here
    # Check PendulumSystem.py for more details on Pendulum class
    pendulum_params = PendulumParameters()  # Instantiate pendulum parameters
    pendulum_params.L = 0.5  # To change the default length of the pendulum
    pendulum_params.m = 1.  # To change the default mass of the pendulum
    pendulum = PendulumSystem(pendulum_params)  # Instantiate Pendulum object

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

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

    # Define and Setup your pendulum model here
    # Check MuscleSytem.py for more details on MuscleSytem class
    M1_param = MuscleParameters()  # Instantiate Muscle 1 parameters
    M1_param.f_max = 1500  # To change Muscle 1 max force
    M2_param = MuscleParameters()  # Instantiate Muscle 2 parameters
    M2_param.f_max = 1500  # To change Muscle 2 max force
    M1 = Muscle(M1_param)  # Instantiate Muscle 1 object
    M2 = Muscle(M2_param)  # Instantiate Muscle 2 object
    # Use the MuscleSystem Class to define your muscles in the system
    muscles = MuscleSytem(M1, M2)  # Instantiate Muscle System with two muscles
    pylog.info('Muscle system initialized \n {} \n {}'.format(
        M1.parameters.showParameters(), M2.parameters.showParameters()))

    # Define Muscle Attachment points
    m1_origin = np.array([-0.17, 0.0])  # Origin of Muscle 1
    m1_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 1

    m2_origin = np.array([0.17, 0.0])  # Origin of Muscle 2
    m2_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 2

    # Attach the muscles
    muscles.attach(np.array([m1_origin, m1_insertion]),
                   np.array([m2_origin, m2_insertion]))

    # 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

    ##### Time #####
    t_max = 15  # Maximum simulation time
    time = np.arange(0., t_max, 0.005)  # Time vector

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

    # Muscle Model initial condition
    x0_M = np.array([0., M1.L_OPT, 0., M2.L_OPT])

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

    sim = SystemSimulation(sys)  # Instantiate Simulation object

    plt.figure('Pendulum with different stimulation frequencies')
    frequencies = [0.25, 0.5, 0.75, 1.0, 2.0, 3.0, 4.0, 5.0]

    for freq in frequencies:
        act1 = np.array([np.sin(freq * time)]).T
        act2 = np.array([-np.sin(freq * time)]).T

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

        # Method to add the muscle activations to the simulation

        sim.add_muscle_activations(activations)

        # Simulate the system for given time

        sim.initalize_system(x0, time)  # Initialize the system state

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

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

        # Plotting the results
        plt.plot(res[:, 1], res[:, 2])

    plt.title('Pendulum Phase')
    plt.xlabel('Position [rad]')
    plt.ylabel('Velocity [rad.s]')
    plt.legend((
        '0.25',
        '0.5',
        '0.75',
        '1.0',
        '2.0',
        '3.0',
        '4.0',
        '5.0',
    ))
    plt.grid()

    plt.figure('Pendulum with different stimulation amplitudes')
    amplitudes = [0.25, 0.5, 0.75, 1.0, 2.0, 3.0, 4.0, 5.0]

    for amp in amplitudes:
        act1 = np.array([amp * np.sin(time)]).T
        act2 = np.array([amp * (-np.sin(time))]).T

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

        # Method to add the muscle activations to the simulation

        sim.add_muscle_activations(activations)

        # Simulate the system for given time

        sim.initalize_system(x0, time)  # Initialize the system state

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

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

        # Plotting the results
        plt.plot(res[:, 1], res[:, 2])

    plt.title('Pendulum Phase')
    plt.xlabel('Position [rad]')
    plt.ylabel('Velocity [rad.s]')
    plt.legend((
        '0.25',
        '0.5',
        '0.75',
        '1.0',
        '2.0',
        '3.0',
        '4.0',
        '5.0',
    ))
    plt.grid()
Пример #4
0
def exercise2b():
    """ Main function to run for Exercise 2b.

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

    Returns
    -------
        None
    """
    # Define and Setup your pendulum model here
    # Check PendulumSystem.py for more details on Pendulum class
    pendulum_params = PendulumParameters()  # Instantiate pendulum parameters
    pendulum_params.L = 0.5  # To change the default length of the pendulum
    pendulum_params.m = 1.  # To change the default mass of the pendulum
    pendulum = PendulumSystem(pendulum_params)  # Instantiate Pendulum object

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

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

    # Define and Setup your pendulum model here
    # Check MuscleSytem.py for more details on MuscleSytem class
    M1_param = MuscleParameters()  # Instantiate Muscle 1 parameters
    M1_param.f_max = 1500  # To change Muscle 1 max force
    M2_param = MuscleParameters()  # Instantiate Muscle 2 parameters
    M2_param.f_max = 1500  # To change Muscle 2 max force
    M1 = Muscle(M1_param)  # Instantiate Muscle 1 object
    M2 = Muscle(M2_param)  # Instantiate Muscle 2 object
    # Use the MuscleSystem Class to define your muscles in the system
    muscles = MuscleSytem(M1, M2)  # Instantiate Muscle System with two muscles
    pylog.info('Muscle system initialized \n {} \n {}'.format(
        M1.parameters.showParameters(), M2.parameters.showParameters()))

    # Define Muscle Attachment points
    m1_origin = np.array([-0.17, 0.0])  # Origin of Muscle 1
    m1_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 1

    m2_origin = np.array([0.17, 0.0])  # Origin of Muscle 2
    m2_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 2

    # Attach the muscles
    muscles.attach(np.array([m1_origin, m1_insertion]),
                   np.array([m2_origin, m2_insertion]))

    # 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

    ##### Time #####
    t_max = 20  # Maximum simulation time
    time = np.arange(0., t_max, 0.005)  # Time vector

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

    # Muscle Model initial condition
    x0_M = np.array([0., M1.L_OPT, 0., M2.L_OPT])

    x0 = np.concatenate((x0_P, x0_M))  # 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

    sim1 = SystemSimulation(sys)  # Instantiate Simulation object

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

    #act1 = np.ones((len(time), 1)) * 1.
    #act2 = np.ones((len(time), 1)) * 0.05
    act1 = np.array([np.sin(time)]).T
    act2 = np.array([-np.sin(time)]).T

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

    # Method to add the muscle activations to the simulation

    sim1.add_muscle_activations(activations)

    # Simulate the system for given time

    sim1.initalize_system(x0, time)  # Initialize the system state

    #: 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
    sim1.simulate()

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

    sim2 = SystemSimulation(sys)  # Instantiate Simulation object
    sim2.add_muscle_activations(activations)

    # Simulate the system for given time

    sim2.initalize_system(x0, time)  # Initialize the system state
    #add perturbation
    sim2.sys.pendulum_sys.parameters.PERTURBATION = True

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

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

    # In order to obtain internal states of the muscle
    # you can access the results attribute in the muscle class
    muscle1_results = sim1.sys.muscle_sys.Muscle1.results
    muscle2_results = sim1.sys.muscle_sys.Muscle2.results

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

    plt.figure('Pendulum with perturbation')
    plt.title('Pendulum Phase')
    plt.plot(res2[:, 1], res2[:, 2])
    plt.xlabel('Position [rad]')
    plt.ylabel('Velocity [rad.s]')
    plt.grid()

    plt.figure('Activation Wave Forms')
    plt.title('Activation Wave Forms')
    plt.plot(time, act1)
    plt.plot(time, act2)
    plt.xlabel('Time [s]')
    plt.ylabel('Activation')
    plt.legend(('Actication muscle 1', 'Activation muscle 2'))
    plt.grid

    poincare_crossings(res1, 0.5, 1, "poincare_cross")

    # To animate the model, use the SystemAnimation class
    # Pass the res(states) and systems you wish to animate
    simulation1 = SystemAnimation(res1, pendulum, muscles)
    simulation2 = SystemAnimation(res2, pendulum, muscles)
    # To start the animation
    if DEFAULT["save_figures"] is False:
        simulation1.animate()
        simulation2.animate()
Пример #5
0
def exercise2():
    """ Main function to run for Exercise 2.
    """

    # Define and Setup your pendulum model here
    # Check PendulumSystem.py for more details on Pendulum class
    pendulum_params = PendulumParameters()  # Instantiate pendulum parameters
    pendulum_params.L = 0.5  # To change the default length of the pendulum
    pendulum_params.m = 1.  # To change the default mass of the pendulum
    pendulum = PendulumSystem(pendulum_params)  # Instantiate Pendulum object

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

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

    # Define and Setup your pendulum model here
    # Check MuscleSytem.py for more details on MuscleSytem class
    M1_param = MuscleParameters()  # Instantiate Muscle 1 parameters
    M1_param.f_max = 1500  # To change Muscle 1 max force
    M2_param = MuscleParameters()  # Instantiate Muscle 2 parameters
    M2_param.f_max = 1500  # To change Muscle 2 max force
    M1 = Muscle(M1_param)  # Instantiate Muscle 1 object
    M2 = Muscle(M2_param)  # Instantiate Muscle 2 object
    # Use the MuscleSystem Class to define your muscles in the system
    muscles = MuscleSytem(M1, M2)  # Instantiate Muscle System with two muscles
    pylog.info('Muscle system initialized \n {} \n {}'.format(
        M1.parameters.showParameters(),
        M2.parameters.showParameters()))

    # 2a : set of muscle 1 attachment points
    
    m1_origin = np.array([[-0.17, 0.0]])  # Origin of Muscle 1
    m1_insertion = np.array([[0.0, -0.17], [0.0, -0.3], [0.0, -0.4], [0.0, -0.5]])  # Insertion of Muscle 1
    
    theta = np.linspace(-np.pi/2,np.pi/2)
        
    m_lengths = np.zeros((len(m1_insertion),len(theta)))
    m_moment_arms = np.zeros((len(m1_insertion),len(theta)))
    leg=[]
    for i in range(0,len(m1_insertion)):
        m_lengths[i,:]=np.sqrt(m1_origin[0,0]**2 + m1_insertion[i,1]**2 +
                         2 * np.abs(m1_origin[0,0]) * np.abs(m1_insertion[i,1]) * np.sin(theta))
        m_moment_arms[i,:]= m1_origin[0,0] * m1_insertion[i,1] * np.cos(theta) / m_lengths[i,:]
        leg.append('Origin: {}m, Insertion: {}m'.format(m1_origin[0,0],m1_insertion[i,1]))
        
    # Plotting
    plt.figure('2a length')
    plt.title('Length of M1 with respect to the position of the limb') 
    for i in range(0,len(m_lengths)):
        plt.plot(theta*180/np.pi, m_lengths[i,:])
    plt.plot((theta[0]*180/np.pi,theta[len(theta)-1]*180/np.pi),(0.11,0.11), ls='dashed')
    leg.append('l_opt')
    plt.plot((theta[0]*180/np.pi,theta[len(theta)-1]*180/np.pi),(0.13,0.13), ls='dashed')
    leg.append('l_slack') 
    plt.xlabel('Position [deg]')
    plt.ylabel('Muscle length [m]')
    plt.legend(leg)
    plt.grid()
    plt.savefig('2_a_length.png')
    
    plt.figure('2a moment')
    plt.title('Moment arm over M1 with respect to the position of the limb')
    for i in range(0,len(m_moment_arms)):
        plt.plot(theta*180/np.pi, m_moment_arms[i,:])
    plt.xlabel('Position [deg]')
    plt.ylabel('Moment arm [m]')
    plt.legend(leg)
    plt.grid()
    plt.savefig('2_a_moment.png')
    
    
    # 2b : simple activation wave forms
        
    # Muscle 2 attachement point
    m2_origin = np.array([0.17, 0.0])  # Origin of Muscle 2
    m2_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 2
    
    # Attach the muscles
    muscles.attach(np.array([m1_origin[0,:], m1_insertion[0,:]]),
                   np.array([m2_origin, m2_insertion]))

    # 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

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

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

    # Muscle Model initial condition
    x0_M = np.array([0., M1.L_OPT, 0., M2.L_OPT])

    x0 = np.concatenate((x0_P, x0_M))  # 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

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

    sin_frequency = 2 #Hz
    amp_stim = 1
    phase_shift = np.pi
    act1 = np.zeros((len(time),1))
    act2 = np.zeros((len(time),1))
    for i in range(0,len(time)):
        act1[i,0] = amp_stim*(1+np.sin(2*np.pi*sin_frequency*time[i]))/2
        act2[i,0] = amp_stim*(1+ np.sin(2*np.pi*sin_frequency*time[i] + phase_shift))/2
    
    plt.figure('2b activation')
    plt.plot(time,act1)
    plt.plot(time,act2)
    plt.legend(["Activation for muscle 1", "Activation for muscle 2"])
    plt.title('Activation for muscle 1 and 2 with simple activation wave forms')
    plt.xlabel("Time [s]")
    plt.ylabel("Activation")
    plt.savefig('2_b_activation.png')
    plt.show()

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

    # Method to add the muscle activations to the simulation

    sim.add_muscle_activations(activations)

    # Simulate the system for given time

    sim.initalize_system(x0, time)  # Initialize the system state
    
    #: 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.array [time, states]
    # states vector is in the same order as x0
    res = sim.results()
    
    # Plotting the results
    plt.figure('2b phase')
    plt.title('Pendulum Phase')
    plt.plot(res[:, 1], res[:, 2])
    plt.xlabel('Position [rad]')
    plt.ylabel('Velocity [rad/s]')
    plt.grid()
    plt.savefig('2_b_phase.png')
    plt.show()
    
    plt.figure('2b oscillations')
    plt.title('Pendulum Oscillations')
    plt.plot(time,res[:, 1])
    plt.xlabel('Time [s]')
    plt.ylabel('Position [rad]')
    plt.grid()
    plt.savefig('2_b_oscillations.png')
    plt.show()
    
    # To animate the model, use the SystemAnimation class
    # Pass the res(states) and systems you wish to animate
    simulation = SystemAnimation(res, pendulum, muscles)
    # To start the animation
    if DEFAULT["save_figures"] is False:
        simulation.animate()

    if not DEFAULT["save_figures"]:
        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)
    
 # 2c : relationship between stimulation frequency and amplitude
    
    # Effect of frequency
    stim_frequency_range = np.array([0.05,0.1,0.5,1,5,10,50,100,500]) #Hz
    stim_amp = 1
    phase_shift = np.pi
    frequency_pend=np.zeros(len(stim_frequency_range))
    amplitude_pend=np.zeros(len(stim_frequency_range))
    
    for j,stim_frequency in enumerate(stim_frequency_range):
        period = 1/stim_frequency
        t_max = 10*period  # Maximum simulation time
        time = np.arange(0., t_max, 0.001*period)  # Time vector

        act1 = np.zeros((len(time),1))
        act2 = np.zeros((len(time),1))
        act1[:,0] = stim_amp*(1 + np.sin(2*np.pi*stim_frequency*time))/2
        act2[:,0] = stim_amp*(1+ np.sin(2*np.pi*stim_frequency*time + phase_shift))/2
        activations = np.hstack((act1, act2))
        sim.add_muscle_activations(activations)
        sim.initalize_system(x0, time)  # Initialize the system state
        sim.simulate()
        res = sim.results()  
        # computing the frequency and amplitude
        angular_position = res[:,1]
        signal_stat = angular_position[int(len(angular_position)/2):len(angular_position)]
        index_zeros = np.where(np.diff(np.sign(signal_stat)))[0]
        deltas = np.diff(index_zeros)
        delta = np.mean(deltas)
        period = 2*delta*0.001*period
        frequency_pend[j] = 1/period
        amplitude_pend[j] = (np.max(signal_stat)-np.min(signal_stat))/2

    # Plotting
    plt.figure('2c : effect of frequency')
    plt.subplot(121)
    plt.loglog(stim_frequency_range,frequency_pend)
    plt.grid()
    plt.xlabel('Stimulation Frequency in Hz')
    plt.ylabel('Pendulum Oscillation Frequency [Hz]')
    plt.subplot(122)
    plt.loglog(stim_frequency_range,amplitude_pend)
    plt.grid()
    plt.xlabel('Stimulation Frequency in Hz')
    plt.ylabel('Pendulum Oscillation Amplitude [rad]')
    plt.savefig('2c_frequency.png')
    plt.show()

    # Effect of amplitude
    stim_frequency = 10 #Hz
    stim_amp_range = np.arange(0,1.1,0.1)
    phase_shift = np.pi
    frequency_pend=np.zeros(len(stim_amp_range))
    amplitude_pend=np.zeros(len(stim_amp_range))
    
    for j,stim_amp in enumerate(stim_amp_range):
        period = 1/stim_frequency
        t_max = 5*period  # Maximum simulation time
        time = np.arange(0., t_max, 0.001*period)  # Time vector

        act1 = np.zeros((len(time),1))
        act2 = np.zeros((len(time),1))
        act1[:,0] = stim_amp*(1 + np.sin(2*np.pi*stim_frequency*time))/2
        act2[:,0] = stim_amp*(1+ np.sin(2*np.pi*stim_frequency*time + phase_shift))/2
        activations = np.hstack((act1, act2))
        sim.add_muscle_activations(activations)
        sim.initalize_system(x0, time)  # Initialize the system state
        sim.simulate()
        res = sim.results()  
        # computing the frequency and amplitude
        angular_position = res[:,1]
        signal_stat = angular_position[int(len(angular_position)/2):len(angular_position)]
        index_zeros = np.where(np.diff(np.sign(signal_stat)))[0]
        deltas = np.diff(index_zeros)
        delta = np.mean(deltas)
        period = 2*delta*0.001*period
        frequency_pend[j] = 1/period
        amplitude_pend[j] = (np.max(signal_stat)-np.min(signal_stat))/2
        
    frequency_pend[0] = 0.0;
    
    # Plotting
    plt.figure('2c : effect of amplitude')
    plt.subplot(121)
    plt.plot(stim_amp_range,frequency_pend)
    plt.grid()
    plt.xlabel('Stimulation Amplitude')
    plt.ylabel('Pendulum Oscillation Frequency [Hz]')
    plt.subplot(122)
    plt.plot(stim_amp_range,amplitude_pend)
    plt.grid()
    plt.xlabel('Stimulation Amplitude')
    plt.ylabel('Pendulum Oscillation Amplitude [rad]')
    plt.savefig('2c_amplitude.png')
    plt.show()
Пример #6
0
def exercise2():
    """ Main function to run for Exercise 2.

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

    Returns
    -------
        None
    """

    # Define and Setup your pendulum model here
    # Check PendulumSystem.py for more details on Pendulum class
    pendulum_params = PendulumParameters()  # Instantiate pendulum parameters
    pendulum_params.L = 0.5  # To change the default length of the pendulum
    pendulum_params.m = 1.  # To change the default mass of the pendulum
    pendulum = PendulumSystem(pendulum_params)  # Instantiate Pendulum object

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

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

    # Define and Setup your pendulum model here
    # Check MuscleSytem.py for more details on MuscleSytem class
    M1_param = MuscleParameters()  # Instantiate Muscle 1 parameters
    M1_param.f_max = 1500  # To change Muscle 1 max force
    M2_param = MuscleParameters()  # Instantiate Muscle 2 parameters
    M2_param.f_max = 1500  # To change Muscle 2 max force
    M1 = Muscle(M1_param)  # Instantiate Muscle 1 object
    M2 = Muscle(M2_param)  # Instantiate Muscle 2 object
    # Use the MuscleSystem Class to define your muscles in the system
    muscles = MuscleSytem(M1, M2)  # Instantiate Muscle System with two muscles
    pylog.info('Muscle system initialized \n {} \n {}'.format(
        M1.parameters.showParameters(), M2.parameters.showParameters()))

    # Define Muscle Attachment points
    m1_origin = np.array([-0.17, 0.0])  # Origin of Muscle 1
    m1_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 1

    m2_origin = np.array([0.17, 0.0])  # Origin of Muscle 2
    m2_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 2

    # Attach the muscles
    muscles.attach(np.array([m1_origin, m1_insertion]),
                   np.array([m2_origin, m2_insertion]))

    ############Exercise 2A ###############################################
    # rigth after creating and attaching both muscles:

    print(m1_origin, m2_origin)
    m1a1 = abs(abs(m1_origin[0]) - abs(m1_origin[1]))
    m1a2 = abs(abs(m1_insertion[0]) - abs(m1_insertion[1]))

    m1a1 = m1_origin[0] - m1_origin[1]
    m1a2 = m1_insertion[0] - m1_insertion[1]
    m2a1 = m2_origin[0] - m2_origin[1]
    m2a2 = m2_insertion[0] - m2_insertion[1]

    print(m1a1, m1a2)
    fromtheta(M1, m1a1, m1a2, 1)
    fromtheta(M2, m2a1, m2a2, 2)

    # 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

    ##### Time #####
    t_max = 5  # Maximum simulation time

    time = np.arange(0., t_max, 0.002)  # Time vector

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

    # Muscle Model initial condition
    x0_M = np.array([0., M1.L_OPT, 0., M2.L_OPT])

    x0 = np.concatenate((x0_P, x0_M))  # 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

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

    wave_h1 = np.sin(time * 3) * 1  #makes a sinusoidal wave from 'time'
    wave_h2 = np.sin(time * 3 +
                     np.pi) * 1  #makes a sinusoidal wave from 'time'

    wave_h1[wave_h1 < 0] = 0  #formality of passing negative values to zero
    wave_h2[wave_h2 < 0] = 0  #formality of passing negative values to zero

    act1 = wave_h1.reshape(len(time), 1)  #makes a vertical array like act1
    act2 = wave_h2.reshape(len(time), 1)  #makes a vertical array like act1

    # Plotting the waveforms
    plt.figure('Muscle Activations')
    plt.title('Muscle Activation Functions')
    plt.plot(time, wave_h1, label='Muscle 1')
    plt.plot(time, wave_h2, label='Muscle 2')
    plt.xlabel('Time [s]')
    plt.ylabel('Muscle Excitation')
    plt.legend(loc='upper right')
    plt.grid()

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

    # Method to add the muscle activations to the simulation
    sim.add_muscle_activations(activations)

    # Simulate the system for given time
    sim.initalize_system(x0, time)  # Initialize the system state

    #: If you would like to perturb the pedulum model then you could do
    # so by
    sim.sys.pendulum_sys.parameters.PERTURBATION = False
    # 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.array [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
    muscle1_results = sim.sys.muscle_sys.Muscle1.results
    muscle2_results = sim.sys.muscle_sys.Muscle2.results

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

    # Plotting the results: Amplidute stimulation
    plt.figure('Amplidute stimulation')
    plt.title('Amplidute stimulation')
    plt.plot(time, res[:, 1], label='Stimul. 0.2')
    plt.xlabel('time [s]')
    plt.ylabel('Position [rad]')
    plt.legend(loc='upper left')
    plt.grid()

    # Plotting the results: frequency stimulation
    plt.figure('Frequency stimulation')
    plt.title('Frequency stimulation')
    plt.plot(time, res[:, 1], label='w: 3 rad/s')
    plt.xlabel('time [s]')
    plt.ylabel('Position [rad]')
    plt.legend(loc='upper left')
    plt.grid()

    poincare_crossings(res, -2, 1, "Pendulum")

    # To animate the model, use the SystemAnimation class
    # Pass the res(states) and systems you wish to animate
    simulation = SystemAnimation(res, pendulum, muscles)
    # To start the animation
    if DEFAULT["save_figures"] is False:
        simulation.animate()

    if not DEFAULT["save_figures"]:
        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)
Пример #7
0
def exercise2():
    """ Main function to run for Exercise 2.

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

    Returns
    -------
        None
    """

    # Define and Setup your pendulum model here
    # Check PendulumSystem.py for more details on Pendulum class
    pendulum_params = PendulumParameters()  # Instantiate pendulum parameters
    pendulum_params.L = 0.5  # To change the default length of the pendulum
    pendulum_params.m = 1.  # To change the default mass of the pendulum
    pendulum = PendulumSystem(pendulum_params)  # Instantiate Pendulum object

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

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

    # Define and Setup your pendulum model here
    # Check MuscleSytem.py for more details on MuscleSytem class
    M1_param = MuscleParameters()  # Instantiate Muscle 1 parameters
    M1_param.f_max = 1500  # To change Muscle 1 max force
    M2_param = MuscleParameters()  # Instantiate Muscle 2 parameters
    M2_param.f_max = 1500  # To change Muscle 2 max force
    M1 = Muscle(M1_param)  # Instantiate Muscle 1 object
    M2 = Muscle(M2_param)  # Instantiate Muscle 2 object
    # Use the MuscleSystem Class to define your muscles in the system
    muscles = MuscleSytem(M1, M2)  # Instantiate Muscle System with two muscles
    pylog.info('Muscle system initialized \n {} \n {}'.format(
        M1.parameters.showParameters(), M2.parameters.showParameters()))

    # Define Muscle Attachment points
    m1_origin = np.array([-0.17, 0.0])  # Origin of Muscle 1
    m1_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 1

    m2_origin = np.array([0.17, 0.0])  # Origin of Muscle 2
    m2_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 2

    # Attach the muscles
    muscles.attach(np.array([m1_origin, m1_insertion]),
                   np.array([m2_origin, m2_insertion]))

    # 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

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

    ##### Model Initial Conditions #####
    x0_P = np.array([0., 0.])  # Pendulum initial condition

    # Muscle Model initial condition
    x0_M = np.array([0., M1.L_OPT, 0., M2.L_OPT])

    x0 = np.concatenate((x0_P, x0_M))  # 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

    simsin = SystemSimulation(sys)  # Instantiate Simulation object

    #simsquare = SystemSimulation(sys)

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

    label_test = []
    """" definition of different kinds of activation for each muscle.
    Amplitude1 and amplitude2 allows to play with the amplitude of activation on each muscle (RMS value for the sinus activation)
    
    act1 and act2 activates the muscle all the time.
    actsin activates with sin(wi) if sin(wi)>0 (no negative activation). The 2 muscles are in opposition of phase.
    actsquare does the same with a square signal.
    
    
    
    """

    amplitude1 = 1.
    amplitude2 = 1.

    #declaration of the activations
    act1 = np.ones((len(time), 1)) * amplitude1
    act2 = np.ones((len(time), 1)) * amplitude2
    actsin = np.ones((len(time), 1))
    actsin2 = np.ones((len(time), 1))
    actsquare = np.ones((len(time), 1))
    actsquare2 = np.ones((len(time), 1))

    wlist = [0.1, 0.05, 0.01, 0.005]

    k = 0

    for w in wlist:
        #generation of the signals at pulsation w
        for i in range(len(actsin)):
            if math.sin(w * i) <= 0:
                actsin[i] = 0
                actsin2[i] = abs(amplitude2 * math.sqrt(2) * math.sin(w * i))
            else:
                actsin[i] = abs(amplitude1 * math.sqrt(2) * math.sin(w * i))
                actsin2[i] = 0

        for i in range(len(actsquare)):

            if i % (2 * math.pi / w) <= math.pi / w:
                actsquare[i] = amplitude1
                actsquare2[i] = 0
            else:
                actsquare[i] = 0
                actsquare2[i] = amplitude2
        """ uncomment this to plot the activation signals"""
        #        #Plot of the activation through time
        #        plt.figure
        #        plt.plot(actsquare)
        #        plt.plot(actsin)
        #        plt.title("Activations wave forms used")
        #        plt.xlabel("Time (s)")
        #        plt.ylabel("Activation amplitude (.)")
        """ put as parameters the activation you want (act1/2, actsin1/2 or actsquare1/2)"""
        activationssin = np.hstack((actsquare, actsquare2))
        #activationssquare = np.hstack((actsquare, actsquare2))

        # Method to add the muscle activations to the simulation

        simsin.add_muscle_activations(activationssin)
        #simsquare.add_muscle_activations(activationssquare)
        # Simulate the system for given time

        simsin.initalize_system(x0, time)  # Initialize the system state
        #simsquare.initalize_system(x0, time)
        #: If you would like to perturb the pedulum model then you could do
        # so by
        """perturbation of the signal"""
        simsin.sys.pendulum_sys.parameters.PERTURBATION = False
        #simsquare.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
        simsin.simulate()
        #simsquare.simulate()
        # Obtain the states of the system after integration
        # res is np.array [time, states]
        # states vector is in the same order as x0
        ressin = simsin.results()
        #ressquare = simsquare.results()

        # In order to obtain internal states of the muscle
        # you can access the results attribute in the muscle class
        muscle1_results = simsin.sys.muscle_sys.Muscle1.results
        muscle2_results = simsin.sys.muscle_sys.Muscle2.results

        # Plotting the results
        plt.figure('Pendulum')
        plt.title('Pendulum Phase')
        plt.plot(ressin[:, 1], ressin[:, 2])
        label_test.append('w=' + str(wlist[k]))
        k = k + 1
        #plt.plot(ressquare[:, 1], ressquare[:, 2])
        plt.xlabel('Position [rad]')
        plt.ylabel('Velocity [rad.s]')
        plt.legend(label_test)
        plt.grid()

        # To animate the model, use the SystemAnimation class
        # Pass the res(states) and systems you wish to animate
        simulationsin = SystemAnimation(ressin, pendulum, muscles)
        #simulationsquare = SystemAnimation(ressquare, pendulum, muscles)

        # To start the animation
        if DEFAULT["save_figures"] is False:
            simulationsin.animate()
        #simulationsquare.animate()
        if not DEFAULT["save_figures"]:
            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)
Пример #8
0
def exercise2():
    """ Main function to run for Exercise 2.

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

    Returns
    -------
        None
    """

    # Define and Setup your pendulum model here
    # Check PendulumSystem.py for more details on Pendulum class
    pendulum_params = PendulumParameters()  # Instantiate pendulum parameters
    pendulum_params.L = 0.5  # To change the default length of the pendulum
    pendulum_params.m = 1.  # To change the default mass of the pendulum
    pendulum = PendulumSystem(pendulum_params)  # Instantiate Pendulum object

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

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

    # Define and Setup your pendulum model here
    # Check MuscleSytem.py for more details on MuscleSytem class
    M1_param = MuscleParameters()  # Instantiate Muscle 1 parameters
    M1_param.f_max = 1500  # To change Muscle 1 max force
    M2_param = MuscleParameters()  # Instantiate Muscle 2 parameters
    M2_param.f_max = 1500  # To change Muscle 2 max force
    M1 = Muscle(M1_param)  # Instantiate Muscle 1 object
    M2 = Muscle(M2_param)  # Instantiate Muscle 2 object
    # Use the MuscleSystem Class to define your muscles in the system
    muscles = MuscleSytem(M1, M2)  # Instantiate Muscle System with two muscles
    pylog.info('Muscle system initialized \n {} \n {}'.format(
        M1.parameters.showParameters(), M2.parameters.showParameters()))

    # Define Muscle Attachment points
    m1_origin = np.array([-0.17, 0.0])  # Origin of Muscle 1
    m1_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 1

    m2_origin = np.array([0.17, 0.0])  # Origin of Muscle 2
    m2_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 2

    # Attach the muscles
    muscles.attach(np.array([m1_origin, m1_insertion]),
                   np.array([m2_origin, m2_insertion]))

    # 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

    ##### Time #####
    t_max = 3  # Maximum simulation time
    time = np.arange(0., t_max, 0.004)  # Time vector

    ##### Model Initial Conditions #####
    x0_P = np.array([0., 0.])  # Pendulum initial condition

    # Muscle Model initial condition
    x0_M = np.array([0., M1.L_OPT, 0., M2.L_OPT])

    x0 = np.concatenate((x0_P, x0_M))  # 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

    # Add muscle activations to the simulation
    # Here you can define your muscle activation vectors
    # that are time dependent
    '''
    #act1 = np.ones((len(time), 1)) * 1.
    #act2 = np.ones((len(time), 1)) * 0.05
    act1 = (np.sin((time/t_max)*10*np.pi)+1)/2
    act2 = (np.sin((time/t_max)*10*np.pi + np.pi)+1)/2
    
    act1 = np.reshape(act1, (len(time),1)) 
    act2 = np.reshape(act2, (len(time),1)) 

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

    # Plotting the results
    plt.figure('Activations')
    plt.title('Muscle activations')
    plt.plot(time, act1, label = 'Activation muscle 1')
    plt.plot(time, act2, label = 'Activation muscle 2')
    plt.xlabel('Time [s]')
    plt.ylabel('Activation')
    plt.legend()
    plt.grid()
    # Method to add the muscle activations to the simulation

    sim.add_muscle_activations(activations)
    '''
    max_amplitude = np.zeros([10, 10])
    i = 0
    j = 0
    # Simulate the system for given time
    for activation_max in np.arange(0, 1, 0.9):
        i = 0
        for frequency in np.arange(1, 10, 4):
            act1 = ((np.sin(
                (time / t_max) * frequency * np.pi) + 1) / 2) * activation_max
            act2 = ((np.sin((time / t_max) * frequency * np.pi + 1) + 1) /
                    2) * activation_max

            act1 = np.reshape(act1, (len(time), 1))
            act2 = np.reshape(act2, (len(time), 1))

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

            sim.initalize_system(x0, time)  # Initialize the system state

            #: If you would like to perturb the pedulum model then you could do
            # so by
            sim.sys.pendulum_sys.parameters.PERTURBATION = False
            # 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.array [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
            muscle1_results = sim.sys.muscle_sys.Muscle1.results
            muscle2_results = sim.sys.muscle_sys.Muscle2.results

            max_amplitude[i, j] = np.max(np.abs(res[:, 1]))
            i += 1

            # Plotting the results
            plt.figure('Pendulum')
            plt.title('Pendulum Phase')
            plt.plot(res[:, 1],
                     res[:, 2],
                     label='activation %.2f - frequency %f' %
                     (activation_max, frequency))
            plt.xlabel('Position [rad]')
            plt.ylabel('Velocity [rad.s]')
            plt.grid()
        j += 1

    plt.figure('Amplitude')
    fig, ax1 = plt.subplots(1, 1)
    ax1.set_xticklabels(np.array([0, 0, 0.2, 0.4, 0.8, 1]))
    ax1.set_yticklabels(np.array([0, 1, 3, 5, 7, 9]))
    plt.title('Ampliudes')
    plt.imshow(max_amplitude, aspect='equal', origin='lower')

    plt.xlabel('Activation')
    plt.ylabel('Frequncy')
    # To animate the model, use the SystemAnimation class
    # Pass the res(states) and systems you wish to animate
    simulation = SystemAnimation(res, pendulum, muscles)
    # To start the animation
    if DEFAULT["save_figures"] is False:
        simulation.animate()

    if not DEFAULT["save_figures"]:
        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)
Пример #9
0
def exercise2():
    """ Main function to run for Exercise 2.

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

    Returns
    -------
        None
    """
    
    #----------------# Exercise 2a #----------------#

    theta = np.linspace(-np.pi/4, np.pi/4,num=50)
    h1=[]
    a1= 1
    a2a1=np.linspace(0.5,2,num=4)

    plt.figure('2a_Muscle_Length_vs_Theta')    
    plt.title('Muscle Length vs Theta')
    plt.xlabel('Position [rad]')
    plt.ylabel('Muscle length [m]')
    plt.grid()
    plt.figure('2a_Moment_arm_vs_Theta')    
    plt.title('Moment arm vs Theta')
    plt.xlabel('Position [rad]')
    plt.ylabel('Moment arm [m]')
    plt.grid()

    for i in range(0,len(a2a1)):
        a2=a2a1[i]*a1
        L1=(np.sqrt(a1**2+a2**2+2*a1*a2*np.sin(theta)))
        h1=((a1*a2*np.cos(theta))/L1)

        plt.figure('2a_Muscle_Length_vs_Theta')
        plt.plot(theta,L1,label=('a2/a1 = %.1f' %(a2a1[i])))

        plt.figure('2a_Moment_arm_vs_Theta')
        plt.plot(theta,h1,label=('a2/a1= %.1f' %(a2a1[i])))
        
    plt.figure('2a_Muscle_Length_vs_Theta')
    plt.legend()
    plt.figure('2a_Moment_arm_vs_Theta')
    plt.legend()

    #----------------# Exercise 2a finished #----------------#
    
    
    # Define and Setup your pendulum model here
    # Check PendulumSystem.py for more details on Pendulum class
    pendulum_params = PendulumParameters()  # Instantiate pendulum parameters
    pendulum_params.L = 0.5  # To change the default length of the pendulum
    pendulum_params.m = 1.  # To change the default mass of the pendulum
    pendulum = PendulumSystem(pendulum_params)  # Instantiate Pendulum object

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

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

    # Define and Setup your pendulum model here
    # Check MuscleSytem.py for more details on MuscleSytem class
    M1_param = MuscleParameters()  # Instantiate Muscle 1 parameters
    M1_param.f_max = 1500  # To change Muscle 1 max force
    M2_param = MuscleParameters()  # Instantiate Muscle 2 parameters
    M2_param.f_max = 1500  # To change Muscle 2 max force
    M1 = Muscle(M1_param)  # Instantiate Muscle 1 object
    M2 = Muscle(M2_param)  # Instantiate Muscle 2 object
    # Use the MuscleSystem Class to define your muscles in the system
    muscles = MuscleSytem(M1, M2)  # Instantiate Muscle System with two muscles
    pylog.info('Muscle system initialized \n {} \n {}'.format(
        M1.parameters.showParameters(),
        M2.parameters.showParameters()))

    # Define Muscle Attachment points
    m1_origin = np.array([-0.17, 0.0])  # Origin of Muscle 1
    m1_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 1

    m2_origin = np.array([0.17, 0.0])  # Origin of Muscle 2
    m2_insertion = np.array([0.0, -0.17])  # Insertion of Muscle 2

    # Attach the muscles
    muscles.attach(np.array([m1_origin, m1_insertion]),
                   np.array([m2_origin, m2_insertion]))

    # 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

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

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

    # Muscle Model initial condition
    x0_M = np.array([0., M1.L_OPT, 0., M2.L_OPT])

    x0 = np.concatenate((x0_P, x0_M))  # 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

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

    activationFunction = ['sin','square']
    for idx, act in enumerate(activationFunction):
        #----------------# Exercise 2c #----------------#
        
        w = np.linspace(0.2,4,4)
#        w = 0.5
#        a = np.linspace(0.1,1,4)
        plt.figure('2c_LimitCycle_'+str(act))
#        plt.figure('2c_LimitCycle_Amplitude_'+str(act))
        plt.title('Pendulum Phase')
        
        plt.figure('2c_Amplitude_'+str(act))
#        plt.figure('2c_Amplitude_Amplitude_'+str(act))
        plt.title('Amplitude vs. Frequency')
#        plt.title('Amplitude vs. Stimulation Amplitude')
        
        for i in range(0,len(w)):
#        for i in range(0,len(a)):
#            plt.figure('2c_LimitCycle_Amplitude_'+str(act))
            plt.figure('2c_LimitCycle_'+str(act))
            print('Running simulation %d out of %d'%(i+1,len(w)))
#            print('Running simulation %d out of %d'%(i+1,len(a)))
            
            if act == 'sin':
                sinAct = np.sin(2*np.pi*w[i]*time).reshape(len(time),1)
#                sinAct = a[i]*np.sin(2*np.pi*w*time).reshape(len(time),1)
            else:
                sinAct = signal.square(2*np.pi*w[i]*time).reshape(len(time),1)
#                sinAct = a[i]*signal.square(2*np.pi*w*time).reshape(len(time),1)
                
            sinFlex = sinAct.copy()
            sinFlex[sinAct<0] = 0 
            sinExt = sinAct.copy()
            sinExt[sinAct>0] = 0
            sinExt = abs(sinExt)
            
            sinAct1 = np.ones((len(time),1))
            sinAct2 = np.ones((len(time),1))
            sinAct1 = sinFlex
            sinAct2 = sinExt
        
            sinActivations = np.hstack((sinAct1,sinAct2))
            # Method to add the muscle activations to the simulation
        
            sim.add_muscle_activations(sinActivations)
        
            # Simulate the system for given time
        
            sim.initalize_system(x0, time)  # Initialize the system state
        
            #: If you would like to perturb the pedulum model then you could do
            # so by
            sim.sys.pendulum_sys.parameters.PERTURBATION = False
            # 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.array [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
            muscle1_results = sim.sys.muscle_sys.Muscle1.results
            muscle2_results = sim.sys.muscle_sys.Muscle2.results
        
            # Plotting the results
            
            plt.plot(res[:, 1], res[:, 2], label='Act. $%s(2\cdot{}\\pi\cdot{}%.1f\cdot{}t)$'%(act,w[i]))
#            plt.plot(res[:, 1], res[:, 2], label='Act. $%.1f\cdot{}%s(2\cdot{}\\pi\cdot{}0.5\cdot{}t)$'%(a[i],act))
            plt.figure('2c_Amplitude_'+str(act))
            plt.plot(time,res[:, 1], label='Frequency = %.1f'%(w[i]))
            
#            plt.figure('2c_Amplitude_Amplitude_'+str(act))
#            plt.plot(time,res[:, 1], label='Amplitude = %.1f'%(a[i]))
            
            
        plt.figure('2c_LimitCycle_'+str(act))
#        plt.figure('2c_LimitCycle_Amplitude_'+str(act))
        
        plt.xlabel('Position [rad]')
        plt.ylabel('Velocity [rad/s]')
        plt.grid()
        plt.legend()
        
        plt.figure('2c_Amplitude_'+str(act))
#        plt.figure('2c_Amplitude_Amplitude_'+str(act))
        plt.xlabel('Time [s]')
        plt.ylabel('Amplitude [rad]')
        plt.grid()
        plt.legend()
        
        #----------------# Exercise 2c finished #----------------#
        
        #----------------# Exercise 2b #----------------#

        w = 0.5
        if act == 'sin':
            sinAct = np.sin(2*np.pi*w*time).reshape(len(time),1)
        else:
            sinAct = signal.square(2*np.pi*w*time).reshape(len(time),1)
        sinFlex = sinAct.copy()
        sinFlex[sinAct<0] = 0 
        sinExt = sinAct.copy()
        sinExt[sinAct>0] = 0
        sinExt = abs(sinExt)
        
        sinAct1 = np.ones((len(time),1))
        sinAct2 = np.ones((len(time),1))
        sinAct1 = sinFlex
        sinAct2 = sinExt
        activations = np.hstack((sinAct1,sinAct2))     
            
        # Method to add the muscle activations to the simulation
    
        sim.add_muscle_activations(activations)
    
        # Simulate the system for given time
    
        sim.initalize_system(x0, time)  # Initialize the system state
    
        #: 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.array [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
        muscle1_results = sim.sys.muscle_sys.Muscle1.results
        muscle2_results = sim.sys.muscle_sys.Muscle2.results
    
        # Plotting the results
        plt.figure('2b_LimitCycle_'+str(act))
        plt.title('Pendulum Phase')
        plt.plot(res[:, 1], res[:, 2], label='Act. $%s(2\cdot{}\\pi\cdot{}%.1f\cdot{}t)$, Pert. ($t=3.2,\\theta = 1, \dot{\\theta} = -0.5$)' %(act,w))
        plt.xlabel('Position [rad]')
        plt.ylabel('Velocity [rad/s]')
        plt.grid()
        plt.legend()
        
        plt.figure('2b_ActivationFunction_'+str(act))
        plt.title('Activation Function')
        plt.plot(time, sinAct1, label='Flexor')
        plt.plot(time, sinAct2, label='Extensor')
        plt.xlabel('Time [s]')
        plt.ylabel('Activation')
        plt.grid()
        plt.legend()
  
        #----------------# Exercise 2b finished #----------------#
    
    # To animate the model, use the SystemAnimation class
    # Pass the res(states) and systems you wish to animate
    simulation = SystemAnimation(res, pendulum, muscles)
    # To start the animation
    if DEFAULT["save_figures"] is False:
        simulation.animate()

    if not DEFAULT["save_figures"]:
        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)
        plt.show