2929from shutil import copyfile
3030from jupyter_geppetto import jupyter_geppetto , synchronization
3131import imp
32+ from contextlib import redirect_stdout , redirect_stderr
3233
3334
3435class NetPyNEGeppetto ():
@@ -53,42 +54,51 @@ def getData(self):
5354
5455 def instantiateNetPyNEModelInGeppetto (self ):
5556 try :
56- netpyne_model = self .instantiateNetPyNEModel ()
57- self .geppetto_model = self .model_interpreter .getGeppettoModel (netpyne_model )
58- return json .loads (GeppettoModelSerializer ().serialize (self .geppetto_model ).decode ("utf-8" ))
57+ with redirect_stdout (sys .__stdout__ ):
58+ if not 'usePrevInst' in args or not args ['usePrevInst' ]:
59+ netpyne_model = self .instantiateNetPyNEModel ()
60+ self .geppetto_model = self .model_interpreter .getGeppettoModel (netpyne_model )
61+
62+ return json .loads (GeppettoModelSerializer ().serialize (self .geppetto_model ))
5963 except :
6064 return self .getJSONError ("Error while instantiating the NetPyNE model" ,traceback .format_exc ())
6165
62- def simulateNetPyNEModelInGeppetto (self , modelParameters ):
66+ def simulateNetPyNEModelInGeppetto (self , args ):
6367 try :
64- if modelParameters ['parallelSimulation' ]:
65- logging .debug ('Running parallel simulation' )
66-
67- self .netParams .save ("netParams.json" )
68- self .simConfig .saveJson = True
69- self .simConfig .save ("simParams.json" )
70-
71- template = os .path .join (os .path .dirname (__file__ ), 'template.py' )
72- copyfile (template , 'init.py' )
73-
74- subprocess .call (["mpiexec" , "-n" , modelParameters ['cores' ], "nrniv" , "-python" , "-mpi" , "init.py" ])
75-
76- sim .load ('model_output.json' )
77-
78- self .geppetto_model = self .model_interpreter .getGeppettoModel (sim )
79- netpyne_model = sim
80-
81- else :
82- if modelParameters ['previousTab' ] == 'define' :
83- logging .debug ('Instantiating single thread simulation' )
84- netpyne_model = self .instantiateNetPyNEModel ()
85- self .geppetto_model = self .model_interpreter .getGeppettoModel (netpyne_model )
86-
87- logging .debug ('Running single thread simulation' )
88- netpyne_model = self .simulateNetPyNEModel ()
89-
90- # return GeppettoModelSerializer().serialize(self.geppetto_model)
91- return json .loads (GeppettoModelSerializer ().serialize (self .geppetto_model ).decode ("utf-8" ))
68+ with redirect_stdout (sys .__stdout__ ):
69+ if args ['parallelSimulation' ]: # TODO mpi is not finding libmpi.dylib.. set LD_LIBRARY_PATH to openmpi bin folder, but nothing
70+ logging .debug ('Running parallel simulation' )
71+ if not 'usePrevInst' in args or not args ['usePrevInst' ]:
72+ self .netParams .save ("netParams.json" )
73+ self .simConfig .saveJson = True
74+ self .simConfig .save ("simParams.json" )
75+ template = os .path .join (os .path .dirname (__file__ ), 'template.py' )
76+ else :
77+ sim .cfg .saveJson = True
78+ oldName = sim .cfg .filename
79+ sim .cfg .filename = 'model_output'
80+ sim .saveData ()
81+ sim .cfg .filename = oldName
82+ template = os .path .join (os .path .dirname (__file__ ), 'template2.py' )
83+ copyfile (template , './init.py' )
84+
85+ cp = subprocess .run (["mpiexec" , "-n" , args ['cores' ], "nrniv" , "-mpi" , "-python" , "init.py" ], capture_output = True )
86+ print (cp .stdout .decode ()+ cp .stderr .decode ())
87+ if cp .returncode != 0 : return self .getJSONError ("Error while simulating the NetPyNE model" , cp .stderr .decode ())
88+ sim .load ('model_output.json' )
89+ self .geppetto_model = self .model_interpreter .getGeppettoModel (sim )
90+ netpyne_model = sim
91+
92+ else : # single cpu computation
93+ if not 'usePrevInst' in args or not args ['usePrevInst' ]:
94+ logging .debug ('Instantiating single thread simulation' )
95+ netpyne_model = self .instantiateNetPyNEModel ()
96+ self .geppetto_model = self .model_interpreter .getGeppettoModel (netpyne_model )
97+
98+ logging .debug ('Running single thread simulation' )
99+ netpyne_model = self .simulateNetPyNEModel ()
100+
101+ return json .loads (GeppettoModelSerializer ().serialize (self .geppetto_model ))
92102 except :
93103 return self .getJSONError ("Error while simulating the NetPyNE model" ,traceback .format_exc ())
94104
@@ -117,7 +127,83 @@ def compileModMechFiles(self, compileMod, modFolder):
117127 # Load mechanism if mod path is passed
118128 if modFolder :
119129 neuron .load_mechanisms (str (modFolder ))
130+
131+ def loadModel (self , args ): # handles all data coming from a .json file (default file system for Netpyne)
132+ def remove (dictionary ):
133+ # remove reserved keys such as __dict__, __Method__, etc
134+ # they appear when we do sim.loadAll(json_file)
135+ if isinstance (dictionary , dict ):
136+ for key , value in list (dictionary .items ()):
137+ if key .startswith ('__' ):
138+ dictionary .pop (key )
139+ else :
140+ remove (value )
141+
142+ if not any ([args [option ] for option in ['loadNetParams' , 'loadSimCfg' , 'loadSimData' , 'loadNet' ]]):
143+ return self .getJSONError ("Error while loading data" , 'You have to select at least one option' )
120144
145+ try :
146+ owd = os .getcwd ()
147+ self .compileModMechFiles (args ['compileMod' ], args ['modFolder' ])
148+ except :
149+ return self .getJSONError ("Error while importing/compiling mods" ,traceback .format_exc ())
150+ finally :
151+ os .chdir (owd )
152+
153+ try :
154+ with redirect_stdout (sys .__stdout__ ):
155+ from . import netpyne_geppetto
156+ sim .initialize ()
157+ wake_up_geppetto = False
158+ if all ([args [option ] for option in ['loadNetParams' , 'loadSimCfg' , 'loadSimData' , 'loadNet' ]]):
159+ wake_up_geppetto = True
160+ if self .doIhaveInstOrSimData ()['haveInstance' ]: sim .clearAll ()
161+ sim .initialize ()
162+ sim .loadAll (args ['jsonModelFolder' ])
163+ netpyne_geppetto .netParams = sim .net .params
164+ netpyne_geppetto .simConfig = sim .cfg
165+ remove (netpyne_geppetto .netParams .todict ())
166+ remove (netpyne_geppetto .simConfig .todict ())
167+ else :
168+ if args ['loadNet' ]:
169+ wake_up_geppetto = True
170+ if self .doIhaveInstOrSimData ()['haveInstance' ]: sim .clearAll ()
171+ sim .initialize ()
172+ sim .loadNet (args ['jsonModelFolder' ])
173+
174+ if args ['loadSimData' ]: # TODO (https://github.com/Neurosim-lab/netpyne/issues/360)
175+ wake_up_geppetto = True
176+ if not self .doIhaveInstOrSimData ()['haveInstance' ]:
177+ sim .create (specs .NetParams (), specs .SimConfig ())
178+ sim .net .defineCellShapes ()
179+ sim .gatherData (gatherLFP = False )
180+ sim .loadSimData (args ['jsonModelFolder' ])
181+
182+ if args ['loadSimCfg' ]:
183+ sim .loadSimCfg (args ['jsonModelFolder' ])
184+ netpyne_geppetto .simConfig = sim .cfg
185+ remove (netpyne_geppetto .simConfig .todict ())
186+
187+ if args ['loadNetParams' ]:
188+ if self .doIhaveInstOrSimData ()['haveInstance' ]: sim .clearAll ()
189+ sim .loadNetParams (args ['jsonModelFolder' ])
190+ netpyne_geppetto .netParams = sim .net .params
191+ remove (netpyne_geppetto .netParams .todict ())
192+
193+ if wake_up_geppetto :
194+ section = list (sim .net .cells [0 ].secs .keys ())[0 ]
195+ if not 'pt3d' in list (sim .net .cells [0 ].secs [section ].geom .keys ()):
196+ sim .net .defineCellShapes ()
197+ sim .gatherData ()
198+ sim .loadSimData (args ['jsonModelFolder' ])
199+ self .geppetto_model = self .model_interpreter .getGeppettoModel (sim )
200+
201+ return GeppettoModelSerializer ().serialize (self .geppetto_model )
202+ else :
203+ return self .getJSONReply ()
204+ except :
205+ return self .getJSONError ("Error while loading the NetPyNE model" ,traceback .format_exc ())
206+
121207 def importModel (self , modelParameters ):
122208 try :
123209 # Get Current dir
@@ -126,8 +212,8 @@ def importModel(self, modelParameters):
126212 self .compileModMechFiles (modelParameters ['compileMod' ], modelParameters ['modFolder' ])
127213
128214 from . import netpyne_geppetto
129-
130- if modelParameters [ 'importFormat' ] == 'py' :
215+
216+ with redirect_stdout ( sys . __stdout__ ) :
131217 # NetParams
132218 netParamsPath = str (modelParameters ["netParamsPath" ])
133219 sys .path .append (netParamsPath )
@@ -149,22 +235,7 @@ def importModel(self, modelParameters):
149235 simConfigModuleName = importlib .import_module (str (modelParameters ["simConfigModuleName" ]))
150236 # Import Model attributes
151237 self .simConfig = getattr (simConfigModuleName , str (modelParameters ["simConfigVariable" ]))
152-
153- elif modelParameters ['importFormat' ]== 'json' :
154- with open (modelParameters ['jsonModelFolder' ], 'r' ) as file :
155- jsonData = json .load (file )
156-
157- if 'net' in jsonData :
158- if 'params' in jsonData ['net' ] and 'simConfig' in jsonData :
159- self .netParams = specs .NetParams (jsonData ['net' ]['params' ])
160- self .simConfig = specs .SimConfig (jsonData ['simConfig' ])
161- self .netParams .cellParams = jsonData ['net' ]['params' ]['cellParams' ]
162- else :
163- return self .getJSONError ("Assertion error while importing the NetPyNE model" , "The json file does not contain the following keys: [params, simConfig]" )
164- else :
165- return self .getJSONError ("Assertion error while importing the NetPyNE model" , "The json file does not contain the following keys: [net]" )
166- else :
167- return self .getJSONError ("Assertion error while importing the NetPyNE model" , "frontend sent a wrong option for 'importFormat'. allowed values are py and json" )
238+
168239 return self .getJSONReply ()
169240 except :
170241 return self .getJSONError ("Error while importing the NetPyNE model" ,traceback .format_exc ())
@@ -176,6 +247,8 @@ def importCellTemplate(self, modelParameters, modFolder, compileMod):
176247 # Get Current dir
177248 owd = os .getcwd ()
178249
250+ from .netpyne_geppetto import netParams
251+
179252 self .compileModMechFiles (compileMod , modFolder )
180253
181254 # import cell template
@@ -191,33 +264,86 @@ def importCellTemplate(self, modelParameters, modFolder, compileMod):
191264 finally :
192265 os .chdir (owd )
193266
194- def exportModel (self , modelParameters ):
267+ def exportModel (self , args ):
195268 try :
196- sim .initialize (netParams = self .netParams , simConfig = self .simConfig )
197- sim .saveData ()
269+ with redirect_stdout (sys .__stdout__ ):
270+ if not args ['netCells' ]:
271+ sim .initialize (netParams = netParams , simConfig = simConfig )
272+ sim .cfg .filename = args ['fileName' ]
273+ include = [el for el in specs .SimConfig ().saveDataInclude if el in args .keys () and args [el ]]
274+ if args ['netCells' ]: include += ['netPops' ]
275+ sim .cfg .saveJson = True
276+ sim .saveData (include )
277+ sim .cfg .saveJson = False
198278 return self .getJSONReply ()
199279 except :
200280 return self .getJSONError ("Error while exporting the NetPyNE model" ,traceback .format_exc ())
281+
282+ def exportNeuroML (self , modelParams ):
283+ try :
284+ with redirect_stdout (sys .__stdout__ ):
285+ sim .exportNeuroML2 (modelParams ['fileName' ], specs .SimConfig ())
286+ return self .getJSONReply ()
287+ except :
288+ return self .getJSONError ("Error while exporting the NetPyNE model" , traceback .format_exc ())
289+
290+ def importNeuroML (self , modelParams ):
291+ try :
292+ with redirect_stdout (sys .__stdout__ ):
293+ sim .initialize ()
294+ sim .importNeuroML2 (modelParams ['neuroMLFolder' ], simConfig = specs .SimConfig (), simulate = False , analyze = False )
295+ self .geppetto_model = self .model_interpreter .getGeppettoModel (sim )
296+ return GeppettoModelSerializer ().serialize (self .geppetto_model )
201297
298+ except :
299+ return self .getJSONError ("Error while exporting the NetPyNE model" ,traceback .format_exc ())
300+
301+ def deleteModel (self , modelParams ):
302+ try :
303+ from . import netpyne_geppetto
304+ with redirect_stdout (sys .__stdout__ ):
305+ netpyne_geppetto .netParams = specs .NetParams ()
306+ netpyne_geppetto .simConfig = specs .SimConfig ()
307+ netpyne_geppetto .netParams .todict ()
308+ netpyne_geppetto .netParams .todict ()
309+ if self .doIhaveInstOrSimData ()['haveInstance' ]: sim .clearAll ()
310+ self .geppetto_model = None
311+ return self .getJSONReply ()
312+
313+ except :
314+ return self .getJSONError ("Error while exporting the NetPyNE model" ,traceback .format_exc ())
315+
202316 def instantiateNetPyNEModel (self ):
203- import sys ; imp .reload (sys )
204- sim .initialize (self .netParams , self .simConfig ) # create network object and set cfg and net params
205- sim .net .createPops () # instantiate network populations
206- sim .net .createCells () # instantiate network cells based on defined populations
207- sim .net .connectCells () # create connections between cells based on params
208- sim .net .addStims () # add external stimulation to cells (IClamps etc)
209-
210- sim .net .defineCellShapes () # creates 3d pt for cells with stylized geometries
211- sim .gatherData (gatherLFP = False )
212- #sim.saveData()
317+ with redirect_stdout (sys .__stdout__ ):
318+ from . import netpyne_geppetto
319+ saveData = sim .allSimData if hasattr (sim , 'allSimData' ) and 'spkt' in sim .allSimData .keys () and len (sim .allSimData ['spkt' ])> 0 else False
320+ sim .create (netpyne_geppetto .netParams , netpyne_geppetto .simConfig )
321+ sim .net .defineCellShapes () # creates 3d pt for cells with stylized geometries
322+ sim .gatherData (gatherLFP = False )
323+ if saveData : sim .allSimData = saveData # preserve data from previous simulation
324+
213325 return sim
214326
215327 def simulateNetPyNEModel (self ):
216- import sys ; imp . reload (sys )
217- sim .setupRecording ()
218- sim .simulate ()
219- sim .saveData ()
328+ with redirect_stdout (sys . __stdout__ ):
329+ sim .setupRecording ()
330+ sim .simulate ()
331+ sim .saveData ()
220332 return sim
333+
334+ def doIhaveInstOrSimData (self ): # return [bool, bool] telling if we have an instance and simulated data
335+ with redirect_stdout (sys .__stdout__ ):
336+ out = [False , False ]
337+ if hasattr (sim , 'net' ):
338+ if hasattr (sim .net , 'cells' ) and hasattr (sim .net , 'pops' ):
339+ if len (sim .net .cells )> 0 and len (sim .net .pops .keys ())> 0 :
340+ out [0 ] = True
341+ if hasattr (sim , 'allSimData' ):
342+ if 'spkt' in sim .allSimData .keys () and 'spkid' in sim .allSimData .keys ():
343+ if len (sim .allSimData ['spkt' ])> 0 and len (sim .allSimData ['spkid' ])> 0 :
344+ out [1 ] = True
345+
346+ return {'haveInstance' : out [0 ], 'haveSimData' : out [1 ]}
221347
222348 def rename (self , path , oldValue ,newValue ):
223349 command = 'sim.rename(self.' + path + ',"' + oldValue + '","' + newValue + '")'
@@ -236,17 +362,18 @@ def getPlotSettings(self, plot):
236362 return self .simConfig .analysis [plot ]
237363 return {}
238364
239- def getDirList (self , dir = None , onlyDirs = False ):
365+ def getDirList (self , dir = None , onlyDirs = False , filterFiles = False ):
240366 # Get Current dir
241367 if dir == None :
242368 dir = os .getcwd ()
243369 dir_list = []
244370 for f in sorted (os .listdir (str (dir )), key = str .lower ):
245- ff = os .path .join (dir ,f )
246- if os .path .isdir (ff ):
247- dir_list .insert (0 , {'title' : f , 'path' : ff , 'load' : False , 'children' : [{'title' : 'Loading...' }]})
248- elif not onlyDirs :
249- dir_list .append ({'title' : f , 'path' : ff })
371+ ff = os .path .join (dir ,f )
372+ if os .path .isdir (ff ):
373+ dir_list .insert (0 , {'title' : f , 'path' : ff , 'load' : False , 'children' : [{'title' : 'Loading...' }]})
374+ elif not onlyDirs :
375+ if not filterFiles or os .path .isfile (ff ) and ff .endswith (filterFiles ):
376+ dir_list .append ({'title' : f , 'path' : ff })
250377 return dir_list
251378
252379 def getPlot (self , plotName , LFPflavour ):
@@ -329,7 +456,7 @@ def deleteParam(self, paramToDel):
329456 def validateFunction (self , functionString ):
330457 return validateFunction (functionString , self .netParams .__dict__ )
331458
332- def generateScript (self , metadata ):
459+ def exportHLS (self , args ):
333460 def convert2bool (string ):
334461 return string .replace ('true' , 'True' ).replace ('false' , 'False' )
335462
@@ -340,7 +467,7 @@ def header(title, spacer='-'):
340467 params = ['popParams' , 'cellParams' , 'synMechParams' ]
341468 params += ['connParams' , 'stimSourceParams' , 'stimTargetParams' ]
342469
343- fname = metadata [ 'scriptName ' ] if metadata [ 'scriptName ' ][- 3 :]== '.py' else metadata [ 'scriptName ' ]+ '.py'
470+ fname = args [ 'fileName ' ] if args [ 'fileName ' ][- 3 :]== '.py' else args [ 'fileName ' ]+ '.py'
344471
345472 with open (fname , 'w' ) as script :
346473 script .write ('from netpyne import specs, sim\n ' )
0 commit comments