コード例 #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
コード例 #2
0
ファイル: network.py プロジェクト: mthunemann/Neuroptikon
 def createMuscle(self, *args, **keywordArgs):
     """
     Create a new muscle.
     
     >>> muscle = network.createMuscle(name = 'M1')
      
     Returns the :class:`muscle <Network.Muscle.Muscle>` that is created.
     """
     
     muscle = Muscle(self, *args, **keywordArgs)
     self.addObject(muscle)
     return muscle
コード例 #3
0
def plotRelationLceAPForces(muscle_stretch,muscle_stimulation=1.,l_opt=0.11):
    # Defination of muscles
    parameters = MuscleParameters()
    # Create muscle object
    muscle = Muscle(parameters)    
    # Instatiate isometric muscle system
    sys = IsometricMuscleSystem()
    # Add the muscle to the system
    sys.add_muscle(muscle)
    sys.muscle.L_OPT = l_opt
    # Set the initial condition
    x0 = [0.0, sys.muscle.L_OPT] # x0[0] --> muscle stimulation intial value 
                                 # x0[1] --> muscle contracticle length initial value
    # Set the time for integration
    t_start = 0.0
    t_stop = 0.2
    time_step = 0.001
    time = np.arange(t_start, t_stop, time_step)
    
    # Store the results 
    l_ce = []
    active = []
    passive = []
    tendon = []
    # Run the experiment for different length of the MTU
    for l in muscle_stretch:
        # Run the integration
        result = sys.integrate(x0=x0,
                           time=time,
                           time_step=time_step,
                           stimulation=muscle_stimulation,
                           muscle_length=l)
        l_ce.append(result.l_ce[-1])
        active.append(result.active_force[-1])
        passive.append(result.passive_force[-1])
        tendon.append(result.tendon_force[-1])
        
    plt.figure('Active/passive forces as function of l_ce\n'+
               '(activation: {}, l_opt: {})'
               .format(muscle_stimulation,l_opt))
    plt.plot(l_ce, active,label='active force')
    plt.plot(l_ce, passive,label='passive force')
    plt.plot(l_ce, tendon,label='tendon force')
    plt.legend()
    plt.title('Isometric muscle experiment\nActive/passive forces as function '+  
              'of l_ce\n(activation: {}, l_opt: {})'.format(muscle_stimulation,l_opt))
    plt.xlabel('l_ce [m]')
    plt.ylabel('Force [N]')
    axes = plt.gca()
    axes.set_xlim([0.05,0.2])
    axes.set_ylim([0,1700])
    plt.grid()
コード例 #4
0
def isotonic_experiment(muscle_stimulation, loads,
                        time_param=TimeParameters()):

    # Muscle
    muscle_parameters = MuscleParameters()
    muscle = Muscle(muscle_parameters)

    # Initial conditions
    x0 = [0] * StatesIsotonic.NB_STATES.value
    x0[StatesIsotonic.STIMULATION.value] = 0.
    x0[StatesIsotonic.L_CE.value] = muscle.L_OPT
    x0[StatesIsotonic.LOAD_POS.value] = muscle.L_OPT + muscle.L_SLACK
    x0[StatesIsotonic.LOAD_SPEED.value] = 0.

    # Containers
    v_ce = []
    tendon_force = []

    # Integration
    pylog.info("Running the experiments (this might take a while)...")
    for load in loads:

        # New load definition
        mass_parameters = MassParameters()
        mass_parameters.mass = load
        mass = Mass(mass_parameters)

        # System definition
        sys = IsotonicMuscleSystem()
        sys.add_muscle(muscle)
        sys.add_mass(mass)

        result = sys.integrate(x0=x0,
                               time=time_param.times,
                               time_step=time_param.t_step,
                               time_stabilize=time_param.t_stabilize,
                               stimulation=muscle_stimulation,
                               load=load)

        # Result processing
        if result.l_mtc[-1] > x0[StatesIsotonic.LOAD_POS.value]:
            # Extension
            index = result.v_ce.argmax()
            v_ce.append(result.v_ce.max())
            tendon_force.append(result.tendon_force[index])
        else:
            # Contraction
            index = result.v_ce.argmin()
            v_ce.append(result.v_ce.min())
            tendon_force.append(result.tendon_force[index])

    return v_ce, tendon_force
コード例 #5
0
def exercise1f():
    """ Exercise 1f

    What happens to the force-velocity relationship when the stimulation is varied
    between [0 - 1]?"""
    # Defination of muscles
    muscle_parameters = MuscleParameters()
    print(muscle_parameters.showParameters())

    mass_parameters = MassParameters()
    print(mass_parameters.showParameters())

    # Create muscle object
    muscle = Muscle(muscle_parameters)

    # Create mass object
    mass = Mass(mass_parameters)

    # Instantiate isotonic muscle system
    sys = IsotonicMuscleSystem()

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

    # Add the mass to the system
    sys.add_mass(mass)

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.L_OPT # To get the muscle optimal length

    # Evaluate for a single load
    load = 100.

    # Set the initial condition
    x0 = [0.0, sys.muscle.L_OPT, sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0]
    # x0[0] - -> activation
    # x0[1] - -> contractile length(l_ce)
    # x0[2] - -> position of the mass/load
    # x0[3] - -> velocity of the mass/load

    # Set the time for integration
    t_start = 0.0
    t_stop = 1.25
    time_step = 0.001
    time_stabilize = 0.2

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

    # ---------------------------------------------
    # maximum force over stimulation
    # ---------------------------------------------

    # Evaluate for different muscle stimulation
    muscle_stimulation = np.arange(0, 1.1, 0.1)
    max_active_force = []
    max_passive_force = []
    max_sum_force = []

    # Begin plotting
    for s in muscle_stimulation:
        # Run the integration
        result = sys.integrate(x0=x0,
                               time=time,
                               time_step=time_step,
                               time_stabilize=time_stabilize,
                               stimulation=s,
                               load=load)

        if abs(min(result.active_force)) > max(result.active_force):
            max_active_force.append(min(result.active_force))
        else:
            max_active_force.append(max(result.active_force))

        if abs(min(result.passive_force)) > max(result.passive_force):
            max_passive_force.append(min(result.passive_force))
        else:
            max_passive_force.append(max(result.passive_force))

        max_sum_force.append(max_active_force[-1] + max_passive_force[-1])

    plt.figure('Isotonic muscle active force - stimulation [0, 1]')

    plt.plot(muscle_stimulation,
             max_active_force,
             label='maximum active force')
    plt.plot(muscle_stimulation,
             max_passive_force,
             label='maximum passive force')
    plt.plot(muscle_stimulation, max_sum_force, label='maximum sum force')

    plt.xlabel('Stimulation [-]')
    plt.ylabel('Muscle sum forces [N]')
    plt.legend(loc='upper right')
    plt.grid()

    # ---------------------------------------------
    # force - velocity over stimulation
    # ---------------------------------------------
    muscle_stimulation = np.arange(0, 1.1, 0.1)

    # Begin plotting
    for s in muscle_stimulation:
        # Run the integration
        result = sys.integrate(x0=x0,
                               time=time,
                               time_step=time_step,
                               time_stabilize=time_stabilize,
                               stimulation=s,
                               load=load)

        plt.figure('Isotonic muscle active force - velocity')
        plt.plot(result.v_ce[200:-1],
                 result.active_force[200:-1],
                 label='stimulation {:0.1f}'.format(s))

        plt.figure('Isotonic muscle passive force - velocity')
        plt.plot(result.v_ce[200:-1],
                 result.passive_force[200:-1],
                 label='stimulation {:0.1f}'.format(s))

        plt.figure('Isotonic muscle sum forces - velocity')
        plt.plot(result.v_ce[200:-1],
                 result.active_force[200:-1] + result.passive_force[200:-1],
                 label='stimulation {:0.1f}'.format(s))

    plt.figure('Isotonic muscle active force - velocity')
    plt.xlabel('Velocity contractile element [m/s]')
    plt.ylabel('Active force [N]')
    plt.legend(loc='upper right')
    plt.grid()

    plt.figure('Isotonic muscle passive force - velocity')
    plt.xlabel('Velocity contractile element [m/s]')
    plt.ylabel('Passive force [N]')
    plt.legend(loc='upper right')
    plt.grid()

    plt.figure('Isotonic muscle sum forces - velocity')
    plt.xlabel('Velocity contractile element [m/s]')
    plt.ylabel('Sum forces [N]')
    plt.legend(loc='upper right')
    plt.grid()

    # ---------------------------------------------
    # Plot velocity - tension relation
    # ---------------------------------------------
    muscle_stimulation = np.arange(0, 1.1, 0.25)
    load = np.arange(5, 1500, 20)
    plt.figure('Velocity - Tension')

    # Begin plotting
    for s in muscle_stimulation:
        (max_vce, active_force) = ex1d_for(sys, x0, time, time_step,
                                           time_stabilize, s, load, False)
        plt.plot(load, max_vce, label="stimulation {:0.1f}".format(s))

    plt.title('Velocity [m/s] - Load [N]')
    plt.xlabel('Load [N]')
    plt.ylabel('Velocity [m/s]')
    plt.legend(loc='lower right')
    plt.grid()
