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
  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
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
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.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] = []
        self._radius_generating_fns = None  # Defined by `.read_swc()`.

        # 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 of compartment centers to nodes.

        Centers are the midpoint between the comparment endpoints on the morphology
        as defined by xyzr.

        Note: For sake of performance, interpolation is not done for each branch
        individually, but only once along a concatenated (and padded) array of all branches.
        This means for nsegs = [2,4] and normalized cum_branch_lens of [[0,1],[0,1]] we would
        interpolate xyz at the locations comp_ends = [[0,0.5,1], [0,0.25,0.5,0.75,1]],
        where 0 is the start of the branch and 1 is the end point at the full branch_len.
        To avoid do this in one go we set comp_ends = [0,0.5,1,2,2.25,2.5,2.75,3], and
        norm_cum_branch_len = [0,1,2,3] incrememting and also padding them by 1 to
        avoid overlapping branch_lens i.e. norm_cum_branch_len = [0,1,1,2] for only
        incrementing.
        """
        nsegs = self.nodes.groupby("branch_index")["comp_index"].nunique().to_numpy()

        comp_ends = np.hstack(
            [np.linspace(0, 1, nseg + 1) + 2 * i for i, nseg in enumerate(nsegs)]
        )
        comp_ends = comp_ends.reshape(-1)
        cum_branch_lens = []
        for i, xyzr in enumerate(self.xyzr):
            branch_len = np.sqrt(np.sum(np.diff(xyzr[:, :3], axis=0) ** 2, axis=1))
            cum_branch_len = np.cumsum(np.concatenate([np.array([0]), branch_len]))
            max_len = cum_branch_len.max()
            # add padding like above
            cum_branch_len = cum_branch_len / (max_len if max_len > 0 else 1) + 2 * i
            cum_branch_len[np.isnan(cum_branch_len)] = 0
            cum_branch_lens.append(cum_branch_len)
        cum_branch_lens = np.hstack(cum_branch_lens)
        xyz = np.vstack(self.xyzr)[:, :3]
        xyz = v_interp(comp_ends, cum_branch_lens, xyz).T
        centers = (xyz[:-1] + xyz[1:]) / 2  # unaware of inter vs intra comp centers
        cum_nsegs = np.cumsum(nsegs)
        # this means centers between comps have to be removed here
        between_comp_inds = (cum_nsegs + np.arange(len(cum_nsegs)))[:-1]
        centers = np.delete(centers, between_comp_inds, axis=0)
        idcs = self.nodes["comp_index"]
        self.nodes.loc[idcs, ["x", "y", "z"]] = centers
        return centers, xyz

    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()))

    @property
    def _module_type(self):
        """Return type of the module (compartment, branch, cell, network) as string.

        This is used to perform asserts for some modules (e.g. network cannot use
        `set_ncomp`) without having to import the module in `base.py`."""
        return self.__class__.__name__.lower()

    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

    def init_morph(self):
        """Initialize the morphology such that it can be processed by the solvers."""
        self._init_morph_jaxley_spsolve()
        self._init_morph_jax_spsolve()
        self.initialized_morph = True

    @abstractmethod
    def _init_morph_jax_spsolve(self):
        """Initialize the morphology for the JAX sparse solver."""
        raise NotImplementedError

    @abstractmethod
    def _init_morph_jaxley_spsolve(self):
        """Initialize the morphology for the custom Jaxley solver."""
        raise NotImplementedError

    def _compute_axial_conductances(self, params: Dict[str, jnp.ndarray]):
        """Given radius, length, r_a, compute the axial coupling conductances."""
        return compute_axial_conductances(self._comp_edges, params)

    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 _set_ncomp(
        self,
        ncomp: int,
        view: pd.DataFrame,
        all_nodes: pd.DataFrame,
        start_idx: int,
        nseg_per_branch: jnp.asarray,
        channel_names: List[str],
        channel_param_names: List[str],
        channel_state_names: List[str],
        radius_generating_fns: List[Callable],
        min_radius: Optional[float],
    ):
        """Set the number of compartments with which the branch is discretized."""
        within_branch_radiuses = view["radius"].to_numpy()
        compartment_lengths = view["length"].to_numpy()
        num_previous_ncomp = len(within_branch_radiuses)
        branch_indices = pd.unique(view["branch_index"])

        error_msg = lambda name: (
            f"You previously modified the {name} of individual compartments, but "
            f"now you are modifying the number of compartments in this branch. "
            f"This is not allowed. First build the morphology with `set_ncomp()` and "
            f"then modify the radiuses and lengths of compartments."
        )

        if (
            ~np.all(within_branch_radiuses == within_branch_radiuses[0])
            and radius_generating_fns is None
        ):
            raise ValueError(error_msg("radius"))

        for property_name in ["length", "capacitance", "axial_resistivity"]:
            compartment_properties = view[property_name].to_numpy()
            if ~np.all(compartment_properties == compartment_properties[0]):
                raise ValueError(error_msg(property_name))

        if not (view[channel_names].var() == 0.0).all():
            raise ValueError(
                "Some channel exists only in some compartments of the branch which you"
                "are trying to modify. This is not allowed. First specify the number"
                "of compartments with `.set_ncomp()` and then insert the channels"
                "accordingly."
            )

        if not (view[channel_param_names + channel_state_names].var() == 0.0).all():
            raise ValueError(
                "Some channel has different parameters or states between the "
                "different compartments of the branch which you are trying to modify. "
                "This is not allowed. First specify the number of compartments with "
                "`.set_ncomp()` and then insert the channels accordingly."
            )

        # Add new rows as the average of all rows. Special case for the length is below.
        average_row = view.mean(skipna=False)
        average_row = average_row.to_frame().T
        view = pd.concat([*[average_row] * ncomp], axis="rows")

        # If the `view` is not the entire `Module`, but a `View` (i.e. if one changes
        # the number of comps within a branch of a cell), then the `self.pointer.view`
        # will contain the additional `global_xyz_index` columns. However, the
        # `self.nodes` will not have these columns.
        #
        # Note that we assert that there are no trainables, so `controlled_by_params`
        # of the `self.nodes` has to be empty.
        if "global_comp_index" in view.columns:
            view = view.drop(
                columns=[
                    "global_comp_index",
                    "global_branch_index",
                    "global_cell_index",
                    "controlled_by_param",
                ]
            )

        # Set the correct datatype after having performed an average which cast
        # everything to float.
        integer_cols = ["comp_index", "branch_index", "cell_index"]
        view[integer_cols] = view[integer_cols].astype(int)

        # Whether or not a channel exists in a compartment is a boolean.
        boolean_cols = channel_names
        view[boolean_cols] = view[boolean_cols].astype(bool)

        # Special treatment for the lengths and radiuses. These are not being set as
        # the average because we:
        # 1) Want to maintain the total length of a branch.
        # 2) Want to use the SWC inferred radius.
        #
        # Compute new compartment lengths.
        comp_lengths = np.sum(compartment_lengths) / ncomp
        view["length"] = comp_lengths

        # Compute new compartment radiuses.
        if radius_generating_fns is not None:
            view["radius"] = build_radiuses_from_xyzr(
                radius_fns=radius_generating_fns,
                branch_indices=branch_indices,
                min_radius=min_radius,
                nseg=ncomp,
            )
        else:
            view["radius"] = within_branch_radiuses[0] * np.ones(ncomp)

        # Update `.nodes`.
        #
        # 1) Delete N rows starting from start_idx
        number_deleted = num_previous_ncomp
        all_nodes = all_nodes.drop(index=range(start_idx, start_idx + number_deleted))

        # 2) Insert M new rows at the same location
        df1 = all_nodes.iloc[:start_idx]  # Rows before the insertion point
        df2 = all_nodes.iloc[start_idx:]  # Rows after the insertion point

        # 3) Combine the parts: before, new rows, and after
        all_nodes = pd.concat([df1, view, df2]).reset_index(drop=True)

        # Override `comp_index` to just be a consecutive list.
        all_nodes["comp_index"] = np.arange(len(all_nodes))

        # Update compartment structure arguments.
        nseg_per_branch[branch_indices] = ncomp
        nseg = int(np.max(nseg_per_branch))
        cumsum_nseg = cumsum_leading_zero(nseg_per_branch)
        internal_node_inds = np.arange(cumsum_nseg[-1])

        return all_nodes, nseg_per_branch, nseg, cumsum_nseg, internal_node_inds

    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")
            num_elements_being_set = grouped_view.apply(len).to_numpy()
            assert np.all(num_elements_being_set == num_elements_being_set[0]), (
                "You are using `make_trainable()` with parameter sharing (e.g. same "
                "parameter for an entire cell, or same parameter for entire branches). "
                "This error is caused because you are trying to share a parameter "
                "across an inhomogenous number of compartments. To overcome this "
                "error, write a for-loop across cells (or branches). For example, "
                "change `net.cell('all').make_trainable('HH_gNa')` to "
                "`for i in range(num_cells): net.cell(i).make_trainable('HH_gNa')`"
            )
            # 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], voltage_solver: str
    ) -> Dict[str, jnp.ndarray]:
        """Return all parameters (and coupling conductances) needed to simulate.

        Runs `_compute_axial_conductances()` 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])
                }, ...].
            voltage_solver: The voltage solver that is used. Since `jax.sparse` and
                `jaxley.xyz` require different formats of the axial conductances, this
                function will default to different building methods.

        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 add them to the params dictionary.
        params["axial_conductances"] = self._compute_axial_conductances(params=params)
        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.
        # `voltage_solver` could also be `jax.sparse` here, because both of them
        # build the channel parameters in the same way.
        params = self.get_all_parameters([], voltage_solver="jaxley.thomas")

        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 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.

        # Arguments used by all solvers.
        solver_kwargs = {
            "voltages": voltages,
            "voltage_terms": (v_terms + syn_v_terms) / cm,
            "constant_terms": (const_terms + i_ext + syn_const_terms) / cm,
            "axial_conductances": params["axial_conductances"],
            "internal_node_inds": self._internal_node_inds,
        }

        # Add solver specific arguments.
        if voltage_solver == "jax.sparse":
            solver_kwargs.update(
                {
                    "sinks": np.asarray(self._comp_edges["sink"].to_list()),
                    "data_inds": self._data_inds,
                    "indices": self._indices_jax_spsolve,
                    "indptr": self._indptr_jax_spsolve,
                    "n_nodes": self._n_nodes,
                }
            )
            # Only for `bwd_euler` and `cranck-nicolson`.
            step_voltage_implicit = step_voltage_implicit_with_jax_spsolve
        else:
            # Our custom sparse solver requires a different format of all conductance
            # values to perform triangulation and backsubstution optimally.
            #
            # Currently, the forward Euler solver also uses this format. However,
            # this is only for historical reasons and we are planning to change this in
            # the future.
            solver_kwargs.update(
                {
                    "sinks": np.asarray(self._comp_edges["sink"].to_list()),
                    "sources": np.asarray(self._comp_edges["source"].to_list()),
                    "types": np.asarray(self._comp_edges["type"].to_list()),
                    "nseg_per_branch": self.nseg_per_branch,
                    "par_inds": self.par_inds,
                    "child_inds": self.child_inds,
                    "nbranches": self.total_nbranches,
                    "solver": voltage_solver,
                    "idx": self.solve_indexer,
                    "debug_states": self.debug_states,
                }
            )
            # Only for `bwd_euler` and `cranck-nicolson`.
            step_voltage_implicit = step_voltage_implicit_with_jaxley_spsolve

        if solver == "bwd_euler":
            u["v"] = step_voltage_implicit(**solver_kwargs, delta_t=delta_t)
        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 - voltages
        elif solver == "fwd_euler":
            u["v"] = step_voltage_explicit(**solver_kwargs, delta_t=delta_t)
        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",
                "capacitance",
            ]
            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.

        Modules can be visualized on one of the cardinal planes (xy, xz, yz) or
        even in 3D.

        Several options are available:
        - `line`: All points from the traced morphology (`xyzr`), are connected
        with a line plot.
        - `scatter`: All traced points, are plotted as scatter points.
        - `comp`: Plots the compartmentalized morphology, including radius
        and shape. (shows the true compartment lengths per default, but this can
        be changed via the `morph_plot_kwargs`, for details see
        `jaxley.utils.plot_utils.plot_comps`).
        - `morph`: Reconstructs the 3D shape of the traced morphology. For details see
        `jaxley.utils.plot_utils.plot_morph`. Warning: For 3D plots and morphologies
        with many traced points this can be very slow.

        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.
            type: The type of plot. One of ["line", "scatter", "comp", "morph"].
            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()

        if "comp" in type.lower():
            return plot_comps(
                self, view, dims=dims, ax=ax, col=col, **morph_plot_kwargs
            )
        if "morph" in type.lower():
            return plot_morph(
                self, view, dims=dims, ax=ax, col=col, **morph_plot_kwargs
            )

        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_graph(
            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,
            branch_ind,
            self.nseg_per_branch,
        )
        coords = self.xyzr[branch_ind]
        interpolated_xyz = interpolate_xyz(comp_fraction, coords)

        ax = plot_graph(
            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]

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
646
647
648
649
650
651
652
653
654
655
656
657
658
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
947
948
949
950
951
952
953
954
955
956
957
958
959
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
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
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
986
987
988
989
990
991
992
993
994
995
996
997
998
999
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
927
928
929
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
1033
1034
1035
1036
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
640
641
642
643
644
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, voltage_solver)

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

