Пример #1
0
def display_error(errors, method):
    err = error(errors, n=1)
    err_max = error(errors)

    pylog.debug(
        "Obtained an error of {} using {} method (max={}, len={})".format(
            err, method, err_max, len(method)))
Пример #2
0
def exercise1():

    if DEFAULT["1a"] is True:
        exercise1a()
    elif DEFAULT["1b"] is True:
        exercise1b()
    elif DEFAULT["1c"] is True:
        exercise1c()
    elif DEFAULT["1d"] is True:
        exercise1d()
    elif DEFAULT["1f"] is True:
        exercise1f()
    else:
        exercise1a()
        exercise1b()
        exercise1c()
        exercise1d()
        exercise1f()

    if DEFAULT["save_figures"] is False:
        plt.show()
    else:
        figures = plt.get_figlabels()
        print(figures)
        pylog.debug("Saving figures:\n{}".format(figures))
        for fig in figures:
            plt.figure(fig)
            save_figure(fig)
            plt.close(fig)
Пример #3
0
def error(method_state, analytical_state, method):
    """ Compute error of an ode method based on analytical solution """
    err = np.sum(np.abs(analytical_state - method_state)) / len(method_state)
    err_max = max(np.abs(analytical_state - method_state))
    pylog.debug(
        "Obtained an error of {} using {} method (max={}, len={})".format(
            err, method, err_max, len(method_state)))
    return err
Пример #4
0
 def L(self, value):
     """ Keyword Arguments:
     value -- Set the value of pendulum's length [m] """
     self.parameters['L'] = value
     # ReCompute inertia
     # Inertia = m*l**2
     self.I = self.m * self.parameters['L']**2
     pylog.debug('Changed pendulum length to {} [m]'.format(self.L))
Пример #5
0
 def m(self, value):
     """
     Set the mass of the pendulum.
     Setting/Changing mass will automatically recompute the inertia.
     """
     self.parameters['m'] = value
     # ReCompute inertia
     # Inertia = m*l**2
     self.I = self.parameters['m'] * self.L**2
     pylog.debug('Changed pendulum mass to {} [kg]'.format(self.m))
Пример #6
0
def exercise1(clargs):
    """ Exercise 1 """
    # Setup
    pylog.info("Running exercise 1")

    # Setup
    time_max = 5  # Maximum simulation time
    time_step = 0.2  # Time step for ODE integration in simulation
    x0 = np.array([1.])  # Initial state

    # Integration methods (Exercises 1.a - 1.d)
    pylog.info("Running function integration using different methods")

    # Example
    pylog.debug("Running example plot for integration (remove)")
    example = example_integrate(x0, time_max, time_step)
    example.plot_state(figure="Example", label="Example", marker=".")

    # Analytical (1.a)
    time = np.arange(0, time_max, time_step)  # Time vector
    x_a = analytic_function(time)
    analytical = Result(x_a, time) if x_a is not None else None

    # Euler (1.b)
    euler = euler_integrate(function, x0, time_max, time_step)

    # ODE (1.c)
    ode = ode_integrate(function, x0, time_max, time_step)

    # ODE Runge-Kutta (1.c)
    ode_rk = ode_integrate_rk(function_rk, x0, time_max, time_step)

    # Euler with lower time step (1.d)
    pylog.warning("Euler with smaller ts must be implemented")
    euler_time_step = None
    euler_ts_small = (euler_integrate(function, x0, time_max, euler_time_step)
                      if euler_time_step is not None else None)

    # Plot integration results
    plot_integration_methods(analytical=analytical,
                             euler=euler,
                             ode=ode,
                             ode_rk=ode_rk,
                             euler_ts_small=euler_ts_small,
                             euler_timestep=time_step,
                             euler_timestep_small=euler_time_step)

    # Error analysis (Exercise 1.e)
    pylog.warning("Error analysis must be implemented")

    # Show plots of all results
    if not clargs.save_figures:
        plt.show()
    return
Пример #7
0
def save_figure(figure, name=None, **kwargs):
    """ Save figure """
    for extension in kwargs.pop("extensions", ["png"]):
        fig = figure.replace(" ", "_").replace(".", "dot")
        if name is None:
            name = "{}.{}".format(fig, extension)
        else:
            name = "{}.{}".format(name, extension)
        name = save_folder + name
        plt.figure(figure)
        plt.savefig(name, bbox_inches='tight')
        pylog.debug("Saving figure {}...".format(name))
