oat_rust 0.2.0

User-friendly tools for applied topology
Documentation
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
//! The filtered Clique complex (aka filtered Flag complex, filtered Vietoris-Rips complex); often constructed from a metric space or point cloud
//!
//! 
//! # Clique chain complex oracles
//! Mathematically, a filtered clique complex is determined by two pieces of data:
//! * a **dissimilarity matrix**
//!     * we represent this by a symmetric matrix *S* that has been flattened into a vector *v*
//! * a **threshold**  that determines where we stop growing the filtration
//!     * we represent this as a real number *t*
//! The boundary matrices of this chain complex oracle are indexed by `WeightedSimplex` objects which are
//! (essentially) pairs of form `(simplex, filtration_value)`.
//! 
//! Example:
//!     - construct a dissimilarity matrix
//!     - construct the associated clique complex
//!     - access a row + column of the boundary matrix
//!     - compute the dimension 1 barcode





use core::panic;
use std::collections::binary_heap::Iter;
use std::iter::Peekable;
use std::sync::Arc;

use std::hash::Hash;
use std::fmt::Debug;
use std::vec::IntoIter;

use derive_new::new;
use itertools::Itertools;
use num::iter::Range;
use num_traits::Bounded;
use ordered_float::OrderedFloat;
use sprs::vec;

use crate::algebra::chain_complexes::{ChainComplex, FilteredChainComplex};
use crate::algebra::vectors::operations::ChangeEntryType;
use crate::topology::simplicial::simplices::unweighted::{coboundary_entry_for_facet_vertex_pair, Simplex};
use crate::topology::simplicial::simplices::vector::insert_vertex;
use crate::topology::simplicial::simplices::weighted::{WeightedSimplex, OrderOperatorTwistWeightedSimplex};

use crate::algebra::vectors::entries::{KeyValGet, KeyValNew};


// use crate::matrix::{SmOracle, RingMetadata, MajorDimension};
// use crate::chx::{ChainComplex, ChxTransformKind};


use crate::algebra::matrices::operations::umatch::differential::DifferentialUmatch;
use crate::algebra::matrices::operations::MatrixOracleOperations;
use crate::algebra::matrices::query::{MatrixAlgebra, MatrixOracle};
use crate::algebra::rings::traits::DivisionRingOperations;
use crate::algebra::rings::traits::{RingOperations};

use crate::utilities::order::{ is_sorted_strictly, JudgeOrder, MakeNoneMaximum, OrderOperatorAuto, OrderOperatorByKey};
use crate::utilities::iterators::general::{minmax, symmetric_difference_of_ordered_iterators, TwoTypeIterator, IterWrappedArcVec, PeekUnqualified};
// use oat_rust::utilities::indexing_and_bijection::sparsevec_lookup;



// The specific type we use to store vertices
type Vertex = u16;
                                        










//  ===========================================================
//  FUNCTION TO EVALUATE DIAMETER
//  ===========================================================


/// Returns the filtration value of a simplex in the Vietoris-Rips complex, or `Err( vertices )`, if the input is invalid.
///
/// # Parameters
/// 
/// -`vertices`: vertices of the simplex
/// 
/// # Returns
/// 
/// - `Err( vertices.clone() )` if either
///   - `vertices` is not sorted in strictly ascending order, or
///   - the vietoris-rips complex does not contain the simplex, meaning that there exists a pair of vertices
///     `a, b` such that `dissimilarity_matrix.structural_nonzero_entry( &a, &b )` is `None`. 
///     **Note**  *we do not disallow dissimilarity matrices with missing diagonal entries*, so it is for `dissimilarity_matrix.structural_nonzero_entry( &a, &a )` to equal `None`.
///     In this case the function will return `Err( vertices.clone() )`.
/// 
/// - `Ok(DissimilarityMatrix::Coefficient::min_value())` if the vector `vertices` is empty; this is the minimum possible value that can be represented by an object of type  `DissimilarityMatrix::Coefficient`
/// - the maximum of the pairwise dissimilarities of the vertices in the simplex, otherwise.
///   If the simplex contains only one vertex `v`, then the value returned is `Ok(dissimilarity_matrix.structural_nonzero_entry( &v, &v ))`.
pub fn filtration_value_for_clique< DissimilarityMatrix >( 
        vertices:                       & Vec< Vertex >, 
        dissimilarity_matrix:           DissimilarityMatrix
    ) 
    -> Result< DissimilarityMatrix::Coefficient, Vec< Vertex >> 

    where
        DissimilarityMatrix:                MatrixOracle< ColumnIndex=usize, RowIndex=usize >,
        DissimilarityMatrix::Coefficient:   Debug + Ord + num_traits::Bounded,
{
    if ! is_sorted_strictly(&vertices, & OrderOperatorAuto) {
        return Err( vertices.clone() ); // vertices must be sorted in ascending order
    }
    let mut diam = DissimilarityMatrix::Coefficient::min_value();
    let mut a;
    let mut b;
    for ii in 0..vertices.len() {
        a = usize::from( vertices[ii] ); 
        for jj in ii .. vertices.len() {
            b = usize::from( vertices[jj] ); 
            match dissimilarity_matrix.structural_nonzero_entry( &a, &b ) {
                None => { return Err( vertices.clone() ) } // the simplex never enters the filtration
                Some( diam_bound ) => {
                    if diam_bound > diam { diam = diam_bound.clone(); }
                }
            }
        }
    }
    Ok(diam)
}   



//  ===========================================================
//  SORTED ENUMERATION OF CLIQUES
//  ===========================================================




/// A vector of simplices sorted first by dimension (ascending `0..dimension_max`, including `dimension_max`) 
/// then by diameter (descending) then by lexicographic order (descending)
/// 
/// If `allow_empty_simplex = True`, then the empty simplex (which has dimension -1) will be included.
pub fn filtered_cliques_in_row_reduction_order< DissimilarityMatrix >( 
            dimension_max:                  isize,
            dissimilarity_matrix:           DissimilarityMatrix,
            dissimilarity_matrix_size:      usize,   
            allow_empty_simplex:            bool         
        ) 
        ->  Vec< WeightedSimplex< DissimilarityMatrix::Coefficient > >  

    where   DissimilarityMatrix:                    Clone + MatrixOracle< ColumnIndex=usize, RowIndex=usize >,
            DissimilarityMatrix::Coefficient:       Ord + Debug + Bounded,
            DissimilarityMatrix::RowEntry:          KeyValNew,   // required for DiagonalEntryIterator to be an iterator    
            DissimilarityMatrix::Row:               Clone,   
        
    {
        let order_operator = OrderOperatorTwistWeightedSimplex{};
        let dissimilarity_matrix_ref = & dissimilarity_matrix;
        let vec: Vec<_> = (-1..dimension_max+1).flat_map(|dimension|
            {
                let mut vec =   AgileSimplexIteratorLexicographicOrder::new(                          
                                        dissimilarity_matrix_ref, 
                                        dissimilarity_matrix_size,                                      
                                        dimension, // dimension is an isize, but we need a usize here   
                                        allow_empty_simplex, // whether or not to include the empty simplex                 
                                    )
                                    .collect_vec();
                vec.sort_by(|x,y| order_operator.judge_cmp(y,x) );
                vec
            })
        .collect();
        vec
}









//  ===========================================================
//  FILTERED VIETORIS RIPS BOUNDARY MATRIX 
//  ===========================================================



/// The chain complex of a filtered Vietoris-Rips complex
/// 
/// This struct represents a filtered Vietoris-Rips complex, as well as its boundary matrix.
/// The coefficient ring is encoded in the `RingOperator` field.
/// 
/// # Internal structure
/// 
/// The `VietorisRipsComplex` struct contains the following fields:
/// - `ring_operator`: a ring operator for the coefficient ring
/// - `dissimilarity_matrix`: symmetric matrix (oracle) representing pairwise dissimilarity values
/// - `dissimilarity_matrix_size`: the number of rows/columns in the dissimilarity matrix; this is necessary because the matrix oracle traits are passive, and do not give a means to directly count or generate the number of row/column indices
/// - `filtration_ordered_neighbor_lists`: a vector of vectors `V`. For each vertex `i`, the vector
///    `V[i] = [ (f0,v0) .. (fn,vn) ]` contains a list of `(filtration, neighbor)` pairs for vertex `i`,
///    such that `filtration` is the filtration value of the edge `(i,neighbor)` in the underlying weighted graph.
///    The list `[ (f0,v0) .. (fn,vn) ]` is sorted by filtration value, with ties broken by lexicographic order of the vertices.
/// 
/// # Examples 
/// 
/// This example shows how to construct a [VietorisRipsComplex], and use it to compute persistent homology.
/// 
/// 
/// ```
/// use oat_rust::algebra::rings::types::native::{FieldRational64};    
/// use oat_rust::algebra::matrices::query::MatrixOracle;
/// use oat_rust::algebra::matrices::operations::umatch::differential::DifferentialUmatch;    
/// use oat_rust::algebra::matrices::types::third_party::IntoCSR;
/// use oat_rust::algebra::chain_complexes::barcode::get_barcode;
/// 
/// use oat_rust::topology::simplicial::from::graph_weighted::VietorisRipsComplex;        
/// use oat_rust::topology::point_cloud::unit_circle;            
/// 
/// use oat_rust::utilities::order::{ is_sorted_strictly, OrderOperatorByKeyCustom, OrderOperatorAuto, OrderOperatorAutoReverse}; 
/// use oat_rust::utilities::distances::{rowwise_distances};
/// 
/// 
/// use std::sync::Arc;
/// use itertools::Itertools;      
/// 
/// 
/// // Define a point cloud (points sampled from a unit circle)
/// //
/// // In this example we don't want any noise, but we can add noise
/// // to the circle by replacying None with Some(-1.0 .. 1.0); this will
/// // add noise uniformly sampled from [-1,1] to each x and y coordinate
/// 
/// let number_of_points = 5;
/// let pcloud = unit_circle( number_of_points, None);
/// 
/// // Get the distance matrix
/// 
/// let dissimilarity_matrix_data
///     = rowwise_distances(pcloud)
///         .into_iter()
///         .map(|x| x.into_iter().enumerate().collect_vec() )
///         .collect_vec()
///         .into_csr( number_of_points, number_of_points );
/// let dissimilarity_matrix = & dissimilarity_matrix_data;       
/// 
/// // Define the coefficient ring
/// 
/// let ring_operator = FieldRational64::new();
/// 
/// // Define the chain complex
/// 
/// let chain_complex_data = VietorisRipsComplex::new(
///     & dissimilarity_matrix,
///     number_of_points, ring_operator 
/// ).ok().unwrap();
/// let chain_complex = Arc::new(chain_complex_data);    
/// 
/// let dimension_max = 2;       
/// let row_index_vec = chain_complex.cliques_in_row_reduction_order(dimension_max); // runs over the row indices we want to use when computing the factorization
/// 
/// 
/// // Check that oracle has strictly sorted rows
/// 
/// for row_index in row_index_vec.iter() {        
///     assert!( is_sorted_strictly( 
///                                     & chain_complex.row(row_index).collect_vec() , // this line accesses a row 
///                                     & OrderOperatorByKeyCustom::new( OrderOperatorAuto ) 
///                                 ) );
/// }      
/// 
/// // Check that oracle has strictly sorted columns
/// 
/// 
/// for row_index in row_index_vec.iter() {
///     assert!( is_sorted_strictly(    & chain_complex.column_reverse(row_index).collect_vec() ,  // this line accesses a column
///                                     & OrderOperatorByKeyCustom::new( OrderOperatorAutoReverse::new() )  
///                                 ) );
/// }    
/// 
/// 
/// // Get a Umatch factorization
/// // --------------------------
/// 
/// let min_homology_dimension = 0;
/// let max_homology_dimension = 2;
/// let umatch = DifferentialUmatch::new(
///         chain_complex.clone(), 
///         min_homology_dimension,
///         max_homology_dimension,
///     );       
/// 
/// println!("Umatch factorization: {:#?}", &umatch);  
/// 
/// // Get the barcode
/// // ---------------
/// 
/// let return_cycle_representatives = true;
/// let return_bounding_chains = true;
/// let barcode =  get_barcode( 
///         &umatch, 
///         return_cycle_representatives,
///         return_bounding_chains,
///     );
///             
/// // Print the barcode in dimension 1
/// // --------------------------------
///             
/// let dimension = 1;
/// for (id,birth,death) in barcode.intervals_f64( dimension ) {
///     println!("Interval id {:?}:", id);
///     println!("    Dimension {:?}", dimension);
///     println!("    Birth:    {:?}", birth);
///     println!("    Death:    {:?}", death);
/// }
/// 
/// // This should print the following:
/// //
/// // Interval id 5:
/// //     Dimension 1
/// //     Birth:    1.1755705045849465
/// //     Death:    1.902113032590307
/// 
/// // Print the corresponding betti curve in dimension 1
/// // --------------------------------------------------
/// 
/// // The betti curve is formatted as a list of pairs (t0,b0) .. (tN, bN) such that
/// // the betti number for each half-closed interval [ti,ti+1) is bi.
/// 
/// println!(""); // new line
/// println!("Betti curve in dimension {:?}:", dimension);
/// for (t,b) in barcode.betti_curve(dimension) {
///     println!("    {:?} --> betti number {:?}", t.into_inner(), b);
/// }
/// 
/// // This should print the following:
/// //
/// // Betti curve in dimension 1:
/// //     1.1755705045849465 --> betti number 1
/// //     1.902113032590307 --> betti number 0        
/// 
/// 
/// // Print a cycle representative for the bar in dimension 1
/// // -------------------------------------------------------
/// //
/// // Note: calling `barcode.bar(5)` returns information abou the 5th
/// // bar in the barcode. We know that this is the bar we want, because
/// // the id number 5 appears in the barcode information printed above
/// 
/// let bar = barcode.bar(5);
/// println!(""); // new line
/// println!("Cycle representative for the bar in dimension 1:");
/// for entry in bar.cycle_representative().clone().unwrap() {
///     println!("    Simplex: {:?}", entry.0.vertices());
///     println!("       Filtration: {:?}", entry.0.filtration());            
///     println!("       Coefficient: {:?}", entry.1);            
/// }
/// 
/// // This should print the following
/// //
/// // Cycle representative for the bar in dimension 1:
/// //     Simplex: [3, 4]
/// //     Filtration: OrderedFloat(1.175570504584946)
/// //     Coefficient: Ratio { numer: -1, denom: 1 }
/// //     Simplex: [0, 1]
/// //     Filtration: OrderedFloat(1.1755705045849463)
/// //     Coefficient: Ratio { numer: -1, denom: 1 }
/// //     Simplex: [1, 2]
/// //     Filtration: OrderedFloat(1.1755705045849463)
/// //     Coefficient: Ratio { numer: -1, denom: 1 }
/// //     Simplex: [2, 3]
/// //     Filtration: OrderedFloat(1.1755705045849463)
/// //     Coefficient: Ratio { numer: -1, denom: 1 }
/// //     Simplex: [0, 4]
/// //     Filtration: OrderedFloat(1.1755705045849465)
/// //     Coefficient: Ratio { numer: 1, denom: 1 }
/// ```