コード例 #6
0
def exercise1a():
    """ Exercise 1a
    The goal of this exercise is to understand the relationship
    between muscle length and tension.
    Here you will re-create the isometric muscle contraction experiment.
    To do so, you will have to keep the muscle at a constant length and
    observe the force while stimulating the muscle at a constant activation."""

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

    # Create muscle object
    muscle = Muscle(parameters)

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

    # Instatiate isometric muscle system
    sys = IsometricMuscleSystem()

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

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.L_OPT # To get the muscle optimal length
    muscle_stretches = np.arange(.12, .30, .002)

    #muscle_tendon_forces = []  #Erase or comment
    muscle_active_forces = []
    muscle_passive_forces = []
    total_force = []
    contractile_element_length = []

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

        # Evalute for a single muscle stimulation
        muscle_stimulation = 1.

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

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

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

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

        #        muscle_tendon_forces.append(result.tendon_force[-1])#Erase or comment
        muscle_active_forces.append(result.active_force[-1])
        muscle_passive_forces.append(result.passive_force[-1])
        total_force.append(result.active_force[-1] + result.passive_force[-1])
        contractile_element_length.append(result.l_ce[-1])


#        plotXY(time,result.l_ce,'Time [s]','Contractile Element Length [m]','Active',
#               'Isometric Muscle: Contractile Element Length vs Time',
#               'Isometric Muscle: Contractile Element Length vs Time')

#        plotXY(result.l_ce,result.active_force,'Contractile Element Length [m]','Active Force [N]','Active',
#               'Isometric Muscle: Contractile Element Length vs Force',
#               'Isometric Muscle: Contractile Element Length vs Force')
#        plt.plot(result.l_ce, result.passive_force, label='passive')
#        plt.plot(result.l_ce, result.active_force+result.passive_force, label='total')

# Plotting
    plt.figure('Isometric Muscle: L_ce vs Force')
    plt.plot(contractile_element_length, muscle_active_forces, label='active')
    plt.plot(contractile_element_length,
             muscle_passive_forces,
             label='passive')
    plt.plot(contractile_element_length, total_force, label='total')
    plt.title('Isometric Muscle: Stretch Length vs Force')
    plt.xlabel('Contractile Element Length [m]')
    plt.ylabel('Muscle Force [N]')
    plt.legend(loc='upper right')
    plt.grid()
コード例 #7
0
def exercise1d():
    """ Exercise 1d

    Under isotonic conditions external load is kept constant.
    A constant stimulation is applied and then suddenly the muscle
    is allowed contract. The instantaneous velocity at which the muscle
    contracts is of our interest."""

    # Defination of muscles
    muscle_parameters = MuscleParameters()
    print(muscle_parameters.showParameters())

    mass_parameters = MassParameters()
    print(mass_parameters.showParameters())

    # Create muscle object
    muscle = Muscle(muscle_parameters)

    # Create mass object
    mass = Mass(mass_parameters)

    pylog.warning("Isotonic muscle contraction to be implemented")

    # Instatiate isotonic muscle system
    sys = IsotonicMuscleSystem()

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

    # Add the mass to the system
    sys.add_mass(mass)

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.L_OPT # To get the muscle optimal length

    # Evaluate for a single muscle stimulation
    muscle_stimulation = 1.

    # Set the initial condition
    x0 = [0.0, sys.muscle.L_OPT, sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0]
    # x0[0] - -> activation
    # x0[1] - -> contractile length(l_ce)
    # x0[2] - -> position of the mass/load
    # x0[3] - -> velocity of the mass/load

    # Set the time for integration
    t_start = 0.0
    t_stop = 1.25
    time_step = 0.001
    time_stabilize = 0.2

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

    # Set max_vce
    max_vce = []

    # ---------------------------------------------
    # Small load experiment
    # ---------------------------------------------
    load_table_small = [5, 10, 20, 50, 100]

    # Begin plotting
    plt.figure('Isotonic muscle experiment - load [10, 200] [N]')
    max_vce_small = ex1d_for(sys, x0, time, time_step, time_stabilize,
                             muscle_stimulation, load_table_small, False)

    plt.title('Isotonic muscle experiment - load [5, 140] [N]')
    plt.xlabel('Time [s]')
    plt.ylabel('Muscle contractile velocity [m/s]')
    plt.legend(loc='upper right')
    plt.grid()

    # ---------------------------------------------
    # Big load experiment
    # ---------------------------------------------
    load_table_big = [150, 200, 220, 250, 500, 1000, 1500]

    # Begin plotting
    plt.figure('Isotonic muscle experiment - load [150, 1500] [N]')
    max_vce += ex1d_for(sys, x0, time, time_step, time_stabilize,
                        muscle_stimulation, load_table_big, True)

    plt.title('Isotonic muscle experiment - load [150, 1500] [N]')
    plt.xlabel('Time [s]')
    plt.ylabel('Muscle contractile velocity [m/s]')
    plt.legend(loc='upper right')
    plt.grid()

    # ---------------------------------------------
    # Plot velocity - tension relation
    # ---------------------------------------------
    load = np.arange(5, 2500, 200)
    (max_vce, active_force) = ex1d_for(sys, x0, time, time_step,
                                       time_stabilize, muscle_stimulation,
                                       load, False)

    fig = plt.figure('Velocity - Tension')
    ax = fig.add_subplot(111)

    # Plot comments and line at 0 value
    min_val = 0.0
    if min(map(abs, max_vce)) not in max_vce:
        min_val = -min(map(abs, max_vce))
    else:
        min_val = min(map(abs, max_vce))

    xy = (load[max_vce.index(min_val)], min_val)
    xytext = (load[max_vce.index(min_val)] + 50, min_val)
    ax.annotate('load = {:0.1f}'.format(152.2), xy=xy, xytext=xytext)

    plt.title('Velocity [m/s] - Tension [N]')
    plt.xlabel('Tension [N]')
    plt.ylabel('Velocity [m/s]')
    plt.grid()

    plt.plot(load, max_vce)
    plt.plot(load[max_vce.index(min_val)], min_val, 'o')
