Code description

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

Introduction (path and modules):

First of all we check the path and import the necessary modules .

Check where I am and place myself in the right folder:

# Import the os module
import os

#Print the current working directory
print("Current working directory: {0}".format(os.getcwd()))

# Change the current working directory
os.chdir('/mnt/user/shared/Slow waves in fading anesthesia/Nest3Python3')

# Print the current working directory
print("Current working directory: {0}".format(os.getcwd()))

Import the modules necessary for the simulation:

import nest
import time
from numpy import exp
import numpy
import math
import random
import multiprocessing
Inizio=time.time()
print('tempo di Inizio:',Inizio)

Define necessary classes to import the Initialization Files:

 
class ImportIniLIFCA():
   #initialize the information to look for in perseo.ini
    inf=["NeuronType",               #still fixed value 
        "DelayDistribType",         #still fixed value 
        "SynapticExtractionType",   #still fixed value 
        "Life"]
   
   def __init__(self,files):
       self.files=files
   
   def FilesControllo(self):
       import sys
       for i in range(0,len(self.files)):
           if self.FileControllo(self.files[i]):
                sys.exit(0)

   def FileControllo(self,file1):
       try:
            f1=open(file1,"r")
            f1.close()
           return 0
       except ValueError:
           print("ValueError")
           return 1
       except IOError as err:
           print("OS error: {0}".format(err))   
           return 1
       except:
           print("Unexpected error:", sys.exc_info()[0])
           return 1    
       
   def Estrai_inf(self,stampa=0):

        InfoPerseo=self.EstraiInfoPerseo()                   #extract info from  perseo.ini
        AppoggioTempM=self.EstraiInfoModuli()                #extract info from   modules.ini
        AppoggioTempC=self.EstraiInfoConnectivity()          #extract info from  connectivity.ini
        AppoggioTempP=self.EstraiProtocol()                  #extract info from  protocol.ini

       def getKey(item):
           return item[0]
        InfoProtocol=AppoggioTempP        
       # I convert the extracted information into a suitable format from tuple to list 
       
        InfoBuildT=[AppoggioTempM[0]]
       for i in range(0,AppoggioTempM[0]):
            app1=[int(AppoggioTempM[2][i][0])]
            app=(app1+list(AppoggioTempM[2][i][3:9])+list(AppoggioTempM[2][i][12])+list(AppoggioTempM[2][i][9:12]))
            InfoBuildT.append(app)
       del app    

        InfoBuild=[float(InfoBuildT[0])]
       for i in range(0,int(InfoBuildT[0])):
            app=[]
           for j in range(0,11):
                app.append(float(InfoBuildT[i+1][j]))
            InfoBuild=InfoBuild+[app]
       del app

        InfoConnectPop=[AppoggioTempM[0]]
       for i in range(0,len(AppoggioTempC[1][:])):
            app=list(AppoggioTempC[1][i])
            InfoConnectPop.append(app)
       del app

        InfoConnectNoise=[AppoggioTempM[0]]
       for i in range(0,AppoggioTempM[0]):
            app=list(AppoggioTempM[2][i][1:3])
            InfoConnectNoise.append(app)
           
           
       if stampa==1: #Print on screen of saved data 
           for i,j in enumerate(InfoPerseo):
               print(self.inf[i],"=",j)
           print("\n")
           print("the network consists of ", AppoggioTempM[0], " neuronal population" )
           print(AppoggioTempM[1])
           for i in range(0,AppoggioTempM[0]):
               print(AppoggioTempM[2][i])
           print("\n")
           print(AppoggioTempC[0])
           for i in range(0,AppoggioTempM[0]**2):
               print(AppoggioTempC[1][i])
           print("\n")
           for i in InfoProtocol:
               print("SET_PARAM"+str(i))


       return InfoPerseo,InfoBuild,InfoConnectPop,InfoConnectNoise,InfoProtocol
   
   def EstraiProtocol(self):
       import string
        f1=open(self.files[3],"r")  
        ProtocolList= []
       for x in f1.readlines():    
            y=x.split()
           if len(y):
               if x[0]!="#" and y[0]=="SET_PARAM":
                   try:
                        ProtocolList.append([float(y[1]),int(y[2]),float(y[3]),float(y[4])])                      
                   except ValueError:                        
                       pass                                       
        f1.close()
       return ProtocolList
                                           
   def EstraiInfoPerseo(self):
       import string
        f1=open(self.files[0],"r")  
        InfList= []
       for x in f1.readlines():    
            y=x.split()
           if len(y):
               if x[0]!="#":
                   for findinf in self.inf:
                       try:
                            temp=y.index(findinf)
                            InfList.append(y[temp+2])                      
                       except ValueError:                        
                           pass                                       
        f1.close()
       return InfList

   def EstraiInfoModuli(self):
       import string
        f1=open(self.files[2],"r")  
        NumPop=0
       for i,x in enumerate(f1.readlines()):    
            y=x.split()
           if len(y):
               if x[0]!="#":
                    NumPop=NumPop+1  
           if i==2:
                ParamList=[]
               for j in range(1,14):
                    ParamList.append(y[j])              
        f1.close()
        PopsParamList=[]
        f1=open(self.files[2],"r")
        x=f1.readlines()
       for j in range(0,NumPop):     
            appo=x[4+j];
            PopsParamList.append(appo.split())
        f1.close()
       return NumPop,ParamList,PopsParamList
   
   def EstraiInfoConnectivity(self):
       import string
        f1=open(self.files[1],"r")      
        PopConParamList=[]
       for i,x in enumerate(f1.readlines()):    
            y=x.split()
           if len(y):
               if x[0]!="#":
                    PopConParamList.append(y)
           if i==1:
                ParamList=[]
               for j in range(1,9):
                    ParamList.append(y[j])
        f1.close()
       return ParamList,PopConParamList