Runs _compute_axial_conductances() 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
voltage_solver str

The voltage solver that is used. Since jax.sparse and jaxley.xyz require different formats of the axial conductances, this function will default to different building methods.

required

Returns:

Type Description
Dict[str, ndarray]

A dictionary of all module parameters.

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

    Runs `_compute_axial_conductances()` 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])
            }, ...].
        voltage_solver: The voltage solver that is used. Since `jax.sparse` and
            `jaxley.xyz` require different formats of the axial conductances, this
            function will default to different building methods.

    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 add them to the params dictionary.
    params["axial_conductances"] = self._compute_axial_conductances(params=params)
    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
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
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
665
666
667
668
669
670
671
672
673
674
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
736
737
738
739
740
741
742
743
744
745
746
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_morph()

Initialize the morphology such that it can be processed by the solvers.

Source code in jaxley/modules/base.py
297
298
299
300
301
def init_morph(self):
    """Initialize the morphology such that it can be processed by the solvers."""
    self._init_morph_jaxley_spsolve()
    self._init_morph_jax_spsolve()
    self.initialized_morph = True

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
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
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.
    # `voltage_solver` could also be `jax.sparse` here, because both of them
    # build the channel parameters in the same way.
    params = self.get_all_parameters([], voltage_solver="jaxley.thomas")

    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
