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 exercise2a(): """ Exercise 2a 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() biolog.warning("Loading default muscle parameters") biolog.info(parameters.showParameters()) # Create muscle object muscle = Muscle.Muscle(parameters) muscle.l_opt = 0.11 activation = 0.05 stretch=np.arange(-0.09, 0.09, 0.001) res = isometric_contraction(muscle, stretch, activation) plt.title('Force-Length when activation is %s' %activation) plt.title('Force-Length when Lopt is %s' %muscle.l_opt) plt.ylim(0,1.7*max(res[1])) # plt.ylim(0,2500) plt.plot(res[0],res[1]) plt.plot(res[0],res[2]) plt.plot(res[0],res[2]+res[1]) plt.legend(['active force','passive force','total force']) plt.xlabel('Length(m)') plt.ylabel('Force(N)') plt.grid() plt.show() """ Example for plotting graphs using matplotlib. """
def k2(self, value): """ Keyword Arguments: value -- Set the value of spring constant for spring 2[N/rad] """ if (value < 0.0): biolog.warning('Setting bad spring constant. Should be positive!') else: self.parameters['k2'] = value
def k1(self, value): """ Keyword Arguments: value -- Set the value of spring constant for spring 1 [N/rad] """ if (value < 0.0): biolog.warning('Setting bad spring constant. Should be positive!') else: self.parameters['k1'] = value biolog.info( 'Changed spring constant of spring 1 to {} [N/rad]'.format(self.parameters['k1']))
def b2(self, value): """ Keyword Arguments: value -- Set the value of damping constant for damper 2. [N-s/rad] """ if (value < 0.0): biolog.warning('Setting bad damping values. Should be positive!') else: self.parameters['b2'] = value biolog.info( 'Changed damping constant for damper 2 to {} [N-s/rad]'.format(self.parameters['b2']))
def isometric_contraction( muscle, stretch=np.arange(-0.05, 0.05, 0.001), # !!! stretch is in percent! activation=0.25): # activation original = 0.05 """ This function implements the isometric contraction of the muscle. Parameters: ----------- muscle : <Muscle> Instance of Muscle class stretch : list/array A list/array of muscle stretches to be evaluated activation : float Muscle activation Returns: ------- """ stretch = np.array(stretch) biolog.warning('Exercise 2b isotonic contraction to be implemented') # Time settings t_start = 0.0 # Start time t_stop = 0.25 # Stop time dt = 0.0001 # Time step timesteps = np.arange(t_start, t_stop, dt) # Useless?? # Empty vectors for further isometric representations Fp = np.zeros(np.size(stretch)) # passive force Fa = np.zeros(np.size(stretch)) # active force F = np.zeros(np.size(stretch)) # total force totLen = np.zeros(np.size( stretch)) # total length of the CONTRACTILE ELEMENT (l_CE + stretch) stabs = np.zeros(np.size(timesteps)) biolog.info("Muscle Isometric implemented") for i, s in enumerate(stretch): for j, t in enumerate(timesteps): effect = muscle_integrate(muscle, s, activation, dt) stabs[j] = effect['activeForce'] # effect=muscle_integrate(muscle, s, activation, dt) # effect=muscle_integrate(muscle, s, activation, dt) Fp[i] = effect['passiveForce'] Fa[i] = effect['activeForce'] F[i] = effect['force'] totLen[i] = effect['l_CE'] + s * effect['l_CE'] #print("Length of the contractile element is: {} \n and its TOTAL length+stretch is: {}".format(effect['l_CE'],totLen[i])) #print("LIMIT: {} \n {}".format(muscle.l_MTC-muscle.l_CE, muscle.l_slack)) c = np.array([totLen, Fp, Fa, F, timesteps, stabs]) #print(c) return c
def add_pendulum_system(self, system): """Add the pendulum system. Parameters ---------- system: Pendulum Pendulum system """ if self.systems_list.count('pendulum') == 1: biolog.warning( 'You have already added the pendulum model to the system.') return else: biolog.info('Added pedulum model to the system') self.systems_list.append('pendulum') self.pendulum_sys = system
def add_neural_system(self, system): """Add the neural network system. Parameters ---------- system: NeuralSystem Neural Network system """ if self.systems_list.count('neural') == 1: biolog.warning( 'You have already added the neural model to the system.') return else: biolog.info('Added neural network to the system') self.systems_list.append('neural') self.neural_sys = system
def add_muscle_system(self, system): """Add the muscle system. Parameters ---------- system: MuscleSystem Muscle system """ if self.systems_list.count('muscle') == 1: biolog.warning( 'You have already added the muscle model to the system.') return else: biolog.info('Added muscle model to the system') self.systems_list.append('muscle') self.muscle_sys = system
def exercise1b(): """ Exercise 1 """ biolog.info("Executing Lab 4 : Exercise 1") parameters = PendulumParameters() ### With damping t_start = 0.0 t_stop = 10.0 dt = 0.05 biolog.warning("Using large time step dt={}".format(dt)) time = np.arange(t_start, t_stop, dt) parameters.b1 = 0.5 parameters.b2 = 0.5 x0 = [np.pi / 3, 0] biolog.info(parameters.showParameters()) res = integrate(pendulum_integration, x0, time, args=(parameters, )) res.plot_state("State")
def exercise1(): """ Exercise 1 """ biolog.info("Executing Lab 4 : Exercise 1") parameters = PendulumParameters() biolog.info( "Find more information about Pendulum Parameters in SystemParameters.py" ) biolog.info("Loading default pendulum parameters") biolog.info(parameters.showParameters()) # Simulation Parameters t_start = 0.0 t_stop = 10.0 dt = 0.001 biolog.warning("Using large time step dt={}".format(dt)) time0 = np.arange(t_start, t_stop / 2., dt) x0 = [np.pi / 2., 0.3] # x0[0] = initial position in rad, x0[1] = initial velocity time1 = np.arange(t_stop / 2., t_stop, dt) x1 = [1.0, 0.7] # x0[0] = initial position in rad, x0[1] = initial velocity res0 = integrate(pendulum_integration, x0, time0, args=(parameters, )) res1 = integrate(pendulum_integration, x1, time1, args=(parameters, )) res0.plot_phase("Phase") res1.plot_phase("Phase") res0.plot_state("State") res1.plot_state("State") if DEFAULT["save_figures"] is False: plt.show() font = {'family': 'normal', 'weight': 'normal', 'size': 16} plt.rc('font', **font) plt.title( " Init_Pos_0 = $\pi/2$, Init_Vel_0 = {}, Init_Pos_1 = {}, Init_Vel_1 = {},\nK1 = {}, K2 = {}, theta_ref_1 = {}, theta_ref_2 = {}" .format(x0[1], x1[0], x1[1], parameters.k1, parameters.k2, parameters.s_theta_ref1, parameters.s_theta_ref2)) plt.minorticks_on() plt.grid(which='major', linestyle='-', linewidth='0.5', color='black') plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black') return
def pendulum_equation(theta, dtheta, time=0, parameters=None): """ Pendulum equation with: - theta: Angle [rad] - dtheta: Angular velocity [rad/s] - g: Gravity constant [m/s**2] - L: Length [m] - d: Damping coefficient [] """ if parameters is None: parameters = PendulumParameters() biolog.warning( "Parameters not given, using defaults\n{}".format(parameters)) g, L, d, sin, dry = (parameters.g, parameters.L, parameters.d, parameters.sin, parameters.dry) if parameters.dry == False: return (-g / L) * ( np.sin(theta) ) - d * dtheta # returns theta-point-point, which is integrated afterwards else: return (-g / L) * np.sin(theta) - ( d * np.sign(dtheta) ) # returns theta-point-point, which is integrated afterwards
def exercise3(): """ Exercise 3 """ parameters = PendulumParameters() # Checkout pendulum.py for more info biolog.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.L = 1. # Length # 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) biolog.debug("Running integration example") res = integrate(pendulum_integration, x0, time, args=(parameters, )) res.plot_state("State") res.plot_phase("Phase") # Evolutions # Write code here (You can add functions for the different cases) biolog.warning( "Evolution of pendulum in normal conditions must be implemented") biolog.warning("Evolution of pendulum without damping must be implemented") biolog.warning( "Evolution of pendulum with perturbations must be implemented") biolog.warning( "Evolution of pendulum with dry friction must be implemented") # Show plots of all results if DEFAULT["save_figures"] is False: plt.show() return
"""This script explains the basic data types used in Python. All the comman data types used in programming langauges are in Python too. """ from __future__ import print_function # Only necessary in Python 2 import biolog # Import the biolog module to display log messages biolog.info(3 * '\t' + 20 * '#' + 'DATA TYPES' + 20 * '#' + 3 * '\n') biolog.warning("In Python every element is treated as an Object." + " Including numbers and literals!!!") # Different Data types # Use 'type' method to identify the types biolog.info('Data Type of 2 is : {}'.format(type(2))) # int biolog.info('Data Type of 2.0 is : {}'.format(type(2.0))) # Float biolog.info('Data Type of \'two\' is : {}'.format(type('two'))) # String biolog.warning('There is no separate char data type in Python.') biolog.info('Data Type of keyword True is : {}'.format(type(True))) # Boolean biolog.info('Data Type of keyword None is : {}'.format( type(None))) # None type
def exercise1a(): """ Exercise 1 """ biolog.info("Executing Lab 4 : Exercise 1") def period_(dt, state): zero = [0.0, 0.0] j = 0 for i in range(1, len(state)): if state[i] * state[i - 1] <= 0: zero[j] = i j += 1 if j == 2: break period = (zero[1] - zero[0]) * dt return period def different_initial_conditions(position, parameters, time): for position_ in position: x0 = [position_, 0] res = integrate(pendulum_integration, x0, time, args=(parameters, )) res.plot_state("State") plt.title('State') res.plot_phase("Phase") plt.title('Phase') plt.show() return None def influence_of_k(k, parameters, time, x0, k_test): maxposition = np.ones(len(k)) maxvelocity = np.ones(len(k)) period = np.ones(len(k)) ''' the change of amplitude and the period in function of k ''' for i in range(0, len(k)): parameters.k1 = k[i] parameters.k2 = k[i] res = integrate(pendulum_integration, x0, time, args=(parameters, )) maxposition[i] = max(res.state[:, 0]) maxvelocity[i] = max(res.state[:, 1]) period[i] = period_(dt, res.state[:, 1]) plt.plot(k, maxposition) plt.plot(k, maxvelocity) plt.plot(k, period) plt.grid() plt.title( 'The change of the amplitude and the period in function of k') plt.legend([ 'amplitude of position(rad)', 'amplitude of velocity(rad/s)', 'period of movement(s)' ]) plt.show() ''' plot position and velocity seperately for 2 k''' for i in range(0, 2): for k_ in k_test: parameters.k1 = k_ parameters.k2 = k_ res = integrate(pendulum_integration, x0, time, args=(parameters, )) plt.plot(time, res.state[:, i]) if i == 0: plt.title('Position-time') else: plt.title('Velocity-time') plt.legend(['k1 = %s' % (k_test[0]), 'k2 = %s' % (k_test[1])]) # plt.legend(['k = s']) plt.grid() plt.show() return None def influence_of_theta0(theta0, parameters, time, x0, theta0_test): maxposition = np.ones(len(theta0)) minposition = np.ones(len(theta0)) maxvelocity = np.ones(len(k)) period = np.ones(len(k)) ''' the change of amplitude, the range of motion, and the period in function of k ''' for i in range(0, len(theta0)): parameters.s_theta_ref1 = theta0[i] parameters.s_theta_ref2 = theta0[i] res = integrate(pendulum_integration, x0, time, args=(parameters, )) maxposition[i] = max(res.state[:, 0]) minposition[i] = min(res.state[:, 0]) maxvelocity[i] = max(res.state[:, 1]) period[i] = period_(dt, res.state[:, 1]) plt.plot(theta0, maxposition) plt.plot(theta0, minposition) plt.plot(theta0, maxvelocity) plt.plot(theta0, period) plt.title( 'The change of the amplitude, the range of motion, and the period in function of k' ) plt.legend([ 'amplitude of right position(rad)', 'amplitude of left position(rad)', 'amplitude of velocity(rad/s)', 'period of movement(s)' ]) plt.grid() plt.show() for i in range(0, 2): for theta0_ in theta0_test: parameters.s_theta_ref1 = theta0_ parameters.s_theta_ref2 = theta0_ res = integrate(pendulum_integration, x0, time, args=(parameters, )) plt.plot(time, res.state[:, i]) if i == 0: plt.title('Position-time') else: plt.title('Velocity-time') plt.legend([ 'theta01 = %s' % (theta0_test[0]), 'theta02 = %s' % (theta0_test[1]) ]) plt.grid() plt.show() return None def different_k1_k2(k1, k2, parameters, time, x0): parameters.k1 = k1 parameters.k2 = k2 res = integrate(pendulum_integration, x0, time, args=(parameters, )) res.plot_state("State") plt.title('State with k1 = %s, k2 = %s' % (k1, k2)) plt.show() return None def different_theta01_theta02(theta01, theta02, parameters, time, x0): parameters.s_theta_ref1 = theta01 parameters.s_theta_ref2 = theta02 res = integrate(pendulum_integration, x0, time, args=(parameters, )) res.plot_state("State") plt.title('State with theta01 = %s, theta02 = %s' % (theta01, theta02)) plt.show() return None # Simulation Parameters parameters = PendulumParameters() t_start = 0.0 t_stop = 10.0 dt = 0.05 biolog.warning("Using large time step dt={}".format(dt)) time = np.arange(t_start, t_stop, dt) # no damping parameters.b1 = 0 parameters.b2 = 0 x0 = [np.pi / 3, 0] position = [-np.pi / 2, 0, np.pi / 4] different_initial_conditions(position, parameters, time) k = np.linspace(1, 60, 40) k_test = [20, 50] influence_of_k(k, parameters, time, x0, k_test) theta0 = np.linspace(-np.pi / 2, np.pi / 2, 40) theta0_test = [np.pi / 6, np.pi / 3] influence_of_theta0(theta0, parameters, time, x0, theta0_test) ### different k1 and k2 k1 = 10 k2 = 30 different_k1_k2(k1, k2, parameters, time, x0) ### different theta01 and theta02 theta01 = 1.5 theta02 = 1 different_theta01_theta02(theta01, theta02, parameters, time, x0)
def exercise2a(): """ Exercise 2a 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.""" font1 = {'family': 'normal', 'weight': 'bold', 'size': 18} font2 = {'family': 'normal', 'weight': 'normal', 'size': 12} # Definition of muscles parameters = MuscleParameters() biolog.warning("Loading default muscle parameters") biolog.info(parameters.showParameters()) # Create muscle object muscle = Muscle.Muscle(parameters) # Isometric contraction, varying the activation between [0-1] isoM = isometric_contraction(muscle) legend1 = ("Passive Force", "Active Force", "Total Force") plt.figure('Forces vs Length') plt.title("Force-Length relationship") plt.plot(isoM[0], isoM[1]) plt.plot(isoM[0], isoM[2]) plt.plot(isoM[0], isoM[3]) plt.xlabel('Total length of the contractile element [m]') plt.ylabel('Force [N]') plt.legend(legend1) plt.grid() save_figure('F_vs_length') # Stabilisation has been verified for integrating the muscle for 0.2s. However, to be sure, we integrated it for 0.25s # plt.figure("Stab??") # plt.plot(isoM[4],isoM[5]) # Effect of varying l_opt (fiber length) NOT SURE) muscleS = Muscle.Muscle(parameters) # 'short' muscle muscleS.l_opt = 0.05 # short fiber length muscleL = Muscle.Muscle(parameters) # 'long' muscle muscleL.l_opt = 0.25 # long fiber length muscleXL = Muscle.Muscle(parameters) # 'extra long' muscle muscleXL.l_opt = 0.50 # extra long fiber length isoS = isometric_contraction(muscleS, stretch=np.arange(-0.25, 0.25, 0.001), activation=0.25) isoL = isometric_contraction(muscleL, stretch=np.arange(-0.25, 0.25, 0.001), activation=0.25) isoXL = isometric_contraction(muscleXL, stretch=np.arange(-0.25, 0.25, 0.001), activation=0.25) legendS = ("Short fibers: {} [m], \n max_total_length: {} [m]".format( muscleS.l_opt, np.max(isoS[0])), "Long fibers: {} [m], \n max_total_length: {} [m]".format( muscleL.l_opt, np.max(isoL[0])), "Extra Long fibers: {} [m], \n max_total_length: {} [m]".format( muscleXL.l_opt, np.max(isoXL[0]))) plt.figure( 'Short, Long and Extra Long muscle fibers (l_opt) active force vs length' ) plt.title( "Stretching of -25% to +25% and activation of 25% for each muscle type" ) plt.plot((isoS[0]) / (np.max(isoS[0])) * 100, isoS[2]) # we plot the percentage of total length plt.plot((isoL[0]) / (np.max(isoL[0])) * 100, isoL[2]) plt.plot((isoXL[0]) / (np.max(isoXL[0])) * 100, isoXL[2]) plt.xlabel( 'Percentage of maximal total length (l_CE + stretching) of the contractile element [m]' ) plt.ylabel('Active Force [N]') plt.legend(legendS) plt.grid() plt.minorticks_on() plt.grid(which='major', linestyle='-', linewidth='0.5', color='black') plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black') save_figure('short_vs_long_vs_xtraLong') legendSx = ("Short fibers: {} [m], \n max_total_length: {} [m]".format( muscleS.l_opt, np.max(isoS[0])), "Long fibers: {} [m], \n max_total_length: {} [m]".format( muscleL.l_opt, np.max(isoL[0]))) plt.figure('Short and Long muscle fibers (l_opt) active force vs length') plt.plot(isoS[0], isoS[2]) plt.plot(isoL[0], isoL[2]) plt.xlabel('Length (l_CE + stretching) of the contractile element [m]') plt.ylabel('Active Force [N]') plt.legend(legendSx) plt.grid() plt.minorticks_on() plt.grid(which='major', linestyle='-', linewidth='0.5', color='black') plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black') save_figure('short_vs_Long') # Effect of varying activation (stimulation) activations = np.arange(0.0, 1.05, 0.05) max_F_Diff = np.zeros( np.size(activations) ) # vectors to assess the evolution of the difference of the maximas of passive and active force ratio = np.zeros( np.size(activations) ) # to implement the total_force/total_length ratio for every activation value plt.figure('Active force vs Length with varying activation time') legend2 = list() #print(activations) for i, a in enumerate(activations): muscle1 = Muscle.Muscle(parameters) #print("Activation = {} [s]".format(a)) iso = isometric_contraction(muscle1, activation=a) #print("lapin \n {}".format(iso[2])) legend2.append("Activation = {} [-]".format(a)) plt.plot(iso[0], iso[2]) # plot for active force # plt.plot(iso[0],iso[3]) # plot for total force max_F_Diff[i] = np.abs(np.max(iso[1]) - np.max(iso[2])) ratio[i] = ((np.mean(iso[3])) / (np.mean(iso[0]))) / 1000 plt.xlabel('Total length of the contractile element [m]') plt.ylabel('Force [N]') plt.legend(legend2) plt.grid() save_figure('F_vs_length') # Force difference figure plt.figure( 'Difference between the max of the passive and the active force') plt.plot(activations, max_F_Diff, color='black', marker='v', linestyle='dashed', linewidth=1, markersize=5) plt.xlabel('Activation value [s]') plt.ylabel('Force Difference [N]') plt.legend(['$\Delta$']) plt.minorticks_on() plt.grid(which='major', linestyle='-', linewidth='0.5', color='red') plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black') save_figure('delta_plot') # Force/length ratio plt.figure( 'Ratio between the total force (active + passive) and the total length of the contractile element' ) plt.plot(activations, ratio, color='black', marker='v', linestyle='dashed', linewidth=1, markersize=5) plt.xlabel('Activation value [-]') plt.ylabel('(Total_force/total_length)/1000 [N]/[m]') plt.legend(['$Ratio$']) plt.minorticks_on() plt.grid(which='major', linestyle='-', linewidth='0.5', color='red') plt.grid(which='minor', linestyle=':', linewidth='0.5', color='black') save_figure('ratio_plot') biolog.info("Isometric muscle contraction implemented") """ Example for plotting graphs using matplotlib. """
## Lists ## properties: ordered, iterable, mutable, can contain multiple data types biolog.info(3 * '\t' + 20 * '#' + 'LISTS' + 20 * '#' + 3 * '\n') # create an empty list (two ways) empty_list = [] empty_list = list() # create a list course = ['computational', 'motor', 'control'] # examine a list biolog.info("Examine the first element of the course : {}".format( course[0])) # print element 0 ('homer') biolog.warning('Indexing in Python starts from 0 and not 1') biolog.info("Print the length of the list : {}".format( len(course))) # returns the length (3) # modify a list (does not return the list) course.append('I') # append element to end biolog.info(".append : {}".format(course)) course.extend(['love', 'Python']) # append multiple elements to end biolog.info(".extend : {}".format(course)) course.insert(0, '2018 : ') # insert element at index 0 (shifts everything right) biolog.info(".insert : {}".format(course))
def exercise5(): """ Lab 3 - Exrecise 5 """ # Fixed parameters of the neural network tau = [1, 1] D = 1 # Additional parameters b = [-3.233, -1.75] w = [ [5.5, 1], [-1, 5.5] ] # pay attention to the w_ij indices, they manage the input to the neuron!!! # w[0][0] = signal of neuron 0 on itself # w[0][1] = signal of neuron 1 on neuron 0 # w[1][0] = signal of neuron 0 on neuron 1 # w[0][1] = signal of neuron 1 on itself # All system parameters packed in object for integration params = LeakyIntegratorParameters(tau, D, b, w) # Initial conditions # SET THE INITIAL CONDITIONS y_0 = [ [5, 0] ] # Values of the membrane potentials of the two neurons (initial conditions) y_1 = [[5.5, 2]] # Other inital conditions membrane potentials y_2 = [[7, 1.2]] # Other inital conditions membrane potentials # Integration time parameters # Force integration to return values at small steps for # better detecting Poincare maps crossings dt = 1e-4 t_max = 300 # Set total simulation time # Integration (make sure to implement) biolog.warning("Uncomment next line to run integration" " after implementing two_li_ode()") two_coupled_li_neurons(y_0, t_max, dt, params, "Case1") two_coupled_li_neurons(y_1, t_max, dt, params, "Case2") two_coupled_li_neurons(y_2, t_max, dt, params, "Case3") # Two stable fixed points and one saddle node biolog.warning("Implement two stable fixed points and one saddle node") # Limit cycle biolog.warning("Implement limit cycle") biolog.warning(u"Implement Poincare analysis of limit cycle") # Limit cycle (small), one stable fixed point and one saddle node biolog.warning("Implement a system with:" "\n- One limit cycle (small)" "\n- One stable fixed point" "\n- One saddle node") biolog.warning("Implement Poincare analysis of limit cycle") if DEFAULT["save_figures"] is False: plt.show() return t_max
"""This script discussess the basic math operations used in Python.""" from __future__ import print_function # Only necessary in Python 2 from __future__ import division import biolog # Import biolog module for log messages biolog.info(3 * '\t' + 20 * '#' + 'MATH' + 20 * '#' + 3 * '\n') # Basic operations biolog.info("Adding 132 + 123 : {}".format((132 + 123))) # Add biolog.info("Subrtacting 43 - 23 : {}".format((43 - 23))) # Subtract biolog.info("Multiply 65 * 87 : {}".format((65 * 87))) # Multiply biolog.info("Exponent 65**4 : {}".format((65**4))) # Exponent biolog.info("Modulo 5 % 4 : {}".format((5 % 4))) # Modulo biolog.info("Division 10 / 4 : {}".format((10 / 4))) # Division biolog.warning("Returns 2 in Python 2, returns 2.5 in Python 3") biolog.info("Division 10.0 / 4 : {}".format((10.0 / 4))) # True division biolog.info( "Force True Division in Python 2 by importing division from __future__")
print_text() biolog.info('A python file can contain more than one function!') # define a function with one argument and no return values def print_this(x): biolog.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 biolog.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
# A generic import of a default module named math import math # Now you have access to all the functionality availble # in the math module to be used in this function print('Square root of 25 computed from math module : {}'.format(math.sqrt(25))) # To import a specific function from a module from math import sqrt # Now you can avoid referencing that the sqrt function is from # math module and directly use it. print('Square root of 25 computed from math module by importing only sqrt function: ', sqrt(25)) # Import a user defined module # Here we import biolog : Module developed to display log messages for the exercise import biolog biolog.info('Module developed to display log messages for the exercies') biolog.warning("When you explicitly import functions from modules, it can lead to naming errors!!!""") # Importing multiple functions from the same module from math import sqrt, cos # Defining an alias : # Often having to reuse the actual name of module can be a pain. # We can assign aliases to module names to avoid this problem import datetime as dt biolog.info("Here we import the module datetime as dt.") # Getting to know the methods availble in a module biolog.info(dir(math))
from __future__ import print_function # Only necessary in Python 2 import biolog # import biolog for log messages ### FOR LOOPS AND WHILE LOOPS ### biolog.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 biolog.info('Using range method between 0 and 3 {}'.format(list(range(0, 3)))) biolog.info('A very useful method for iteration') biolog.warning('Includes start value but excludes the stop values') biolog.info('Python 2 returns a list and Python 3 returns a sequence') 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) range(100, 100000, 5) # for loop (not the recommended style) fruits = ['apple', 'banana', 'cherry'] biolog.warning('Not a Recommended style') for i in range(len(fruits)): biolog.info((fruits[i].upper()))
biolog.info('You can also explicity mention the type of data in the array') A = np.array([[1, 2, 3], [4, 5, 6]], np.float) # Basic numpy methods similar to the ones in MATLAB # arange, linspace, zeros, shape biolog.info('Array of integers between 0 and 10 using arange method in numpy : \n{}'.format(np.arange(0,10,1))) biolog.info('Array of integers between 0 and 10 using linspace method in numpy : \n{}'.format(np.linspace(0,10,11))) biolog.info('Array of zeros using zeros method in numpy :\n{}'.format(np.zeros((2, 3)))) biolog.info('Shape of an array using shape method in numpy :\n{}'.format(np.zeros((2,3)).shape)) biolog.warning('Numpy arrays are not matrices!!!') # Math operations ## As mentioned numpy array's are not matrices ## Math operations operate element-wise by default a = np.arange(4) biolog.info('Array a : \n{}'.format(a)) b = np.array([2, 3, 2, 4]) biolog.info(b[0]) biolog.info('Array b : \n{}'.format(b)) biolog.info('Element wise multiplication of numpy arrays a*b : \n{}'.format(a*b))
def pendulum_integration(state, time, *args, **kwargs): """ Function for system integration """ biolog.warning( "Pendulum equation with spring and damper must be implemented") # l_S return pendulum_system(state[0], state[1], *args, **kwargs)[:, 0]