コード例 #8
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') 
コード例 #9
0
def exercise1c():
    """describe how fiber length influences the force-length curve. Compare 
    a muscle comprised of short muscle fibers to a muscle comprised of 
    long muscle fibers. Change the parameter, you can use 
    system_parameters.py::MuscleParameters before instantiating the muscle
    No more than 2 plots are required.
    """

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

    # Create muscle object
    muscle = Muscle(parameters)

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

    # Instatiate isometric muscle system
    sys = IsometricMuscleSystem()

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

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

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

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

        parameters.l_opt = muscle_length
        muscle = Muscle(parameters)

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

        # Instatiate isometric muscle system
        sys = IsometricMuscleSystem()

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

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

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

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

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

            # Evalute for a single muscle stimulation
            muscle_stimulation = 1.

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

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

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

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

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

        max_muscle_active_forces.append(max(muscle_active_forces))

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

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

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

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

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

    #    print(max_muscle_active_forces)
    # Plot max stretch lengths of max vals
    plt.figure('Isometric muscle experiment max Force stretch')
    plt.plot(muscle_lengths, max_force_stretch, label='active')
    #plt.plot(muscle_lengths, max_muscle_passive_forces, label='passive')
    #plt.plot(muscle_lengths, max_total_force, label='total')
    plt.title('Isometric muscle experiment 1C, Max Stretch')
    plt.xlabel('Muscle Optimal Length [m]')
    plt.ylabel('Muscle Stretch of Max Force [m]')
    plt.legend(loc='upper left')
    plt.grid()
コード例 #10
0
ファイル: exercise2.py プロジェクト: thirteenfoil8/CMC
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()
コード例 #11
0
ファイル: exercise2.py プロジェクト: mfendri2/CMC2019
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()
コード例 #12
0
def exercise1d():
    """ Exercise 1d

    Under isotonic conditions external load is kept constant.
    A constant stimulation is applied and then suddenly the muscle
    is allowed contract. The instantaneous velocity at which the muscle
    contracts is of our interest."""

    # Defination of muscles
    muscle_parameters = MuscleParameters()
    print(muscle_parameters.showParameters())

    mass_parameters = MassParameters()
    print(mass_parameters.showParameters())

    # Create muscle object
    muscle = Muscle(muscle_parameters)

    # Create mass object
    mass = Mass(mass_parameters)

    pylog.warning("Isotonic muscle contraction to be implemented")

    # Instatiate isotonic muscle system
    sys = IsotonicMuscleSystem()

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

    # Add the mass to the system
    sys.add_mass(mass)

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.L_OPT # To get the muscle optimal length

    # Evalute for a single load
    load = 100.

    # Evalute for a single muscle stimulation
    muscle_stimulation = 1.

    # Set the initial condition
    x0 = [0.0, sys.muscle.L_OPT, sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0]

    # x0[0] - -> activation
    # x0[1] - -> contractile length(l_ce)
    # x0[2] - -> position of the mass/load
    # x0[3] - -> velocity of the mass/load

    # Set the time for integration
    t_start = 0.0
    t_stop = 0.5
    time_step = 0.001
    time_stabilize = 0.2

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

    loads = np.arange(20, 351, 10)

    velocities = []

    for index, load in enumerate(loads):

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

        if (result.l_mtc[-1] < sys.muscle.L_OPT + sys.muscle.L_SLACK):
            velocities.append(np.max(result.v_ce))
            print('max')
        else:
            velocities.append(np.min(result.v_ce))
            print('min')

    #Muscle contracile Velocity - Tension (load) relationship

    plt.figure('Isotonic muscle experiment')
    plt.title('Isotonic muscle experiment')
    plt.xlabel('Muscle Contractile Velocity [m/s]')
    plt.ylabel('Tension (load) [N]')
    plt.plot(velocities, loads)
    plt.grid()

    #For different stimulations 1.f

    muscle_stimulation = np.arange(0, 1.1, 0.2)
    plt.figure('Isotonic muscle exp with different stimulations')
    plt.title('Isotonic muscle experiment with different stimulations')

    for stim in muscle_stimulation:
        velocities = []
        for index, load in enumerate(loads):
            #    Run the integration
            result = sys.integrate(x0=x0,
                                   time=time,
                                   time_step=time_step,
                                   time_stabilize=time_stabilize,
                                   stimulation=stim,
                                   load=load)

            if (result.l_mtc[-1] < sys.muscle.L_OPT + sys.muscle.L_SLACK):
                velocities.append(np.max(result.v_ce))
            else:
                velocities.append(np.min(result.v_ce))
        plt.xlabel('Muscle Contractile Velocity [m/s]')
        plt.ylabel('Tension (load) [N]')
        plt.plot(velocities, loads)

    plt.legend(('0', '0.2', '0.4', '0.6', '0.8', '1.0'))
    plt.grid()