Import the initialization files:

in this section we...

Salva=1
file1="perseo35.ini"
file2="c_cortsurf_Pot1.43PotStr148v3.ini"
file3="m_cortsurf_Pot1.43.ini"
file4="ProtocolExploration36.ini"
files=[file1,file2,file3,file4]
#define the name of the Output file 
FileName="dati/Rates_Nest_Run_Milano_Test36_13x13_"+str(nest.Rank())+"_Pot1.43PotStr148v3Long3.dat"
#check the existence of the files being read      
ImpFil=ImportIniLIFCA(files);
ImpFil.FilesControllo()

#extract the information of interest from the files.ini and transfer them to the files: 
#InfoPerseo,InfoBuild,InfoConnectPop,InfoConnectNoise

stampa=0;  #stampa=1 print  output simulation data on screen stampa=0 dont
InfoPerseo,InfoBuild,InfoConnectPop,InfoConnectNoise,InfoProtocol=ImpFil.Estrai_inf(stampa)

# InfoPerseo=["NeuronType","DelayDistribType","SynapticExtractionType","Life" ]
# InfoBuild=[numero di popolazioni,
#             [N,C_ext,\nu_ext,\tau,\tetha,H,\tau_arp,NeuronInitType,\alpha_c,\tau_c,g_c],
#             [.....],[],...]
# InfoConnectPop=[numero di popolazioni,
#             [post,pre,c,Dmin,Dmax,syn typ,J,DJ],
#             [.....],[],...]
# InfoConnectNoise=[numero di popolazioni,
#             [J_ext,DJ_ext],
#             [.....],[],...]
# InfoProtocol=[[time,population,param_num,value],
#             [.....],[],...]

image-20220127173048-1.png

Defining general  and nest.kernel  parameters

#############################------------------------------------------------------------------------
#Clean the Network
#############################------------------------------------------------------------------------
nest.ResetKernel()

#############################------------------------------------------------------------------------
#insert the introductory parameters of the simulation 
#############################------------------------------------------------------------------------


