grid1d 0.5.1

A mathematically rigorous, type-safe Rust library for 1D grid operations and interval partitions, supporting both native and arbitrary-precision numerics.
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
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
#![deny(rustdoc::broken_intra_doc_links)]

//! Concrete 1D grid types with performance specialization.
//!
//! This module defines the three concrete grid types and their shared error enum:
//!
//! | Type | Point location | Memory | Best for |
//! |------|---------------|--------|----------|
//! | [`Grid1DUniform`] | **O(1)** analytical | O(n) | Equal spacing, FDM, spectral methods |
//! | [`Grid1DNonUniform`] | O(log n) binary search | O(n) | Adaptive spacing, boundary layers |
//! | [`Grid1D`] | O(1) or O(log n) | O(n) | Enum dispatch over the two variants above |
//!
//! The submodule [`traits`] defines the core grid traits ([`Grid1DTrait`],
//! [`HasDomain1D`], [`HasCoords1D`], etc.) that are re-exported at the crate root.
//! The submodule [`window`] provides [`Grid1DWindow`], a zero-copy borrowed view
//! over a contiguous slice of intervals within any [`Grid1DTrait`].
//!
//! # Examples
//!
//! ## Uniform grid
//!
//! ```rust
//! use grid1d::{*, intervals::*};
//! use try_create::TryNew;
//!
//! let grid = Grid1DUniform::new(
//!     IntervalClosed::new(0.0_f64, 1.0),
//!     NumIntervals::try_new(4).unwrap(),
//! );
//! assert_eq!(grid.num_intervals().as_ref(), &4);
//! ```
//!
//! ## Non-uniform grid from sorted coordinates
//!
//! ```rust
//! use grid1d::{*, intervals::*};
//! use sorted_vec::partial::SortedSet;
//!
//! let grid = Grid1D::<IntervalClosed<f64>>::try_from_sorted(
//!     SortedSet::from_unsorted(vec![0.0, 0.1, 0.5, 1.0]),
//! ).unwrap();
//! assert_eq!(grid.num_intervals().as_ref(), &3);
//! ```
//!
//! ## Uniform refinement
//!
//! ```rust
//! use grid1d::{*, intervals::*};
//! use try_create::TryNew;
//!
//! let grid = Grid1D::uniform(IntervalClosed::new(0.0_f64, 1.0), NumIntervals::try_new(4).unwrap());
//! let refined = grid.refine_uniform(&PositiveNumPoints1D::try_new(1).unwrap());
//! assert_eq!(refined.refined_grid().num_intervals().as_ref(), &8);
//! ```

pub mod traits;
pub use traits::{
    FindIntervalIdOfPoint, Grid1DIntervalBuilder, Grid1DTrait, HasCoordIdRange, HasCoords1D,
    HasDomain1D, HasIntervalIdRange, HasIntervals,
};

pub mod window;
pub use window::{ErrorsGrid1DWindow, Grid1DWindow};

use crate::{
    CoordId, Coords1D, ErrorsCoords1D, ErrorsIntervalConstruction, ErrorsPositiveInt,
    Grid1DIndexSpaces, IntervalFinitePositiveLengthTrait, IntervalFromBounds, IntervalId,
    NumIntervals, PositiveNumPoints1D, SupportsCircularTopology, Topology1D,
    operations::refinement::{
        Grid1DNonUniformRefinement, Grid1DUniformRefinement, build_non_uniform_grid_refinement,
        refine_all_intervals_in_coords1d_same_subdivisions,
    },
};
use getset::Getters;
use num_valid::{
    RealScalar,
    core::errors::capture_backtrace,
    functions::{Reciprocal, Rounding},
    scalars::{PositiveRealScalar, RelativeTolerance},
};
use serde::{Deserialize, Serialize};
use sorted_vec::partial::SortedSet;
use std::backtrace::Backtrace;
use thiserror::Error;
use try_create::TryNew;

//------------------------------------------------------------------------------------------------------------------------------
///  Comprehensive error types for 1D grid construction and manipulation.
///
/// [`ErrorsGrid1D`] provides specific error information for all failure modes
/// in grid construction, enabling robust error handling and debugging.
///
/// ## Error Variants
///
/// ### Construction Errors
/// - [`ErrorsGrid1D::RequiredAtLeastTwoDistinctPoints`]: Grid needs minimum 2 distinct coordinates
/// - [`ErrorsGrid1D::FromCoords1DConstructor`]: Error from underlying coordinate construction
/// - [`ErrorsGrid1D::FromIntervalConstructor`]: Error from underlying interval construction
///
/// # Examples
///
/// ## Handling Insufficient Points
///
/// ```rust
/// use grid1d::{
///     Coords1D, Grid1D, ErrorsGrid1D,
///     intervals::*,
/// };
/// use sorted_vec::partial::SortedSet;
///
/// let coords = SortedSet::from_unsorted(vec![0.0]); // Only one point provided
/// let err = Grid1D::<IntervalClosed<f64>>::try_from_sorted(coords).unwrap_err();
/// assert!(matches!(err, ErrorsGrid1D::RequiredAtLeastTwoDistinctPoints { .. }), "{:?}", err);
/// ```
#[derive(Debug, Error)]
pub enum ErrorsGrid1D<Domain1D: IntervalFinitePositiveLengthTrait> {
    /// Indicates that fewer than two distinct points were provided, which is insufficient to define a valid grid.
    ///
    /// This error occurs when attempting to construct a [`Grid1D`] with fewer than two points, as at least two points
    /// are required to define a partition of a 1D interval.
    #[error("The number of distinct points required to define an interval partition must be >= 2!")]
    RequiredAtLeastTwoDistinctPoints {
        /// The actual number of points that were provided.
        num_points_provided: PositiveNumPoints1D,
        /// Captured backtrace for debugging.
        backtrace: Backtrace,
    },

    /// Error propagated from the underlying [`Coords1D`] construction.
    #[error("Error from Coords1D construction")]
    FromCoords1DConstructor {
        /// The underlying error from [`Coords1D`] construction.
        #[from]
        source: ErrorsCoords1D,
    },

    /// Error propagated from the construction of the underlying interval.
    #[error("Error from the construction of the interval")]
    FromIntervalConstructor {
        /// The underlying error from interval construction.
        #[from]
        source: ErrorsIntervalConstruction<Domain1D::RealType>,
    },

    #[error(
        "The first point of the grid ({first_point}) is not equal to the lower bound of the interval representing the domain {domain:?}!"
    )]
    /// Indicates that the first coordinate does not match the domain's lower bound.
    FirstPointIsNotDomainLowerBound {
        /// The actual first coordinate found in the grid.
        first_point: Domain1D::RealType,
        /// The domain interval whose lower bound was expected.
        domain: Domain1D,
        /// Captured backtrace for debugging.
        backtrace: Backtrace,
    },

    #[error(
        "The last point of the grid ({last_point}) is not equal to the upper bound of the interval representing the domain {domain:?}!"
    )]
    /// Indicates that the last coordinate does not match the domain's upper bound.
    LastPointIsNotDomainUpperBound {
        /// The actual last coordinate found in the grid.
        last_point: Domain1D::RealType,
        /// The domain interval whose upper bound was expected.
        domain: Domain1D,
        /// Captured backtrace for debugging.
        backtrace: Backtrace,
    },

    #[error(transparent)]
    /// Wraps a [`ErrorsPositiveInt`] from an invalid interval count.
    NumIntervals(#[from] ErrorsPositiveInt),
}
//------------------------------------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------------------------------------
pub(crate) fn validate_coords_in_domain_closure<Domain1D: IntervalFinitePositiveLengthTrait>(
    coords: &Coords1D<Domain1D::RealType>,
    domain: &Domain1D,
) -> Result<NumIntervals, ErrorsGrid1D<Domain1D>> {
    let lower_bound = domain.lower_bound_value();
    let upper_bound = domain.upper_bound_value();

    let first_point = coords.first();
    if first_point != lower_bound {
        return Err(ErrorsGrid1D::FirstPointIsNotDomainLowerBound {
            first_point: first_point.clone(),
            domain: domain.clone(),
            backtrace: capture_backtrace(),
        });
    }

    let last_point = coords.last();
    if last_point != upper_bound {
        return Err(ErrorsGrid1D::LastPointIsNotDomainUpperBound {
            last_point: last_point.clone(),
            domain: domain.clone(),
            backtrace: capture_backtrace(),
        });
    }

    let num_intervals = NumIntervals::try_new(coords.num_points().as_ref() - 1)?;

    Ok(num_intervals)
}
//------------------------------------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------------------------------------
///  A general-purpose, non-uniform partition of a finite interval with positive length.
///
/// The [`Grid1DNonUniform`] struct represents a partition of a bounded interval into
/// adjacent, non-overlapping sub-intervals where **the spacing between points can be arbitrary**.
/// This provides maximum flexibility for creating adaptive grids that can resolve complex
/// features, such as boundary layers, shock fronts, or regions with high solution gradients.
///
/// Unlike [`Grid1DUniform`] which enforces equal spacing, [`Grid1DNonUniform`] is defined by an
/// explicit set of coordinates, allowing for fine-grained control over the mesh resolution.
///
/// ## Mathematical Definition
///
/// Given a domain `D` and a set of `n+1` unique, sorted coordinates `{p₀, p₁, ..., pₙ}`,
/// a non-uniform grid is formed if and only if:
/// 1.  `p₀` equals the lower bound of `D`.
/// 2.  `pₙ` equals the upper bound of `D`.
///
/// This creates `n` sub-intervals `{I₀, I₁, ..., I_{n-1}}` where `Iᵢ` is the interval
/// between `pᵢ` and `pᵢ₊₁`. The length of each interval, `δᵢ = pᵢ₊₁ - pᵢ`, can vary.
///
/// ## Core Mathematical Properties
///
/// - **Arbitrary Spacing**: Interval lengths `δᵢ` can be different, allowing for adaptive resolution.
/// - **Boundary Matching**: The first and last grid points are guaranteed to match the domain's lower and upper bounds exactly. This is a critical validation step.
/// - **Complete Coverage**: `D = I₀ ∪ I₁ ∪ ... ∪ I_{n-1}` (the union of sub-intervals perfectly reconstructs the domain).
/// - **Non-Overlapping**: `Iᵢ ∩ Iⱼ = ∅` for `i ≠ j` (sub-intervals are disjoint).
/// - **Inherited Properties**: Inherits uniqueness, sorting, and non-emptiness from [`Coords1D`].
///
/// ## Performance Characteristics vs. Uniform Grids
///
/// | Operation | [`Grid1DNonUniform`] | [`Grid1DUniform`] | Advantage |
/// |-----------|----------------------|-------------------|-----------|
/// | **Construction** | O(n) + validation | O(n) | Equal |
/// | **Memory Storage** | O(n) | O(n) | Equal (both store coordinates) |
/// | **Point Location** | O(log n) binary search | O(1) analytical | ✅ **Uniform much faster** |
/// | **Interval Access** | O(1) | O(1) | Equal |
/// | **Coordinate Access** | O(1) | O(1) | Equal (pre-computed) |
/// | **Length Queries** | O(1) computed | O(1) cached | ✅ **Uniform simpler** |
///
/// ## Design Philosophy
///
/// ### Correctness Through Strict Validation
/// The primary design principle is **mathematical correctness**. The `try_new` constructor is strict and performs critical runtime checks to ensure the grid is a valid partition *of the specified domain*. This prevents common numerical errors, such as:
/// - Grids that do not fully cover the intended domain.
/// - Off-by-one errors at boundaries.
/// - Inconsistencies between the grid's span and the domain's length.
///
/// ### Flexibility and Generality
/// By accepting any valid `Coords1D`, this struct can represent any one-dimensional partition, making it the general-purpose backbone of the `Grid1D` system. It is suitable for:
/// - Manually defined meshes.
/// - Programmatically generated adaptive meshes.
/// - Results of grid union operations.
///
/// ### Integration with numerical Ecosystem
/// - **Unified Interface**: Implements the `Grid1DTrait` trait, providing the same API as `Grid1DUniform`.
/// - **Grid Enum Integration**: Serves as the general-purpose variant in the `Grid1D` enum.
/// - **Domain-Awareness**: Correctly handles open, closed, and semi-open domains through the `Grid1DIntervalBuilder` trait.
///
/// ## Construction and Usage Examples
///
/// ### Basic Construction
/// ```rust
/// use grid1d::{
///     Grid1DNonUniform, HasCoords1D, Grid1DTrait, HasIntervalIdRange,
///     intervals::*, HasDomain1D,
///     scalars::NumIntervals,
/// };
/// use grid1d::Coords1D;
/// use sorted_vec::partial::SortedSet;
/// use std::ops::Deref;
///
/// // Define a non-uniform set of coordinates
/// let coords = Coords1D::try_from(
///     SortedSet::from_unsorted(vec![0.0, 0.1, 0.5, 0.9, 1.0])
/// ).unwrap();
///
/// // Create the non-uniform grid
/// let grid = Grid1DNonUniform::<IntervalClosed<f64>>::try_new_from_coords(coords).unwrap();
///
/// // Verify properties
/// assert_eq!(grid.num_intervals().as_ref(), &4);
/// assert_eq!(grid.coords().deref(), &[0.0, 0.1, 0.5, 0.9, 1.0]);
/// ```
///
/// ### Adaptive Mesh for a Boundary Layer
/// ```rust
/// use grid1d::{
///     Coords1D, Grid1DNonUniform, Grid1DTrait, HasCoords1D,
///     intervals::*,
///     scalars::IntervalId,
/// };
/// use sorted_vec::partial::SortedSet;
///
/// // Simulate a boundary layer by clustering points near x=0
/// let mut points = vec![0.0, 1.0];
/// for i in 1..=5 {
///     points.push(1.0 / (2.0_f64.powi(i)));
/// }
///
/// let coords = Coords1D::try_from(SortedSet::from_unsorted(points)).unwrap();
/// let grid = Grid1DNonUniform::<IntervalClosed<f64>>::try_new_from_coords(coords).unwrap();
///
/// println!("Adaptive grid points: {:?}", grid.coords());
///
/// // Interval lengths decrease towards the boundary
/// let id_0 = IntervalId::new(0);
/// let id_1 = IntervalId::new(1);
/// more_asserts::assert_lt!((grid.interval_length(&id_0).into_inner() - grid.interval_length(&id_1).as_ref()).abs(), 1e-15);
/// ```
///
/// ### Error Handling During Construction
/// ```rust
/// use grid1d::{
///     Grid1DNonUniform, ErrorsGrid1D, Coords1D,
///     intervals::*,
/// };
/// use sorted_vec::partial::SortedSet;
///
/// // Not enough points
/// let coords_too_few = Coords1D::try_from(SortedSet::from_unsorted(vec![0.0])).unwrap();
/// let result = Grid1DNonUniform::<IntervalClosed<f64>>::try_new_from_coords(coords_too_few);
/// assert!(matches!(result, Err(ErrorsGrid1D::RequiredAtLeastTwoDistinctPoints { .. })));
/// ```
///
/// ## Best Practices and Recommendations
///
/// ### When to Use [`Grid1DNonUniform`]
/// - **Adaptive Mesh Refinement (AMR)**: When you need higher resolution in specific areas (e.g., near boundaries, shocks, or high-gradient regions).
/// - **Complex Geometries**: When mapping from a simple computational domain to a complex physical domain results in non-uniform spacing.
/// - **Multi-Physics Coupling**: When combining grids from different simulations, the resulting union is typically non-uniform.
/// - **Error-Driven Adaptation**: When grid points are placed dynamically to minimize numerical error.
///
/// ### When to Prefer [`Grid1DUniform`]
/// - For problems where the solution is smooth and does not have sharp features.
/// - When using standard finite difference or Fourier spectral methods that rely on equal spacing.
/// - When point location performance is the absolute top priority (O(1) vs. O(log n)).
///
/// ## Mathematical Properties and Guarantees
///
/// ### Boundary Matching (Runtime Validated)
/// ```text
/// coords.first() == domain.lower_bound_value()
/// coords.last()  == domain.upper_bound_value()
/// ```
/// This is the core invariant enforced by `try_new`.
///
/// Note: these are equality checks on boundary *values*. Containment of those
/// boundary values still follows the domain boundary semantics (open/closed).
/// For example, with an open domain `(a, b)`, `a` and `b` may appear as endpoint
/// coordinate values while remaining outside the domain as points.
///
/// ### Partition Completeness
/// The union of all sub-intervals perfectly reconstructs the domain.
/// ```text
/// D = I₀ ∪ I₁ ∪ ... ∪ Iₙ₋₁
/// ```
///
/// ### Point Location Uniqueness
/// Every point `x` in the domain belongs to exactly one sub-interval.
///
/// ## See Also
///
/// - [`Grid1DUniform`]: The specialized, high-performance alternative for equally spaced grids.
/// - [`Grid1D`]: The enum that unifies both uniform and non-uniform grids under a single API.
/// - [`Grid1DTrait`]: The core trait providing partition operations.
/// - [`Coords1D`]: The underlying coordinate container.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(bound(deserialize = "Domain1D: for<'d> serde::Deserialize<'d>, \
                  Domain1D::RealType: for<'d> serde::Deserialize<'d>"))]
pub struct Grid1DNonUniform<Domain1D: IntervalFinitePositiveLengthTrait> {
    /// Domain covered by the grid.
    pub(crate) domain: Domain1D,

    /// The index spaces associated with the grid, which define the topology and interval indexing.
    pub(crate) index_spaces: Grid1DIndexSpaces,

    /// Strictly sorted, duplicate-free coordinates of partition points.
    pub(crate) coords: Coords1D<Domain1D::RealType>,
}

impl<Domain1D: IntervalFinitePositiveLengthTrait> Grid1DNonUniform<Domain1D> {
    /// Creates a new non-uniform grid from an explicit domain and pre-validated coordinates.
    ///
    /// Validates that the coordinates are consistent with the domain (first and last
    /// coordinate must match the domain bounds). Prefer [`Grid1D::try_from_sorted`]
    /// or [`Grid1D::try_from_coords`] when the domain can be inferred from the coordinates.
    pub fn try_new(
        domain: Domain1D,
        coords: Coords1D<Domain1D::RealType>,
    ) -> Result<Self, ErrorsGrid1D<Domain1D>> {
        let num_intervals = validate_coords_in_domain_closure(&coords, &domain)?;

        let index_spaces = Grid1DIndexSpaces::new_non_periodic(num_intervals);

        Ok(Self {
            domain,
            coords,
            index_spaces,
        })
    }
}

impl<Domain1D: IntervalFromBounds> Grid1DNonUniform<Domain1D> {
    fn create_domain_from_coords(
        coords: &Coords1D<Domain1D::RealType>,
    ) -> Result<Domain1D, ErrorsGrid1D<Domain1D>>
//    where
//        Domain1D: IntervalFromBounds,
    {
        let n_pts = coords.num_points();
        if n_pts.as_ref() < &2 {
            Err(ErrorsGrid1D::RequiredAtLeastTwoDistinctPoints {
                num_points_provided: n_pts,
                backtrace: capture_backtrace(),
            })
        } else {
            Ok(Domain1D::try_new(
                coords.first().clone(),
                coords.last().clone(),
            )?)
        }
    }