コード例 #13
0
def exercise1a():
    """ Exercise 1a
    The goal of this exercise is to understand the relationship
    between muscle length and tension.
    Here you will re-create the isometric muscle contraction experiment.
    To do so, you will have to keep the muscle at a constant length and
    observe the force while stimulating the muscle at a constant activation."""

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

    # Create muscle object
    muscle = Muscle(parameters)

    # Instatiate isometric muscle system
    sys = IsometricMuscleSystem()

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

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

    # Set the time for integration
    t_start = 0.0
    t_stop = 0.5
    time_step = 0.001
    time = np.arange(t_start, t_stop, time_step)

    # Evalute for a single muscle stimulation
    muscle_stimulation = np.arange(0, 1., 0.2)

    # Several muscle stretch
    muscle_stretches = np.arange(0, 0.3, 0.01)

    active_active = []

    for stim in muscle_stimulation:
        active_forces = []
        passive_forces = []
        total = []
        lengths = []
        for stretch in muscle_stretches:
            # Run the integration
            result = sys.integrate(x0=x0,
                                   time=time,
                                   time_step=time_step,
                                   stimulation=stim,
                                   muscle_length=stretch)
            active_forces.append(result.active_force[-1])
            passive_forces.append(result.passive_force[-1])
            total.append(result.active_force[-1] + result.passive_force[-1])
            lengths.append(result.l_ce[-1])
        active_active.append(active_forces)

    # Plotting
    plt.figure('Isometric muscle experiment 1')
    plt.plot(lengths, active_forces)
    plt.plot(lengths, passive_forces)
    plt.plot(lengths, total)
    plt.title('Isometric muscle experiment stimulation')
    plt.xlabel('Muscle stretch')
    plt.ylabel('Muscle force')
    plt.legend(('Active', 'Passive', 'Total'))
    plt.grid()
    plt.show()

    # Plotting
    plt.figure('Isometric muscle experiment 2')
    for i in range(len(muscle_stimulation)):
        plt.plot(lengths, active_active[i])
    plt.title('Isometric muscle experiment')
    plt.xlabel('Muscle stretch')
    plt.ylabel('Muscle force')
    plt.legend(muscle_stimulation)
    plt.grid()
    plt.show()

    # Plotting
    #plt.figure('Isotonic muscle experiment')
    #plt.plot(result.time, result.v_ce)
    #plt.title('Isotonic muscle experiment')
    #plt.xlabel('Time [s]')
    #plt.ylabel('Muscle contractilve velocity')
    #plt.grid()

    #muscle with longer l_opt
    muscle.L_OPT = 0.5
    muscle_stimulation = 1.
    lce = []
    totalF = []
    activeF = []
    passiveF = []
    for stretch in muscle_stretches:
        # Run the integration
        result = sys.integrate(x0=x0,
                               time=time,
                               time_step=time_step,
                               stimulation=muscle_stimulation,
                               muscle_length=stretch)
        activeF.append(result.active_force[-1])
        passiveF.append(result.passive_force[-1])
        lce.append(result.l_ce[-1])
        totalF.append(result.active_force[-1] + result.passive_force[-1])
    plt.figure('muscle with l_opt=0.5')
    plt.title('muscle with l_opt=0.5')
    plt.plot(lce, activeF)
    plt.plot(lce, passiveF)
    plt.plot(lce, totalF)
    plt.xlabel('Muscle Stretch')
    plt.ylabel('Force')
    plt.ylim((0, 4000))
    plt.legend(('Active Force', 'Passive Force', 'Total Force'))

    plt.grid()

    #muscle with shorter l_opt
    t_start = 0.0
    t_stop = 1
    time_step = 0.005

    time = np.arange(t_start, t_stop, time_step)
    muscle_stretches = np.arange(0, 0.3, 0.01)
    muscle.L_OPT = 0.075
    muscle_stimulation = 1.
    lce = []
    totalF = []
    activeF = []
    passiveF = []
    plt.figure('muscle with l_opt=0.075')

    for stretch in muscle_stretches:
        # Run the integration
        result = sys.integrate(x0=x0,
                               time=time,
                               time_step=time_step,
                               stimulation=muscle_stimulation,
                               muscle_length=stretch)
        activeF.append(result.active_force[-1])
        passiveF.append(result.passive_force[-1])
        lce.append(result.l_ce[-1])
        totalF.append(result.active_force[-1] + result.passive_force[-1])
    plt.title('muscle with l_opt=0.075')
    plt.plot(lce, activeF)
    plt.plot(lce, passiveF)
    plt.plot(lce, totalF)
    plt.xlabel('Muscle Stretch')
    plt.ylabel('Force')
    plt.ylim((0, 4000))
    plt.legend(('Active Force', 'Passive Force', 'Total Force'))
    plt.grid()
