Exemplo n.º 1
0
def system_initialisation(l_pendulum=0.5,
                          m_pendulum=1.,
                          f_max=1500,
                          l_attach=0.17):
    """Generates a oscillatory system and its default initial conditions"""

    # Neural parameters for oscillatory system
    d = 1.
    w = np.array([[0, -5, -5, 0], [-5, 0, 0, -5], [5, -5, 0, 0], [-5, 5, 0,
                                                                  0]])
    b = np.array([3., 3., -3., -3.])
    tau = np.array([0.02, 0.02, 0.1, 0.1])

    # Pendulum parameters
    pendulum_params = PendulumParameters()
    pendulum_params.L = l_pendulum
    pendulum_params.m = m_pendulum
    pendulum = PendulumSystem(pendulum_params)

    # Muscles parameters
    m1_param = MuscleParameters()
    m1_param.f_max = f_max
    m2_param = MuscleParameters()
    m2_param.f_max = f_max
    m1 = Muscle(m1_param)
    m2 = Muscle(m2_param)
    muscles = MuscleSytem(m1, m2)

    # Muscle_attachment
    m1_origin = np.array([-l_attach, 0.0])
    m1_insertion = np.array([0.0, -l_attach])
    m2_origin = np.array([l_attach, 0.0])
    m2_insertion = np.array([0.0, -l_attach])
    muscles.attach(np.array([m1_origin, m1_insertion]),
                   np.array([m2_origin, m2_insertion]))

    # Neural network
    n_params = NetworkParameters()
    n_params.D = d
    n_params.w = w
    n_params.b = b
    n_params.tau = tau
    neural_network = NeuralSystem(n_params)

    # System creation
    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
    sys.add_neural_system(
        neural_network)  # Add neural network model to the system

    # Default initial conditions
    x0_p = np.array([0, 0.])  # Pendulum initial condition
    x0_m = np.array([0., m1.L_OPT, 0.,
                     m2.L_OPT])  # Muscle Model initial condition
    x0_n = np.array([-0.5, 1, 0.5, 1])  # Neural Network initial condition
    x0 = np.concatenate((x0_p, x0_m, x0_n))  # System initial conditions
    return sys, x0