    /// Attempts to create an [`Grid1DNonUniform`] from a set of coordinates modeled by a [`Coords1D`] object.
    ///
    /// # Parameters
    ///
    /// - `coords`: A [`Coords1D`] object containing the sorted coordinates of the points.
    ///
    /// # Errors
    ///
    /// - Returns [`ErrorsGrid1D::RequiredAtLeastTwoDistinctPoints`] if fewer than 2 points are provided.
    ///
    /// # Example
    ///
    /// ```rust
    /// use grid1d::{
    ///     Coords1D, Grid1DNonUniform, HasDomain1D,
    ///     intervals::*,
    /// };
    /// use sorted_vec::partial::SortedSet;
    ///
    /// let coords = Coords1D::try_from(SortedSet::from_unsorted(vec![0.0, 1.0])).unwrap();
    /// let partition = Grid1DNonUniform::<IntervalClosed<f64>>::try_new_from_coords(coords).unwrap();
    ///
    /// let domain = partition.domain();
    /// assert_eq!(domain.lower_bound_value(), &0.0);
    /// assert_eq!(domain.upper_bound_value(), &1.0);
    /// ```
    pub fn try_new_from_coords(
        coords: Coords1D<Domain1D::RealType>,
    ) -> Result<Self, ErrorsGrid1D<Domain1D>> {
        let domain = Self::create_domain_from_coords(&coords)?;

        let num_intervals = NumIntervals::try_new(coords.num_points().as_ref() - 1)
            .expect("At least 2 points are required to form a valid grid!");
        let index_spaces = Grid1DIndexSpaces::new_non_periodic(num_intervals);

        Ok(Self {
            domain,
            coords,
            index_spaces,
        })
    }
}

impl<Domain1D> Grid1DNonUniform<Domain1D>
where
    Domain1D: IntervalFinitePositiveLengthTrait + SupportsCircularTopology,
{
    /// Attempts to create a periodic non-uniform grid from sorted coordinates.
    ///
    /// The resulting grid uses [`Topology1D::Circle`], so the first and last
    /// intervals are considered neighbors.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorsGrid1D::RequiredAtLeastTwoDistinctPoints`] if fewer than
    /// two distinct points are provided.
    pub fn try_new_periodic(
        domain: Domain1D,
        coords: Coords1D<Domain1D::RealType>,
    ) -> Result<Self, ErrorsGrid1D<Domain1D>> {
        let num_intervals = validate_coords_in_domain_closure(&coords, &domain)?;

        let index_spaces = if domain.is_lower_bound_open() {
            Grid1DIndexSpaces::new_periodic_lower_open_interval(num_intervals)
        } else {
            Grid1DIndexSpaces::new_periodic_upper_open_interval(num_intervals)
        };

        Ok(Self {
            domain,
            coords,
            index_spaces,
        })
    }
}

impl<Domain1D> Grid1DNonUniform<Domain1D>
where
    Domain1D: IntervalFromBounds + SupportsCircularTopology,
{
    /// Attempts to create a periodic non-uniform grid from sorted coordinates.
    ///
    /// The resulting grid uses [`Topology1D::Circle`], so the first and last
    /// intervals are considered neighbors.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorsGrid1D::RequiredAtLeastTwoDistinctPoints`] if fewer than
    /// two distinct points are provided.
    pub fn try_new_periodic_from_coords(
        coords: Coords1D<Domain1D::RealType>,
    ) -> Result<Self, ErrorsGrid1D<Domain1D>> {
        let domain = Self::create_domain_from_coords(&coords)?;

        let num_intervals = NumIntervals::try_new(coords.num_points().as_ref() - 1)
            .expect("At least 2 points are required to form a valid grid!");

        let index_spaces = if domain.is_lower_bound_open() {
            Grid1DIndexSpaces::new_periodic_lower_open_interval(num_intervals)
        } else {
            Grid1DIndexSpaces::new_periodic_upper_open_interval(num_intervals)
        };

        Ok(Self {
            domain,
            coords,
            index_spaces,
        })
    }
}

impl<Domain1D: IntervalFinitePositiveLengthTrait> HasDomain1D for Grid1DNonUniform<Domain1D> {
    type Domain1D = Domain1D;

    #[inline(always)]
    fn domain(&self) -> &Domain1D {
        &self.domain
    }
}

impl<Domain1D: IntervalFinitePositiveLengthTrait> HasCoords1D for Grid1DNonUniform<Domain1D> {
    type CoordType = Domain1D::RealType;

    #[inline(always)]
    fn coords(&self) -> &Coords1D<Self::CoordType> {
        &self.coords
    }
}

impl<Domain1D: Grid1DIntervalBuilder> FindIntervalIdOfPoint for Grid1DNonUniform<Domain1D> {
    type Point1DType = Domain1D::RealType;

    fn find_interval_id_of_point(&self, x: &Self::Point1DType) -> Option<IntervalId> {
        if !self.domain().contains_point(x) {
            return None;
        }

        // Here we use the domain's lower bound closure property to determine the assignment of interior partition points.
        // This is because the domain type dictates the sub-interval construction rules, which in turn determine how boundary points are assigned to intervals.
        // For example:
        // - For a closed domain [a, b], all sub-intervals are left-closed, so interior points belong to the right interval.
        // - For a half-open domain (a, b], all sub-intervals are right-closed, so interior points belong to the left interval.
        // - For a half-open domain [a, b), the first interval is left-closed and the last interval is open, so interior points belong to the right interval.
        // - For a open domain (a, b), all sub-intervals are open, so interior points do not belong to any interval, but since we are checking for exact matches with grid points, we can still assign them based on the closure of the lower bound.
        // This logic ensures that the point location is consistent with the interval construction rules defined by the domain type, while still leveraging the uniform spacing for O(1) access.
        // The key point is that the domain's lower bound closure property directly informs how we assign interior partition points to intervals, which is crucial for maintaining the correct semantics of the partitioning.
        if self.domain().is_lower_bound_closed() {
            // Sub-intervals are left-closed [pₖ, pₖ₊₁): boundary point pₖ belongs to interval k.
            // find_floor_index returns the largest index j where coords[j] ≤ x.
            // Clamped to num_intervals-1 to handle the closed upper boundary of [a,b] domains.
            let floor = self
                .coords()
                .find_floor_index(x)
                .expect("Point is in domain but has no floor coordinate");
            let final_id = floor.min(*self.num_intervals().as_ref() - 1);
            Some(IntervalId::new(final_id))
        } else {
            // Sub-intervals are right-closed (pₖ, pₖ₊₁]: boundary point pₖ belongs to interval k-1.
            // partition_point(c < x) returns the first index where coord ≥ x.
            let idx = self.coords().find_insertion_index(x);
            if idx == 0 {
                Some(IntervalId::new(0))
            } else {
                Some(IntervalId::new(idx - 1))
            }
        }
    }
}

impl<Domain1D> HasIntervalIdRange for Grid1DNonUniform<Domain1D>
where
    Domain1D: Grid1DIntervalBuilder,
{
    #[inline(always)]
    fn first_interval_id(&self) -> IntervalId {
        self.index_spaces.interval_index_space().first_interval_id()
    }

    #[inline(always)]
    fn last_interval_id(&self) -> IntervalId {
        self.index_spaces.interval_index_space().last_interval_id()
    }
}

impl<Domain1D> HasCoordIdRange for Grid1DNonUniform<Domain1D>
where
    Domain1D: Grid1DIntervalBuilder,
{
    #[inline(always)]
    fn first_coord_id(&self) -> CoordId {
        self.index_spaces.coord_index_space().first_coord_id()
    }

    #[inline(always)]
    fn last_coord_id(&self) -> CoordId {
        self.index_spaces.coord_index_space().last_coord_id()
    }
}