def exercise1a():
    """ Exercise 1a
    The goal of this exercise is to understand the relationship
    between muscle length and tension.
    Here you will re-create the isometric muscle contraction experiment.
    To do so, you will have to keep the muscle at a constant length and
    observe the force while stimulating the muscle at a constant activation."""

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

    # Create muscle object
    muscle = Muscle(parameters)

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

    # Instatiate isometric muscle system
    sys = IsometricMuscleSystem()

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

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.l_opt # To get the muscle optimal length
    #x0 = [0.0, sys.muscle.L_OPT]

    # Evalute for a single muscle stretch
    muscle_stretch = 0.2

    # Evalute for a single muscle stimulation
    muscle_stimulation = 1.

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

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

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

    # Run the integration

    result = sys.integrate(x0=x0,
                           time=time,
                           time_step=time_step,
                           stimulation=muscle_stimulation,
                           muscle_length=muscle_stretch)

    # Plotting
    plt.figure('Isometric muscle experiment')
    plt.plot(result.time, result.l_ce)
    plt.title('Isometric muscle experiment')
    plt.xlabel('Time [s]')
    plt.ylabel('Muscle contracticle length [m]')
    plt.grid()

    muscle_stretches = np.arange(0, muscle_stretch, 0.001)

    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ### code for 1a
    pylog.info(
        "1a. relationship between forces and contractile element length")

    length_start = 0.0
    length_stop = 0.3
    length_step = 0.005
    muscle_lengths = np.arange(length_start, length_stop, length_step)

    active_forces = []
    passive_forces = []
    total_forces = []
    element_lengths = []

    for temp_length in muscle_lengths:

        temp_result = sys.integrate(x0=x0,
                                    time=time,
                                    time_step=time_step,
                                    stimulation=muscle_stimulation,
                                    muscle_length=temp_length)
        temp_active_force = temp_result.active_force[-1]
        temp_passive_force = temp_result.passive_force[-1]
        tenp_total_force = temp_active_force + temp_passive_force
        temp_element_length = temp_result.l_ce[-1]

        active_forces = active_forces + [temp_active_force]
        passive_forces = passive_forces + [temp_passive_force]
        total_forces = total_forces + [tenp_total_force]
        element_lengths = element_lengths + [temp_element_length]

    plt.figure("1a. Isometric muscle experiment (muscle_stimulation == 1)")
    plt.plot(element_lengths, active_forces)
    plt.plot(element_lengths, passive_forces)
    plt.plot(element_lengths, total_forces)
    plt.title('Isometric Muscle Experiment (muscle_stimulation == 1)')
    plt.xlabel('Muscle contracticle length [m]')
    plt.ylabel('Tension [N]')
    plt.legend(("Active Force", "Passive Force", "Total force"))
    plt.grid()
    plt.show()

    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ### code for 1b
    pylog.info(
        "1b. relationship between forces and contractile element length with different stimulations"
    )

    length_start = 0.0
    length_stop = 0.3
    length_step = 0.005
    muscle_lengths = np.arange(length_start, length_stop, length_step)

    muscle_stimulations = np.arange(0, muscle_stimulation + 0.1, 0.1)

    all_active_forces = []
    all_passive_forces = []
    all_total_forces = []
    all_element_lengths = []

    for temp_muscle_stimulation in muscle_stimulations:
        temp_active_forces = []
        temp_passive_forces = []
        temp_total_forces = []
        temp_element_lengths = []

        for temp_length in muscle_lengths:
            temp_result = sys.integrate(x0=x0,
                                        time=time,
                                        time_step=time_step,
                                        stimulation=temp_muscle_stimulation,
                                        muscle_length=temp_length)
            temp_active_force = temp_result.active_force[-1]
            temp_passive_force = temp_result.passive_force[-1]
            tenp_total_force = temp_active_force + temp_passive_force
            temp_element_length = temp_result.l_ce[-1]

            temp_active_forces = temp_active_forces + [temp_active_force]
            temp_passive_forces = temp_passive_forces + [temp_passive_force]
            temp_total_forces = temp_total_forces + [tenp_total_force]
            temp_element_lengths = temp_element_lengths + [temp_element_length]

        all_active_forces = all_active_forces + [temp_active_forces]
        all_passive_forces = all_passive_forces + [temp_passive_forces]
        all_total_forces = all_total_forces + [temp_total_forces]
        all_element_lengths = all_element_lengths + [temp_element_lengths]

    plt.figure(
        '1b. Isometric muscle experiment for active forces with different stimulations'
    )
    for i in range(len(muscle_stimulations)):
        plt.plot(all_element_lengths[i], all_active_forces[i])
    plt.title(
        'Isometric muscle experiment for active forces with different stimulations'
    )
    plt.xlabel('Muscle contracticle length [m]')
    plt.ylabel('Tension [N]')
    temp_legends = [
        'stimulation = ' + format((temp_stimulation), '.1f')
        for temp_stimulation in muscle_stimulations
    ]
    plt.legend(temp_legends)
    plt.grid()
    plt.show()

    plt.figure(
        '1b. Isometric muscle experiment for passive forces with different stimulations'
    )
    for i in range(len(muscle_stimulations)):
        plt.plot(all_element_lengths[i], all_passive_forces[i])
    plt.title(
        'Isometric muscle experiment for passive forces with different stimulations'
    )
    plt.xlabel('Muscle contracticle length [m]')
    plt.ylabel('Tension [N]')
    temp_legends = [
        'stimulation = ' + format((temp_stimulation), '.1f')
        for temp_stimulation in muscle_stimulations
    ]
    plt.legend(temp_legends)
    plt.grid()
    plt.show()

    plt.figure(
        '1b. Isometric muscle experiment for total forces with different stimulations'
    )
    for i in range(len(muscle_stimulations)):
        plt.plot(all_element_lengths[i], all_total_forces[i])
    plt.title(
        'Isometric muscle experiment for total forces with different stimulations'
    )
    plt.xlabel('Muscle contracticle length [m]')
    plt.ylabel('Tension [N]')
    temp_legends = [
        'stimulation = ' + format((temp_stimulation), '.1f')
        for temp_stimulation in muscle_stimulations
    ]
    plt.legend(temp_legends)
    plt.grid()
    plt.show()

    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ### code for 1c
    pylog.info(
        "1c. relationship between forces and contractile element length with different fiber lengths"
    )

    short_opt = 0.05
    medium_opt = 0.1
    long_opt = 0.15
    opt_range = [short_opt, medium_opt, long_opt]

    muscle_stimulation = 1.

    length_start = 0.0
    length_stop = 0.3
    length_step = 0.005
    muscle_lengths = np.arange(length_start, length_stop, length_step)

    for temp_opt in opt_range:

        parameters = MuscleParameters(l_opt=temp_opt)
        muscle = Muscle(parameters)
        sys = IsometricMuscleSystem()
        sys.add_muscle(muscle)
        #muscle.L_OPT = temp_opt

        temp_active_forces = []
        temp_passive_forces = []
        temp_total_forces = []
        temp_element_lengths = []

        for temp_length in muscle_lengths:
            temp_result = sys.integrate(x0=x0,
                                        time=time,
                                        time_step=time_step,
                                        stimulation=muscle_stimulation,
                                        muscle_length=temp_length)
            temp_active_force = temp_result.active_force[-1]
            temp_passive_force = temp_result.passive_force[-1]
            tenp_total_force = temp_active_force + temp_passive_force
            temp_element_length = temp_result.l_ce[-1]

            temp_active_forces = temp_active_forces + [temp_active_force]
            temp_passive_forces = temp_passive_forces + [temp_passive_force]
            temp_total_forces = temp_total_forces + [tenp_total_force]
            temp_element_lengths = temp_element_lengths + [temp_element_length]

        plt.figure(
            "1c. Isometric muscle experiment with musle fiber length  = " +
            format((temp_opt), '.2f'))
        plt.plot(temp_element_lengths, temp_active_forces)
        plt.plot(temp_element_lengths, temp_passive_forces)
        plt.plot(temp_element_lengths, temp_total_forces)
        plt.xlabel('Muscle contracticle length [m]')
        plt.ylabel('Tension [N]')
        plt.title("Isometric muscle experiment with musle fiber length  = " +
                  format((temp_opt), '.2f'))
        plt.legend(("Active Force", "Passive Force ", "Total Force "))
        plt.grid()
        plt.show()
