Skip to content

Modules

Module

Bases: ABC

Module base class.

Modules are everything that can be passed to jx.integrate, i.e. compartments, branches, cells, and networks.

This base class defines the scaffold for all jaxley modules (compartments, branches, cells, networks).

Source code in jaxley/modules/base.py
  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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
class Module(ABC):
    """Module base class.

    Modules are everything that can be passed to `jx.integrate`, i.e. compartments,
    branches, cells, and networks.

    This base class defines the scaffold for all jaxley modules (compartments,
    branches, cells, networks).
    """

    def __init__(self):
        self.nseg: int = None
        self.total_nbranches: int = 0
        self.nbranches_per_cell: List[int] = None

        self.group_nodes = {}

        self.nodes: Optional[pd.DataFrame] = None

        self.edges = pd.DataFrame(
            columns=[
                "pre_locs",
                "pre_branch_index",
                "pre_cell_index",
                "post_locs",
                "post_branch_index",
                "post_cell_index",
                "type",
                "type_ind",
                "global_pre_comp_index",
                "global_post_comp_index",
                "global_pre_branch_index",
                "global_post_branch_index",
            ]
        )

        self.cumsum_nbranches: Optional[jnp.ndarray] = None

        self.comb_parents: jnp.ndarray = jnp.asarray([-1])
        self.comb_branches_in_each_level: List[jnp.ndarray] = [jnp.asarray([0])]

        self.initialized_morph: bool = False
        self.initialized_syns: bool = False

        # List of all types of `jx.Synapse`s.
        self.synapses: List = []
        self.synapse_param_names = []
        self.synapse_state_names = []
        self.synapse_names = []

        # List of types of all `jx.Channel`s.
        self.channels: List[Channel] = []
        self.membrane_current_names: List[str] = []

        # For trainable parameters.
        self.indices_set_by_trainables: List[jnp.ndarray] = []
        self.trainable_params: List[Dict[str, jnp.ndarray]] = []
        self.allow_make_trainable: bool = True
        self.num_trainable_params: int = 0

        # For recordings.
        self.recordings: pd.DataFrame = pd.DataFrame().from_dict({})

        # For stimuli or clamps.
        # E.g. `self.externals = {"v": zeros(1000,2), "i": ones(1000, 2)}`
        # for 1000 timesteps and two compartments.
        self.externals: Dict[str, jnp.ndarray] = {}
        # E.g. `self.external)inds = {"v": jnp.asarray([0,1]), "i": jnp.asarray([2,3])}`
        self.external_inds: Dict[str, jnp.ndarray] = {}

        # x, y, z coordinates and radius.
        self.xyzr: List[np.ndarray] = []

        # For debugging the solver. Will be empty by default and only filled if
        # `self._init_morph_for_debugging` is run.
        self.debug_states = {}

    def _update_nodes_with_xyz(self):
        """Add xyz coordinates to nodes."""
        num_branches = len(self.xyzr)
        x = np.linspace(
            0.5 / self.nseg,
            (num_branches * 1 - 0.5 / self.nseg),
            num_branches * self.nseg,
        )
        x += np.arange(num_branches).repeat(
            self.nseg
        )  # add offset to prevent branch loc overlap
        xp = np.hstack(
            [np.linspace(0, 1, x.shape[0]) + 2 * i for i, x in enumerate(self.xyzr)]
        )
        xyz = v_interp(x, xp, np.vstack(self.xyzr)[:, :3])
        idcs = self.nodes["comp_index"]
        self.nodes.loc[idcs, ["x", "y", "z"]] = xyz.T
        return xyz.T

    def __repr__(self):
        return f"{type(self).__name__} with {len(self.channels)} different channels. Use `.show()` for details."

    def __str__(self):
        return f"jx.{type(self).__name__}"

    def __dir__(self):
        base_dir = object.__dir__(self)
        return sorted(base_dir + self.synapse_names + list(self.group_nodes.keys()))

    def _append_params_and_states(self, param_dict: Dict, state_dict: Dict):
        """Insert the default params of the module (e.g. radius, length).

        This is run at `__init__()`. It does not deal with channels.
        """
        for param_name, param_value in param_dict.items():
            self.nodes[param_name] = param_value
        for state_name, state_value in state_dict.items():
            self.nodes[state_name] = state_value

    def _gather_channels_from_constituents(self, constituents: List):
        """Modify `self.channels` and `self.nodes` with channel info from constituents.

        This is run at `__init__()`. It takes all branches of constituents (e.g.
        of all branches when the are assembled into a cell) and adds columns to
        `.nodes` for the relevant channels.
        """
        for module in constituents:
            for channel in module.channels:
                if channel._name not in [c._name for c in self.channels]:
                    self.channels.append(channel)
                if channel.current_name not in self.membrane_current_names:
                    self.membrane_current_names.append(channel.current_name)
        # Setting columns of channel names to `False` instead of `NaN`.
        for channel in self.channels:
            name = channel._name
            self.nodes.loc[self.nodes[name].isna(), name] = False

    def to_jax(self):
        """Move `.nodes` to `.jaxnodes`.

        Before the actual simulation is run (via `jx.integrate`), all parameters of
        the `jx.Module` are stored in `.nodes` (a `pd.DataFrame`). However, for
        simulation, these parameters have to be moved to be `jnp.ndarrays` such that
        they can be processed on GPU/TPU and such that the simulation can be
        differentiated. `.to_jax()` copies the `.nodes` to `.jaxnodes`.
        """
        self.jaxnodes = {}
        for key, value in self.nodes.to_dict(orient="list").items():
            inds = jnp.arange(len(value))
            self.jaxnodes[key] = jnp.asarray(value)[inds]

        # `jaxedges` contains only parameters (no indices).
        # `jaxedges` contains only non-Nan elements. This is unlike the channels where
        # we allow parameter sharing.
        self.jaxedges = {}
        edges = self.edges.to_dict(orient="list")
        for i, synapse in enumerate(self.synapses):
            for key in synapse.synapse_params:
                condition = np.asarray(edges["type_ind"]) == i
                self.jaxedges[key] = jnp.asarray(np.asarray(edges[key])[condition])
            for key in synapse.synapse_states:
                self.jaxedges[key] = jnp.asarray(np.asarray(edges[key])[condition])

    def show(
        self,
        param_names: Optional[Union[str, List[str]]] = None,  # TODO.
        *,
        indices: bool = True,
        params: bool = True,
        states: bool = True,
        channel_names: Optional[List[str]] = None,
    ) -> pd.DataFrame:
        """Print detailed information about the Module or a view of it.

        Args:
            param_names: The names of the parameters to show. If `None`, all parameters
                are shown. NOT YET IMPLEMENTED.
            indices: Whether to show the indices of the compartments.
            params: Whether to show the parameters of the compartments.
            states: Whether to show the states of the compartments.
            channel_names: The names of the channels to show. If `None`, all channels are
                shown.

        Returns:
            A `pd.DataFrame` with the requested information.
        """
        return self._show(
            self.nodes, param_names, indices, params, states, channel_names
        )

    def _show(
        self,
        view: pd.DataFrame,
        param_names: Optional[Union[str, List[str]]] = None,
        indices: bool = True,
        params: bool = True,
        states: bool = True,
        channel_names: Optional[List[str]] = None,
    ):
        """Print detailed information about the entire Module."""
        printable_nodes = deepcopy(view)

        for channel in self.channels:
            name = channel._name
            param_names = list(channel.channel_params.keys())
            state_names = list(channel.channel_states.keys())
            if channel_names is not None and name not in channel_names:
                printable_nodes = printable_nodes.drop(name, axis=1)
                printable_nodes = printable_nodes.drop(param_names, axis=1)
                printable_nodes = printable_nodes.drop(state_names, axis=1)
            else:
                if not params:
                    printable_nodes = printable_nodes.drop(param_names, axis=1)
                if not states:
                    printable_nodes = printable_nodes.drop(state_names, axis=1)

        if not indices:
            for name in ["comp_index", "branch_index", "cell_index"]:
                printable_nodes = printable_nodes.drop(name, axis=1)

        return printable_nodes

    @abstractmethod
    def init_conds(self, params: Dict):
        """Initialize coupling conductances.

        Args:
            params: Conductances and morphology parameters, not yet including
                coupling conductances.
        """
        raise NotImplementedError

    def _append_channel_to_nodes(self, view: pd.DataFrame, channel: "jx.Channel"):
        """Adds channel nodes from constituents to `self.channel_nodes`."""
        name = channel._name

        # Channel does not yet exist in the `jx.Module` at all.
        if name not in [c._name for c in self.channels]:
            self.channels.append(channel)
            self.nodes[name] = False  # Previous columns do not have the new channel.

        if channel.current_name not in self.membrane_current_names:
            self.membrane_current_names.append(channel.current_name)

        # Add a binary column that indicates if a channel is present.
        self.nodes.loc[view.index.values, name] = True

        # Loop over all new parameters, e.g. gNa, eNa.
        for key in channel.channel_params:
            self.nodes.loc[view.index.values, key] = channel.channel_params[key]

        # Loop over all new parameters, e.g. gNa, eNa.
        for key in channel.channel_states:
            self.nodes.loc[view.index.values, key] = channel.channel_states[key]

    def set(self, key: str, val: Union[float, jnp.ndarray]):
        """Set parameter of module (or its view) to a new value.

        Note that this function can not be called within `jax.jit` or `jax.grad`.
        Instead, it should be used set the parameters of the module **before** the
        simulation. Use `.data_set()` to set parameters during `jax.jit` or
        `jax.grad`.

        Args:
            key: The name of the parameter to set.
            val: The value to set the parameter to. If it is `jnp.ndarray` then it
                must be of shape `(len(num_compartments))`.
        """
        # TODO(@michaeldeistler) should we allow `.set()` for synaptic parameters
        # without using the `SynapseView`, purely for consistency with `make_trainable`?
        view = (
            self.edges
            if key in self.synapse_param_names or key in self.synapse_state_names
            else self.nodes
        )
        self._set(key, val, view, view)

    def _set(
        self,
        key: str,
        val: Union[float, jnp.ndarray],
        view: pd.DataFrame,
        table_to_update: pd.DataFrame,
    ):
        if key in view.columns:
            view = view[~np.isnan(view[key])]
            table_to_update.loc[view.index.values, key] = val
        else:
            raise KeyError("Key not recognized.")

    def data_set(
        self,
        key: str,
        val: Union[float, jnp.ndarray],
        param_state: Optional[List[Dict]],
    ):
        """Set parameter of module (or its view) to a new value within `jit`.

        Args:
            key: The name of the parameter to set.
            val: The value to set the parameter to. If it is `jnp.ndarray` then it
                must be of shape `(len(num_compartments))`.
            param_state: State of the setted parameters, internally used such that this
                function does not modify global state.
        """
        view = (
            self.edges
            if key in self.synapse_param_names or key in self.synapse_state_names
            else self.nodes
        )
        return self._data_set(key, val, view, param_state=param_state)

    def _data_set(
        self,
        key: str,
        val: Tuple[float, jnp.ndarray],
        view: pd.DataFrame,
        param_state: Optional[List[Dict]] = None,
    ):
        # Note: `data_set` does not support arrays for `val`.
        if key in view.columns:
            view = view[~np.isnan(view[key])]
            added_param_state = [
                {
                    "indices": np.atleast_2d(view.index.values),
                    "key": key,
                    "val": jnp.atleast_1d(jnp.asarray(val)),
                }
            ]
            if param_state is not None:
                param_state += added_param_state
            else:
                param_state = added_param_state
        else:
            raise KeyError("Key not recognized.")
        return param_state

    def make_trainable(
        self,
        key: str,
        init_val: Optional[Union[float, list]] = None,
        verbose: bool = True,
    ):
        """Make a parameter trainable.

        If a parameter is made trainable, it will be returned by `get_parameters()`
        and should then be passed to `jx.integrate(..., params=params)`.

        Args:
            key: Name of the parameter to make trainable.
            init_val: Initial value of the parameter. If `float`, the same value is
                used for every created parameter. If `list`, the length of the list has
                to match the number of created parameters. If `None`, the current
                parameter value is used and if parameter sharing is performed that the
                current parameter value is averaged over all shared parameters.
            verbose: Whether to print the number of parameters that are added and the
                total number of parameters.
        """
        assert (
            key not in self.synapse_param_names and key not in self.synapse_state_names
        ), "Parameters of synapses can only be made trainable via the `SynapseView`."
        view = self.nodes
        view = deepcopy(view.assign(controlled_by_param=0))
        self._make_trainable(view, key, init_val, verbose=verbose)

    def _make_trainable(
        self,
        view: pd.DataFrame,
        key: str,
        init_val: Optional[Union[float, list]] = None,
        verbose: bool = True,
    ):
        assert (
            self.allow_make_trainable
        ), "network.cell('all').make_trainable() is not supported. Use a for-loop over cells."

        if key in view.columns:
            view = view[~np.isnan(view[key])]
            grouped_view = view.groupby("controlled_by_param")
            # Because of this `x.index.values` we cannot support `make_trainable()` on
            # the module level for synapse parameters (but only for `SynapseView`).
            inds_of_comps = list(grouped_view.apply(lambda x: x.index.values))

            # Sorted inds are only used to infer the correct starting values.
            param_vals = jnp.asarray(
                [view.loc[inds, key].to_numpy() for inds in inds_of_comps]
            )
        else:
            raise KeyError(f"Parameter {key} not recognized.")

        indices_per_param = jnp.stack(inds_of_comps)
        self.indices_set_by_trainables.append(indices_per_param)

        # Set the value which the trainable parameter should take.
        num_created_parameters = len(indices_per_param)
        if init_val is not None:
            if isinstance(init_val, float):
                new_params = jnp.asarray([init_val] * num_created_parameters)
            elif isinstance(init_val, list):
                assert (
                    len(init_val) == num_created_parameters
                ), f"len(init_val)={len(init_val)}, but trying to create {num_created_parameters} parameters."
                new_params = jnp.asarray(init_val)
            else:
                raise ValueError(
                    f"init_val must a float, list, or None, but it is a {type(init_val).__name__}."
                )
        else:
            new_params = jnp.mean(param_vals, axis=1)

        self.trainable_params.append({key: new_params})
        self.num_trainable_params += num_created_parameters
        if verbose:
            print(
                f"Number of newly added trainable parameters: {num_created_parameters}. Total number of trainable parameters: {self.num_trainable_params}"
            )

    def delete_trainables(self):
        """Removes all trainable parameters from the module."""
        self.indices_set_by_trainables: List[jnp.ndarray] = []
        self.trainable_params: List[Dict[str, jnp.ndarray]] = []
        self.num_trainable_params: int = 0

    def add_to_group(self, group_name: str):
        """Add a view of the module to a group.

        Groups can then be indexed. For example:
        ```python
        net.cell(0).add_to_group("excitatory")
        net.excitatory.set("radius", 0.1)
        ```

        Args:
            group_name: The name of the group.
        """
        raise ValueError("`add_to_group()` makes no sense for an entire module.")

    def _add_to_group(self, group_name: str, view: pd.DataFrame):
        if group_name in self.group_nodes:
            view = pd.concat([self.group_nodes[group_name], view])
        self.group_nodes[group_name] = view

    def get_parameters(self) -> List[Dict[str, jnp.ndarray]]:
        """Get all trainable parameters.

        The returned parameters should be passed to `jx.integrate(..., params=params).

        Returns:
            A list of all trainable parameters in the form of
                [{"gNa": jnp.array([0.1, 0.2, 0.3])}, ...].
        """
        return self.trainable_params

    def get_all_parameters(self, pstate: List[Dict]) -> Dict[str, jnp.ndarray]:
        """Return all parameters (and coupling conductances) needed to simulate.

        Runs `init_conds()` and return every parameter that is needed to solve the ODE.
        This includes conductances, radiuses, lengths, axial_resistivities, but also
        coupling conductances.

        This is done by first obtaining the current value of every parameter (not only
        the trainable ones) and then replacing the trainable ones with the value
        in `trainable_params()`. This function is run within `jx.integrate()`.

        pstate can be obtained by calling `params_to_pstate()`.
        ```
        params = module.get_parameters() # i.e. [0, 1, 2]
        pstate = params_to_pstate(params, module.indices_set_by_trainables)
        module.to_jax() # needed for call to module.jaxnodes
        ```

        Args:
            pstate: The state of the trainable parameters. pstate takes the form
                [{"key": "gNa", "indices": jnp.array([0, 1, 2]), "val": jnp.array([0.1, 0.2, 0.3])}, ...].

        Returns:
            A dictionary of all module parameters.
        """
        params = {}
        for key in ["radius", "length", "axial_resistivity", "capacitance"]:
            params[key] = self.jaxnodes[key]

        for channel in self.channels:
            for channel_params in channel.channel_params:
                params[channel_params] = self.jaxnodes[channel_params]

        for synapse_params in self.synapse_param_names:
            params[synapse_params] = self.jaxedges[synapse_params]

        # Override with those parameters set by `.make_trainable()`.
        for parameter in pstate:
            key = parameter["key"]
            inds = parameter["indices"]
            set_param = parameter["val"]
            if key in params:  # Only parameters, not initial states.
                # `inds` is of shape `(num_params, num_comps_per_param)`.
                # `set_param` is of shape `(num_params,)`
                # We need to unsqueeze `set_param` to make it `(num_params, 1)` for the
                # `.set()` to work. This is done with `[:, None]`.
                params[key] = params[key].at[inds].set(set_param[:, None])

        # Compute conductance params and append them.
        cond_params = self.init_conds(params)
        for key in cond_params:
            params[key] = cond_params[key]

        return params

    def get_states_from_nodes_and_edges(self):
        """Return states as they are set in the `.nodes` and `.edges` tables."""
        self.to_jax()  # Create `.jaxnodes` from `.nodes` and `.jaxedges` from `.edges`.
        states = {"v": self.jaxnodes["v"]}
        # Join node and edge states into a single state dictionary.
        for channel in self.channels:
            for channel_states in channel.channel_states:
                states[channel_states] = self.jaxnodes[channel_states]
        for synapse_states in self.synapse_state_names:
            states[synapse_states] = self.jaxedges[synapse_states]
        return states

    def get_all_states(
        self, pstate: List[Dict], all_params, delta_t: float
    ) -> Dict[str, jnp.ndarray]:
        """Get the full initial state of the module from jaxnodes and trainables.

        Args:
            pstate: The state of the trainable parameters.
            all_params: All parameters of the module.
            delta_t: The time step.

        Returns:
            A dictionary of all states of the module.
        """
        states = self.get_states_from_nodes_and_edges()

        # Override with the initial states set by `.make_trainable()`.
        for parameter in pstate:
            key = parameter["key"]
            inds = parameter["indices"]
            set_param = parameter["val"]
            if key in states:  # Only initial states, not parameters.
                # `inds` is of shape `(num_params, num_comps_per_param)`.
                # `set_param` is of shape `(num_params,)`
                # We need to unsqueeze `set_param` to make it `(num_params, 1)` for the
                # `.set()` to work. This is done with `[:, None]`.
                states[key] = states[key].at[inds].set(set_param[:, None])

        # Add to the states the initial current through every channel.
        states, _ = self._channel_currents(
            states, delta_t, self.channels, self.nodes, all_params
        )

        # Add to the states the initial current through every synapse.
        states, _ = self._synapse_currents(
            states, self.synapses, all_params, delta_t, self.edges
        )
        return states

    @property
    def initialized(self):
        """Whether the `Module` is ready to be solved or not."""
        return self.initialized_morph and self.initialized_syns

    def initialize(self):
        """Initialize the module."""
        self.init_morph()
        return self

    def init_states(self, delta_t: float = 0.025):
        """Initialize all mechanisms in their steady state.

        This considers the voltages and parameters of each compartment.

        Args:
            delta_t: Passed on to `channel.init_state()`.
        """
        # Update states of the channels.
        channel_nodes = self.nodes
        states = self.get_states_from_nodes_and_edges()

        # We do not use any `pstate` for initializing. In principle, we could change
        # that by allowing an input `params` and `pstate` to this function.
        params = self.get_all_parameters([])

        for channel in self.channels:
            name = channel._name
            channel_indices = channel_nodes.loc[channel_nodes[name]][
                "comp_index"
            ].to_numpy()
            voltages = channel_nodes.loc[channel_indices, "v"].to_numpy()

            channel_param_names = list(channel.channel_params.keys())
            channel_state_names = list(channel.channel_states.keys())
            channel_states = query_channel_states_and_params(
                states, channel_state_names, channel_indices
            )
            channel_params = query_channel_states_and_params(
                params, channel_param_names, channel_indices
            )

            init_state = channel.init_state(
                channel_states, voltages, channel_params, delta_t
            )

            # `init_state` might not return all channel states. Only the ones that are
            # returned are updated here.
            for key, val in init_state.items():
                # Note that we are overriding `self.nodes` here, but `self.nodes` is
                # not used above to actually compute the current states (so there are
                # no issues with overriding states).
                self.nodes.loc[channel_indices, key] = val

    def _init_morph_for_debugging(self):
        """Instandiates row and column inds which can be used to solve the voltage eqs.

        This is important only for expert users who try to modify the solver for the
        voltage equations. By default, this function is never run.

        This is useful for debugging the solver because one can use
        `scipy.linalg.sparse.spsolve` after every step of the solve.

        Here is the code snippet that can be used for debugging then (to be inserted in
        `solver_voltage`):
        ```python
        from scipy.sparse import csc_matrix
        from scipy.sparse.linalg import spsolve
        from jaxley.utils.debug_solver import build_voltage_matrix_elements

        elements, solve, num_entries, start_ind_for_branchpoints = (
            build_voltage_matrix_elements(
                uppers,
                lowers,
                diags,
                solves,
                branchpoint_conds_children[debug_states["child_inds"]],
                branchpoint_conds_parents[debug_states["par_inds"]],
                branchpoint_weights_children[debug_states["child_inds"]],
                branchpoint_weights_parents[debug_states["par_inds"]],
                branchpoint_diags,
                branchpoint_solves,
                debug_states["nseg"],
                nbranches,
            )
        )
        sparse_matrix = csc_matrix(
            (elements, (debug_states["row_inds"], debug_states["col_inds"])),
            shape=(num_entries, num_entries),
        )
        solution = spsolve(sparse_matrix, solve)
        solution = solution[:start_ind_for_branchpoints]  # Delete branchpoint voltages.
        solves = jnp.reshape(solution, (debug_states["nseg"], nbranches))
        return solves
        ```
        """
        # For scipy and jax.scipy.
        row_and_col_inds = compute_morphology_indices(
            len(self.par_inds),
            self.child_belongs_to_branchpoint,
            self.par_inds,
            self.child_inds,
            self.nseg,
            self.total_nbranches,
        )

        num_elements = len(row_and_col_inds["row_inds"])
        data_inds, indices, indptr = convert_to_csc(
            num_elements=num_elements,
            row_ind=row_and_col_inds["row_inds"],
            col_ind=row_and_col_inds["col_inds"],
        )
        self.debug_states["row_inds"] = row_and_col_inds["row_inds"]
        self.debug_states["col_inds"] = row_and_col_inds["col_inds"]
        self.debug_states["data_inds"] = data_inds
        self.debug_states["indices"] = indices
        self.debug_states["indptr"] = indptr

        self.debug_states["nseg"] = self.nseg
        self.debug_states["child_inds"] = self.child_inds
        self.debug_states["par_inds"] = self.par_inds

    def record(self, state: str = "v", verbose: bool = True):
        """Insert a recording into the compartment.

        Args:
            state: The name of the state to record.
            verbose: Whether to print number of inserted recordings."""
        view = deepcopy(self.nodes)
        view["state"] = state
        recording_view = view[["comp_index", "state"]]
        recording_view = recording_view.rename(columns={"comp_index": "rec_index"})
        self._record(recording_view, verbose=verbose)

    def _record(self, view: pd.DataFrame, verbose: bool = True):
        self.recordings = pd.concat([self.recordings, view], ignore_index=True)
        if verbose:
            print(f"Added {len(view)} recordings. See `.recordings` for details.")

    def delete_recordings(self):
        """Removes all recordings from the module."""
        self.recordings = pd.DataFrame().from_dict({})

    def stimulate(self, current: Optional[jnp.ndarray] = None, verbose: bool = True):
        """Insert a stimulus into the compartment.

        current must be a 1d array or have batch dimension of size `(num_compartments, )`
        or `(1, )`. If 1d, the same stimulus is added to all compartments.

        This function cannot be run during `jax.jit` and `jax.grad`. Because of this,
        it should only be used for static stimuli (i.e., stimuli that do not depend
        on the data and that should not be learned). For stimuli that depend on data
        (or that should be learned), please use `data_stimulate()`.

        Args:
            current: Current in `nA`.
        """
        self._external_input("i", current, self.nodes, verbose=verbose)

    def clamp(self, state_name: str, state_array: jnp.ndarray, verbose: bool = True):
        """Clamp a state to a given value across specified compartments.

        Args:
            state_name: The name of the state to clamp.
            state_array (jnp.nd: Array of values to clamp the state to.
            verbose : If True, prints details about the clamping.

        This function sets external states for the compartments.
        """
        if state_name not in self.nodes.columns:
            raise KeyError(f"{state_name} is not a recognized state in this module.")
        self._external_input(state_name, state_array, self.nodes, verbose=verbose)

    def _external_input(
        self,
        key: str,
        values: Optional[jnp.ndarray],
        view: pd.DataFrame,
        verbose: bool = True,
    ):
        values = values if values.ndim == 2 else jnp.expand_dims(values, axis=0)
        batch_size = values.shape[0]
        is_multiple = len(view) == batch_size
        values = values if is_multiple else jnp.repeat(values, len(view), axis=0)
        assert batch_size in [1, len(view)], "Number of comps and stimuli do not match."

        if key in self.externals.keys():
            self.externals[key] = jnp.concatenate([self.externals[key], values])
            self.external_inds[key] = jnp.concatenate(
                [self.external_inds[key], view.comp_index.to_numpy()]
            )
        else:
            self.externals[key] = values
            self.external_inds[key] = view.comp_index.to_numpy()

        if verbose:
            print(f"Added {len(view)} external_states. See `.externals` for details.")

    def data_stimulate(
        self,
        current: jnp.ndarray,
        data_stimuli: Optional[Tuple[jnp.ndarray, pd.DataFrame]] = None,
        verbose: bool = False,
    ) -> Tuple[jnp.ndarray, pd.DataFrame]:
        """Insert a stimulus into the module within jit (or grad).

        Args:
            current: Current in `nA`.
            verbose: Whether or not to print the number of inserted stimuli. `False`
                by default because this method is meant to be jitted.
        """
        return self._data_stimulate(current, data_stimuli, self.nodes, verbose=verbose)

    def _data_stimulate(
        self,
        current: jnp.ndarray,
        data_stimuli: Optional[Tuple[jnp.ndarray, pd.DataFrame]],
        view: pd.DataFrame,
        verbose: bool = False,
    ) -> Tuple[jnp.ndarray, pd.DataFrame]:
        current = current if current.ndim == 2 else jnp.expand_dims(current, axis=0)
        batch_size = current.shape[0]
        is_multiple = len(view) == batch_size
        current = current if is_multiple else jnp.repeat(current, len(view), axis=0)
        assert batch_size in [1, len(view)], "Number of comps and stimuli do not match."

        if data_stimuli is not None:
            currents = data_stimuli[0]
            inds = data_stimuli[1]
        else:
            currents = None
            inds = pd.DataFrame().from_dict({})

        # Same as in `.stimulate()`.
        if currents is not None:
            currents = jnp.concatenate([currents, current])
        else:
            currents = current
        inds = pd.concat([inds, view])

        if verbose:
            print(f"Added {len(view)} stimuli.")

        return (currents, inds)

    def delete_stimuli(self):
        """Removes all stimuli from the module."""
        self.externals.pop("i", None)
        self.external_inds.pop("i", None)

    def insert(self, channel: Channel):
        """Insert a channel into the module.

        Args:
            channel: The channel to insert."""
        self._insert(channel, self.nodes)

    def _insert(self, channel, view):
        self._append_channel_to_nodes(view, channel)

    def init_syns(self):
        self.initialized_syns = True

    def init_morph(self):
        self.initialized_morph = True

    def step(
        self,
        u: Dict[str, jnp.ndarray],
        delta_t: float,
        external_inds: Dict[str, jnp.ndarray],
        externals: Dict[str, jnp.ndarray],
        params: Dict[str, jnp.ndarray],
        solver: str = "bwd_euler",
        voltage_solver: str = "jaxley.stone",
    ) -> Dict[str, jnp.ndarray]:
        """One step of solving the Ordinary Differential Equation.

        This function is called inside of `integrate` and increments the state of the
        module by one time step. Calls `_step_channels` and `_step_synapse` to update
        the states of the channels and synapses using fwd_euler.

        Args:
            u: The state of the module. voltages = u["v"]
            delta_t: The time step.
            external_inds: The indices of the external inputs.
            externals: The external inputs.
            params: The parameters of the module.
            solver: The solver to use for the voltages. Either of ["bwd_euler",
                "fwd_euler", "crank_nicolson"].
            voltage_solver: The tridiagonal solver used to diagonalize the
                coefficient matrix of the ODE system. Either of ["jaxley.thomas",
                "jaxley.stone"].

        Returns:
            The updated state of the module.
        """

        # Extract the voltages
        voltages = u["v"]

        # Extract the external inputs
        has_current = "i" in externals.keys()
        i_current = externals["i"] if has_current else jnp.asarray([]).astype("float")
        i_inds = external_inds["i"] if has_current else jnp.asarray([]).astype("int32")
        i_ext = self._get_external_input(
            voltages, i_inds, i_current, params["radius"], params["length"]
        )

        # Step of the channels.
        u, (v_terms, const_terms) = self._step_channels(
            u, delta_t, self.channels, self.nodes, params
        )

        # Step of the synapse.
        u, (syn_v_terms, syn_const_terms) = self._step_synapse(
            u,
            self.synapses,
            params,
            delta_t,
            self.edges,
        )

        # Clamp for channels and synapses.
        for key in externals.keys():
            if key not in ["i", "v"]:
                u[key] = u[key].at[external_inds[key]].set(externals[key])

        # Voltage steps.
        cm = params["capacitance"]  # Abbreviation.

        solver_kwargs = {
            "voltages": voltages,
            "voltage_terms": (v_terms + syn_v_terms) / cm,
            "constant_terms": (const_terms + i_ext + syn_const_terms) / cm,
            "coupling_conds_upper": params["branch_uppers"],
            "coupling_conds_lower": params["branch_lowers"],
            "summed_coupling_conds": params["branch_diags"],
            "branchpoint_conds_children": params["branchpoint_conds_children"],
            "branchpoint_conds_parents": params["branchpoint_conds_parents"],
            "branchpoint_weights_children": params["branchpoint_weights_children"],
            "branchpoint_weights_parents": params["branchpoint_weights_parents"],
            "par_inds": self.par_inds,
            "child_inds": self.child_inds,
            "nbranches": self.total_nbranches,
            "solver": voltage_solver,
            "children_in_level": self.children_in_level,
            "parents_in_level": self.parents_in_level,
            "root_inds": self.root_inds,
            "branchpoint_group_inds": self.branchpoint_group_inds,
            "debug_states": self.debug_states,
        }
        if solver == "bwd_euler":
            new_voltages = step_voltage_implicit(**solver_kwargs, delta_t=delta_t)
            u["v"] = new_voltages.ravel(order="C")
        elif solver == "fwd_euler":
            new_voltages = step_voltage_explicit(**solver_kwargs, delta_t=delta_t)
            u["v"] = new_voltages.ravel(order="C")
        elif solver == "crank_nicolson":
            # Crank Nicolson advances by half a step of backward and half a step of
            # forward Euler.
            half_step_delta_t = delta_t / 2
            half_step_voltages = step_voltage_implicit(
                **solver_kwargs, delta_t=half_step_delta_t
            )
            # The forward Euler step in Crank Nicolson can be performed easily as
            # `V_{n+1} = 2 * V_{n+1/2} - V_n`. See also NEURON book Chapter 4.
            u["v"] = 2 * half_step_voltages.ravel(order="C") - voltages
        else:
            raise ValueError(
                f"You specified `solver={solver}`. The only allowed solvers are "
                "['bwd_euler', 'fwd_euler', 'crank_nicolson']."
            )

        # Clamp for voltages.
        if "v" in externals.keys():
            u["v"] = u["v"].at[external_inds["v"]].set(externals["v"])

        return u

    def _step_channels(
        self,
        states: Dict[str, jnp.ndarray],
        delta_t: float,
        channels: List[Channel],
        channel_nodes: pd.DataFrame,
        params: Dict[str, jnp.ndarray],
    ) -> Tuple[Dict[str, jnp.ndarray], Tuple[jnp.ndarray, jnp.ndarray]]:
        """One step of integration of the channels and of computing their current."""
        states = self._step_channels_state(
            states, delta_t, channels, channel_nodes, params
        )
        states, current_terms = self._channel_currents(
            states, delta_t, channels, channel_nodes, params
        )
        return states, current_terms

    def _step_channels_state(
        self,
        states,
        delta_t,
        channels: List[Channel],
        channel_nodes: pd.DataFrame,
        params: Dict[str, jnp.ndarray],
    ) -> Dict[str, jnp.ndarray]:
        """One integration step of the channels."""
        voltages = states["v"]

        # Update states of the channels.
        indices = channel_nodes["comp_index"].to_numpy()
        for channel in channels:
            channel_param_names = list(channel.channel_params)
            channel_param_names += ["radius", "length", "axial_resistivity"]
            channel_state_names = list(channel.channel_states)
            channel_state_names += self.membrane_current_names
            channel_indices = indices[channel_nodes[channel._name].astype(bool)]

            channel_params = query_channel_states_and_params(
                params, channel_param_names, channel_indices
            )
            channel_states = query_channel_states_and_params(
                states, channel_state_names, channel_indices
            )

            states_updated = channel.update_states(
                channel_states, delta_t, voltages[channel_indices], channel_params
            )
            # Rebuild state. This has to be done within the loop over channels to allow
            # multiple channels which modify the same state.
            for key, val in states_updated.items():
                states[key] = states[key].at[channel_indices].set(val)

        return states

    def _channel_currents(
        self,
        states: Dict[str, jnp.ndarray],
        delta_t: float,
        channels: List[Channel],
        channel_nodes: pd.DataFrame,
        params: Dict[str, jnp.ndarray],
    ) -> Tuple[Dict[str, jnp.ndarray], Tuple[jnp.ndarray, jnp.ndarray]]:
        """Return the current through each channel.

        This is also updates `state` because the `state` also contains the current.
        """
        voltages = states["v"]

        # Compute current through channels.
        voltage_terms = jnp.zeros_like(voltages)
        constant_terms = jnp.zeros_like(voltages)
        # Run with two different voltages that are `diff` apart to infer the slope and
        # offset.
        diff = 1e-3

        current_states = {}
        for name in self.membrane_current_names:
            current_states[name] = jnp.zeros_like(voltages)

        for channel in channels:
            name = channel._name
            channel_param_names = list(channel.channel_params.keys())
            channel_state_names = list(channel.channel_states.keys())
            indices = channel_nodes.loc[channel_nodes[name]]["comp_index"].to_numpy()

            channel_params = {}
            for p in channel_param_names:
                channel_params[p] = params[p][indices]
            channel_params["radius"] = params["radius"][indices]
            channel_params["length"] = params["length"][indices]
            channel_params["axial_resistivity"] = params["axial_resistivity"][indices]

            channel_states = {}
            for s in channel_state_names:
                channel_states[s] = states[s][indices]

            v_and_perturbed = jnp.stack([voltages[indices], voltages[indices] + diff])
            membrane_currents = vmap(channel.compute_current, in_axes=(None, 0, None))(
                channel_states, v_and_perturbed, channel_params
            )
            voltage_term = (membrane_currents[1] - membrane_currents[0]) / diff
            constant_term = membrane_currents[0] - voltage_term * voltages[indices]
            voltage_terms = voltage_terms.at[indices].add(voltage_term)
            constant_terms = constant_terms.at[indices].add(-constant_term)

            # Save the current (for the unperturbed voltage) as a state that will
            # also be passed to the state update.
            current_states[channel.current_name] = (
                current_states[channel.current_name]
                .at[indices]
                .add(membrane_currents[0])
            )

        # Copy the currents into the `state` dictionary such that they can be
        # recorded and used by `Channel.update_states()`.
        for name in self.membrane_current_names:
            states[name] = current_states[name]

        return states, (voltage_terms, constant_terms)

    def _step_synapse(
        self,
        u: Dict[str, jnp.ndarray],
        syn_channels: List[Channel],
        params: Dict[str, jnp.ndarray],
        delta_t: float,
        edges: pd.DataFrame,
    ) -> Tuple[Dict[str, jnp.ndarray], Tuple[jnp.ndarray, jnp.ndarray]]:
        """One step of integration of the channels.

        `Network` overrides this method (because it actually has synapses), whereas
        `Compartment`, `Branch`, and `Cell` do not override this.
        """
        voltages = u["v"]
        return u, (jnp.zeros_like(voltages), jnp.zeros_like(voltages))

    def _synapse_currents(
        self, states, syn_channels, params, delta_t, edges: pd.DataFrame
    ) -> Tuple[Dict[str, jnp.ndarray], Tuple[jnp.ndarray, jnp.ndarray]]:
        return states, (None, None)

    @staticmethod
    def _get_external_input(
        voltages: jnp.ndarray,
        i_inds: jnp.ndarray,
        i_stim: jnp.ndarray,
        radius: float,
        length_single_compartment: float,
    ) -> jnp.ndarray:
        """
        Return external input to each compartment in uA / cm^2.

        Args:
            voltages: mV.
            i_stim: nA.
            radius: um.
            length_single_compartment: um.
        """
        zero_vec = jnp.zeros_like(voltages)
        current = convert_point_process_to_distributed(
            i_stim, radius[i_inds], length_single_compartment[i_inds]
        )

        dnums = ScatterDimensionNumbers(
            update_window_dims=(),
            inserted_window_dims=(0,),
            scatter_dims_to_operand_dims=(0,),
        )
        stim_at_timestep = scatter_add(zero_vec, i_inds[:, None], current, dnums)
        return stim_at_timestep

    def vis(
        self,
        ax: Optional[Axes] = None,
        col: str = "k",
        dims: Tuple[int] = (0, 1),
        type: str = "line",
        morph_plot_kwargs: Dict = {},
    ) -> Axes:
        """Visualize the module.

        Args:
            ax: An axis into which to plot.
            col: The color for all branches.
            dims: Which dimensions to plot. 1=x, 2=y, 3=z coordinate. Must be a tuple of
                two of them.
            morph_plot_kwargs: Keyword arguments passed to the plotting function.
        """
        return self._vis(
            dims=dims,
            col=col,
            ax=ax,
            view=self.nodes,
            type=type,
            morph_plot_kwargs=morph_plot_kwargs,
        )

    def _vis(
        self,
        ax: Axes,
        col: str,
        dims: Tuple[int],
        view: pd.DataFrame,
        type: str,
        morph_plot_kwargs: Dict,
    ) -> Axes:
        branches_inds = view["branch_index"].to_numpy()
        coords = []
        for branch_ind in branches_inds:
            assert not np.any(
                np.isnan(self.xyzr[branch_ind][:, dims])
            ), "No coordinates available. Use `vis(detail='point')` or run `.compute_xyz()` before running `.vis()`."
            coords.append(self.xyzr[branch_ind])

        ax = plot_morph(
            coords,
            dims=dims,
            col=col,
            ax=ax,
            type=type,
            morph_plot_kwargs=morph_plot_kwargs,
        )

        return ax

    def _scatter(self, ax, col, dims, view, morph_plot_kwargs):
        """Scatter visualization (used only for compartments)."""
        assert len(view) == 1, "Scatter only deals with compartments."
        branch_ind = view["branch_index"].to_numpy().item()
        comp_ind = view["comp_index"].to_numpy().item()
        assert not np.any(
            np.isnan(self.xyzr[branch_ind][:, dims])
        ), "No coordinates available. Use `vis(detail='point')` or run `.compute_xyz()` before running `.vis()`."

        comp_fraction = loc_of_index(comp_ind, self.nseg)
        coords = self.xyzr[branch_ind]
        interpolated_xyz = interpolate_xyz(comp_fraction, coords)

        ax = plot_morph(
            np.asarray([[interpolated_xyz]]),
            dims=dims,
            col=col,
            ax=ax,
            type="scatter",
            morph_plot_kwargs=morph_plot_kwargs,
        )

        return ax

    def compute_xyz(self):
        """Return xyz coordinates of every branch, based on the branch length.

        This function should not be called if the morphology was read from an `.swc`
        file. However, for morphologies that were constructed from scratch, this
        function **must** be called before `.vis()`. The computed `xyz` coordinates
        are only used for plotting.
        """
        max_y_multiplier = 5.0
        min_y_multiplier = 0.5

        parents = self.comb_parents
        num_children = _compute_num_children(parents)
        index_of_child = _compute_index_of_child(parents)
        levels = compute_levels(parents)

        # Extract branch.
        inds_branch = self.nodes.groupby("branch_index")["comp_index"].apply(list)
        branch_lens = [np.sum(self.nodes["length"][np.asarray(i)]) for i in inds_branch]
        endpoints = []

        # Different levels will get a different "angle" at which the children emerge from
        # the parents. This angle is defined by the `y_offset_multiplier`. This value
        # defines the range between y-location of the first and of the last child of a
        # parent.
        y_offset_multiplier = np.linspace(
            max_y_multiplier, min_y_multiplier, np.max(levels) + 1
        )

        for b in range(self.total_nbranches):
            # For networks with mixed SWC and from-scatch neurons, only update those
            # branches that do not have coordingates yet.
            if np.any(np.isnan(self.xyzr[b])):
                if parents[b] > -1:
                    start_point = endpoints[parents[b]]
                    num_children_of_parent = num_children[parents[b]]
                    if num_children_of_parent > 1:
                        y_offset = (
                            ((index_of_child[b] / (num_children_of_parent - 1))) - 0.5
                        ) * y_offset_multiplier[levels[b]]
                    else:
                        y_offset = 0.0
                else:
                    start_point = [0, 0, 0]
                    y_offset = 0.0

                len_of_path = np.sqrt(y_offset**2 + 1.0)

                end_point = [
                    start_point[0] + branch_lens[b] / len_of_path * 1.0,
                    start_point[1] + branch_lens[b] / len_of_path * y_offset,
                    start_point[2],
                ]
                endpoints.append(end_point)

                self.xyzr[b][:, :3] = np.asarray([start_point, end_point])
            else:
                # Dummy to keey the index `endpoints[parent[b]]` above working.
                endpoints.append(np.zeros((2,)))

    def move(
        self, x: float = 0.0, y: float = 0.0, z: float = 0.0, update_nodes: bool = True
    ):
        """Move cells or networks by adding to their (x, y, z) coordinates.

        This function is used only for visualization. It does not affect the simulation.

        Args:
            x: The amount to move in the x direction in um.
            y: The amount to move in the y direction in um.
            z: The amount to move in the z direction in um.
            update_nodes: Whether `.nodes` should be updated or not. Setting this to
                `False` largely speeds up moving, especially for big networks, but
                `.nodes` or `.show` will not show the new xyz coordinates.
        """
        self._move(x, y, z, self.nodes, update_nodes)

    def _move(self, x: float, y: float, z: float, view, update_nodes: bool):
        # Need to cast to set because this will return one columnn per compartment,
        # not one column per branch.
        indizes = set(view["branch_index"].to_numpy().tolist())
        for i in indizes:
            self.xyzr[i][:, 0] += x
            self.xyzr[i][:, 1] += y
            self.xyzr[i][:, 2] += z
        if update_nodes:
            self._update_nodes_with_xyz()

    def move_to(
        self,
        x: Union[float, np.ndarray] = 0.0,
        y: Union[float, np.ndarray] = 0.0,
        z: Union[float, np.ndarray] = 0.0,
        update_nodes: bool = True,
    ):
        """Move cells or networks to a location (x, y, z).

        If x, y, and z are floats, then the first compartment of the first branch
        of the first cell is moved to that float coordinate, and everything else is
        shifted by the difference between that compartment's previous coordinate and
        the new float location.

        If x, y, and z are arrays, then they must each have a length equal to the number
        of cells being moved. Then the first compartment of the first branch of each
        cell is moved to the specified location.

        Args:
            update_nodes: Whether `.nodes` should be updated or not. Setting this to
                `False` largely speeds up moving, especially for big networks, but
                `.nodes` or `.show` will not show the new xyz coordinates.
        """
        self._move_to(x, y, z, self.nodes, update_nodes)

    def _move_to(
        self,
        x: Union[float, np.ndarray],
        y: Union[float, np.ndarray],
        z: Union[float, np.ndarray],
        view: pd.DataFrame,
        update_nodes: bool,
    ):
        # Test if any coordinate values are NaN which would greatly affect moving
        if np.any(np.concatenate(self.xyzr, axis=0)[:, :3] == np.nan):
            raise ValueError(
                "NaN coordinate values detected. Shift amounts cannot be computed. Please run compute_xyzr() or assign initial coordinate values."
            )

        # Get the indices of the cells and branches to move
        cell_inds = list(view.cell_index.unique())
        branch_inds = view.branch_index.unique()

        if (
            isinstance(x, np.ndarray)
            and isinstance(y, np.ndarray)
            and isinstance(z, np.ndarray)
        ):
            assert (
                x.shape == y.shape == z.shape == (len(cell_inds),)
            ), "x, y, and z array shapes are not all equal to the number of cells to be moved."

            # Split the branches by cell id
            tup_indices = np.array([view.cell_index, view.branch_index])
            view_cell_branch_inds = np.unique(tup_indices, axis=1)[0]
            _, branch_split_inds = np.unique(view_cell_branch_inds, return_index=True)
            branches_by_cell = np.split(
                view.branch_index.unique(), branch_split_inds[1:]
            )

            # Calculate the amount to shift all of the branches of each cell
            shift_amounts = (
                np.array([x, y, z]).T - np.stack(self[cell_inds, 0].xyzr)[:, 0, :3]
            )

        else:
            # Treat as if all branches belong to the same cell to be moved
            branches_by_cell = [branch_inds]
            # Calculate the amount to shift all branches by the 1st branch of 1st cell
            shift_amounts = [np.array([x, y, z]) - self[cell_inds].xyzr[0][0, :3]]

        # Move all of the branches
        for i, branches in enumerate(branches_by_cell):
            for b in branches:
                self.xyzr[b][:, :3] += shift_amounts[i]

        if update_nodes:
            self._update_nodes_with_xyz()

    def rotate(self, degrees: float, rotation_axis: str = "xy"):
        """Rotate jaxley modules clockwise. Used only for visualization.

        This function is used only for visualization. It does not affect the simulation.

        Args:
            degrees: How many degrees to rotate the module by.
            rotation_axis: Either of {`xy` | `xz` | `yz`}.
        """
        self._rotate(degrees=degrees, rotation_axis=rotation_axis, view=self.nodes)

    def _rotate(self, degrees: float, rotation_axis: str, view: pd.DataFrame):
        degrees = degrees / 180 * np.pi
        if rotation_axis == "xy":
            dims = [0, 1]
        elif rotation_axis == "xz":
            dims = [0, 2]
        elif rotation_axis == "yz":
            dims = [1, 2]
        else:
            raise ValueError

        rotation_matrix = np.asarray(
            [[np.cos(degrees), np.sin(degrees)], [-np.sin(degrees), np.cos(degrees)]]
        )
        indizes = set(view["branch_index"].to_numpy().tolist())
        for i in indizes:
            rot = np.dot(rotation_matrix, self.xyzr[i][:, dims].T).T
            self.xyzr[i][:, dims] = rot

    @property
    def shape(self) -> Tuple[int]:
        """Returns the number of submodules contained in a module.

        ```
        network.shape = (num_cells, num_branches, num_compartments)
        cell.shape = (num_branches, num_compartments)
        branch.shape = (num_compartments,)
        ```"""
        mod_name = self.__class__.__name__.lower()
        if "comp" in mod_name:
            return (1,)
        elif "branch" in mod_name:
            return self[:].shape[1:]
        return self[:].shape

    def __getitem__(self, index):
        return self._getitem(self, index)

    def _getitem(
        self,
        module: Union["Module", "View"],
        index: Union[Tuple, int],
        child_name: Optional[str] = None,
    ) -> "View":
        """Return View which is created from indexing the module.

        Args:
            module: The module to be indexed. Will be a `Module` if `._getitem` is
                called from `__getitem__` in a `Module` and will be a `View` if it was
                called from `__getitem__` in a `View`.
            index: The index (or indices) to index the module.
            child_name: If passed, this will be the key that is used to index the
                `module`, e.g. if it is the string `branch` then we will try to call
                `module.xyz(index)`. If `None` then we try to infer automatically what
                the childview should be, given the name of the `module`.

        Returns:
            An indexed `View`.
        """
        if isinstance(index, tuple):
            if len(index) > 1:
                return childview(module, index[0], child_name)[index[1:]]
            return childview(module, index[0], child_name)
        return childview(module, index, child_name)

    def __iter__(self):
        for i in range(self.shape[0]):
            yield self[i]

    def _local_inds_to_global(
        self, cell_inds: np.ndarray, branch_inds: np.ndarray, comp_inds: np.ndarray
    ):
        """Given local inds of cell, branch, and comp, return the global comp index."""
        global_ind = (
            self.cumsum_nbranches[cell_inds] + branch_inds
        ) * self.nseg + comp_inds
        return global_ind.astype(int)