791
792
793
794
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
1038
1039
1040
1041
1042
1043
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
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
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
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
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
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
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
910
911
912
913
914
915
916
917
918
919
920
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
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
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
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
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
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
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.

    # Arguments used by all solvers.
    solver_kwargs = {
        "voltages": voltages,
        "voltage_terms": (v_terms + syn_v_terms) / cm,
        "constant_terms": (const_terms + i_ext + syn_const_terms) / cm,
        "axial_conductances": params["axial_conductances"],
        "internal_node_inds": self._internal_node_inds,
    }

    # Add solver specific arguments.
    if voltage_solver == "jax.sparse":
        solver_kwargs.update(
            {
                "sinks": np.asarray(self._comp_edges["sink"].to_list()),
                "data_inds": self._data_inds,
                "indices": self._indices_jax_spsolve,
                "indptr": self._indptr_jax_spsolve,
                "n_nodes": self._n_nodes,
            }
        )
        # Only for `bwd_euler` and `cranck-nicolson`.
        step_voltage_implicit = step_voltage_implicit_with_jax_spsolve
    else:
        # Our custom sparse solver requires a different format of all conductance
        # values to perform triangulation and backsubstution optimally.
        #
        # Currently, the forward Euler solver also uses this format. However,
        # this is only for historical reasons and we are planning to change this in
        # the future.
        solver_kwargs.update(
            {
                "sinks": np.asarray(self._comp_edges["sink"].to_list()),
                "sources": np.asarray(self._comp_edges["source"].to_list()),
                "types": np.asarray(self._comp_edges["type"].to_list()),
                "nseg_per_branch": self.nseg_per_branch,
                "par_inds": self.par_inds,
                "child_inds": self.child_inds,
                "nbranches": self.total_nbranches,
                "solver": voltage_solver,
                "idx": self.solve_indexer,
                "debug_states": self.debug_states,
            }
        )
        # Only for `bwd_euler` and `cranck-nicolson`.
        step_voltage_implicit = step_voltage_implicit_with_jaxley_spsolve

    if solver == "bwd_euler":
        u["v"] = step_voltage_implicit(**solver_kwargs, delta_t=delta_t)
    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 - voltages
    elif solver == "fwd_euler":
        u["v"] = step_voltage_explicit(**solver_kwargs, delta_t=delta_t)
    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
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
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
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
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.

