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 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.25 # 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) plt.title('Isometric muscle experiment') plt.xlabel('Time [s]') plt.ylabel('Tendon Force') plt.grid() ########################################################################" muscle_stretch_listA = range(5, 20) muscle_stretch_list = np.array(muscle_stretch_listA) muscle_stretch_list = muscle_stretch_list / 50 active_forces = [] passive_forces = [] tendon_forces = [] # Run the integration for muscle_stretch in muscle_stretch_list: result = sys.integrate(x0=x0, time=time, time_step=time_step, stimulation=muscle_stimulation, muscle_length=muscle_stretch) active_forces.append(result.active_force[-1]) passive_forces.append(result.passive_force[-1]) tendon_forces.append(result.tendon_force[-1]) # Plotting plt.figure('Isometric muscle experiment, varying length') plt.plot(muscle_stretch_list, active_forces) plt.plot(muscle_stretch_list, passive_forces) plt.plot(muscle_stretch_list, tendon_forces) plt.title('Isometric muscle experiment, varying length') plt.xlabel('Muscle stretch') plt.ylabel('Active, passive and total tendon forces') plt.legend(['active forces', 'passive forces', 'total forces']) plt.grid() stimulation_listA = range(0, 11) stimulation_list = np.array(stimulation_listA) stimulation_list = stimulation_list / 10 plt.figure('Isometric muscle experiment, varying stimulation and length') plt.title('Isometric muscle experiment, varying stimulation and length') plt.xlabel('Muscle stretch') plt.ylabel('Total force') legend = [] for stimul in stimulation_list: tendon_forces = [] for muscle_stretch in muscle_stretch_list: result = sys.integrate(x0=x0, time=time, time_step=time_step, stimulation=stimul, muscle_length=muscle_stretch) tendon_forces.append(result.tendon_force[-1]) plt.plot(muscle_stretch_list, tendon_forces) legend.append('Stimulation of ' + str(stimul)) plt.legend(legend)
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.sin(theta)) temp_h2 = (temp_a1 * temp_a2 * np.cos(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.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 * 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() ''' # 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)
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 = 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())) ########## ADD SYSTEMS ########## # Create system of Pendulum, Muscles and neural network using SystemClass # Check System.py for more details on System class sys = System() # Instantiate a new system sys.add_pendulum_system(pendulum) # Add the pendulum model to the system sys.add_muscle_system(muscles) # Add the muscle model to the system # Add the neural network to the system sys.add_neural_system(neural_network) ##### Time ##### t_max = 2.5 # Maximum simulation time time = np.arange(0., t_max, 0.001) # Time vector ##### Model Initial Conditions ##### x0_P = np.asarray([np.pi / 2, 0.]) # Pendulum initial condition # Muscle Model initial condition l_ce_0 = sys.muscle_sys.initialize_muscle_length(np.pi / 2) x0_M = np.asarray([0.05, l_ce_0[0], 0.05, l_ce_0[1]]) x0_N = np.asarray([-0.5, 1, 0.5, 1]) # Neural Network Initial Conditions x0 = np.concatenate((x0_P, x0_M, x0_N)) # System initial conditions ##### System Simulation ##### # For more details on System Simulation check SystemSimulation.py # SystemSimulation is used to initialize the system and integrate # over time sim = SystemSimulation(sys) # Instantiate Simulation object sim.initalize_system(x0, time) # Initialize the system state return sim
def 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) ####custom code##### fiber_length = np.arange(0.01, 0.11, 0.01) my_velocity = [] plt.figure('Isotonic muscle experiment') for lopt in fiber_length: # Run the integration sys.muscle.L_OPT = lopt result = sys.integrate(x0=x0, time=time, time_step=time_step, stimulation=muscle_stimulation, muscle_length=muscle_stretch) plt.figure('Isometric muscle experiment') plt.plot(result.time, result.tendon_force, label='fiber length: %.2f' % lopt) plt.title('Isometric muscle experiment') plt.xlabel('Time [s]') plt.ylabel('Muscle Force') plt.legend() # 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) plt.title('Isometric muscle experiment') plt.xlabel('Time [s]') plt.ylabel('Muscle Force') plt.grid()
def exercise1a(): """ Exercise 1a """ # 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) # Force-length curves # Evalute for various muscle stretch stretch_min = muscle.L_OPT stretch_max = muscle.L_OPT * 3 N_stretch = 100 muscle_stretch = np.arange(stretch_min, stretch_max, (stretch_max - stretch_min) / N_stretch) # 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) activeF = np.zeros(N_stretch) passiveF = np.zeros(N_stretch) tendonF = np.zeros(N_stretch) lceF = np.zeros(N_stretch) for index_strech, stretch in enumerate(muscle_stretch): # Run the integration result = sys.integrate(x0=x0, time=time, time_step=time_step, stimulation=1.0, muscle_length=stretch) activeF[index_strech] = result.active_force[-1] passiveF[index_strech] = result.passive_force[-1] tendonF[index_strech] = result.tendon_force[-1] lceF[index_strech] = result.l_ce[-1] # Plotting plt.figure('Isometric Muscle Experiment 1a') plt.plot(lceF * 100 / muscle.L_OPT, activeF * 100 / muscle.F_MAX, label='Active Force') plt.plot(lceF * 100 / muscle.L_OPT, passiveF * 100 / muscle.F_MAX, label='Passive Force') plt.plot(lceF * 100 / muscle.L_OPT, tendonF * 100 / muscle.F_MAX, label=' Tendon Force') plt.axvline(100, linewidth=1, linestyle='--', color='r') plt.axvline(145, linewidth=1, linestyle='--', color='r') plt.xlabel('Contractile element length [% of $L_{opt}$]') plt.ylabel('Force [% of $F_{max}$]') plt.title( 'Force-length curves for isometric muscle experiment (Stimulation = 1.0)' ) plt.legend() plt.grid()
def exercise1f(): """ Exercise 1f """ # 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) # 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) # Velocity-tension curve # Evalute for various loads load_min = 1 load_max = 501 N_load = 50 load_list = np.arange(load_min, load_max, (load_max - load_min) / N_load) # Evalute for various muscle stimulation N_stim = 4 muscle_stimulation = np.round(np.arange(N_stim) / (N_stim - 1), 2) # Set the initial condition x0 = [0.0, sys.muscle.L_OPT, sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0] # 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) max_velocity = np.zeros((N_stim, N_load)) tendonF = np.zeros((N_stim, N_load)) for i, stim in enumerate(muscle_stimulation): for ind_load, load in enumerate(load_list): # 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)): max_velocity[i, ind_load] = np.max(-result.v_ce) else: max_velocity[i, ind_load] = np.min(-result.v_ce) tendonF[i, ind_load] = result.tendon_force[-1] # Plotting plt.figure('Isotonic Muscle Experiment 1f') v_min = np.amin(max_velocity) v_max = np.amax(max_velocity) for i, stim in enumerate(muscle_stimulation): plt.plot(max_velocity[i, :] * 100 / -muscle.V_MAX, tendonF[i, :] * 100 / muscle.F_MAX, label='Tendon Force - Stimulation = {}'.format(stim)) plt.xlim(v_min * 100 / -muscle.V_MAX, v_max * 100 / -muscle.V_MAX) plt.ylim(0, 200) plt.axvline(linestyle='--', color='r', linewidth=2) plt.text(v_min * 100 / -muscle.V_MAX * 2 / 3, 170, r'lengthening', fontsize=16) plt.text(v_max * 100 / -muscle.V_MAX * 1 / 8, 170, r'shortening', fontsize=16) plt.xlabel('Maximal velocity [% of $V_{max}$]') plt.ylabel('Tendon Force [% of $F_{max}$]') plt.title( 'Velocity-tension curves for isotonic muscle experiment with various muscle stimulations' ) plt.legend() plt.grid()
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) load = np.linspace(100/9.81,1700/9.81,50) Stimu = np.linspace(0,1,6) Vce = np.zeros((len(load),len(Stimu))) plt.figure('Isotonix Globale') for j in range(len(Stimu)): # Vce = np.empty(len(load)) # Vcemax = np.empty(len(load)) # Vcemin = np.empty(len(load)) for i in range(len(load)): # Run the integration result = sys.integrate(x0=x0, time=time, time_step=time_step, time_stabilize=time_stabilize, stimulation=Stimu[j], load=load[i] ) print(result.l_mtu[-1]) print(sys.muscle.l_opt + sys.muscle.l_slack) if (result.l_mtu[-1] > sys.muscle.l_opt + sys.muscle.l_slack): Vce[i,j]=(max(result.v_ce)) else: Vce[i,j] = min(result.v_ce) Vce[:,j] plt.plot(Vce[:,j],load, label ="MS %s" %round(Stimu[j],1)) plt.legend(loc = "upper left") plt.xlabel('Vitesse max [m/s]') plt.ylabel('Load [kg]') # Plotting plt.figure('Isotonic muscle experiment') #plt.plot(result.time, # result.v_ce) plt.plot(Vce,load) plt.title('Isotonic muscle experiment') plt.xlabel('Vitesse max [m/s]') plt.ylabel('Load [kg]') #plt.xlabel('Time [s]') #plt.ylabel('Muscle contracticle velocity [lopts/s]') plt.grid() #MUSCLE-Force Velocity relationship : plt.figure('Muscle Force-Velocity') plt.plot(result.v_ce,result.active_force, label ="Active Force") plt.plot(result.v_ce,result.active_force+result.passive_force, label = "Passive + Active") plt.plot(result.v_ce,result.passive_force, label = "Passive Force") plt.legend(loc = "upper left") plt.xlabel('Vitesse m') plt.ylabel('Force')
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.35 # Evalute for a single muscle stimulation muscle_stimulation = 1. sys.muscle.l_opt=0.15 # Set the initial condition x0 = [0.0, sys.muscle.l_opt] # x0[0] --> muscle stimulation intial value # x0[1] --> muscle contracticle length initial value print(x0) # 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.l_ce/sys.muscle.l_opt, result.active_force, label = "Active Force") plt.plot(result.l_ce/sys.muscle.l_opt, result.passive_force, label = "Passive Force") plt.plot(result.l_ce/sys.muscle.l_opt, result.passive_force + result.active_force, label = "Total Force") plt.legend(loc="upper left") plt.title('Isometric muscle experiment') plt.xlabel('length') plt.ylabel('Force [N]') plt.grid() plt.show plt.figure('Isometric Muscle experiment 2') stim = np.linspace(0,1,11) print(stim) for i in range(10): muscle_stimulation = stim[i] j = 0.1*i j = round(j,1) # Run the integration result = sys.integrate(x0=x0, time=time, time_step=time_step, stimulation=muscle_stimulation, muscle_length=muscle_stretch) plt.plot(result.l_ce,result.active_force, label ="MS %s" %j) a plt.xlabel('length') plt.ylabel('Force [N]') 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) # Evalute for a single muscle stimulation muscle_stimulation = 1. #sys.muscle.L_OPT=0.05 # 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.25 time_step = 0.001 time_stabilize = 0.2 time = np.arange(t_start, t_stop, time_step) # You can still access the muscle inside the system by doing # >>> sys.muscle.L_OPT # To get the muscle optimal # Create a V_ce vector V_ce_1d = np.zeros(100) PF_ce_1d = np.zeros(100) AF_ce_1d = np.zeros(100) # Create load vector Load = np.linspace(1, 600, num=100) """1.d) velocity-tension analysis """ for i in range(0, len(Load)): # Set the initial condition x0 = [ muscle_stimulation, sys.muscle.L_OPT, sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0 ] # Evalute for a single load load = Load[i] # Run the integration result = sys.integrate(x0=x0, time=time, time_step=time_step, time_stabilize=time_stabilize, stimulation=muscle_stimulation, load=load) #print(sys.muscle.L_OPT+sys.muscle.L_SLACK) #print(result.l_mtc[-1]-(sys.muscle.L_OPT+sys.muscle.L_SLACK)) if (result.l_mtc[-1] < sys.muscle.L_OPT + sys.muscle.L_SLACK): V_ce_1d[i] = min(result.v_ce) else: V_ce_1d[i] = max(result.v_ce) PF_ce_1d[i] = result.passive_force[-1] AF_ce_1d[i] = result.active_force[-1] # Plotting plt.figure('Isotonic muscle experiment') plt.plot(result.time, result.v_ce) plt.title('Isotonic muscle experiment') plt.xlabel('Time [s]') plt.ylabel('Contractile element velocity') plt.grid() # Plot velocity versus tension plt.figure() plt.plot(V_ce_1d, Load) plt.title('Isotonic muscle experiment') plt.xlabel('Contractile element velocity') plt.ylabel('Load') plt.grid() plt.axvline(0, color='r', linestyle='--') # Plot velocity versus tension plt.figure() plt.plot(V_ce_1d, PF_ce_1d + AF_ce_1d) #plt.plot(V_ce_1d, PF_ce_1d) #plt.plot(V_ce_1d, AF_ce_1d, '--') plt.title('Isotonic muscle experiment') plt.xlabel('Contractile element velocity') plt.ylabel('Total Force') plt.grid() #plt.legend(['total','passive', 'active']) plt.axvline(0, color='r', linestyle='--') """ 1.f) velocity-tension as a function of muscle activation """ # Create solution vector #R_glob=np.zeros((5,50)) # Create muscle activation vector dS = np.linspace(0.1, 1, num=5) # Create a V_ce vector V_ce = np.zeros((5, 100)) PF_ce = np.zeros((5, 100)) AF_ce = np.zeros((5, 100)) for i in range(0, len(Load)): for j in range(0, len(dS)): # Evalute for a single load load = Load[i] # Evalute for a single muscle stimulation muscle_stimulation = dS[j] # Set the initial condition x0 = [ muscle_stimulation, sys.muscle.L_OPT, sys.muscle.L_OPT + sys.muscle.L_SLACK, 0.0 ] # Run the integration result = sys.integrate(x0=x0, time=time, time_step=time_step, time_stabilize=time_stabilize, stimulation=muscle_stimulation, load=load) #R_glob[j,i]=result.tendon_force[len(result.tendon_force)-1] #print(sys.muscle.L_OPT+sys.muscle.L_SLACK) #print(result.l_mtc[-1]-(sys.muscle.L_OPT+sys.muscle.L_SLACK)) if (result.l_mtc[-1] < sys.muscle.L_OPT + sys.muscle.L_SLACK): V_ce[j, i] = min(result.v_ce) else: V_ce[j, i] = max(result.v_ce) PF_ce[j, i] = result.passive_force[-1] AF_ce[j, i] = result.active_force[-1] # # Plotting # plt.figure('Isotonic muscle experiment') # plt.plot(result.time, result.v_ce) # plt.title('Isotonic muscle experiment') # plt.xlabel('Time [s]') # plt.ylabel('Contractile element velocity') # plt.grid() # Plot velocity versus tension plt.figure() for i in range(0, 5): plt.plot(V_ce[i, :], PF_ce[i, :] + AF_ce[i, :]) plt.title('Isotonic muscle experiment') plt.xlabel('Contractile element velocity') plt.ylabel('Force') plt.grid() plt.legend([ 'Stimulation = 0.1', 'Stimulation = 0.28', 'Stimulation = 0.46', 'Stimulation = 0.64', 'Stimulation = 0.82', 'Stimulation = 1' ])
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()) # Create muscle object muscle = Muscle(parameters) # Instatiate isometric muscle system sys = IsometricMuscleSystem() # Add the muscle to the system sys.add_muscle(muscle) # Evalute for a single muscle stimulation muscle_stimulation = 0.5 # Create time vector t_start = 0.0 t_stop = 0.3 time_step = 0.001 time = np.arange(t_start, t_stop, time_step) # Set the initial condition x0 = [0.0, sys.muscle.L_OPT] # Create stretch coefficient vector dL = np.linspace(-0.5, 0.5, num=50) len_ce = np.zeros(dL.size) # Create a steady state muscle force vector R_glob_1a = np.zeros((50)) R_pass_1a = np.zeros((50)) R_activ_1a = np.zeros((50)) """ 1.a) Effect of stretching coefficient on the muscle force """ for i in range(0, len(dL)): # Evalute for a single muscle stretch muscle_stretch = (sys.muscle.L_OPT + sys.muscle.L_SLACK) * (1 + dL[i]) # Run the integration result = sys.integrate(x0=x0, time=time, time_step=time_step, stimulation=muscle_stimulation, muscle_length=muscle_stretch) R_glob_1a[i] = result.tendon_force[-1] R_pass_1a[i] = result.passive_force[-1] R_activ_1a[i] = result.active_force[-1] len_ce[i] = result.l_ce[-1] # # Plot Isometric muscle experiment # plt.figure('Isometric muscle experiment') # plt.plot(result.time, result.tendon_force) # plt.title('Isometric muscle experiment') # plt.xlabel('Time [s]') # plt.ylabel('Muscle force') # Plot force-length curve plt.figure('Forces as a function of stretching coefficient') # Passive Force plt.plot(dL, R_pass_1a) # Active Force plt.plot(dL, R_activ_1a) # Total force plt.plot(dL, R_glob_1a) plt.xlabel('Stretch coeffcient [%]') plt.ylabel('Muscle force [N]') plt.legend(['Passive Force', 'Active Force', 'Total Force']) plt.ylim([0, 4000]) plt.xlim([-0.4, 0.4]) plt.figure('Forces as a function of the contractile element length') # Passive Force plt.plot(len_ce, R_pass_1a) # Active Force plt.plot(len_ce, R_activ_1a) # Total force plt.plot(len_ce, R_glob_1a) plt.ylim([0, 4000]) plt.xlim([0.06, 0.18]) plt.xlabel('Contractile element Lenght [m]') plt.ylabel('Muscle force [N]') plt.legend(['Passive Force', 'Active Force', 'Total Force']) #plt.savefig('Forces_stretch_coeff') """1.b) Effect of muscle stimulation [-1,0] on muscle force as a function of stretch coefficient""" # Create a steady state muscle force vector R_glob_1b = np.zeros((5, 50)) R_pass_1b = np.zeros((5, 50)) R_act_1b = np.zeros((5, 50)) # Create muscle activation vector dS = np.linspace(0, 1, num=5) for i in range(0, len(dL)): for j in range(0, len(dS)): # Evalute for a single muscle stimulation muscle_stimulation = dS[j] # Evalute for a single muscle stretch muscle_stretch = (sys.muscle.L_OPT + sys.muscle.L_SLACK) * (1 + dL[i]) # Run the integration result = sys.integrate(x0=x0, time=time, time_step=time_step, stimulation=muscle_stimulation, muscle_length=muscle_stretch) R_glob_1b[j, i] = result.tendon_force[-1] R_pass_1b[j, i] = result.passive_force[-1] R_act_1b[j, i] = result.active_force[-1] # Plot force-length curve for different muscle activation plt.figure('Forces as a function of dL for different muscle stimulation') plt.plot(dL, R_glob_1b[0, :]) plt.plot(dL, R_glob_1b[1, :]) plt.plot(dL, R_glob_1b[2, :]) plt.plot(dL, R_glob_1b[3, :]) plt.plot(dL, R_glob_1b[4, :]) plt.xlabel('Stretch coeffcient [%]') plt.ylabel('Muscle force [N]') plt.legend([ 'Stimulation = 0', 'Stimulation = 0.25', 'Stimulation = 0.5', 'Stimulation = 0.75', 'Stimulation = 1' ]) plt.title('Total forces') plt.ylim([0, 4000]) plt.figure( 'Active forces as a function of dL for different muscle stimulation') plt.plot(dL, R_act_1b[0, :]) plt.plot(dL, R_act_1b[1, :]) plt.plot(dL, R_act_1b[2, :]) plt.plot(dL, R_act_1b[3, :]) plt.plot(dL, R_act_1b[4, :]) plt.xlabel('Stretch coeffcient [%]') plt.ylabel('Muscle force [N]') plt.legend([ 'Stimulation = 0', 'Stimulation = 0.25', 'Stimulation = 0.5', 'Stimulation = 0.75', 'Stimulation = 1' ]) plt.title('Active forces') plt.figure( 'Passive forces as a function of dL for different muscle stimulation') plt.plot(dL, R_pass_1b[0, :]) plt.plot(dL, R_pass_1b[1, :]) plt.plot(dL, R_pass_1b[2, :]) plt.plot(dL, R_pass_1b[3, :]) plt.plot(dL, R_pass_1b[4, :]) plt.xlabel('Stretch coeffcient [%]') plt.ylabel('Muscle force [N]') plt.legend([ 'Stimulation = 0', 'Stimulation = 0.25', 'Stimulation = 0.5', 'Stimulation = 0.75', 'Stimulation = 1' ]) plt.title('Passive forces') """ 1.c) Effect of fiber length on force-length curve """ # Evalute for a single muscle stimulation muscle_stimulation = 0.5 # Create fiber length vector #dl=np.linspace(0.1,1,num=10) dl = [0.07, 0.11, 0.15] # Create a steady state muscle force vectors R_glob_1c = np.zeros((len(dl), len(dL))) # Create active force vectors R_act_1c = np.zeros((len(dl), len(dL))) # Create passive force vectors R_pas_1c = np.zeros((len(dl), len(dL))) # Create contractile element length vectors len_ce = np.zeros((len(dl), len(dL))) for i in range(0, len(dL)): for j in range(0, len(dl)): # Change the fiber length sys.muscle.L_OPT = dl[j] # Evalute for a single muscle stretch muscle_stretch = (sys.muscle.L_OPT + sys.muscle.L_SLACK) * (1 + dL[i]) # Run the integration result = sys.integrate(x0=x0, time=time, time_step=time_step, stimulation=muscle_stimulation, muscle_length=muscle_stretch) R_glob_1c[j, i] = result.tendon_force[-1] R_act_1c[j, i] = result.active_force[-1] R_pas_1c[j, i] = result.passive_force[-1] len_ce[j, i] = result.l_ce[-1] plt.figure('Forces as a function of dL for different fiber lengths') for i in range(0, len(dl)): plt.plot(dL, R_glob_1c[i, :]) plt.xlabel('Strecth coeffcient') plt.ylabel('Muscle force') plt.legend(['Opt_len: 0.07', 'Opt_len: 0.11', 'Opt_len : 0.15']) plt.figure('Forces wrt CE length for different optimal lengths') for i in range(0, len(dl)): plt.plot(len_ce[i, :], R_glob_1c[i, :]) plt.legend(['Opt_len: 0.07', 'Opt_len: 0.11', 'Opt_len : 0.15']) for i in range(0, len(dl)): plt.axvline(dl[i], color='r', linestyle='--') mvs = np.max(R_act_1c, axis=1) mv = np.unique(np.round(mvs)) plt.axhline(mv, color='black', linestyle='--') plt.ylim([0, 3000]) plt.xlabel('Contractile elememnt length [m]') plt.ylabel('Muscle force [n]') plt.figure('Active forces') for i in range(0, len(dl)): plt.plot(len_ce[i, :], R_act_1c[i, :]) plt.xlabel('Contractile elememnt length [m]') plt.ylabel('Muscle force [n]') plt.legend(['Opt_len: 0.07', 'Opt_len: 0.11', 'Opt_len : 0.15']) plt.figure('Passive forces') for i in range(0, len(dl)): plt.plot(len_ce[i, :], R_pas_1c[i, :]) plt.xlabel('Contractile elememnt length [m]') plt.ylabel('Muscle force [n]') plt.legend(['Opt_len: 0.07', 'Opt_len: 0.11', 'Opt_len : 0.15'])
else: exercises = Exercise.all # then filter by person if who != None: exercises = who.acceptable_exercises(exercises) # finally, filter by muscle group yes = [] for group in what: yes += group.musclegroup_exercises(exercises) # start creating workout!!! workout = Exercise.populate_workout(how_long, exercises) # getting output... return Exercise.gimme_gains(workout) upperabs = Muscle("Upper Abs") lowerabs = Muscle("Lower Abs") obliques = Muscle("Obliques") shoulders = Muscle("Shoulders") glutes = Muscle("Glutes") thighs = Muscle("Thighs") biceps = Muscle("Biceps") triceps = Muscle("Triceps") chest = Muscle("Chest") crunches = Exercise('Crunches x20', [upperabs], 1) # legraise = Exercise('Leg Raises x15', [lowerabs], 2) # plank = Exercise('Plank: 90sec', [upperabs, lowerabs, shoulders], 2) # sideplank = Exercise('Side Planks: 45sec/side', [upperabs, lowerabs, obliques, shoulders], 2) # bikecrunch = Exercise('Bicycle Crunches x40', [upperabs, obliques], 1) #
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 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.08 #medium_opt=0.1 long_opt = 0.10 opt_range = [short_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) active_forces = [] passive_forces = [] total_forces = [] element_lengths = [] 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] active_forces = active_forces + [temp_active_forces] passive_forces = passive_forces + [temp_passive_forces] total_forces = total_forces + [temp_total_forces] element_lengths = element_lengths + [temp_element_lengths] plt.figure( "1c. Isometric muscle experiment with different musle fiber lengths") for i in range(2): plt.plot(element_lengths[i], active_forces[i]) plt.plot(element_lengths[i], passive_forces[i]) plt.plot(element_lengths[i], total_forces[i]) plt.xlabel('Muscle contracticle length [m]') plt.ylabel('Tension [N]') plt.title("Isometric muscle experiment with different musle fiber lengths") plt.legend([ "Active Force: musle fiber lengths=0.08", "Passive Force musle: fiber lengths=0.08", "Total Force: musle fiber lengths=0.08", "Active Force: musle fiber lengths=0.10", "Passive Force musle: fiber lengths=0.10", "Total Force: musle fiber lengths=0.10" ]) plt.grid() plt.show()
def exercise1b(): """ Exercise 1b """ # 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) # Force-length curves # Evalute for various muscle stretch stretch_min = muscle.L_OPT * 0.5 stretch_max = muscle.L_OPT * 2.8 N_stretch = 40 muscle_stretch = np.arange(stretch_min, stretch_max, (stretch_max - stretch_min) / N_stretch) # Evaluate for various muscle stimulation N_stim = 6 muscle_stimulation = np.round(np.arange(N_stim) / (N_stim - 1), 2) # Set the initial condition x0 = [0.0, sys.muscle.L_OPT] # 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) activeF = np.zeros(N_stretch) passiveF = np.zeros(N_stretch) tendonF = np.zeros(N_stretch) lceF = np.zeros(N_stretch) # Plotting plt.figure('Isometric Muscle Experiment 1b') colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k'] for stim in range(len(muscle_stimulation)): pylog.info('Stimulation = {}'.format(stim)) activeF = np.zeros(N_stretch) tendonF = np.zeros(N_stretch) for stretch in range(len(muscle_stretch)): # Run the integration result = sys.integrate(x0=x0, time=time, time_step=time_step, stimulation=muscle_stimulation[stim], muscle_length=muscle_stretch[stretch]) activeF[stretch] = result.active_force[-1] if (stim == 0): passiveF[stretch] = result.passive_force[-1] tendonF[stretch] = result.tendon_force[-1] lceF[stretch] = result.l_ce[-1] color = colors[stim] plt.plot(lceF * 100 / muscle.L_OPT, 100 * activeF / muscle.F_MAX, color, label='Active Force - Stimulation = ' + str(round(muscle_stimulation[stim], 2))) plt.plot(lceF * 100 / muscle.L_OPT, 100 * passiveF / muscle.F_MAX, '+' + 'k', label='Passive Force') plt.title( 'Force-length curves for isometric muscle experiment with various muscle stimulations' ) plt.xlabel('Contractile element length [% of $L_{opt}$]') plt.ylabel('Force [% of $F_{max}$]') plt.legend() plt.grid()
import cmc_pylog as pylog from muscle import Muscle from mass import Mass from cmcpack import DEFAULT, parse_args from cmcpack.plot import save_figure from system_parameters import MuscleParameters, MassParameters from isometric_muscle_system import IsometricMuscleSystem from isotonic_muscle_system import IsotonicMuscleSystem 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) stretch_min = muscle.L_OPT stretch_max = muscle.L_OPT * 3 N_stretch = 40 muscle_stretch = np.arange(stretch_min, stretch_max, (stretch_max - stretch_min) / N_stretch) # Set the initial condition x0 = [0.0, sys.muscle.L_OPT]
def exercise1c(): """ Exercice 1c """ # 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) # Force-length curves # Set the initial condition x0 = [0.0, sys.muscle.L_OPT] # 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) N_stretch = 40 activeF = np.zeros(N_stretch) passiveF = np.zeros(N_stretch) tendonF = np.zeros(N_stretch) lceF = np.zeros(N_stretch) # Evaluate for various optimal length l_opt_list = np.array([0.1, 0.3]) # Subplots grid n_plot = len(l_opt_list) n_subplot = int((np.sqrt(n_plot - 1)) + 1) if (n_plot <= n_subplot * (n_subplot - 1)): fig, axes = plt.subplots(n_subplot, n_subplot - 1) n_subplot2 = n_subplot - 1 else: fig, axes = plt.subplots(n_subplot, n_subplot) n_subplot2 = n_subplot for i, l_opt in enumerate(l_opt_list): # Evaluate for various muscle stretch muscle.L_OPT = l_opt stretch_min = muscle.L_OPT stretch_max = muscle.L_OPT * 3 muscle_stretch = np.arange(stretch_min, stretch_max, (stretch_max - stretch_min) / N_stretch) for stretch in range(len(muscle_stretch)): # Run the integration result = sys.integrate(x0=x0, time=time, time_step=time_step, stimulation=1., muscle_length=muscle_stretch[stretch]) activeF[stretch] = result.active_force[-1] passiveF[stretch] = result.passive_force[-1] tendonF[stretch] = result.tendon_force[-1] lceF[stretch] = result.l_ce[-1] plt.subplot(n_subplot, n_subplot2, i + 1) plt.plot(lceF, 100 * activeF / muscle.F_MAX, label='Active Force') plt.plot(lceF, 100 * passiveF / muscle.F_MAX, label='Passive Force') plt.plot(lceF, 100 * tendonF / muscle.F_MAX, label='Tendon Force') plt.axvline(l_opt, linestyle="--", color="r") plt.xlim([l_opt - 0.3, l_opt + 0.3]) plt.ylim([0, 120]) plt.xlabel('Contractile element length') plt.ylabel('Force [% of $F_{max}$]') plt.title('Optimal length = {} [m]'.format(l_opt)) plt.legend() plt.grid() plt.suptitle( 'Force-length curves for isometric muscle experiment with various muscle optimal lengths' ) fig.tight_layout()
def exercise2(): """ Main function to run for Exercise 2. Parameters ---------- None Returns ------- None """ #----------------# Exercise 2a #----------------# theta = np.linspace(-np.pi/4, np.pi/4,num=50) h1=[] a1= 1 a2a1=np.linspace(0.5,2,num=4) plt.figure('2a_Muscle_Length_vs_Theta') plt.title('Muscle Length vs Theta') plt.xlabel('Position [rad]') plt.ylabel('Muscle length [m]') plt.grid() plt.figure('2a_Moment_arm_vs_Theta') plt.title('Moment arm vs Theta') plt.xlabel('Position [rad]') plt.ylabel('Moment arm [m]') plt.grid() for i in range(0,len(a2a1)): a2=a2a1[i]*a1 L1=(np.sqrt(a1**2+a2**2+2*a1*a2*np.sin(theta))) h1=((a1*a2*np.cos(theta))/L1) plt.figure('2a_Muscle_Length_vs_Theta') plt.plot(theta,L1,label=('a2/a1 = %.1f' %(a2a1[i]))) plt.figure('2a_Moment_arm_vs_Theta') plt.plot(theta,h1,label=('a2/a1= %.1f' %(a2a1[i]))) plt.figure('2a_Muscle_Length_vs_Theta') plt.legend() plt.figure('2a_Moment_arm_vs_Theta') plt.legend() #----------------# Exercise 2a finished #----------------# # Define and Setup your pendulum model here # Check PendulumSystem.py for more details on Pendulum class pendulum_params = PendulumParameters() # Instantiate pendulum parameters pendulum_params.L = 0.5 # To change the default length of the pendulum pendulum_params.m = 1. # To change the default mass of the pendulum pendulum = PendulumSystem(pendulum_params) # Instantiate Pendulum object #### CHECK OUT PendulumSystem.py to ADD PERTURBATIONS TO THE MODEL ##### pylog.info('Pendulum model initialized \n {}'.format( pendulum.parameters.showParameters())) # Define and Setup your pendulum model here # Check MuscleSytem.py for more details on MuscleSytem class M1_param = MuscleParameters() # Instantiate Muscle 1 parameters M1_param.f_max = 1500 # To change Muscle 1 max force M2_param = MuscleParameters() # Instantiate Muscle 2 parameters M2_param.f_max = 1500 # To change Muscle 2 max force M1 = Muscle(M1_param) # Instantiate Muscle 1 object M2 = Muscle(M2_param) # Instantiate Muscle 2 object # Use the MuscleSystem Class to define your muscles in the system muscles = MuscleSytem(M1, M2) # Instantiate Muscle System with two muscles pylog.info('Muscle system initialized \n {} \n {}'.format( M1.parameters.showParameters(), M2.parameters.showParameters())) # Define Muscle Attachment points m1_origin = np.array([-0.17, 0.0]) # Origin of Muscle 1 m1_insertion = np.array([0.0, -0.17]) # Insertion of Muscle 1 m2_origin = np.array([0.17, 0.0]) # Origin of Muscle 2 m2_insertion = np.array([0.0, -0.17]) # Insertion of Muscle 2 # Attach the muscles muscles.attach(np.array([m1_origin, m1_insertion]), np.array([m2_origin, m2_insertion])) # Create a system with Pendulum and Muscles using the System Class # Check System.py for more details on System class sys = System() # Instantiate a new system sys.add_pendulum_system(pendulum) # Add the pendulum model to the system sys.add_muscle_system(muscles) # Add the muscle model to the system ##### Time ##### t_max = 5 # Maximum simulation time time = np.arange(0., t_max, 0.001) # Time vector ##### Model Initial Conditions ##### x0_P = np.array([np.pi/4, 0.]) # Pendulum initial condition # Muscle Model initial condition x0_M = np.array([0., M1.L_OPT, 0., M2.L_OPT]) x0 = np.concatenate((x0_P, x0_M)) # System initial conditions ##### System Simulation ##### # For more details on System Simulation check SystemSimulation.py # SystemSimulation is used to initialize the system and integrate # over time sim = SystemSimulation(sys) # Instantiate Simulation object # Add muscle activations to the simulation # Here you can define your muscle activation vectors # that are time dependent activationFunction = ['sin','square'] for idx, act in enumerate(activationFunction): #----------------# Exercise 2c #----------------# w = np.linspace(0.2,4,4) # w = 0.5 # a = np.linspace(0.1,1,4) plt.figure('2c_LimitCycle_'+str(act)) # plt.figure('2c_LimitCycle_Amplitude_'+str(act)) plt.title('Pendulum Phase') plt.figure('2c_Amplitude_'+str(act)) # plt.figure('2c_Amplitude_Amplitude_'+str(act)) plt.title('Amplitude vs. Frequency') # plt.title('Amplitude vs. Stimulation Amplitude') for i in range(0,len(w)): # for i in range(0,len(a)): # plt.figure('2c_LimitCycle_Amplitude_'+str(act)) plt.figure('2c_LimitCycle_'+str(act)) print('Running simulation %d out of %d'%(i+1,len(w))) # print('Running simulation %d out of %d'%(i+1,len(a))) if act == 'sin': sinAct = np.sin(2*np.pi*w[i]*time).reshape(len(time),1) # sinAct = a[i]*np.sin(2*np.pi*w*time).reshape(len(time),1) else: sinAct = signal.square(2*np.pi*w[i]*time).reshape(len(time),1) # sinAct = a[i]*signal.square(2*np.pi*w*time).reshape(len(time),1) sinFlex = sinAct.copy() sinFlex[sinAct<0] = 0 sinExt = sinAct.copy() sinExt[sinAct>0] = 0 sinExt = abs(sinExt) sinAct1 = np.ones((len(time),1)) sinAct2 = np.ones((len(time),1)) sinAct1 = sinFlex sinAct2 = sinExt sinActivations = np.hstack((sinAct1,sinAct2)) # Method to add the muscle activations to the simulation sim.add_muscle_activations(sinActivations) # Simulate the system for given time sim.initalize_system(x0, time) # Initialize the system state #: If you would like to perturb the pedulum model then you could do # so by sim.sys.pendulum_sys.parameters.PERTURBATION = False # The above line sets the state of the pendulum model to zeros between # time interval 1.2 < t < 1.25. You can change this and the type of # perturbation in # pendulum_system.py::pendulum_system function # Integrate the system for the above initialized state and time sim.simulate() # Obtain the states of the system after integration # res is np.array [time, states] # states vector is in the same order as x0 res = sim.results() # In order to obtain internal states of the muscle # you can access the results attribute in the muscle class muscle1_results = sim.sys.muscle_sys.Muscle1.results muscle2_results = sim.sys.muscle_sys.Muscle2.results # Plotting the results plt.plot(res[:, 1], res[:, 2], label='Act. $%s(2\cdot{}\\pi\cdot{}%.1f\cdot{}t)$'%(act,w[i])) # plt.plot(res[:, 1], res[:, 2], label='Act. $%.1f\cdot{}%s(2\cdot{}\\pi\cdot{}0.5\cdot{}t)$'%(a[i],act)) plt.figure('2c_Amplitude_'+str(act)) plt.plot(time,res[:, 1], label='Frequency = %.1f'%(w[i])) # plt.figure('2c_Amplitude_Amplitude_'+str(act)) # plt.plot(time,res[:, 1], label='Amplitude = %.1f'%(a[i])) plt.figure('2c_LimitCycle_'+str(act)) # plt.figure('2c_LimitCycle_Amplitude_'+str(act)) plt.xlabel('Position [rad]') plt.ylabel('Velocity [rad/s]') plt.grid() plt.legend() plt.figure('2c_Amplitude_'+str(act)) # plt.figure('2c_Amplitude_Amplitude_'+str(act)) plt.xlabel('Time [s]') plt.ylabel('Amplitude [rad]') plt.grid() plt.legend() #----------------# Exercise 2c finished #----------------# #----------------# Exercise 2b #----------------# w = 0.5 if act == 'sin': sinAct = np.sin(2*np.pi*w*time).reshape(len(time),1) else: sinAct = signal.square(2*np.pi*w*time).reshape(len(time),1) sinFlex = sinAct.copy() sinFlex[sinAct<0] = 0 sinExt = sinAct.copy() sinExt[sinAct>0] = 0 sinExt = abs(sinExt) sinAct1 = np.ones((len(time),1)) sinAct2 = np.ones((len(time),1)) sinAct1 = sinFlex sinAct2 = sinExt activations = np.hstack((sinAct1,sinAct2)) # Method to add the muscle activations to the simulation sim.add_muscle_activations(activations) # Simulate the system for given time sim.initalize_system(x0, time) # Initialize the system state #: If you would like to perturb the pedulum model then you could do # so by sim.sys.pendulum_sys.parameters.PERTURBATION = True # The above line sets the state of the pendulum model to zeros between # time interval 1.2 < t < 1.25. You can change this and the type of # perturbation in # pendulum_system.py::pendulum_system function # Integrate the system for the above initialized state and time sim.simulate() # Obtain the states of the system after integration # res is np.array [time, states] # states vector is in the same order as x0 res = sim.results() # In order to obtain internal states of the muscle # you can access the results attribute in the muscle class muscle1_results = sim.sys.muscle_sys.Muscle1.results muscle2_results = sim.sys.muscle_sys.Muscle2.results # Plotting the results plt.figure('2b_LimitCycle_'+str(act)) plt.title('Pendulum Phase') plt.plot(res[:, 1], res[:, 2], label='Act. $%s(2\cdot{}\\pi\cdot{}%.1f\cdot{}t)$, Pert. ($t=3.2,\\theta = 1, \dot{\\theta} = -0.5$)' %(act,w)) plt.xlabel('Position [rad]') plt.ylabel('Velocity [rad/s]') plt.grid() plt.legend() plt.figure('2b_ActivationFunction_'+str(act)) plt.title('Activation Function') plt.plot(time, sinAct1, label='Flexor') plt.plot(time, sinAct2, label='Extensor') plt.xlabel('Time [s]') plt.ylabel('Activation') plt.grid() plt.legend() #----------------# Exercise 2b finished #----------------# # To animate the model, use the SystemAnimation class # Pass the res(states) and systems you wish to animate simulation = SystemAnimation(res, pendulum, muscles) # To start the animation if DEFAULT["save_figures"] is False: simulation.animate() if not DEFAULT["save_figures"]: plt.show() else: figures = plt.get_figlabels() pylog.debug("Saving figures:\n{}".format(figures)) for fig in figures: plt.figure(fig) save_figure(fig) #plt.close(fig) plt.show
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) # 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 # Velocity-tension curve # Evalute for various loads load_min = 1 load_max = 301 N_load = 50 load_list = np.arange(load_min, load_max, (load_max - load_min) / N_load) # Evalute for Stimulation = 1.0 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.3 time_step = 0.001 time_stabilize = 0.2 time = np.arange(t_start, t_stop, time_step) max_velocity = np.zeros(N_load) tendonF = np.zeros(N_load) for ind_load, load in enumerate(load_list): # Run the integration result = sys.integrate(x0=x0, time=time, time_step=time_step, time_stabilize=time_stabilize, stimulation=stimulation, load=load) if (result.l_mtc[-1] < (sys.muscle.L_OPT + sys.muscle.L_SLACK)): max_velocity[ind_load] = np.max(-result.v_ce) else: max_velocity[ind_load] = np.min(-result.v_ce) tendonF[ind_load] = result.tendon_force[-1] # Plotting plt.figure('Isotonic Muscle Experiment 1d') v_min = np.amin(max_velocity) v_max = np.amax(max_velocity) plt.plot(max_velocity * 100 / -muscle.V_MAX, tendonF * 100 / muscle.F_MAX) plt.axvline(linestyle='--', color='r', linewidth=2) plt.text(v_min * 100 / -muscle.V_MAX, 20, r'lengthening', fontsize=14) plt.text(v_max * 100 / -muscle.V_MAX * 1 / 3, 20, r'shortening', fontsize=14) plt.xlabel('Maximal velocity [% of $V_{max}$]') plt.ylabel('Tendon Force [% of $F_{max}$]') plt.title( 'Velocity-tension curve for isotonic muscle experiment (Stimulation = 1.0)' ) plt.grid()
def exercise2(): """ Main function to run for Exercise 2. Parameters ---------- None Returns ------- None """ # Define and Setup your pendulum model here # Check PendulumSystem.py for more details on Pendulum class pendulum_params = PendulumParameters() # Instantiate pendulum parameters pendulum_params.L = 0.5 # To change the default length of the pendulum pendulum_params.m = 1. # To change the default mass of the pendulum pendulum = PendulumSystem(pendulum_params) # Instantiate Pendulum object #### CHECK OUT PendulumSystem.py to ADD PERTURBATIONS TO THE MODEL ##### pylog.info('Pendulum model initialized \n {}'.format( pendulum.parameters.showParameters())) # Define and Setup your pendulum model here # Check MuscleSytem.py for more details on MuscleSytem class M1_param = MuscleParameters() # Instantiate Muscle 1 parameters M1_param.f_max = 1500 # To change Muscle 1 max force M2_param = MuscleParameters() # Instantiate Muscle 2 parameters M2_param.f_max = 1500 # To change Muscle 2 max force M1 = Muscle(M1_param) # Instantiate Muscle 1 object M2 = Muscle(M2_param) # Instantiate Muscle 2 object # Use the MuscleSystem Class to define your muscles in the system muscles = MuscleSytem(M1, M2) # Instantiate Muscle System with two muscles pylog.info('Muscle system initialized \n {} \n {}'.format( M1.parameters.showParameters(), M2.parameters.showParameters())) # Define Muscle Attachment points m1_origin = np.array([-0.17, 0.0]) # Origin of Muscle 1 m1_insertion = np.array([0.0, -0.17]) # Insertion of Muscle 1 m2_origin = np.array([0.17, 0.0]) # Origin of Muscle 2 m2_insertion = np.array([0.0, -0.17]) # Insertion of Muscle 2 # Attach the muscles muscles.attach(np.array([m1_origin, m1_insertion]), np.array([m2_origin, m2_insertion])) # Create a system with Pendulum and Muscles using the System Class # Check System.py for more details on System class sys = System() # Instantiate a new system sys.add_pendulum_system(pendulum) # Add the pendulum model to the system sys.add_muscle_system(muscles) # Add the muscle model to the system ##### Time ##### t_max = 3 # Maximum simulation time time = np.arange(0., t_max, 0.004) # Time vector ##### Model Initial Conditions ##### x0_P = np.array([0., 0.]) # Pendulum initial condition # Muscle Model initial condition x0_M = np.array([0., M1.L_OPT, 0., M2.L_OPT]) x0 = np.concatenate((x0_P, x0_M)) # System initial conditions ##### System Simulation ##### # For more details on System Simulation check SystemSimulation.py # SystemSimulation is used to initialize the system and integrate # over time sim = SystemSimulation(sys) # Instantiate Simulation object # Add muscle activations to the simulation # Here you can define your muscle activation vectors # that are time dependent ''' #act1 = np.ones((len(time), 1)) * 1. #act2 = np.ones((len(time), 1)) * 0.05 act1 = (np.sin((time/t_max)*10*np.pi)+1)/2 act2 = (np.sin((time/t_max)*10*np.pi + np.pi)+1)/2 act1 = np.reshape(act1, (len(time),1)) act2 = np.reshape(act2, (len(time),1)) activations = np.hstack((act1, act2)) # Plotting the results plt.figure('Activations') plt.title('Muscle activations') plt.plot(time, act1, label = 'Activation muscle 1') plt.plot(time, act2, label = 'Activation muscle 2') plt.xlabel('Time [s]') plt.ylabel('Activation') plt.legend() plt.grid() # Method to add the muscle activations to the simulation sim.add_muscle_activations(activations) ''' max_amplitude = np.zeros([10, 10]) i = 0 j = 0 # Simulate the system for given time for activation_max in np.arange(0, 1, 0.9): i = 0 for frequency in np.arange(1, 10, 4): act1 = ((np.sin( (time / t_max) * frequency * np.pi) + 1) / 2) * activation_max act2 = ((np.sin((time / t_max) * frequency * np.pi + 1) + 1) / 2) * activation_max act1 = np.reshape(act1, (len(time), 1)) act2 = np.reshape(act2, (len(time), 1)) activations = np.hstack((act1, act2)) sim.add_muscle_activations(activations) sim.initalize_system(x0, time) # Initialize the system state #: If you would like to perturb the pedulum model then you could do # so by sim.sys.pendulum_sys.parameters.PERTURBATION = False # The above line sets the state of the pendulum model to zeros between # time interval 1.2 < t < 1.25. You can change this and the type of # perturbation in # pendulum_system.py::pendulum_system function # Integrate the system for the above initialized state and time sim.simulate() # Obtain the states of the system after integration # res is np.array [time, states] # states vector is in the same order as x0 res = sim.results() # In order to obtain internal states of the muscle # you can access the results attribute in the muscle class muscle1_results = sim.sys.muscle_sys.Muscle1.results muscle2_results = sim.sys.muscle_sys.Muscle2.results max_amplitude[i, j] = np.max(np.abs(res[:, 1])) i += 1 # Plotting the results plt.figure('Pendulum') plt.title('Pendulum Phase') plt.plot(res[:, 1], res[:, 2], label='activation %.2f - frequency %f' % (activation_max, frequency)) plt.xlabel('Position [rad]') plt.ylabel('Velocity [rad.s]') plt.grid() j += 1 plt.figure('Amplitude') fig, ax1 = plt.subplots(1, 1) ax1.set_xticklabels(np.array([0, 0, 0.2, 0.4, 0.8, 1])) ax1.set_yticklabels(np.array([0, 1, 3, 5, 7, 9])) plt.title('Ampliudes') plt.imshow(max_amplitude, aspect='equal', origin='lower') plt.xlabel('Activation') plt.ylabel('Frequncy') # To animate the model, use the SystemAnimation class # Pass the res(states) and systems you wish to animate simulation = SystemAnimation(res, pendulum, muscles) # To start the animation if DEFAULT["save_figures"] is False: simulation.animate() if not DEFAULT["save_figures"]: plt.show() else: figures = plt.get_figlabels() pylog.debug("Saving figures:\n{}".format(figures)) for fig in figures: plt.figure(fig) save_figure(fig) plt.close(fig)
def exercise3(): """ Main function to run for Exercise 3. Parameters ---------- None Returns ------- None """ ''' # Create system sim = system_init() # Add external inputs to neural network sim.add_external_inputs_to_network(np.ones((len(sim.time), 4))) # Integrate the system for the above initialized state and time sim.simulate() # Obtain the states of the system after integration # res is np.asarray [time, states] # states vector is in the same order as x0 res = sim.results() # Obtain the states of the system after integration # res is np.asarray [time, states] # states vector is in the same order as x0 res = sim.results() # In order to obtain internal states of the muscle # you can access the results attribute in the muscle class muscle_1_results = sim.sys.muscle_sys.muscle_1.results muscle_2_results = sim.sys.muscle_sys.muscle_2.results # Plotting the results plt.figure('Pendulum') plt.title('Pendulum Phase') plt.plot(res[:, 1], res[:, 2]) plt.xlabel('Position [rad]') plt.ylabel('Velocity [rad.s]') plt.grid() ''' ###################################################### # initialization ########## PENDULUM ########## P_params = PendulumParameters() P_params.L = 1.0 P_params.m = 0.25 pendulum = PendulumSystem(P_params) pylog.info('Pendulum model initialized \n {}'.format( pendulum.parameters.showParameters())) ########## MUSCLES ########## m1_param = MuscleParameters() m1_param.f_max = 200. m1_param.l_opt = 0.4 m1_param.l_slack = 0.45 m2_param = MuscleParameters() m2_param.f_max = 200. m2_param.l_opt = 0.4 m2_param.l_slack = 0.45 m1 = Muscle('m1', m1_param) m2 = Muscle('m2', m2_param) muscles = MuscleSystem(m1, m2) pylog.info('Muscle system initialized \n {} \n {}'.format( m1.parameters.showParameters(), m2.parameters.showParameters())) ######## Define Muscle Attachment points m1_origin = np.asarray([0.0, 0.9]) m1_insertion = np.asarray([0.0, 0.15]) m2_origin = np.asarray([0.0, 0.8]) m2_insertion = np.asarray([0.0, -0.3]) muscles.attach(np.asarray([m1_origin, m1_insertion]), np.asarray([m2_origin, m2_insertion])) ##### Time ##### t_max = 2.5 time = np.arange(0., t_max, 0.001) ########################################################### ########################################################### ########################################################### ########################################################### ########################################################### ### code for 3a pylog.info("3a") d = 1. tau = np.array([0.02, 0.02, 0.1, 0.1]) b = np.array([3., 3., -3., -3.]) w = np.zeros((4, 4)) w[0, 1] = w[0, 3] = w[1, 0] = w[1, 2] = -5 w[0, 2] = w[1, 3] = 5 w[2, 0] = w[3, 1] = -5 w = w.T N_params = NetworkParameters() N_params.D = d N_params.tau = tau N_params.b = b N_params.w = w neural_network = NeuralSystem(N_params) sys = System() sys.add_pendulum_system(pendulum) sys.add_muscle_system(muscles) sys.add_neural_system(neural_network) x0_P = np.asarray([np.pi / 2, 0.]) l_ce_0 = sys.muscle_sys.initialize_muscle_length(np.pi / 2) x0_M = np.asarray([0.05, l_ce_0[0], 0.05, l_ce_0[1]]) x0_N = np.asarray([-0.5, 1, 0.5, 1]) x0 = np.concatenate((x0_P, x0_M, x0_N)) sim = SystemSimulation(sys) sim.initalize_system(x0, time) sim.simulate() res = sim.results() positions = res[:, 1] vels = res[:, 2] plt.figure('3a. Activation with time ') plt.title('Activation with time') plt.plot(res[:, 0], res[:, 3], label="Activation 1") plt.plot(res[:, 0], res[:, 5], label="Activation 2") plt.xlabel('Time [s]') plt.ylabel('Activation') plt.legend() plt.grid() plt.show() # Plotting the results plt.figure('3a. Pendulum state with time') plt.title('Pendulum state with time') plt.plot(res[:, 0], positions) plt.xlabel('Time [s]') plt.ylabel('Position [rad]') plt.grid() plt.show() # Plotting the results plt.figure('3a. Pendulum phase plot') plt.title('Pendulum phase plot') plt.plot(positions, vels) plt.xlabel('Position [rad]') plt.ylabel('Velocity [rad/s]') plt.grid() plt.show() ########################################################### ########################################################### ########################################################### ########################################################### ########################################################### ### code for 3b pylog.info("3b") all_positions = [] all_vels = [] all_time = [] all_act_1 = [] all_act_2 = [] external_drives = np.array([0, 0.2, 0.5, 1., 2., 5.]) for temp_drive in external_drives: sim = SystemSimulation(sys) sim.initalize_system(x0, time) sim.add_external_inputs_to_network( np.ones((len(sim.time), 4)) * temp_drive) sim.simulate() res = sim.results() all_time = all_time + [res[:, 0]] all_positions = all_positions + [res[:, 1]] all_vels = all_vels + [res[:, 2]] all_act_1 = all_act_1 + [res[:, 3]] all_act_2 = all_act_2 + [res[:, 5]] plt.figure('3a. Activation with time by different external drives') plt.title('Activation with time by different external drives') for i in range(len(external_drives)): plt.plot(all_time[i], all_act_1[i]) plt.plot(all_time[i], all_act_2[i]) plt.xlabel('Time [s]') plt.ylabel('Activation') temp_legends = [ 'external drive: ' + format((temp_drive), '.2f') for temp_drive in external_drives ] plt.legend(temp_legends) plt.grid() plt.show() plt.figure('3b. Pendulum state with time by different external drives') plt.title('Pendulum state with time by different external drives') for i in range(len(external_drives)): plt.plot(all_time[i], all_positions[i]) plt.xlabel('Time [s]') plt.ylabel('Position [rad]') temp_legends = [ 'external drive: ' + format((temp_drive), '.2f') for temp_drive in external_drives ] plt.legend(temp_legends) plt.grid() plt.show() plt.figure('3a. Pendulum phase plot by different external drives') plt.title('Pendulum phase plot by different external drives') for i in range(len(external_drives)): plt.plot(all_positions[i], all_vels[i]) plt.xlabel('Position [rad]') plt.ylabel('Velocity [rad/s]') temp_legends = [ 'external drive: ' + format((temp_drive), '.2f') for temp_drive in external_drives ] plt.legend(temp_legends) plt.grid() plt.show() # To animate the model, use the SystemAnimation class # Pass the res(states) and systems you wish to animate simulation = SystemAnimation(res, sim.sys.pendulum_sys, sim.sys.muscle_sys, sim.sys.neural_sys) if DEFAULT["save_figures"] is False: # To start the animation simulation.animate() plt.show() else: figures = plt.get_figlabels() pylog.debug("Saving figures:\n{}".format(figures)) for fig in figures: plt.figure(fig) save_figure(fig) plt.close(fig)
def isometric_experiment(muscle_stimulation=1., ce_stretch_max=1.5, ce_stretch_min=0.5, nb_pts=1000, time_param=TimeParameters(), l_opt=None): """ Runs a experiments in isometric mode for multiple stretches, returns the results Parameters: - muscle_stimulation: applied stimulation. - ce_stretch_max: the maximal stretch to apply to the contractile element. - ce_stretch_min: the minimal stretch to apply to the contractile element. - nb_pts: the number of times the experiment should be ran between the min and max stretch. (i.e number of points in the results) - time_param: A TimeParameters object to pass the intended time parameters for every experiment. - l_opt: The optimal length of the contractile element. If None the default one is taken Returns every parameters for the experiments. """ # System definition parameters = MuscleParameters() if l_opt is not None: parameters.l_opt = l_opt muscle = Muscle(parameters) sys = IsometricMuscleSystem() sys.add_muscle(muscle) # Experiment parameters muscle_stretch_max = find_ce_stretch_iso(sys, ce_stretch_max, time_param) muscle_stretch_min = find_ce_stretch_iso(sys, ce_stretch_min, time_param) stretches = np.arange(muscle_stretch_min, muscle_stretch_max, muscle_stretch_max / nb_pts) x0 = [0] * StatesIsometric.NB_STATES.value x0[StatesIsometric.STIMULATION.value] = 0 x0[StatesIsometric.L_CE.value] = sys.muscle.L_OPT # Containers active_force = [] passive_force = [] total_force = [] l_ce = [] l_slack = [] l_mtc = [] # Experiences pylog.info( "Running isometric experiments for stretches (this might take a while)..." ) for stretch in stretches: result = sys.integrate(x0=x0, time=time_param.times, time_step=time_param.t_step, stimulation=muscle_stimulation, muscle_length=stretch) active_force.append(result.active_force[-1]) passive_force.append(result.passive_force[-1]) total_force.append(result.tendon_force[-1]) l_ce.append(result.l_ce[-1]) l_mtc.append(result.l_mtc[-1]) l_slack.append(result.l_mtc[-1] - result.l_ce[-1]) return active_force, passive_force, total_force, l_ce, l_slack, l_mtc
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 = 15. # 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.35 time_step = 0.001 time_stabilize = 0.2 time = np.arange(t_start, t_stop, time_step) ####custom code##### load_range = np.arange(1, 361, 5) my_velocity = [] plt.figure('Isotonic muscle experiment') for load in load_range: # Run the integration result = sys.integrate(x0=x0, time=time, time_step=time_step, time_stabilize=time_stabilize, stimulation=muscle_stimulation, load=load) my_velocity.append(max(abs(result.v_ce))) i, = np.where(result.v_ce == my_velocity[-1]) if i.shape == (0, ): #checks for negative velocity my_velocity[-1] *= -1 plt.plot(result.time, result.v_ce, label='Load: %s' % load) # Plotting #plt.plot(result.time, result.v_ce) plt.title('Isotonic muscle experiment') plt.xlabel('Time [s]') plt.ylabel('Muscle contractilve velocity') plt.grid() plt.figure('Isotonic Experiment') plt.plot(load_range, my_velocity) plt.xlabel('Load[Kg]') plt.ylabel('Maximal Muscle Contractile Velocity[m/s]') plt.grid()
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 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 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 # Add the neural network to the system sys.add_neural_system(neural_network) ##### 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., 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))) # 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() # Obtain the states of the system after integration # res is np.array [time, states] # states vector is in the same order as x0 res = sim.results() # In order to obtain internal states of the muscle # you can access the results attribute in the muscle class muscle1_results = sim.sys.muscle_sys.Muscle1.results muscle2_results = sim.sys.muscle_sys.Muscle2.results # Plotting the results: Position(phase) vs time plt.figure('Pendulum Phase') plt.title('Pendulum Phase') plt.plot(res[:, 0], res[:, 1]) #to plot pendulum Position (phase) # plt.plot(res[:, 0], time) #to plot position # plt.plot(res[:, 0], res[:, -5:-1]) # to Plot neurons' states plt.xlabel('time [s]') plt.ylabel('Position [rad]') plt.grid() # Plotting the results: Velocity vs Position (phase) plt.figure('Pendulum Vel v.s. Phase') plt.title('Pendulum Vel v.s. Phase') plt.plot(res[:, 1], res[:, 2]) #to plot Velocity vs Position (phase) plt.xlabel('Position [rad]') plt.ylabel('Velocity [rad.s]') plt.grid() # Plotting the results: Velocity vs time plt.figure('Pendulum Velocity') plt.title('Pendulum Velocity') plt.plot(res[:, 0], res[:, 2]) #to plot Velocity vs Position plt.xlabel('time [s]') plt.ylabel('Velocity [rad.s]') plt.grid() # Plotting the results: Output of the network plt.figure('Network output') plt.title('Network output') plt.plot(res[:, 0], res[:, -1], label='neuron1') #to plot Velocity vs Position plt.plot(res[:, 0], res[:, -2], label='neuron2') plt.plot(res[:, 0], res[:, -3], label='neuron3') plt.plot(res[:, 0], res[:, -4], label='neuron4') plt.xlabel('time [s]') plt.ylabel('Stimulation ') plt.legend(loc='upper right') plt.grid() if DEFAULT["save_figures"] is False: plt.show() else: figures = plt.get_figlabels() pylog.debug("Saving figures:\n{}".format(figures)) for fig in figures: plt.figure(fig) save_figure(fig) plt.close(fig) # To animate the model, use the SystemAnimation class # Pass the res(states) and systems you wish to animate simulation = SystemAnimation(res, sim.sys.pendulum_sys, sim.sys.muscle_sys, sim.sys.neural_sys) # To start the animation simulation.animate()
def 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) # 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 load_array=np.arange(0.1,3000/sys.mass.parameters.g,5) vel_ce=[] act_force_int=[] stimulation=[0.,0.2,0.4,0.6,0.8,1.] colors=['r','g','b','c','m','y'] for loadx in load_array: result = sys.integrate(x0=x0, time=time, time_step=time_step, time_stabilize=time_stabilize, stimulation=muscle_stimulation, load=loadx) if (loadx==150.1 or loadx==155.1): plt.figure("Single Exp") plt.title("Result for a single experiment") plt.plot(result.time,result.v_ce*(-1)) plt.xlabel("Time [s]") plt.ylabel("Velocity [m/s]") plt.legend(('Shortening','Lengthening')) pylog.info(result.l_mtc[-1]) plt.grid() plt.show() if result.l_mtc[-1] < ( muscle_parameters.l_opt + muscle_parameters.l_slack): #pylog.info("min condition") vel_ce.append(min(result.v_ce[:])*(-1)) act_force_int.append(max(result.active_force)) else: vel_ce.append(max(result.v_ce[:])*(-1)) act_force_int.append(max(result.active_force)) # pylog.info("max condition") plt.figure('Isotonic muscle experiment') plt.plot(vel_ce,load_array*mass_parameters.g) plt.plot(vel_ce,act_force_int) plt.title('Isotonic Muscle Experiment') plt.xlabel('Contractile Element Velocity [m/s]') plt.ylabel('Force[N]') plt.legend(("External Load","Internal Active Force")) plt.grid() plt.show() plt.figure('Varying Stimulation') leg=[] for i,stim in enumerate(stimulation): pylog.info("Stim is {}".format(stim)) vel_ce=[] act_force_int=[] for loadx in load_array: result = sys.integrate(x0=x0, time=time, time_step=time_step, time_stabilize=time_stabilize, stimulation=stim, load=loadx) if result.l_mtc[-1] < ( muscle_parameters.l_opt + muscle_parameters.l_slack): #pylog.info("min condition") vel_ce.append(min(result.v_ce[:])*(-1)) act_force_int.append(max(result.active_force)) else: vel_ce.append(max(result.v_ce[:])*(-1)) act_force_int.append(max(result.active_force)) plt.plot(vel_ce,load_array*mass_parameters.g,colors[i],label='Stimulation={}'.format(stim)) plt.plot(vel_ce,act_force_int,colors[i],linestyle=":",label='Stimulation={}'.format(stim)) leg.append(("Load-velocity plot with simulation={}".format(stim))) leg.append(("Force-velocity with simulation={}".format(stim))) plt.title('Varying Stimulation') plt.legend(leg) plt.xlabel('Contractile Element Velocity [m/s]') plt.ylabel('Force[N]') #("Stimulation = 0","Stimulation = 0.2","Stimulation = 0.4","Stimulation = 0.6","Stimulation = 0.8","Stimulation = 1") plt.grid()
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()