Пример #8
0
def exercise3():

    time_param = TimeParameters(time_start=0, time_stop=10., time_step=0.001)
    exercise3a(time_param)
    exercise3b(time_param)

    if DEFAULT["save_figures"]:
        figures = plt.get_figlabels()
        pylog.debug("Saving figures:\n{}".format(figures))
        for fig in figures:
            plt.figure(fig)
            save_figure(fig)
    plt.show()
Пример #9
0
def save_figure(figure, name=None, **kwargs):
    """ Save figure """
    for extension in kwargs.pop("extensions", ["pdf"]):
        fig = figure.replace(" ", "_").replace(".", "dot")
        if name is None:
            name = "{}.{}".format(fig, extension)
        else:
            name = "{}.{}".format(name, extension)
        fig = plt.figure(figure)
        size = plt.rcParams.get('figure.figsize')
        fig.set_size_inches(0.7 * size[0], 0.7 * size[1], forward=True)
        plt.savefig(name, bbox_inches='tight')
        pylog.debug("Saving figure {}...".format(name))
        fig.set_size_inches(size[0], size[1], forward=True)
Пример #10
0
def exercise1():
    #exercise1a()
    exercise1d()

    if DEFAULT["save_figures"] is False:
        plt.show()
    else:
        figures = plt.get_figlabels()
        print(figures)
        pylog.debug("Saving figures:\n{}".format(figures))
        for fig in figures:
            plt.figure(fig)
            save_figure(fig)
            plt.close(fig)
Пример #11
0
def exercise2():
    """ Main function to run for Exercise 2.

    """
    exercise2b()

    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)
Пример #12
0
def pendulum_set_position(x0, time=0.0, *args):
    """ Function to analyse the pendulum spring damper system"""
    pendulum = args[0]
    pendulum.parameters.b1 = 1.
    pendulum.parameters.b2 = 1.
    pendulum.parameters.k1 = 50.0
    pendulum.parameters.k2 = 50.0
    pendulum.parameters.s_theta_ref1 = np.deg2rad(0.0)
    pendulum.parameters.s_theta_ref2 = np.deg2rad(65.6)

    pylog.info(
        "1b. Running pendulum_system to set fixed position")
    pylog.info(pendulum.parameters.showParameters())
    title = "{} Pendulum Fixed Position (x0 = {})"
    res = integrate(pendulum_integration, x0, time, args=args)
    pylog.debug('Position : {}'.format(np.rad2deg(res.state[-1])))
    res.plot_state(title.format("State", x0))
    res.plot_phase(title.format("Phase", x0))
Пример #13
0
def save_figure(figure, name=None):
    """ Save figure """
    if os.path.isdir(DEFAULT["save_folder"]):
        path = DEFAULT["save_folder"]
    else:
        pylog.warning(
            "The DEFAULT save directory does not exist. Switching to current directory"
        )
        path = os.getcwd()

    if DEFAULT["save_figures"]:
        for extension in DEFAULT["save_extensions"]:
            fig = figure.replace(" ", "_").replace(".", "dot")
            if name is None:
                name = "{}.{}".format(fig, extension)
            else:
                name = "{}.{}".format(name, extension)
            plt.savefig(path + name, bbox_inches='tight')
            pylog.debug("Saving figure {}...".format(name))
Пример #14
0
def exercise3(clargs):
    """ Exercise 3 """
    parameters = PendulumParameters()  # Checkout pendulum.py for more info
    pylog.info(parameters)
    # Simulation parameters
    time = np.arange(0, 30, 0.01)  # Simulation time
    x0 = [0.1, 0.0]  # Initial state

    # To use/modify pendulum parameters (See PendulumParameters documentation):
    # parameters.g = 9.81  # Gravity constant
    # parameters.m = 1.  # Mass
    # parameters.L = 1.  # Length
    # parameters.I = 1. # Inertia (Automatically computed!)
    # parameters.d = 0.3  # damping
    # parameters.sin = np.sin  # Sine function
    # parameters.dry = False  # Use dry friction (True or False)

    # Example of system integration (Similar to lab1)
    # (NOTE: pendulum_equation must be imlpemented first)
    pylog.debug("Running integration example")
    res = integrate(pendulum_system, x0, time, args=(parameters,))
    res.plot_state("State")
    res.plot_phase("Phase")

    # Evolutions
    # Write code here (You can add functions for the different cases)
    pylog.warning(
        "Evolution of pendulum in normal conditions must be implemented"
    )
    pylog.warning(
        "Evolution of pendulum without damping must be implemented"
    )
    pylog.warning(
        "Evolution of pendulum with perturbations must be implemented"
    )
    pylog.warning(
        "Evolution of pendulum with dry friction must be implemented"
    )

    # Show plots of all results
    if not clargs.save_figures:
        plt.show()