Modules can be visualized on one of the cardinal planes (xy, xz, yz) or even in 3D.

Several options are available: - line: All points from the traced morphology (xyzr), are connected with a line plot. - scatter: All traced points, are plotted as scatter points. - comp: Plots the compartmentalized morphology, including radius and shape. (shows the true compartment lengths per default, but this can be changed via the morph_plot_kwargs, for details see jaxley.utils.plot_utils.plot_comps). - morph: Reconstructs the 3D shape of the traced morphology. For details see jaxley.utils.plot_utils.plot_morph. Warning: For 3D plots and morphologies with many traced points this can be very slow.

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)
type str

The type of plot. One of [“line”, “scatter”, “comp”, “morph”].

'line'
morph_plot_kwargs Dict

Keyword arguments passed to the plotting function.

{}
Source code in jaxley/modules/base.py
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
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.

    Modules can be visualized on one of the cardinal planes (xy, xz, yz) or
    even in 3D.

    Several options are available:
    - `line`: All points from the traced morphology (`xyzr`), are connected
    with a line plot.
    - `scatter`: All traced points, are plotted as scatter points.
    - `comp`: Plots the compartmentalized morphology, including radius
    and shape. (shows the true compartment lengths per default, but this can
    be changed via the `morph_plot_kwargs`, for details see
    `jaxley.utils.plot_utils.plot_comps`).
    - `morph`: Reconstructs the 3D shape of the traced morphology. For details see
    `jaxley.utils.plot_utils.plot_morph`. Warning: For 3D plots and morphologies
    with many traced points this can be very slow.

    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.
        type: The type of plot. One of ["line", "scatter", "comp", "morph"].
        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
 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
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.nseg_per_branch = np.asarray([1])
        self.total_nbranches = 1
        self.nbranches_per_cell = [1]
        self.cumsum_nbranches = jnp.asarray([0, 1])
        self.cumsum_nseg = cumsum_leading_zero(self.nseg_per_branch)

        # 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.par_inds, self.child_inds, self.child_belongs_to_branchpoint = (
            compute_children_and_parents(self.branch_edges)
        )
        self._internal_node_inds = jnp.asarray([0])

        # Initialize the module.
        self.initialize()
        self.init_syns()

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

    def _init_morph_jaxley_spsolve(self):
        self.solve_indexer = JaxleySolveIndexer(
            cumsum_nseg=self.cumsum_nseg,
            branchpoint_group_inds=np.asarray([]).astype(int),
            children_in_level=[],
            parents_in_level=[],
            root_inds=np.asarray([0]),
            remapped_node_indices=self._internal_node_inds,
        )

    def _init_morph_jax_spsolve(self):
        """Initialize morphology for the jax sparse voltage solver.

        Explanation of `self._comp_eges['type']`:
        `type == 0`: compartment <--> compartment (within branch)
        `type == 1`: branchpoint --> parent-compartment
        `type == 2`: branchpoint --> child-compartment
        `type == 3`: parent-compartment --> branchpoint
        `type == 4`: child-compartment --> branchpoint
        """
        self._comp_edges = pd.DataFrame().from_dict(
            {"source": [], "sink": [], "type": []}
        )
        n_nodes, data_inds, indices, indptr = comp_edges_to_indices(self._comp_edges)
        self._n_nodes = n_nodes
        self._data_inds = data_inds
        self._indices_jax_spsolve = indices
        self._indptr_jax_spsolve = indptr

    def init_conds(self, params: Dict[str, jnp.ndarray]):
        """Override `Base.init_axial_conds()`.

        This is because compartments do not have any axial conductances."""
        return {"axial_conductances": jnp.asarray([])}

init_conds(params)

Override Base.init_axial_conds().

This is because compartments do not have any axial conductances.