impl<Domain1D> Grid1DTrait for Grid1DNonUniform<Domain1D>
where
    Domain1D: Grid1DIntervalBuilder,
{
    #[inline(always)]
    fn index_spaces(&self) -> &Grid1DIndexSpaces {
        &self.index_spaces
    }

    type UniformlyRefinedGrid1DType = Self;

    fn refine_uniform(
        self,
        num_extra_points_each_interval: &PositiveNumPoints1D,
    ) -> Grid1DUniformRefinement<Self> {
        let (
            refined_coords,
            refined_to_original_interval_mapping,
            original_to_refined_interval_mapping,
        ) = refine_all_intervals_in_coords1d_same_subdivisions(
            self.coords(),
            num_extra_points_each_interval,
        );

        let domain = self.domain().clone();
        let num_refined_intervals = validate_coords_in_domain_closure(&refined_coords, &domain)
            .expect("Refined coordinates do not form a valid grid!");

        let topology = self.index_spaces.topology();
        let refined_index_spaces = match topology {
            Topology1D::RealLine => Grid1DIndexSpaces::new_non_periodic(num_refined_intervals),
            Topology1D::Circle => {
                if self.domain().is_lower_bound_open() {
                    Grid1DIndexSpaces::new_periodic_lower_open_interval(num_refined_intervals)
                } else {
                    Grid1DIndexSpaces::new_periodic_upper_open_interval(num_refined_intervals)
                }
            }
        };

        let refined_grid = Self {
            domain,
            coords: refined_coords,
            index_spaces: refined_index_spaces,
        };

        Grid1DUniformRefinement::new(
            refined_grid,
            self,
            refined_to_original_interval_mapping,
            original_to_refined_interval_mapping,
        )
    }

    fn refine(
        self,
        intervals_to_refine: &std::collections::BTreeMap<IntervalId, PositiveNumPoints1D>,
    ) -> Grid1DNonUniformRefinement<Self> {
        build_non_uniform_grid_refinement(self, intervals_to_refine)
    }
}
//-------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------------------------------------
///  A uniform partition of a finite interval with positive length into equal-sized sub-intervals.
///
/// The [`Grid1DUniform`] struct represents a partition of a bounded interval into
/// adjacent, non-overlapping sub-intervals where **all sub-intervals have exactly the same length**.
/// This provides optimal performance and memory efficiency for regular grids commonly used in
/// finite difference methods, spectral computations, and uniform discretizations.
///
/// Unlike [`Grid1DNonUniform`] which allows arbitrary point distributions, [`Grid1DUniform`]
/// enforces equal spacing while providing specialized optimizations for uniform access patterns.
///
/// ## Mathematical Definition
///
/// Given a domain `D` with finite positive length and a number of intervals `n`, the uniform
/// partition creates `n+1` equally spaced points:
/// ```text
/// p_k = lower_bound(D) + k * δ  for k = 0, 1, ..., n
/// ```
/// where `δ = length(D) / n` is the uniform spacing.
///
/// This creates `n` sub-intervals `{I₀, I₁, ..., I_{n-1}}` where each interval has length `δ`.
///
/// ## Core Mathematical Properties
///
/// - **Uniform Spacing**: All sub-intervals have identical length `δ = domain_length / num_intervals`
/// - **Complete Coverage**: `D = I₀ ∪ I₁ ∪ ... ∪ I_{n-1}` (complete domain coverage)
/// - **Non-Overlapping**: `Iᵢ ∩ Iⱼ = ∅` for `i ≠ j` (disjoint sub-intervals)
/// - **Boundary Matching**: First point equals domain lower bound, last point equals upper bound
///   (value matching only). For open or semi-open domains, those endpoint values
///   are not necessarily contained points of the domain.
/// - **Regularity**: Perfect geometric regularity enables analytical optimizations
/// - **Predictable Access**: Any coordinate can be computed as `p_k = lower + k * δ`
///
/// ## Performance Characteristics vs. Non-Uniform Grids
///
/// | Operation | [`Grid1DUniform`] | [`Grid1DNonUniform`] | Advantage |
/// |-----------|-------------------|----------------------|-----------|
/// | **Construction** | O(n) | O(n) | Equal |
/// | **Memory Storage** | O(n) | O(n) | Equal (both cache coordinates) |
/// | **Point Location** | O(1) analytical | O(log n) binary search | ✅ **Uniform much faster** |
/// | **Interval Access** | O(1) | O(1) | Equal |
/// | **Coordinate Access** | O(1) | O(1) | Equal (both pre-computed) |
/// | **Length Queries** | O(1) cached | O(1) computed | ✅ **Uniform simpler** |
/// | **Cache Efficiency** | Excellent | Good | ✅ **Uniform better** |
///
/// ## Design Philosophy
///
/// ### Performance Through Uniformity
/// - **Analytical Formulas**: Many operations can use closed-form expressions
/// - **Predictable Memory Patterns**: Enables excellent CPU cache utilization
/// - **SIMD Optimization**: Regular patterns are ideal for vectorized operations
/// - **Minimal Branching**: Uniform structure reduces conditional logic
///
/// ### Memory vs. Computation Trade-offs
/// **Current Design (O(n) memory)**:
/// - ✅ **Compatibility**: Same interface as [`Grid1DNonUniform`]
/// - ✅ **Zero computation overhead**: Pre-computed coordinates
/// - ✅ **Simple access patterns**: Direct array indexing
/// - ❌ **Memory overhead**: Stores redundant coordinate data
///
/// **Alternative O(1) Design** (not implemented):
/// - ✅ **Memory efficient**: Only stores `(domain, num_intervals, δ)`
/// - ✅ **Analytical point location**: No binary search needed
/// - ❌ **Computation overhead**: Must compute coordinates on-demand
/// - ❌ **Interface complexity**: Different from non-uniform grids
///
/// ### Integration with other numerical Ecosystem
/// - **Unified Interface**: Implements [`Grid1DTrait`] trait like non-uniform grids
/// - **Trait Compatibility**: Same [`HasDomain1D`] and [`HasCoords1D`] interfaces
/// - **Grid Enum Integration**: Seamlessly works within [`Grid1D`] enum
/// - **Optimization Opportunities**: Specialized methods for uniform-specific operations
///
/// ## Construction and Usage Examples
///
/// ### Basic Construction
/// ```rust
/// use grid1d::{
///     Grid1DUniform, HasCoords1D, HasDomain1D, Grid1DTrait, HasIntervalIdRange,
///     intervals::*,
///     scalars::{NumIntervals, IntervalId},
/// };
/// use std::ops::Deref;
/// use try_create::TryNew;
///
/// // Create uniform grid with 4 intervals
/// let domain = IntervalClosed::new(0.0, 1.0);
/// let num_intervals = NumIntervals::try_new(4).unwrap();
/// let grid = Grid1DUniform::new(domain.clone(), num_intervals);
///
/// // Verify properties
/// assert_eq!(grid.domain(), &domain);
/// assert_eq!(grid.num_intervals().as_ref(), &4);
/// assert_eq!(grid.coords().deref(), &[0.0, 0.25, 0.5, 0.75, 1.0]);
/// assert_eq!(grid.delta_points().as_ref(), &0.25);
/// ```
///
/// ### High-Resolution Grids
/// ```rust
/// use grid1d::{*, intervals::*};
/// use try_create::TryNew;
///
/// // Create high-resolution grid for numerical simulations
/// let domain = IntervalClosed::new(0.0, 10.0);
/// let num_intervals = NumIntervals::try_new(10000).unwrap();
/// let grid = Grid1DUniform::new(domain, num_intervals);
///
/// // Properties
/// assert_eq!(grid.coords().len(), 10001); // n+1 points
/// more_asserts::assert_lt!((*grid.delta_points().as_ref() - 0.001).abs(), 1.0e-15); // Δx = 10.0/10000
///
/// // Efficient operations on large grids
/// let interval_id = grid.find_interval_id_of_point(&0.).unwrap();
/// assert_eq!(interval_id, IntervalId::new(0));
///
/// let interval_id = grid.find_interval_id_of_point(&0.0009).unwrap();
/// assert_eq!(interval_id, IntervalId::new(0));
///
/// let interval_id = grid.find_interval_id_of_point(&0.001).unwrap();
/// assert_eq!(interval_id, IntervalId::new(1)); // p₁ = 0.001 belongs to interval 1 (left-closed)
///
/// let interval_id = grid.find_interval_id_of_point(&0.0015).unwrap();
/// assert_eq!(interval_id, IntervalId::new(1));
///
/// let interval_id = grid.find_interval_id_of_point(&0.002).unwrap();
/// assert_eq!(interval_id, IntervalId::new(2)); // p₂ = 0.002 belongs to interval 2 (left-closed)
///
/// let interval_id = grid.find_interval_id_of_point(&2.537).unwrap();
/// assert_eq!(interval_id, IntervalId::new(2537)); // p₂₅₃₇ = 2.537 belongs to interval 2537 (left-closed)
///
/// let interval_id = grid.find_interval_id_of_point(&9.999).unwrap();
/// assert_eq!(interval_id, IntervalId::new(9999)); // p₉₉₉₉ = 9.999 belongs to interval 9999 (left-closed)
///
/// let interval_id = grid.find_interval_id_of_point(&9.9991).unwrap();
/// assert_eq!(interval_id, IntervalId::new(9999));
///
/// let interval_id = grid.find_interval_id_of_point(&10.000).unwrap();
/// assert_eq!(interval_id, IntervalId::new(9999));
///
/// ```
///
/// ### Different Domain Types
/// ```rust
/// use grid1d::{*, intervals::*, scalars::*};
/// use try_create::TryNew;
///
/// // Closed interval [0, 2π] for Fourier analysis
/// let fourier_domain = IntervalClosed::new(0.0, 2.0 * std::f64::consts::PI);
/// let fourier_grid = Grid1DUniform::new(fourier_domain, NumIntervals::try_new(256).unwrap());
///
/// // Semi-open interval [0, 1) for periodic boundaries
/// let periodic_domain = IntervalLowerClosedUpperOpen::new(0.0, 1.0);
/// let periodic_grid = Grid1DUniform::new(periodic_domain, NumIntervals::try_new(100).unwrap());
///
/// // Different boundary semantics in partition
/// let closed_interval_0 = fourier_grid.interval(&IntervalId::new(0));
/// let periodic_interval_0 = periodic_grid.interval(&IntervalId::new(0));
///
/// // Both have uniform spacing but different boundary conditions
/// let diff_delta_fourier_grid = (fourier_grid.delta_points().clone().into_inner() - 2.0 * std::f64::consts::PI / 256.0).abs();
/// more_asserts::assert_lt!(diff_delta_fourier_grid, 1.0e-15);
///
/// let diff_delta_periodic_grid = (periodic_grid.delta_points().clone().into_inner() - &0.01).abs();
/// more_asserts::assert_lt!(diff_delta_periodic_grid, 1.0e-15);
/// ```
///
/// ### Working with Different Scalar Types
/// ```rust
/// use grid1d::{
///     Grid1DUniform, HasCoords1D,
///     intervals::*,
///     scalars::NumIntervals,
/// };
/// use num_valid::RealNative64StrictFiniteInDebug;
/// use try_create::TryNew;
///
/// type Real = RealNative64StrictFiniteInDebug;
///
/// // Create grid with validated scalar type
/// let domain = IntervalClosed::new(
///     Real::try_new(-1.0).unwrap(),
///     Real::try_new(1.0).unwrap()
/// );
/// let grid = Grid1DUniform::new(domain, NumIntervals::try_new(8).unwrap());
///
/// // All operations work with the validated type
/// assert_eq!(grid.coords().num_points().as_ref(), &9);
/// assert_eq!(grid.delta_points().as_ref(), &Real::try_new(0.25).unwrap());
/// ```
///
/// ## Advanced Usage Patterns
///
/// ### Finite Difference Method Integration
/// ```rust
/// use grid1d::{
///     Grid1DUniform, HasCoords1D, Grid1DTrait,
///     intervals::*,
///     scalars::{NumIntervals, IntervalId},
/// };
/// use try_create::TryNew;
///
/// fn finite_difference_setup(
///     domain: IntervalClosed<f64>,
///     resolution: usize
/// ) -> (Grid1DUniform<IntervalClosed<f64>>, Vec<f64>) {
///     let grid = Grid1DUniform::new(domain, NumIntervals::try_new(resolution).unwrap());
///     
///     // Initialize solution vector
///     let solution = vec![0.0; grid.coords().len()];
///     
///     (grid, solution)
/// }
///
/// // Usage for heat equation on [0, 1]
/// let (grid, mut u) = finite_difference_setup(IntervalClosed::new(0.0, 1.0), 100);
/// let dx = *grid.delta_points().as_ref();
/// let dt = 0.5 * dx * dx; // Stability condition
///
/// // Apply finite difference stencil
/// for i in 1..u.len()-1 {
///     let d2u_dx2 = (u[i-1] - 2.0*u[i] + u[i+1]) / (dx * dx);
///     // Time stepping logic here...
/// }
/// ```
///
/// ### Spectral Method Grid Setup
/// ```rust
/// use grid1d::{
///     Grid1DUniform, HasCoords1D,
///     intervals::*,
///     scalars::NumIntervals,
/// };
/// use try_create::TryNew;
///
/// fn spectral_grid_setup(n_modes: usize) -> Grid1DUniform<IntervalLowerClosedUpperOpen<f64>> {
///     // Periodic domain [0, 2π) for Fourier spectral methods
///     let domain = IntervalLowerClosedUpperOpen::new(0.0, 2.0 * std::f64::consts::PI);
///     Grid1DUniform::new(domain, NumIntervals::try_new(n_modes).unwrap())
/// }
///
/// let spectral_grid = spectral_grid_setup(256);
/// let coords = spectral_grid.coords();
///
/// // Create FFT-ready data
/// let mut function_values: Vec<f64> = coords.iter()
///     .map(|&x| (x.sin() + 0.5 * (2.0 * x).cos()))
///     .collect();
///
/// // Grid spacing is perfect for FFT
/// let dx = *spectral_grid.delta_points().as_ref();
/// assert!((dx - 2.0 * std::f64::consts::PI / 256.0).abs() < 1e-15);
/// ```
///
/// ### Performance-Critical Point Location
/// ```rust
/// use grid1d::{*, intervals::*};
/// use try_create::TryNew;
///
/// let grid = Grid1DUniform::new(
///     IntervalClosed::new(0.0, 100.0),
///     NumIntervals::try_new(10000).unwrap()
/// );
///
/// // Batch point location - O(1) per point for uniform grids
/// let test_points: Vec<f64> = (0..1000).map(|i| i as f64 * 0.1).collect();
/// let start = std::time::Instant::now();
///
/// let interval_ids: Vec<IntervalId> = test_points.iter()
///     .map(|&point| grid.find_interval_id_of_point(&point).unwrap())
///     .collect();
///
/// let elapsed = start.elapsed();
/// println!("Located {} points in {:.2}μs ({:.2}ns per point)",
///          test_points.len(), elapsed.as_micros(), elapsed.as_nanos() as f64 / test_points.len() as f64);
///
/// // For uniform grids, all intervals have the same length
/// for &id in &interval_ids[0..10] {
///     let length_diff = (grid.interval_length(&id).into_inner()  - grid.delta_points().as_ref()).abs();
///     more_asserts::assert_lt!(length_diff, 1.0e-15);
/// }
/// ```
///
/// ### Grid Quality and Analysis
/// ```rust
/// use grid1d::{
///     Grid1DUniform, Grid1DTrait, HasIntervalIdRange, HasDomain1D,
///     intervals::*,
///     scalars::NumIntervals,
/// };
/// use try_create::TryNew;
///
/// let grid = Grid1DUniform::new(
///     IntervalClosed::new(-1.0, 1.0),
///     NumIntervals::try_new(1000).unwrap()
/// );
///
/// // Perfect uniformity properties
/// let min_length = grid.min_interval_length();
/// let max_length = grid.max_interval_length();
/// let uniformity_ratio = grid.uniformity_ratio();
///
/// // For uniform grids, these are always equal
/// assert_eq!(min_length, max_length);
/// assert_eq!(min_length, *grid.delta_points());
/// assert_eq!(uniformity_ratio.as_ref(), &1.0); // Perfect uniformity
///
/// println!("Grid Analysis:");
/// println!("  Domain: [{}, {}]",
///          grid.domain().lower_bound_value(), grid.domain().upper_bound_value());
/// println!("  Intervals: {}", grid.num_intervals().as_ref());
/// println!("  Spacing: {:.6}", grid.delta_points().as_ref());
/// println!("  Uniformity ratio: {:.1} (perfect)", uniformity_ratio.as_ref());
/// ```
///
/// ### Integration with Grid1D Enum
/// ```rust
/// use grid1d::{*, intervals::*};
/// use try_create::TryNew;
///
/// // Grid1DUniform is used internally by Grid1D for uniform cases
/// let domain = IntervalClosed::new(0.0, 10.0);
/// let uniform_grid = Grid1D::uniform(domain.clone(), NumIntervals::try_new(100).unwrap());
///
/// // Grid1D automatically uses Grid1DUniform for uniform spacing
/// match &uniform_grid {
///     Grid1D::Uniform(uniform_partition) => {
///         println!("Using Grid1DUniform with spacing: {:.3}",
///                  uniform_partition.delta_points().as_ref());
///         
///         // Access uniform-specific properties
///         assert_eq!(uniform_partition.delta_points().as_ref(), &0.1);
///         
///         // All standard Grid1DTrait methods work
///         assert_eq!(uniform_partition.uniformity_ratio().as_ref(), &1.0);
///     }
///     Grid1D::NonUniform(_) => {
///         panic!("Expected uniform grid");
///     }
/// }
///
/// // Unified interface works regardless of internal type
/// let point = 5.37;
/// let interval_id = uniform_grid.find_interval_id_of_point(&point).unwrap();
/// let length = uniform_grid.interval_length(&interval_id);
/// println!("Point {} in interval {} with length {:.3}",
///          point, interval_id.as_ref(), length.as_ref());
/// ```
///
/// ### Memory Layout and Performance Optimization
/// ```rust
/// use grid1d::{
///     Grid1DUniform, HasCoords1D,
///     intervals::*,
///     scalars::NumIntervals,
/// };
/// use std::mem;
/// use try_create::TryNew;
///
/// let grid = Grid1DUniform::new(
///     IntervalClosed::new(0.0, 1000.0),
///     NumIntervals::try_new(10000).unwrap()
/// );
///
/// // Memory analysis
/// let coords_size = mem::size_of_val(grid.coords());
/// let delta_size = mem::size_of_val(grid.delta_points());
/// let total_size = mem::size_of_val(&grid);
///
/// println!("Memory breakdown:");
/// println!("  Coordinates: {} bytes", coords_size);
/// println!("  Delta storage: {} bytes", delta_size);
/// println!("  Total grid: {} bytes", total_size);
/// println!("  Overhead: {} bytes", total_size - coords_size);
///
/// // Cache-friendly access patterns
/// let coords = grid.coords().as_ref();
/// let mut sum = 0.0;
///
/// // Sequential access is very cache-friendly for uniform grids
/// for &coord in coords.iter() {
///     sum += coord; // Perfect memory locality
/// }
///
/// let last_coord = coords.last().unwrap();
/// let analytical_sum = coords.len() as f64 * (coords[0] + last_coord) / 2.0;
/// assert!((sum - analytical_sum).abs() < 1e-10);
/// ```
///
/// ## Domain-Specific Behavior
///
/// The [`Grid1DUniform`] works with different domain types, each with specific
/// sub-interval construction rules:
///
/// ### Closed Domain `[a, b]`
/// ```rust
/// use grid1d::{*, intervals::*, scalars::*};
/// use try_create::TryNew;
///
/// let grid = Grid1DUniform::new(
///     IntervalClosed::new(0.0, 3.0),
///     NumIntervals::try_new(3).unwrap()
/// );
///
/// // First interval: [0, 1) (closed on lower bound, open on upper bound)
/// let interval_0 = grid.interval(&IntervalId::new(0));
/// assert!(interval_0.contains_point(&0.0)); // ✓ includes lower bound
/// assert!(!interval_0.contains_point(&1.0)); // ✗ excludes upper bound
///
/// // Middle interval: [1, 2) (closed on lower bound, open on upper bound for middle intervals)
/// let interval_1 = grid.interval(&IntervalId::new(1));
/// assert!(interval_1.contains_point(&1.0)); // ✓ includes left bound
/// assert!(!interval_1.contains_point(&2.0));  // ✗ excludes right bound
///
/// // Last interval: [2, 3] (closed on both ends)
/// let interval_2 = grid.interval(&IntervalId::new(2));
/// assert!(interval_2.contains_point(&2.0)); // ✓ includes left bound
/// assert!(interval_2.contains_point(&3.0));  // ✓ includes right bound
/// ```
///
/// ### Semi-Open Domain `[a, b)`
/// ```rust
/// use grid1d::{*, intervals::*, scalars::*};
/// use try_create::TryNew;
///
/// let grid = Grid1DUniform::new(
///     IntervalLowerClosedUpperOpen::new(0.0, 2.0),
///     NumIntervals::try_new(2).unwrap()
/// );
///
/// // First interval: [0, 1) (closed on lower bound, open on upper bound for first interval)
/// let interval_0 = grid.interval(&IntervalId::new(0));
/// assert!(interval_0.contains_point(&0.0)); // ✓ includes lower bound
/// assert!(!interval_0.contains_point(&1.0)); // ✗ excludes upper bound
///
/// // Last interval: [1, 2) (respects open upper bound of domain)
/// let interval_1 = grid.interval(&IntervalId::new(1));
/// assert!(interval_1.contains_point(&1.0)); // ✓ includes lower bound
/// assert!(!interval_1.contains_point(&2.0)); // ✗ excludes upper bound
/// ```
///
/// ## Specialized Uniform Grid Operations
///
/// ### Optimized Range Queries
/// ```rust
/// use grid1d::{*, intervals::*, scalars::*};
/// use try_create::TryNew;
///
/// let grid = Grid1DUniform::new(
///     IntervalClosed::new(0.0, 10.0),
///     NumIntervals::try_new(1000).unwrap()
/// );
///
/// // For uniform grids, range queries can be analytical
/// fn find_intervals_in_range(
///     grid: &Grid1DUniform<IntervalClosed<f64>>,
///     x_min: f64,
///     x_max: f64
/// ) -> Vec<IntervalId> {
///     let delta = *grid.delta_points().as_ref();
///     let domain_start = *grid.domain().lower_bound_value();
///     
///     // Analytical calculation - O(1) instead of O(log n)
///     let start_interval = ((x_min - domain_start) / delta).floor() as usize;
///     let end_interval = ((x_max - domain_start) / delta).ceil() as usize;
///     
///     let start_clamped = start_interval.min(*grid.num_intervals().as_ref() - 1);
///     let end_clamped = end_interval.min(*grid.num_intervals().as_ref() - 1);
///     
///     (start_clamped..=end_clamped)
///         .map(IntervalId::new)
///         .collect()
/// }
///
/// let range_intervals = find_intervals_in_range(&grid, 2.5, 7.3);
/// println!("Range [2.5, 7.3] spans {} intervals", range_intervals.len());
/// ```
///
/// ### Analytical Derivatives and Integration
/// ```rust
/// use grid1d::{
///     Grid1DUniform, HasCoords1D,
///     intervals::*,
///     scalars::{NumIntervals, CoordId},
/// };
/// use try_create::TryNew;
///
/// let grid = Grid1DUniform::new(
///     IntervalClosed::new(0.0, 1.0),
///     NumIntervals::try_new(100).unwrap()
/// );
///
/// // Function values on the grid
/// let coords = grid.coords();
/// let values: Vec<f64> = coords.iter().map(|&x| x.powi(2)).collect();
///
/// // Analytical integration using trapezoidal rule
/// let dx = *grid.delta_points().as_ref();
/// let integral = dx * (values[0]/2.0 + values.iter().skip(1).take(values.len()-2).sum::<f64>() + values.last().unwrap()/2.0);
/// let analytical = 1.0/3.0; // ∫₀¹ x² dx = 1/3
///
/// println!("Numerical integral: {:.6}", integral);
/// println!("Analytical result: {:.6}", analytical);
/// println!("Error: {:.2e}", (integral - analytical).abs());
///
/// // Finite difference derivatives
/// let mut derivatives = vec![0.0; values.len()];
/// for i in 1..values.len()-1 {
///     derivatives[i] = (values[i+1] - values[i-1]) / (2.0 * dx);
/// }
///
/// // At x=0.5, analytical derivative is 2*0.5 = 1.0
/// let mid_idx = values.len() / 2;
/// let numerical_deriv = derivatives[mid_idx];
/// let analytical_deriv = 2.0 * coords[CoordId::new(mid_idx)];
/// println!("Derivative at x=0.5: numerical={:.6}, analytical={:.6}",
///          numerical_deriv, analytical_deriv);
/// ```
///
/// ## Error Handling and Validation
///
/// ### Construction Validation
/// ```rust
/// use grid1d::{
///     Grid1DTrait, HasIntervalIdRange, Grid1DUniform, HasCoords1D,
///     intervals::*,
///     scalars::NumIntervals,
/// };
/// use try_create::TryNew;
///
/// // Valid construction
/// let domain = IntervalClosed::new(0.0, 1.0);
/// let num_intervals = NumIntervals::try_new(10).unwrap();
/// let grid = Grid1DUniform::new(domain, num_intervals);
///
/// // The constructor doesn't fail for Grid1DUniform since it computes
/// // coordinates analytically, but domain validation happens in the
/// // IntervalClosed construction
/// assert_eq!(grid.coords().len(), 11); // n+1 points
/// assert_eq!(grid.num_intervals().as_ref(), &10);
/// ```
///
/// ### Robust Integration Pattern
/// ```rust
/// use grid1d::{
///     Grid1D, Grid1DUniform, HasCoords1D, Grid1DTrait, HasIntervalIdRange,
///     intervals::*,
///     scalars::NumIntervals,
/// };
/// use try_create::TryNew;
///
/// fn create_simulation_grid(
///     x_min: f64,
///     x_max: f64,
///     target_resolution: f64
/// ) -> Result<Grid1DUniform<IntervalClosed<f64>>, String> {
///     if x_min >= x_max {
///         return Err("Invalid domain: x_min must be less than x_max".to_string());
///     }
///     
///     if target_resolution <= 0.0 {
///         return Err("Invalid resolution: must be positive".to_string());
///     }
///     
///     let domain_length = x_max - x_min;
///     let num_intervals = (domain_length / target_resolution).ceil() as usize;
///     
///     if num_intervals < 1 {
///         return Err("Domain too small for target resolution".to_string());
///     }
///     
///     let domain = IntervalClosed::new(x_min, x_max);
///     let num_intervals = NumIntervals::try_new(num_intervals)
///         .map_err(|e| format!("Invalid number of intervals: {}", e))?;
///     
///     Ok(Grid1DUniform::new(domain, num_intervals))
/// }
///
/// // Usage
/// let grid = create_simulation_grid(0.0, 1.0, 0.01).unwrap();
/// println!("Created grid with {} intervals, actual spacing: {:.6}",
///          grid.num_intervals().as_ref(), grid.delta_points().as_ref());
///
/// // Error cases
/// assert!(create_simulation_grid(1.0, 0.0, 0.01).is_err()); // Invalid domain
/// assert!(create_simulation_grid(0.0, 1.0, -0.01).is_err()); // Invalid resolution
/// ```
///
/// ## Best Practices and Recommendations
///
/// ### When to Use [`Grid1DUniform`]
/// - **Finite difference methods**: Equal spacing required for standard stencils
/// - **Spectral methods**: Uniform grids for Fourier transforms and Chebyshev methods
/// - **Regular sampling**: Data collection or function evaluation at uniform intervals
/// - **Performance-critical applications**: When O(1) point location is essential
/// - **Memory-constrained systems**: When uniform spacing allows analytical computation
/// - **Simple problems**: When uniform resolution is sufficient across the domain
///
/// ### When to Use [`Grid1DNonUniform`] Instead
/// - **Adaptive mesh refinement**: Variable resolution based on solution gradients
/// - **Boundary layers**: High resolution near walls or interfaces
/// - **Multi-scale problems**: Different length scales in the same domain
/// - **Complex geometries**: Non-uniform point distributions for irregular shapes
/// - **Error-based refinement**: Points placed based on error indicators
/// - **Shock capturing**: Concentrated points near discontinuities
///
/// ## Mathematical Properties and Guarantees
///
/// The [`Grid1DUniform`] struct maintains these mathematical properties:
///
/// ### Uniform Spacing Property
/// ```text
/// ∀i ∈ [0, n-1]: length(Iᵢ) = δ = domain_length / n
/// ```
/// All sub-intervals have exactly the same length.
///
/// ### Perfect Regularity
/// ```text
/// ∀i ∈ [0, n]: pᵢ = lower_bound + i * δ
/// ```
/// Coordinates follow a perfect arithmetic progression.
///
/// ### Optimal Uniformity
/// ```text
/// uniformity_ratio = max_length / min_length = 1.0
/// ```
/// The uniformity ratio is always exactly 1.0.
///
/// ### Boundary Consistency
/// ```text
/// p₀ = domain.lower_bound ∧ pₙ = domain.upper_bound
/// ```
/// First and last points exactly match domain boundaries.
///
/// ### Analytical Predictability
/// ```text
/// point_location(x) = floor((x - lower_bound) / δ)  [O(1) operation]
/// ```
/// Point location can be computed analytically without search.
///
/// ### Cache Efficiency
/// ```text
/// memory_pattern = contiguous_array[n+1]  [optimal for CPU cache]
/// ```
/// Coordinates are stored in a contiguous array for maximum cache efficiency.
///
/// These properties make [`Grid1DUniform`] ideal for numerical methods that benefit
/// from regular spacing and predictable access patterns.
///
/// ## See Also
///
/// - [`Grid1DNonUniform`]: Variable spacing alternative for adaptive applications
/// - [`Grid1D`]: Unified interface supporting both uniform and non-uniform partitions
/// - [`Grid1DTrait`]: Core trait providing partition operations
/// - [`Coords1D`]: Underlying coordinate container
/// - [`HasDomain1D`], [`HasCoords1D`]: Core domain access traits
/// - [`NumIntervals`]: Type for specifying the number of intervals
/// - [`PositiveRealScalar`]: Type for the uniform spacing value (`delta_points`)
#[derive(Debug, Clone, Getters, PartialEq, Serialize, Deserialize)]
#[serde(bound(deserialize = "Domain1D: for<'d> serde::Deserialize<'d>, \
                  Domain1D::RealType: for<'d> serde::Deserialize<'d>"))]
pub struct Grid1DUniform<Domain1D: IntervalFinitePositiveLengthTrait> {
    /// The points that defines the partition of the domain.
    coords: Coords1D<Domain1D::RealType>,

    /// Domain covered by the grid.
    domain: Domain1D,

    /// The index spaces associated with the grid, which define the topology and interval indexing.
    index_spaces: Grid1DIndexSpaces,

    /// The distance between two consecutive points (i.e. the length of the interval defined by two consecutive points).
    #[getset(get = "pub")]
    delta_points: PositiveRealScalar<Domain1D::RealType>,
}

fn compute_delta_points<Domain1D: IntervalFinitePositiveLengthTrait>(
    domain: &Domain1D,
    num_intervals: &NumIntervals,
) -> PositiveRealScalar<Domain1D::RealType> {
    let n_intervals = *num_intervals.as_ref();

    PositiveRealScalar::try_new(
        domain.length().into_inner()
            * Domain1D::RealType::try_from_f64(n_intervals as f64)
                .unwrap()
                .try_reciprocal()
                .unwrap(),
    )
    .expect("Delta points must be positive!")
}

