-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsynapses.py
3397 lines (2917 loc) · 147 KB
/
synapses.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 sys, collections, copy, itertools, math, pprint, uuid, time, traceback
from functools import reduce
from collections import defaultdict, namedtuple
import numpy as np
from scipy import signal, spatial
from neuroh5.io import write_cell_attributes
from dentate.nnls import nnls_gdal
from dentate.cells import get_distance_to_node, get_donor, get_mech_rules_dict, get_param_val_by_distance, \
import_mech_dict_from_file, make_section_graph, custom_filter_if_terminal, \
custom_filter_modify_slope_if_terminal, custom_filter_by_branch_order
from dentate.neuron_utils import h, default_ordered_sec_types, mknetcon, mknetcon_vecstim, interplocs, list_find
from dentate.utils import KDDict, ExprClosure, Promise, NamedTupleWithDocstring, get_module_logger, generator_ifempty, map, range, str, \
viewitems, viewkeys, zip, zip_longest, partitionn, rejection_sampling
# This logger will inherit its settings from the root logger, created in dentate.env
logger = get_module_logger(__name__)
SynParam = namedtuple('SynParam',
('population',
'source',
'sec_type',
'syn_name',
'param_path',
'param_range',
'phenotype'),
defaults=(None,
None,
None,
None,
None,
None,
None))
def syn_param_from_dict(d):
return SynParam(*[d[key] for key in SynParam._fields])
def parse_flat_syn_params_with_index(pop_params_dict):
"""Parses synaptic parameters of the form:
population:
gid:
- index:
- postsyn population
- presyn population list
- section type
- synaptic mechanism
- synaptic mechanism parameter path
- parameter value
"""
pop_params_tuple_dict = {}
for this_pop_name, this_pop_param_dict in viewitems(pop_params_dict):
this_pop_params_tuple_dict = defaultdict(lambda: defaultdict(list))
for this_gid, this_gid_index_dict in viewitems(this_pop_param_dict):
for this_index, this_gid_index_params in viewitems(this_gid_index_dict):
for this_gid_param in this_gid_index_params:
if len(this_gid_param) > 6:
(
this_population,
source,
sec_type,
syn_name,
param_path,
phenotype_id,
param_val,
) = this_gid_param
else:
(
this_population,
source,
sec_type,
syn_name,
param_path,
param_val,
) = this_gid_param
phenotype_id = None
syn_param = SynParam(
this_population,
source,
sec_type,
syn_name,
param_path,
phenotype_id,
)
this_pop_params_tuple_dict[this_gid][this_index].append(
(syn_param, param_val)
)
pop_params_tuple_dict[this_pop_name] = dict(
this_pop_params_tuple_dict
)
return pop_params_tuple_dict
def parse_flat_syn_params(pop_params_dict):
"""Parses synaptic parameters of the form:
population:
gid:
- postsyn population
- presyn population list
- section type
- synaptic mechanism
- synaptic mechanism parameter path
- parameter value
"""
pop_params_tuple_dict = {}
for this_pop_name, this_pop_param_dict in viewitems(pop_params_dict):
this_pop_params_tuple_dict = defaultdict(list)
for this_gid, this_gid_params in viewitems(this_pop_param_dict):
for this_gid_param in this_gid_params:
(
this_population,
source,
sec_type,
syn_name,
param_path,
param_val,
) = this_gid_param
syn_param = SynParam(
this_population,
source,
sec_type,
syn_name,
param_path,
None,
)
this_pop_params_tuple_dict[this_gid].append(
(syn_param, param_val)
)
pop_params_tuple_dict[this_pop_name] = dict(
this_pop_params_tuple_dict
)
return pop_params_tuple_dict
class SynapseSource(object):
"""This class provides information about the presynaptic (source) cell
connected to a synapse.
- gid - gid of source cell (int)
- population - population index of source cell (int)
- delay - connection delay (float)
"""
__slots__ = 'gid', 'population', 'delay'
def __init__(self):
self.gid = None
self.population = None
self.delay = None
def __repr__(self):
if self.delay is None:
repr_delay = 'None'
else:
repr_delay = f'{self.delay:.02f}'
return f'SynapseSource({self.gid}, {self.population}, {repr_delay})'
def __str__(self):
if self.delay is None:
str_delay = 'None'
else:
str_delay = f'{self.delay:.02f}'
return f'SynapseSource({self.gid}, {self.population}, {str_delay})'
SynapsePointProcess = NamedTupleWithDocstring(
"""This class provides information about the point processes associated with a synapse.
- mech - dictionary of synapse mechanisms
- netcon - dictionary of netcons
- vecstim - dictionary of vecstims
""",
"SynapsePointProcess",
['mech', 'netcon', 'vecstim'])
Synapse = NamedTupleWithDocstring(
"""A container for synapse configuration, synapse mechanism instantiation,
and associated netcon/vecstim instances.
- syn_type - enumerated synapse type (int)
- swc_type - enumerated swc type (int)
- syn_layer - enumerated synapse layer (int)
- syn_loc - synapse location in segment (float)
- syn_section - synapse section index (int)
- source: instance of SynapseSource with the slots:
- gid - source cell gid (int)
- population - enumerated source population index (int)
- delay - connection delay (float)
- attr_dict - dictionary of attributes per synapse mechanism
(for cases when multiple mechanisms are associated with a
synapse, e.g. GABA_A and GABA_B)
""",
'Synapse',
['syn_type',
'swc_type',
'syn_layer',
'syn_loc',
'syn_section',
'source',
'attr_dict'
])
class SynapseAttributes(object):
"""This class provides an interface to store, retrieve, and modify
attributes of synaptic mechanisms. Handles instantiation of
complex subcellular gradients of synaptic mechanism attributes.
"""
def __init__(self, env, syn_mech_names, syn_param_rules):
"""An Env object containing imported network configuration metadata
uses an instance of SynapseAttributes to track all metadata
related to the identity, location, and configuration of all
synaptic connections in the network.
:param env: :class:'Env'
:param syn_mech_names: dict of the form: { label: mechanism name }
:param syn_param_rules: dict of the form:
{ mechanism name:
mech_file: path.mod
mech_params: list of parameter names
netcon_params: dictionary { parameter name: index }
}
"""
self.env = env
self.syn_mech_names = syn_mech_names
self.syn_config = { k: v['synapses'] for k, v in viewitems(env.celltypes) if 'synapses' in v }
self.syn_param_rules = syn_param_rules
self.syn_name_index_dict = {label: index for index, label in enumerate(syn_mech_names)} # int : mech_name dict
self.syn_id_attr_dict = defaultdict(lambda: defaultdict(lambda: None))
self.syn_id_attr_backup_dict = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: None)))
self.sec_dict = defaultdict(lambda: defaultdict(lambda: dict()))
self.pps_dict = defaultdict(lambda: defaultdict(lambda: SynapsePointProcess(mech={}, netcon={}, vecstim={})))
self.presyn_names = {id: name for name, id in viewitems(env.Populations)}
self.filter_cache = {}
def init_syn_id_attrs_from_iter(self, cell_iter, attr_type='dict', attr_tuple_index=None, debug=False):
"""
Initializes synaptic attributes given an iterator that returns (gid, attr_dict).
See `init_syn_id_attrs` for details on the format of the input dictionary.
"""
first_gid = True
if attr_type == 'dict':
for (gid, attr_dict) in cell_iter:
syn_ids = attr_dict['syn_ids']
syn_layers = attr_dict['syn_layers']
syn_types = attr_dict['syn_types']
swc_types = attr_dict['swc_types']
syn_secs = attr_dict['syn_secs']
syn_locs = attr_dict['syn_locs']
self.init_syn_id_attrs(gid, syn_ids, syn_layers, syn_types, swc_types, syn_secs, syn_locs)
elif attr_type == 'tuple':
syn_ids_ind = attr_tuple_index.get('syn_ids', None)
syn_locs_ind = attr_tuple_index.get('syn_locs', None)
syn_layers_ind = attr_tuple_index.get('syn_layers', None)
syn_types_ind = attr_tuple_index.get('syn_types', None)
swc_types_ind = attr_tuple_index.get('swc_types', None)
syn_secs_ind = attr_tuple_index.get('syn_secs', None)
syn_locs_ind = attr_tuple_index.get('syn_locs', None)
for (gid, attr_tuple) in cell_iter:
syn_ids = attr_tuple[syn_ids_ind]
syn_layers = attr_tuple[syn_layers_ind]
syn_types = attr_tuple[syn_types_ind]
swc_types = attr_tuple[swc_types_ind]
syn_secs = attr_tuple[syn_secs_ind]
syn_locs = attr_tuple[syn_locs_ind]
self.init_syn_id_attrs(gid, syn_ids, syn_layers, syn_types, swc_types, syn_secs, syn_locs)
else:
raise RuntimeError(f'init_syn_id_attrs_from_iter: unrecognized input attribute type {attr_type}')
def init_syn_id_attrs(self, gid, syn_ids, syn_layers, syn_types, swc_types, syn_secs, syn_locs):
"""
Initializes synaptic attributes for the given cell gid.
Only the intrinsic properties of a synapse, such as type, layer, location are set.
Connection edge attributes such as source gid, point process
parameters, and netcon/vecstim objects are initialized to None
or empty dictionaries.
- syn_ids: synapse ids
- syn_layers: layer index for each synapse id
- syn_types: synapse type for each synapse id
- swc_types: swc type for each synapse id
- syn_secs: section index for each synapse id
- syn_locs: section location for each synapse id
"""
if gid in self.syn_id_attr_dict:
raise RuntimeError(f'Entry {gid} exists in synapse attribute dictionary')
else:
syn_dict = self.syn_id_attr_dict[gid]
sec_dict = self.sec_dict[gid]
for i, (syn_id, syn_layer, syn_type, swc_type, syn_sec, syn_loc) in \
enumerate(zip_longest(syn_ids, syn_layers, syn_types, swc_types, syn_secs, syn_locs)):
syn = Synapse(syn_type=syn_type, syn_layer=syn_layer, syn_section=syn_sec, syn_loc=syn_loc,
swc_type=swc_type, source=SynapseSource(), attr_dict=defaultdict(dict))
syn_dict[syn_id] = syn
sec_dict[syn_sec][syn_id] = syn
def modify_syn_locs(self, gid, syn_ids, syn_secs, syn_locs):
"""
Modifies synaptic section and location for existing synapses.
"""
syn_dict = self.syn_id_attr_dict[gid]
sec_dict = self.sec_dict[gid]
for syn_id, syn_sec, syn_loc in zip(syn_ids, syn_secs, syn_locs):
syn = syn_dict[syn_id]
old_syn_sec = syn.syn_section
del(sec_dict[old_syn_sec][syn_id])
syn = syn._replace(syn_section=syn_sec, syn_loc=syn_loc)
syn_dict[syn_id] = syn
sec_dict[syn_sec][syn_id] = syn
def init_edge_attrs(self, gid, presyn_name, presyn_gids, edge_syn_ids, delays=None):
"""
Sets connection edge attributes for the specified synapse ids.
:param gid: gid for post-synaptic (target) cell (int)
:param presyn_name: name of presynaptic (source) population (string)
:param presyn_ids: gids for presynaptic (source) cells (array of int)
:param edge_syn_ids: synapse ids on target cells to be used for connections (array of int)
:param delays: axon conduction (netcon) delays (array of float)
"""
presyn_index = int(self.env.Populations[presyn_name])
connection_velocity = float(self.env.connection_velocity[presyn_name])
if delays is None:
delays = [2.0*h.dt] * len(edge_syn_ids)
syn_id_dict = self.syn_id_attr_dict[gid]
for edge_syn_id, presyn_gid, delay in zip_longest(edge_syn_ids, presyn_gids, delays):
syn = syn_id_dict[edge_syn_id]
if syn is None:
raise RuntimeError(f'init_edge_attrs: gid {gid}: synapse id {edge_syn_id} has not been initialized')
if syn.source.gid is not None:
raise RuntimeError('init_edge_attrs: gid {gid}: synapse id {edge_syn_id} has already been initialized with edge attributes')
syn.source.gid = presyn_gid
syn.source.population = presyn_index
syn.source.delay = delay
def init_edge_attrs_from_iter(self, pop_name, presyn_name, attr_info, edge_iter, set_edge_delays=True):
"""
Initializes edge attributes for all cell gids returned by iterator.
:param pop_name: name of postsynaptic (target) population (string)
:param source_name: name of presynaptic (source) population (string)
:param attr_info: dictionary mapping attribute name to indices in iterator tuple
:param edge_iter: edge attribute iterator
:param set_edge_delays: bool
"""
connection_velocity = float(self.env.connection_velocity[presyn_name])
if pop_name in attr_info and presyn_name in attr_info[pop_name]:
edge_attr_info = attr_info[pop_name][presyn_name]
else:
raise RuntimeError(f'init_edge_attrs_from_iter: missing edge attributes for projection {presyn_name} -> {pop_name}')
if 'Synapses' in edge_attr_info and \
'syn_id' in edge_attr_info['Synapses'] and \
'Connections' in edge_attr_info and \
'distance' in edge_attr_info['Connections']:
syn_id_attr_index = edge_attr_info['Synapses']['syn_id']
distance_attr_index = edge_attr_info['Connections']['distance']
else:
raise RuntimeError(f'init_edge_attrs_from_iter: missing edge attributes for projection {presyn_name} -> {pop_name}')
for (postsyn_gid, edges) in edge_iter:
presyn_gids, edge_attrs = edges
edge_syn_ids = edge_attrs['Synapses'][syn_id_attr_index]
edge_dists = edge_attrs['Connections'][distance_attr_index]
if set_edge_delays:
delays = [max((distance / connection_velocity), 2.0*h.dt) for distance in edge_dists]
else:
delays = None
self.init_edge_attrs(postsyn_gid, presyn_name, presyn_gids, edge_syn_ids, delays=delays)
def add_pps(self, gid, syn_id, syn_name, pps):
"""
Adds mechanism point process for the specified cell/synapse id/mechanism name.
:param gid: cell id
:param syn_id: synapse id
:param syn_name: synapse mechanism name
:param pps: hoc point process
"""
syn_index = self.syn_name_index_dict[syn_name]
gid_pps_dict = self.pps_dict[gid]
pps_dict = gid_pps_dict[syn_id]
if syn_index in pps_dict.mech:
raise RuntimeError(f'add_pps: gid {gid} Synapse id {syn_id} already has mechanism {syn_name}')
else:
pps_dict.mech[syn_index] = pps
return pps
def has_pps(self, gid, syn_id, syn_name):
"""
Returns True if the given synapse id already has the named mechanism, False otherwise.
:param gid: cell id
:param syn_id: synapse id
:param syn_name: synapse mechanism name
:return: bool
"""
syn_index = self.syn_name_index_dict[syn_name]
gid_pps_dict = self.pps_dict[gid]
pps_dict = gid_pps_dict[syn_id]
return syn_index in pps_dict.mech
def get_pps(self, gid, syn_id, syn_name, throw_error=True):
"""
Returns the mechanism for the given synapse id on the given cell.
:param gid: cell id
:param syn_id: synapse id
:param syn_name: mechanism name
:return: hoc point process
"""
syn_index = self.syn_name_index_dict[syn_name]
gid_pps_dict = self.pps_dict[gid]
pps_dict = gid_pps_dict[syn_id]
if syn_index in pps_dict.mech:
return pps_dict.mech[syn_index]
else:
if throw_error:
raise RuntimeError(f'get_pps: gid {gid} synapse id {syn_id} has no point process for mechanism {syn_name}')
else:
return None
def add_netcon(self, gid, syn_id, syn_name, nc):
"""
Adds a NetCon object for the specified cell/synapse id/mechanism name.
:param gid: cell id
:param syn_id: synapse id
:param syn_name: synapse mechanism name
:param nc: :class:'h.NetCon'
"""
syn_index = self.syn_name_index_dict[syn_name]
gid_pps_dict = self.pps_dict[gid]
pps_dict = gid_pps_dict[syn_id]
if syn_index in pps_dict.netcon:
raise RuntimeError(f'add_netcon: gid {gid} Synapse id {syn_id} mechanism {syn_name} already has netcon')
else:
pps_dict.netcon[syn_index] = nc
return nc
def has_netcon(self, gid, syn_id, syn_name):
"""
Returns True if a netcon exists for the specified cell/synapse id/mechanism name, False otherwise.
:param gid: cell id
:param syn_id: synapse id
:param syn_name: synapse mechanism name
:return: bool
"""
syn_index = self.syn_name_index_dict[syn_name]
gid_pps_dict = self.pps_dict[gid]
pps_dict = gid_pps_dict[syn_id]
return syn_index in pps_dict.netcon
def get_netcon(self, gid, syn_id, syn_name, throw_error=True):
"""
Returns the NetCon object associated with the specified cell/synapse id/mechanism name.
:param gid: cell id
:param syn_id: synapse id
:param syn_name: synapse mechanism name
:return: :class:'h.NetCon'
"""
syn_index = self.syn_name_index_dict[syn_name]
gid_pps_dict = self.pps_dict[gid]
pps_dict = gid_pps_dict[syn_id]
if syn_index in pps_dict.netcon:
return pps_dict.netcon[syn_index]
else:
if throw_error:
raise RuntimeError(f'get_netcon: gid {gid} synapse id {syn_id} has no netcon for mechanism {syn_name}')
else:
return None
def del_netcon(self, gid, syn_id, syn_name, throw_error=True):
"""
Removes a NetCon object for the specified cell/synapse id/mechanism name.
:param gid: cell id
:param syn_id: synapse id
:param syn_name: synapse mechanism name
"""
syn_index = self.syn_name_index_dict[syn_name]
gid_pps_dict = self.pps_dict[gid]
pps_dict = gid_pps_dict[syn_id]
if syn_index in pps_dict.netcon:
del pps_dict.netcon[syn_index]
else:
if throw_error:
raise RuntimeError(f'del_netcon: gid {gid} synapse id {syn_id} has no netcon for mechanism {syn_name}')
def add_vecstim(self, gid, syn_id, syn_name, vs, nc):
"""
Adds a VecStim object and associated NetCon for the specified cell/synapse id/mechanism name.
:param gid: cell id
:param syn_id: synapse id
:param syn_name: synapse mechanism name
:param vs: :class:'h.VecStim'
:param nc: :class:'h.NetCon'
"""
syn_index = self.syn_name_index_dict[syn_name]
gid_pps_dict = self.pps_dict[gid]
pps_dict = gid_pps_dict[syn_id]
if syn_index in pps_dict.vecstim:
raise RuntimeError(f'add_vecstim: gid {gid} synapse id {syn_id} mechanism {syn_name} already has vecstim')
else:
pps_dict.vecstim[syn_index] = vs, nc
return vs
def has_vecstim(self, gid, syn_id, syn_name):
"""
Returns True if a vecstim exists for the specified cell/synapse id/mechanism name, False otherwise.
:param gid: cell id
:param syn_id: synapse id
:param syn_name: synapse mechanism name
:return: bool
"""
syn_index = self.syn_name_index_dict[syn_name]
gid_pps_dict = self.pps_dict[gid]
pps_dict = gid_pps_dict[syn_id]
return syn_index in pps_dict.vecstim
def get_vecstim(self, gid, syn_id, syn_name, throw_error=True):
"""
Returns the VecStim and NetCon objects associated with the specified cell/synapse id/mechanism name.
:param gid: cell id
:param syn_id: synapse id
:param syn_name: synapse mechanism name
:return: tuple of :class:'h.VecStim' :class:'h.NetCon'
"""
syn_index = self.syn_name_index_dict[syn_name]
gid_pps_dict = self.pps_dict[gid]
pps_dict = gid_pps_dict[syn_id]
if syn_index in pps_dict.vecstim:
return pps_dict.vecstim[syn_index]
else:
if throw_error:
raise RuntimeError(f'get_vecstim: gid {gid} synapse {syn_id}: vecstim for mechanism {syn_name} not found')
else:
return None
def has_mech_attrs(self, gid, syn_id, syn_name):
"""
Returns True if mechanism attributes have been specified for the given cell id/synapse id/mechanism name, False otherwise.
:param gid: cell id
:param syn_id: synapse id
:param syn_name: synapse mechanism name
:return: bool
"""
syn_index = self.syn_name_index_dict[syn_name]
syn_id_dict = self.syn_id_attr_dict[gid]
syn = syn_id_dict[syn_id]
return syn_index in syn.attr_dict
def get_mech_attrs(self, gid, syn_id, syn_name, throw_error=True):
"""
Returns mechanism attribute dictionary associated with the given cell id/synapse id/mechanism name, False otherwise.
:param gid: cell id
:param syn_id: synapse id
:param syn_name: synapse mechanism name
:return: dict
"""
syn_index = self.syn_name_index_dict[syn_name]
syn_id_dict = self.syn_id_attr_dict[gid]
syn = syn_id_dict[syn_id]
if syn_index in syn.attr_dict:
return syn.attr_dict[syn_index]
else:
if throw_error:
raise RuntimeError(f'get_mech_attrs: gid {gid} synapse {syn_id}: attributes for mechanism {syn_name} not found')
else:
return None
def add_mech_attrs(self, gid, syn_id, syn_name, params, append=False):
"""
Specifies mechanism attribute dictionary for the given cell id/synapse id/mechanism name. Assumes mechanism
attributes have not been set yet for this synapse mechanism.
:param gid: cell id
:param syn_id: synapse id
:param syn_name: synapse mechanism name
:param params: dict
:param append: whether to append attribute values with the same attribute name
"""
self.add_mech_attrs_from_iter(gid, syn_name, iter({syn_id: params}), multiple='error', append=append)
def stash_syn_attrs(self, pop_name, gid):
"""
Preserves synaptic attributes for the given cell id.
:param pop_name: population name
:param gid: cell id
:param syn_id: synapse id
"""
rules = self.syn_param_rules
syn_id_dict = self.syn_id_attr_dict[gid]
syn_id_backup_dict = self.syn_id_attr_backup_dict[gid]
stash_id = uuid.uuid4()
syn_id_backup_dict[stash_id] = copy.deepcopy(syn_id_dict)
return stash_id
def restore_syn_attrs(self, pop_name, gid, stash_id):
"""
Restores synaptic attributes for the given cell id.
:param pop_name: population name
:param gid: cell id
:param syn_id: synapse id
"""
rules = self.syn_param_rules
syn_id_backup_dict = self.syn_id_attr_backup_dict[gid][stash_id]
if syn_id_backup_dict is not None:
self.syn_id_attr_dict[gid] = copy.deepcopy(syn_id_backup_dict)
del(self.syn_id_attr_backup_dict[gid][stash_id])
def modify_mech_attrs(self, pop_name, gid, syn_id, syn_name, params, expr_param_check='ignore'):
"""
Modifies mechanism attributes for the given cell id/synapse id/mechanism name.
:param pop_name: population name
:param gid: cell id
:param syn_id: synapse id
:param syn_name: synapse mechanism name
:param params: dict
"""
rules = self.syn_param_rules
syn_index = self.syn_name_index_dict[syn_name]
syn_id_dict = self.syn_id_attr_dict[gid]
mech_name = self.syn_mech_names[syn_name]
syn = syn_id_dict[syn_id]
presyn_name = self.presyn_names.get(syn.source.population, None)
if presyn_name:
connection_syn_params = self.env.connection_config[pop_name][presyn_name].mechanisms
else:
connection_syn_params = None
mech_params = {}
if connection_syn_params is not None:
if 'default' in connection_syn_params:
section_syn_params = connection_syn_params['default']
else:
section_syn_params = connection_syn_params[syn.swc_type]
mech_params = section_syn_params.get(syn_name, {})
attr_dict = syn.attr_dict[syn_index]
for k, v in viewitems(params):
if k in rules[mech_name]['mech_params']:
mech_param = mech_params.get(k, None)
if isinstance(mech_param, ExprClosure):
if mech_param.parameters[0] == 'delay':
new_val = mech_param(syn.source.delay)
else:
raise RuntimeError(f'modify_mech_attrs: unknown dependent expression parameter {mech_param.parameters}')
else:
new_val = v
assert(new_val is not None)
old_val = attr_dict.get(k, mech_param)
if isinstance(new_val, ExprClosure):
if isinstance(old_val, Promise):
old_val.clos = new_val
else:
attr_dict[k] = Promise(new_val, old_val)
elif isinstance(new_val, dict):
if isinstance(old_val, Promise):
for sk, sv in viewitems(new_val):
old_val.clos[sk] = sv
elif isinstance(old_val, ExprClosure):
for sk, sv in viewitems(new_val):
old_val[sk] = sv
else:
if expr_param_check == 'ignore':
pass
else:
raise RuntimeError(f'modify_mech_attrs: dictionary value provided to a non-expression parameter {k}')
else:
attr_dict[k] = new_val
elif k in rules[mech_name]['netcon_params']:
mech_param = mech_params.get(k, None)
if isinstance(mech_param, ExprClosure):
if mech_param.parameters[0] == 'delay':
new_val = mech_param(syn.source.delay)
else:
raise RuntimeError(f'modify_mech_attrs: unknown dependent expression parameter {mech_param.parameters}')
else:
new_val = v
assert(new_val is not None)
old_val = attr_dict.get(k, mech_param)
if isinstance(new_val, ExprClosure):
if isinstance(old_val, Promise):
old_val.clos = new_val
else:
attr_dict[k] = Promise(new_val, old_val)
elif isinstance(new_val, dict):
if isinstance(old_val, Promise):
for sk, sv in viewitems(new_val):
old_val.clos[sk] = sv
elif isinstance(old_val, ExprClosure):
for sk, sv in viewitems(new_val):
old_val[sk] = sv
else:
if expr_param_check == 'ignore':
pass
else:
raise RuntimeError('modify_mech_attrs: dictionary value provided to a non-expression parameter '
f'{k} mechanism: {mech_name} presynaptic: {presyn_name} old value: {old_val}')
else:
attr_dict[k] = new_val
else:
raise RuntimeError(f'modify_mech_attrs: unknown type of parameter {k}')
syn.attr_dict[syn_index] = attr_dict
def add_mech_attrs_from_iter(self, gid, syn_name, params_iter, multiple='error', append=False):
"""
Adds mechanism attributes for the given cell id/synapse id/synapse mechanism.
:param gid: cell id
:param syn_id: synapse id
:param syn_name: synapse mechanism name
:param params_iter: iterator
:param multiple: behavior when an attribute value is provided for a synapse that already has attributes:
- 'error' (default): raise an error
- 'skip': do not update attribute value
- 'overwrite': overwrite value
:param append: whether to append attribute values with the same attribute name
"""
syn_index = self.syn_name_index_dict[syn_name]
syn_id_dict = self.syn_id_attr_dict[gid]
for syn_id, params_dict in params_iter:
syn = syn_id_dict[syn_id]
if syn is None:
raise RuntimeError('add_mech_attrs_from_iter: '
f'gid {gid} synapse id {syn_id} has not been created yet')
if syn_index in syn.attr_dict:
if multiple == 'error':
raise RuntimeError('add_mech_attrs_from_iter: '
f'gid {gid} synapse id {syn_id} mechanism {syn_name} already has parameters')
elif multiple == 'skip':
continue
elif multiple == 'overwrite':
pass
else:
raise RuntimeError(f'add_mech_attrs_from_iter: unknown multiple value {multiple}')
attr_dict = syn.attr_dict[syn_index]
for k, v in viewitems(params_dict):
if v is None:
raise RuntimeError('add_mech_attrs_from_iter: '
f'gid {gid} synapse id {syn_id} mechanism {syn_name} parameter {k} has no value')
if append:
k_val = attr_dict.get(k, [])
k_val.append(v)
attr_dict[k] = k_val
else:
attr_dict[k] = v
def filter_synapses(self, gid, syn_sections=None, syn_indexes=None, syn_types=None, layers=None, sources=None,
swc_types=None, cache=False):
"""
Returns a subset of the synapses of the given cell according to the given criteria.
:param gid: int
:param syn_sections: array of int
:param syn_indexes: array of int: syn_ids
:param syn_types: list of enumerated type: synapse category
:param layers: list of enumerated type: layer
:param sources: list of enumerated type: population names of source projections
:param swc_types: list of enumerated type: swc_type
:param cache: bool
:return: dictionary { syn_id: { attribute: value } }
"""
matches = lambda items: all(
map(lambda query_item: (query_item[0] is None) or (query_item[1] in query_item[0]), items))
if cache:
cache_args = tuple([tuple(x) if isinstance(x, list) else x for x in
[gid, syn_sections, syn_indexes, syn_types, layers, sources, swc_types]])
if cache_args in self.filter_cache:
return self.filter_cache[cache_args]
if sources is None:
source_indexes = None
else:
source_indexes = set(sources)
sec_dict = self.sec_dict[gid]
if syn_sections is not None:
# Fast path
it = itertools.chain.from_iterable([sec_dict[sec_index].items() for sec_index in syn_sections])
syn_dict = {k: v for (k, v) in it}
else:
syn_dict = self.syn_id_attr_dict[gid]
result = {k: v for k, v in viewitems(syn_dict)
if matches([(syn_indexes, k),
(syn_types, v.syn_type),
(layers, v.syn_layer),
(source_indexes, v.source.population),
(swc_types, v.swc_type)])}
if cache:
self.filter_cache[cache_args] = result
return result
def partition_synapses_by_source(self, gid, syn_ids=None):
"""
Partitions the synapse objects for the given cell based on the
presynaptic (source) population index.
:param gid: int
:param syn_ids: array of int
"""
source_names = {id: name for name, id in viewitems(self.env.Populations)}
source_names[-1] = None
if syn_ids is None:
syn_id_attr_dict = self.syn_id_attr_dict[gid]
else:
syn_id_attr_dict = {syn_id: self.syn_id_attr_dict[gid][syn_id] for syn_id in syn_ids}
source_iter = partitionn(viewitems(syn_id_attr_dict),
lambda syn_id_syn: syn_id_syn[1].source.population+1
if syn_id_syn[1].source.population is not None else 0,
n=len(source_names))
return dict([(source_names[source_id_x[0]-1], generator_ifempty(source_id_x[1])) for source_id_x in
enumerate(source_iter)])
def get_filtered_syn_ids(self, gid, syn_sections=None, syn_indexes=None, syn_types=None, layers=None,
sources=None, swc_types=None, cache=False):
"""
Returns a subset of the synapse ids of the given cell according to the given criteria.
:param gid:
:param syn_sections:
:param syn_indexes:
:param syn_types:
:param layers:
:param sources:
:param swc_types:
:param cache:
:return: sequence
"""
return list(self.filter_synapses(gid, syn_sections=syn_sections, syn_indexes=syn_indexes, syn_types=syn_types,
layers=layers, sources=sources, swc_types=swc_types, cache=cache).keys())
def partition_syn_ids_by_source(self, gid, syn_ids=None):
"""
Partitions the synapse ids for the given cell based on the
presynaptic (source) population index.
:param gid: int
:param syn_ids: array of int
"""
start_time = time.time()
source_names = {id: name for name, id in viewitems(self.env.Populations)}
source_names[-1] = None
syn_id_attr_dict = self.syn_id_attr_dict[gid]
if syn_ids is None:
syn_ids = list(syn_id_attr_dict.keys())
def partition_pred(syn_id):
syn = syn_id_attr_dict[syn_id]
return syn.source.population+1 if syn.source.population is not None else 0
source_iter = partitionn(syn_ids, partition_pred, n=len(source_names))
return dict([(source_names[source_id_x[0]-1], generator_ifempty(source_id_x[1])) for source_id_x in
enumerate(source_iter)])
def del_syn_id_attr_dict(self, gid):
"""
Removes the synapse attributes associated with the given cell gid.
"""
del self.syn_id_attr_dict[gid]
del self.sec_dict[gid]
def clear(self):
self.syn_id_attr_dict = defaultdict(lambda: defaultdict(lambda: None))
self.sec_dict = defaultdict(lambda: defaultdict(lambda: dict()))
self.pps_dict = defaultdict(lambda: defaultdict(lambda: SynapsePointProcess(mech={}, netcon={}, vecstim={})))
self.filter_cache = {}
def clear_filter_cache(self):
self.filter_cache.clear()
def has_gid(self, gid):
return (gid in self.syn_id_attr_dict)
def gids(self):
return viewkeys(self.syn_id_attr_dict)
def items(self):
return viewitems(self.syn_id_attr_dict)
def __getitem__(self, gid):
return self.syn_id_attr_dict[gid]
class PlasticityTransform:
def __init__(self, X, w0, U=None, uw=None, logger=None):
self.logger = logger
self.y = None
self.xin = X.copy()
self.uin = None
if U is not None:
self.uin = U.copy()
xlb = np.min(X, axis=1)
xub = np.max(X, axis=1)
xrng = np.where(np.isclose(xub - xlb, 0., rtol=1e-6, atol=1e-6), 1., xub - xlb)
self.xlb = xlb
self.xub = xub
self.xrng = xrng
xdim = X.shape[0]
N = X.shape[1]
self.xn = np.zeros_like(X)
for i in range(xdim):
self.xn[i,:] = (X[i,:] - self.xlb[i]) / self.xrng[i]
ulb = np.min(U, axis=1)
uub = np.max(U, axis=1)
urng = np.where(np.isclose(uub - ulb, 0., rtol=1e-6, atol=1e-6), 1., uub - ulb)
self.un = None
self.ulb = ulb
self.uub = uub
self.urng = urng
if U is not None:
udim = U.shape[0]
N = U.shape[1]
self.un = np.zeros_like(U)
for i in range(udim):
self.un[i,:] = (U[i,:] - self.ulb[i]) / self.urng[i]
self.uw = uw
self.w0 = w0
initial = np.dot(self.xin, w0)
if self.un is not None:
initial += np.dot(self.uin, uw)
self.wnorm = np.mean(initial)
self.scaled_y = None
self.w = None
def fit(self, y, max_amplitude=3, max_opt_iter=1000, optimize_tol=1e-8, verbose=False):
scaled_initial = np.dot(self.xin, self.w0 / self.wnorm)
if self.uw is not None:
scaled_initial += np.dot(self.uin, self.uw / self.wnorm)
scaled_initial -= 1.
y_scaling_factor = max_amplitude / np.max(y)
self.scaled_y = (y.flatten() * y_scaling_factor) + scaled_initial
self.y_shape = y.shape
self.lsqr_target = self.scaled_y
if self.un is not None:
self.lsqr_target -= np.dot(self.un, self.uw / self.wnorm)
res = nnls_gdal(self.xn, self.lsqr_target.reshape((-1,1)),
max_n_iter=max_opt_iter, epsilon=optimize_tol, verbose=verbose)
lsqr_weights = np.asarray(res, dtype=np.float32).reshape((res.shape[0],))
self.w = lsqr_weights
return self.w
def insert_hoc_cell_syns(env, gid, cell, syn_ids, syn_params, unique=False, insert_netcons=False,
insert_vecstims=False):
"""
TODO: Only config the point process object if it has not already been configured.
Insert mechanisms into given cell according to the synapse objects created in env.synapse_attributes.