initialized property

Whether the Module is ready to be solved or not.

shape: Tuple[int] property

Returns the number of submodules contained in a module.

network.shape = (num_cells, num_branches, num_compartments)
cell.shape = (num_branches, num_compartments)
branch.shape = (num_compartments,)

add_to_group(group_name)

Add a view of the module to a group.

Groups can then be indexed. For example:

net.cell(0).add_to_group("excitatory")
net.excitatory.set("radius", 0.1)

Parameters:

Name Type Description Default
group_name str

The name of the group.

required
Source code in jaxley/modules/base.py
455
456
457
458
459
460
461
462
463
464
465
466
467
def add_to_group(self, group_name: str):
    """Add a view of the module to a group.

    Groups can then be indexed. For example:
    ```python
    net.cell(0).add_to_group("excitatory")
    net.excitatory.set("radius", 0.1)
    ```

    Args:
        group_name: The name of the group.
    """
    raise ValueError("`add_to_group()` makes no sense for an entire module.")

clamp(state_name, state_array, verbose=True)

Clamp a state to a given value across specified compartments.

Parameters:

Name Type Description Default
state_name str

The name of the state to clamp.

required
state_array nd

Array of values to clamp the state to.

required
verbose

If True, prints details about the clamping.

True

This function sets external states for the compartments.