#[derive(Clone,Debug,)]
pub struct VietorisRipsComplex< DissimilarityMatrix, RingOperator >
    where 
        DissimilarityMatrix:    MatrixOracle< ColumnIndex=usize, RowIndex=usize, >
{
    pub ring_operator:                              RingOperator, // ring meta data
	pub dissimilarity_matrix:                       DissimilarityMatrix,
    pub dissimilarity_matrix_size:                  usize,
    pub filtration_ordered_neighbor_lists:          Arc< Vec<  // one vec for every vertex in the whole Vietoris-Rips complex
                                                        Arc< Vec< (DissimilarityMatrix::Coefficient, Vertex) >
                                                    >>>,
    pub allow_empty_simplex:                        bool, // determines whether or not we include the emtpy simplex in the simplicial complex
}


/// Methods of VietorisRipsComplex struct
impl < DissimilarityMatrix, RingOperator  > 

    VietorisRipsComplex
        < DissimilarityMatrix, RingOperator > 

    where   DissimilarityMatrix:                MatrixOracle< ColumnIndex=usize, RowIndex=usize, >,
            DissimilarityMatrix::Coefficient:   Debug + Ord + num_traits::Bounded,
            RingOperator:                       RingOperations,
               
{

    /// Construct a (lazy) boundary matrix for the filtered VR complex of a symmetric matrix.
    /// - `dissimilarity_matrix` a symmetric matrix representing pairwise dissimilarity values
    /// - `dissimilarity_matrix_size` an integer representing the number of rows/columns of the dissimilarity matrix; this parameter is necessary because the matrix oracle traits are passive, and do not give a means to directly count or generate the number of row/column indices
    /// - `dissimilarity_value_max` maximum dissimilarity threshold
    /// - `dissimilarity_value_min` diameter of the empty simplex; this can be any number that is equal or less than every structural nonzero entry in the dissimilarity matrix
    /// - `ring_operator`: ring operator for the coefficient ring
    /// The filtration parameter of
    /// - the empty simplex `[]` is `dissimilarity_value_min`
    /// - a singletime `[i]` is `dissimilarity_matrix[i,i]`
    /// - an edge `[i,j]` is `dissimilarity_matrix[i,j]`
    /// - an arbitrary simplex `s` is the maximum of the filtration parameters of cardinality 0, 1, and 2 subsets of `s`
    /// subject to the condition that the filtration parameter of
    /// - a singleton `[i]` is undefined if `dissimilarity_matrix[i,i]` is structurally zero
    /// - an edge `[i,j]` is undefined if `dissimilarity_matrix[i,j]` is structurally zero
    /// - an arbitrary simplex `s` is undefined if the filtration parameter of any cardinality 0, 1, or 2 subset of `s` is undefined
    /// This means that some vertices may never enter the filtration.
    /// 
    /// # NB: Empty simplex
    /// 
    /// This constructor initializes the `allow_empty_simplex` field to `false`, meaning that the empty simplex is not included in the simplicial complex.
    /// However, for those who want to include the empty simplex, it is possible to set the `allow_empty_simplex` field to `true` after construction.
    /// 
    /// # Safety checks
    /// 
    /// The constructor checks that 
    /// - the input matrix is symmetric
    /// - the filtration parameter of every edge equals or exceeds the filtration parameter of its vertices.
    pub fn new(
            dissimilarity_matrix:               DissimilarityMatrix,
            dissimilarity_matrix_size:          usize,
            ring_operator:                      RingOperator,
        ) -> Result< Self, (usize,usize) >
    {

        let number_of_points = dissimilarity_matrix_size;

        // initialize the filtration ordered neighbor lists
        let mut filtration_ordered_neighbor_lists = Vec::with_capacity(number_of_points);

        // check that the dissimilarity matrix is symmetric
        for i in 0 .. number_of_points {

            // we will store the min filtration value of the row in this variable after iterating through the row
            let mut min_filtration = MakeNoneMaximum::from_opt(None); 
            
            // we will store the number of neighbors in this variable after iterating through the row
            let mut num_neighbors = 0;
            
            // iterate through the row
            for entry in dissimilarity_matrix.row( & i ) {   
                let n = entry.key(); 
                let f = entry.val(); 

                // update the min filtration
                min_filtration = min_filtration.min( MakeNoneMaximum::from_val(f.clone()) );   

                // increment the number of neighbors
                num_neighbors += 1;

                // check that the dissimilarity matrix has equal values for (i,j) and (j,i)         
                let entry_n_i = dissimilarity_matrix.structural_nonzero_entry( &n, &i );
                if Some( f.clone() ) != entry_n_i {
                    println!("\n\nError: The dissimilarity matrix passed to the `VietorisRipsComplex` constructor is not symmetric");
                    println!(" - Entry {:?} equals {:?}", (i,n) , f.clone() );
                    println!(" - However, entry {:?} equals {:?}.", (n,i), entry_n_i);
                    println!("\nThis message is generated by OAT.\n\n");                    
                    return Err( (i,n) );
                }
            }

            // check that the diagonal entry in row i is no greater than any other entry in the row
            let diagonal_entry = dissimilarity_matrix.structural_nonzero_entry( &i, &i );
            if min_filtration != MakeNoneMaximum::from_opt( diagonal_entry.clone() ) {
                println!("\n\nError during construction of the `VietorisRipsComplex`: Entry ({:?},{:?}) of the dissimilarity matrix is {:?} but the minimum structural nonzero entry in row {:?} is {:?}.  In this case `None` represents a value strictly greater than `Some(x)`, for every filtration value `x`. This indicates that input dissimilarity matrix is invalid.\nThis message is generated by OAT.\n\n",
                    i, 
                    i, 
                    diagonal_entry, 
                    i, 
                    min_filtration.into_inner() 
                );
                return Err( (i,i) );
            }

            // construct the filtration-ordered list of neighbors
            let mut filtration_ordered_neighbor_list = Vec::with_capacity(num_neighbors);
            for entry in dissimilarity_matrix.row( & i ) {   
                let neighbor = entry.key() as Vertex; 
                let filtration = entry.val(); 
                filtration_ordered_neighbor_list.push( (filtration, neighbor) );
            }
            // sort the list
            filtration_ordered_neighbor_list.sort();

            // push the list into our records, wrapping in Arc
            filtration_ordered_neighbor_lists.push(Arc::new(filtration_ordered_neighbor_list));
        }        

        Ok(
            VietorisRipsComplex { 
                ring_operator, 
                dissimilarity_matrix, 
                dissimilarity_matrix_size,
                filtration_ordered_neighbor_lists: Arc::new(filtration_ordered_neighbor_lists),
                allow_empty_simplex: false,
            }
        )

        
    }            




    /// Returns the diameter of a simplex
    ///
    /// # Parameters
    /// 
    /// -`vertices`: vertices of the simplex
    /// 
    /// # Returns
    /// 
    /// - `Err( vertices.clone() )` if either
    ///   - `vertices` is not sorted in strictly ascending order, or
    ///   - the vietoris-rips complex does not contain the simplex, meaning that there exists a pair of vertices
    ///     `a, b` such that `dissimilarity_matrix.structural_nonzero_entry( &a, &b )` is `None`. 
    ///     **Note**  *we do not disallow dissimilarity matrices with missing diagonal entries*, so it is for `dissimilarity_matrix.structural_nonzero_entry( &a, &a )` to equal `None`.
    ///     In this case the function will return `Err( vertices.clone() )`.
    /// 
    /// - `Ok(DissimilarityMatrix::Coefficient::min_value())` if the `vertices` is empty; this is the minimum possible value that can be represented by an object of type  `DissimilarityMatrix::Coefficient`
    /// - the maximum of the pairwise dissimilarities of the vertices in the simplex, otherwise.
    ///   If the simplex contains only one vertex `v`, then the value returned is `Ok(dissimilarity_matrix.structural_nonzero_entry( &v, &v ))`.
    pub fn filtration_value_for_clique( 
            & self, 
            vertices: & Vec< Vertex > 
        ) -> Result< DissimilarityMatrix::Coefficient, Vec< Vertex >> 
    {
        filtration_value_for_clique( vertices, self.dissimilarity_matrix_ref() )
    }    


    /// Add a filtration value to a simplex, returning a `WeightedSimplex` object
    /// 
    /// # Parameters
    /// 
    /// - `vertices`: vertices of the simplex
    /// 
    /// # Returns
    /// 
    /// - `Ok(WeightedSimplex)` if the filtration value is defined for the simplex
    /// - `Err( vertices.clone() )` if the filtration value is not defined for the simplex,
    ///    meanint that either the vertices are not sorted in strictly ascending order, or
    ///    the dissimilarity matrix lacks a value for one or more pairs of vertices
    pub fn add_filtration_value_to_simplex( &self, vertices: &Vec<Vertex> ) 
        -> Result<
                WeightedSimplex< DissimilarityMatrix::Coefficient >,
                Vec<Vertex>
            >
    {
        let filtration_value = self.filtration_value_for_clique( vertices )?;
        Ok(WeightedSimplex { vertices: vertices.clone(), weight: filtration_value })
    }


    /// Returns a reference to the internally stored symmetric dissimilarity matrix, wrapped in a struct that allows query operations to be performed.
    pub fn dissimilarity_matrix_ref(&self) -> & DissimilarityMatrix { & self.dissimilarity_matrix }

    /// Returns a reference to the internally stored symmetric dissimilarity matrix, wrapped in a struct that allows query operations to be performed.
    pub fn dissimilarity_matrix_size(&self) -> usize { self.dissimilarity_matrix_size }    

    /// Returns the dissimilarity value of two vertices, wrapped in a `MakeNoneMaximum` struct
    /// 
    /// The purpose of the `MakeNoneMaximum` struct is to "switch" the order of None values,
    /// so that they are regarded as strictly greater (rather than strictly less) than all `Some(x)` values.
    pub fn dissimilarity_as_nonegreater( &self, a: Vertex, b: Vertex ) -> MakeNoneMaximum<DissimilarityMatrix::Coefficient> 
        { MakeNoneMaximum { opt: self.dissimilarity_matrix.structural_nonzero_entry(& (a as usize), & (b as usize) ) } }

    /// The ring operator for the coefficient ring.
    pub fn ring_operator( &self ) -> RingOperator where RingOperator: Clone { self.ring_operator.clone() }

    /// A vector of simplices appearing in the order that rows are visited during row reduction of the boundary matrix for U-match factorization.
    /// 
    /// Simplices sorted first by dimension (ascending `0..dimension_max`, including `dimension_max`) 
    /// then by diameter (descending) then by lexicographic order (descending)
    pub fn cliques_in_row_reduction_order( &self, dimension_max: isize ) 
        -> 
        Vec< WeightedSimplex< DissimilarityMatrix::Coefficient > > 
        where 
            DissimilarityMatrix::RowEntry:      KeyValNew,   // required for DiagonalEntryIterator to be an iterator    
            DissimilarityMatrix::Row:           Clone,       // required for AgileSimplexIteratorLexicographicOrder to be an iterator   
    { 
        return filtered_cliques_in_row_reduction_order( 
            dimension_max,  
            self.dissimilarity_matrix_ref(), 
            self.dissimilarity_matrix_size,
            self.allow_empty_simplex, // determines whether or not we include the empty simplex in the simplicial complex
        )
    }    

    /// A vector of simplices sorted in the order imposed on the boundary matrix.
    /// 
    /// Simplices are sorted first by dimension (ascending `0..dimension_max`, including `dimension_max`),
    /// then by filtration value (ascending), then by lexicographic order (ascending).
    pub fn cliques_in_boundary_matrix_order_fixed_dimension( &self, dimension_max: isize ) 
        -> Vec< WeightedSimplex< DissimilarityMatrix::Coefficient > > 
        where 
            DissimilarityMatrix::RowEntry:      KeyValNew,   // required for DiagonalEntryIterator to be an iterator    
            DissimilarityMatrix::Row:           Clone,       // required for AgileSimplexIteratorLexicographicOrder to be an iterator    
    { 
        let mut simplices = self.cliques_in_lexicographic_order_fixed_dimension(dimension_max).collect_vec();
        simplices.sort_by( |x,y| OrderOperatorTwistWeightedSimplex{}.judge_cmp( x, y ) );
        simplices
    }

    /// An iterator that runs over simplices in ascending lexicographic order (not by filtration, etc.).
    pub fn cliques_in_lexicographic_order_fixed_dimension( &self, dimension: isize ) 
        -> AgileSimplexIteratorLexicographicOrder< & DissimilarityMatrix > 
        where 
            DissimilarityMatrix::RowEntry:      KeyValNew,   // required for DiagonalEntryIterator to be an iterator    
            DissimilarityMatrix::Row:           Clone,       // required for AgileSimplexIteratorLexicographicOrder to be an iterator    
    { 
        AgileSimplexIteratorLexicographicOrder::new(                          
            self.dissimilarity_matrix_ref(), // a simple trick to make a copy of the dissimilarity matrix that implements the Copy trait
            self.dissimilarity_matrix_size,                
            dimension,   
            self.allow_empty_simplex,                            
        )
    }        

    /// Returns a factorization of the boundary matrix restricted to simplices
    /// of dimension 0 .. dimension_max+1 (inclusive)
    /// 
    /// This factorization can be used to compute betti numbers, cycle representatives,
    /// and more.  See the documenation for `FactoredChainComplex`.
    pub fn factor_from_arc( self, max_homology_dimension: isize ) 
            ->
            DifferentialUmatch< 
                    Arc< VietorisRipsComplex< DissimilarityMatrix, RingOperator > >,                                     
                >    

        where
            RingOperator::Element:                  Debug + PartialEq, 
            RingOperator:                           Clone + DivisionRingOperations,
            DissimilarityMatrix:                    Clone + MatrixOracle< ColumnIndex=usize, RowIndex=usize, >,    
            DissimilarityMatrix::RowEntry:          KeyValNew,   // required for DiagonalEntryIterator to be an iterator               
            DissimilarityMatrix::Row:               Clone,       // required for AgileSimplexIteratorLexicographicOrder to be an iterator
            DissimilarityMatrix::Coefficient:       Copy + Clone + Debug + Ord + Hash + Bounded,             
    {
        let min_homology_dimension = 0;
        let arc = Arc::new(self);
        DifferentialUmatch::new(
            arc,
            min_homology_dimension,
            max_homology_dimension,
        )
    }



}




















//  ===========================================================
//  CHAIN COMPLEX TRAIT
//  ===========================================================




impl  < DissimilarityMatrix, RingOperator >

    ChainComplex for
    
    Arc< 
            VietorisRipsComplex
                < DissimilarityMatrix, RingOperator > 
        >    

    where
        DissimilarityMatrix:                        Clone + MatrixOracle< ColumnIndex=usize, RowIndex=usize >,     
        DissimilarityMatrix::Coefficient:           Copy + Debug + Ord + Bounded, 
        DissimilarityMatrix::RowEntry:              KeyValNew,   // required for DiagonalEntryIterator to be an iterator
        DissimilarityMatrix::Row:                   Clone,       // required for AgileSimplexIteratorLexicographicOrder to be an iterator
        RingOperator:                               Clone + RingOperations,
        RingOperator::Element:                      Debug + PartialEq,
{

    type BasisVectorIndicesIterable = Vec< WeightedSimplex< DissimilarityMatrix::Coefficient > >; 


    fn basis_vector_indices_for_dimension( &self, dimension: isize ) -> Self::BasisVectorIndicesIterable {
        self.cliques_in_boundary_matrix_order_fixed_dimension( dimension )
    }


    fn dimension_for_basis_vector_with_index( &self, index: & Self::RowIndex ) -> Result<isize, Self::RowIndex> {        

        match self.has_row_for_index( index ) {
            false => Err( index.clone() ), // if input is invalid return an error
            true => Ok( index.dimension() as isize ), // otherwise return the dimension of the simplex
        }
    }
}