Source code in jaxley/modules/compartment.py
100
101
102
103
104
def init_conds(self, params: Dict[str, jnp.ndarray]):
    """Override `Base.init_axial_conds()`.

    This is because compartments do not have any axial conductances."""
    return {"axial_conductances": jnp.asarray([])}

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
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
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.nseg_per_branch = np.asarray([self.nseg])
        self.total_nbranches = 1
        self.nbranches_per_cell = [1]
        self.cumsum_nbranches = jnp.asarray([0, 1])
        self.cumsum_nseg = cumsum_leading_zero(self.nseg_per_branch)

        # 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.par_inds, self.child_inds, self.child_belongs_to_branchpoint = (
            compute_children_and_parents(self.branch_edges)
        )
        self._internal_node_inds = jnp.arange(self.nseg)

        self.initialize()
        self.init_syns()

        # 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_morph_jaxley_spsolve(self):
        self.solve_indexer = JaxleySolveIndexer(
            cumsum_nseg=self.cumsum_nseg,
            branchpoint_group_inds=np.asarray([]).astype(int),
            remapped_node_indices=self._internal_node_inds,
            children_in_level=[],
            parents_in_level=[],
            root_inds=np.asarray([0]),
        )

    def _init_morph_jax_spsolve(self):
        """Initialize morphology for the jax sparse voltage solver.

        Explanation of `self._comp_eges['type']`:
        `type == 0`: compartment <--> compartment (within branch)
        `type == 1`: branchpoint --> parent-compartment
        `type == 2`: branchpoint --> child-compartment
        `type == 3`: parent-compartment --> branchpoint
        `type == 4`: child-compartment --> branchpoint
        """
        self._comp_edges = pd.DataFrame().from_dict(
            {
                "source": list(range(self.nseg - 1)) + list(range(1, self.nseg)),
                "sink": list(range(1, self.nseg)) + list(range(self.nseg - 1)),
            }
        )
        self._comp_edges["type"] = 0
        n_nodes, data_inds, indices, indptr = comp_edges_to_indices(self._comp_edges)
        self._n_nodes = n_nodes
        self._data_inds = data_inds
        self._indices_jax_spsolve = indices
        self._indptr_jax_spsolve = indptr

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

    def set_ncomp(self, ncomp: int, min_radius: Optional[float] = None):
        """Set the number of compartments with which the branch is discretized.

        Args:
            ncomp: The number of compartments that the branch should be discretized
                into.

        Raises:
            - When the Module is a Network.
            - When there are stimuli in any compartment in the Module.
            - When there are recordings in any compartment in the Module.
            - When the channels of the compartments are not the same within the branch
            that is modified.
            - When the lengths of the compartments are not the same within the branch
            that is modified.
            - Unless the morphology was read from an SWC file, when the radiuses of the
            compartments are not the same within the branch that is modified.
        """
        assert len(self.externals) == 0, "No stimuli allowed!"
        assert len(self.recordings) == 0, "No recordings allowed!"
        assert len(self.trainable_params) == 0, "No trainables allowed!"

        # Update all attributes that are affected by compartment structure.
        (
            self.nodes,
            self.nseg_per_branch,
            self.nseg,
            self.cumsum_nseg,
            self._internal_node_inds,
        ) = self._set_ncomp(
            ncomp,
            self.nodes,
            self.nodes,
            self.nodes["comp_index"].to_numpy()[0],
            self.nseg_per_branch,
            [c._name for c in self.channels],
            list(chain(*[c.channel_params for c in self.channels])),
            list(chain(*[c.channel_states for c in self.channels])),
            self._radius_generating_fns,
            min_radius,
        )

        # Update the morphology indexing (e.g., `.comp_edges`).
        self.initialize()

__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
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
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.nseg_per_branch = np.asarray([self.nseg])
    self.total_nbranches = 1
    self.nbranches_per_cell = [1]
    self.cumsum_nbranches = jnp.asarray([0, 1])
    self.cumsum_nseg = cumsum_leading_zero(self.nseg_per_branch)

    # 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.par_inds, self.child_inds, self.child_belongs_to_branchpoint = (
        compute_children_and_parents(self.branch_edges)
    )
    self._internal_node_inds = jnp.arange(self.nseg)

    self.initialize()
    self.init_syns()

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

set_ncomp(ncomp, min_radius=None)

Set the number of compartments with which the branch is discretized.

Parameters:

Name Type Description Default
ncomp int

The number of compartments that the branch should be discretized into.