Source code in jaxley/modules/base.py
749
750
751
752
753
754
755
756
757
758
759
760
761
def clamp(self, state_name: str, state_array: jnp.ndarray, verbose: bool = True):
    """Clamp a state to a given value across specified compartments.

    Args:
        state_name: The name of the state to clamp.
        state_array (jnp.nd: Array of values to clamp the state to.
        verbose : If True, prints details about the clamping.

    This function sets external states for the compartments.
    """
    if state_name not in self.nodes.columns:
        raise KeyError(f"{state_name} is not a recognized state in this module.")
    self._external_input(state_name, state_array, self.nodes, verbose=verbose)

compute_xyz()

Return xyz coordinates of every branch, based on the branch length.

This function should not be called if the morphology was read from an .swc file. However, for morphologies that were constructed from scratch, this function must be called before .vis(). The computed xyz coordinates are only used for plotting.

Source code in jaxley/modules/base.py
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
def compute_xyz(self):
    """Return xyz coordinates of every branch, based on the branch length.

    This function should not be called if the morphology was read from an `.swc`
    file. However, for morphologies that were constructed from scratch, this
    function **must** be called before `.vis()`. The computed `xyz` coordinates
    are only used for plotting.
    """
    max_y_multiplier = 5.0
    min_y_multiplier = 0.5

    parents = self.comb_parents
    num_children = _compute_num_children(parents)
    index_of_child = _compute_index_of_child(parents)
    levels = compute_levels(parents)

    # Extract branch.
    inds_branch = self.nodes.groupby("branch_index")["comp_index"].apply(list)
    branch_lens = [np.sum(self.nodes["length"][np.asarray(i)]) for i in inds_branch]
    endpoints = []

    # Different levels will get a different "angle" at which the children emerge from
    # the parents. This angle is defined by the `y_offset_multiplier`. This value
    # defines the range between y-location of the first and of the last child of a
    # parent.
    y_offset_multiplier = np.linspace(
        max_y_multiplier, min_y_multiplier, np.max(levels) + 1
    )

    for b in range(self.total_nbranches):
        # For networks with mixed SWC and from-scatch neurons, only update those
        # branches that do not have coordingates yet.
        if np.any(np.isnan(self.xyzr[b])):
            if parents[b] > -1:
                start_point = endpoints[parents[b]]
                num_children_of_parent = num_children[parents[b]]
                if num_children_of_parent > 1:
                    y_offset = (
                        ((index_of_child[b] / (num_children_of_parent - 1))) - 0.5
                    ) * y_offset_multiplier[levels[b]]
                else:
                    y_offset = 0.0
            else:
                start_point = [0, 0, 0]
                y_offset = 0.0

            len_of_path = np.sqrt(y_offset**2 + 1.0)

            end_point = [
                start_point[0] + branch_lens[b] / len_of_path * 1.0,
                start_point[1] + branch_lens[b] / len_of_path * y_offset,
                start_point[2],
            ]
            endpoints.append(end_point)

            self.xyzr[b][:, :3] = np.asarray([start_point, end_point])
        else:
            # Dummy to keey the index `endpoints[parent[b]]` above working.
            endpoints.append(np.zeros((2,)))

data_set(key, val, param_state)

Set parameter of module (or its view) to a new value within jit.

Parameters:

Name Type Description Default
key str

The name of the parameter to set.

required
val Union[float, ndarray]

The value to set the parameter to. If it is jnp.ndarray then it must be of shape (len(num_compartments)).

required
param_state Optional[List[Dict]]

State of the setted parameters, internally used such that this function does not modify global state.