def exercise1d():
    """ Exercise 1d

    Under isotonic conditions external load is kept constant.
    A constant stimulation is applied and then suddenly the muscle
    is allowed contract. The instantaneous velocity at which the muscle
    contracts is of our interest."""

    # Defination of muscles
    muscle_parameters = MuscleParameters()
    print(muscle_parameters.showParameters())

    mass_parameters = MassParameters()
    print(mass_parameters.showParameters())

    # Create muscle object
    muscle = Muscle(muscle_parameters)

    # Create mass object
    mass = Mass(mass_parameters)

    pylog.warning("Isotonic muscle contraction to be implemented")

    # Instatiate isotonic muscle system
    sys = IsotonicMuscleSystem()

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

    # Add the mass to the system
    sys.add_mass(mass)

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.l_opt # To get the muscle optimal length

    # Evalute for a single load
    load = 250 / 9.81

    # Evalute for a single muscle stimulation
    muscle_stimulation = 1.0

    # Set the initial condition
    x0 = [0.0, sys.muscle.l_opt, sys.muscle.l_opt + sys.muscle.l_slack, 0.0]
    # x0[0] - -> activation
    # x0[1] - -> contractile length(l_ce)
    # x0[2] - -> position of the mass/load
    # x0[3] - -> velocity of the mass/load

    # Set the time for integration
    t_start = 0.0
    t_stop = 0.4
    time_step = 0.001
    time_stabilize = 0.2

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

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

    # Plotting
    plt.figure('Isotonic muscle experiment')
    plt.plot(result.time, result.v_ce)
    plt.title('Isotonic muscle experiment')
    plt.xlabel('Time [s]')
    plt.ylabel('Muscle contracticle velocity [lopts/s]')
    plt.grid()

    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ### code for 1d
    pylog.info(
        "1d. relationship between muscle contractile velocity and external load"
    )

    load_start = 1
    load_stop = 501
    load_step = 10
    load_range = np.arange(load_start, load_stop, load_step)

    muscle_stimulation = 1.0

    vels = []
    tendon_forces = []
    active_forces = []
    passive_forces = []
    total_forces = []

    for temp_load in load_range:
        temp_result = sys.integrate(x0=x0,
                                    time=time,
                                    time_step=time_step,
                                    time_stabilize=time_stabilize,
                                    stimulation=muscle_stimulation,
                                    load=temp_load)

        temp_tendon_force = temp_result.tendon_force[-1]
        temp_active_force = temp_result.active_force[-1]
        temp_passive_force = temp_result.passive_force[-1]
        temp_total_force = temp_active_force + temp_passive_force

        tendon_forces = tendon_forces + [temp_tendon_force]
        active_forces = active_forces + [temp_active_force]
        passive_forces = passive_forces + [temp_passive_force]
        total_forces = total_forces + [temp_total_force]

        temp_l_mtu = temp_result.l_mtu[-1]

        if temp_l_mtu < sys.muscle.l_opt + sys.muscle.l_slack:
            vels = vels + [np.min(temp_result.v_ce)]
        else:
            vels = vels + [np.max(temp_result.v_ce)]

    plt.figure(
        '1d. Isotonic muscle experiment for tension and contractile velocities'
    )
    plt.plot(vels, tendon_forces)
    plt.plot(vels, load_range)
    plt.plot(vels, active_forces)
    plt.plot(vels, passive_forces)
    plt.plot(vels, total_forces)
    plt.title(
        'Isotonic muscle experiment for tension and contractile velocities')
    plt.xlabel('Muscle contracticle velocity [lopts/s]')
    plt.ylabel('Tension [N]')
    plt.legend(("Tendon Force", "Load", "Active Force", "Passive Force",
                "Total force"))
    plt.grid()
    plt.show()

    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ######################################################################
    ### code for 1f

    pylog.info(
        "1f. relationship between muscle contractile velocity and external load with different stimulations"
    )

    muscle_stimulations = np.arange(0, muscle_stimulation + 0.1, 0.1)

    load_start = 1
    load_stop = 501
    load_step = 10
    load_range = np.arange(load_start, load_stop, load_step)

    all_vels = []
    all_tendon_forces = []

    for temp_muscle_stimulation in muscle_stimulations:

        temp_vels = []
        temp_tendon_forces = []

        for temp_load in load_range:
            temp_result = sys.integrate(x0=x0,
                                        time=time,
                                        time_step=time_step,
                                        time_stabilize=time_stabilize,
                                        stimulation=temp_muscle_stimulation,
                                        load=temp_load)

            temp_tendon_force = temp_result.tendon_force[-1]
            temp_tendon_forces = temp_tendon_forces + [temp_tendon_force]

            temp_l_mtu = temp_result.l_mtu[-1]

            if temp_l_mtu < sys.muscle.l_opt + sys.muscle.l_slack:
                temp_vels = temp_vels + [np.min(temp_result.v_ce)]
            else:
                temp_vels = temp_vels + [np.max(temp_result.v_ce)]

        all_vels = all_vels + [temp_vels]
        all_tendon_forces = all_tendon_forces + [temp_tendon_forces]

    plt.figure(
        '1f. Isotonic muscle experiment for loads and contractile velocities with different stimulations'
    )
    for i in range(len(muscle_stimulations)):
        plt.plot(all_vels[i], load_range)
    plt.title(
        'Isotonic muscle experiment for loads and contractile velocities with different stimulations'
    )
    plt.xlabel('Muscle contracticle velocity [lopts/s]')
    plt.ylabel('Tension [N]')
    temp_legends = [
        'stimulation = ' + format((temp_stimulation), '.1f')
        for temp_stimulation in muscle_stimulations
    ]
    plt.legend(temp_legends)
    plt.grid()
    plt.show()

    plt.figure(
        '1f. Isotonic muscle experiment for tendon forces and contractile velocities with different stimulations'
    )
    for i in range(len(muscle_stimulations)):
        plt.plot(all_vels[i], all_tendon_forces[i])
    plt.title(
        'Isotonic muscle experiment for tendon forces and contractile velocities with different stimulations'
    )
    plt.xlabel('Muscle contracticle velocity [lopts/s]')
    plt.ylabel('Tension [N]')
    temp_legends = [
        'stimulation = ' + format((temp_stimulation), '.1f')
        for temp_stimulation in muscle_stimulations
    ]
    plt.legend(temp_legends)
    plt.grid()
    plt.show()
def system_init():
    """Initialize default system."""
    ########## PENDULUM ##########
    # Define and Setup your pendulum model here
    # Check Pendulum.py for more details on Pendulum class
    P_params = PendulumParameters()  # Instantiate pendulum parameters
    P_params.L = 1.0  # To change the default length of the pendulum
    P_params.m = 0.25  # To change the default mass of the pendulum
    pendulum = PendulumSystem(P_params)  # Instantiate Pendulum object
    #### CHECK OUT Pendulum.py to ADD PERTURBATIONS TO THE MODEL #####
    pylog.info('Pendulum model initialized \n {}'.format(
        pendulum.parameters.showParameters()))

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

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

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

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

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

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

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

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

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

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

    # Method to add the muscle activations to the simulation

    sim.add_muscle_stimulations(activations)

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

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

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

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

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

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

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

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

    L2_s = []
    h2_s = []

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    positions = []
    vels = []

    for temp_omega in omegas:

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

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

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

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

    # To animate the model, use the SystemAnimation class
    # Pass the res(states) and systems you wish to animate
    simulation = SystemAnimation(res, sim.sys.pendulum_sys, sim.sys.muscle_sys)
    if not DEFAULT["save_figures"]:
        # To start the animation
        simulation.animate()
        plt.show()
    else:
        figures = plt.get_figlabels()
        pylog.debug("Saving figures:\n{}".format(figures))
        for fig in figures:
            plt.figure(fig)
            save_figure(fig)
            plt.close(fig)