dt = 0.1                                  # the resolution in ms
StartMisure=0.                            # start time of measurements 
simtime = int(float(InfoPerseo[3]))       # Simulation time in ms (200 s)
if simtime<=StartMisure:                  # If the simulation time is less than StartMisure, it is increased by StartMisure 
    simtime=simtime+StartMisure           
start=0.0                                 # start time of poissonian processes
origin=0.0                                # temporal origin 

#############################------------------------------------------------------------------------
# Kernel parameters
#############################------------------------------------------------------------------------
LNT=multiprocessing.cpu_count();
nest.SetKernelStatus({"local_num_threads": LNT})
nest.SetKernelStatus({"resolution": dt, "print_time": True,
                     "overwrite_files": True})

#############################------------------------------------------------------------------------
#"randomize" the seeds of the random generators 
#############################------------------------------------------------------------------------

#msd = int(math.fabs(time.process_time()*1000))
#N_vp = nest.GetKernelStatus(['total_num_virtual_procs'])[0]
#pyrngs = [numpy.random.RandomState(s) for s in range(msd, msd+N_vp)]
#nest.SetKernelStatus({"grng_seed" : msd+N_vp})
#nest.SetKernelStatus({"rng_seeds" : list(range(msd+N_vp+1, msd+2*N_vp+1))})

Building the network:  neuronal populations , Poisson processes and spike detectors

#############################------------------------------------------------------------------------
print("Building network")
#############################------------------------------------------------------------------------

startbuild = time.time() #initialize the calculation of the time used to simulate 

NeuronPop=[]
NoisePop=[]
DetectorPop=[]

#define and initialize the populations of neurons with the parameters extracted from the.ini files 
for i in range(1,int(InfoBuild[0])+1):    
   if int(InfoBuild[i][7])==0:
        app=float(InfoBuild[i][5])
   else:
        app=0.   
    app2= nest.Create("aeif_psc_exp", int(InfoBuild[i][0]),params={"C_m":     1.0,
                                                                  "g_L":     1.0/float(InfoBuild[i][3]),
                                                                  "t_ref":   float(InfoBuild[i][6]),
                                                                  "E_L":     0.0,
                                                                  "V_reset": float(InfoBuild[i][5]),
                                                                  "V_m":     app,
                                                                  "V_th":    float(InfoBuild[i][4]),
                                                                  "Delta_T": 0.,
                                                                  "tau_syn_ex": 1.0,
                                                                  "tau_syn_in": 1.0,
                                                                  "a":     0.0,
                                                                  "b":     float(InfoBuild[i][10]),
                                                                  "tau_w": float(InfoBuild[i][9]),
                                                                  "V_peak":float(InfoBuild[i][4])+10.0})
    NeuronPop.append(app2)

#define and initialize the poisson generators and the spike detectors with  the parameters extracted from the.ini files

for i in range(1,int(InfoBuild[0])+1):       
    app3= nest.Create("poisson_generator",params={"rate": float(InfoBuild[i][1]*InfoBuild[i][2]),
                                                'origin':0.,
                                                'start':start})
    NoisePop.append(app3)
    app4 = nest.Create("spike_recorder",params={ "start":StartMisure})
    DetectorPop.append(app4)

endbuild = time.time()

image-20220127165908-2.png

Connecting the network nodes:  neuronal populations, Poisson processes and spike detectors

#############################------------------------------------------------------------------------
print("Connecting ")
#############################------------------------------------------------------------------------

startconnect = time.time()
Connessioni=[]
Medie=[]

#create and define the connections between the populations of neurons and the poisson generators 
#and between the populations of neurons and the spike detectors with the parameters extracted from the.ini files 

for i in range(0,int(InfoBuild[0])):   
    nest.Connect(NoisePop[i], NeuronPop[i], syn_spec={'synapse_model': 'static_synapse_hpc',
                                             'delay': dt,        
                                             'weight': nest.math.redraw(nest.random.normal(mean=float(InfoConnectNoise[i+1][0]),
                                                                                            std=(float(InfoConnectNoise[i+1][1])*float(InfoConnectNoise[i+1][0]))),
                                                                        min=0., max=float('Inf'))
                                                    })
    nest.Connect(NeuronPop[i][:int(InfoBuild[i+1][0])], DetectorPop[i], syn_spec={"weight": 1.0, "delay": dt})