//  ===========================================================
//  *FILTERED* CHAIN COMPLEX TRAIT
//  ===========================================================




impl  < DissimilarityMatrix, RingOperator >

    FilteredChainComplex for
    
    Arc< 
            VietorisRipsComplex
                < DissimilarityMatrix, RingOperator > 
        >    

    where
        DissimilarityMatrix:                        Clone + MatrixOracle< ColumnIndex=usize, RowIndex=usize >,     
        DissimilarityMatrix::Coefficient:           Copy + Debug + Ord + Bounded, 
        DissimilarityMatrix::RowEntry:              KeyValNew,   // required for DiagonalEntryIterator to be an iterator
        DissimilarityMatrix::Row:                   Clone,       // required for AgileSimplexIteratorLexicographicOrder to be an iterator
        RingOperator:                               Clone + RingOperations,
        RingOperator::Element:                      Debug + PartialEq,
{

    type FiltrationValue = DissimilarityMatrix::Coefficient; // the filtration value is the same as the dissimilarity value

    /// Returns the filtration value of the basis vector (i.e. simplex) with the given index.
    /// 
    /// This function returns `Ok(filtration_value)` if the input is a correctly formatted simplex in the Vietoris-Rips complex
    /// (with correctly calculated weight), and `Err(index.clone())` otherwise.
    fn filtration_value_for_basis_vector_with_index( 
            &self, 
            index: & Self::RowIndex 
        ) ->    
            Result<
                Self::FiltrationValue, 
                Self::RowIndex 
            > {
        
        match self.has_row_for_index( index ) {
            false => Err( index.clone() ), // if input is invalid return an error
            true => {
                Ok( index.filtration() )
            }            
        }
    }
}


















//  ===========================================================
//  FACET ITERATORS
//  ===========================================================



/// A iterator that runs over all entries in the boundary of a simplex, in ascending lexicographic order.
/// 
/// If the original simplex is `[0,1,2]`, it returns entries in the following order: `([0,1],1), ([0,2],-1), ([1,2],1)`.
/// 
/// # Example
/// 
/// ```
/// use oat_rust::topology::simplicial::from::graph_weighted::{AgileBoundaryIteratorLexicographicOrder, VietorisRipsComplex};
/// use oat_rust::topology::simplicial::simplices::weighted::WeightedSimplex;   
/// use oat_rust::algebra::matrices::types::vec_of_vec::sorted::VecOfVec;
/// use oat_rust::algebra::rings::types::native::FieldFloat64;
/// use ordered_float::OrderedFloat;
/// use std::sync::Arc;
///
/// // define the ring operator
/// let ring_operator = FieldFloat64::new();        
/// 
/// // define the dissimilarity matrix
/// // (this is a convenient way to build a VecOfVec from a "dense matrix")
/// let dissimilarity_matrix = VecOfVec::from_ragged(
///     & vec![
///         vec![OrderedFloat(0.0), OrderedFloat(1.0), OrderedFloat(2.0)],
///         vec![OrderedFloat(1.0), OrderedFloat(0.0), OrderedFloat(3.0)],
///         vec![OrderedFloat(2.0), OrderedFloat(3.0), OrderedFloat(0.0)],
///     ]
/// );
/// 
/// // define the Vietoris-Rips complex
/// let vietoris_rips_complex = Arc::new( 
///     VietorisRipsComplex::new(
///         & dissimilarity_matrix,
///         3, // dissimilarity_matrix_size
///         ring_operator,
///     ).ok().unwrap()
/// );
/// 
/// // define the simplex
/// let simplex = WeightedSimplex {
///     vertices: vec![0, 1, 2],
///     weight: OrderedFloat(2.0),
/// }; 
/// 
/// // create the iterator
/// let mut boundary = AgileBoundaryIteratorLexicographicOrder::new(
///     vietoris_rips_complex,
///     simplex,
///     false, // this indicates we don't consider the emtpy simplex to be a "real" simplex
/// );   
/// 
/// // check the results
/// assert!( 
///     boundary.eq(
///         vec![
///             ( WeightedSimplex { vertices: vec![0, 1], weight: OrderedFloat(1.0) },  1.0 ),
///             ( WeightedSimplex { vertices: vec![0, 2], weight: OrderedFloat(2.0) }, -1.0 ),
///             ( WeightedSimplex { vertices: vec![1, 2], weight: OrderedFloat(3.0) },  1.0 ),
///         ]
///     )         
/// );
/// ```
/// A iterator that runs over all entries in the boundary of a simplex, in **descending lexicographic order**
/// 
/// If the original simplex is `[0,1,2]`, it return entries in the following order: `([1,2],1), ([0,2],-1), ([0,1],1)`.
#[derive(Clone, Debug)]
pub struct AgileBoundaryIteratorLexicographicOrder
        < DissimilarityMatrix, RingOperator >
    where
        DissimilarityMatrix:                            MatrixOracle< ColumnIndex=usize, RowIndex=usize >,       
        RingOperator:                                   RingOperations, 
{
    pub vietoris_rips_complex: Arc< VietorisRipsComplex< DissimilarityMatrix, RingOperator > >,
	pub simplex: WeightedSimplex<DissimilarityMatrix::Coefficient>,
	pub removal_location_for_next_facet: Option<usize>,
    pub ring_operator: RingOperator,
}


impl< DissimilarityMatrix, RingOperator > 
    
    AgileBoundaryIteratorLexicographicOrder
        < DissimilarityMatrix, RingOperator >
    where // we impose all these conditions so that the VietorisRipsComplex will implement MatrixAlgebra, which lets us extract the coefficient ring
        DissimilarityMatrix::Coefficient:           Copy + Debug + Ord + Bounded,
        DissimilarityMatrix::RowEntry:              KeyValNew,   // required for DiagonalEntryIterator to be an iterator
        DissimilarityMatrix::Row:                   Clone,       // required for AgileSimplexIteratorLexicographicOrder to be an iterator 
        DissimilarityMatrix:                        Clone + MatrixOracle< ColumnIndex=usize, RowIndex=usize >,         
        RingOperator:                               Clone + RingOperations,
        RingOperator::Element:                      Debug + PartialEq,
{

    /// Create a new [AgileBoundaryIteratorLexicographicOrder]
    /// 
    ///  # Parameters
    /// 
    ///  - `vietoris_rips_complex`: an Arc-wrapped Vietoris-Rips complex
    ///  - `simplex`: a `WeightedSimplex` object representing the simplex for which the boundary is computed
    ///  - `allow_empty_simplex`: a boolean flag that indicates whether the iterator should include the 
    ///     empty simplex (of dimension -1) in the boundary of a singleton simplex.
    /// 
    /// # See also
    /// 
    /// The documentation for [AgileBoundaryIteratorLexicographicOrder] for more details on the iterator.
    pub fn new(
            vietoris_rips_complex: Arc< VietorisRipsComplex< DissimilarityMatrix, RingOperator > >,
            simplex: WeightedSimplex<DissimilarityMatrix::Coefficient>,
            allow_empty_simplex: bool,
        ) -> Self
    {
        // get the initial removal location for the next facet; this should be the last vertex in the simplex
        let removal_location_for_next_facet = match simplex.vertices.len() {
            0 => {
                // if the simplex is empty, there is no next vertex to remove
                None
            } 
            1 => {
                // if the simplex is a singleton, we can remove it to get the empty simplex, if that's allowed
                if allow_empty_simplex {
                    Some(0) 
                } else {
                    None 
                }
            } 
            _ => {
                Some(simplex.vertices.len() - 1)
            }
        };

        let ring_operator = vietoris_rips_complex.ring_operator();
        AgileBoundaryIteratorLexicographicOrder {
            vietoris_rips_complex,
            simplex,
            removal_location_for_next_facet,
            ring_operator,
        }
    }
}        




/// implement standard methods of Iterator for AgileBoundaryIteratorLexicographicOrder struct
impl< DissimilarityMatrix, RingOperator >

    Iterator for 
    
    AgileBoundaryIteratorLexicographicOrder
        < DissimilarityMatrix, RingOperator >
    where
        DissimilarityMatrix:                            MatrixOracle< 
                                                            ColumnIndex     =   usize, 
                                                            RowIndex        =   usize,
                                                            Coefficient:        Ord + Bounded,
                                                        >,   
        RingOperator:                                   RingOperations, 
{
	type Item =     (
                        WeightedSimplex
                            <DissimilarityMatrix::Coefficient>, 
                        RingOperator
                            ::Element
                    );

	fn next( &mut self ) -> Option<Self::Item> {

        // return None if there is no "next" vertex to delete; otherwise get a pointer
        // to the next vertex to delete
        let removal_location_for_next_facet = self.removal_location_for_next_facet?;
        
        // remove the vertex and compute the filtraiton and coefficient
        let mut simplex = self.simplex.clone();
        simplex.vertices.remove(removal_location_for_next_facet );
        simplex.weight = self.vietoris_rips_complex.filtration_value_for_clique(&simplex.vertices).unwrap();
        let coeff = self.ring_operator.minus_one_to_power( removal_location_for_next_facet );

        // update the removal location for the next facet
        match removal_location_for_next_facet {
            0 => { self.removal_location_for_next_facet = None; }
            _ => { self.removal_location_for_next_facet = Some(removal_location_for_next_facet - 1); }
        }

        // return the facet and coefficient
        Some((simplex, coeff))        
    }
}


//  ---------------------------------------------------------------------------
//  IMPLEMENT MATRIX ORACLE CLIQUE BOUNDARY MATRIX + DEFINE SOME SORTED (CO)BOUNDARY ITERATORS
//  ---------------------------------------------------------------------------



//  MATRIX ORACLE
//  ------------------------------------------






// Matrix Oracle
impl  < DissimilarityMatrix, RingOperator >

    MatrixOracle for
    
    Arc< 
            VietorisRipsComplex
                < DissimilarityMatrix, RingOperator > 
        >    

    where
        DissimilarityMatrix::Coefficient:           Copy + Debug + Ord + Bounded, 
        DissimilarityMatrix::RowEntry:              KeyValNew,   // required for DiagonalEntryIterator to be an iterator
        DissimilarityMatrix::Row:                   Clone,       // required for AgileSimplexIteratorLexicographicOrder to be an iterator
        RingOperator:                               Clone + RingOperations,
        RingOperator::Element:                      Debug + PartialEq,
        DissimilarityMatrix:                        Clone + MatrixOracle< ColumnIndex=usize, RowIndex=usize >, 
{   

    type Coefficient            =   RingOperator::Element;// The type of coefficient stored in each entry of the matrix    
    type RowIndex               =   WeightedSimplex<DissimilarityMatrix::Coefficient>;// The type key used to look up rows.  Matrices can have rows indexed by anything: integers, simplices, strings, etc.
    type RowEntry               =   ( Self::RowIndex, Self::Coefficient );// The type of entries in each row; these are essentially pairs of form `(column_index, coefficient)`
    type ColumnIndex            =   WeightedSimplex<DissimilarityMatrix::Coefficient>;// The type of column indices    
    type ColumnEntry            =   ( Self::RowIndex, Self::Coefficient );// The type of entries in each column; these are essentially pairs of form `(row_index, coefficient)`
    type Row                    =   AgileCoboundaryIteratorFiltrationOrder< DissimilarityMatrix, RingOperator >; // An iterator that runs over the entries in a row, sorted by filtration value (ascending) and then by lexicographic order (descending)
    type RowReverse             =   std::vec::IntoIter<(WeightedSimplex<DissimilarityMatrix::Coefficient>, RingOperator::Element)>; // What you get when you ask for a row with the order of entries reversed
    type Column                 =   std::vec::IntoIter<(WeightedSimplex<DissimilarityMatrix::Coefficient>, RingOperator::Element)>; // What you get when you ask for a column
    type ColumnReverse          =   std::vec::IntoIter<(WeightedSimplex<DissimilarityMatrix::Coefficient>, RingOperator::Element)>;
    
    fn row(                     &   self, row_index: & Self::RowIndex   )   -> Self::Row {
        self.row_result(row_index).ok().unwrap()
    }
    
    fn row_reverse(             &   self, index: & Self::RowIndex   )   -> Self::RowReverse {
        let mut row: Vec<_>     =   self.row( index ).collect();
        (&mut row).reverse();
        row.shrink_to_fit();
        return row.into_iter()
    }

    fn row_result(                 &   self, index: & Self::RowIndex   )   -> Result< Self::Row, Self::RowIndex > {
        let row_result =         AgileCoboundaryIteratorFiltrationOrder::new(
            index.vertices().clone(),
            self.dissimilarity_matrix.clone(),
            self.dissimilarity_matrix_size,
            self.filtration_ordered_neighbor_lists.clone(),
            self.ring_operator(),
        );
        match row_result {
            Ok(row) => Ok(row),
            Err(_) => {
                // if the row is not defined, we return an error
                Err(index.clone())
            }
        }
    }    
    
    fn column(                  &   self, index: & Self::ColumnIndex)   -> Self::Column {

        let cardinality = index.number_of_vertices();

        let iter = AgileBoundaryIteratorLexicographicOrder::new(
            self.clone(), // vietoris_rips_complex: 
            index.clone(), // simplex:  
            self.allow_empty_simplex, // the AgileBoundaryIteratorLexicographicOrder will be empty is this value is set to false (and self.allow_empty_simplex *IS* set to false by default)
        );        
        // initialize empty list
        let mut vec = Vec::with_capacity( cardinality );
        // fill with entries from the iterator
        vec.extend( iter );
        // sort
        vec.sort_by(|x,y| x.0.cmp(&y.0)); 
        // return as iterator
        vec.into_iter()
    }
    
    fn column_reverse(          &   self, index: & Self::ColumnIndex)   -> Self::ColumnReverse {
        let cardinality = index.number_of_vertices();
        let iter = AgileBoundaryIteratorLexicographicOrder::new(
            self.clone(), // vietoris_rips_complex: 
            index.clone(), // simplex: 
            self.allow_empty_simplex, // the AgileBoundaryIteratorLexicographicOrder will be empty is this value is set to false (and self.allow_empty_simplex *IS* set to false by default)
        );        
        // initialize empty list
        let mut vec = Vec::with_capacity( cardinality );
        // fill with entries from the iterator
        vec.extend( iter );
        // sort
        vec.sort_by(|x,y| y.0.cmp(&x.0)); // sort in REVERSE order
        // return as iterator
        vec.into_iter()
    }
    
    /// Returns `false` if any of the following conditions fails:
    /// - the list of vertices is sorted in strictly ascending order (in particular, it does not contain repeated entries)
    /// - every pair of vertices is adjacent in the underlying graph
    /// - the filtration value of `index` is the maximum of the weights of the edges (and the vertices) in `index`. 
    ///   In practice, the weights of the vertices come into play only in the special case where there are no
    ///   edges, i.e. when the simplex is a singleton.
    /// If all these conditions are satisfied, then the function returns `true`.
    fn has_row_for_index(     &   self, index: & Self::RowIndex   )   -> bool {

        match self.filtration_value_for_clique( index.vertices() ) {
            Err(_) => false, // if the filtration value is not defined, then the row does not exist
            Ok(filtration_value) => {
                filtration_value == index.weight
            }            
        }
    }
    
    fn has_column_for_index(  &   self, index: & Self::ColumnIndex)   -> bool {
        self.has_row_for_index( index )
    }
    
    fn structural_nonzero_entry(&   self, row:   & Self::RowIndex, column: & Self::ColumnIndex ) ->  Option< Self::Coefficient > {

        // both indices must be valid
        if !  self.has_row_for_index(row)  {
            panic!("Attempted to look up the entry in row {:?}, column {:?} of a Vietoris Rips boundary matrix, but {:?} is either an invalid simplex (not sorted or has a repeat entry) or it is not contained in the complex", row, column, row );
        }
        if !  self.has_column_for_index(row)  {
            panic!("Attempted to look up the entry in row {:?}, column {:?} of a Vietoris Rips boundary matrix, but {:?} is either an invalid simplex (not sorted or has a repeat entry) or it is not contained in the complex", row, column, column );
        }        

        // this criterion has to be satisfied to have a facet-cofacet pair
        if column.number_of_vertices() != row.number_of_vertices() + 1 { 
            return None 
        }

        // get the symmetric difference
        let mut symmetric_difference                        =   symmetric_difference_of_ordered_iterators( row.vertices.iter(), column.vertices.iter() );
        let first_different_vertex                      =   symmetric_difference.next(); 
        
        if symmetric_difference.next().is_some() {
            // in this case the row and column indices differ by more than one vertex, so they cannot be a facet-cofacet pair
            return None
        } 
                
        // if we make it to here then we do have a facet-cofacet pair, so we have to calculate the corresponding coefficient by finding 
        // which vertex in column is not contained in row, and then calculating the corresponding coefficient
        for (counter, vertex) in column.vertices.iter().enumerate() {
            if Some(vertex) == first_different_vertex {
                let coefficient         =   self.ring_operator.minus_one_to_power( counter );
                return Some( coefficient )
            }
        }    

        panic!("Something went wrong in the calculation of a structural nonzero");
    } 

} 









