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

Modules can be traversed and modified using the at, cell, branch, comp, edge, and loc methods. The scope method can be used to toggle between global and local indices. Traversal of Modules will return a View of itself, that has a modified set of attributes, which only consider the part of the Module that is in view.

For developers: The above has consequences for how to operate on Module and which changes take affect where. The following guidelines should be followed (copied from View):

  1. We consider a Module to have everything in view.
  2. Views can display and keep track of how a module is traversed. But(!), do not support making changes or setting variables. This still has to be done in the base Module, i.e. self.base. In order to enssure that these changes only affects whatever is currently in view self._nodes_in_view, or self._edges_in_view among others have to be used. Operating on nodes currently in view can for example be done with self.base.node.loc[self._nodes_in_view].
  3. Every attribute of Module that changes based on what’s in view, i.e. xyzr, needs to modified when View is instantiated. I.e. xyzr of cell.branch(0), should be [self.base.xyzr[0]] This could be achieved via: [self.base.xyzr[b] for b in self._branches_in_view].

For developers: If you want to add a new method to Module, here is an example of how to make methods of Module compatible with View:

.. code-block:: python

# Use data in view to return something.
def count_small_branches(self):
    # no need to use self.base.attr + viewed indices,
    # since no change is made to the attr in question (nodes)
    comp_lens = self.nodes["length"]
    branch_lens = comp_lens.groupby("global_branch_index").sum()
    return np.sum(branch_lens < 10)

# Change data in view.
def change_attr_in_view(self):
    # changes to attrs have to be made via self.base.attr + viewed indices
    a = func1(self.base.attr1[self._cells_in_view])
    b = func2(self.base.attr2[self._edges_in_view])
    self.base.attr3[self._branches_in_view] = a + b