impl<Domain1D: IntervalFinitePositiveLengthTrait> Grid1DUniform<Domain1D> {
    /// Creates a non-periodic uniform grid on a real-line topology.
    ///
    /// # Parameters
    ///
    /// - `domain`: Bounded interval domain to partition.
    /// - `num_intervals`: Number of equal sub-intervals.
    ///
    /// # Returns
    ///
    /// A [`Grid1DUniform`] with [`Topology1D::RealLine`].
    #[must_use]
    pub fn new(domain: Domain1D, num_intervals: NumIntervals) -> Self {
        let delta_points = compute_delta_points(&domain, &num_intervals);

        let coords = Coords1D::new_uniform(&domain, &num_intervals);

        let index_spaces = Grid1DIndexSpaces::new_non_periodic(num_intervals);

        Self {
            coords,
            domain,
            delta_points,
            index_spaces,
        }
    }
}

impl<Domain1D> Grid1DUniform<Domain1D>
where
    Domain1D: IntervalFinitePositiveLengthTrait + SupportsCircularTopology,
{
    /// Creates a periodic uniform grid with circular topology.
    ///
    /// This constructor is available only for domain interval types that support
    /// circular topology (currently half-open bounded intervals).
    ///
    /// # Parameters
    ///
    /// - `domain`: Bounded interval domain to partition.
    /// - `num_intervals`: Number of equal sub-intervals.
    ///
    /// # Returns
    ///
    /// A [`Grid1DUniform`] with [`Topology1D::Circle`].
    #[must_use]
    pub fn new_periodic(domain: Domain1D, num_intervals: NumIntervals) -> Self {
        let delta_points = compute_delta_points(&domain, &num_intervals);

        let coords = Coords1D::new_uniform(&domain, &num_intervals);

        let index_spaces = if domain.is_lower_bound_open() {
            Grid1DIndexSpaces::new_periodic_lower_open_interval(num_intervals)
        } else {
            Grid1DIndexSpaces::new_periodic_upper_open_interval(num_intervals)
        };

        Self {
            coords,
            domain,
            delta_points,
            index_spaces,
        }
    }
}

impl<Domain1D: IntervalFinitePositiveLengthTrait> HasDomain1D for Grid1DUniform<Domain1D> {
    type Domain1D = Domain1D;

    #[inline(always)]
    fn domain(&self) -> &Domain1D {
        &self.domain
    }
}

impl<Domain1D: IntervalFinitePositiveLengthTrait> HasCoords1D for Grid1DUniform<Domain1D> {
    type CoordType = Domain1D::RealType;

    /// Get the coordinates of the 1D points.
    ///
    /// # Note
    /// The returned values does not contain duplicates and are sorted in ascending order.
    #[inline(always)]
    fn coords(&self) -> &Coords1D<Self::CoordType> {
        &self.coords
    }
}

impl<Domain1D: Grid1DIntervalBuilder> FindIntervalIdOfPoint for Grid1DUniform<Domain1D> {
    type Point1DType = Domain1D::RealType;

    /// Optimized O(1) point location for uniform grids.
    ///
    /// This implementation leverages the uniform spacing to compute the interval ID analytically,
    /// while ensuring consistency with the boundary point assignment rules defined by the
    /// [`Grid1DTrait`] trait.
    ///
    /// # Boundary Point Assignment Rules
    ///
    /// - **Interior partition points**: For left-closed sub-intervals (`[a,b]` and `[a,b)` domains),
    ///   `pₖ` belongs to the **right** interval; for right-closed sub-intervals, to the **left** interval.
    /// - **Domain lower bound**: Belongs to the first interval (ID 0)
    /// - **Domain upper bound**: Belongs to the last interval (ID n-1)
    ///
    /// # Example
    /// ```rust
    /// use grid1d::{*, intervals::*};
    /// use try_create::TryNew;
    ///
    /// let grid = Grid1DUniform::new(
    ///     IntervalClosed::new(0.0, 2.0),
    ///     NumIntervals::try_new(2).unwrap()
    /// );
    /// // Grid points: [0.0, 1.0, 2.0]
    /// // Intervals: [0.0, 1.0), [1.0, 2.0]  (left-closed for [a,b] domain)
    ///
    /// assert_eq!(grid.find_interval_id_of_point(&0.0).unwrap(), IntervalId::new(0)); // Domain lower bound
    /// assert_eq!(grid.find_interval_id_of_point(&0.5).unwrap(), IntervalId::new(0)); // Interior point
    /// assert_eq!(grid.find_interval_id_of_point(&1.0).unwrap(), IntervalId::new(1)); // p₁ → right interval (left-closed)
    /// assert_eq!(grid.find_interval_id_of_point(&1.5).unwrap(), IntervalId::new(1)); // Interior point
    /// assert_eq!(grid.find_interval_id_of_point(&2.0).unwrap(), IntervalId::new(1)); // Domain upper bound
    /// ```
    fn find_interval_id_of_point(&self, x: &Self::Point1DType) -> Option<IntervalId> {
        let domain = self.domain();

        if !domain.contains_point(x) {
            return None;
        }

        let num_intervals = *self.num_intervals().as_ref();
        // Check if x is exactly equal to any grid coordinate
        match self.coords().find_index(x) {
            Some(coord_id) => {
                let coord_id = coord_id.into_inner();

                // Exact match with a grid point
                if coord_id == 0 {
                    // This corresponds to the domain lower bound
                    Some(IntervalId::new(0))
                } else if coord_id == num_intervals {
                    // This corresponds to the domain upper bound
                    Some(IntervalId::new(num_intervals - 1))
                } else {
                    // Here we use the domain's lower bound closure property to determine the assignment of interior partition points.
                    // This is because the domain type dictates the sub-interval construction rules, which in turn determine how boundary points are assigned to intervals.
                    // For example:
                    // - For a closed domain [a, b], all sub-intervals are left-closed, so interior points belong to the right interval.
                    // - For a half-open domain (a, b], all sub-intervals are right-closed, so interior points belong to the left interval.
                    // - For a half-open domain [a, b), the first interval is left-closed and the last interval is open, so interior points belong to the right interval.
                    // - For a open domain (a, b), all sub-intervals are open, so interior points do not belong to any interval, but since we are checking for exact matches with grid points, we can still assign them based on the closure of the lower bound.
                    // This logic ensures that the point location is consistent with the interval construction rules defined by the domain type, while still leveraging the uniform spacing for O(1) access.
                    // The key point is that the domain's lower bound closure property directly informs how we assign interior partition points to intervals, which is crucial for maintaining the correct semantics of the partitioning.
                    if self.domain().is_lower_bound_closed() {
                        Some(IntervalId::new(coord_id))
                    } else {
                        Some(IntervalId::new(coord_id - 1))
                    }
                }
            }
            None => {
                // No exact match, so x lies strictly within an interval

                // Compute the analytical interval index
                let domain_start = domain.lower_bound_value();
                let delta = self.delta_points.as_ref();
                let offset = x.clone() - domain_start;
                let offset_div_delta = offset / delta;

                // Convert to usize and clamp to valid range
                let index = offset_div_delta
                    .kernel_floor()
                    .truncate_to_usize()
                    .unwrap()
                    .min(num_intervals - 1);

                Some(IntervalId::new(index))
            }
        }
    }
}

impl<Domain1D: Grid1DIntervalBuilder> HasIntervalIdRange for Grid1DUniform<Domain1D> {
    #[inline(always)]
    fn first_interval_id(&self) -> IntervalId {
        self.index_spaces.interval_index_space().first_interval_id()
    }

    #[inline(always)]
    fn last_interval_id(&self) -> IntervalId {
        self.index_spaces.interval_index_space().last_interval_id()
    }
}

impl<Domain1D: Grid1DIntervalBuilder> HasCoordIdRange for Grid1DUniform<Domain1D> {
    #[inline(always)]
    fn first_coord_id(&self) -> CoordId {
        self.index_spaces.coord_index_space().first_coord_id()
    }

    #[inline(always)]
    fn last_coord_id(&self) -> CoordId {
        self.index_spaces.coord_index_space().last_coord_id()
    }
}

impl<Domain1D: Grid1DIntervalBuilder> Grid1DTrait for Grid1DUniform<Domain1D> {
    #[inline(always)]
    fn index_spaces(&self) -> &Grid1DIndexSpaces {
        &self.index_spaces
    }

    /// Returns the maximum interval length in the partition.
    ///
    /// # Example
    ///
    /// ```rust
    /// use grid1d::{*, intervals::*, scalars::*};
    /// use sorted_vec::partial::SortedSet;
    ///
    /// let coords = SortedSet::from_unsorted(vec![0.0, 1.0, 1.5, 3.0]);
    /// let grid = Grid1D::<IntervalClosed<f64>>::try_from_sorted(coords).unwrap();
    /// let max_length = grid.max_interval_length();
    /// assert_eq!(max_length.as_ref(), &1.5); // Interval [1.5, 3.0] has length 1.5
    /// ```
    #[inline(always)]
    fn max_interval_length(&self) -> PositiveRealScalar<Self::Point1DType> {
        self.delta_points.clone()
    }

    /// Returns the minimum interval length in the partition.
    ///
    /// # Example
    ///
    /// ```rust
    /// use grid1d::{*, intervals::*, scalars::*};
    /// use sorted_vec::partial::SortedSet;
    ///
    /// let coords = SortedSet::from_unsorted(vec![0.0, 1.0, 1.5, 3.0]);
    /// let grid = Grid1D::<IntervalClosed<f64>>::try_from_sorted(coords).unwrap();
    /// let min_length = grid.min_interval_length();
    /// assert_eq!(min_length.as_ref(), &0.5); // Interval [1.0, 1.5] has length 0.5
    /// ```
    #[inline(always)]
    fn min_interval_length(&self) -> PositiveRealScalar<Self::Point1DType> {
        self.delta_points.clone()
    }

    type UniformlyRefinedGrid1DType = Self;

    fn refine_uniform(
        self,
        num_extra_points_each_interval: &PositiveNumPoints1D,
    ) -> Grid1DUniformRefinement<Self> {
        let num_old_intervals = *self.num_intervals().as_ref();
        let num_sub_intervals = *num_extra_points_each_interval.as_ref() + 1;
        let num_new_intervals = num_old_intervals * num_sub_intervals;

        let refined_grid = Grid1DUniform::new(
            self.domain.clone(),
            NumIntervals::try_new(num_new_intervals).unwrap(),
        );

        // Maps each interval in the refined grid to the corresponding interval in the original grid.
        let mut refined_to_original_interval_mapping: Vec<IntervalId> =
            Vec::with_capacity(num_new_intervals);

        // Maps each interval in the original grid to the corresponding intervals in the refined grid.
        let mut original_to_refined_interval_mapping: Vec<Vec<IntervalId>> =
            Vec::with_capacity(num_old_intervals);

        let mut refined_id = 0;
        for original_id in 0..num_old_intervals {
            refined_to_original_interval_mapping.resize(
                refined_to_original_interval_mapping.len() + num_sub_intervals,
                IntervalId::new(original_id),
            );

            original_to_refined_interval_mapping.push(
                (refined_id..refined_id + num_sub_intervals)
                    .map(IntervalId::new)
                    .collect(),
            );

            refined_id += num_sub_intervals;
        }

        Grid1DUniformRefinement::new(
            refined_grid,
            self,
            refined_to_original_interval_mapping,
            original_to_refined_interval_mapping,
        )
    }

    fn refine(
        self,
        intervals_to_refine: &std::collections::BTreeMap<IntervalId, PositiveNumPoints1D>,
    ) -> Grid1DNonUniformRefinement<Self> {
        build_non_uniform_grid_refinement(self, intervals_to_refine)
    }
}
//-------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------------------------------------
/// An enum representing a one-dimensional grid, which defines a partition of a bounded interval with positive length.
///
/// The [`Grid1D`] enum models a set of points that partition a bounded interval into adjacent, non-overlapping subintervals.
/// It supports both ***uniform grids***, where all subintervals have the same length, and ***non-uniform grids***, where
/// subintervals can have varying lengths.
///
/// # Type Parameters
///
/// - `Point1DType`: The type of the points in the grid. It must implement the [`RealScalar`] trait, ensuring that the
///   points are real numbers with additional mathematical properties.
///
/// # Variants
///
/// - `Uniform`: Represents a grid where all subintervals have the same length. This is modeled by the
///   [`Grid1DUniform`] struct.
/// - `NonUniform`: Represents a grid where subintervals can have varying lengths. This is modeled by the
///   [`Grid1DNonUniform`] struct.
///
/// # Features
///
/// - **Uniform Grids**: All subintervals have the same length, making them suitable for evenly spaced computations.
/// - **Non-Uniform Grids**: Subintervals can have varying lengths, allowing for more flexibility in grid design.
/// - **Integration with Grid1DTrait**: The [`Grid1D`] enum implements the [`Grid1DTrait`] trait, providing
///   methods for accessing intervals and performing operations on the grid.
///
/// # Examples
///
/// ## Creating a Uniform Grid
///
/// ```rust
/// use grid1d::{
///     Grid1D, HasCoords1D, Grid1DTrait, HasIntervalIdRange,
///     intervals::*,
///     scalars::NumIntervals,
/// };
/// use std::ops::Deref;
/// use try_create::TryNew;
///
/// let domain = IntervalClosed::new(0.0, 1.0);
/// let grid = Grid1D::uniform(domain, NumIntervals::try_new(4).unwrap());
///
/// assert_eq!(grid.coords().deref(), &[0.0, 0.25, 0.5, 0.75, 1.0]);
/// assert_eq!(grid.num_intervals().as_ref(), &4);
/// ```
///
/// ## Creating a Non-Uniform Grid
///
/// ```rust
/// use grid1d::{
///     Coords1D, Grid1D, HasCoords1D,
///     intervals::*,
/// };
/// use sorted_vec::partial::SortedSet;
/// use std::ops::Deref;
///
/// let coords = SortedSet::from_unsorted(vec![0.0, 0.5, 1.0, 2.0]);
/// let grid = Grid1D::<IntervalClosed<f64>>::try_from_sorted(coords).unwrap();
/// assert_eq!(grid.coords().deref(), &[0.0, 0.5, 1.0, 2.0]);
/// ```
///
/// ## Handling Errors
///
/// ```rust
/// use grid1d::{
///     Grid1D, ErrorsGrid1D,
///     intervals::*,
/// };
/// use sorted_vec::partial::SortedSet;
///
/// let coords = SortedSet::from_unsorted(vec![0.0]); // Only one point provided
/// let err = Grid1D::<IntervalClosed<f64>>::try_from_sorted(coords).unwrap_err();
/// assert!(matches!(err, ErrorsGrid1D::RequiredAtLeastTwoDistinctPoints { .. }), "{:?}", err);
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(bound(deserialize = "Domain1D: for<'d> serde::Deserialize<'d>, \
                  Domain1D::RealType: for<'d> serde::Deserialize<'d>"))]
pub enum Grid1D<Domain1D: IntervalFinitePositiveLengthTrait> {
    /// All the intervals defined by the [`Grid1D`] object have the same length.
    Uniform(Grid1DUniform<Domain1D>),

    /// The intervals defined by the [`Grid1D`] object have not the same length.
    NonUniform(Grid1DNonUniform<Domain1D>),
}

impl<Domain1D: IntervalFinitePositiveLengthTrait> Grid1D<Domain1D> {
    /// Creates a new uniform grid over the specified domain with the given number of intervals.
    ///
    /// # Parameters
    ///
    /// - `domain`: The bounded interval over which the grid is defined.
    /// - `num_intervals`: The number of subintervals in the grid.
    ///
    /// # Returns
    ///
    /// A [`Grid1D`] instance representing a uniform grid.
    ///
    /// # Example
    ///
    /// ```rust
    /// use grid1d::{
    ///     Grid1D, HasCoords1D, Grid1DTrait,
    ///     intervals::*,
    ///     scalars::NumIntervals,
    /// };
    /// use std::ops::Deref;
    /// use try_create::TryNew;
    ///
    /// let domain = IntervalClosed::new(0., 1.);
    /// let grid = Grid1D::uniform(domain, NumIntervals::try_new(4).unwrap());
    ///
    /// assert_eq!(grid.coords().deref(), &[0., 0.25, 0.5, 0.75, 1.]);
    /// ```
    #[must_use]
    pub fn uniform(domain: Domain1D, num_intervals: NumIntervals) -> Self {
        Grid1D::Uniform(Grid1DUniform::new(domain, num_intervals))
    }

    /// Creates a new grid from a sorted set of points (at least 2).
    ///
    /// # Parameters
    ///
    /// - `values`: A sorted set of points defining the grid.
    ///
    /// # Returns
    ///
    /// - `Ok(Self)`: If at least two points are provided.
    /// - [`Err<ErrorsGrid1D>`]: If fewer than two points are provided.
    ///
    /// # Errors
    ///
    /// - Returns [`ErrorsGrid1D::RequiredAtLeastTwoDistinctPoints`] if fewer than two points are provided.
    ///
    /// # Example
    ///
    /// ```rust
    /// use grid1d::{
    ///     Grid1D, HasCoords1D,
    ///     intervals::*,
    /// };
    /// use sorted_vec::partial::SortedSet;
    /// use std::ops::Deref;
    ///
    /// let coords = SortedSet::from_unsorted(vec![0., 0.5, 1., 2.]);
    /// let grid = Grid1D::<IntervalClosed<f64>>::try_from_sorted(coords).unwrap();
    /// assert_eq!(grid.coords().deref(), &[0., 0.5, 1., 2.]);
    /// ```
    pub fn try_from_sorted(
        values: SortedSet<Domain1D::RealType>,
    ) -> Result<Self, ErrorsGrid1D<Domain1D>>
    where
        Domain1D: IntervalFromBounds,
    {
        Self::try_from_coords(Coords1D::try_from(values)?)
    }

    /// Creates a new grid from a domain and pre-validated coordinates.
    ///
    /// This is a more efficient constructor when you already have a [`Coords1D`]
    /// object, avoiding redundant validation.
    pub fn try_from_coords(
        coords: Coords1D<Domain1D::RealType>,
    ) -> Result<Self, ErrorsGrid1D<Domain1D>>
    where
        Domain1D: IntervalFromBounds,
    {
        let num_coords = coords.num_points();
        if *num_coords.as_ref() < 2 {
            return Err(ErrorsGrid1D::RequiredAtLeastTwoDistinctPoints {
                num_points_provided: num_coords,
                backtrace: capture_backtrace(),
            });
        }

        let domain = Domain1D::try_new(coords.first().clone(), coords.last().clone())?;

        Self::try_new(domain, coords)
    }

    /// Creates a new [`Grid1D`] from an explicit domain and pre-validated coordinates.
    ///
    /// Validates that the coordinates are consistent with the domain (first and last
    /// coordinate must match the domain bounds, and at least two distinct points must
    /// be present). Prefer [`Grid1D::try_from_sorted`] or [`Grid1D::try_from_coords`]
    /// when the domain can be inferred automatically.
    pub fn try_new(
        domain: Domain1D,
        coords: Coords1D<Domain1D::RealType>,
    ) -> Result<Self, ErrorsGrid1D<Domain1D>> {
        let num_intervals = validate_coords_in_domain_closure(&coords, &domain)?;

        let n_pts = coords.num_points();

        // In order to build a NumIntervals object, we need at least 2 distinct points
        if n_pts.as_ref() < &2 {
            return Err(ErrorsGrid1D::RequiredAtLeastTwoDistinctPoints {
                num_points_provided: n_pts,
                backtrace: capture_backtrace(),
            });
        }
        let n_pts = n_pts.into_inner();

        // Check if the coordinates are uniform
        let coords_slice = coords.as_ref();
        let length_first_interval = coords_slice[1].clone() - &coords_slice[0];

        // Use a small absolute tolerance for cases where interval lengths are near zero.
        let rel_tol = RelativeTolerance::epsilon();

        let is_uniform = (2..n_pts).all(|i| {
            let length_current_interval = coords_slice[i].clone() - &coords_slice[i - 1];
            approx_eq(&length_current_interval, &length_first_interval, &rel_tol)
        });

        if is_uniform {
            Ok(Grid1D::Uniform(Grid1DUniform::new(domain, num_intervals)))
        } else {
            let index_spaces = Grid1DIndexSpaces::new_non_periodic(num_intervals);

            let grid1d = Grid1DNonUniform {
                domain,
                coords,
                index_spaces,
            };

            Ok(Grid1D::NonUniform(grid1d))
        }
    }
}

