1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
// SPDX-FileCopyrightText: 2026 philo-the-dendron
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Spiking Neural Network — topology builders + step orchestrator.
//!
//! # Module placement
//!
//! This module is `std`-gated. The hot-path primitives ([`LIFNeuron`], [`Synapse`])
//! are `no_std`-compatible; this orchestrator uses `Vec`
//! for desktop/server simulation. For bare-metal RISC-V deployment,
//! [`FixedNetwork`](crate::fixed::FixedNetwork) steps the same network in arrays,
//! `no_std`, without plasticity.
//!
//! # Invariants (testable)
//!
//! - `SpikingNeuralNetwork::new(0, ...)` always refuses, with
//! [`Error::NeuronCountOutOfRange`].
//! - `step()` advances `time_us()`, a `u64`, by exactly `dt_us`
//! (saturating at `u64::MAX`, about 585,000 years of model time).
//! - Topology builders never create self-connections.
//! - LFSR RNG is deterministic: same seed → same network connectivity.
//! - The topology builders' weights respect the presynaptic neuron's type (E →
//! positive, I → negative; `prop_topology_weights_respect_presynaptic_type`).
//! `add_synapse` keeps the weight it is given, of either sign, as an NIR import
//! wires them.
//! - `step()` delivers each synapse under its own `pre`, in the order it
//! was added, however adds and steps interleave.
//!
//! # Bug fixes vs v0.1
//!
//! - **Spatial grid dropped entirely.** v0.1's spatial grid used `grid_x = id % size`
//! and `grid_y = id % size` (same formula → diagonal-only grid, not 2D), and a
//! fallback loop processed every firing neuron anyway, making the grid dead code
//! that only added memory + complexity. CSR sparse matrix is the real value.
//! - **Plasticity dt fixed.** v0.1 used hardcoded `dt_ltd = -1000` for the LTD branch,
//! but `dt < 0` means pre-before-post which is LTP sign — the LTD branch was
//! secretly doing LTP. v2 computes dt from actual pre/post spike timing.
//! - **Plasticity synapse-index bug fixed.** v0.1 indexed `self.synapses[post_id]`,
//! using the postsynaptic neuron ID as a synapse vector index. That accesses the
//! wrong synapse (or panics). v2 tracks `synapse_index` in the plasticity queue.
//! - **Full pairwise STDP (Stage 1.5d).** Through Stage 1.5c `update_plasticity`
//! visited only pre-firing events, so `dt ≥ 0` always and the LTP branch
//! (`dt < 0`) was unreachable — the rule was structurally LTD-only. v2 now runs
//! a second, disjoint post-firing LTP pass via a reverse CSR.
//! - **CSR `set_weight` inverse-permutation fix (Stage 1.5d).** The counting-sort
//! `finalize()` reorders `weights[]` by `pre_id`, so the prior `set_weight(syn_idx)`
//! (which indexed `weights[syn_idx]` directly) wrote deltas to the wrong slots,
//! desynchronizing transmission weights from `synapses[].weight`. v2 routes the
//! write through an inverse permutation built in `finalize()`.
#![allow(clippy::module_name_repetitions)]
#![allow(
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_sign_loss,
clippy::cast_precision_loss,
clippy::cast_lossless,
clippy::float_cmp,
clippy::similar_names
)]
use crate::csr::SparseSynapseMatrix;
pub use crate::stats::NetworkStats;
use crate::lif_neuron::{dt_over_tau, LIFNeuron, NeuronType, VoltageResolution};
#[cfg(feature = "unstable-stdp")]
use crate::synapse::STDPRule;
use crate::synapse::Synapse;
use crate::{Error, Result};
use std::collections::HashMap;
use std::vec::Vec;
/// Default biological E/I ratio (80% excitatory, 20% inhibitory — cortical).
const DEFAULT_EXCITATORY_RATIO: f64 = 0.8;
/// Default weight for excitatory synapses (fixed-point, 1000 = 1.0).
const DEFAULT_EXCITATORY_WEIGHT: i16 = 100;
/// Default weight for inhibitory synapses (negative, fixed-point).
const DEFAULT_INHIBITORY_WEIGHT: i16 = -150;
/// Default LFSR seed (deterministic across runs).
const DEFAULT_SEED: u32 = 0x1234_5678;
/// LFSR seed for stochastic ternary flips (Stage 1.5b). Independent of the
/// topology seed so plasticity randomness doesn't correlate with wiring.
#[cfg(feature = "unstable-stdp")]
const TERNARY_FLIP_SEED: u32 = 0xA5A5_5A5A;
/// LFSR Galois tap for 16-bit maximal-length (period `65_535`).
const LFSR_TAP: u32 = 0xB400;
/// Default synaptic transmission divisor (the historical bare `weight / 10`).
/// See [`SpikingNeuralNetwork::synaptic_input_divisor`] — THE coupling knob.
const DEFAULT_SYNAPTIC_INPUT_DIVISOR: u16 = 10;
/// Network topology descriptor. Passed to [`SpikingNeuralNetwork::new`] and
/// consumed by `build_topology()`.
///
/// `f64` fields are configuration-time parameters (not hot-path), so floating-point
/// is acceptable here — the `no_std` constraint applies to per-step computation only.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum NetworkTopology {
/// Random sparse connectivity. `connectivity ∈ [0.0, 1.0]` is the fraction of
/// all possible (pre ≠ post) pairs to wire; `build_topology` refuses
/// any other value, NaN included.
Random {
/// Fraction of the possible (pre ≠ post) pairs to wire.
connectivity: f64,
},
/// Watts-Strogatz small-world. Ring lattice: each neuron wires to the
/// `local_connections` neurons after it on the ring, each edge rewired
/// with probability `rewiring_prob ∈ [0.0, 1.0]`; `build_topology`
/// refuses any other value, NaN included. Past `neuron_count − 1` the
/// offsets go round the ring again: an offset that lands on the neuron
/// itself is skipped, and the others wire the same neighbours again, so
/// a pair can carry more than one synapse
/// (`smallworld_keeps_its_wiring_inside_0_to_1`, 5 neurons at 10).
SmallWorld {
/// Ring offsets per neuron, 1 to this, before rewiring.
local_connections: u8,
/// Probability a local connection is rewired.
rewiring_prob: f64,
},
/// Layered feedforward. `layers` defines the neuron count per layer:
/// every layer has at least one neuron, and the sizes sum to the
/// network's `neuron_count`. `build_topology` refuses any other list.
Feedforward {
/// Neuron count per layer, input first.
layers: &'static [u16],
},
/// Balanced E/I network with 4 connection classes (E→E, E→I, I→E, I→I).
/// `excitatory_ratio ∈ (0.0, 1.0)` is the fraction of neurons that are excitatory.
/// The excitatory count is the neuron count times the ratio, truncated,
/// and `build_topology` refuses a network it leaves with no neuron of
/// one type: a network of one neuron at the default 0.8 has no
/// excitatory neuron.
Balanced {
/// Fraction of the neurons that are excitatory.
excitatory_ratio: f64,
},
}
impl Default for NetworkTopology {
fn default() -> Self {
Self::Balanced {
excitatory_ratio: DEFAULT_EXCITATORY_RATIO,
}
}
}
/// Spike event emitted by a neuron during a [`SpikingNeuralNetwork::step`].
///
/// The step builds it and a caller reads it. Not exhaustive: a field may
/// come in a minor release.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Spike {
/// ID of the neuron that fired.
pub neuron_id: u16,
/// Simulation time (μs) at which the spike occurred. A `u64`: past 2^32 μs
/// (71.6 min) it no longer fits a `u32`, and the stamp the neuron keeps
/// of its last spike, which has no getter, holds its low 32 bits.
pub time_us: u64,
}
/// Plasticity queue entry: `(pre_neuron_id, post_neuron_id, synapse_index, pre_spike_time_us)`.
///
/// `synapse_index` is the shared stable index into both `self.synapses` and the
/// corresponding CSR weight slot, so plasticity can update the same synapse the
/// propagation pass just used.
/// Drained by [`SpikingNeuralNetwork::update_plasticity`].
#[cfg(feature = "unstable-stdp")]
type PlasticityEntry = (u16, u16, usize, u64);
/// Main spiking neural network orchestrator.
///
/// Holds [`LIFNeuron`] + [`Synapse`] collections, a CSR synapse matrix
/// for fast synaptic transmission, and, with the `unstable-stdp` feature, an
/// `STDPRule` for plasticity. One call to [`step`](Self::step) advances the
/// simulation by `dt_us` microseconds.
///
/// A network starts with plasticity off and does not learn. Only
/// `set_plasticity_enabled`, behind `unstable-stdp`, turns it on.
pub struct SpikingNeuralNetwork {
neurons: Vec<LIFNeuron>,
/// Parallel to CSR insertion order. Indexed via the plasticity queue and the
/// stable indices carried inside `synapse_matrix`.
synapses: Vec<Synapse>,
/// CSR storage for fast per-presynaptic iteration during transmission.
///
/// Invariant: `synapse_matrix.synapse_indices[k]` identifies the same logical
/// synapse as `synapses[synapse_matrix.synapse_indices[k]]`, and the weight in
/// the corresponding CSR slot is kept in sync after every STDP update.
synapse_matrix: SparseSynapseMatrix,
dt_us: u32,
time_us: u64,
#[cfg(feature = "unstable-stdp")]
plasticity_rule: STDPRule,
stats: NetworkStats,
topology: NetworkTopology,
seed: u32,
/// Buffer of pending plasticity updates from the most recent step.
#[cfg(feature = "unstable-stdp")]
plasticity_queue: Vec<PlasticityEntry>,
/// Whether STDP weight updates are applied each step. Default `false`
/// in both constructors; only `set_plasticity_enabled`, behind
/// `unstable-stdp`, can raise it, so a build without the feature never
/// learns. The visualizer toggles it on to watch learning happen.
plasticity_enabled: bool,
/// LFSR state for stochastic ternary bucket-flips (Stage 1.5b). Advanced
/// once per active synapse in [`stochastic_ternary_step`]. Independent of
/// `seed` (topology) so plasticity randomness decorrelates from wiring.
#[cfg(feature = "unstable-stdp")]
ternary_flip_lfsr: u32,
/// The voltage grid every neuron is on, one per network: `from_neurons`
/// refuses two (see [`LIFNeuron::voltage_resolution`]). Kept at network
/// level so stats can convert native quanta back to mV.
voltage_resolution: VoltageResolution,
/// Synaptic transmission divisor — **THE coupling knob** (R4(ii),
/// 2026-08-20). Each presynaptic spike injects
/// `weight / synaptic_input_divisor` pA into the postsynaptic neuron.
///
/// This is the constant the session-E/F redesign fork turns on (ISA
/// 2026-08-18, "coupling constant / in-vivo drive / balanced
/// background" fork): whether imported weights can gate firing at a
/// given drive is decided here. Historical value `10` (the bare
/// `weight / 10` the audits found); the default preserves every
/// recorded result bit-exactly. Smaller divisor ⇒ stronger coupling
/// (a DIVISOR, not a gain: higher = weaker).
synaptic_input_divisor: u16,
}
/// The noise amplitude (pA) a topology builder gives the neurons it makes: the
/// amplitude every neuron had by default until round 61, so a network built by
/// [`SpikingNeuralNetwork::new`] runs as it always did. A neuron built by its
/// own constructor has none.
const BUILT_NEURON_NOISE_PA: u8 = 5;
impl SpikingNeuralNetwork {
/// Construct a network with `neuron_count` neurons, `dt_us` simulation
/// step, and the given `topology`. Neurons are created with the biological
/// 80/20 E/I ratio, or with the ratio a `Balanced` topology gives.
/// Each has noise amplitude 5 pA (`BUILT_NEURON_NOISE_PA`), unlike a neuron
/// from `LIFNeuron::new`, which is silent; [`from_neurons`](Self::from_neurons)
/// takes neurons as given.
///
/// # Errors
///
/// [`Error::NeuronCountOutOfRange`] if `neuron_count == 0`;
/// [`Error::ZeroTimeStep`] if `dt_us == 0`;
/// [`Error::FrozenMembrane`] if a neuron's membrane cannot move at
/// `dt_us`: under 20 μs with an excitatory neuron (τ = 20 ms),
/// under 10 μs with an inhibitory one (τ = 10 ms).
pub fn new(neuron_count: u16, dt_us: u32, topology: NetworkTopology) -> Result<Self> {
Self::new_with_voltage_resolution(
neuron_count,
dt_us,
topology,
VoltageResolution::Millivolt,
)
}
/// [`new`](Self::new) with an explicit voltage grid for every neuron —
/// [`VoltageResolution::CentiMillivolt`] opens the sub-mV regime (dead
/// zone ≈ 2 pA) where the ternary substrate's ±12 pA recurrent pulses
/// move the membrane. All downstream behavior (drive, STDP, plasticity)
/// is grid-independent; only membrane arithmetic granularity changes.
///
/// # Errors
///
/// Same as [`new`](Self::new).
pub fn new_with_voltage_resolution(
neuron_count: u16,
dt_us: u32,
topology: NetworkTopology,
resolution: VoltageResolution,
) -> Result<Self> {
if neuron_count == 0 {
return Err(Error::NeuronCountOutOfRange);
}
if dt_us == 0 {
return Err(Error::ZeroTimeStep);
}
// Neuron-type assignment honors the topology's ratio when `Balanced`
// parameterizes it; otherwise the biological 80/20 default. Keeping
// this in sync with `build_balanced`'s E/I partition is what upholds
// the module-doc sign invariant (E → positive outgoing weight,
// I → negative). Previously this was hardcoded to 0.8, so a Balanced
// topology with a different ratio silently mismatched the wiring
// partition and broke the invariant.
let excitatory_ratio = match topology {
NetworkTopology::Balanced { excitatory_ratio } => excitatory_ratio.clamp(0.0, 1.0),
_ => DEFAULT_EXCITATORY_RATIO,
};
// Same truncation as `build_balanced`'s `exc_count` — the partition
// must be bit-identical or the sign invariant breaks at non-integer
// `n * ratio` boundaries.
let exc_count = (neuron_count as f64 * excitatory_ratio) as u16;
let mut neurons = Vec::with_capacity(neuron_count as usize);
for id in 0..neuron_count {
let nt = if id < exc_count {
NeuronType::Excitatory
} else {
NeuronType::Inhibitory
};
neurons.push(
LIFNeuron::new(id, nt, resolution).with_noise_amplitude_pa(BUILT_NEURON_NOISE_PA),
);
}
if !membranes_move(&neurons, dt_us) {
return Err(Error::FrozenMembrane);
}
// No room is reserved for synapses, as in `from_neurons`: they grow
// as `build_topology` adds them, after its rules.
Ok(Self {
neurons,
synapses: Vec::new(),
synapse_matrix: SparseSynapseMatrix::new(neuron_count, 0),
dt_us,
time_us: 0,
#[cfg(feature = "unstable-stdp")]
plasticity_rule: STDPRule::new(),
stats: NetworkStats::new(),
topology,
seed: DEFAULT_SEED,
#[cfg(feature = "unstable-stdp")]
plasticity_queue: Vec::new(),
plasticity_enabled: false,
#[cfg(feature = "unstable-stdp")]
ternary_flip_lfsr: TERNARY_FLIP_SEED,
voltage_resolution: resolution,
synaptic_input_divisor: DEFAULT_SYNAPTIC_INPUT_DIVISOR,
})
}
/// Build a network from caller-supplied neurons — synapses come
/// only from later [`add_synapse`](Self::add_synapse) calls and
/// [`build_topology`](Self::build_topology) must NOT be called
/// (it would discard the caller's wiring; the stored topology
/// marker is inert here). The constructor path for imported
/// models (NIR) whose neuron parameters are not the biological
/// defaults. Each neuron is at rest, as `LIFNeuron::new` and the
/// `with_*` chain build it, and its id is its position, which indexes
/// it and seeds its noise.
///
/// # Errors
///
/// [`Error::NeuronCountOutOfRange`] unless `neurons` holds 1 to 65,535
/// neurons, since ids are `u16` (`Spike::neuron_id`, `add_synapse`) and
/// so is the count; [`Error::ZeroTimeStep`] when `dt_us == 0`;
/// [`Error::FrozenMembrane`] when a neuron's membrane cannot move at
/// `dt_us`, its `tau_membrane_us` 0 or above
/// `1000 · dt_us`; [`Error::MixedVoltageGrids`] unless every
/// neuron is on one voltage grid, the one the network keeps for its
/// stats; [`Error::NeuronNotAtRest`] when a neuron carries state: its
/// membrane off its resting potential, refractory time left, a current
/// or a stamp ([`LIFNeuron::reset`] brings it back);
/// [`Error::NeuronIdMismatch`] unless each neuron's id is its position
/// in `neurons`.
pub fn from_neurons(neurons: Vec<LIFNeuron>, dt_us: u32) -> Result<Self> {
if !(1..=usize::from(u16::MAX)).contains(&neurons.len()) {
return Err(Error::NeuronCountOutOfRange);
}
if dt_us == 0 {
return Err(Error::ZeroTimeStep);
}
if !membranes_move(&neurons, dt_us) {
return Err(Error::FrozenMembrane);
}
let resolution = neurons[0].voltage_resolution;
if neurons.iter().any(|n| n.voltage_resolution != resolution) {
return Err(Error::MixedVoltageGrids);
}
if !neurons.iter().all(at_rest) {
return Err(Error::NeuronNotAtRest);
}
if !ids_are_positions(&neurons) {
return Err(Error::NeuronIdMismatch);
}
let neuron_count = neurons.len() as u16; // exact: at most 65,535
Ok(Self {
neurons,
synapses: Vec::new(),
synapse_matrix: SparseSynapseMatrix::new(neuron_count, 0),
dt_us,
time_us: 0,
#[cfg(feature = "unstable-stdp")]
plasticity_rule: STDPRule::new(),
stats: NetworkStats::new(),
topology: NetworkTopology::Random { connectivity: 0.0 },
seed: DEFAULT_SEED,
#[cfg(feature = "unstable-stdp")]
plasticity_queue: Vec::new(),
plasticity_enabled: false,
#[cfg(feature = "unstable-stdp")]
ternary_flip_lfsr: TERNARY_FLIP_SEED,
voltage_resolution: resolution,
synaptic_input_divisor: DEFAULT_SYNAPTIC_INPUT_DIVISOR,
})
}
/// Build the configured topology. [`new`](Self::new) wires nothing, so
/// a network stepped before this call steps with no synapse but those
/// [`add_synapse`](Self::add_synapse) gave it.
///
/// A second call clears any existing synapses, CSR state and pending
/// plasticity entries before it builds, so synapses never accumulate;
/// `Random`, `SmallWorld` and `Balanced` go on from the seed the last
/// build left, so a second call can wire differently. Runtime spike
/// counters are preserved (use [`reset`](Self::reset) to clear those
/// too). On success, [`synapse_count`](Self::synapse_count) is the new
/// synapse count.
///
/// # Errors
///
/// [`Error::ProbabilityOutOfRange`] for a `Random` connectivity or a
/// `SmallWorld` rewiring probability outside 0 to 1, NaN included, at
/// any neuron count;
/// [`Error::BadLayerSizes`] for a `Feedforward` list with a layer of no
/// neuron, or whose sizes do not sum to the neuron count;
/// [`Error::MissingNeuronType`] for a `Balanced` ratio that leaves no
/// excitatory or no inhibitory neuron (each topology's doc states its
/// rule).
pub fn build_topology(&mut self) -> Result<()> {
self.synapses.clear();
self.synapse_matrix.clear();
#[cfg(feature = "unstable-stdp")]
self.plasticity_queue.clear();
match self.topology {
NetworkTopology::Random { connectivity } => self.build_random(connectivity)?,
NetworkTopology::SmallWorld {
local_connections,
rewiring_prob,
} => self.build_small_world(local_connections, rewiring_prob)?,
NetworkTopology::Feedforward { layers } => self.build_feedforward(layers)?,
NetworkTopology::Balanced { excitatory_ratio } => {
self.build_balanced(excitatory_ratio)?;
}
}
// The builders add in any pre order; one sort here, so the network
// leaves clean and its first step sorts nothing.
self.synapse_matrix.finalize();
Ok(())
}
/// Advance the simulation by one `dt_us`. Returns the spikes emitted
/// this step in neuron-id order (`every_wiring_steps_as_its_synapses_were_added`
/// reads it); every spike of a step carries the step's time.
///
/// A step first sorts the CSR if a synapse came in since the last sort
/// ([`add_synapse`](Self::add_synapse); a step and `build_topology`
/// sort): O(S + N), S the synapses and N the neurons. A batch of adds
/// pays it once, at the next step; a caller who adds between steps pays
/// it at each step after an add.
///
/// # Order
///
/// 1. Every neuron's adaptation current decays by 1 pA toward 0: one at
/// or under 0 stays ([`LIFNeuron::decay_adaptation_current`]).
/// 2. Every neuron integrates, in id order, at the current time: step 0
/// runs at time 0. Its current is `input_currents[id]` plus the pulses
/// the step before delivered ([`LIFNeuron::integrate_and_fire`]
/// § Semantics). A missing entry of `input_currents` reads as 0 and an
/// entry past the last neuron is ignored.
/// 3. Every neuron's synaptic current is cleared.
/// 4. Each neuron that fired, in id order, adds `weight / divisor` pA to
/// each of its targets, in the CSR's order: the division truncates
/// toward zero, the add saturates in `i16`
/// ([`synaptic_input_divisor`](Self::synaptic_input_divisor)).
/// 5. With the `unstable-stdp` feature and plasticity enabled
/// (`set_plasticity_enabled`; a network starts with it off), the STDP
/// passes run on this step's spikes. A build without the feature has
/// no item 5.
/// 6. The time advances by `dt_us`. It is a `u64`, saturating at
/// `u64::MAX`, about 585,000 years of model time: no run reaches it.
/// The neurons are handed its low 32 bits, which wrap at 2^32 μs (71.6
/// min) without changing a spike
/// (`the_clock_runs_past_the_u32_ceiling`).
///
/// [`FixedNetwork::step`](crate::fixed::FixedNetwork::step) is this order
/// without item 5, in every build.
///
/// # The one-step delay
///
/// A spike at step t reaches `post` at step t + 1: a step integrates the
/// pulses of the step before it, then clears them, then propagates its
/// own (the three `transmission_*` tests). A `post` that is refractory at
/// step t + 1 integrates nothing, and the clear drops the pulse: it is
/// lost, not deferred
/// (`a_pulse_to_a_refractory_post_is_dropped_not_deferred`).
///
/// # Errors
///
/// None today: no path of the step returns `Err`.
pub fn step(&mut self, input_currents: &[i16]) -> Result<Vec<Spike>> {
// A synapse added since the last sort is in no row yet: sort first,
// so this step delivers each synapse under its own `pre`, in the
// order added (nothing to do on a clean network).
self.finalize_synapses();
let mut output_spikes: Vec<Spike> = Vec::new();
let mut firing_neurons: Vec<u16> = Vec::new();
// Adaptation decay (adaptation ONLY — session F split). MUST run
// each step or adaptation accumulates (+2/spike while a neuron's
// switch is on) without bound and silences the network — a bug
// that previously made every sustained run self-quench after ~3 s.
// Position: pre-integration, phase-identical to the historical
// opening loop.
for n in &mut self.neurons {
n.decay_adaptation_current();
}
#[cfg(feature = "unstable-stdp")]
self.plasticity_queue.clear();
// Phase 1: integrate-and-fire all neurons (O(n)). This READS the
// recurrent pulses injected by the PREVIOUS step's Phase 2 — the
// one-step synaptic delay this orchestrator has always claimed and,
// since session F, actually has. (Historical bug, pinned then fixed:
// the pulses used to be cleared before this read, so recurrent
// transmission was structurally dead — every network-dynamic number
// in the lineage was re-pinned on this fix.)
// The neurons keep the low 32 bits of the clock
// (`LIFNeuron::integrate_and_fire` § Semantics item 1).
let now_us = self.time_us as u32;
for (idx, neuron) in self.neurons.iter_mut().enumerate() {
let current_pa = input_currents.get(idx).copied().unwrap_or(0);
if neuron.integrate_and_fire(current_pa, self.dt_us, now_us) {
let neuron_id = idx as u16;
let spike = Spike {
neuron_id,
time_us: self.time_us,
};
output_spikes.push(spike);
firing_neurons.push(neuron_id);
}
}
// Post-read clear: the accumulator has been consumed; zero it so
// Phase 2's fresh pulses are the only content next step integrates.
// (A refractory neuron's unread pulse is dropped here — rare at
// ~35 Hz vs 2 ms refractory; documented, session F.)
for n in &mut self.neurons {
n.clear_synaptic_current();
}
// Phase 2: propagate spikes through synapses (O(active_synapses)).
// For each firing neuron, iterate its outgoing CSR slice and inject
// current into each postsynaptic partner. Queue plasticity updates.
// The divisor (default 10) is the coupling knob — see
// `synaptic_input_divisor`.
let input_divisor = self.synaptic_input_divisor as i16;
for &pre_id in &firing_neurons {
for (post_id, weight, syn_idx) in self.synapse_matrix.connections(pre_id) {
if let Some(post_n) = self.neurons.get_mut(post_id as usize) {
post_n.add_synaptic_current(weight / input_divisor);
}
#[cfg(feature = "unstable-stdp")]
self.plasticity_queue
.push((pre_id, post_id, syn_idx, self.time_us));
// The queue is `syn_idx`'s one reader in the step.
#[cfg(not(feature = "unstable-stdp"))]
let _ = syn_idx;
}
}
// Phase 3: apply pairwise STDP plasticity (LTD + LTP passes).
// Gated so callers (e.g. the visualizer) can run in a sustained-firing
// mode with fixed weights, toggling learning on to observe it.
#[cfg(feature = "unstable-stdp")]
if self.plasticity_enabled {
self.update_plasticity(&firing_neurons);
}
// Advance time and stats.
self.time_us = self.time_us.saturating_add(u64::from(self.dt_us));
self.stats.total_spikes += output_spikes.len() as u64;
self.update_stats();
Ok(output_spikes)
}
/// `pre − post` in μs for two times read from a clock wider than the
/// neurons' 32-bit stamps: the difference of their low 32 bits, as a
/// two's-complement `i32`. It is exact while the real gap is under 2^31 μs
/// (35.8 min), and the rule is zero from |dt| = τ on (20 ms at the
/// defaults, and in effect from about 16 ms: the integer product
/// truncates), so a pair further apart counts for nothing. A stamp a whole
/// number of 71.6-minute turns stale pairs by chance, at the rate of the
/// nonzero values of dt over the turn: 32,259 of 2^32 at the defaults,
/// about 1 in 133,000 (`stdp_pairs_the_same_past_the_u32_ceiling`).
#[cfg(feature = "unstable-stdp")]
fn stamp_dt_us(pre_time: u64, post_time: u64) -> i32 {
(pre_time as u32).wrapping_sub(post_time as u32) as i32
}
/// Apply pairwise STDP for this step — both halves of the rule.
///
/// **LTD pass (pre-firing, post-before-pre):** for every queued presynaptic
/// spike, pair it with the postsynaptic neuron's most recent spike. If post
/// fired this step too, the a9a2679 same-step tie-break yields `dt = +1` →
/// LTD (the documented bias toward depression on coincidence); otherwise
/// `dt = pre_time − post.last_spike ≥ 0` → LTD branch. This is the
/// historically-existing path; left intact.
///
/// **LTP pass (post-firing, pre-before-post):** for every postsynaptic
/// neuron that fired this step, pair it with each incoming synapse's
/// presynaptic partner. When that presynaptic neuron fired *earlier* (a
/// previous step, within the STDP window) but *not this step*, `dt =
/// pre.last_spike − post_time < 0` → LTP. This is the half that was missing
/// through Stage 1.5c — the prior substrate was structurally LTD-only
/// (`update_plasticity` only visited pre-firing events, so `dt ≥ 0` always
/// and the LTP branch of `calculate_weight_change` was unreachable). It is
/// now reachable via the reverse CSR ([`SparseSynapseMatrix::incoming`]).
///
/// **No double-counting.** The two passes are disjoint per synapse per step:
/// a synapse whose pre and post both fire this step is handled by the LTD
/// pass (tie-break) and explicitly skipped by the LTP pass's `pre didn't
/// fire this step` guard — preserving the a9a2679 same-step invariant.
///
/// # Bug fix vs v0.1
///
/// v0.1 used `dt_ltd = -1000` hardcoded for the LTD branch (post not firing
/// this step), which is LTP sign. v2 computes dt from actual pre/post spike
/// timing. And through Stage 1.5c v2 only computed the LTD half (pre-firing
/// events); the LTP half is added here.
///
/// [`SparseSynapseMatrix::incoming`]: SparseSynapseMatrix::incoming
#[cfg(feature = "unstable-stdp")]
fn update_plasticity(&mut self, firing_neurons: &[u16]) {
if self.plasticity_queue.is_empty() && firing_neurons.is_empty() {
return;
}
let fired_this_step = |id: u16| firing_neurons.contains(&id);
// ----- LTD pass: pre-firing events (post-before-pre) -----
// dt ≥ 0 by construction (pre fires this step; post's reference spike is
// ≤ pre_time), so only the LTD branch of the rule fires here.
if !self.plasticity_queue.is_empty() {
for &(_pre_id, post_id, syn_idx, pre_time) in &self.plasticity_queue.clone() {
let Some(synapse) = self.synapses.get_mut(syn_idx) else {
continue;
};
let post_time = if fired_this_step(post_id) {
// Post fired this step → near-simultaneous → small positive
// dt → LTD. Use 1μs to break the tie toward LTD (treat pre
// as just after post). (a9a2679 same-step fix.)
pre_time.saturating_sub(1)
} else {
// Post didn't fire this step — use its last actual spike.
// If post never fired, last_spike_time_us = 0, giving a
// large positive dt → LTD with decayed magnitude (~0 outside
// the window once the sim has run a while).
self.neurons
.get(post_id as usize)
.map_or(0, |n| u64::from(n.last_spike_time_us))
};
// dt = pre_time - post_time. Positive (pre after post) → LTD.
let dt_us = Self::stamp_dt_us(pre_time, post_time);
let delta = self.plasticity_rule.calculate_weight_change(dt_us);
if delta != 0 {
// In-window pairing: bucket by dt for the histogram
// (dt = 1 is the same-step tie-break; larger dt is
// post-leads). Out-of-window deltas are 0, uncounted.
if dt_us <= 1 {
self.stats.stdp_pairs_same_step += 1;
} else {
self.stats.stdp_pairs_post_leads += 1;
}
}
synapse.update_weight(delta);
debug_assert!(syn_idx < self.synapse_matrix.len());
self.synapse_matrix.set_weight(syn_idx, synapse.weight);
self.stats.plasticity_events += 1;
}
}
// ----- LTP pass: post-firing events (pre-before-post) -----
// For each firing post, pair with each incoming presynaptic spike that
// happened strictly earlier (a previous step, within the window). The
// guard `!fired_this_step(pre_id)` keeps this disjoint from the LTD pass
// (same-step co-fire is LTD-only, preserving a9a2679) and prevents
// double-counting. `last_spike_time_us > 0` excludes neurons that never
// fired (their time-0 sentinel would otherwise fake a recent pre spike
// and spuriously potentiate silent partners early in the run).
let post_time = self.time_us;
// Collect work items first: incoming() borrows synapse_matrix
// immutably, but applying the delta mutates synapses + synapse_matrix.
let mut ltp_work: Vec<(usize, i32)> = Vec::new();
for &post_id in firing_neurons {
for (pre_id, syn_idx) in self.synapse_matrix.incoming(post_id) {
if fired_this_step(pre_id) {
continue; // same-step co-fire handled by LTD pass.
}
let Some(pre_n) = self.neurons.get(pre_id as usize) else {
continue;
};
let pre_time = u64::from(pre_n.last_spike_time_us);
if pre_time == 0 {
continue; // pre never fired — no real pre-before-post pair.
}
// dt = pre_time - post_time < 0 (pre fired earlier) → LTP branch.
let dt_us = Self::stamp_dt_us(pre_time, post_time);
if dt_us >= 0 {
continue; // defensive: only the LTP (dt<0) branch belongs here.
}
ltp_work.push((syn_idx, dt_us));
}
}
for (syn_idx, dt_us) in ltp_work {
let Some(synapse) = self.synapses.get_mut(syn_idx) else {
continue;
};
let delta = self.plasticity_rule.calculate_weight_change(dt_us);
if delta == 0 {
continue; // outside the window — no event to count.
}
self.stats.stdp_pairs_pre_leads += 1; // in-window pre-leads (LTP)
synapse.update_weight(delta);
debug_assert!(syn_idx < self.synapse_matrix.len());
self.synapse_matrix.set_weight(syn_idx, synapse.weight);
self.stats.plasticity_events += 1;
}
}
/// Update running statistics — the membrane average over every neuron.
fn update_stats(&mut self) {
let n = self.neurons.len();
if n == 0 {
return;
}
let total_v: i64 = self
.neurons
.iter()
.map(|x| i64::from(x.membrane_potential))
.sum();
// Convert native quanta → mV for the stat (÷scale; identity on
// the default grid).
let s = self.voltage_resolution.scale();
self.stats.avg_membrane_potential_mv = total_v as f64 / (n as f64 * f64::from(s));
let time_sec = self.time_us as f64 / 1_000_000.0;
if time_sec > 0.0 {
self.stats.firing_rate_hz = self.stats.total_spikes as f64 / (time_sec * n as f64);
}
}
/// Append a synapse. Both the CSR and the `synapses` vec get a copy,
/// and [`synapse_count`](Self::synapse_count) counts it. The next
/// [`step`](Self::step) delivers it, after the sort it runs first
/// (O(S + N)): adding between steps pays that sort at each step after
/// an add.
///
/// # Errors
///
/// [`Error::NeuronIdOutOfRange`] when `pre_id` or `post_id` is not
/// below the neuron count; [`Error::SelfConnection`] when they are one
/// id ([`Synapse::new`]).
pub fn add_synapse(&mut self, pre_id: u16, post_id: u16, weight: i16) -> Result<()> {
if pre_id as usize >= self.neurons.len() || post_id as usize >= self.neurons.len() {
return Err(Error::NeuronIdOutOfRange);
}
let synapse = Synapse::new(pre_id, post_id, weight)?;
let synapse_index = self.synapses.len();
debug_assert_eq!(synapse_index, self.synapse_matrix.len());
self.synapse_matrix
.add(pre_id, post_id, weight, synapse_index);
self.synapses.push(synapse);
Ok(())
}
/// Sort the CSR if a synapse came in since the last sort; on a clean
/// network, nothing. The step runs it first, and the NIR import once,
/// after its last edge, so the network it returns steps without a sort.
/// Crate-private: a network sorts its own CSR, so no caller needs to.
pub(crate) fn finalize_synapses(&mut self) {
if !self.synapse_matrix.is_dirty() {
return;
}
self.synapse_matrix.finalize();
}
/// Unstable: behind `unstable-stdp`.
/// Enable or disable STDP weight updates. Disabled is the default, in
/// both constructors: `step()` propagates spikes and advances time, and
/// synapse weights stay fixed — the sustained-firing visualization, the
/// control baseline, and the one state
/// [`FixedNetwork`](crate::fixed::FixedNetwork) converts from.
#[cfg(feature = "unstable-stdp")]
pub fn set_plasticity_enabled(&mut self, enabled: bool) {
self.plasticity_enabled = enabled;
}
/// Set the synaptic transmission divisor — **THE coupling knob** (see
/// [`synaptic_input_divisor`](Self::synaptic_input_divisor)). Each
/// presynaptic spike injects `weight / divisor` pA postsynaptically.
/// Default `10` (the historical bare constant); smaller = stronger
/// coupling.
///
/// # Errors
///
/// [`Error::DivisorOutOfRange`] unless `divisor` is 1 to 32,767: the
/// step divides by `divisor as i16`, and above 32,767 that cast is
/// negative.
pub fn set_synaptic_input_divisor(&mut self, divisor: u16) -> Result<()> {
if !(1..=32_767).contains(&divisor) {
return Err(Error::DivisorOutOfRange);
}
self.synaptic_input_divisor = divisor;
Ok(())
}
/// The current synaptic transmission divisor (default `10`).
#[must_use]
pub fn synaptic_input_divisor(&self) -> u16 {
self.synaptic_input_divisor
}
/// Whether STDP weight updates are currently applied each step. `false`
/// from both constructors, and always `false` in a build without
/// `unstable-stdp`, where nothing can turn it on. Stable, unlike its
/// setter: `FixedNetwork::try_from` reads it.
#[must_use]
pub fn plasticity_enabled(&self) -> bool {
self.plasticity_enabled
}
/// One-shot BitNet-Round ternarization of all synapse weights: `γ = mean|w|`,
/// each weight snapped to the nearest of `{-γ, 0, +γ}`. Syncs the CSR
/// transmission weights (`ternary_writes_reach_their_csr_slot`). Returns
/// `γ`; when `γ` rounds to 0, with no synapse or a mean magnitude under
/// one half, it returns 0 and leaves every weight as it was
/// (`ternarize_weights_leaves_the_weights_when_gamma_rounds_to_0`).
///
/// This is a *one-shot* quantizer for the ternary-bridge Stage 1 gate — it
/// does **not** install an ongoing ternary mode. Keeping weights on-grid
/// during a live STDP run is the caller's job: call [`reproject_ternary`]
/// after each [`step`](Self::step).
///
/// [`reproject_ternary`]: Self::reproject_ternary
#[must_use]
pub fn ternarize_weights(&mut self) -> i16 {
// Collect into a temp so the immutable γ scan borrow ends before the
// mutable snap pass (borrow-checker hygiene; one-shot op, alloc is fine).
let weights: Vec<i16> = self.synapses.iter().map(|s| s.weight).collect();
let gamma = crate::trit::tensor_scale(&weights);
if gamma == 0 {
return 0;
}
for (idx, s) in self.synapses.iter_mut().enumerate() {
s.weight = crate::trit::project_to_ternary(s.weight, gamma);
self.synapse_matrix.set_weight(idx, s.weight);
}
gamma
}
/// Re-project every synapse weight onto `{-gamma, 0, +gamma}` (nearest of
/// three) and sync the CSR. Returns the count of weights whose *stored i16
/// value* changed this call (i.e. STDP had pushed them off-grid).
///
/// Note: this counts i16 snaps, not ternary *bucket* transitions — a snap
/// from `+130` back to `+125` is a nonzero return but NOT a bucket flip.
/// Callers running the Stage 1 gate should track bucket flips separately
/// (classify with [`Trit::from_weight`] before/after) for the learning
/// signal; that's the metric that determines the gate verdict.
///
/// [`Trit::from_weight`]: crate::trit::Trit::from_weight
pub fn reproject_ternary(&mut self, gamma: i16) -> u32 {
if gamma == 0 {
return 0;
}
let mut snapped = 0u32;
for (idx, s) in self.synapses.iter_mut().enumerate() {
let new_w = crate::trit::project_to_ternary(s.weight, gamma);
if new_w != s.weight {
snapped += 1;
}
s.weight = new_w;
self.synapse_matrix.set_weight(idx, s.weight);
}
snapped
}
/// Unstable: behind `unstable-stdp`.
/// Stochastic ternary bucket-flip step (Stage 1.5b).
///
/// For every synapse, the STDP delta applied during [`step`](Self::step)
/// pushed the weight slightly off-grid (the weight was on-grid before the
/// step). This method:
///
/// 1. Measures the off-grid residual (= this step's STDP delta, since
/// `weight − project(weight) = delta` for small deltas relative to γ/2).
/// 2. Draws a Bernoulli trial with `P(flip) ∝ |residual|` via the network's
/// independent LFSR.
/// 3. On success, flips the ternary bucket one step toward the delta's sign
/// (LTP → +γ, LTD → −γ), saturating at the extreme bucket and respecting
/// each synapse's `[min_weight, max_weight]` bounds.
/// 4. Snaps all weights back onto `{-γ, 0, +γ}` regardless.
///
/// The stored weight is **genuinely ternary** at all times — no latent or
/// shadow state. Call after each `step()` in the Stage 1.5b regime, the
/// same way [`reproject_ternary`] is called in the Stage 1 (deterministic)
/// regime.
///
/// Returns the number of ternary bucket transitions (flips) this call.
///
/// [`reproject_ternary`]: Self::reproject_ternary
#[cfg(feature = "unstable-stdp")]
pub fn stochastic_ternary_step(&mut self, gamma: i16) -> u32 {
if gamma == 0 {
return 0;
}
let mut flips = 0u32;
let mut lfsr = self.ternary_flip_lfsr;
for (idx, s) in self.synapses.iter_mut().enumerate() {
let projected = crate::trit::project_to_ternary(s.weight, gamma);
let residual = s.weight - projected;
if residual == 0 {
continue; // No STDP event this step (or delta was zero).
}
lfsr = advance_lfsr(lfsr);
let draw = (lfsr & 0xFFFF) as u16;
let target = crate::trit::stochastic_ternary_flip(s.weight, gamma, residual, draw);
let clamped = target.clamp(s.min_weight, s.max_weight);
if clamped != projected {
flips += 1;
}
s.weight = clamped;
self.synapse_matrix.set_weight(idx, s.weight);
}
self.ternary_flip_lfsr = lfsr;
flips
}
/// Start the run over on the same network: every neuron back to rest
/// ([`LIFNeuron::reset`]), the clock at 0, and the stats a fresh
/// network's, every count 0 and the means at −70.0 mV and 0 Hz until
/// the next step. With `unstable-stdp`, each synapse's two counters,
/// `raw_stdp_delta` and `absorbed_delta`, go back to 0, and
/// `stochastic_ternary_step` draws its stream from the start. The
/// wiring and the weights stay (`reset_brings_every_neuron_to_rest`,
/// `reset_clears_time_and_spikes`,
/// `reset_gives_fresh_stats_and_keeps_the_weights`,
/// `reset_draws_the_flip_stream_from_the_start`).
pub fn reset(&mut self) {
for n in &mut self.neurons {
n.reset();
}
self.time_us = 0;
self.stats = NetworkStats::new();
#[cfg(feature = "unstable-stdp")]
{
self.plasticity_queue.clear();
self.ternary_flip_lfsr = TERNARY_FLIP_SEED;
for s in &mut self.synapses {
s.raw_stdp_delta = 0;
s.absorbed_delta = 0;
}
}
}
/// Read-only access to the synapse collection (for analysis / visualization).
/// Useful for demos, stats, and weight-evolution tracking.
#[must_use]
pub fn synapses(&self) -> &[Synapse] {
&self.synapses
}
/// Read-only access to the neuron collection (for analysis / visualization).
#[must_use]
pub fn neurons(&self) -> &[LIFNeuron] {
&self.neurons
}
/// The neurons, writable, for the crate's own tests: the one way to a
/// network at clock 0 on two grids, with a neuron that is not at rest,
/// or with an id off its position, which `from_neurons` refuses, so the
/// guards in `trace::header` and the freezer keep a test each.
#[cfg(test)]
pub(crate) fn neurons_mut(&mut self) -> &mut [LIFNeuron] {
&mut self.neurons
}
/// Read-only access to current stats.
#[must_use]
pub fn stats(&self) -> &NetworkStats {
&self.stats
}
/// Current simulation time (μs), a `u64`: it does not reach its ceiling in
/// any run (about 585,000 years of model time).
#[must_use]
pub fn time_us(&self) -> u64 {
self.time_us
}
/// The simulation step (μs), read by `FixedNetwork`'s conversion.
/// `pub(crate)` at 0.1.0 on purpose; it can go public in a minor release.
#[must_use]
pub(crate) fn dt_us(&self) -> u32 {
self.dt_us
}
/// Total neuron count.
#[must_use]
pub fn neuron_count(&self) -> u16 {
self.neurons.len() as u16
}
/// Total synapse count.
#[must_use]
pub fn synapse_count(&self) -> u32 {
self.synapses.len() as u32
}
// ----- Topology builders (private) -----
/// Random sparse connectivity via Fisher-Yates sampling without replacement.
fn build_random(&mut self, connectivity: f64) -> Result<()> {
if !probability_fits(connectivity) {
return Err(Error::ProbabilityOutOfRange);
}
let n = self.neurons.len();
if n < 2 {
return Ok(());
}
let total_possible = n * (n - 1);
// At most `total_possible`: the rule keeps `connectivity` within 0 to 1.
let target = ((total_possible as f64) * connectivity) as usize;
let mut rng = self.seed;
// The list of every pair is never stored: place k holds pair k
// (`pair_at`) unless a swap moved another pair there, and `moved`
// keeps only those places. The same draws and swaps as a stored
// list, so the same wiring, without its 4 bytes a pair.
let mut moved: HashMap<usize, usize> = HashMap::new();
for i in 0..target {
rng = advance_lfsr(rng);
let range = (total_possible - i) as u32;
let j = i + (rng % range) as usize;
// Swap places i and j, then take place i, which no later draw reaches.
let at_i = moved.remove(&i).unwrap_or(i);
let drawn = if j == i {
at_i
} else {
moved.insert(j, at_i).unwrap_or(j)
};
let (pre_id, post_id) = pair_at(drawn, n);
rng = advance_lfsr(rng);
let weight = typed_weight(self.neurons[pre_id as usize].neuron_type, rng);
self.add_synapse(pre_id, post_id, weight)?;
}
self.seed = rng;
Ok(())
}
/// Watts-Strogatz small-world: ring lattice with probabilistic **rewiring**.
///
/// For each directed local edge `(i, i+offset)`, with probability
/// `rewiring_prob` the target is replaced by a uniformly random node `≠ i`;
/// otherwise the local edge is kept. This is true Watts-Strogatz rewiring
/// (keep-or-replace), not shortcut augmentation — total edge count is
/// conserved at `~n × local_connections` (minus any wrap-around self-skips).
fn build_small_world(&mut self, local_connections: u8, rewiring_prob: f64) -> Result<()> {
if !probability_fits(rewiring_prob) {
return Err(Error::ProbabilityOutOfRange);
}
let n = self.neurons.len() as u16;
if n < 2 {
return Ok(());
}
let mut rng = self.seed;
for i in 0..n {
for offset in 1..=local_connections as u16 {
// Summed wide: near 65,535 neurons `i + offset` passes
// `u16::MAX`. Exact: the target is below `n`.
let local_target = ((u32::from(i) + u32::from(offset)) % u32::from(n)) as u16;
// Bug fix vs v0.1: when `local_connections >= n`, the modulo
// wraps to self-connections (e.g., n=5, offset=5 → target = i). Skip them.
if local_target == i {
continue;
}
rng = advance_lfsr(rng);
let roll = (rng & 0xFFFF) as f64 / 65_536.0;
let target = if roll < rewiring_prob {
// Rewire: pick a uniformly random target ≠ i.
rng = advance_lfsr(rng);
let mut new_target = (rng % n as u32) as u16;
if new_target == i {
new_target = (i + 1) % n;
}
new_target
} else {
local_target
};
let weight = typed_weight(self.neurons[i as usize].neuron_type, 0);
self.add_synapse(i, target, weight)?;
}
}
self.seed = rng;
Ok(())
}
/// Layered feedforward: connect each layer to the next with sparse projection.
/// Under the layer rule (`layer_sizes_fit`) the `u16` sums below stay
/// within the count, and no layer is divided by zero.
fn build_feedforward(&mut self, layers: &[u16]) -> Result<()> {
if !layer_sizes_fit(layers, self.neurons.len()) {
return Err(Error::BadLayerSizes);
}
let mut offset = 0u16;
for window in layers.windows(2) {
let curr_size = window[0];
let next_size = window[1];
let next_offset = offset + curr_size;
let conns_per = (next_size / 4).max(1);
let stride = (next_size / conns_per).max(1);
for i in 0..curr_size {
let pre_id = offset + i;
let nt = self.neurons[pre_id as usize].neuron_type;
for j in 0..conns_per {
let post_id = next_offset + (i + j * stride) % next_size;
let weight = typed_weight(nt, 0);
self.add_synapse(pre_id, post_id, weight)?;
}
}
offset += curr_size;
}
Ok(())
}
/// Balanced E/I network with 4 connection classes (E→E, E→I, I→E, I→I).
fn build_balanced(&mut self, excitatory_ratio: f64) -> Result<()> {
let n = self.neurons.len() as u16;
let exc_count = (n as f64 * excitatory_ratio.clamp(0.0, 1.0)) as u16;
let inh_count = n - exc_count;
// A neuron of each type, or an edge class below has no target: with
// no excitatory neuron the I→E edges divide by `exc_count`.
if exc_count == 0 || inh_count == 0 {
return Err(Error::MissingNeuronType);
}
let mut rng = self.seed;
// E→E (weak excitatory)
for _ in 0..(exc_count as u32 * 5) {
rng = advance_lfsr(rng);
let pre = (rng % exc_count as u32) as u16;
rng = advance_lfsr(rng);
let post = (rng % exc_count as u32) as u16;
if pre != post {
self.add_synapse(pre, post, 80)?;
}
}
// E→I (strong excitatory)
for _ in 0..(exc_count as u32 * 3) {
rng = advance_lfsr(rng);
let pre = (rng % exc_count as u32) as u16;
rng = advance_lfsr(rng);
let post = exc_count + (rng % inh_count as u32) as u16;
self.add_synapse(pre, post, 150)?;
}
// I→E (strong inhibitory)
for _ in 0..(inh_count as u32 * 8) {
rng = advance_lfsr(rng);
let pre = exc_count + (rng % inh_count as u32) as u16;
rng = advance_lfsr(rng);
let post = (rng % exc_count as u32) as u16;
self.add_synapse(pre, post, -200)?;
}
// I→I (moderate inhibitory)
for _ in 0..(inh_count as u32 * 2) {
rng = advance_lfsr(rng);
let pre = exc_count + (rng % inh_count as u32) as u16;
rng = advance_lfsr(rng);
let post_off = (rng % inh_count as u32) as u16;
if (pre - exc_count) != post_off {
self.add_synapse(pre, exc_count + post_off, -120)?;
}
}
self.seed = rng;
Ok(())
}
}
impl std::fmt::Debug for SpikingNeuralNetwork {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SpikingNeuralNetwork")
.field("neurons", &self.neurons.len())
.field("synapses", &self.synapses.len())
.field("dt_us", &self.dt_us)
.field("time_us", &self.time_us)
.field("topology", &self.topology)
.finish_non_exhaustive()
}
}
/// Pick weight sign based on presynaptic neuron type + a small jitter from `rng`.
fn typed_weight(nt: NeuronType, rng: u32) -> i16 {
match nt {
NeuronType::Excitatory => DEFAULT_EXCITATORY_WEIGHT + ((rng & 0xFF) as i16 % 50),
NeuronType::Inhibitory => DEFAULT_INHIBITORY_WEIGHT - ((rng & 0xFF) as i16 % 50),
}
}
/// Pair `k` of the list of every (pre, post) with pre ≠ post on `n`
/// neurons, by pre then post: each pre's row holds `n - 1` posts, itself
/// skipped.
fn pair_at(k: usize, n: usize) -> (u16, u16) {
let (pre, post) = (k / (n - 1), k % (n - 1));
let post = if post < pre { post } else { post + 1 };
(pre as u16, post as u16)
}
/// 16-bit Galois LFSR advance. Deterministic, no_std-friendly.
fn advance_lfsr(lfsr: u32) -> u32 {
(lfsr >> 1) ^ (if lfsr & 1 != 0 { LFSR_TAP } else { 0 })
}
/// The probability rule, `Random`'s connectivity and `SmallWorld`'s
/// rewiring probability alike: from 0 to 1. NaN is outside, as every
/// comparison with it is false. Checked before a builder reads the neuron
/// count, so it holds at every size.
fn probability_fits(p: f64) -> bool {
(0.0..=1.0).contains(&p)
}
/// The `Feedforward` rule: every layer has a neuron, and the sizes sum to
/// the neuron count. Summed in `usize`, since the sizes' `u16` overflows
/// past 65,535; an empty list sums to 0, which no network's count is. Its
/// one home: `build_feedforward` refuses a list that breaks it.
fn layer_sizes_fit(layers: &[u16], neuron_count: usize) -> bool {
!layers.contains(&0)
&& layers.iter().map(|&size| usize::from(size)).sum::<usize>() == neuron_count
}
/// The membrane rule: at the time step every neuron's `dt_over_tau` is at
/// least 1, so its membrane moves, a time constant neither 0 nor above
/// 1,000 time steps. Its one home: `new` and `from_neurons` refuse neurons
/// that break it.
fn membranes_move(neurons: &[LIFNeuron], dt_us: u32) -> bool {
neurons
.iter()
.all(|n| dt_over_tau(dt_us, n.tau_membrane_us) > 0)
}
/// At rest: the six fields [`LIFNeuron::reset`] writes hold the values it
/// writes, as `LIFNeuron::new` and the `with_*` chain build a neuron
/// (`from_neurons`; the freezer writes only neurons at rest).
fn at_rest(n: &LIFNeuron) -> bool {
n.membrane_potential == n.resting_potential
&& n.refractory_remaining_us == 0
&& n.last_update_time_us == 0
&& n.last_spike_time_us == 0
&& n.synaptic_current_pa == 0
&& n.adaptation_current_pa == 0
}
/// Each neuron's id is its position: what indexes it and seeds its noise
/// (`from_neurons`). Compared in `usize`, so no count of neurons wraps it.
fn ids_are_positions(neurons: &[LIFNeuron]) -> bool {
neurons
.iter()
.enumerate()
.all(|(i, n)| usize::from(n.id) == i)
}
#[cfg(test)]
mod tests {
#![allow(clippy::shadow_unrelated)]
use super::*;
use crate::trit::Trit;
use proptest::prelude::*;
// ----- Unit tests -----
#[test]
fn empty_network_rejected() {
let err = SpikingNeuralNetwork::new(0, 1000, NetworkTopology::default());
assert_eq!(err.err(), Some(Error::NeuronCountOutOfRange));
}
/// A zero step breaks two rules, since it freezes every membrane, and
/// `Error` promises no order between them. This test pins
/// `ZeroTimeStep`, today's order, on purpose: only the name shows that
/// `new`'s zero-step check ran.
#[test]
fn zero_time_step_rejected() {
let err = SpikingNeuralNetwork::new(10, 0, NetworkTopology::default());
assert_eq!(err.err(), Some(Error::ZeroTimeStep));
}
/// Ids are `u16`: 65,535 neurons build, counted whole, and the last one
/// fires as id 65,534; one more is refused, where its count wrapped to
/// 0 and the first step panicked in the CSR.
#[test]
fn from_neurons_takes_65_535_neurons_and_refuses_one_more() {
let most = (0..u16::MAX)
.map(|id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
.collect();
let mut net = SpikingNeuralNetwork::from_neurons(most, 1000).expect("the most neurons");
assert_eq!(net.neuron_count(), 65_535);
let mut drive = vec![0; 65_535];
drive[65_534] = 3000; // ON the threshold: the last neuron fires
let fired: Vec<u16> = net
.step(&drive)
.expect("step 0")
.iter()
.map(|s| s.neuron_id)
.collect();
assert_eq!(fired, [65_534]);
let one_more = (0..=u16::MAX)
.map(|id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
.collect();
assert_eq!(
SpikingNeuralNetwork::from_neurons(one_more, 1000).err(),
Some(Error::NeuronCountOutOfRange)
);
}
/// `from_neurons` refuses an empty list and a zero step, each by name.
/// A zero step also freezes every membrane, and `Error` promises no
/// order between two broken rules: the test pins `ZeroTimeStep`,
/// today's order, on purpose, since only the name shows that the
/// zero-step check ran.
#[test]
fn from_neurons_refuses_by_rule() {
assert_eq!(
SpikingNeuralNetwork::from_neurons(Vec::new(), 1000).err(),
Some(Error::NeuronCountOutOfRange)
);
assert_eq!(
SpikingNeuralNetwork::from_neurons(
vec![LIFNeuron::new(
0,
NeuronType::Excitatory,
VoltageResolution::Millivolt
)],
0
)
.err(),
Some(Error::ZeroTimeStep)
);
}
/// At rest means the six fields `reset` writes, each alone off its
/// value: not at rest; `reset` brings each back. The parameters are
/// not state: a neuron the chain rewrote is at rest, the membrane
/// moving with the resting potential.
#[test]
fn at_rest_reads_the_six_fields_reset_writes() {
let built = || LIFNeuron::new(0, NeuronType::Excitatory, VoltageResolution::Millivolt);
assert!(at_rest(&built()));
let off: [fn(&mut LIFNeuron); 6] = [
|n| n.membrane_potential -= 1,
|n| n.refractory_remaining_us = 1,
|n| n.last_update_time_us = 1,
|n| n.last_spike_time_us = 1,
|n| n.synaptic_current_pa = -1,
|n| n.adaptation_current_pa = 1,
];
for (i, move_it) in off.iter().enumerate() {
let mut n = built();
move_it(&mut n);
assert!(!at_rest(&n), "state field {i}");
n.reset();
assert!(at_rest(&n), "state field {i}, after reset");
}
let chained = built()
.with_resting_potential(-60)
.with_threshold(-40)
.with_refractory_period_us(0)
.with_adaptation_enabled(false);
assert!(at_rest(&chained));
}
/// A neuron that is not at rest, at each place of three: stepped once
/// with a current, stepped once at a clock past 0, given a pulse, and
/// fired. Refused by name; the same neuron after `reset`, and a
/// neuron the chain rewrote, build.
#[test]
fn from_neurons_refuses_a_neuron_not_at_rest() {
let mv = |id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt);
let stage: [fn(&mut LIFNeuron); 4] = [
|n| {
n.integrate_and_fire(600, 1000, 0);
},
|n| {
n.integrate_and_fire(0, 1000, 5000);
},
|n| n.add_synaptic_current(100),
|n| {
*n = n.clone().with_threshold(-100);
assert!(n.integrate_and_fire(0, 1000, 0));
},
];
for (s, staged) in stage.iter().enumerate() {
for at in 0..3u16 {
let mut neurons: Vec<LIFNeuron> = (0..3).map(mv).collect();
staged(&mut neurons[usize::from(at)]);
assert_eq!(
SpikingNeuralNetwork::from_neurons(neurons.clone(), 1000).err(),
Some(Error::NeuronNotAtRest),
"stage {s} at {at}"
);
neurons[usize::from(at)].reset();
assert!(
SpikingNeuralNetwork::from_neurons(neurons, 1000).is_ok(),
"stage {s} at {at}, after reset"
);
}
}
let chained = vec![mv(0).with_resting_potential(-60), mv(1)];
assert!(SpikingNeuralNetwork::from_neurons(chained, 1000).is_ok());
}
/// An id off its position: two swapped, every order of three but the
/// one in place, a gap and a repeat. In place, it builds.
#[test]
fn from_neurons_refuses_an_id_off_its_position() {
let with_ids = |ids: &[u16]| -> Vec<LIFNeuron> {
ids.iter()
.map(|&id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
.collect()
};
for ids in [
&[1, 0][..],
&[0, 2, 1],
&[1, 0, 2],
&[1, 2, 0],
&[2, 0, 1],
&[2, 1, 0],
&[0, 1, 3],
&[0, 0, 1],
&[1],
] {
assert_eq!(
SpikingNeuralNetwork::from_neurons(with_ids(ids), 1000).err(),
Some(Error::NeuronIdMismatch),
"{ids:?}"
);
}
for ids in [&[0][..], &[0, 1, 2]] {
assert!(SpikingNeuralNetwork::from_neurons(with_ids(ids), 1000).is_ok());
}
}
/// One grid per network: two grids in either order, and the odd one
/// second of three, last of three and third of four, where the network
/// kept neuron 0's grid and its stats read the other neurons' membranes
/// on it. One grid, either one, builds.
#[test]
fn from_neurons_refuses_two_grids() {
use VoltageResolution::{CentiMillivolt, Millivolt};
let on = |grids: &[VoltageResolution]| -> Vec<LIFNeuron> {
(0u16..)
.zip(grids)
.map(|(id, &grid)| LIFNeuron::new(id, NeuronType::Excitatory, grid))
.collect()
};
for grids in [
&[Millivolt, CentiMillivolt][..],
&[CentiMillivolt, Millivolt],
&[Millivolt, CentiMillivolt, Millivolt],
&[Millivolt, Millivolt, CentiMillivolt],
&[Millivolt, Millivolt, CentiMillivolt, Millivolt],
] {
assert_eq!(
SpikingNeuralNetwork::from_neurons(on(grids), 1000).err(),
Some(Error::MixedVoltageGrids),
"{grids:?}"
);
}
for grid in [Millivolt, CentiMillivolt] {
let net = SpikingNeuralNetwork::from_neurons(on(&[grid; 3]), 1000).expect("one grid");
assert_eq!(net.voltage_resolution, grid);
}
}
/// `new` refuses a step its neurons' membranes cannot move at: under
/// 20 μs with an excitatory neuron (τ = 20 ms), under 10 μs with an
/// inhibitory one (τ = 10 ms). One neuron at the default ratio is
/// inhibitory, and a `Balanced` ratio of 0 makes every neuron
/// inhibitory, of 1 excitatory. Before round 64 each built, its
/// membranes frozen.
#[test]
fn new_refuses_a_step_its_membranes_cannot_move_at() {
let mixed = NetworkTopology::default();
let inhibitory = NetworkTopology::Balanced {
excitatory_ratio: 0.0,
};
let excitatory = NetworkTopology::Balanced {
excitatory_ratio: 1.0,
};
for (n, topology, moves_from_us) in [
(10, mixed, 20),
(1, mixed, 10),
(10, inhibitory, 10),
(10, excitatory, 20),
] {
for dt in [1, 9, 10, 19, 20, 1000] {
assert_eq!(
SpikingNeuralNetwork::new(n, dt, topology).err(),
(dt < moves_from_us).then_some(Error::FrozenMembrane),
"{n} neurons, {topology:?}, {dt} μs"
);
}
}
}
/// `from_neurons` refuses a neuron whose membrane cannot move at the
/// step, a time constant of 0 or above 1,000 steps, at each place of
/// three; 1,000 steps exactly moves (`dt_over_tau` is 1). The other
/// two neurons' time constant is one step.
#[test]
fn from_neurons_refuses_a_membrane_that_cannot_move() {
for dt in [1u32, 1000, u32::MAX] {
let longest = u64::from(dt) * 1000;
let taus = [0, 1, longest, longest + 1, u64::from(u32::MAX)];
for tau in taus.into_iter().filter_map(|tau| u32::try_from(tau).ok()) {
for at in 0..3u16 {
let neurons = (0..3u16)
.map(|id| {
LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt)
.with_tau_membrane_us(if id == at { tau } else { dt })
})
.collect();
let moves = tau != 0 && u64::from(tau) <= longest;
assert_eq!(
SpikingNeuralNetwork::from_neurons(neurons, dt).err(),
(!moves).then_some(Error::FrozenMembrane),
"{dt} μs, a time constant of {tau} μs at {at}"
);
}
}
}
}
#[test]
fn new_network_has_correct_neuron_count() {
let net = SpikingNeuralNetwork::new(100, 1000, NetworkTopology::default())
.expect("100 neurons valid");
assert_eq!(net.neuron_count(), 100);
assert_eq!(net.time_us(), 0);
}
#[test]
fn topology_default_is_balanced_80_20() {
let net = SpikingNeuralNetwork::new(100, 1000, NetworkTopology::default()).expect("valid");
let excitatory = net
.neurons
.iter()
.filter(|n| n.neuron_type == NeuronType::Excitatory)
.count();
assert_eq!(
excitatory, 80,
"default topology should give 80% excitatory"
);
}
#[test]
fn random_topology_produces_synapses() {
let mut net =
SpikingNeuralNetwork::new(50, 1000, NetworkTopology::Random { connectivity: 0.2 })
.expect("valid");
net.build_topology().expect("build");
assert!(
net.synapse_count() > 0,
"random topology must produce synapses"
);
}
#[test]
fn smallworld_topology_produces_synapses() {
let mut net = SpikingNeuralNetwork::new(
50,
1000,
NetworkTopology::SmallWorld {
local_connections: 4,
rewiring_prob: 0.1,
},
)
.expect("valid");
net.build_topology().expect("build");
assert!(net.synapse_count() > 0);
}
#[test]
fn feedforward_topology_produces_synapses() {
let mut net = SpikingNeuralNetwork::new(
30,
1000,
NetworkTopology::Feedforward {
layers: &[10, 15, 5],
},
)
.expect("valid");
net.build_topology().expect("build");
assert!(net.synapse_count() > 0);
}
#[test]
fn balanced_topology_produces_synapses() {
let mut net = SpikingNeuralNetwork::new(
50,
1000,
NetworkTopology::Balanced {
excitatory_ratio: 0.8,
},
)
.expect("valid");
net.build_topology().expect("build");
assert!(net.synapse_count() > 0);
}
#[test]
fn feedforward_wrong_total_rejected() {
let mut net = SpikingNeuralNetwork::new(
30,
1000,
NetworkTopology::Feedforward {
layers: &[10, 15, 10],
}, // sums to 35, not 30
)
.expect("valid net init");
let err = net.build_topology();
assert_eq!(err, Err(Error::BadLayerSizes), "mismatched layer total");
// sums to 10, not 11: a neuron in no layer
let mut net =
SpikingNeuralNetwork::new(11, 1000, NetworkTopology::Feedforward { layers: &[5, 5] })
.expect("valid net init");
let err = net.build_topology();
assert_eq!(err, Err(Error::BadLayerSizes), "a total below the count");
}
/// A layer of no neuron, first or not, is refused: after the first one
/// the projection divided by its size, a panic; a first one built a
/// network whose first layer sends nothing. One neuron a layer builds.
#[test]
fn feedforward_layer_of_no_neuron_rejected() {
for layers in [&[5, 0, 5][..], &[10, 0], &[0, 10]] {
let mut net =
SpikingNeuralNetwork::new(10, 1000, NetworkTopology::Feedforward { layers })
.expect("valid net init");
assert_eq!(
net.build_topology(),
Err(Error::BadLayerSizes),
"{layers:?}"
);
}
let mut net =
SpikingNeuralNetwork::new(3, 1000, NetworkTopology::Feedforward { layers: &[1, 1, 1] })
.expect("valid net init");
net.build_topology().expect("one neuron a layer");
assert_eq!(net.synapse_count(), 2);
}
/// Layer sizes past 65,535 are summed whole: in a `u16`, `[65535, 11]`
/// wrapped to 10 and passed the check on 10 neurons (a panic in a debug
/// build, a neuron id out of range from the projection in release),
/// and `[65535, 1]` on 65,535 overflowed too.
#[test]
fn feedforward_sum_past_u16_rejected() {
for (n, layers) in [(10, &[65_535, 11][..]), (65_535, &[65_535, 1])] {
let mut net =
SpikingNeuralNetwork::new(n, 1000, NetworkTopology::Feedforward { layers })
.expect("valid net init");
assert_eq!(
net.build_topology(),
Err(Error::BadLayerSizes),
"{layers:?} on {n}"
);
}
}
/// `new` reserves nothing, so no topology can fail it: two layers of
/// 32,768 on 65,535 neurons are refused by `build_topology`. Its
/// estimate asked 17 GB for layers of 32,767 and 32,768, a list the
/// rule takes, and 137 GB for a connectivity of 1, which aborted `new`
/// on a 15 GiB machine; 1e30 and infinity overflowed the capacity, a
/// panic.
#[test]
fn new_takes_any_topology() {
let ff = |layers: &'static [u16]| NetworkTopology::Feedforward { layers };
let mut net =
SpikingNeuralNetwork::new(65_535, 1000, ff(&[32_768, 32_768])).expect("valid net init");
assert_eq!(net.build_topology(), Err(Error::BadLayerSizes));
// Built, it would hold 268,427,264 synapses: `new` alone here.
SpikingNeuralNetwork::new(65_535, 1000, ff(&[32_767, 32_768])).expect("valid net init");
for connectivity in [1.0, 1e30, f64::INFINITY] {
SpikingNeuralNetwork::new(65_535, 1000, NetworkTopology::Random { connectivity })
.expect("valid net init");
}
}
/// The probability rule, both parameters at both edges: 0 and 1 build,
/// -0.0 too; just past each edge, the infinities and NaN are refused, on
/// one neuron as on many. The builders clamped them: past 1 wired every
/// pair or rewired every edge, and below 0 or NaN wired or rewired
/// nothing.
#[test]
fn a_probability_outside_0_to_1_is_refused() {
let topologies = |p: f64| {
[
NetworkTopology::Random { connectivity: p },
NetworkTopology::SmallWorld {
local_connections: 2,
rewiring_prob: p,
},
]
};
let outside = [
1.0_f64.next_up(),
0.0_f64.next_down(),
2.0,
-1.0,
f64::INFINITY,
f64::NEG_INFINITY,
f64::NAN,
];
for n in [1, 2, 10] {
for p in outside {
for topology in topologies(p) {
let mut net =
SpikingNeuralNetwork::new(n, 1000, topology).expect("valid net init");
assert_eq!(
net.build_topology(),
Err(Error::ProbabilityOutOfRange),
"{topology:?} on {n}"
);
}
}
for p in [0.0, -0.0, 1.0] {
for topology in topologies(p) {
let mut net =
SpikingNeuralNetwork::new(n, 1000, topology).expect("valid net init");
net.build_topology().expect("a probability from 0 to 1");
}
}
}
}
/// An FNV-1a hash of every synapse (pre, post, weight) in the order
/// added: two networks with one hash were wired alike.
fn wiring_hash(net: &SpikingNeuralNetwork) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for s in &net.synapses {
let bytes = [
s.pre_neuron_id.to_le_bytes(),
s.post_neuron_id.to_le_bytes(),
s.weight.to_le_bytes(),
];
for b in bytes.concat() {
h ^= u64::from(b);
h = h.wrapping_mul(0x0100_0000_01b3);
}
}
h
}
/// `SmallWorld` keeps its wiring inside 0 to 1: the hash of every
/// synapse, for two builds in a row (the second continues the seed),
/// each measured at `main@9170afa`, where the builder clamped the
/// probability. 0, 0.3 and 1 on 200 neurons with 4 local connections;
/// 0.5 on 30 with 10; 0.75 on 100 with 16, whose second build draws a
/// roll equal to the probability; and 0.3 with more local connections
/// than neurons, where the offsets wrap past a neuron's own place.
#[test]
fn smallworld_keeps_its_wiring_inside_0_to_1() {
for (n, local_connections, rewiring_prob, synapses, pin) in [
(
200,
4,
0.0,
800,
[0x16d6_a58b_01b9_5ef5, 0x16d6_a58b_01b9_5ef5],
),
(
200,
4,
0.3,
800,
[0x5081_e07d_8634_35bb, 0xca68_d1ee_206d_3eca],
),
(
200,
4,
1.0,
800,
[0x2cab_c139_f6d2_2aa3, 0xfe29_df1c_6013_77f0],
),
(
30,
10,
0.5,
300,
[0x2137_bf29_e8c2_3f2f, 0x1321_75de_a2a5_853f],
),
(
100,
16,
0.75,
1600,
[0x8f58_2584_cbe4_723c, 0xd982_9650_36de_a02a],
),
(
5,
10,
0.3,
40,
[0xfeef_3437_a7da_8474, 0x3a09_d8ba_0c1e_306c],
),
] {
let topology = NetworkTopology::SmallWorld {
local_connections,
rewiring_prob,
};
let mut net = SpikingNeuralNetwork::new(n, 1000, topology).expect("valid net init");
for want in pin {
net.build_topology().expect("build");
assert_eq!(net.synapse_count(), synapses);
assert_eq!(wiring_hash(&net), want, "{topology:?} on {n}");
}
}
}
/// The balanced rule's other half: no excitatory neuron. The I→E edges
/// divided by the excitatory count, a panic, for one neuron at the
/// default ratio, for a ratio of 0, one that truncates to no neuron,
/// one below 0, or NaN. One neuron of each type builds.
#[test]
fn balanced_zero_excitatory_rejected() {
for (n, ratio) in [(1, 0.8), (10, 0.0), (4, 0.2), (10, -0.5), (10, f64::NAN)] {
let mut net = SpikingNeuralNetwork::new(
n,
1000,
NetworkTopology::Balanced {
excitatory_ratio: ratio,
},
)
.expect("valid net init");
assert_eq!(
net.build_topology(),
Err(Error::MissingNeuronType),
"{ratio} on {n}"
);
}
let mut net = SpikingNeuralNetwork::new(
2,
1000,
NetworkTopology::Balanced {
excitatory_ratio: 0.5,
},
)
.expect("valid net init");
net.build_topology().expect("one neuron of each type");
}
#[test]
fn balanced_zero_inhibitory_rejected() {
let mut net = SpikingNeuralNetwork::new(
10,
1000,
NetworkTopology::Balanced {
excitatory_ratio: 1.0,
},
)
.expect("valid net init");
let err = net.build_topology();
assert_eq!(err, Err(Error::MissingNeuronType), "0 inhibitory");
}
/// A ratio above 1 leaves no inhibitory neuron, as 1 does: the builders
/// clamp it, and `build_topology` refuses it.
#[test]
fn balanced_ratio_above_one_rejected() {
let mut net = SpikingNeuralNetwork::new(
10,
1000,
NetworkTopology::Balanced {
excitatory_ratio: 1.5,
},
)
.expect("valid net init");
assert_eq!(net.build_topology(), Err(Error::MissingNeuronType));
}
#[test]
fn step_advances_time_by_time_step() {
let mut net =
SpikingNeuralNetwork::new(10, 1000, NetworkTopology::default()).expect("valid");
net.build_topology().expect("build");
let inputs = vec![0; 10];
let _ = net.step(&inputs).expect("step");
assert_eq!(net.time_us(), 1000);
let _ = net.step(&inputs).expect("step");
assert_eq!(net.time_us(), 2000);
}
/// A neuron past the end of `input_currents` gets 0 pA, as a 0 in the
/// slice would give it: a membrane that 1 pA would move (10 GΩ, and
/// τ = dt) stays at rest through a step with an empty slice.
#[test]
fn a_neuron_past_the_input_slice_gets_no_current() {
let neurons = (0..2)
.map(|id| {
LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt)
.with_tau_membrane_us(1_000)
.with_resistance_mohm(10_000)
})
.collect();
let mut net = SpikingNeuralNetwork::from_neurons(neurons, 1_000).unwrap();
net.step(&[]).unwrap();
for n in net.neurons() {
assert_eq!(n.membrane_potential, n.resting_potential, "neuron {}", n.id);
}
}
#[test]
fn step_with_strong_input_produces_spikes() {
let mut net =
SpikingNeuralNetwork::new(10, 1000, NetworkTopology::default()).expect("valid");
net.build_topology().expect("build");
let inputs = vec![1000; 10]; // Strong input to all
let mut total_spikes = 0u32;
for _ in 0..50 {
let spikes = net.step(&inputs).expect("step");
total_spikes += spikes.len() as u32;
}
assert!(
total_spikes > 0,
"strong input over 50 steps must produce spikes"
);
}
#[test]
fn reset_clears_time_and_spikes() {
let mut net =
SpikingNeuralNetwork::new(20, 1000, NetworkTopology::default()).expect("valid");
net.build_topology().expect("build");
#[cfg(feature = "unstable-stdp")]
net.set_plasticity_enabled(true);
let inputs = vec![1000; 20];
for _ in 0..5 {
let _ = net.step(&inputs).expect("step");
}
assert!(net.time_us() > 0);
assert!(net.stats().total_spikes > 0);
#[cfg(feature = "unstable-stdp")]
assert!(
net.stats().plasticity_events > 0,
"the counter must have moved, or the reset below clears a 0"
);
net.reset();
assert_eq!(net.time_us(), 0);
assert_eq!(net.stats().total_spikes, 0);
#[cfg(feature = "unstable-stdp")]
assert_eq!(net.stats().plasticity_events, 0);
}
/// `reset` gives the network a fresh network's stats and, with the
/// feature, zeroes each synapse's two counters; the weights stay. The
/// run moves every stat and both counters first, or the reset proves
/// nothing for them: the synapse added at weight 0 absorbs the LTD its
/// two co-firing neurons give it.
#[test]
fn reset_gives_fresh_stats_and_keeps_the_weights() {
let build = || {
let mut net =
SpikingNeuralNetwork::new(20, 1000, NetworkTopology::default()).expect("valid");
net.build_topology().expect("build");
net.add_synapse(0, 1, 0).expect("adds");
net
};
let fresh = build();
let mut net = build();
#[cfg(feature = "unstable-stdp")]
net.set_plasticity_enabled(true);
for _ in 0..20 {
net.step(&[1000; 20]).expect("step");
}
let (ran, base) = (net.stats().clone(), fresh.stats());
assert_ne!(ran.total_spikes, base.total_spikes);
assert_ne!(
ran.avg_membrane_potential_mv,
base.avg_membrane_potential_mv
);
assert_ne!(ran.firing_rate_hz, base.firing_rate_hz);
#[cfg(feature = "unstable-stdp")]
{
assert_ne!(ran.plasticity_events, base.plasticity_events);
assert_ne!(ran.stdp_pairs_same_step, base.stdp_pairs_same_step);
assert_ne!(ran.stdp_pairs_post_leads, base.stdp_pairs_post_leads);
assert_ne!(ran.stdp_pairs_pre_leads, base.stdp_pairs_pre_leads);
assert!(net.synapses().iter().any(|s| s.raw_stdp_delta() != 0));
assert!(net.synapses().iter().any(|s| s.absorbed_delta() != 0));
}
let weights: Vec<i16> = net.synapses().iter().map(Synapse::weight).collect();
net.reset();
assert_eq!(net.stats(), fresh.stats());
let kept: Vec<i16> = net.synapses().iter().map(Synapse::weight).collect();
assert_eq!(kept, weights);
#[cfg(feature = "unstable-stdp")]
assert!(net
.synapses()
.iter()
.all(|s| (s.raw_stdp_delta(), s.absorbed_delta()) == (0, 0)));
}
/// After `reset`, `stochastic_ternary_step` draws its stream from the
/// start, where a fresh network's starts: a step that drew moved the
/// stream, and the reset brings it back.
#[cfg(feature = "unstable-stdp")]
#[test]
fn reset_draws_the_flip_stream_from_the_start() {
let three = || {
let neurons = (0..3)
.map(|id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
.collect();
SpikingNeuralNetwork::from_neurons(neurons, 1_000).expect("three neurons")
};
let fresh = three();
let mut net = three();
net.add_synapse(1, 2, 122)
.expect("γ − 3: an off-grid weight draws");
let _ = net.stochastic_ternary_step(125);
assert_ne!(
net.ternary_flip_lfsr, fresh.ternary_flip_lfsr,
"the step drew, or the reset below proves nothing"
);
net.reset();
assert_eq!(net.ternary_flip_lfsr, fresh.ternary_flip_lfsr);
}
#[test]
fn add_synapse_rejects_out_of_bounds() {
let mut net =
SpikingNeuralNetwork::new(10, 1000, NetworkTopology::default()).expect("valid");
let err = net.add_synapse(0, 100, 50);
assert_eq!(err, Err(Error::NeuronIdOutOfRange));
let err = net.add_synapse(100, 0, 50);
assert_eq!(err, Err(Error::NeuronIdOutOfRange));
}
#[test]
fn add_synapse_rejects_self_connection() {
let mut net =
SpikingNeuralNetwork::new(10, 1000, NetworkTopology::default()).expect("valid");
let err = net.add_synapse(3, 3, 100);
assert_eq!(err, Err(Error::SelfConnection));
}
/// The rows are `finalize`'s: an edge added since the last one is in
/// no row, and the matrix says so, until the next; `clear` leaves it
/// clean.
#[test]
fn sparse_matrix_delivers_added_synapses_after_finalize() {
let mut m = SparseSynapseMatrix::new(5, 4);
assert!(!m.is_dirty(), "a new matrix is clean");
m.add(0, 1, 100, 0);
m.add(0, 2, 200, 1);
m.add(2, 3, -150, 2);
assert!(m.is_dirty(), "an add marks it");
assert_eq!(m.connections(0).count(), 0, "no row before the sort");
m.finalize();
assert!(!m.is_dirty(), "the sort clears the mark");
let row0: Vec<(u16, i16, usize)> = m.connections(0).collect();
assert_eq!(row0, vec![(1, 100, 0), (2, 200, 1)]);
let row2: Vec<(u16, i16, usize)> = m.connections(2).collect();
assert_eq!(row2, vec![(3, -150, 2)]);
let row1: Vec<(u16, i16, usize)> = m.connections(1).collect();
assert!(row1.is_empty());
assert_eq!(m.len(), 3);
m.add(1, 4, 50, 3);
assert!(m.is_dirty());
assert_eq!(
m.connections(1).count(),
0,
"the new edge waits for the sort"
);
assert_eq!(m.connections(0).count(), 2, "the sorted rows stand");
m.clear();
assert!(!m.is_dirty(), "a cleared matrix is clean");
assert_eq!(
(0..5).map(|pre| m.connections(pre).count()).sum::<usize>(),
0
);
}
#[test]
fn csr_finalize_recovers_correct_members_for_unsorted_insertion() {
// Regression: add() in arbitrary pre_id order used to make
// connections(pre) return slices with the right COUNT but the wrong
// MEMBERS (the incremental row_ptrs, gone since round 64, was right
// only for sorted insertion). finalize() counting-sorts by pre_id
// so connections returns each neuron's actual outgoing edges.
let mut m = SparseSynapseMatrix::new(5, 4);
m.add(0, 1, 100, 0);
m.add(2, 3, 200, 1);
m.add(0, 4, 150, 2); // unsorted: pre=0 reappears after pre=2
m.finalize();
let mut row0: Vec<(u16, i16, usize)> = m.connections(0).collect();
row0.sort_by_key(|t| t.0);
assert_eq!(
row0,
vec![(1, 100, 0), (4, 150, 2)],
"connections(0) must return only pre=0's edges"
);
let row2: Vec<(u16, i16, usize)> = m.connections(2).collect();
assert_eq!(
row2,
vec![(3, 200, 1)],
"connections(2) must return pre=2's edge only"
);
// Empty rows stay empty.
assert_eq!(m.connections(1).count(), 0);
assert_eq!(m.connections(3).count(), 0);
assert_eq!(m.connections(4).count(), 0);
// Total conserved.
let total: usize = (0..5).map(|i| m.connections(i).count()).sum();
assert_eq!(total, 3);
}
#[test]
fn csr_connections_pre_id_consistent_after_build() {
// Network-level regression for the unsorted-insertion CSR bug. After
// build_topology (which now finalizes), connections(pre) must return
// only synapses whose presynaptic neuron IS `pre`. The old incremental
// row_ptrs violated this for build_balanced's arbitrary insertion order
// — corrupting propagation targeting and STDP synapse selection.
let mut net =
SpikingNeuralNetwork::new(64, 1000, NetworkTopology::default()).expect("valid");
net.build_topology().expect("build");
for pre in 0..net.neuron_count() {
for (_post, _w, syn_idx) in net.synapse_matrix.connections(pre) {
assert_eq!(
net.synapses[syn_idx].pre_neuron_id, pre,
"CSR returned a synapse under connections({pre}) whose presynaptic neuron is {} — finalize() must group by pre_id",
net.synapses[syn_idx].pre_neuron_id
);
}
}
}
#[test]
fn the_first_step_sorts_external_adds_and_builds_both_csrs() {
// Session D-2's external-wiring path, sorted by the step since
// round 64. `add_synapse` in arbitrary pre_id order, then a step,
// must produce the authoritative forward CSR (right members, stable
// within-row order), the reverse CSR (right incoming edges), and
// the count.
let mut net =
SpikingNeuralNetwork::new(4, 1000, NetworkTopology::Random { connectivity: 0.0 })
.expect("valid");
net.build_topology().expect("build");
assert_eq!(net.synapse_count(), 0, "zero-connectivity start is empty");
// Deliberately unsorted pre order (pre 2, pre 0, pre 2 again, pre 1).
net.add_synapse(2, 0, -125).expect("add");
net.add_synapse(0, 1, 125).expect("add");
net.add_synapse(2, 3, -125).expect("add");
net.add_synapse(1, 3, 0).expect("add");
assert_eq!(net.synapse_count(), 4, "each add is counted");
net.step(&[0; 4]).expect("steps");
assert_eq!(net.synapse_count(), 4);
// Forward CSR: each row holds exactly its presynaptic neuron's edges,
// stable order among same-pre adds (0 was added before 3 for pre 2).
let row0: Vec<(u16, i16)> = net
.synapse_matrix
.connections(0)
.map(|(p, w, _)| (p, w))
.collect();
assert_eq!(row0, vec![(1, 125)]);
let row1: Vec<(u16, i16)> = net
.synapse_matrix
.connections(1)
.map(|(p, w, _)| (p, w))
.collect();
assert_eq!(row1, vec![(3, 0)]);
let row2: Vec<(u16, i16)> = net
.synapse_matrix
.connections(2)
.map(|(p, w, _)| (p, w))
.collect();
assert_eq!(row2, vec![(0, -125), (3, -125)]);
assert_eq!(net.synapse_matrix.connections(3).count(), 0);
// Reverse CSR: post 3 receives from pre 1 and pre 2 (stable insertion
// order among same-post adds: pre 2's edge was added before pre 1's).
let inc3: Vec<u16> = net.synapse_matrix.incoming(3).map(|(p, _)| p).collect();
assert_eq!(inc3, vec![2, 1]);
let inc0: Vec<u16> = net.synapse_matrix.incoming(0).map(|(p, _)| p).collect();
assert_eq!(inc0, vec![2]);
}
/// The LTP (post-firing) pass reads the reverse CSR, which only a sort
/// builds. External wiring that no caller sorted is sorted by its first
/// step, so it learns as sorted wiring does: the same drive on two
/// nets, one sorted by hand and one not, potentiates both to the same
/// weight. Before round 64 the second stayed at 0 (LTD clamps the
/// zero-born excitatory weight there): the pre-1.5d LTD-only
/// substrate, in silence.
#[test]
fn ltp_reaches_external_wiring_never_sorted() {
let wired = |sorted: bool| {
let mut net =
SpikingNeuralNetwork::new(4, 1000, NetworkTopology::Random { connectivity: 0.0 })
.expect("valid");
net.build_topology().expect("build");
net.neurons[1].noise_amplitude_pa = 0;
net.neurons[2].noise_amplitude_pa = 0;
net.add_synapse(1, 2, 0).expect("add");
if sorted {
net.finalize_synapses();
}
#[cfg(feature = "unstable-stdp")]
net.set_plasticity_enabled(true);
net
};
let mut net = wired(true);
let mut raw = wired(false);
// Drive: pre (neuron 1) steps 0..6, then post (neuron 2) steps 7..17.
// Pre fires ≈step 6 (integer LIF integration needs 7 driven steps to
// reach −55 mV from rest), post ≈step 13 → pre-before-post within the
// STDP window → LTP is the only rule that can raise this weight.
for step in 0..18u32 {
let mut inp = vec![0_i16; 4];
if step < 7 {
inp[1] = 600;
} else {
inp[2] = 600;
}
net.step(&inp).expect("step");
raw.step(&inp).expect("step");
}
assert!(
net.neurons[1].last_spike_time_us > 0 && net.neurons[2].last_spike_time_us > 0,
"drive must make both pre and post fire (pre @ {}μs, post @ {}μs)",
net.neurons[1].last_spike_time_us,
net.neurons[2].last_spike_time_us
);
#[cfg(feature = "unstable-stdp")]
assert!(
net.synapses[0].weight > 0,
"sorted external wiring must allow LTP: weight {} (started 0)",
net.synapses[0].weight
);
assert_eq!(
raw.synapses[0].weight, net.synapses[0].weight,
"never sorted, the wiring learns as the sorted one"
);
}
#[test]
fn lfsr_is_deterministic_same_seed() {
let a = advance_lfsr(0xDEAD_BEEF);
let b = advance_lfsr(0xDEAD_BEEF);
assert_eq!(a, b);
}
#[test]
fn smallworld_rewiring_conserves_edge_count() {
// True Watts-Strogatz rewiring keeps-or-replaces each local edge; it
// never augments. With `local_connections` well below `n` (no wrap-around
// self-skip), the count must equal exactly `n × local_connections`.
let mut net = SpikingNeuralNetwork::new(
50,
1000,
NetworkTopology::SmallWorld {
local_connections: 4,
rewiring_prob: 0.3,
},
)
.expect("valid");
net.build_topology().expect("build");
assert_eq!(
net.synapse_count(),
50 * 4,
"rewiring must conserve edge count (keep-or-replace, not augment)"
);
}
/// `SmallWorld` near the cap wires the ring: each neuron to the next
/// `local_connections` neurons around it, computed here in `u32`. At
/// 65,535 neurons and 2 local connections the last neuron's
/// `i + offset` passed `u16::MAX`: a panic in a debug build, and in
/// release its second edge went to neuron 0 again, where the ring
/// says 1.
#[test]
fn smallworld_near_the_cap_wires_the_ring() {
let (n, k) = (65_535u32, 2u32);
let mut net = SpikingNeuralNetwork::new(
n as u16,
1000,
NetworkTopology::SmallWorld {
local_connections: k as u8,
rewiring_prob: 0.0,
},
)
.expect("valid net init");
net.build_topology().expect("build");
let mut built: Vec<(u32, u32)> = net
.synapses
.iter()
.map(|s| (u32::from(s.pre_neuron_id), u32::from(s.post_neuron_id)))
.collect();
built.sort_unstable();
let mut ring: Vec<(u32, u32)> = (0..n)
.flat_map(|i| (1..=k).map(move |offset| (i, (i + offset) % n)))
.collect();
ring.sort_unstable();
assert_eq!(built.len(), ring.len());
let wrong = built.iter().zip(&ring).filter(|(b, r)| b != r).count();
assert_eq!(wrong, 0, "edges off the ring");
built.dedup();
assert_eq!(built.len(), ring.len(), "parallel edges");
}
/// `Random` keeps no list of every pair: on 65,535 neurons it builds
/// at 0 and at 1e-7 (429 synapses). The list asked 17 GB there, 4
/// bytes for each of 4,294,770,690 pairs, at any connectivity, and
/// aborted on a 15 GiB machine.
#[test]
fn random_builds_on_65_535_neurons() {
for (connectivity, synapses) in [(0.0, 0), (1e-7, 429)] {
let mut net =
SpikingNeuralNetwork::new(65_535, 1000, NetworkTopology::Random { connectivity })
.expect("valid net init");
net.build_topology().expect("build");
assert_eq!(net.synapse_count(), synapses, "{connectivity}");
}
}
/// `Random` wires as the stored list did: the hash of every synapse,
/// for two builds in a row (the second continues the seed), each
/// measured at `main@9170afa`, which stored the list whole. 300 neurons
/// is past 256, where the list holds more pairs than one draw spans.
#[test]
fn random_wires_as_the_stored_list_did() {
for (n, connectivity, synapses, pin) in [
(2, 1.0, 2, [0xc5bd_377b_a6fd_5d87, 0xcd48_8a51_e44c_3f6b]),
(20, 1.0, 380, [0x9bda_53c5_4ed6_9348, 0xff82_5265_f00d_749a]),
(
50,
0.5,
1225,
[0x53d4_81c2_d27e_b05b, 0x21f0_b383_5f58_e87f],
),
(
300,
0.1,
8970,
[0x4d16_19b7_1778_0061, 0xfe99_21d3_778e_1e6e],
),
] {
let mut net =
SpikingNeuralNetwork::new(n, 1000, NetworkTopology::Random { connectivity })
.expect("valid net init");
for want in pin {
net.build_topology().expect("build");
assert_eq!(net.synapse_count(), synapses);
assert_eq!(wiring_hash(&net), want, "{n} neurons at {connectivity}");
}
}
}
#[test]
fn build_topology_does_not_accumulate() {
// Regression for the silent-accumulation footgun: a second build must
// REPLACE the topology, not stack on top of the first.
let mut net =
SpikingNeuralNetwork::new(50, 1000, NetworkTopology::Random { connectivity: 0.3 })
.expect("valid");
net.build_topology().expect("first build");
let count_first = net.synapse_count();
assert!(count_first > 0, "first build must produce synapses");
net.build_topology().expect("second build");
let count_second = net.synapse_count();
assert_ne!(
count_second,
2 * count_first,
"second build must not double the synapse count"
);
// Random topology's count is formula-determined (connectivity ×
// total_possible), so it is also stable across rebuilds.
assert_eq!(count_second, count_first);
}
#[test]
fn ternary_gate_stage1_deterministic_is_frozen() {
// Stage 1 DETERMINISTIC baseline — pins the ruled-out negative result.
// Under per-step re-projection with BitNet-Round γ = mean|w|, STDP
// deltas (max ±5) are ~12× smaller than the bucket boundary γ/2 (≈62),
// so no weight ever crosses a ternary threshold → 0 flips. This is the
// known-dead regime the field identified; Stage 1.5b (stochastic flips)
// is the reopen path. See docs/VISION.md "Stage 1" + "Stage 1.5 reopen
// paths."
let mut net =
SpikingNeuralNetwork::new(128, 1000, NetworkTopology::default()).expect("valid");
net.build_topology().expect("build");
let gamma = net.ternarize_weights();
assert!(gamma > 0, "balanced net must produce a nonzero γ");
let mut prev: Vec<Trit> = net
.synapses()
.iter()
.map(|s| Trit::from_weight(s.weight, gamma))
.collect();
// Without the feature no weight moves: what this pins then is that
// `reproject_ternary` leaves an on-grid network alone.
#[cfg(feature = "unstable-stdp")]
net.set_plasticity_enabled(true);
let inputs = vec![600_i16; 128];
let mut flips = 0u64;
for _ in 0..200 {
let _ = net.step(&inputs).expect("step");
net.reproject_ternary(gamma);
for (i, s) in net.synapses().iter().enumerate() {
let cur = Trit::from_weight(s.weight, gamma);
if cur != prev[i] {
flips += 1;
prev[i] = cur;
}
}
}
assert_eq!(
flips, 0,
"Stage 1 deterministic: ternary learning must be frozen under per-step re-projection; got {flips} flips"
);
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn ternary_gate_stage1_5b_stochastic_unfreezes_learning() {
// Stage 1.5b CANARY — stochastic bucket-flips reopen ternary learning.
// Under deterministic re-projection (Stage 1), STDP deltas can't cross
// the γ/2 boundary → 0 flips. The stochastic rule dissolves that: each
// STDP event does a Bernoulli(∝|δ|) draw to flip one bucket in the
// delta's direction. The stored weight stays genuinely ternary — no
// latent/shadow state.
//
// This test asserts nonzero bucket movement over a balanced 128-net run
// — the signal that the regime changed from Stage 1's frozen baseline.
let mut net =
SpikingNeuralNetwork::new(128, 1000, NetworkTopology::default()).expect("valid");
net.build_topology().expect("build");
let gamma = net.ternarize_weights();
assert!(gamma > 0, "balanced net must produce a nonzero γ");
let mut prev: Vec<Trit> = net
.synapses()
.iter()
.map(|s| Trit::from_weight(s.weight, gamma))
.collect();
net.set_plasticity_enabled(true);
let inputs = vec![600_i16; 128];
let mut flips = 0u64;
for _ in 0..200 {
let _ = net.step(&inputs).expect("step");
net.stochastic_ternary_step(gamma);
for (i, s) in net.synapses().iter().enumerate() {
let cur = Trit::from_weight(s.weight, gamma);
if cur != prev[i] {
flips += 1;
prev[i] = cur;
}
}
}
assert!(
flips > 0,
"Stage 1.5b: stochastic flips must produce nonzero bucket movement; got 0"
);
}
#[cfg(feature = "unstable-stdp")]
#[test]
#[allow(clippy::too_many_lines)]
fn ternary_gate_stage1_5c_selectivity_under_structured_input() {
// Stage 1.5c CANARY — ternary STDP discriminates by correlation.
//
// 1.5b proved the stochastic-flip mechanism moves weights (802 flips)
// but under *uniform synchronous* drive — a degenerate one-directional
// collapse. This canary runs the real test: under *structured* input
// (correlated groups, gapped rotation) where the i16 baseline
// discriminates (intra-group E→E depress via co-fire LTD, inter-group
// don't), ternary-stochastic must PRESERVE that differential (intra
// mean < inter mean) with nonzero flips and non-collapsed spiking.
// Gates whether the Stage 2 format bridge is worth building.
// See the repository's examples/ternary_selectivity.rs, which the
// package leaves out, for the full diagnostic.
let neurons: u16 = 128;
let exc = (f64::from(neurons) * 0.8) as u16;
let groups: u16 = 4;
let active_on = 60u32;
let off_gap = 40u32;
let slot_len = active_on + off_gap;
let init_steps = (slot_len * u32::from(groups)) as usize;
let learn_steps = 600usize;
let total = init_steps + learn_steps;
let i_active = 600_i16;
let i_idle = 0_i16;
let i_inh = 600_i16;
let group_of = |nid: u16| -> u16 {
let g = (u32::from(nid) * u32::from(groups) / u32::from(exc)) as u16;
g.min(groups - 1)
};
// Gapped rotating drive: one group active per slot, silent gap between.
let mut inputs: Vec<Vec<i16>> = Vec::with_capacity(total);
for step in 0..total {
let within = (step as u32) % (slot_len * u32::from(groups));
let slot = within / slot_len;
let within_slot = within % slot_len;
let active_group = if slot < u32::from(groups) && within_slot < active_on {
slot as u16
} else {
groups
};
let mut inp = vec![i_inh; neurons as usize];
for n in 0..exc {
inp[n as usize] = if group_of(n) == active_group {
i_active
} else {
i_idle
};
}
inputs.push(inp);
}
let classify = |net: &SpikingNeuralNetwork| -> (Vec<usize>, Vec<usize>) {
let mut intra = Vec::new();
let mut inter = Vec::new();
for (i, s) in net.synapses().iter().enumerate() {
if s.pre_neuron_id < exc && s.post_neuron_id < exc {
if group_of(s.pre_neuron_id) == group_of(s.post_neuron_id) {
intra.push(i);
} else {
inter.push(i);
}
}
}
(intra, inter)
};
let mean = |w: &[i16], idx: &[usize]| -> f64 {
if idx.is_empty() {
0.0
} else {
idx.iter().map(|&i| f64::from(w[i])).sum::<f64>() / idx.len() as f64
}
};
// (1) i16 baseline control — MUST discriminate.
let mut net =
SpikingNeuralNetwork::new(neurons, 1000, NetworkTopology::default()).expect("valid");
net.build_topology().expect("build");
let (intra, inter) = classify(&net);
for inp in &inputs[..init_steps] {
let _ = net.step(inp).expect("init");
}
net.set_plasticity_enabled(true);
for inp in &inputs[init_steps..] {
let _ = net.step(inp).expect("learn");
}
let i16_w: Vec<i16> = net.synapses().iter().map(|s| s.weight).collect();
let i16_intra = mean(&i16_w, &intra);
let i16_inter = mean(&i16_w, &inter);
assert!(
i16_inter - i16_intra > 20.0,
"i16 control must discriminate by >20: inter={i16_inter:.2} intra={i16_intra:.2}"
);
// (2) Ternary stochastic — must preserve the differential + flip.
let mut tnet =
SpikingNeuralNetwork::new(neurons, 1000, NetworkTopology::default()).expect("valid");
tnet.build_topology().expect("build");
let (tintra, tinter) = classify(&tnet);
for inp in &inputs[..init_steps] {
let _ = tnet.step(inp).expect("init");
}
let gamma = tnet.ternarize_weights();
let mut prev: Vec<Trit> = tnet
.synapses()
.iter()
.map(|s| Trit::from_weight(s.weight, gamma))
.collect();
tnet.set_plasticity_enabled(true);
let mut flips = 0u64;
for inp in &inputs[init_steps..] {
let _ = tnet.step(inp).expect("learn");
tnet.stochastic_ternary_step(gamma);
for (i, s) in tnet.synapses().iter().enumerate() {
let cur = Trit::from_weight(s.weight, gamma);
if cur != prev[i] {
flips += 1;
prev[i] = cur;
}
}
}
let tern_w: Vec<i16> = tnet.synapses().iter().map(|s| s.weight).collect();
let tern_intra = mean(&tern_w, &tintra);
let tern_inter = mean(&tern_w, &tinter);
assert!(flips > 0, "ternary must produce bucket flips; got 0");
assert!(
tern_inter - tern_intra > f64::from(gamma) / 2.0,
"ternary must discriminate by >γ/2: inter={tern_inter:.2} intra={tern_intra:.2} γ={gamma}"
);
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn same_step_cofire_biases_toward_ltd() {
let mut net = SpikingNeuralNetwork::new(
2,
1000,
NetworkTopology::Balanced {
excitatory_ratio: 0.5,
},
)
.expect("valid");
net.neurons[0].noise_amplitude_pa = 0;
net.neurons[1].noise_amplitude_pa = 0;
net.add_synapse(0, 1, 100).expect("synapse");
net.neurons[0].last_spike_time_us = 1_000;
net.neurons[1].last_spike_time_us = 1_000;
net.plasticity_queue.push((0, 1, 0, 1_000));
net.update_plasticity(&[0, 1]);
assert!(
net.synapses[0].weight < 100,
"same-step tie should depress weight"
);
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn plasticity_updated_weight_affects_future_propagation() {
let mut net = SpikingNeuralNetwork::new(
2,
1000,
NetworkTopology::Balanced {
excitatory_ratio: 0.5,
},
)
.expect("valid");
net.neurons[0].noise_amplitude_pa = 0;
net.neurons[1].noise_amplitude_pa = 0;
net.add_synapse(0, 1, 100).expect("synapse");
net.finalize_synapses(); // the rows read below are the sort's
net.neurons[0].last_spike_time_us = 1_000;
net.neurons[1].last_spike_time_us = 1_000;
net.plasticity_queue.push((0, 1, 0, 1_000));
net.update_plasticity(&[0, 1]);
let updated_weight = net.synapses[0].weight;
assert_ne!(updated_weight, 100, "plasticity should change weight");
net.neurons[1].clear_synaptic_current();
let divisor = net.synaptic_input_divisor() as i16;
for (post_id, weight, _) in net.synapse_matrix.connections(0) {
if post_id == 1 {
net.neurons[1].add_synaptic_current(weight / divisor);
}
}
assert_eq!(
net.neurons[1].synaptic_current_pa,
updated_weight / divisor,
"propagation must use the updated synapse weight"
);
}
#[test]
fn csr_weight_stays_in_sync_with_synapse_after_plasticity() {
let mut net = SpikingNeuralNetwork::new(
2,
1000,
NetworkTopology::Balanced {
excitatory_ratio: 0.5,
},
)
.expect("valid");
net.neurons[0].noise_amplitude_pa = 0;
net.neurons[1].noise_amplitude_pa = 0;
net.add_synapse(0, 1, 100).expect("synapse");
#[cfg(feature = "unstable-stdp")]
net.set_plasticity_enabled(true);
// Four steps: at 1000 pA the post fires at step 2 and the pre at
// step 3, the first pairing (LTD). One step pairs nothing.
for _ in 0..4 {
let _ = net.step(&[1000, 1000]).expect("plasticity step");
}
let synapse_weight = net.synapses[0].weight;
#[cfg(feature = "unstable-stdp")]
assert_ne!(
synapse_weight, 100,
"the step must move the weight, or the mirror below compares 100 with 100"
);
let csr_edge = net
.synapse_matrix
.connections(0)
.next()
.expect("csr edge must exist");
assert_eq!(csr_edge.2, 0, "first inserted synapse should keep index 0");
assert_eq!(
csr_edge.1, synapse_weight,
"CSR transmission weight must mirror synapse weight after STDP"
);
}
// ----- Full pairwise STDP (LTP + LTD) regression suite -----
//
// Through Stage 1.5c the substrate was structurally LTD-only:
// `update_plasticity` visited only pre-firing events, so `dt ≥ 0` always and
// the LTP branch (`dt < 0`) was unreachable. The post-firing LTP path added
// in this change makes the rule genuinely bidirectional. These tests pin
// both halves and the invariants that keep them from interfering.
#[cfg(feature = "unstable-stdp")]
#[test]
fn ltp_post_firing_strengthens_synapse_when_pre_fired_earlier() {
// The focused proof that LTP is now reachable in orchestration: a
// postsynaptic spike paired with a recent presynaptic spike (pre-before-
// post, dt < 0) potentiates the synapse. This was impossible before the
// post-firing LTP pass existed.
let mut net = SpikingNeuralNetwork::new(
2,
1000,
NetworkTopology::Balanced {
excitatory_ratio: 0.5,
},
)
.expect("valid");
net.neurons[0].noise_amplitude_pa = 0;
net.neurons[1].noise_amplitude_pa = 0;
net.add_synapse(0, 1, 100).expect("synapse");
// finalize() builds the reverse CSR so incoming(post) resolves the
// pre→post edge for the LTP pass.
net.synapse_matrix.finalize();
assert_eq!(
net.synapse_matrix.incoming(1).count(),
1,
"reverse CSR must list the one incoming edge to post 1"
);
let start_weight = net.synapses[0].weight;
// Pre fired 3 ms ago; post fires "now" at time_us = 10_000.
net.neurons[0].last_spike_time_us = 7_000;
net.time_us = 10_000;
// Only the post fired this step; plasticity_queue stays empty (no pre
// spike this step) so the LTD pass is inert — only LTP can fire.
net.update_plasticity(&[1]);
assert!(
net.synapses[0].weight > start_weight,
"pre-before-post (dt = 7000−10000 = −3000μs) must potentiate: was {start_weight}, now {}",
net.synapses[0].weight
);
// And the CSR slot must mirror the strengthened synapse (inverse-perm fix).
let csr_w = net
.synapse_matrix
.connections(0)
.next()
.expect("csr edge")
.1;
assert_eq!(
csr_w, net.synapses[0].weight,
"CSR weight must mirror potentiated synapse weight"
);
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn ltp_pass_does_not_double_count_same_step_cofire() {
// a9a2679 invariant under full STDP: when pre and post both fire in the
// same step, the LTD pass applies its +1μs tie-break (→ LTD) and the LTP
// pass must SKIP the edge (pre fired this step) — it must not cancel the
// depression. Net effect on a same-step co-fire is still depression.
let mut net = SpikingNeuralNetwork::new(
2,
1000,
NetworkTopology::Balanced {
excitatory_ratio: 0.5,
},
)
.expect("valid");
net.neurons[0].noise_amplitude_pa = 0;
net.neurons[1].noise_amplitude_pa = 0;
net.add_synapse(0, 1, 100).expect("synapse");
net.synapse_matrix.finalize();
let start_weight = net.synapses[0].weight;
net.neurons[0].last_spike_time_us = 1_000;
net.neurons[1].last_spike_time_us = 1_000;
net.time_us = 1_000;
// Both fire this step; queue the pre-firing event as step() would.
net.plasticity_queue.push((0, 1, 0, 1_000));
net.update_plasticity(&[0, 1]);
assert!(
net.synapses[0].weight < start_weight,
"same-step co-fire must still depress under full STDP: was {start_weight}, now {}",
net.synapses[0].weight
);
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn ltd_pre_after_post_still_depresses_under_full_stdp() {
// LTD half still works under the now-bidirectional rule: pre fires this
// step, post fired earlier → dt > 0 → depression. The LTP pass must not
// fire here (post did not fire this step), so the net is pure LTD.
let mut net = SpikingNeuralNetwork::new(
2,
1000,
NetworkTopology::Balanced {
excitatory_ratio: 0.5,
},
)
.expect("valid");
net.neurons[0].noise_amplitude_pa = 0;
net.neurons[1].noise_amplitude_pa = 0;
net.add_synapse(0, 1, 100).expect("synapse");
net.synapse_matrix.finalize();
let start_weight = net.synapses[0].weight;
// Post fired 3 ms ago; pre fires now.
net.neurons[1].last_spike_time_us = 7_000;
net.time_us = 10_000;
net.plasticity_queue.push((0, 1, 0, 10_000));
// Only pre fired this step.
net.update_plasticity(&[0]);
assert!(
net.synapses[0].weight < start_weight,
"post-before-pre (dt = +3000μs) must depress under full STDP: was {start_weight}, now {}",
net.synapses[0].weight
);
}
#[cfg(feature = "unstable-stdp")]
#[test]
fn full_stdp_is_bidirectional_in_orchestration() {
// Orchestration-level proof that both branches are reachable in a real
// (non-hand-primed) run. Under sustained drive, recurrent timing jitter
// produces both pre-after-post (LTD) and pre-before-post (LTP) pairs, so
// some weights must increase AND some decrease. Through 1.5c `up` was
// always 0 (depression-only); this pins that the substrate no longer is.
let mut net =
SpikingNeuralNetwork::new(64, 1000, NetworkTopology::default()).expect("valid");
net.build_topology().expect("build");
let init: Vec<i16> = net.synapses().iter().map(|s| s.weight).collect();
net.set_plasticity_enabled(true);
let inputs = vec![600_i16; 64];
for _ in 0..400 {
let _ = net.step(&inputs).expect("step");
}
let (mut up, mut down) = (0u32, 0u32);
for (s, &w0) in net.synapses().iter().zip(init.iter()) {
if s.weight > w0 {
up += 1;
} else if s.weight < w0 {
down += 1;
}
}
assert!(up > 0, "LTP must be reachable: got 0 weights increased");
assert!(down > 0, "LTD must still fire: got 0 weights decreased");
}
#[test]
fn csr_weight_index_of_keeps_slots_synced_in_multi_synapse_net() {
// Regression for the bd5b098 latent bug: finalize()'s counting sort
// reorders `weights` by pre_id, so the old `set_weight(syn_idx)` (which
// indexed weights[syn_idx] directly) wrote deltas to the WRONG slots —
// desynchronizing the CSR transmission weights from `synapses[].weight`.
// The inverse-permutation `weight_index_of` routes each write to the
// correct sorted position. This runs a real balanced net (finalize
// reorders heavily) and asserts every CSR slot matches its synapse.
let mut net =
SpikingNeuralNetwork::new(64, 1000, NetworkTopology::default()).expect("valid");
net.build_topology().expect("build");
// Without the feature nothing writes a weight: what this pins then
// is the two counting sorts, not `weight_index_of`. The
// default-build pin on the inverse permutation is
// `ternary_writes_reach_their_csr_slot` below.
#[cfg(feature = "unstable-stdp")]
net.set_plasticity_enabled(true);
let inputs = vec![600_i16; 64];
for _ in 0..50 {
let _ = net.step(&inputs).expect("step");
}
let mut mismatches = 0u32;
for pre in 0..net.neuron_count() {
for (_post, csr_w, syn_idx) in net.synapse_matrix.connections(pre) {
if csr_w != net.synapses[syn_idx].weight {
mismatches += 1;
}
}
}
assert_eq!(
mismatches, 0,
"every CSR forward slot must mirror its synapse weight after plasticity"
);
// Reverse CSR consistency: every incoming entry must name a synapse whose
// post_neuron_id matches the queried post (pins the reverse counting sort).
let mut rv_mismatches = 0u32;
for post in 0..net.neuron_count() {
for (pre, syn_idx) in net.synapse_matrix.incoming(post) {
let s = &net.synapses[syn_idx];
if s.pre_neuron_id != pre || s.post_neuron_id != post {
rv_mismatches += 1;
}
}
}
assert_eq!(
rv_mismatches, 0,
"every reverse-CSR edge must match its synapse's (pre, post)"
);
}
/// `ternarize_weights` at the `γ` edge: weights whose mean magnitude
/// rounds to 0, `[1, 0, 0]`, return 0 and stay as they were; at `γ = 1`
/// they snap, `[2, 1, 0]` to `[1, 1, 0]`.
#[test]
fn ternarize_weights_leaves_the_weights_when_gamma_rounds_to_0() {
for (given, gamma, kept) in [([1_i16, 0, 0], 0, [1_i16, 0, 0]), ([2, 1, 0], 1, [1, 1, 0])] {
let neurons = (0..3)
.map(|id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
.collect();
let mut net =
SpikingNeuralNetwork::from_neurons(neurons, 1_000).expect("three neurons");
for (pre, weight) in (0_u16..).zip(given) {
net.add_synapse(pre, (pre + 1) % 3, weight).expect("adds");
}
assert_eq!(net.ternarize_weights(), gamma, "{given:?}");
let weights: Vec<i16> = net.synapses().iter().map(Synapse::weight).collect();
assert_eq!(weights, kept, "{given:?}");
}
}
/// A ternary write reaches its own CSR slot. The five edges of
/// `fixed::tests::from_network_is_the_csr_order`, finalized: the
/// counting sort moves four of the five slots, so a `set_weight`
/// writing `weights[synapse_index]` — the bd5b098 bug — would reach
/// the wrong slot for every one of them. `ternarize_weights` writes
/// once, `reproject_ternary` again, and this reads both back; no other
/// test reads `reproject_ternary`'s write in either build.
///
/// Its limit: five edges over three ternary values force two equal
/// pairs, so a wrong-slot write between synapses 0 and 2 (both −109,
/// then −54) leaves the same final state — an equivalent mutant on
/// this fixture.
#[test]
fn ternary_writes_reach_their_csr_slot() {
// (synapse index, that slot's weight, that synapse's weight), pre
// by pre: the CSR as the step reads it, beside the list.
fn mirror_slots(net: &SpikingNeuralNetwork) -> Vec<(usize, i16, i16)> {
let mut slots = Vec::new();
for pre in 0..net.neuron_count() {
for (_post, weight, idx) in net.synapse_matrix.connections(pre) {
slots.push((idx, weight, net.synapses[idx].weight));
}
}
slots
}
fn every_slot_mirrors_its_synapse(net: &SpikingNeuralNetwork, after: &str) {
let slots = mirror_slots(net);
assert_eq!(
slots.len(),
net.synapses().len(),
"{after}: the mirror loop must read every slot, or it pins nothing"
);
let wrong: Vec<(usize, i16, i16)> = slots
.into_iter()
.filter(|&(_idx, slot, synapse)| slot != synapse)
.collect();
assert!(
wrong.is_empty(),
"{after}: (synapse, its CSR slot, its weight): {wrong:?}"
);
}
let edges: [(u16, u16, i16); 5] = [
(2, 0, -125),
(0, 2, 7),
(2, 3, -250),
(1, 3, 40),
(0, 1, 125),
];
let mut net = SpikingNeuralNetwork::from_neurons(
(0..4)
.map(|id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
.collect(),
1_000,
)
.expect("four neurons, 1 ms");
for &(pre, post, weight) in &edges {
net.add_synapse(pre, post, weight)
.expect("ids in range, no self edge");
}
net.finalize_synapses();
let order: Vec<usize> = mirror_slots(&net).iter().map(|&(idx, ..)| idx).collect();
assert_eq!(
order,
[1, 4, 3, 0, 2],
"the CSR order, pre by pre: four of the five slots moved"
);
let gamma = net.ternarize_weights();
assert_eq!(gamma, 109, "γ = mean|w| over the five edges");
assert_eq!(
net.synapses()
.iter()
.map(|s| s.weight)
.collect::<Vec<i16>>(),
[-109, 0, -109, 0, 109],
"the ternary images, by synapse index"
);
every_slot_mirrors_its_synapse(&net, "ternarize_weights");
assert_eq!(
net.reproject_ternary(gamma / 2),
3,
"γ/2 = 54 snaps the three nonzero weights"
);
assert_eq!(
net.synapses()
.iter()
.map(|s| s.weight)
.collect::<Vec<i16>>(),
[-54, 0, -54, 0, 54],
"the new grid, by synapse index"
);
every_slot_mirrors_its_synapse(&net, "reproject_ternary");
}
#[test]
fn reverse_csr_incoming_lists_correct_edges_after_finalize() {
// Focused unit test for the reverse CSR: incoming(post) must return
// exactly the edges whose post_neuron_id == post, in a net where
// build_topology inserts in arbitrary order.
let mut net =
SpikingNeuralNetwork::new(48, 1000, NetworkTopology::default()).expect("valid");
net.build_topology().expect("build");
let mut by_post: Vec<Vec<(u16, usize)>> =
(0..net.neuron_count()).map(|_| Vec::new()).collect();
for (syn_idx, s) in net.synapses().iter().enumerate() {
by_post[s.post_neuron_id as usize].push((s.pre_neuron_id, syn_idx));
}
for post in 0..net.neuron_count() {
let mut got: Vec<(u16, usize)> = net.synapse_matrix.incoming(post).collect();
got.sort_unstable();
let mut want = by_post[post as usize].clone();
want.sort_unstable();
assert_eq!(
got, want,
"incoming({post}) must return post's actual incoming edges"
);
}
}
// ----- A network steps its synapses as added (round 64) -----
//
// A step delivers each synapse under its own `pre`, in the order added,
// whatever adds, sorts and steps came before it: the step sorts the CSR
// first when a synapse came in since the last sort. `Wiring` is that
// rule written apart from the CSR, from the step's § Order; with
// plasticity on, the reference is a network wired in `pre` order and
// sorted after each batch of adds.
/// The cases' generator: xorshift64*, no dependency.
struct Rng(u64);
impl Rng {
fn new(seed: u64) -> Self {
Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
}
/// A draw in `0..n`.
fn below(&mut self, n: u64) -> u64 {
let mut x = self.0;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
self.0 = x;
x.wrapping_mul(0x2545_F491_4F6C_DD1D) % n
}
}
/// The drive of step `t` on `n` neurons: neuron 0 at 400 pA, which
/// fires it on its own, every other at 100 pA plus 0 to 150 pA, which
/// fires none of them. It holds an excitatory neuron at −70 to −64 mV,
/// where one pulse fires it from about 1,600 to 2,900 pA, by the
/// membrane and the drive; an inhibitory one, in a built topology,
/// climbs to −54 mV, 4 mV under its threshold.
fn drive(seed: u64, t: u32, n: usize) -> Vec<i16> {
let mut rng = Rng::new(seed ^ (u64::from(t) << 20));
(0..n)
.map(|i| {
if i == 0 {
400
} else {
100 + rng.below(151) as i16
}
})
.collect()
}
/// Every field a step writes, neuron by neuron.
fn written(neurons: &[LIFNeuron]) -> Vec<(i16, u32, u32, u32, i16, i16)> {
neurons
.iter()
.map(|n| {
(
n.membrane_potential,
n.refractory_remaining_us,
n.last_update_time_us,
n.last_spike_time_us,
n.synaptic_current_pa,
n.adaptation_current_pa,
)
})
.collect()
}
/// The step's § Order without plasticity, written apart from the CSR:
/// each neuron that fired, in id order, sends the pulse of each of its
/// synapses, in the order they were added.
struct Wiring {
neurons: Vec<LIFNeuron>,
synapses: Vec<(u16, u16, i16)>,
divisor: i16,
dt_us: u32,
time_us: u64,
}
impl Wiring {
/// `net` as it stands, before its first step.
fn of(net: &SpikingNeuralNetwork) -> Self {
Self {
neurons: net.neurons().to_vec(),
synapses: net
.synapses()
.iter()
.map(|s| (s.pre_neuron_id, s.post_neuron_id, s.weight))
.collect(),
divisor: net.synaptic_input_divisor() as i16,
dt_us: net.dt_us,
time_us: net.time_us,
}
}
fn step(&mut self, input: &[i16]) -> Vec<u16> {
for n in &mut self.neurons {
n.decay_adaptation_current();
}
let now_us = self.time_us as u32;
let mut fired = Vec::new();
for (id, n) in (0u16..).zip(&mut self.neurons) {
let current = input.get(usize::from(id)).copied().unwrap_or(0);
if n.integrate_and_fire(current, self.dt_us, now_us) {
fired.push(id);
}
}
for n in &mut self.neurons {
n.clear_synaptic_current();
}
for &pre in &fired {
for &(_, post, weight) in self.synapses.iter().filter(|s| s.0 == pre) {
self.neurons[usize::from(post)].add_synaptic_current(weight / self.divisor);
}
}
self.time_us += u64::from(self.dt_us);
fired
}
}
/// One act on a hand-wired network.
#[derive(Clone, Copy, Debug)]
enum Act {
Add(u16, u16, i16),
/// `finalize_synapses`.
Sort,
/// That many steps, on the case's drive.
Steps(u32),
}
/// The steps of a run.
const STEPS: u32 = 200;
/// One step of `net` and of its `Wiring`: the spikes of every neuron
/// but 0, which only a pulse fires, when the two spike alike and every
/// field a step writes is the same, or `None`.
fn step_both(
net: &mut SpikingNeuralNetwork,
rule: &mut Wiring,
seed: u64,
t: u32,
) -> Option<usize> {
let input = drive(seed, t, usize::from(net.neuron_count()));
let got: Vec<u16> = net
.step(&input)
.expect("steps")
.iter()
.map(|s| s.neuron_id)
.collect();
let alike = got == rule.step(&input) && written(net.neurons()) == written(&rule.neurons);
alike.then(|| got.iter().filter(|&&id| id != 0).count())
}
/// `acts` on `net` and on its `Wiring` side by side, then both stepped
/// to `STEPS`: `Err` with the first step at which they part, or `Ok`
/// with the spikes of every neuron but 0.
fn steps_as_its_wiring(
mut net: SpikingNeuralNetwork,
acts: &[Act],
seed: u64,
) -> std::result::Result<usize, u32> {
let mut rule = Wiring::of(&net);
let (mut t, mut pulsed) = (0, 0);
for &act in acts {
match act {
Act::Add(pre, post, weight) => {
net.add_synapse(pre, post, weight)
.expect("ids in range, no self edge");
rule.synapses.push((pre, post, weight));
}
Act::Sort => net.finalize_synapses(),
Act::Steps(k) => {
for _ in 0..k {
pulsed += step_both(&mut net, &mut rule, seed, t).ok_or(t)?;
t += 1;
}
}
}
}
while t < STEPS {
pulsed += step_both(&mut net, &mut rule, seed, t).ok_or(t)?;
t += 1;
}
Ok(pulsed)
}
/// The synapses of `net` by `pre`, a stable sort: within one `pre` in
/// the order added.
#[cfg(feature = "unstable-stdp")]
fn by_pre(net: &SpikingNeuralNetwork) -> Vec<(u16, u16, i16)> {
let mut list: Vec<(u16, u16, i16)> = net
.synapses()
.iter()
.map(|s| (s.pre_neuron_id, s.post_neuron_id, s.weight))
.collect();
list.sort_by_key(|s| s.0);
list
}
/// The batch on `reference`, in `pre` order, then a sort.
#[cfg(feature = "unstable-stdp")]
fn add_sorted(reference: &mut SpikingNeuralNetwork, batch: &mut Vec<(u16, u16, i16)>) {
batch.sort_by_key(|s| s.0);
for &(pre, post, weight) in &*batch {
reference
.add_synapse(pre, post, weight)
.expect("ids in range, no self edge");
}
reference.finalize_synapses();
batch.clear();
}
/// One step of both: the same spikes.
#[cfg(feature = "unstable-stdp")]
fn spike_alike(
net: &mut SpikingNeuralNetwork,
reference: &mut SpikingNeuralNetwork,
seed: u64,
t: u32,
) -> bool {
let input = drive(seed, t, usize::from(net.neuron_count()));
let ids = |net: &mut SpikingNeuralNetwork| -> Vec<u16> {
net.step(&input)
.expect("steps")
.iter()
.map(|s| s.neuron_id)
.collect()
};
ids(net) == ids(reference)
}
/// With plasticity on: `acts` on `net`, and the same synapses on a
/// network of the same neurons wired in `pre` order and sorted after
/// each batch, side by side to `STEPS`. Whether every spike agrees,
/// and at the end every weight, each list taken `by_pre`.
#[cfg(feature = "unstable-stdp")]
fn learns_as_its_reference(mut net: SpikingNeuralNetwork, acts: &[Act], seed: u64) -> bool {
let mut reference = SpikingNeuralNetwork::from_neurons(net.neurons().to_vec(), net.dt_us)
.expect("the same neurons");
reference
.set_synaptic_input_divisor(net.synaptic_input_divisor())
.expect("the same divisor");
net.set_plasticity_enabled(true);
reference.set_plasticity_enabled(true);
// The synapses `net` holds already (a topology's), then each batch.
let mut batch = by_pre(&net);
let mut t = 0;
for &act in acts {
match act {
Act::Add(pre, post, weight) => {
net.add_synapse(pre, post, weight)
.expect("ids in range, no self edge");
batch.push((pre, post, weight));
}
Act::Sort => net.finalize_synapses(),
Act::Steps(k) => {
add_sorted(&mut reference, &mut batch);
for _ in 0..k {
if !spike_alike(&mut net, &mut reference, seed, t) {
return false;
}
t += 1;
}
}
}
}
add_sorted(&mut reference, &mut batch);
while t < STEPS {
if !spike_alike(&mut net, &mut reference, seed, t) {
return false;
}
t += 1;
}
by_pre(&net) == by_pre(&reference)
}
/// The cases' seed.
const SEED: u64 = 1;
/// Case `c`: 3 to 8 neurons and two or more distinct pairs in random
/// order, weights 200 to 2,000 pA.
fn case_edges(case: u64) -> (u16, Vec<(u16, u16, i16)>) {
let mut rng = Rng::new(SEED.wrapping_add(case));
let neurons = 3 + rng.below(6) as u16;
let pairs: Vec<(u16, u16)> = (0..neurons)
.flat_map(|pre| {
(0..neurons)
.filter(move |&post| post != pre)
.map(move |post| (pre, post))
})
.collect();
let count = 2 + rng.below(pairs.len() as u64 - 1) as usize;
let mut order: Vec<usize> = (0..pairs.len()).collect();
for i in 0..order.len() {
let j = i + rng.below((order.len() - i) as u64) as usize;
order.swap(i, j);
}
let edges = order[..count]
.iter()
.map(|&k| (pairs[k].0, pairs[k].1, 200 + rng.below(1801) as i16))
.collect();
(neurons, edges)
}
fn adds(edges: &[(u16, u16, i16)]) -> impl Iterator<Item = Act> + '_ {
edges
.iter()
.map(|&(pre, post, weight)| Act::Add(pre, post, weight))
}
/// A built network for wiring 8: one of the four topologies, by case.
fn built(n: u16, c: u64) -> SpikingNeuralNetwork {
let topology = match (c / WIRINGS) % 4 {
0 => NetworkTopology::Random { connectivity: 0.3 },
1 => NetworkTopology::SmallWorld {
local_connections: 2,
rewiring_prob: 0.3,
},
2 => NetworkTopology::Feedforward {
layers: Box::leak(vec![n / 2, n - n / 2].into_boxed_slice()),
},
_ => NetworkTopology::Balanced {
excitatory_ratio: 0.8,
},
};
let mut net = SpikingNeuralNetwork::new(n, 1000, topology).expect("3 to 8 neurons");
net.build_topology().expect("each rule holds");
net
}
/// The wirings of a case, each the network it starts from (divisor 1)
/// and the acts that wire it. 0 to 6: in random order and sorted once;
/// in `pre` order and never sorted; in random order and never sorted;
/// half, a sort, the rest; the same and a sort; in random order and
/// sorted twice; half, a sort, the rest and two sorts. 7: half, 50
/// steps, the rest. 8: a built topology, then the case's synapses. 9:
/// one synapse before each of the first steps.
const WIRINGS: u64 = 10;
fn wiring(c: u64) -> (SpikingNeuralNetwork, Vec<Act>) {
let (n, mut edges) = case_edges(c);
let half = edges.len() / 2;
let mut net = SpikingNeuralNetwork::from_neurons(
(0..n)
.map(|id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
.collect(),
1000,
)
.expect("3 to 8 neurons");
let (first, rest) = edges.split_at(half);
let acts: Vec<Act> = match c % WIRINGS {
0 => adds(&edges).chain([Act::Sort]).collect(),
1 => {
edges.sort_by_key(|s| s.0);
adds(&edges).collect()
}
2 => adds(&edges).collect(),
3 => adds(first).chain([Act::Sort]).chain(adds(rest)).collect(),
4 => adds(first)
.chain([Act::Sort])
.chain(adds(rest))
.chain([Act::Sort])
.collect(),
5 => adds(&edges).chain([Act::Sort, Act::Sort]).collect(),
6 => adds(first)
.chain([Act::Sort])
.chain(adds(rest))
.chain([Act::Sort, Act::Sort])
.collect(),
7 => adds(first)
.chain([Act::Steps(50)])
.chain(adds(rest))
.collect(),
8 => {
net = built(n, c);
adds(&edges).collect()
}
_ => adds(&edges).flat_map(|a| [a, Act::Steps(1)]).collect(),
};
net.set_synaptic_input_divisor(1).expect("in 1 to 32,767");
(net, acts)
}
/// Every wiring of 400 cases steps as its synapses were added, against
/// its `Wiring`, and with `unstable-stdp` learns as its reference with
/// plasticity on. In most cases a pulse fires a neuron (the guard
/// below): the drive fires neuron 0 alone, so without such pulses only
/// its synapses would deliver.
#[test]
fn every_wiring_steps_as_its_synapses_were_added() {
const CASES: u64 = 400;
let mut parted: Vec<String> = Vec::new();
let (mut parted_cases, mut pulsed_cases) = (0, 0);
for c in 0..CASES {
let before = parted.len();
let (net, acts) = wiring(c);
match steps_as_its_wiring(net, &acts, SEED ^ c) {
Ok(pulsed) => pulsed_cases += usize::from(pulsed > 0),
Err(t) => {
parted.push(format!(
"case {c}, wiring {}: parts at step {t}",
c % WIRINGS
));
}
}
#[cfg(feature = "unstable-stdp")]
{
let (net, acts) = wiring(c);
if !learns_as_its_reference(net, &acts, SEED ^ c) {
parted.push(format!(
"case {c}, wiring {}: learns otherwise",
c % WIRINGS
));
}
}
parted_cases += usize::from(parted.len() > before);
}
assert!(
parted.is_empty(),
"{parted_cases} of {CASES} cases part:\n{}",
parted.join("\n")
);
assert!(
pulsed_cases * 4 >= CASES as usize * 3,
"a pulse fires a neuron in {pulsed_cases} of {CASES} cases, not three in four"
);
}
/// The step sorts a network wired since the last sort and leaves it
/// clean; `build_topology` leaves it clean too.
#[test]
fn a_step_sorts_what_was_added_since_the_last_sort() {
let mut net = SpikingNeuralNetwork::from_neurons(
(0..3)
.map(|id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
.collect(),
1000,
)
.expect("three neurons");
assert!(!net.synapse_matrix.is_dirty(), "built clean");
net.add_synapse(1, 2, 500).expect("ids in range");
net.add_synapse(0, 1, 500).expect("ids in range");
assert!(net.synapse_matrix.is_dirty(), "two adds since");
net.step(&[0, 0, 0]).expect("steps");
assert!(!net.synapse_matrix.is_dirty(), "the step sorted");
let rows = |net: &SpikingNeuralNetwork| -> Vec<Vec<(u16, i16, usize)>> {
(0..3)
.map(|pre| net.synapse_matrix.connections(pre).collect())
.collect()
};
assert_eq!(
rows(&net),
vec![vec![(1, 500, 1)], vec![(2, 500, 0)], vec![]]
);
net.add_synapse(0, 2, 300).expect("ids in range");
net.step(&[0, 0, 0]).expect("steps");
assert_eq!(
rows(&net),
vec![vec![(1, 500, 1), (2, 300, 2)], vec![(2, 500, 0)], vec![]],
"pre 0's two in the order added"
);
assert_eq!(net.synapse_count(), 3);
let mut built =
SpikingNeuralNetwork::new(10, 1000, NetworkTopology::default()).expect("ten neurons");
built.build_topology().expect("builds");
assert!(!built.synapse_matrix.is_dirty(), "build_topology sorts");
}
/// `finalize` sorts whatever order it finds: a second call, or one
/// after more adds, keeps each `pre`'s edges in the order they were
/// added. Round 43's witness: `add(3→2)`, `add(2→3, 200)`, finalize,
/// `add(2→3, 300)`, finalize, finalize. Before round 64 the last two
/// walked a key list the arrays no longer matched and left pre 2's two
/// edges newest first. And on edges added out of `pre` order a second
/// finalize keeps every forward slot, each post's incoming edges, and
/// where `set_weight` writes.
#[test]
fn a_finalize_after_a_finalize_keeps_the_order_added() {
let rows = |m: &SparseSynapseMatrix| -> Vec<Vec<(u16, i16, usize)>> {
(0..4).map(|pre| m.connections(pre).collect()).collect()
};
let mut m = SparseSynapseMatrix::new(4, 3);
m.add(3, 2, 100, 0);
m.add(2, 3, 200, 1);
m.finalize();
m.add(2, 3, 300, 2);
m.finalize();
m.finalize();
assert_eq!(
rows(&m),
vec![
vec![],
vec![],
vec![(3, 200, 1), (3, 300, 2)],
vec![(2, 100, 0)]
],
"pre 2's two in the order added"
);
let edges: [(u16, u16, i16); 6] = [
(2, 0, -125),
(0, 2, 7),
(2, 3, -250),
(1, 3, 40),
(0, 1, 125),
(3, 1, 60),
];
let mut m = SparseSynapseMatrix::new(4, edges.len());
for (i, &(pre, post, weight)) in edges.iter().enumerate() {
m.add(pre, post, weight, i);
}
m.finalize();
let incoming = |m: &SparseSynapseMatrix| -> Vec<Vec<(u16, usize)>> {
(0..4)
.map(|post| {
let mut edges: Vec<(u16, usize)> = m.incoming(post).collect();
edges.sort_unstable();
edges
})
.collect()
};
let (once_rows, once_incoming) = (rows(&m), incoming(&m));
m.finalize();
assert_eq!(rows(&m), once_rows, "every forward slot kept");
assert_eq!(
incoming(&m),
once_incoming,
"each post's incoming edges kept"
);
for (i, weight) in (0..edges.len()).zip(1i16..) {
m.set_weight(i, weight);
}
for pre in 0..4 {
for (_post, weight, i) in m.connections(pre) {
assert_eq!(weight, i as i16 + 1, "synapse {i}'s write on its slot");
}
}
}
/// An add after `build_topology` steps as added, in each of the four
/// topologies: one synapse from neuron 0 to the last.
#[test]
fn an_add_after_build_topology_steps_as_added() {
let mut parted = Vec::new();
for (n, topology) in [
(6, NetworkTopology::Feedforward { layers: &[2, 2, 2] }),
(12, NetworkTopology::Random { connectivity: 0.3 }),
(
12,
NetworkTopology::SmallWorld {
local_connections: 2,
rewiring_prob: 0.3,
},
),
(
12,
NetworkTopology::Balanced {
excitatory_ratio: 0.8,
},
),
] {
let mut net = SpikingNeuralNetwork::new(n, 1000, topology).expect("valid");
net.build_topology().expect("builds");
net.set_synaptic_input_divisor(1).expect("in 1 to 32,767");
let pulsed = steps_as_its_wiring(net, &[Act::Add(0, n - 1, 1500)], 7);
if !matches!(pulsed, Ok(1..)) {
parted.push(format!("{topology:?}: {pulsed:?}"));
}
}
assert!(parted.is_empty(), "{parted:#?}");
}
// ----- Transmission live (session F fix: clear-after-read reorder) -----
// Historical bug, pinned 2026-08-18 (stage 1c): Phase 2 injected
// weight/10 AFTER Phase 1's integration and the next step cleared the
// accumulator BEFORE it — recurrent current was never integrated; every
// "weights don't shape firing" result in the D-2/E lineage was this cut
// wire. The fix reorders step() (adaptation decay → integrate → clear →
// propagate): pulses now integrate on the NEXT step — the one-step
// delay the orchestrator always claimed. The tests below pin it exact.
#[test]
fn transmission_is_live_one_step_delayed_centimv() {
// 2 neurons ⇒ neuron 0 E, neuron 1 I (exc_count truncates to 1).
// Centi grid, noise off. Pre driven to fire on step 0 (E on centi:
// 3000 pA ⇒ delta_v 1500 quanta ⇒ −7000+1500 = −5500 = threshold).
// A +125-weight spike injects +12 pA (weight / default divisor 10,
// truncating);
// I-type integration: current_term = 12·100·100/1000 = 120 cV,
// delta_v = 100·120/1000 = 12 quanta ⇒ post −7000 → −6988 exactly
// ONE step after the pre spike (and unmoved the step of the spike —
// the delay itself is pinned).
let mut net = SpikingNeuralNetwork::new_with_voltage_resolution(
2,
1000,
NetworkTopology::Random { connectivity: 0.0 },
VoltageResolution::CentiMillivolt,
)
.expect("constructs");
net.build_topology().expect("empty build");
for n in &mut net.neurons {
n.noise_amplitude_pa = 0;
}
net.add_synapse(0, 1, 125).expect("edge");
net.finalize_synapses();
let spikes = net.step(&[3000, 0]).expect("step 0");
assert_eq!(spikes.len(), 1, "pre fires on step 0");
assert_eq!(
net.neurons[1].membrane_potential, -7_000,
"post unmoved on the spike step itself — one-step delay"
);
net.step(&[0, 0]).expect("step 1");
assert_eq!(
net.neurons[1].membrane_potential, -6_988,
"post integrates the pulse exactly one step later (+12 quanta)"
);
}
#[test]
fn transmission_is_live_one_step_delayed_mv_strong_weight() {
// Same pin on the DEFAULT mV grid with a strong weight: 2000 →
// +200 pA pulse. I-type mV: current_term = 200·100/1000 = 20,
// delta_v = 100·20/1000 = 2 mV ⇒ post −70 → −68 one step after pre.
// (A single ±12 pA pulse cannot move an mV-grid I neuron — dead
// zone ~100 pA; that sensitivity belongs to the centi grid.)
let mut net =
SpikingNeuralNetwork::new(2, 1000, NetworkTopology::Random { connectivity: 0.0 })
.expect("constructs");
net.build_topology().expect("empty build");
for n in &mut net.neurons {
n.noise_amplitude_pa = 0;
}
net.add_synapse(0, 1, 2000).expect("edge");
net.finalize_synapses();
let spikes = net.step(&[3000, 0]).expect("step 0");
assert_eq!(
spikes.len(),
1,
"pre fires on step 0 (E mV: 3000 pA ⇒ +15 mV)"
);
assert_eq!(
net.neurons[1].membrane_potential, -70,
"delay: unmoved this step"
);
net.step(&[0, 0]).expect("step 1");
assert_eq!(
net.neurons[1].membrane_potential, -68,
"+2 mV one step later"
);
}
/// The exception to the one-step delay: a `post` refractory at the step
/// that would read the pulse. mV grid, the +200 pA pulse of the test
/// above, which moves a listening `post` to −68. Here `post` is
/// refractory for two steps from step 0: the pulse sits in its
/// accumulator through step 1, unread, and step 1's clear drops it.
/// Step 2 integrates, and finds nothing: lost, not deferred.
#[test]
fn a_pulse_to_a_refractory_post_is_dropped_not_deferred() {
let mut net =
SpikingNeuralNetwork::new(2, 1000, NetworkTopology::Random { connectivity: 0.0 })
.expect("constructs");
net.build_topology().expect("empty build");
for n in &mut net.neurons {
n.noise_amplitude_pa = 0;
}
net.neurons[1].refractory_remaining_us = 2_000;
net.add_synapse(0, 1, 2000).expect("edge");
net.finalize_synapses();
let spikes = net.step(&[3000, 0]).expect("step 0");
assert_eq!(spikes.len(), 1, "pre fires on step 0");
assert_eq!(net.neurons[1].synaptic_current_pa, 200, "delivered");
net.step(&[0, 0]).expect("step 1");
assert_eq!(net.neurons[1].membrane_potential, -70, "refractory");
assert_eq!(net.neurons[1].synaptic_current_pa, 0, "cleared unread");
assert_eq!(net.neurons[1].refractory_remaining_us, 0);
net.step(&[0, 0]).expect("step 2");
assert_eq!(
net.neurons[1].membrane_potential, -70,
"step 2 integrates and no pulse is left: dropped, not deferred"
);
}
/// The step divides by `divisor as i16`: from 32,768 the cast wrapped
/// negative (65,534 is `-2`, and a +2000 weight delivered −1000 pA),
/// and 65,535, `-1`, overflowed on a weight of `i16::MIN`, a panic in
/// the step. The setter refuses each, and the divisor it had stays.
#[test]
fn a_divisor_above_i16_max_is_refused() {
let mut net =
SpikingNeuralNetwork::new(2, 1000, NetworkTopology::Random { connectivity: 0.0 })
.expect("constructs");
for divisor in [32_768, 65_534, 65_535] {
assert_eq!(
net.set_synaptic_input_divisor(divisor),
Err(Error::DivisorOutOfRange),
"{divisor}"
);
assert_eq!(net.synaptic_input_divisor(), 10, "{divisor}: unchanged");
}
}
/// 32,767, the largest divisor, divides a weight of `i16::MIN` in
/// `i16`: the pulse truncates to −1 pA, where 65,535 panicked.
#[test]
fn the_largest_divisor_steps_the_weight_i16_min() {
let mut net =
SpikingNeuralNetwork::new(2, 1000, NetworkTopology::Random { connectivity: 0.0 })
.expect("constructs");
net.build_topology().expect("empty build");
for n in &mut net.neurons {
n.noise_amplitude_pa = 0; // 3000 pA lands ON the threshold: pre fires
}
net.set_synaptic_input_divisor(32_767)
.expect("the largest divisor");
net.add_synapse(0, 1, i16::MIN)
.expect("add_synapse accepts it");
net.finalize_synapses();
let spikes = net.step(&[3000, 0]).expect("step 0");
assert_eq!(spikes.len(), 1, "pre fires on step 0");
assert_eq!(net.neurons[1].synaptic_current_pa, -1);
}
/// The hand-written `Debug` reads the two counts and names the step and
/// the clock as their getters do, `dt_us` and `time_us`, the names
/// `FixedNetwork`'s derived one prints. It steps twice, so the clock and
/// the step differ and a crossed pair shows.
#[test]
fn debug_reads_the_counts_the_step_and_the_clock() {
let mut net =
SpikingNeuralNetwork::new(3, 1000, NetworkTopology::default()).expect("constructs");
net.add_synapse(0, 1, 100).expect("adds");
net.add_synapse(1, 2, -50).expect("adds");
net.step(&[0, 0, 0]).expect("step");
net.step(&[0, 0, 0]).expect("step");
let text = format!("{net:?}");
let head = "SpikingNeuralNetwork { neurons: 3, synapses: 2, dt_us: 1000, time_us: 2000, ";
assert!(text.starts_with(head), "{text}");
assert!(text.ends_with(", .. }"), "{text}");
}
/// The clock runs past 2^32 μs, where it used to saturate: the neurons are
/// handed its low 32 bits, all 32 of them, and a spike, the firing rate
/// and a `FixedNetwork` converted from the network read the whole clock.
#[test]
fn the_clock_runs_past_the_u32_ceiling() {
let mut net =
SpikingNeuralNetwork::new(2, 1000, NetworkTopology::Random { connectivity: 0.0 })
.expect("constructs");
net.time_us = u64::from(u32::MAX) - 400;
net.step(&[0, 0]).expect("step");
assert_eq!(net.time_us(), u64::from(u32::MAX) + 600);
// The first step ran at 2^32 - 401: its stamp keeps bit 31.
assert_eq!(net.neurons[0].last_update_time_us, u32::MAX - 400);
// Neuron 0 fires on the second step, which runs at 2^32 + 599.
let spikes = net.step(&[i16::MAX, 0]).expect("step");
assert_eq!(net.time_us(), u64::from(u32::MAX) + 1_600);
assert_eq!(spikes.len(), 1, "neuron 0 fires, neuron 1 does not");
assert_eq!(spikes[0].time_us, u64::from(u32::MAX) + 600);
// The neuron's own stamps are the low 32 bits: 599.
assert_eq!(net.neurons[0].last_update_time_us, 599);
assert_eq!(net.neurons[0].last_spike_time_us, 599);
// One spike over two neurons in 2^32 + 1,599 μs, 4,294.968895 s: the
// rate is not read off the 1,599 μs of the clock's low 32 bits.
let rate = net.stats().firing_rate_hz;
assert!(
(rate - 1.0 / (4_294.968_895 * 2.0)).abs() < 1e-12,
"{rate} Hz"
);
let fixed = crate::fixed::FixedNetwork::<2, 0>::try_from(&net).expect("2 and 0");
assert_eq!(fixed.time_us(), u64::from(u32::MAX) + 1_600);
}
/// A topology builder gives every neuron noise 5, whatever the topology
/// and the grid, and `new` builds through it; `from_neurons` keeps the
/// neurons as given, their noise too.
#[test]
fn a_topology_builder_gives_its_neurons_noise() {
for res in [
VoltageResolution::Millivolt,
VoltageResolution::CentiMillivolt,
] {
for topology in [
NetworkTopology::default(),
NetworkTopology::Random { connectivity: 0.0 },
] {
let net =
SpikingNeuralNetwork::new_with_voltage_resolution(10, 1000, topology, res)
.expect("builds");
assert!(
net.neurons().iter().all(|n| n.noise_amplitude_pa == 5),
"{res:?}"
);
}
}
// `new`, which the visualizer, the examples and the README call.
for topology in [
NetworkTopology::default(),
NetworkTopology::Random { connectivity: 0.0 },
] {
let net = SpikingNeuralNetwork::new(10, 1000, topology).expect("builds");
assert!(
net.neurons().iter().all(|n| n.noise_amplitude_pa == 5),
"new, {topology:?}"
);
}
let given = SpikingNeuralNetwork::from_neurons(
vec![
LIFNeuron::new(0, NeuronType::Excitatory, VoltageResolution::Millivolt)
.with_noise_amplitude_pa(3),
],
1000,
)
.expect("builds");
assert_eq!(given.neurons()[0].noise_amplitude_pa, 3);
}
/// STDP does the same past 2^32 μs as at the start: the three pairings the
/// rule tells apart give a weight change of −3, +3 and 0 at time 0, at
/// 2^31 + 10^7 μs (bit 31 set in every stamp) and at 2^32 + 10^7 μs
/// alike. The neurons carry 32-bit stamps and the clock is a `u64`, so
/// the pairing takes the difference of their low 32 bits
/// (`stamp_dt_us`), and a pair across a turn of them still reads −3. At
/// the old saturated clock every pre spike whose post had fired since the
/// ceiling gained +5, whatever the timing; in this test's shape, a fresh
/// network per pairing, the three read +5, 0 and 0.
#[cfg(feature = "unstable-stdp")]
#[test]
fn stdp_pairs_the_same_past_the_u32_ceiling() {
use crate::lif_neuron::{NeuronType, VoltageResolution};
// `first` fires, then `gap` steps later the other (gap 0: it alone).
let change = |start_us: u64, first: usize, gap: u64| -> i16 {
let quiet = |id| {
LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt)
.with_noise_amplitude_pa(0)
};
let mut net =
SpikingNeuralNetwork::from_neurons(vec![quiet(0), quiet(1)], 1_000).expect("two");
net.add_synapse(0, 1, 500).expect("0 -> 1");
net.finalize_synapses();
net.set_plasticity_enabled(true);
net.time_us = start_us;
let fire = |net: &mut SpikingNeuralNetwork, id: usize| {
let mut input = [0i16; 2];
input[id] = i16::MAX;
let ids: Vec<u16> = net
.step(&input)
.expect("steps")
.iter()
.map(|s| s.neuron_id)
.collect();
assert_eq!(ids, [id as u16], "only neuron {id} fires");
};
for _ in 0..2_000 {
net.step(&[0, 0]).expect("steps");
}
fire(&mut net, first);
if gap > 0 {
for _ in 1..gap {
net.step(&[0, 0]).expect("steps");
}
fire(&mut net, 1 - first);
}
net.synapses()[0].weight - 500
};
for start_us in [0, (1u64 << 31) + 10_000_000, (1u64 << 32) + 10_000_000] {
assert_eq!(
change(start_us, 1, 5),
-3,
"post 5 steps before pre, from {start_us}"
);
assert_eq!(
change(start_us, 0, 5),
3,
"pre 5 steps before post, from {start_us}"
);
assert_eq!(change(start_us, 0, 0), 0, "pre alone, from {start_us}");
}
// Post at 2^32 - 3,000 μs, pre 5 ms later at 2^32 + 2,000: the low 32
// bits turn between them. Post first only: a pre spike this close to
// the turn would also pair with the never-fired post's stamp 0.
assert_eq!(
change((1u64 << 32) - 2_003_000, 1, 5),
-3,
"post 5 steps before pre, across the turn"
);
}
/// Two neurons firing in the same step pair as pre 1 μs after post, the
/// LTD tie-break, −5 at any clock past 0: at 1 ms, at the turns of the
/// clock's low 32 bits and between them. At a turn's first microsecond
/// the low 32 bits are 0, so the tie-break must take 1 off the whole
/// clock, as the queue must hold it: off the low 32 bits it would
/// saturate at 0.
#[cfg(feature = "unstable-stdp")]
#[test]
fn the_same_step_tie_break_holds_at_the_turns() {
const TURN: u64 = 1 << 32;
for clock in [
1_000,
TURN - 1,
TURN,
TURN + 1_000,
2 * TURN - 1,
2 * TURN,
5 * TURN + 3,
] {
let mut net = SpikingNeuralNetwork::from_neurons(
(0..2)
.map(|id| {
LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt)
})
.collect(),
1_000,
)
.expect("two");
net.add_synapse(0, 1, 500).expect("0 -> 1");
net.finalize_synapses();
net.set_plasticity_enabled(true);
net.time_us = clock;
let ids: Vec<u16> = net
.step(&[i16::MAX, i16::MAX])
.expect("steps")
.iter()
.map(|s| s.neuron_id)
.collect();
assert_eq!(ids, [0, 1], "both fire at {clock:#x}");
assert_eq!(
net.synapses()[0].weight - 500,
-5,
"the tie-break at {clock:#x}"
);
}
}
#[test]
fn transmission_pulses_sum_across_presynaptic_spikes() {
// Two presynaptic neurons firing the same step ⇒ both pulses land
// together in the accumulator ⇒ integrated as ONE summed current
// next step (the σ-accumulation the channel physics runs on).
// 3 neurons ⇒ 0,1 E; 2 I. Post = neuron 2 (I-type). Weights 125 each
// ⇒ 2 × +12 = +24 pA; centi I: current_term = 24·100·100/1000 = 240,
// delta_v = 100·240/1000 = 24 quanta ⇒ −7000 → −6976.
let mut net = SpikingNeuralNetwork::new_with_voltage_resolution(
3,
1000,
NetworkTopology::Random { connectivity: 0.0 },
VoltageResolution::CentiMillivolt,
)
.expect("constructs");
net.build_topology().expect("empty build");
for n in &mut net.neurons {
n.noise_amplitude_pa = 0;
}
net.add_synapse(0, 2, 125).expect("edge a");
net.add_synapse(1, 2, 125).expect("edge b");
net.finalize_synapses();
let spikes = net.step(&[3000, 3000, 0]).expect("step 0");
assert_eq!(spikes.len(), 2, "both pres fire");
assert_eq!(net.neurons[2].membrane_potential, -7_000, "delay");
net.step(&[0, 0, 0]).expect("step 1");
assert_eq!(
net.neurons[2].membrane_potential, -6_976,
"summed +24 quanta"
);
}
#[test]
fn network_propagates_centimillivolt_resolution_to_every_neuron() {
let mut net = SpikingNeuralNetwork::new_with_voltage_resolution(
50,
1000,
NetworkTopology::Random { connectivity: 0.0 },
VoltageResolution::CentiMillivolt,
)
.expect("constructs");
net.build_topology().expect("empty build");
for n in &net.neurons {
assert_eq!(n.voltage_resolution, VoltageResolution::CentiMillivolt);
assert_eq!(n.resting_potential, -7_000);
}
// E threshold −5_500 / I −5_000 on the scaled grid.
assert_eq!(net.neurons[0].threshold, -5_500);
assert_eq!(net.neurons[49].threshold, -5_000);
}
#[test]
fn sub_dead_zone_drive_spikes_only_in_centimillivolt_network() {
// Network-level dead-zone proof: 160 pA sustained (above the ~150 pA
// E threshold current, below the mV grid's 200 pA dead zone from
// rest). Same drive, same noise seeds — only the grid differs.
// 5 neurons ⇒ exc_count = 4 (neuron 0 is Excitatory; the I neurons
// sit at V_ss −54 mV < their −50 threshold and stay silent in both
// grids). Zero connectivity ⇒ every neuron is driven independently.
let drive = || vec![160_i16; 5];
let mut mv =
SpikingNeuralNetwork::new(5, 1000, NetworkTopology::Random { connectivity: 0.0 })
.expect("constructs");
mv.build_topology().expect("build");
for n in &mut mv.neurons {
n.noise_amplitude_pa = 0;
}
let mut mv_spikes = 0;
for _ in 0..100 {
mv_spikes += mv.step(&drive()).expect("step").len();
}
assert_eq!(mv_spikes, 0, "mV grid: blind to 160 pA from rest");
let mut cmv = SpikingNeuralNetwork::new_with_voltage_resolution(
5,
1000,
NetworkTopology::Random { connectivity: 0.0 },
VoltageResolution::CentiMillivolt,
)
.expect("constructs");
cmv.build_topology().expect("build");
for n in &mut cmv.neurons {
n.noise_amplitude_pa = 0;
}
let mut cmv_spikes = 0;
for _ in 0..100 {
cmv_spikes += cmv.step(&drive()).expect("step").len();
}
assert!(cmv_spikes >= 1, "centi grid: 160 pA fires the E neurons");
}
// ----- Property tests (Cardano-grade rigor) -----
proptest! {
/// Any neuron_count > 0 with any valid topology succeeds at construction.
#[test]
fn prop_valid_network_constructs(
n in 1u16..=200,
topology in topology_strategy(),
) {
let result = SpikingNeuralNetwork::new(n, 1000, topology);
prop_assert!(result.is_ok(), "valid n+topology must construct");
}
/// step() advances time by exactly dt_us, regardless of input,
/// from time 0. Past the `u32` ceiling the clock keeps running
/// (`the_clock_runs_past_the_u32_ceiling`).
#[test]
fn prop_step_advances_time(
n in 5u16..=50,
dt in 100u32..=10_000,
input_value in -500i16..=500,
) {
let mut net = SpikingNeuralNetwork::new(n, dt, NetworkTopology::default())?;
net.build_topology()?;
let inputs = vec![input_value; n as usize];
net.step(&inputs)?;
prop_assert_eq!(net.time_us(), u64::from(dt));
}
/// No topologies create self-connections (pre != post for every synapse).
#[test]
fn prop_no_self_connections(
n in 5u16..=30,
topology in topology_strategy(),
) {
let mut net = SpikingNeuralNetwork::new(n, 1000, topology)?;
net.build_topology()?;
for s in &net.synapses {
prop_assert_ne!(
s.pre_neuron_id, s.post_neuron_id,
"self-connection created"
);
}
}
/// Presynaptic-type sign invariant (module-doc claim): excitatory
/// presynaptic → strictly positive weight; inhibitory → strictly negative.
/// Pins the contract every topology builder relies on via `typed_weight`.
#[test]
fn prop_topology_weights_respect_presynaptic_type(
n in 5u16..=30,
topology in topology_strategy(),
) {
let mut net = SpikingNeuralNetwork::new(n, 1000, topology)?;
net.build_topology()?;
// The sign invariant holds vacuously when a sparse topology wires
// nothing (e.g. tiny n × tiny connectivity); proptest still explores
// plenty of non-empty cases across the strategy range.
for s in &net.synapses {
let pre_type = net.neurons[s.pre_neuron_id as usize].neuron_type;
match pre_type {
NeuronType::Excitatory => prop_assert!(
s.weight > 0,
"excitatory presynaptic must yield positive weight, got {}",
s.weight
),
NeuronType::Inhibitory => prop_assert!(
s.weight < 0,
"inhibitory presynaptic must yield negative weight, got {}",
s.weight
),
}
}
}
/// LFSR produces same output for same input (deterministic).
#[test]
fn prop_lfsr_deterministic(seed in any::<u32>()) {
let a = advance_lfsr(seed);
let b = advance_lfsr(seed);
let c = advance_lfsr(seed);
prop_assert_eq!(a, b);
prop_assert_eq!(a, c);
}
/// Sparse matrix iteration count, after a sort, matches total
/// synapses added.
#[test]
fn prop_sparse_matrix_iter_matches_count(
n in 1u16..=20,
syn_count in 0usize..=50,
) {
let mut m = SparseSynapseMatrix::new(n, syn_count);
for i in 0..syn_count {
let pre = (i as u16) % n;
let post = ((i as u16) + 1) % n;
let post = if post == pre { (post + 1) % n } else { post };
m.add(pre, post, 100, i);
}
m.finalize();
let total: usize = (0..n).map(|i| m.connections(i).count()).sum();
prop_assert_eq!(total, syn_count);
}
}
/// Proptest strategy for `NetworkTopology` variants with sane parameter ranges.
/// Feedforward is excluded — its layer sizes must match the neuron count,
/// which can't be expressed in a standalone strategy. Feedforward is covered
/// by the dedicated `feedforward_topology_produces_synapses` unit test.
fn topology_strategy() -> impl Strategy<Value = NetworkTopology> {
prop_oneof![
(0.01f64..=0.99).prop_map(|c| NetworkTopology::Random { connectivity: c }),
(1u8..=10u8, 0.0f64..=1.0).prop_map(|(lc, rp)| NetworkTopology::SmallWorld {
local_connections: lc,
rewiring_prob: rp,
}),
(0.5f64..=0.95).prop_map(|er| NetworkTopology::Balanced {
excitatory_ratio: er
}),
]
}
// ----- 2026-08-20 substrate-audit live pin (F1): the per-step decay
// contract. Without `decay_adaptation_current` inside `step()`,
// adaptation (+2/spike) grows monotonically until it exceeds the drive
// and the network falls permanently silent. With it, adaptation
// equilibrates and a driven net cycles forever. Both halves asserted
// through the public orchestration, noise off, mV grid. -----
// ----- R4(ii): the coupling knob. Default = the historical bare 10 —
// every exact-value pin above already proves bit-identity at default.
// These pin the knob's contract itself. -----
#[test]
fn synaptic_input_divisor_defaults_to_ten_and_rejects_zero() {
let mut net =
SpikingNeuralNetwork::new(2, 1000, NetworkTopology::Random { connectivity: 0.0 })
.expect("constructs");
assert_eq!(net.synaptic_input_divisor(), 10, "the historical value");
assert_eq!(
net.set_synaptic_input_divisor(0),
Err(Error::DivisorOutOfRange)
);
net.set_synaptic_input_divisor(4).expect("set");
assert_eq!(net.synaptic_input_divisor(), 4);
}
#[test]
fn divisor_five_doubles_the_transmitted_pulse_centimv() {
// Same derivation as transmission_is_live_one_step_delayed_centimv,
// divisor 5 instead of the default 10: a +125-weight spike injects
// 125/5 = +25 pA; I-type centi integration:
// current_term = 25·100·100/1000 = 250 cV,
// delta_v = 100·250/1000 = 25 quanta ⇒ post −7000 → −6975 exactly
// one step after the pre spike. The knob moves the coupling,
// exactly and only.
let mut net = SpikingNeuralNetwork::new_with_voltage_resolution(
2,
1000,
NetworkTopology::Random { connectivity: 0.0 },
VoltageResolution::CentiMillivolt,
)
.expect("constructs");
net.build_topology().expect("empty build");
for n in &mut net.neurons {
n.noise_amplitude_pa = 0;
}
net.add_synapse(0, 1, 125).expect("edge");
net.finalize_synapses();
net.set_synaptic_input_divisor(5).expect("divisor 5");
let spikes = net.step(&[3000, 0]).expect("step 0");
assert_eq!(spikes.len(), 1, "pre fires on step 0");
assert_eq!(
net.neurons[1].membrane_potential, -7_000,
"post unmoved on the spike step itself — one-step delay"
);
net.step(&[0, 0]).expect("step 1");
assert_eq!(
net.neurons[1].membrane_potential, -6_975,
"post integrates a doubled pulse one step later (+25 quanta)"
);
}
#[test]
fn adaptation_decay_each_step_keeps_a_driven_net_alive() {
let mut net = SpikingNeuralNetwork::new_with_voltage_resolution(
2,
1000,
NetworkTopology::Random { connectivity: 0.0 },
VoltageResolution::Millivolt,
)
.expect("constructs");
net.build_topology().expect("empty build");
for n in &mut net.neurons {
n.noise_amplitude_pa = 0;
}
let (mut max_adaptation, mut late_spikes) = (0_i16, 0_usize);
for step in 0..6_000 {
let spikes = net.step(&[600, 0]).expect("step");
max_adaptation = max_adaptation.max(net.neurons[0].adaptation_current_pa);
if step >= 5_000 {
late_spikes += spikes.len();
}
}
assert!(
late_spikes > 0,
"a decay-less adaptation term silences the net forever; the live \
net must still fire late (got {late_spikes} late spikes)"
);
assert!(
max_adaptation < 500,
"adaptation must equilibrate under the 600 pA drive (peaked at {max_adaptation})"
);
}
#[test]
fn plasticity_off_freezes_weights_under_adapting_drive() {
// The R8 inventory's named gap: stuck-ON plasticity (the OFF
// toggle silently ignored) was invisible to CI. Falsifier: the
// identical drive that demonstrably moves the weight with
// plasticity ON must leave it byte-identical, with zero
// plasticity events, with it OFF.
let build = || {
let mut net = SpikingNeuralNetwork::new(
2,
1000,
NetworkTopology::Balanced {
excitatory_ratio: 0.5,
},
)
.expect("valid");
// deterministic constants: noise off, no refractory,
// tau=dt → ΔV = leak + (I−A)·R/1000 per step
for n in &mut net.neurons {
n.noise_amplitude_pa = 0;
n.refractory_period_us = 0;
n.tau_membrane_us = 1000;
n.resistance_mohm = 1000;
}
net.add_synapse(0, 1, 100).expect("synapse");
net.synapse_matrix.finalize();
net
};
// init cycle plasticity-OFF (the default) with both neurons
// firing (the harness recipe: makes last_spike times real), then
// one pre-only step → LTD pairing at dt = +1000 μs (inside the
// 20 ms window)
let init = |net: &mut SpikingNeuralNetwork| {
for _ in 0..4 {
net.step(&[600, 600]).expect("init step");
}
assert_eq!(
net.synapses[0].weight, 100,
"the OFF init cycle must not touch the weight"
);
};
#[cfg(feature = "unstable-stdp")]
{
let mut on = build();
init(&mut on);
on.set_plasticity_enabled(true);
let on_spikes = on.step(&[1000, 0]).expect("pairing step");
assert_eq!(
on_spikes.len(),
1,
"the pre neuron must fire the pairing step"
);
assert!(
on.synapses[0].weight < 100,
"ON leg adapts (post-leads LTD at dt=+1000): weight now {}",
on.synapses[0].weight
);
assert!(on.stats().plasticity_events > 0);
}
let mut off = build();
init(&mut off);
let off_spikes = off.step(&[1000, 0]).expect("pairing step");
assert_eq!(off_spikes.len(), 1, "spiking is plasticity-independent");
assert_eq!(
off.synapses[0].weight, 100,
"OFF must freeze the weight exactly (stuck-ON detector)"
);
#[cfg(feature = "unstable-stdp")]
assert_eq!(
off.stats().plasticity_events,
0,
"no plasticity events may accumulate while OFF"
);
}
#[test]
fn adaptation_decay_runs_before_integration_exact() {
// The R8 inventory's other named gap: the session-F step order
// (decay → integrate) was pinned at unit + liveness level only.
// Exact-value orchestration pin. Constants chosen so one step
// computes ΔV = 1 − A_effective:
// membrane −56, threshold −55 (SET — default is −50),
// resting −70 (leak −14),
// R = 1000 mΩ, tau = dt = 1000 μs, drive 15 pA
// → current_term = (15 − A)·1000/1000 = 15 − A
// → ΔV = 1000·(−14 + 15 − A)/1000 = 1 − A
// A_start = 1: decay-first → integrate sees 0 → ΔV = +1 →
// V = −55 → SPIKES (if decay ran after integrate, it would
// see 1 → ΔV = 0 → silent — the spike proves the position).
// A_start = 2: integrate sees exactly 1 → ΔV = 0 → silent
// (pins the effective adaptation at exactly A_start − 1).
let mut net1 = SpikingNeuralNetwork::new_with_voltage_resolution(
1,
1000,
NetworkTopology::Random { connectivity: 0.0 },
VoltageResolution::Millivolt,
)
.expect("constructs");
net1.build_topology().expect("empty build");
for n in &mut net1.neurons {
n.noise_amplitude_pa = 0;
n.refractory_period_us = 0;
n.tau_membrane_us = 1000;
n.resistance_mohm = 1000;
n.membrane_potential = -56;
n.threshold = -55;
}
net1.neurons[0].adaptation_current_pa = 1;
let spikes1 = net1.step(&[15]).expect("step A=1");
assert_eq!(
spikes1.len(),
1,
"decayed-to-0 adaptation must let V reach −55"
);
assert_eq!(
net1.neurons[0].membrane_potential, net1.neurons[0].reset_potential,
"spike resets to reset potential"
);
assert_eq!(
net1.neurons[0].adaptation_current_pa, 2,
"decay 1→0 then +2 on spike"
);
let mut net2 = SpikingNeuralNetwork::new_with_voltage_resolution(
1,
1000,
NetworkTopology::Random { connectivity: 0.0 },
VoltageResolution::Millivolt,
)
.expect("constructs");
net2.build_topology().expect("empty build");
for n in &mut net2.neurons {
n.noise_amplitude_pa = 0;
n.refractory_period_us = 0;
n.tau_membrane_us = 1000;
n.resistance_mohm = 1000;
n.membrane_potential = -56;
n.threshold = -55;
}
net2.neurons[0].adaptation_current_pa = 2;
let spikes2 = net2.step(&[15]).expect("step A=2");
assert_eq!(
spikes2.len(),
0,
"integrate must see exactly A_start − 1 = 1"
);
assert_eq!(net2.neurons[0].membrane_potential, -56, "ΔV = 0 exactly");
assert_eq!(
net2.neurons[0].adaptation_current_pa, 1,
"decay 2→1, no spike"
);
}
// ----- The membrane average: every neuron, in mV -----
/// Before its first step a network's stats read what `NetworkStats`
/// starts at, from either constructor: no spike, a rate of 0, and a
/// mean membrane of -70.0, as the field's doc says ("reads `-70.0`
/// until the first step"; the derived `Default` gave 0.0, and went).
#[test]
fn the_stats_read_rest_before_the_first_step() {
let built = SpikingNeuralNetwork::new(3, 1000, NetworkTopology::default()).expect("valid");
let neurons = (0..3)
.map(|id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
.collect();
let given = SpikingNeuralNetwork::from_neurons(neurons, 1000).expect("valid");
for net in [&built, &given] {
let s = net.stats();
assert_eq!(s.avg_membrane_potential_mv, -70.0);
assert_eq!(s.firing_rate_hz, 0.0);
assert_eq!(s.total_spikes, 0);
}
}
#[test]
fn membrane_average_reads_rest_after_a_step() {
// The mean over EVERY neuron reads the rest value at any n, not
// only at a multiple of 10. Noise off, zero input: the leak term
// and the current term are both 0, so −70 is exact by
// construction, not by truncation luck. After a step, because an
// unstepped network reads the −70.0 that `NetworkStats` starts
// at, whatever the body does.
for n in [5_u16, 15, 20, 100] {
let mut net =
SpikingNeuralNetwork::new(n, 1000, NetworkTopology::Random { connectivity: 0.0 })
.expect("constructs");
net.build_topology().expect("empty build");
for neuron in &mut net.neurons {
neuron.noise_amplitude_pa = 0;
}
let spikes = net.step(&[]).expect("step at zero input");
assert_eq!(spikes.len(), 0, "n = {n}: zero input fires nothing");
assert_eq!(
net.stats().avg_membrane_potential_mv,
-70.0,
"n = {n}: every neuron sits at rest"
);
}
}
#[test]
fn membrane_average_is_the_mean_of_all_neurons() {
// A ramp: each neuron carries a different potential, so a strided
// sample and the mean cannot agree by accident. The stride of 10
// reads indices 0 and 10 at both n below — with the RIGHT divisor
// that is −65.0 twice; the mean is −63.0 and −60.5. n = 20 is a
// multiple of 10, where the old divisor was "right": the stride
// is wrong there too.
for (n, want) in [(15_u16, -63.0_f64), (20, -60.5)] {
let mut net =
SpikingNeuralNetwork::new(n, 1000, NetworkTopology::Random { connectivity: 0.0 })
.expect("constructs");
net.build_topology().expect("empty build");
for (i, neuron) in net.neurons.iter_mut().enumerate() {
neuron.membrane_potential = -70 + (i as i16);
}
net.update_stats();
assert_eq!(
net.stats().avg_membrane_potential_mv,
want,
"n = {n}: the mean of −70 + i over all n"
);
}
}
#[test]
fn membrane_average_is_in_mv_on_the_centi_grid() {
// The stat is mV whatever the grid. Five neurons at −7_000 + 50·i
// quanta sum to −34_500 → −6_900 quanta → −69.0 mV. Nothing else
// pins the ÷scale: drop it and this reads −6900.0.
let mut net = SpikingNeuralNetwork::new_with_voltage_resolution(
5,
1000,
NetworkTopology::Random { connectivity: 0.0 },
VoltageResolution::CentiMillivolt,
)
.expect("constructs");
net.build_topology().expect("empty build");
for (i, neuron) in net.neurons.iter_mut().enumerate() {
neuron.membrane_potential = -7_000 + 50 * (i as i16);
}
net.update_stats();
assert_eq!(
net.stats().avg_membrane_potential_mv,
-69.0,
"centi-mV quanta must be reported in mV"
);
}
// ----- ISA round 70: a test for each network sentence no test held at
// 645afa8; each is run green there and red under its mutant. -----
/// `reset` brings every neuron back to rest, as its doc says: after a
/// driven run, every neuron reads at rest (`at_rest`, the six fields
/// `LIFNeuron::reset` writes).
#[test]
fn reset_brings_every_neuron_to_rest() {
let mut net =
SpikingNeuralNetwork::new(20, 1000, NetworkTopology::default()).expect("valid");
net.build_topology().expect("build");
for _ in 0..5 {
net.step(&[1000; 20]).expect("step");
}
assert!(
!net.neurons().iter().all(at_rest),
"the run must move a neuron, or the reset below proves nothing"
);
net.reset();
assert!(net.neurons().iter().all(at_rest));
}
/// `Balanced` wires as it did at `645afa8`, its four classes and two
/// builds in a row (the second goes on from the seed the first left):
/// the hash of every synapse, measured there. The default topology,
/// which `new`'s callers, the README and the visualizer build; no test
/// held its wiring.
#[test]
fn balanced_wires_as_it_did_at_the_pin() {
for (n, pins) in [
(
50,
[(416, 0x53d9_2eb0_e102_a144), (404, 0x4e41_80c5_d8a7_5623)],
),
(
128,
[(1069, 0xedd1_168e_1005_322b), (1073, 0x96c1_6dad_c070_6358)],
),
] {
let mut net =
SpikingNeuralNetwork::new(n, 1000, NetworkTopology::default()).expect("valid");
for (synapses, hash) in pins {
net.build_topology().expect("build");
assert_eq!(net.synapse_count(), synapses, "{n} neurons");
assert_eq!(wiring_hash(&net), hash, "{n} neurons");
}
}
}
/// `build_topology` keeps the runtime spike counter.
#[test]
fn a_rebuild_keeps_the_spike_count() {
let mut net =
SpikingNeuralNetwork::new(20, 1000, NetworkTopology::default()).expect("valid");
net.build_topology().expect("build");
for _ in 0..5 {
net.step(&[1000; 20]).expect("step");
}
let spikes = net.stats().total_spikes;
assert!(spikes > 0, "the run must spike, or the count kept is a 0");
net.build_topology().expect("rebuild");
assert_eq!(net.stats().total_spikes, spikes);
}
/// An entry of `input_currents` past the last neuron is ignored: a
/// longer slice steps as the slice cut to the network.
#[test]
fn an_input_past_the_last_neuron_is_ignored() {
let build = || {
let neurons = (0..2)
.map(|id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
.collect();
SpikingNeuralNetwork::from_neurons(neurons, 1000).expect("two neurons")
};
let (mut cut, mut long) = (build(), build());
let membranes = |net: &SpikingNeuralNetwork| {
net.neurons()
.iter()
.map(|n| n.membrane_potential)
.collect::<Vec<i16>>()
};
for _ in 0..20 {
let a = cut.step(&[600, 3000]).expect("step");
let b = long.step(&[600, 3000, i16::MAX, i16::MIN]).expect("step");
assert_eq!(a, b);
assert_eq!(membranes(&cut), membranes(&long));
}
}
/// The step delivers in id order, and within one `pre` in the CSR's
/// order, each add saturating in `i16`: from 0, +30,000 twice then
/// −30,000 is 2,767, where −30,000 first would end at 30,000
/// (`FixedNetwork::synapses`' example, on the std network).
#[test]
fn the_step_delivers_in_id_order_then_in_csr_order() {
// fires at every integrating step: rest, −70, is over −100
let firing = |id| {
LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt)
.with_threshold(-100)
};
let quiet = |id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt);
// across pres: 0 and 1 send +30,000, then 2 sends −30,000
let mut net = SpikingNeuralNetwork::from_neurons(
vec![firing(0), firing(1), firing(2), quiet(3)],
1000,
)
.expect("four neurons");
net.set_synaptic_input_divisor(1).expect("in 1 to 32,767");
net.add_synapse(2, 3, -30_000).expect("adds");
net.add_synapse(0, 3, 30_000).expect("adds");
net.add_synapse(1, 3, 30_000).expect("adds");
assert_eq!(net.step(&[0; 4]).expect("step 0").len(), 3);
assert_eq!(net.neurons()[3].synaptic_current_pa, 2_767, "id order");
// within one pre: +30,000 twice then −30,000, as added
let mut net = SpikingNeuralNetwork::from_neurons(vec![firing(0), quiet(1)], 1000)
.expect("two neurons");
net.set_synaptic_input_divisor(1).expect("in 1 to 32,767");
net.add_synapse(0, 1, 30_000).expect("adds");
net.add_synapse(0, 1, 30_000).expect("adds");
net.add_synapse(0, 1, -30_000).expect("adds");
assert_eq!(net.step(&[0; 2]).expect("step 0").len(), 1);
assert_eq!(
net.neurons()[1].synaptic_current_pa,
2_767,
"the CSR's order"
);
}
/// The clock saturates at `u64::MAX`, which no run reaches: the field
/// is written as `the_clock_runs_past_the_u32_ceiling` writes it.
#[test]
fn the_clock_saturates_at_the_u64_ceiling() {
let mut net =
SpikingNeuralNetwork::new(2, 1000, NetworkTopology::Random { connectivity: 0.0 })
.expect("constructs");
net.time_us = u64::MAX - 10;
net.step(&[0, 0]).expect("step");
assert_eq!(net.time_us(), u64::MAX);
}
/// `build_topology` on a `from_neurons` network discards the caller's
/// wiring and adds none: its stored marker is `Random` at 0.
#[test]
fn a_build_on_a_network_from_neurons_discards_its_wiring_and_adds_none() {
let neurons = (0..3)
.map(|id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt))
.collect();
let mut net = SpikingNeuralNetwork::from_neurons(neurons, 1000).expect("three neurons");
net.add_synapse(0, 1, 100).expect("adds");
net.add_synapse(1, 2, 100).expect("adds");
net.build_topology().expect("the marker builds");
assert_eq!(net.synapse_count(), 0);
}
// ----- ISA round 70: tests for the network.rs survivors of a mutation
// pass at 645afa8, each value measured there and each test run red
// under the survivors it answers. -----
/// `Feedforward` wires as it did at `645afa8` on layers past 8, where
/// a layer's fan-out is not 1. No test before this one read the wiring
/// of a layer past 8, and under 8 the fan-out, `max(next_size / 4, 1)`,
/// is 1, so the stride is never read.
#[test]
fn feedforward_wires_as_it_did_at_the_pin() {
let check = |layers: &'static [u16], synapses: u32, hash: u64| {
let n = layers.iter().sum();
let mut net =
SpikingNeuralNetwork::new(n, 1000, NetworkTopology::Feedforward { layers })
.expect("valid");
net.build_topology().expect("build");
assert_eq!(net.synapse_count(), synapses, "{layers:?}");
assert_eq!(wiring_hash(&net), hash, "{layers:?}");
};
check(&[10, 15, 5], 45, 0xe3a7_11a0_bbec_0fe7);
check(&[8, 16, 9], 64, 0xf179_ca2d_997d_60e3);
}
/// `SmallWorld` on two neurons wires the ring both ways.
#[test]
fn smallworld_wires_two_neurons_both_ways() {
let mut net = SpikingNeuralNetwork::new(
2,
1000,
NetworkTopology::SmallWorld {
local_connections: 1,
rewiring_prob: 0.0,
},
)
.expect("valid");
net.build_topology().expect("build");
let pairs: Vec<(u16, u16)> = net.synapses().iter().map(|s| (s.pre(), s.post())).collect();
assert_eq!(pairs, [(0, 1), (1, 0)]);
}
/// The stats of a network of one neuron are that neuron's: the mean
/// membrane is its membrane after the step.
#[test]
fn the_stats_of_one_neuron_are_its_own() {
let one = LIFNeuron::new(0, NeuronType::Excitatory, VoltageResolution::Millivolt);
let mut net = SpikingNeuralNetwork::from_neurons(vec![one], 1000).expect("one neuron");
net.step(&[600]).expect("step");
assert_eq!(net.neurons()[0].membrane_potential, -67);
assert_eq!(net.stats().avg_membrane_potential_mv, -67.0);
}
/// The firing rate is computed after every step, before a second of
/// model time too: one spike over two neurons in 10 ms is 50 Hz.
#[test]
fn the_firing_rate_reads_before_a_second() {
let quiet = |id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt);
let mut net =
SpikingNeuralNetwork::from_neurons(vec![quiet(0), quiet(1)], 1000).expect("two");
assert_eq!(
net.step(&[3000, 0]).expect("step 0").len(),
1,
"neuron 0 fires"
);
for _ in 1..10 {
assert!(net.step(&[0, 0]).expect("step").is_empty());
}
assert_eq!(net.stats().firing_rate_hz, 50.0);
}
/// STDP's instruments on a scripted run, two neurons and one synapse:
/// the post neuron fires alone first (its pre never fired, so no pair:
/// the `last_spike_time_us > 0` guard), then a co-fire (the same-step
/// tie-break, LTD), then pre-leads and post-leads pairs at 3, 8 and
/// 4, 1, 8 ms, a pre-leads pair at 15 ms, whose delta is +1, and a
/// post-leads and a pre-leads pair at 20 ms, both outside the window
/// (delta 0): the first counts an event and no pair, the second
/// neither. Every count, the weight and the raw sum, measured at
/// `645afa8`.
#[cfg(feature = "unstable-stdp")]
#[test]
fn the_stdp_instruments_count_a_scripted_run() {
let quiet = |id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt);
let mut net =
SpikingNeuralNetwork::from_neurons(vec![quiet(0), quiet(1)], 1000).expect("two");
net.add_synapse(0, 1, 100).expect("adds");
net.set_plasticity_enabled(true);
let plan: [(u32, [i16; 2]); 10] = [
(1, [0, 3000]),
(5, [3000, 6000]),
(9, [6000, 0]),
(12, [0, 6000]),
(17, [0, 6000]),
(18, [6000, 0]),
(25, [6000, 0]),
(40, [0, 6000]),
(60, [6000, 0]),
(80, [0, 6000]),
];
let mut fired = Vec::new();
for step in 0..85u32 {
let input = plan
.iter()
.find(|(s, _)| *s == step)
.map_or([0, 0], |(_, i)| *i);
for s in net.step(&input).expect("step") {
fired.push((step, s.neuron_id));
}
}
assert_eq!(
fired,
[
(1, 1),
(5, 0),
(5, 1),
(9, 0),
(12, 1),
(17, 1),
(18, 0),
(25, 0),
(40, 1),
(60, 0),
(80, 1)
],
"every planned spike, and no other"
);
let st = net.stats();
assert_eq!(
(
st.plasticity_events,
st.stdp_pairs_same_step,
st.stdp_pairs_post_leads,
st.stdp_pairs_pre_leads
),
(8, 1, 3, 3)
);
let s = &net.synapses()[0];
assert_eq!(
(s.weight(), s.raw_stdp_delta(), s.absorbed_delta()),
(91, -9, 0)
);
}
/// `stochastic_ternary_step` on a seeded stream: an on-grid synapse is
/// skipped and draws nothing; an excitatory one an LTD delta pushed
/// off `+γ` flips toward `−γ` and the clamp holds it at 0; two an LTP
/// delta pushed off `+γ` draw and stay. The return counts the one
/// flip, not the two that stayed, and every CSR slot mirrors its
/// synapse.
#[cfg(feature = "unstable-stdp")]
#[test]
fn a_stochastic_step_flips_clamps_counts_and_syncs() {
let quiet = |id| LIFNeuron::new(id, NeuronType::Excitatory, VoltageResolution::Millivolt);
let mut net = SpikingNeuralNetwork::from_neurons(vec![quiet(0), quiet(1), quiet(2)], 1000)
.expect("three");
net.add_synapse(0, 1, 125).expect("on grid");
net.add_synapse(1, 2, 122).expect("γ − 3: an LTD residual");
net.add_synapse(2, 0, 127).expect("γ + 2: an LTP residual");
net.add_synapse(0, 2, 126).expect("γ + 1: an LTP residual");
net.finalize_synapses();
net.ternary_flip_lfsr = 2; // the draws: 1, then 46,080, then 23,040
assert_eq!(net.stochastic_ternary_step(125), 1);
let weights: Vec<i16> = net.synapses().iter().map(|s| s.weight).collect();
assert_eq!(weights, [125, 0, 125, 125]);
// each CSR slot beside its synapse, as `ternary_writes_reach_their_csr_slot` reads them
let mut slots = Vec::new();
for pre in 0..net.neuron_count() {
for (_post, weight, idx) in net.synapse_matrix.connections(pre) {
slots.push((idx, weight, net.synapses[idx].weight));
}
}
assert_eq!(slots.len(), 4, "every slot read");
assert!(
slots.iter().all(|&(_, slot, synapse)| slot == synapse),
"{slots:?}"
);
}
// ----- ISA round 70: the csr.rs survivor that falls under
// `build_topology`'s doc; run green at 645afa8 and red under the
// survivor. -----
/// A second `build_topology` clears the CSR's state before it builds,
/// as its doc says: after a rebuild, each CSR slot names the synapse of
/// its own edge, so `ternarize_weights` writes each synapse's value
/// into its own slot. A stale index would land the writes on other
/// edges' slots, which a slot-against-its-index check cannot see (it
/// reads the index from the same table); the edge check can.
#[test]
fn a_rebuild_leaves_no_stale_csr_index() {
let mut net =
SpikingNeuralNetwork::new(20, 1000, NetworkTopology::Random { connectivity: 0.3 })
.expect("valid");
net.build_topology().expect("first build");
net.build_topology().expect("second build");
let _ = net.ternarize_weights();
let mut slots = Vec::new();
for pre in 0..net.neuron_count() {
for (post, weight, idx) in net.synapse_matrix.connections(pre) {
let s = &net.synapses[idx];
assert_eq!((s.pre(), s.post()), (pre, post), "slot of synapse {idx}");
slots.push((idx, weight, s.weight));
}
}
assert_eq!(slots.len(), net.synapses().len(), "every slot read");
assert!(
slots.iter().all(|&(_, slot, synapse)| slot == synapse),
"{slots:?}"
);
}
}