Exemplo n.º 2
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)
Exemplo n.º 3
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()
Exemplo n.º 4
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()
Exemplo n.º 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()
def exercise3a():
    """ Main function to run for Exercise 3.

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

    Returns
    -------
        None
    """
    # 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 = 0.5  # To change the default length of the pendulum
    P_params.m = 1.  # To change the default mass of the pendulum
    P_params.PERTURBATION = True
    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()))

    # 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]))

    ##### Neural Network #####
    # The network consists of four neurons
    N_params = NetworkParameters()  # Instantiate default network parameters
    N_params.tau = [0.02, 0.02, 0.1, 0.1]
    N_params.b = [3.0, 3.0, -3.0, -3.0]
    N_params.D = 1.0  # To change a network parameter
    N_params.w = np.asarray([[0.0, -5.0, -5.0, 0.0], [-5.0, 0.0, 0.0, -5.0],
                             [5.0, -5.0, 0.0, 0.0], [-5.0, 5.0, 0.0, 0.0]])
    # Similarly to change w -> N_params.w = (4x4) array
    print(N_params.w)
    ############################# Exercise 3A  ######################
    N_params.w = np.transpose(
        np.asarray([[0, -1, 1, -1], [-1, 0, -1, 1], [-1, 0, 0, 0],
                    [0, -1, 0, 0]])) * 5
    print(N_params.w, N_params.D, N_params.tau, N_params.b, N_params.exp)

    # Create a new neural network with above parameters
    neural_network = NeuralSystem(N_params)
    pylog.info('Neural system initialized \n {}'.format(
        N_params.showParameters()))

    # 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
    sys.add_neural_system(
        neural_network)  # Add the neural network to the system

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

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

    for i in x0_P:
        # Muscle Model initial condition
        x0_M = np.array([0., M1.L_OPT, 0., M2.L_OPT])

        x0_N = np.array([-1.5, 1, 2.5, 1])  # Neural Network Initial Conditions

        x0 = np.concatenate((i, 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.add_external_inputs_to_network(np.ones((len(time), 4)))

        #    wave_h1 = np.sin(time*3)*2               #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
        #    column = np.ones((len(time), 1))

        #    ext_in = np.hstack((act1, column, act2, column))

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

        sim.sys.pendulum_sys.parameters.PERTURBATION = False

        # 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: Position(phase) vs time
    plt.figure('Pendulum Phase')
    plt.title('Pendulum Phase')
    plt.plot(res[:, 0], res[:, 1])  #to plot pendulum Position (phase)
    #    plt.plot(res[:, 0], time)   #to plot position
    #    plt.plot(res[:, 0], res[:, -5:-1])  # to Plot neurons' states
    plt.xlabel('time [s]')
    plt.ylabel('Position [rad]')
    plt.grid()

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

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

    # Plotting the results: Output of the network
    plt.figure('Network output')
    plt.title('Network output')
    plt.plot(res[:, 0], res[:, -1],
             label='neuron1')  #to plot Velocity vs Position
    plt.plot(res[:, 0], res[:, -2], label='neuron2')
    plt.plot(res[:, 0], res[:, -3], label='neuron3')
    plt.plot(res[:, 0], res[:, -4], label='neuron4')
    plt.xlabel('time [s]')
    plt.ylabel('Stimulation ')
    plt.legend(loc='upper right')
    plt.grid()

    if DEFAULT["save_figures"] is False:
        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)

    # 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)
    # To start the animation
    simulation.animate()
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
Exemplo n.º 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)
Exemplo n.º 9
0
def exercise3():
    """ Main function to run for Exercise 3.

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

    Returns
    -------
        None
    """
    # 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 = 0.5  # To change the default length of the pendulum
    P_params.m = 1.  # 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()))

    # 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]))

    ##### Neural Network #####
    # The network consists of four neurons
    N_params = NetworkParameters()  # Instantiate default network parameters 
    # Similarly to change w -> N_params.w = (4x4) array
    # From lecture 4, slide 85 -> Generate oscillations !!
    N_params.D = 2.
    N_params.tau = [0.02,0.02,0.1,0.1]
    N_params.b = [3.0,3.0,-3.0,-3.0]
    N_params.w = [[0,-5,-5,0], # 1 <- 2
                  [-5,0,0,-5],
                  [5,-5,0,-5],
                  [-5,5,0,0]] 

    # Create a new neural network with above parameters
    neural_network = NeuralSystem(N_params)
    pylog.info('Neural system initialized \n {}'.format(
        N_params.showParameters()))

    # 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.array([0., 0.])  # Pendulum initial condition

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

    x0_N = np.array([-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

    # Add external inputs to neural network

    # sim.add_external_inputs_to_network(np.ones((len(time), 4)))
    #ext_in = np.ones((len(time), 4))
    #ext_in[:,2] = 0.2
    #ext_in[:,3] = 0.2
    #sim.add_external_inputs_to_network(ext_in)

    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()

    # 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 phase
    fig = plt.figure('Pendulum')
    plt.title('Pendulum Phase')
    plt.plot(res[:, 1], res[:, 2])
    plt.xlabel('Position [rad]')
    plt.ylabel('Velocity [rad/s]')
    plt.grid()
    fig.tight_layout()
    fig.savefig('graphs/PendulumPhase.png')
    
    # Plotting the neuronal activation
    # Access the neurons outputs:
    # [t] theta theta. A1 lCE1 A2 lCE2 m1 m2 m3 m4
    fig = plt.figure('Neuron output')
    plt.title('Membrane potentials')
    plt.plot(res[:, 0], res[:, 7],label='m1')
    plt.plot(res[:, 0], res[:, 8],label='m2')
    plt.plot(res[:, 0], res[:, 9],label='m3')
    plt.plot(res[:, 0], res[:, 10],label='m4')
    plt.xlabel('Time [s]')
    plt.ylabel('Potential')
    plt.legend()
    plt.grid()
    fig.tight_layout()
    fig.savefig('graphs/MembranePotentials.png')

    if DEFAULT["save_figures"] is False:
        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)

    # 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)
    # To start the animation
    simulation.animate()
    
    # 3.b
    ext_in = np.ones((len(time), 4))*0.0
    plotExternalDrive(sys,x0,ext_in,typ='low')
    
    ext_in = np.ones((len(time), 4))
    plotExternalDrive(sys,x0,ext_in,typ='high')
    
    ext_in = np.ones((len(time), 4))
    ext_in[:,0] *= 0.1
    ext_in[:,1] *= 0.1
    plotExternalDrive(sys,x0,ext_in,typ='asymmetric') 
Exemplo n.º 10
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
Exemplo n.º 11
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)
Exemplo n.º 12
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)
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)
Exemplo n.º 14
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()
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)
Exemplo n.º 16
0
def exercise3():
    """ Main function to run for Exercise 3.

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

    Returns
    -------
        None
    """
    # 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 = 0.5  # To change the default length of the pendulum
    P_params.m = 1.  # 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()))

    # 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]))

    ##### Neural Network #####
    # The network consists of four neurons
    N_params = NetworkParameters()  # Instantiate default network parameters
    N_params.D = 2.  # To change a network parameter
    # Similarly to change w -> N_params.w = (4x4) array

    # Create a new neural network with above parameters
    neural_network = NeuralSystem(N_params)
    pylog.info('Neural system initialized \n {}'.format(
        N_params.showParameters()))

    # 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.array([0., 0.])  # Pendulum initial condition

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

    x0_N = np.array([-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

    # Add external inputs to neural network

    # sim.add_external_inputs_to_network(np.ones((len(time), 4)))
    # sim.add_external_inputs_to_network(ext_in)

    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()

    # 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[:, 0], res[:, :2])
    plt.xlabel('Position [rad]')
    plt.ylabel('Velocity [rad.s]')
    plt.grid()

    if DEFAULT["save_figures"] is False:
        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)

    # 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)
    # To start the animation
    simulation.animate()
Exemplo n.º 17
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