/// **INTERNAL** Checks approximate equality using relative tolerance.
///
/// This function determines if two real numbers are approximately equal by comparing
/// their relative difference to a specified tolerance. It's used internally to
/// detect uniform spacing in coordinate arrays.
///
/// ## Mathematical Definition
/// Two numbers `a` and `b` are considered approximately equal if:
/// ```text
/// |a - b| ≤ max(|a|, |b|) * relative_tolerance
/// ```
///
/// ## Parameters
/// - `a`: First value to compare
/// - `b`: Second value to compare  
/// - `rel_tol`: Relative tolerance for the comparison
///
/// ## Returns
/// `true` if the values are approximately equal within the specified tolerance.
///
/// ## Use Cases
/// - **Uniform grid detection**: Checking if intervals have consistent spacing
/// - **Numerical comparison**: Handling floating-point precision issues
/// - **Grid classification**: Determining if a grid should be treated as uniform
fn approx_eq<T: RealScalar>(a: &T, b: &T, rel_tol: &RelativeTolerance<T>) -> bool {
    let diff = (a.clone() - b).abs();

    // Use the max of the absolute values for the relative comparison
    let abs_a = a.clone().abs();
    let abs_b = b.clone().abs();
    let max_abs = abs_a.max_by_ref(&abs_b).clone();
    diff <= max_abs * rel_tol.as_ref()
}

impl<Domain1D: IntervalFinitePositiveLengthTrait> HasDomain1D for Grid1D<Domain1D> {
    type Domain1D = Domain1D;

    #[inline]
    fn domain(&self) -> &Domain1D {
        match self {
            Grid1D::Uniform(pts) => pts.domain(),
            Grid1D::NonUniform(pts) => pts.domain(),
        }
    }
}

impl<Domain1D: IntervalFinitePositiveLengthTrait> HasCoords1D for Grid1D<Domain1D> {
    type CoordType = Domain1D::RealType;

    #[inline]
    fn coords(&self) -> &Coords1D<Self::CoordType> {
        match self {
            Grid1D::Uniform(pts) => pts.coords(),
            Grid1D::NonUniform(pts) => pts.coords(),
        }
    }
}

impl<Domain1D: Grid1DIntervalBuilder> FindIntervalIdOfPoint for Grid1D<Domain1D> {
    type Point1DType = Domain1D::RealType;

    /// Dispatches to the inner grid's point-location method.
    ///
    /// For the [`Grid1D::Uniform`] variant this resolves to the O(1) analytical
    /// override defined on [`Grid1DUniform`]; for [`Grid1D::NonUniform`] it uses
    /// the default O(log n) binary-search implementation.
    fn find_interval_id_of_point(&self, x: &Self::Point1DType) -> Option<IntervalId> {
        match self {
            Grid1D::Uniform(grid) => grid.find_interval_id_of_point(x),
            Grid1D::NonUniform(grid) => grid.find_interval_id_of_point(x),
        }
    }
}

impl<Domain1D: Grid1DIntervalBuilder> HasIntervalIdRange for Grid1D<Domain1D> {
    #[inline]
    fn first_interval_id(&self) -> IntervalId {
        match self {
            Grid1D::Uniform(grid) => grid.first_interval_id(),
            Grid1D::NonUniform(grid) => grid.first_interval_id(),
        }
    }

    #[inline]
    fn last_interval_id(&self) -> IntervalId {
        match self {
            Grid1D::Uniform(grid) => grid.last_interval_id(),
            Grid1D::NonUniform(grid) => grid.last_interval_id(),
        }
    }
}

impl<Domain1D: Grid1DIntervalBuilder> HasCoordIdRange for Grid1D<Domain1D> {
    #[inline]
    fn first_coord_id(&self) -> CoordId {
        match self {
            Grid1D::Uniform(grid) => grid.first_coord_id(),
            Grid1D::NonUniform(grid) => grid.first_coord_id(),
        }
    }

    #[inline]
    fn last_coord_id(&self) -> CoordId {
        match self {
            Grid1D::Uniform(grid) => grid.last_coord_id(),
            Grid1D::NonUniform(grid) => grid.last_coord_id(),
        }
    }
}

impl<Domain1D: Grid1DIntervalBuilder> Grid1DTrait for Grid1D<Domain1D> {
    #[inline]
    fn index_spaces(&self) -> &Grid1DIndexSpaces {
        match self {
            Grid1D::Uniform(grid) => grid.index_spaces(),
            Grid1D::NonUniform(grid) => grid.index_spaces(),
        }
    }

    type UniformlyRefinedGrid1DType = Self;

    fn refine_uniform(
        self,
        num_extra_points_each_interval: &PositiveNumPoints1D,
    ) -> Grid1DUniformRefinement<Self> {
        match self {
            Grid1D::Uniform(grid_uniform) => grid_uniform
                .refine_uniform(num_extra_points_each_interval)
                .into(),
            Grid1D::NonUniform(grid_non_uniform) => grid_non_uniform
                .refine_uniform(num_extra_points_each_interval)
                .into(),
        }
    }

    fn refine(
        self,
        intervals_to_refine: &std::collections::BTreeMap<IntervalId, PositiveNumPoints1D>,
    ) -> Grid1DNonUniformRefinement<Self> {
        match self {
            Grid1D::Uniform(grid_uniform) => grid_uniform.refine(intervals_to_refine).into(),
            Grid1D::NonUniform(grid_non_uniform) => {
                grid_non_uniform.refine(intervals_to_refine).into()
            }
        }
    }
}

// ============================================================================
// From trait implementations for Grid1D enum
// ============================================================================

/// Converts a [`Grid1DUniform`] into a [`Grid1D`] enum variant.
///
/// This allows seamless use of uniform grids in contexts expecting
/// the unified [`Grid1D`] interface.
///
/// # Example
///
/// ```rust
/// use grid1d::{Grid1D, Grid1DUniform, intervals::*, scalars::NumIntervals};
/// use try_create::TryNew;
///
/// let domain = IntervalClosed::new(0.0, 1.0);
/// let uniform_grid = Grid1DUniform::new(domain, NumIntervals::try_new(10).unwrap());
///
/// // Using From::from
/// let grid: Grid1D<IntervalClosed<f64>> = Grid1D::from(uniform_grid.clone());
///
/// // Using .into()
/// let grid: Grid1D<IntervalClosed<f64>> = uniform_grid.into();
/// ```
impl<Domain1D: IntervalFinitePositiveLengthTrait> From<Grid1DUniform<Domain1D>>
    for Grid1D<Domain1D>
{
    fn from(grid: Grid1DUniform<Domain1D>) -> Self {
        Grid1D::Uniform(grid)
    }
}

/// Converts a [`Grid1DNonUniform`] into a [`Grid1D`] enum variant.
///
/// This allows seamless use of non-uniform grids in contexts expecting
/// the unified [`Grid1D`] interface.
///
/// # Example
///
/// ```rust
/// use grid1d::{Grid1D, Grid1DNonUniform, coords::Coords1D, intervals::*};
/// use sorted_vec::partial::SortedSet;
///
/// let coords = Coords1D::try_from(SortedSet::from_unsorted(vec![0.0, 0.3, 0.7, 1.0])).unwrap();
/// let non_uniform_grid = Grid1DNonUniform::<IntervalClosed<f64>>::try_new_from_coords(coords).unwrap();
///
/// // Using From::from
/// let grid: Grid1D<IntervalClosed<f64>> = Grid1D::from(non_uniform_grid.clone());
///
/// // Using .into()
/// let grid: Grid1D<IntervalClosed<f64>> = non_uniform_grid.into();
/// ```
impl<Domain1D: IntervalFinitePositiveLengthTrait> From<Grid1DNonUniform<Domain1D>>
    for Grid1D<Domain1D>
{
    fn from(grid: Grid1DNonUniform<Domain1D>) -> Self {
        Grid1D::NonUniform(grid)
    }
}
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
#[cfg(test)]
mod tests {
    use crate::{coords::*, grids::*, intervals::*, *};
    use std::ops::Deref;

    #[cfg(feature = "rug")]
    use num_valid::vec_f64_into_vec_real;

    mod native64_strict_finite {
        use super::*;
        use num_valid::RealNative64StrictFinite;

        type Real = RealNative64StrictFinite;

        mod grid1d {

            use super::*;

            #[test]
            fn test_grid1d_uniform_creation() {
                let domain =
                    IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(1.0).unwrap());
                let grid = Grid1D::uniform(domain.clone(), NumIntervals::try_new(4).unwrap());

                assert_eq!(grid.domain(), &domain);
                assert_eq!(
                    grid.coords().deref(),
                    &[
                        Real::try_new(0.0).unwrap(),
                        Real::try_new(0.25).unwrap(),
                        Real::try_new(0.5).unwrap(),
                        Real::try_new(0.75).unwrap(),
                        Real::try_new(1.0).unwrap()
                    ]
                );
            }

            #[test]
            fn test_grid1d_non_uniform_creation() {
                let coords = SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(0.5).unwrap(),
                    Real::try_new(1.0).unwrap(),
                    Real::try_new(2.0).unwrap(),
                ]);
                let grid = Grid1D::<IntervalClosed<Real>>::try_from_sorted(coords.clone()).unwrap();