Source code in jaxley/modules/base.py
  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
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
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).

    Modules can be traversed and modified using the `at`, `cell`, `branch`, `comp`,
    `edge`, and `loc` methods. The `scope` method can be used to toggle between
    global and local indices. Traversal of Modules will return a `View` of itself,
    that has a modified set of attributes, which only consider the part of the Module
    that is in view.

    For developers: The above has consequences for how to operate on `Module` and which
    changes take affect where. The following guidelines should be followed (copied from
    `View`):

    1. We consider a Module to have everything in view.
    2. Views can display and keep track of how a module is traversed. But(!),
       do not support making changes or setting variables. This still has to be
       done in the base Module, i.e. `self.base`. In order to enssure that these
       changes only affects whatever is currently in view `self._nodes_in_view`,
       or `self._edges_in_view` among others have to be used. Operating on nodes
       currently in view can for example be done with
       `self.base.node.loc[self._nodes_in_view]`.
    3. Every attribute of Module that changes based on what's in view, i.e. `xyzr`,
       needs to modified when View is instantiated. I.e. `xyzr` of `cell.branch(0)`,
       should be `[self.base.xyzr[0]]` This could be achieved via:
       `[self.base.xyzr[b] for b in self._branches_in_view]`.

    For developers: If you want to add a new method to `Module`, here is an example of
    how to make methods of Module compatible with View:

    .. code-block:: python

        # Use data in view to return something.
        def count_small_branches(self):
            # no need to use self.base.attr + viewed indices,
            # since no change is made to the attr in question (nodes)
            comp_lens = self.nodes["length"]
            branch_lens = comp_lens.groupby("global_branch_index").sum()
            return np.sum(branch_lens < 10)

        # Change data in view.
        def change_attr_in_view(self):
            # changes to attrs have to be made via self.base.attr + viewed indices
            a = func1(self.base.attr1[self._cells_in_view])
            b = func2(self.base.attr2[self._edges_in_view])
            self.base.attr3[self._branches_in_view] = a + b
    """

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

        self.groups = {}

        self.nodes: Optional[pd.DataFrame] = None
        self._scope = "local"  # defaults to local scope
        self._nodes_in_view: np.ndarray = None
        self._edges_in_view: np.ndarray = None

        self.edges = pd.DataFrame(
            columns=[
                "global_edge_index",
                "pre_global_comp_index",
                "post_global_comp_index",
                "pre_locs",
                "post_locs",
                "type",
                "type_ind",
            ]
        )

        self._cumsum_nbranches: Optional[np.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 = {}

        # needs to be set at the end
        self.base: Module = self

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

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

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

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

        # intercepts calls to groups
        if key in self.base.groups:
            view = (
                self.select(self.groups[key])
                if key in self.groups
                else self.select(None)
            )
            view._set_controlled_by_param(key)
            return view

        # intercepts calls to channels
        if key in [c._name for c in self.base.channels]:
            channel_names = [c._name for c in self.channels]
            inds = self.nodes.index[self.nodes[key]].to_numpy()
            view = self.select(inds) if key in channel_names else self.select(None)
            view._set_controlled_by_param(key)
            return view

        # intercepts calls to synapse types
        if key in self.base.synapse_names:
            syn_inds = self.edges[self.edges["type"] == key][
                "global_edge_index"
            ].to_numpy()
            orig_scope = self._scope
            view = (
                self.scope("global").edge(syn_inds).scope(orig_scope)
                if key in self.synapse_names
                else self.select(None)
            )
            view._set_controlled_by_param(key)  # overwrites param set by edge
            # Ensure synapse param sharing works with `edge`
            # `edge` will be removed as part of #463
            view.edges["local_edge_index"] = np.arange(len(view.edges))
            return view

    def _childviews(self) -> List[str]:
        """Returns levels that module can be viewed at.

        I.e. for net -> [cell, branch, comp]. For branch -> [comp]"""
        levels = ["network", "cell", "branch", "comp"]
        if self._current_view in levels:
            children = levels[levels.index(self._current_view) + 1 :]
            return children
        return []

    def _has_childview(self, key: str) -> bool:
        child_views = self._childviews()
        return key in child_views

    def __getitem__(self, index):
        """Lazy indexing of the module."""
        supported_parents = ["network", "cell", "branch"]  # cannot index into comp

        not_group_view = self._current_view not in self.groups
        assert (
            self._current_view in supported_parents or not_group_view
        ), "Lazy indexing is only supported for `Network`, `Cell`, `Branch` and Views thereof."
        index = index if isinstance(index, tuple) else (index,)

        child_views = self._childviews()
        assert len(index) <= len(child_views), "Too many indices."
        view = self
        for i, child in zip(index, child_views):
            view = view._at_nodes(child, i)
        return view

    def _update_local_indices(self) -> pd.DataFrame:
        """Compute local indices from the global indices that are in view.
        This is recomputed everytime a View is created."""
        rerank = lambda df: df.rank(method="dense").astype(int) - 1

        def reorder_cols(
            df: pd.DataFrame, cols: List[str], first: bool = True
        ) -> pd.DataFrame:
            """Move cols to front/back.

            Args:
                df: DataFrame to reorder.
                cols: List of columns to place before/after remaining columns.
                first: If True, cols are placed in front, otherwise at the end.

            Returns:
                DataFrame with reordered columns."""
            new_cols = [col for col in df.columns if first == (col in cols)]
            new_cols += [col for col in df.columns if first != (col in cols)]
            return df[new_cols]

        def reindex_a_by_b(
            df: pd.DataFrame, a: str, b: Optional[Union[str, List[str]]] = None
        ) -> pd.DataFrame:
            """Reindex based on a different col or several columns
            for b=[0,0,1,1,2,2,2] -> a=[0,1,0,1,0,1,2]"""
            grouped_df = df.groupby(b) if b is not None else df
            df.loc[:, a] = rerank(grouped_df[a])
            return df

        index_names = ["cell_index", "branch_index", "comp_index"]  # order is important
        global_idx_cols = [f"global_{name}" for name in index_names]
        local_idx_cols = [f"local_{name}" for name in index_names]
        idcs = self.nodes[global_idx_cols]

        # update local indices of nodes
        idcs = reindex_a_by_b(idcs, global_idx_cols[0])
        idcs = reindex_a_by_b(idcs, global_idx_cols[1], global_idx_cols[0])
        idcs = reindex_a_by_b(idcs, global_idx_cols[2], global_idx_cols[:2])
        idcs.columns = [col.replace("global", "local") for col in global_idx_cols]
        self.nodes[local_idx_cols] = idcs[local_idx_cols].astype(int)

        # move indices to the front of the dataframe; move controlled_by_param to the end
        # move indices of current scope to the front and the others to the back
        not_scope = "global" if self._scope == "local" else "local"
        self.nodes = reorder_cols(
            self.nodes, [f"{self._scope}_{name}" for name in index_names], first=True
        )
        self.nodes = reorder_cols(
            self.nodes, [f"{not_scope}_{name}" for name in index_names], first=False
        )

        self.edges = reorder_cols(self.edges, ["global_edge_index"])
        self.nodes = reorder_cols(self.nodes, ["controlled_by_param"], first=False)
        self.edges = reorder_cols(self.edges, ["controlled_by_param"], first=False)

    def _init_view(self):
        """Init attributes critical for View.

        Needs to be called at init of a Module."""
        parent = self.__class__.__name__.lower()
        self._current_view = "comp" if parent == "compartment" else parent
        self._nodes_in_view = self.nodes.index.to_numpy()
        self._edges_in_view = self.edges.index.to_numpy()
        self.nodes["controlled_by_param"] = 0

    def _compute_coords_of_comp_centers(self) -> np.ndarray:
        """Compute xyz coordinates of compartment centers.

        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 ncomps = [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.
        """
        nodes_by_branches = self.nodes.groupby("global_branch_index")
        ncomps = nodes_by_branches["global_comp_index"].nunique().to_numpy()

        comp_ends = [
            np.linspace(0, 1, ncomp + 1) + 2 * i for i, ncomp in enumerate(ncomps)
        ]
        comp_ends = np.hstack(comp_ends)

        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_ncomps = np.cumsum(ncomps)
        # this means centers between comps have to be removed here
        between_comp_inds = (cum_ncomps + np.arange(len(cum_ncomps)))[:-1]
        centers = np.delete(centers, between_comp_inds, axis=0)
        return centers

    def compute_compartment_centers(self):
        """Add compartment centers to nodes dataframe"""
        centers = self._compute_coords_of_comp_centers()
        self.base.nodes.loc[self._nodes_in_view, ["x", "y", "z"]] = centers

    def _reformat_index(self, idx: Any, dtype: type = int) -> np.ndarray:
        """Transforms different types of indices into an array.

        Takes slice, list, array, ints, range and None and transforms
        it into array of indices. If index == "all" it returns "all"
        to be handled downstream.

        Args:
            idx: index that specifies at which locations to view the module.
            dtype: defaults to int, but can also reformat float for use in `loc`

        Returns:
            array of indices of shape (N,)"""
        if is_str_all(idx):  # also asserts that the only allowed str == "all"
            return idx

        np_dtype = np.int64 if dtype is int else np.float64
        idx = np.array([], dtype=dtype) if idx is None else idx
        idx = np.array([idx]) if isinstance(idx, (dtype, np_dtype)) else idx
        idx = np.array(idx) if isinstance(idx, (list, range, pd.Index)) else idx

        idx = np.arange(len(self.base.nodes))[idx] if isinstance(idx, slice) else idx
        if idx.dtype == bool:
            shape = (*self.shape, len(self.edges))
            which_idx = len(idx) == np.array(shape)
            assert np.any(which_idx), "Index not matching num of cells/branches/comps."
            dim = shape[np.where(which_idx)[0][0]]
            idx = np.arange(dim)[idx]
        assert isinstance(idx, np.ndarray), "Invalid type"
        assert idx.dtype in [np_dtype, bool], "Invalid dtype"
        return idx.reshape(-1)

    def _set_controlled_by_param(self, key: str):
        """Determines which parameters are shared in `make_trainable`.

        Adds column to nodes/edges dataframes to read of shared params from.

        Args:
            key: key specifying group / view that is in control of the params."""
        if key in ["comp", "branch", "cell"]:
            self.nodes["controlled_by_param"] = self.nodes[f"global_{key}_index"]
            self.edges["controlled_by_param"] = 0
        elif key == "edge":
            self.edges["controlled_by_param"] = np.arange(len(self.edges))
        elif key == "filter":
            self.nodes["controlled_by_param"] = np.arange(len(self.nodes))
            self.edges["controlled_by_param"] = np.arange(len(self.edges))
        else:
            self.nodes["controlled_by_param"] = 0
            self.edges["controlled_by_param"] = 0
        self._current_view = key

    def select(
        self, nodes: np.ndarray = None, edges: np.ndarray = None, sorted: bool = False
    ) -> View:
        """Return View of the module filtered by specific node or edges indices.

        Args:
            nodes: indices of nodes to view. If None, all nodes are viewed.
            edges: indices of edges to view. If None, all edges are viewed.
            sorted: if True, nodes and edges are sorted.

        Returns:
            View for subset of selected nodes and/or edges."""

        nodes = self._reformat_index(nodes) if nodes is not None else None
        nodes = self._nodes_in_view if is_str_all(nodes) else nodes
        nodes = np.sort(nodes) if sorted else nodes

        edges = self._reformat_index(edges) if edges is not None else None
        edges = self._edges_in_view if is_str_all(edges) else edges
        edges = np.sort(edges) if sorted else edges

        view = View(self, nodes, edges)
        view._set_controlled_by_param("filter")
        return view

    def set_scope(self, scope: str):
        """Toggle between "global" or "local" scope.

        Determines if global or local indices are used for viewing the module.

        Args:
            scope: either "global" or "local"."""
        assert scope in ["global", "local"], "Invalid scope."
        self._scope = scope

    def scope(self, scope: str) -> View:
        """Return a View of the module with the specified scope.

        For example `cell.scope("global").branch(2).scope("local").comp(1)`
        will return the 1st compartment of branch 2.

        Args:
            scope: either "global" or "local".

        Returns:
            View with the specified scope."""
        view = self.view
        view.set_scope(scope)
        return view

    def _at_nodes(self, key: str, idx: Any) -> View:
        """Return a View of the module filtering `nodes` by specified key and index.

        Keys can be `cell`, `branch`, `comp` and determine which index is used to filter.
        """
        base_name = self.base.__class__.__name__
        assert self.base._has_childview(key), f"{base_name} does not support {key}."
        idx = self._reformat_index(idx)
        idx = self.nodes[self._scope + f"_{key}_index"] if is_str_all(idx) else idx
        where = self.nodes[self._scope + f"_{key}_index"].isin(idx)
        inds = self.nodes.index[where].to_numpy()

        view = View(self, nodes=inds)
        view._set_controlled_by_param(key)
        return view

    def _at_edges(self, key: str, idx: Any) -> View:
        """Return a View of the module filtering `edges` by specified key and index.

        Keys can be `pre`, `post`, `edge` and determine which index is used to filter.
        """
        idx = self._reformat_index(idx)
        idx = self.edges[self._scope + f"_{key}_index"] if is_str_all(idx) else idx
        where = self.edges[self._scope + f"_{key}_index"].isin(idx)
        inds = self.edges.index[where].to_numpy()

        view = View(self, edges=inds)
        view._set_controlled_by_param(key)
        return view

    def cell(self, idx: Any) -> View:
        """Return a View of the module at the selected cell(s).

        Args:
            idx: index of the cell to view.

        Returns:
            View of the module at the specified cell index."""
        return self._at_nodes("cell", idx)

    def branch(self, idx: Any) -> View:
        """Return a View of the module at the selected branches(s).

        Args:
            idx: index of the branch to view.

        Returns:
            View of the module at the specified branch index."""
        return self._at_nodes("branch", idx)

    def comp(self, idx: Any) -> View:
        """Return a View of the module at the selected compartments(s).

        Args:
            idx: index of the comp to view.

        Returns:
            View of the module at the specified compartment index."""
        return self._at_nodes("comp", idx)

    def edge(self, idx: Any) -> View:
        """Return a View of the module at the selected synapse edges(s).

        Args:
            idx: index of the edge to view.

        Returns:
            View of the module at the specified edge index."""
        return self._at_edges("edge", idx)

    def loc(self, at: Any) -> View:
        """Return a View of the module at the selected branch location(s).

        Args:
            at: location along the branch.

        Returns:
            View of the module at the specified branch location."""
        global_comp_idxs = []
        for i in self._branches_in_view:
            ncomp = self.base.ncomp_per_branch[i]
            comp_locs = np.linspace(0, 1, ncomp)
            at = comp_locs if is_str_all(at) else self._reformat_index(at, dtype=float)
            comp_edges = np.linspace(0, 1 + 1e-10, ncomp + 1)
            idx = np.digitize(at, comp_edges) - 1 + self.base.cumsum_ncomp[i]
            global_comp_idxs.append(idx)
        global_comp_idxs = np.concatenate(global_comp_idxs)
        orig_scope = self._scope
        # global scope needed to select correct comps, for i.e. branches w. ncomp=[1,2]
        # loc(0.9)  will correspond to different local branches (0 vs 1).
        view = self.scope("global").comp(global_comp_idxs).scope(orig_scope)
        view._current_view = "loc"
        return view

    @property
    def _comps_in_view(self):
        """Lists the global compartment indices which are currently part of the view."""
        # method also exists in View. this copy forgoes need to instantiate a View
        return self.nodes["global_comp_index"].unique()

    @property
    def _branches_in_view(self):
        """Lists the global branch indices which are currently part of the view."""
        # method also exists in View. this copy forgoes need to instantiate a View
        return self.nodes["global_branch_index"].unique()

    @property
    def _cells_in_view(self):
        """Lists the global cell indices which are currently part of the view."""
        # method also exists in View. this copy forgoes need to instantiate a View
        return self.nodes["global_cell_index"].unique()

    def _iter_submodules(self, name: str):
        """Iterate over submoduleslevel.

        Used for `cells`, `branches`, `comps`."""
        col = self._scope + f"_{name}_index"
        idxs = self.nodes[col].unique()
        for idx in idxs:
            yield self._at_nodes(name, idx)

    @property
    def cells(self):
        """Iterate over all cells in the module.

        Returns a generator that yields a View of each cell."""
        yield from self._iter_submodules("cell")

    @property
    def branches(self):
        """Iterate over all branches in the module.

        Returns a generator that yields a View of each branch."""
        yield from self._iter_submodules("branch")

    @property
    def comps(self):
        """Iterate over all compartments in the module.
        Can be called on any module, i.e. `net.comps`, `cell.comps` or
        `branch.comps`. `__iter__` does not allow for this.

        Returns a generator that yields a View of each compartment."""
        yield from self._iter_submodules("comp")

    def __iter__(self):
        """Iterate over parts of the module.

        Internally calls `cells`, `branches`, `comps` at the appropriate level.

        Example:

        .. code-block:: python

            for cell in network:
                for branch in cell:
                    for comp in branch:
                        print(comp.nodes.shape)
        """
        next_level = self._childviews()[0]
        yield from self._iter_submodules(next_level)

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

        .. code-block:: python

            network.shape = (num_cells, num_branches, num_compartments)
            cell.shape = (num_branches, num_compartments)
            branch.shape = (num_compartments,)
        """
        cols = ["global_cell_index", "global_branch_index", "global_comp_index"]
        raw_shape = self.nodes[cols].nunique().to_list()

        # ensure (net.shape -> dim=3, cell.shape -> dim=2, branch.shape -> dim=1, comp.shape -> dim=0)
        levels = ["network", "cell", "branch", "comp"]
        module = self.base.__class__.__name__.lower()
        module = "comp" if module == "compartment" else module
        shape = tuple(raw_shape[levels.index(module) :])
        return shape

    def copy(
        self, reset_index: bool = False, as_module: bool = False
    ) -> Union[Module, View]:
        """Extract part of a module and return a copy of its View or a new module.

        This can be used to call `jx.integrate` on part of a Module.

        Args:
            reset_index: if True, the indices of the new module are reset to start from 0.
            as_module: if True, a new module is returned instead of a View.

        Returns:
            A part of the module or a copied view of it."""
        view = deepcopy(self)
        warnings.warn("This method is experimental, use at your own risk.")
        # TODO FROM #447: add reset_index, i.e. for parents, nodes, edges etc. such that they
        # start from 0/-1 and are contiguous
        if as_module:
            raise NotImplementedError("Not yet implemented.")
            # initialize a new module with the same attributes
        return view

    @property
    def view(self):
        """Return view of the module."""
        return View(self, self._nodes_in_view, self._edges_in_view)

    @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.base.nodes[param_name] = param_value
        for state_name, state_value in state_dict.items():
            self.base.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.base.channels.append(channel)
                if channel.current_name not in self.membrane_current_names:
                    self.base.membrane_current_names.append(channel.current_name)
        # Setting columns of channel names to `False` instead of `NaN`.
        for channel in self.base.channels:
            name = channel._name
            self.base.nodes.loc[self.nodes[name].isna(), name] = False

    @only_allow_module
    def to_jax(self):
        # TODO FROM #447: Make this work for View?
        """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.base.jaxnodes = {}
        for key, value in self.base.nodes.to_dict(orient="list").items():
            inds = jnp.arange(len(value))
            self.base.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.base.jaxedges = {}
        edges = self.base.edges.to_dict(orient="list")
        for i, synapse in enumerate(self.base.synapses):
            condition = np.asarray(edges["type_ind"]) == i
            for key in synapse.synapse_params:
                self.base.jaxedges[key] = jnp.asarray(np.asarray(edges[key])[condition])
            for key in synapse.synapse_states:
                self.base.jaxedges[key] = jnp.asarray(np.asarray(edges[key])[condition])

    def show(
        self,
        param_names: Optional[Union[str, List[str]]] = None,
        *,
        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.
            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.
        """
        nodes = self.nodes.copy()  # prevents this from being edited

        cols = []
        inds = ["comp_index", "branch_index", "cell_index"]
        scopes = ["local", "global"]
        inds = [f"{s}_{i}" for i in inds for s in scopes] if indices else []
        cols += inds
        cols += [ch._name for ch in self.channels] if channel_names else []
        cols += (
            sum([list(ch.channel_params) for ch in self.channels], []) if params else []
        )
        cols += (
            sum([list(ch.channel_states) for ch in self.channels], []) if states else []
        )

        if not param_names is None:
            cols = (
                inds + [c for c in cols if c in param_names]
                if params
                else list(param_names)
            )

        return nodes[cols]

    @only_allow_module
    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 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))`.
        """
        if key in self.nodes.columns:
            not_nan = ~self.nodes[key].isna().to_numpy()
            self.base.nodes.loc[self._nodes_in_view[not_nan], key] = val
        elif key in self.edges.columns:
            not_nan = ~self.edges[key].isna().to_numpy()
            self.base.edges.loc[self._edges_in_view[not_nan], key] = val
        else:
            raise KeyError(f"Key '{key}' not found in nodes or edges")

    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.
        """
        # Note: `data_set` does not support arrays for `val`.
        is_node_param = key in self.nodes.columns
        data = self.nodes if is_node_param else self.edges
        viewed_inds = self._nodes_in_view if is_node_param else self._edges_in_view
        if key in data.columns:
            not_nan = ~data[key].isna()
            added_param_state = [
                {
                    "indices": np.atleast_2d(viewed_inds[not_nan]),
                    "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,
        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.
            min_radius: Only used if the morphology was read from an SWC file. If passed
                the radius is capped to be at least this value.

        Raises:
            - 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.base.externals) == 0, "No stimuli allowed!"
        assert len(self.base.recordings) == 0, "No recordings allowed!"
        assert len(self.base.trainable_params) == 0, "No trainables allowed!"

        assert self.base._module_type != "network", "This is not allowed for networks."
        assert not (
            self.base._module_type == "cell"
            and len(self._branches_in_view) == len(self.base._branches_in_view)
        ), "This is not allowed for cells."

        # Update all attributes that are affected by compartment structure.
        view = self.nodes.copy()
        all_nodes = self.base.nodes
        start_idx = self.nodes["global_comp_index"].to_numpy()[0]
        ncomp_per_branch = self.base.ncomp_per_branch
        channel_names = [c._name for c in self.base.channels]
        channel_param_names = list(
            chain(*[c.channel_params for c in self.base.channels])
        )
        channel_state_names = list(
            chain(*[c.channel_states for c in self.base.channels])
        )
        radius_generating_fns = self.base._radius_generating_fns

        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["global_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 (self.nodes[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 (
            self.nodes[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 = self.nodes.mean(skipna=False)
        average_row = average_row.to_frame().T
        view = pd.concat([*[average_row] * ncomp], axis="rows")

        # Set the correct datatype after having performed an average which cast
        # everything to float.
        integer_cols = ["global_cell_index", "global_branch_index", "global_comp_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,
                ncomp=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["global_comp_index"] = np.arange(len(all_nodes))

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

        self.base.nodes = all_nodes
        self.base.ncomp_per_branch = ncomp_per_branch
        self.base.ncomp = ncomp
        self.base.cumsum_ncomp = cumsum_ncomp
        self.base._internal_node_inds = internal_node_inds

        # Update the morphology indexing (e.g., `.comp_edges`).
        self.base._initialize()
        self.base._init_view()
        self.base._update_local_indices()

    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 (
            self.allow_make_trainable
        ), "network.cell('all').make_trainable() is not supported. Use a for-loop over cells."
        ncomps_per_branch = (
            self.base.nodes["global_branch_index"].value_counts().to_numpy()
        )
        assert np.all(
            ncomps_per_branch == ncomps_per_branch[0]
        ), "Parameter sharing is not allowed for modules containing branches with different numbers of compartments."

        data = self.nodes if key in self.nodes.columns else None
        data = self.edges if key in self.edges.columns else data

        assert data is not None, f"Key '{key}' not found in nodes or edges"
        not_nan = ~data[key].isna()
        data = data.loc[not_nan]
        assert (
            len(data) > 0
        ), "No settable parameters found in the selected compartments."

        grouped_view = data.groupby("controlled_by_param")
        # Because of this `x.index.values` we cannot support `make_trainable()` on
        # the module level for synapse parameters (but only for `SynapseView`).
        inds_of_comps = list(
            grouped_view.apply(lambda x: x.index.values, include_groups=False)
        )
        indices_per_param = jnp.stack(inds_of_comps)
        # Sorted inds are only used to infer the correct starting values.
        param_vals = jnp.asarray(
            [data.loc[inds, key].to_numpy() for inds in inds_of_comps]
        )

        # 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.base.trainable_params.append({key: new_params})
        self.base.indices_set_by_trainables.append(indices_per_param)
        self.base.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.base.num_trainable_params}"
            )

    def write_trainables(self, trainable_params: List[Dict[str, jnp.ndarray]]):
        """Write the trainables into `.nodes` and `.edges`.

        This allows to, e.g., visualize trained networks with `.vis()`.

        Args:
            trainable_params: The trainable parameters returned by `get_parameters()`.
        """
        # We do not support views. Why? `jaxedges` does not have any NaN
        # elements, whereas edges does. Because of this, we already need special
        # treatment to make this function work, and it would be an even bigger hassle
        # if we wanted to support this.
        assert self.__class__.__name__ in [
            "Compartment",
            "Branch",
            "Cell",
            "Network",
        ], "Only supports modules."

        # We could also implement this without casting the module to jax.
        # However, I think it allows us to reuse as much code as possible and it avoids
        # any kind of issues with indexing or parameter sharing (as this is fully
        # taken care of by `get_all_parameters()`).
        self.base.to_jax()
        pstate = params_to_pstate(trainable_params, self.base.indices_set_by_trainables)
        all_params = self.base.get_all_parameters(pstate, voltage_solver="jaxley.stone")

        # The value for `delta_t` does not matter here because it is only used to
        # compute the initial current. However, the initial current cannot be made
        # trainable and so its value never gets used below.
        all_states = self.base.get_all_states(pstate, all_params, delta_t=0.025)

        # Loop only over the keys in `pstate` to avoid unnecessary computation.
        for parameter in pstate:
            key = parameter["key"]
            if key in self.base.nodes.columns:
                vals_to_set = all_params if key in all_params.keys() else all_states
                self.base.nodes[key] = vals_to_set[key]

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

    def distance(self, endpoint: "View") -> float:
        """Return the direct distance between two compartments.
        This does not compute the pathwise distance (which is currently not
        implemented).
        Args:
            endpoint: The compartment to which to compute the distance to.
        """
        assert len(self.xyzr) == 1 and len(endpoint.xyzr) == 1
        start_xyz = np.mean(self.xyzr[0][:, :3], axis=0)
        end_xyz = np.mean(endpoint.xyzr[0][:, :3], axis=0)
        return np.sqrt(np.sum((start_xyz - end_xyz) ** 2))

    def delete_trainables(self):
        """Removes all trainable parameters from the module."""

        if isinstance(self, View):
            trainables_and_inds = self._filter_trainables(is_viewed=False)
            self.base.indices_set_by_trainables = trainables_and_inds[0]
            self.base.trainable_params = trainables_and_inds[1]
            self.base.num_trainable_params -= self.num_trainable_params
        else:
            self.base.indices_set_by_trainables = []
            self.base.trainable_params = []
            self.base.num_trainable_params = 0
        self._update_view()

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

        Groups can then be indexed. For example:

        .. code-block:: python

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

        Args:
            group_name: The name of the group.
        """
        if group_name not in self.base.groups:
            self.base.groups[group_name] = self._nodes_in_view
        else:
            self.base.groups[group_name] = np.unique(
                np.concatenate([self.base.groups[group_name], self._nodes_in_view])
            )

    def _get_state_names(self) -> Tuple[List, List]:
        """Collect all recordable / clampable states in the membrane and synapses.

        Returns states seperated by comps and edges."""
        channel_states = [name for c in self.channels for name in c.channel_states]
        synapse_states = [name for s in self.synapses for name in s.synapse_states]
        membrane_states = ["v", "i"] + self.membrane_current_names
        return channel_states + membrane_states, synapse_states

    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

    @only_allow_module
    def get_all_parameters(
        self, pstate: List[Dict], voltage_solver: str
    ) -> Dict[str, jnp.ndarray]:
        # TODO FROM #447: MAKE THIS WORK FOR VIEW?
        """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()`.

        .. code-block:: python

            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.base.jaxnodes[key]

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

        for synapse_params in self.base.synapse_param_names:
            params[synapse_params] = self.base.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"]

            # This is needed since SynapseViews worked differently before.
            # This mimics the old behaviour and tranformes the new indices
            # to the old indices.
            # TODO FROM #447: Longterm this should be gotten rid of.
            # Instead edges should work similar to nodes (would also allow for
            # param sharing).
            synapse_inds = self.base.edges.groupby("type").rank()["global_edge_index"]
            synapse_inds = (synapse_inds.astype(int) - 1).to_numpy()
            if key in self.base.synapse_param_names:
                inds = synapse_inds[inds]

            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.base._compute_axial_conductances(
            params=params
        )
        return params

    @only_allow_module
    def _get_states_from_nodes_and_edges(self) -> Dict[str, jnp.ndarray]:
        # TODO FROM #447: MAKE THIS WORK FOR VIEW?
        """Return states as they are set in the `.nodes` and `.edges` tables."""
        self.base.to_jax()  # Create `.jaxnodes` from `.nodes` and `.jaxedges` from `.edges`.
        states = {"v": self.base.jaxnodes["v"]}
        # Join node and edge states into a single state dictionary.
        for channel in self.base.channels:
            for channel_states in channel.channel_states:
                states[channel_states] = self.base.jaxnodes[channel_states]
        for synapse_states in self.base.synapse_state_names:
            states[synapse_states] = self.base.jaxedges[synapse_states]
        return states

    @only_allow_module
    def get_all_states(
        self, pstate: List[Dict], all_params, delta_t: float
    ) -> Dict[str, jnp.ndarray]:
        # TODO FROM #447: MAKE THIS WORK FOR VIEW?
        """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.base._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.base._channel_currents(
            states, delta_t, self.channels, self.nodes, all_params
        )

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

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

    def _initialize(self):
        """Initialize the module."""
        self._init_morph()
        return self

    @only_allow_module
    def init_states(self, delta_t: float = 0.025):
        # TODO FROM #447: MAKE THIS WORK FOR VIEW?
        """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.base.nodes
        states = self.base._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.base.get_all_parameters([], voltage_solver="jaxley.thomas")

        for channel in self.base.channels:
            name = channel._name
            channel_indices = channel_nodes.loc[channel_nodes[name]][
                "global_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["ncomp"],
                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["ncomp"], nbranches))
        return solves
        ```
        """
        # For scipy and jax.scipy.
        row_and_col_inds = compute_morphology_indices(
            len(self.base._par_inds),
            self.base._child_belongs_to_branchpoint,
            self.base._par_inds,
            self.base._child_inds,
            self.base.ncomp,
            self.base.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.base.debug_states["row_inds"] = row_and_col_inds["row_inds"]
        self.base.debug_states["col_inds"] = row_and_col_inds["col_inds"]
        self.base.debug_states["data_inds"] = data_inds
        self.base.debug_states["indices"] = indices
        self.base.debug_states["indptr"] = indptr

        self.base.debug_states["ncomp"] = self.base.ncomp
        self.base.debug_states["child_inds"] = self.base._child_inds
        self.base.debug_states["par_inds"] = self.base._par_inds

    def record(self, state: str = "v", verbose=True):
        comp_states, edge_states = self._get_state_names()
        if state not in comp_states + edge_states:
            raise KeyError(f"{state} is not a recognized state in this module.")
        in_view = self._nodes_in_view if state in comp_states else self._edges_in_view

        new_recs = pd.DataFrame(in_view, columns=["rec_index"])
        new_recs["state"] = state
        self.base.recordings = pd.concat([self.base.recordings, new_recs])
        has_duplicates = self.base.recordings.duplicated()
        self.base.recordings = self.base.recordings.loc[~has_duplicates]
        if verbose:
            print(
                f"Added {len(in_view)-sum(has_duplicates)} recordings. See `.recordings` for details."
            )

    def _update_view(self):
        """Update the attrs of the view after changes in the base module."""
        if isinstance(self, View):
            scope = self._scope
            current_view = self._current_view
            # copy dict of new View. For some reason doing self = View(self)
            # did not work.
            self.__dict__ = View(
                self.base, self._nodes_in_view, self._edges_in_view
            ).__dict__

            # retain the scope and current_view of the previous view
            self._scope = scope
            self._current_view = current_view

    def delete_recordings(self):
        """Removes all recordings from the module."""
        if isinstance(self, View):
            base_recs = self.base.recordings
            self.base.recordings = base_recs[
                ~base_recs.isin(self.recordings).all(axis=1)
            ]
            self._update_view()
        else:
            self.base.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, 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.
        """
        self._external_input(state_name, state_array, verbose=verbose)

    def _external_input(
        self,
        key: str,
        values: Optional[jnp.ndarray],
        verbose: bool = True,
    ):
        comp_states, edge_states = self._get_state_names()
        if key not in comp_states + edge_states:
            raise KeyError(f"{key} is not a recognized state in this module.")
        values = values if values.ndim == 2 else jnp.expand_dims(values, axis=0)
        batch_size = values.shape[0]
        num_inserted = (
            len(self._nodes_in_view) if key in comp_states else len(self._edges_in_view)
        )
        is_multiple = num_inserted == batch_size
        values = values if is_multiple else jnp.repeat(values, num_inserted, axis=0)
        assert batch_size in [
            1,
            num_inserted,
        ], "Number of comps and stimuli do not match."

        if key in self.base.externals.keys():
            self.base.externals[key] = jnp.concatenate(
                [self.base.externals[key], values]
            )
            self.base.external_inds[key] = jnp.concatenate(
                [self.base.external_inds[key], self._nodes_in_view]
            )
        else:
            if key in comp_states:
                self.base.externals[key] = values
                self.base.external_inds[key] = self._nodes_in_view
            else:
                self.base.externals[key] = values
                self.base.external_inds[key] = self._edges_in_view
        if verbose:
            print(
                f"Added {num_inserted} 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_external_input(
            "i", current, data_stimuli, self.nodes, verbose=verbose
        )

    def data_clamp(
        self,
        state_name: str,
        state_array: jnp.ndarray,
        data_clamps: Optional[Tuple[jnp.ndarray, pd.DataFrame]] = None,
        verbose: bool = False,
    ):
        """Insert a clamp into the module within jit (or grad).

        Args:
            state_name: Name of the state variable to set.
            state_array: Time series of the state variable in the default Jaxley unit.
                State array should be of shape (num_clamps, simulation_time) or
                (simulation_time, ) for a single clamp.
            verbose: Whether or not to print the number of inserted clamps. `False`
                by default because this method is meant to be jitted.
        """
        comp_states, edge_states = self._get_state_names()
        if state_name not in comp_states + edge_states:
            raise KeyError(f"{state_name} is not a recognized state in this module.")
        data = self.nodes if state_name in comp_states else self.edges
        return self._data_external_input(
            state_name, state_array, data_clamps, data, verbose=verbose
        )

    def _data_external_input(
        self,
        state_name: str,
        state_array: jnp.ndarray,
        data_external_input: Optional[Tuple[jnp.ndarray, pd.DataFrame]],
        view: pd.DataFrame,
        verbose: bool = False,
    ):
        comp_states, edge_states = self._get_state_names()
        state_array = (
            state_array
            if state_array.ndim == 2
            else jnp.expand_dims(state_array, axis=0)
        )
        batch_size = state_array.shape[0]
        num_inserted = (
            len(self._nodes_in_view)
            if state_name in comp_states
            else len(self._edges_in_view)
        )
        is_multiple = num_inserted == batch_size
        state_array = (
            state_array
            if is_multiple
            else jnp.repeat(state_array, num_inserted, axis=0)
        )
        assert batch_size in [
            1,
            num_inserted,
        ], "Number of comps and clamps do not match."

        if data_external_input is not None:
            external_input = data_external_input[1]
            external_input = jnp.concatenate([external_input, state_array])
            inds = data_external_input[2]
        else:
            external_input = state_array
            inds = pd.DataFrame().from_dict({})

        inds = pd.concat([inds, view])

        if verbose:
            if state_name == "i":
                print(f"Added {len(view)} stimuli.")
            else:
                print(f"Added {len(view)} clamps.")

        return (state_name, external_input, inds)

    def delete_stimuli(self):
        """Removes all stimuli from the module."""
        self.delete_clamps("i")

    def delete_clamps(self, state_name: Optional[str] = None):
        """Removes all clamps of the given state from the module."""
        all_externals = list(self.externals.keys())
        if "i" in all_externals:
            all_externals.remove("i")
        state_names = all_externals if state_name is None else [state_name]
        for state_name in state_names:
            if state_name in self.externals:
                keep_inds = ~np.isin(
                    self.base.external_inds[state_name], self._nodes_in_view
                )
                base_exts = self.base.externals
                base_exts_inds = self.base.external_inds
                if np.all(~keep_inds):
                    base_exts.pop(state_name, None)
                    base_exts_inds.pop(state_name, None)
                else:
                    base_exts[state_name] = base_exts[state_name][keep_inds]
                    base_exts_inds[state_name] = base_exts_inds[state_name][keep_inds]
                self._update_view()
            else:
                pass  # does not have to be deleted if not in externals

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

        Args:
            channel: The channel to insert."""
        name = channel._name

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

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

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

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

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

    def delete_channel(self, channel: Channel):
        """Remove a channel from the module.

        Args:
            channel: The channel to remove."""
        name = channel._name
        channel_names = [c._name for c in self.channels]
        all_channel_names = [c._name for c in self.base.channels]
        if name in channel_names:
            channel_cols = list(channel.channel_params.keys())
            channel_cols += list(channel.channel_states.keys())
            self.base.nodes.loc[self._nodes_in_view, channel_cols] = float("nan")
            self.base.nodes.loc[self._nodes_in_view, name] = False

            # only delete cols if no other comps in the module have the same channel
            if np.all(~self.base.nodes[name]):
                self.base.channels.pop(all_channel_names.index(name))
                self.base.membrane_current_names.remove(channel.current_name)
                self.base.nodes.drop(columns=channel_cols + [name], inplace=True)
        else:
            raise ValueError(f"Channel {name} not found in the module.")

    @only_allow_module
    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
        if "i" in externals.keys():
            i_current = externals["i"]
            i_inds = external_inds["i"]
            i_ext = self._get_external_input(
                voltages, i_inds, i_current, params["radius"], params["length"]
            )
        else:
            i_ext = 0.0

        # 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()),
                    "ncomp_per_branch": self.ncomp_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["global_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]][
                "global_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]

            # * 1000 to convert from mA/cm^2 to uA/cm^2.
            voltage_terms = voltage_terms.at[indices].add(voltage_term * 1000.0)
            constant_terms = constant_terms.at[indices].add(-constant_term * 1000.0)

            # 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.
        """
        if "comp" in type.lower():
            return plot_comps(self, dims=dims, ax=ax, col=col, **morph_plot_kwargs)
        if "morph" in type.lower():
            return plot_morph(self, dims=dims, ax=ax, col=col, **morph_plot_kwargs)

        assert not np.any(
            [np.isnan(xyzr[:, dims]).all() for xyzr in self.xyzr]
        ), "No coordinates available. Use `vis(detail='point')` or run `.compute_xyz()` before running `.vis()`."

        ax = plot_graph(
            self.xyzr,
            dims=dims,
            col=col,
            ax=ax,
            type=type,
            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("global_branch_index")[
            "global_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 = False
    ):
        """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.
        """
        for i in self._branches_in_view:
            self.base.xyzr[i][:, :3] += np.array([x, y, z])
        if update_nodes:
            self.compute_compartment_centers()

    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 = False,
    ):
        """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.
        """
        # 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."
            )

        # can only iterate over cells for networks
        # lambda makes sure that generator can be created multiple times
        base_is_net = self.base._current_view == "network"
        cells = lambda: (self.cells if base_is_net else [self])

        root_xyz_cells = np.array([c.xyzr[0][0, :3] for c in cells()])
        root_xyz = root_xyz_cells[0] if isinstance(x, float) else root_xyz_cells
        move_by = np.array([x, y, z]).T - root_xyz

        if len(move_by.shape) == 1:
            move_by = np.tile(move_by, (len(self._cells_in_view), 1))

        for cell, offset in zip(cells(), move_by):
            for idx in cell._branches_in_view:
                self.base.xyzr[idx][:, :3] += offset
        if update_nodes:
            self.compute_compartment_centers()

    def rotate(
        self, degrees: float, rotation_axis: str = "xy", update_nodes: bool = False
    ):
        """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`}.
        """
        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)]]
        )
        for i in self._branches_in_view:
            rot = np.dot(rotation_matrix, self.base.xyzr[i][:, dims].T).T
            self.base.xyzr[i][:, dims] = rot
        if update_nodes:
            self.compute_compartment_centers()

    def copy_node_property_to_edges(
        self,
        properties_to_import: Union[str, List[str]],
        pre_or_post: Union[str, List[str]] = ["pre", "post"],
    ) -> Module:
        """Copy a property that is in `node` over to `edges`.

        By default, `.edges` does not contain the properties (radius, length, cm,
        channel properties,...) of the pre- and post-synaptic compartments. This
        method allows to copy a property of the pre- and/or post-synaptic compartment
        to the edges. It is then accessible as `module.edges.pre_property_name` or
        `module.edges.post_property_name`.

        Note that, if you modify the node property _after_ having run
        `copy_node_property_to_edges`, it will not automatically update the value in
        `.edges`.

        Note that, if this method is called on a View (e.g.
        `net.cell(0).copy_node_property_to_edges`), then it will return a View, but
        it will _not_ modify the module itself.

        Args:
            properties_to_import: The name of the node properties that should be
                imported. To list all available properties, look at
                `module.nodes.columns`.
            pre_or_post: Whether to import only the pre-synaptic property ('pre'), only
                the post-synaptic property ('post'), or both (['pre', 'post']).

        Returns:
            A new module which has the property copied to the `nodes`.
        """
        # If a string is passed, wrap it as a list.
        if isinstance(pre_or_post, str):
            pre_or_post = [pre_or_post]
        if isinstance(properties_to_import, str):
            properties_to_import = [properties_to_import]

        for pre_or_post_val in pre_or_post:
            assert pre_or_post_val in ["pre", "post"]
            for property_to_import in properties_to_import:
                # Delete the column if it already exists. Otherwise it would exist
                # twice.
                if f"{pre_or_post_val}_{property_to_import}" in self.edges.columns:
                    self.edges.drop(
                        columns=f"{pre_or_post_val}_{property_to_import}", inplace=True
                    )

                self.edges = self.edges.join(
                    self.nodes[[property_to_import, "global_comp_index"]].set_index(
                        "global_comp_index"
                    ),
                    on=f"{pre_or_post_val}_global_comp_index",
                )
                self.edges = self.edges.rename(
                    columns={
                        property_to_import: f"{pre_or_post_val}_{property_to_import}"
                    }
                )

branches property

Iterate over all branches in the module.

Returns a generator that yields a View of each branch.

cells property

Iterate over all cells in the module.

Returns a generator that yields a View of each cell.

comps property

Iterate over all compartments in the module. Can be called on any module, i.e. net.comps, cell.comps or branch.comps. __iter__ does not allow for this.

Returns a generator that yields a View of each compartment.

initialized: bool property

Whether the Module is ready to be solved or not.

shape: Tuple[int] property

Returns the number of submodules contained in a module.

.. code-block:: python

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

view property

Return view of the module.

__getitem__(index)

Lazy indexing of the module.

Source code in jaxley/modules/base.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
def __getitem__(self, index):
    """Lazy indexing of the module."""
    supported_parents = ["network", "cell", "branch"]  # cannot index into comp

    not_group_view = self._current_view not in self.groups
    assert (
        self._current_view in supported_parents or not_group_view
    ), "Lazy indexing is only supported for `Network`, `Cell`, `Branch` and Views thereof."
    index = index if isinstance(index, tuple) else (index,)

    child_views = self._childviews()
    assert len(index) <= len(child_views), "Too many indices."
    view = self
    for i, child in zip(index, child_views):
        view = view._at_nodes(child, i)
    return view

__iter__()

Iterate over parts of the module.

Internally calls cells, branches, comps at the appropriate level.

Example:

.. code-block:: python

for cell in network:
    for branch in cell:
        for comp in branch:
            print(comp.nodes.shape)
Source code in jaxley/modules/base.py
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
def __iter__(self):
    """Iterate over parts of the module.

    Internally calls `cells`, `branches`, `comps` at the appropriate level.

    Example:

    .. code-block:: python

        for cell in network:
            for branch in cell:
                for comp in branch:
                    print(comp.nodes.shape)
    """
    next_level = self._childviews()[0]
    yield from self._iter_submodules(next_level)

add_to_group(group_name)

Add a view of the module to a group.

Groups can then be indexed. For example:

.. code-block:: python

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
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
def add_to_group(self, group_name: str):
    """Add a view of the module to a group.

    Groups can then be indexed. For example:

    .. code-block:: python

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

    Args:
        group_name: The name of the group.
    """
    if group_name not in self.base.groups:
        self.base.groups[group_name] = self._nodes_in_view
    else:
        self.base.groups[group_name] = np.unique(
            np.concatenate([self.base.groups[group_name], self._nodes_in_view])
        )

branch(idx)

Return a View of the module at the selected branches(s).

Parameters:

Name Type Description Default
idx Any

index of the branch to view.

required

Returns:

Type Description
View

View of the module at the specified branch index.

Source code in jaxley/modules/base.py
521
522
523
524
525
526
527
528
529
def branch(self, idx: Any) -> View:
    """Return a View of the module at the selected branches(s).

    Args:
        idx: index of the branch to view.

    Returns:
        View of the module at the specified branch index."""
    return self._at_nodes("branch", idx)

cell(idx)

Return a View of the module at the selected cell(s).

Parameters:

Name Type Description Default
idx Any

index of the cell to view.

required

Returns:

Type Description
View

View of the module at the specified cell index.

Source code in jaxley/modules/base.py
511
512
513
514
515
516
517
518
519
def cell(self, idx: Any) -> View:
    """Return a View of the module at the selected cell(s).

    Args:
        idx: index of the cell to view.

    Returns:
        View of the module at the specified cell index."""
    return self._at_nodes("cell", idx)

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
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
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.
    """
    self._external_input(state_name, state_array, verbose=verbose)

