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
//! MOC storage, protected from concurrent access.
//! The purpose is to be used this common storage in MOCWasm, MOCSet and MOCGui
//! to store MOC in memory on the Rust side.
//!
//! # Note
//! Internally we use a [slab](https://crates.io/crates/slab) with concurrent access protected
//! by a [RwLock](https://doc.rust-lang.org/std/sync/struct.RwLock.html).
//! We may have used [sharded-slab](https://crates.io/crates/sharded-slab) but the current version
//! (v0.11.4) is still experimental according to the README, and the development does not seem to be
//! very active.
use std::{
fs::{self, File},
io::{BufRead, BufReader, Cursor},
ops::Range,
path::Path,
};
#[cfg(not(target_arch = "wasm32"))]
use rayon::iter::{
IndexedParallelIterator, IntoParallelIterator, IntoParallelRefMutIterator, ParallelIterator,
};
use crate::{
deser::{
ascii::{from_ascii_ivoa, moc2d_from_ascii_ivoa},
fits::{
from_fits_ivoa, multiordermap::from_fits_multiordermap, skymap::from_fits_skymap, MocIdxType,
},
img::to_img_default,
json::{cellmoc2d_from_json_aladin, from_json_aladin},
stcs::stcs2moc,
},
elem::valuedcell::valued_cells_to_moc_with_opt,
elemset::range::HpxRanges,
hpxranges2d::{FreqSpaceMoc, TimeSpaceMoc},
idx::Idx,
moc::{
range::{CellSelection, RangeMOC},
CellMOCIntoIterator, CellMOCIterator, CellOrCellRangeMOCIntoIterator,
CellOrCellRangeMOCIterator, RangeMOCIterator,
},
moc2d::{
range::RangeMOC2, CellMOC2IntoIterator, CellOrCellRangeMOC2IntoIterator, RangeMOC2IntoIterator,
RangeMOC2Iterator,
},
qty::{Frequency, Hpx, MocQty, Time},
storage::u64idx::op1::{
op1_mom_filter, op1_mom_filter_mask, op1_mom_sum, op1_mom_sum_from_data, op1_mom_sum_from_path,
},
};
pub mod common;
mod load;
mod op1;
mod op2;
mod opn;
mod store;
use self::{
common::{
check_depth, lat_deg2rad, lon_deg2rad, lon_deg2rad_relaxed, InternalMoc, MocQType, FMOC,
HALF_PI, PI, SFMOC, SMOC, STMOC, TMOC,
},
load::{
fmoc_from_fits_gen, from_fits_gen, from_fits_u64, sfmoc_from_fits_u64, smoc_from_fits_gen,
stmoc_from_fits_u64, tmoc_from_fits_gen,
},
op1::{
op1_1st_axis_max, op1_1st_axis_min, op1_border_elementary_edges_vertices, op1_count_split,
op1_flatten_to_depth, op1_flatten_to_moc_depth, op1_moc_barycenter,
op1_moc_largest_distance_from_coo_to_moc_vertices, Op1, Op1MultiRes,
},
op2::Op2,
opn::OpN,
};
/// Number of microseconds in a 24h day.
const JD_TO_USEC: f64 = (24_u64 * 60 * 60 * 1_000_000) as f64;
static GLOBAL_STORE: U64MocStore = U64MocStore;
pub struct U64MocStore;
// TODO: add methods
// Filters
// * returning the list of MOCs intersecting/containing a MOC
// - input: array of moc indices
// - output: array of boolean
// * filter on st-moc: Input = iter of ((lon, lat), jd)
// * fill holes
impl U64MocStore {
pub fn get_global_store() -> &'static Self {
&GLOBAL_STORE
}
pub fn insert_smoc(&self, moc: SMOC) -> Result<usize, String> {
store::add(moc)
}
pub fn insert_tmoc(&self, moc: TMOC) -> Result<usize, String> {
store::add(moc)
}
pub fn insert_fmoc(&self, moc: FMOC) -> Result<usize, String> {
store::add(moc)
}
pub fn insert_stmoc(&self, moc: STMOC) -> Result<usize, String> {
store::add(moc)
}
pub fn new_empty_smoc(&self, depth: u8) -> Result<usize, String> {
let moc = RangeMOC::<u64, Hpx<u64>>::new_empty(depth);
store::add(moc)
}
pub fn new_empty_tmoc(&self, depth: u8) -> Result<usize, String> {
let moc = RangeMOC::<u64, Time<u64>>::new_empty(depth);
store::add(moc)
}
pub fn new_empty_fmoc(&self, depth: u8) -> Result<usize, String> {
let moc = RangeMOC::<u64, Frequency<u64>>::new_empty(depth);
store::add(moc)
}
pub fn new_empty_stmoc(&self, depth_time: u8, depth_space: u8) -> Result<usize, String> {
let moc = STMOC::new_empty(depth_time, depth_space);
store::add(moc)
}
pub fn new_empty_sfmoc(&self, depth_freq: u8, depth_space: u8) -> Result<usize, String> {
let moc = SFMOC::new_empty(depth_freq, depth_space);
store::add(moc)
}
/// Copy the moc at the given index
pub fn copy(&self, index: usize) -> Result<(), String> {
store::copy_moc(index)
}
/// Remove from the store the MOC at the given index.
pub fn drop(&self, index: usize) -> Result<(), String> {
store::drop(index).map(|_| ())
}
pub fn drop_smoc(&self, index: usize) -> Result<Option<SMOC>, String> {
store::drop(index).and_then(|opt_moc| {
opt_moc
.map(|moc| match moc {
InternalMoc::Space(moc) => Ok(moc),
_ => Err(String::from("MOC at the given index is not a S-MOC")),
})
.transpose()
})
}
pub fn drop_tmoc(&self, index: usize) -> Result<Option<TMOC>, String> {
store::drop(index).and_then(|opt_moc| {
opt_moc
.map(|moc| match moc {
InternalMoc::Time(moc) => Ok(moc),
_ => Err(String::from("MOC at the given index is not a T-MOC")),
})
.transpose()
})
}
pub fn drop_fmoc(&self, index: usize) -> Result<Option<FMOC>, String> {
store::drop(index).and_then(|opt_moc| {
opt_moc
.map(|moc| match moc {
InternalMoc::Frequency(moc) => Ok(moc),
_ => Err(String::from("MOC at the given index is not a F-MOC")),
})
.transpose()
})
}
pub fn drop_stmoc(&self, index: usize) -> Result<Option<STMOC>, String> {
store::drop(index).and_then(|opt_moc| {
opt_moc
.map(|moc| match moc {
InternalMoc::TimeSpace(moc) => Ok(moc),
_ => Err(String::from("MOC at the given index is not a ST-MOC")),
})
.transpose()
})
}
pub fn get_1st_axis_min(&self, index: usize) -> Result<Option<u64>, String> {
op1_1st_axis_min(index)
}
pub fn get_1st_axis_max(&self, index: usize) -> Result<Option<u64>, String> {
op1_1st_axis_max(index)
}
//////////////////
// Get MOC info //
pub fn get_qty_type(&self, index: usize) -> Result<MocQType, String> {
store::exec_on_one_readonly_moc(index, InternalMoc::get_qty_type)
}
pub fn get_smoc_depth(&self, index: usize) -> Result<u8, String> {
store::exec_on_one_readonly_moc(index, InternalMoc::get_smoc_depth)
}
pub fn get_smoc_copy(&self, index: usize) -> Result<SMOC, String> {
store::exec_on_one_readonly_moc(index, InternalMoc::get_smoc_copy)
}
pub fn get_tmoc_depth(&self, index: usize) -> Result<u8, String> {
store::exec_on_one_readonly_moc(index, InternalMoc::get_tmoc_depth)
}
pub fn get_fmoc_depth(&self, index: usize) -> Result<u8, String> {
store::exec_on_one_readonly_moc(index, InternalMoc::get_fmoc_depth)
}
pub fn get_stmoc_depths(&self, index: usize) -> Result<(u8, u8), String> {
store::exec_on_one_readonly_moc(index, InternalMoc::get_stmoc_time_and_space_depths)
}
pub fn get_sfmoc_depths(&self, index: usize) -> Result<(u8, u8), String> {
store::exec_on_one_readonly_moc(index, InternalMoc::get_sfmoc_freq_and_space_depths)
}
pub fn is_empty(&self, index: usize) -> Result<bool, String> {
store::exec_on_one_readonly_moc(index, InternalMoc::is_empty)
}
pub fn get_n_ranges(&self, index: usize) -> Result<u32, String> {
store::exec_on_one_readonly_moc(index, InternalMoc::get_n_ranges)
}
pub fn get_ranges_sum(&self, index: usize) -> Result<u64, String> {
store::exec_on_one_readonly_moc(index, InternalMoc::get_ranges_sum)
}
pub fn get_coverage_percentage(&self, index: usize) -> Result<f64, String> {
store::exec_on_one_readonly_moc(index, |internal_moc| {
internal_moc
.get_coverage_percentage()
.ok_or_else(|| String::from("No coverage available for this type of MOC"))
})
}
pub fn eq(&self, left_index: usize, right_index: usize) -> Result<bool, String> {
store::exec_on_two_readonly_mocs(left_index, right_index, |l, r| Ok(l == r))
}
pub fn to_uniq_hpx(&self, index: usize) -> Result<Vec<u64>, String> {
store::exec_on_one_readonly_moc(index, InternalMoc::get_uniq_hpx)
}
pub fn to_uniq_gen(&self, index: usize) -> Result<Vec<u64>, String> {
store::exec_on_one_readonly_moc(index, InternalMoc::get_uniq_gen)
}
pub fn to_uniq_zorder(&self, index: usize) -> Result<Vec<u64>, String> {
store::exec_on_one_readonly_moc(index, InternalMoc::get_uniq_zorder)
}
pub fn to_ranges(&self, index: usize) -> Result<Vec<Range<u64>>, String> {
store::exec_on_one_readonly_moc(index, InternalMoc::get_ranges)
}
pub fn to_hz_ranges(&self, index: usize) -> Result<Vec<Range<f64>>, String> {
store::exec_on_one_readonly_moc(index, InternalMoc::get_hz_ranges)
}
///////////////////////
// LOAD EXISTING MOC //
// - from fits //
/// Load a MOC from the pre-loaded content of a FITS file, and put it in the store
///
/// # Output
/// - The index in the storage
pub fn load_from_fits_file<P: AsRef<Path>>(&self, source: P) -> Result<usize, String> {
let file = File::open(&source).map_err(|e| e.to_string())?;
let reader = BufReader::new(file);
self.load_from_fits(reader)
}
/// Load a MOC from the pre-loaded content of a FITS file, and put it in the store
///
/// # Output
/// - The index in the storage
pub fn load_from_fits_buff(&self, content: &[u8]) -> Result<usize, String> {
self.load_from_fits(Cursor::new(content))
}
pub fn load_from_fits<R: BufRead>(&self, reader: R) -> Result<usize, String> {
from_fits_ivoa(reader)
.map_err(|e| e.to_string())
.and_then(|moc| {
match moc {
MocIdxType::U16(moc) => from_fits_gen(moc),
MocIdxType::U32(moc) => from_fits_gen(moc),
MocIdxType::U64(moc) => from_fits_u64(moc),
}
.map_err(|e| e.to_string())
})
.and_then(store::add)
}
/// Load a MOC from the pre-loaded content of a FITS file, and put it in the store
///
/// # Output
/// - The index in the storage
pub fn load_smoc_from_fits_file<P: AsRef<Path>>(&self, source: P) -> Result<usize, String> {
let file = File::open(&source).map_err(|e| e.to_string())?;
let reader = BufReader::new(file);
self.load_smoc_from_fits(reader)
}
/// Load a MOC from the pre-loaded content of a FITS file, and put it in the store
///
/// # Output
/// - The index in the storage
pub fn load_smoc_from_fits_buff(&self, content: &[u8]) -> Result<usize, String> {
self.load_smoc_from_fits(Cursor::new(content))
}
pub fn load_smoc_from_fits<R: BufRead>(&self, reader: R) -> Result<usize, String> {
from_fits_ivoa(reader)
.map_err(|e| e.to_string())
.and_then(|moc| {
match moc {
MocIdxType::U16(moc) => smoc_from_fits_gen(moc),
MocIdxType::U32(moc) => smoc_from_fits_gen(moc),
MocIdxType::U64(moc) => smoc_from_fits_gen(moc),
}
.map_err(|e| e.to_string())
})
.and_then(store::add)
}
/// Load a MOC from the pre-loaded content of a FITS file, and put it in the store
///
/// # Output
/// - The index in the storage
pub fn load_tmoc_from_fits_file<P: AsRef<Path>>(&self, source: P) -> Result<usize, String> {
let file = File::open(&source).map_err(|e| e.to_string())?;
let reader = BufReader::new(file);
self.load_tmoc_from_fits(reader)
}
/// Load a MOC from the pre-loaded content of a FITS file, and put it in the store
///
/// # Output
/// - The index in the storage
pub fn load_tmoc_from_fits_buff(&self, content: &[u8]) -> Result<usize, String> {
self.load_tmoc_from_fits(Cursor::new(content))
}
pub fn load_tmoc_from_fits<R: BufRead>(&self, reader: R) -> Result<usize, String> {
from_fits_ivoa(reader)
.map_err(|e| e.to_string())
.and_then(|moc| {
match moc {
MocIdxType::U16(moc) => tmoc_from_fits_gen(moc),
MocIdxType::U32(moc) => tmoc_from_fits_gen(moc),
MocIdxType::U64(moc) => tmoc_from_fits_gen(moc),
}
.map_err(|e| e.to_string())
})
.and_then(store::add)
}
/// Load a MOC from the pre-loaded content of a FITS file, and put it in the store
///
/// # Output
/// - The index in the storage
pub fn load_fmoc_from_fits_file<P: AsRef<Path>>(&self, source: P) -> Result<usize, String> {
let file = File::open(&source).map_err(|e| e.to_string())?;
let reader = BufReader::new(file);
self.load_fmoc_from_fits(reader)
}
/// Load a MOC from the pre-loaded content of a FITS file, and put it in the store
///
/// # Output
/// - The index in the storage
pub fn load_fmoc_from_fits_buff(&self, content: &[u8]) -> Result<usize, String> {
self.load_fmoc_from_fits(Cursor::new(content))
}
pub fn load_fmoc_from_fits<R: BufRead>(&self, reader: R) -> Result<usize, String> {
from_fits_ivoa(reader)
.map_err(|e| e.to_string())
.and_then(|moc| {
match moc {
MocIdxType::U16(moc) => fmoc_from_fits_gen(moc),
MocIdxType::U32(moc) => fmoc_from_fits_gen(moc),
MocIdxType::U64(moc) => fmoc_from_fits_gen(moc),
}
.map_err(|e| e.to_string())
})
.and_then(store::add)
}
/// Load a MOC from the pre-loaded content of a FITS file, and put it in the store
///
/// # Output
/// - The index in the storage
pub fn load_stmoc_from_fits_file<P: AsRef<Path>>(&self, source: P) -> Result<usize, String> {
let file = File::open(&source).map_err(|e| e.to_string())?;
let reader = BufReader::new(file);
self.load_stmoc_from_fits(reader)
}
/// Load a MOC from the pre-loaded content of a FITS file, and put it in the store
///
/// # Output
/// - The index in the storage
pub fn load_stmoc_from_fits_buff(&self, content: &[u8]) -> Result<usize, String> {
self.load_stmoc_from_fits(Cursor::new(content))
}
pub fn load_stmoc_from_fits<R: BufRead>(&self, reader: R) -> Result<usize, String> {
from_fits_ivoa(reader)
.map_err(|e| e.to_string())
.and_then(|moc| {
match moc {
MocIdxType::U16(_) => Err(String::from("Only u64 ST-MOCs are supported").into()),
MocIdxType::U32(_) => Err(String::from("Only u64 ST-MOCs are supported").into()),
MocIdxType::U64(moc) => stmoc_from_fits_u64(moc),
}
.map_err(|e| e.to_string())
})
.and_then(store::add)
}
/// Load a MOC from the pre-loaded content of a FITS file, and put it in the store
///
/// # Output
/// - The index in the storage
pub fn load_sfmoc_from_fits_file<P: AsRef<Path>>(&self, source: P) -> Result<usize, String> {
let file = File::open(&source).map_err(|e| e.to_string())?;
let reader = BufReader::new(file);
self.load_sfmoc_from_fits(reader)
}
/// Load a MOC from the pre-loaded content of a FITS file, and put it in the store
///
/// # Output
/// - The index in the storage
pub fn load_sfmoc_from_fits_buff(&self, content: &[u8]) -> Result<usize, String> {
self.load_sfmoc_from_fits(Cursor::new(content))
}
pub fn load_sfmoc_from_fits<R: BufRead>(&self, reader: R) -> Result<usize, String> {
from_fits_ivoa(reader)
.map_err(|e| e.to_string())
.and_then(|moc| {
match moc {
MocIdxType::U16(_) => Err(String::from("Only u64 ST-MOCs are supported").into()),
MocIdxType::U32(_) => Err(String::from("Only u64 ST-MOCs are supported").into()),
MocIdxType::U64(moc) => sfmoc_from_fits_u64(moc),
}
.map_err(|e| e.to_string())
})
.and_then(store::add)
}
/// Create o S-MOC from a FITS multi-order map plus other parameters.
/// # Args
/// * `path`: path of the fits file
/// * `from_threshold`: Cumulative value at which we start putting cells in he MOC (often = 0).
/// * `to_threshold`: Cumulative value at which we stop putting cells in the MOC.
/// * `asc`: Compute cumulative value from ascending density values instead of descending (often = false).
/// * `not_strict`: Cells overlapping with the upper or the lower cumulative bounds are not rejected (often = false).
/// * `split`: Split recursively the cells overlapping the upper or the lower cumulative bounds (often = false).
/// * `revese_recursive_descent`: Perform the recursive descent from the highest to the lowest sub-cell, only with option 'split' (set both flags to be compatibile with Aladin)
pub fn from_multiordermap_fits_file<P: AsRef<Path>>(
&self,
path: P,
from_threshold: f64,
to_threshold: f64,
asc: bool,
not_strict: bool,
split: bool,
revese_recursive_descent: bool,
) -> Result<usize, String> {
let file = File::open(&path).map_err(|e| e.to_string())?;
let reader = BufReader::new(file);
from_fits_multiordermap(
reader,
from_threshold,
to_threshold,
asc,
!not_strict,
split,
revese_recursive_descent,
)
.map_err(|e| e.to_string())
.and_then(store::add)
}
/// Create o S-MOC from a FITS multi-order map plus other parameters.
/// # Args
/// * `data`: binary content of the fits file
/// * `from_threshold`: Cumulative value at which we start putting cells in he MOC (often = 0).
/// * `to_threshold`: Cumulative value at which we stop putting cells in the MOC.
/// * `asc`: Compute cumulative value from ascending density values instead of descending (often = false).
/// * `not_strict`: Cells overlapping with the upper or the lower cumulative bounds are not rejected (often = false).
/// * `split`: Split recursively the cells overlapping the upper or the lower cumulative bounds (often = false).
/// * `revese_recursive_descent`: Perform the recursive descent from the highest to the lowest sub-cell, only with option 'split' (set both flags to be compatibile with Aladin)
pub fn from_multiordermap_fits_file_content(
&self,
data: &[u8],
from_threshold: f64,
to_threshold: f64,
asc: bool,
not_strict: bool,
split: bool,
revese_recursive_descent: bool,
) -> Result<usize, String> {
from_fits_multiordermap(
BufReader::new(Cursor::new(data)),
from_threshold,
to_threshold,
asc,
!not_strict,
split,
revese_recursive_descent,
)
.map_err(|e| e.to_string())
.and_then(store::add)
}
/// Create o S-MOC from a FITS skymap plus other parameters.
/// # Args
/// * `path`: path of the fits file
/// * `skip_values_le`: skip cells associated to values lower or equal to the given value
/// * `from_threshold`: Cumulative value at which we start putting cells in he MOC (often = 0).
/// * `to_threshold`: Cumulative value at which we stop putting cells in the MOC.
/// * `asc`: Compute cumulative value from ascending density values instead of descending (often = false).
/// * `not_strict`: Cells overlapping with the upper or the lower cumulative bounds are not rejected (often = false).
/// * `split`: Split recursively the cells overlapping the upper or the lower cumulative bounds (often = false).
/// * `revese_recursive_descent`: Perform the recursive descent from the highest to the lowest sub-cell, only with option 'split' (set both flags to be compatibile with Aladin)
pub fn from_skymap_fits_file<P: AsRef<Path>>(
&self,
path: P,
skip_values_le: f64,
from_threshold: f64,
to_threshold: f64,
asc: bool,
not_strict: bool,
split: bool,
revese_recursive_descent: bool,
) -> Result<usize, String> {
let file = File::open(&path).map_err(|e| e.to_string())?;
let reader = BufReader::new(file);
from_fits_skymap(
reader,
skip_values_le,
from_threshold,
to_threshold,
asc,
!not_strict,
split,
revese_recursive_descent,
)
.map_err(|e| e.to_string())
.and_then(store::add)
}
/// Create o S-MOC from a FITS skymap plus other parameters.
/// # Args
/// * `data`: binary content of the fits file
/// * `skip_values_le`: skip cells associated to values lower or equal to the given value
/// * `from_threshold`: Cumulative value at which we start putting cells in he MOC (often = 0).
/// * `to_threshold`: Cumulative value at which we stop putting cells in the MOC.
/// * `asc`: Compute cumulative value from ascending density values instead of descending (often = false).
/// * `not_strict`: Cells overlapping with the upper or the lower cumulative bounds are not rejected (often = false).
/// * `split`: Split recursively the cells overlapping the upper or the lower cumulative bounds (often = false).
/// * `revese_recursive_descent`: Perform the recursive descent from the highest to the lowest sub-cell, only with option 'split' (set both flags to be compatibile with Aladin)
pub fn from_skymap_fits_file_content(
&self,
data: &[u8],
skip_values_le: f64,
from_threshold: f64,
to_threshold: f64,
asc: bool,
not_strict: bool,
split: bool,
revese_recursive_descent: bool,
) -> Result<usize, String> {
from_fits_skymap(
BufReader::new(Cursor::new(data)),
skip_values_le,
from_threshold,
to_threshold,
asc,
!not_strict,
split,
revese_recursive_descent,
)
.map_err(|e| e.to_string())
.and_then(store::add)
}
// - from ascii //
pub fn load_smoc_from_ascii_file<P: AsRef<Path>>(&self, path: P) -> Result<usize, String> {
fs::read_to_string(path)
.map_err(|e| e.to_string())
.and_then(|s| self.load_smoc_from_ascii(&s))
}
pub fn load_tmoc_from_ascii_file<P: AsRef<Path>>(&self, path: P) -> Result<usize, String> {
fs::read_to_string(path)
.map_err(|e| e.to_string())
.and_then(|s| self.load_tmoc_from_ascii(&s))
}
pub fn load_fmoc_from_ascii_file<P: AsRef<Path>>(&self, path: P) -> Result<usize, String> {
fs::read_to_string(path)
.map_err(|e| e.to_string())
.and_then(|s| self.load_fmoc_from_ascii(&s))
}
pub fn load_stmoc_from_ascii_file<P: AsRef<Path>>(&self, path: P) -> Result<usize, String> {
fs::read_to_string(path)
.map_err(|e| e.to_string())
.and_then(|s| self.load_stmoc_from_ascii(&s))
}
pub fn load_sfmoc_from_ascii_file<P: AsRef<Path>>(&self, path: P) -> Result<usize, String> {
fs::read_to_string(path)
.map_err(|e| e.to_string())
.and_then(|s| self.load_sfmoc_from_ascii(&s))
}
pub fn load_smoc_from_ascii(&self, content: &str) -> Result<usize, String> {
from_ascii_ivoa::<u64, Hpx<u64>>(content)
.map_err(|e| e.to_string())
.and_then(|cellcellranges| {
let moc = cellcellranges
.into_cellcellrange_moc_iter()
.ranges()
.into_range_moc();
store::add(moc)
})
}
pub fn load_tmoc_from_ascii(&self, content: &str) -> Result<usize, String> {
from_ascii_ivoa::<u64, Time<u64>>(content)
.map_err(|e| e.to_string())
.and_then(|cellcellranges| {
let moc = cellcellranges
.into_cellcellrange_moc_iter()
.ranges()
.into_range_moc();
store::add(moc)
})
}
pub fn load_fmoc_from_ascii(&self, content: &str) -> Result<usize, String> {
from_ascii_ivoa::<u64, Frequency<u64>>(content)
.map_err(|e| e.to_string())
.and_then(|cellcellranges| {
let moc = cellcellranges
.into_cellcellrange_moc_iter()
.ranges()
.into_range_moc();
store::add(moc)
})
}
pub fn load_stmoc_from_ascii(&self, content: &str) -> Result<usize, String> {
moc2d_from_ascii_ivoa::<u64, Time<u64>, u64, Hpx<u64>>(content)
.map_err(|e| e.to_string())
.and_then(|cellrange2| {
let moc2 = cellrange2
.into_cellcellrange_moc2_iter()
.into_range_moc2_iter()
.into_range_moc2();
store::add(moc2)
})
}
pub fn load_sfmoc_from_ascii(&self, content: &str) -> Result<usize, String> {
moc2d_from_ascii_ivoa::<u64, Frequency<u64>, u64, Hpx<u64>>(content)
.map_err(|e| e.to_string())
.and_then(|cellrange2| {
let moc2 = cellrange2
.into_cellcellrange_moc2_iter()
.into_range_moc2_iter()
.into_range_moc2();
store::add(moc2)
})
}
// - from json //
pub fn load_smoc_from_json_file<P: AsRef<Path>>(&self, path: P) -> Result<usize, String> {
fs::read_to_string(path)
.map_err(|e| e.to_string())
.and_then(|s| self.load_smoc_from_json(&s))
}
pub fn load_tmoc_from_json_file<P: AsRef<Path>>(&self, path: P) -> Result<usize, String> {
fs::read_to_string(path)
.map_err(|e| e.to_string())
.and_then(|s| self.load_tmoc_from_json(&s))
}
pub fn load_fmoc_from_json_file<P: AsRef<Path>>(&self, path: P) -> Result<usize, String> {
fs::read_to_string(path)
.map_err(|e| e.to_string())
.and_then(|s| self.load_fmoc_from_json(&s))
}
pub fn load_stmoc_from_json_file<P: AsRef<Path>>(&self, path: P) -> Result<usize, String> {
fs::read_to_string(path)
.map_err(|e| e.to_string())
.and_then(|s| self.load_stmoc_from_json(&s))
}
pub fn load_sfmoc_from_json_file<P: AsRef<Path>>(&self, path: P) -> Result<usize, String> {
fs::read_to_string(path)
.map_err(|e| e.to_string())
.and_then(|s| self.load_sfmoc_from_json(&s))
}
pub fn load_smoc_from_json(&self, content: &str) -> Result<usize, String> {
from_json_aladin::<u64, Hpx<u64>>(content)
.map_err(|e| e.to_string())
.and_then(|cellrange2| {
let moc = cellrange2.into_cell_moc_iter().ranges().into_range_moc();
store::add(moc)
})
}
pub fn load_tmoc_from_json(&self, content: &str) -> Result<usize, String> {
from_json_aladin::<u64, Time<u64>>(content)
.map_err(|e| e.to_string())
.and_then(|cells| {
let moc = cells.into_cell_moc_iter().ranges().into_range_moc();
store::add(moc)
})
}
pub fn load_fmoc_from_json(&self, content: &str) -> Result<usize, String> {
from_json_aladin::<u64, Frequency<u64>>(content)
.map_err(|e| e.to_string())
.and_then(|cells| {
let moc = cells.into_cell_moc_iter().ranges().into_range_moc();
store::add(moc)
})
}
pub fn load_stmoc_from_json(&self, content: &str) -> Result<usize, String> {
cellmoc2d_from_json_aladin::<u64, Time<u64>, u64, Hpx<u64>>(content)
.map_err(|e| e.to_string())
.and_then(|cell2| {
let moc2 = cell2
.into_cell_moc2_iter()
.into_range_moc2_iter()
.into_range_moc2();
store::add(moc2)
})
}
pub fn load_sfmoc_from_json(&self, content: &str) -> Result<usize, String> {
cellmoc2d_from_json_aladin::<u64, Frequency<u64>, u64, Hpx<u64>>(content)
.map_err(|e| e.to_string())
.and_then(|cell2| {
let moc2 = cell2
.into_cell_moc2_iter()
.into_range_moc2_iter()
.into_range_moc2();
store::add(moc2)
})
}
///////////////////////
// SAVE EXISTING MOC //
/// # Params
/// * `smoc`: the Spatial MOC to be print;
/// * `img_y_size`: the `Y` number of pixels in the image, the image size will be `(2*Y, Y)`;
pub fn to_png(&self, moc_index: usize, img_y_size: u16) -> Result<Box<[u8]>, String> {
let xsize = (img_y_size << 1) as usize;
let ysize = img_y_size as usize;
let op = move |moc: &InternalMoc| match moc {
InternalMoc::Space(smoc) => {
let data = to_img_default(smoc, (xsize as u16, ysize as u16), None, None, None);
let mut buff = Vec::<u8>::with_capacity(1024 + xsize * ysize);
let mut encoder = png::Encoder::new(&mut buff, xsize as u32, ysize as u32);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder
.write_header()
.map_err(|e| e.to_string())
.and_then(move |mut writer| writer.write_image_data(&data).map_err(|e| e.to_string()))
.map(move |_| buff.into_boxed_slice())
}
_ => Err(String::from(
"Can't make a PNG for a MOC different from a S-MOC",
)),
};
store::exec_on_one_readonly_moc(moc_index, op)
}
/// Returns an RGBA array (each pixel is made of 4 successive u8: RGBA) using the Mollweide projection.
pub fn to_image(&self, moc_index: usize, img_y_size: u16) -> Result<Box<[u8]>, String> {
let xsize = (img_y_size << 1) as usize;
let ysize = img_y_size as usize;
let op = move |moc: &InternalMoc| match moc {
InternalMoc::Space(smoc) => {
Ok(to_img_default(smoc, (xsize as u16, ysize as u16), None, None, None).into_boxed_slice())
}
_ => Err(String::from(
"Can't make an image for a MOC different from a S-MOC",
)),
};
store::exec_on_one_readonly_moc(moc_index, op)
}
/// Returns the ASCII serialization of the given MOC.
/// # Args
///
pub fn to_ascii_str(&self, moc_index: usize, fold: Option<usize>) -> Result<String, String> {
// from_str creates a copy :o/
store::exec_on_one_readonly_moc(moc_index, move |moc| moc.to_ascii_str(fold))
}
/// Write the ASCII serialization of the given MOC in the given path.
/// # Args
///
pub fn to_ascii_file<P: AsRef<Path>>(
&self,
moc_index: usize,
destination: P,
fold: Option<usize>,
) -> Result<(), String> {
// from_str creates a copy :o/
store::exec_on_one_readonly_moc(moc_index, move |moc| moc.to_ascii_file(destination, fold))
}
// Instead of returning a String, we should probably return a map of (depth, array of indices) values :o/
/// Returns the JSON serialization of the given MOC.
/// # Args
///
pub fn to_json_str(&self, moc_index: usize, fold: Option<usize>) -> Result<String, String> {
store::exec_on_one_readonly_moc(moc_index, move |moc| moc.to_json_str(fold))
}
/// Write the KSON serialization of the given MOC in the given path.
/// # Args
///
pub fn to_json_file<P: AsRef<Path>>(
&self,
moc_index: usize,
destination: P,
fold: Option<usize>,
) -> Result<(), String> {
store::exec_on_one_readonly_moc(moc_index, move |moc| moc.to_json_file(destination, fold))
}
/// Returns in memory the FITS serialization of the MOC of given `name`.
/// # Args
/// * `name`: name of the MOC in the internal store
/// * `force_v1_compatibility`: for S-MOCs, force compatibility with Version 1 of the MOC standard.
pub fn to_fits_buff(
&self,
moc_index: usize,
force_v1_compatibility: Option<bool>,
) -> Result<Box<[u8]>, String> {
store::exec_on_one_readonly_moc(moc_index, move |moc| {
moc.to_fits_buff(force_v1_compatibility.unwrap_or(false))
})
}
/// Returns in memory the FITS serialization of the MOC of given `name` in the given path.
/// # Args
/// * `name`: name of the MOC in the internal store
/// * `force_v1_compatibility`: for S-MOCs, force compatibility with Version 1 of the MOC standard.
pub fn to_fits_file<P: AsRef<Path>>(
&self,
moc_index: usize,
destination: P,
force_v1_compatibility: Option<bool>,
) -> Result<(), String> {
store::exec_on_one_readonly_moc(moc_index, move |moc| {
moc.to_fits_file(destination, force_v1_compatibility.unwrap_or(false))
})
}
//////////////////
// MOC CREATION //
// * S-MOC CREATION //
pub fn from_hpx_cells<T: Idx, I>(
&self,
depth: u8,
cells_it: I,
buf_capacity: Option<usize>,
) -> Result<usize, String>
where
I: Iterator<Item = (u8, T)>,
{
let it = cells_it.map(|(depth, idx)| (depth, idx.to_u64()));
let moc: RangeMOC<u64, Hpx<u64>> = RangeMOC::from_cells(depth, it, buf_capacity);
store::add(moc)
}
pub fn from_hpx_ranges<T: Idx, I>(
&self,
depth: u8,
ranges_it: I,
buf_capacity: Option<usize>,
) -> Result<usize, String>
where
I: Iterator<Item = Range<T>>,
{
let it = ranges_it.map(|range| T::to_u64_idx(range.start)..T::to_u64_idx(range.end));
let moc: RangeMOC<u64, Hpx<u64>> = RangeMOC::from_maxdepth_ranges(depth, it, buf_capacity);
store::add(moc)
}
/// Create and store a MOC from the given cone.
///
/// # Input
/// * `lon_deg` the longitude of the center of the cone, in degrees
/// * `lat_deg` the latitude of the center of the cone, in degrees
/// * `radius_deg` the radius of the cone, in degrees
/// * `depth`: the MOC depth
/// * `delta_depth` the difference between the MOC depth and the depth at which the computations
/// are made (should remain quite small).
/// * `selection`: select BMOC cells to keep in the MOC
///
/// # Output
/// - The index in the storage
pub fn from_cone(
&self,
lon_deg: f64,
lat_deg: f64,
radius_deg: f64,
depth: u8,
delta_depth: u8,
selection: CellSelection,
) -> Result<usize, String> {
check_depth::<Hpx<u64>>(depth)?;
let lon = lon_deg2rad(lon_deg)?;
let lat = lat_deg2rad(lat_deg)?;
let r = radius_deg.to_radians();
if (0.0..=PI).contains(&r) {
let dd = delta_depth.min(Hpx::<u64>::MAX_DEPTH - depth);
let moc: RangeMOC<u64, Hpx<u64>> = RangeMOC::from_cone(lon, lat, r, depth, dd, selection);
store::add(moc)
} else {
Err(String::from("Cone radius must be in [0, pi["))
}
}
/// Create and store a MOC from the given ring.
///
/// # Input
/// * `lon_deg` the longitude of the center of the ring, in degrees
/// * `lat_deg` the latitude of the center of the ring, in degrees
/// * `internal_radius_deg` the internal radius of the ring, in degrees
/// * `external_radius_deg` the external radius of the ring, in degrees
/// * `depth`: the MOC depth
/// * `delta_depth` the difference between the MOC depth and the depth at which the computations
/// are made (should remain quite small).
/// * `selection`: select BMOC cells to keep in the MOC
///
/// # Output
/// - The index in the storage
pub fn from_ring(
&self,
lon_deg: f64,
lat_deg: f64,
internal_radius_deg: f64,
external_radius_deg: f64,
depth: u8,
delta_depth: u8,
selection: CellSelection,
) -> Result<usize, String> {
check_depth::<Hpx<u64>>(depth)?;
let lon = lon_deg2rad(lon_deg)?;
let lat = lat_deg2rad(lat_deg)?;
let r_int = internal_radius_deg.to_radians();
let r_ext = external_radius_deg.to_radians();
if r_int <= 0.0 || PI <= r_int {
Err(String::from("Internal radius must be in ]0, pi["))
} else if r_ext <= 0.0 || PI <= r_ext {
Err(String::from("External radius must be in ]0, pi["))
} else if r_ext < r_int {
Err(String::from(
"External radius must be larger than the internal radius",
))
} else {
let dd = delta_depth.min(Hpx::<u64>::MAX_DEPTH - depth);
let moc: RangeMOC<u64, Hpx<u64>> =
RangeMOC::from_ring(lon, lat, r_int, r_ext, depth, dd, selection);
store::add(moc)
}
}
/// Create and store a MOC from the given elliptical cone.
///
/// # Input
/// * `lon_deg` the longitude of the center of the elliptical cone, in degrees
/// * `lat_deg` the latitude of the center of the elliptical cone, in degrees
/// * `a_deg` the semi-major axis of the elliptical cone, in degrees
/// * `b_deg` the semi-minor axis of the elliptical cone, in degrees
/// * `pa_deg` the position angle (i.e. the angle between the north and the semi-major axis, east-of-north), in degrees
/// * `depth`: the MOC depth
/// * `delta_depth` the difference between the MOC depth and the depth at which the computations
/// are made (should remain quite small).
/// * `selection`: select BMOC cells to keep in the MOC
///
/// # Output
/// - The index in the storage
pub fn from_elliptical_cone(
&self,
lon_deg: f64,
lat_deg: f64,
a_deg: f64,
b_deg: f64,
pa_deg: f64,
depth: u8,
delta_depth: u8,
selection: CellSelection,
) -> Result<usize, String> {
check_depth::<Hpx<u64>>(depth)?;
let lon = lon_deg2rad(lon_deg)?;
let lat = lat_deg2rad(lat_deg)?;
let a = a_deg.to_radians();
let b = b_deg.to_radians();
let pa = pa_deg.to_radians();
if a <= 0.0 || HALF_PI <= a {
Err(String::from("Semi-major axis must be in ]0, pi/2]"))
} else if b <= 0.0 || a <= b {
Err(String::from("Semi-minor axis must be in ]0, a["))
} else if pa < 0.0 || PI <= pa {
Err(String::from("Position angle must be in [0, pi["))
} else {
let dd = delta_depth.min(Hpx::<u64>::MAX_DEPTH - depth);
let moc: RangeMOC<u64, Hpx<u64>> =
RangeMOC::from_elliptical_cone(lon, lat, a, b, pa, depth, dd, selection);
store::add(moc)
}
}
/// Create and store a MOC from the given zone.
///
/// # Input
/// * `lon_deg_min` the longitude of the bottom left corner, in degrees
/// * `lat_deg_min` the latitude of the bottom left corner, in degrees
/// * `lon_deg_max` the longitude of the upper left corner, in degrees
/// * `lat_deg_max` the latitude of the upper left corner, in degrees
/// * `depth`: the MOC depth
/// * `selection`: select BMOC cells to keep in the MOC
///
/// # Output
/// - The index in the storage
///
/// # Remark
/// - If `lon_min > lon_max` then we consider that the zone crosses the primary meridian.
/// - The north pole is included only if `lon_min == 0 && lat_max == pi/2`
pub fn from_zone(
&self,
lon_deg_min: f64,
lat_deg_min: f64,
lon_deg_max: f64,
lat_deg_max: f64,
depth: u8,
selection: CellSelection,
) -> Result<usize, String> {
check_depth::<Hpx<u64>>(depth)?;
let lon_min = lon_deg2rad(lon_deg_min)?;
let lat_min = lat_deg2rad(lat_deg_min)?;
let lon_max = lon_deg2rad_relaxed(lon_deg_max)?;
let lat_max = lat_deg2rad(lat_deg_max)?;
let moc: RangeMOC<u64, Hpx<u64>> =
RangeMOC::from_zone(lon_min, lat_min, lon_max, lat_max, depth, selection);
store::add(moc)
}
/// Create and store a MOC from the given box.
///
/// # Input
/// * `lon_deg` the longitude of the center of the box, in degrees
/// * `lat_deg` the latitude of the center of the box, in degrees
/// * `a_deg` the semi-major axis of the box (half the box width), in degrees
/// * `b_deg` the semi-minor axis of the box (half the box height), in degrees
/// * `pa_deg` the position angle (i.e. the angle between the north and the semi-major axis, east-of-north), in degrees
/// * `depth`: the MOC depth
/// * `selection`: select BMOC cells to keep in the MOC
///
/// # Output
/// - The index in the storage
pub fn from_box(
&self,
lon_deg: f64,
lat_deg: f64,
a_deg: f64,
b_deg: f64,
pa_deg: f64,
depth: u8,
selection: CellSelection,
) -> Result<usize, String> {
check_depth::<Hpx<u64>>(depth)?;
let lon = lon_deg2rad(lon_deg)?;
let lat = lat_deg2rad(lat_deg)?;
let a = a_deg.to_radians();
let b = b_deg.to_radians();
let pa = pa_deg.to_radians();
if a <= 0.0 || HALF_PI <= a {
Err(String::from("Semi-major axis must be in ]0, pi/2]"))
} else if b <= 0.0 || a < b {
Err(String::from("Semi-minor axis must be in ]0, a["))
} else if pa < 0.0 || PI <= pa {
Err(String::from("Position angle must be in [0, pi["))
} else {
let moc: RangeMOC<u64, Hpx<u64>> = RangeMOC::from_box(lon, lat, a, b, pa, depth, selection);
store::add(moc)
}
}
/*pub fn from_boxes() {
// ((lon_deg, lat_deg), ((a_deg, b_deg), pa_deg))
}*/
pub fn from_small_boxes<T>(&self, depth: u8, coos_and_params_deg: T) -> Result<usize, String>
where
T: Iterator<Item = ((f64, f64), ((f64, f64), f64))>,
{
check_depth::<Hpx<u64>>(depth)?;
let coos_and_params_rad_it =
coos_and_params_deg.filter_map(|((lon_deg, lat_deg), ((a_deg, b_deg), pa_deg))| {
let lon = lon_deg2rad(lon_deg);
let lat = lat_deg2rad(lat_deg);
let a = a_deg.to_radians();
let b = b_deg.to_radians();
let pa = pa_deg.to_radians();
match (lon, lat) {
(Ok(lon), Ok(lat)) => {
if a <= 0.0 || HALF_PI <= a {
None
} else if b <= 0.0 || a < b {
None
} else if pa < 0.0 || PI <= pa {
None
} else {
Some((lon, lat, a, b, pa))
}
}
_ => None,
}
});
let moc: RangeMOC<u64, Hpx<u64>> =
RangeMOC::from_small_boxes(depth, coos_and_params_rad_it, None);
store::add(moc)
}
pub fn from_large_boxes<T>(
&self,
depth: u8,
selection: CellSelection,
coos_and_params_deg: T,
) -> Result<usize, String>
where
T: Iterator<Item = ((f64, f64), ((f64, f64), f64))>,
{
check_depth::<Hpx<u64>>(depth)?;
let coos_and_params_rad_it =
coos_and_params_deg.filter_map(|((lon_deg, lat_deg), ((a_deg, b_deg), pa_deg))| {
let lon = lon_deg2rad(lon_deg);
let lat = lat_deg2rad(lat_deg);
let a = a_deg.to_radians();
let b = b_deg.to_radians();
let pa = pa_deg.to_radians();
match (lon, lat) {
(Ok(lon), Ok(lat)) => {
if a <= 0.0 || HALF_PI <= a {
None
} else if b <= 0.0 || a < b {
None
} else if pa < 0.0 || PI <= pa {
None
} else {
Some((lon, lat, a, b, pa))
}
}
_ => None,
}
});
let moc: RangeMOC<u64, Hpx<u64>> =
RangeMOC::from_large_boxes(depth, selection, coos_and_params_rad_it);
store::add(moc)
}
/// Same as `from_large_cones`, but in parallel.
#[cfg(not(target_arch = "wasm32"))]
pub fn from_small_boxes_par<T>(&self, depth: u8, coos_and_params_deg: T) -> Result<usize, String>
where
T: ParallelIterator<Item = ((f64, f64), ((f64, f64), f64))>,
{
check_depth::<Hpx<u64>>(depth)?;
let coos_and_params_rad_it =
coos_and_params_deg.filter_map(|((lon_deg, lat_deg), ((a_deg, b_deg), pa_deg))| {
let lon = lon_deg2rad(lon_deg);
let lat = lat_deg2rad(lat_deg);
let a = a_deg.to_radians();
let b = b_deg.to_radians();
let pa = pa_deg.to_radians();
match (lon, lat) {
(Ok(lon), Ok(lat)) => {
if a <= 0.0 || HALF_PI <= a {
None
} else if b <= 0.0 || a < b {
None
} else if pa < 0.0 || PI <= pa {
None
} else {
Some((lon, lat, a, b, pa))
}
}
_ => None,
}
});
let moc: RangeMOC<u64, Hpx<u64>> =
RangeMOC::from_small_boxes_par(depth, coos_and_params_rad_it, None);
store::add(moc)
}
#[cfg(not(target_arch = "wasm32"))]
pub fn from_large_boxes_par<T>(
&self,
depth: u8,
selection: CellSelection,
coos_and_params_deg: T,
) -> Result<usize, String>
where
T: ParallelIterator<Item = ((f64, f64), ((f64, f64), f64))>,
{
check_depth::<Hpx<u64>>(depth)?;
let coos_and_params_rad_it =
coos_and_params_deg.filter_map(|((lon_deg, lat_deg), ((a_deg, b_deg), pa_deg))| {
let lon = lon_deg2rad(lon_deg);
let lat = lat_deg2rad(lat_deg);
let a = a_deg.to_radians();
let b = b_deg.to_radians();
let pa = pa_deg.to_radians();
match (lon, lat) {
(Ok(lon), Ok(lat)) => {
if a <= 0.0 || HALF_PI <= a {
None
} else if b <= 0.0 || a < b {
None
} else if pa < 0.0 || PI <= pa {
None
} else {
Some((lon, lat, a, b, pa))
}
}
_ => None,
}
});
let moc: RangeMOC<u64, Hpx<u64>> =
RangeMOC::from_large_boxes_par(depth, selection, coos_and_params_rad_it);
store::add(moc)
}
/// Create and store a new MOC from the given polygon vertices.
///
/// # Params
/// * `vertices`: vertices coordinates, in degrees
/// * `complement`: reverse the default inside/outside of the polygon
/// * `depth`: MOC maximum depth in `[0, 29]`
/// * `selection`: select BMOC cells to keep in the MOC
///
/// # Output
/// - The index in the storage
pub fn from_polygon<T>(
&self,
vertices_it: T,
complement: bool,
depth: u8,
selection: CellSelection,
) -> Result<usize, String>
where
T: Iterator<Item = (f64, f64)>,
{
check_depth::<Hpx<u64>>(depth)?;
let vertices = vertices_it
.map(|(lon_deg, lat_deg)| {
let lon = lon_deg2rad(lon_deg)?;
let lat = lat_deg2rad(lat_deg)?;
Ok((lon, lat))
})
.collect::<Result<Vec<(f64, f64)>, String>>()?;
let moc: RangeMOC<u64, Hpx<u64>> =
RangeMOC::from_polygon(&vertices, complement, depth, selection);
store::add(moc)
}
/// Create and store a new MOC from the given list of coordinates (assumed to be equatorial)
/// # Params
/// * `depth`: MOC maximum depth in `[0, 29]`
/// * `coos_deg`: list of coordinates in degrees
///
/// # Output
/// - The index in the storage
pub fn from_coo<T>(&self, depth: u8, coos_deg: T) -> Result<usize, String>
where
T: Iterator<Item = (f64, f64)>,
{
check_depth::<Hpx<u64>>(depth)?;
let moc: RangeMOC<u64, Hpx<u64>> = RangeMOC::from_coos(
depth,
coos_deg.filter_map(|(lon_deg, lat_deg)| {
let lon = lon_deg2rad(lon_deg);
let lat = lat_deg2rad(lat_deg);
match (lon, lat) {
(Ok(lon), Ok(lat)) => Some((lon, lat)),
_ => None,
}
}),
None,
);
store::add(moc)
}
/// Create and store a new MOC from the given list of cone centers and radii
/// Adapted for a large number of small cones (a few cells each).
///
/// # Params
/// * `depth`: MOC maximum depth in `[0, 29]`
/// * `delta_depth` the difference between the MOC depth and the depth at which the computations
/// are made (should remain quite small).
/// * `coos_and_radius_deg`: list of coordinates and radii in degrees `((lon, lat), rad)`
///
/// # Output
/// - The index in the storage
pub fn from_small_cones<T>(
&self,
depth: u8,
delta_depth: u8,
coos_and_radius_deg: T,
) -> Result<usize, String>
where
T: Iterator<Item = ((f64, f64), f64)>,
{
check_depth::<Hpx<u64>>(depth)?;
let dd = delta_depth.min(Hpx::<u64>::MAX_DEPTH - depth);
let coos_rad = coos_and_radius_deg.filter_map(|((lon_deg, lat_deg), radius_deg)| {
let lon = lon_deg2rad(lon_deg);
let lat = lat_deg2rad(lat_deg);
match (lon, lat) {
(Ok(lon), Ok(lat)) => Some((lon, lat, radius_deg.to_radians())),
_ => None,
}
});
let moc: RangeMOC<u64, Hpx<u64>> = RangeMOC::from_small_cones(depth, dd, coos_rad, None);
store::add(moc)
}
/// Same as `from_small_cones`, but in parallel.
#[cfg(not(target_arch = "wasm32"))]
pub fn from_small_cones_par<T>(
&self,
depth: u8,
delta_depth: u8,
coos_and_radius_deg: T,
) -> Result<usize, String>
where
T: ParallelIterator<Item = ((f64, f64), f64)>,
{
check_depth::<Hpx<u64>>(depth)?;
let dd = delta_depth.min(Hpx::<u64>::MAX_DEPTH - depth);
let coos_rad = coos_and_radius_deg.filter_map(|((lon_deg, lat_deg), radius_deg)| {
let lon = lon_deg2rad(lon_deg);
let lat = lat_deg2rad(lat_deg);
match (lon, lat) {
(Ok(lon), Ok(lat)) => Some((lon, lat, radius_deg.to_radians())),
_ => None,
}
});
let moc: RangeMOC<u64, Hpx<u64>> = RangeMOC::from_small_cones_par(depth, dd, coos_rad, None);
store::add(moc)
}
/// Create and store a new MOC from the given list of cone centers and radii
/// Adapted for a reasonable number of possibly large cones.
///
/// # Params
/// * `depth`: MOC maximum depth in `[0, 29]`
/// * `delta_depth` the difference between the MOC depth and the depth at which the computations
/// are made (should remain quite small).
/// * `selection`: select BMOC cells to keep in the MOC
/// * `coos_and_radius_deg`: list of coordinates and radii in degrees `((lon, lat), rad)`
///
/// # Output
/// - The index in the storage
pub fn from_large_cones<T>(
&self,
depth: u8,
delta_depth: u8,
selection: CellSelection,
coos_and_radius_deg: T,
) -> Result<usize, String>
where
T: Iterator<Item = ((f64, f64), f64)>,
{
check_depth::<Hpx<u64>>(depth)?;
let dd = delta_depth.min(Hpx::<u64>::MAX_DEPTH - depth);
let coos_rad = coos_and_radius_deg.filter_map(|((lon_deg, lat_deg), radius_deg)| {
let lon = lon_deg2rad(lon_deg);
let lat = lat_deg2rad(lat_deg);
match (lon, lat) {
(Ok(lon), Ok(lat)) => Some((lon, lat, radius_deg.to_radians())),
_ => None,
}
});
let moc: RangeMOC<u64, Hpx<u64>> = RangeMOC::from_large_cones(depth, dd, selection, coos_rad);
store::add(moc)
}
/// Same as `from_large_cones`, but in parallel.
#[cfg(not(target_arch = "wasm32"))]
pub fn from_large_cones_par<T>(
&self,
depth: u8,
delta_depth: u8,
selection: CellSelection,
coos_and_radius_deg: T,
) -> Result<usize, String>
where
T: ParallelIterator<Item = ((f64, f64), f64)>,
{
check_depth::<Hpx<u64>>(depth)?;
let dd = delta_depth.min(Hpx::<u64>::MAX_DEPTH - depth);
let coos_rad = coos_and_radius_deg.filter_map(|((lon_deg, lat_deg), radius_deg)| {
let lon = lon_deg2rad(lon_deg);
let lat = lat_deg2rad(lat_deg);
match (lon, lat) {
(Ok(lon), Ok(lat)) => Some((lon, lat, radius_deg.to_radians())),
_ => None,
}
});
/*let cone_moc_it = coos_rad.map(move |(lon, lat, radius)| {
RangeMOC::<u64, Hpx<u64>>::from_cone(lon, lat, radius, depth, dd, selection)
});
let moc = cone_moc_it.reduce(
|| RangeMOC::<u64, Hpx<u64>>::new_empty(depth),
|l, r| l.or(&r),
);*/
let moc: RangeMOC<u64, Hpx<u64>> =
RangeMOC::from_large_cones_par(depth, dd, selection, coos_rad);
store::add(moc)
}
/// Create a new S-MOC from the given lists of UNIQ and Values.
/// # Params
/// * `depth`: S-MOC maximum depth in `[0, 29]`, Must be >= largest input cells depth.
/// * `density`: Input values are densities, i.e. they are not proportional to the area of their associated cells.
/// * `from_threshold`: Cumulative value at which we start putting cells in he MOC (often = 0).
/// * `to_threshold`: Cumulative value at which we stop putting cells in the MOC.
/// * `asc`: Compute cumulative value from ascending density values instead of descending (often = false).
/// * `not_strict`: Cells overlapping with the upper or the lower cumulative bounds are not rejected (often = false).
/// * `split`: Split recursively the cells overlapping the upper or the lower cumulative bounds (often = false).
/// * `revese_recursive_descent`: Perform the recursive descent from the highest to the lowest sub-cell, only with option 'split' (set both flags to be compatibile with Aladin)
/// * `uniqs`: array of uniq HEALPix cells
/// * `values`: array of values associated to the HEALPix cells
pub fn from_valued_cells<T>(
&self,
depth: u8,
density: bool,
from_threshold: f64,
to_threshold: f64,
asc: bool,
not_strict: bool,
split: bool,
revese_recursive_descent: bool,
uniq_vals: T,
) -> Result<usize, String>
where
T: Iterator<Item = (u64, f64)>,
{
if to_threshold < from_threshold {
return Err(String::from("`cumul_from` has to be < to `cumul_to`."));
}
let area_per_cell = (PI / 3.0) / (1_u64 << (depth << 1) as u32) as f64; // = 4pi / (12*4^depth)
let ranges: HpxRanges<u64> = if density {
valued_cells_to_moc_with_opt::<u64, f64>(
depth,
uniq_vals
.map(|(uniq, dens)| {
let (cdepth, _ipix) = Hpx::<u64>::from_uniq_hpx(uniq);
if cdepth > depth {
Err(format!(
"Too deep cell depth. Expected: <= {}; Actual: {}",
depth, cdepth
))
} else {
let n_sub_cells = (1_u64 << (((depth - cdepth) << 1) as u32)) as f64;
Ok((uniq, dens * n_sub_cells * area_per_cell, dens))
}
})
.collect::<Result<_, String>>()?,
from_threshold,
to_threshold,
asc,
!not_strict,
!split,
revese_recursive_descent,
)
} else {
valued_cells_to_moc_with_opt::<u64, f64>(
depth,
uniq_vals
.map(|(uniq, val)| {
let (cdepth, _ipix) = Hpx::<u64>::from_uniq_hpx(uniq);
if cdepth > depth {
Err(format!(
"Too deep cell depth. Expected: <= {}; Actual: {}",
depth, cdepth
))
} else {
let n_sub_cells = (1_u64 << (((depth - cdepth) << 1) as u32)) as f64;
Ok((uniq, val, val / (n_sub_cells * area_per_cell)))
}
})
.collect::<Result<_, String>>()?,
from_threshold,
to_threshold,
asc,
!not_strict,
!split,
revese_recursive_descent,
)
};
let moc = RangeMOC::new(depth, ranges);
store::add(moc)
}
/// Create and store a new S-MOC from the given STC-S string.
/// # WARNING
/// * `DIFFERENCE` is interpreted as a symmetrical difference (it is a `MINUS` in the STC standard)
/// * `Polygon` do not follow the STC-S standard: here self-intersecting polygons are supported
/// * No implicit conversion: the STC-S will be rejected if
/// + the frame is different from `ICRS`
/// + the flavor is different from `Spher2`
/// + the units are different from `degrees`
/// * Time, Spectral and Redshift sub-phrases are ignored
///
/// # Params
/// * `depth`: MOC maximum depth in `[0, 29]`
/// * `delta_depth` the difference between the MOC depth and the depth at which the computations
/// are made (should remain quite small).
/// * `ascii_stcs`: lthe STC-S string
///
/// # Output
/// - The index in the storage
pub fn from_stcs(&self, depth: u8, delta_depth: u8, ascii_stcs: &str) -> Result<usize, String> {
check_depth::<Hpx<u64>>(depth)?;
let dd = delta_depth.min(Hpx::<u64>::MAX_DEPTH - depth);
let moc: RangeMOC<u64, Hpx<u64>> =
stcs2moc(depth, Some(dd), ascii_stcs).map_err(|e| e.to_string())?;
store::add(moc)
}
// - SMOC MutliOrder
// - SMOC SkyMaps
// * T-MOC CREATION //
pub fn from_microsec_since_jd0<T>(
&self,
depth: u8,
microsec_since_jd0_it: T,
) -> Result<usize, String>
where
T: Iterator<Item = u64>,
{
check_depth::<Time<u64>>(depth)?;
let moc =
RangeMOC::<u64, Time<u64>>::from_microsec_since_jd0(depth, microsec_since_jd0_it, None);
store::add(moc)
}
/// Create a new T-MOC from the given list of decimal Julian Days (JD) times.
/// # Params
/// * `name`: the name to be given to the MOC
/// * `depth`: T-MOC maximum depth in `[0, 61]`
/// * `jd`: array of decimal JD time (`f64`)
/// # WARNING
/// Using decimal Julian Days stored on `f64`, the precision does not reach the microsecond
/// since JD=0.
/// In Javascript, there is no `u64` type (integers are stored on the mantissa of
/// a double -- a `f64` --, which is made of 52 bits).
/// The other approach is to use a couple of `f64`: one for the integer part of the JD, the
/// other for the fractional part of the JD.
/// We will add such a method later if required by users.
pub fn from_decimal_jd_values<T>(&self, depth: u8, jd: T) -> Result<usize, String>
where
T: Iterator<Item = f64>,
{
self.from_microsec_since_jd0(depth, jd.map(|jd| (jd * JD_TO_USEC) as u64))
}
pub fn from_microsec_ranges_since_jd0<T>(
&self,
depth: u8,
microsec_ranges_since_jd0_it: T,
) -> Result<usize, String>
where
T: Iterator<Item = Range<u64>>,
{
check_depth::<Time<u64>>(depth)?;
let moc = RangeMOC::<u64, Time<u64>>::from_microsec_ranges_since_jd0(
depth,
microsec_ranges_since_jd0_it,
None,
);
store::add(moc)
}
pub fn from_decimal_jd_ranges<T>(&self, depth: u8, jd_ranges: T) -> Result<usize, String>
where
T: Iterator<Item = Range<f64>>,
{
self.from_microsec_ranges_since_jd0(
depth,
jd_ranges.map(
|Range {
start: jd_min,
end: jd_max,
}| (jd_min * JD_TO_USEC) as u64..(jd_max * JD_TO_USEC) as u64,
),
)
}
// * F-MOC CREATION //
pub fn from_fmoc_ranges<T: Idx, I>(&self, depth: u8, ranges_it: I) -> Result<usize, String>
where
I: Iterator<Item = Range<T>>,
{
let it = ranges_it.map(|range| T::to_u64_idx(range.start)..T::to_u64_idx(range.end));
let moc: RangeMOC<u64, Frequency<u64>> = RangeMOC::from_maxdepth_ranges(depth, it, None);
store::add(moc)
}
/// Create an store a new F-MOC from the given list of frequencies (Hz).
///
/// # Input
/// * `depth`: F-MOC maximum depth in `[0, 59]`
/// * `freq`: iterator on frequencies, in Hz (`f64`)
///
/// # Output
/// - The index in the storage
pub fn from_hz_values<T>(&self, depth: u8, freq: T) -> Result<usize, String>
where
T: Iterator<Item = f64>,
{
check_depth::<Frequency<u64>>(depth)?;
let moc = RangeMOC::<u64, Frequency<u64>>::from_freq_in_hz(depth, freq, None);
store::add(moc)
}
/// Create and store a new F-MOC from the given list of frequencies (Hz) ranges.
///
/// # Input
/// * `depth`: F-MOC maximum depth in `[0, 59]`
/// * `freq_ranges`: iterator on frequencies ranges, in Hz (`f64`)
///
/// # Output
/// - The index in the storage
pub fn from_hz_ranges<T>(&self, depth: u8, freq_ranges: T) -> Result<usize, String>
where
T: Iterator<Item = Range<f64>>,
{
check_depth::<Frequency<u64>>(depth)?;
let moc = RangeMOC::<u64, Frequency<u64>>::from_freq_ranges_in_hz(depth, freq_ranges, None);
store::add(moc)
}
// * ST-MOC CREATION //
/// Create a abd store a new ST-MOC from a list of sky coordinates and times.
///
/// # Arguments
///
/// * `times` - The times expressed in jd coded on doubles (=> not precise to the microsecond).
/// * `lon` - The longitudes of the sky coordinates, in radians.
/// * `lat` - The latitudes of the sky coordinates, in radians.
/// * `dt` - The depth along the time (i.e. `T`) axis.
/// * `ds` - The depth at which HEALPix cell indices
/// will be computed.
///
/// # Output
/// - The index in the storage
pub fn create_from_times_positions_approx(
&self,
times: Vec<f64>,
lon: Vec<f64>,
lat: Vec<f64>,
time_depth: u8,
space_depth: u8,
) -> Result<usize, String> {
let times = jd2mas_approx(times);
self.create_from_times_positions(times, lon, lat, time_depth, space_depth)
}
/// Create a abd store a new ST-MOC from a list of sky coordinates and times.
///
/// # Arguments
///
/// * `times` - The times expressed in microsecond since jd=0.
/// * `lon` - The longitudes of the sky coordinates, in radians.
/// * `lat` - The latitudes of the sky coordinates, in radians.
/// * `time_depth` - The depth along the time (i.e. `T`) axis.
/// * `space_depth` - The depth at which HEALPix cell indices
/// will be computed.
///
/// # Output
/// - The index in the storage
pub fn create_from_times_positions(
&self,
times: Vec<u64>,
lon: Vec<f64>,
lat: Vec<f64>,
time_depth: u8,
space_depth: u8,
) -> Result<usize, String> {
if time_depth > Time::<u64>::MAX_DEPTH {
Err(format!(
"Time depth must be in [0, {}]",
Time::<u64>::MAX_DEPTH
))
} else if times.len() != lon.len() {
Err(format!(
"Times and longitudes do not have the same size: {} != {}",
times.len(),
lon.len()
))
} else {
let stmoc = STMOC::from_time_and_coos(
time_depth,
space_depth,
times
.into_iter()
.zip(lon.into_iter().zip(lat.into_iter()))
.map(|(t, (l, b))| (t, l, b)),
None,
);
store::add(stmoc)
}
}
/// Create a time-spatial coverage (2D) from a list of sky coordinates
/// and ranges of times.
///
/// # Arguments
///
/// * ``times_start`` - The starting times expressed in jd.
/// * ``times_end`` - The ending times expressed in jd.
/// * ``lon`` - The longitudes of the sky coordinates.
/// * ``lat`` - The latitudes of the sky coordinates.
/// * ``dt`` - The depth along the time (i.e. `T`) axis.
/// * ``ds`` - The depth at which HEALPix cell indices
/// will be computed.
///
/// # Precondition
///
/// * ``lon`` and ``lat`` are expressed in radians.
/// They are valid because they come from
/// `astropy.units.Quantity` objects.
/// * ``times`` are expressed in jd and are coming
/// from `astropy.time.Time` objects.
///
/// # Errors
///
/// If the number of longitudes, latitudes and times do not match.
///
pub fn create_from_time_ranges_positions_approx(
&self,
times_start: Vec<f64>,
times_end: Vec<f64>,
time_depth: u8,
lon: Vec<f64>,
lat: Vec<f64>,
space_depth: u8,
) -> Result<usize, String> {
let times_start = jd2mas_approx(times_start);
let times_end = jd2mas_approx(times_end);
self.create_from_time_ranges_positions(
times_start,
times_end,
time_depth,
lon,
lat,
space_depth,
)
}
/// Create a time-spatial coverage (2D) from a list of sky coordinates
/// and ranges of times.
///
/// # Arguments
///
/// * ``times_start`` - The starting times expressed in microseconds since jd=0.
/// * ``times_end`` - The ending times expressed in microseconds since jd=0.
/// * ``lon`` - The longitudes of the sky coordinates.
/// * ``lat`` - The latitudes of the sky coordinates.
/// * ``dt`` - The depth along the time (i.e. `T`) axis.
/// * ``ds`` - The depth at which HEALPix cell indices
/// will be computed.
///
/// # Precondition
///
/// * ``lon`` and ``lat`` are expressed in radians.
/// They are valid because they come from
/// `astropy.units.Quantity` objects.
/// * ``times`` are expressed in jd and are coming
/// from `astropy.time.Time` objects.
///
/// # Errors
///
/// If the number of longitudes, latitudes and times do not match.
pub fn create_from_time_ranges_positions(
&self,
times_start: Vec<u64>,
times_end: Vec<u64>,
time_depth: u8,
lon: Vec<f64>,
lat: Vec<f64>,
space_depth: u8,
) -> Result<usize, String> {
if times_start.len() != lon.len() {
Err(format!(
"Times and coos do not have the same size: {} != {}.",
times_start.len(),
lon.len()
))
} else {
let ipix = lonlat2hash(space_depth, lon, lat)?;
let times = times2hash(time_depth, times_start, times_end)?;
let stmoc = STMOC::from_ranges_and_fixed_depth_cells(
time_depth,
space_depth,
times.into_iter().zip(ipix.into_iter()),
None,
);
store::add(stmoc)
}
}
/// Create a time-spatial coverage (2D) from a list of cones
/// and time ranges.
///
/// # Arguments
///
/// * ``times_start`` - The starting times expressed in jd.
/// * ``times_end`` - The ending times expressed in jd.
/// * ``lon`` - The longitudes of the sky coordinates.
/// * ``lat`` - The latitudes of the sky coordinates.
/// * ``radius`` - The radiuses of the cones.
/// * ``dt`` - The depth along the time (i.e. `T`) axis.
/// * ``ds`` - The depth at which HEALPix cell indices
/// will be computed.
///
pub fn from_time_ranges_spatial_coverages_approx(
&self,
times_start: Vec<f64>,
times_end: Vec<f64>,
time_depth: u8,
spatial_coverages: Vec<HpxRanges<u64>>,
space_depth: u8,
) -> Result<usize, String> {
let times_start = jd2mas_approx(times_start);
let times_end = jd2mas_approx(times_end);
self.from_time_ranges_spatial_coverages(
times_start,
times_end,
time_depth,
spatial_coverages,
space_depth,
)
}
/// Create a time-spatial coverage (2D) from a list of cones
/// and time ranges.
///
/// # Arguments
///
/// * ``times_start`` - The starting times expressed in microseconds since jd=0.
/// * ``times_end`` - The ending times expressed in microseconds since jd=0.
/// * ``dt`` - The depth along the time (i.e. `T`) axis.
///
/// * ``ds`` - The depth at which HEALPix cell indices
/// will be computed.
///
/// # Precondition
///
/// * ``lon`` and ``lat`` are expressed in radians.
/// They are valid because they come from
/// `astropy.units.Quantity` objects.
/// * ``times`` are expressed in jd and are coming
/// from `astropy.time.Time` objects.
///
/// # Errors
///
/// If the number of longitudes, latitudes and times do not match.
pub fn from_time_ranges_spatial_coverages(
&self,
times_start: Vec<u64>,
times_end: Vec<u64>,
time_depth: u8,
spatial_coverages: Vec<HpxRanges<u64>>,
space_depth: u8,
) -> Result<usize, String> {
let times = times2hash(time_depth, times_start, times_end)?;
let moc = TimeSpaceMoc::<u64, u64>::create_from_time_ranges_spatial_coverage(
times,
spatial_coverages,
time_depth,
);
store::add(
moc
.time_space_iter(time_depth, space_depth)
.into_range_moc2(),
)
}
/// Create a time-spatial coverage (2D) from a list of cones
/// and time ranges.
///
/// # Arguments
///
/// * ``times_start`` - The starting times expressed in jd.
/// * ``times_end`` - The ending times expressed in jd.
/// * ``lon`` - The longitudes of the sky coordinates.
/// * ``lat`` - The latitudes of the sky coordinates.
/// * ``radius`` - The radiuses of the cones.
/// * ``dt`` - The depth along the time (i.e. `T`) axis.
/// * ``ds`` - The depth at which HEALPix cell indices
/// will be computed.
///
pub fn from_time_ranges_spatial_coverages_in_store_approx(
&self,
times_start: Vec<f64>,
times_end: Vec<f64>,
time_depth: u8,
spatial_coverages: Vec<usize>,
// space_depth: u8,
) -> Result<usize, String> {
let times_start = jd2mas_approx(times_start);
let times_end = jd2mas_approx(times_end);
self.from_time_ranges_spatial_coverages_in_store(
times_start,
times_end,
time_depth,
spatial_coverages, //, space_depth
)
}
/// Create a time-spatial coverage (2D) from a list of cones
/// and time ranges.
///
/// # Arguments
///
/// * ``times_start`` - The starting times expressed in microseconds since jd=0.
/// * ``times_end`` - The ending times expressed in microseconds since jd=0.
/// * ``lon`` - The longitudes of the sky coordinates.
/// * ``lat`` - The latitudes of the sky coordinates.
/// * ``radius`` - The radiuses of the cones.
/// * ``dt`` - The depth along the time (i.e. `T`) axis.
/// * ``ds`` - The depth at which HEALPix cell indices
/// will be computed.
///
/// # Precondition
///
/// * ``lon`` and ``lat`` are expressed in radians.
/// They are valid because they come from
/// `astropy.units.Quantity` objects.
/// * ``times`` are expressed in jd and are coming
/// from `astropy.time.Time` objects.
///
/// # Errors
///
/// If the number of longitudes, latitudes and times do not match.
pub fn from_time_ranges_spatial_coverages_in_store(
&self,
times_start: Vec<u64>,
times_end: Vec<u64>,
time_depth: u8,
spatial_coverage_indices: Vec<usize>,
// space_depth: u8,
) -> Result<usize, String> {
let times = times2hash(time_depth, times_start, times_end)?;
let space_depth = spatial_coverage_indices
.iter()
.filter_map(|index| self.get_smoc_depth(*index).ok())
.max()
.unwrap_or(0);
let spatial_coverages: Vec<HpxRanges<u64>> = spatial_coverage_indices
.into_iter()
.map(
|index| self.get_smoc_copy(index).map(|moc| moc.into_moc_ranges()), // |index| self.degrade(index, space_depth).map(|moc| moc.into_moc_ranges())
)
.collect::<Result<_, _>>()?;
let moc = TimeSpaceMoc::<u64, u64>::create_from_time_ranges_spatial_coverage(
times,
spatial_coverages,
time_depth,
);
store::add(
moc
.time_space_iter(time_depth, space_depth)
.into_range_moc2(),
)
}
// * SF-MOC CREATION //
/// Create and store a new SF-MOC from a list of sky coordinates and frequencies.
///
/// # Arguments
///
/// * `freq_hz` - The frequencies expressed in Hz.
/// * `lon` - The longitudes of the sky coordinates, in radians.
/// * `lat` - The latitudes of the sky coordinates, in radians.
/// * `freq_depth` - The depth along the frequency (i.e. `F`) axis.
/// * `space_depth` - The depth at which HEALPix cell indices
/// will be computed.
///
/// # Output
/// - The index in the storage
pub fn create_from_hz_positions(
&self,
freq_hz: Vec<f64>,
lon: Vec<f64>,
lat: Vec<f64>,
freq_depth: u8,
space_depth: u8,
) -> Result<usize, String> {
if freq_depth > Frequency::<u64>::MAX_DEPTH {
Err(format!(
"Frequency depth must be in [0, {}]",
Frequency::<u64>::MAX_DEPTH
))
} else if freq_hz.len() != lon.len() {
Err(format!(
"Frequencies and longitudes do not have the same size: {} != {}",
freq_hz.len(),
lon.len()
))
} else if lon.len() != lat.len() {
Err(format!(
"Longitudes and latitudes do not have the same size: {} != {}",
lon.len(),
lat.len()
))
} else {
store::add(
RangeMOC2::<u64, Frequency<u64>, u64, Hpx<u64>>::from_freq_in_hz_and_coos(
freq_depth,
space_depth,
freq_hz.into_iter().zip(lon.into_iter().zip(lat)),
None,
),
)
}
}
/// Create a frequency-spatial coverage (2D) from a list of sky coordinates
/// and ranges of frequencies.
///
/// # Arguments
///
/// * ``freq_hz_start`` - The starting frequency, in Hz.
/// * ``freq_hz_end`` - The ending frequency, in Hz.
/// * ``lon`` - The longitudes of the sky coordinates.
/// * ``lat`` - The latitudes of the sky coordinates.
/// * ``freq_depth`` - The depth along the frequency (i.e. `F`) axis.
/// * ``space_depth`` - The depth at which HEALPix cell indices
/// will be computed.
///
/// # Precondition
///
/// * ``lon`` and ``lat`` are expressed in radians.
/// They are valid because they come from
/// `astropy.units.Quantity` objects.
/// * ``freq_hz_start`` and ``freq_hz_ebd`` are expressed in Hz
///
/// # Errors
///
/// If the number of longitudes, latitudes and freq_hz_start and freq_hz_start do not match.
pub fn create_from_hzranges_positions(
&self,
freq_hz_start: Vec<f64>,
freq_hz_end: Vec<f64>,
lon: Vec<f64>,
lat: Vec<f64>,
freq_depth: u8,
space_depth: u8,
) -> Result<usize, String> {
if freq_depth > Frequency::<u64>::MAX_DEPTH {
Err(format!(
"Frequency depth must be in [0, {}]",
Frequency::<u64>::MAX_DEPTH
))
} else if freq_hz_start.len() != lon.len() {
Err(format!(
"Frequencies and longitudes do not have the same size: {} != {}",
freq_hz_start.len(),
lon.len()
))
} else if freq_hz_start.len() != freq_hz_end.len() {
Err(format!(
"Frequencies range start and end do not have the same size: {} != {}",
freq_hz_start.len(),
freq_hz_end.len()
))
} else if lon.len() != lat.len() {
Err(format!(
"Longitudes and latitudes do not have the same size: {} != {}",
lon.len(),
lat.len()
))
} else {
store::add(
RangeMOC2::<u64, Frequency<u64>, u64, Hpx<u64>>::from_freqranges_in_hz_and_coos(
freq_depth,
space_depth,
freq_hz_start
.into_iter()
.zip(freq_hz_end)
.map(|(start, end)| start..end)
.zip(lon.into_iter().zip(lat)),
None,
),
)
}
}
/// Create a frequency-spatial coverage (2D) from a list of frequency ranges (in hz)
/// and S-MOCs.
///
/// # Arguments
///
/// * ``freq_hz_start`` - The starting frequency, in Hz.
/// * ``freq_hz_end`` - The ending frequency, in Hz.
/// * ``freq_hz`` - The depth along the frequency (i.e. `F`) axis.
/// * ``spatial_coverage_indices`` - Indices in the store of the S-MOCs associated to each range
/// will be computed.
///
/// # Errors
///
/// If the number of elements in `freq_hz_start`, `freq_hz_end` and `spatial_coverage_indices` do not match.
pub fn from_freq_ranges_spatial_coverages_in_store(
&self,
freq_hz_start: Vec<f64>,
freq_hz_end: Vec<f64>,
freq_depth: u8,
spatial_coverage_indices: Vec<usize>,
// space_depth: u8,
) -> Result<usize, String> {
if freq_depth > Frequency::<u64>::MAX_DEPTH {
Err(format!(
"Frequency depth must be in [0, {}]",
Frequency::<u64>::MAX_DEPTH
))
} else if freq_hz_start.len() != freq_hz_end.len() {
Err(format!(
"Frequencies range start and end do not have the same size: {} != {}",
freq_hz_start.len(),
freq_hz_end.len()
))
} else if freq_hz_start.len() != spatial_coverage_indices.len() {
Err(format!(
"Frequency ranges and S-MOC indices do not have the same size: {} != {}",
freq_hz_start.len(),
spatial_coverage_indices.len()
))
} else {
let frequencies = freqs2hash(freq_depth, freq_hz_start, freq_hz_end)?;
let space_depth = spatial_coverage_indices
.iter()
.filter_map(|index| self.get_smoc_depth(*index).ok())
.max()
.unwrap_or(0);
let spatial_coverages: Vec<HpxRanges<u64>> = spatial_coverage_indices
.into_iter()
.map(
|index| self.get_smoc_copy(index).map(|moc| moc.into_moc_ranges()), // |index| self.degrade(index, space_depth).map(|moc| moc.into_moc_ranges())
)
.collect::<Result<_, _>>()?;
let moc = FreqSpaceMoc::<u64, u64>::create_from_freq_ranges_spatial_coverage(
frequencies,
spatial_coverages,
freq_depth,
);
store::add(
moc
.freq_space_iter(freq_depth, space_depth)
.into_range_moc2(),
)
}
}
/////////////////////////
// OPERATIONS ON 1 MOC //
// return a hierachical view (Json like) for display?
// (not necessary if display made from rust code too)
pub fn barycenter(&self, index: usize) -> Result<(f64, f64), String> {
op1_moc_barycenter(index)
}
pub fn largest_distance_from_coo_to_moc_vertices(
&self,
index: usize,
lon: f64,
lat: f64,
) -> Result<f64, String> {
op1_moc_largest_distance_from_coo_to_moc_vertices(index, lon, lat)
}
pub fn not(&self, index: usize) -> Result<usize, String> {
self.complement(index)
}
pub fn complement(&self, index: usize) -> Result<usize, String> {
Op1::Complement.exec(index)
}
pub fn flatten_to_moc_depth(&self, index: usize) -> Result<Vec<u64>, String> {
op1_flatten_to_moc_depth(index)
}
pub fn flatten_to_depth(&self, index: usize, depth: u8) -> Result<Vec<u64>, String> {
op1_flatten_to_depth(index, depth)
}
/// Returns the MOC elementary edges, i.e. the edges at the deepest depth, in any order, made of
/// the starting vertex and the ending vertex so that each item is of the form:
/// `[stat_vertex_lon, starting_vertex_lat, ending_vertex_lon, ending_vertex_lat]`.
pub fn border_elementary_edges_vertices(&self, index: usize) -> Result<Vec<[f64; 4]>, String> {
op1_border_elementary_edges_vertices(index)
}
//
/// Split the given disjoint S-MOC int joint S-MOCs.
/// Split "direct", i.e. we consider 2 neighboring cells to be the same only if the share an edge.
/// WARNING: may create a lot of new MOCs, exec `splitCount` first!!
pub fn split(&self, index: usize) -> Result<Vec<usize>, String> {
Op1MultiRes::Split.exec(index)
}
/// Count the number of joint S-MOC splitting ("direct") the given disjoint S-MOC.
pub fn split_count(&self, index: usize) -> Result<u32, String> {
op1_count_split(index, false)
}
/// Split the given disjoint S-MOC int joint S-MOCs.
/// Split "indirect", i.e. we consider 2 neighboring cells to be the same if the share an edge
/// or a vertex.
/// WARNING: may create a lot of new MOCs, exec `splitIndirectCount` first!!
pub fn split_indirect(&self, index: usize) -> Result<Vec<usize>, String> {
Op1MultiRes::SplitIndirect.exec(index)
}
/// Count the number of joint S-MOC splitting ("direct") the given disjoint S-MOC.
pub fn split_indirect_count(&self, index: usize) -> Result<u32, String> {
op1_count_split(index, true)
}
/// Sum the value of the given multi-order map which are in the given MOC.
/// Remark: we have no information and cannot make any guess on the order if te `UNIQ` cell
/// in the iterator.
/// # Params
/// * `index`: index pf the S-MOC in the storage
/// * `mom_it`: iterator on non-overlapping `(uniq, value)` pairs.
pub fn multiordermap_sum_in_moc<I>(&self, index: usize, mom_it: I) -> Result<f64, String>
where
I: Sized + Iterator<Item = (u64, f64)>,
{
op1_mom_sum(index, mom_it)
}
/// Filter the value of the given multi-order map to return only the one which are in the given MOC,
/// together with the associated sky area (or weight).
/// # Params
/// * `index`: index pf the S-MOC in the storage
/// * `mom_it`: iterator on non-overlapping `(uniq, value)` pairs.
/// # Output
/// * result made of first the vector of values, and the vector of associated weights.
pub fn multiordermap_filter_in_moc<I>(
&self,
index: usize,
mom_it: I,
) -> Result<(Vec<f64>, Vec<f64>), String>
where
I: Sized + Iterator<Item = (u64, f64)>,
{
op1_mom_filter(index, mom_it)
}
/// Set to 'false' the booleans associated to the UNIQ HEALPix cells
/// intersecting (or fully covered) by the MOC of given index.
///
/// # Params
/// * `index`: index pf the S-MOC in the storage
/// * `it`: iterator on `uniq` HEALPix cells.
/// * `fully_covered_only`: set the boolean to false only if the cell is fully covered (else if it intersects)
pub fn multiordermap_filter_mask_moc<'a, I>(
&self,
index: usize,
it: I,
fully_covered_only: bool,
) -> Result<(), String>
where
I: Sized + Iterator<Item = (u64, &'a mut bool)>,
{
op1_mom_filter_mask(index, it, fully_covered_only)
}
/// Sum the value of the multi-order map in the given path which are in the given MOC.
/// Remark: we have no information and cannot make any guess on the order if te `UNIQ` cell
/// in the iterator.
/// # Params
/// * `index`: index pf the S-MOC in the storage
/// * `mom_path`: path of the MOM FITS file.
pub fn multiordermap_sum_in_moc_from_path<P: AsRef<Path>>(
&self,
index: usize,
mom_path: P,
) -> Result<f64, String> {
op1_mom_sum_from_path(index, mom_path)
}
/// Sum the value of the multi-order map in the given FITS data which are in the given MOC.
/// Remark: we have no information and cannot make any guess on the order if te `UNIQ` cell
/// in the iterator.
/// # Params
/// * `index`: index pf the S-MOC in the storage
/// * `data`: raw FITS file containing the MOM
pub fn multiordermap_sum_in_moc_from_data(
&self,
index: usize,
mom_data: &[u8],
) -> Result<f64, String> {
op1_mom_sum_from_data(index, mom_data)
}
pub fn degrade(&self, index: usize, new_depth: u8) -> Result<usize, String> {
Op1::Degrade { new_depth }.exec(index)
}
pub fn refine(&self, index: usize, new_depth: u8) -> Result<(), String> {
let op = |moc: &mut InternalMoc| match moc {
InternalMoc::Space(moc) => {
moc.refine(new_depth);
Ok(())
}
InternalMoc::Time(moc) => {
moc.refine(new_depth);
Ok(())
}
InternalMoc::Frequency(moc) => {
moc.refine(new_depth);
Ok(())
}
_ => Err(String::from(
"Can't 'refine' with a single new depth on a MOC different from a S-MOC, T-MOC or F-MOC",
)),
};
store::exec_on_one_readwrite_moc(index, op)
}
pub fn extend(&self, index: usize) -> Result<usize, String> {
Op1::Extend.exec(index)
}
pub fn contract(&self, index: usize) -> Result<usize, String> {
Op1::Contract.exec(index)
}
pub fn ext_border(&self, index: usize) -> Result<usize, String> {
Op1::ExtBorder.exec(index)
}
pub fn int_border(&self, index: usize) -> Result<usize, String> {
Op1::IntBorder.exec(index)
}
////////////////////////////////////////////////////
// LOGICAL OPERATIONS BETWEEN 2 MOCs of same type //
pub fn or(&self, left_index: usize, right_index: usize) -> Result<usize, String> {
self.union(left_index, right_index)
}
pub fn union(&self, left_index: usize, right_index: usize) -> Result<usize, String> {
Op2::Union.exec(left_index, right_index)
}
pub fn and(&self, left_index: usize, right_index: usize) -> Result<usize, String> {
self.intersection(left_index, right_index)
}
pub fn intersection(&self, left_index: usize, right_index: usize) -> Result<usize, String> {
Op2::Intersection.exec(left_index, right_index)
}
pub fn xor(&self, left_index: usize, right_index: usize) -> Result<usize, String> {
self.symmetric_difference(left_index, right_index)
}
pub fn symmetric_difference(
&self,
left_index: usize,
right_index: usize,
) -> Result<usize, String> {
Op2::SymmetricDifference.exec(left_index, right_index)
}
pub fn minus(&self, left_index: usize, right_index: usize) -> Result<usize, String> {
Op2::Minus.exec(left_index, right_index)
}
pub fn difference(&self, left_index: usize, right_index: usize) -> Result<usize, String> {
self.minus(left_index, right_index)
}
/////////////////////////////////////////////////////
// LOGICAL OPERATIONS BETWEEN >2 MOCs of same type //
pub fn multi_union(&self, indices: &[usize]) -> Result<usize, String> {
OpN::Union.exec(indices)
}
pub fn multi_intersection(&self, indices: &[usize]) -> Result<usize, String> {
OpN::Intersection.exec(indices)
}
pub fn multi_symmetric_difference(&self, indices: &[usize]) -> Result<usize, String> {
OpN::SymmetricDifference.exec(indices)
}
////////////////////////
// ST/SF-MOC projections //
/// Returns the union of the S-MOCs associated to T-MOCs intersecting the given T-MOC.
/// Left: T-MOC, right: ST-MOC, result: S-MOC.
pub fn time_fold(&self, time_moc_index: usize, st_moc_index: usize) -> Result<usize, String> {
Op2::TFold.exec(time_moc_index, st_moc_index)
}
/// Returns the union of the T-MOCs or F-MOCs associated to S-MOCs intersecting the given S-MOC.
/// Left: S-MOC, right: ST-MOC or SF-MOC, result: T-MOC or F-MOC.
pub fn space_fold(
&self,
space_moc_index: usize,
st_or_sf_moc_index: usize,
) -> Result<usize, String> {
Op2::SFold.exec(space_moc_index, st_or_sf_moc_index)
}
/// Returns the union of the S-MOCs associated to F-MOCs intersecting the given F-MOC.
/// Left: F-MOC, right: SF-MOC, result: S-MOC.
pub fn frequency_fold(
&self,
freq_moc_index: usize,
sf_moc_index: usize,
) -> Result<usize, String> {
Op2::FFold.exec(freq_moc_index, sf_moc_index)
}
///////////////////////
// FILTER OPERATIONS //
//////////////////////////////////////////////////////
// Filter/Contains (returning an array of boolean?) //
/// Returns an array (of boolean or u8 or ...) telling if the pairs of coordinates
/// in the input slice are in (true=1) or out of (false=0) the S-MOC.
/// # Args
/// * `moc_index`: index of the S-MOC to be used for filtering
/// * `coos_deg`: iterator on coordinates in degrees `[lon_1, lat_1, lon_2, lat_2, ..., lon_n, lat_n]`
/// # Remarks
/// * the size of the returned array is the same as the number of elements on the input iterator.
/// * we do not return an iterator to avoid chaining with possibly costly operations
/// while keeping a read lock on the store.
/// * similarly, be carefull not to use an input Iterator based on costly operations...
pub fn filter_pos<T, F, R>(
&self,
moc_index: usize,
coos_deg: T,
fn_bool: F,
) -> Result<Vec<R>, String>
where
T: Iterator<Item = (f64, f64)>,
F: Fn(bool) -> R,
{
let filter = |moc: &InternalMoc| match moc {
InternalMoc::Space(moc) => {
let depth = moc.depth_max();
let layer = healpix::nested::get(depth);
let shift = Hpx::<u64>::shift_from_depth_max(depth) as u32;
Ok(
coos_deg
.map(|(lon_deg, lat_deg)| {
let lon = lon_deg2rad(lon_deg);
let lat = lat_deg2rad(lat_deg);
match (lon, lat) {
(Ok(lon), Ok(lat)) => {
let icell = layer.hash(lon, lat) << shift;
fn_bool(moc.contains_val(&icell))
}
_ => fn_bool(false),
}
})
.collect::<Vec<R>>(),
)
}
_ => Err(String::from(
"Can't filter coos on a MOC different from a S-MOC",
)),
};
store::exec_on_one_readonly_moc(moc_index, filter)
}
/// Returns an array (of boolean or u8 or ...) telling if the time (in Julian Days)
/// in the input array are in (true=1) or out of (false=0) the T-MOC of given name.
/// # Args
/// * `moc_index`: index of the S-MOC to be used for filtering
/// * `jds`: iterator on decimal JD time (`f64`)
/// # Remarks
/// * the size of the returned array is the same as the number of elements on the input iterator.
/// * we do not return an iterator to avoid chaining with possibly costly operations
/// while keeping a read lock on the store.
/// * similarly, be careful not to use an input Iterator based on costly operations...
pub fn filter_time_approx<T, F, R>(
&self,
moc_index: usize,
jds_it: T,
fn_bool: F,
) -> Result<Vec<R>, String>
where
T: Iterator<Item = f64>,
F: Fn(bool) -> R,
{
self.filter_time(
moc_index,
jds_it.map(|jd| (jd * JD_TO_USEC) as u64),
fn_bool,
)
}
/// Returns an array (of boolean or u8 or ...) telling if the time (in Julian Days)
/// in the input array are in (true=1) or out of (false=0) the T-MOC of given name.
/// # Args
/// * `moc_index`: index of the S-MOC to be used for filtering
/// * `jds`: iterator of times, in microsec since JD=0
/// # Remarks
/// * the size of the returned array is the same as the number of elements on the input iterator.
/// * we do not return an iterator to avoid chaining with possibly costly operations
/// while keeping a read lock on the store.
/// * similarly, be carefull not to use an input Iterator based on costly operations...
pub fn filter_time<T, F, R>(
&self,
moc_index: usize,
usec_it: T,
fn_bool: F,
) -> Result<Vec<R>, String>
where
T: Iterator<Item = u64>,
F: Fn(bool) -> R,
{
let filter = move |moc: &InternalMoc| match moc {
InternalMoc::Time(moc) => Ok(
usec_it
.map(|usec| fn_bool(moc.contains_val(&usec)))
.collect::<Vec<R>>(),
),
_ => Err(String::from(
"Can't filter time on a MOC different from a T-MOC",
)),
};
store::exec_on_one_readonly_moc(moc_index, filter)
}
pub fn filter_freq<T, F, R>(
&self,
moc_index: usize,
hz_it: T,
fn_bool: F,
) -> Result<Vec<R>, String>
where
T: Iterator<Item = f64>,
F: Fn(bool) -> R,
{
let filter = move |moc: &InternalMoc| match moc {
InternalMoc::Frequency(moc) => Ok(
hz_it
.map(|hz| fn_bool(moc.contains_val(&Frequency::<u64>::freq2hash(hz))))
.collect::<Vec<R>>(),
),
_ => Err(String::from(
"Can't filter time on a MOC different from a T-MOC",
)),
};
store::exec_on_one_readonly_moc(moc_index, filter)
}
/// Returns an array (of boolean or u8 or ...) telling if the pairs of coordinates
/// in the input slice are in (true=1) or out of (false=0) the S-MOC.
/// # Args
/// * `moc_index`: index of the S-MOC to be used for filtering
/// * `coos_deg`: list of coordinates in degrees `[lon_1, lat_1, lon_2, lat_2, ..., lon_n, lat_n]`
/// # Remarks
/// * the size of the returned array is the same as the number of elements on the input iterator.
/// * we do not return an iterator to avoid chaining with possibly costly operations
/// while keeping a read lock on the store.
/// * similarly, be carefull not to use an input Iterator based on costly operations...
pub fn filter_timepos_approx<T, F, R>(
&self,
moc_index: usize,
jd_pos_it: T,
fn_bool: F,
) -> Result<Vec<R>, String>
where
T: Iterator<Item = (f64, (f64, f64))>,
F: Fn(bool) -> R,
{
self.filter_timepos(
moc_index,
jd_pos_it.map(|(jd, pos)| {
let usec = (jd * JD_TO_USEC) as u64;
(usec, pos)
}),
fn_bool,
)
}
/// Returns an array (of boolean or u8 or ...) telling if the pairs of time and coordinates
/// in the input slice are in (true=1) or out of (false=0) the ST-MOC.
/// # Args
/// * `moc_index`: index of the ST-MOC to be used for filtering
/// * `usec_pos_it`: iterator on tuples made of a time, in microsec since JD=0, and coordinates
/// in radians `(lon, lat)`
/// # Remarks
/// * the size of the returned array is the same as the number of elements on the input iterator.
/// * we do not return an iterator to avoid chaining with possibly costly operations
/// while keeping a read lock on the store.
/// * similarly, be careful not to use an input Iterator based on costly operations...
pub fn filter_timepos<T, F, R>(
&self,
moc_index: usize,
usec_pos_it: T,
fn_bool: F,
) -> Result<Vec<R>, String>
where
T: Iterator<Item = (u64, (f64, f64))>,
F: Fn(bool) -> R,
{
let layer = healpix::nested::get(Hpx::<u64>::MAX_DEPTH);
let filter = move |moc: &InternalMoc| match moc {
InternalMoc::TimeSpace(stmoc) => Ok(
usec_pos_it
.map(|(usec, (lon, lat))| {
let idx = layer.hash(lon, lat);
fn_bool(stmoc.contains_val(&usec, &idx))
})
.collect::<Vec<R>>(),
),
_ => Err(String::from(
"Can't filter time and space on a MOC different from a ST-MOC",
)),
};
store::exec_on_one_readonly_moc(moc_index, filter)
}
/// Returns an array (of boolean or u8 or ...) telling if the pairs of frequency and coordinates
/// in the input iterator are in (true=1) or out of (false=0) the SF-MOC.
/// # Args
/// * `moc_index`: index of the SF-MOC to be used for filtering
/// * `hz_pos_it`: iterator on tuples made of a frequency, in Hz since JD=0, and coordinates
/// in radians `(lon, lat)`
/// # Remarks
/// * the size of the returned array is the same as the number of elements on the input iterator.
/// * we do not return an iterator to avoid chaining with possibly costly operations
/// while keeping a read lock on the store.
/// * similarly, be careful not to use an input Iterator based on costly operations...
pub fn filter_freqpos<T, F, R>(
&self,
moc_index: usize,
freq_pos_it: T,
fn_bool: F,
) -> Result<Vec<R>, String>
where
T: Iterator<Item = (f64, (f64, f64))>,
F: Fn(bool) -> R,
{
let layer = healpix::nested::get(Hpx::<u64>::MAX_DEPTH);
let filter = move |moc: &InternalMoc| match moc {
InternalMoc::FreqSpace(sfmoc) => Ok(
freq_pos_it
.map(|(freq_hz, (lon, lat))| {
let freq = Frequency::<u64>::freq2hash(freq_hz);
let idx = layer.hash(lon, lat);
fn_bool(sfmoc.contains_val(&freq, &idx))
})
.collect::<Vec<R>>(),
),
_ => Err(String::from(
"Can't filter frequency and space on a MOC different from a SF-MOC",
)),
};
store::exec_on_one_readonly_moc(moc_index, filter)
}
}
fn jd2mas_approx(times: Vec<f64>) -> Vec<u64> {
let jd2mas = |t: f64| (t * 86400000000_f64).floor() as u64;
#[cfg(not(target_arch = "wasm32"))]
{
times.into_par_iter().map(jd2mas).collect::<Vec<_>>()
}
#[cfg(target_arch = "wasm32")]
{
times.into_iter().map(jd2mas).collect::<Vec<_>>()
}
}
fn lonlat2hash(depth: u8, lon: Vec<f64>, lat: Vec<f64>) -> Result<Vec<u64>, String> {
if depth > Hpx::<u64>::MAX_DEPTH {
Err(format!(
"Space depth must be in [0, {}]",
Hpx::<u64>::MAX_DEPTH
))
} else if lon.len() != lat.len() {
Err(format!(
"Longitudes and latitudes do not have the same size: {} != {}",
lon.len(),
lat.len()
))
} else {
let mut ipix = vec![0; lon.len()];
let layer = healpix::nested::get(depth);
#[cfg(not(target_arch = "wasm32"))]
ipix
.par_iter_mut()
.zip_eq(lon.into_par_iter().zip_eq(lat.into_par_iter()))
.for_each(|(p, (l, b))| {
*p = layer.hash(l, b);
});
#[cfg(target_arch = "wasm32")]
ipix
.iter_mut()
.zip(lon.into_iter().zip(lat.into_iter()))
.for_each(|(p, (l, b))| {
*p = layer.hash(l, b);
});
Ok(ipix)
}
}
fn times2hash(
depth: u8,
times_start: Vec<u64>,
times_end: Vec<u64>,
) -> Result<Vec<Range<u64>>, String> {
if depth > Time::<u64>::MAX_DEPTH {
Err(format!(
"Time depth must be in [0, {}]",
Time::<u64>::MAX_DEPTH
))
} else if times_start.len() != times_end.len() {
Err(format!(
"Times start and end do not have the same size: {} != {}",
times_start.len(),
times_end.len()
))
} else {
let mut times = vec![0..0; times_start.len()];
#[cfg(not(target_arch = "wasm32"))]
times
.par_iter_mut()
.zip_eq(
times_start
.into_par_iter()
.zip_eq(times_end.into_par_iter()),
)
.for_each(|(t, (t1, t2))| {
*t = t1..t2;
});
#[cfg(target_arch = "wasm32")]
times
.iter_mut()
.zip(times_start.into_iter().zip(times_end.into_iter()))
.for_each(|(t, (t1, t2))| {
*t = t1..t2;
});
Ok(times)
}
}
fn freqs2hash(
depth: u8,
freq_start: Vec<f64>,
freq_end: Vec<f64>,
) -> Result<Vec<Range<u64>>, String> {
if depth > Frequency::<u64>::MAX_DEPTH {
Err(format!(
"Frequency depth must be in [0, {}]",
Frequency::<u64>::MAX_DEPTH
))
} else if freq_start.len() != freq_end.len() {
Err(format!(
"Frequency start and end do not have the same size: {} != {}",
freq_start.len(),
freq_end.len()
))
} else {
let mut freqs = vec![0..0; freq_start.len()];
#[cfg(not(target_arch = "wasm32"))]
freqs
.par_iter_mut()
.zip_eq(freq_start.into_par_iter().zip_eq(freq_end.into_par_iter()))
.for_each(|(f, (f1, f2))| {
*f = Frequency::<u64>::freq2hash(f1)..Frequency::<u64>::freq2hash(f2);
});
#[cfg(target_arch = "wasm32")]
freqs
.iter_mut()
.zip(freq_start.into_iter().zip(freq_end.into_iter()))
.for_each(|(f, (f1, f2))| {
*f = Frequency::<u64>::freq2hash(f1)..Frequency::<u64>::freq2hash(f2);
});
Ok(freqs)
}
}
// See maybe https://github.com/mikaelmello/inquire
// to build an interactive prompt ?