コード例 #18
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)
コード例 #19
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()
コード例 #20
0
def exercise1d():
    """ Exercise 1d

    Under isotonic conditions external load is kept constant.
    A constant stimulation is applied and then suddenly the muscle
    is allowed contract. The instantaneous velocity at which the muscle
    contracts is of our interest."""

    # Defination of muscles
    muscle_parameters = MuscleParameters()
    print(muscle_parameters.showParameters())

    mass_parameters = MassParameters()
    print(mass_parameters.showParameters())

    # Create muscle object
    muscle = Muscle(muscle_parameters)

    # Create mass object
    mass = Mass(mass_parameters)

    pylog.warning("Isotonic muscle contraction to be implemented")

    # Instatiate isotonic muscle system
    sys = IsotonicMuscleSystem()

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

    # Add the mass to the system
    sys.add_mass(mass)

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.L_OPT # To get the muscle optimal length

    # Evalute for a single load
    load = 100.

    # Evalute for a single muscle stimulation
    muscle_stimulation = 1.

    # Set the initial condition
    x0 = [0.0, sys.muscle.L_OPT,
          sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0]
    # x0[0] - -> activation
    # x0[1] - -> contractile length(l_ce)
    # x0[2] - -> position of the mass/load
    # x0[3] - -> velocity of the mass/load

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

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

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

    # Plotting
    plt.figure('Isotonic muscle experiment')
    plt.plot(result.time, result.v_ce)
    plt.title('Isotonic muscle experiment')
    plt.xlabel('Time [s]')
    plt.ylabel('Muscle contractilve velocity')
    plt.grid()
    
    # Run 1.d
    load = np.arange(0,1000,20)
    plotVceLoad(load,[0.1,0.5,1])
コード例 #21
0
ファイル: exercise2.py プロジェクト: thirteenfoil8/CMC
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()
コード例 #22
0
def exercise1a():
    """ Exercise 1a
    The goal of this exercise is to understand the relationship
    between muscle length and tension.
    Here you will re-create the isometric muscle contraction experiment.
    To do so, you will have to keep the muscle at a constant length and
    observe the force while stimulating the muscle at a constant activation."""

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

    # Create muscle object
    muscle = Muscle(parameters)

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

    # Instatiate isometric muscle system
    sys = IsometricMuscleSystem()

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

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.L_OPT # To get the muscle optimal length

    # Evalute for a single muscle stretch
    muscle_stretch = 0.2

    # Evalute for a single muscle stimulation
    muscle_stimulation = 1.

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

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

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

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

    # Plotting
    plt.figure('Isometric muscle experiment')
    plt.plot(result.time, result.tendon_force,label='tendon force')
    plt.plot(result.time, result.passive_force,label='passive force')
    plt.plot(result.time, result.active_force,label='active force')
    plt.plot(result.time, result.l_ce,label='l_ce')
    plt.legend()
    plt.title('Isometric muscle experiment')
    plt.xlabel('Time [s]')
    plt.ylabel('Muscle Force')
    plt.grid()
    
    # Run 1.a and 1.b - relation between l_ce and active/oassive forces 
    ms=np.arange(start=0.0,stop=0.32,step=0.005)
    plotRelationLceAPForces(muscle_stretch=ms,muscle_stimulation=0.1)
    plotRelationLceAPForces(muscle_stretch=ms,muscle_stimulation=0.5)
    plotRelationLceAPForces(muscle_stretch=ms,muscle_stimulation=1.)
    
    # Run 1.c 
    plotRelationLceAPForces(ms,l_opt=0.09)
    plotRelationLceAPForces(ms,l_opt=0.13)
コード例 #23
0
ファイル: exercise2.py プロジェクト: mfendri2/CMC2019
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)
コード例 #24
0
ファイル: exercise2.py プロジェクト: iricchi/CMC
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
ファイル: main.py プロジェクト: iandanforth/toy-arm-sim
def main():

    # Parameters
    muscle_count = 100  # How many muscles to create
    min_innervation_ratio = 5
    max_innervation_ratio = 2000  # This is a probabalistic set point, not a hard max
    min_fiber_count = 1000
    max_fiber_count = 1500000
    skew = -500000

    # Create all the fibers in the body
    # We want an aproximately normal distribution of fiber counts across all muscles
    # We skew that distribution toward smaller fiber counts as is found in the human body
    fiber_counts_by_muscle = norm_in_range(min_fiber_count,
                                           max_fiber_count,
                                           std=3,
                                           count=muscle_count,
                                           round=True,
                                           skew=skew)
    fiber_counts_by_muscle = sorted(fiber_counts_by_muscle)
    fiber_population_mean = np.mean(fiber_counts_by_muscle)  # ~300,000

    if plotly and DEBUG:
        data = [go.Histogram(x=fiber_counts_by_muscle)]
        plotly.offline.plot(data)

    ##############################################################################
    # One muscle
    f_count = norm_in_range(min_fiber_count,
                            max_fiber_count,
                            3,
                            round=True,
                            skew=skew)
    f_count = f_count[0]
    print "Number of fibers: ", f_count

    motor_units = gen_motor_units(f_count, fiber_population_mean,
                                  max_innervation_ratio)
    print "Number of Motor Units: ", len(motor_units)
    print "Innervation Number: ", f_count / len(motor_units)
    m = Muscle(motor_units)
    activations = m.get_activations()

    print m.get_force()

    ##############################################################################
    # All muscles
    muscles = []
    for fiber_count in fiber_counts_by_muscle:
        # For each muscle we want to group muscle fibers into motor units
        # Each motor unit is an int representing the number of fibers the unit innervates
        motor_units = gen_motor_units(fiber_count, fiber_population_mean,
                                      max_innervation_ratio)

        m = Muscle(motor_units)
        muscles.append(m)

    # Activate all the muscles
    forces = []

    for m in muscles:
        l = m.get_motor_unit_count()
        m.set_activations(np.random.rand(l))
        force = m.get_force()
        forces.append(force)

    print sorted(forces)