required
Source code in jaxley/modules/base.py
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def data_set(
    self,
    key: str,
    val: Union[float, jnp.ndarray],
    param_state: Optional[List[Dict]],
):
    """Set parameter of module (or its view) to a new value within `jit`.

    Args:
        key: The name of the parameter to set.
        val: The value to set the parameter to. If it is `jnp.ndarray` then it
            must be of shape `(len(num_compartments))`.
        param_state: State of the setted parameters, internally used such that this
            function does not modify global state.
    """
    view = (
        self.edges
        if key in self.synapse_param_names or key in self.synapse_state_names
        else self.nodes
    )
    return self._data_set(key, val, view, param_state=param_state)

data_stimulate(current, data_stimuli=None, verbose=False)

Insert a stimulus into the module within jit (or grad).

Parameters:

Name Type Description Default
current ndarray

Current in nA.

required
verbose bool

Whether or not to print the number of inserted stimuli. False by default because this method is meant to be jitted.

False
Source code in jaxley/modules/base.py
788
789
790
791
792
793
794
795
796
797
798
799
800
801
def data_stimulate(
    self,
    current: jnp.ndarray,
    data_stimuli: Optional[Tuple[jnp.ndarray, pd.DataFrame]] = None,
    verbose: bool = False,
) -> Tuple[jnp.ndarray, pd.DataFrame]:
    """Insert a stimulus into the module within jit (or grad).

    Args:
        current: Current in `nA`.
        verbose: Whether or not to print the number of inserted stimuli. `False`
            by default because this method is meant to be jitted.
    """
    return self._data_stimulate(current, data_stimuli, self.nodes, verbose=verbose)

delete_recordings()

Removes all recordings from the module.

Source code in jaxley/modules/base.py
729
730
731
def delete_recordings(self):
    """Removes all recordings from the module."""
    self.recordings = pd.DataFrame().from_dict({})

delete_stimuli()

Removes all stimuli from the module.

Source code in jaxley/modules/base.py
835
836
837
838
def delete_stimuli(self):
    """Removes all stimuli from the module."""
    self.externals.pop("i", None)
    self.external_inds.pop("i", None)

delete_trainables()

Removes all trainable parameters from the module.

Source code in jaxley/modules/base.py
449
450
451
452
453
def delete_trainables(self):
    """Removes all trainable parameters from the module."""
    self.indices_set_by_trainables: List[jnp.ndarray] = []
    self.trainable_params: List[Dict[str, jnp.ndarray]] = []
    self.num_trainable_params: int = 0

get_all_parameters(pstate)

Return all parameters (and coupling conductances) needed to simulate.

Runs init_conds() and return every parameter that is needed to solve the ODE. This includes conductances, radiuses, lengths, axial_resistivities, but also coupling conductances.

This is done by first obtaining the current value of every parameter (not only the trainable ones) and then replacing the trainable ones with the value in trainable_params(). This function is run within jx.integrate().

pstate can be obtained by calling params_to_pstate().

params = module.get_parameters() # i.e. [0, 1, 2]
pstate = params_to_pstate(params, module.indices_set_by_trainables)
module.to_jax() # needed for call to module.jaxnodes

Parameters:

Name Type Description Default
pstate List[Dict]

The state of the trainable parameters. pstate takes the form [{“key”: “gNa”, “indices”: jnp.array([0, 1, 2]), “val”: jnp.array([0.1, 0.2, 0.3])}, …].

required

Returns:

Type Description
Dict[str, ndarray]

A dictionary of all module parameters.

Source code in jaxley/modules/base.py
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
def get_all_parameters(self, pstate: List[Dict]) -> Dict[str, jnp.ndarray]:
    """Return all parameters (and coupling conductances) needed to simulate.

    Runs `init_conds()` and return every parameter that is needed to solve the ODE.
    This includes conductances, radiuses, lengths, axial_resistivities, but also
    coupling conductances.

    This is done by first obtaining the current value of every parameter (not only
    the trainable ones) and then replacing the trainable ones with the value
    in `trainable_params()`. This function is run within `jx.integrate()`.

    pstate can be obtained by calling `params_to_pstate()`.
    ```
    params = module.get_parameters() # i.e. [0, 1, 2]
    pstate = params_to_pstate(params, module.indices_set_by_trainables)
    module.to_jax() # needed for call to module.jaxnodes
    ```

    Args:
        pstate: The state of the trainable parameters. pstate takes the form
            [{"key": "gNa", "indices": jnp.array([0, 1, 2]), "val": jnp.array([0.1, 0.2, 0.3])}, ...].

    Returns:
        A dictionary of all module parameters.
    """
    params = {}
    for key in ["radius", "length", "axial_resistivity", "capacitance"]:
        params[key] = self.jaxnodes[key]

    for channel in self.channels:
        for channel_params in channel.channel_params:
            params[channel_params] = self.jaxnodes[channel_params]

    for synapse_params in self.synapse_param_names:
        params[synapse_params] = self.jaxedges[synapse_params]

    # Override with those parameters set by `.make_trainable()`.
    for parameter in pstate:
        key = parameter["key"]
        inds = parameter["indices"]
        set_param = parameter["val"]
        if key in params:  # Only parameters, not initial states.
            # `inds` is of shape `(num_params, num_comps_per_param)`.
            # `set_param` is of shape `(num_params,)`
            # We need to unsqueeze `set_param` to make it `(num_params, 1)` for the
            # `.set()` to work. This is done with `[:, None]`.
            params[key] = params[key].at[inds].set(set_param[:, None])

    # Compute conductance params and append them.
    cond_params = self.init_conds(params)
    for key in cond_params:
        params[key] = cond_params[key]

    return params

get_all_states(pstate, all_params, delta_t)

Get the full initial state of the module from jaxnodes and trainables.

Parameters:

Name Type Description Default
pstate List[Dict]

The state of the trainable parameters.

required
all_params

All parameters of the module.

required
delta_t float

The time step.

required

Returns:

Type Description
Dict[str, ndarray]

A dictionary of all states of the module.

Source code in jaxley/modules/base.py
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
def get_all_states(
    self, pstate: List[Dict], all_params, delta_t: float
) -> Dict[str, jnp.ndarray]:
    """Get the full initial state of the module from jaxnodes and trainables.

    Args:
        pstate: The state of the trainable parameters.
        all_params: All parameters of the module.
        delta_t: The time step.

    Returns:
        A dictionary of all states of the module.
    """
    states = self.get_states_from_nodes_and_edges()

    # Override with the initial states set by `.make_trainable()`.
    for parameter in pstate:
        key = parameter["key"]
        inds = parameter["indices"]
        set_param = parameter["val"]
        if key in states:  # Only initial states, not parameters.
            # `inds` is of shape `(num_params, num_comps_per_param)`.
            # `set_param` is of shape `(num_params,)`
            # We need to unsqueeze `set_param` to make it `(num_params, 1)` for the
            # `.set()` to work. This is done with `[:, None]`.
            states[key] = states[key].at[inds].set(set_param[:, None])

    # Add to the states the initial current through every channel.
    states, _ = self._channel_currents(
        states, delta_t, self.channels, self.nodes, all_params
    )

    # Add to the states the initial current through every synapse.
    states, _ = self._synapse_currents(
        states, self.synapses, all_params, delta_t, self.edges
    )
    return states

get_parameters()

Get all trainable parameters.