comp(idx)

Return a View of the module at the selected compartments(s).

Parameters:

Name Type Description Default
idx Any

index of the comp to view.

required

Returns:

Type Description
View

View of the module at the specified compartment index.

Source code in jaxley/modules/base.py
531
532
533
534
535
536
537
538
539
def comp(self, idx: Any) -> View:
    """Return a View of the module at the selected compartments(s).

    Args:
        idx: index of the comp to view.

    Returns:
        View of the module at the specified compartment index."""
    return self._at_nodes("comp", idx)

compute_compartment_centers()

Add compartment centers to nodes dataframe

Source code in jaxley/modules/base.py
374
375
376
377
def compute_compartment_centers(self):
    """Add compartment centers to nodes dataframe"""
    centers = self._compute_coords_of_comp_centers()
    self.base.nodes.loc[self._nodes_in_view, ["x", "y", "z"]] = centers

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
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
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("global_branch_index")[
        "global_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,)))

copy(reset_index=False, as_module=False)

Extract part of a module and return a copy of its View or a new module.

This can be used to call jx.integrate on part of a Module.

Parameters:

Name Type Description Default
reset_index bool

if True, the indices of the new module are reset to start from 0.

False
as_module bool

if True, a new module is returned instead of a View.

False

Returns:

Type Description
Union[Module, View]

A part of the module or a copied view of it.

Source code in jaxley/modules/base.py
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
def copy(
    self, reset_index: bool = False, as_module: bool = False
) -> Union[Module, View]:
    """Extract part of a module and return a copy of its View or a new module.

    This can be used to call `jx.integrate` on part of a Module.

    Args:
        reset_index: if True, the indices of the new module are reset to start from 0.
        as_module: if True, a new module is returned instead of a View.

    Returns:
        A part of the module or a copied view of it."""
    view = deepcopy(self)
    warnings.warn("This method is experimental, use at your own risk.")
    # TODO FROM #447: add reset_index, i.e. for parents, nodes, edges etc. such that they
    # start from 0/-1 and are contiguous
    if as_module:
        raise NotImplementedError("Not yet implemented.")
        # initialize a new module with the same attributes
    return view

copy_node_property_to_edges(properties_to_import, pre_or_post=['pre', 'post'])

Copy a property that is in node over to edges.

By default, .edges does not contain the properties (radius, length, cm, channel properties,…) of the pre- and post-synaptic compartments. This method allows to copy a property of the pre- and/or post-synaptic compartment to the edges. It is then accessible as module.edges.pre_property_name or module.edges.post_property_name.

Note that, if you modify the node property after having run copy_node_property_to_edges, it will not automatically update the value in .edges.

Note that, if this method is called on a View (e.g. net.cell(0).copy_node_property_to_edges), then it will return a View, but it will not modify the module itself.

Parameters:

Name Type Description Default
properties_to_import Union[str, List[str]]

The name of the node properties that should be imported. To list all available properties, look at module.nodes.columns.

required
pre_or_post Union[str, List[str]]

Whether to import only the pre-synaptic property (‘pre’), only the post-synaptic property (‘post’), or both ([‘pre’, ‘post’]).

['pre', 'post']

Returns:

Type Description
Module

A new module which has the property copied to the nodes.

Source code in jaxley/modules/base.py
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
def copy_node_property_to_edges(
    self,
    properties_to_import: Union[str, List[str]],
    pre_or_post: Union[str, List[str]] = ["pre", "post"],
) -> Module:
    """Copy a property that is in `node` over to `edges`.

    By default, `.edges` does not contain the properties (radius, length, cm,
    channel properties,...) of the pre- and post-synaptic compartments. This
    method allows to copy a property of the pre- and/or post-synaptic compartment
    to the edges. It is then accessible as `module.edges.pre_property_name` or
    `module.edges.post_property_name`.

    Note that, if you modify the node property _after_ having run
    `copy_node_property_to_edges`, it will not automatically update the value in
    `.edges`.

    Note that, if this method is called on a View (e.g.
    `net.cell(0).copy_node_property_to_edges`), then it will return a View, but
    it will _not_ modify the module itself.

    Args:
        properties_to_import: The name of the node properties that should be
            imported. To list all available properties, look at
            `module.nodes.columns`.
        pre_or_post: Whether to import only the pre-synaptic property ('pre'), only
            the post-synaptic property ('post'), or both (['pre', 'post']).

    Returns:
        A new module which has the property copied to the `nodes`.
    """
    # If a string is passed, wrap it as a list.
    if isinstance(pre_or_post, str):
        pre_or_post = [pre_or_post]
    if isinstance(properties_to_import, str):
        properties_to_import = [properties_to_import]

    for pre_or_post_val in pre_or_post:
        assert pre_or_post_val in ["pre", "post"]
        for property_to_import in properties_to_import:
            # Delete the column if it already exists. Otherwise it would exist
            # twice.
            if f"{pre_or_post_val}_{property_to_import}" in self.edges.columns:
                self.edges.drop(
                    columns=f"{pre_or_post_val}_{property_to_import}", inplace=True
                )

            self.edges = self.edges.join(
                self.nodes[[property_to_import, "global_comp_index"]].set_index(
                    "global_comp_index"
                ),
                on=f"{pre_or_post_val}_global_comp_index",
            )
            self.edges = self.edges.rename(
                columns={
                    property_to_import: f"{pre_or_post_val}_{property_to_import}"
                }
            )

data_clamp(state_name, state_array, data_clamps=None, verbose=False)

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

Parameters:

Name Type Description Default
state_name str

Name of the state variable to set.

required
state_array ndarray

Time series of the state variable in the default Jaxley unit. State array should be of shape (num_clamps, simulation_time) or (simulation_time, ) for a single clamp.

required
verbose bool

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

False
Source code in jaxley/modules/base.py
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
def data_clamp(
    self,
    state_name: str,
    state_array: jnp.ndarray,
    data_clamps: Optional[Tuple[jnp.ndarray, pd.DataFrame]] = None,
    verbose: bool = False,
):
    """Insert a clamp into the module within jit (or grad).

    Args:
        state_name: Name of the state variable to set.
        state_array: Time series of the state variable in the default Jaxley unit.
            State array should be of shape (num_clamps, simulation_time) or
            (simulation_time, ) for a single clamp.
        verbose: Whether or not to print the number of inserted clamps. `False`
            by default because this method is meant to be jitted.
    """
    comp_states, edge_states = self._get_state_names()
    if state_name not in comp_states + edge_states:
        raise KeyError(f"{state_name} is not a recognized state in this module.")
    data = self.nodes if state_name in comp_states else self.edges
    return self._data_external_input(
        state_name, state_array, data_clamps, data, verbose=verbose
    )

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
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
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.
    """
    # Note: `data_set` does not support arrays for `val`.
    is_node_param = key in self.nodes.columns
    data = self.nodes if is_node_param else self.edges
    viewed_inds = self._nodes_in_view if is_node_param else self._edges_in_view
    if key in data.columns:
        not_nan = ~data[key].isna()
        added_param_state = [
            {
                "indices": np.atleast_2d(viewed_inds[not_nan]),
                "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

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
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
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_external_input(
        "i", current, data_stimuli, self.nodes, verbose=verbose
    )

delete_channel(channel)

Remove a channel from the module.

Parameters:

Name Type Description Default
channel Channel

The channel to remove.

required
Source code in jaxley/modules/base.py
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
def delete_channel(self, channel: Channel):
    """Remove a channel from the module.

    Args:
        channel: The channel to remove."""
    name = channel._name
    channel_names = [c._name for c in self.channels]
    all_channel_names = [c._name for c in self.base.channels]
    if name in channel_names:
        channel_cols = list(channel.channel_params.keys())
        channel_cols += list(channel.channel_states.keys())
        self.base.nodes.loc[self._nodes_in_view, channel_cols] = float("nan")
        self.base.nodes.loc[self._nodes_in_view, name] = False

        # only delete cols if no other comps in the module have the same channel
        if np.all(~self.base.nodes[name]):
            self.base.channels.pop(all_channel_names.index(name))
            self.base.membrane_current_names.remove(channel.current_name)
            self.base.nodes.drop(columns=channel_cols + [name], inplace=True)
    else:
        raise ValueError(f"Channel {name} not found in the module.")

delete_clamps(state_name=None)

Removes all clamps of the given state from the module.

Source code in jaxley/modules/base.py
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
def delete_clamps(self, state_name: Optional[str] = None):
    """Removes all clamps of the given state from the module."""
    all_externals = list(self.externals.keys())
    if "i" in all_externals:
        all_externals.remove("i")
    state_names = all_externals if state_name is None else [state_name]
    for state_name in state_names:
        if state_name in self.externals:
            keep_inds = ~np.isin(
                self.base.external_inds[state_name], self._nodes_in_view
            )
            base_exts = self.base.externals
            base_exts_inds = self.base.external_inds
            if np.all(~keep_inds):
                base_exts.pop(state_name, None)
                base_exts_inds.pop(state_name, None)
            else:
                base_exts[state_name] = base_exts[state_name][keep_inds]
                base_exts_inds[state_name] = base_exts_inds[state_name][keep_inds]
            self._update_view()
        else:
            pass  # does not have to be deleted if not in externals

delete_recordings()

Removes all recordings from the module.

Source code in jaxley/modules/base.py
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
def delete_recordings(self):
    """Removes all recordings from the module."""
    if isinstance(self, View):
        base_recs = self.base.recordings
        self.base.recordings = base_recs[
            ~base_recs.isin(self.recordings).all(axis=1)
        ]
        self._update_view()
    else:
        self.base.recordings = pd.DataFrame().from_dict({})

delete_stimuli()

Removes all stimuli from the module.

Source code in jaxley/modules/base.py
1683
1684
1685
def delete_stimuli(self):
    """Removes all stimuli from the module."""
    self.delete_clamps("i")

delete_trainables()

Removes all trainable parameters from the module.

Source code in jaxley/modules/base.py
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
def delete_trainables(self):
    """Removes all trainable parameters from the module."""

    if isinstance(self, View):
        trainables_and_inds = self._filter_trainables(is_viewed=False)
        self.base.indices_set_by_trainables = trainables_and_inds[0]
        self.base.trainable_params = trainables_and_inds[1]
        self.base.num_trainable_params -= self.num_trainable_params
    else:
        self.base.indices_set_by_trainables = []
        self.base.trainable_params = []
        self.base.num_trainable_params = 0
    self._update_view()

distance(endpoint)

Return the direct distance between two compartments. This does not compute the pathwise distance (which is currently not implemented). Args: endpoint: The compartment to which to compute the distance to.

Source code in jaxley/modules/base.py
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
def distance(self, endpoint: "View") -> float:
    """Return the direct distance between two compartments.
    This does not compute the pathwise distance (which is currently not
    implemented).
    Args:
        endpoint: The compartment to which to compute the distance to.
    """
    assert len(self.xyzr) == 1 and len(endpoint.xyzr) == 1
    start_xyz = np.mean(self.xyzr[0][:, :3], axis=0)
    end_xyz = np.mean(endpoint.xyzr[0][:, :3], axis=0)
    return np.sqrt(np.sum((start_xyz - end_xyz) ** 2))

edge(idx)

Return a View of the module at the selected synapse edges(s).

Parameters:

Name Type Description Default
idx Any

index of the edge to view.

required

Returns:

Type Description
View

View of the module at the specified edge index.

Source code in jaxley/modules/base.py
541
542
543
544
545
546
547
548
549
def edge(self, idx: Any) -> View:
    """Return a View of the module at the selected synapse edges(s).

    Args:
        idx: index of the edge to view.

    Returns:
        View of the module at the specified edge index."""
    return self._at_edges("edge", idx)

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

.. code-block:: python

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
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
@only_allow_module
def get_all_parameters(
    self, pstate: List[Dict], voltage_solver: str
) -> Dict[str, jnp.ndarray]:
    # TODO FROM #447: MAKE THIS WORK FOR VIEW?
    """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()`.

    .. code-block:: python

        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.base.jaxnodes[key]

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

    for synapse_params in self.base.synapse_param_names:
        params[synapse_params] = self.base.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"]

        # This is needed since SynapseViews worked differently before.
        # This mimics the old behaviour and tranformes the new indices
        # to the old indices.
        # TODO FROM #447: Longterm this should be gotten rid of.
        # Instead edges should work similar to nodes (would also allow for
        # param sharing).
        synapse_inds = self.base.edges.groupby("type").rank()["global_edge_index"]
        synapse_inds = (synapse_inds.astype(int) - 1).to_numpy()
        if key in self.base.synapse_param_names:
            inds = synapse_inds[inds]

        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.base._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
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
@only_allow_module
def get_all_states(
    self, pstate: List[Dict], all_params, delta_t: float
) -> Dict[str, jnp.ndarray]:
    # TODO FROM #447: MAKE THIS WORK FOR VIEW?
    """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.base._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.base._channel_currents(
        states, delta_t, self.channels, self.nodes, all_params
    )

    # Add to the states the initial current through every synapse.
    states, _ = self.base._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
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
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

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
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
@only_allow_module
def init_states(self, delta_t: float = 0.025):
    # TODO FROM #447: MAKE THIS WORK FOR VIEW?
    """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.base.nodes
    states = self.base._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.base.get_all_parameters([], voltage_solver="jaxley.thomas")

    for channel in self.base.channels:
        name = channel._name
        channel_indices = channel_nodes.loc[channel_nodes[name]][
            "global_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

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
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
def insert(self, channel: Channel):
    """Insert a channel into the module.

    Args:
        channel: The channel to insert."""
    name = channel._name

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

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

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

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

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

loc(at)

Return a View of the module at the selected branch location(s).

Parameters:

Name Type Description Default
at Any

location along the branch.

required

Returns:

Type Description
View

View of the module at the specified branch location.

Source code in jaxley/modules/base.py
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
def loc(self, at: Any) -> View:
    """Return a View of the module at the selected branch location(s).

    Args:
        at: location along the branch.

    Returns:
        View of the module at the specified branch location."""
    global_comp_idxs = []
    for i in self._branches_in_view:
        ncomp = self.base.ncomp_per_branch[i]
        comp_locs = np.linspace(0, 1, ncomp)
        at = comp_locs if is_str_all(at) else self._reformat_index(at, dtype=float)
        comp_edges = np.linspace(0, 1 + 1e-10, ncomp + 1)
        idx = np.digitize(at, comp_edges) - 1 + self.base.cumsum_ncomp[i]
        global_comp_idxs.append(idx)
    global_comp_idxs = np.concatenate(global_comp_idxs)
    orig_scope = self._scope
    # global scope needed to select correct comps, for i.e. branches w. ncomp=[1,2]
    # loc(0.9)  will correspond to different local branches (0 vs 1).
    view = self.scope("global").comp(global_comp_idxs).scope(orig_scope)
    view._current_view = "loc"
    return view

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
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
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 (
        self.allow_make_trainable
    ), "network.cell('all').make_trainable() is not supported. Use a for-loop over cells."
    ncomps_per_branch = (
        self.base.nodes["global_branch_index"].value_counts().to_numpy()
    )
    assert np.all(
        ncomps_per_branch == ncomps_per_branch[0]
    ), "Parameter sharing is not allowed for modules containing branches with different numbers of compartments."

    data = self.nodes if key in self.nodes.columns else None
    data = self.edges if key in self.edges.columns else data

    assert data is not None, f"Key '{key}' not found in nodes or edges"
    not_nan = ~data[key].isna()
    data = data.loc[not_nan]
    assert (
        len(data) > 0
    ), "No settable parameters found in the selected compartments."

    grouped_view = data.groupby("controlled_by_param")
    # Because of this `x.index.values` we cannot support `make_trainable()` on
    # the module level for synapse parameters (but only for `SynapseView`).
    inds_of_comps = list(
        grouped_view.apply(lambda x: x.index.values, include_groups=False)
    )
    indices_per_param = jnp.stack(inds_of_comps)
    # Sorted inds are only used to infer the correct starting values.
    param_vals = jnp.asarray(
        [data.loc[inds, key].to_numpy() for inds in inds_of_comps]
    )

    # 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.base.trainable_params.append({key: new_params})
    self.base.indices_set_by_trainables.append(indices_per_param)
    self.base.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.base.num_trainable_params}"
        )

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

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.

False
Source code in jaxley/modules/base.py
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
def move(
    self, x: float = 0.0, y: float = 0.0, z: float = 0.0, update_nodes: bool = False
):
    """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.
    """
    for i in self._branches_in_view:
        self.base.xyzr[i][:, :3] += np.array([x, y, z])
    if update_nodes:
        self.compute_compartment_centers()

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

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.

False
Source code in jaxley/modules/base.py
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
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 = False,
):
    """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.
    """
    # 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."
        )

    # can only iterate over cells for networks
    # lambda makes sure that generator can be created multiple times
    base_is_net = self.base._current_view == "network"
    cells = lambda: (self.cells if base_is_net else [self])

    root_xyz_cells = np.array([c.xyzr[0][0, :3] for c in cells()])
    root_xyz = root_xyz_cells[0] if isinstance(x, float) else root_xyz_cells
    move_by = np.array([x, y, z]).T - root_xyz

    if len(move_by.shape) == 1:
        move_by = np.tile(move_by, (len(self._cells_in_view), 1))

    for cell, offset in zip(cells(), move_by):
        for idx in cell._branches_in_view:
            self.base.xyzr[idx][:, :3] += offset
    if update_nodes:
        self.compute_compartment_centers()

rotate(degrees, rotation_axis='xy', update_nodes=False)

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
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
def rotate(
    self, degrees: float, rotation_axis: str = "xy", update_nodes: bool = False
):
    """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`}.
    """
    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)]]
    )
    for i in self._branches_in_view:
        rot = np.dot(rotation_matrix, self.base.xyzr[i][:, dims].T).T
        self.base.xyzr[i][:, dims] = rot
    if update_nodes:
        self.compute_compartment_centers()

scope(scope)

Return a View of the module with the specified scope.

For example cell.scope("global").branch(2).scope("local").comp(1) will return the 1st compartment of branch 2.

Parameters:

Name Type Description Default
scope str

either “global” or “local”.

required

Returns:

Type Description
View

View with the specified scope.

Source code in jaxley/modules/base.py
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def scope(self, scope: str) -> View:
    """Return a View of the module with the specified scope.

    For example `cell.scope("global").branch(2).scope("local").comp(1)`
    will return the 1st compartment of branch 2.

    Args:
        scope: either "global" or "local".

    Returns:
        View with the specified scope."""
    view = self.view
    view.set_scope(scope)
    return view

select(nodes=None, edges=None, sorted=False)

Return View of the module filtered by specific node or edges indices.

Parameters:

Name Type Description Default
nodes ndarray

indices of nodes to view. If None, all nodes are viewed.

None
edges ndarray

indices of edges to view. If None, all edges are viewed.

None
sorted bool

if True, nodes and edges are sorted.

False

Returns:

Type Description
View

View for subset of selected nodes and/or edges.

Source code in jaxley/modules/base.py
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
def select(
    self, nodes: np.ndarray = None, edges: np.ndarray = None, sorted: bool = False
) -> View:
    """Return View of the module filtered by specific node or edges indices.

    Args:
        nodes: indices of nodes to view. If None, all nodes are viewed.
        edges: indices of edges to view. If None, all edges are viewed.
        sorted: if True, nodes and edges are sorted.

    Returns:
        View for subset of selected nodes and/or edges."""

    nodes = self._reformat_index(nodes) if nodes is not None else None
    nodes = self._nodes_in_view if is_str_all(nodes) else nodes
    nodes = np.sort(nodes) if sorted else nodes

    edges = self._reformat_index(edges) if edges is not None else None
    edges = self._edges_in_view if is_str_all(edges) else edges
    edges = np.sort(edges) if sorted else edges

    view = View(self, nodes, edges)
    view._set_controlled_by_param("filter")
    return view

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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
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))`.
    """
    if key in self.nodes.columns:
        not_nan = ~self.nodes[key].isna().to_numpy()
        self.base.nodes.loc[self._nodes_in_view[not_nan], key] = val
    elif key in self.edges.columns:
        not_nan = ~self.edges[key].isna().to_numpy()
        self.base.edges.loc[self._edges_in_view[not_nan], key] = val
    else:
        raise KeyError(f"Key '{key}' not found in nodes or edges")

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
min_radius Optional[float]