// Matrix Algebra
impl  < DissimilarityMatrix, RingOperator >

    MatrixAlgebra for
    
    Arc< 
            VietorisRipsComplex
                < DissimilarityMatrix, RingOperator > 
        >    

    where
        DissimilarityMatrix:                        Clone + MatrixOracle< ColumnIndex=usize, RowIndex=usize >,     
        DissimilarityMatrix::Coefficient:           Copy + Debug + Ord + Bounded, 
        DissimilarityMatrix::RowEntry:              KeyValNew,   // required for DiagonalEntryIterator to be an iterator
        DissimilarityMatrix::Row:                   Clone,       // required for AgileSimplexIteratorLexicographicOrder to be an iterator
        RingOperator:                               Clone + RingOperations,
        RingOperator::Element:                      Debug + PartialEq,
{
    type RingOperator                                   =   RingOperator;

    type OrderOperatorForRowEntries                     =   OrderOperatorByKey;

    type OrderOperatorForRowIndices                     =   OrderOperatorAuto;

    type OrderOperatorForColumnEntries                  =   OrderOperatorByKey;

    type OrderOperatorForColumnIndices                  =   OrderOperatorAuto;

    fn ring_operator( &self ) -> Self::RingOperator {
        self.ring_operator.clone()
    }

    fn order_operator_for_row_entries( &self ) -> Self::OrderOperatorForRowEntries {
        OrderOperatorByKey::new()
    }

    fn order_operator_for_row_indices( &self ) -> Self::OrderOperatorForRowIndices {
        OrderOperatorAuto::new()
    }

    fn order_operator_for_column_entries( &self ) -> Self::OrderOperatorForColumnEntries {
        OrderOperatorByKey::new()
    }

    fn order_operator_for_column_indices( &self ) -> Self::OrderOperatorForColumnIndices {
        OrderOperatorAuto::new()
    }
}









//  Matrix Oracle Operations
//  ------------------------------------------


impl < DissimilarityMatrix, RingOperator >

    MatrixOracleOperations for
    
    Arc< 
        VietorisRipsComplex
            < DissimilarityMatrix, RingOperator > 
    >    

    where
        DissimilarityMatrix:                        Clone + MatrixOracle< ColumnIndex=usize, RowIndex=usize >,     
        DissimilarityMatrix::Coefficient:           Copy + Debug + Ord + Bounded, 
        DissimilarityMatrix::RowEntry:              KeyValNew,   // required for DiagonalEntryIterator to be an iterator
        DissimilarityMatrix::Row:                   Clone,       // required for AgileSimplexIteratorLexicographicOrder to be an iterator
        RingOperator:                               Clone + RingOperations,
        RingOperator::Element:                      Debug + PartialEq,    

{
    fn bottom_entry_for_column( &self, column_index: &<Arc<VietorisRipsComplex<DissimilarityMatrix, RingOperator>> as crate::algebra::matrices::query::MatrixOracle>::ColumnIndex ) 
        -> Option< 
                <Arc<VietorisRipsComplex<DissimilarityMatrix, RingOperator>> as MatrixOracle>::ColumnEntry
        > {

        let order_operator = self.order_operator_for_column_entries();
        let iter = AgileBoundaryIteratorLexicographicOrder::new(
            self.clone(),
            column_index.clone(),
            false, // don't allow the empty simplex to be returned as a boundary
        );
        return iter.max_by(|x, y| order_operator.judge_cmp( &x, &y ) );
    }

}






//  ===========================================================================
//  SMALL COFACET ITERATOR
//  ===========================================================================





/// Iterates over all vertices which can be added to a facet to form a cofacet of equal filtration value
/// 
/// Internally, this iterator essentially works by intersecting the set of all neighborhoods of the vertices
/// in the facet.
#[derive(Clone,PartialEq)]
pub struct SmallCofacetVertexIterator< DissimilarityMatrix >
    where
        DissimilarityMatrix:                    MatrixOracle< ColumnIndex=usize, RowIndex=usize >,
        DissimilarityMatrix::Coefficient:       Ord + Debug + Bounded,
        DissimilarityMatrix::RowEntry:          KeyValNew,   // required for DiagonalEntryIterator to be an iterator
{
    pub proveably_exhausted:                    bool,
    pub neighbor_iterators:                     Vec< DissimilarityMatrix::Row >, 
    pub facet:                                  Arc< Vec< Vertex > >,
    pub facet_filtration:                       DissimilarityMatrix::Coefficient,
}


impl < DissimilarityMatrix > 

    SmallCofacetVertexIterator
        < DissimilarityMatrix >

    where
        DissimilarityMatrix:                    MatrixOracle< ColumnIndex=usize, RowIndex=usize >,
        DissimilarityMatrix::Coefficient:       Ord + Debug + Bounded,
        DissimilarityMatrix::RowEntry:          KeyValNew,   // required for DiagonalEntryIterator to be an iterator        
{


    /// Constructs a new `SmallCofacetVertexIterator` iterator.
    /// 
    /// # Parameters
    /// 
    /// - `dissimilarity_matrix`: a symmetric matrix representing pairwise dissimilarity values
    /// - `dissimilarity_matrix_size`: an integer representing the number of rows/columns of the dissimilarity matrix; this parameter is necessary because the matrix oracle traits are passive, and do not give a means to directly count or generate the number of row/column indices
    /// - `facet`: a vector of vertices that form the facet
    /// - `facet_filtration`: the filtration value of the facet, which is the maximum of the filtration values of all vertices in the facet
    /// 
    /// # Returns
    /// 
    /// A new `SmallCofacetVertexIterator` iterator that can be used to iterate over all vertices which can be added to the facet to form a cofacet of equal filtration value (all other vertices are skipped).
    /// 
    /// # Note
    /// 
    /// We do not that the inputs are valid, i.e. that
    /// - the facet is sorted in strictly ascending order
    /// - the user-provided filtration is correct
    /// - all vertices in the facet are adjacent
    pub fn new(
            dissimilarity_matrix: DissimilarityMatrix,
            facet: Arc< Vec< Vertex > >,
            facet_filtration: DissimilarityMatrix::Coefficient,
        ) -> Self 
    {

        // we haven't checked any vertices yet, so we ONLY mark the iterator as proveably exhausted if the facet is empty
        // (if it is, then by convention SmallCofacetVertexIterator should act as an empty iterator)
        let proveably_exhausted =  facet.is_empty();


        // collect the neighbor iterartors
        let mut neighbor_iterators = Vec::with_capacity(facet.len());
        for vertex in facet.iter() {
            let row = dissimilarity_matrix.row(& (*vertex as usize ) );
            neighbor_iterators.push(row);
        }

        SmallCofacetVertexIterator {
            proveably_exhausted,
            neighbor_iterators,
            facet,
            facet_filtration,
        }
    }


    /// Reurns the lexicographically smallest vertex that lies within distance `self.facet_filtration` of vertex `self.facet[k]`
    pub fn next_plausible_candidate_for_kth_facet_vertex( &mut self, k: usize )
        -> Option< Vertex >
    {   
        let neighbor_iterator = &mut self.neighbor_iterators[k];
        while let Some(entry) = neighbor_iterator.next() {                    

            let neighbor = entry.key() as Vertex;
            let filtration = entry.val();

            // check that the neighbor is not already in the facet
            if self.facet.contains(&neighbor) {
                continue; // if the neighbor is already in the facet, we skip it
            }

            // if the neighbor equals candidate but filtration is greater than the facet, we skip this neighbor and seek a new candidate
            if filtration > self.facet_filtration { 
                continue
            } else {
                return Some( neighbor );
            }

        }     
        return None;   
    }
}




impl < DissimilarityMatrix >

    Iterator for 

    SmallCofacetVertexIterator
        < DissimilarityMatrix >

    where
        DissimilarityMatrix:                    MatrixOracle< ColumnIndex=usize, RowIndex=usize >,
        DissimilarityMatrix::Coefficient:       Ord + Debug + Bounded,
        DissimilarityMatrix::RowEntry:          KeyValNew,   // required for DiagonalEntryIterator to be an iterator        
{
    type Item = Vertex;

    fn next( &mut self ) -> Option<Self::Item> {

        if self.proveably_exhausted {
            return None; // if we are exhausted, we return None
        }

        // NB: 

        let mut candidate_neighbor: u16                       = self.next_plausible_candidate_for_kth_facet_vertex( 0 )?;
        let mut number_of_facet_vertices_checked            = 1;
        let mut next_facet_vertex_to_check: usize           = 0 % self.facet.len(); // we will increment this variable in the first phase of the outer loop
        
        'outer_loop: loop {               

            // if we have checked all vertices then the candidate is valid; return it
            if number_of_facet_vertices_checked == self.facet.len() {
                return Some( candidate_neighbor );
            }

            // otherwise get a pointer to the next vertex to check
            // we do this by incrementing the vertex to check by 1, modulo the number of vertices in the facet
            next_facet_vertex_to_check += 1;
            next_facet_vertex_to_check %= self.facet.len();    

            while let Some( neighbor ) = self.next_plausible_candidate_for_kth_facet_vertex( next_facet_vertex_to_check ) {
                if neighbor < candidate_neighbor {
                    // in this case neighbor can't be a cofacet vertex, since candidate_neighbor is the lowest possible number, so move on
                    continue 
                }
                if neighbor > candidate_neighbor {
                    // in this case candidate_neighbor is not viable; neighbor is the new lowest-possible value candidate value
                    candidate_neighbor = neighbor;
                    number_of_facet_vertices_checked = 1; // reset the number of facet vertices checked
                    continue 'outer_loop;
                } 
                // if we make it here, then neighbor == candidate_neighbor, candidate_neighbor is sufficiently close
                // to vertex `next_vertex_to_check`
                // therefore we can increment the number of facet vertices checked, and move on to the next facet vertex
                number_of_facet_vertices_checked += 1;
                continue 'outer_loop;
            }

            // if we make it here then next_facet_vertex_to_check has no more viable neighbors, so no more cofacet vertices remain to be found
            self.proveably_exhausted = true;
            return None;
        }
    }
}












//  ===========================================================================
//  DIAGONAL ENTRY ITERATOR  -- ordered lexicographically
//  ===========================================================================







/// Runs over all structural nonzero diagonal entries in a dissimilarity matrix
/// 
/// Items returned have type `Option< DissimilarityMatrix::RowEntry >`
#[derive(Clone,Debug,PartialEq, Eq)]
pub struct DiagonalEntryIterator< DissimilarityMatrix >
    where   DissimilarityMatrix:                    MatrixOracle< ColumnIndex=usize, RowIndex=usize >,
            DissimilarityMatrix::Coefficient:       Ord + Debug + Bounded,
{
    pub row_number_iterator:        std::ops::Range<usize>,
    pub dissimilarity_matrix:       DissimilarityMatrix,    
}



impl < DissimilarityMatrix >

    DiagonalEntryIterator
        < DissimilarityMatrix > 

    where   DissimilarityMatrix:                    MatrixOracle< ColumnIndex=usize, RowIndex=usize >,
            DissimilarityMatrix::Coefficient:       Ord + Debug + Bounded,
{
    pub fn new( dissimilarity_matrix: DissimilarityMatrix, size: usize ) -> Self {
        DiagonalEntryIterator {
            row_number_iterator: 0..size,
            dissimilarity_matrix,
        }
    }
}




impl < DissimilarityMatrix >

    Iterator for

    DiagonalEntryIterator
        < DissimilarityMatrix > 

    where   DissimilarityMatrix:                    MatrixOracle< ColumnIndex=usize, RowIndex=usize >,
            DissimilarityMatrix::Coefficient:       Ord + Debug + Bounded,
            DissimilarityMatrix::RowEntry:          KeyValNew,
{
    type Item =  DissimilarityMatrix::RowEntry;

    fn next( &mut self ) -> Option<Self::Item> {        
        while let Some(row_number) = self.row_number_iterator.next() {
            match self.dissimilarity_matrix.structural_nonzero_entry( & row_number, & row_number ) {
                None => continue, // skip to the next row if this one has no entry
                Some(coefficient) => {
                    return Some( 
                        DissimilarityMatrix::RowEntry::new( row_number, coefficient ) 
                    );
                }
            }
        }
        return None;        
    }
}












//  ===========================================================================
//  SIMPLEX ITERATOR  -- ordered lexicographically
//  ===========================================================================










