def __init__(self, update_param, min_param=6.3, max_param=46.3, param_steps=10, model=hh.HodgkinHuxley(), tol=0.5, currentPar=None): """Initialize values used experiment. Parameters: - update_param: function that updates the desired paramater (takes HodgkinHuxley and param value) - min_param, max_param, param_steps: Used for parameter range in which to test. - model: model of neuron (Hodgkin Huxley) - tol: tolerance used to distinguish from resting potential. We consider the range [-tol, +tol] to be resting potential - currentPar: class containing current injection parameters.""" self.min_param = min_param self.max_param = max_param self.update_param = update_param self.param_steps = param_steps self.model = model self.tol = tol self.results = ([], []) if currentPar is None: self.currentPar = CurrentParameters() else: self.currentPar = currentPar
def sim_temp(entries_gen, entries_op2): """This function runs the temperature experiments and shows a plot, using the parameters enterded by the user.""" valid = True # For every general entry, get value and validate. for entry in entries_gen: validate_func = entry + "_val" # If invalid input print error and set valid False, such that the simulation # won't be run. if not getattr(Validation, validate_func)(entries_gen[entry].get()): print( f"ERROR: Entry {entry} contains invalid input.\nWon't run simulation." ) valid = False # For every option specific entry, get value and validate. for entry in entries_op2: validate_func = entry + "_val" # If invalid input print error and set valid False, such that the simulation # won't be run. if not getattr(Validation, validate_func)(entries_op2[entry].get()): print( f"ERROR: Entry {entry} contains invalid input.\nWon't run simulation." ) valid = False if valid: print("Running temperature experiments. This could take some time...") model = hh.HodgkinHuxley() curr_params = expy.CurrentParameters() temp_exp = expy.TempExperiment() # Set parameters model.set_num_method(bool(int(entries_gen['quick'].get())), float(entries_gen['num_method_steps'].get())) temp_exp.set_temp_exp_data(float(entries_op2['min_temp'].get()), float(entries_op2['max_temp'].get()), int(entries_op2['temp_steps'].get()), float(entries_op2['rest_pot_eps'].get()), model, curr_params) curr_params.set_curr_data(float(entries_op2['inj_mean'].get()), float(entries_op2['inj_var'].get()), float(entries_op2['dur_mean'].get()), float(entries_op2['dur_var'].get()), float(entries_op2['i_start_time'].get())) model.set_run_time(float(entries_op2['run_time2'].get())) file_path = str(entries_op2['file_name'].get()) # Simulate model and show plot. temp_exp.run(int(entries_op2['num_exps'].get())) # Store results in csv file, if file name specified. if file_path: temp_exp.store_csv("stored_figs/" + file_path) temp_exp.plot() print("------------------------------------------------------")
def sim_AP(entries_gen, entries_op1): """This function simulates an action potential and shows a plot, using the parameters entered by the user.""" model = hh.HodgkinHuxley() valid = True # For every general entry, get value and validate. for entry in entries_gen: validate_func = entry + "_val" # If invalid input print error and set valid False, such that the simulation # won't be run. if not getattr(Validation, validate_func)(entries_gen[entry].get()): print( f"ERROR: Entry {entry} contains invalid input.\nWon't run simulation." ) valid = False # For every option specific entry, get value and validate. for entry in entries_op1: validate_func = entry + "_val" # If invalid input print error and set valid False, such that the simulation # won't be run. if not getattr(Validation, validate_func)(entries_op1[entry].get()): print( f"ERROR: Entry {entry} contains invalid input.\nWon't run simulation." ) valid = False if valid: print("Simulating one action potential. This could take some time...") # Set parameters model.set_num_method(bool(int(entries_gen['quick'].get())), float(entries_gen['num_method_steps'].get())) model.set_injection_data(float(entries_op1['inj_current'].get()), float(entries_op1['inj_start'].get()), float(entries_op1['inj_end'].get())) model.set_temperature(float(entries_op1['temp'].get())) model.set_run_time(float(entries_op1['run_time1'].get())) # Simulate model and show plot. model.solve_model() model.plot_results() print("------------------------------------------------------")
def large_temp_exp(): """Runs large temperature with 100 tests and stores result (this can also be done with the GUI but this does not store results)""" model = hh.HodgkinHuxley() curr_params = expy.CurrentParameters() temp_exp = expy.TempExperiment() # Test temperatures between 5 and 45 degrees. Test 100 temperatures, # with 1 test per temperature (since experiment is deterministic) temp_exp.set_temp_exp_data(5, 45, 100, 1, model, curr_params) # Inject 50 nA/cm^2, starting at t=0, for 1ms, with no variance. curr_params.set_curr_data(50, 0, 1, 0, 0) model.set_run_time(20) # Simulate model and show plot. temp_exp.run(1) temp_exp.store_csv("results_100_deter_1.csv") plot_temp_exp_polyfit()
def __init__(self, min_temp=6.3, max_temp=46.3, temp_steps=10, model=hh.HodgkinHuxley(), tol=0.5, currentPar=None): """Initialize values used experiment. Parameters: - minTemp, maxTemp, tempsteps: Used for temperature range in which to test. - model: model of neuron (HodgkinHuxley object) - tol: tolerance used to distinguish from resting potential. Given equilibrium optential Ve, we consider the range [V - tol, V + tol] to be resting potential - currentPar: object containing current injection parameters.""" def update_func(neuron, value): neuron.set_temperature(value) super().__init__(update_func, min_param=min_temp, max_param=max_temp, param_steps=temp_steps, \ model=model, tol=tol, currentPar=currentPar)
def generate_ionic_current(V, A, delta_t): V_send = np.matmul(A, V) V_send = np.add(V_send, 70) I_ion = hh.HodgkinHuxley().main(flat(V_send)) return 1000 * delta_t * np.asarray(I_ion)
blit=True) plt.show() def frame_function(self, i): """Function used in FuncAnimation. Returns tuple with line to be plotted.""" x_data, y_data = self.frames[i] assert len(x_data) == len(y_data) self.ln.set_xdata(x_data) self.ln.set_ydata(y_data) return self.ln, if __name__ == "__main__": # Plot hodgkin huxley model neuron = hh.HodgkinHuxley() neuron.quick = True neuron.run_time = 20 neuron.num_method_time_steps = 0.025 # Retrieve data to be plotted. t, y = neuron.solve_model() volts = y[:, 0] assert len(t) == len(y) frames = [(t[:n], volts[:n]) for n in range(len(volts))] # Set plottting limits y_scaling = 1.2 xlim = (t[0], t[-1]) # The scaling should only mode the y window larger. ylim = (y_scaling * min(0, min(volts)), y_scaling * max(0, max(volts)))
def main(): """ An implementation of the CableEquation where the Hodgkin Huxley equations describe the nature of Ionic current """ """ Defining our constants and assumptions """ # Total duration of the simulation (in sec) T = 1.5 # The number of time steps that we track for N = 1000 # The time that passes by between each time step dt = float(T)/float(N) # Cell length (in cm) Cell_len = 0.01 # Cell radius is width/2 (in cm) # width = Cell length/6 [assumption: the cell would be roughly 6:1 | length:width] Cell_rad = .00241/2 # Cell perimeter = perimeter of circle (in cm) Cell_peri = 2*math.pi*Cell_rad # A node is point in space where we observe the action potential n_cells = 10 # number of nodes per cell J = n_cells*10 # total number of nodes # The seperation between two nodes (in cm) dx = float(Cell_len*n_cells)/float(J) # Every node that we observe in an array x_grid = np.array([j*dx for j in range(J)]) # membrane capacitance, (in uF/cm^2) C_m = 1 # resistance per unit len intracellular space, (in omega-cm) # r_i = 1/(math.pi*Cell_rad*Cell_rad*6.7) # resistance per unit len extracellular space, (in omega-cm) # r_e = 1/(math.pi*(Cell_rad+0.00001)*(Cell_rad+0.00001)*20) # We use the constant values below for the simulation but they are governed as shown above r_i = 178330.0 r_e = 888740.0 # A array of transmembrane potentials that exists at each node (in mV) # resting potential = -70 V_old= [-70 for _ in range(J)] # Laplacian # The D_v is the constant that gets multiplied to the laplacian matrix D_v = dt/((r_i + r_e)*dx*dx*Cell_peri*C_m) # Constructing the Laplacian for the (n+1)th time step # The + and - cover the identity matrix that is expressed in our final equation A_v = np.diagflat([-D_v/2 for _ in range(J-1)], -1) + np.diagflat([1. + D_v for _ in range(J)]) + np.diagflat([-1*D_v/2 for _ in range(J-1)], 1) # Defining the boundary conditions # Note there are only two boundaries for the cable equation because there are only two ends for a cable A_v[0][0] = 1+D_v/2 A_v[-1][-1] = 1+D_v/2 # Constructing the Laplacian for the (n)th time step B_v = np.diagflat([ D_v/2 for _ in range(J-1)], -1) + np.diagflat([1. - D_v for _ in range(J)]) + np.diagflat([D_v/2 for _ in range(J-1)], 1) # Defining the boundary conditions B_v[0][0] = 1-D_v/2 B_v[-1][-1] = 1-D_v/2 #change this value for the actual nth printing of the graph nplot = 10 c = 0 # injected current val = 30 # Actually making for i in range(N): # Continually inject current for the first 200 timesteps # This will serve as our excitation that we artificially give to spark the propagation of the action potential if i < 200: V_old[0] = -70+val V_old[1] = -70+val V_old[2] = -70+val V_old[-1] = -70-val V_old[-2] = -70-val V_old[-3] = -70-val # Here i is the ith time step in the entire simulation I_ion_old = hh.HodgkinHuxley().main([j+70.0 for j in V_old]) B_part = np.matmul(B_v, V_old) - dt*np.asarray(I_ion_old) V_new = np.linalg.solve(A_v, B_part) if i % nplot == 0: #plot results every nplot timesteps plt.plot(x_grid,V_new,linewidth=2) plt.ylim([-100, 100]) #plt.xlim([-2,35]) filename = 'foo' + str(c+1).zfill(3) + '.jpg' plt.xlabel("x in cm") plt.ylabel("Transmembrane pot in mv") plt.axhline(0, color='black') plt.axvline(-0, color='black') plt.title("t = %2.2f"%(dt*(i+1))) plt.savefig(filename) plt.clf() c += 1 # setup for the next iteration V_old = V_new
def multiple_ap_plot(): """Plots 5 action potentials using our standard parameters at temperatures from 15 to 45 degrees Celcius.""" x = hh.HodgkinHuxley() x.set_run_time(2.5) x.plot_multiple_ap(15, 45, 5)
def __init__(self, current_duration=0.5, current_range=np.linspace(0,60,15), model=hh.HodgkinHuxley()): """Initialize validation experiment. Paramters: - current_duration: duration for which current will be injected - current_range: range of rates at which current is injected. Should be lower than the peak value. - model: Hodgkin Huxley model of a neuron. Contains time and number of steps used in the numerical method (and which to use).""" self.current_duration = current_duration self.current_range = current_range self.model = model