def generate_muscle_joint_interface(self): """This function creates interface between muscles and joint.""" try: MuscleJointInterface(self.config_file, self.muscle_sys.muscles, self.joint_sys.joints) except AttributeError: biolog.warning('No joints present in the system')
def __init__(self, parameters=None): super(Mass, self).__init__() if parameters is None: pylog.warning('Setting default parameters to mass model.') self.parameters = MassParameters() else: self.parameters = parameters
def pendulum_equation(theta, dtheta, time=0, parameters=None, torque=0.): """ Pendulum equation with: - theta: Angle [rad] - dtheta: Angular velocity [rad/s] - g: Gravity constant [m/s**2] - m: Mass [kg] - L: Length [m] - d: Damping coefficient [] - torque: External torque [N-m] """ if parameters is None: parameters = PendulumParameters() pylog.warning( "Parameters not given, using defaults\n{}".format(parameters) ) g, m, L, I, d, sin, dry = ( parameters.g, parameters.m, parameters.L, parameters.I, parameters.d, parameters.sin, parameters.dry ) pylog.warning("Pendulum equation must be implemented") return 0
def add_muscle(self, muscle): """Add the muscle model to the system. Parameters ---------- muscle: <Muscle> Instance of muscle model Example: -------- >>> from muscle import Muscle >>> from system_parameters import MuscleParameters >>> muscle = Muscle(MuscleParameters()) #: Default muscle >>> isometric_system = IsometricMuscleSystem() >>> isometric_system.add_muscle(muscle) """ if self.muscle is not None: pylog.warning( 'You have already added the muscle model to the system.') return else: if muscle.__class__ is not Muscle: pylog.error('Trying to set of type {} to muscle'.format( muscle.__class__)) raise TypeError() else: pylog.info('Added new muscle model to the system') self.muscle = muscle
def set_sym(self, key, sym): """ Get the attribute symbol by name.""" if key not in self._name_to_idx: raise AttributeError() else: biolog.warning('Overwriting existing symbol') self.param_list[self._name_to_idx[key]].sym = sym
def k2(self, value): """ Keyword Arguments: value -- Set the value of spring constant for spring 2[N/rad] """ if (value < 0.0): pylog.warning('Setting bad spring constant. Should be positive!') else: self.parameters['k2'] = value pylog.info('Changed spring constant of spring 1 to {} [N/rad]'.format( self.parameters['k2']))
def b2(self, value): """ Keyword Arguments: value -- Set the value of damping constant for damper 2. [N-s/rad] """ if (value < 0.0): pylog.warning('Setting bad damping values. Should be positive!') else: self.parameters['b2'] = value pylog.info( 'Changed damping constant for damper 2 to {} [N-s/rad]'.format( self.parameters['b2']))
def exercise1(clargs): """ Exercise 1 """ # Setup pylog.info("Running exercise 1") # Setup time_max = 5 # Maximum simulation time time_step = 0.2 # Time step for ODE integration in simulation x0 = np.array([1.]) # Initial state # Integration methods (Exercises 1.a - 1.d) pylog.info("Running function integration using different methods") # Example pylog.debug("Running example plot for integration (remove)") example = example_integrate(x0, time_max, time_step) example.plot_state(figure="Example", label="Example", marker=".") # Analytical (1.a) time = np.arange(0, time_max, time_step) # Time vector x_a = analytic_function(time) analytical = Result(x_a, time) if x_a is not None else None # Euler (1.b) euler = euler_integrate(function, x0, time_max, time_step) # ODE (1.c) ode = ode_integrate(function, x0, time_max, time_step) # ODE Runge-Kutta (1.c) ode_rk = ode_integrate_rk(function_rk, x0, time_max, time_step) # Euler with lower time step (1.d) pylog.warning("Euler with smaller ts must be implemented") euler_time_step = None euler_ts_small = (euler_integrate(function, x0, time_max, euler_time_step) if euler_time_step is not None else None) # Plot integration results plot_integration_methods(analytical=analytical, euler=euler, ode=ode, ode_rk=ode_rk, euler_ts_small=euler_ts_small, euler_timestep=time_step, euler_timestep_small=euler_time_step) # Error analysis (Exercise 1.e) pylog.warning("Error analysis must be implemented") # Show plots of all results if not clargs.save_figures: plt.show() return
def pendulum_system(self, time, theta, dtheta, torque): """ Pendulum System. Accessor method adding pertrubtions.""" # YOU CAN ADD PERTURBATIONS TO THE PENDULUM MODEL HERE if self.parameters.PERTURBATION is True: if 1.2 < time < 1.25: pylog.warning('Perturbing the pendulum') torque = 0.0 return np.asarray([ [dtheta], [self.pendulum_equation(theta, dtheta, torque)] # d2theta ])[:, 0]
def add_muscle_system(self, system): """Add the muscle system. Parameters ---------- system: MuscleSystem Muscle system """ if self.systems_list.count('muscle') == 1: pylog.warning( 'You have already added the muscle model to the system.') return else: pylog.info('Added muscle model to the system') self.systems_list.append('muscle') self.muscle_sys = system
def add_pendulum_system(self, system): """Add the pendulum system. Parameters ---------- system: Pendulum Pendulum system """ if self.systems_list.count('pendulum') == 1: pylog.warning( 'You have already added the pendulum model to the system.') return else: pylog.info('Added pedulum model to the system') self.systems_list.append('pendulum') self.pendulum_sys = system
def analytic_function(t): """ Analytic funtion x(t) (To be written) Notes: - To write exponential(x) in Python with numpy: np.exp(x) Example: >>> np.exp(0.0) 1.0 This function should simply return the state with same shape as input t (i.e. as a list or an areray) """ # COMPLETE CODE import farms_pylog as pylog pylog.warning("Analytical function must be implemented") return None
def add_neural_system(self, system): """Add the neural network system. Parameters ---------- system: NeuralSystem Neural Network system """ if self.systems_list.count('neural') == 1: pylog.warning( 'You have already added the neural model to the system.') return else: pylog.info('Added neural network to the system') self.systems_list.append('neural') self.neural_sys = system
def ode_integrate(fun, x0, time_max, time_step): """ Integrate function using Euler method - fun: Function df/dt = f(x, t) to integrate - x0: Initial state - time_tot: Total time to simulate [s] - time_step: Time step [s] Use odeint from the scipy library for integration Make sure to then use the Result class similarly to the example_integrate found above (i.e. Result(x, time)) """ time = np.arange(0, time_max, time_step) # COMPLETE CODE pylog.warning("ODE integration must be implemented") return None
def euler_integrate(fun, x0, time_max, time_step): """ Integrate function using Euler method - fun: Function df/dt = f(x, t) to integrate - x0: Initial state - time_tot: Total time to simulate [s] - time_step: Time step [s] For loop in Python: >>> a = [0, 0, 0] # Same as [0 for _ in range(3)] (List comprehension) >>> for i in range(3): ... a[i] = i >>> print(a) [0, 1, 2] Creating a matrix of zeros in python: >>> state = np.zeros([3, 2]) >>> print(state) [[0. 0.] [0. 0.] [0. 0.]] For loop for a state in python >>> state = np.zeros([3, 2]) >>> state[0, 0], state[0, 1] = 1, 2 >>> for i, time in enumerate([0, 0.1, 0.2]): ... state[i, 0] += time ... state[i, 1] -= time >>> print(state) [[ 1. 2. ] [ 0.1 -0.1] [ 0.2 -0.2]] Make sure to use the Result class similarly to the example_integrate found above (i.e. Result(x, time)) """ time = np.arange(0, time_max, time_step) x = np.zeros([len(time), len(x0)]) # COMPLETE CODE pylog.warning("Euler integration must be implemented") return None
def ode_integrate_rk(fun_rk, x0, time_max, time_step): """ Integrate function using Euler method - fun: Function df/dt = f(x, t) to integrate - x0: Initial state - time_tot: Total time to simulate [s] - time_step: Time step [s] For Runge-Kutta, use: solver = ode(fun) solver.set_integrator('dopri5') solver.set_initial_value(x0, time[0]) xi = solver.integrate(ti) Note that solver.integrate(ti) only integrates for one time step at time ti (where ti is the current time), so you will need to use a for loop Make sure to use the Result class similarly to the example_integrate found above (i.e. Result(x, time)) """ time = np.arange(0, time_max, time_step) # COMPLETE CODE pylog.warning("ODE integration with RK must be implemented") return None
def exercise3(clargs): """ Exercise 3 """ parameters = PendulumParameters() # Checkout pendulum.py for more info pylog.info(parameters) # Simulation parameters time = np.arange(0, 30, 0.01) # Simulation time x0 = [0.1, 0.0] # Initial state # To use/modify pendulum parameters (See PendulumParameters documentation): # parameters.g = 9.81 # Gravity constant # parameters.m = 1. # Mass # parameters.L = 1. # Length # parameters.I = 1. # Inertia (Automatically computed!) # parameters.d = 0.3 # damping # parameters.sin = np.sin # Sine function # parameters.dry = False # Use dry friction (True or False) # Example of system integration (Similar to lab1) # (NOTE: pendulum_equation must be imlpemented first) pylog.debug("Running integration example") res = integrate(pendulum_system, x0, time, args=(parameters,)) res.plot_state("State") res.plot_phase("Phase") # Evolutions # Write code here (You can add functions for the different cases) pylog.warning( "Evolution of pendulum in normal conditions must be implemented" ) pylog.warning( "Evolution of pendulum without damping must be implemented" ) pylog.warning( "Evolution of pendulum with perturbations must be implemented" ) pylog.warning( "Evolution of pendulum with dry friction must be implemented" ) # Show plots of all results if not clargs.save_figures: plt.show()
def exercise2(clargs): """ Exercise 2 """ pylog.info("Running exercise 2") # System definition pylog.warning("Proper matrix A must be implemented") A = np.array([[1, 0], [0, 1]]) time_total = 10 time_step = 0.01 x0, time = [0, 1], np.arange(0, time_total, time_step) # Normal run pylog.warning("System integration must be implemented") # integration(x0, time, A, "example") # Stable point (Optional) pylog.warning("Stable point integration must be implemented") # Periodic pylog.warning("Periodic system must be implemented") # Plot if not clargs.save_figures: plt.show()
def coupled_hopf_ocillator(): """ 4b - Coupled Hopf oscillator simulation """ pylog.warning("Coupled Hopf oscillator must be implemented")
def hopf_ocillator(): """ 4a - Hopf oscillator simulation """ pylog.warning("Hopf oscillator must be implemented")
Here we look at for and while loops in particular""" import farms_pylog as pylog # import farms_pylog for log messages ### FOR LOOPS AND WHILE LOOPS ### pylog.info(3*'\t' + 20*'#' + ' FOR AND WHILE LOOPS ' + 20*'#' + 3*'\n') # range returns a list of integers (Python 2) or a sequence (Python 3) # returns [0, 1, 2]: includes start value but excludes stop value pylog.info('Using range method between 0 and 3 {}'.format( list(range(0, 3)))) pylog.info('A very useful method for iteration') pylog.warning('Includes start value but excludes the stop values') list(range(3)) # equivalent: default start value is 0 list(range(0, 5, 2)) # returns [0, 2, 4]: third argument is the step value # Python 2 only: use xrange to create a sequence rather than a list (saves # memory) list(range(100, 100000, 5)) # for loop (not the recommended style) fruits = ['apple', 'banana', 'cherry'] pylog.warning('Not a Recommended style') for i in range(len(fruits)): pylog.info((fruits[i].upper())) # for loop (recommended style)
def set_nominal_amplitudes(self, parameters): """Set nominal amplitudes""" pylog.warning("Nominal amplitudes must be set")
def set_amplitudes_rate(self, parameters): """Set amplitude rates""" pylog.warning("Convergence rates must be set")
def set_phase_bias(self, parameters): """Set phase bias""" pylog.warning("Phase bias must be set")
def set_coupling_weights(self, parameters): """Set coupling weights""" pylog.warning("Coupling weights must be set")
def set_frequencies(self, parameters): """Set frequencies""" pylog.warning("Coupling weights must be set")
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.05 medium_opt = 0.1 long_opt = 0.15 opt_range = [short_opt, medium_opt, long_opt] muscle_stimulation = 1. length_start = 0.0 length_stop = 0.3 length_step = 0.005 muscle_lengths = np.arange(length_start, length_stop, length_step) for temp_opt in opt_range: parameters = MuscleParameters(l_opt=temp_opt) muscle = Muscle(parameters) sys = IsometricMuscleSystem() sys.add_muscle(muscle) #muscle.L_OPT = temp_opt temp_active_forces = [] temp_passive_forces = [] temp_total_forces = [] temp_element_lengths = [] for temp_length in muscle_lengths: temp_result = sys.integrate(x0=x0, time=time, time_step=time_step, stimulation=muscle_stimulation, muscle_length=temp_length) temp_active_force = temp_result.active_force[-1] temp_passive_force = temp_result.passive_force[-1] tenp_total_force = temp_active_force + temp_passive_force temp_element_length = temp_result.l_ce[-1] temp_active_forces = temp_active_forces + [temp_active_force] temp_passive_forces = temp_passive_forces + [temp_passive_force] temp_total_forces = temp_total_forces + [tenp_total_force] temp_element_lengths = temp_element_lengths + [temp_element_length] plt.figure( "1c. Isometric muscle experiment with musle fiber length = " + format((temp_opt), '.2f')) plt.plot(temp_element_lengths, temp_active_forces) plt.plot(temp_element_lengths, temp_passive_forces) plt.plot(temp_element_lengths, temp_total_forces) plt.xlabel('Muscle contracticle length [m]') plt.ylabel('Tension [N]') plt.title("Isometric muscle experiment with musle fiber length = " + format((temp_opt), '.2f')) plt.legend(("Active Force", "Passive Force ", "Total Force ")) plt.grid() plt.show()
def run_network(duration, update=False, drive=0): """Run network without Webots and plot results Parameters ---------- duration: <float> Duration in [s] for which the network should be run update: <bool> description drive: <float/array> Central drive to the oscillators """ # Simulation setup timestep = 5e-3 times = np.arange(0, duration, timestep) n_iterations = len(times) parameters = SimulationParameters( drive=drive, amplitude_gradient=None, phase_lag=None, turn=None, ) network = SalamandraNetwork(timestep, parameters, n_iterations) osc_left = np.arange(10) osc_right = np.arange(10, 20) osc_legs = np.arange(20, 24) # Logs phases_log = np.zeros( [n_iterations, len(network.state.phases(iteration=0))]) phases_log[0, :] = network.state.phases(iteration=0) amplitudes_log = np.zeros( [n_iterations, len(network.state.amplitudes(iteration=0))]) amplitudes_log[0, :] = network.state.amplitudes(iteration=0) freqs_log = np.zeros([n_iterations, len(network.parameters.freqs)]) freqs_log[0, :] = network.parameters.freqs outputs_log = np.zeros( [n_iterations, len(network.get_motor_position_output(iteration=0))]) outputs_log[0, :] = network.get_motor_position_output(iteration=0) # Run network ODE and log data tic = time.time() for i, time0 in enumerate(times[1:]): if update: network.parameters.update( SimulationParameters( # amplitude_gradient=None, # phase_lag=None )) network.step(i, time0, timestep) phases_log[i + 1, :] = network.state.phases(iteration=i + 1) amplitudes_log[i + 1, :] = network.state.amplitudes(iteration=i + 1) outputs_log[i + 1, :] = network.get_motor_position_output(iteration=i + 1) freqs_log[i + 1, :] = network.parameters.freqs # # Alternative option # phases_log[:, :] = network.state.phases() # amplitudes_log[:, :] = network.state.amplitudes() # outputs_log[:, :] = network.get_motor_position_output() toc = time.time() # Network performance pylog.info("Time to run simulation for {} steps: {} [s]".format( n_iterations, toc - tic)) # Implement plots of network results pylog.warning("Implement plots")
print_text() pylog.info('A python file can contain more than one function!') # define a function with one argument and no return values def print_this(x): pylog.info(('Printing input \'x\'', x)) # call the function print_this(3) # prints 3 n = print_this(3) # prints 3, but doesn't assign 3 to n # because the function has no return statement pylog.warning( ' prints 3, but doesn\'t assign 3 to n because the function has no return statement' ) # define a function with one argument and one return value def square_this(x): return x**2 # include an optional docstring to describe the effect of a function def square_this(x): """Return the square of a number.""" return x**2 # call the function