                assert_eq!(grid.coords().deref(), &coords.to_vec());
            }

            #[test]
            fn test_grid1d_insufficient_points() {
                let coords = SortedSet::from_unsorted(vec![Real::try_new(0.0).unwrap()]);
                let grid = Grid1D::<IntervalClosed<Real>>::try_from_sorted(coords);
                matches!(
                    grid,
                    Err(ErrorsGrid1D::RequiredAtLeastTwoDistinctPoints { .. })
                );
            }

            #[test]
            fn grid1d_01() {
                let v = SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(1.0).unwrap(),
                ]);
                let grid1d = Grid1D::<IntervalClosed<Real>>::try_from_sorted(v.clone()).unwrap();
                assert_eq!(grid1d.coords().deref(), &v.to_vec());
            }

            #[test]
            fn interval_01() {
                let v = SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(1.0).unwrap(),
                ]);

                let grid1d = Grid1D::<IntervalClosed<Real>>::try_from_sorted(v.clone()).unwrap();

                let interval = grid1d.interval(&IntervalId::new(0));

                match interval {
                    SubIntervalInPartition::Single(interval) => {
                        assert_eq!(
                            TryInto::<IntervalClosed<Real>>::try_into(interval).unwrap(),
                            IntervalClosed::new(
                                Real::try_new(0.0).unwrap(),
                                Real::try_new(1.0).unwrap()
                            )
                        );
                    }
                    _ => {
                        panic!("There should be only one interval")
                    }
                }
            }

            #[test]
            #[cfg(debug_assertions)]
            #[should_panic]
            fn interval_02() {
                let v = SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(1.0).unwrap(),
                ]);
                let grid1d = Grid1D::<IntervalClosed<Real>>::try_from_sorted(v.clone()).unwrap();
                let _interval = grid1d.interval(&IntervalId::new(1));
            }

            #[test]
            fn find_interval_id_01() {
                let v = SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(1.0).unwrap(),
                    Real::try_new(2.0).unwrap(),
                    Real::try_new(3.0).unwrap(),
                ]);
                let grid1d = Grid1D::<IntervalClosed<Real>>::try_from_sorted(v.clone()).unwrap();

                let i0 = grid1d
                    .find_interval_id_of_point(&Real::try_new(0.0).unwrap())
                    .unwrap();
                assert_eq!(i0, IntervalId::new(0));

                let i1 = grid1d
                    .find_interval_id_of_point(&Real::try_new(0.5).unwrap())
                    .unwrap();
                assert_eq!(i1, IntervalId::new(0));

                let i2 = grid1d
                    .find_interval_id_of_point(&Real::try_new(1.0).unwrap())
                    .unwrap();
                assert_eq!(i2, IntervalId::new(1)); // p₁ → right interval

                let i3 = grid1d
                    .find_interval_id_of_point(&Real::try_new(1.5).unwrap())
                    .unwrap();
                assert_eq!(i3, IntervalId::new(1));

                let i4 = grid1d
                    .find_interval_id_of_point(&Real::try_new(2.0).unwrap())
                    .unwrap();
                assert_eq!(i4, IntervalId::new(2)); // p₂ → right interval

                let i5 = grid1d
                    .find_interval_id_of_point(&Real::try_new(2.5).unwrap())
                    .unwrap();
                assert_eq!(i5, IntervalId::new(2));

                let i6 = grid1d
                    .find_interval_id_of_point(&Real::try_new(3.0).unwrap())
                    .unwrap();
                assert_eq!(i6, IntervalId::new(2));
            }

            #[test]
            fn uniform_01() {
                let interval =
                    IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(1.0).unwrap());
                let grid1d = Grid1D::uniform(interval, NumIntervals::try_new(4).unwrap());

                let expected_coords = vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(0.25).unwrap(),
                    Real::try_new(0.5).unwrap(),
                    Real::try_new(0.75).unwrap(),
                    Real::try_new(1.0).unwrap(),
                ];

                assert_eq!(grid1d.coords().deref(), &expected_coords);
                //        assert_eq!(grid1d.coords(), &Grid1DCoords::Uniform);
            }

            #[test]
            fn grid_intersection_01() {
                let grid1d_a = Grid1D::<IntervalClosed<Real>>::try_from_sorted(
                    SortedSet::from_unsorted(vec![
                        Real::try_new(0.0).unwrap(),
                        Real::try_new(1.0).unwrap(),
                        Real::try_new(2.0).unwrap(),
                    ]),
                )
                .unwrap();
                let grid1d_b = Grid1D::<IntervalClosed<Real>>::try_from_sorted(
                    SortedSet::from_unsorted(vec![
                        Real::try_new(0.0).unwrap(),
                        Real::try_new(0.5).unwrap(),
                        Real::try_new(2.0).unwrap(),
                    ]),
                )
                .unwrap();

                let union = Grid1DUnion::try_new(&grid1d_a, &grid1d_b).unwrap();
                let (grid1d_fine, map_a, map_b) = union.into_parts();
                assert_eq!(
                    grid1d_fine.coords().deref(),
                    &[
                        Real::try_new(0.0).unwrap(),
                        Real::try_new(0.5).unwrap(),
                        Real::try_new(1.0).unwrap(),
                        Real::try_new(2.0).unwrap()
                    ]
                );
                assert_eq!(map_a[0], IntervalId::new(0));
                assert_eq!(map_a[1], IntervalId::new(0));
                assert_eq!(map_a[2], IntervalId::new(1));

                assert_eq!(map_b[0], IntervalId::new(0));
                assert_eq!(map_b[1], IntervalId::new(1));
                assert_eq!(map_b[2], IntervalId::new(1));
            }

            #[test]
            fn intervals_in_intersection_single_interval() {
                let coords = SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(1.0).unwrap(),
                    Real::try_new(2.0).unwrap(),
                    Real::try_new(3.0).unwrap(),
                ]);
                let grid = Grid1D::<IntervalClosed<Real>>::try_from_sorted(coords).unwrap();

                let domain =
                    IntervalClosed::new(Real::try_new(1.0).unwrap(), Real::try_new(1.5).unwrap());
                let intervals = grid.intervals_in_intersection(&domain);

                assert_eq!(intervals.len(), 1);
                assert_eq!(intervals[0].0, IntervalId::new(1));
                assert_eq!(
                    intervals[0].1,
                    IntervalFinitePositiveLength::from(IntervalClosed::new(
                        Real::try_new(1.0).unwrap(),
                        Real::try_new(1.5).unwrap()
                    ))
                );
            }

            #[test]
            fn intervals_in_intersection_multiple_intervals() {
                let coords = SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(1.0).unwrap(),
                    Real::try_new(2.0).unwrap(),
                    Real::try_new(3.0).unwrap(),
                ]);
                let grid = Grid1D::<IntervalClosed<Real>>::try_from_sorted(coords).unwrap();

                let domain =
                    IntervalClosed::new(Real::try_new(0.5).unwrap(), Real::try_new(2.5).unwrap());
                let intervals = grid.intervals_in_intersection(&domain);

                assert_eq!(intervals.len(), 3);

                // First interval
                assert_eq!(intervals[0].0, IntervalId::new(0));
                assert_eq!(
                    intervals[0].1,
                    IntervalFinitePositiveLength::from(IntervalLowerClosedUpperOpen::new(
                        Real::try_new(0.5).unwrap(),
                        Real::try_new(1.0).unwrap()
                    ))
                );

                // Middle interval
                assert_eq!(intervals[1].0, IntervalId::new(1));
                assert_eq!(
                    intervals[1].1,
                    IntervalFinitePositiveLength::from(IntervalLowerClosedUpperOpen::new(
                        Real::try_new(1.0).unwrap(),
                        Real::try_new(2.0).unwrap()
                    ))
                );

                // Last interval
                assert_eq!(intervals[2].0, IntervalId::new(2));
                assert_eq!(
                    intervals[2].1,
                    IntervalFinitePositiveLength::from(IntervalClosed::new(
                        Real::try_new(2.0).unwrap(),
                        Real::try_new(2.5).unwrap()
                    ))
                );
            }

            #[test]
            fn intervals_in_intersection_full_overlap() {
                let coords = SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(1.0).unwrap(),
                    Real::try_new(2.0).unwrap(),
                    Real::try_new(3.0).unwrap(),
                ]);
                let grid = Grid1D::<IntervalClosed<Real>>::try_from_sorted(coords).unwrap();

                let intervals = grid.intervals_in_intersection(grid.domain());

                assert_eq!(intervals.len(), 3);

                // First interval
                assert_eq!(intervals[0].0, IntervalId::new(0));
                assert_eq!(
                    intervals[0].1,
                    IntervalFinitePositiveLength::from(IntervalLowerClosedUpperOpen::new(
                        Real::try_new(0.0).unwrap(),
                        Real::try_new(1.0).unwrap()
                    ))
                );

                // Middle interval
                assert_eq!(intervals[1].0, IntervalId::new(1));
                assert_eq!(
                    intervals[1].1,
                    IntervalFinitePositiveLength::from(IntervalLowerClosedUpperOpen::new(
                        Real::try_new(1.0).unwrap(),
                        Real::try_new(2.0).unwrap()
                    ))
                );

                // Last interval
                assert_eq!(intervals[2].0, IntervalId::new(2));
                assert_eq!(
                    intervals[2].1,
                    IntervalFinitePositiveLength::from(IntervalClosed::new(
                        Real::try_new(2.0).unwrap(),
                        Real::try_new(3.0).unwrap()
                    ))
                );
            }

            #[test]
            fn intervals_in_intersection_no_overlap() {
                let coords = SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(1.0).unwrap(),
                    Real::try_new(2.0).unwrap(),
                    Real::try_new(3.0).unwrap(),
                ]);
                let grid = Grid1D::<IntervalClosed<Real>>::try_from_sorted(coords).unwrap();

                let domain =
                    IntervalClosed::new(Real::try_new(3.5).unwrap(), Real::try_new(4.0).unwrap());
                let intervals = grid.intervals_in_intersection(&domain);

                assert!(intervals.is_empty());
            }

            #[test]
            fn intervals_in_intersection_out_of_bounds_01() {
                let coords = SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(1.0).unwrap(),
                    Real::try_new(2.0).unwrap(),
                    Real::try_new(3.0).unwrap(),
                ]);
                let grid = Grid1D::<IntervalClosed<Real>>::try_from_sorted(coords).unwrap();

                let domain =
                    IntervalClosed::new(Real::try_new(2.5).unwrap(), Real::try_new(4.0).unwrap());
                let intervals = grid.intervals_in_intersection(&domain);
                assert_eq!(
                    intervals[0],
                    (
                        IntervalId::new(2),
                        IntervalFinitePositiveLength::from(IntervalClosed::new(
                            Real::try_new(2.5).unwrap(),
                            Real::try_new(3.0).unwrap()
                        ))
                    )
                );
            }

            #[test]
            fn intervals_in_intersection_out_of_bounds_02() {
                let coords = SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(1.0).unwrap(),
                    Real::try_new(2.0).unwrap(),
                    Real::try_new(3.0).unwrap(),
                ]);
                let grid = Grid1D::<IntervalClosed<Real>>::try_from_sorted(coords).unwrap();

                let domain = IntervalLowerOpenUpperClosed::new(
                    Real::try_new(2.5).unwrap(),
                    Real::try_new(4.0).unwrap(),
                );
                let intervals = grid.intervals_in_intersection(&domain);
                assert_eq!(
                    intervals[0],
                    (
                        IntervalId::new(2),
                        IntervalFinitePositiveLength::from(IntervalLowerOpenUpperClosed::new(
                            Real::try_new(2.5).unwrap(),
                            Real::try_new(3.0).unwrap()
                        ))
                    )
                );
            }

            #[test]
            fn test_from_grid1d_uniform_to_grid1d() {
                let domain =
                    IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(1.0).unwrap());
                let uniform_grid =
                    Grid1DUniform::new(domain.clone(), NumIntervals::try_new(4).unwrap());

                // Convert using From trait
                let grid: Grid1D<IntervalClosed<Real>> = Grid1D::from(uniform_grid.clone());

                // Verify it's a Uniform variant
                assert!(matches!(grid, Grid1D::Uniform(_)));

                // Verify properties are preserved
                assert_eq!(grid.domain(), &domain);
                assert_eq!(grid.num_intervals().as_ref(), &4);
                assert_eq!(grid.coords().deref(), uniform_grid.coords().deref());
            }

            #[test]
            fn test_from_grid1d_non_uniform_to_grid1d() {
                let coords = Coords1D::try_from(SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(0.3).unwrap(),
                    Real::try_new(0.7).unwrap(),
                    Real::try_new(1.0).unwrap(),
                ]))
                .unwrap();
                let non_uniform_grid =
                    Grid1DNonUniform::<IntervalClosed<Real>>::try_new_from_coords(coords).unwrap();

                // Convert using From trait
                let grid: Grid1D<IntervalClosed<Real>> = Grid1D::from(non_uniform_grid.clone());

                // Verify it's a NonUniform variant
                assert!(matches!(grid, Grid1D::NonUniform(_)));

                // Verify properties are preserved
                assert_eq!(grid.domain(), non_uniform_grid.domain());
                assert_eq!(grid.num_intervals().as_ref(), &3);
                assert_eq!(grid.coords().deref(), non_uniform_grid.coords().deref());
            }

            #[test]
            fn test_from_grid1d_uniform_into_syntax() {
                let domain =
                    IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(1.0).unwrap());
                let uniform_grid =
                    Grid1DUniform::new(domain.clone(), NumIntervals::try_new(4).unwrap());

                // Test .into() syntax
                let grid: Grid1D<IntervalClosed<Real>> = uniform_grid.into();
                assert!(matches!(grid, Grid1D::Uniform(_)));
            }

            #[test]
            fn test_from_grid1d_non_uniform_into_syntax() {
                let coords = Coords1D::try_from(SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(0.5).unwrap(),
                    Real::try_new(1.0).unwrap(),
                ]))
                .unwrap();
                let non_uniform_grid =
                    Grid1DNonUniform::<IntervalClosed<Real>>::try_new_from_coords(coords).unwrap();

                // Test .into() syntax
                let grid: Grid1D<IntervalClosed<Real>> = non_uniform_grid.into();
                assert!(matches!(grid, Grid1D::NonUniform(_)));
            }

            #[test]
            fn test_grid1d_non_uniform_refine_uniform_dispatch() {
                let coords = Coords1D::try_from(SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(0.2).unwrap(),
                    Real::try_new(1.0).unwrap(),
                ]))
                .unwrap();
                let grid = Grid1D::NonUniform(
                    Grid1DNonUniform::<IntervalClosed<Real>>::try_new_from_coords(coords).unwrap(),
                );

                let refinement = grid.refine_uniform(&PositiveNumPoints1D::try_new(1).unwrap());

                assert!(matches!(refinement.original_grid(), Grid1D::NonUniform(_)));
                assert!(matches!(refinement.refined_grid(), Grid1D::NonUniform(_)));
                assert_eq!(refinement.original_grid().num_intervals().as_ref(), &2);
                assert_eq!(refinement.refined_grid().num_intervals().as_ref(), &4);

                assert_eq!(
                    refinement.find_original_interval(&IntervalId::new(0)),
                    IntervalId::new(0)
                );
                assert_eq!(
                    refinement.find_original_interval(&IntervalId::new(1)),
                    IntervalId::new(0)
                );
                assert_eq!(
                    refinement.find_original_interval(&IntervalId::new(2)),
                    IntervalId::new(1)
                );
                assert_eq!(
                    refinement.find_original_interval(&IntervalId::new(3)),
                    IntervalId::new(1)
                );
            }
        }

        mod grid1d_open_intervals {
            use super::*;

            #[test]
            fn test_open_interval_partition() {
                let coords = SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(1.0).unwrap(),
                    Real::try_new(2.0).unwrap(),
                ]);
                let grid = Grid1D::<IntervalOpen<Real>>::try_from_sorted(coords).unwrap();

                // Test first interval: should be (0, 1]
                let interval_0 = grid.interval(&IntervalId::new(0));
                match interval_0 {
                    SubIntervalInPartition::First(interval) => {
                        assert!(!interval.contains_point(&Real::try_new(0.0).unwrap())); // Open lower bound
                        assert!(interval.contains_point(&Real::try_new(0.5).unwrap())); // Inside
                        assert!(interval.contains_point(&Real::try_new(1.0).unwrap())); // Closed upper bound
                    }
                    _ => panic!("Expected first interval"),
                }

                // Test last interval: should be (1, 2)
                let interval_1 = grid.interval(&IntervalId::new(1));
                match interval_1 {
                    SubIntervalInPartition::Last(interval) => {
                        assert!(!interval.contains_point(&Real::try_new(1.0).unwrap())); // Open lower bound
                        assert!(interval.contains_point(&Real::try_new(1.5).unwrap())); // Inside
                        assert!(!interval.contains_point(&Real::try_new(2.0).unwrap())); // Open upper bound
                    }
                    _ => panic!("Expected last interval"),
                }
            }

            #[test]
            fn test_find_interval_on_open_domain() {
                let coords = SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(1.0).unwrap(),
                    Real::try_new(2.0).unwrap(),
                    Real::try_new(3.0).unwrap(),
                ]);
                let grid = Grid1D::<IntervalOpen<Real>>::try_from_sorted(coords).unwrap();

                // Points inside the domain should be found correctly
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(0.5).unwrap())
                        .unwrap(),
                    IntervalId::new(0)
                );
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(1.5).unwrap())
                        .unwrap(),
                    IntervalId::new(1)
                );
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(2.5).unwrap())
                        .unwrap(),
                    IntervalId::new(2)
                );

                // Point exactly on boundary
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(1.0).unwrap())
                        .unwrap(),
                    IntervalId::new(0)
                );
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(2.0).unwrap())
                        .unwrap(),
                    IntervalId::new(1)
                );
            }

            #[test]
            fn test_find_interval_boundary_point_not_in_open_domain() {
                let coords = SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(1.0).unwrap(),
                    Real::try_new(2.0).unwrap(),
                ]);
                let grid = Grid1D::<IntervalOpen<Real>>::try_from_sorted(coords).unwrap();

                let res = grid.find_interval_id_of_point(&Real::try_new(0.0).unwrap());
                assert!(res.is_none(), "Expected None for point on open boundary");
            }
        }

        mod grid1d_semi_open_intervals {
            use super::*;

            #[test]
            fn test_lower_closed_upper_open_partition() {
                let coords = SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(1.0).unwrap(),
                    Real::try_new(2.0).unwrap(),
                ]);
                let grid =
                    Grid1D::<IntervalLowerClosedUpperOpen<Real>>::try_from_sorted(coords).unwrap();

                // Test first interval: should be [0, 1)
                let interval_0 = grid.interval(&IntervalId::new(0));
                match interval_0 {
                    SubIntervalInPartition::First(interval) => {
                        assert!(interval.contains_point(&Real::try_new(0.0).unwrap())); // Closed lower bound
                        assert!(interval.contains_point(&Real::try_new(0.5).unwrap())); // Inside
                        assert!(!interval.contains_point(&Real::try_new(1.0).unwrap())); // Open upper bound
                    }
                    _ => panic!("Expected first interval"),
                }

                // Test last interval: should be [1, 2)
                let interval_1 = grid.interval(&IntervalId::new(1));
                match interval_1 {
                    SubIntervalInPartition::Last(interval) => {
                        assert!(interval.contains_point(&Real::try_new(1.0).unwrap())); // Closed lower bound
                        assert!(interval.contains_point(&Real::try_new(1.5).unwrap())); // Inside
                        assert!(!interval.contains_point(&Real::try_new(2.0).unwrap())); // Open upper bound
                    }
                    _ => panic!("Expected last interval"),
                }
            }

            #[test]
            fn test_lower_open_upper_closed_partition() {
                let coords = SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(1.0).unwrap(),
                    Real::try_new(2.0).unwrap(),
                ]);
                let grid =
                    Grid1D::<IntervalLowerOpenUpperClosed<Real>>::try_from_sorted(coords).unwrap();

                // Test first interval: should be (0, 1]
                let interval_0 = grid.interval(&IntervalId::new(0));
                match interval_0 {
                    SubIntervalInPartition::First(interval) => {
                        assert!(!interval.contains_point(&Real::try_new(0.0).unwrap())); // Open lower bound
                        assert!(interval.contains_point(&Real::try_new(0.5).unwrap())); // Inside
                        assert!(interval.contains_point(&Real::try_new(1.0).unwrap())); // Closed upper bound
                    }
                    _ => panic!("Expected first interval"),
                }

                // Test last interval: should be (1, 2]
                let interval_1 = grid.interval(&IntervalId::new(1));
                match interval_1 {
                    SubIntervalInPartition::Last(interval) => {
                        assert!(!interval.contains_point(&Real::try_new(1.0).unwrap())); // Open lower bound
                        assert!(interval.contains_point(&Real::try_new(1.5).unwrap())); // Inside
                        assert!(interval.contains_point(&Real::try_new(2.0).unwrap())); // Closed upper bound
                    }
                    _ => panic!("Expected last interval"),
                }
            }
        }

        mod interval_partition_general {
            use super::*;

            #[test]
            fn test_interval_partition_general_creation() {
                let coords = Coords1D::try_from(SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(0.5).unwrap(),
                    Real::try_new(1.0).unwrap(),
                ]))
                .unwrap();
                let partition =
                    Grid1DNonUniform::<IntervalClosed<Real>>::try_new_from_coords(coords.clone())
                        .unwrap();

                assert_eq!(partition.coords(), &coords);
                assert_eq!(
                    partition.domain(),
                    &IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(1.0).unwrap())
                );
            }

            #[test]
            fn test_interval_partition_general_insufficient_points() {
                let coords =
                    Coords1D::try_from(SortedSet::from_unsorted(vec![Real::try_new(0.0).unwrap()]))
                        .unwrap();
                let partition =
                    Grid1DNonUniform::<IntervalClosed<Real>>::try_new_from_coords(coords);
                matches!(
                    partition,
                    Err(ErrorsGrid1D::RequiredAtLeastTwoDistinctPoints { .. })
                );
            }
        }

        mod interval_partition_advanced {
            use super::*;

            #[test]
            fn test_interval_partition_iter_intervals() {
                let grid = Grid1D::uniform(
                    IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(3.0).unwrap()),
                    NumIntervals::try_new(3).unwrap(),
                );

                let intervals: Vec<(IntervalId, SubIntervalInPartition<IntervalClosed<Real>>)> =
                    grid.iter_intervals().collect();
                assert_eq!(intervals.len(), 3);

                // Check that interval IDs are sequential
                for (i, (id, _)) in intervals.iter().enumerate() {
                    assert_eq!(*id.as_ref(), i);
                }
            }

            #[test]
            fn test_interval_partition_find_intervals_for_points() {
                let grid = Grid1D::uniform(
                    IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(10.0).unwrap()),
                    NumIntervals::try_new(10).unwrap(),
                );

                let points = vec![
                    Real::try_new(0.5).unwrap(),
                    Real::try_new(2.3).unwrap(),
                    Real::try_new(5.0).unwrap(),
                    Real::try_new(7.8).unwrap(),
                    Real::try_new(10.0).unwrap(),
                    Real::try_new(11.0).unwrap(),
                ];
                let intervals = grid.find_intervals_for_points(&points);

                assert_eq!(intervals.len(), 6);
                assert_eq!(intervals[0], Some(IntervalId::new(0)));
                assert_eq!(intervals[1], Some(IntervalId::new(2)));
                assert_eq!(intervals[2], Some(IntervalId::new(5))); // p₅ = 5.0 → right interval
                assert_eq!(intervals[3], Some(IntervalId::new(7)));
                assert_eq!(intervals[4], Some(IntervalId::new(9)));
                assert_eq!(intervals[5], None); // Outside domain
            }

            #[test]
            fn test_interval_partition_length_statistics() {
                let coords = SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(1.0).unwrap(),
                    Real::try_new(1.5).unwrap(),
                    Real::try_new(4.0).unwrap(),
                ]);
                let grid = Grid1D::<IntervalClosed<Real>>::try_from_sorted(coords).unwrap();

                // Intervals: [0,1] (length 1), (1,1.5] (length 0.5), (1.5,4] (length 2.5)
                assert_eq!(
                    grid.min_interval_length().as_ref(),
                    &Real::try_new(0.5).unwrap()
                );
                assert_eq!(
                    grid.max_interval_length().as_ref(),
                    &Real::try_new(2.5).unwrap()
                );
                assert_eq!(
                    grid.uniformity_ratio().as_ref(),
                    &Real::try_new(5.0).unwrap()
                ); // 2.5/0.5
            }

            #[test]
            fn test_interval_partition_intersection_edge_cases() {
                let grid = Grid1D::uniform(
                    IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(2.0).unwrap()),
                    NumIntervals::try_new(2).unwrap(),
                );

                // Test intersection with smaller domain
                let domain_small =
                    IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(0.5).unwrap());
                let intersections = grid.intervals_in_intersection(&domain_small);
                assert_eq!(
                    &intersections,
                    &[(
                        IntervalId::new(0),
                        IntervalClosed::new(
                            Real::try_new(0.0).unwrap(),
                            Real::try_new(0.5).unwrap()
                        )
                        .into()
                    )]
                );

                // Test intersection with entire domain
                let domain_full =
                    IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(2.0).unwrap());
                let intersections_full = grid.intervals_in_intersection(&domain_full);
                assert_eq!(
                    &intersections_full,
                    &[
                        (
                            IntervalId::new(0),
                            IntervalLowerClosedUpperOpen::new(
                                Real::try_new(0.0).unwrap(),
                                Real::try_new(1.0).unwrap()
                            )
                            .into()
                        ),
                        (
                            IntervalId::new(1),
                            IntervalClosed::new(
                                Real::try_new(1.0).unwrap(),
                                Real::try_new(2.0).unwrap()
                            )
                            .into()
                        )
                    ]
                );

                // Test intersection with domain slightly larger
                let domain_larger =
                    IntervalClosed::new(Real::try_new(-0.1).unwrap(), Real::try_new(2.1).unwrap());
                let intersections_larger = grid.intervals_in_intersection(&domain_larger);
                assert_eq!(intersections_larger.len(), 2); // Should clip to actual domain
                assert_eq!(
                    &intersections_larger,
                    &[
                        (
                            IntervalId::new(0),
                            IntervalLowerClosedUpperOpen::new(
                                Real::try_new(0.0).unwrap(),
                                Real::try_new(1.0).unwrap()
                            )
                            .into()
                        ),
                        (
                            IntervalId::new(1),
                            IntervalClosed::new(
                                Real::try_new(1.0).unwrap(),
                                Real::try_new(2.0).unwrap()
                            )
                            .into()
                        )
                    ]
                );
            }
        }

        mod grid1d_uniform {
            use super::*;

            #[test]
            fn test_uniform_grid_creation() {
                let domain =
                    IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(10.0).unwrap());
                let num_intervals = NumIntervals::try_new(5).unwrap();
                let grid = Grid1DUniform::new(domain.clone(), num_intervals);

                assert_eq!(grid.domain(), &domain);
                assert_eq!(grid.num_intervals(), num_intervals);
                assert_eq!(
                    grid.coords().deref(),
                    &[
                        Real::try_new(0.0).unwrap(),
                        Real::try_new(2.0).unwrap(),
                        Real::try_new(4.0).unwrap(),
                        Real::try_new(6.0).unwrap(),
                        Real::try_new(8.0).unwrap(),
                        Real::try_new(10.0).unwrap()
                    ]
                );
                assert_eq!(*grid.delta_points().as_ref(), Real::try_new(2.0).unwrap());
            }

            #[test]
            fn test_uniform_grid_interval_partition_closed_domain() {
                let domain =
                    IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(2.0).unwrap());
                let grid = Grid1DUniform::new(domain, NumIntervals::try_new(2).unwrap());

                // Test interval lengths and uniformity
                assert_eq!(
                    *grid.interval_length(&IntervalId::new(0)).as_ref(),
                    Real::try_new(1.0).unwrap()
                );
                assert_eq!(
                    *grid.min_interval_length().as_ref(),
                    Real::try_new(1.0).unwrap()
                );
                assert_eq!(
                    *grid.max_interval_length().as_ref(),
                    Real::try_new(1.0).unwrap()
                );
                assert_eq!(
                    *grid.uniformity_ratio().as_ref(),
                    Real::try_new(1.0).unwrap()
                );

                // Test interval types
                let interval_0 = grid.interval(&IntervalId::new(0));
                let interval_1 = grid.interval(&IntervalId::new(1));

                // First interval: [0, 1)
                match interval_0 {
                    SubIntervalInPartition::First(i) => {
                        assert_eq!(
                            i,
                            IntervalLowerClosedUpperOpen::new(
                                Real::try_new(0.0).unwrap(),
                                Real::try_new(1.0).unwrap()
                            )
                        );
                        assert!(i.contains_point(&Real::try_new(0.0).unwrap()));
                        assert!(!i.contains_point(&Real::try_new(1.0).unwrap()));
                    }
                    _ => panic!("Expected first interval"),
                }

                // Last interval: [1, 2]
                match interval_1 {
                    SubIntervalInPartition::Last(i) => {
                        assert_eq!(
                            i,
                            IntervalClosed::new(
                                Real::try_new(1.0).unwrap(),
                                Real::try_new(2.0).unwrap()
                            )
                        );
                        assert!(i.contains_point(&Real::try_new(1.0).unwrap()));
                        assert!(i.contains_point(&Real::try_new(2.0).unwrap()));
                    }
                    _ => panic!("Expected last interval"),
                }
            }

            #[test]
            fn test_uniform_grid_point_location_o1() {
                let domain =
                    IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(10.0).unwrap());
                let grid = Grid1DUniform::new(domain, NumIntervals::try_new(10).unwrap());

                // Test boundaries
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(0.0).unwrap()),
                    Some(IntervalId::new(0))
                );
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(10.0).unwrap()),
                    Some(IntervalId::new(9))
                );

                // Test interior points
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(0.5).unwrap()),
                    Some(IntervalId::new(0))
                );
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(1.5).unwrap()),
                    Some(IntervalId::new(1))
                );
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(9.9).unwrap()),
                    Some(IntervalId::new(9))
                );

                // Test points exactly on grid nodes (belong to RIGHT interval for [a,b] domain)
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(1.0).unwrap()),
                    Some(IntervalId::new(1))
                ); // p₁ → right interval
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(2.0).unwrap()),
                    Some(IntervalId::new(2))
                );
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(9.0).unwrap()),
                    Some(IntervalId::new(9))
                );

                // Test points outside domain
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(-0.1).unwrap()),
                    None
                );
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(10.1).unwrap()),
                    None
                );
            }

            #[test]
            fn test_uniform_grid_point_location_high_res() {
                let grid = Grid1DUniform::new(
                    IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(1.0).unwrap()),
                    NumIntervals::try_new(10000).unwrap(),
                );

                // Point near start
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(0.00005).unwrap()),
                    Some(IntervalId::new(0))
                );
                // Point on first node (p₁ = 0.0001 belongs to right interval for left-closed)
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(0.0001).unwrap()),
                    Some(IntervalId::new(1))
                );
                // Point just after first node
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(0.00011).unwrap()),
                    Some(IntervalId::new(1))
                );
                // Point in the middle
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(0.54321).unwrap()),
                    Some(IntervalId::new(5432))
                );
                // Point near end
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(0.99999).unwrap()),
                    Some(IntervalId::new(9999))
                );
                // Point on end
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(1.0).unwrap()),
                    Some(IntervalId::new(9999))
                );
            }

            #[test]
            fn test_uniform_grid_open_domain() {
                let domain =
                    IntervalOpen::new(Real::try_new(0.0).unwrap(), Real::try_new(2.0).unwrap());
                let grid = Grid1DUniform::new(domain, NumIntervals::try_new(2).unwrap());

                let expected_coords = [
                    Real::try_new(0.).unwrap(),
                    Real::try_new(1.).unwrap(),
                    Real::try_new(2.).unwrap(),
                ];
                assert_eq!(grid.coords().deref(), expected_coords.as_slice());

                // First interval: (0, 1]
                let interval_0 = grid.interval(&IntervalId::new(0));
                match interval_0 {
                    SubIntervalInPartition::First(i) => {
                        assert_eq!(
                            i,
                            IntervalLowerOpenUpperClosed::new(
                                Real::try_new(0.0).unwrap(),
                                Real::try_new(1.0).unwrap()
                            )
                        );
                        assert!(!i.contains_point(&Real::try_new(0.0).unwrap()));
                        assert!(i.contains_point(&Real::try_new(1.0).unwrap()));
                    }
                    _ => panic!("Expected first interval"),
                }

                // Last interval: (1, 2)
                let interval_1 = grid.interval(&IntervalId::new(1));
                match interval_1 {
                    SubIntervalInPartition::Last(i) => {
                        assert_eq!(
                            i,
                            IntervalOpen::new(
                                Real::try_new(1.0).unwrap(),
                                Real::try_new(2.0).unwrap()
                            )
                        );
                        assert!(!i.contains_point(&Real::try_new(1.0).unwrap()));
                        assert!(!i.contains_point(&Real::try_new(2.0).unwrap()));
                    }
                    _ => panic!("Expected last interval"),
                }

                // Point location
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(0.1).unwrap()),
                    Some(IntervalId::new(0))
                );
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(1.0).unwrap()),
                    Some(IntervalId::new(0))
                );
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(1.9).unwrap()),
                    Some(IntervalId::new(1))
                );
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(0.0).unwrap()),
                    None
                ); // Outside open domain
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(2.0).unwrap()),
                    None
                ); // Outside open domain
            }

            #[test]
            fn test_uniform_grid_intersection() {
                let grid = Grid1DUniform::new(
                    IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(10.0).unwrap()),
                    NumIntervals::try_new(10).unwrap(),
                );
                let domain_in =
                    IntervalClosed::new(Real::try_new(2.5).unwrap(), Real::try_new(7.5).unwrap());
                let intersections = grid.intervals_in_intersection(&domain_in);

                assert_eq!(intersections.len(), 6);

                // Check first intersection: interval 2, [2.0, 3.0) intersects with [2.5, 7.5] -> [2.5, 3.0)
                assert_eq!(intersections[0].0, IntervalId::new(2));
                assert_eq!(
                    intersections[0].1,
                    IntervalFinitePositiveLength::from(IntervalLowerClosedUpperOpen::new(
                        Real::try_new(2.5).unwrap(),
                        Real::try_new(3.0).unwrap()
                    ))
                );

                // Check a middle intersection: interval 4, [4.0, 5.0) intersects with [2.5, 7.5] -> [4.0, 5.0)
                assert_eq!(intersections[2].0, IntervalId::new(4));
                assert_eq!(
                    intersections[2].1,
                    IntervalFinitePositiveLength::from(IntervalLowerClosedUpperOpen::new(
                        Real::try_new(4.0).unwrap(),
                        Real::try_new(5.0).unwrap()
                    ))
                );

                // Check last intersection: interval 7, [7.0, 8.0] intersects with [2.5, 7.5] -> [7.0, 7.5]
                assert_eq!(intersections[5].0, IntervalId::new(7));
                assert_eq!(
                    intersections[5].1,
                    IntervalFinitePositiveLength::from(IntervalClosed::new(
                        Real::try_new(7.0).unwrap(),
                        Real::try_new(7.5).unwrap()
                    ))
                );
            }
        }

        mod grid1d_non_uniform {
            use super::*;
            use crate::intervals::IntervalClosed;

            fn create_test_grid() -> Grid1DNonUniform<IntervalClosed<Real>> {
                let coords = Coords1D::try_from(SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(1.0).unwrap(),
                    Real::try_new(3.0).unwrap(),
                    Real::try_new(7.0).unwrap(),
                    Real::try_new(10.0).unwrap(),
                ]))
                .unwrap();
                Grid1DNonUniform::<IntervalClosed<Real>>::try_new_from_coords(coords).unwrap()
            }

            #[test]
            fn test_non_uniform_grid_creation() {
                let grid = create_test_grid();
                assert_eq!(
                    grid.domain(),
                    &IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(10.0).unwrap())
                );
                assert_eq!(
                    grid.coords().deref(),
                    &[
                        Real::try_new(0.0).unwrap(),
                        Real::try_new(1.0).unwrap(),
                        Real::try_new(3.0).unwrap(),
                        Real::try_new(7.0).unwrap(),
                        Real::try_new(10.0).unwrap()
                    ]
                );
                assert_eq!(grid.num_intervals().as_ref(), &4);
            }

            #[test]
            fn test_creation_fails_with_insufficient_points() {
                let coords =
                    Coords1D::try_from(SortedSet::from_unsorted(vec![Real::try_new(0.0).unwrap()]))
                        .unwrap();
                let result = Grid1DNonUniform::<IntervalClosed<Real>>::try_new_from_coords(coords);
                assert!(matches!(
                    result,
                    Err(ErrorsGrid1D::RequiredAtLeastTwoDistinctPoints { .. })
                ));
            }

            #[test]
            fn test_non_uniform_interval_partition() {
                let grid = create_test_grid();

                // First interval: [0, 1)
                let interval_0 = grid.interval(&IntervalId::new(0));
                match interval_0 {
                    SubIntervalInPartition::First(i) => {
                        assert_eq!(
                            i,
                            IntervalLowerClosedUpperOpen::new(
                                Real::try_new(0.0).unwrap(),
                                Real::try_new(1.0).unwrap()
                            )
                        );
                    }
                    _ => panic!("Expected first interval"),
                }

                // Middle interval: [1, 3)
                let interval_1 = grid.interval(&IntervalId::new(1));
                match interval_1 {
                    SubIntervalInPartition::Middle(i) => {
                        assert_eq!(
                            i,
                            IntervalLowerClosedUpperOpen::new(
                                Real::try_new(1.0).unwrap(),
                                Real::try_new(3.0).unwrap()
                            )
                        );
                    }
                    _ => panic!("Expected middle interval"),
                }

                // Last interval: [7, 10]
                let interval_3 = grid.interval(&IntervalId::new(3));
                match interval_3 {
                    SubIntervalInPartition::Last(i) => {
                        assert_eq!(
                            i,
                            IntervalClosed::new(
                                Real::try_new(7.0).unwrap(),
                                Real::try_new(10.0).unwrap()
                            )
                        );
                    }
                    _ => panic!("Expected last interval"),
                }
            }

            #[test]
            fn test_non_uniform_statistics() {
                let grid = create_test_grid();
                assert_eq!(
                    *grid.interval_length(&IntervalId::new(0)).as_ref(),
                    Real::try_new(1.0).unwrap()
                ); // [0,1]
                assert_eq!(
                    *grid.interval_length(&IntervalId::new(1)).as_ref(),
                    Real::try_new(2.0).unwrap()
                ); // (1,3]
                assert_eq!(
                    *grid.interval_length(&IntervalId::new(2)).as_ref(),
                    Real::try_new(4.0).unwrap()
                ); // (3,7]
                assert_eq!(
                    *grid.interval_length(&IntervalId::new(3)).as_ref(),
                    Real::try_new(3.0).unwrap()
                ); // (7,10]

                assert_eq!(
                    *grid.min_interval_length().as_ref(),
                    Real::try_new(1.0).unwrap()
                );
                assert_eq!(
                    *grid.max_interval_length().as_ref(),
                    Real::try_new(4.0).unwrap()
                );
                assert_eq!(
                    *grid.uniformity_ratio().as_ref(),
                    Real::try_new(4.0).unwrap()
                );
            }

            #[test]
            fn test_non_uniform_point_location() {
                let grid = create_test_grid();

                // Boundaries
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(0.0).unwrap()),
                    Some(IntervalId::new(0))
                );
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(10.0).unwrap()),
                    Some(IntervalId::new(3))
                );

                // Interior points
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(0.5).unwrap()),
                    Some(IntervalId::new(0))
                );
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(2.5).unwrap()),
                    Some(IntervalId::new(1))
                );
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(5.0).unwrap()),
                    Some(IntervalId::new(2))
                );
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(8.5).unwrap()),
                    Some(IntervalId::new(3))
                );

                // Points exactly on grid nodes (belong to RIGHT interval for [a,b] domain)
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(1.0).unwrap()),
                    Some(IntervalId::new(1))
                );
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(3.0).unwrap()),
                    Some(IntervalId::new(2))
                );
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(7.0).unwrap()),
                    Some(IntervalId::new(3))
                );

                // Outside domain
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(-0.1).unwrap()),
                    None
                );
                assert_eq!(
                    grid.find_interval_id_of_point(&Real::try_new(10.1).unwrap()),
                    None
                );
            }

            #[test]
            fn test_non_uniform_intersection() {
                let grid = create_test_grid();
                let domain_in =
                    IntervalClosed::new(Real::try_new(0.5).unwrap(), Real::try_new(8.5).unwrap());
                let intersections = grid.intervals_in_intersection(&domain_in);

                assert_eq!(intersections.len(), 4);

                // First intersection: interval 0, [0,1) intersects [0.5, 8.5] -> [0.5, 1)
                assert_eq!(intersections[0].0, IntervalId::new(0));
                assert_eq!(
                    intersections[0].1,
                    IntervalFinitePositiveLength::from(IntervalLowerClosedUpperOpen::new(
                        Real::try_new(0.5).unwrap(),
                        Real::try_new(1.0).unwrap()
                    ))
                );

                // Second intersection: interval 1, [1,3) intersects [0.5, 8.5] -> [1,3)
                assert_eq!(intersections[1].0, IntervalId::new(1));
                assert_eq!(
                    intersections[1].1,
                    IntervalFinitePositiveLength::from(IntervalLowerClosedUpperOpen::new(
                        Real::try_new(1.0).unwrap(),
                        Real::try_new(3.0).unwrap()
                    ))
                );

                // Third intersection: interval 2, [3,7) intersects [0.5, 8.5] -> [3,7)
                assert_eq!(intersections[2].0, IntervalId::new(2));
                assert_eq!(
                    intersections[2].1,
                    IntervalFinitePositiveLength::from(IntervalLowerClosedUpperOpen::new(
                        Real::try_new(3.0).unwrap(),
                        Real::try_new(7.0).unwrap()
                    ))
                );

                // Fourth intersection: interval 3, [7,10] intersects [0.5, 8.5] -> [7,8.5]
                assert_eq!(intersections[3].0, IntervalId::new(3));
                assert_eq!(
                    intersections[3].1,
                    IntervalFinitePositiveLength::from(IntervalClosed::new(
                        Real::try_new(7.0).unwrap(),
                        Real::try_new(8.5).unwrap()
                    ))
                );
            }
        }

        // NOTE: Comprehensive tests for Grid1DRefinement are in src/operations/refinement.rs
        // NOTE: Comprehensive tests for Grid1DUnion are in src/operations/union.rs

        mod find_interval_id_of_point {
            use super::*;

            fn r(v: f64) -> Real {
                Real::try_new(v).unwrap()
            }

            /// Checks that `find_interval_id_of_point` returns `expected` AND,
            /// when the result is `Some(id)`, that `grid.interval(&id)` actually
            /// contains the queried point.
            fn assert_finds<G>(grid: &G, x: G::CoordType, expected: Option<IntervalId>)
            where
                G: Grid1DTrait,
            {
                let found = grid.find_interval_id_of_point(&x);
                assert_eq!(found, expected);
                if let Some(ref id) = found {
                    assert!(
                        grid.interval(id).contains_point(&x),
                        "interval {:?} returned for point but does not contain it",
                        id
                    );
                }
            }

            // ----------------------------------------------------------------
            // Grid1DNonUniform tests
            //
            // Coords: [0.0, 1.0, 3.0, 6.0, 10.0]  → 4 intervals
            // Internal boundaries: p₁=1.0, p₂=3.0, p₃=6.0
            // ----------------------------------------------------------------
            mod grid1d_non_uniform {
                use super::*;

                mod interval_closed {
                    use super::*;

                    // Domain [0, 10]: sub-intervals [0,1), [1,3), [3,6), [6,10]
                    // Lower-bound closed → internal boundary pₖ belongs to RIGHT interval k

                    fn make_grid() -> Grid1DNonUniform<IntervalClosed<Real>> {
                        let coords = Coords1D::try_from(SortedSet::from_unsorted(vec![
                            r(0.0),
                            r(1.0),
                            r(3.0),
                            r(6.0),
                            r(10.0),
                        ]))
                        .unwrap();
                        Grid1DNonUniform::<IntervalClosed<Real>>::try_new_from_coords(coords)
                            .unwrap()
                    }

                    #[test]
                    fn first_interval_interior() {
                        assert_finds(&make_grid(), r(0.5), Some(IntervalId::new(0)));
                    }

                    #[test]
                    fn middle_intervals_interior() {
                        let grid = make_grid();
                        assert_finds(&grid, r(2.0), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(4.0), Some(IntervalId::new(2)));
                    }

                    #[test]
                    fn last_interval_interior() {
                        assert_finds(&make_grid(), r(8.0), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn lower_domain_boundary() {
                        // p₀ = 0.0, closed lower bound → belongs to interval 0
                        assert_finds(&make_grid(), r(0.0), Some(IntervalId::new(0)));
                    }

                    #[test]
                    fn internal_boundaries_belong_to_right_interval() {
                        let grid = make_grid();
                        assert_finds(&grid, r(1.0), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(3.0), Some(IntervalId::new(2)));
                        assert_finds(&grid, r(6.0), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn upper_domain_boundary() {
                        // p₄ = 10.0, closed upper bound → belongs to last interval
                        assert_finds(&make_grid(), r(10.0), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn outside_domain_returns_none() {
                        let grid = make_grid();
                        assert_finds(&grid, r(-0.1), None);
                        assert_finds(&grid, r(10.1), None);
                    }
                }

                mod interval_open {
                    use super::*;

                    // Domain (0, 10): sub-intervals (0,1], (1,3], (3,6], (6,10)
                    // Lower-bound open → internal boundary pₖ belongs to LEFT interval k-1

                    fn make_grid() -> Grid1DNonUniform<IntervalOpen<Real>> {
                        let coords = Coords1D::try_from(SortedSet::from_unsorted(vec![
                            r(0.0),
                            r(1.0),
                            r(3.0),
                            r(6.0),
                            r(10.0),
                        ]))
                        .unwrap();
                        Grid1DNonUniform::<IntervalOpen<Real>>::try_new_from_coords(coords).unwrap()
                    }

                    #[test]
                    fn first_interval_interior() {
                        assert_finds(&make_grid(), r(0.5), Some(IntervalId::new(0)));
                    }

                    #[test]
                    fn middle_intervals_interior() {
                        let grid = make_grid();
                        assert_finds(&grid, r(2.0), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(4.0), Some(IntervalId::new(2)));
                    }

                    #[test]
                    fn last_interval_interior() {
                        assert_finds(&make_grid(), r(8.0), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn lower_domain_boundary_returns_none() {
                        // p₀ = 0.0 is NOT in open domain (0, 10)
                        assert_finds(&make_grid(), r(0.0), None);
                    }

                    #[test]
                    fn internal_boundaries_belong_to_left_interval() {
                        // (a,b): sub-intervals are right-closed (pₖ, pₖ₊₁]
                        // pₖ belongs to the left interval k-1
                        let grid = make_grid();
                        assert_finds(&grid, r(1.0), Some(IntervalId::new(0)));
                        assert_finds(&grid, r(3.0), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(6.0), Some(IntervalId::new(2)));
                    }

                    #[test]
                    fn upper_domain_boundary_returns_none() {
                        // p₄ = 10.0 is NOT in open domain (0, 10)
                        assert_finds(&make_grid(), r(10.0), None);
                    }

                    #[test]
                    fn outside_domain_returns_none() {
                        let grid = make_grid();
                        assert_finds(&grid, r(-0.1), None);
                        assert_finds(&grid, r(10.1), None);
                    }
                }

                mod interval_lower_closed_upper_open {
                    use super::*;

                    // Domain [0, 10): sub-intervals [0,1), [1,3), [3,6), [6,10)
                    // Lower-bound closed → internal pₖ belongs to RIGHT interval k

                    fn make_grid() -> Grid1DNonUniform<IntervalLowerClosedUpperOpen<Real>> {
                        let coords = Coords1D::try_from(SortedSet::from_unsorted(vec![
                            r(0.0),
                            r(1.0),
                            r(3.0),
                            r(6.0),
                            r(10.0),
                        ]))
                        .unwrap();
                        Grid1DNonUniform::<IntervalLowerClosedUpperOpen<Real>>::try_new_from_coords(
                            coords,
                        )
                        .unwrap()
                    }

                    #[test]
                    fn first_interval_interior() {
                        assert_finds(&make_grid(), r(0.5), Some(IntervalId::new(0)));
                    }

                    #[test]
                    fn middle_intervals_interior() {
                        let grid = make_grid();
                        assert_finds(&grid, r(2.0), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(4.0), Some(IntervalId::new(2)));
                    }

                    #[test]
                    fn last_interval_interior() {
                        assert_finds(&make_grid(), r(8.0), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn lower_domain_boundary() {
                        // p₀ = 0.0 is in [a, b) domain
                        assert_finds(&make_grid(), r(0.0), Some(IntervalId::new(0)));
                    }

                    #[test]
                    fn internal_boundaries_belong_to_right_interval() {
                        let grid = make_grid();
                        assert_finds(&grid, r(1.0), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(3.0), Some(IntervalId::new(2)));
                        assert_finds(&grid, r(6.0), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn upper_domain_boundary_returns_none() {
                        // p₄ = 10.0 is NOT in [a, b) domain
                        assert_finds(&make_grid(), r(10.0), None);
                    }

                    #[test]
                    fn outside_domain_returns_none() {
                        let grid = make_grid();
                        assert_finds(&grid, r(-0.1), None);
                        assert_finds(&grid, r(10.1), None);
                    }
                }

                mod interval_lower_open_upper_closed {
                    use super::*;

                    // Domain (0, 10]: sub-intervals (0,1], (1,3], (3,6], (6,10]
                    // Lower-bound open → internal pₖ belongs to LEFT interval k-1

                    fn make_grid() -> Grid1DNonUniform<IntervalLowerOpenUpperClosed<Real>> {
                        let coords = Coords1D::try_from(SortedSet::from_unsorted(vec![
                            r(0.0),
                            r(1.0),
                            r(3.0),
                            r(6.0),
                            r(10.0),
                        ]))
                        .unwrap();
                        Grid1DNonUniform::<IntervalLowerOpenUpperClosed<Real>>::try_new_from_coords(
                            coords,
                        )
                        .unwrap()
                    }

                    #[test]
                    fn first_interval_interior() {
                        assert_finds(&make_grid(), r(0.5), Some(IntervalId::new(0)));
                    }

                    #[test]
                    fn middle_intervals_interior() {
                        let grid = make_grid();
                        assert_finds(&grid, r(2.0), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(4.0), Some(IntervalId::new(2)));
                    }

                    #[test]
                    fn last_interval_interior() {
                        assert_finds(&make_grid(), r(8.0), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn lower_domain_boundary_returns_none() {
                        // p₀ = 0.0 is NOT in (a, b] domain
                        assert_finds(&make_grid(), r(0.0), None);
                    }

                    #[test]
                    fn internal_boundaries_belong_to_left_interval() {
                        // (a,b]: sub-intervals are right-closed (pₖ, pₖ₊₁]
                        let grid = make_grid();
                        assert_finds(&grid, r(1.0), Some(IntervalId::new(0)));
                        assert_finds(&grid, r(3.0), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(6.0), Some(IntervalId::new(2)));
                    }

                    #[test]
                    fn upper_domain_boundary() {
                        // p₄ = 10.0 is in (a, b] domain → belongs to last interval
                        assert_finds(&make_grid(), r(10.0), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn outside_domain_returns_none() {
                        let grid = make_grid();
                        assert_finds(&grid, r(-0.1), None);
                        assert_finds(&grid, r(10.1), None);
                    }
                }

                mod interval_finite_positive_length {
                    use super::*;

                    // IntervalFinitePositiveLength::Closed creates a Closed variant,
                    // so boundary semantics are identical to the interval_closed tests.
                    // Domain [0, 10]: sub-intervals [0,1), [1,3), [3,6), [6,10]

                    fn make_grid() -> Grid1DNonUniform<IntervalFinitePositiveLength<Real>> {
                        let coords = Coords1D::try_from(SortedSet::from_unsorted(vec![
                            r(0.0),
                            r(1.0),
                            r(3.0),
                            r(6.0),
                            r(10.0),
                        ]))
                        .unwrap();
                        let domain: IntervalFinitePositiveLength<Real> =
                            IntervalClosed::new(r(0.0), r(10.0)).into();

                        Grid1DNonUniform::<IntervalFinitePositiveLength<Real>>::try_new(
                            domain, coords,
                        )
                        .unwrap()
                    }

                    #[test]
                    fn first_interval_interior() {
                        assert_finds(&make_grid(), r(0.5), Some(IntervalId::new(0)));
                    }

                    #[test]
                    fn middle_intervals_interior() {
                        let grid = make_grid();
                        assert_finds(&grid, r(2.0), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(4.0), Some(IntervalId::new(2)));
                    }

                    #[test]
                    fn last_interval_interior() {
                        assert_finds(&make_grid(), r(8.0), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn lower_domain_boundary() {
                        assert_finds(&make_grid(), r(0.0), Some(IntervalId::new(0)));
                    }

                    #[test]
                    fn internal_boundaries_belong_to_right_interval() {
                        let grid = make_grid();
                        assert_finds(&grid, r(1.0), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(3.0), Some(IntervalId::new(2)));
                        assert_finds(&grid, r(6.0), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn upper_domain_boundary() {
                        assert_finds(&make_grid(), r(10.0), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn outside_domain_returns_none() {
                        let grid = make_grid();
                        assert_finds(&grid, r(-0.1), None);
                        assert_finds(&grid, r(10.1), None);
                    }
                }
            }

            // ----------------------------------------------------------------
            // Grid1DUniform tests
            //
            // Domain [0.0, 4.0] with 4 intervals → coords [0.0, 1.0, 2.0, 3.0, 4.0]
            // Internal boundaries: p₁=1.0, p₂=2.0, p₃=3.0
            // ----------------------------------------------------------------
            mod grid1d_uniform {
                use super::*;

                mod interval_closed {
                    use super::*;

                    // Domain [0, 4]: sub-intervals [0,1), [1,2), [2,3), [3,4]
                    // Lower-bound closed → internal pₖ belongs to RIGHT interval k

                    fn make_grid() -> Grid1DUniform<IntervalClosed<Real>> {
                        Grid1DUniform::new(
                            IntervalClosed::new(r(0.0), r(4.0)),
                            NumIntervals::try_new(4).unwrap(),
                        )
                    }

                    #[test]
                    fn first_interval_interior() {
                        assert_finds(&make_grid(), r(0.5), Some(IntervalId::new(0)));
                    }

                    #[test]
                    fn middle_intervals_interior() {
                        let grid = make_grid();
                        assert_finds(&grid, r(1.5), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(2.5), Some(IntervalId::new(2)));
                    }

                    #[test]
                    fn last_interval_interior() {
                        assert_finds(&make_grid(), r(3.5), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn lower_domain_boundary() {
                        assert_finds(&make_grid(), r(0.0), Some(IntervalId::new(0)));
                    }

                    #[test]
                    fn internal_boundaries_belong_to_right_interval() {
                        let grid = make_grid();
                        assert_finds(&grid, r(1.0), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(2.0), Some(IntervalId::new(2)));
                        assert_finds(&grid, r(3.0), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn upper_domain_boundary() {
                        assert_finds(&make_grid(), r(4.0), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn outside_domain_returns_none() {
                        let grid = make_grid();
                        assert_finds(&grid, r(-0.1), None);
                        assert_finds(&grid, r(4.1), None);
                    }
                }

                mod interval_open {
                    use super::*;

                    // Domain (0, 4): sub-intervals (0,1], (1,2], (2,3], (3,4)
                    // Lower-bound open → internal pₖ belongs to LEFT interval k-1

                    fn make_grid() -> Grid1DUniform<IntervalOpen<Real>> {
                        Grid1DUniform::new(
                            IntervalOpen::new(r(0.0), r(4.0)),
                            NumIntervals::try_new(4).unwrap(),
                        )
                    }

                    #[test]
                    fn first_interval_interior() {
                        assert_finds(&make_grid(), r(0.5), Some(IntervalId::new(0)));
                    }

                    #[test]
                    fn middle_intervals_interior() {
                        let grid = make_grid();
                        assert_finds(&grid, r(1.5), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(2.5), Some(IntervalId::new(2)));
                    }

                    #[test]
                    fn last_interval_interior() {
                        assert_finds(&make_grid(), r(3.5), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn lower_domain_boundary_returns_none() {
                        // p₀ = 0.0 is NOT in (a, b) domain
                        assert_finds(&make_grid(), r(0.0), None);
                    }

                    #[test]
                    fn internal_boundaries_belong_to_left_interval() {
                        let grid = make_grid();
                        assert_finds(&grid, r(1.0), Some(IntervalId::new(0)));
                        assert_finds(&grid, r(2.0), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(3.0), Some(IntervalId::new(2)));
                    }

                    #[test]
                    fn upper_domain_boundary_returns_none() {
                        // p₄ = 4.0 is NOT in (a, b) domain
                        assert_finds(&make_grid(), r(4.0), None);
                    }

                    #[test]
                    fn outside_domain_returns_none() {
                        let grid = make_grid();
                        assert_finds(&grid, r(-0.1), None);
                        assert_finds(&grid, r(4.1), None);
                    }
                }

                mod interval_lower_closed_upper_open {
                    use super::*;

                    // Domain [0, 4): sub-intervals [0,1), [1,2), [2,3), [3,4)
                    // Lower-bound closed → internal pₖ belongs to RIGHT interval k

                    fn make_grid() -> Grid1DUniform<IntervalLowerClosedUpperOpen<Real>> {
                        Grid1DUniform::new(
                            IntervalLowerClosedUpperOpen::new(r(0.0), r(4.0)),
                            NumIntervals::try_new(4).unwrap(),
                        )
                    }

                    #[test]
                    fn first_interval_interior() {
                        assert_finds(&make_grid(), r(0.5), Some(IntervalId::new(0)));
                    }

                    #[test]
                    fn middle_intervals_interior() {
                        let grid = make_grid();
                        assert_finds(&grid, r(1.5), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(2.5), Some(IntervalId::new(2)));
                    }

                    #[test]
                    fn last_interval_interior() {
                        assert_finds(&make_grid(), r(3.5), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn lower_domain_boundary() {
                        // p₀ = 0.0 is in [a, b) domain
                        assert_finds(&make_grid(), r(0.0), Some(IntervalId::new(0)));
                    }

                    #[test]
                    fn internal_boundaries_belong_to_right_interval() {
                        let grid = make_grid();
                        assert_finds(&grid, r(1.0), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(2.0), Some(IntervalId::new(2)));
                        assert_finds(&grid, r(3.0), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn upper_domain_boundary_returns_none() {
                        // p₄ = 4.0 is NOT in [a, b) domain
                        assert_finds(&make_grid(), r(4.0), None);
                    }

                    #[test]
                    fn outside_domain_returns_none() {
                        let grid = make_grid();
                        assert_finds(&grid, r(-0.1), None);
                        assert_finds(&grid, r(4.1), None);
                    }
                }

                mod interval_lower_open_upper_closed {
                    use super::*;

                    // Domain (0, 4]: sub-intervals (0,1], (1,2], (2,3], (3,4]
                    // Lower-bound open → internal pₖ belongs to LEFT interval k-1

                    fn make_grid() -> Grid1DUniform<IntervalLowerOpenUpperClosed<Real>> {
                        Grid1DUniform::new(
                            IntervalLowerOpenUpperClosed::new(r(0.0), r(4.0)),
                            NumIntervals::try_new(4).unwrap(),
                        )
                    }

                    #[test]
                    fn first_interval_interior() {
                        assert_finds(&make_grid(), r(0.5), Some(IntervalId::new(0)));
                    }

                    #[test]
                    fn middle_intervals_interior() {
                        let grid = make_grid();
                        assert_finds(&grid, r(1.5), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(2.5), Some(IntervalId::new(2)));
                    }

                    #[test]
                    fn last_interval_interior() {
                        assert_finds(&make_grid(), r(3.5), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn lower_domain_boundary_returns_none() {
                        // p₀ = 0.0 is NOT in (a, b] domain
                        assert_finds(&make_grid(), r(0.0), None);
                    }

                    #[test]
                    fn internal_boundaries_belong_to_left_interval() {
                        let grid = make_grid();
                        assert_finds(&grid, r(1.0), Some(IntervalId::new(0)));
                        assert_finds(&grid, r(2.0), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(3.0), Some(IntervalId::new(2)));
                    }

                    #[test]
                    fn upper_domain_boundary() {
                        // p₄ = 4.0 is in (a, b] domain → belongs to last interval
                        assert_finds(&make_grid(), r(4.0), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn outside_domain_returns_none() {
                        let grid = make_grid();
                        assert_finds(&grid, r(-0.1), None);
                        assert_finds(&grid, r(4.1), None);
                    }
                }

                mod interval_finite_positive_length {
                    use super::*;

                    // IntervalFinitePositiveLength::Closed creates a Closed variant,
                    // so boundary semantics are identical to interval_closed tests.
                    // Domain [0, 4]: sub-intervals [0,1), [1,2), [2,3), [3,4]

                    fn make_grid() -> Grid1DUniform<IntervalFinitePositiveLength<Real>> {
                        Grid1DUniform::new(
                            IntervalFinitePositiveLength::Closed(IntervalClosed::new(
                                r(0.0),
                                r(4.0),
                            )),
                            NumIntervals::try_new(4).unwrap(),
                        )
                    }

                    #[test]
                    fn first_interval_interior() {
                        assert_finds(&make_grid(), r(0.5), Some(IntervalId::new(0)));
                    }

                    #[test]
                    fn middle_intervals_interior() {
                        let grid = make_grid();
                        assert_finds(&grid, r(1.5), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(2.5), Some(IntervalId::new(2)));
                    }

                    #[test]
                    fn last_interval_interior() {
                        assert_finds(&make_grid(), r(3.5), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn lower_domain_boundary() {
                        assert_finds(&make_grid(), r(0.0), Some(IntervalId::new(0)));
                    }

                    #[test]
                    fn internal_boundaries_belong_to_right_interval() {
                        let grid = make_grid();
                        assert_finds(&grid, r(1.0), Some(IntervalId::new(1)));
                        assert_finds(&grid, r(2.0), Some(IntervalId::new(2)));
                        assert_finds(&grid, r(3.0), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn upper_domain_boundary() {
                        assert_finds(&make_grid(), r(4.0), Some(IntervalId::new(3)));
                    }

                    #[test]
                    fn outside_domain_returns_none() {
                        let grid = make_grid();
                        assert_finds(&grid, r(-0.1), None);
                        assert_finds(&grid, r(4.1), None);
                    }
                }
            }
        }
    }

    #[cfg(feature = "rug")]
    mod rug100 {
        use super::*;
        use num::{One, Zero};
        use num_valid::RealRugStrictFinite;

        const PRECISION: u32 = 100;
        type Real = RealRugStrictFinite<PRECISION>;

        mod grid1d {
            use super::*;
            use num_valid::Constants;

            #[test]
            fn grid1d_01() {
                let v = SortedSet::from_unsorted(vec_f64_into_vec_real::<Real>(vec![0., 1.]));
                let grid1d = Grid1D::<IntervalClosed<Real>>::try_from_sorted(v.clone()).unwrap();
                assert_eq!(grid1d.coords().deref(), &v.to_vec());
            }

            #[test]
            #[cfg(debug_assertions)]
            #[should_panic]
            fn grid1d_02() {
                let v = SortedSet::from_unsorted(vec_f64_into_vec_real::<Real>(vec![0.]));
                let _grid1d = Grid1D::<IntervalClosed<Real>>::try_from_sorted(v.clone()).unwrap();
            }

            #[test]
            fn interval_01() {
                let v = SortedSet::from_unsorted(vec_f64_into_vec_real::<Real>(vec![0., 1.]));

                let grid1d = Grid1D::<IntervalClosed<Real>>::try_from_sorted(v.clone()).unwrap();

                let interval = grid1d.interval(&IntervalId::new(0));

                match interval {
                    SubIntervalInPartition::Single(interval) => {
                        assert_eq!(
                            TryInto::<IntervalClosed<Real>>::try_into(interval).unwrap(),
                            IntervalClosed::new(Real::zero(), Real::one())
                        );
                    }
                    _ => {
                        panic!("There should be only one interval")
                    }
                }
            }

            #[test]
            #[cfg(debug_assertions)]
            #[should_panic]
            fn interval_02() {
                let v = SortedSet::from_unsorted(vec_f64_into_vec_real::<Real>(vec![0., 1.]));
                let grid1d = Grid1D::<IntervalClosed<Real>>::try_from_sorted(v.clone()).unwrap();
                let _interval = grid1d.interval(&IntervalId::new(1));
            }

            #[test]
            fn find_interval_id_01() {
                let v =
                    SortedSet::from_unsorted(vec_f64_into_vec_real::<Real>(vec![0., 1., 2., 3.]));
                let grid1d = Grid1D::<IntervalClosed<Real>>::try_from_sorted(v.clone()).unwrap();

                let i0 = grid1d.find_interval_id_of_point(&Real::zero()).unwrap();
                assert_eq!(i0, IntervalId::new(0));

                let i1 = grid1d
                    .find_interval_id_of_point(
                        &Real::try_new(rug::Float::with_val(PRECISION, 0.5)).unwrap(),
                    )
                    .unwrap();
                assert_eq!(i1, IntervalId::new(0));

                let i2 = grid1d.find_interval_id_of_point(&Real::one()).unwrap();
                assert_eq!(i2, IntervalId::new(1));

                let i3 = grid1d
                    .find_interval_id_of_point(
                        &Real::try_new(rug::Float::with_val(PRECISION, 1.5)).unwrap(),
                    )
                    .unwrap();
                assert_eq!(i3, IntervalId::new(1));

                let i4 = grid1d.find_interval_id_of_point(&Real::two()).unwrap();
                assert_eq!(i4, IntervalId::new(2));

                let i5 = grid1d
                    .find_interval_id_of_point(
                        &Real::try_new(rug::Float::with_val(PRECISION, 2.5)).unwrap(),
                    )
                    .unwrap();
                assert_eq!(i5, IntervalId::new(2));

                let i6 = grid1d
                    .find_interval_id_of_point(
                        &Real::try_new(rug::Float::with_val(PRECISION, 3.)).unwrap(),
                    )
                    .unwrap();
                assert_eq!(i6, IntervalId::new(2));
            }

            #[test]
            fn uniform_01() {
                let interval = IntervalClosed::new(Real::zero(), Real::one());
                let grid1d = Grid1D::uniform(interval, NumIntervals::try_new(4).unwrap());

                let expected_coords = vec_f64_into_vec_real::<Real>(vec![0., 0.25, 0.5, 0.75, 1.0]);

                assert_eq!(grid1d.coords().deref(), &expected_coords);
            }

            #[test]
            fn intersection_01() {
                let grid1d_a = Grid1D::<IntervalClosed<Real>>::try_from_sorted(
                    SortedSet::from_unsorted(vec_f64_into_vec_real::<Real>(vec![0.0, 1.0, 2.0])),
                )
                .unwrap();
                let grid1d_b = Grid1D::<IntervalClosed<Real>>::try_from_sorted(
                    SortedSet::from_unsorted(vec_f64_into_vec_real::<Real>(vec![0.0, 0.5, 2.0])),
                )
                .unwrap();

                let union = Grid1DUnion::try_new(&grid1d_a, &grid1d_b).unwrap();
                let (grid1d_fine, map_a, map_b) = union.into_parts();
                assert_eq!(
                    grid1d_fine.coords().deref(),
                    &vec_f64_into_vec_real::<f64>(vec![0.0, 0.5, 1.0, 2.0])
                );
                assert_eq!(map_a[0], IntervalId::new(0));
                assert_eq!(map_a[1], IntervalId::new(0));
                assert_eq!(map_a[2], IntervalId::new(1));

                assert_eq!(map_b[0], IntervalId::new(0));
                assert_eq!(map_b[1], IntervalId::new(1));
                assert_eq!(map_b[2], IntervalId::new(1));
            }
        }
    }
}
//------------------------------------------------------------------------------------------------