The returned parameters should be passed to `jx.integrate(…, params=params).

Returns:

Type Description
List[Dict[str, ndarray]]

A list of all trainable parameters in the form of [{“gNa”: jnp.array([0.1, 0.2, 0.3])}, …].

Source code in jaxley/modules/base.py
474
475
476
477
478
479
480
481
482
483
def get_parameters(self) -> List[Dict[str, jnp.ndarray]]:
    """Get all trainable parameters.

    The returned parameters should be passed to `jx.integrate(..., params=params).

    Returns:
        A list of all trainable parameters in the form of
            [{"gNa": jnp.array([0.1, 0.2, 0.3])}, ...].
    """
    return self.trainable_params

get_states_from_nodes_and_edges()

Return states as they are set in the .nodes and .edges tables.

Source code in jaxley/modules/base.py
540
541
542
543
544
545
546
547
548
549
550
def get_states_from_nodes_and_edges(self):
    """Return states as they are set in the `.nodes` and `.edges` tables."""
    self.to_jax()  # Create `.jaxnodes` from `.nodes` and `.jaxedges` from `.edges`.
    states = {"v": self.jaxnodes["v"]}
    # Join node and edge states into a single state dictionary.
    for channel in self.channels:
        for channel_states in channel.channel_states:
            states[channel_states] = self.jaxnodes[channel_states]
    for synapse_states in self.synapse_state_names:
        states[synapse_states] = self.jaxedges[synapse_states]
    return states

init_conds(params) abstractmethod

Initialize coupling conductances.

Parameters:

Name Type Description Default
params Dict

Conductances and morphology parameters, not yet including coupling conductances.

required
Source code in jaxley/modules/base.py
254
255
256
257
258
259
260
261
262
@abstractmethod
def init_conds(self, params: Dict):
    """Initialize coupling conductances.

    Args:
        params: Conductances and morphology parameters, not yet including
            coupling conductances.
    """
    raise NotImplementedError

init_states(delta_t=0.025)

Initialize all mechanisms in their steady state.

This considers the voltages and parameters of each compartment.

Parameters:

Name Type Description Default
delta_t float

Passed on to channel.init_state().

0.025
Source code in jaxley/modules/base.py
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
def init_states(self, delta_t: float = 0.025):
    """Initialize all mechanisms in their steady state.

    This considers the voltages and parameters of each compartment.

    Args:
        delta_t: Passed on to `channel.init_state()`.
    """
    # Update states of the channels.
    channel_nodes = self.nodes
    states = self.get_states_from_nodes_and_edges()

    # We do not use any `pstate` for initializing. In principle, we could change
    # that by allowing an input `params` and `pstate` to this function.
    params = self.get_all_parameters([])

    for channel in self.channels:
        name = channel._name
        channel_indices = channel_nodes.loc[channel_nodes[name]][
            "comp_index"
        ].to_numpy()
        voltages = channel_nodes.loc[channel_indices, "v"].to_numpy()

        channel_param_names = list(channel.channel_params.keys())
        channel_state_names = list(channel.channel_states.keys())
        channel_states = query_channel_states_and_params(
            states, channel_state_names, channel_indices
        )
        channel_params = query_channel_states_and_params(
            params, channel_param_names, channel_indices
        )

        init_state = channel.init_state(
            channel_states, voltages, channel_params, delta_t
        )

        # `init_state` might not return all channel states. Only the ones that are
        # returned are updated here.
        for key, val in init_state.items():
            # Note that we are overriding `self.nodes` here, but `self.nodes` is
            # not used above to actually compute the current states (so there are
            # no issues with overriding states).
            self.nodes.loc[channel_indices, key] = val

initialize()

Initialize the module.

Source code in jaxley/modules/base.py
595
596
597
598
def initialize(self):
    """Initialize the module."""
    self.init_morph()
    return self

insert(channel)

Insert a channel into the module.

Parameters:

Name Type Description Default
channel Channel

The channel to insert.

required
Source code in jaxley/modules/base.py
840
841
842
843
844
845
def insert(self, channel: Channel):
    """Insert a channel into the module.

    Args:
        channel: The channel to insert."""
    self._insert(channel, self.nodes)

make_trainable(key, init_val=None, verbose=True)

Make a parameter trainable.

If a parameter is made trainable, it will be returned by get_parameters() and should then be passed to jx.integrate(..., params=params).

Parameters:

Name Type Description Default
key str

Name of the parameter to make trainable.

required
init_val Optional[Union[float, list]]

Initial value of the parameter. If float, the same value is used for every created parameter. If list, the length of the list has to match the number of created parameters. If None, the current parameter value is used and if parameter sharing is performed that the current parameter value is averaged over all shared parameters.

None
verbose bool

Whether to print the number of parameters that are added and the total number of parameters.

True
Source code in jaxley/modules/base.py
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
def make_trainable(
    self,
    key: str,
    init_val: Optional[Union[float, list]] = None,
    verbose: bool = True,
):
    """Make a parameter trainable.

    If a parameter is made trainable, it will be returned by `get_parameters()`
    and should then be passed to `jx.integrate(..., params=params)`.

    Args:
        key: Name of the parameter to make trainable.
        init_val: Initial value of the parameter. If `float`, the same value is
            used for every created parameter. If `list`, the length of the list has
            to match the number of created parameters. If `None`, the current
            parameter value is used and if parameter sharing is performed that the
            current parameter value is averaged over all shared parameters.
        verbose: Whether to print the number of parameters that are added and the
            total number of parameters.
    """
    assert (
        key not in self.synapse_param_names and key not in self.synapse_state_names
    ), "Parameters of synapses can only be made trainable via the `SynapseView`."
    view = self.nodes
    view = deepcopy(view.assign(controlled_by_param=0))
    self._make_trainable(view, key, init_val, verbose=verbose)

move(x=0.0, y=0.0, z=0.0, update_nodes=True)

Move cells or networks by adding to their (x, y, z) coordinates.

This function is used only for visualization. It does not affect the simulation.

Parameters:

Name Type Description Default
x float

The amount to move in the x direction in um.

0.0
y float

The amount to move in the y direction in um.

0.0
z float

The amount to move in the z direction in um.

0.0
update_nodes bool

Whether .nodes should be updated or not. Setting this to False largely speeds up moving, especially for big networks, but .nodes or .show will not show the new xyz coordinates.

True
Source code in jaxley/modules/base.py
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
def move(
    self, x: float = 0.0, y: float = 0.0, z: float = 0.0, update_nodes: bool = True
):
    """Move cells or networks by adding to their (x, y, z) coordinates.

    This function is used only for visualization. It does not affect the simulation.

    Args:
        x: The amount to move in the x direction in um.
        y: The amount to move in the y direction in um.
        z: The amount to move in the z direction in um.
        update_nodes: Whether `.nodes` should be updated or not. Setting this to
            `False` largely speeds up moving, especially for big networks, but
            `.nodes` or `.show` will not show the new xyz coordinates.
    """
    self._move(x, y, z, self.nodes, update_nodes)

move_to(x=0.0, y=0.0, z=0.0, update_nodes=True)

Move cells or networks to a location (x, y, z).

If x, y, and z are floats, then the first compartment of the first branch of the first cell is moved to that float coordinate, and everything else is shifted by the difference between that compartment’s previous coordinate and the new float location.

If x, y, and z are arrays, then they must each have a length equal to the number of cells being moved. Then the first compartment of the first branch of each cell is moved to the specified location.

Parameters:

Name Type Description Default
update_nodes bool

Whether .nodes should be updated or not. Setting this to False largely speeds up moving, especially for big networks, but .nodes or .show will not show the new xyz coordinates.

True
Source code in jaxley/modules/base.py
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
def move_to(
    self,
    x: Union[float, np.ndarray] = 0.0,
    y: Union[float, np.ndarray] = 0.0,
    z: Union[float, np.ndarray] = 0.0,
    update_nodes: bool = True,
):
    """Move cells or networks to a location (x, y, z).

    If x, y, and z are floats, then the first compartment of the first branch
    of the first cell is moved to that float coordinate, and everything else is
    shifted by the difference between that compartment's previous coordinate and
    the new float location.

    If x, y, and z are arrays, then they must each have a length equal to the number
    of cells being moved. Then the first compartment of the first branch of each
    cell is moved to the specified location.

    Args:
        update_nodes: Whether `.nodes` should be updated or not. Setting this to
            `False` largely speeds up moving, especially for big networks, but
            `.nodes` or `.show` will not show the new xyz coordinates.
    """
    self._move_to(x, y, z, self.nodes, update_nodes)

record(state='v', verbose=True)

Insert a recording into the compartment.

Parameters:

Name Type Description Default
state str

The name of the state to record.

'v'
verbose bool

Whether to print number of inserted recordings.

True
Source code in jaxley/modules/base.py
712
713
714
715
716
717
718
719
720
721
722
def record(self, state: str = "v", verbose: bool = True):
    """Insert a recording into the compartment.

    Args:
        state: The name of the state to record.
        verbose: Whether to print number of inserted recordings."""
    view = deepcopy(self.nodes)
    view["state"] = state
    recording_view = view[["comp_index", "state"]]
    recording_view = recording_view.rename(columns={"comp_index": "rec_index"})
    self._record(recording_view, verbose=verbose)

rotate(degrees, rotation_axis='xy')

Rotate jaxley modules clockwise. Used only for visualization.

This function is used only for visualization. It does not affect the simulation.

Parameters:

Name Type Description Default
degrees float

How many degrees to rotate the module by.

required
rotation_axis str

Either of {xy | xz | yz}.

'xy'
Source code in jaxley/modules/base.py
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
def rotate(self, degrees: float, rotation_axis: str = "xy"):
    """Rotate jaxley modules clockwise. Used only for visualization.

    This function is used only for visualization. It does not affect the simulation.

    Args:
        degrees: How many degrees to rotate the module by.
        rotation_axis: Either of {`xy` | `xz` | `yz`}.
    """
    self._rotate(degrees=degrees, rotation_axis=rotation_axis, view=self.nodes)

set(key, val)

Set parameter of module (or its view) to a new value.

Note that this function can not be called within jax.jit or jax.grad. Instead, it should be used set the parameters of the module before the simulation. Use .data_set() to set parameters during jax.jit or jax.grad.

Parameters:

Name Type Description Default
key str

The name of the parameter to set.

required
val Union[float, ndarray]

The value to set the parameter to. If it is jnp.ndarray then it must be of shape (len(num_compartments)).

required
Source code in jaxley/modules/base.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
def set(self, key: str, val: Union[float, jnp.ndarray]):
    """Set parameter of module (or its view) to a new value.

    Note that this function can not be called within `jax.jit` or `jax.grad`.
    Instead, it should be used set the parameters of the module **before** the
    simulation. Use `.data_set()` to set parameters during `jax.jit` or
    `jax.grad`.

    Args:
        key: The name of the parameter to set.
        val: The value to set the parameter to. If it is `jnp.ndarray` then it
            must be of shape `(len(num_compartments))`.
    """
    # TODO(@michaeldeistler) should we allow `.set()` for synaptic parameters
    # without using the `SynapseView`, purely for consistency with `make_trainable`?
    view = (
        self.edges
        if key in self.synapse_param_names or key in self.synapse_state_names
        else self.nodes
    )
    self._set(key, val, view, view)

show(param_names=None, *, indices=True, params=True, states=True, channel_names=None)

Print detailed information about the Module or a view of it.

Parameters:

Name Type Description Default
param_names Optional[Union[str, List[str]]]

The names of the parameters to show. If None, all parameters are shown. NOT YET IMPLEMENTED.

None
indices bool

Whether to show the indices of the compartments.

True
params bool

Whether to show the parameters of the compartments.

True
states bool

Whether to show the states of the compartments.

True
channel_names Optional[List[str]]

The names of the channels to show. If None, all channels are shown.

None

Returns:

Type Description
DataFrame

A pd.DataFrame with the requested information.

Source code in jaxley/modules/base.py
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
def show(
    self,
    param_names: Optional[Union[str, List[str]]] = None,  # TODO.
    *,
    indices: bool = True,
    params: bool = True,
    states: bool = True,
    channel_names: Optional[List[str]] = None,
) -> pd.DataFrame:
    """Print detailed information about the Module or a view of it.

    Args:
        param_names: The names of the parameters to show. If `None`, all parameters
            are shown. NOT YET IMPLEMENTED.
        indices: Whether to show the indices of the compartments.
        params: Whether to show the parameters of the compartments.
        states: Whether to show the states of the compartments.
        channel_names: The names of the channels to show. If `None`, all channels are
            shown.

    Returns:
        A `pd.DataFrame` with the requested information.
    """
    return self._show(
        self.nodes, param_names, indices, params, states, channel_names
    )

step(u, delta_t, external_inds, externals, params, solver='bwd_euler', voltage_solver='jaxley.stone')

One step of solving the Ordinary Differential Equation.

This function is called inside of integrate and increments the state of the module by one time step. Calls _step_channels and _step_synapse to update the states of the channels and synapses using fwd_euler.

Parameters:

Name Type Description Default
u Dict[str, ndarray]

The state of the module. voltages = u[“v”]

required
delta_t float

The time step.

required
external_inds Dict[str, ndarray]

The indices of the external inputs.

required
externals Dict[str, ndarray]

The external inputs.

required
params Dict[str, ndarray]

The parameters of the module.

required
solver str

The solver to use for the voltages. Either of [“bwd_euler”, “fwd_euler”, “crank_nicolson”].

'bwd_euler'
voltage_solver str

The tridiagonal solver used to diagonalize the coefficient matrix of the ODE system. Either of [“jaxley.thomas”, “jaxley.stone”].

'jaxley.stone'

Returns:

Type Description
Dict[str, ndarray]

The updated state of the module.

Source code in jaxley/modules/base.py
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
def step(
    self,
    u: Dict[str, jnp.ndarray],
    delta_t: float,
    external_inds: Dict[str, jnp.ndarray],
    externals: Dict[str, jnp.ndarray],
    params: Dict[str, jnp.ndarray],
    solver: str = "bwd_euler",
    voltage_solver: str = "jaxley.stone",
) -> Dict[str, jnp.ndarray]:
    """One step of solving the Ordinary Differential Equation.

    This function is called inside of `integrate` and increments the state of the
    module by one time step. Calls `_step_channels` and `_step_synapse` to update
    the states of the channels and synapses using fwd_euler.

    Args:
        u: The state of the module. voltages = u["v"]
        delta_t: The time step.
        external_inds: The indices of the external inputs.
        externals: The external inputs.
        params: The parameters of the module.
        solver: The solver to use for the voltages. Either of ["bwd_euler",
            "fwd_euler", "crank_nicolson"].
        voltage_solver: The tridiagonal solver used to diagonalize the
            coefficient matrix of the ODE system. Either of ["jaxley.thomas",
            "jaxley.stone"].

    Returns:
        The updated state of the module.
    """

    # Extract the voltages
    voltages = u["v"]

    # Extract the external inputs
    has_current = "i" in externals.keys()
    i_current = externals["i"] if has_current else jnp.asarray([]).astype("float")
    i_inds = external_inds["i"] if has_current else jnp.asarray([]).astype("int32")
    i_ext = self._get_external_input(
        voltages, i_inds, i_current, params["radius"], params["length"]
    )

    # Step of the channels.
    u, (v_terms, const_terms) = self._step_channels(
        u, delta_t, self.channels, self.nodes, params
    )

    # Step of the synapse.
    u, (syn_v_terms, syn_const_terms) = self._step_synapse(
        u,
        self.synapses,
        params,
        delta_t,
        self.edges,
    )

    # Clamp for channels and synapses.
    for key in externals.keys():
        if key not in ["i", "v"]:
            u[key] = u[key].at[external_inds[key]].set(externals[key])

    # Voltage steps.
    cm = params["capacitance"]  # Abbreviation.

    solver_kwargs = {
        "voltages": voltages,
        "voltage_terms": (v_terms + syn_v_terms) / cm,
        "constant_terms": (const_terms + i_ext + syn_const_terms) / cm,
        "coupling_conds_upper": params["branch_uppers"],
        "coupling_conds_lower": params["branch_lowers"],
        "summed_coupling_conds": params["branch_diags"],
        "branchpoint_conds_children": params["branchpoint_conds_children"],
        "branchpoint_conds_parents": params["branchpoint_conds_parents"],
        "branchpoint_weights_children": params["branchpoint_weights_children"],
        "branchpoint_weights_parents": params["branchpoint_weights_parents"],
        "par_inds": self.par_inds,
        "child_inds": self.child_inds,
        "nbranches": self.total_nbranches,
        "solver": voltage_solver,
        "children_in_level": self.children_in_level,
        "parents_in_level": self.parents_in_level,
        "root_inds": self.root_inds,
        "branchpoint_group_inds": self.branchpoint_group_inds,
        "debug_states": self.debug_states,
    }
    if solver == "bwd_euler":
        new_voltages = step_voltage_implicit(**solver_kwargs, delta_t=delta_t)
        u["v"] = new_voltages.ravel(order="C")
    elif solver == "fwd_euler":
        new_voltages = step_voltage_explicit(**solver_kwargs, delta_t=delta_t)
        u["v"] = new_voltages.ravel(order="C")
    elif solver == "crank_nicolson":
        # Crank Nicolson advances by half a step of backward and half a step of
        # forward Euler.
        half_step_delta_t = delta_t / 2
        half_step_voltages = step_voltage_implicit(
            **solver_kwargs, delta_t=half_step_delta_t
        )
        # The forward Euler step in Crank Nicolson can be performed easily as
        # `V_{n+1} = 2 * V_{n+1/2} - V_n`. See also NEURON book Chapter 4.
        u["v"] = 2 * half_step_voltages.ravel(order="C") - voltages
    else:
        raise ValueError(
            f"You specified `solver={solver}`. The only allowed solvers are "
            "['bwd_euler', 'fwd_euler', 'crank_nicolson']."
        )

    # Clamp for voltages.
    if "v" in externals.keys():
        u["v"] = u["v"].at[external_inds["v"]].set(externals["v"])

    return u

stimulate(current=None, verbose=True)

Insert a stimulus into the compartment.

current must be a 1d array or have batch dimension of size (num_compartments, ) or (1, ). If 1d, the same stimulus is added to all compartments.

This function cannot be run during jax.jit and jax.grad. Because of this, it should only be used for static stimuli (i.e., stimuli that do not depend on the data and that should not be learned). For stimuli that depend on data (or that should be learned), please use data_stimulate().

Parameters:

Name Type Description Default
current Optional[ndarray]

Current in nA.

None
Source code in jaxley/modules/base.py
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
def stimulate(self, current: Optional[jnp.ndarray] = None, verbose: bool = True):
    """Insert a stimulus into the compartment.

    current must be a 1d array or have batch dimension of size `(num_compartments, )`
    or `(1, )`. If 1d, the same stimulus is added to all compartments.

    This function cannot be run during `jax.jit` and `jax.grad`. Because of this,
    it should only be used for static stimuli (i.e., stimuli that do not depend
    on the data and that should not be learned). For stimuli that depend on data
    (or that should be learned), please use `data_stimulate()`.

    Args:
        current: Current in `nA`.
    """
    self._external_input("i", current, self.nodes, verbose=verbose)

to_jax()

Move .nodes to .jaxnodes.

Before the actual simulation is run (via jx.integrate), all parameters of the jx.Module are stored in .nodes (a pd.DataFrame). However, for simulation, these parameters have to be moved to be jnp.ndarrays such that they can be processed on GPU/TPU and such that the simulation can be differentiated. .to_jax() copies the .nodes to .jaxnodes.

Source code in jaxley/modules/base.py
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
def to_jax(self):
    """Move `.nodes` to `.jaxnodes`.

    Before the actual simulation is run (via `jx.integrate`), all parameters of
    the `jx.Module` are stored in `.nodes` (a `pd.DataFrame`). However, for
    simulation, these parameters have to be moved to be `jnp.ndarrays` such that
    they can be processed on GPU/TPU and such that the simulation can be
    differentiated. `.to_jax()` copies the `.nodes` to `.jaxnodes`.
    """
    self.jaxnodes = {}
    for key, value in self.nodes.to_dict(orient="list").items():
        inds = jnp.arange(len(value))
        self.jaxnodes[key] = jnp.asarray(value)[inds]

    # `jaxedges` contains only parameters (no indices).
    # `jaxedges` contains only non-Nan elements. This is unlike the channels where
    # we allow parameter sharing.
    self.jaxedges = {}
    edges = self.edges.to_dict(orient="list")
    for i, synapse in enumerate(self.synapses):
        for key in synapse.synapse_params:
            condition = np.asarray(edges["type_ind"]) == i
            self.jaxedges[key] = jnp.asarray(np.asarray(edges[key])[condition])
        for key in synapse.synapse_states:
            self.jaxedges[key] = jnp.asarray(np.asarray(edges[key])[condition])

vis(ax=None, col='k', dims=(0, 1), type='line', morph_plot_kwargs={})

Visualize the module.

Parameters:

Name Type Description Default
ax Optional[Axes]

An axis into which to plot.

None
col str

The color for all branches.

'k'
dims Tuple[int]

Which dimensions to plot. 1=x, 2=y, 3=z coordinate. Must be a tuple of two of them.

(0, 1)
morph_plot_kwargs Dict

Keyword arguments passed to the plotting function.

{}
Source code in jaxley/modules/base.py
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
def vis(
    self,
    ax: Optional[Axes] = None,
    col: str = "k",
    dims: Tuple[int] = (0, 1),
    type: str = "line",
    morph_plot_kwargs: Dict = {},
) -> Axes:
    """Visualize the module.

    Args:
        ax: An axis into which to plot.
        col: The color for all branches.
        dims: Which dimensions to plot. 1=x, 2=y, 3=z coordinate. Must be a tuple of
            two of them.
        morph_plot_kwargs: Keyword arguments passed to the plotting function.
    """
    return self._vis(
        dims=dims,
        col=col,
        ax=ax,
        view=self.nodes,
        type=type,
        morph_plot_kwargs=morph_plot_kwargs,
    )

Compartment

Bases: Module

Compartment class.

This class defines a single compartment that can be simulated by itself or connected up into branches. It is the basic building block of a neuron model.

Source code in jaxley/modules/compartment.py
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
class Compartment(Module):
    """Compartment class.

    This class defines a single compartment that can be simulated by itself or
    connected up into branches. It is the basic building block of a neuron model.
    """

    compartment_params: Dict = {
        "length": 10.0,  # um
        "radius": 1.0,  # um
        "axial_resistivity": 5_000.0,  # ohm cm
        "capacitance": 1.0,  # uF/cm^2
    }
    compartment_states: Dict = {"v": -70.0}

    def __init__(self):
        super().__init__()

        self.nseg = 1
        self.total_nbranches = 1
        self.nbranches_per_cell = [1]
        self.cumsum_nbranches = jnp.asarray([0, 1])

        # Setting up the `nodes` for indexing.
        self.nodes = pd.DataFrame(
            dict(comp_index=[0], branch_index=[0], cell_index=[0])
        )
        self._append_params_and_states(self.compartment_params, self.compartment_states)

        # Synapses.
        self.branch_edges = pd.DataFrame(
            dict(parent_branch_index=[], child_branch_index=[])
        )

        # For morphology indexing.
        self.child_inds = np.asarray([]).astype(int)
        self.child_belongs_to_branchpoint = np.asarray([]).astype(int)
        self.par_inds = np.asarray([]).astype(int)
        self.total_nbranchpoints = 0
        self.branchpoint_group_inds = np.asarray([]).astype(int)

        self.children_in_level = []
        self.parents_in_level = []
        self.root_inds = jnp.asarray([0])

        # Initialize the module.
        self.initialize()
        self.init_syns()
        self.initialized_conds = True

        # Coordinates.
        self.xyzr = [float("NaN") * np.zeros((2, 4))]

    def init_conds(self, params):
        return {
            "branchpoint_conds_children": jnp.asarray([]),
            "branchpoint_conds_parents": jnp.asarray([]),
            "branchpoint_weights_children": jnp.asarray([]),
            "branchpoint_weights_parents": jnp.asarray([]),
            "branch_uppers": jnp.asarray([]),
            "branch_lowers": jnp.asarray([]),
            "branch_diags": jnp.asarray([0.0]),
        }

Branch

Bases: Module

Branch class.

This class defines a single branch that can be simulated by itself or connected to build a cell. A branch is linear segment of several compartments and can be connected to no, one or more other branches at each end to build more intricate cell morphologies.

Source code in jaxley/modules/branch.py
 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
class Branch(Module):
    """Branch class.

    This class defines a single branch that can be simulated by itself or
    connected to build a cell. A branch is linear segment of several compartments
    and can be connected to no, one or more other branches at each end to build more
    intricate cell morphologies.
    """

    branch_params: Dict = {}
    branch_states: Dict = {}

    def __init__(
        self,
        compartments: Optional[Union[Compartment, List[Compartment]]] = None,
        nseg: Optional[int] = None,
    ):
        """
        Args:
            compartments: A single compartment or a list of compartments that make up the
                branch.
            nseg: Number of segments to divide the branch into. If `compartments` is an
                a single compartment, than the compartment is repeated `nseg` times to
                create the branch.
        """
        super().__init__()
        assert (
            isinstance(compartments, (Compartment, List)) or compartments is None
        ), "Only Compartment or List[Compartment] is allowed."
        if isinstance(compartments, Compartment):
            assert (
                nseg is not None
            ), "If `compartments` is not a list then you have to set `nseg`."
        compartments = Compartment() if compartments is None else compartments
        nseg = 1 if nseg is None else nseg

        if isinstance(compartments, Compartment):
            compartment_list = [compartments] * nseg
        else:
            compartment_list = compartments

        self.nseg = len(compartment_list)
        self.total_nbranches = 1
        self.nbranches_per_cell = [1]
        self.cumsum_nbranches = jnp.asarray([0, 1])

        # Indexing.
        self.nodes = pd.concat([c.nodes for c in compartment_list], ignore_index=True)
        self._append_params_and_states(self.branch_params, self.branch_states)
        self.nodes["comp_index"] = np.arange(self.nseg).tolist()
        self.nodes["branch_index"] = [0] * self.nseg
        self.nodes["cell_index"] = [0] * self.nseg

        # Channels.
        self._gather_channels_from_constituents(compartment_list)

        # Synapse indexing.
        self.syn_edges = pd.DataFrame(
            dict(global_pre_comp_index=[], global_post_comp_index=[], type="")
        )
        self.branch_edges = pd.DataFrame(
            dict(parent_branch_index=[], child_branch_index=[])
        )

        # For morphology indexing.
        self.child_inds = np.asarray([]).astype(int)
        self.child_belongs_to_branchpoint = np.asarray([]).astype(int)
        self.par_inds = np.asarray([]).astype(int)
        self.total_nbranchpoints = 0
        self.branchpoint_group_inds = np.asarray([]).astype(int)

        self.children_in_level = []
        self.parents_in_level = []
        self.root_inds = jnp.asarray([0])

        self.initialize()
        self.init_syns()
        self.initialized_conds = False

        # Coordinates.
        self.xyzr = [float("NaN") * np.zeros((2, 4))]

    def __getattr__(self, key: str):
        # Ensure that hidden methods such as `__deepcopy__` still work.
        if key.startswith("__"):
            return super().__getattribute__(key)

        if key in ["comp", "loc"]:
            view = deepcopy(self.nodes)
            view["global_comp_index"] = view["comp_index"]
            view["global_branch_index"] = view["branch_index"]
            view["global_cell_index"] = view["cell_index"]
            compview = CompartmentView(self, view)
            return compview if key == "comp" else compview.loc
        elif key in self.group_nodes:
            inds = self.group_nodes[key].index.values
            view = self.nodes.loc[inds]
            view["global_comp_index"] = view["comp_index"]
            view["global_branch_index"] = view["branch_index"]
            view["global_cell_index"] = view["cell_index"]
            return GroupView(self, view, CompartmentView, ["comp", "loc"])
        else:
            raise KeyError(f"Key {key} not recognized.")

    def init_conds(self, params: Dict) -> Dict[str, jnp.ndarray]:
        conds = self.init_branch_conds(
            params["axial_resistivity"], params["radius"], params["length"], self.nseg
        )
        cond_params = {
            "branchpoint_conds_children": jnp.asarray([]),
            "branchpoint_conds_parents": jnp.asarray([]),
            "branchpoint_weights_children": jnp.asarray([]),
            "branchpoint_weights_parents": jnp.asarray([]),
        }
        cond_params["branch_lowers"] = conds[0]
        cond_params["branch_uppers"] = conds[1]
        cond_params["branch_diags"] = conds[2]

        return cond_params

    @staticmethod
    def init_branch_conds(
        axial_resistivity: jnp.ndarray,
        radiuses: jnp.ndarray,
        lengths: jnp.ndarray,
        nseg: int,
    ) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]:
        """Given an axial resisitivity, set the coupling conductances.

        Args:
            axial_resistivity: Axial resistivity of each compartment.
            radiuses: Radius of each compartment.
            lengths: Length of each compartment.
            nseg: Number of compartments in the branch.

        Returns:
            Tuple of forward coupling conductances, backward coupling conductances, and summed coupling conductances.
        """

        # Compute coupling conductance for segments within a branch.
        # `radius`: um
        # `r_a`: ohm cm
        # `length_single_compartment`: um
        # `coupling_conds`: S * um / cm / um^2 = S / cm / um
        r1 = radiuses[:-1]
        r2 = radiuses[1:]
        r_a1 = axial_resistivity[:-1]
        r_a2 = axial_resistivity[1:]
        l1 = lengths[:-1]
        l2 = lengths[1:]
        coupling_conds_bwd = compute_coupling_cond(r1, r2, r_a1, r_a2, l1, l2)
        coupling_conds_fwd = compute_coupling_cond(r2, r1, r_a2, r_a1, l2, l1)

        # Compute the summed coupling conductances of each compartment.
        summed_coupling_conds = jnp.zeros((nseg))
        summed_coupling_conds = summed_coupling_conds.at[1:].add(coupling_conds_fwd)
        summed_coupling_conds = summed_coupling_conds.at[:-1].add(coupling_conds_bwd)
        return coupling_conds_fwd, coupling_conds_bwd, summed_coupling_conds

    def __len__(self) -> int:
        return self.nseg

__init__(compartments=None, nseg=None)

Parameters:

Name Type Description Default
compartments Optional[Union[Compartment, List[Compartment]]]

A single compartment or a list of compartments that make up the branch.

None
nseg Optional[int]

Number of segments to divide the branch into. If compartments is an a single compartment, than the compartment is repeated nseg times to create the branch.

None
Source code in jaxley/modules/branch.py
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
def __init__(
    self,
    compartments: Optional[Union[Compartment, List[Compartment]]] = None,
    nseg: Optional[int] = None,
):
    """
    Args:
        compartments: A single compartment or a list of compartments that make up the
            branch.
        nseg: Number of segments to divide the branch into. If `compartments` is an
            a single compartment, than the compartment is repeated `nseg` times to
            create the branch.
    """
    super().__init__()
    assert (
        isinstance(compartments, (Compartment, List)) or compartments is None
    ), "Only Compartment or List[Compartment] is allowed."
    if isinstance(compartments, Compartment):
        assert (
            nseg is not None
        ), "If `compartments` is not a list then you have to set `nseg`."
    compartments = Compartment() if compartments is None else compartments
    nseg = 1 if nseg is None else nseg

    if isinstance(compartments, Compartment):
        compartment_list = [compartments] * nseg
    else:
        compartment_list = compartments

    self.nseg = len(compartment_list)
    self.total_nbranches = 1
    self.nbranches_per_cell = [1]
    self.cumsum_nbranches = jnp.asarray([0, 1])

    # Indexing.
    self.nodes = pd.concat([c.nodes for c in compartment_list], ignore_index=True)
    self._append_params_and_states(self.branch_params, self.branch_states)
    self.nodes["comp_index"] = np.arange(self.nseg).tolist()
    self.nodes["branch_index"] = [0] * self.nseg
    self.nodes["cell_index"] = [0] * self.nseg

    # Channels.
    self._gather_channels_from_constituents(compartment_list)

    # Synapse indexing.
    self.syn_edges = pd.DataFrame(
        dict(global_pre_comp_index=[], global_post_comp_index=[], type="")
    )
    self.branch_edges = pd.DataFrame(
        dict(parent_branch_index=[], child_branch_index=[])
    )

    # For morphology indexing.
    self.child_inds = np.asarray([]).astype(int)
    self.child_belongs_to_branchpoint = np.asarray([]).astype(int)
    self.par_inds = np.asarray([]).astype(int)
    self.total_nbranchpoints = 0
    self.branchpoint_group_inds = np.asarray([]).astype(int)

    self.children_in_level = []
    self.parents_in_level = []
    self.root_inds = jnp.asarray([0])

    self.initialize()
    self.init_syns()
    self.initialized_conds = False

    # Coordinates.
    self.xyzr = [float("NaN") * np.zeros((2, 4))]

init_branch_conds(axial_resistivity, radiuses, lengths, nseg) staticmethod

Given an axial resisitivity, set the coupling conductances.

Parameters:

Name Type Description Default
axial_resistivity ndarray

Axial resistivity of each compartment.

required
radiuses ndarray

Radius of each compartment.

required
lengths ndarray

Length of each compartment.

required
nseg int

Number of compartments in the branch.

required

Returns:

Type Description
Tuple[ndarray, ndarray, ndarray]

Tuple of forward coupling conductances, backward coupling conductances, and summed coupling conductances.

Source code in jaxley/modules/branch.py
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
@staticmethod
def init_branch_conds(
    axial_resistivity: jnp.ndarray,
    radiuses: jnp.ndarray,
    lengths: jnp.ndarray,
    nseg: int,
) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]:
    """Given an axial resisitivity, set the coupling conductances.

    Args:
        axial_resistivity: Axial resistivity of each compartment.
        radiuses: Radius of each compartment.
        lengths: Length of each compartment.
        nseg: Number of compartments in the branch.

    Returns:
        Tuple of forward coupling conductances, backward coupling conductances, and summed coupling conductances.
    """

    # Compute coupling conductance for segments within a branch.
    # `radius`: um
    # `r_a`: ohm cm
    # `length_single_compartment`: um
    # `coupling_conds`: S * um / cm / um^2 = S / cm / um
    r1 = radiuses[:-1]
    r2 = radiuses[1:]
    r_a1 = axial_resistivity[:-1]
    r_a2 = axial_resistivity[1:]
    l1 = lengths[:-1]
    l2 = lengths[1:]
    coupling_conds_bwd = compute_coupling_cond(r1, r2, r_a1, r_a2, l1, l2)
    coupling_conds_fwd = compute_coupling_cond(r2, r1, r_a2, r_a1, l2, l1)

    # Compute the summed coupling conductances of each compartment.
    summed_coupling_conds = jnp.zeros((nseg))
    summed_coupling_conds = summed_coupling_conds.at[1:].add(coupling_conds_fwd)
    summed_coupling_conds = summed_coupling_conds.at[:-1].add(coupling_conds_bwd)
    return coupling_conds_fwd, coupling_conds_bwd, summed_coupling_conds

Cell

Bases: Module

Cell class.

This class defines a single cell that can be simulated by itself or connected with synapses to build a network. A cell is made up of several branches and supports intricate cell morphologies.

Source code in jaxley/modules/cell.py
 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
class Cell(Module):
    """Cell class.

    This class defines a single cell that can be simulated by itself or
    connected with synapses to build a network. A cell is made up of several branches
    and supports intricate cell morphologies.
    """

    cell_params: Dict = {}
    cell_states: Dict = {}

    def __init__(
        self,
        branches: Optional[Union[Branch, List[Branch]]] = None,
        parents: Optional[List[int]] = None,
        xyzr: Optional[List[np.ndarray]] = None,
    ):
        """Initialize a cell.

        Args:
            branches: A single branch or a list of branches that make up the cell.
                If a single branch is provided, then the branch is repeated `len(parents)`
                times to create the cell.
            parents: The parent branch index for each branch. The first branch has no
                parent and is therefore set to -1.
            xyzr: For every branch, the x, y, and z coordinates and the radius at the
                traced coordinates. Note that this is the full tracing (from SWC), not
                the stick representation coordinates.
        """
        super().__init__()
        assert (
            isinstance(branches, (Branch, List)) or branches is None
        ), "Only Branch or List[Branch] is allowed."
        if branches is not None:
            assert (
                parents is not None
            ), "If `branches` is not a list then you have to set `parents`."
        if isinstance(branches, List):
            assert len(parents) == len(
                branches
            ), "Ensure equally many parents, i.e. len(branches) == len(parents)."

        branches = Branch() if branches is None else branches
        parents = [-1] if parents is None else parents

        if isinstance(branches, Branch):
            branch_list = [branches for _ in range(len(parents))]
        else:
            branch_list = branches

        if xyzr is not None:
            assert len(xyzr) == len(parents)
            self.xyzr = xyzr
        else:
            # For every branch (`len(parents)`), we have a start and end point (`2`) and
            # a (x,y,z,r) coordinate for each of them (`4`).
            # Since `xyzr` is only inspected at `.vis()` and because it depends on the
            # (potentially learned) length of every compartment, we only populate
            # self.xyzr at `.vis()`.
            self.xyzr = [float("NaN") * np.zeros((2, 4)) for _ in range(len(parents))]

        self.nseg = branch_list[0].nseg
        self.total_nbranches = len(branch_list)
        self.nbranches_per_cell = [len(branch_list)]
        self.comb_parents = jnp.asarray(parents)
        self.comb_children = compute_children_indices(self.comb_parents)
        self.cumsum_nbranches = jnp.asarray([0, len(branch_list)])

        # Indexing.
        self.nodes = pd.concat([c.nodes for c in branch_list], ignore_index=True)
        self._append_params_and_states(self.cell_params, self.cell_states)
        self.nodes["comp_index"] = np.arange(self.nseg * self.total_nbranches).tolist()
        self.nodes["branch_index"] = (
            np.arange(self.nseg * self.total_nbranches) // self.nseg
        ).tolist()
        self.nodes["cell_index"] = [0] * (self.nseg * self.total_nbranches)

        # Channels.
        self._gather_channels_from_constituents(branch_list)

        # Synapse indexing.
        self.syn_edges = pd.DataFrame(
            dict(global_pre_comp_index=[], global_post_comp_index=[], type="")
        )
        self.branch_edges = pd.DataFrame(
            dict(
                parent_branch_index=self.comb_parents[1:],
                child_branch_index=np.arange(1, self.total_nbranches),
            )
        )

        # For morphology indexing.
        par_inds = self.branch_edges["parent_branch_index"].to_numpy()
        self.child_inds = self.branch_edges["child_branch_index"].to_numpy()
        self.child_belongs_to_branchpoint = remap_to_consecutive(par_inds)

        # TODO: does order have to be preserved?
        self.par_inds = np.unique(par_inds)
        self.total_nbranchpoints = len(self.par_inds)
        self.root_inds = jnp.asarray([0])

        self.initialize()

        self.init_syns()
        self.initialized_conds = False

    def __getattr__(self, key: str):
        # Ensure that hidden methods such as `__deepcopy__` still work.
        if key.startswith("__"):
            return super().__getattribute__(key)

        if key == "branch":
            view = deepcopy(self.nodes)
            view["global_comp_index"] = view["comp_index"]
            view["global_branch_index"] = view["branch_index"]
            view["global_cell_index"] = view["cell_index"]
            return BranchView(self, view)
        elif key in self.group_nodes:
            inds = self.group_nodes[key].index.values
            view = self.nodes.loc[inds]
            view["global_comp_index"] = view["comp_index"]
            view["global_branch_index"] = view["branch_index"]
            view["global_cell_index"] = view["cell_index"]
            return GroupView(self, view, BranchView, ["branch"])
        else:
            raise KeyError(f"Key {key} not recognized.")

    def init_morph(self):
        """Initialize morphology."""

        # For Jaxley custom implementation.
        children_and_parents = compute_morphology_indices_in_levels(
            len(self.par_inds),
            self.child_belongs_to_branchpoint,
            self.par_inds,
            self.child_inds,
        )
        self.branchpoint_group_inds = build_branchpoint_group_inds(
            len(self.par_inds),
            self.child_belongs_to_branchpoint,
            self.nseg,
            self.total_nbranches,
        )
        parents = self.comb_parents
        children_inds = children_and_parents["children"]
        parents_inds = children_and_parents["parents"]

        levels = compute_levels(parents)
        self.children_in_level = compute_children_in_level(levels, children_inds)
        self.parents_in_level = compute_parents_in_level(
            levels, self.par_inds, parents_inds
        )

        self.initialized_morph = True

    def init_conds(self, params: Dict) -> Dict[str, jnp.ndarray]:
        """Given an axial resisitivity, set the coupling conductances."""
        nbranches = self.total_nbranches
        nseg = self.nseg

        axial_resistivity = jnp.reshape(params["axial_resistivity"], (nbranches, nseg))
        radiuses = jnp.reshape(params["radius"], (nbranches, nseg))
        lengths = jnp.reshape(params["length"], (nbranches, nseg))

        conds = vmap(Branch.init_branch_conds, in_axes=(0, 0, 0, None))(
            axial_resistivity, radiuses, lengths, self.nseg
        )
        coupling_conds_fwd = conds[0]
        coupling_conds_bwd = conds[1]
        summed_coupling_conds = conds[2]

        # The conductance from the children to the branch point.
        branchpoint_conds_children = vmap(
            compute_coupling_cond_branchpoint, in_axes=(0, 0, 0)
        )(
            radiuses[self.child_inds, 0],
            axial_resistivity[self.child_inds, 0],
            lengths[self.child_inds, 0],
        )
        # The conductance from the parents to the branch point.
        branchpoint_conds_parents = vmap(
            compute_coupling_cond_branchpoint, in_axes=(0, 0, 0)
        )(
            radiuses[self.par_inds, -1],
            axial_resistivity[self.par_inds, -1],
            lengths[self.par_inds, -1],
        )

        # Weights with which the compartments influence their nearby node.
        # The impact of the children on the branch point.
        branchpoint_weights_children = vmap(compute_impact_on_node, in_axes=(0, 0, 0))(
            radiuses[self.child_inds, 0],
            axial_resistivity[self.child_inds, 0],
            lengths[self.child_inds, 0],
        )
        # The impact of parents on the branch point.
        branchpoint_weights_parents = vmap(compute_impact_on_node, in_axes=(0, 0, 0))(
            radiuses[self.par_inds, -1],
            axial_resistivity[self.par_inds, -1],
            lengths[self.par_inds, -1],
        )

        summed_coupling_conds = self.update_summed_coupling_conds(
            summed_coupling_conds,
            self.child_inds,
            self.par_inds,
            branchpoint_conds_children,
            branchpoint_conds_parents,
        )

        cond_params = {
            "branch_uppers": coupling_conds_bwd,
            "branch_lowers": coupling_conds_fwd,
            "branch_diags": summed_coupling_conds,
            "branchpoint_conds_children": branchpoint_conds_children,
            "branchpoint_conds_parents": branchpoint_conds_parents,
            "branchpoint_weights_children": branchpoint_weights_children,
            "branchpoint_weights_parents": branchpoint_weights_parents,
        }
        return cond_params

    @staticmethod
    def update_summed_coupling_conds(
        summed_conds,
        child_inds,
        par_inds,
        branchpoint_conds_children,
        branchpoint_conds_parents,
    ):
        """Perform updates on the diagonal based on conductances of the branchpoints.

        Args:
            summed_conds: shape [num_branches, nseg]
            child_inds: shape [num_branches - 1]
            conds_fwd: shape [num_branches - 1]
            conds_bwd: shape [num_branches - 1]
            parents: shape [num_branches]

        Returns:
            Updated `summed_coupling_conds`.
        """
        summed_conds = summed_conds.at[child_inds, 0].add(branchpoint_conds_children)
        summed_conds = summed_conds.at[par_inds, -1].add(branchpoint_conds_parents)
        return summed_conds

__init__(branches=None, parents=None, xyzr=None)

Initialize a cell.

Parameters:

Name Type Description Default
branches Optional[Union[Branch, List[Branch]]]

A single branch or a list of branches that make up the cell. If a single branch is provided, then the branch is repeated len(parents) times to create the cell.

None
parents Optional[List[int]]

The parent branch index for each branch. The first branch has no parent and is therefore set to -1.

None
xyzr Optional[List[ndarray]]

For every branch, the x, y, and z coordinates and the radius at the traced coordinates. Note that this is the full tracing (from SWC), not the stick representation coordinates.

None
Source code in jaxley/modules/cell.py
 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
def __init__(
    self,
    branches: Optional[Union[Branch, List[Branch]]] = None,
    parents: Optional[List[int]] = None,
    xyzr: Optional[List[np.ndarray]] = None,
):
    """Initialize a cell.

    Args:
        branches: A single branch or a list of branches that make up the cell.
            If a single branch is provided, then the branch is repeated `len(parents)`
            times to create the cell.
        parents: The parent branch index for each branch. The first branch has no
            parent and is therefore set to -1.
        xyzr: For every branch, the x, y, and z coordinates and the radius at the
            traced coordinates. Note that this is the full tracing (from SWC), not
            the stick representation coordinates.
    """
    super().__init__()
    assert (
        isinstance(branches, (Branch, List)) or branches is None
    ), "Only Branch or List[Branch] is allowed."
    if branches is not None:
        assert (
            parents is not None
        ), "If `branches` is not a list then you have to set `parents`."
    if isinstance(branches, List):
        assert len(parents) == len(
            branches
        ), "Ensure equally many parents, i.e. len(branches) == len(parents)."

    branches = Branch() if branches is None else branches
    parents = [-1] if parents is None else parents

    if isinstance(branches, Branch):
        branch_list = [branches for _ in range(len(parents))]
    else:
        branch_list = branches

    if xyzr is not None:
        assert len(xyzr) == len(parents)
        self.xyzr = xyzr
    else:
        # For every branch (`len(parents)`), we have a start and end point (`2`) and
        # a (x,y,z,r) coordinate for each of them (`4`).
        # Since `xyzr` is only inspected at `.vis()` and because it depends on the
        # (potentially learned) length of every compartment, we only populate
        # self.xyzr at `.vis()`.
        self.xyzr = [float("NaN") * np.zeros((2, 4)) for _ in range(len(parents))]

    self.nseg = branch_list[0].nseg
    self.total_nbranches = len(branch_list)
    self.nbranches_per_cell = [len(branch_list)]
    self.comb_parents = jnp.asarray(parents)
    self.comb_children = compute_children_indices(self.comb_parents)
    self.cumsum_nbranches = jnp.asarray([0, len(branch_list)])

    # Indexing.
    self.nodes = pd.concat([c.nodes for c in branch_list], ignore_index=True)
    self._append_params_and_states(self.cell_params, self.cell_states)
    self.nodes["comp_index"] = np.arange(self.nseg * self.total_nbranches).tolist()
    self.nodes["branch_index"] = (
        np.arange(self.nseg * self.total_nbranches) // self.nseg
    ).tolist()
    self.nodes["cell_index"] = [0] * (self.nseg * self.total_nbranches)

    # Channels.
    self._gather_channels_from_constituents(branch_list)

    # Synapse indexing.
    self.syn_edges = pd.DataFrame(
        dict(global_pre_comp_index=[], global_post_comp_index=[], type="")
    )
    self.branch_edges = pd.DataFrame(
        dict(
            parent_branch_index=self.comb_parents[1:],
            child_branch_index=np.arange(1, self.total_nbranches),
        )
    )

    # For morphology indexing.
    par_inds = self.branch_edges["parent_branch_index"].to_numpy()
    self.child_inds = self.branch_edges["child_branch_index"].to_numpy()
    self.child_belongs_to_branchpoint = remap_to_consecutive(par_inds)

    # TODO: does order have to be preserved?
    self.par_inds = np.unique(par_inds)
    self.total_nbranchpoints = len(self.par_inds)
    self.root_inds = jnp.asarray([0])

    self.initialize()

    self.init_syns()
    self.initialized_conds = False

init_conds(params)

Given an axial resisitivity, set the coupling conductances.

Source code in jaxley/modules/cell.py
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
def init_conds(self, params: Dict) -> Dict[str, jnp.ndarray]:
    """Given an axial resisitivity, set the coupling conductances."""
    nbranches = self.total_nbranches
    nseg = self.nseg

    axial_resistivity = jnp.reshape(params["axial_resistivity"], (nbranches, nseg))
    radiuses = jnp.reshape(params["radius"], (nbranches, nseg))
    lengths = jnp.reshape(params["length"], (nbranches, nseg))

    conds = vmap(Branch.init_branch_conds, in_axes=(0, 0, 0, None))(
        axial_resistivity, radiuses, lengths, self.nseg
    )
    coupling_conds_fwd = conds[0]
    coupling_conds_bwd = conds[1]
    summed_coupling_conds = conds[2]

    # The conductance from the children to the branch point.
    branchpoint_conds_children = vmap(
        compute_coupling_cond_branchpoint, in_axes=(0, 0, 0)
    )(
        radiuses[self.child_inds, 0],
        axial_resistivity[self.child_inds, 0],
        lengths[self.child_inds, 0],
    )
    # The conductance from the parents to the branch point.
    branchpoint_conds_parents = vmap(
        compute_coupling_cond_branchpoint, in_axes=(0, 0, 0)
    )(
        radiuses[self.par_inds, -1],
        axial_resistivity[self.par_inds, -1],
        lengths[self.par_inds, -1],
    )

    # Weights with which the compartments influence their nearby node.
    # The impact of the children on the branch point.
    branchpoint_weights_children = vmap(compute_impact_on_node, in_axes=(0, 0, 0))(
        radiuses[self.child_inds, 0],
        axial_resistivity[self.child_inds, 0],
        lengths[self.child_inds, 0],
    )
    # The impact of parents on the branch point.
    branchpoint_weights_parents = vmap(compute_impact_on_node, in_axes=(0, 0, 0))(
        radiuses[self.par_inds, -1],
        axial_resistivity[self.par_inds, -1],
        lengths[self.par_inds, -1],
    )

    summed_coupling_conds = self.update_summed_coupling_conds(
        summed_coupling_conds,
        self.child_inds,
        self.par_inds,
        branchpoint_conds_children,
        branchpoint_conds_parents,
    )

    cond_params = {
        "branch_uppers": coupling_conds_bwd,
        "branch_lowers": coupling_conds_fwd,
        "branch_diags": summed_coupling_conds,
        "branchpoint_conds_children": branchpoint_conds_children,
        "branchpoint_conds_parents": branchpoint_conds_parents,
        "branchpoint_weights_children": branchpoint_weights_children,
        "branchpoint_weights_parents": branchpoint_weights_parents,
    }
    return cond_params

init_morph()

Initialize morphology.

Source code in jaxley/modules/cell.py
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
def init_morph(self):
    """Initialize morphology."""

    # For Jaxley custom implementation.
    children_and_parents = compute_morphology_indices_in_levels(
        len(self.par_inds),
        self.child_belongs_to_branchpoint,
        self.par_inds,
        self.child_inds,
    )
    self.branchpoint_group_inds = build_branchpoint_group_inds(
        len(self.par_inds),
        self.child_belongs_to_branchpoint,
        self.nseg,
        self.total_nbranches,
    )
    parents = self.comb_parents
    children_inds = children_and_parents["children"]
    parents_inds = children_and_parents["parents"]

    levels = compute_levels(parents)
    self.children_in_level = compute_children_in_level(levels, children_inds)
    self.parents_in_level = compute_parents_in_level(
        levels, self.par_inds, parents_inds
    )

    self.initialized_morph = True

update_summed_coupling_conds(summed_conds, child_inds, par_inds, branchpoint_conds_children, branchpoint_conds_parents) staticmethod

Perform updates on the diagonal based on conductances of the branchpoints.

Parameters:

Name Type Description Default
summed_conds

shape [num_branches, nseg]

required
child_inds

shape [num_branches - 1]

required
conds_fwd

shape [num_branches - 1]

required
conds_bwd

shape [num_branches - 1]

required
parents

shape [num_branches]

required

Returns:

Type Description

Updated summed_coupling_conds.

Source code in jaxley/modules/cell.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
@staticmethod
def update_summed_coupling_conds(
    summed_conds,
    child_inds,
    par_inds,
    branchpoint_conds_children,
    branchpoint_conds_parents,
):
    """Perform updates on the diagonal based on conductances of the branchpoints.

    Args:
        summed_conds: shape [num_branches, nseg]
        child_inds: shape [num_branches - 1]
        conds_fwd: shape [num_branches - 1]
        conds_bwd: shape [num_branches - 1]
        parents: shape [num_branches]

    Returns:
        Updated `summed_coupling_conds`.
    """
    summed_conds = summed_conds.at[child_inds, 0].add(branchpoint_conds_children)
    summed_conds = summed_conds.at[par_inds, -1].add(branchpoint_conds_parents)
    return summed_conds

Network

Bases: Module

Network class.

This class defines a network of cells that can be connected with synapses.

Source code in jaxley/modules/network.py
 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
class Network(Module):
    """Network class.

    This class defines a network of cells that can be connected with synapses.
    """

    network_params: Dict = {}
    network_states: Dict = {}

    def __init__(
        self,
        cells: List[Cell],
    ):
        """Initialize network of cells and synapses.

        Args:
            cells: A list of cells that make up the network.
        """
        super().__init__()
        for cell in cells:
            self.xyzr += deepcopy(cell.xyzr)

        self.cells = cells
        self.nseg = cells[0].nseg
        self._append_params_and_states(self.network_params, self.network_states)

        self.nbranches_per_cell = [cell.total_nbranches for cell in self.cells]
        self.nbranchpoints_per_cell = [cell.total_nbranchpoints for cell in self.cells]
        self.total_nbranches = sum(self.nbranches_per_cell)
        self.cumsum_nbranches = jnp.cumsum(jnp.asarray([0] + self.nbranches_per_cell))
        self.cumsum_nbranchpoints = jnp.cumsum(
            jnp.asarray([0] + self.nbranchpoints_per_cell)
        )

        self.nodes = pd.concat([c.nodes for c in cells], ignore_index=True)
        self.nodes["comp_index"] = np.arange(self.nseg * self.total_nbranches).tolist()
        self.nodes["branch_index"] = (
            np.arange(self.nseg * self.total_nbranches) // self.nseg
        ).tolist()
        self.nodes["cell_index"] = list(
            itertools.chain(
                *[[i] * (self.nseg * b) for i, b in enumerate(self.nbranches_per_cell)]
            )
        )

        parents = [cell.comb_parents for cell in self.cells]
        self.comb_parents = jnp.concatenate(
            [p.at[1:].add(self.cumsum_nbranches[i]) for i, p in enumerate(parents)]
        )

        # Two columns: `parent_branch_index` and `child_branch_index`. One row per
        # branch, apart from those branches which do not have a parent (i.e.
        # -1 in parents). For every branch, tracks the global index of that branch
        # (`child_branch_index`) and the global index of its parent
        # (`parent_branch_index`).
        self.branch_edges = pd.DataFrame(
            dict(
                parent_branch_index=self.comb_parents[self.comb_parents != -1],
                child_branch_index=np.where(self.comb_parents != -1)[0],
            )
        )

        # For morphology indexing.
        par_inds = self.branch_edges["parent_branch_index"].to_numpy()
        self.child_inds = self.branch_edges["child_branch_index"].to_numpy()
        self.child_belongs_to_branchpoint = remap_to_consecutive(par_inds)
        self.par_inds = np.unique(par_inds)  # TODO: does order have to be preserved?
        self.total_nbranchpoints = len(self.par_inds)
        self.root_inds = self.cumsum_nbranches[:-1]

        # Channels.
        self._gather_channels_from_constituents(cells)

        self.initialize()
        self.init_syns()
        self.initialized_conds = False

    def __getattr__(self, key: str):
        # Ensure that hidden methods such as `__deepcopy__` still work.
        if key.startswith("__"):
            return super().__getattribute__(key)

        if key == "cell":
            view = deepcopy(self.nodes)
            view["global_comp_index"] = view["comp_index"]
            view["global_branch_index"] = view["branch_index"]
            view["global_cell_index"] = view["cell_index"]
            return CellView(self, view)
        elif key in self.synapse_names:
            type_index = self.synapse_names.index(key)
            return SynapseView(self, self.edges, key, self.synapses[type_index])
        elif key in self.group_nodes:
            inds = self.group_nodes[key].index.values
            view = self.nodes.loc[inds]
            view["global_comp_index"] = view["comp_index"]
            view["global_branch_index"] = view["branch_index"]
            view["global_cell_index"] = view["cell_index"]
            return GroupView(self, view, CellView, ["cell"])
        else:
            raise KeyError(f"Key {key} not recognized.")

    def init_morph(self):
        self.branchpoint_group_inds = build_branchpoint_group_inds(
            len(self.par_inds),
            self.child_belongs_to_branchpoint,
            self.nseg,
            self.total_nbranches,
        )
        self.children_in_level = merge_cells(
            self.cumsum_nbranches,
            self.cumsum_nbranchpoints,
            [cell.children_in_level for cell in self.cells],
            exclude_first=False,
        )
        self.parents_in_level = merge_cells(
            self.cumsum_nbranches,
            self.cumsum_nbranchpoints,
            [cell.parents_in_level for cell in self.cells],
            exclude_first=False,
        )
        self.initialized_morph = True

    def init_conds(self, params: Dict) -> Dict[str, jnp.ndarray]:
        """Given an axial resisitivity, set the coupling conductances."""
        nbranches = self.total_nbranches
        nseg = self.nseg
        parents = self.comb_parents

        axial_resistivity = jnp.reshape(params["axial_resistivity"], (nbranches, nseg))
        radiuses = jnp.reshape(params["radius"], (nbranches, nseg))
        lengths = jnp.reshape(params["length"], (nbranches, nseg))

        conds = vmap(Branch.init_branch_conds, in_axes=(0, 0, 0, None))(
            axial_resistivity, radiuses, lengths, self.nseg
        )
        coupling_conds_fwd = conds[0]
        coupling_conds_bwd = conds[1]
        summed_coupling_conds = conds[2]

        # The conductance from the children to the branch point.
        branchpoint_conds_children = vmap(
            compute_coupling_cond_branchpoint, in_axes=(0, 0, 0)
        )(
            radiuses[self.child_inds, 0],
            axial_resistivity[self.child_inds, 0],
            lengths[self.child_inds, 0],
        )
        # The conductance from the parents to the branch point.
        branchpoint_conds_parents = vmap(
            compute_coupling_cond_branchpoint, in_axes=(0, 0, 0)
        )(
            radiuses[self.par_inds, -1],
            axial_resistivity[self.par_inds, -1],
            lengths[self.par_inds, -1],
        )

        # Weights with which the compartments influence their nearby node.
        # The impact of the children on the branch point.
        branchpoint_weights_children = vmap(compute_impact_on_node, in_axes=(0, 0, 0))(
            radiuses[self.child_inds, 0],
            axial_resistivity[self.child_inds, 0],
            lengths[self.child_inds, 0],
        )
        # The impact of parents on the branch point.
        branchpoint_weights_parents = vmap(compute_impact_on_node, in_axes=(0, 0, 0))(
            radiuses[self.par_inds, -1],
            axial_resistivity[self.par_inds, -1],
            lengths[self.par_inds, -1],
        )

        summed_coupling_conds = Cell.update_summed_coupling_conds(
            summed_coupling_conds,
            self.child_inds,
            self.par_inds,
            branchpoint_conds_children,
            branchpoint_conds_parents,
        )

        cond_params = {
            "branch_uppers": coupling_conds_bwd,
            "branch_lowers": coupling_conds_fwd,
            "branch_diags": summed_coupling_conds,
            "branchpoint_conds_children": branchpoint_conds_children,
            "branchpoint_conds_parents": branchpoint_conds_parents,
            "branchpoint_weights_children": branchpoint_weights_children,
            "branchpoint_weights_parents": branchpoint_weights_parents,
        }
        return cond_params

    def init_syns(self):
        """Initialize synapses."""
        self.synapses = []

        # TODO(@michaeldeistler): should we also track this for channels?
        self.synapse_names = []
        self.synapse_param_names = []
        self.synapse_state_names = []

        self.initialized_syns = True

    def _step_synapse(
        self,
        states: Dict,
        syn_channels: List,
        params: Dict,
        delta_t: float,
        edges: pd.DataFrame,
    ) -> Tuple[Dict, Tuple[jnp.ndarray, jnp.ndarray]]:
        """Perform one step of the synapses and obtain their currents."""
        states = self._step_synapse_state(states, syn_channels, params, delta_t, edges)
        states, current_terms = self._synapse_currents(
            states, syn_channels, params, delta_t, edges
        )
        return states, current_terms

    def _step_synapse_state(
        self,
        states: Dict,
        syn_channels: List,
        params: Dict,
        delta_t: float,
        edges: pd.DataFrame,
    ) -> Dict:
        voltages = states["v"]

        grouped_syns = edges.groupby("type", sort=False, group_keys=False)
        pre_syn_inds = grouped_syns["global_pre_comp_index"].apply(list)
        post_syn_inds = grouped_syns["global_post_comp_index"].apply(list)
        synapse_names = list(grouped_syns.indices.keys())

        for i, synapse_type in enumerate(syn_channels):
            assert (
                synapse_names[i] == synapse_type._name
            ), "Mixup in the ordering of synapses. Please create an issue on Github."
            synapse_param_names = list(synapse_type.synapse_params.keys())
            synapse_state_names = list(synapse_type.synapse_states.keys())

            synapse_params = {}
            for p in synapse_param_names:
                synapse_params[p] = params[p]
            synapse_states = {}
            for s in synapse_state_names:
                synapse_states[s] = states[s]

            pre_inds = np.asarray(pre_syn_inds[synapse_names[i]])
            post_inds = np.asarray(post_syn_inds[synapse_names[i]])

            # State updates.
            states_updated = synapse_type.update_states(
                synapse_states,
                delta_t,
                voltages[pre_inds],
                voltages[post_inds],
                synapse_params,
            )

            # Rebuild state.
            for key, val in states_updated.items():
                states[key] = val

        return states

    def _synapse_currents(
        self,
        states: Dict,
        syn_channels: List,
        params: Dict,
        delta_t: float,
        edges: pd.DataFrame,
    ) -> Tuple[Dict, Tuple[jnp.ndarray, jnp.ndarray]]:
        voltages = states["v"]

        grouped_syns = edges.groupby("type", sort=False, group_keys=False)
        pre_syn_inds = grouped_syns["global_pre_comp_index"].apply(list)
        post_syn_inds = grouped_syns["global_post_comp_index"].apply(list)
        synapse_names = list(grouped_syns.indices.keys())

        syn_voltage_terms = jnp.zeros_like(voltages)
        syn_constant_terms = jnp.zeros_like(voltages)
        # Run with two different voltages that are `diff` apart to infer the slope and
        # offset.
        diff = 1e-3
        for i, synapse_type in enumerate(syn_channels):
            assert (
                synapse_names[i] == synapse_type._name
            ), "Mixup in the ordering of synapses. Please create an issue on Github."
            synapse_param_names = list(synapse_type.synapse_params.keys())
            synapse_state_names = list(synapse_type.synapse_states.keys())

            synapse_params = {}
            for p in synapse_param_names:
                synapse_params[p] = params[p]
            synapse_states = {}
            for s in synapse_state_names:
                synapse_states[s] = states[s]

            # Get pre and post indexes of the current synapse type.
            pre_inds = np.asarray(pre_syn_inds[synapse_names[i]])
            post_inds = np.asarray(post_syn_inds[synapse_names[i]])

            # Compute slope and offset of the current through every synapse.
            pre_v_and_perturbed = jnp.stack(
                [voltages[pre_inds], voltages[pre_inds] + diff]
            )
            post_v_and_perturbed = jnp.stack(
                [voltages[post_inds], voltages[post_inds] + diff]
            )
            synapse_currents = vmap(
                synapse_type.compute_current, in_axes=(None, 0, 0, None)
            )(
                synapse_states,
                pre_v_and_perturbed,
                post_v_and_perturbed,
                synapse_params,
            )
            synapse_currents_dist = convert_point_process_to_distributed(
                synapse_currents,
                params["radius"][post_inds],
                params["length"][post_inds],
            )

            # Split into voltage and constant terms.
            voltage_term = (synapse_currents_dist[1] - synapse_currents_dist[0]) / diff
            constant_term = (
                synapse_currents_dist[0] - voltage_term * voltages[post_inds]
            )

            # Gather slope and offset for every postsynaptic compartment.
            gathered_syn_currents = gather_synapes(
                len(voltages),
                post_inds,
                voltage_term,
                constant_term,
            )
            syn_voltage_terms += gathered_syn_currents[0]
            syn_constant_terms -= gathered_syn_currents[1]

            # Add the synaptic currents through every compartment as state.
            # `post_syn_currents` is a `jnp.ndarray` of as many elements as there are
            # compartments in the network.
            # `[0]` because we only use the non-perturbed voltage.
            states[f"{synapse_type._name}_current"] = synapse_currents[0]

        return states, (syn_voltage_terms, syn_constant_terms)

    def vis(
        self,
        detail: str = "full",
        ax: Optional[Axes] = None,
        col: str = "k",
        synapse_col: str = "b",
        dims: Tuple[int] = (0, 1),
        type: str = "line",
        layers: Optional[List] = None,
        morph_plot_kwargs: Dict = {},
        synapse_plot_kwargs: Dict = {},
        synapse_scatter_kwargs: Dict = {},
        networkx_options: Dict = {},
        layer_kwargs: Dict = {},
    ) -> Axes:
        """Visualize the module.

        Args:
            detail: Either of [point, full]. `point` visualizes every neuron in the
                network as a dot (and it uses `networkx` to obtain cell positions).
                `full` plots the full morphology of every neuron. It requires that
                `compute_xyz()` has been run and allows for indivual neurons to be
                moved with `.move()`.
            col: The color in which cells are plotted. Only takes effect if
                `detail='full'`.
            type: Either `line` or `scatter`. Only takes effect if `detail='full'`.
            synapse_col: The color in which synapses are plotted. Only takes effect if
                `detail='full'`.
            dims: Which dimensions to plot. 1=x, 2=y, 3=z coordinate. Must be a tuple of
                two of them.
            layers: Allows to plot the network in layers. Should provide the number of
                neurons in each layer, e.g., [5, 10, 1] would be a network with 5 input
                neurons, 10 hidden layer neurons, and 1 output neuron.
            morph_plot_kwargs: Keyword arguments passed to the plotting function for
                cell morphologies. Only takes effect for `detail='full'`.
            synapse_plot_kwargs: Keyword arguments passed to the plotting function for
                syanpses. Only takes effect for `detail='full'`.
            synapse_scatter_kwargs: Keyword arguments passed to the scatter function
                for the end point of synapses. Only takes effect for `detail='full'`.
            networkx_options: Options passed to `networkx.draw()`. Only takes effect if
                `detail='point'`.
            layer_kwargs: Only used if `layers` is specified and if `detail='full'`.
                Can have the following entries: `within_layer_offset` (float),
                `between_layer_offset` (float), `vertical_layers` (bool).
        """
        if detail == "point":
            graph = self._build_graph(layers)

            if layers is not None:
                pos = nx.multipartite_layout(graph, subset_key="layer")
                nx.draw(graph, pos, with_labels=True, **networkx_options)
            else:
                nx.draw(graph, with_labels=True, **networkx_options)
        elif detail == "full":
            if layers is not None:
                # Assemble cells in the network into layers.
                global_counter = 0
                layers_config = {
                    "within_layer_offset": 500.0,
                    "between_layer_offset": 1500.0,
                    "vertical_layers": False,
                }
                layers_config.update(layer_kwargs)
                for layer_ind, num_in_layer in enumerate(layers):
                    for ind_within_layer in range(num_in_layer):
                        if layers_config["vertical_layers"]:
                            x_offset = (
                                ind_within_layer - (num_in_layer - 1) / 2
                            ) * layers_config["within_layer_offset"]
                            y_offset = (len(layers) - 1 - layer_ind) * layers_config[
                                "between_layer_offset"
                            ]
                        else:
                            x_offset = layer_ind * layers_config["between_layer_offset"]
                            y_offset = (
                                ind_within_layer - (num_in_layer - 1) / 2
                            ) * layers_config["within_layer_offset"]

                        self.cell(global_counter).move_to(x=x_offset, y=y_offset, z=0)
                        global_counter += 1
            ax = self._vis(
                dims=dims,
                col=col,
                ax=ax,
                type=type,
                view=self.nodes,
                morph_plot_kwargs=morph_plot_kwargs,
            )

            pre_locs = self.edges["pre_locs"].to_numpy()
            post_locs = self.edges["post_locs"].to_numpy()
            pre_branch = self.edges["global_pre_branch_index"].to_numpy()
            post_branch = self.edges["global_post_branch_index"].to_numpy()

            dims_np = np.asarray(dims)

            for pre_loc, post_loc, pre_b, post_b in zip(
                pre_locs, post_locs, pre_branch, post_branch
            ):
                pre_coord = self.xyzr[pre_b]
                if len(pre_coord) == 2:
                    # If only start and end point of a branch are traced, perform a
                    # linear interpolation to get the synpase location.
                    pre_coord = pre_coord[0] + (pre_coord[1] - pre_coord[0]) * pre_loc
                else:
                    # If densely traced, use intermediate trace values for synapse loc.
                    middle_ind = int((len(pre_coord) - 1) * pre_loc)
                    pre_coord = pre_coord[middle_ind]

                post_coord = self.xyzr[post_b]
                if len(post_coord) == 2:
                    # If only start and end point of a branch are traced, perform a
                    # linear interpolation to get the synpase location.
                    post_coord = (
                        post_coord[0] + (post_coord[1] - post_coord[0]) * post_loc
                    )
                else:
                    # If densely traced, use intermediate trace values for synapse loc.
                    middle_ind = int((len(post_coord) - 1) * post_loc)
                    post_coord = post_coord[middle_ind]

                coords = np.stack([pre_coord[dims_np], post_coord[dims_np]]).T
                ax.plot(
                    coords[0],
                    coords[1],
                    c=synapse_col,
                    **synapse_plot_kwargs,
                )
                ax.scatter(
                    post_coord[dims_np[0]],
                    post_coord[dims_np[1]],
                    c=synapse_col,
                    **synapse_scatter_kwargs,
                )
        else:
            raise ValueError("detail must be in {full, point}.")

        return ax

    def _build_graph(self, layers: Optional[List] = None, **options):
        graph = nx.DiGraph()

        def build_extents(*subset_sizes):
            return nx.utils.pairwise(itertools.accumulate((0,) + subset_sizes))

        if layers is not None:
            extents = build_extents(*layers)
            layers = [range(start, end) for start, end in extents]
            for i, layer in enumerate(layers):
                graph.add_nodes_from(layer, layer=i)
        else:
            graph.add_nodes_from(range(len(self.cells)))

        pre_cell = self.edges["pre_cell_index"].to_numpy()
        post_cell = self.edges["post_cell_index"].to_numpy()

        inds = np.stack([pre_cell, post_cell]).T
        graph.add_edges_from(inds)

        return graph

__init__(cells)

Initialize network of cells and synapses.

Parameters:

Name Type Description Default
cells List[Cell]

A list of cells that make up the network.

required
Source code in jaxley/modules/network.py
 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
def __init__(
    self,
    cells: List[Cell],
):
    """Initialize network of cells and synapses.

    Args:
        cells: A list of cells that make up the network.
    """
    super().__init__()
    for cell in cells:
        self.xyzr += deepcopy(cell.xyzr)

    self.cells = cells
    self.nseg = cells[0].nseg
    self._append_params_and_states(self.network_params, self.network_states)

    self.nbranches_per_cell = [cell.total_nbranches for cell in self.cells]
    self.nbranchpoints_per_cell = [cell.total_nbranchpoints for cell in self.cells]
    self.total_nbranches = sum(self.nbranches_per_cell)
    self.cumsum_nbranches = jnp.cumsum(jnp.asarray([0] + self.nbranches_per_cell))
    self.cumsum_nbranchpoints = jnp.cumsum(
        jnp.asarray([0] + self.nbranchpoints_per_cell)
    )

    self.nodes = pd.concat([c.nodes for c in cells], ignore_index=True)
    self.nodes["comp_index"] = np.arange(self.nseg * self.total_nbranches).tolist()
    self.nodes["branch_index"] = (
        np.arange(self.nseg * self.total_nbranches) // self.nseg
    ).tolist()
    self.nodes["cell_index"] = list(
        itertools.chain(
            *[[i] * (self.nseg * b) for i, b in enumerate(self.nbranches_per_cell)]
        )
    )

    parents = [cell.comb_parents for cell in self.cells]
    self.comb_parents = jnp.concatenate(
        [p.at[1:].add(self.cumsum_nbranches[i]) for i, p in enumerate(parents)]
    )

    # Two columns: `parent_branch_index` and `child_branch_index`. One row per
    # branch, apart from those branches which do not have a parent (i.e.
    # -1 in parents). For every branch, tracks the global index of that branch
    # (`child_branch_index`) and the global index of its parent
    # (`parent_branch_index`).
    self.branch_edges = pd.DataFrame(
        dict(
            parent_branch_index=self.comb_parents[self.comb_parents != -1],
            child_branch_index=np.where(self.comb_parents != -1)[0],
        )
    )

    # For morphology indexing.
    par_inds = self.branch_edges["parent_branch_index"].to_numpy()
    self.child_inds = self.branch_edges["child_branch_index"].to_numpy()
    self.child_belongs_to_branchpoint = remap_to_consecutive(par_inds)
    self.par_inds = np.unique(par_inds)  # TODO: does order have to be preserved?
    self.total_nbranchpoints = len(self.par_inds)
    self.root_inds = self.cumsum_nbranches[:-1]

    # Channels.
    self._gather_channels_from_constituents(cells)

    self.initialize()
    self.init_syns()
    self.initialized_conds = False

init_conds(params)

Given an axial resisitivity, set the coupling conductances.

Source code in jaxley/modules/network.py
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
def init_conds(self, params: Dict) -> Dict[str, jnp.ndarray]:
    """Given an axial resisitivity, set the coupling conductances."""
    nbranches = self.total_nbranches
    nseg = self.nseg
    parents = self.comb_parents

    axial_resistivity = jnp.reshape(params["axial_resistivity"], (nbranches, nseg))
    radiuses = jnp.reshape(params["radius"], (nbranches, nseg))
    lengths = jnp.reshape(params["length"], (nbranches, nseg))

    conds = vmap(Branch.init_branch_conds, in_axes=(0, 0, 0, None))(
        axial_resistivity, radiuses, lengths, self.nseg
    )
    coupling_conds_fwd = conds[0]
    coupling_conds_bwd = conds[1]
    summed_coupling_conds = conds[2]

    # The conductance from the children to the branch point.
    branchpoint_conds_children = vmap(
        compute_coupling_cond_branchpoint, in_axes=(0, 0, 0)
    )(
        radiuses[self.child_inds, 0],
        axial_resistivity[self.child_inds, 0],
        lengths[self.child_inds, 0],
    )
    # The conductance from the parents to the branch point.
    branchpoint_conds_parents = vmap(
        compute_coupling_cond_branchpoint, in_axes=(0, 0, 0)
    )(
        radiuses[self.par_inds, -1],
        axial_resistivity[self.par_inds, -1],
        lengths[self.par_inds, -1],
    )

    # Weights with which the compartments influence their nearby node.
    # The impact of the children on the branch point.
    branchpoint_weights_children = vmap(compute_impact_on_node, in_axes=(0, 0, 0))(
        radiuses[self.child_inds, 0],
        axial_resistivity[self.child_inds, 0],
        lengths[self.child_inds, 0],
    )
    # The impact of parents on the branch point.
    branchpoint_weights_parents = vmap(compute_impact_on_node, in_axes=(0, 0, 0))(
        radiuses[self.par_inds, -1],
        axial_resistivity[self.par_inds, -1],
        lengths[self.par_inds, -1],
    )

    summed_coupling_conds = Cell.update_summed_coupling_conds(
        summed_coupling_conds,
        self.child_inds,
        self.par_inds,
        branchpoint_conds_children,
        branchpoint_conds_parents,
    )

    cond_params = {
        "branch_uppers": coupling_conds_bwd,
        "branch_lowers": coupling_conds_fwd,
        "branch_diags": summed_coupling_conds,
        "branchpoint_conds_children": branchpoint_conds_children,
        "branchpoint_conds_parents": branchpoint_conds_parents,
        "branchpoint_weights_children": branchpoint_weights_children,
        "branchpoint_weights_parents": branchpoint_weights_parents,
    }
    return cond_params

init_syns()

Initialize synapses.

Source code in jaxley/modules/network.py
218
219
220
221
222
223
224
225
226
227
def init_syns(self):
    """Initialize synapses."""
    self.synapses = []

    # TODO(@michaeldeistler): should we also track this for channels?
    self.synapse_names = []
    self.synapse_param_names = []
    self.synapse_state_names = []

    self.initialized_syns = True

vis(detail='full', ax=None, col='k', synapse_col='b', dims=(0, 1), type='line', layers=None, morph_plot_kwargs={}, synapse_plot_kwargs={}, synapse_scatter_kwargs={}, networkx_options={}, layer_kwargs={})

Visualize the module.

Parameters:

Name Type Description Default
detail str

Either of [point, full]. point visualizes every neuron in the network as a dot (and it uses networkx to obtain cell positions). full plots the full morphology of every neuron. It requires that compute_xyz() has been run and allows for indivual neurons to be moved with .move().

'full'
col str

The color in which cells are plotted. Only takes effect if detail='full'.

'k'
type str

Either line or scatter. Only takes effect if detail='full'.

'line'
synapse_col str

The color in which synapses are plotted. Only takes effect if detail='full'.

'b'
dims Tuple[int]

Which dimensions to plot. 1=x, 2=y, 3=z coordinate. Must be a tuple of two of them.

(0, 1)
layers Optional[List]

Allows to plot the network in layers. Should provide the number of neurons in each layer, e.g., [5, 10, 1] would be a network with 5 input neurons, 10 hidden layer neurons, and 1 output neuron.

None
morph_plot_kwargs Dict

Keyword arguments passed to the plotting function for cell morphologies. Only takes effect for detail='full'.

{}
synapse_plot_kwargs Dict

Keyword arguments passed to the plotting function for syanpses. Only takes effect for detail='full'.

{}
synapse_scatter_kwargs Dict

Keyword arguments passed to the scatter function for the end point of synapses. Only takes effect for detail='full'.

{}
networkx_options Dict

Options passed to networkx.draw(). Only takes effect if detail='point'.

{}
layer_kwargs Dict

Only used if layers is specified and if detail='full'. Can have the following entries: within_layer_offset (float), between_layer_offset (float), vertical_layers (bool).

{}
Source code in jaxley/modules/network.py
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
def vis(
    self,
    detail: str = "full",
    ax: Optional[Axes] = None,
    col: str = "k",
    synapse_col: str = "b",
    dims: Tuple[int] = (0, 1),
    type: str = "line",
    layers: Optional[List] = None,
    morph_plot_kwargs: Dict = {},
    synapse_plot_kwargs: Dict = {},
    synapse_scatter_kwargs: Dict = {},
    networkx_options: Dict = {},
    layer_kwargs: Dict = {},
) -> Axes:
    """Visualize the module.

    Args:
        detail: Either of [point, full]. `point` visualizes every neuron in the
            network as a dot (and it uses `networkx` to obtain cell positions).
            `full` plots the full morphology of every neuron. It requires that
            `compute_xyz()` has been run and allows for indivual neurons to be
            moved with `.move()`.
        col: The color in which cells are plotted. Only takes effect if
            `detail='full'`.
        type: Either `line` or `scatter`. Only takes effect if `detail='full'`.
        synapse_col: The color in which synapses are plotted. Only takes effect if
            `detail='full'`.
        dims: Which dimensions to plot. 1=x, 2=y, 3=z coordinate. Must be a tuple of
            two of them.
        layers: Allows to plot the network in layers. Should provide the number of
            neurons in each layer, e.g., [5, 10, 1] would be a network with 5 input
            neurons, 10 hidden layer neurons, and 1 output neuron.
        morph_plot_kwargs: Keyword arguments passed to the plotting function for
            cell morphologies. Only takes effect for `detail='full'`.
        synapse_plot_kwargs: Keyword arguments passed to the plotting function for
            syanpses. Only takes effect for `detail='full'`.
        synapse_scatter_kwargs: Keyword arguments passed to the scatter function
            for the end point of synapses. Only takes effect for `detail='full'`.
        networkx_options: Options passed to `networkx.draw()`. Only takes effect if
            `detail='point'`.
        layer_kwargs: Only used if `layers` is specified and if `detail='full'`.
            Can have the following entries: `within_layer_offset` (float),
            `between_layer_offset` (float), `vertical_layers` (bool).
    """
    if detail == "point":
        graph = self._build_graph(layers)

        if layers is not None:
            pos = nx.multipartite_layout(graph, subset_key="layer")
            nx.draw(graph, pos, with_labels=True, **networkx_options)
        else:
            nx.draw(graph, with_labels=True, **networkx_options)
    elif detail == "full":
        if layers is not None:
            # Assemble cells in the network into layers.
            global_counter = 0
            layers_config = {
                "within_layer_offset": 500.0,
                "between_layer_offset": 1500.0,
                "vertical_layers": False,
            }
            layers_config.update(layer_kwargs)
            for layer_ind, num_in_layer in enumerate(layers):
                for ind_within_layer in range(num_in_layer):
                    if layers_config["vertical_layers"]:
                        x_offset = (
                            ind_within_layer - (num_in_layer - 1) / 2
                        ) * layers_config["within_layer_offset"]
                        y_offset = (len(layers) - 1 - layer_ind) * layers_config[
                            "between_layer_offset"
                        ]
                    else:
                        x_offset = layer_ind * layers_config["between_layer_offset"]
                        y_offset = (
                            ind_within_layer - (num_in_layer - 1) / 2
                        ) * layers_config["within_layer_offset"]

                    self.cell(global_counter).move_to(x=x_offset, y=y_offset, z=0)
                    global_counter += 1
        ax = self._vis(
            dims=dims,
            col=col,
            ax=ax,
            type=type,
            view=self.nodes,
            morph_plot_kwargs=morph_plot_kwargs,
        )

        pre_locs = self.edges["pre_locs"].to_numpy()
        post_locs = self.edges["post_locs"].to_numpy()
        pre_branch = self.edges["global_pre_branch_index"].to_numpy()
        post_branch = self.edges["global_post_branch_index"].to_numpy()

        dims_np = np.asarray(dims)

        for pre_loc, post_loc, pre_b, post_b in zip(
            pre_locs, post_locs, pre_branch, post_branch
        ):
            pre_coord = self.xyzr[pre_b]
            if len(pre_coord) == 2:
                # If only start and end point of a branch are traced, perform a
                # linear interpolation to get the synpase location.
                pre_coord = pre_coord[0] + (pre_coord[1] - pre_coord[0]) * pre_loc
            else:
                # If densely traced, use intermediate trace values for synapse loc.
                middle_ind = int((len(pre_coord) - 1) * pre_loc)
                pre_coord = pre_coord[middle_ind]

            post_coord = self.xyzr[post_b]
            if len(post_coord) == 2:
                # If only start and end point of a branch are traced, perform a
                # linear interpolation to get the synpase location.
                post_coord = (
                    post_coord[0] + (post_coord[1] - post_coord[0]) * post_loc
                )
            else:
                # If densely traced, use intermediate trace values for synapse loc.
                middle_ind = int((len(post_coord) - 1) * post_loc)
                post_coord = post_coord[middle_ind]

            coords = np.stack([pre_coord[dims_np], post_coord[dims_np]]).T
            ax.plot(
                coords[0],
                coords[1],
                c=synapse_col,
                **synapse_plot_kwargs,
            )
            ax.scatter(
                post_coord[dims_np[0]],
                post_coord[dims_np[1]],
                c=synapse_col,
                **synapse_scatter_kwargs,
            )
    else:
        raise ValueError("detail must be in {full, point}.")

    return ax