def create_meta_data_for_predefined_models(d,MRI_param): # shift to the positive octant space Xt_new=MRI_param.x_shift+d["Implantation_coordinate_X"] Yt_new=MRI_param.y_shift+d["Implantation_coordinate_Y"] Zt_new=MRI_param.z_shift+d["Implantation_coordinate_Z"] if d["Name_prepared_neuron_array"][-4:]=='.csv': if d["Axon_Model_Type"] == 'McIntyre2002': from Axon_files.axon import Axon param_ax={ 'centered':True, 'diameter':d["diam_fib"] } a=Axon(param_ax) nr=Axon.get_axonparams(a) param_axon=[nr["ranvier_nodes"], nr["para1_nodes"], nr["para2_nodes"], nr["inter_nodes"], nr["ranvier_length"], nr["para1_length"], nr["para2_length"], nr["inter_length"], nr["deltax"], d["diam_fib"]] n_comp=((nr["ranvier_nodes"]-1)+nr["inter_nodes"]+nr["para1_nodes"]+nr["para2_nodes"])/(nr["ranvier_nodes"]-1) n_segments=int((d["n_Ranvier"]-1)*n_comp+1) #overall number of points on Axon incl. internodal elif d["Axon_Model_Type"] == 'Reilly2016': if d["diam_fib"]>=5.0 and d["diam_fib"]<=10.0: # if I understand correctly, this is the only parameter that is influenced by the change of the diameter in Reilly2016 by Carnevale internodel_length=d["diam_fib"]*200.0 # from 1 to 2 mm param_axon=[d["n_Ranvier"], 0, 0, d["n_Ranvier"]-1, 0.0, 0.0, 0.0, 0.0, internodel_length, d["diam_fib"]] else: print("Wrong fiber diameter for Reilly2016, exiting") raise SystemExit else: print("The neuron model "+str(d["Axon_Model_Type"])+" is not implemented, exiting") raise SystemExit #from Neuron_models_arangement import get_neuron_models_dims ROI_radius=get_neuron_models_dims(d["Neuron_model_array_prepared"],Xt_new,Yt_new,Zt_new,0,param_axon,0) #here we do not need Neuron_param class if d["Axon_Model_Type"] == 'McIntyre2002': Neuron_model_misc=np.array([nr["ranvier_nodes"], nr["para1_nodes"], nr["para2_nodes"], nr["inter_nodes"], nr["ranvier_length"], nr["para1_length"], nr["para2_length"], nr["inter_length"], nr["deltax"],d["diam_fib"],d["n_Ranvier"],ROI_radius,n_segments]) elif d["Axon_Model_Type"] == 'Reilly2016': Neuron_model_misc=np.array([d["n_Ranvier"], 0, 0, d["n_Ranvier"]-1, 0.0, 0.0, 0.0, 0.0, internodel_length,d["diam_fib"],d["n_Ranvier"],ROI_radius,n_segments]) '''Save meta data for the future simulations with the current Neuron model data set''' np.savetxt('/opt/Patient/Neuron_model_arrays/Neuron_model_misc.csv', Neuron_model_misc, delimiter=" ") print("Meta data for predefined neuron models was created\n") if d["Name_prepared_neuron_array"][-3:]=='.h5': param_axon=[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1] #not needed here n_segments_fib_diam_array=np.load('/opt/Patient/Neuron_model_arrays/Neuron_populations_misc.npy') ROI_radius=get_neuron_models_dims(d["Neuron_model_array_prepared"],Xt_new,Yt_new,Zt_new,0,0,0) Neuron_model_misc=np.array([-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ROI_radius,-1]) #not needed here np.savetxt('/opt/Patient/Neuron_model_arrays/Neuron_model_misc.csv', Neuron_model_misc, delimiter=" ") n_segments=n_segments_fib_diam_array[:,0] n_segments=n_segments.astype(int) return ROI_radius,param_axon,n_segments
def get_neuron_morhology( self, fib_diam, N_Ranvier ): # pass fib_diam and N_Ranvier explicitly, because they might be from a list """ Input : class Returns: dictionary with neuron morphology, number of segments (compartments) per neuron, number of compartments per section """ if self.neuron_model == 'McIntyre2002': # load the morphology param_ax = { 'centered': True, 'diameter': fib_diam # float, not a list here! Will throw an error if uneligible fiber diameter } a = Axon(param_ax) nr = Axon.get_axonparams( a ) # we need here distances between compartments: nr["ranvier_length"], nr["para1_length"], nr["para2_length"], nr["inter_length"], nr["deltax"] n_comp = int(((nr["ranvier_nodes"] - 1) + nr["inter_nodes"] + nr["para1_nodes"] + nr["para2_nodes"]) / (nr["ranvier_nodes"] - 1)) n_segm = int( (N_Ranvier - 1) * n_comp + 1 ) # overall number of compartments on one axon incl. internodal elif self.neuron_model == 'Reilly2016': n_comp = 2 n_segm = int( (N_Ranvier - 1) * n_comp + 1 ) # Reilly's (Carnevale's implementation) model has 1 internodal compartment per section nr = {} nr['deltax'] = fib_diam * 200.0 # from 1 to 2 micrometers if fib_diam > 10.0 or fib_diam < 5.0: print("Wrong fiber diameter for Reilly2016, exiting") raise SystemExit else: print("The neuron model " + self.neuron_model + " is not implemented, exiting") raise SystemExit return nr, n_segm, n_comp
def fibers_to_axons(name_of_combined_file, name_of_fiber_file, projection_name, axon_model, diam_fib, axon_length, active_contact_coordinates): name_of_directory = name_of_fiber_file.rsplit('/', 1)[0] file = h5py.File(name_of_fiber_file) fiber_array = file['fibers'][:] #fiber_array has 4 rows (x,y,z,fiber_index), columns - all points #from nibabel.streamlines.array_sequence import ArraySequence from nibabel_SequenceArray import ArraySequence streamlines = ArraySequence() #streamlines=[] N_streamlines = int(fiber_array[ 3, :].max()) #yes, indexing starts with one in those .mat files k = 0 i_previous = 0 for i in range(N_streamlines): #print(i) loc_counter = 0 #stream_line_list=[] while ((i + 1) == fiber_array[3, k] ): # this is very slow, you need to extract a pack by np.count? #stream_line_list.append(file.root.fibers[:3,k]) k += 1 loc_counter += 1 if (k == fiber_array[3, :].shape[0]): break stream_line = fiber_array[:3, i_previous:i_previous + loc_counter].T i_previous = k streamlines.append(stream_line) streamlines_filtered_ROIs = streamlines # pre-filtered in Lead-DBS if axon_model == 'McIntyre2002': from Axon_files.axon import Axon param_ax = {'centered': True, 'diameter': diam_fib} a = Axon(param_ax) nr = Axon.get_axonparams(a) n_comp = ( (nr["ranvier_nodes"] - 1) + nr["inter_nodes"] + nr["para1_nodes"] + nr["para2_nodes"]) / (nr["ranvier_nodes"] - 1) ranvier_length, para1_length, para2_length, node_step = ( nr["ranvier_length"] * 1e-3, nr["para1_length"] * 1e-3, nr["para2_length"] * 1e-3, nr["deltax"] * 1e-3) if diam_fib >= 5.7: inter_length = (node_step - para1_length * 2 - para2_length * 2) / 6 else: inter_length = (node_step - para1_length * 2 - para2_length * 2) / 3 n_Ranviers = int(axon_length / node_step) n_segments = int((n_Ranviers - 1) * n_comp + 1) #overall number of points on Axon incl. internodal n_total = (n_Ranviers - 1) * n_comp + 1 #total incl. Ranvier # print(n_Ranviers,axon_length,node_step) elif axon_model == 'Reilly2016': n_comp = 2 #only nodes and one internodal per segment node_step = diam_fib * 0.2 # from 1 to 2 mm n_Ranviers = int(axon_length / node_step) n_segments = int((n_Ranviers - 1) * n_comp + 1) n_total = (n_Ranviers - 1) * 2 + 1 #one internodal per segment + the last Ranvier else: print("The neuron model is not implemented") raise SystemExit #resampling with different number of nodes of Ranvier from Arbitrary_streamline_to_Ranviers import length_fiber lengths_streamlines_filtered = list( length_fiber(streamlines_filtered_ROIs)) streamlines_resampled = ArraySequence() #streamlines_resampled=[] from Arbitrary_streamline_to_Ranviers import resample_streamline_for_Ranvier streamline_index = 0 excluded_streamlines = [] total_points = 0 for single_stream_lime in streamlines_filtered_ROIs: n_Ranvier_this_axon = int( lengths_streamlines_filtered[streamline_index] / node_step) streamline_resampled = resample_streamline_for_Ranvier( streamlines_filtered_ROIs[streamline_index], n_Ranvier_this_axon * node_step, n_Ranvier_this_axon) if len(streamline_resampled) < n_Ranviers: print("streamline ", streamline_index, " is too short") excluded_streamlines.append(streamline_index) else: streamlines_resampled.append(streamline_resampled) total_points = total_points + len(streamline_resampled) streamline_index = streamline_index + 1 streamline_index = 0 #print(len(streamlines_resampled),len(streamlines_filtered_ROIs),n_total) # streamlines_resampled=streamlines_filtered_ROIs # the length check was already done in Lead-DBS # from dipy.viz import ui, window # from dipy.viz import window, actor, colormap as cmap # from nibabel.streamlines.array_sequence import ArraySequence # # # stream_actor_dm = actor.line(streamlines_resampled,[0.0,0.4470,0.7410]) #particular color # ren = window.Renderer() # #hdp # ren.add(stream_actor_dm) # #ren.add(seedroi_actor) # window.show(ren) # # now we transform it back to .mat for visualization # #point_fibers_array=np.zeros((4,total_points),float) # point_fibers_array=np.zeros((total_points,4),float) # glob_counter=0 # for i_steamline in range(len(streamlines_resampled)): # # streamline_length = len(streamlines_resampled[i_steamline]) # # # point_fibers_array[glob_counter:glob_counter+streamline_length,:3]=streamlines_resampled[i_steamline][:] # point_fibers_array[glob_counter:glob_counter+streamline_length,3]=i_steamline+1 # # glob_counter=glob_counter+streamline_length # # from scipy.io import savemat # mdic = {"fibers": point_fibers_array, "ea_fibformat": "1.0"} # savemat(name_of_directory+'/'+projection_name+"_resampled_to_nodes.mat", mdic) center_of_mass = active_contact_coordinates # it is a list from scipy import spatial streamlines_ROI_centered = ArraySequence() #streamlines_ROI_centered=[] max_A_len = 0 overall_shape = 0 for inx_axn in range(len(streamlines_resampled)): single_streamline_ROI_centered = np.zeros((n_Ranviers, 3), float) A = streamlines_resampled[inx_axn] if inx_axn > 600: for k in range(A.shape[0]): if A[k, 2] == 0.0: print(inx_axn) overall_shape = overall_shape + A.shape[0] if max_A_len < A.shape[0]: max_A_len = A.shape[0] #A[spatial.KDTree(A).query(pt)[1]] #distance,index = spatial.KDTree(A).query(center_of_mass) #distance is a local index of closest node of Ranvier on the axon. You should check for several center_of_mass as you do already when seeding for the network distance_list = [] index_list = [] for j in range(len(center_of_mass)): distance, index = spatial.KDTree(A).query( center_of_mass[j] ) #distance is a local index of closest node of Ranvier on the axon distance_list.append(distance) index_list.append(index) index = index_list[distance_list.index(min( distance_list))] #index of the closest point as assigned as index distance = min(distance_list) loc_index = 0 if index < int(n_Ranviers / 2): bias_to_right = int(n_Ranviers / 2) - index #for i in xrange(0,index+int(n_Ranviers/2)+bias_to_right): for i in range(0, int(n_Ranviers)): single_streamline_ROI_centered[loc_index, :] = A[i] loc_index = loc_index + 1 elif index + int(n_Ranviers / 2) + 1 > A.shape[0]: #bias_to_left=index+int(n_Ranviers/2)-A.shape[0] #for i in xrange(index-int(n_Ranviers/2)-bias_to_left,index+int(n_Ranviers/2)-bias_to_left): #for i in range(0,A.shape[0]-n_Ranviers,A.shape[0]): for i in range(A.shape[0] - n_Ranviers, A.shape[0]): single_streamline_ROI_centered[loc_index, :] = A[i] loc_index = loc_index + 1 else: if n_Ranviers % 2 == 0: for i in range(index - int(n_Ranviers / 2), index + int(n_Ranviers / 2)): #for i in xrange(index-int(n_Ranviers/2),index+int(n_Ranviers/2)): single_streamline_ROI_centered[loc_index, :] = A[i] loc_index = loc_index + 1 else: for i in range(index - int(n_Ranviers / 2), index + int(n_Ranviers / 2) + 1): #for i in xrange(index-int(n_Ranviers/2),index+int(n_Ranviers/2)): single_streamline_ROI_centered[loc_index, :] = A[i] loc_index = loc_index + 1 streamlines_ROI_centered.append(single_streamline_ROI_centered) if len(streamlines_ROI_centered) != len(streamlines_resampled): print("Failed to sample some axons!") raise SystemExit # from dipy.viz import ui, window # from dipy.viz import window, actor, colormap as cmap # from nibabel.streamlines.array_sequence import ArraySequence # # # stream_actor_dm = actor.line(streamlines_ROI_centered,[0.0,0.4470,0.7410]) #particular color # ren = window.Renderer() # #hdp # ren.add(stream_actor_dm) # #ren.add(seedroi_actor) # window.show(ren) '''streamlines_ROI_centered should already contain the position of Ranvier nodes. Now we get internodal compartments''' def normalized(a, axis=-1, order=2): l2 = np.atleast_1d(np.linalg.norm(a, order, axis)) l2[l2 == 0] = 1 return a / np.expand_dims(l2, axis) n_total = int(n_total) Array_coord = np.zeros((n_total, 3, len(streamlines_ROI_centered)), float) for inx_axn in range(len(streamlines_ROI_centered)): if axon_model == 'McIntyre2002': inx_comp = 0 for inx in range(n_Ranviers - 1): #the last node is not included Array_coord[inx_comp, :, inx_axn] = streamlines_ROI_centered[inx_axn][inx] if diam_fib >= 5.7: Array_coord[inx_comp + 11, :, inx_axn] = streamlines_ROI_centered[inx_axn][ inx + 1] internodal_vector = Array_coord[ inx_comp + 11, :, inx_axn] - Array_coord[inx_comp, :, inx_axn] else: Array_coord[inx_comp + 8, :, inx_axn] = streamlines_ROI_centered[inx_axn][ inx + 1] internodal_vector = Array_coord[ inx_comp + 8, :, inx_axn] - Array_coord[inx_comp, :, inx_axn] #internodal_vector_normalized=preprocessing.normalize(internodal_vector,norm='l2') internodal_vector_normalized = normalized(internodal_vector) loc_pos = 0.0 if diam_fib >= 5.7: for inx_loc in np.arange( 1, n_comp ): #only internodal compartments. The distances will be computed from the node of Ranvier using loc_pos inx_loc = int(inx_loc) if inx_loc == 1: loc_pos = (ranvier_length + para1_length) / 2 if inx_loc == 2 or inx_loc == 10: loc_pos = loc_pos + (para1_length + para2_length) / 2 if inx_loc == 3 or inx_loc == 9: loc_pos = loc_pos + (para2_length + inter_length) / 2 if inx_loc == 4 or inx_loc == 5 or inx_loc == 6 or inx_loc == 7 or inx_loc == 8: loc_pos = loc_pos + ( inter_length) / 1 #switch to mm from µm #print(inx_comp,inx_loc,inx_axn) Array_coord[inx_comp + inx_loc, 0, inx_axn] = Array_coord[ inx_comp, 0, inx_axn] + loc_pos * internodal_vector_normalized[ 0][0] Array_coord[inx_comp + inx_loc, 1, inx_axn] = Array_coord[ inx_comp, 1, inx_axn] + loc_pos * internodal_vector_normalized[ 0][1] Array_coord[inx_comp + inx_loc, 2, inx_axn] = Array_coord[ inx_comp, 2, inx_axn] + loc_pos * internodal_vector_normalized[ 0][2] inx_comp = inx_comp + 11 if diam_fib < 5.7: for inx_loc in np.arange( 1, n_comp ): #only internodal compartments. The distances will be computed from the node of Ranvier using loc_pos if inx_loc == 1: loc_pos = (ranvier_length + para1_length) / 2 if inx_loc == 2 or inx_loc == 7: loc_pos = loc_pos + (para1_length + para2_length) / 2 if inx_loc == 3 or inx_loc == 6: loc_pos = loc_pos + (para2_length + inter_length) / 2 if inx_loc == 4 or inx_loc == 5: loc_pos = loc_pos + ( inter_length) / 1 #switch to mm from µm inx_loc = int(inx_loc) Array_coord[inx_comp + inx_loc, 0, inx_axn] = Array_coord[ inx_comp, 0, inx_axn] + loc_pos * internodal_vector_normalized[ 0][0] Array_coord[inx_comp + inx_loc, 1, inx_axn] = Array_coord[ inx_comp, 1, inx_axn] + loc_pos * internodal_vector_normalized[ 0][1] Array_coord[inx_comp + inx_loc, 2, inx_axn] = Array_coord[ inx_comp, 2, inx_axn] + loc_pos * internodal_vector_normalized[ 0][2] inx_comp = inx_comp + 8 elif axon_model == 'Reilly2016': inx_comp = 0 for inx in range(n_Ranviers - 1): #the last node is not included Array_coord[inx_comp, :, inx_axn] = streamlines_ROI_centered[inx_axn][inx] Array_coord[inx_comp + 2, :, inx_axn] = streamlines_ROI_centered[inx_axn][inx + 1] internodal_vector = Array_coord[ inx_comp + 2, :, inx_axn] - Array_coord[inx_comp, :, inx_axn] internodal_vector_normalized = normalized(internodal_vector) # we need only loc_pos = node_step * 0.5 Array_coord[inx_comp + 1, 0, inx_axn] = Array_coord[ inx_comp, 0, inx_axn] + loc_pos * internodal_vector_normalized[0][0] Array_coord[inx_comp + 1, 1, inx_axn] = Array_coord[ inx_comp, 1, inx_axn] + loc_pos * internodal_vector_normalized[0][1] Array_coord[inx_comp + 1, 2, inx_axn] = Array_coord[ inx_comp, 2, inx_axn] + loc_pos * internodal_vector_normalized[0][2] inx_comp = inx_comp + 2 # #np.savetxt('Array_coord.csv', Array_coord, delimiter=" ") Array_coord_platform = np.zeros( (n_total * len(streamlines_ROI_centered), 3), float) Array_coord_colored = np.zeros( (n_total * len(streamlines_ROI_centered), 4), float) glob_ind = 0 for axon_index in range(len(streamlines_ROI_centered)): Array_coord_platform[glob_ind:glob_ind + n_total, :] = Array_coord[:, :, axon_index] Array_coord_colored[glob_ind:glob_ind + n_total, :3] = Array_coord[:, :, axon_index] Array_coord_colored[ glob_ind:glob_ind + n_total, 3] = axon_index + 1 # because in Matlab they start from 1 glob_ind = glob_ind + n_total #name_of_directory+'/'+projection_name+ np.savetxt(name_of_directory + '/' + 'Array_coord_colored_' + projection_name + '.csv', Array_coord_colored, delimiter=" ") np.savetxt(name_of_directory + '/' + 'Array_coord_' + projection_name + '.csv', Array_coord_platform, delimiter=" ") #np.savetxt('Array_coord_colored_'+name_of_fiber_file+'.csv', Array_coord_colored, delimiter=" ") #np.savetxt('Array_coord_'+name_of_fiber_file+'.csv', Array_coord_platform, delimiter=" ") #hf = h5py.File(name_of_combined_file + '.h5', 'a') #hf = h5py.File(name_of_directory+'/'+name_of_combined_file + '.h5', 'a') #hf.create_dataset(projection_name, data=Array_coord_platform) #hf.close() #let's save it in /opt/Patient/ hf = h5py.File('/opt/Patient/' + name_of_combined_file + '.h5', 'a') hf.create_dataset(projection_name, data=Array_coord_platform) hf.close() from scipy.io import savemat mdic = {"fibers": Array_coord_colored, "ea_fibformat": "1.0"} savemat( name_of_directory + '/' + name_of_combined_file + '_' + projection_name + "_axons.mat", mdic) return int(n_Ranviers)
def run_simulation_with_NEURON(last_point, population_index, fib_diam, dt, tstop, n_Ranvier, N_models, v_init, t_steps, Ampl_scale, n_processors): # this script is solely for McIntyre2002 model '''Here we assume that all axons have the same number of nodes of Ranvier (and hence the length) and the morphology''' n_pulse = 1 # we always simulate only one pulse from DBS. If need more, we should just copy the array and make sure the time vectors are in order param_ax = {'centered': True, 'diameter': fib_diam} ax = Axon(param_ax) axon_dict = Axon.get_axonparams(ax) paranodes1 = axon_dict["para1_nodes"] * (n_Ranvier - 1) / (21 - 1) paranodes2 = axon_dict["para2_nodes"] * (n_Ranvier - 1) / (21 - 1) if axon_dict["fiberD"] > 3.0: axoninter = (n_Ranvier - 1) * 6 else: axoninter = (n_Ranvier - 1) * 3 n_segments = int(n_Ranvier + paranodes1 + paranodes2 + axoninter) #passing through n.h. does not work sometimes, so we do insert the parameters straight to the file paste_to_hoc_python3( n_Ranvier, paranodes1, paranodes2, axoninter, n_segments, v_init, axon_dict["fiberD"], axon_dict["para1_length"], axon_dict["para2_length"], axon_dict["ranvier_length"], axon_dict["node_diameter"], axon_dict["axon_diameter"], axon_dict["para1_diameter"], axon_dict["para2_diameter"], axon_dict["deltax"], axon_dict["lamellas"], int(1.0 / dt)) os.chdir("..") if population_index == -1: # only one population is simulated population_name = '' Vert_full_get = read_csv('Neuron_model_arrays/All_neuron_models.csv', delimiter=' ', header=None) # get all neuron models Vert_full = Vert_full_get.values Vert_full = np.round(Vert_full, 8) Vert_get = read_csv( 'Neuron_model_arrays/Vert_of_Neural_model_NEURON.csv', delimiter=' ', header=None) # get only physiologically correct neuron models Vert = Vert_get.values Vert = np.round(Vert, 8) else: hf = h5py.File( 'Neuron_model_arrays/All_neuron_models_by_populations.h5', 'r') lst = list(hf.keys()) if N_models == 0: print(str(lst[population_index]) + " population was not placed") return 0 population_name = str(lst[population_index]) + '/' Vert_full = hf.get(lst[population_index]) Vert_full = np.array(Vert_full) hf.close() Vert_full = np.round(Vert_full, 8) hf2 = h5py.File( 'Neuron_model_arrays/Vert_of_Neural_model_NEURON_by_populations.h5', 'r') lst = list(hf2.keys()) Vert = hf2.get(lst[population_index]) Vert = np.array(Vert) hf2.close() Vert = np.round(Vert, 8) # #only if we want to save potential in time on axons # if not os.path.isdir('Field_on_axons_in_time/'+str(lst[population_index])+'/'): # os.makedirs('Field_on_axons_in_time/'+str(lst[population_index])) Nodes_status = np.zeros( (N_models * n_segments, 4), float ) #Nodes_status will contain info whether the placed(!) axon was activated Nodes_status[:, :3] = Vert[:, :] List_of_activated = [] List_of_not_activated = [] Activated_models = 0 int_counter = 0 Neuron_index = 0 neuron_global_index_array = np.zeros((N_models), int) os.chdir("Axon_files/") # run NEURON simulation in parallel while Neuron_index < N_models: proc = [] j_proc = 0 #counter for processes output = mp.Queue() while j_proc < n_processors and Neuron_index < N_models: first_axon_point = np.array([ Vert[Neuron_index * n_segments, 0], Vert[Neuron_index * n_segments, 1], Vert[Neuron_index * n_segments, 2] ]) second_axon_point = np.array([ Vert[Neuron_index * n_segments + 1, 0], Vert[Neuron_index * n_segments + 1, 1], Vert[Neuron_index * n_segments + 1, 2] ]) last_axon_point = np.array([ Vert[Neuron_index * n_segments + n_segments - 1, 0], Vert[Neuron_index * n_segments + n_segments - 1, 1], Vert[Neuron_index * n_segments + n_segments - 1, 2] ]) inx_first = np.flatnonzero( (Vert_full == first_axon_point).all(1)) # Finally get indices inx_second = np.flatnonzero( (Vert_full == second_axon_point).all(1)) # Finally get indices inx_last = np.flatnonzero( (Vert_full == last_axon_point).all(1)) # Finally get indices #assuming we do not have axons that start (first two points) and end in the same points for j in inx_first: for j_second in inx_second: if j_second - j == 1: for j_last in inx_last: if j_last - j == n_segments - 1: inx_first_true = j break neuron_global_index_array[Neuron_index] = int( inx_first_true / n_segments) #index in Prepared_models_full processes = mp.Process( target=conduct_parallel_NEURON, args=(population_name, last_point, neuron_global_index_array[Neuron_index], Neuron_index, Ampl_scale, t_steps, n_segments, dt, tstop, n_pulse, v_init, output)) proc.append(processes) j_proc = j_proc + 1 Neuron_index = Neuron_index + 1 for p in proc: p.start() for p in proc: p.join() #returns list, where activated models have corresponding numbers, others have -1 Activated_numbers = [output.get() for p in proc] for n_mdls in Activated_numbers: #n_mdls is list[N_glob,N_loc]! if n_mdls[1] != -1: Nodes_status[n_segments * n_mdls[1]:(n_segments * n_mdls[1] + n_segments), 3] = 1.0 Activated_models = Activated_models + 1 List_of_activated.append(n_mdls[0]) else: List_of_not_activated.append(int(n_mdls[0])) int_counter = int_counter + 1 os.chdir("..") Number_of_axons_initially = int(Vert_full.shape[0] / n_segments) Vert_full_status = np.zeros( Number_of_axons_initially, int ) # has status of all neurons (-1 - was not placed, 0 - was not activated, 1 - was activated) num_removed = 0 for axon_i in range(Number_of_axons_initially): if axon_i in List_of_activated: Vert_full_status[axon_i] = 1 elif axon_i in List_of_not_activated: Vert_full_status[axon_i] = 0 else: Vert_full_status[axon_i] = -1 #was removed num_removed = num_removed + 1 Axon_status = np.zeros( (N_models, 7), float ) #x1,y1,z1,x2,y2,z2,status. Holds info only about placed neurons. Important: coordinates are in the initial MRI space! [ Mx_mri, My_mri, Mz_mri, x_min, y_min, z_min, x_max, y_max, z_max, MRI_voxel_size_x, MRI_voxel_size_y, MRI_voxel_size_z ] = np.genfromtxt('MRI_DTI_derived_data/MRI_misc.csv', delimiter=' ') shift_to_MRI_space = np.array([x_min, y_min, z_min]) loc_ind_start = 0 for i in range(N_models): Axon_status[ i, :3] = Nodes_status[loc_ind_start, :3] + shift_to_MRI_space Axon_status[i, 3:6] = Nodes_status[loc_ind_start + n_segments - 1, :3] + shift_to_MRI_space Axon_status[i, 6] = Nodes_status[loc_ind_start, 3] loc_ind_start = loc_ind_start + n_segments print(Activated_models, " models were activated") List_of_activated = np.asarray(List_of_activated) if population_index == -1: print(np.round(Activated_models / float(N_models) * 100, 2), "% activation (subtracted axons do not count)\n") np.savetxt('Field_solutions/Activation/Last_run.csv', List_of_activated, delimiter=" ") np.save('Field_solutions/Activation/Connection_status', Axon_status) np.save('Field_solutions/Activation/Network_status', Vert_full_status) np.savetxt('Field_solutions/Activation/Neuron_model_results.csv', Nodes_status, delimiter=" ") else: print(np.round(Activated_models / float(N_models) * 100, 2), "% activation in ", lst[population_index], "(subtracted axons do not count)\n") np.savetxt('Field_solutions/Activation/Last_run_in_' + str(lst[population_index]) + '.csv', List_of_activated, delimiter=" ") np.save( 'Field_solutions/Activation/Connection_status_' + str(lst[population_index]), Axon_status) np.savetxt('Field_solutions/Activation/Neuron_model_results_' + str(lst[population_index]) + '.csv', Nodes_status, delimiter=" ") hf = h5py.File('Field_solutions/Activation/Network_status.h5', 'a') hf.create_dataset(str(lst[population_index]), data=Vert_full_status) hf.close() #this function will prepare data for connection states due to DBS if population_index != -1: connection_visualizator(Activated_models, Number_of_axons_initially, lst[population_index], last_point) return Activated_models
def cut_models_by_domain(d,Brain_shape_name,name_prepared_neuron_array): if Brain_shape_name=='Brain_substitute.brep': # load the brain approximation mesh_brain_sub = Mesh("/opt/Patient/Meshes/Mesh_brain_substitute_max_ROI.xml") if name_prepared_neuron_array[-4:]=='.csv': #if we have an array where all axons have the same length if d["Axon_Model_Type"] == 'McIntyre2002': param_ax={ 'centered':True, 'diameter':d["diam_fib"] } a=Axon(param_ax) nr=Axon.get_axonparams(a) n_comp=((nr["ranvier_nodes"]-1)+nr["inter_nodes"]+nr["para1_nodes"]+nr["para2_nodes"])/(nr["ranvier_nodes"]-1) n_segments=int((d["n_Ranvier"]-1)*n_comp+1) #overall number of points on Axon incl. internodal elif d["Axon_Model_Type"] == 'Reilly2016': n_comp=2 #only nodes and one internodal per segment n_segments=int((d["n_Ranvier"]-1)*n_comp+1) else: print("The neuron model "+str(d["Axon_Model_Type"])+" is not implemented, exiting") raise SystemExit Array_coord_get=read_csv('/opt/Patient/'+name_prepared_neuron_array, delimiter=' ', header=None) # Array_coord_in_MRI=Array_coord_get.values if Brain_shape_name=='Brain_substitute.brep': n_models_before=int(Array_coord_in_MRI.shape[0]/n_segments) print("Initial number of neuron models: ",n_models_before) points_outside=0 for inx in range(Array_coord_in_MRI.shape[0]): pnt=Point(Array_coord_in_MRI[inx,0],Array_coord_in_MRI[inx,1],Array_coord_in_MRI[inx,2]) if not(mesh_brain_sub.bounding_box_tree().compute_first_entity_collision(pnt)<mesh_brain_sub.num_cells()*100): #if one point of the neural model is absent, the whole model is subtracted points_outside=points_outside+1 inx_start=int(inx/n_segments)*n_segments Array_coord_in_MRI[inx_start:inx_start+n_segments,:]=-100000000.0 Array_coord_in_MRI=Array_coord_in_MRI[~np.all(Array_coord_in_MRI==-100000000.0,axis=1)] #deletes all zero enteries n_models_after=int(Array_coord_in_MRI.shape[0]/n_segments) print(n_models_before-n_models_after, " models were outside of the approximating geometrical domain") Array_coord_in_MRI=np.round(Array_coord_in_MRI,8) np.savetxt('/opt/Patient/Neuron_model_arrays/Prepared_models_full_filtered.csv', Array_coord_in_MRI, delimiter=" ") del Array_coord_in_MRI return True if name_prepared_neuron_array[-3:]=='.h5': if not isinstance(d["diam_fib"],list): d["diam_fib"]=[d["diam_fib"]] d["n_Ranvier"]=[d["n_Ranvier"]] diam_of_populations=d["diam_fib"] hf = h5py.File('/opt/Patient/'+name_prepared_neuron_array, 'r') lst=list(hf.keys()) population_index=0 n_segments_fib_diam_array=np.zeros((len(lst),2),float) #colums are n_segments and fib_diam for i in lst: Array_coord_in_MRI=hf.get(i) Array_coord_in_MRI=np.array(Array_coord_in_MRI) if d["Axon_Model_Type"] == 'McIntyre2002': param_ax={ 'centered':True, 'diameter':diam_of_populations[population_index] } a=Axon(param_ax) nr=Axon.get_axonparams(a) n_comp=((nr["ranvier_nodes"]-1)+nr["inter_nodes"]+nr["para1_nodes"]+nr["para2_nodes"])/(nr["ranvier_nodes"]-1) n_segments=int((d["n_Ranvier"][population_index]-1)*n_comp+1) #overall number of points on Axon incl. internodal elif d["Axon_Model_Type"] == 'Reilly2016': n_comp=2 #only nodes and one internodal per segment n_segments=int((d["n_Ranvier"][population_index]-1)*n_comp+1) else: print("The neuron model "+str(d["Axon_Model_Type"])+" is not implemented, exiting") raise SystemExit n_segments_fib_diam_array[population_index,0]=n_segments n_segments_fib_diam_array[population_index,1]=diam_of_populations[population_index] if Brain_shape_name=='Brain_substitute.brep': # cut models if use brain approximation n_models_before=int(Array_coord_in_MRI.shape[0]/n_segments) print("Initial number of neuron models in",str(i),": ",n_models_before) points_outside=0 for inx in range(Array_coord_in_MRI.shape[0]): pnt=Point(Array_coord_in_MRI[inx,0],Array_coord_in_MRI[inx,1],Array_coord_in_MRI[inx,2]) if not(mesh_brain_sub.bounding_box_tree().compute_first_entity_collision(pnt)<mesh_brain_sub.num_cells()*100): #if one point of the neural model is absent, the whole model is disabled points_outside=points_outside+1 inx_start=int(inx/n_segments)*n_segments Array_coord_in_MRI[inx_start:inx_start+n_segments,:]=-100000000.0 Array_coord_in_MRI=Array_coord_in_MRI[~np.all(Array_coord_in_MRI==-100000000.0,axis=1)] #deletes all -10000000 enteries n_models_after=int(Array_coord_in_MRI.shape[0]/n_segments) if int(n_models_before-n_models_after)!=0: print("In ",str(i), n_models_before-n_models_after, " models were outside of the approximating geometrical domain") Array_coord_in_MRI=np.round(Array_coord_in_MRI,8) hf2 = h5py.File('/opt/Patient/Neuron_model_arrays/Prepared_models_full_filtered.h5', 'a') hf2.create_dataset(i, data=Array_coord_in_MRI) hf2.close() population_index=population_index+1 hf.close() '''Here the meta data is different as we have different structure of the input array''' np.save('/opt/Patient/Neuron_model_arrays/Neuron_populations_misc', n_segments_fib_diam_array) return True
def build_neuron_models(d,MRI_param): if d["Global_rot"]==1: # for VTA #center node of the center neuron is located at the seed (the seeding coordinate is in the positive octant space) x_seeding=MRI_param.x_shift+d["x_seed"] y_seeding=MRI_param.y_shift+d["y_seed"] z_seeding=MRI_param.z_shift+d["z_seed"] #number of models, seeded in one plane. This parameter is 0 by default in Neuron_info class N_models_in_plane=(d["x_steps"]+1)*(d["y_steps"]+1)*(d["z_steps"]+1) [X_coord_old,Y_coord_old,Z_coord_old]=create_structured_array(d) X_coord=[xs+x_seeding for xs in X_coord_old] Y_coord=[ys+y_seeding for ys in Y_coord_old] Z_coord=[zs+z_seeding for zs in Z_coord_old] else: # manual allocation X_coord=[xs+MRI_param.x_shift for xs in d["X_coord_old"]] Y_coord=[ys+MRI_param.y_shift for ys in d["Y_coord_old"]] Z_coord=[zs+MRI_param.z_shift for zs in d["Z_coord_old"]] N_models_in_plane=0 #not need for this method #get morphology depending on the neuron model if d["Axon_Model_Type"] == 'McIntyre2002': param_ax={ 'centered':True, 'diameter':d["diam_fib"] } a=Axon(param_ax) nr=Axon.get_axonparams(a) param_axon=[nr["ranvier_nodes"], nr["para1_nodes"], nr["para2_nodes"], nr["inter_nodes"], nr["ranvier_length"], nr["para1_length"], nr["para2_length"], nr["inter_length"], nr["deltax"], d["diam_fib"]] elif d["Axon_Model_Type"] == 'Reilly2016': # lumped internodal compartments if d["diam_fib"]>=5.0 and d["diam_fib"]<=10.0: # if I understand correctly, this is the only parameter that is influenced by the change of the diameter in Reilly2016 by Carnevale internodel_length=d["diam_fib"]*200.0 # from 1 to 2 mm param_axon=[d["n_Ranvier"], 0, 0, d["n_Ranvier"]-1, 0.0, 0.0, 0.0, 0.0, internodel_length, d["diam_fib"]] else: print("Wrong fiber diameter for Reilly2016, exiting") raise SystemExit else: print("The neuron model "+str(d["Axon_Model_Type"])+" is not implemented, exiting") raise SystemExit if d["pattern_model_name"]==0: #we can build axon model pattern pattern_model_name=('pattern.csv') # name with .csv, angle in rad n_segments=generate_pattern_model(pattern_model_name,d["n_Ranvier"],param_axon,d["Axon_Model_Type"]) else: pattern_model_name=d["pattern_model_name"] # or get a pattern from the external file Array_coord_load_get=read_csv(pattern_model_name, delimiter=' ', header=None) Array_coord_load=Array_coord_load_get.values n_segments=Array_coord_load.shape[0] #all segments should be in the pattern model del Array_coord_load Neuron_param=Neuron_info(pattern_model_name,X_coord,Y_coord,Z_coord,d["YZ_angles"],d["ZX_angles"],d["XY_angles"],d["alpha_array_glob"],d["beta_array_glob"],d["gamma_array_glob"],N_models_in_plane) with open('/opt/Patient/Neuron_model_arrays/Neuron_param_class.file', "wb") as f: pickle.dump(Neuron_param, f, pickle.HIGHEST_PROTOCOL) # implantation coordinated in the positive octant space Xt_new=MRI_param.x_shift+d["Implantation_coordinate_X"] Yt_new=MRI_param.y_shift+d["Implantation_coordinate_Y"] Zt_new=MRI_param.z_shift+d["Implantation_coordinate_Z"] "definition of ROI is required for adaptive mesh refinement. ROI is a sphere encompassing all neuron models" ROI_radius=get_neuron_models_dims(d["Neuron_model_array_prepared"],Xt_new,Yt_new,Zt_new,Neuron_param,param_axon,d["Global_rot"]) if d["Axon_Model_Type"] == 'McIntyre2002': Neuron_model_misc=np.array([nr["ranvier_nodes"], nr["para1_nodes"], nr["para2_nodes"], nr["inter_nodes"], nr["ranvier_length"], nr["para1_length"], nr["para2_length"], nr["inter_length"], nr["deltax"],d["diam_fib"],d["n_Ranvier"],ROI_radius,n_segments]) elif d["Axon_Model_Type"] == 'Reilly2016': Neuron_model_misc=np.array([d["n_Ranvier"], 0, 0, d["n_Ranvier"]-1, 0.0, 0.0, 0.0, 0.0, internodel_length,d["diam_fib"],d["n_Ranvier"],ROI_radius,n_segments]) '''Save meta data for the future simulations with the current Neuron model data set''' np.savetxt('/opt/Patient/Neuron_model_arrays/Neuron_model_misc.csv', Neuron_model_misc, delimiter=" ") print("Initial neuron models and corresponding meta data were created\n") return Neuron_param,param_axon,ROI_radius,n_segments