Пример #15
0
def exercise1():
    plt.close("all")
    pylog.info("Start exercise 1")
    time_param = TimeParameters(time_start=0.0,
                                time_stop=0.2,
                                time_step=0.001,
                                time_stabilize=0.2)

    exercise1a(time_param)
    exercise1b(time_param)
    exercise1c(time_param)
    time_param.t_stop = 0.3  # change time parameters for the second part
    exercise1d(time_param)
    exercise1e(time_param)

    if DEFAULT["save_figures"]:
        figures = plt.get_figlabels()
        pylog.debug("Saving figures:\n{}".format(figures))
        for fig in figures:
            plt.figure(fig)
            save_figure(fig)
    plt.show()
Пример #16
0
def two_li_ode(y, t, params):
    """ Derivative function of a network of 2 leaky integrator neurons

    y is the vector of membrane potentials (variable m in lecture equations)
    yd the derivative of the vector of membrane potentials
    """
    # Extract parameters
    tau, D, b, w, exp = params.list()

    # Update the firing rates:
    y = np.array(y)
    x = 1 / (1 + exp(-D * (y + b)))

    # IMPLEMENT THE DIFFERENTIAL EQUATION FOR THE MEMBRANE POTENTIAL
    # Compute the dentritic sums for both neurons
    dend_sum = w[0] * x[0] + w[1] * x[1]

    # Compute the membrane potential derivative:
    yd = (-y + dend_sum) / tau

    pylog.debug("x: {}\ndend_sum: {}\nyd: {}".format(x, dend_sum, yd))
    return yd
Пример #17
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)
Пример #18
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()
Пример #20
0
    @property
    def mass(self):
        """Get the value of mass in the mass system  """
        return self.parameters["mass"]

    @mass.setter
    def mass(self, value):
        """ Keyword Arguments:
            value --  Set the value of mass"""
        if value <= 0.00001:
            pylog.error(
                "Mass you are trying to set is too low!. Setting to 1.")
            value = 1.0
        self.parameters["mass"] = value

    def showParameters(self):
        return self.msg(self.parameters, self.units)


if __name__ == '__main__':
    P = PendulumParameters(g=9.81, L=1.)
    pylog.debug(P.showParameters())

    M = MuscleParameters()
    pylog.debug(M.showParameters())

    Mass = MassParameters()
    pylog.debug(Mass.showParameters())