required
Source code in jaxley/modules/branch.py
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
def set_ncomp(self, ncomp: int, min_radius: Optional[float] = None):
    """Set the number of compartments with which the branch is discretized.

    Args:
        ncomp: The number of compartments that the branch should be discretized
            into.

    Raises:
        - When the Module is a Network.
        - When there are stimuli in any compartment in the Module.
        - When there are recordings in any compartment in the Module.
        - When the channels of the compartments are not the same within the branch
        that is modified.
        - When the lengths of the compartments are not the same within the branch
        that is modified.
        - Unless the morphology was read from an SWC file, when the radiuses of the
        compartments are not the same within the branch that is modified.
    """
    assert len(self.externals) == 0, "No stimuli allowed!"
    assert len(self.recordings) == 0, "No recordings allowed!"
    assert len(self.trainable_params) == 0, "No trainables allowed!"

    # Update all attributes that are affected by compartment structure.
    (
        self.nodes,
        self.nseg_per_branch,
        self.nseg,
        self.cumsum_nseg,
        self._internal_node_inds,
    ) = self._set_ncomp(
        ncomp,
        self.nodes,
        self.nodes,
        self.nodes["comp_index"].to_numpy()[0],
        self.nseg_per_branch,
        [c._name for c in self.channels],
        list(chain(*[c.channel_params for c in self.channels])),
        list(chain(*[c.channel_states for c in self.channels])),
        self._radius_generating_fns,
        min_radius,
    )

    # Update the morphology indexing (e.g., `.comp_edges`).
    self.initialize()

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
 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
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.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)])

        # Compartment structure. These arguments have to be rebuilt when `.set_ncomp()`
        # is run.
        self.nseg_per_branch = np.asarray([branch.nseg for branch in branch_list])
        self.nseg = int(np.max(self.nseg_per_branch))
        self.cumsum_nseg = cumsum_leading_zero(self.nseg_per_branch)
        self._internal_node_inds = np.arange(self.cumsum_nseg[-1])

        # Build nodes. Has to be changed when `.set_ncomp()` is run.
        self.nodes = pd.concat([c.nodes for c in branch_list], ignore_index=True)
        self.nodes["comp_index"] = np.arange(self.cumsum_nseg[-1])
        self.nodes["branch_index"] = np.repeat(
            np.arange(self.total_nbranches), self.nseg_per_branch
        ).tolist()
        self.nodes["cell_index"] = np.repeat(0, self.cumsum_nseg[-1]).tolist()

        # Appending general parameters (radius, length, r_a, cm) and channel parameters,
        # as well as the states (v, and channel states).
        self._append_params_and_states(self.cell_params, self.cell_states)

        # 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.
        self.par_inds, self.child_inds, self.child_belongs_to_branchpoint = (
            compute_children_and_parents(self.branch_edges)
        )

        self.initialize()
        self.init_syns()

    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_jaxley_spsolve(self):
        """Initialize morphology for the custom sparse solver.

        Running this function is only required for custom Jaxley solvers, i.e., for
        `voltage_solver={'jaxley.stone', 'jaxley.thomas'}`. However, because at
        `.__init__()` (when the function is run), we do not yet know which solver the
        user will use. Therefore, we always run this function at `.__init__()`.
        """
        children_and_parents = compute_morphology_indices_in_levels(
            len(self.par_inds),
            self.child_belongs_to_branchpoint,
            self.par_inds,
            self.child_inds,
        )
        branchpoint_group_inds = build_branchpoint_group_inds(
            len(self.par_inds),
            self.child_belongs_to_branchpoint,
            self.cumsum_nseg[-1],
        )
        parents = self.comb_parents
        children_inds = children_and_parents["children"]
        parents_inds = children_and_parents["parents"]

        levels = compute_levels(parents)
        children_in_level = compute_children_in_level(levels, children_inds)
        parents_in_level = compute_parents_in_level(levels, self.par_inds, parents_inds)
        levels_and_nseg = pd.DataFrame().from_dict(
            {
                "levels": levels,
                "nsegs": self.nseg_per_branch,
            }
        )
        levels_and_nseg["max_nseg_in_level"] = levels_and_nseg.groupby("levels")[
            "nsegs"
        ].transform("max")
        padded_cumsum_nseg = cumsum_leading_zero(
            levels_and_nseg["max_nseg_in_level"].to_numpy()
        )

        # Generate mapping to deal with the masking which allows using the custom
        # sparse solver to deal with different nseg per branch.
        remapped_node_indices = remap_index_to_masked(
            self._internal_node_inds,
            self.nodes,
            padded_cumsum_nseg,
            self.nseg_per_branch,
        )
        self.solve_indexer = JaxleySolveIndexer(
            cumsum_nseg=padded_cumsum_nseg,
            branchpoint_group_inds=branchpoint_group_inds,
            children_in_level=children_in_level,
            parents_in_level=parents_in_level,
            root_inds=np.asarray([0]),
            remapped_node_indices=remapped_node_indices,
        )

    def _init_morph_jax_spsolve(self):
        """For morphology indexing with the `jax.sparse` voltage volver.

        Explanation of `self._comp_eges['type']`:
        `type == 0`: compartment <--> compartment (within branch)
        `type == 1`: branchpoint --> parent-compartment
        `type == 2`: branchpoint --> child-compartment
        `type == 3`: parent-compartment --> branchpoint
        `type == 4`: child-compartment --> branchpoint

        Running this function is only required for generic sparse solvers, i.e., for
        `voltage_solver='jax.sparse'`.
        """

        # Edges between compartments within the branches.
        self._comp_edges = pd.concat(
            [
                pd.DataFrame()
                .from_dict(
                    {
                        "source": list(range(cumsum_nseg, nseg - 1 + cumsum_nseg))
                        + list(range(1 + cumsum_nseg, nseg + cumsum_nseg)),
                        "sink": list(range(1 + cumsum_nseg, nseg + cumsum_nseg))
                        + list(range(cumsum_nseg, nseg - 1 + cumsum_nseg)),
                    }
                )
                .astype(int)
                for nseg, cumsum_nseg in zip(self.nseg_per_branch, self.cumsum_nseg)
            ]
        )
        self._comp_edges["type"] = 0

        # Edges from branchpoints to compartments.
        branchpoint_to_parent_edges = pd.DataFrame().from_dict(
            {
                "source": np.arange(len(self.par_inds)) + self.cumsum_nseg[-1],
                "sink": self.cumsum_nseg[self.par_inds + 1] - 1,
                "type": 1,
            }
        )
        branchpoint_to_child_edges = pd.DataFrame().from_dict(
            {
                "source": self.child_belongs_to_branchpoint + self.cumsum_nseg[-1],
                "sink": self.cumsum_nseg[self.child_inds],
                "type": 2,
            }
        )
        self._comp_edges = pd.concat(
            [
                self._comp_edges,
                branchpoint_to_parent_edges,
                branchpoint_to_child_edges,
            ],
            ignore_index=True,
        )

        # Edges from compartments to branchpoints.
        parent_to_branchpoint_edges = branchpoint_to_parent_edges.rename(
            columns={"sink": "source", "source": "sink"}
        )
        parent_to_branchpoint_edges["type"] = 3
        child_to_branchpoint_edges = branchpoint_to_child_edges.rename(
            columns={"sink": "source", "source": "sink"}
        )
        child_to_branchpoint_edges["type"] = 4

        self._comp_edges = pd.concat(
            [
                self._comp_edges,
                parent_to_branchpoint_edges,
                child_to_branchpoint_edges,
            ],
            ignore_index=True,
        )

        n_nodes, data_inds, indices, indptr = comp_edges_to_indices(self._comp_edges)
        self._n_nodes = n_nodes
        self._data_inds = data_inds
        self._indices_jax_spsolve = indices
        self._indptr_jax_spsolve = indptr

    @staticmethod
    def update_summed_coupling_conds_jaxley_spsolve(
        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

    def set_ncomp(self, ncomp: int, min_radius: Optional[float] = None):
        """Raise an explict error if `set_ncomp` is set for an entire cell."""
        raise NotImplementedError(
            "`cell.set_ncomp()` is not supported. Loop over all branches with "
            "`for b in range(cell.total_nbranches): cell.branch(b).set_ncomp(n)`."
        )

__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
 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
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.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)])

    # Compartment structure. These arguments have to be rebuilt when `.set_ncomp()`
    # is run.
    self.nseg_per_branch = np.asarray([branch.nseg for branch in branch_list])
    self.nseg = int(np.max(self.nseg_per_branch))
    self.cumsum_nseg = cumsum_leading_zero(self.nseg_per_branch)
    self._internal_node_inds = np.arange(self.cumsum_nseg[-1])

    # Build nodes. Has to be changed when `.set_ncomp()` is run.
    self.nodes = pd.concat([c.nodes for c in branch_list], ignore_index=True)
    self.nodes["comp_index"] = np.arange(self.cumsum_nseg[-1])
    self.nodes["branch_index"] = np.repeat(
        np.arange(self.total_nbranches), self.nseg_per_branch
    ).tolist()
    self.nodes["cell_index"] = np.repeat(0, self.cumsum_nseg[-1]).tolist()

    # Appending general parameters (radius, length, r_a, cm) and channel parameters,
    # as well as the states (v, and channel states).
    self._append_params_and_states(self.cell_params, self.cell_states)

    # 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.
    self.par_inds, self.child_inds, self.child_belongs_to_branchpoint = (
        compute_children_and_parents(self.branch_edges)
    )

    self.initialize()
    self.init_syns()