/// An iterator that runs over all simplices of given dimension in a clique complex, in **ascending lexicographic order**.
/// 
/// # How it works
/// 
/// Internally, this object stores a list of iterators, a list of filtration values, and a list of vertices.
/// The structure is as shown in the following example:
/// 
/// ```text
/// 
/// Iterators       =   [ D   I1  I2  I3  I4  I5 ]
/// Vertices        =   [ V0  V1  V2  V3  V4     ]
/// Filtrations     =   [ F0  F1  F2  F3  F4     ]
/// ```
/// 
/// Here `D` is an iterator that runs over all pairs `(v,f)` such that `dissimilarity_matrix[v,v]=f` is
/// a structural nonzero entry in the dissimilarity matrix. The iterator runs over vertices in
/// lexicographic order. The value `f` is the filtration value of the vertex.
/// 
/// The each iterator `I1, I2, ..` is a (partially expended) copy of row `V0` of the dissimilarity matrix.
/// 
/// For each `k`
/// - the sequence `[V0, V1, ..., Vk]` is a valid simplex of dimension `k`, in the Vietoris-Rips complex
/// - the filtration value of this simplex is `fk`
/// 
/// **The number of iterators always exceeds the number of vertices (respectively, filtrations) by one.**
/// 
/// When the function `self.next()` is called, this object will pass through the following stages.
/// 
/// **(A)** Begin drawing elements `(V,F)` from the last iterator in `Iterators`.
/// Here `V` is a neighbor of `V0` and `F` is the filtration value of the simplex `[V0, V]`. 
/// 
/// **(A1)** If `[V0 .. V4 V]` is a valid simplex with filtration value `K`, then ..
/// 
/// - If `5 = self.dimension`, then the simplex `[V0, V1, V2, V3, V4, V]` is returned, and the process
///   terminates until the next call to `self.next()`.
/// 
/// - If `5 < self.dimension`, then we push V to the end of the list of vertice and F to the end of the list of filtrations.
///   We then make an identical copy of I5, and push it to the end of the list of iterators. Thus the structure becomes
///  as follows:
/// 
/// ```text
/// Iterators       =   [ D   I1  I2  I3  I4  I5  I6 ]
/// Vertices        =   [ V0  V1  V2  V3  V4  V5     ]
/// Filtrations     =   [ F0  F1  F2  F3  F4  F5     ]
/// ``` 
/// Then we return to step (A) and continue drawing elements from the last iterator `I6`.
/// 
/// **(A2)** If `[V0 .. V4 V]` is **not** a valid simplex, then we continue drawing elements from the last iterator `I6`
/// until we find a valid simplex (in which case we proceed with (A1)), or until the iterator is exhausted. 
/// 
/// **(A3)** If iterator `I5` is exhausted then we remove `I5`, `V4`, and `F4` from their respective lists.
/// Thus the structure becomes:   
///   
/// ```text
/// Iterators       =   [ D   I1  I2  I3  I4 ]
/// Vertices        =   [ V0  V1  V2  V3     ]
/// Filtrations     =   [ F0  F1  F2  F3     ]  
/// ```
/// 
/// We then begin fresh with step (A).
/// 
/// **(B)** Once we exhaust iterator `D`, the process terminates. At this point we have generated all simplices of
/// dimension `self.dimension`
/// 
/// 
/// 
/// 
/// 
/// # Examples
/// 
/// ```
/// use oat_rust::algebra::matrices::types::third_party::IntoCSR;
/// use oat_rust::algebra::matrices::types::vec_of_vec::sorted::VecOfVec;   
/// use oat_rust::algebra::rings::types::native::FieldRationalSize;     
/// use oat_rust::topology::simplicial::simplices::weighted::WeightedSimplex;
/// use oat_rust::topology::simplicial::from::graph_weighted::VietorisRipsComplex;
/// use std::sync::Arc;   
/// use itertools::Itertools;                   
/// 
/// let number_of_points = 10;
/// let maxdim = 2;       
/// 
/// // initialize a random dissimilarity matrix
/// let dissimilarity_matrix_vecvec = VecOfVec::random_symmetric_zero_diagonal_with_enclosing_radius_threshold(number_of_points);
/// let dissimilarity_matrix =  Arc::new( dissimilarity_matrix_vecvec.into_csr(number_of_points, number_of_points) );                
/// 
/// // create the Vietoris-Rips complex
/// let ring_operator = FieldRationalSize::new();
/// let vietoris_rips_complex_data = VietorisRipsComplex::new( dissimilarity_matrix, number_of_points, ring_operator ).ok().unwrap();
/// let vietoris_rips_complex = Arc::new(vietoris_rips_complex_data);        
/// 
/// // generate simplices using the agile iterator
/// let mut simplices_agile = vietoris_rips_complex.cliques_in_row_reduction_order(maxdim);
/// simplices_agile.sort();
/// 
/// // generate simplices using a brute-force approach
/// let mut simplices_brute_force = Vec::new();
/// for dimension in 0 .. maxdim as usize + 1 {
///     for combination in (0..number_of_points as u16).combinations(dimension+1) {
///         if let Ok( filtration ) = vietoris_rips_complex.filtration_value_for_clique(&combination) {
///             simplices_brute_force.push(WeightedSimplex {
///                 vertices: combination,
///                 weight: filtration,
///             });
///         }
///     }
/// }
/// simplices_brute_force.sort();        
/// 
/// // verify that both generation methods align
/// assert!(
///     simplices_agile.eq( & simplices_brute_force ),
///     "The agile simplex enumeration does not match the brute-force enumeration"
/// );
/// ```
/// 
/// An empty iterator:
/// 
/// ```
/// use sprs::CsMatBase;
/// use ordered_float::OrderedFloat;
/// use oat_rust::topology::simplicial::from::graph_weighted::AgileSimplexIteratorLexicographicOrder;
/// use oat_rust::topology::simplicial::simplices::weighted::WeightedSimplex;
/// 
/// 
/// let dissimilarity_matrix = CsMatBase::new( (2,2), vec![0,1,2], vec![0,1], vec![OrderedFloat(0.0),OrderedFloat(0.0)] );
///     
/// let simplices: Vec<_>    =   AgileSimplexIteratorLexicographicOrder::new( 
///                                  & dissimilarity_matrix, 
///                                  2,          //  matrix size
///                                  1,          //  dimension
///                                  false,      //  do not include the empty simplex (this only applies when dimension is -1)
///                              ).collect();
/// let empty_list           =   Vec::< WeightedSimplex<OrderedFloat<f64>> >::new();
///             
/// assert!( empty_list.eq( &simplices ) ) 
/// ```
#[derive(Clone,Debug)]
pub struct AgileSimplexIteratorLexicographicOrder< DissimilarityMatrix > 
    
    where   DissimilarityMatrix:                    MatrixOracle< ColumnIndex=usize, RowIndex=usize >,
            DissimilarityMatrix::Coefficient:       Ord + Debug + Bounded,
            DissimilarityMatrix::RowEntry:          KeyValNew,            // apparently to be inside an itertwotype we require an object to be an iterator; and DiagonalEntryIterator is only an iterator if DissimilarityMatrix::RowEntry implements KeyValNew              
{
    pub dissimilarity_matrix:       DissimilarityMatrix,
    pub neighbor_iterators:         Vec< 
                                        TwoTypeIterator<
                                            DiagonalEntryIterator< DissimilarityMatrix >,
                                            DissimilarityMatrix::Row,
                                        >
                                    >,
    pub face_filtrations:           Vec< DissimilarityMatrix::Coefficient >, // the filtration values of the simplices we are building
    pub vertices:                   Vec<Vertex>, // the vertices of the simplex we are building
    pub dimension:                  isize,
}

impl < DissimilarityMatrix >

    AgileSimplexIteratorLexicographicOrder
        < DissimilarityMatrix > 

    where   DissimilarityMatrix:                    Clone + MatrixOracle< ColumnIndex=usize, RowIndex=usize >,
            DissimilarityMatrix::Coefficient:       Ord + Debug + Bounded,
            DissimilarityMatrix::RowEntry:          KeyValNew,                        
    {

    /// Creates a new AgileSimplexIteratorLexicographicOrder object that runs over all simplices of given dimension in a clique complex
    /// 
    /// # Arguments
    /// 
    /// * `dissimilarity_matrix` - a dissimilarity matrix that defines the clique complex; it must be indexed by `usize` and have a `Coefficient` type that implements `Ord + Debug + Bounded`
    /// * `dissimilarity_matrix_size` - the number of rows and columns of the dissimilarity matrix
    /// * `dimension` - the dimension of simplices to iterate over; must be a non-negative integer
    /// 
    /// # Returns
    /// 
    /// A new AgileSimplexIteratorLexicographicOrder object that runs over all simplices of given dimension in a clique complex
    /// 
    /// # Initialization
    /// 
    /// See the documentation of the AgileSimplexIteratorLexicographicOrder struct on internal structure.  We initialize the relevant lists as follows:
    /// ```text
    /// Iterators       =   [ D   ]
    /// Vertices        =   [     ]
    /// Filtrations     =   [     ]  
    /// ```
    pub fn new( 
            dissimilarity_matrix:           DissimilarityMatrix,
            dissimilarity_matrix_size:      usize, // the size of the dissimilarity matrix
            dimension:                      isize,
            allow_empty_simplex:            bool,
        ) 
        -> 
        Self 
        where
            DissimilarityMatrix:                            MatrixOracle< ColumnIndex=usize, RowIndex=usize >
    {      

        // if the dimension is negative, initialize all internal data as empty, with one caveat
        if dimension < 0 {
            let neighborhood_iterators = Vec::with_capacity(0);
            let face_filtrations = Vec::with_capacity(0);
            // if dimension is -1 (corresponding to the empty simplex), then we add one unit of capacity to vertices as a flag;
            // the first time we call `next()` on the iterator, we will return an empty simplex with minimum filtration value, 
            // then reduce capacity to zero
            let mut vertices= match dimension {
                -1 => Vec::with_capacity(1), 
                _ => Vec::with_capacity(0), 
            };
            // if directed to exclude the empty clique, then we reset the flag from the previous step
            if ! allow_empty_simplex {
                vertices = Vec::with_capacity(0); 
            }
            return AgileSimplexIteratorLexicographicOrder {
                dimension,
                dissimilarity_matrix,
                neighbor_iterators: neighborhood_iterators,
                face_filtrations,
                vertices,
            };
        }

        // in this case dimension is non-negative, so we can convert to usize for convenience
        let dimension = dimension as usize;

        // runs over vertices and their filtration values
        let diagonal_entry_iterator         =   TwoTypeIterator::Version1(
                                                    DiagonalEntryIterator::new( dissimilarity_matrix.clone(), dissimilarity_matrix_size )
                                                );
        let mut neighbor_iterators          =   Vec::with_capacity( dimension + 1 );
        neighbor_iterators.push( diagonal_entry_iterator ); // the first neighbor iterator is the diagonal entry iterator, which runs over all vertices and their filtration values

        let face_filtrations            =   Vec::with_capacity(dimension+1); 

        let vertices                    =   Vec::with_capacity(dimension+1);


        AgileSimplexIteratorLexicographicOrder {
            dimension: dimension as isize, 
            dissimilarity_matrix,
            neighbor_iterators,
            face_filtrations,
            vertices,
        }
    }




    // Returns `Some(n-1)` if `self.neighbor_iterators` has length `n > 0`, otherwise returns `None`.
    pub fn last_neighborhood_ordinal( &self ) -> Option<usize> {
        match self.neighbor_iterators.len() {
            0 => None, // if there are no neighbor iterators, we are done
            n => Some( n - 1 ), // otherwise return the ordinal of the last neighbor iterator
        }
    }

}







impl< DissimilarityMatrix > 

    Iterator for 
    
    AgileSimplexIteratorLexicographicOrder
        < DissimilarityMatrix > 
        
    where   DissimilarityMatrix:                    Clone + MatrixOracle< ColumnIndex=usize, RowIndex=usize >,
            DissimilarityMatrix::Coefficient:       Ord + Debug + Bounded,
            DissimilarityMatrix::RowEntry:          KeyValNew,   // required for DiagonalEntryIterator to be an iterator    
            DissimilarityMatrix::Row:               Clone,   
{
    type Item = WeightedSimplex<DissimilarityMatrix::Coefficient>;


    /// This implementation requires `DissimilarityMatrix` to implement Clone, because we want to be able to clone
    /// an `TwoTypeIterator< DiagonalEntryIterator, DissimilarityMatrix::Row >` object, and the `DiagonalEntryIterator` requires
    /// `DissimilarityMatrix` to implement `Clone` in order to be able to clone itself.
    /// 
    /// In practice this hasn't been a problem, since we usually use an `Arc<T>` or `& T` for our dissimilarity matrix.
    fn next(&mut self) -> Option<Self::Item> {



        // first handle some the edge cases where dimension < 0
        if self.dimension < 0 {
            if self.vertices.capacity() == 0 {
                // we use self.vertices.capacity() as a flag to indicate that, even if we do count the empty simplex as a simplex of dimension -1, we have already returned it
                return None;
            } else {
                if self.vertices.len() > 0 {
                    panic!("AgileSimplexIteratorLexicographicOrder::next() called on a simplex iterator with dimension < 0, but the vertices list is not empty. This indicates that the simplex iterator was not properly initialized. This error message originates in the oat_rust::topology::simplicial::from::graph_weighted module, in the AgileSimplexIteratorLexicographicOrder struct.");
                }
                self.vertices.shrink_to(0); 
                return  Some( WeightedSimplex { 
                            vertices: self.vertices.clone(), 
                            weight: DissimilarityMatrix::Coefficient::min_value(), 
                        } );
            }
        }



        'outer_loop: loop {

            
            // if ZERO neighborhoods are stored in memory, then there are no more neighbors to check, so there are no more simplices to return, and the iterator is exhausted
            let last_neighborhood_ordinal                =   self.last_neighborhood_ordinal()?; 


            // this while-loop scans through elements of last_neighbor_iterator
            'search_within_neighborhood: while let Some(entry) = ( &mut self.neighbor_iterators[last_neighborhood_ordinal] ).next() { // get the next entry from the last neighbor iterator
                let v = entry.key(); // get the vertex of the next neighbor
                let mut f = entry.val(); // get the filtration value of the next neighbor

                // update f to be at least as large as the filtration value of the simplex we are building
                // if the last_ordinal is 0 there's no prior filtration to compare
                // if the last_ordinal is 1 then the only prior filtration to compare is the filtration of vertex 0, which is
                // is no greater than f since f is the filtration parameter of an edge incident to vertex 0
                // thus we only update f if the last_ordinal is greater than 1
                if last_neighborhood_ordinal > 1 { 
                    // update the filtration value to be at least as large as the previous filtration value
                    // recall that the previous filtration value is stored int he slot ONE TO THE LEFT of the last neighborhood ordinal
                    f = f.max(self.face_filtrations[last_neighborhood_ordinal-1].clone()); 
                }


                // update the filtration to equal the maximum of the distances to the other vertices in the facet
                // !! NB: we can skip the first vertex, because the original value of f was the distance from that vertex to the new vertex v
                if last_neighborhood_ordinal > 0 {
                    for vertex in self.vertices[1..last_neighborhood_ordinal].iter().cloned().map(|x| x as usize) {
                        match self.dissimilarity_matrix.structural_nonzero_entry( &vertex, &v) {
                            Some(dissimilarity) => {
                                f = f.max(dissimilarity); // update the filtration value to be at least as large as the dissimilarity value
                            },
                            None => { 
                                continue 'search_within_neighborhood; // this vertex can't be added; continue scanning for the next neighbor in the neighborhood
                            }
                        }
                    }
                }


                // if we make it hear then we have checked that v is adjacent to every vertex in self.vertices, so we can add it to create a valid simplex in the VR complex
                // NP: no matter what happens in the following match statement, we will exit the ambient while-loop
                match last_neighborhood_ordinal == self.dimension as usize  {
                    true => { 
                        // the new simplex has dimension self.dimension
                        let mut vertices = self.vertices.clone();
                        vertices.push(v as u16);

                        return Some( WeightedSimplex { vertices, weight: f, } );

                    } false => { 
                        // the new siplex has sub-full dimension
                        //
                        // in this case we record the new vertex and filtration
                        self.vertices.push(v as u16); // add the new vertex to the simplex                        
                        self.face_filtrations.push(f); // update the filtration value of the simplex

                        // we also push a new neighbor iterator to our list
                        match last_neighborhood_ordinal == 0 {
                            // if the current list of iterators only includes the diagonal entry iterator, grab the neighors of the first vertex
                            true => {
                                let mut new_neighbor_iterator = self.dissimilarity_matrix.row( &v ); // get the iterator for the new vertex
                                // remove all entries for vertices that come before v
                                while let Some(entry) = new_neighbor_iterator.next() { 
                                    if entry.key() == v { break }
                                }
                                // now we can push the new neighbor iterator to the list of iterators
                                self.neighbor_iterators.push( 
                                    TwoTypeIterator::Version2(
                                        new_neighbor_iterator
                                    )
                                ); 
                            } false => { // otherwise just clone the last neighbor iterator; it will start in the right place, since it just returned vertex v
                                self.neighbor_iterators.push( 
                                    self.neighbor_iterators[last_neighborhood_ordinal].clone()
                                ); 
                            }
                        }

                        // now we can keep scanning for the next vertex to add
                        continue 'outer_loop; 

                    }                    
                }
            }
            // at this point our neighbor iterator is exhausted and we haven't found a new vertex to add
            // so first we have to step back in the search tree:
            self.neighbor_iterators.pop(); 
            self.face_filtrations.pop();
            self.vertices.pop(); 
            // now we can re-start the outer loop           

        }

    }

}