Пример #21
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') 
Пример #22
0
def exercise1(clargs):
    """ Exercise 1 """
    # Setup
    pylog.info("Running exercise 1")

    # Setup
    time_max = 5  # Maximum simulation time
    time_step = 0.2  # Time step for ODE integration in simulation
    x0 = np.array([1.])  # Initial state

    # Integration methods (Exercises 1.a - 1.d)
    pylog.info("Running function integration using different methods")

    # Example
    pylog.debug("Running example plot for integration (remove)")
    example = example_integrate(x0, time_max, time_step)
    example.plot_state(figure="Example", label="Example", marker=".")

    # Analytical (1.a)
    time = np.arange(0, time_max, time_step)  # Time vector
    x_a = analytic_function(time)
    analytical = Result(x_a, time) if x_a is not None else None

    # Euler (1.b)
    euler = euler_integrate(function, x0, time_max, time_step)
    display_error(euler.state - analytical.state, "Euler")

    # ODE (1.c)
    ode = ode_integrate(function, x0, time_max, time_step)
    display_error(ode.state - analytical.state, "LSODA")

    # ODE Runge-Kutta (1.c)
    ode_rk = ode_integrate_rk(function_rk, x0, time_max, time_step)
    display_error(ode_rk.state - analytical.state, "Runge-Kutta")

    # Euler with lower time step (1.d)
    euler_time_step = 0.05
    euler_ts_small = (euler_integrate(function, x0, time_max, euler_time_step)
                      if euler_time_step is not None else None)

    # New analytical time step
    time_step_small = 0.05
    time_small = np.arange(0, time_max, time_step_small)  # Time vector
    x_a_small = analytic_function(time_small)
    analytical_small = Result(x_a_small,
                              time_small) if x_a_small is not None else None

    display_error(euler_ts_small.state - analytical_small.state, "Euler small")

    # Plot integration results
    plot_integration_methods(analytical=analytical_small,
                             euler=euler,
                             ode=ode,
                             ode_rk=ode_rk,
                             euler_ts_small=euler_ts_small,
                             euler_timestep=time_step_small,
                             euler_timestep_small=euler_time_step)

    # Error analysis (Exercise 1.e)
    pylog.warning("Error analysis must be implemented")
    dt_list = np.logspace(-3, 0, 20)  # List of timesteps (powers of 10)
    integration_errors = [["L1", 1], ["L2", 2], ["Linf", 0]]
    methods = [["Euler", euler_integrate, function],
               ["Lsoda", ode_integrate, function],
               ["RK", ode_integrate_rk, function_rk]]
    for error_name, error_index in integration_errors:
        for name, integration_function, f in methods:
            compute_error(f,
                          analytic_function,
                          integration_function,
                          x0,
                          dt_list,
                          time_max=time_max,
                          figure=error_name,
                          label=name,
                          n=error_index)

    # Show plots of all results
    if not clargs.save_figures:
        plt.show()
    return
Пример #23
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)
Пример #24
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)
Пример #25
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
Пример #26
0
def save_figures(**kwargs):
    """Save_figures"""
    figures = [str(figure) for figure in plt.get_figlabels()]
    pylog.debug("Other files:\n    - " + "\n    - ".join(figures))
    for name in figures:
        save_figure(name, extensions=kwargs.pop("extensions", ["pdf"]))
Пример #27
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)
Пример #28
0
def plotExternalDrive(sys,x0,ext_in,typ='low'):
    ##### Time #####
    t_max = 2.5  # Maximum simulation time
    time = np.arange(0., t_max, 0.001)  # Time vector
    
    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 Phase, {} drive'.format(typ))
    plt.title('Pendulum Phase, {} drive'.format(typ))
    plt.plot(res[:, 1], res[:, 2])
    plt.xlabel('Position [rad]')
    plt.ylabel('Velocity [rad/s]')
    plt.grid()
    fig.tight_layout()
    fig.savefig('graphs/PendulumPhase{}Drive.png'.format(typ))
    
    # Plotting the state evolution
    fig = plt.figure('Pendulum State, {} drive'.format(typ))
    plt.title('Pendulum State, {} drive'.format(typ))
    plt.plot(res[:, 0], res[:, 1], label='position [rad]')
    plt.plot(res[:, 0], res[:, 2], label='speed [rad/s]')
    plt.xlabel('Time [s]')
    plt.ylabel('')
    plt.legend()
    plt.grid()
    fig.tight_layout()
    fig.savefig('graphs/PendulumState{}drive.png'.format(typ))
    
    # Plotting the neuronal activation
    # Access the neurons outputs:
    # [t] theta theta. A1 lCE1 A2 lCE2 m1 m2 m3 m4
    fig = plt.figure('Neuron output, {} drive'.format(typ))
    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{}drive.png'.format(typ))

    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()
Пример #29
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()
Пример #30
0
            self.parameters['b1'] = value
        pylog.info(
            'Changed damping constant for damper 1 to {} [N-s/rad]'.format(
                self.parameters['b1']))

    @property
    def b2(self):
        """ Get the value of damping constant for damper 2. [N-s/rad]
        Default is 0.5"""
        return self.parameters['b2']

    @b2.setter
    def b2(self, value):
        """ Keyword Arguments:
        value -- Set the value of damping constant for damper 2. [N-s/rad] """
        if (value < 0.0):
            pylog.warning('Setting bad damping values. Should be positive!')
        else:
            self.parameters['b2'] = value
        pylog.info(
            'Changed damping constant for damper 2 to {} [N-s/rad]'.format(
                self.parameters['b2']))

    def showParameters(self):
        return self.msg(self.parameters, self.units)


if __name__ == '__main__':
    P = PendulumParameters(g=9.81, L=1.)
    pylog.debug(P.showParameters())