-
Notifications
You must be signed in to change notification settings - Fork 12
/
SonataReader.py
1352 lines (1097 loc) · 50.7 KB
/
SonataReader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import tables # pytables for HDF5 support
import os
import sys
import random
from neuroml.hdf5.NetworkContainer import *
from neuromllite import NetworkReader
from neuromllite.utils import print_v, load_json
from pyneuroml.lems import generate_lems_file_for_neuroml
import pprint
pp = pprint.PrettyPrinter(depth=6)
DUMMY_CELL = "dummy_cell"
DEFAULT_NEST_SPIKE_SYN = "DEFAULT_NEST_SPIKE_SYN"
REPORT_FILE = "report.txt"
def _get_default_nest_syn(nml_doc):
if nml_doc.get_by_id(DEFAULT_NEST_SPIKE_SYN):
return nml_doc.get_by_id(DEFAULT_NEST_SPIKE_SYN)
from neuroml import AlphaCurrSynapse
nest_syn = AlphaCurrSynapse(id=DEFAULT_NEST_SPIKE_SYN, tau_syn="2")
nml_doc.alpha_curr_synapses.append(nest_syn)
return nest_syn
def _parse_entry(w):
"""
Check whether it's an int, float or string & return with that type
"""
try:
return int(w)
except:
try:
return float(w)
except:
return w
def load_csv_props(info_file):
"""
Load a generic csv file as used in Sonata
"""
info = {}
columns = {}
for line in open(info_file):
w = line.split()
if len(columns) == 0:
for i in range(len(w)):
columns[i] = _parse_entry(w[i])
else:
info[int(w[0])] = {}
for i in range(len(w)):
if i != 0:
info[int(w[0])][columns[i]] = _parse_entry(w[i])
return info
def _matches_node_set_props(type_info, node_set_props):
"""
Check whether the node_set properties match the given model type definition
"""
matches = None
for key in node_set_props:
ns_val = node_set_props[key]
if key in type_info:
if ns_val == type_info[key]:
if matches:
matches = matches and True
else:
matches = True
else:
matches = False
return matches
class SonataReader(NetworkReader):
"""
Main class for reading a Sonata model. For typical usage, see main method below
"""
component_objects = {} # Store cell ids vs objects, e.g. NeuroML2 based object
nml_includes = ["PyNN.xml"]
def __init__(self, **parameters):
print_v("Creating SonataReader with %s..." % parameters)
self.parameters = parameters
self.current_sonata_pop = None
self.current_node_group = None
self.cell_info = {}
self.node_set_mappings = {}
self.pop_comp_info = {}
self.syn_comp_info = {}
self.input_comp_info = {}
self.nml_pop_vs_comps = {}
self.nml_pops_having_locations = []
self.nml_ids_vs_gids = {}
self.init_substitutes = {}
self.substitutes = {}
self.current_edge = None
self.pre_pop = None
self.post_pop = None
self.myrandom = random.Random(12345)
def subs(self, path):
"""
Search the strings in a config file for a substitutable value, e.g.
"morphologies_dir": "$COMPONENT_DIR/morphologies",
"""
# print_v('Checking for: \n %s, \n %s \n in %s'%(self.substitutes,self.init_substitutes,path))
if type(path) == int or type(path) == float:
return path
for s in self.init_substitutes:
if path.startswith(s):
path = path.replace(s, self.init_substitutes[s], 1)
# print_v(' So far: %s'%path)
for s in self.substitutes:
if s in path:
path = path.replace(s, self.substitutes[s])
# print_v(' Returning: %s'%path)
return path
def parse(self, handler):
"""
Main method to parse the Sonata files and call the appropriate methods
in the handler
"""
########################################################################
# load the main configuration scripts
main_config_filename = os.path.abspath(self.parameters["filename"])
config = load_json(main_config_filename)
self.init_substitutes = {
".": "%s/" % os.path.dirname(main_config_filename),
"../": "%s/" % os.path.dirname(os.path.dirname(main_config_filename)),
}
self.substitutes = {
"${configdir}": "%s" % os.path.dirname(main_config_filename)
}
if "network" in config:
self.network_config = load_json(self.subs(config["network"]))
else:
self.network_config = config
if "simulation" in config:
self.simulation_config = load_json(self.subs(config["simulation"]))
else:
self.simulation_config = None
for m in self.network_config["manifest"]:
path = self.subs(self.network_config["manifest"][m])
self.substitutes[m] = path
if "id" in self.parameters:
id = self.parameters["id"]
else:
id = "SonataNetwork"
if id[0].isdigit(): # id like 9_cells is not a valid id for NeuroML
id = "NML2_%s" % id
########################################################################
# Feed the handler the info on the network
self.handler = handler
notes = "Network read in from Sonata: %s" % main_config_filename
handler.handle_document_start(id, notes)
handler.handle_network(id, notes)
self.node_types = {}
########################################################################
# Get info from nodes files
for n in self.network_config["networks"]["nodes"]:
nodes_file = self.subs(n["nodes_file"])
node_types_file = self.subs(n["node_types_file"])
print_v("\nLoading nodes from %s and %s" % (nodes_file, node_types_file))
h5file = tables.open_file(nodes_file, mode="r")
print_v("Opened HDF5 file: %s" % (h5file.filename))
self.parse_group(h5file.root.nodes)
h5file.close()
self.node_types[self.current_sonata_pop] = load_csv_props(node_types_file)
self.current_sonata_pop = None
########################################################################
# Get info from edges files
self.edges_info = {}
self.conn_info = {}
if "edges" in self.network_config["networks"]:
for e in self.network_config["networks"]["edges"]:
edges_file = self.subs(e["edges_file"])
edge_types_file = self.subs(e["edge_types_file"])
print_v(
"\nLoading edges from %s and %s" % (edges_file, edge_types_file)
)
h5file = tables.open_file(edges_file, mode="r")
print_v("Opened HDF5 file: %s" % (h5file.filename))
self.parse_group(h5file.root.edges)
h5file.close()
self.edges_info[self.current_edge] = load_csv_props(edge_types_file)
self.current_edge = None
########################################################################
# Use extracted node/cell info to create populations
for sonata_pop in self.cell_info:
types_vs_pops = {}
for type in self.cell_info[sonata_pop]["type_count"]:
node_type_info = self.node_types[sonata_pop][type]
model_name_type = (
node_type_info["model_name"]
if "model_name" in node_type_info
else (
node_type_info["pop_name"]
if "pop_name" in node_type_info
else node_type_info["model_type"]
)
)
model_type = node_type_info["model_type"]
model_template = (
node_type_info["model_template"]
if "model_template" in node_type_info
else "- None -"
)
nml_pop_id = "%s_%s_%s" % (sonata_pop, model_name_type, type)
print_v(
" - Adding population: %s which has model info: %s"
% (nml_pop_id, node_type_info)
)
size = self.cell_info[sonata_pop]["type_count"][type]
if model_type == "point_process" and model_template == "nrn:IntFire1":
raise Exception(
"Point process model not currently supported: %s\nTry expressing the I&F cell in NEST format with nest:iaf_psc_alpha"
% model_template
)
pop_comp = "cell_%s" % nml_pop_id # model_template.replace(':','_')
self.pop_comp_info[pop_comp] = {}
self.pop_comp_info[pop_comp]["model_type"] = model_type
dynamics_params_file = (
self.subs(
self.network_config["components"]["point_neuron_models_dir"]
)
+ "/"
+ node_type_info["dynamics_params"]
)
self.pop_comp_info[pop_comp]["dynamics_params"] = load_json(
dynamics_params_file
)
elif (
model_type == "point_process"
and model_template == "nest:iaf_psc_alpha"
):
pop_comp = (
"cell_%s" % nml_pop_id
) # = model_template.replace(':','_')
self.pop_comp_info[pop_comp] = {}
self.pop_comp_info[pop_comp]["model_type"] = model_type
self.pop_comp_info[pop_comp]["model_template"] = model_template
dynamics_params_file = (
self.subs(
self.network_config["components"]["point_neuron_models_dir"]
)
+ "/"
+ node_type_info["dynamics_params"]
)
self.pop_comp_info[pop_comp]["dynamics_params"] = load_json(
dynamics_params_file
)
else:
pop_comp = DUMMY_CELL
self.pop_comp_info[pop_comp] = {}
self.pop_comp_info[pop_comp]["model_type"] = pop_comp
self.nml_pop_vs_comps[nml_pop_id] = pop_comp
properties = {}
properties["type_id"] = type
properties["sonata_population"] = sonata_pop
properties["region"] = sonata_pop
for i in node_type_info:
properties[i] = node_type_info[i]
if i == "ei":
properties["type"] = node_type_info[i].upper()
color = "%s %s %s" % (
self.myrandom.random(),
self.myrandom.random(),
self.myrandom.random(),
)
try:
import opencortex.utils.color as occ
interneuron = "SOM" in nml_pop_id or "PV" in nml_pop_id
if "L23" in nml_pop_id:
color = (
occ.L23_INTERNEURON
if interneuron
else occ.L23_PRINCIPAL_CELL
)
pop.properties.append(neuroml.Property("region", "L23"))
if "L4" in nml_pop_id:
color = (
occ.L4_INTERNEURON if interneuron else occ.L4_PRINCIPAL_CELL
)
pop.properties.append(neuroml.Property("region", "L4"))
if "L5" in nml_pop_id:
color = (
occ.L5_INTERNEURON if interneuron else occ.L5_PRINCIPAL_CELL
)
pop.properties.append(neuroml.Property("region", "L5"))
if "L6" in nml_pop_id:
color = (
occ.L6_INTERNEURON if interneuron else occ.L6_PRINCIPAL_CELL
)
pop.properties.append(neuroml.Property("region", "L6"))
except:
pass # Don't specify a particular color, use random, not a problem...
properties["color"] = color
if True or not "locations" in self.cell_info[sonata_pop]["0"]:
properties = {} ############# temp for LEMS...
if model_type != "virtual":
self.handler.handle_population(
nml_pop_id,
pop_comp,
size,
component_obj=None,
properties=properties,
)
types_vs_pops[type] = nml_pop_id
self.cell_info[sonata_pop]["pop_count"] = {}
self.cell_info[sonata_pop]["pop_map"] = {}
for i in self.cell_info[sonata_pop]["types"]:
pop = types_vs_pops[self.cell_info[sonata_pop]["types"][i]]
if not pop in self.cell_info[sonata_pop]["pop_count"]:
self.cell_info[sonata_pop]["pop_count"][pop] = 0
index = self.cell_info[sonata_pop]["pop_count"][pop]
self.cell_info[sonata_pop]["pop_map"][i] = (pop, index)
if not pop in self.nml_ids_vs_gids:
self.nml_ids_vs_gids[pop] = {}
self.nml_ids_vs_gids[pop][index] = (sonata_pop, i)
if i in self.cell_info[sonata_pop]["0"]["locations"]:
if not pop in self.nml_pops_having_locations:
self.nml_pops_having_locations.append(pop)
pos = self.cell_info[sonata_pop]["0"]["locations"][i]
# print('Adding pos %i: %s'%(i,pos))
self.handler.handle_location(
index,
pop,
pop_comp,
pos["x"] if "x" in pos and pos["x"] is not None else 0,
pos["y"] if "y" in pos and pos["y"] is not None else 0,
pos["z"] if "z" in pos and pos["z"] is not None else 0,
)
self.cell_info[sonata_pop]["pop_count"][pop] += 1
########################################################################
# Load simulation info into self.simulation_config
if self.simulation_config:
if self.simulation_config:
for m in self.simulation_config["manifest"]:
path = self.subs(self.simulation_config["manifest"][m])
self.substitutes[m] = path
for s1 in ["output"]:
for k in self.simulation_config[s1]:
self.simulation_config[s1][k] = self.subs(
self.simulation_config[s1][k]
)
for s1 in ["inputs"]:
for s2 in self.simulation_config[s1]:
for k in self.simulation_config[s1][s2]:
self.simulation_config[s1][s2][k] = self.subs(
self.simulation_config[s1][s2][k]
)
if "node_sets_file" in self.simulation_config:
node_sets = load_json(
self.subs(self.simulation_config["node_sets_file"])
)
self.simulation_config["node_sets"] = node_sets
if not "node_sets" in self.simulation_config:
self.simulation_config["node_sets"] = {}
for sonata_pop in self.cell_info:
self.node_set_mappings[sonata_pop] = {}
for sindex in self.cell_info[sonata_pop]["pop_map"]:
nml_pop = self.cell_info[sonata_pop]["pop_map"][sindex][0]
nml_index = self.cell_info[sonata_pop]["pop_map"][sindex][1]
# Add all in this sonata_pop to a 'node_set' named after the sonata_pop
if not nml_pop in self.node_set_mappings[sonata_pop]:
self.node_set_mappings[sonata_pop][nml_pop] = []
self.node_set_mappings[sonata_pop][nml_pop].append(nml_index)
# pp.pprint(self.simulation_config)
# pp.pprint(self.pop_comp_info)
for node_set in self.simulation_config["node_sets"]:
self.node_set_mappings[node_set] = {}
node_set_props = self.simulation_config["node_sets"][node_set]
# print_v('===========Checking which cells in pops match node_set: %s = %s'%(node_set,node_set_props))
for sonata_pop in self.cell_info:
for sindex in self.cell_info[sonata_pop]["pop_map"]:
# print('Does %s %s match %s?'%(sonata_pop, sindex, node_set_props))
type = self.cell_info[sonata_pop]["types"][sindex]
type_info = self.node_types[sonata_pop][type]
nml_pop = self.cell_info[sonata_pop]["pop_map"][sindex][0]
nml_index = self.cell_info[sonata_pop]["pop_map"][sindex][1]
if (
"population" in node_set_props
and node_set_props["population"] == sonata_pop
):
if (
"node_id" in node_set_props
and sindex in node_set_props["node_id"]
):
if not nml_pop in self.node_set_mappings[node_set]:
self.node_set_mappings[node_set][nml_pop] = []
self.node_set_mappings[node_set][nml_pop].append(
nml_index
)
matches = _matches_node_set_props(type_info, node_set_props)
# print_v('Node %i in %s (NML: %s[%i]) has type %s (%s); matches: %s'%(sindex, sonata_pop, nml_pop, nml_index, type, type_info, matches))
if matches:
if not nml_pop in self.node_set_mappings[node_set]:
self.node_set_mappings[node_set][nml_pop] = []
self.node_set_mappings[node_set][nml_pop].append(nml_index)
##pp.pprint(self.node_set_mappings)
########################################################################
# Extract info from inputs in simulation_config
# pp.pprint(self.simulation_config)
for input in self.simulation_config["inputs"]:
info = self.simulation_config["inputs"][input]
# print_v(" - Adding input: %s which has info: %s"%(input, info))
self.input_comp_info[input] = {}
self.input_comp_info[input][info["input_type"]] = {}
node_set = info["node_set"]
if info["input_type"] == "current_clamp":
comp = "PG_%s" % input
self.input_comp_info[input][info["input_type"]][comp] = {
"amp": info["amp"],
"delay": info["delay"],
"duration": info["duration"],
}
for nml_pop_id in self.node_set_mappings[node_set]:
input_list_id = "il_%s_%s" % (input, nml_pop_id)
indices = self.node_set_mappings[node_set][nml_pop_id]
self.handler.handle_input_list(
input_list_id, nml_pop_id, comp, len(indices)
)
count = 0
for index in indices:
self.handler.handle_single_input(
input_list_id, count, cellId=index, segId=0, fract=0.5
)
count += 1
elif info["input_type"] == "spikes":
node_info = self.cell_info[node_set]
from pyneuroml.plot.PlotSpikes import read_sonata_spikes_hdf5_file
from pyneuroml.plot.PlotSpikes import POP_NAME_SPIKEFILE_WITH_GIDS
ids_times = read_sonata_spikes_hdf5_file(self.subs(info["input_file"]))
for id in ids_times[POP_NAME_SPIKEFILE_WITH_GIDS]:
times = ids_times[POP_NAME_SPIKEFILE_WITH_GIDS][id]
if id in node_info["pop_map"]:
nml_pop_id, cell_id = node_info["pop_map"][id]
print_v(
"Cell %i in Sonata node set %s (cell %s in nml pop %s) has %i spikes"
% (id, node_set, nml_pop_id, cell_id, len(times))
)
component = "%s__%i" % (nml_pop_id, cell_id)
self.input_comp_info[input][info["input_type"]][component] = {
"id": cell_id,
"times": times,
}
"""
input_list_id = 'il_%s_%i'%(input,cell_id)
self.handler.handle_input_list(input_list_id,
nml_pop_id,
component,
1)
self.handler.handle_single_input(input_list_id,
0,
cellId = cell_id,
segId = 0,
fract = 0.5)
"""
else:
print_v(
"Cell %i in Sonata node set %s NOT FOUND!" % (id, node_set)
)
else:
raise Exception(
"Sonata input type not yet supported: %s" % (info["input_type"])
)
########################################################################
# Use extracted edge info to create connections
projections_created = []
for conn in self.conn_info:
pre_node = self.conn_info[conn]["pre_node"]
post_node = self.conn_info[conn]["post_node"]
for i in range(len(self.conn_info[conn]["pre_id"])):
pre_id = self.conn_info[conn]["pre_id"][i]
post_id = self.conn_info[conn]["post_id"][i]
nsyns = (
self.conn_info[conn]["nsyns"][i]
if "nsyns" in self.conn_info[conn]
else 1
)
type = self.conn_info[conn]["edge_type_id"][i]
# print_v(' Conn with %i syns, type %s: %s(%s) -> %s(%s)'%(nsyns,type,pre_node,pre_id,post_node,post_id))
pre_pop, pre_i = self.cell_info[pre_node]["pop_map"][pre_id]
post_pop, post_i = self.cell_info[post_node]["pop_map"][post_id]
# print_v(' Mapped: Conn %s(%s) -> %s(%s)'%(pre_pop,pre_i,post_pop,post_i))
# print self.edges_info[conn][type]
# print self.cell_info[pre_node]
# print 11
# print self.node_types[pre_node]
# print 22
cell_type_pre = self.cell_info[pre_node]["types"][pre_id]
# print cell_type_pre
# print 444
pop_type_pre = self.node_types[pre_node][cell_type_pre]["model_type"]
# print pop_type_pre
# print 333
synapse = self.edges_info[conn][type]["dynamics_params"].split(".")[0]
self.syn_comp_info[synapse] = {}
# print self.edges_info[conn][type]
# pp.pprint(self.init_substitutes)
# pp.pprint(self.substitutes)
dynamics_params_file = (
self.subs(self.network_config["components"]["synaptic_models_dir"])
+ "/"
+ self.edges_info[conn][type]["dynamics_params"]
)
# print_v('Adding syn %s (at %s)'%(self.edges_info[conn][type]['dynamics_params'], dynamics_params_file))
# TODO: don't load this file every connection!!!
self.syn_comp_info[synapse]["dynamics_params"] = load_json(
dynamics_params_file
)
proj_id = "%s_%s_%s" % (pre_pop, post_pop, synapse)
sign = (
self.syn_comp_info[synapse]["dynamics_params"]["sign"]
if "sign" in self.syn_comp_info[synapse]["dynamics_params"]
else 1
)
weight = (
self.edges_info[conn][type]["syn_weight"]
if "syn_weight" in self.edges_info[conn][type]
else 1.0
)
syn_weight_edge_group_0 = (
self.conn_info[conn]["syn_weight_edge_group_0"][i]
if "syn_weight_edge_group_0" in self.conn_info[conn]
else None
)
# Assume this overrides value from csv file...
if syn_weight_edge_group_0:
weight = syn_weight_edge_group_0
# print_v('Adding syn %s (at %s), weight: %s, sign: %s, nsyns: %s'%(self.edges_info[conn][type]['dynamics_params'], dynamics_params_file, weight, sign, nsyns))
weight_scale = 0.001
if "level_of_detail" in self.syn_comp_info[synapse]["dynamics_params"]:
weight_scale = 1
weight = weight_scale * sign * weight * nsyns
delay = (
self.edges_info[conn][type]["delay"]
if "delay" in self.edges_info[conn][type]
else 0
)
if not pop_type_pre == "virtual":
if not proj_id in projections_created:
self.handler.handle_projection(
proj_id, pre_pop, post_pop, synapse
)
projections_created.append(proj_id)
self.handler.handle_connection(
proj_id,
i,
pre_pop,
post_pop,
synapse,
pre_i,
post_i,
weight=weight,
delay=delay,
)
else:
component = "%s__%i" % (pre_pop, pre_i)
# print_v(' --- Connecting %s to %s[%s]'%(component, post_pop, post_i))
# self.input_comp_info[input][info['input_type']][component] ={'id': cell_id, 'times': times}
input_list_id = "il_%s_%s_%i_%i" % (component, post_pop, post_i, i)
self.handler.handle_input_list(
input_list_id, post_pop, component, 1
)
self.handler.handle_single_input(
input_list_id,
0,
cellId=post_i,
segId=0,
fract=0.5,
weight=weight,
)
"""
print('~~~~~~~~~~~~~~~')
print('node_types:')
pp.pprint(self.node_types)
print('~~~~~~~~~~~~~~~')
print('cell_info:')
pp.pprint(self.cell_info)
print('================')"""
def parse_group(self, g):
# print("+++++++++++++++Parsing group: "+ str(g)+", name: "+g._v_name)
for node in g:
# print(" ------Sub node: %s, class: %s, name: %s (parent: %s)" % (node,node._c_classid,node._v_name, g._v_name))
if node._c_classid == "GROUP":
if g._v_name == "nodes":
son_pop_id = node._v_name.replace("-", "_")
self.current_sonata_pop = son_pop_id
self.cell_info[self.current_sonata_pop] = {}
self.cell_info[self.current_sonata_pop]["types"] = {}
self.cell_info[self.current_sonata_pop]["type_count"] = {}
if g._v_name == self.current_sonata_pop:
node_group = node._v_name
self.current_node_group = node_group
self.cell_info[self.current_sonata_pop][
self.current_node_group
] = {}
self.cell_info[self.current_sonata_pop][self.current_node_group][
"locations"
] = {}
if g._v_name == "edges":
edge_id = node._v_name.replace("-", "_")
# print(' Found edge: %s'%edge_id)
self.current_edge = edge_id
self.conn_info[self.current_edge] = {}
if g._v_name == self.current_edge:
self.current_pre_node = g._v_name.split("_to_")[0]
self.current_post_node = g._v_name.split("_to_")[1]
# print(' Found edge %s -> %s'%(self.current_pre_node, self.current_post_node))
self.conn_info[self.current_edge][
"pre_node"
] = self.current_pre_node
self.conn_info[self.current_edge][
"post_node"
] = self.current_post_node
self.parse_group(node)
if self._is_dataset(node):
self.parse_dataset(node)
self.current_node_group = None
def _is_dataset(self, node):
return node._c_classid == "ARRAY" or node._c_classid == "CARRAY"
def parse_dataset(self, d):
# print_v("Parsing dataset/array: %s; at node: %s, node_group %s"%(str(d), self.current_sonata_pop, self.current_node_group))
if self.current_node_group: # e.g. parent group is 0 with child datasets x,y,z
for i in range(0, d.shape[0]):
if (
not i
in self.cell_info[self.current_sonata_pop][self.current_node_group][
"locations"
]
):
self.cell_info[self.current_sonata_pop][self.current_node_group][
"locations"
][i] = {}
self.cell_info[self.current_sonata_pop][self.current_node_group][
"locations"
][i][d.name] = d[i]
elif (
self.current_sonata_pop
): # e.g. parent group is cortex with child datasets node_id etc.
if d.name == "node_group_id":
for i in range(0, d.shape[0]):
if not d[i] == 0:
raise Exception(
"Error: currently only support node_group_id==0!"
)
if d.name == "node_id":
for i in range(0, d.shape[0]):
if not d[i] == i:
raise Exception(
"Error: currently only support dataset node_id when index is same as node_id (fails in %s)...!"
% d
)
if d.name == "node_type_id":
for i in range(0, d.shape[0]):
self.cell_info[self.current_sonata_pop]["types"][i] = d[i]
if (
not d[i]
in self.cell_info[self.current_sonata_pop]["type_count"]
):
self.cell_info[self.current_sonata_pop]["type_count"][d[i]] = 0
self.cell_info[self.current_sonata_pop]["type_count"][d[i]] += 1
elif d.name == "source_node_id":
self.conn_info[self.current_edge]["pre_id"] = [i for i in d]
elif d.name == "edge_type_id":
self.conn_info[self.current_edge]["edge_type_id"] = [int(i) for i in d]
elif d.name == "target_node_id":
self.conn_info[self.current_edge]["post_id"] = [i for i in d]
elif d.name == "nsyns":
self.conn_info[self.current_edge]["nsyns"] = [i for i in d]
elif d.name == "edge_group_id":
for i in range(0, d.shape[0]):
if not d[i] == 0:
raise Exception("Error: currently only support edge_group_id==0!")
elif d.name == "syn_weight":
# Has to be edge_group_id==0, as above check would fail...
self.conn_info[self.current_edge]["syn_weight_edge_group_0"] = [
i for i in d
]
else:
print_v("Unhandled dataset: %s" % d.name)
def add_neuroml_components(self, nml_doc):
"""
Based on cell & synapse properties found, create the corresponding NeuroML components
"""
is_nest = False
print_v("Adding NeuroML cells to: %s" % nml_doc.id)
# pp.pprint(self.pop_comp_info)
for c in self.pop_comp_info:
info = self.pop_comp_info[c]
model_template = (
info["model_template"]
if "model_template" in info
else (
info["dynamics_params"]["type"]
if "dynamics_params" in info
else info["model_type"]
)
)
print_v(" - Adding %s: %s" % (model_template, info))
if (
info["model_type"] == "point_process"
and model_template == "nest:iaf_psc_alpha"
):
is_nest = True
from neuroml import IF_curr_alpha
pynn0 = IF_curr_alpha(
id=c,
cm=info["dynamics_params"]["C_m"] / 1000.0,
i_offset="0",
tau_m=info["dynamics_params"]["tau_m"],
tau_refrac=info["dynamics_params"]["t_ref"],
tau_syn_E="1",
tau_syn_I="1",
v_init="-70",
v_reset=info["dynamics_params"]["V_reset"],
v_rest=info["dynamics_params"]["E_L"],
v_thresh=info["dynamics_params"]["V_th"],
)
nml_doc.IF_curr_alpha.append(pynn0)
elif (
info["model_type"] == "point_process"
and model_template == "NEURON_IntFire1"
):
contents = """<Lems>
<intFire1Cell id="%s" thresh="1mV" reset="0mV" tau="%sms" refract="%sms"/>
</Lems>""" % (
c,
info["dynamics_params"]["tau"] * 1000,
info["dynamics_params"]["refrac"] * 1000,
)
cell_file_name = "%s.xml" % c
cell_file = open(cell_file_name, "w")
cell_file.write(contents)
cell_file.close()
self.nml_includes.append(cell_file_name)
self.nml_includes.append(
"../../../examples/sonatatest/IntFireCells.xml"
)
else:
from neuroml import IafRefCell
IafRefCell0 = IafRefCell(
id=DUMMY_CELL,
C=".2 nF",
thresh="1mV",
reset="0mV",
refract="3ms",
leak_conductance="1.2 nS",
leak_reversal="0mV",
)
print_v(" - Adding: %s" % IafRefCell0)
nml_doc.iaf_ref_cells.append(IafRefCell0)
print_v("Adding NeuroML synapses to: %s" % nml_doc.id)
# pp.pprint(self.syn_comp_info)
for s in self.syn_comp_info:
dyn_params = self.syn_comp_info[s]["dynamics_params"]
print_v(" - Syn: %s: %s" % (s, dyn_params))
if (
"level_of_detail" in dyn_params
and dyn_params["level_of_detail"] == "exp2syn"
):
from neuroml import ExpTwoSynapse
syn = ExpTwoSynapse(
id=s,
gbase="1nS",
erev="%smV" % dyn_params["erev"],
tau_rise="%sms" % dyn_params["tau1"],
tau_decay="%sms" % dyn_params["tau2"],
)
# print("Adding syn: %s"%syn)
nml_doc.exp_two_synapses.append(syn)
elif (
"level_of_detail" in dyn_params
and dyn_params["level_of_detail"] == "instanteneous"
):
contents = """<Lems>
<impulseSynapse id="%s"/>
</Lems>""" % (
s
)
syn_file_name = "%s.xml" % s
syn_file = open(syn_file_name, "w")
syn_file.write(contents)
syn_file.close()
self.nml_includes.append(syn_file_name)
# self.nml_includes.append('../examples/sonatatest/IntFireCells.xml')
else:
from neuroml import AlphaCurrSynapse
pynnSynn0 = AlphaCurrSynapse(id=s, tau_syn="2")
# print("Adding syn: %s"%pynnSynn0)
nml_doc.alpha_curr_synapses.append(pynnSynn0)
print_v("Adding NeuroML inputs to: %s" % nml_doc.id)
# pp.pprint(self.input_comp_info)
for input in self.input_comp_info:
for input_type in self.input_comp_info[input]:
if input_type == "spikes":
for comp_id in self.input_comp_info[input][input_type]:
info = self.input_comp_info[input][input_type][comp_id]
print_v("Adding input %s: %s" % (comp_id, info.keys()))
nest_syn = _get_default_nest_syn(nml_doc)
from neuroml import TimedSynapticInput, Spike
tsi = TimedSynapticInput(
id=comp_id,
synapse=nest_syn.id,
spike_target="./%s" % nest_syn.id,
)
nml_doc.timed_synaptic_inputs.append(tsi)
for ti in range(len(info["times"])):
tsi.spikes.append(
Spike(id=ti, time="%sms" % info["times"][ti])
)
elif input_type == "current_clamp":
from neuroml import PulseGenerator
for comp_id in self.input_comp_info[input][input_type]:
info = self.input_comp_info[input][input_type][comp_id]
# TODO remove when https://github.com/AllenInstitute/sonata/issues/42 is fixed!
amp_template = "%spA" if is_nest else "%snA" #
pg = PulseGenerator(
id=comp_id,
delay="%sms" % info["delay"],
duration="%sms" % info["duration"],
amplitude=amp_template % info["amp"],
)
nml_doc.pulse_generators.append(pg)
def generate_lems_file(self, nml_file_name, nml_doc):
"""
Generate a LEMS file to use in simulations of the NeuroML file
"""
# pp.pprint(self.simulation_config)