//  ===========================================================================
//  EDGE IDENTIFIER ITERATOR  -- for cofacets ordered by filtration
//  ===========================================================================

/// Iterates over the "big cofacet edge identifiers" of a facet in a Vietoris-Rips complex.
/// 
/// 
/// A **big cofacet** is a cofacet with filtration strictly greater than the given facet.
/// The **edge identifier** for a big cofacet is the unique edge whose length equals
/// the filtration of the cofacet, and which is lexicographically smallest
/// among all edges with that property.
/// There is a 1-1 correspondence between big cofacets and edge identifiers.
/// 
/// We can impose a total order on edge identifiers by
/// 
/// (1) mapping each edge identifier to the ordered pair `(filtration, vertex)` where `vertex` is the vertex that is not in the facet,
/// and `filtration` is the filtration value of the edge identifier (equivalently, of the associated cofacet), 
/// (2) ordering these pairs lexcicographically
/// 
/// This order corresponds exactly to the order we impose on cofacets (first by filtraiton, with ties broken by lexicographic order of vertices).
/// 
/// **This iterator returns edge identifiers in for big cofacets, in the order described.**
#[derive(Clone,Debug,PartialEq, Eq)]
pub struct BigCofacetEdgeIterator
        < DissimilarityMatrix >

    where
        DissimilarityMatrix:                MatrixOracle< ColumnIndex=usize, RowIndex=usize >,        
{
    facet_filtration:                       DissimilarityMatrix::Coefficient,
    facet:                                  Arc<Vec< Vertex >>,
    filtration_ordered_neighborhood_lists:  Vec<
                                                    IterWrappedArcVec<
                                                    (
                                                        DissimilarityMatrix::Coefficient, 
                                                        Vertex,
                                                    )
                                                >
                                            >,
    dissimilarity_matrix:                   DissimilarityMatrix,
    cofacet_edge_identifiers:               Vec< MakeNoneMaximum<(DissimilarityMatrix::Coefficient, Vertex)> >,
}


impl < DissimilarityMatrix >   

    BigCofacetEdgeIterator
        < DissimilarityMatrix >
    where
        DissimilarityMatrix:                MatrixOracle< ColumnIndex=usize, RowIndex=usize >,        
        DissimilarityMatrix::Coefficient:   Ord + Copy,
{


    fn new( 
        facet:                                              Arc<Vec<Vertex>>,
        dissimilarity_matrix:                               DissimilarityMatrix,
        facet_filtration:                                   DissimilarityMatrix::Coefficient,
        all_ambient_filtration_ordered_neighborhood_lists:  Arc< Vec<  // one vec for every vertex in the whole Vietoris-Rips complex
                                                                Arc< Vec< (DissimilarityMatrix::Coefficient, Vertex) >
                                                            >>>, 
    ) -> Self {

        let facet_cardinality = facet.len();
        
        // look up the neighborhood iterators for each vertex in the facet, and place them all in a vector
        // (recall these iterators run over (filtration, neighbor) pairs in filtration order, which in this case coincides with lexicographic order)
        let mut neighbor_lists_filtration_order = Vec::with_capacity( facet_cardinality );
        for v in facet.iter() {
            neighbor_lists_filtration_order.push(
                IterWrappedArcVec::new(
                    all_ambient_filtration_ordered_neighborhood_lists[ *v as usize ].clone()
                )                
            );
        }

        // initialize the iterator
        let mut initialized_cofacet_iterator = BigCofacetEdgeIterator {
            facet_filtration: facet_filtration,
            facet,
            filtration_ordered_neighborhood_lists: neighbor_lists_filtration_order,
            dissimilarity_matrix,
            cofacet_edge_identifiers: Vec::new(),
        };


        // find the first valid cofacet edge identifier for each vertex in the facet
        let mut cofacet_edge_identifiers: Vec<_> = Vec::with_capacity( facet_cardinality );
        for k in 0 .. facet_cardinality {
            cofacet_edge_identifiers.push(
                MakeNoneMaximum::from_opt(
                    initialized_cofacet_iterator
                        .find_next_identifier_for_the_kth_vertex( k )
                )
            );
        }

        // insert these identifiers into the initialized object
        initialized_cofacet_iterator.cofacet_edge_identifiers = cofacet_edge_identifiers;

        return initialized_cofacet_iterator;
    }


    /// The number of vertices in the facet
    fn facet_cardinality( &self ) -> usize {
        self.facet.len()
    }

    /// The dimension of the facet
    fn facet_dimension( &self ) -> isize {
        ( self.facet.len() as isize ) - 1
    }    



    /// Checks if a given edge is a valid cofacet identifier for the facet
    /// 
    /// Specifically, the edge must be longer than the facet filtration, 
    /// and it must be farther from the vertex vk than any other vertex in the facet.
    /// If it is equidistant to vk and any other vertex vj in the facet,
    /// then it is valid only if k < j.
    fn edge_is_a_valid_cofacet_identifier( 
        &self, 
        k: usize, 
        neighbor_of_vk: Vertex, 
        distance_vk_to_neighbor_of_vk: DissimilarityMatrix::Coefficient,
    ) -> bool {

        // only edges strictly longer than the facet filtration are valid cofacet identifiers
        if distance_vk_to_neighbor_of_vk <= self.facet_filtration { 
            return false; 
        }        

        // check that the edge is farther from vk than any other vertex in the facet
        for ( facet_vertex_ordinal, facet_vertex ) in self.facet.iter().enumerate() {

            // if neighbor_of_vk is already in the facet, then we can't add it to form a cofacet
            if *facet_vertex == neighbor_of_vk { 
                continue; 
            }

            // check the filtration value
            if facet_vertex_ordinal == k { continue }   // in this case we've already done the relevant check for vk, so we skip it
            match self.dissimilarity_matrix.structural_nonzero_entry( 
                & ( neighbor_of_vk as usize), 
                &( * facet_vertex as usize ) 
            ) {
                // case 1: facet_vertex is not adjacent to neighbor_of_vk, so we exclude neighbor_of_vk
                None => {
                    return false;                                        
                }
                // case 2: facet_vertex is adjacent to neighbor_of_vk
                Some(f) => {
                    match f.cmp(&distance_vk_to_neighbor_of_vk) {
                        // if neighbor_of_vk is strictly closer to facet_vertex than to vk, then we don't discard neighbor_of_vk
                        std::cmp::Ordering::Less => {
                            continue
                        }
                        // if neighbor_of_vk is strictly closer to vk than to facet_vertex, then we discard neighbor_of_vk
                        std::cmp::Ordering::Greater => {
                            return false;                                        
                        }          
                        // if there is a tie, we give ownership of neighbor_of_vk to the facet vertex with the lowest index                          
                        std::cmp::Ordering::Equal => {
                            if facet_vertex_ordinal < k {
                                return false;
                            } else {
                                continue
                            }
                        }
                    }
                }
            }
        }
        // if we make it to here, then the edge is a valid cofacet identifier
        return true
    }




    fn find_next_identifier_for_the_kth_vertex( &mut self, facet_vertex_ordinal:usize ) -> Option< (DissimilarityMatrix::Coefficient, Vertex) >{

        // ordinarily we could do a standard find operation to pull out the next valid edge,
        // but rust doesn't like certain borrow conflicts, so we do it by hand
        let mut replacement_identifier: Option< (DissimilarityMatrix::Coefficient, Vertex) >;
        loop {
            replacement_identifier  =   self.filtration_ordered_neighborhood_lists[facet_vertex_ordinal].next();
            // if the next candidate is Some, then we check if it is a valid replacement identifier
            if let Some(  (f, v) ) = replacement_identifier {
                if  self.edge_is_a_valid_cofacet_identifier(
                        facet_vertex_ordinal, 
                        v, 
                        f
                    )                 
                {
                    break;
                // otherwise we keep looking for a valid replacement identifier                    
                } else {
                    continue; 
                }
            // if there are replacement_identifier is None, then we are out of candidates!
            } else {
                break;
            }
        }       
        replacement_identifier 
    }

}





impl < DissimilarityMatrix >  

    Iterator for

    BigCofacetEdgeIterator
        < DissimilarityMatrix >
    where
        DissimilarityMatrix:                MatrixOracle< ColumnIndex=usize, RowIndex=usize >,        
        DissimilarityMatrix::Coefficient:   Ord + Copy,
{
    type Item = (DissimilarityMatrix::Coefficient, Vertex);

    fn next(&mut self) -> Option<Self::Item> {

        // find the next valid cofacet identifier
        let (facet_vertex_ordinal, _next_identifier_ref)    =   self.cofacet_edge_identifiers
                                                        .iter()
                                                        .enumerate()
                                                        .min_by_key( 
                                                            |(_facet_vertex_ordinal, identifier)| {
                                                                // we use the filtration as the primary key, and the vertex number as the secondary key
                                                                **identifier
                                                            }
                                                        )?;
        let replacement_identifier =    MakeNoneMaximum::from_opt(
            self.find_next_identifier_for_the_kth_vertex( 
                facet_vertex_ordinal 
            )
        );
        
        // pull out the selected identifier, and replace it with its successor
        let selected_identifier =   std::mem::replace(
                                        &mut self.cofacet_edge_identifiers[facet_vertex_ordinal], // element we pull from the vector
                                        replacement_identifier                                     // element we put in the vector
                                    );
        
        return selected_identifier.into_inner()
        
    }
}        











//  ===========================================================================
//  COBOUNDARY ITERATOR ----   FILTRATION ORDER
//  ===========================================================================









/// Iterates over all `(WeightedSimplex, RingOperator::Element)` pairs in the coboundary
/// of a simplex, in **filtration order** (with ties broken by lexicographic order of vertices).
/// 
/// # Internal structure
/// 
/// Stores Option<S> and Option<T>, where S and T are iterators that run over vertices which can be added to
/// form valid cofacets.  S runs over vertices for "small cofacet vertices" (those with filtration equal to the facet filtration),
/// and T runs over vertices for "big cofacet edge identifiers" (those with filtration strictly greater than the facet filtration).
///
/// Both Option<S> and Option<T> are initialized as `None`, since there is a small startup cost to initializing them,
/// and in many applications not all entries are needed.
/// 
/// # Example
/// 
/// ```
/// use oat_rust::topology::simplicial::from::graph_weighted::{AgileBoundaryIteratorLexicographicOrder, AgileCoboundaryIteratorFiltrationOrder, VietorisRipsComplex};
/// use oat_rust::topology::simplicial::simplices::weighted::WeightedSimplex;   
/// use oat_rust::algebra::matrices::types::vec_of_vec::sorted::VecOfVec;
/// use oat_rust::algebra::matrices::query::MatrixOracle;
/// use oat_rust::algebra::rings::types::native::FieldFloat64;
/// use ordered_float::OrderedFloat;
/// use std::sync::Arc;
/// 
/// // define the ring operator
/// let ring_operator = FieldFloat64::new();        
/// 
/// // define the dissimilarity matrix
/// // (this is a convenient way to build a VecOfVec from a "dense matrix")
/// let dissimilarity_matrix = VecOfVec::from_ragged(
///     & vec![
///         vec![OrderedFloat(0.0), OrderedFloat(1.0), OrderedFloat(2.0), OrderedFloat(3.0)],
///         vec![OrderedFloat(1.0), OrderedFloat(0.0), OrderedFloat(1.0), OrderedFloat(2.0)],
///         vec![OrderedFloat(2.0), OrderedFloat(1.0), OrderedFloat(0.0), OrderedFloat(1.0)],
///         vec![OrderedFloat(3.0), OrderedFloat(2.0), OrderedFloat(1.0), OrderedFloat(1.0)],                
///     ]
/// );
/// 
/// // define the Vietoris-Rips complex
/// let vietoris_rips_complex = Arc::new( 
///     VietorisRipsComplex::new(
///         & dissimilarity_matrix,
///         3, // dissimilarity_matrix_size
///         ring_operator,
///     ).ok().unwrap()
/// );
/// 
/// // Check a boundary iterator
/// // ---------------------------------------------------------------
/// 
/// // define the simplex
/// let simplex = WeightedSimplex {
///     vertices: vec![0, 1, 2],
///     weight: OrderedFloat(2.0),
/// };         
/// 
/// // create the iterator
/// let boundary = AgileBoundaryIteratorLexicographicOrder::new(
///     vietoris_rips_complex.clone(),
///     simplex,
///     false, // this indicates we don't consider the emtpy simplex to be a "real" simplex
/// );   
/// 
/// // check the results
/// assert!( 
///     boundary.eq(
///         vec![
///             ( WeightedSimplex { vertices: vec![0, 1], weight: OrderedFloat(1.0) },  1.0 ),
///             ( WeightedSimplex { vertices: vec![0, 2], weight: OrderedFloat(2.0) }, -1.0 ),
///             ( WeightedSimplex { vertices: vec![1, 2], weight: OrderedFloat(1.0) },  1.0 ),
///         ]
///     )         
/// );
/// 
/// // Check a coboundary iterator
/// // ---------------------------------------------------------------   
/// 
/// // Here we use the constructor from the Vietoris-Rips complex, which is more convenient  
/// 
/// // define the simplex
/// let simplex = WeightedSimplex {
///     vertices: vec![0, 2],
///     weight: OrderedFloat(2.0),
/// };  
/// 
/// // create the iterator
/// let coboundary = vietoris_rips_complex.row( & simplex );
/// 
/// // check the results
/// assert!( 
///     coboundary.eq(
///         vec![
///             ( WeightedSimplex { vertices: vec![0, 1, 2], weight: OrderedFloat(2.0) },  -1.0 ),
///             ( WeightedSimplex { vertices: vec![0, 2, 3], weight: OrderedFloat(3.0) },   1.0 ),
///         ]
///     )         
/// );
/// ```
#[derive(Clone)]
pub struct AgileCoboundaryIteratorFiltrationOrder
        < DissimilarityMatrix, RingOperator >
    where
        DissimilarityMatrix:                                MatrixOracle< ColumnIndex=usize, RowIndex=usize >,  
        DissimilarityMatrix::Row:                           Clone, 
        DissimilarityMatrix::RowEntry:                      KeyValNew,     
        DissimilarityMatrix::Coefficient:                   Ord + Copy + Debug + Bounded,      
        RingOperator:                                       RingOperations,  
{
    facet:                                                  Arc<Vec<Vertex>>,
    facet_filtration:                                       DissimilarityMatrix::Coefficient,
    small_cofacet_vertices:                                 Option< SmallCofacetVertexIterator< DissimilarityMatrix > >,
    big_cofacet_edge_identifiers:                           Option< BigCofacetEdgeIterator< DissimilarityMatrix > >,
    dissimilarity_matrix:                                   DissimilarityMatrix,
    dissimilarity_matrix_size:                              usize, // the size of the dissimilarity matrix
    zero_dimensional_cofacets_opt:                          Option< 
                                                                IntoIter<
                                                                    WeightedSimplex< 
                                                                        DissimilarityMatrix::Coefficient
                                                                    >
                                                                >
                                                            >,  
    all_ambient_filtration_ordered_neighborhood_lists:      Arc< Vec<  // one vec for every vertex in the whole Vietoris-Rips complex
                                                                     Arc< Vec< 
                                                                        (DissimilarityMatrix::Coefficient, Vertex) 
                                                                    >>
                                                            >>,
    ring_operator:                                          RingOperator,
}