#create and define the connections between the populations of neurons with the parameters extracted from the.ini files 

for i in range(0,len(InfoConnectPop[1:])):

    conn=nest.Connect(NeuronPop[int(InfoConnectPop[i+1][1])], NeuronPop[int(InfoConnectPop[i+1][0])],
                                     {'rule': 'pairwise_bernoulli',
                                     'p':float(InfoConnectPop[i+1][2]) },        
                                      syn_spec={'synapse_model': 'static_synapse_hpc',      
                                     'delay':nest.math.redraw(nest.random.exponential(beta=float(1./(2.99573227355/(float(InfoConnectPop[i+1][4])-float(InfoConnectPop[i+1][3]))))),
                                                              min= numpy.max([dt,float(1./float(InfoConnectPop[i+1][4]))]),
                                                              max= float(1./(float(InfoConnectPop[i+1][3])-dt/2))),
                                               
                                       'weight':nest.random.normal(mean=float(InfoConnectPop[i+1][6]),
                                                                    std=math.fabs(float(InfoConnectPop[i+1][6])*float(InfoConnectPop[i+1][7])))})


endconnect = time.time()

image-20220127170722-1.png

Simulating: neuronal time evolution.

        #############################------------------------------------------------------------------------
       print("Simulating")
       #############################------------------------------------------------------------------------   
       ###################################################################################################################################################################
       if Salva:
           print("I m going to save the data")
           #x=str(iterazioni)
            f = open(FileName,"w")
           if len(InfoProtocol):
               print("I m going to split the simulation")
                tempo=0
               for contatore in range(0,len(InfoProtocol)):
                    appoggio1=int((tempo+InfoProtocol[contatore][0])/1000.)
                    appoggio2=int(tempo/1000.)
                    appoggio3=tempo+InfoProtocol[contatore][0]
                   if (appoggio1-appoggio2)>=1:
                        T1=(1+appoggio2)*1000-tempo
                        nest.Simulate(T1)
                       #Save the Data!!!!
                       ###########################################################  
                        Equilibri=[]
                       for i in range(0,int(InfoBuild[0])):
                            Equilibri.append([])
                            a=nest.GetStatus(DetectorPop[i])[0]["events"]["times"]
                           if len(a)>0:
                                Trange=(1000*int(numpy.min(a)/1000.),1000*int(numpy.min(a)/1000.)+1000)
                                hist,Tbin=numpy.histogram(a,200,(Trange[0],Trange[1]))
                                Equilibri[i]=hist*1000./(5.*int(InfoBuild[i+1][0]))
                           else:
                                Trange=(1000*int(tempo/1000.),1000*int(tempo/1000.)+1000)
                                hist=numpy.zeros(200)
                                Tbin=numpy.linspace(Trange[0],Trange[1],num=201)
                                Equilibri[i]=hist
                            nest.SetStatus(DetectorPop[i],{'n_events':0})
                       for j in range(0,len(hist)):
                            f.write(str(Tbin[j])+" ")
                           for i in range(0,int(InfoBuild[0])):
                                f.write(str(Equilibri[i][j])+" ")
                            f.write("\n ")
                       ###########################################################
                        tempo=tempo+T1
                       for contatore2 in range(1,(appoggio1-appoggio2)):
                            nest.Simulate(1000.)
                           #Save the Data!!!!
                           ###########################################################  
                            Equilibri=[]
                           for i in range(0,int(InfoBuild[0])):
                                Equilibri.append([])
                                a=nest.GetStatus(DetectorPop[i])[0]["events"]["times"]
                               if len(a)>0:
                                    Trange=(1000*int(numpy.min(a)/1000.),1000*int(numpy.min(a)/1000.)+1000)
                                    hist,Tbin=numpy.histogram(a,200,(Trange[0],Trange[1]))
                                    Equilibri[i]=hist*1000./(5.*int(InfoBuild[i+1][0]))
                               else:
                                    Trange=(1000*int(tempo/1000.),1000*int(tempo/1000.)+1000)
                                    hist=numpy.zeros(200)
                                    Tbin=numpy.linspace(Trange[0],Trange[1],num=201)
                                    Equilibri[i]=hist
                                nest.SetStatus(DetectorPop[i],{'n_events':0})
                           for j in range(0,len(hist)):
                                f.write(str(Tbin[j])+" ")
                               for i in range(0,int(InfoBuild[0])):
                                    f.write(str(Equilibri[i][j])+" ")
                                f.write("\n ")
                            tempo=tempo+1000.
                        T2=appoggio3-tempo
                        nest.Simulate(T2);
                        tempo=tempo+T2;
                   else:
                        nest.Simulate(InfoProtocol[contatore][0])
                        temp=InfoProtocol[contatore][0]
                        tempo=tempo+temp
                   if InfoProtocol[contatore][2]==4:
                        nest.SetStatus(NoisePop[InfoProtocol[contatore][1]],params={"rate": float(InfoBuild[1+InfoProtocol[contatore][1]][2]*InfoProtocol[contatore][3])})
                   if InfoProtocol[contatore][2]==12:
                        nest.SetStatus(NeuronPop[InfoProtocol[contatore][1]], params={"b": float(InfoProtocol[contatore][3])})
           else:
                nest.Simulate(simtime)
                tempo=simtime
           if (simtime-tempo)>0.:
                nest.Simulate(simtime-tempo)


            endsimulate = time.time()
            f.close()
       else:
           if len(InfoProtocol):
                tempo=0
               for contatore in range(0,len(InfoProtocol)):
                    nest.Simulate(InfoProtocol[contatore][0])
                    temp=InfoProtocol[contatore][0]
                    tempo=tempo+temp
                   if InfoProtocol[contatore][2]==4:
                                    nest.SetStatus(NoisePop[InfoProtocol[contatore][1]],params={"rate": float(InfoBuild[1+InfoProtocol[contatore][1]][2]*InfoProtocol[contatore][3])})
                                   #print "Population:", InfoProtocol[contatore][1] ,";Parameter:", InfoProtocol[contatore][2]  ,";  Value: ",InfoProtocol[contatore][3]
                   if InfoProtocol[contatore][2]==12:
                                                  nest.SetStatus(NeuronPop[InfoProtocol[contatore][1]], params={"b": float(InfoProtocol[contatore][3])})
                                                 #print "Population:", InfoProtocol[contatore][1] ,";Parameter:", InfoProtocol[contatore][2]  ,";  Value: ",InfoProtocol[contatore][3]

           else:
                nest.Simulate(simtime)
                tempo=simtime
           if (simtime-tempo)>0.:
                nest.Simulate(simtime-tempo)
            endsimulate = time.time()


       ###################################################################################################################################################################

       #############################------------------------------------------------------------------------
       #print some information from the simulation 
       #############################------------------------------------------------------------------------

        num_synapses = nest.GetDefaults('static_synapse_hpc')["num_connections"]
        build_time = endbuild - startbuild
        connect_time = endconnect - startconnect
        sim_time = endsimulate - endconnect

        N_neurons=0
       for i in range(0,int(InfoBuild[0])):
            N_neurons=N_neurons+int(InfoBuild[i+1][0])

       print(" Network simulation (Python) neuron type:",InfoPerseo[0])
       print("Number of neurons : {0}".format(N_neurons))
       print("Number of synapses: {0}".format(num_synapses))
       print("Building time     : %.2f s" % build_time)
       print("Connecting time     : %.2f s" % connect_time)
       print("Simulation time   : %.2f s" % sim_time)

Fine=time.time()              
print ("Total Simulation time   : %.2f s" % (Fine-Inizio))

image-20220127171242-1.png

Results:

the output of this simulation is...