コード例 #26
0
ファイル: exercise3.py プロジェクト: Gabmrtt/CMC
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
コード例 #27
0
def plotVceLoad(load,ms=[1.]):
    # Defination of muscles
    muscle_parameters = MuscleParameters()
    mass_parameters = MassParameters()
    # Create muscle object
    muscle = Muscle(muscle_parameters)
    # Create mass object
    mass = Mass(mass_parameters)
    # Instatiate isotonic muscle system
    sys = IsotonicMuscleSystem()
    # Add the muscle to the system
    sys.add_muscle(muscle)
    # Add the mass to the system
    sys.add_mass(mass)
    
    # Evalute for a single load
    #load = 100.

    # Set the initial condition
    x0 = [0.0, sys.muscle.L_OPT,
          sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0]
    # x0[0] - -> activation
    # x0[1] - -> contractile length(l_ce)
    # x0[2] - -> position of the mass/load
    # x0[3] - -> velocity of the mass/load

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

    time = np.arange(t_start, t_stop, time_step)
    
    plt.figure('Max Velocity-Tension curve')
    for s in ms:
        muscle_stimulation = s
        v = []
        for l in load:
            # Run the integration
            result = sys.integrate(x0=x0,
                                   time=time,
                                   time_step=time_step,
                                   time_stabilize=time_stabilize,
                                   stimulation=muscle_stimulation,
                                   load=l)
            # Find the max or min speed achieved
            i = np.argmax(np.abs(result.v_ce))
            v.append(-result.v_ce[i])
            #if result[i].l_mtc < sys.muscle.L_OPT + sys.muscle.L_SLACK:
        
        for i in range(len(v)):
            if i >= 1 and v[i]*v[i-1] <=0:
                plt.plot(load[i],v[i],color='green', marker='x', linestyle='dashed',
                         linewidth=2, markersize=12)
        plt.plot(load, v,label='maximal speed\nMuscle stimulation: {}'.format(s))
        plt.legend()
        plt.title('Isotonic muscle experiment\nMax Velocity-Tension curve')
        plt.xlabel('load [kg]')
        plt.ylabel('CE speed [m/s]') 
        #axes = plt.gca()
        #axes.set_xlim([0.05,0.2])
        #axes.set_ylim([0,1700])
    plt.grid()
コード例 #28
0
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()
コード例 #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
def exercise1b():
    """ Exercise 1a
    The goal of this exercise is to understand the relationship
    between muscle length and tension.
    Here you will re-create the isometric muscle contraction experiment.
    To do so, you will have to keep the muscle at a constant length and
    observe the force while stimulating the muscle at a constant activation."""

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

    # Create muscle object
    muscle = Muscle(parameters)

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

    # Instatiate isometric muscle system
    sys = IsometricMuscleSystem()

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

    # You can still access the muscle inside the system by doing
    # >>> sys.muscle.L_OPT # To get the muscle optimal length
    stimulations = np.arange(.0, 1.0, .02)
    stretches = np.arange(.12, .36, .05)  #default length is 0.24

    allStretches = []
    allStims = []
    allActForces = []
    allPassForces = []
    allNetForces = []

    for stretch in stretches:
        # Evalute for a single muscle stretch
        muscle_active_forces = []
        muscle_passive_forces = []
        total_force = []
        l_ce = []
        for stimulation in stimulations:

            # Evalute for a single muscle stimulation
            muscle_stimulation = stimulation

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

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

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

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

            muscle_active_forces.append(result.active_force[-1])
            muscle_passive_forces.append(result.passive_force[-1])
            total_force.append(result.active_force[-1] +
                               result.passive_force[-1])
            l_ce.append(result.l_ce[-1])
            allStretches.append(stretch)
            allStims.append(stimulation)
            allActForces.append(result.active_force[-1])
            allPassForces.append(result.passive_force[-1])
            allNetForces.append(total_force[-1])

#            # Plotting results of individual trials to verify steady state assumption
#            plt.figure('Force over time with different stimulations and lengths %.2f' %stretch)
#            plt.plot(time, result.active_force, label='Active: Stim = %.2f'%stimulation + ' L = %.2f'%stretch)
#            plt.plot(time, result.passive_force, label='Passive: Stim = %.2f'%stimulation + ' L = %.2f'%stretch)
#            plt.plot(time, result.active_force+result.passive_force, label='Net: Stim = %.2f'%stimulation + ' L = %.2f'%stretch)
#            plt.title('Force over time with different stimulations and lengths')
#            plt.xlabel('Time [s]')
#            plt.ylabel('Active Muscle Force [N]')
#            plt.legend(loc='upper right')
#            plt.grid()

# Plotting
        plt.figure('Isometric Muscle: Stimulation vs Force')
        plt.subplot(3, 1, 1)
        plt.plot(stimulations,
                 muscle_active_forces,
                 label='L_mtu = %.2f' % stretch)
        plt.title('Isometric Muscle: Stimulation vs Force')
        plt.xlabel('Stimulation')
        plt.ylabel('Active Force [N]')
        plt.legend(loc='upper right')
        plt.grid()
        plt.subplot(3, 1, 2)
        plt.plot(stimulations,
                 muscle_passive_forces,
                 label='L_mtu = %.2f' % stretch)
        plt.xlabel('Stimulation')
        plt.ylabel('Passive Force [N]')
        plt.legend(loc='upper right')
        plt.grid()

        plt.subplot(3, 1, 3)
        plt.plot(stimulations, total_force, label='L_mtu = %.2f' % stretch)
        plt.xlabel('Stimulation')
        plt.ylabel('Total Force [N]')
        plt.legend(loc='upper right')
        plt.grid()

    allActForces = np.array(allActForces).reshape(
        (stretches.size, stimulations.size))
    allPassForces = np.array(allPassForces).reshape(
        (stretches.size, stimulations.size))
    allNetForces = np.array(allNetForces).reshape(
        (stretches.size, stimulations.size))
    stimulations, stretches = np.meshgrid(stimulations, stretches)

    fig1b = plt.figure('1b. Stim vs Active Force Surface Plot')
    ax = fig1b.gca(projection='3d')
    ax = fig1b.add_subplot(111, projection='3d')
    ax.plot_surface(stimulations,
                    stretches,
                    allActForces,
                    cmap=cm.coolwarm,
                    linewidth=0.5,
                    antialiased=False)
    ax.set_xlabel('Stimulation')
    ax.set_ylabel('Muscle Length (m)')
    ax.set_zlabel('Active Force (N)')
    plt.title('Stimulation vs Active Force')

    fig1b = plt.figure('1b. Stim vs Passive Force Surface Plot')
    ax = fig1b.gca(projection='3d')
    ax = fig1b.add_subplot(111, projection='3d')
    ax.plot_surface(stimulations,
                    stretches,
                    allPassForces,
                    cmap=cm.coolwarm,
                    linewidth=0.5,
                    antialiased=False)
    ax.set_xlabel('Stimulation')
    ax.set_ylabel('Muscle Length (m)')
    ax.set_zlabel('Passive Force (N)')
    plt.title('Stimulation vs Passive Force')

    fig1b = plt.figure('1b. Stim vs Total Force Surface Plot')
    ax = fig1b.gca(projection='3d')
    ax = fig1b.add_subplot(111, projection='3d')
    ax.plot_surface(stimulations,
                    stretches,
                    allNetForces,
                    cmap=cm.coolwarm,
                    linewidth=0.5,
                    antialiased=False)
    ax.set_xlabel('Stimulation')
    ax.set_ylabel('Muscle Length (m)')
    ax.set_zlabel('Net Force (N)')
    plt.title('Stimulation vs Total Force')