impl < 'a, DissimilarityMatrix, RingOperator >

    AgileCoboundaryIteratorFiltrationOrder
        < DissimilarityMatrix, RingOperator >
    where
        DissimilarityMatrix:                Clone + MatrixOracle< ColumnIndex=usize, RowIndex=usize >,        
        DissimilarityMatrix::Row:           Clone,   
        DissimilarityMatrix::RowEntry:      KeyValNew,             
        DissimilarityMatrix::Coefficient:   Ord + Copy + Debug + Bounded,   
        RingOperator:                       RingOperations,
{
    /// Creates a new AgileCoboundaryIteratorFiltrationOrder object
    /// 
    /// # Arguments
    /// 
    /// * `facet` - a vector of vertices that form the facet; must be sorted in strictly ascending order
    /// * `dissimilarity_matrix` - a dissimilarity matrix that defines the clique complex; it must be indexed by `usize` and have a `Coefficient` type that implements `Ord + Debug + Bounded`
    /// * `all_ambient_filtration_ordered_neighborhood_lists` - a vector of vectors, where each inner vector is an `Arc<Vec<(DissimilarityMatrix::Coefficient, Vertex)>>` that contains the filtration-ordered neighborhood lists for each vertex in the whole Vietoris-Rips complex
    /// * `ring_operator` - a ring operator that defines the coefficients of the chain complex
    /// 
    /// # Returns
    /// 
    /// A new AgileCoboundaryIteratorFiltrationOrder object that runs over all nonzero entries in the boundary of the facet in filtraton order (with ties split by lexicographic order of vertices)
    /// 
    /// # Errors
    /// 
    /// Returns an error if the facet is invalid, either because the vertices are not sorted in strictly ascending order,
    /// or because it does not represent a clique in the underlying weighted graph.
    pub fn new( 
        facet:                                              Vec<Vertex>,
        dissimilarity_matrix:                               DissimilarityMatrix,
        dissimilarity_matrix_size:                          usize,
        all_ambient_filtration_ordered_neighbor_lists:      Arc< Vec<  // one vec for every vertex in the whole Vietoris-Rips complex
                                                                Arc< Vec< (DissimilarityMatrix::Coefficient, Vertex) >
                                                            >>>, 
        ring_operator:                                      RingOperator,
    ) -> Result< Self, Vec<Vertex> > {


        // first place the facet inside a vec that has capacity for exactly one additional vertex
        // (this is just to ensure we don't use unnecessary memory)
        let mut exact_facet = Vec::with_capacity( facet.len() + 1 );
        exact_facet.extend_from_slice( &facet );
        let facet = Arc::new( exact_facet );



        // returns an error if the facet is invalid, either because the vertices are not sorted in strictly ascending order, or because it does not represent a clique in the underlying graph
        let facet_filtration = filtration_value_for_clique(&(*facet), &dissimilarity_matrix)?;


        // we initialize the dissimilarity matrix diagonal iterator iff the facet is empty
        //
        // if it *is* the empty facet ([],-MAX), then the cofacets are essentially ([vertex], filtration) pairs such that dissimilarity_matrix[vertex, vertex] is structurally nonzero
        // moreover, the coefficient of every entry in the coboundary is 1
        let zero_dimensional_cofacets_opt = match facet.is_empty() {
            true => {
                let mut cofacets = Vec::new();
                for entry in  DiagonalEntryIterator::new( 
                        dissimilarity_matrix.clone(), 
                        dissimilarity_matrix_size
                ){
                    let vertex = entry.key() as Vertex; // get the vertex from the entry
                    let filtration = entry.val(); // get the filtration value from the entry
                    let simplex = vec![vertex];
                    let cofacet = WeightedSimplex::new( filtration, simplex );
                    cofacets.push( cofacet );
                }
                cofacets.sort(); // sort the cofacets
                Some( cofacets.into_iter() )
            }
            false => None, 
        };
        
        Ok( 
            AgileCoboundaryIteratorFiltrationOrder {
                facet,
                facet_filtration,
                dissimilarity_matrix,
                dissimilarity_matrix_size,
                ring_operator,                
                small_cofacet_vertices:                                 None,
                big_cofacet_edge_identifiers:                           None,
                zero_dimensional_cofacets_opt:                          zero_dimensional_cofacets_opt,
                all_ambient_filtration_ordered_neighborhood_lists:      all_ambient_filtration_ordered_neighbor_lists,
            } 
        )
    }


    /// Generates the entry of the coboundary of `self.facet` corresponding to the given vertex.
    /// 
    /// # Arguments
    /// 
    /// * `vertex` - the vertex to add to the facet
    /// * `filtration` - the filtration value of the cofacet that is generated by adding the vertex to the facet
    /// 
    /// # Returns
    /// 
    /// A tuple containing the weighted simplex and the coefficient of the entry in the coboundary
    pub fn coboundary_entry_for_exogenous_vertex(
            & self,
            vertex:             Vertex,
            filtration:         DissimilarityMatrix::Coefficient,
        ) -> ( WeightedSimplex<DissimilarityMatrix::Coefficient>, RingOperator::Element ) 

        where
            RingOperator:               Clone,    
    {        

        let (cofacet_vertices, coefficient) = coboundary_entry_for_facet_vertex_pair(
            & self.facet,
            vertex,
            self.ring_operator.clone(),
        ).ok().unwrap();   

        // create the weighted simplex
        let weighted_simplex = WeightedSimplex {
            vertices: cofacet_vertices,
            weight: filtration,
        };

        return ( weighted_simplex, coefficient );
    }


}





impl < DissimilarityMatrix, RingOperator >

    Iterator for

    AgileCoboundaryIteratorFiltrationOrder
        < DissimilarityMatrix, RingOperator >
    where
        DissimilarityMatrix::Coefficient:       Clone + Copy + Debug + Ord + Bounded,
        DissimilarityMatrix::RowEntry:          KeyValNew,   // required for DiagonalEntryIterator to be an iterator
        DissimilarityMatrix::Row:               Clone,
        DissimilarityMatrix:                    Clone + MatrixOracle< ColumnIndex=usize, RowIndex=usize >,
        RingOperator:                           Clone + RingOperations,
{
    type Item = (WeightedSimplex<DissimilarityMatrix::Coefficient>, RingOperator::Element);

    fn next(&mut self) -> Option<Self::Item> {


        // check for 0-dimensional cofacets first
        // -----------------------------------------------------    

        // The field `self.zero_dimensional_cofacets_opt` is Some iff the facet is empty (ie has dimension -1).

        if let Some( zero_dimensional_cofacets ) = &mut self.zero_dimensional_cofacets_opt {

            return zero_dimensional_cofacets
                .next()
                .map( |weighted_simplex| {
                    ( weighted_simplex, RingOperator::one() )
                })
        }


        // check for small cofacets next
        // -----------------------------------------------------
        //
        // we define "small cofacets" as cofacets with filtration equal to the facet filtration,

        // if we haven't yet initialized the small cofacet vertices iterator, do so now
        if self.small_cofacet_vertices.is_none() {
            self.small_cofacet_vertices = Some(
                SmallCofacetVertexIterator::new(
                    self.dissimilarity_matrix.clone(),
                    self.facet.clone(),
                    self.facet_filtration, // the filtration value of the facet
                )
            );
        }

        // now self.small_cofacet_vertices is initialized
        // check if it contains any remaining small cofacets, then return the next one
        if let Some( small_cofacet_vertices ) = &mut self.small_cofacet_vertices {
            if let Some( neighbor ) = small_cofacet_vertices.next() {

                // let filtration = match self.facet.is_empty() {
                //     true => { self.dissimilarity_matrix.structural_nonzero_entry(& (neighbor as usize),& (neighbor as usize)).unwrap() }
                //     false => { self.facet_filtration.clone() } 
                // };

                return Some( self.coboundary_entry_for_exogenous_vertex( 
                    neighbor, 
                    self.facet_filtration.clone(), // the filtration value of small cofacets equals that of the facet by definition
                ) );
            }
        }


        // check for big cofacets next
        // -----------------------------------------------------    
        //
        // we define "big cofacets" as cofacets with filtration strictly greater than the facet filtration,
     

        // if we haven't yet initialized the big cofacet edge identifiers iterator, do so now                   
        if self.big_cofacet_edge_identifiers.is_none() {
            self.big_cofacet_edge_identifiers = Some(
                BigCofacetEdgeIterator::new(
                    self.facet.clone(),
                    self.dissimilarity_matrix.clone(),
                    self.facet_filtration, // the filtration value of the facet
                    self.all_ambient_filtration_ordered_neighborhood_lists.clone()
                )
            );
        }

        // now self.big_cofacet_vertices is initialized        
        // if there are remaining big cofacets, then return the next one
        if let Some( big_cofacet_edge_identifiers ) = &mut self.big_cofacet_edge_identifiers {
            if let Some( (cofacet_filtration, vertex) ) = big_cofacet_edge_identifiers.next() {
                return Some( self.coboundary_entry_for_exogenous_vertex( 
                    vertex, 
                    cofacet_filtration // the new filtration will be the length of the edge identifier
                ) );
            }
        }


        // otherwise all entries in the coboundary are exhausted
        return None
    }
}








//  ===========================================================================
//  COBOUNDARY ITERATOR ----   LEXICOGRAPHIC ORDER
//  ===========================================================================




/// An iterator that runs over all cofacets of a given simplex, in ascending lexicographic order, regardless of filtration value
pub struct AgileCoboundaryIterartorLexicographicOrder
        < DissimilarityMatrix, RingOperator >
    where
        DissimilarityMatrix:                        MatrixOracle< ColumnIndex=usize, RowIndex=usize, >,   
{
	pub facet:                                      Vec<Vertex>,
    pub facet_filtration:                           DissimilarityMatrix::Coefficient,
	pub dissimilarity_matrix:                       DissimilarityMatrix,
    pub neighbors_of_vertex_0:                      DissimilarityMatrix::Row,    
    pub ring_operator:                              RingOperator,
}



impl < DissimilarityMatrix, RingOperator >

    AgileCoboundaryIterartorLexicographicOrder
        < DissimilarityMatrix, RingOperator >

    where
        DissimilarityMatrix:                        MatrixOracle< 
                                                        ColumnIndex         =   usize, 
                                                        RowIndex            =   usize, 
                                                        Coefficient:            Ord + Bounded, 
                                                    >,   
{
    pub fn new(
        facet:                                              Vec<Vertex>,
        dissimilarity_matrix:                               DissimilarityMatrix,
        ring_operator:                                      RingOperator,
    ) -> Result<Self, Vec<Vertex>> {

        let facet_filtration = filtration_value_for_clique(&facet, &dissimilarity_matrix)?;
        let neighbors_of_vertex_0 = dissimilarity_matrix.row( & (facet[0] as usize) );

        return Ok(
            AgileCoboundaryIterartorLexicographicOrder {
                facet,
                facet_filtration,
                dissimilarity_matrix,
                neighbors_of_vertex_0,
                ring_operator,
            }
        );
    }
}        




/// implement standard methods of Iterator for AgileCoboundaryIterartorLexicographicOrder struct
impl< 'a, DissimilarityMatrix, RingOperator >

    Iterator for 
    
    AgileCoboundaryIterartorLexicographicOrder
        < DissimilarityMatrix, RingOperator >
        
    where
        DissimilarityMatrix::Coefficient:       Debug + Ord,
        DissimilarityMatrix:                    MatrixOracle< ColumnIndex=usize, RowIndex=usize >,
        RingOperator:                           Clone + RingOperations,    
{
	type Item = (
                    WeightedSimplex
                        < DissimilarityMatrix::Coefficient >, 
                    RingOperator
                        ::Element
                );

    fn next( &mut self ) -> Option<Self::Item> {
        
        'outer_loop: while let Some( neighbor_entry ) = self.neighbors_of_vertex_0.next() {
            
            // get the next neighbor of vertex 0
            let neighbor = neighbor_entry.key();
            let mut filtration = neighbor_entry.val();
            filtration = filtration.max(self.facet_filtration.clone()); // update the filtration value to be at least as large as the facet filtration

            // skip if the vertex is already in the facet
            if self.facet.contains(& (neighbor as Vertex )) {
                continue 'outer_loop; // skip this vertex, since it is already in the facet
            }

            // exclude the vertex if it is too far from any facet vertices
            // otherwise update the filtration value to be the maximum of the distances to the facet vertices            
            for facet_vertex in self.facet[1..].iter().cloned() {                
                match self.dissimilarity_matrix.structural_nonzero_entry( & (facet_vertex as usize), & neighbor ) {
                    None => continue 'outer_loop, // skip this vertex, since it is not adjacent to the facet vertex
                    Some(new_filtration) => filtration = filtration.max(new_filtration), // the vertex is adjacent to the facet vertex

                }
            }

            // if we make it here, then the vertex is neighbor is adjacent to all facet vertices

            // create the cofacet and get its coefficient
            // !! NB: this will throw an error if the facet is not sorted or the vertex already belongs to the facet
            let (cofacet, coefficient) = coboundary_entry_for_facet_vertex_pair( 
                &self.facet, 
                neighbor as  Vertex, 
                self.ring_operator.clone(),
            ).ok().unwrap();

            // wrap the cofacet in a WeightedSimplex
            let weighted_cofacet = WeightedSimplex {
                vertices: cofacet,
                weight: filtration,
            };

            return Some((weighted_cofacet, coefficient));
        }

        return None; // no more cofacets to return
	}
}

























//  =========================================================================
//  UNIT TESTS
//  =========================================================================

#[cfg(test)]
mod tests {
    use crate::{algebra::matrices::{debug::matrix_oracle_is_internally_consistent, operations::umatch::differential::DifferentialUmatch}, topology::{point_cloud, simplicial::simplices::{self, weighted::WeightedSimplex}}, utilities::order::OrderOperatorAuto};

    

    