Only used if the morphology was read from an SWC file. If passed the radius is capped to be at least this value.

None
Source code in jaxley/modules/base.py
 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
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.
        min_radius: Only used if the morphology was read from an SWC file. If passed
            the radius is capped to be at least this value.

    Raises:
        - 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.base.externals) == 0, "No stimuli allowed!"
    assert len(self.base.recordings) == 0, "No recordings allowed!"
    assert len(self.base.trainable_params) == 0, "No trainables allowed!"

    assert self.base._module_type != "network", "This is not allowed for networks."
    assert not (
        self.base._module_type == "cell"
        and len(self._branches_in_view) == len(self.base._branches_in_view)
    ), "This is not allowed for cells."

    # Update all attributes that are affected by compartment structure.
    view = self.nodes.copy()
    all_nodes = self.base.nodes
    start_idx = self.nodes["global_comp_index"].to_numpy()[0]
    ncomp_per_branch = self.base.ncomp_per_branch
    channel_names = [c._name for c in self.base.channels]
    channel_param_names = list(
        chain(*[c.channel_params for c in self.base.channels])
    )
    channel_state_names = list(
        chain(*[c.channel_states for c in self.base.channels])
    )
    radius_generating_fns = self.base._radius_generating_fns

    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["global_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 (self.nodes[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 (
        self.nodes[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 = self.nodes.mean(skipna=False)
    average_row = average_row.to_frame().T
    view = pd.concat([*[average_row] * ncomp], axis="rows")

    # Set the correct datatype after having performed an average which cast
    # everything to float.
    integer_cols = ["global_cell_index", "global_branch_index", "global_comp_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,
            ncomp=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["global_comp_index"] = np.arange(len(all_nodes))

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

    self.base.nodes = all_nodes
    self.base.ncomp_per_branch = ncomp_per_branch
    self.base.ncomp = ncomp
    self.base.cumsum_ncomp = cumsum_ncomp
    self.base._internal_node_inds = internal_node_inds

    # Update the morphology indexing (e.g., `.comp_edges`).
    self.base._initialize()
    self.base._init_view()
    self.base._update_local_indices()

set_scope(scope)

Toggle between “global” or “local” scope.

Determines if global or local indices are used for viewing the module.

Parameters:

Name Type Description Default
scope str

either “global” or “local”.

required
Source code in jaxley/modules/base.py
456
457
458
459
460
461
462
463
464
def set_scope(self, scope: str):
    """Toggle between "global" or "local" scope.

    Determines if global or local indices are used for viewing the module.

    Args:
        scope: either "global" or "local"."""
    assert scope in ["global", "local"], "Invalid scope."
    self._scope = scope

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.

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
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
def show(
    self,
    param_names: Optional[Union[str, List[str]]] = None,
    *,
    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.
        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.
    """
    nodes = self.nodes.copy()  # prevents this from being edited

    cols = []
    inds = ["comp_index", "branch_index", "cell_index"]
    scopes = ["local", "global"]
    inds = [f"{s}_{i}" for i in inds for s in scopes] if indices else []
    cols += inds
    cols += [ch._name for ch in self.channels] if channel_names else []
    cols += (
        sum([list(ch.channel_params) for ch in self.channels], []) if params else []
    )
    cols += (
        sum([list(ch.channel_states) for ch in self.channels], []) if states else []
    )

    if not param_names is None:
        cols = (
            inds + [c for c in cols if c in param_names]
            if params
            else list(param_names)
        )

    return nodes[cols]

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
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
@only_allow_module
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
    if "i" in externals.keys():
        i_current = externals["i"]
        i_inds = external_inds["i"]
        i_ext = self._get_external_input(
            voltages, i_inds, i_current, params["radius"], params["length"]
        )
    else:
        i_ext = 0.0

    # 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()),
                "ncomp_per_branch": self.ncomp_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
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
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, 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
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
@only_allow_module
def to_jax(self):
    # TODO FROM #447: Make this work for View?
    """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.base.jaxnodes = {}
    for key, value in self.base.nodes.to_dict(orient="list").items():
        inds = jnp.arange(len(value))
        self.base.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.base.jaxedges = {}
    edges = self.base.edges.to_dict(orient="list")
    for i, synapse in enumerate(self.base.synapses):
        condition = np.asarray(edges["type_ind"]) == i
        for key in synapse.synapse_params:
            self.base.jaxedges[key] = jnp.asarray(np.asarray(edges[key])[condition])
        for key in synapse.synapse_states:
            self.base.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
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
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.
    """
    if "comp" in type.lower():
        return plot_comps(self, dims=dims, ax=ax, col=col, **morph_plot_kwargs)
    if "morph" in type.lower():
        return plot_morph(self, dims=dims, ax=ax, col=col, **morph_plot_kwargs)

    assert not np.any(
        [np.isnan(xyzr[:, dims]).all() for xyzr in self.xyzr]
    ), "No coordinates available. Use `vis(detail='point')` or run `.compute_xyz()` before running `.vis()`."

    ax = plot_graph(
        self.xyzr,
        dims=dims,
        col=col,
        ax=ax,
        type=type,
        morph_plot_kwargs=morph_plot_kwargs,
    )

    return ax

write_trainables(trainable_params)

Write the trainables into .nodes and .edges.

This allows to, e.g., visualize trained networks with .vis().

Parameters:

Name Type Description Default
trainable_params List[Dict[str, ndarray]]

The trainable parameters returned by get_parameters().

required
Source code in jaxley/modules/base.py
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
def write_trainables(self, trainable_params: List[Dict[str, jnp.ndarray]]):
    """Write the trainables into `.nodes` and `.edges`.

    This allows to, e.g., visualize trained networks with `.vis()`.

    Args:
        trainable_params: The trainable parameters returned by `get_parameters()`.
    """
    # We do not support views. Why? `jaxedges` does not have any NaN
    # elements, whereas edges does. Because of this, we already need special
    # treatment to make this function work, and it would be an even bigger hassle
    # if we wanted to support this.
    assert self.__class__.__name__ in [
        "Compartment",
        "Branch",
        "Cell",
        "Network",
    ], "Only supports modules."

    # We could also implement this without casting the module to jax.
    # However, I think it allows us to reuse as much code as possible and it avoids
    # any kind of issues with indexing or parameter sharing (as this is fully
    # taken care of by `get_all_parameters()`).
    self.base.to_jax()
    pstate = params_to_pstate(trainable_params, self.base.indices_set_by_trainables)
    all_params = self.base.get_all_parameters(pstate, voltage_solver="jaxley.stone")

    # The value for `delta_t` does not matter here because it is only used to
    # compute the initial current. However, the initial current cannot be made
    # trainable and so its value never gets used below.
    all_states = self.base.get_all_states(pstate, all_params, delta_t=0.025)

    # Loop only over the keys in `pstate` to avoid unnecessary computation.
    for parameter in pstate:
        key = parameter["key"]
        if key in self.base.nodes.columns:
            vals_to_set = all_params if key in all_params.keys() else all_states
            self.base.nodes[key] = vals_to_set[key]

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

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
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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.ncomp = 1
        self.ncomp_per_branch = np.asarray([1])
        self.total_nbranches = 1
        self.nbranches_per_cell = [1]
        self._cumsum_nbranches = np.asarray([0, 1])
        self.cumsum_ncomp = cumsum_leading_zero(self.ncomp_per_branch)

        # Setting up the `nodes` for indexing.
        self.nodes = pd.DataFrame(
            dict(global_cell_index=[0], global_branch_index=[0], global_comp_index=[0])
        )
        self._append_params_and_states(self.compartment_params, self.compartment_states)
        self._update_local_indices()
        self._init_view()

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

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

    def _init_morph_jaxley_spsolve(self):
        self._solve_indexer = JaxleySolveIndexer(
            cumsum_ncomp=self.cumsum_ncomp,
            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

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
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
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 = {}

    @deprecated_kwargs("0.6.0", ["nseg"])
    def __init__(
        self,
        compartments: Optional[Union[Compartment, List[Compartment]]] = None,
        ncomp: Optional[int] = None,
        nseg: Optional[int] = None,
    ):
        """
        Args:
            compartments: A single compartment or a list of compartments that make up the
                branch.
            ncomp: Number of segments to divide the branch into. If `compartments` is an
                a single compartment, than the compartment is repeated `ncomp` times to
                create the branch.
        """
        # Warnings and errors that deal with the change from `nseg` to `ncomp` change
        # in Jaxley v0.5.0.
        if ncomp is not None and nseg is not None:
            raise ValueError("You passed `ncomp` and `nseg`. Please pass only `ncomp`.")
        if ncomp is None and nseg is not None:
            ncomp = nseg

        super().__init__()
        assert (
            isinstance(compartments, (Compartment, List)) or compartments is None
        ), "Only Compartment or List[Compartment] is allowed."
        if isinstance(compartments, Compartment):
            assert (
                ncomp is not None
            ), "If `compartments` is not a list then you have to set `ncomp`."
        compartments = Compartment() if compartments is None else compartments
        ncomp = 1 if ncomp is None else ncomp

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

        self.ncomp = len(compartment_list)
        self.ncomp_per_branch = np.asarray([self.ncomp])
        self.total_nbranches = 1
        self.nbranches_per_cell = [1]
        self._cumsum_nbranches = jnp.asarray([0, 1])
        self.cumsum_ncomp = cumsum_leading_zero(self.ncomp_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["global_comp_index"] = np.arange(self.ncomp).tolist()
        self.nodes["global_branch_index"] = [0] * self.ncomp
        self.nodes["global_cell_index"] = [0] * self.ncomp
        self._update_local_indices()
        self._init_view()

        # Channels.
        self._gather_channels_from_constituents(compartment_list)

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

        self._initialize()

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

    def _init_morph_jaxley_spsolve(self):
        self._solve_indexer = JaxleySolveIndexer(
            cumsum_ncomp=self.cumsum_ncomp,
            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.ncomp - 1)) + list(range(1, self.ncomp)),
                "sink": list(range(1, self.ncomp)) + list(range(self.ncomp - 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.ncomp

__init__(compartments=None, ncomp=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
ncomp Optional[int]

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

None
Source code in jaxley/modules/branch.py
 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
@deprecated_kwargs("0.6.0", ["nseg"])
def __init__(
    self,
    compartments: Optional[Union[Compartment, List[Compartment]]] = None,
    ncomp: Optional[int] = None,
    nseg: Optional[int] = None,
):
    """
    Args:
        compartments: A single compartment or a list of compartments that make up the
            branch.
        ncomp: Number of segments to divide the branch into. If `compartments` is an
            a single compartment, than the compartment is repeated `ncomp` times to
            create the branch.
    """
    # Warnings and errors that deal with the change from `nseg` to `ncomp` change
    # in Jaxley v0.5.0.
    if ncomp is not None and nseg is not None:
        raise ValueError("You passed `ncomp` and `nseg`. Please pass only `ncomp`.")
    if ncomp is None and nseg is not None:
        ncomp = nseg

    super().__init__()
    assert (
        isinstance(compartments, (Compartment, List)) or compartments is None
    ), "Only Compartment or List[Compartment] is allowed."
    if isinstance(compartments, Compartment):
        assert (
            ncomp is not None
        ), "If `compartments` is not a list then you have to set `ncomp`."
    compartments = Compartment() if compartments is None else compartments
    ncomp = 1 if ncomp is None else ncomp

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

    self.ncomp = len(compartment_list)
    self.ncomp_per_branch = np.asarray([self.ncomp])
    self.total_nbranches = 1
    self.nbranches_per_cell = [1]
    self._cumsum_nbranches = jnp.asarray([0, 1])
    self.cumsum_ncomp = cumsum_leading_zero(self.ncomp_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["global_comp_index"] = np.arange(self.ncomp).tolist()
    self.nodes["global_branch_index"] = [0] * self.ncomp
    self.nodes["global_cell_index"] = [0] * self.ncomp
    self._update_local_indices()
    self._init_view()

    # Channels.
    self._gather_channels_from_constituents(compartment_list)

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

    self._initialize()

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

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
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
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 = np.asarray([0, len(branch_list)])

        # Compartment structure. These arguments have to be rebuilt when `.set_ncomp()`
        # is run.
        self.ncomp_per_branch = np.asarray([branch.ncomp for branch in branch_list])
        self.ncomp = int(np.max(self.ncomp_per_branch))
        self.cumsum_ncomp = cumsum_leading_zero(self.ncomp_per_branch)
        self._internal_node_inds = np.arange(self.cumsum_ncomp[-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["global_comp_index"] = np.arange(self.cumsum_ncomp[-1])
        self.nodes["global_branch_index"] = np.repeat(
            np.arange(self.total_nbranches), self.ncomp_per_branch
        ).tolist()
        self.nodes["global_cell_index"] = np.repeat(0, self.cumsum_ncomp[-1]).tolist()
        self._update_local_indices()
        self._init_view()

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

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

    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_ncomp[-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_ncomp = pd.DataFrame().from_dict(
            {
                "levels": levels,
                "ncomps": self.ncomp_per_branch,
            }
        )
        levels_and_ncomp["max_ncomp_in_level"] = levels_and_ncomp.groupby("levels")[
            "ncomps"
        ].transform("max")
        padded_cumsum_ncomp = cumsum_leading_zero(
            levels_and_ncomp["max_ncomp_in_level"].to_numpy()
        )

        # Generate mapping to deal with the masking which allows using the custom
        # sparse solver to deal with different ncomp per branch.
        remapped_node_indices = remap_index_to_masked(
            self._internal_node_inds,
            self.nodes,
            padded_cumsum_ncomp,
            self.ncomp_per_branch,
        )
        self._solve_indexer = JaxleySolveIndexer(
            cumsum_ncomp=padded_cumsum_ncomp,
            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_ncomp, ncomp - 1 + cumsum_ncomp))
                        + list(range(1 + cumsum_ncomp, ncomp + cumsum_ncomp)),
                        "sink": list(range(1 + cumsum_ncomp, ncomp + cumsum_ncomp))
                        + list(range(cumsum_ncomp, ncomp - 1 + cumsum_ncomp)),
                    }
                )
                .astype(int)
                for ncomp, cumsum_ncomp in zip(self.ncomp_per_branch, self.cumsum_ncomp)
            ]
        )
        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_ncomp[-1],
                "sink": self.cumsum_ncomp[self._par_inds + 1] - 1,
                "type": 1,
            }
        )
        branchpoint_to_child_edges = pd.DataFrame().from_dict(
            {
                "source": self._child_belongs_to_branchpoint + self.cumsum_ncomp[-1],
                "sink": self.cumsum_ncomp[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

__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
 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
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 = np.asarray([0, len(branch_list)])

    # Compartment structure. These arguments have to be rebuilt when `.set_ncomp()`
    # is run.
    self.ncomp_per_branch = np.asarray([branch.ncomp for branch in branch_list])
    self.ncomp = int(np.max(self.ncomp_per_branch))
    self.cumsum_ncomp = cumsum_leading_zero(self.ncomp_per_branch)
    self._internal_node_inds = np.arange(self.cumsum_ncomp[-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["global_comp_index"] = np.arange(self.cumsum_ncomp[-1])
    self.nodes["global_branch_index"] = np.repeat(
        np.arange(self.total_nbranches), self.ncomp_per_branch
    ).tolist()
    self.nodes["global_cell_index"] = np.repeat(0, self.cumsum_ncomp[-1]).tolist()
    self._update_local_indices()
    self._init_view()

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

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

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

        self.nbranches_per_cell = [cell.total_nbranches for cell in 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["global_comp_index"] = np.arange(self.cumsum_ncomp[-1])
        self.nodes["global_branch_index"] = np.repeat(
            np.arange(self.total_nbranches), self.ncomp_per_branch
        ).tolist()
        self.nodes["global_cell_index"] = list(
            itertools.chain(
                *[[i] * int(cell.cumsum_ncomp[-1]) for i, cell in enumerate(cells)]
            )
        )
        self._update_local_indices()
        self._init_view()

        parents = [cell.comb_parents for cell in 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 cells])
        self._cumsum_nbranchpoints_per_cell = cumsum_leading_zero(nbranchpoints)

        # Channels.
        self._gather_channels_from_constituents(cells)

        self._initialize()
        del self._cells_list

    def __repr__(self):
        return f"{type(self).__name__} with {len(self.channels)} different channels and {len(self.synapses)} synapses. Use `.nodes` or `.edges` for details."

    def _init_morph_jaxley_spsolve(self):
        branchpoint_group_inds = build_branchpoint_group_inds(
            len(self._par_inds),
            self._child_belongs_to_branchpoint,
            self.cumsum_ncomp[-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_list],
            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_list],
            exclude_first=False,
        )
        padded_cumsum_ncomp = cumsum_leading_zero(
            np.concatenate(
                [np.diff(cell._solve_indexer.cumsum_ncomp) for cell in self._cells_list]
            )
        )

        # Generate mapping to dealing with the masking which allows using the custom
        # sparse solver to deal with different ncomp per branch.
        remapped_node_indices = remap_index_to_masked(
            self._internal_node_inds,
            self.nodes,
            padded_cumsum_ncomp,
            self.ncomp_per_branch,
        )
        self._solve_indexer = JaxleySolveIndexer(
            cumsum_ncomp=padded_cumsum_ncomp,
            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_ncomp` 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_ncomp_per_cell = cumsum_leading_zero(
            jnp.asarray([cell.cumsum_ncomp[-1] for cell in self.cells])
        )
        self._comp_edges = pd.DataFrame()

        # Add all the internal nodes.
        for offset, cell in zip(self._cumsum_ncomp_per_cell, self._cells_list):
            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_ncomp[-1]  # Index of the first branchpoint.
        for offset, offset_branchpoints, cell in zip(
            self._cumsum_ncomp_per_cell,
            self._cumsum_nbranchpoints_per_cell,
            self._cells_list,
        ):
            offset_within_cell = cell.cumsum_ncomp[-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_ncomp_per_cell,
            self._cumsum_nbranchpoints_per_cell,
            self._cells_list,
        ):
            offset_within_cell = cell.cumsum_ncomp[-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,
            )

        # 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 _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["pre_global_comp_index"].apply(list)
        post_syn_inds = grouped_syns["post_global_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["pre_global_comp_index"].apply(list)
        post_syn_inds = grouped_syns["post_global_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 = super().vis(
                dims=dims,
                col=col,
                ax=ax,
                type=type,
                morph_plot_kwargs=morph_plot_kwargs,
            )

            pre_locs = self.edges["pre_locs"].to_numpy()
            post_locs = self.edges["post_locs"].to_numpy()
            pre_comp = self.edges["pre_global_comp_index"].to_numpy()
            nodes = self.nodes.set_index("global_comp_index")
            pre_branch = nodes.loc[pre_comp, "global_branch_index"].to_numpy()
            post_comp = self.edges["post_global_comp_index"].to_numpy()
            post_branch = nodes.loc[post_comp, "global_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_in_view)))

        pre_comp = self.edges["pre_global_comp_index"].to_numpy()
        nodes = self.nodes.set_index("global_comp_index")
        pre_cell = nodes.loc[pre_comp, "global_cell_index"].to_numpy()
        post_comp = self.edges["post_global_comp_index"].to_numpy()
        post_cell = nodes.loc[post_comp, "global_cell_index"].to_numpy()

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

        return graph

    def _infer_synapse_type_ind(self, synapse_name):
        syn_names = self.base.synapse_names
        is_new_type = False if synapse_name in syn_names else True
        type_ind = len(syn_names) if is_new_type else syn_names.index(synapse_name)
        return type_ind, is_new_type

    def _update_synapse_state_names(self, synapse_type):
        # (Potentially) update variables that track meta information about synapses.
        self.base.synapse_names.append(synapse_type._name)
        self.base.synapse_param_names += list(synapse_type.synapse_params.keys())
        self.base.synapse_state_names += list(synapse_type.synapse_states.keys())
        self.base.synapses.append(synapse_type)

    def _append_multiple_synapses(self, pre_nodes, post_nodes, synapse_type):
        # Add synapse types to the module and infer their unique identifier.
        synapse_name = synapse_type._name
        type_ind, is_new = self._infer_synapse_type_ind(synapse_name)
        if is_new:  # synapse is not known
            self._update_synapse_state_names(synapse_type)

        index = len(self.base.edges)
        indices = [idx for idx in range(index, index + len(pre_nodes))]
        global_edge_index = pd.DataFrame({"global_edge_index": indices})
        post_loc = loc_of_index(
            post_nodes["global_comp_index"].to_numpy(),
            post_nodes["global_branch_index"].to_numpy(),
            self.ncomp_per_branch,
        )
        pre_loc = loc_of_index(
            pre_nodes["global_comp_index"].to_numpy(),
            pre_nodes["global_branch_index"].to_numpy(),
            self.ncomp_per_branch,
        )

        # Define new synapses. Each row is one synapse.
        pre_nodes = pre_nodes[["global_comp_index"]]
        pre_nodes.columns = ["pre_global_comp_index"]
        post_nodes = post_nodes[["global_comp_index"]]
        post_nodes.columns = ["post_global_comp_index"]
        new_rows = pd.concat(
            [
                global_edge_index,
                pre_nodes.reset_index(drop=True),
                post_nodes.reset_index(drop=True),
            ],
            axis=1,
        )
        new_rows["type"] = synapse_name
        new_rows["type_ind"] = type_ind
        new_rows["pre_locs"] = pre_loc
        new_rows["post_locs"] = post_loc
        self.base.edges = concat_and_ignore_empty(
            [self.base.edges, new_rows], ignore_index=True, axis=0
        )
        self._add_params_to_edges(synapse_type, indices)
        self.base.edges["controlled_by_param"] = 0
        self._edges_in_view = self.edges.index.to_numpy()

    def _add_params_to_edges(self, synapse_type, indices):
        # Add parameters and states to the `.edges` table.
        for key, param_val in synapse_type.synapse_params.items():
            self.base.edges.loc[indices, key] = param_val

        # Update synaptic state array.
        for key, state_val in synapse_type.synapse_states.items():
            self.base.edges.loc[indices, key] = state_val

__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
 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
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_list = cells
    self.ncomp_per_branch = np.concatenate(
        [cell.ncomp_per_branch for cell in cells]
    )
    self.ncomp = int(np.max(self.ncomp_per_branch))
    self.cumsum_ncomp = cumsum_leading_zero(self.ncomp_per_branch)
    self._internal_node_inds = np.arange(self.cumsum_ncomp[-1])
    self._append_params_and_states(self.network_params, self.network_states)

    self.nbranches_per_cell = [cell.total_nbranches for cell in 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["global_comp_index"] = np.arange(self.cumsum_ncomp[-1])
    self.nodes["global_branch_index"] = np.repeat(
        np.arange(self.total_nbranches), self.ncomp_per_branch
    ).tolist()
    self.nodes["global_cell_index"] = list(
        itertools.chain(
            *[[i] * int(cell.cumsum_ncomp[-1]) for i, cell in enumerate(cells)]
        )
    )
    self._update_local_indices()
    self._init_view()

    parents = [cell.comb_parents for cell in 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 cells])
    self._cumsum_nbranchpoints_per_cell = cumsum_leading_zero(nbranchpoints)

    # Channels.
    self._gather_channels_from_constituents(cells)

    self._initialize()
    del self._cells_list

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
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
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 = super().vis(
            dims=dims,
            col=col,
            ax=ax,
            type=type,
            morph_plot_kwargs=morph_plot_kwargs,
        )

        pre_locs = self.edges["pre_locs"].to_numpy()
        post_locs = self.edges["post_locs"].to_numpy()
        pre_comp = self.edges["pre_global_comp_index"].to_numpy()
        nodes = self.nodes.set_index("global_comp_index")
        pre_branch = nodes.loc[pre_comp, "global_branch_index"].to_numpy()
        post_comp = self.edges["post_global_comp_index"].to_numpy()
        post_branch = nodes.loc[post_comp, "global_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