Changes for page Code description

Last modified by galluzziandrea on 2022/06/20 12:33

From version 4.1
edited by galluzziandrea
on 2021/12/09 14:38
Change comment: There is no comment for this version
To version 10.1
edited by galluzziandrea
on 2021/12/09 15:05
Change comment: There is no comment for this version

Summary

Details

Page properties
Content
... ... @@ -1,8 +1,8 @@
1 -== Introduction (path and modules) ==
1 +== Introduction (path and modules): ==
2 2  
3 3  First of all we check the path and import the necessary modules .
4 4  
5 -=== Check where I am and place myself in the right folder : ===
5 +=== Check where I am and place myself in the right folder: ===
6 6  
7 7  {{code language="python"}}
8 8  # Import the os module
... ... @@ -18,7 +18,7 @@
18 18  print("Current working directory: {0}".format(os.getcwd()))
19 19  {{/code}}
20 20  
21 -=== import the modules necessary for the simulation ===
21 +=== Import the modules necessary for the simulation: ===
22 22  
23 23  {{code language="python"}}
24 24  import nest
... ... @@ -34,6 +34,488 @@
34 34  
35 35  === ===
36 36  
37 -==== Results ====
37 +=== Define necessary classes to import the Initialization Files: ===
38 38  
39 +{{code language="python" title=" "}}
40 +class ImportIniLIFCA():
41 + #initialize the information to look for in perseo.ini
42 + inf=["NeuronType", #still fixed value
43 + "DelayDistribType", #still fixed value
44 + "SynapticExtractionType", #still fixed value
45 + "Life"]
46 +
47 + def __init__(self,files):
48 + self.files=files
49 +
50 + def FilesControllo(self):
51 + import sys
52 + for i in range(0,len(self.files)):
53 + if self.FileControllo(self.files[i]):
54 + sys.exit(0)
55 +
56 + def FileControllo(self,file1):
57 + try:
58 + f1=open(file1,"r")
59 + f1.close()
60 + return 0
61 + except ValueError:
62 + print("ValueError")
63 + return 1
64 + except IOError as err:
65 + print("OS error: {0}".format(err))
66 + return 1
67 + except:
68 + print("Unexpected error:", sys.exc_info()[0])
69 + return 1
70 +
71 + def Estrai_inf(self,stampa=0):
72 +
73 + InfoPerseo=self.EstraiInfoPerseo() #extract info from perseo.ini
74 + AppoggioTempM=self.EstraiInfoModuli() #extract info from modules.ini
75 + AppoggioTempC=self.EstraiInfoConnectivity() #extract info from connectivity.ini
76 + AppoggioTempP=self.EstraiProtocol() #extract info from protocol.ini
77 +
78 + def getKey(item):
79 + return item[0]
80 + InfoProtocol=AppoggioTempP
81 + # I convert the extracted information into a suitable format from tuple to list
82 +
83 + InfoBuildT=[AppoggioTempM[0]]
84 + for i in range(0,AppoggioTempM[0]):
85 + app1=[int(AppoggioTempM[2][i][0])]
86 + app=(app1+list(AppoggioTempM[2][i][3:9])+list(AppoggioTempM[2][i][12])+list(AppoggioTempM[2][i][9:12]))
87 + InfoBuildT.append(app)
88 + del app
89 +
90 + InfoBuild=[float(InfoBuildT[0])]
91 + for i in range(0,int(InfoBuildT[0])):
92 + app=[]
93 + for j in range(0,11):
94 + app.append(float(InfoBuildT[i+1][j]))
95 + InfoBuild=InfoBuild+[app]
96 + del app
97 +
98 + InfoConnectPop=[AppoggioTempM[0]]
99 + for i in range(0,len(AppoggioTempC[1][:])):
100 + app=list(AppoggioTempC[1][i])
101 + InfoConnectPop.append(app)
102 + del app
103 +
104 + InfoConnectNoise=[AppoggioTempM[0]]
105 + for i in range(0,AppoggioTempM[0]):
106 + app=list(AppoggioTempM[2][i][1:3])
107 + InfoConnectNoise.append(app)
108 +
109 +
110 + if stampa==1: #Print on screen of saved data
111 + for i,j in enumerate(InfoPerseo):
112 + print(self.inf[i],"=",j)
113 + print("\n")
114 + print("the network consists of ", AppoggioTempM[0], " neuronal population" )
115 + print(AppoggioTempM[1])
116 + for i in range(0,AppoggioTempM[0]):
117 + print(AppoggioTempM[2][i])
118 + print("\n")
119 + print(AppoggioTempC[0])
120 + for i in range(0,AppoggioTempM[0]**2):
121 + print(AppoggioTempC[1][i])
122 + print("\n")
123 + for i in InfoProtocol:
124 + print("SET_PARAM"+str(i))
125 +
126 +
127 + return InfoPerseo,InfoBuild,InfoConnectPop,InfoConnectNoise,InfoProtocol
128 +
129 + def EstraiProtocol(self):
130 + import string
131 + f1=open(self.files[3],"r")
132 + ProtocolList= []
133 + for x in f1.readlines():
134 + y=x.split()
135 + if len(y):
136 + if x[0]!="#" and y[0]=="SET_PARAM":
137 + try:
138 + ProtocolList.append([float(y[1]),int(y[2]),float(y[3]),float(y[4])])
139 + except ValueError:
140 + pass
141 + f1.close()
142 + return ProtocolList
143 +
144 + def EstraiInfoPerseo(self):
145 + import string
146 + f1=open(self.files[0],"r")
147 + InfList= []
148 + for x in f1.readlines():
149 + y=x.split()
150 + if len(y):
151 + if x[0]!="#":
152 + for findinf in self.inf:
153 + try:
154 + temp=y.index(findinf)
155 + InfList.append(y[temp+2])
156 + except ValueError:
157 + pass
158 + f1.close()
159 + return InfList
160 +
161 + def EstraiInfoModuli(self):
162 + import string
163 + f1=open(self.files[2],"r")
164 + NumPop=0
165 + for i,x in enumerate(f1.readlines()):
166 + y=x.split()
167 + if len(y):
168 + if x[0]!="#":
169 + NumPop=NumPop+1
170 + if i==2:
171 + ParamList=[]
172 + for j in range(1,14):
173 + ParamList.append(y[j])
174 + f1.close()
175 + PopsParamList=[]
176 + f1=open(self.files[2],"r")
177 + x=f1.readlines()
178 + for j in range(0,NumPop):
179 + appo=x[4+j];
180 + PopsParamList.append(appo.split())
181 + f1.close()
182 + return NumPop,ParamList,PopsParamList
183 +
184 + def EstraiInfoConnectivity(self):
185 + import string
186 + f1=open(self.files[1],"r")
187 + PopConParamList=[]
188 + for i,x in enumerate(f1.readlines()):
189 + y=x.split()
190 + if len(y):
191 + if x[0]!="#":
192 + PopConParamList.append(y)
193 + if i==1:
194 + ParamList=[]
195 + for j in range(1,9):
196 + ParamList.append(y[j])
197 + f1.close()
198 + return ParamList,PopConParamList
199 +{{/code}}
200 +
201 +=== Import the initialization files: ===
202 +
203 +in this section we...
204 +
205 +{{code language="python"}}
206 +Salva=1
207 +file1="perseo35.ini"
208 +file2="c_cortsurf_Pot1.43PotStr148v3.ini"
209 +file3="m_cortsurf_Pot1.43.ini"
210 +file4="ProtocolExploration36.ini"
211 +files=[file1,file2,file3,file4]
212 +#define the name of the Output file
213 +FileName="dati/Rates_Nest_Run_Milano_Test36_13x13_"+str(nest.Rank())+"_Pot1.43PotStr148v3Long3.dat"
214 +#check the existence of the files being read
215 +ImpFil=ImportIniLIFCA(files);
216 +ImpFil.FilesControllo()
217 +
218 +#extract the information of interest from the files.ini and transfer them to the files:
219 +#InfoPerseo,InfoBuild,InfoConnectPop,InfoConnectNoise
220 +
221 +stampa=0; #stampa=1 print output simulation data on screen stampa=0 dont
222 +InfoPerseo,InfoBuild,InfoConnectPop,InfoConnectNoise,InfoProtocol=ImpFil.Estrai_inf(stampa)
223 +
224 +# InfoPerseo=["NeuronType","DelayDistribType","SynapticExtractionType","Life" ]
225 +# InfoBuild=[numero di popolazioni,
226 +# [N,C_ext,\nu_ext,\tau,\tetha,H,\tau_arp,NeuronInitType,\alpha_c,\tau_c,g_c],
227 +# [.....],[],...]
228 +# InfoConnectPop=[numero di popolazioni,
229 +# [post,pre,c,Dmin,Dmax,syn typ,J,DJ],
230 +# [.....],[],...]
231 +# InfoConnectNoise=[numero di popolazioni,
232 +# [J_ext,DJ_ext],
233 +# [.....],[],...]
234 +# InfoProtocol=[[time,population,param_num,value],
235 +# [.....],[],...]
236 +{{/code}}
237 +
238 +=== Defining general and nest.kernel parameters ===
239 +
240 +{{code language="python"}}
241 +#############################------------------------------------------------------------------------
242 +#Clean the Network
243 +#############################------------------------------------------------------------------------
244 +nest.ResetKernel()
245 +
246 +#############################------------------------------------------------------------------------
247 +#insert the introductory parameters of the simulation
248 +#############################------------------------------------------------------------------------
249 +
250 +
251 +dt = 0.1 # the resolution in ms
252 +StartMisure=0. # start time of measurements
253 +simtime = int(float(InfoPerseo[3])) # Simulation time in ms (200 s)
254 +if simtime<=StartMisure: # If the simulation time is less than StartMisure, it is increased by StartMisure
255 + simtime=simtime+StartMisure
256 +start=0.0 # start time of poissonian processes
257 +origin=0.0 # temporal origin
258 +
259 +#############################------------------------------------------------------------------------
260 +# Kernel parameters
261 +#############################------------------------------------------------------------------------
262 +LNT=multiprocessing.cpu_count();
263 +nest.SetKernelStatus({"local_num_threads": LNT})
264 +nest.SetKernelStatus({"resolution": dt, "print_time": True,
265 + "overwrite_files": True})
266 +
267 +#############################------------------------------------------------------------------------
268 +#"randomize" the seeds of the random generators
269 +#############################------------------------------------------------------------------------
270 +
271 +#msd = int(math.fabs(time.process_time()*1000))
272 +#N_vp = nest.GetKernelStatus(['total_num_virtual_procs'])[0]
273 +#pyrngs = [numpy.random.RandomState(s) for s in range(msd, msd+N_vp)]
274 +#nest.SetKernelStatus({"grng_seed" : msd+N_vp})
275 +#nest.SetKernelStatus({"rng_seeds" : list(range(msd+N_vp+1, msd+2*N_vp+1))})
276 +{{/code}}
277 +
278 +=== Building the network: neuronal populations , Poisson processes and spike detectors ===
279 +
280 +{{code language="python"}}
281 +#############################------------------------------------------------------------------------
282 +print("Building network")
283 +#############################------------------------------------------------------------------------
284 +
285 +startbuild = time.time() #initialize the calculation of the time used to simulate
286 +
287 +NeuronPop=[]
288 +NoisePop=[]
289 +DetectorPop=[]
290 +
291 +#define and initialize the populations of neurons with the parameters extracted from the.ini files
292 +for i in range(1,int(InfoBuild[0])+1):
293 + if int(InfoBuild[i][7])==0:
294 + app=float(InfoBuild[i][5])
295 + else:
296 + app=0.
297 + app2= nest.Create("aeif_psc_exp", int(InfoBuild[i][0]),params={"C_m": 1.0,
298 + "g_L": 1.0/float(InfoBuild[i][3]),
299 + "t_ref": float(InfoBuild[i][6]),
300 + "E_L": 0.0,
301 + "V_reset": float(InfoBuild[i][5]),
302 + "V_m": app,
303 + "V_th": float(InfoBuild[i][4]),
304 + "Delta_T": 0.,
305 + "tau_syn_ex": 1.0,
306 + "tau_syn_in": 1.0,
307 + "a": 0.0,
308 + "b": float(InfoBuild[i][10]),
309 + "tau_w": float(InfoBuild[i][9]),
310 + "V_peak":float(InfoBuild[i][4])+10.0})
311 + NeuronPop.append(app2)
312 +
313 +#define and initialize the poisson generators and the spike detectors with the parameters extracted from the.ini files
314 +
315 +for i in range(1,int(InfoBuild[0])+1):
316 + app3= nest.Create("poisson_generator",params={"rate": float(InfoBuild[i][1]*InfoBuild[i][2]),
317 + 'origin':0.,
318 + 'start':start})
319 + NoisePop.append(app3)
320 + app4 = nest.Create("spike_recorder",params={ "start":StartMisure})
321 + DetectorPop.append(app4)
322 +
323 +endbuild = time.time()
324 +{{/code}}
325 +
326 +=== Connecting the network nodes: neuronal populations, Poisson processes and spike detectors ===
327 +
328 +{{code language="python"}}
329 +#############################------------------------------------------------------------------------
330 +print("Connecting ")
331 +#############################------------------------------------------------------------------------
332 +
333 +startconnect = time.time()
334 +Connessioni=[]
335 +Medie=[]
336 +
337 +#create and define the connections between the populations of neurons and the poisson generators
338 +#and between the populations of neurons and the spike detectors with the parameters extracted from the.ini files
339 +
340 +for i in range(0,int(InfoBuild[0])):
341 + nest.Connect(NoisePop[i], NeuronPop[i], syn_spec={'synapse_model': 'static_synapse_hpc',
342 + 'delay': dt,
343 + 'weight': nest.math.redraw(nest.random.normal(mean=float(InfoConnectNoise[i+1][0]),
344 + std=(float(InfoConnectNoise[i+1][1])*float(InfoConnectNoise[i+1][0]))),
345 + min=0., max=float('Inf'))
346 + })
347 + nest.Connect(NeuronPop[i][:int(InfoBuild[i+1][0])], DetectorPop[i], syn_spec={"weight": 1.0, "delay": dt})
348 +
349 +#create and define the connections between the populations of neurons with the parameters extracted from the.ini files
350 +
351 +for i in range(0,len(InfoConnectPop[1:])):
352 +
353 + conn=nest.Connect(NeuronPop[int(InfoConnectPop[i+1][1])], NeuronPop[int(InfoConnectPop[i+1][0])],
354 + {'rule': 'pairwise_bernoulli',
355 + 'p':float(InfoConnectPop[i+1][2]) },
356 + syn_spec={'synapse_model': 'static_synapse_hpc',
357 + 'delay':nest.math.redraw(nest.random.exponential(beta=float(1./(2.99573227355/(float(InfoConnectPop[i+1][4])-float(InfoConnectPop[i+1][3]))))),
358 + min= numpy.max([dt,float(1./float(InfoConnectPop[i+1][4]))]),
359 + max= float(1./(float(InfoConnectPop[i+1][3])-dt/2))),
360 +
361 + 'weight':nest.random.normal(mean=float(InfoConnectPop[i+1][6]),
362 + std=math.fabs(float(InfoConnectPop[i+1][6])*float(InfoConnectPop[i+1][7])))})
363 +
364 +
365 +endconnect = time.time()
366 +{{/code}}
367 +
368 +=== ===
369 +
370 +=== ===
371 +
372 +=== Simulating: neuronal time evolution. ===
373 +
374 +=== ===
375 +
376 +{{code language="python"}}
377 + #############################------------------------------------------------------------------------
378 + print("Simulating")
379 + #############################------------------------------------------------------------------------
380 + ###################################################################################################################################################################
381 + if Salva:
382 + print("I m going to save the data")
383 + #x=str(iterazioni)
384 + f = open(FileName,"w")
385 + if len(InfoProtocol):
386 + print("I m going to split the simulation")
387 + tempo=0
388 + for contatore in range(0,len(InfoProtocol)):
389 + appoggio1=int((tempo+InfoProtocol[contatore][0])/1000.)
390 + appoggio2=int(tempo/1000.)
391 + appoggio3=tempo+InfoProtocol[contatore][0]
392 + if (appoggio1-appoggio2)>=1:
393 + T1=(1+appoggio2)*1000-tempo
394 + nest.Simulate(T1)
395 + #Save the Data!!!!
396 + ###########################################################
397 + Equilibri=[]
398 + for i in range(0,int(InfoBuild[0])):
399 + Equilibri.append([])
400 + a=nest.GetStatus(DetectorPop[i])[0]["events"]["times"]
401 + if len(a)>0:
402 + Trange=(1000*int(numpy.min(a)/1000.),1000*int(numpy.min(a)/1000.)+1000)
403 + hist,Tbin=numpy.histogram(a,200,(Trange[0],Trange[1]))
404 + Equilibri[i]=hist*1000./(5.*int(InfoBuild[i+1][0]))
405 + else:
406 + Trange=(1000*int(tempo/1000.),1000*int(tempo/1000.)+1000)
407 + hist=numpy.zeros(200)
408 + Tbin=numpy.linspace(Trange[0],Trange[1],num=201)
409 + Equilibri[i]=hist
410 + nest.SetStatus(DetectorPop[i],{'n_events':0})
411 + for j in range(0,len(hist)):
412 + f.write(str(Tbin[j])+" ")
413 + for i in range(0,int(InfoBuild[0])):
414 + f.write(str(Equilibri[i][j])+" ")
415 + f.write("\n ")
416 + ###########################################################
417 + tempo=tempo+T1
418 + for contatore2 in range(1,(appoggio1-appoggio2)):
419 + nest.Simulate(1000.)
420 + #Save the Data!!!!
421 + ###########################################################
422 + Equilibri=[]
423 + for i in range(0,int(InfoBuild[0])):
424 + Equilibri.append([])
425 + a=nest.GetStatus(DetectorPop[i])[0]["events"]["times"]
426 + if len(a)>0:
427 + Trange=(1000*int(numpy.min(a)/1000.),1000*int(numpy.min(a)/1000.)+1000)
428 + hist,Tbin=numpy.histogram(a,200,(Trange[0],Trange[1]))
429 + Equilibri[i]=hist*1000./(5.*int(InfoBuild[i+1][0]))
430 + else:
431 + Trange=(1000*int(tempo/1000.),1000*int(tempo/1000.)+1000)
432 + hist=numpy.zeros(200)
433 + Tbin=numpy.linspace(Trange[0],Trange[1],num=201)
434 + Equilibri[i]=hist
435 + nest.SetStatus(DetectorPop[i],{'n_events':0})
436 + for j in range(0,len(hist)):
437 + f.write(str(Tbin[j])+" ")
438 + for i in range(0,int(InfoBuild[0])):
439 + f.write(str(Equilibri[i][j])+" ")
440 + f.write("\n ")
441 + tempo=tempo+1000.
442 + T2=appoggio3-tempo
443 + nest.Simulate(T2);
444 + tempo=tempo+T2;
445 + else:
446 + nest.Simulate(InfoProtocol[contatore][0])
447 + temp=InfoProtocol[contatore][0]
448 + tempo=tempo+temp
449 + if InfoProtocol[contatore][2]==4:
450 + nest.SetStatus(NoisePop[InfoProtocol[contatore][1]],params={"rate": float(InfoBuild[1+InfoProtocol[contatore][1]][2]*InfoProtocol[contatore][3])})
451 + if InfoProtocol[contatore][2]==12:
452 + nest.SetStatus(NeuronPop[InfoProtocol[contatore][1]], params={"b": float(InfoProtocol[contatore][3])})
453 + else:
454 + nest.Simulate(simtime)
455 + tempo=simtime
456 + if (simtime-tempo)>0.:
457 + nest.Simulate(simtime-tempo)
458 +
459 +
460 + endsimulate = time.time()
461 + f.close()
462 + else:
463 + if len(InfoProtocol):
464 + tempo=0
465 + for contatore in range(0,len(InfoProtocol)):
466 + nest.Simulate(InfoProtocol[contatore][0])
467 + temp=InfoProtocol[contatore][0]
468 + tempo=tempo+temp
469 + if InfoProtocol[contatore][2]==4:
470 + nest.SetStatus(NoisePop[InfoProtocol[contatore][1]],params={"rate": float(InfoBuild[1+InfoProtocol[contatore][1]][2]*InfoProtocol[contatore][3])})
471 + #print "Population:", InfoProtocol[contatore][1] ,";Parameter:", InfoProtocol[contatore][2] ,"; Value: ",InfoProtocol[contatore][3]
472 + if InfoProtocol[contatore][2]==12:
473 + nest.SetStatus(NeuronPop[InfoProtocol[contatore][1]], params={"b": float(InfoProtocol[contatore][3])})
474 + #print "Population:", InfoProtocol[contatore][1] ,";Parameter:", InfoProtocol[contatore][2] ,"; Value: ",InfoProtocol[contatore][3]
475 +
476 + else:
477 + nest.Simulate(simtime)
478 + tempo=simtime
479 + if (simtime-tempo)>0.:
480 + nest.Simulate(simtime-tempo)
481 + endsimulate = time.time()
482 +
483 +
484 + ###################################################################################################################################################################
485 +
486 + #############################------------------------------------------------------------------------
487 + #print some information from the simulation
488 + #############################------------------------------------------------------------------------
489 +
490 + num_synapses = nest.GetDefaults('static_synapse_hpc')["num_connections"]
491 + build_time = endbuild - startbuild
492 + connect_time = endconnect - startconnect
493 + sim_time = endsimulate - endconnect
494 +
495 + N_neurons=0
496 + for i in range(0,int(InfoBuild[0])):
497 + N_neurons=N_neurons+int(InfoBuild[i+1][0])
498 +
499 + print(" Network simulation (Python) neuron type:",InfoPerseo[0])
500 + print("Number of neurons : {0}".format(N_neurons))
501 + print("Number of synapses: {0}".format(num_synapses))
502 + print("Building time : %.2f s" % build_time)
503 + print("Connecting time : %.2f s" % connect_time)
504 + print("Simulation time : %.2f s" % sim_time)
505 +
506 +Fine=time.time()
507 +print ("Total Simulation time : %.2f s" % (Fine-Inizio))
508 +{{/code}}
509 +
510 +=== ===
511 +
512 +=== Results: ===
513 +
514 +the output of this simulationo is...
515 +
516 +
517 +
518 +
519 +
520 +
39 39  ==== ====