set_ncomp(ncomp, min_radius=None)

Raise an explict error if set_ncomp is set for an entire cell.

Source code in jaxley/modules/cell.py
322
323
324
325
326
327
def set_ncomp(self, ncomp: int, min_radius: Optional[float] = None):
    """Raise an explict error if `set_ncomp` is set for an entire cell."""
    raise NotImplementedError(
        "`cell.set_ncomp()` is not supported. Loop over all branches with "
        "`for b in range(cell.total_nbranches): cell.branch(b).set_ncomp(n)`."
    )

update_summed_coupling_conds_jaxley_spsolve(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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
@staticmethod
def update_summed_coupling_conds_jaxley_spsolve(
    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
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
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_per_branch = np.concatenate(
            [cell.nseg_per_branch for cell in self.cells]
        )
        self.nseg = int(np.max(self.nseg_per_branch))
        self.cumsum_nseg = cumsum_leading_zero(self.nseg_per_branch)
        self._internal_node_inds = np.arange(self.cumsum_nseg[-1])
        self._append_params_and_states(self.network_params, self.network_states)

        self.nbranches_per_cell = [cell.total_nbranches for cell in self.cells]
        self.total_nbranches = sum(self.nbranches_per_cell)
        self.cumsum_nbranches = cumsum_leading_zero(self.nbranches_per_cell)

        self.nodes = pd.concat([c.nodes for c in cells], ignore_index=True)
        self.nodes["comp_index"] = np.arange(self.cumsum_nseg[-1])
        self.nodes["branch_index"] = np.repeat(
            np.arange(self.total_nbranches), self.nseg_per_branch
        ).tolist()
        self.nodes["cell_index"] = list(
            itertools.chain(
                *[[i] * int(cell.cumsum_nseg[-1]) for i, cell in enumerate(self.cells)]
            )
        )

        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 of both `jax.sparse` and the custom `jaxley` solvers.
        self.par_inds, self.child_inds, self.child_belongs_to_branchpoint = (
            compute_children_and_parents(self.branch_edges)
        )

        # `nbranchpoints` in each cell == cell.par_inds (because `par_inds` are unique).
        nbranchpoints = jnp.asarray([len(cell.par_inds) for cell in self.cells])
        self.cumsum_nbranchpoints_per_cell = cumsum_leading_zero(nbranchpoints)

        # Channels.
        self._gather_channels_from_constituents(cells)

        self.initialize()
        self.init_syns()

    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_jaxley_spsolve(self):
        branchpoint_group_inds = build_branchpoint_group_inds(
            len(self.par_inds),
            self.child_belongs_to_branchpoint,
            self.cumsum_nseg[-1],
        )
        children_in_level = merge_cells(
            self.cumsum_nbranches,
            self.cumsum_nbranchpoints_per_cell,
            [cell.solve_indexer.children_in_level for cell in self.cells],
            exclude_first=False,
        )
        parents_in_level = merge_cells(
            self.cumsum_nbranches,
            self.cumsum_nbranchpoints_per_cell,
            [cell.solve_indexer.parents_in_level for cell in self.cells],
            exclude_first=False,
        )
        padded_cumsum_nseg = cumsum_leading_zero(
            np.concatenate(
                [np.diff(cell.solve_indexer.cumsum_nseg) for cell in self.cells]
            )
        )

        # Generate mapping to dealing with the masking which allows using the custom
        # sparse solver to deal with different nseg per branch.
        remapped_node_indices = remap_index_to_masked(
            self._internal_node_inds,
            self.nodes,
            padded_cumsum_nseg,
            self.nseg_per_branch,
        )
        self.solve_indexer = JaxleySolveIndexer(
            cumsum_nseg=padded_cumsum_nseg,
            branchpoint_group_inds=branchpoint_group_inds,
            children_in_level=children_in_level,
            parents_in_level=parents_in_level,
            root_inds=self.cumsum_nbranches[:-1],
            remapped_node_indices=remapped_node_indices,
        )

    def _init_morph_jax_spsolve(self):
        """Initialize the morphology for networks.

        The reason that this function is a bit involved for a `Network` is that Jaxley
        considers branchpoint nodes to be at the very end of __all__ nodes (i.e. the
        branchpoints of the first cell are even after the compartments of the second
        cell. The reason for this is that, otherwise, `cumsum_nseg` becomes tricky).

        To achieve this, we first loop over all compartments and append them, and then
        loop over all branchpoints and append those. The code for building the indices
        from the `comp_edges` is identical to `jx.Cell`.

        Explanation of `self._comp_eges['type']`:
        `type == 0`: compartment <--> compartment (within branch)
        `type == 1`: branchpoint --> parent-compartment
        `type == 2`: branchpoint --> child-compartment
        `type == 3`: parent-compartment --> branchpoint
        `type == 4`: child-compartment --> branchpoint
        """
        self._cumsum_nseg_per_cell = cumsum_leading_zero(
            jnp.asarray([cell.cumsum_nseg[-1] for cell in self.cells])
        )
        self._comp_edges = pd.DataFrame()

        # Add all the internal nodes.
        for offset, cell in zip(self._cumsum_nseg_per_cell, self.cells):
            condition = cell._comp_edges["type"].to_numpy() == 0
            rows = cell._comp_edges[condition]
            self._comp_edges = pd.concat(
                [self._comp_edges, [offset, offset, 0] + rows], ignore_index=True
            )

        # All branchpoint-to-compartment nodes.
        start_branchpoints = self.cumsum_nseg[-1]  # Index of the first branchpoint.
        for offset, offset_branchpoints, cell in zip(
            self._cumsum_nseg_per_cell, self.cumsum_nbranchpoints_per_cell, self.cells
        ):
            offset_within_cell = cell.cumsum_nseg[-1]
            condition = cell._comp_edges["type"].isin([1, 2])
            rows = cell._comp_edges[condition]
            self._comp_edges = pd.concat(
                [
                    self._comp_edges,
                    [
                        start_branchpoints - offset_within_cell + offset_branchpoints,
                        offset,
                        0,
                    ]
                    + rows,
                ],
                ignore_index=True,
            )

        # All compartment-to-branchpoint nodes.
        for offset, offset_branchpoints, cell in zip(
            self._cumsum_nseg_per_cell, self.cumsum_nbranchpoints_per_cell, self.cells
        ):
            offset_within_cell = cell.cumsum_nseg[-1]
            condition = cell._comp_edges["type"].isin([3, 4])
            rows = cell._comp_edges[condition]
            self._comp_edges = pd.concat(
                [
                    self._comp_edges,
                    [
                        offset,
                        start_branchpoints - offset_within_cell + offset_branchpoints,
                        0,
                    ]
                    + rows,
                ],
                ignore_index=True,
            )

        # Note that, unlike in `cell.py`, we cannot delete `self.cells` here because
        # it is used in plotting.

        # Convert comp_edges to the index format required for `jax.sparse` solvers.
        n_nodes, data_inds, indices, indptr = comp_edges_to_indices(self._comp_edges)
        self._n_nodes = n_nodes
        self._data_inds = data_inds
        self._indices_jax_spsolve = indices
        self._indptr_jax_spsolve = indptr

    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
 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
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_per_branch = np.concatenate(
        [cell.nseg_per_branch for cell in self.cells]
    )
    self.nseg = int(np.max(self.nseg_per_branch))
    self.cumsum_nseg = cumsum_leading_zero(self.nseg_per_branch)
    self._internal_node_inds = np.arange(self.cumsum_nseg[-1])
    self._append_params_and_states(self.network_params, self.network_states)

    self.nbranches_per_cell = [cell.total_nbranches for cell in self.cells]
    self.total_nbranches = sum(self.nbranches_per_cell)
    self.cumsum_nbranches = cumsum_leading_zero(self.nbranches_per_cell)

    self.nodes = pd.concat([c.nodes for c in cells], ignore_index=True)
    self.nodes["comp_index"] = np.arange(self.cumsum_nseg[-1])
    self.nodes["branch_index"] = np.repeat(
        np.arange(self.total_nbranches), self.nseg_per_branch
    ).tolist()
    self.nodes["cell_index"] = list(
        itertools.chain(
            *[[i] * int(cell.cumsum_nseg[-1]) for i, cell in enumerate(self.cells)]
        )
    )

    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 of both `jax.sparse` and the custom `jaxley` solvers.
    self.par_inds, self.child_inds, self.child_belongs_to_branchpoint = (
        compute_children_and_parents(self.branch_edges)
    )

    # `nbranchpoints` in each cell == cell.par_inds (because `par_inds` are unique).
    nbranchpoints = jnp.asarray([len(cell.par_inds) for cell in self.cells])
    self.cumsum_nbranchpoints_per_cell = cumsum_leading_zero(nbranchpoints)

    # Channels.
    self._gather_channels_from_constituents(cells)

    self.initialize()
    self.init_syns()

init_syns()

Initialize synapses.

Source code in jaxley/modules/network.py
258
259
260
261
262
263
264
265
266
267
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
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
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