    #[test]
    fn check_that_some_basic_functions_run_without_error_small() {


        use crate::topology::simplicial::{simplices::weighted::WeightedSimplex, from::graph_weighted::{VietorisRipsComplex}};        
        use crate::topology::point_cloud::unit_circle;    

        use crate::algebra::vectors::entries::KeyValGet;
        use crate::algebra::rings::types::native::{FieldRational64};    
        use crate::algebra::matrices::query::MatrixOracle;
        use crate::algebra::matrices::operations::umatch::row_major::{Umatch};    
        use crate::algebra::matrices::types::third_party::IntoCSR;
        
        use crate::utilities::order::{ is_sorted_strictly, OrderOperatorByKeyCustom, OrderOperatorAutoReverse};
        use crate::utilities::iterators::general::minmax;    
        use crate::utilities::distances::{rowwise_distances};

        use std::sync::Arc;
        use ordered_float::OrderedFloat;  
        use itertools::Itertools;      

        let number_of_points = 2;
        let min_homology_dimension = 0;
        let max_homology_dimension = 2;


        let pcloud: Vec<Vec<f64>> = vec![vec![0.], vec![1.]];

        let dissimilarity_matrix_data
            = rowwise_distances(pcloud.clone())
                .into_iter()
                .map(|x| x.into_iter().enumerate().collect_vec() )
                .collect_vec()
                .into_csr( number_of_points, number_of_points );
        let dissimilarity_matrix = & dissimilarity_matrix_data;

        let dissimilarity_value_min = OrderedFloat(0.0);        
        let dissimilarity_value_max = 
        minmax( 
                (0..number_of_points).map(
                        |x| 
                        dissimilarity_matrix.row(&x).into_iter().map(
                                |x| 
                                x.val()
                            ) 
                    ) 
            ).unwrap_or( dissimilarity_value_min.clone() );         

    
        let ring_operator = FieldRational64::new();
        let chain_complex_data = VietorisRipsComplex::new( & dissimilarity_matrix, number_of_points, ring_operator ).ok().unwrap();
        // let chain_complex_ref = & chain_complex; 
        // let chain_complex = VietorisRipsComplexArc{ arc: Arc::new(chain_complex_data) };   
        let chain_complex = Arc::new(chain_complex_data);           
        let mut row_index_vec = chain_complex.cliques_in_row_reduction_order(max_homology_dimension);
        let mut column_index_vec = chain_complex.cliques_in_row_reduction_order(max_homology_dimension+1);
        
        row_index_vec.reverse();
        column_index_vec.reverse();

   
        // CHECK SIMPLICES ARE FORMATTED CORRECTLY
        // ---------------------------------------------------------------

        // the chain_complex.filtration_value check that the simplex is valid (strictly sorted and a true clique)
        for simplex in row_index_vec.iter() {
            let filtration = chain_complex.filtration_value_for_clique(simplex.vertices()).ok().unwrap();
            assert!( filtration == simplex.filtration() );
        }
        for simplex in column_index_vec.iter() {
            let filtration = chain_complex.filtration_value_for_clique(simplex.vertices()).ok().unwrap();
            assert!( filtration == simplex.filtration() );
        }        


        // CHECK MATRIX IS INTERNALLY VALID
        // ---------------------------------------------------------------
        assert!(
            crate::algebra::matrices::debug::matrix_oracle_is_internally_consistent(
                chain_complex.clone(),
                row_index_vec.iter().cloned(),
                column_index_vec.iter().cloned(),                
            )
        );

        // CHECK ORDER OPERATORS ARE INTERNALLY VALID
        // ---------------------------------------------------------------        
        let mut row_index_vec_sorted = row_index_vec.clone();
        let mut column_index_vec_sorted = column_index_vec.clone();
        row_index_vec_sorted.sort();
        column_index_vec_sorted.sort();

        assert!(
            crate::algebra::matrices::debug::matrix_order_operators_are_internally_consistent(
                chain_complex.clone(), 
                row_index_vec_sorted.iter().cloned(),
                column_index_vec_sorted.iter().cloned(),                
            ).is_ok()
        );
        
      
    

    

    
        println!("starting umatch");
        let umatch = DifferentialUmatch::new(
                chain_complex.clone(), 
                min_homology_dimension,
                max_homology_dimension,
            );      
    
    
        println!("setting up to unpack");  
        let return_cycle_representatives = true;
        let return_bounding_chains = true;
        let _barcode = crate::algebra::chain_complexes::barcode::get_barcode( &umatch, return_cycle_representatives, return_bounding_chains );
    
        println!("getting intervals, reps, bounding chains");
        // let (intervals, representatives, bounding_chains ) = barcode.unwrap();
    
        // let convert_coefficients = |x: Ratio<i64> | (x.numer().clone(), x.denom().clone());
        // let convert_simplex = |x: WeightedSimplex< OrderedFloat<f64> > | x.vertices.iter().map(|y| y.clone() as usize ).collect_vec();
        
        // println!("start reformat reps");     
        // let represntatives_new = representatives.unwrap().iter().map(
        //             |x| // each x is a list of cycle reps
        //             x.iter().map(
        //                 |y| // each y is a cycle rep
        //                 y.iter().map(
        //                     |z| // each z is an entry in a cycle rep
        //                     ( convert_simplex(z.0.clone()), convert_coefficients(z.1.clone()) )
        //                 ).collect_vec()
        //             ).collect_vec()
        //         ).collect_vec();
    
        // println!("start reformat bounding chains");                 
        // let bounding_chains_new = bounding_chains.unwrap().iter().map(
        //             |x| // each x is a list of cycle reps
        //             x.iter().map(
        //                 |y| // each y is a cycle rep
        //                 y.iter().map(
        //                     |z| // each z is an entry in a cycle rep
        //                     ( convert_simplex(z.0.clone()), convert_coefficients(z.1.clone()) )
        //                 ).collect_vec()
        //             ).collect_vec()
        //         ).collect_vec();              
    }






    









  
    
    #[test]
    fn check_that_some_basic_functions_run_without_error() {


        use crate::topology::simplicial::{simplices::weighted::WeightedSimplex, from::graph_weighted::{VietorisRipsComplex}};        
        use crate::topology::point_cloud::unit_circle;    

        use crate::algebra::vectors::entries::KeyValGet;
        use crate::algebra::rings::types::native::{FieldRational64};    
        use crate::algebra::matrices::query::MatrixOracle;
        use crate::algebra::matrices::operations::umatch::row_major::{Umatch};    
        use crate::algebra::matrices::types::third_party::IntoCSR;
        
        use crate::utilities::order::{ is_sorted_strictly, OrderOperatorByKeyCustom, OrderOperatorAutoReverse};
        use crate::utilities::iterators::general::minmax;    
        use crate::utilities::distances::{rowwise_distances};

        use std::sync::Arc;
        use ordered_float::OrderedFloat;  
        use itertools::Itertools;      

        let number_of_points = 8;
        let min_homology_dimension = 0;
        let max_homology_dimension = 2;


        let pcloud = unit_circle( number_of_points, Some(-1.0 .. 1.0));

        let dissimilarity_matrix_data
            = rowwise_distances(pcloud.clone())
                .into_iter()
                .map(|x| x.into_iter().enumerate().collect_vec() )
                .collect_vec()
                .into_csr( number_of_points, number_of_points );
        let dissimilarity_matrix = & dissimilarity_matrix_data;    
    
        let ring_operator = FieldRational64::new();
        let chain_complex_data = VietorisRipsComplex::new( & dissimilarity_matrix, number_of_points, ring_operator ).ok().unwrap();
        // let chain_complex_ref = & chain_complex; 
        // let chain_complex = VietorisRipsComplexArc{ arc: Arc::new(chain_complex_data) };   
        let chain_complex = Arc::new(chain_complex_data);           
        let mut row_index_vec = chain_complex.cliques_in_row_reduction_order(max_homology_dimension);
        let mut column_index_vec = chain_complex.cliques_in_row_reduction_order(max_homology_dimension+1);
        
        row_index_vec.reverse();
        column_index_vec.reverse();


        // CHECK SIMPLICES ARE FORMATTED CORRECTLY
        // ---------------------------------------------------------------

        // the chain_complex.filtration_value check that the simplex is valid (strictly sorted and a true clique)
        for simplex in row_index_vec.iter() {
            let filtration = chain_complex.filtration_value_for_clique(simplex.vertices()).ok().unwrap();
            assert!( filtration == simplex.filtration() );
        }
        for simplex in column_index_vec.iter() {
            let filtration = chain_complex.filtration_value_for_clique(simplex.vertices()).ok().unwrap();
            assert!( filtration == simplex.filtration() );
        }       

        // CHECK MATRIX INTERNALLY VALID
        // ---------------------------------------------------------------        

        assert!(
            crate::algebra::matrices::debug::matrix_oracle_is_internally_consistent(
                chain_complex.clone(),
                row_index_vec.iter().cloned(),
                column_index_vec.iter().cloned(),                
            )
        );
        

        // CHECK ORDER OPERATORS ARE INTERNALLY VALID
        // ---------------------------------------------------------------        
        let mut row_index_vec_sorted = row_index_vec.clone();
        let mut column_index_vec_sorted = column_index_vec.clone();
        row_index_vec_sorted.sort();
        column_index_vec_sorted.sort();

        assert!(
            crate::algebra::matrices::debug::matrix_order_operators_are_internally_consistent(
                chain_complex.clone(), 
                row_index_vec_sorted.iter().cloned(),
                column_index_vec_sorted.iter().cloned(),                
            ).is_ok()
        ); 
    

        println!("starting umatch");
        let iter_row_index = chain_complex.cliques_in_row_reduction_order(max_homology_dimension);  
        let differential_umatch = DifferentialUmatch::new(
            chain_complex.clone(),
            min_homology_dimension,
            max_homology_dimension,
        );   
 
    
    
        println!("setting up to unpack");  
        let return_cycle_representatives = true;
        let return_bounding_chains = true;
        let _barcode = crate::algebra::chain_complexes::barcode::get_barcode( 
            &differential_umatch,
            return_cycle_representatives,
            return_bounding_chains,
        );
    
        println!("getting intervals, reps, bounding chains");
        // let (intervals, representatives, bounding_chains ) = barcode.unwrap();
    
        // let convert_coefficients = |x: Ratio<i64> | (x.numer().clone(), x.denom().clone());
        // let convert_simplex = |x: WeightedSimplex< OrderedFloat<f64> > | x.vertices.iter().map(|y| y.clone() as usize ).collect_vec();
        
        // println!("start reformat reps");     
        // let represntatives_new = representatives.unwrap().iter().map(
        //             |x| // each x is a list of cycle reps
        //             x.iter().map(
        //                 |y| // each y is a cycle rep
        //                 y.iter().map(
        //                     |z| // each z is an entry in a cycle rep
        //                     ( convert_simplex(z.0.clone()), convert_coefficients(z.1.clone()) )
        //                 ).collect_vec()
        //             ).collect_vec()
        //         ).collect_vec();
    
        // println!("start reformat bounding chains");                 
        // let bounding_chains_new = bounding_chains.unwrap().iter().map(
        //             |x| // each x is a list of cycle reps
        //             x.iter().map(
        //                 |y| // each y is a cycle rep
        //                 y.iter().map(
        //                     |z| // each z is an entry in a cycle rep
        //                     ( convert_simplex(z.0.clone()), convert_coefficients(z.1.clone()) )
        //                 ).collect_vec()
        //             ).collect_vec()
        //         ).collect_vec();              
    }




    #[test]
    fn test_empty_simplex_iter() {
        use sprs::CsMatBase;
        use ordered_float::OrderedFloat;
        use crate::topology::simplicial::from::graph_weighted::AgileSimplexIteratorLexicographicOrder;
        use crate::algebra::matrices::query::MatrixOracle;

        
        let dissimilarity_matrix = CsMatBase::new( (2,2), vec![0,1,2], vec![0,1], vec![OrderedFloat(0.0),OrderedFloat(0.0)] );

        println!("entry (0,1) = {:?}", (& dissimilarity_matrix).structural_nonzero_entry(&0, &1));
            
        let simplices: Vec<_>    =   AgileSimplexIteratorLexicographicOrder::new( 
                            & dissimilarity_matrix, 
                            2,          //  matrix size
                            1,          //  dimension
                            false,  // include the empty simplex
                        ).collect();
        println!("generated simplices = {:?}", &simplices );
        let empty =  Vec::< WeightedSimplex<OrderedFloat<f64>> >::new();
                    
        assert!( empty.eq( &simplices ) )        
    }



    
    #[test]
    fn test_simplex_iterators () {
        use crate::topology::simplicial::from::graph_weighted::{AgileBoundaryIteratorLexicographicOrder, AgileCoboundaryIteratorFiltrationOrder, VietorisRipsComplex};
        use crate::topology::simplicial::simplices::weighted::WeightedSimplex;   
        use crate::algebra::matrices::types::vec_of_vec::sorted::VecOfVec;
        use crate::algebra::matrices::query::MatrixOracle;
        use crate::algebra::rings::types::native::FieldFloat64;
        use ordered_float::OrderedFloat;
        use std::sync::Arc;

        // define the ring operator
        let ring_operator = FieldFloat64::new();        

        // define the dissimilarity matrix
        // (this is a convenient way to build a VecOfVec from a "dense matrix")
        let dissimilarity_matrix = VecOfVec::from_ragged(
            & vec![
                vec![OrderedFloat(0.0), OrderedFloat(1.0), OrderedFloat(2.0), OrderedFloat(3.0)],
                vec![OrderedFloat(1.0), OrderedFloat(0.0), OrderedFloat(1.0), OrderedFloat(2.0)],
                vec![OrderedFloat(2.0), OrderedFloat(1.0), OrderedFloat(0.0), OrderedFloat(1.0)],
                vec![OrderedFloat(3.0), OrderedFloat(2.0), OrderedFloat(1.0), OrderedFloat(1.0)],                
            ]
        );

        // define the Vietoris-Rips complex
        let vietoris_rips_complex = Arc::new( 
            VietorisRipsComplex::new(
                & dissimilarity_matrix,
                3, // dissimilarity_matrix_size
                ring_operator,
            ).ok().unwrap()
        );

        // Check a boundary iterator
        // ---------------------------------------------------------------

        // define the simplex
        let simplex = WeightedSimplex {
            vertices: vec![0, 1, 2],
            weight: OrderedFloat(2.0),
        };         

        // create the iterator
        let boundary = AgileBoundaryIteratorLexicographicOrder::new(
            vietoris_rips_complex.clone(),
            simplex,
            false, // this indicates we don't consider the emtpy simplex to be a "real" simplex
        );   

        // check the results
        assert!( 
            boundary.eq(
                vec![
                    ( WeightedSimplex { vertices: vec![0, 1], weight: OrderedFloat(1.0) },  1.0 ),
                    ( WeightedSimplex { vertices: vec![0, 2], weight: OrderedFloat(2.0) }, -1.0 ),
                    ( WeightedSimplex { vertices: vec![1, 2], weight: OrderedFloat(1.0) },  1.0 ),
                ]
            )         
        );

        // Check a coboundary iterator
        // ---------------------------------------------------------------   

        // Here we use the constructor from the Vietoris-Rips complex, which is more convenient  

        // define the simplex
        let simplex = WeightedSimplex {
            vertices: vec![0, 2],
            weight: OrderedFloat(2.0),
        };  

        // create the iterator
        let coboundary = vietoris_rips_complex.row( & simplex );

        // check the results
        assert!( 
            coboundary.eq(
                vec![
                    ( WeightedSimplex { vertices: vec![0, 1, 2], weight: OrderedFloat(2.0) },  -1.0 ),
                    ( WeightedSimplex { vertices: vec![0, 2, 3], weight: OrderedFloat(3.0) },   1.0 ),
                ]
            )         
        );
    } 





}