Repository navigation
Expand file tree
/
Copy pathnetwork.py
More file actions
3153 lines (2821 loc) · 134 KB
/
Copy pathnetwork.py
File metadata and controls
3153 lines (2821 loc) · 134 KB
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
"""Network class."""
# Authors: Mainak Jas <mjas@mgh.harvard.edu>
# Sam Neymotin <samnemo@gmail.com>
# Blake Caldwell <blake_caldwell@brown.edu>
# Christopher Bailey <cjb@cfin.au.dk>
# Nick Tolley <nicholas_tolley@brown.edu>
# Ryan Thorpe <ryan_thorpe@brown.edu>
import itertools as it
from copy import deepcopy
from collections import OrderedDict, defaultdict
from typing import Dict
import numpy as np
import warnings
from .cell_response import read_spikes
from .drives import _drive_cell_event_times
from .drives import _get_target_properties, _add_drives_from_params
from .drives import _check_drive_parameter_values, _check_poisson_rates
from .cells_default import pyramidal, basket
from .params import _long_name
from .viz import plot_cells
from .externals.mne import _validate_type, _check_option
from .extracellular import ExtracellularArray
from .check import _check_gids, _gid_to_type, _string_input_to_list
from .hnn_io import write_network_configuration, network_to_dict
from .externals.mne import copy_doc
from .utils import _replace_dict_identifier
def _create_cell_coords(n_pyr_x, n_pyr_y, z_coord, inplane_distance):
"""Creates coordinate grid and place cells in it.
Parameters
----------
n_pyr_x : int
The number of Pyramidal cells in x direction.
n_pyr_y : int
The number of Pyramidal cells in y direction.
z_coord : float
Expressed as a positive DEPTH of L2 relative to L5 pyramidal cell
somas, where L5 is defined to lie at z==0. Interlaminar weight/delay
calculations (lamtha) are not affected. The basket cells are
arbitrarily placed slightly above (L5) and slightly below (L2) their
respective pyramidal cell layers.
inplane_distance : float
The grid spacing of pyramidal cells (in um). Note that basket cells are
placed in an uneven formation. Each one of them lies on a grid point
together with a pyramidal cell, though (overlapping).
Returns
-------
layer_dict : dict of list of tuple (x, y, z)
Dictionary containing coordinate positions of 'layers'. After calling
'_create_cell_coords', user can create their 'Network.pos_dict' by mapping
'origin' and their celltypes onto the different layers in 'layer_dict'. Keys are
'L2_bottom', 'L2_mid', 'L5_bottom', 'L5_mid', and 'origin'.
Notes
-----
Common positions are all located at origin.
Sort of a hack because of redundancy.
"""
def _calc_pyramidal_coord(xxrange, yyrange, z_coord):
list_coords = [pos for pos in it.product(xxrange, yyrange, [z_coord])]
return list_coords
def _calc_basket_coord(n_x, n_y, z_coord, inplane_distance, weight):
xzero = np.arange(0, n_x, 3) * inplane_distance
xone = np.arange(1, n_x, 3) * inplane_distance
# split even and odd y vals
yeven = np.arange(0, n_y, 2) * inplane_distance
yodd = np.arange(1, n_y, 2) * inplane_distance
# create general list of x,y coords and sort it
coords = [pos for pos in it.product(xzero, yeven)] + [
pos for pos in it.product(xone, yodd)
]
coords_sorted = sorted(coords, key=lambda pos: pos[1])
# append the z value for position
list_coords = [
(pos_xy[0], pos_xy[1], weight * z_coord) for pos_xy in coords_sorted
]
return list_coords
def _calc_origin(xxrange, yyrange, z_coord):
# origin's z component isn't used in calculating distance functions.
# will be used for adding external drives.
origin_x = xxrange[int((len(xxrange) - 1) // 2)]
origin_y = yyrange[int((len(yyrange) - 1) // 2)]
origin_z = np.floor(z_coord / 2)
origin = (origin_x, origin_y, origin_z)
return origin
# Calculate distances
xxrange = np.arange(n_pyr_x) * inplane_distance
yyrange = np.arange(n_pyr_y) * inplane_distance
# Create layer dictionary with anatomical layer positions
layer_dict = {
"L5_bottom": _calc_pyramidal_coord(xxrange, yyrange, z_coord=0),
"L2_bottom": _calc_pyramidal_coord(xxrange, yyrange, z_coord=z_coord),
"L5_mid": _calc_basket_coord(
n_pyr_x,
n_pyr_y,
z_coord=z_coord,
inplane_distance=inplane_distance,
weight=0.2,
),
"L2_mid": _calc_basket_coord(
n_pyr_x,
n_pyr_y,
z_coord=z_coord,
inplane_distance=inplane_distance,
weight=0.8,
),
"origin": _calc_origin(xxrange, yyrange, z_coord),
}
return layer_dict
def _compare_lists(s, t):
"""
Compares lists for equality
From https://stackoverflow.com/a/7829388
"""
t = list(t) # make a mutable copy
try:
for elem in s:
t.remove(elem)
except ValueError:
return False
return not t
def _connection_probability(conn, probability, conn_seed=None):
"""Remove/keep a random subset of connections.
Parameters
----------
conn : Instance of _Connectivity object
Object specifying the biophysical parameters and src target pairs
of a specific connection class. Function modifies conn in place.
probability : float
Probability of connection between any src-target pair.
Defaults to 1.0 producing an all-to-all pattern.
conn_seed : int
Optional initial seed for random number generator (default: None).
Used to randomly remove connections when probability < 1.0.
Notes
-----
num_srcs and num_targets are not updated after pruning connections.
These variables are meant to describe the set of original connections
before they are randomly removed.
The probability attribute will store the most recent value passed to
this function. As such, this number does not accurately describe the
connections probability of the original set after successive calls.
"""
# Random number generator for random connection selection
rng = np.random.default_rng(conn_seed)
_validate_type(probability, float, "probability")
if probability <= 0.0 or probability >= 1.0:
raise ValueError("probability must be in the range (0,1)")
# Flatten connections into a list of targets.
all_connections = np.concatenate(
[target_src_pair for target_src_pair in conn["gid_pairs"].values()]
)
n_connections = np.round(len(all_connections) * probability).astype(int)
# Select a random subset of connections to retain.
new_connections = rng.choice(
range(len(all_connections)), n_connections, replace=False
)
remove_srcs = list()
connection_idx = 0
for src_gid, target_src_pair in conn["gid_pairs"].items():
target_new = list()
for target_gid in target_src_pair:
if connection_idx in new_connections:
target_new.append(target_gid)
connection_idx += 1
# Update targets for src_gid
if target_new:
conn["gid_pairs"][src_gid] = target_new
else:
remove_srcs.append(src_gid)
# Remove src_gids with no targets
for src_gid in remove_srcs:
conn["gid_pairs"].pop(src_gid)
def pick_connection(net, src_gids=None, target_gids=None, loc=None, receptor=None):
"""Returns indices of connections that match search parameters.
Parameters
----------
net : Instance of Network object
The Network object
src_gids : str | int | range | list of int | None
Identifier for source cells. Passing str arguments
('L2_pyramidal', 'L2_basket', 'L5_pyramidal', 'L5_basket') is
equivalent to passing a list of gids for the relevant cell type.
source - target connections are made in an all-to-all pattern.
target_gids : str | int | range | list of int | None
Identifier for targets of source cells. Passing str arguments
('L2_pyramidal', 'L2_basket', 'L5_pyramidal', 'L5_basket') is
equivalent to passing a list of gids for the relevant cell type.
source - target connections are made in an all-to-all pattern.
loc : str | list of str | None
Location of synapse on target cell. Must be
'proximal', 'distal', or 'soma'. Note that inhibitory synapses
(receptor='gabaa' or 'gabab') of L2 pyramidal neurons are only
valid loc='soma'.
receptor : str | list of str | None
Synaptic receptor of connection. Must be one of:
'ampa', 'nmda', 'gabaa', or 'gabab'.
Returns
-------
conn_indices : list of int
List of indices corresponding to items in net.connectivity.
Connection indices are included if any of the provided parameter
values are present in a connection.
Notes
-----
Passing a list of values to a single parameter corresponds to a
logical OR operation across indices. For example,
loc=['distal', 'proximal'] returns all connections that target
distal or proximal dendrites.
Passing multiple parameters corresponds to a logical AND operation.
For example, net.pick_connection(loc='distal', receptor='ampa')
returns only the indices of connections that target the distal
dendrites and have ampa receptors.
"""
# Convert src and target gids to lists
valid_srcs = list(net.gid_ranges.keys()) # includes drives as srcs
valid_targets = list(net.cell_types.keys())
src_gids_checked = _check_gids(
src_gids, net.gid_ranges, valid_srcs, "src_gids", same_type=False
)
target_gids_checked = _check_gids(
target_gids, net.gid_ranges, valid_targets, "target_gids", same_type=False
)
_validate_type(loc, (str, list, None), "loc", "str, list, or None")
_validate_type(receptor, (str, list, None), "receptor", "str, list, or None")
valid_loc = ["proximal", "distal", "soma"]
valid_receptor = ["ampa", "nmda", "gabaa", "gabab"]
# Convert receptor and loc to list
loc_list = _string_input_to_list(loc, valid_loc, "loc")
receptor_list = _string_input_to_list(receptor, valid_receptor, "receptor")
# Create lookup dictionaries
src_dict, target_dict = defaultdict(list), defaultdict(list)
loc_dict, receptor_dict = defaultdict(list), defaultdict(list)
for conn_idx, conn in enumerate(net.connectivity):
# Store connections matching each src_gid
for src_gid in conn["src_gids"]:
src_dict[src_gid].append(conn_idx)
# Store connections matching each target_gid
for target_gid in conn["target_gids"]:
target_dict[target_gid].append(conn_idx)
# Store connections matching each location
loc_dict[conn["loc"]].append(conn_idx)
# Store connections matching each receptor
receptor_dict[conn["receptor"]].append(conn_idx)
# Look up conn indices that match search terms and add to set.
conn_set = set()
search_pairs = [
(src_gids_checked, src_dict),
(target_gids_checked, target_dict),
(loc_list, loc_dict),
(receptor_list, receptor_dict),
]
for search_terms, search_dict in search_pairs:
if search_terms:
inner_set = set()
# Union of indices which match inputs for single parameter
for term in search_terms:
inner_set = inner_set.union(search_dict.get(term, list()))
# Empty search
if not inner_set:
return list()
# Initial search has results
elif inner_set and not conn_set:
conn_set = inner_set.copy()
# Subsequent searches have results
elif inner_set and conn_set:
# Intersect across parameters
conn_set = conn_set.intersection(inner_set)
# If at any point there's no matching elements, return empty
if not conn_set:
return list()
return sorted(conn_set)
def _get_cell_index_by_synapse_type(net):
"""Returns the indices of excitatory and inhibitory cells in the Network.
This function extracts the source GIDs (cell ID) of excitatory and inhibitory cells
based on their connection types. Excitatory and inhibitory cells are identified by
their electrophysiological metadata values. This does *not* return GIDs of external
drives.
Parameters
----------
net : Instance of Network object
The Network object
Returns
-------
e_cell_gids : list
The source GIDs of excitatory cells.
i_cell_gids : list
The source GIDs of inhibitory cells.
"""
e_cell_gids = list()
i_cell_gids = list()
for cell_type_name, cell_data in net.cell_types.items():
if cell_data["cell_metadata"].get("electro_type") == "excitatory":
e_cell_gids.extend(net.gid_ranges[cell_type_name])
elif cell_data["cell_metadata"].get("electro_type") == "inhibitory":
i_cell_gids.extend(net.gid_ranges[cell_type_name])
return e_cell_gids, i_cell_gids
class Network:
"""The Network class.
Parameters
----------
params : dict
The parameters to use for constructing the network.
add_drives_from_params : bool, default=False
If True, add drives as defined in the params-dict. NB this is mainly
for backward-compatibility with HNN GUI, and will be deprecated in a
future release.
legacy_mode : bool, default=False
Set to True by default to enable matching HNN GUI output when drives
are added suitably. Will be deprecated in a future release.
mesh_shape : tuple of int (default: (10, 10))
Defines the (n_x, n_y) shape of the grid of pyramidal cells.
pos_dict : dict of list of tuple (x, y, z), optional
Dictionary containing the coordinate positions of all cells. Keys are
'L2_pyramidal', 'L5_pyramidal', 'L2_basket', 'L5_basket', or any external drive
name. If you specify "pos_dict", you MUST also specify your own "cell_types"
argument (see below).
cell_types : dict of dict of (Cell | dict), optional
Dictionary containing names of real cell types in the network (e.g. 'L2_basket')
as keys and child-dictionaries describing the cell type. If you specify
"cell_types", you MUST also specify your own "pos_dict" argument (see
above). The child-dictionary contains two keys: "cell_object" and
"cell_metadata". The value of "cell_object" is the corresponding Cell instance
of the cell type being described, and this instance is used as a template for
the other cells of its type in the population. The value of "cell_metadata" is a
dictionary containing several key-values pairs that describe different aspects
of the cell type, described below:
- "morpho_type" : either "basket" or "pyramidal"
- "electro_type" : either "inhibitory" or "excitatory"
- "layer" : either "2" or "5"
- "measure_dipole" : either True or False
- "reference": optional
Attributes
----------
cell_types : dict of dict of (Cell | dict)
Dictionary containing names of real cell types in the network (e.g. 'L2_basket')
as keys and child-dictionaries describing the cell type. The child-dictionary
contains two keys: "cell_object" and "cell_metadata". The value of "cell_object"
is the corresponding Cell instance of the cell type being described, and this
instance is used as a template for the other cells of its type in the
population. The value of "cell_metadata" is a dictionary containing several
key-values pairs that describe different aspects of the cell type, described
below:
- "morpho_type" : either "basket" or "pyramidal"
- "electro_type" : either "inhibitory" or "excitatory"
- "layer" : either "2" or "5"
- "measure_dipole" : either True or False
- "reference": optional
gid_ranges : dict
A dictionary of unique identifiers of each real and artificial cell
in the network. Every cell type is represented by a key read from
cell_types, followed by keys read from external_drives. The value
of each key is a range of ints, one for each cell in given category.
Examples: 'L2_basket': range(0, 270), 'evdist1': range(272, 542), etc
pos_dict : dict of list of tuple (x, y, z)
Dictionary containing the coordinate positions of all cells.
Keys are 'L2_pyramidal', 'L5_pyramidal', 'L2_basket', 'L5_basket',
or any external drive name.
cell_response : CellResponse
An instance of the CellResponse object.
external_drives : dict (keys: drive names) of dict (keys: parameters)
The external driving inputs to the network. Drives are added by
defining their spike-time dynamics, and their connectivity to the real
cells of the network. Event times are instantiated before simulation,
and are stored under the ``'events'``-key (list of list; first
index for trials, second for event time lists for each drive cell).
external_biases : dict of dict (bias parameters for each cell type)
The parameters of bias inputs to cell somata, e.g., tonic current clamp
connectivity : list of dict
List of dictionaries specifying each cell-cell and drive-cell
connection
rec_arrays : dict
Stores electrode position information and voltages recorded by them
for extracellular potential measurements. Multiple electrode arrays
may be defined as unique keys. The values of the dictionary are
instances of :class:`hnn_core.extracellular.ExtracellularArray`.
threshold : float
Firing threshold of all cells.
delay : float
Synaptic delay in ms.
Notes
-----
``net = neymotin_2020_model(params)`` is the recommended path for creating a
network. Instantiating the network as ``net = Network(params)`` will
produce a network with no cell-to-cell connections. As such,
connectivity information contained in ``params`` will be ignored.
"""
def __init__(
self,
params,
add_drives_from_params=False,
legacy_mode=False,
mesh_shape=(10, 10),
pos_dict=None,
cell_types=None,
):
# Save the parameters used to create the Network
_validate_type(params, dict, "params")
self._params = params
# The `model_variant` attribute is currently used to distinguish Duecker-style
# networks from all other networks. Duecker-style networks are fundamentally
# different from classic Neymotin (aka Jones) -style networks, in terms of cell
# types, cell type names, baseline correction values for dipoles, etc. As of
# `master` branch's following commit (on 2026-09-02):
# https://github.com/jonescompneurolab/hnn-core/commit/49f210fb41481ab859537e9b3e32a74117ae95fc
# `model_variant` can have any of the following values, based on the
# corresponding functions of `network_models.py`:
#
# - `duecker_ET_model` -> Duecker-style network
# - {`neymotin_2020_model`, `jones_2009_model`, `law_2021_model`, `calcium_model`} -> Jones-style network
# - `None` -> Jones-style network (default)
#
# The case of `None` can arise in two ways: (1) the user is using a (probably
# old) script that creates a raw `Network` object from scratch, or (2) the user
# is loading a network from a JSON file that was created before the
# `model_variant` attribute was added to the `Network` class. In either case,
# the default behavior is to treat the network as a Jones-style network.
#
# TODO: AES The only exception to this is users who are CURRENTLY using an BETA
# version of the Duecker model off of an old branch from before `model_variant`
# was introduced. Soon, these users will be forced to migrate to the latest
# version of the Duecker model code, and this relevant backwards-compatible code
# will be deleted.
self._model_variant = params.get("model_variant", None)
# Initialise a dictionary of cell ID's, which get used when the
# network is constructed ('built') in NetworkBuilder
# We want it to remain in each Network object, so that the user can
# interrogate a built and simulated net. In addition, CellResponse is
# attached to a Network during simulation---Network is the natural
# place to keep this information. Order matters: cell gids first, then
# artificial drive cells
self.gid_ranges = OrderedDict()
self._n_gids = 0 # utility: keep track of last GID
self._verbose = True
self._baseline_correction_applied = False
# XXX this can be removed once tests are made independent of HNN GUI
# creates nc_dict-entries for ALL cell types
self._legacy_mode = legacy_mode
if self._legacy_mode:
warnings.warn(
"Legacy mode is used solely to maintain compatibility with"
".param files of the old HNN GUI. This feature will be "
"deprecrated in future releases.",
FutureWarning,
stacklevel=1,
)
self.cell_response = None
# external drives and biases
self.external_drives = dict()
self.external_biases = dict()
# network connectivity
self.connectivity = list()
self.threshold = self._params["threshold"]
self.delay = 1.0
# extracellular recordings (if applicable)
self.rec_arrays = dict()
# simulation-time params
self._tstop = None
self._dt = None
# contents of pos_dict determines all downstream inferences of
# cell counts, real and artificial
self._n_cells = 0 # used in tests and MPIBackend checks
self.pos_dict = dict()
self.cell_types = dict()
# set the mesh shape
_validate_type(mesh_shape, tuple, "mesh_shape")
_validate_type(mesh_shape[0], int, "mesh_shape[0]")
_validate_type(mesh_shape[1], int, "mesh_shape[1]")
if mesh_shape[0] < 1 or mesh_shape[1] < 1:
raise ValueError(
f"mesh_shape must be a tuple of positive integers, got: {mesh_shape}"
)
self._N_pyr_x = mesh_shape[0]
self._N_pyr_y = mesh_shape[1]
# Handle positions and cell types
# ------------------------------------------------------------------------------
if cell_types is not None or pos_dict is not None:
# Input validation
# --------------------------------------------------------------------------
# If a user is specifying their own cell_types, they must also specify
# pos_dict:
if pos_dict is None:
raise ValueError(
"If custom 'cell_types' are provided to Network, you must "
"also provide a custom 'pos_dict'."
)
# Vice versa:
elif cell_types is None:
raise ValueError(
"If a custom 'pos_dict' is provided to Network, you must "
"also provide custom 'cell_types'."
)
# Test that the keys of pos_dict and cell_types are well-formed:
pos_dict_keys = set(pos_dict.keys())
if "origin" not in pos_dict_keys:
raise ValueError("Origin must be defined for your custom 'pos_dict'")
pos_dict_keys.remove("origin")
cell_type_keys = set(cell_types.keys())
if not (cell_type_keys <= pos_dict_keys):
raise ValueError(
"All keys of 'pos_dict' must be present in 'cell_types'. "
f"'pos_dict' keys: {pos_dict_keys}, 'cell_types' keys: {cell_type_keys}"
)
for ct in cell_types.keys():
if "zdist_origin" not in cell_types[ct]["cell_metadata"].keys():
raise ValueError(
"zdist_origin must be defined for each cell type in "
"your custom 'cell_types' metadata"
)
_validate_type(pos_dict, dict, "pos_dict")
_validate_type(cell_types, dict, "cell_types")
# Use provided positions and cell types
# --------------------------------------------------------------------------
self.pos_dict = deepcopy(pos_dict)
# Add cell types from provided dictionary
for cell_name, cell_template in cell_types.items():
self._add_cell_type(
cell_name,
self.pos_dict[cell_name],
cell_template=cell_template,
)
# Since we're in the initializer, we must calculate our inplane distance
# strictly from the custom pos_dict:
inlay_dist = []
for cell_type in self.cell_types.keys():
# For this cell type, this does the following:
# 1. Grab all the unique, sorted x-coordinates of the cell type.
# 2. Grab all the distances between each unique, sorted x-coordinate of
# the cell type.
# 3. Grab all the unique, sorted y-coordinates of the cell type.
# 4. Grab all the distances between each unique, sorted y-coordinate of
# the cell type.
# 5. Check that there is at least one distance in the x and y
# directions. If not, warn the user, and override the in-plane
# distance for that dimension to be 1.0, in order to prevent NaNs.
# 6. Concatenate the provided distances into a single array, and take
# the mean. This gets you an "average in-plane distance" for this
# cell type in the X and Y (but not Z!) directions.
x_diffs = np.diff(np.unique(np.array(self.pos_dict[cell_type])[:, 0]))
y_diffs = np.diff(np.unique(np.array(self.pos_dict[cell_type])[:, 1]))
for dim_diffs, dimension in [(x_diffs, "X"), (y_diffs, "Y")]:
if len(dim_diffs) == 0:
warnings.warn(
f"Zero distance between cells of type '{cell_type}' "
f"in the {dimension} dimension in the provided 'pos_dict'. "
"\n"
"This can happen if: "
"\n"
"- you are simulating a network with only a single cell of "
"this cell type, e.g. using `mesh_shape=(1, 1)`."
"\n"
f"- the positions of '{cell_type}' in your 'pos_dict' "
f"are all the same in the {dimension} dimension. "
"\n"
"If this is not intentional, check your 'pos_dict'!"
)
# Note for developers: In the warned cases above, it should be
# safe to override the problematic dimension's in-plane distance
# to 1.0. This allows the problematic dimension to still use its
# full lamtha value when it is used in
#
# Cell.parconnect_from_src ->
# cell.py::_get_gaussian_connection ->
# cell.py::_calculate_gaussian
#
# instead of hitting a divide-by-NaN error. Additionally, if the
# OTHER dimension has valid in-plane distances (such as cells in
# a line), then those will still be taken into account when
# ultimately calculating the `self._inplane_distance` below.
if dimension == "X":
x_diffs = np.array([1.0])
elif dimension == "Y":
y_diffs = np.array([1.0])
current_dist = np.mean(np.concatenate((x_diffs, y_diffs)))
inlay_dist.append(current_dist)
self._inplane_distance = np.min(np.array(inlay_dist))
# Since we're in the initializer, we must also calculate our layer separation
# strictly from the custom pos_dict:
for cell_type in self.cell_types:
if self.cell_types[cell_type]["cell_metadata"]["zdist_origin"] == 1:
# Define "layer separation" using the mean z-coordinate (the third
# element of the pos_dict tuples) of the celltype that has
# `zdist_origin == 1` in its metadata (typically the layer
# 2/3 pyramidal cell type). This is meant to identify the distance
# between the somas of pyramidal cells in layer 2/3 versus those in
# layer 5.
#
self._layer_separation = np.mean(
np.array(self.pos_dict[cell_type])[:, 2]
)
# Make a backup copies of all the position information, in case the user
# wants to reset everything to original cell positions
self._original_pos_dict = deepcopy(self.pos_dict)
self._original_inplane_distance = deepcopy(self._inplane_distance)
self._original_layer_separation = deepcopy(self._layer_separation)
# Since we're in the initializer, we do not need to reposition any drives
# after creating the above.
else:
# Default behavior - create standard network
from .network_models import default_cell_metadata
cell_types_default = {
"L2_basket": {
"cell_object": basket(cell_name="L2_basket"),
"cell_metadata": deepcopy(default_cell_metadata["L2_basket"]),
},
"L2_pyramidal": {
"cell_object": pyramidal(cell_name="L2_pyramidal"),
"cell_metadata": deepcopy(default_cell_metadata["L2_pyramidal"]),
},
"L5_basket": {
"cell_object": basket(cell_name="L5_basket"),
"cell_metadata": deepcopy(default_cell_metadata["L5_basket"]),
},
"L5_pyramidal": {
"cell_object": pyramidal(cell_name="L5_pyramidal"),
"cell_metadata": deepcopy(default_cell_metadata["L5_pyramidal"]),
},
}
self._inplane_distance = 1.0 # XXX hard-coded default
self._layer_separation = 1307.4 # XXX hard-coded default
# Set the relative positions of cells (pos_dict) assuming default cell
# types. This arranges them in a square grid.
layer_dict = _create_cell_coords(
n_pyr_x=self._N_pyr_x,
n_pyr_y=self._N_pyr_y,
z_coord=self._layer_separation,
inplane_distance=self._inplane_distance,
)
# Map layers to cell types, for default mapping
self.pos_dict = {
"L5_pyramidal": layer_dict["L5_bottom"],
"L2_pyramidal": layer_dict["L2_bottom"],
"L5_basket": layer_dict["L5_mid"],
"L2_basket": layer_dict["L2_mid"],
"origin": layer_dict["origin"],
}
# Make a backup copies of all the position information, in case the user
# wants to reset everything to original cell positions
self._original_pos_dict = deepcopy(self.pos_dict)
self._original_inplane_distance = deepcopy(self._inplane_distance)
self._original_layer_separation = deepcopy(self._layer_separation)
# populates self.gid_ranges for the 1st time: order matters for
# NetworkBuilder!
for cell_name, cell_template in cell_types_default.items():
self._add_cell_type(
cell_name,
self.pos_dict[cell_name],
cell_template=cell_template,
)
# Must happen after cell types are added
if add_drives_from_params:
warnings.warn(
"add_drives_from_params=True is deprecated. In order to add the "
"canonical set of drives, please use the appropriate argument to the "
"network model you are using, such as 'neymotin_2020_model(..., "
"add_erp_drives=True)' to add canonical ERP drives to the Neymotin "
"2020 model.",
FutureWarning,
)
_add_drives_from_params(self)
def __repr__(self):
class_name = self.__class__.__name__
# Dynamically create the description based on the current cell types
descriptions = []
for cell_name in self.cell_types:
cell_count = len(self.pos_dict.get(cell_name, []))
descriptions.append(f"{cell_count} {cell_name} cells")
# Combine all descriptions into a single string
description_str = "\n".join(descriptions)
return f"<{class_name} | {description_str}>"
def __eq__(self, other):
if not isinstance(other, Network):
return NotImplemented
# Check connectivity
if (len(self.connectivity) != len(other.connectivity)) or not (
_compare_lists(self.connectivity, other.connectivity)
):
return False
# Check all other attributes
attrs_to_ignore = ["connectivity"]
for attr in vars(self).keys():
if attr.startswith("_") or attr in attrs_to_ignore:
continue
if hasattr(self, attr) and hasattr(other, attr):
if getattr(self, attr) != getattr(other, attr):
return False
else:
# Does not have the same set of attributes
return False
return True
def _reset_to_original_cell_positions(self):
"""Reset the relative positions of cells to their original positions.
This resets ``Network.pos_dict``, ``Network._inplane_distance``, and
``Network._layer_separation`` to their original values, which were set when the
Network was first created. This includes whether the original positions were
using the ``Network`` defaults, or if a user passed their own ``pos_dict`` and
``cell_types`` to the constructor and are using the calculated in-plane distance
and layer separation from that custom ``pos_dict``.
This can be used to reset your cell positions to a known-good state after
calling ``Network.update_cell_positions``.
"""
self.pos_dict = deepcopy(self._original_pos_dict)
self._inplane_distance = deepcopy(self._original_inplane_distance)
self._layer_separation = deepcopy(self._original_layer_separation)
# update drives to be positioned at network origin
for drive_name, drive in self.external_drives.items():
pos = [self.pos_dict["origin"]] * drive["n_drive_cells"]
self.pos_dict[drive_name] = pos
def update_cell_positions(
self,
inplane_distance=None,
layer_separation=None,
):
"""Change relative positions of cells arranged in a square grid.
Note that it is possible to change one of the parameters without changing the
other. You must pass at least one argument.
Parameters
----------
inplane_distance : float, optional
The in plane-distance (in um) between pyramidal cell somas in the
square grid. Note that this parameter does not affect the amplitude
of the dipole moment.
layer_separation : float, optional
The separation of pyramidal cell soma layers 2/3 and 5. Note that
this parameter does not affect the amplitude of the dipole moment.
"""
# Input validation
# ------------------------------------------------------------------------------
if inplane_distance is None and layer_separation is None:
raise ValueError(
"At least one of inplane_distance or layer_separation must be provided."
)
if np.isnan(self._inplane_distance) or np.isclose(self._inplane_distance, 0.0):
raise ValueError(
"Cannot reset cell positions because the current in-plane distance "
"is NaN or zero. Something has gone wrong at Network creation time."
)
if inplane_distance is None:
inplane_distance = self._inplane_distance
_validate_type(inplane_distance, (float, int), "inplane_distance")
if not inplane_distance > 0.0:
raise ValueError(
f"In-plane distance must be positive, got: {inplane_distance}"
)
if layer_separation is None:
layer_separation = self._layer_separation
_validate_type(layer_separation, (float, int), "layer_separation")
if not layer_separation > 0.0:
raise ValueError(
f"Layer separation must be positive, got: {layer_separation}"
)
# pos_dict shifting
# ------------------------------------------------------------------------------
# There should always be an existing pos_dict by the point in time when this
# function is called, since it can only be called after the Network is
# initialized.
xy_scaling = inplane_distance / self._inplane_distance
for cell_type in self.cell_types:
new_zdist = (
self.cell_types[cell_type]["cell_metadata"]["zdist_origin"]
* layer_separation
)
# Update the positions of the cells in pos_dict:
# - X and Y coordinates are scaled by the ratio of the new in-plane distance
# to the old one, so that their final location is consistent with the
# new in-plane distance.
# - Z coordinates: Because `zdist_origin` is already normalized to [0, 1],
# the Z-coordinate is simply multiplied by the new layer separation
# distance.
self.pos_dict[cell_type] = [
(
pos[0] * xy_scaling,
pos[1] * xy_scaling,
new_zdist,
)
for pos in self.pos_dict[cell_type]
]
# Update the position of the origin in pos_dict:
# - X and Y coordinates are scaled similarly to the celltypes above, via the
# ratio of the new in-plane distance to the old one.
# - The Z coordinate is unchanged since it already defines the '0' value for
# `zdist_origin` metadata of cell types.
origin = self.pos_dict["origin"]
self.pos_dict["origin"] = (
origin[0] * xy_scaling,
origin[1] * xy_scaling,
origin[2],
)
# Update the position of the drives in pos_dict:
# - Drives are always positioned at the origin of the network (see
# https://github.com/jonescompneurolab/hnn-core/blob/5ca983a3dd53b6e749c377b24bcba64773debbd3/hnn_core/network.py#L1396
# so we simply reset their positions to the new origin of the network.
for drive_name in self.external_drives:
self.pos_dict[drive_name] = [self.pos_dict["origin"]] * len(
self.pos_dict[drive_name]
)
self._inplane_distance = inplane_distance
self._layer_separation = layer_separation
def set_cell_positions(
self,
inplane_distance=None,
layer_separation=None,
):
"""Reset relative positions of cells arranged in a square grid (Deprecated)
This function is deprecated in favor of `Network.update_cell_positions`. Note
that it is possible to change one of the parameters without changing the other.
Parameters
----------
inplane_distance : float, optional
The in plane-distance (in um) between pyramidal cell somas in the
square grid. Note that this parameter does not affect the amplitude
of the dipole moment.
layer_separation : float, optional
The separation of pyramidal cell soma layers 2/3 and 5. Note that
this parameter does not affect the amplitude of the dipole moment.
"""
warnings.warn(
"`Network.set_cell_positions` will be deprecated in favor of "
"`Network.update_cell_positions` in future releases.",
FutureWarning,
stacklevel=1,
)
self.update_cell_positions(
inplane_distance=inplane_distance,
layer_separation=layer_separation,
)
def copy(self):
"""Return a copy of the Network instance
The returned copy retains the intrinsic connectivity between cells, as
well as those of any external drives or biases added to the network.
The parameters of drive dynamics are also retained, but the
instantiated ``events`` of the drives are cleared. This allows
iterating over the values defining drive dynamics, without the need to
re-define connectivity. Extracellular recording arrays are retained in
the network, but cleared of existing data.
Returns
-------
net_copy : instance of Network
A copy of the instance with previous simulation results and
``events`` of external drives removed.
"""
net_copy = deepcopy(self)
net_copy._reset_drives()
net_copy._reset_rec_arrays()
return net_copy
def add_evoked_drive(
self,
name,
*,
mu,
sigma,
numspikes,
location,
n_drive_cells="n_cells",
cell_specific=True,
weights_ampa=None,
weights_nmda=None,
space_constant=3.0,
synaptic_delays=0.1,
probability=1.0,
event_seed=2,
conn_seed=3,
):
"""Add an 'evoked' external drive to the network
Parameters
----------
name : str
Unique name for the drive
mu : float
Mean of Gaussian event time distribution
sigma : float
Standard deviation of event time distribution
numspikes : int
Number of spikes at each target cell
location : str
Target location of synapses. Must be an element of
`Cell.sect_loc` such as 'proximal' or 'distal', which defines a
group of sections, or an existing section such as 'soma' or
'apical_tuft' (defined in `Cell.sections` for all targeted cells).
The parameter `legacy_mode` of the `Network` must be set to `False`
to target specific sections.
n_drive_cells : int | 'n_cells'
The number of drive cells that each contribute an independently
sampled synaptic spike to the network according to the Gaussian
time distribution (mu, sigma). If n_drive_cells='n_cells'
(default) and cell_specific=True, a drive cell gets assigned to
each available simulated cell in the network with 1-to-1
connectivity. Otherwise, drive cells are assigned with
all-to-all connectivity. If you wish to synchronize the timing of
this evoked drive across the network in a given trial with one