filenames.py
174 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
# -*- coding: utf-8 -*-
# from typing import Dict, List, Tuple, Sequence, Any, TypeVar, Union, Callable, Literal
from typing import Tuple
"""
# https://docs.astropy.org/en/stable/samp/example_table_image.html
First launch Aladin
from astropy.samp import SAMPIntegratedClient
client = SAMPIntegratedClient()
client.connect()
params = {}
params["name"] = 'Messier 57'
params["url"] = 'file:///c:/srv/develop/pyros/vendor/guitastro/test/data/m57.fit'
message = {}
message["samp.mtype"] = "image.load.fits"
message["samp.params"] = params
client.notify_all(message)
"""
import os, glob, sys
import datetime
import math
import pathlib
#import inspect
import tkinter as tk
from tkinter.filedialog import askopenfilename, asksaveasfilename
import astropy.time
try:
from .dates import Date
except:
from dates import Date
try:
from .guitastrotools import GuitastroTools, GuitastroException
except:
from guitastrotools import GuitastroTools, GuitastroException
# #####################################################################
# #####################################################################
# #####################################################################
# Class FileNames
# #####################################################################
# #####################################################################
# This class provides tools to manage file names
# #####################################################################
class FileNamesException(GuitastroException):
NO_FILE_FOUND = 0
NO_NAMING_FOUND = 1
EMPTY_STRING = 2
BAD_PARAM = 3
BAD_FILENAME_RULE = 4
NO_PATHING_FOUND = 5
BAD_PATHNAME_RULE = 6
NO_CONTEXT_KEY_FOUND = 7
NO_DELETE_CONTEXT_DEFAULT = 8
BAD_NAMING = 9
LIST_INSTEAD_A_STRING = 10
errors = [""]*11
errors[NO_FILE_FOUND] = "No file found"
errors[NO_NAMING_FOUND] = "The asked naming rule was not found"
errors[EMPTY_STRING] = "Empty string"
errors[BAD_PARAM] = "Bad parameter"
errors[BAD_FILENAME_RULE] = "Bad rule usage to define a filename"
errors[NO_PATHING_FOUND] = "The asked pathing rule was not found"
errors[BAD_PATHNAME_RULE] = "Bad rule usage to define a pathname"
errors[NO_CONTEXT_KEY_FOUND] = "No context key found"
errors[NO_DELETE_CONTEXT_DEFAULT] = "Context key 'default' cannot be deleted"
errors[BAD_NAMING] = "Bad naming of the file name"
errors[LIST_INSTEAD_A_STRING] = "Expected a string but found a list"
class FileNames(FileNamesException, GuitastroTools):
""" Class to manage file names
** File name simple structure **
Any file name can be defined at less in three parts:
* *dirname*: A path as a prefix. e.g. '/tmp/2023/03/21'
* *fname*: The file name without directory nor extension. e.g. 'messier63-1'
* *extension*: The extension as a suffix (dot separator). e.g. '.fits'
The full file name of the example is : '/tmp/2023/03/21/messier63-1.fits'
It is recommended that 'dirname' is an absolute path.
From a given input file name, one can split it into keys of a dictionary:
::
dname = fn.dict("/home/myuser/myimages/messier57.fit")
Three of the keys are:
* *dirname*: "/home/myuser/myimages"
* *fname*: "messier57"
* *extension*: ".fit"
** File context **
The file context (fcontext) of a filename is an important concept of this Class.
It allows to manage different types of files. One type fer file context.
For a file context, any file name is defined in four parts:
* *rootdir*: A fixed root path as a prefix. e.g. '/tmp'
* *subdir*: A sub-directory (can be a tree) that is added to rootdir. e.g. '2023/03/21'
* *fname*: The file name without directory nor extension. e.g. 'messier63-1'
* *extension*: The extension as a suffix (dot separator). e.g. '.fits'
Note that a 'dirname' is the join of 'rootdir' and 'subdir'.
The contents of 'subdir' can be adapted to store files by dates or any other ways.
The contents of 'rootdir' appear as the common part of any files of this context.
It is recommended that 'rootdir' is an absolute path.
The use of file context is very powerfull coupled with naming and pathing rules (see later).
A file context defines a group of (rootdir, subdir, fname, extension).
The user can manage its own file contexts (create, delete).
By default the user is inside the file context named 'default'. The 'default' context cannot be deleted.
The fullfilename of the example is : '/tmp/2023/03/21/messier63-1.fits'
::
fn = FileNames()
fn.fcontext_create("images") # Create a new context named 'images'
fn.fcontext = "images" # Select the context named 'images'
fn.rootdir = "/tmp"
fn.subdir = "2023/03/21"
fn.fname = "messier63-1"
fn.extension = ".fits"
print(fn)
Print should display the following items:
* Current context: images (No description)
* Rootdir: /tmp
* Subdir: 2023/03/21
* Fname: messier63-1
* Extension: .fits
To retreive the full file name:
::
fn.join()
It should returns '/tmp/2023/03/21/messier63-1.fits'
**Night:**
A night is defined as the duration between two consecutive mean noons.
As a consequence the truncated date of the previous noon defines the night.
For example 20230506 is the night between 2023-05-06T12:00:00 and 2023-05-07T12:00:00
for the longitude 0 degree. For the longitude -90 it corresponds to the dates
between 2023-05-06T18:00:00 and 2023-05-07T18:00:00:
::
fn = FileNames()
fn.longitude = -90
night = "20230506"
jd1, jd2 = fn.night2date(night)
The result should be jd1=2460071.25 and jd2=2460072.25.
The night is usefull to dispatch data into folders corresponding to the acquisition night.
**Night directory:**
As astronomical images are often dispatched into night directories,
the method date2night() returns a string corresponding to the night
directory according an input date (i.e. DATE-OBS). The method date2night()
consider a night as from noon to noon. To do that, before using date2night()
you must specify the longitude of the observatory with the attribute longitude.
::
fn = FileNames()
fn.longitude = -90
date = "2023-06-12T23:02:45"
night = fn.date2night(date)
Note that date can be "now" of any format of the class Date of Guitastro.
The night name is useful when using 'subdir' to store large amount of files.
**Naming:**
Naming rules can be applied to verify a structured file name structure.
By default, there is no naming rule. Namings are included into file contexts.
List of naming rules is given by:
::
fn = FileNames()
namings = fn.namings()
To select a naming, use the method naming(). To form a file name in respect
of the selected naming you must prepare a dictionary as input of the
method naming_set(). The output of naming_set() gives the formed filename.
The reciprocal method is naming_get() which gives the dictionary from the
file name. The selected rule description and the list of keys of the dictionary
is returned from the method naming_rules().
**Pathing:**
Pathing rules can be applied to verify a structured path name structure.
By default, there is no pathing rule. Pathings are included into file contexts.
List of pathing rules is given by:
::
fn = FileNames()
pathings = fn.pathings()
To select a pathing, use the method pathing(). To form a path name in respect
of the selected pathing you must prepare a dictionary as input of the
method pathing_set(). The output of pathing_set() gives the formed pathname.
The reciprocal method is naming_get() which gives the dictionary from the
file name. The selected rule description and the list of keys of the dictionary
is returned from the method pathing_rules().
Any file name is defined in three parts: path, shortname, extension.
Default value of path can be get/set using the method path().
Default value of extension can be get/set using the method extension().
This class (when finished) will be used as parent into Guitastro classes
who are using files.
Instanciate an object from the class and use class methods as the following example:
::
fn = FileNames()
fn.extension(".fit")
fs = fn.fullfilename("m57")
**Structure of the generic file names:**
A filename is constituted by :
* 'dirname': The directory where the file is written.
* 'genename': The generic name of the file.
* 'sep': The separator character between genename and the index. Can be an empty string.
* 'index': The index of the file into a series. Can be an empty string.
* 'suffix': The end of the file name between the index and the extension.
* 'file_extension': The file extension (e.g. ".fit").
The concatenation of 'genename', 'sep', 'index', 'suffix' is called the short name.
The full file name is the concatenation of the 'dirname', the short name and the 'extension'. For example, to obtain the full file name from a short name:
::
fn = FileNames()
shortname = "m57"
fullname = fn.fullfilename(shortname)
fullname could be '/tmp/m57.fit'.
**Generic file names:**
It is often interessant to get all the file names corresponding to a series of files.
For example, a camera recorded the files i2.fit to i9.fit in the directory '/tmp',
the method genename() is like a glob.glob() but gives more informations.
The following example show how to get the information of generic name of such a series:
::
fn = FileNames()
shortname = "i1"
imafiles = fn.genename(shortname)
imafiles shoud be a dictionary as {'dirname': '/tmp', 'genename': 'i', 'sep': '', 'indexes': ['2', '3', '4', '5', '6', '7', '8', '9'], 'suffix': '', 'file_extension': '.fit', 'ndigit': 0}
imafiles is useful to process a series of images.
'ndigit' = 0 if the indexes are any number of digit. 'ndigit'=n corresponds to a format as C language "%0nd" (leading zeroes to obtain n characters).
"""
VERBOSE_NONE = 0
VERBOSE_SPECIFIC = 1
VERBOSE_DEBUG = 2
VERBOSE_ESSENTIAL = 4
VERBOSE_ALL = 8
NAMING_NONE = 0
NAMING_INDEXED1 = 1
NAMING_ROS1 = 2
NAMING_T1M1 = 3
NAMING_PYROS_IMG1 = 4
NAMING_PYROS_EPH1 = 5
NAMING_PYROS_SEQ1 = 6
NAMING_PYROS_FIL1 = 7
_naming_list = ["", "Indexed.1", "ROS.1", "T1M.1", "PyROS.img.1", "PyROS.eph.1", "PyROS.seq.1", "PyROS.fil.1"]
_naming_0_stypes = ["C0A", "L0A", "L1A", "L1B", "L1C", "L1D", "L1E", "L2A", "DA0", "DA1", "FL0", "FL1", "BI0", "BI1"]
_naming_1_stypes = ["AL", "IM", "BI", "DA", "FL"]
_see_naming_rules = ". See method naming_rules() to get rules"
_NAMING_RULES_SECTION_DATE = 0
_NAMING_RULES_SECTION_INTRO = 1
_NAMING_RULES_SECTION_FORMAT = 2
_NAMING_RULES_SECTION_REMARKS = 3
PATHING_NONE = 0
PATHING_YYYYMMDD = 1
PATHING_YYYY_YYYYMMDD = 2
PATHING_YYYY_MM_DD = 3
PATHING_PPPP_YYYYMMDD = 4
_pathing_list = ["", "YYYYMMDD", "YYYY/YYYYMMDD", "YYYY/MM/DD", "PPPP/YYYYMMDD"]
_see_pathing_rules = ". See method pathing_rules() to get rules"
_PATHING_RULES_SECTION_INTRO = 0
_PATHING_RULES_SECTION_FORMAT = 1
_PATHING_RULES_SECTION_REMARKS = 2
def __init__(self, *args, **kwargs):
try:
path = os.path.abspath(os.path.dirname(__file__))
file = os.path.join(path, "guitastrotools.py")
if path not in sys.path and os.path.exists(file):
sys.path.append(path)
import guitastrotools
except:
pass
self._rootdir0 = guitastrotools.conf_guitastro['path_products']
self._verbose_level = self.VERBOSE_NONE
self._longiau_deg = 0.0
# --- Contexts
contexts = {}
contexts["default"] = {'description':"No description"}
self._context = {}
for key, val in contexts.items():
val['naming'] = self.NAMING_INDEXED1
val['pathing'] = self.PATHING_NONE
val['pathnaming'] = self.NAMING_NONE
val['rootdir'] = self._rootdir0
val['subdir'] = ""
val['fname'] = "noname"
if key.find("image") >= 0:
val['extension'] = ".fit"
else:
val['extension'] = ".txt"
self._context[key] = val
self.fcontext = "default"
# --- naming_rule
if len(args) > 0 :
self.naming(args[0])
self.longitude = 0
def __repr__(self):
return str(self)
def __str__(self):
msg = ""
msg += f"Longitude: {self._longiau_deg} deg (for the method get_night)."
msg += f"\nContexts: {self.fcontexts}."
msg += f"\nCurrent context: {self.fcontext} ({self.fdescription})"
msg += f"\nPathnaming: {self.pathnaming()}"
msg += f"\nNaming: {self.naming()}"
msg += f"\nPathing: {self.pathing()}"
msg += f"\nRootdir: {self.rootdir}"
msg += f"\nSubdir: {self.subdir}"
msg += f"\nFname: {self.fname}"
msg += f"\nExtension: {self.extension}"
return msg
def _get_longitude(self):
return self._longiau_deg
def _set_longitude(self, longiau_deg:float):
""" Set the longitude of the observation siteobs.
This method is useful for the method get_night().
Args:
longiau_deg: The longitude of the siteobs must expressed in degrees, east increasing, from 0 to 360 (IAU convention).
::
ima1 = Ima()
ima1.longitude = 2.3456
"""
self._longiau_deg = longiau_deg
longitude = property(_get_longitude, _set_longitude)
# =============================================
# Print filters
# =============================================
def print_level(self, level:int=""):
if isinstance(level,type(int)) == True:
self._verbose_level = level
return self._verbose_level
def print_msg(self, level:int, message:str):
if message == "":
self._verbose_level = level
return
else:
if self._verbose_level >= level:
print(message)
# =============================================
# Managing naming
# =============================================
def namings(self):
"""List of file namings
File names can be formed using given rules.
This method returns a list of all possible naming rules.
"""
return self._naming_list
def naming(self, *args):
"""Get the current naming of files or set a new one
Args:
*args: a string with a new naming of files. See the list using namings().
Returns:
The new selected naming.
Example: To get the current naming
::
fn = FileNames()
naming = fn.naming()
Example: To select a new naming
::
fn = FileNames()
fn.naming("PyROS.img.1")
"""
if len(args) >= 1:
new_naming = args[0]
new_namingu = new_naming.upper()
n = len(self._naming_list)
found = False
for k in range(n):
naming = self._naming_list[k]
if naming.upper() == new_namingu:
self.fcontext_value('naming',k)
found = True
if found == False:
texte = f"{new_naming} not found amongst {self._naming_list}"
raise FileNamesException(FileNamesException.NO_NAMING_FOUND, texte)
return self._naming_list[self.fcontext_value('naming')]
def __naming_rules_pyros_img1(self, section):
name = self._naming_list[self.fcontext_value('naming')]
texte = ""
if section == self._NAMING_RULES_SECTION_DATE:
texte += "2023-03-01T15:05:13"
elif section == self._NAMING_RULES_SECTION_INTRO:
texte +=f"{name} is a file name format for the images of Python Robotic Observatory Software.\n"
texte += "Specific terminology:\n"
texte += "* Unit: The set of Mount and Channels that define a 'telescope'.\n"
texte += "* Channel: An optical path + camera of a Unit. A unit can have many Channels.\n"
texte += "* Album: A set of Channels for which data can be combined by post processing.\n"
texte += "* Sequence: A set of Albums. A sequence is a hierarchy Channels/Planes/Frames.\n"
texte += "* Plane: A set of Frames. A Plane is composed by Frames.\n"
texte += "* Frame: A unitary record (e.g. an image).\n"
elif section == self._NAMING_RULES_SECTION_FORMAT:
texte += " 1 2 3 4 5\n"
texte += "0123456789 123456789 123456789 123456789 123456789 123\n"
texte += "TTT_YYYYMMDD_hhmmsscccccc_V_UUU_CCC_IIIIIIIIII_PPP_FFF\n"
texte += "\n"
texte +=f"TTT = 'ftype' = file type amongst {self._naming_0_stypes}\n"
texte += "YYYYMMDD = 'date' = Year Month Day. e.g. 20221109\n"
texte += "hhmmsscccccc = 'time' = Hours Minutes Seconds Microseconds. e.g. 235604123456\n"
texte += "V = 'version' = Version of the naming rule. e.g. 1\n"
texte += "UUU = 'unit' = Telescope unit. e.g. TNC\n"
texte += "CCC = 'channel' = Optical channel designation. e.g. CH1\n"
texte += "IIIIIIIIII = 'id_seq' = ID of the file in the database. e.g. 0000001234\n"
texte += "PPP = 'plane' = index of the plane. e.g. 001\n"
texte += "FFF = 'frame' = index of the frame. e.g. 012\n"
elif section == self._NAMING_RULES_SECTION_REMARKS:
texte += "Example: L0A_20221109_235406123456_1_TNC_CH1_0123456789_001_001\n"
texte += "UUU, CCC are accronyms (string)\n"
texte += "V, IIIIIIIIII, PPP, FFF are digits (int)\n"
texte += "CCC is a Channel for L0A, L1A, L1B, L1C ftype levels but should be the Album for L1D level"
return texte
def __naming_rules_pyros_fil1(self, section):
name = self._naming_list[self.fcontext_value('naming')]
texte = ""
if section == self._NAMING_RULES_SECTION_DATE:
texte += "2023-09-13T21:05:13"
elif section == self._NAMING_RULES_SECTION_INTRO:
texte +=f"{name} is a file name format for the flats of Python Robotic Observatory Software.\n"
texte += "Specific terminology:\n"
texte += "* Unit: The set of Mount and Channels that define a 'telescope'.\n"
texte += "* Channel: An optical path + camera of a Unit. A unit can have many Channels.\n"
texte += "* Album: A set of Channels for which data can be combined by post processing.\n"
texte += "* Sequence: A set of Albums. A sequence is a hierarchy Channels/Planes/Frames.\n"
texte += "* Plane: A set of Frames. A Plane is composed by Frames.\n"
texte += "* Filter: A symbol of a filter (e.g. 'rp').\n"
elif section == self._NAMING_RULES_SECTION_FORMAT:
texte += " 1 2 3 4 5\n"
texte += "0123456789 123456789 123456789 123456789 123456789 123\n"
texte += "TTT_YYYYMMDD_hhmmsscccccc_V_UUU_CCC_IIIIIIIIII_PPP_f*\n"
texte += "\n"
texte +=f"TTT = 'ftype' = file type amongst {self._naming_0_stypes}\n"
texte += "YYYYMMDD = 'date' = Year Month Day. e.g. 20221109\n"
texte += "hhmmsscccccc = 'time' = Hours Minutes Seconds Microseconds. e.g. 235604123456\n"
texte += "V = 'version' = Version of the naming rule. e.g. 1\n"
texte += "UUU = 'unit' = Telescope unit. e.g. TNC\n"
texte += "CCC = 'channel' = Optical channel designation. e.g. CH1\n"
texte += "IIIIIIIIII = 'id_seq' = ID of the file in the database. e.g. 0000001234\n"
texte += "PPP = 'plane' = index of the plane. e.g. 001\n"
texte += "f* = 'filter' = Filter symbol. e.g. rp\n"
elif section == self._NAMING_RULES_SECTION_REMARKS:
texte += "Example: FL1_20221109_235406123456_1_TNC_CH1_0123456789_001_rp\n"
texte += "UUU, CCC are accronyms (string)\n"
texte += "V, IIIIIIIIII, PPP, are digits (int)\n"
texte += "f* is a string (string)\n"
return texte
def __naming_rules_pyros_eph1(self, section):
name = self._naming_list[self.fcontext_value('naming')]
texte = ""
if section == self._NAMING_RULES_SECTION_DATE:
texte += "2023-09-09T08:24:13"
elif section == self._NAMING_RULES_SECTION_INTRO:
texte +=f"{name} is a file name format for the ephemeris of Python Robotic Observatory Software.\n"
texte += "Specific terminology:\n"
texte += "* Period: Symbol that defines a range of dates.\n"
texte += "* Unit: The set of Mount and Channels that define a 'telescope'.\n"
elif section == self._NAMING_RULES_SECTION_FORMAT:
texte += " 1 2 3 4 5\n"
texte += "0123456789 123456789 123456789 123456789 123456789 123\n"
texte += "PPPP_YYYYMMDD_V_UUU_t*\n"
texte += "\n"
texte += "PPPP = 'period' = Period of validity\n"
texte += "YYYYMMDD = 'date' = Year Month Day. e.g. 20221109\n"
texte += "V = 'version' = Version of the naming rule. e.g. 1\n"
texte += "UUU = 'unit' = Telescope unit. e.g. TNC\n"
texte += "t* = Celestial target. e.g. sun\n"
elif section == self._NAMING_RULES_SECTION_REMARKS:
texte += "Example: P001_20221109_1_TNC_sun\n"
texte += "UUU, PPPP are accronyms (string)\n"
texte += "V, is digits (int)\n"
texte += "t*, is a celestial name (string)\n"
return texte
def __naming_rules_pyros_seq1(self, section):
name = self._naming_list[self.fcontext_value('naming')]
texte = ""
if section == self._NAMING_RULES_SECTION_DATE:
texte += "2023-04-24T09:46:13"
elif section == self._NAMING_RULES_SECTION_INTRO:
texte +=f"{name} is a file name format for the sequences of Python Robotic Observatory Software.\n"
texte += "Specific terminology:\n"
texte += "* Period: Symbol that defines a range of dates.\n"
texte += "* Unit: The set of Mount and Channels that define a 'telescope'.\n"
texte += "* Channel: An optical path + camera of a Unit. A unit can have many Channels.\n"
texte += "* Album: A set of Channels for which data can be combined by post processing.\n"
texte += "* Sequence: A set of Albums. A sequence is a hierarchy Channels/Planes/Frames.\n"
elif section == self._NAMING_RULES_SECTION_FORMAT:
texte += " 1 2 3 4 5\n"
texte += "0123456789 123456789 123456789 123456789 123456789 123\n"
texte += "PPPP_YYYYMMDD_V_UUU_IIIIIIIIII\n"
texte += "\n"
texte += "PPPP = 'period' = Period of validity\n"
texte += "YYYYMMDD = 'date' = Year Month Day. e.g. 20221109\n"
texte += "V = 'version' = Version of the naming rule. e.g. 1\n"
texte += "UUU = 'unit' = Telescope unit. e.g. TNC\n"
texte += "IIIIIIIIII = 'id_seq' = ID of the sequence in the database. e.g. 0000001234\n"
elif section == self._NAMING_RULES_SECTION_REMARKS:
texte += "Example: P001_20221109_1_TNC_0123456789\n"
texte += "UUU, PPPP are accronyms (string)\n"
texte += "V, IIIIIIIIII, are digits (int)\n"
return texte
def __naming_rules_ros1(self, section):
name = self._naming_list[self.fcontext_value('naming')]
texte = ""
if section == self._NAMING_RULES_SECTION_DATE:
texte += "2022-11-01T15:05:13"
elif section == self._NAMING_RULES_SECTION_INTRO:
texte +=f"{name} is a file name format for the Robotic Observatory Software.\n"
texte += "Specific terminology:\n"
texte += "* Unit: The set of Mount and Channels that define a 'telescope'.\n"
texte += "* Scene: A set of 1 to 6 images.\n"
elif section == self._NAMING_RULES_SECTION_FORMAT:
texte += " 1 2 3 \n"
texte += "0123456789 123456789 123456789 123456\n"
texte += "TT_YYYYMMDD_hhmmssccc_IIIIII_IIIIIIUU\n"
texte += "\n"
texte +=f"TT = 'ftype' = file type amongst {self._naming_1_stypes}\n"
texte += "YYYYMMDD = 'date' = Year Month Day. e.g. 20221109\n"
texte += "hhmmssccc = 'time' = Hours Minutes Seconds Milliseconds. e.g. 235604123\n"
texte += "IIIIII_IIIIII = 'id_scene' = ID of the file in the database. e.g. 0000001234\n"
texte += "UU = 'unit' = Telescope unit. e.g. 01\n"
elif section == self._NAMING_RULES_SECTION_REMARKS:
texte += "Example: IM_20220715_222616947_000003_79254401\n"
texte += "UU are ID of telescopes (digits)\n"
texte += "IIIIII_IIIIII are digits (int)\n"
texte += "IIIIII_IIIIII is the ID scene IIIIIIIIIIII splited into 6 characters separated by an underscore."
return texte
def __naming_rules_t1m1(self, section):
name = self._naming_list[self.fcontext_value('naming')]
texte = ""
if section == self._NAMING_RULES_SECTION_DATE:
texte += "2022-11-01T15:05:13"
elif section == self._NAMING_RULES_SECTION_INTRO:
texte +=f"{name} is a file name format for the one meter telescope at Pic du Midi.\n"
elif section == self._NAMING_RULES_SECTION_FORMAT:
texte += " 1 2 \n"
texte += "0123456789 123456789 123\n"
texte += "T1M_YYYYMMDD_hhmmss_ccc_t*_Filtre_f*_binbxb.i\n"
texte += "\n"
texte += "T1M = Always 'T1M'\n"
texte += "YYYYMMDD = 'date' = Year Month Day. e.g. 20221109\n"
texte += "hhmmss = 'time' = Hours Minutes Seconds Milliseconds. e.g. 235604\n"
texte += "ccc = 'millis' = Milliseconds. e.g. 123\n"
texte += "t* = 'target' = Name of the target. e.g. 38Lyn\n"
texte += "Filtre = Always 'Filtre'\n"
texte += "f* = 'filter' = Filter name. e.g. 672-SII\n"
texte += "bin = Always 'bin' for binning\n"
texte += "bxb = 'binning' = Binning. e.g. 'bin1x1' or [1, 1] or 1\n"
texte += "i* = 'index' = Index of the series. e.g. 1\n"
elif section == self._NAMING_RULES_SECTION_REMARKS:
texte += "Example: T1M_20220123_010738_702_38LYN_Filtre_672-SII_bin1x1.1\n"
texte += "n*, f* are str\n"
texte += "b is int\n"
texte += "i* is int"
return texte
def __naming_rules_indexed1(self, section):
name = self._naming_list[self.fcontext_value('naming')]
texte = ""
if section == self._NAMING_RULES_SECTION_DATE:
texte += "2023-09-11T15:49:13"
elif section == self._NAMING_RULES_SECTION_INTRO:
texte +=f"{name} is a file name format for files containing an index.\n"
elif section == self._NAMING_RULES_SECTION_FORMAT:
texte += " 1 2 \n"
texte += "0123456789 123456789 123\n"
texte += "g*si*u*\n"
texte += "\n"
texte += "g* = 'genename' = Generic name e.g. 'M63'\n"
texte += "s = 'sep' = Separator character e.g. '-' or nothing\n"
texte += "i* = 'indexes' = Index or List of indexes e.g. ['1', '2'] or ['0001', '0002']\n"
texte += "'ndigit' = Number of digits of the indexe(s) if needed e.g. '' or '4'\n"
texte += "u* = 'suffix' = Suffix e.g. 'B'\n"
elif section == self._NAMING_RULES_SECTION_REMARKS:
texte += "Example: M63-0001B\n"
texte += "g*, s, u* are str\n"
texte += "i* is int\n"
texte += "'ndigit' is int"
return texte
def naming_rules(self) -> str:
"""Get the current naming rules for files
Returns:
A text file giving the rule description.
Example:
::
fn = FileNames()
print(fn.naming_rules())
"""
date_iso = datetime.datetime.utcnow().isoformat()
name = self._naming_list[self.fcontext_value('naming')]
texte = ""
if self.fcontext_value('naming') == self.NAMING_NONE:
texte += "Filename naming rules\n"
else:
texte +=f"Filename naming rules for {name}\n"
date_iso = datetime.datetime.utcnow().isoformat()
dat = ""
if self.fcontext_value('naming') == self.NAMING_PYROS_IMG1:
dat = self.__naming_rules_pyros_img1(self._NAMING_RULES_SECTION_DATE)
elif self.fcontext_value('naming') == self.NAMING_PYROS_SEQ1:
dat = self.__naming_rules_pyros_seq1(self._NAMING_RULES_SECTION_DATE)
elif self.fcontext_value('naming') == self.NAMING_ROS1:
dat = self.__naming_rules_ros1(self._NAMING_RULES_SECTION_DATE)
elif self.fcontext_value('naming') == self.NAMING_T1M1:
dat = self.__naming_rules_t1m1(self._NAMING_RULES_SECTION_DATE)
elif self.fcontext_value('naming') == self.NAMING_INDEXED1:
dat = self.__naming_rules_indexed1(self._NAMING_RULES_SECTION_DATE)
elif self.fcontext_value('naming') == self.NAMING_PYROS_FIL1:
dat = self.__naming_rules_pyros_fil1(self._NAMING_RULES_SECTION_DATE)
if dat != "":
texte +=f"Updated on {dat}\n"
texte +=f"Written on {date_iso}\n"
# ---
h1 = "1. Introduction"
texte +=f"\n{h1}\n" + "="*len(h1) + "\n\n"
if self.fcontext_value('naming') == self.NAMING_NONE:
texte += "No specific rule. File names can be formed as you want.\n"
return texte
elif self.fcontext_value('naming') == self.NAMING_PYROS_IMG1:
texte += self.__naming_rules_pyros_img1(self._NAMING_RULES_SECTION_INTRO)
elif self.fcontext_value('naming') == self.NAMING_PYROS_EPH1:
texte += self.__naming_rules_pyros_eph1(self._NAMING_RULES_SECTION_INTRO)
elif self.fcontext_value('naming') == self.NAMING_PYROS_SEQ1:
texte += self.__naming_rules_pyros_seq1(self._NAMING_RULES_SECTION_INTRO)
elif self.fcontext_value('naming') == self.NAMING_ROS1:
texte += self.__naming_rules_ros1(self._NAMING_RULES_SECTION_INTRO)
elif self.fcontext_value('naming') == self.NAMING_T1M1:
texte += self.__naming_rules_t1m1(self._NAMING_RULES_SECTION_INTRO)
elif self.fcontext_value('naming') == self.NAMING_INDEXED1:
texte += self.__naming_rules_indexed1(self._NAMING_RULES_SECTION_INTRO)
elif self.fcontext_value('naming') == self.NAMING_PYROS_FIL1:
texte += self.__naming_rules_pyros_fil1(self._NAMING_RULES_SECTION_INTRO)
# ---
h1 = "2. Format of the file names"
texte +=f"\n{h1}\n" + "="*len(h1) + "\n\n"
if self.fcontext_value('naming') == self.NAMING_PYROS_IMG1:
texte += self.__naming_rules_pyros_img1(self._NAMING_RULES_SECTION_FORMAT)
elif self.fcontext_value('naming') == self.NAMING_PYROS_EPH1:
texte += self.__naming_rules_pyros_eph1(self._NAMING_RULES_SECTION_FORMAT)
elif self.fcontext_value('naming') == self.NAMING_PYROS_SEQ1:
texte += self.__naming_rules_pyros_seq1(self._NAMING_RULES_SECTION_FORMAT)
elif self.fcontext_value('naming') == self.NAMING_ROS1:
texte += self.__naming_rules_ros1(self._NAMING_RULES_SECTION_FORMAT)
elif self.fcontext_value('naming') == self.NAMING_T1M1:
texte += self.__naming_rules_t1m1(self._NAMING_RULES_SECTION_FORMAT)
elif self.fcontext_value('naming') == self.NAMING_INDEXED1:
texte += self.__naming_rules_indexed1(self._NAMING_RULES_SECTION_FORMAT)
elif self.fcontext_value('naming') == self.NAMING_PYROS_FIL1:
texte += self.__naming_rules_pyros_fil1(self._NAMING_RULES_SECTION_FORMAT)
# ---
h1 = "3. Remarks"
texte +=f"\n{h1}\n" + "="*len(h1) + "\n\n"
if self.fcontext_value('naming') == self.NAMING_PYROS_IMG1:
texte += self.__naming_rules_pyros_img1(self._NAMING_RULES_SECTION_REMARKS)
elif self.fcontext_value('naming') == self.NAMING_PYROS_EPH1:
texte += self.__naming_rules_pyros_eph1(self._NAMING_RULES_SECTION_REMARKS)
elif self.fcontext_value('naming') == self.NAMING_PYROS_SEQ1:
texte += self.__naming_rules_pyros_seq1(self._NAMING_RULES_SECTION_REMARKS)
elif self.fcontext_value('naming') == self.NAMING_ROS1:
texte += self.__naming_rules_ros1(self._NAMING_RULES_SECTION_REMARKS)
elif self.fcontext_value('naming') == self.NAMING_T1M1:
texte += self.__naming_rules_t1m1(self._NAMING_RULES_SECTION_REMARKS)
elif self.fcontext_value('naming') == self.NAMING_INDEXED1:
texte += self.__naming_rules_indexed1(self._NAMING_RULES_SECTION_REMARKS)
elif self.fcontext_value('naming') == self.NAMING_PYROS_FIL1:
texte += self.__naming_rules_pyros_fil1(self._NAMING_RULES_SECTION_REMARKS)
# ---
texte += "\n\n=== End of the Document ==="
return texte
def naming_ident(self, fname:str) -> dict:
"""Identify the naming of a file name comparing with known naming rules
Args:
fname: a filename with no path and no extension.
Returns:
The identified naming.
Example:
::
fn = FileNames()
fn.naming_ident("L0A_20221109_235406123456_1_TNC_CH1_0123456789_001_001")
>>> 'PyROS.img.1'
"""
p = pathlib.Path(fname)
basename = p.name # with suffixes
suffixes = p.suffixes
extension = "" # all the suffixes
for suffixe in suffixes:
extension += suffixe
k = basename.find(extension)
if k>0:
fname = basename[:k] # supress extension
else:
fname = basename # has no extension
naming = self.NAMING_NONE
n = len(fname)
if n == 54:
words = fname.split("_")
n = len(words)
if n == 9:
param = {}
param['ftype'] = words[0]
param['date'] = words[1]
param['time'] = words[2]
param['version'] = words[3]
param['unit'] = words[4]
param['channel'] = words[5]
param['id_seq'] = words[6]
param['plane'] = words[7]
param['frame'] = words[8]
old_naming = self.fcontext_value('naming')
self.fcontext_value('naming', self.NAMING_PYROS_IMG1)
try:
fname_verified = self.naming_set(**param)
if fname == fname_verified:
naming = self.NAMING_PYROS_IMG1
except:
pass
self.fcontext_value('naming', old_naming)
if n == 30:
words = fname.split("_")
n = len(words)
if n == 5:
param = {}
param['period'] = words[0]
param['date'] = words[1]
param['version'] = words[2]
param['unit'] = words[3]
param['id_seq'] = words[4]
old_naming = self.fcontext_value('naming')
self.fcontext_value('naming', self.NAMING_PYROS_SEQ1)
try:
fname_verified = self.naming_set(**param)
if fname == fname_verified:
naming = self.NAMING_PYROS_SEQ1
except:
pass
self.fcontext_value('naming', old_naming)
elif n == 37:
words = fname.split("_")
n = len(words)
if n == 5:
param = {}
param['ftype'] = words[0]
param['date'] = words[1]
param['time'] = words[2]
i1 = words[3]
iu = words[4]
if len(iu)>2:
i2 = iu[:-2]
param['unit'] = iu[-2:]
param['id_scene'] = i1+i2
old_naming = self.fcontext_value('naming')
self.fcontext_value('naming', self.NAMING_ROS1)
try:
fname_verified = self.naming_set(**param)
if fname == fname_verified:
naming = self.NAMING_ROS1
except:
pass
self.fcontext_value('naming', old_naming)
if naming == self.NAMING_NONE and n>3:
# case of floating length file names
if fname[:3] == "T1M":
fname += suffixes[0]
param = {}
words = fname.split("_")
n = len(words)
if n >= 8:
kf = fname.find("_Filtre_", 25)
kb = fname.find("_bin", 36)
if kf > 0 and kb > 0:
param['date'] = words[1]
param['time'] = words[2]
param['millis'] = words[3]
param['target'] = fname[24:kf]
param['filter'] = fname[kf+len("_Filtre_"):kb]
rest = fname[kb+len("_bin"):]
b = int(rest[0])
param['binning'] = [b, b]
kd = rest.find(".")
kd2 = rest.find(".",kd+1)
if kd2 == -1:
kd2 = len(rest)
param['index'] = int(rest[kd+1:kd2])
old_naming = self.fcontext_value('naming')
self.fcontext_value('naming', self.NAMING_T1M1)
try:
fname_verified = self.naming_set(**param)
if fname == fname_verified:
naming = self.NAMING_T1M1
except:
pass
self.fcontext_value('naming', old_naming)
# --- Try NAMING_PYROS_EPH1
words = fname.split("_")
n = len(words)
if n >= 5:
valid = False
if len(words[0])==4 and len(words[1])==8 and len(words[2])==1 and len(words[3])==3:
valid = True
if valid == True:
if words[0][0] != 'P':
valid == False
if valid == True:
param = {}
param['period'] = words[0]
param['date'] = words[1]
param['version'] = words[2]
param['unit'] = words[3]
k4 = 0
for k in range(4):
k4 += len(words[k]) + 1
param['target'] = fname[k4:]
old_naming = self.fcontext_value('naming')
self.fcontext_value('naming', self.NAMING_PYROS_EPH1)
try:
fname_verified = self.naming_set(**param)
if fname == fname_verified:
naming = self.NAMING_PYROS_EPH1
except:
pass
self.fcontext_value('naming', old_naming)
# --- Try NAMING_PYROS_FIL1
if n >= 9:
param = {}
param['ftype'] = words[0]
param['date'] = words[1]
param['time'] = words[2]
param['version'] = words[3]
param['unit'] = words[4]
param['channel'] = words[5]
param['id_seq'] = words[6]
param['plane'] = words[7]
k8 = 0
for k in range(8):
k8 += len(words[k]) + 1
param['filter'] = fname[k8:]
old_naming = self.fcontext_value('naming')
self.fcontext_value('naming', self.NAMING_PYROS_FIL1)
try:
fname_verified = self.naming_set(**param)
if fname == fname_verified:
naming = self.NAMING_PYROS_FIL1
except:
pass
self.fcontext_value('naming', old_naming)
if naming == self.NAMING_NONE:
# Any other formats can reasch the indexed rules
naming = self.NAMING_INDEXED1
return self._naming_list[naming]
def naming_get(self, fname:str) -> dict:
"""Get parameters that build the file name according the current naming rules
Args:
fname: a filename with no path and no extension.
Returns:
The parameter dictionary which differ for each naming.
Example:
::
fn = FileNames()
fn.naming("PyROS.img.1")
params = fn.naming_get("L0A_20221109_235406123456_1_TNC_CH1_0123456789_001_012")
The answer (params dict) should be {'ftype': 'L0A', 'date': '20221109', 'time': '235406123456', 'version': '1', 'unit': 'TNC', 'channel': 'CH1', 'id_seq': '0123456789', 'plane': '001', 'frame': '012'}
"""
param = {}
see_rules = self._see_naming_rules
# --- get only the filename from a fullpathname
if isinstance(fname, list):
fnames = fname
fname = fnames[0]
else:
fnames = []
dname = self.dict(fname)
fname = dname['fname']
fname_verified = ""
if self.fcontext_value('naming') == self.NAMING_NONE:
param['fname'] = fname
elif self.fcontext_value('naming') == self.NAMING_PYROS_IMG1:
n = len(fname)
nn = 54
if n != nn:
texte =f"File name '{fname}' must be a string of {nn} characters" + see_rules
raise FileNamesException(FileNamesException.BAD_FILENAME_RULE, texte)
words = fname.split("_")
n = len(words)
nn = 9
if n != nn:
texte =f"File name '{fname}' must contain {nn-1} underscore characters" + see_rules
raise FileNamesException(FileNamesException.BAD_FILENAME_RULE, texte)
param['ftype'] = words[0]
param['date'] = words[1]
param['time'] = words[2]
param['version'] = words[3]
param['unit'] = words[4]
param['channel'] = words[5]
param['id_seq'] = words[6]
param['plane'] = words[7]
param['frame'] = words[8]
fname_verified = self.naming_set(**param)
if fname != fname_verified:
raise FileNamesException(FileNamesException.BAD_FILENAME_RULE)
elif self.fcontext_value('naming') == self.NAMING_PYROS_FIL1:
n = len(fname)
nn = 52
if n < nn:
texte =f"File name '{fname}' must be a string of at less {nn} characters" + see_rules
raise FileNamesException(FileNamesException.BAD_FILENAME_RULE, texte)
words = fname.split("_")
n = len(words)
nn = 9
if n < nn:
texte =f"File name '{fname}' must contain at less {nn-1} underscore characters" + see_rules
raise FileNamesException(FileNamesException.BAD_FILENAME_RULE, texte)
param['ftype'] = words[0]
param['date'] = words[1]
param['time'] = words[2]
param['version'] = words[3]
param['unit'] = words[4]
param['channel'] = words[5]
param['id_seq'] = words[6]
param['plane'] = words[7]
k8 = 0
for k in range(8):
k8 += len(words[k]) + 1
param['filter'] = fname[k8:]
fname_verified = self.naming_set(**param)
if fname != fname_verified:
raise FileNamesException(FileNamesException.BAD_FILENAME_RULE)
elif self.fcontext_value('naming') == self.NAMING_PYROS_EPH1:
n = len(fname)
nn = 20
if n <= nn:
texte =f"File name '{fname}' must be a string of at less {nn} characters" + see_rules
raise FileNamesException(FileNamesException.BAD_FILENAME_RULE, texte)
words = fname.split("_")
n = len(words)
nn = 5
if n < nn:
texte =f"File name '{fname}' must contain at less {nn-1} underscore characters" + see_rules
raise FileNamesException(FileNamesException.BAD_FILENAME_RULE, texte)
param['period'] = words[0]
param['date'] = words[1]
param['version'] = words[2]
param['unit'] = words[3]
k4 = 0
for k in range(4):
k4 += len(words[k]) + 1
param['target'] = fname[k4:]
fname_verified = self.naming_set(**param)
if fname != fname_verified:
raise FileNamesException(FileNamesException.BAD_FILENAME_RULE)
elif self.fcontext_value('naming') == self.NAMING_PYROS_SEQ1:
n = len(fname)
nn = 30
if n != nn:
texte =f"File name '{fname}' must be a string of {nn} characters" + see_rules
raise FileNamesException(FileNamesException.BAD_FILENAME_RULE, texte)
words = fname.split("_")
n = len(words)
nn = 5
if n != nn:
texte =f"File name '{fname}' must contain {nn-1} underscore characters" + see_rules
raise FileNamesException(FileNamesException.BAD_FILENAME_RULE, texte)
param['period'] = words[0]
param['date'] = words[1]
param['version'] = words[2]
param['unit'] = words[3]
param['id_seq'] = words[4]
fname_verified = self.naming_set(**param)
if fname != fname_verified:
raise FileNamesException(FileNamesException.BAD_FILENAME_RULE)
elif self.fcontext_value('naming') == self.NAMING_ROS1:
n = len(fname)
nn = 37
if n != nn:
texte =f"File name '{fname}' must be a string of {nn} characters" + see_rules
raise FileNamesException(FileNamesException.BAD_FILENAME_RULE, texte)
words = fname.split("_")
n = len(words)
nn = 5
if n != nn:
texte =f"File name '{fname}' must contain {nn-1} underscore characters" + see_rules
raise FileNamesException(FileNamesException.BAD_FILENAME_RULE, texte)
param['ftype'] = words[0]
param['date'] = words[1]
param['time'] = words[2]
i1 = words[3]
iu = words[4]
if len(iu)>2:
i2 = iu[:-2]
param['unit'] = iu[-2:]
param['id_scene'] = i1+i2
fname_verified = self.naming_set(**param)
if fname != fname_verified:
raise FileNamesException(FileNamesException.BAD_FILENAME_RULE)
elif self.fcontext_value('naming') == self.NAMING_T1M1:
if fname[:3] == "T1M":
fname += dname['suffixes'][0] # add the first suffix as rank
words = fname.split("_")
n = len(words)
if n >= 8:
kf = fname.find("_Filtre_", 25)
kb = fname.find("_bin", 36)
if kf > 0 and kb > 0:
param['date'] = words[1]
param['time'] = words[2]
param['millis'] = words[3]
param['target'] = fname[24:kf]
param['filter'] = fname[kf+len("_Filtre_"):kb]
rest = fname[kb+len("_bin"):]
b = int(rest[0])
param['binning'] = [b, b]
kd = rest.find(".")
kd2 = rest.find(".",kd+1)
if kd2 == -1:
kd2 = len(rest)
param['index'] = int(rest[kd+1:kd2])
fname_verified = self.naming_set(**param)
if fname != fname_verified:
raise FileNamesException(FileNamesException.BAD_FILENAME_RULE)
elif self.fcontext_value('naming') == self.NAMING_INDEXED1:
if len(fnames) == 0:
param = self._naming_get_indexed1(fname)
else:
indexes = []
for fname in fnames:
param = self._naming_get_indexed1(fname)
indexes.append(param['indexes'])
param['indexes'] = indexes
# --- update fname
self.fname = fname
# --- return params
return param
def _naming_get_indexed1(self, fname):
"""Return a dict of the semantic analysis for Indexed.1
Take account for wildcard characters.
"""
#print(f"{fname=}")
param = {}
# --- search the separator for index
is_sep = False
seps = ['.', '_', '-']
kseps = []
k = len(fname) - 1
for car in fname[::-1]:
if car in seps:
kseps.append(k)
k -= 1
# --- search a true index
index_indexes = []
for k1 in kseps:
subb = fname[k1+1:]
index = ""
for sub in subb:
if sub.isdigit() or sub == "*" or sub == "?":
index += sub
else:
break
if len(index) > 0:
index_indexes = [k1, k1+1+len(index)]
is_sep = True
break
#print(f"(1) {index_indexes=}")
if index_indexes == []:
param['genename'] = fname
param['sep'] = ""
param['indexes'] = ""
param['ndigit'] = 0
param['suffix'] = ""
# --- search for an index without a separator
k1 = -1
k2 = -1
ki = False
k = len(fname) - 1
for car in fname[::-1]:
#print(f"{car=} {k2=} {k=}")
if car == "*":
k2 = k + 1
k1 = k
break
elif car == "?":
if k2 == -1:
k2 = k + 1
ki = True
k1 = k
elif car.isdigit() and ki == False:
if k2 == -1:
k2 = k + 1
k1 = k
else:
k1 = k + 1
#print(f"(h) {k1=}")
break
k -= 1
if k2 >=0:
if k1 == -1:
k1 = 0
index_indexes = [k1, k2]
#print(f"(2) {index_indexes=}")
if len(index_indexes) == 2:
k1, k2 = index_indexes
param['genename'] = fname[:k1]
#print(f"=> {k1=} {k2=} {param['genename']=} {fname[k1-1:k2]=}")
if is_sep:
param['sep'] = fname[k1]
param['indexes'] = fname[k1+1:k2]
else:
param['indexes'] = fname[k1:k2]
if param['indexes'][0] == '0' or param['indexes'][0] == '?':
param['ndigit'] = len(param['indexes'])
else:
param['ndigit'] = 0
param['suffix'] = fname[k2:]
else:
if param['genename'][-1] == "*" and param['indexes'] == "":
param['genename'] = param['genename'][:-1]
param['indexes'] = "*"
if param['genename'] == "" and param['indexes'] == "*":
param['genename'] = "*"
param['indexes'] = ""
return param
def naming_keys(self) -> list:
"""Return the keys of a file context
Returns:
Key names.
"""
wildcard = self.naming_wildcard()
param = self.naming_get(wildcard)
return list(param.keys())
def naming_wildcard(self, *args: str, **kwargs: int) -> str:
"""Return the wildcard corresponding to the naming rule
Returns:
The wildcard corresponding to the naming rule.
"""
if self.fcontext_value('naming') == self.NAMING_NONE:
wildcard = "*"
elif self.fcontext_value('naming') == self.NAMING_PYROS_IMG1:
wildcard = "???_????????_????????????_?_???_???_??????????_???_???"
elif self.fcontext_value('naming') == self.NAMING_PYROS_FIL1:
wildcard = "???_????????_????????????_?_???_???_??????????_???_*"
elif self.fcontext_value('naming') == self.NAMING_PYROS_EPH1:
wildcard = "????_????????_?_???_*"
elif self.fcontext_value('naming') == self.NAMING_PYROS_SEQ1:
wildcard = "????_????????_?_???_??????????"
elif self.fcontext_value('naming') == self.NAMING_ROS1:
wildcard = "??_????????_?????????_??????_????????"
elif self.fcontext_value('naming') == self.NAMING_T1M1:
wildcard = "T1M_????????_??????_???_*_Filtre_*_bin?x?.*"
elif self.fcontext_value('naming') == self.NAMING_INDEXED1:
wildcard = "*"
# - Param constraints
nkwa = len(kwargs)
na = len(args)
if nkwa > 0:
param = self.naming_get(wildcard)
# - case indexes
if "i" in kwargs.keys():
if kwargs['i'] == True and na >= 1:
fname = args[0]
param_fname = self.naming_get(fname)
keys = []
if self.fcontext_value('naming') == self.NAMING_INDEXED1:
keys = ['indexes']
elif self.fcontext_value('naming') == self.NAMING_ROS1:
keys = ['date','time','id_scene']
elif self.fcontext_value('naming') == self.NAMING_T1M1:
keys = ['date','time','millis','index']
elif self.fcontext_value('naming') == self.NAMING_PYROS_IMG1:
keys = ['date','time','frame']
elif self.fcontext_value('naming') == self.NAMING_PYROS_EPH1:
keys = ['date']
elif self.fcontext_value('naming') == self.NAMING_PYROS_SEQ1:
keys = ['id_seq']
elif self.fcontext_value('naming') == self.NAMING_PYROS_FIL1:
keys = ['date','time']
#print(f"{param_fname=}")
for key in keys:
param_fname[key] = param[key]
param = param_fname
if self.fcontext_value('naming') == self.NAMING_INDEXED1:
if param['indexes'] == "":
if param['ndigit'] > 0:
param['indexes'] = "?"*param['ndigit']
else:
param['indexes'] = "*"
#print(f"{param=}")
# - constraints
for key, val in kwargs.items():
if key in param.keys():
param[key] = val
wildcard = self.naming_set(param)
return wildcard
def naming_set(self, *args, **kwargs) -> str:
"""Set a file name formed by input parameters according the current naming
Args:
*args: a filename if naming is ''.
**kwargs: a dictionnary of parameters that depends on the naming.
Returns:
The formed file name with no path and no extension.
Example:
::
fn = FileNames()
fn.naming("PyROS.img.1")
param = {}
param['ftype'] = "L0A"
param['date'] = "20221109"
param['time'] = "235406123456"
param['version'] = "1"
param['unit'] = "TNC"
param['channel'] = "CH1"
param['id_seq'] = "0123456789"
param['plane'] = "001"
param['frame'] = "001"
fname = fn.naming_set(**param)
The answer should be L0A_20221109_235406123456_TNC_1_CH1_0123456789_001_001.
For naming = "PyROS.img.1", if param['date'] is "*" or "now" then the date and time will be the current UTC time.
If a key is lacking in the dictionary, a wildcard is replaced. Useful to get a glob.
"""
see_rules = self._see_naming_rules
# --- wilcards
wildcard = self.naming_wildcard()
# ---
na = len(args)
nk = len(kwargs)
if self.fcontext_value('naming') == self.NAMING_NONE:
if na > 0:
fname = args[0]
if self.fcontext_value('naming') == self.NAMING_PYROS_IMG1 or self.fcontext_value('naming') == self.NAMING_PYROS_FIL1:
if na > 0:
# case the dict is not **kwargs but *args
if isinstance(args[0], dict):
kwargs = args[0]
nk = len(kwargs)
else:
texte = "Dictionary of input parameters not found " + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
elif nk == 0:
return wildcard
# -- read kwargs
wildcards = wildcard.split("_")
param = {}
param['ftype'] = wildcards[0]
param['date'] = wildcards[1]
param['time'] = wildcards[2]
param['version'] = wildcards[3]
param['unit'] = wildcards[4]
param['channel'] = wildcards[5]
param['id_seq'] = wildcards[6]
param['plane'] = wildcards[7]
if self.fcontext_value('naming') == self.NAMING_PYROS_IMG1:
param['frame'] = wildcards[8]
else:
param['filter'] = wildcards[8]
if nk > 0:
for key, val in kwargs.items():
if key in param.keys():
param[key] = val
# --- verify all params are set
for key, val in param.items():
if val == "":
texte = f"param {key} must not be empty string" + see_rules
raise FileNamesException(FileNamesException.EMPTY_STRING, texte)
# --- verify ftype
if isinstance(param['ftype'],str):
if param['ftype'] != wildcards[0]:
if param['ftype'] not in self._naming_0_stypes:
texte = f"File type {param['ftype']} not found amongst {self._naming_0_stypes}" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify date
valid = False
if isinstance(param['date'],str):
if param['date'] == wildcards[1]:
valid = True
elif len(param['date']) == 8:
if param['date'].isdigit():
valid = True
elif param['date'] == "*" or param['date'] == "now":
d = datetime.datetime.utcnow().isoformat()
fdate = d[0:4]+d[5:7]+d[8:10]
ftime = d[11:13]+d[14:16]+d[17:19]+d[20:26]
param['date'] = fdate
param['time'] = ftime
valid = True
if valid == False:
texte = f"Date {param['date']} must be a string of 8 digits" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify time
valid = False
if isinstance(param['time'],str):
if param['time'] == wildcards[2]:
valid = True
elif len(param['time']) == 12:
if param['time'].isdigit():
valid = True
if valid == False:
texte = f"Time {param['time']} must be a string of 12 digits" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify version
valid = False
if isinstance(param['version'],str):
if param['version'] == wildcards[3]:
valid = True
elif len(param['version']) == 1:
valid = True
elif isinstance(param['version'],int):
param['version'] = f"{param['version']:01d}"
valid = True
if valid == False:
texte = f"Version {param['version']} must be a string of 1 character" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify unit
valid = False
if isinstance(param['unit'],str):
if param['unit'] == wildcards[4]:
valid = True
elif len(param['unit']) == 3:
valid = True
if valid == False:
texte = f"Unit {param['unit']} must be a string of 3 characters" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify channel
valid = False
if isinstance(param['channel'],str):
if param['channel'] == wildcards[5]:
valid = True
elif len(param['channel']) == 3:
valid = True
if valid == False:
texte = f"Channel {param['channel']} must be a string of 3 characters" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify id_seq
valid = False
if isinstance(param['id_seq'],str):
if param['id_seq'] == wildcards[6]:
valid = True
elif len(param['id_seq']) == 10:
valid = True
elif isinstance(param['id_seq'],int):
param['id_seq'] = f"{param['id_seq']:010d}"
valid = True
if valid == False:
texte = f"Id_seq {param['id_seq']} must be a string of 10 characters or an integer" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify plane
valid = False
if isinstance(param['plane'],str):
if param['plane'] == wildcards[7]:
valid = True
elif len(param['plane']) == 3:
valid = True
elif isinstance(param['plane'],int):
param['plane'] = f"{param['plane']:03d}"
valid = True
if valid == False:
texte = f"Plane {param['plane']} must be a string of 3 characters or an integer" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify frame
valid = False
if self.fcontext_value('naming') == self.NAMING_PYROS_IMG1:
if isinstance(param['frame'],str):
if param['frame'] == wildcards[8]:
valid = True
elif len(param['frame']) == 3:
valid = True
elif isinstance(param['frame'],int):
param['frame'] = f"{param['frame']:03d}"
valid = True
if valid == False:
texte = f"Frame {param['frame']} must be a string of 3 characters or an integer" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
else:
if isinstance(param['filter'],int):
param['filter'] = str(param['filter'])
if isinstance(param['filter'],str):
if param['filter'] == wildcards[8]:
valid = True
elif len(param['filter']) >= 1:
valid = True
if valid == False:
texte = f"Frame {param['frame']} must be a string of at less 1 character or an integer" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- form final file name
if self.fcontext_value('naming') == self.NAMING_PYROS_IMG1:
fname = param['ftype']+"_"+param['date']+"_"+param['time']+"_"+param['version']+"_"+param['unit']+"_"+param['channel']+"_"+param['id_seq']+"_"+param['plane']+"_"+param['frame']
else:
fname = param['ftype']+"_"+param['date']+"_"+param['time']+"_"+param['version']+"_"+param['unit']+"_"+param['channel']+"_"+param['id_seq']+"_"+param['plane']+"_"+param['filter']
if self.fcontext_value('naming') == self.NAMING_PYROS_EPH1:
if na > 0:
# case the dict is not **kwargs but *args
if isinstance(args[0], dict):
kwargs = args[0]
nk = len(kwargs)
else:
texte = "Dictionary of input parameters not found " + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
elif nk == 0:
return wildcard
# -- read kwargs
wildcards = wildcard.split("_")
param = {}
param['period'] = wildcards[0]
param['date'] = wildcards[1]
param['version'] = wildcards[2]
param['unit'] = wildcards[3]
param['target'] = wildcards[4]
if nk > 0:
for key, val in kwargs.items():
if key in param.keys():
param[key] = val
# --- verify all params are set
for key, val in param.items():
if val == "":
texte = f"param {key} must not be empty string" + see_rules
raise FileNamesException(FileNamesException.EMPTY_STRING, texte)
# --- verify period
valid = False
if isinstance(param['period'],str):
if param['period'] == wildcards[0]:
valid = True
elif len(param['period']) == 4:
valid = True
if valid == False:
texte = f"Period {param['period']} must be a string of 4 digits" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify date
valid = False
if isinstance(param['date'],str):
if param['date'] == wildcards[1]:
valid = True
elif len(param['date']) == 8:
if param['date'].isdigit():
valid = True
elif param['date'] == "*" or param['date'] == "now":
d = datetime.datetime.utcnow().isoformat()
fdate = d[0:4]+d[5:7]+d[8:10]
ftime = d[11:13]+d[14:16]+d[17:19]+d[20:26]
param['date'] = fdate
param['time'] = ftime
valid = True
if valid == False:
texte = f"Date {param['date']} must be a string of 8 digits" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify version
valid = False
if isinstance(param['version'],str):
if param['version'] == wildcards[2]:
valid = True
elif len(param['version']) == 1:
valid = True
elif isinstance(param['version'],int):
param['version'] = f"{param['version']:01d}"
valid = True
if valid == False:
texte = f"Version {param['version']} must be a string of 1 character" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify unit
valid = False
if isinstance(param['unit'],str):
if param['unit'] == wildcards[3]:
valid = True
elif len(param['unit']) == 3:
valid = True
if valid == False:
texte = f"Unit {param['unit']} must be a string of 3 characters" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify target
valid = False
if isinstance(param['target'],str):
if param['target'] == wildcards[4]:
valid = True
if valid == False:
v = kwargs.get('target')
if v is not None:
param['target'] = v
valid = True
if valid == False:
texte = f"Target {param['target']} must be a string" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- form final file name
fname = param['period']+"_"+param['date']+"_"+param['version']+"_"+param['unit']+"_"+param['target']
if self.fcontext_value('naming') == self.NAMING_PYROS_SEQ1:
if na > 0:
# case the dict is not **kwargs but *args
if isinstance(args[0], dict):
kwargs = args[0]
nk = len(kwargs)
else:
texte = "Dictionary of input parameters not found " + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
elif nk == 0:
return wildcard
# -- read kwargs
wildcards = wildcard.split("_")
param = {}
param['period'] = wildcards[0]
param['date'] = wildcards[1]
param['version'] = wildcards[2]
param['unit'] = wildcards[3]
param['id_seq'] = wildcards[4]
if nk > 0:
for key, val in kwargs.items():
if key in param.keys():
param[key] = val
# --- verify all params are set
for key, val in param.items():
if val == "":
texte = f"param {key} must not be empty string" + see_rules
raise FileNamesException(FileNamesException.EMPTY_STRING, texte)
# --- verify period
valid = False
if isinstance(param['period'],str):
if param['period'] == wildcards[0]:
valid = True
elif len(param['period']) == 4:
valid = True
if valid == False:
texte = f"Period {param['period']} must be a string of 4 digits" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify date
valid = False
if isinstance(param['date'],str):
if param['date'] == wildcards[1]:
valid = True
elif len(param['date']) == 8:
if param['date'].isdigit():
valid = True
elif param['date'] == "*" or param['date'] == "now":
d = datetime.datetime.utcnow().isoformat()
fdate = d[0:4]+d[5:7]+d[8:10]
ftime = d[11:13]+d[14:16]+d[17:19]+d[20:26]
param['date'] = fdate
param['time'] = ftime
valid = True
if valid == False:
texte = f"Date {param['date']} must be a string of 8 digits" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify version
valid = False
if isinstance(param['version'],str):
if param['version'] == wildcards[2]:
valid = True
elif len(param['version']) == 1:
valid = True
elif isinstance(param['version'],int):
param['version'] = f"{param['version']:01d}"
valid = True
if valid == False:
texte = f"Version {param['version']} must be a string of 1 character" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify unit
valid = False
if isinstance(param['unit'],str):
if param['unit'] == wildcards[3]:
valid = True
elif len(param['unit']) == 3:
valid = True
if valid == False:
texte = f"Unit {param['unit']} must be a string of 3 characters" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify id_seq
valid = False
if isinstance(param['id_seq'],str):
if param['id_seq'] == wildcards[4]:
valid = True
elif len(param['id_seq']) == 10:
valid = True
elif isinstance(param['id_seq'],int):
param['id_seq'] = f"{param['id_seq']:010d}"
valid = True
if valid == False:
texte = f"Id_seq {param['id_seq']} must be a string of 10 characters or an integer" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- form final file name
fname = param['period']+"_"+param['date']+"_"+param['version']+"_"+param['unit']+"_"+param['id_seq']
if self.fcontext_value('naming') == self.NAMING_ROS1:
if na > 0:
# case the dict is not **kwargs but *args
if isinstance(args[0], dict):
kwargs = args[0]
nk = len(kwargs)
else:
texte = "Dictionary of input parameters not found " + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
elif nk == 0:
return wildcard
# -- read kwargs
wildcards = wildcard.split("_")
param = {}
param['ftype'] = wildcards[0]
param['date'] = wildcards[1]
param['time'] = wildcards[2]
param['id_scene'] = "????????????"
param['unit'] = "??"
if nk > 0:
for key, val in kwargs.items():
if key in param.keys():
param[key] = val
# --- verify all params are set
for key, val in param.items():
if val == "":
texte = f"param {key} must not be empty string" + see_rules
raise FileNamesException(FileNamesException.EMPTY_STRING, texte)
# --- verify ftype
if isinstance(param['ftype'],str):
if param['ftype'] == wildcards[0]:
valid = True
if param['ftype'] not in self._naming_1_stypes:
texte = f"File type {param['ftype']} not found amongst {self._naming_1_stypes}" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify date
valid = False
if isinstance(param['date'],str):
if param['date'] == wildcards[1]:
valid = True
elif len(param['date']) == 8:
if param['date'].isdigit():
valid = True
elif param['date'] == "*" or param['date'] == "now":
d = datetime.datetime.utcnow().isoformat()
fdate = d[0:4]+d[5:7]+d[8:10]
ftime = d[11:13]+d[14:16]+d[17:19]+d[20:26]
param['date'] = fdate
param['time'] = ftime
valid = True
if valid == False:
texte = f"Date {param['date']} must be a string of 8 digits" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify time
valid = False
if isinstance(param['time'],str):
if param['time'] == wildcards[2]:
valid = True
if len(param['time']) == 9:
if param['time'].isdigit():
valid = True
if valid == False:
texte = f"Time {param['time']} must be a string of 9 digits" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify id_scene
valid = False
if isinstance(param['id_scene'],str):
if param['id_scene'] == wildcards[3]:
valid = True
elif len(param['id_scene']) == 12:
valid = True
elif isinstance(param['id_scene'],int):
param['id_scene'] = f"{param['id_scene']:012d}"
valid = True
if valid == False:
texte = f"Version {param['id_scene']} must be a string of 12 character" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify unit
valid = False
if isinstance(param['unit'],str):
if param['id_scene'] == wildcards[4]:
valid = True
elif len(param['unit']) == 2:
valid = True
if valid == False:
texte = f"Unit {param['unit']} must be a string of 2 characters" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- form final file name
fname = param['ftype']+"_"+param['date']+"_"+param['time']+"_"+param['id_scene'][:6]+"_"+param['id_scene'][6:]+param['unit']
if self.fcontext_value('naming') == self.NAMING_T1M1:
if na > 0:
# case the dict is not **kwargs but *args
if isinstance(args[0], dict):
kwargs = args[0]
nk = len(kwargs)
else:
texte = "Dictionary of input parameters not found " + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
elif nk == 0:
return wildcard
# -- read kwargs
wildcards = wildcard.split("_")
param = {}
param['date'] = wildcards[1]
param['time'] = wildcards[2]
param['millis'] = wildcards[3]
param['target'] = wildcards[4]
param['filter'] = wildcards[6]
b = wildcards[7]
kd = b.find(".")
param['binning'] = b[:kd]
iwildcards = wildcard.split(".")
param['index'] = iwildcards[1]
if nk > 0:
for key, val in kwargs.items():
if key in param.keys():
param[key] = val
# --- verify all params are set
for key, val in param.items():
if val == "":
texte = f"param {key} must not be empty string" + see_rules
raise FileNamesException(FileNamesException.EMPTY_STRING, texte)
# --- verify date
valid = False
if isinstance(param['date'],str):
if param['date'] == wildcards[1]:
valid = True
elif len(param['date']) == 8:
if param['date'].isdigit():
valid = True
elif param['date'] == "*" or param['date'] == "now":
d = datetime.datetime.utcnow().isoformat()
fdate = d[0:4]+d[5:7]+d[8:10]
ftime = d[11:13]+d[14:16]+d[17:19]+d[20:26]
param['date'] = fdate
param['time'] = ftime
valid = True
if valid == False:
texte = f"Date {param['date']} must be a string of 8 digits" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify time
valid = False
if isinstance(param['time'],str):
if param['time'] == wildcards[2]:
valid = True
elif len(param['time']) == 6:
if param['time'].isdigit():
valid = True
if valid == False:
texte = f"Time {param['time']} must be a string of 6 digits" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify milliseconds
valid = False
if isinstance(param['millis'],str):
if param['millis'] == wildcards[3]:
valid = True
elif len(param['millis']) == 3:
if param['millis'].isdigit():
valid = True
if valid == False:
texte = f"Millis {param['millis']} must be a string of 3 digits" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify target
valid = False
if isinstance(param['target'],str):
if param['target'] == wildcards[4]:
valid = True
else:
valid = True
if valid == False:
texte = f"Target {param['target']} must be a string" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify filtre
valid = False
if isinstance(param['filter'],str):
if param['filter'] == wildcards[6]:
valid = True
else:
valid = True
if valid == False:
texte = f"Filter {param['filter']} must be a string" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify binning
valid = False
if isinstance(param['binning'],str):
if param['binning'] == wildcards[7]:
valid = True
else:
n = len(param['binning'])
if n==1:
param['binning'] = f"bin{param['binning']}x{param['binning']}"
valid = True
elif isinstance(param['binning'],int):
param['binning'] = f"bin{param['binning']:1d}x{param['binning']:1d}"
valid = True
elif isinstance(param['binning'],list):
if len(param['binning']) > 1:
b1, b2 = param['binning']
param['binning'] = f"bin{b1}x{b2}"
valid = True
if valid == False:
texte = f"Binning {param['binning']} must be a string or an integer" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify index
valid = False
if isinstance(param['index'],str):
print(f"{iwildcards=:}")
if param['index'] == iwildcards[1]:
valid = True
elif param['index'].isdigit():
valid = True
elif isinstance(param['index'],int):
param['index'] = f"{param['index']}"
valid = True
if valid == False:
texte = f"Index {param['index']} must be an integer" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- form final file name
fname = "T1M_"+param['date']+"_"+param['time']+"_"+param['millis']+"_"+param['target']+"_Filtre_"+param['filter']+"_"+param['binning']+"."+param['index']
if self.fcontext_value('naming') == self.NAMING_INDEXED1:
if na > 0:
# case the dict is not **kwargs but *args
if isinstance(args[0], dict):
kwargs = args[0]
nk = len(kwargs)
else:
texte = "Dictionary of input parameters not found " + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
elif nk == 0:
return wildcard
# -- read kwargs
param = {}
param['genename'] = wildcard
param['sep'] = ""
param['indexes'] = ""
param['ndigit'] = 0
param['suffix'] = ""
if nk > 0:
for key, val in kwargs.items():
if key in param.keys():
param[key] = val
# --- verify genename
valid = False
if isinstance(param['genename'],str):
valid = True
if valid == False:
texte = f"Genename {param['genename']} must be a string" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify sep
valid = False
seps = ["", ".", "-", "_"]
if isinstance(param['sep'],str):
if param['sep'] in seps:
valid = True
if valid == False:
texte = f"Separator {param['sep']} must be a string amongst {seps}" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- verify indexes
valid = False
index_exists = False
if isinstance(param['indexes'],list):
if len(param['indexes']) == 1:
# case ['']
if param['indexes'][0] == "":
valid = True
else:
# case ['1', '2', ...]
valid = True
index_exists = True
for index in param['indexes']:
if isinstance(index,str):
if not index.isdigit():
valid = False
index_exists = False
break
else:
valid = False
index_exists = False
break
if isinstance(param['indexes'],str):
# case '' or '*'
if param['indexes'] == "":
valid = True
if param['indexes'].isdigit() or param['indexes'] == "*":
valid = True
index_exists = True
if len(param['indexes']) > 0:
if param['indexes'][0] == "?":
valid = True
index_exists = True
if valid == False:
texte = f"Indexes {param['indexes']} must be a string or a list of strings" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- Update the default values of wildcards
if index_exists == False and len(param['sep']) > 0:
if param['ndigit'] > 0:
param['indexes'] = "?"*param['ndigit']
else:
param['indexes'] = "*"
# --- verify suffix
valid = False
if isinstance(param['suffix'],str):
valid = True
if valid == False:
texte = f"Suffix {param['suffix']} must be a string" + see_rules
raise FileNamesException(FileNamesException.BAD_PARAM, texte)
# --- form final file name
gname = param['genename']
if param['sep'] != "":
gname += param['sep']
if index_exists:
if isinstance(param['indexes'],list):
fname = []
for index in param['indexes']:
fname.append( gname + index + param['suffix'])
else:
fname = gname + param['indexes'] + param['suffix']
else:
fname = gname + param['suffix']
# --- update fname
self.fname = fname
return fname
def naming_date(self, date:Date) -> str:
"""Compute dates in various string formats.
It is a tool that returns a dictionary allowing to form names.
Args:
date: Date to transform.
Returns:
The formed file name with no path and no extension.
Example:
::
fn = FileNames()
fn.naming_date("2023-01-03T12:43:27.876983")
The result should be {'iso': '2023-01-03T12:43:27.876983', 'iso\_': '2023_01_03_12_43_27_876983', 'yyyy': '2023', 'mm': '43', 'dd': '03', 'hh': '12', 'ss': '27', 'yyyymmdd': '20230103', 'hhmmss': '124327', 'hhmmssssssss': '124327876983'}
"""
date = Date(date);
digits = date.digits(6)
d = {}
d['iso'] = date.iso(6, 'T')
d['iso_'] = d['iso'].replace("-","_")
d['iso_'] = d['iso_'].replace(":","_")
d['iso_'] = d['iso_'].replace(".","_")
d['iso_'] = d['iso_'].replace("T","_")
d['yyyy'] = digits[:4]
d['mm'] = digits[4:6]
d['dd'] = digits[6:8]
d['hh'] = digits[8:10]
d['mm'] = digits[10:12]
d['ss'] = digits[12:14]
d['yyyymmdd'] = digits[:8]
d['night'] = self.date2night(date)
d['hhmmss'] = digits[8:14]
d['hhmmssssssss'] = d['hhmmss'] + digits[15:21]
d['millis'] = digits[15:18]
return d
# =============================================
# Managing pathing
# =============================================
def pathings(self):
"""List of file pathings
Path names can be formed using given rules.
This method returns a list of all possible naming rules.
"""
return self._pathing_list
def pathing(self, *args, **kwargs):
"""Get the current naming of paths or set a new one
Args:
*args: a string with a new naming of paths. See the list using namings().
Returns:
The new selected naming.
Example: To get the current naming
::
fn = FileNames()
pathing = fn.pathing()
Example: To select a new naming
::
fn = FileNames()
fn.pathing("YYYY/MM/DD")
"""
if len(args) >= 1:
new_pathing = args[0]
new_pathingu = new_pathing.upper()
n = len(self._pathing_list)
found = False
for k in range(n):
pathing = self._pathing_list[k]
if pathing.upper() == new_pathingu:
self.fcontext_value('pathing', k)
found = True
if found == False:
texte = f"{new_pathing} not found amongst {self._pathing_list}"
raise FileNamesException(FileNamesException.NO_PATHING_FOUND, texte)
return self._pathing_list[self.fcontext_value('pathing')]
def __pathing_rules_yyyymmdd(self, section):
name = self._pathing_list[self.fcontext_value('pathing')]
texte = ""
if section == self._PATHING_RULES_SECTION_INTRO:
texte +=f"{name} is a path name format.\n"
elif section == self._PATHING_RULES_SECTION_FORMAT:
texte += " 1\n"
texte += "0123456789 \n"
texte += "YYYYMMDD\n"
texte += "\n"
texte += "YYYY = 'yyyy' = Year. e.g. 2022\n"
texte += "MM = 'mm' = Month. e.g. 11\n"
texte += "DD = 'dd' = Day. e.g. 09\n"
elif section == self._PATHING_RULES_SECTION_REMARKS:
texte += "Example: 20221109\n"
texte += "YYYY, MM, DD are digits (int)"
return texte
def __pathing_rules_yyyy_yyyymmdd(self, section):
name = self._pathing_list[self.fcontext_value('pathing')]
texte = ""
if section == self._PATHING_RULES_SECTION_INTRO:
texte +=f"{name} is a path name format.\n"
elif section == self._PATHING_RULES_SECTION_FORMAT:
texte += " 1\n"
texte += "0123456789 12\n"
texte += "YYYY/YYYYMMDD\n"
texte += "\n"
texte += "YYYY = 'yyyy' = Year. e.g. 2022\n"
texte += "YYYY = 'yyyy' = Year. e.g. 2022\n"
texte += "MM = 'mm' = Month. e.g. 11\n"
texte += "DD = 'dd' = Day. e.g. 09\n"
elif section == self._PATHING_RULES_SECTION_REMARKS:
texte += "Example: 2022/20221109\n"
texte += "YYYY, MM, DD are digits (int)\n"
texte += "YYYY is repeated as a suffix directory."
return texte
def __pathing_rules_yyyy_mm_dd(self, section):
name = self._pathing_list[self.fcontext_value('pathing')]
texte = ""
if section == self._PATHING_RULES_SECTION_INTRO:
texte +=f"{name} is a path name format.\n"
elif section == self._PATHING_RULES_SECTION_FORMAT:
texte += " 1\n"
texte += "0123456789 12\n"
texte += "YYYY/MM/DD\n"
texte += "\n"
texte += "YYYY = 'yyyy' = Year. e.g. 2022\n"
texte += "MM = 'mm' = Month. e.g. 11\n"
texte += "DD = 'dd' = Day. e.g. 09\n"
elif section == self._PATHING_RULES_SECTION_REMARKS:
texte += "Example: 2022/11/09\n"
texte += "YYYY, MM, DD are digits (int)."
return texte
def __pathing_rules_pppp_yyyymmdd(self, section):
name = self._pathing_list[self.fcontext_value('pathing')]
texte = ""
if section == self._PATHING_RULES_SECTION_INTRO:
texte +=f"{name} is a path name format.\n"
elif section == self._PATHING_RULES_SECTION_FORMAT:
texte += " 1\n"
texte += "0123456789 12\n"
texte += "PPPP/YYYYMMDD\n"
texte += "\n"
texte += "PPPP = 'pppp' = Period e.g. P001\n"
texte += "YYYY = 'yyyy' = Year. e.g. 2022\n"
texte += "MM = 'mm' = Month. e.g. 11\n"
texte += "DD = 'dd' = Day. e.g. 09\n"
elif section == self._PATHING_RULES_SECTION_REMARKS:
texte += "Example: P001/20221109\n"
texte += "YYYY, MM, DD are digits (int)"
return texte
def pathing_rules(self) -> str:
"""Get the current naming rules for paths
Returns:
A text file giving the rule description.
Example:
::
fn = FileNames()
print(fn.pathing_rules())
"""
date_iso = datetime.datetime.utcnow().isoformat()
name = self._pathing_list[self.fcontext_value('pathing')]
texte = ""
if self.fcontext_value('pathing') == self.PATHING_NONE:
texte += "Pathname naming rules\n"
else:
texte +=f"Pathname naming rules for {name}\n"
date_iso = datetime.datetime.utcnow().isoformat()
texte += "Updated on 2022-12-01T16:25:00\n"
texte +=f"Written on {date_iso}\n"
# ---
h1 = "1. Introduction"
texte +=f"\n{h1}\n" + "="*len(h1) + "\n\n"
if self.fcontext_value('pathing') == self.PATHING_NONE:
texte += "No specific rule. Path names can be formed as you want.\n"
return texte
elif self.fcontext_value('pathing') == self.PATHING_YYYYMMDD:
texte += self.__pathing_rules_yyyymmdd(self._PATHING_RULES_SECTION_INTRO)
elif self.fcontext_value('pathing') == self.PATHING_YYYY_YYYYMMDD:
texte += self.__pathing_rules_yyyy_yyyymmdd(self._PATHING_RULES_SECTION_INTRO)
elif self.fcontext_value('pathing') == self.PATHING_YYYY_MM_DD:
texte += self.__pathing_rules_yyyy_mm_dd(self._PATHING_RULES_SECTION_INTRO)
elif self.fcontext_value('pathing') == self.PATHING_PPPP_YYYYMMDD:
texte += self.__pathing_rules_pppp_yyyymmdd(self._PATHING_RULES_SECTION_INTRO)
# ---
h1 = "2. Format of the path names"
texte +=f"\n{h1}\n" + "="*len(h1) + "\n\n"
if self.fcontext_value('pathing') == self.PATHING_YYYYMMDD:
texte += self.__pathing_rules_yyyymmdd(self._PATHING_RULES_SECTION_FORMAT)
if self.fcontext_value('pathing') == self.PATHING_YYYY_YYYYMMDD:
texte += self.__pathing_rules_yyyy_yyyymmdd(self._PATHING_RULES_SECTION_FORMAT)
if self.fcontext_value('pathing') == self.PATHING_YYYY_MM_DD:
texte += self.__pathing_rules_yyyy_mm_dd(self._PATHING_RULES_SECTION_FORMAT)
if self.fcontext_value('pathing') == self.PATHING_PPPP_YYYYMMDD:
texte += self.__pathing_rules_pppp_yyyymmdd(self._PATHING_RULES_SECTION_FORMAT)
# ---
h1 = "3. Remarks"
texte +=f"\n{h1}\n" + "="*len(h1) + "\n\n"
if self.fcontext_value('pathing') == self.PATHING_YYYYMMDD:
texte += self.__pathing_rules_yyyymmdd(self._PATHING_RULES_SECTION_REMARKS)
if self.fcontext_value('pathing') == self.PATHING_YYYY_YYYYMMDD:
texte += self.__pathing_rules_yyyy_yyyymmdd(self._PATHING_RULES_SECTION_REMARKS)
if self.fcontext_value('pathing') == self.PATHING_YYYY_MM_DD:
texte += self.__pathing_rules_yyyy_mm_dd(self._PATHING_RULES_SECTION_REMARKS)
if self.fcontext_value('pathing') == self.PATHING_PPPP_YYYYMMDD:
texte += self.__pathing_rules_pppp_yyyymmdd(self._PATHING_RULES_SECTION_REMARKS)
# ---
texte += "\n\n=== End of the Document ==="
return texte
def pathing_get(self, pname:str) -> dict:
"""Get parameters that form the path name according the current pathing
Args:
pname: a pathname with no file name.
Returns:
The parameter dictionary which differ for each pathing.
Example:
::
fn = FileNames()
fn.pathing("YYYY/MM/DD")
params = fn.pathing_get("/tmp/2023/01/04")
params = fn.pathing_get("/tmp/20230104")
The answer (params dict) should be {'date': '2022-11-09T00:00:00', 'night': False}
"""
param = {}
see_rules = self._see_pathing_rules
dname = self.dict(pname)
#print(f"> {dname=:}")
pnames = dname['parts']
#print(f"> {pnames=:}")
if self.fcontext_value('pathing') == self.PATHING_NONE:
param['fname'] = fname
elif self.fcontext_value('pathing') == self.PATHING_YYYYMMDD or self.fcontext_value('pathing') == self.PATHING_YYYY_YYYYMMDD or self.fcontext_value('pathing') == self.PATHING_PPPP_YYYYMMDD:
np = len(pnames)
if np > 0:
p = pnames[-1]
n = len(p)
nn = 8
if np == 0 or n != nn:
texte =f"Path name must be a string of {nn} characters" + see_rules
raise FileNamesException(FileNamesException.BAD_PATHNAME_RULE, texte)
yyyy = p[:4]
mm = p[4:6]
dd = p[6:8]
if self.fcontext_value('pathing') == self.PATHING_YYYY_YYYYMMDD:
if np > 1:
p = pnames[-2]
n = len(p)
nn = 4
if np <= 1 or n != nn:
texte =f"Path name must be two strings of {nn} and 8 characters" + see_rules
raise FileNamesException(FileNamesException.BAD_PATHNAME_RULE, texte)
if self.fcontext_value('pathing') == self.PATHING_PPPP_YYYYMMDD:
param['period'] = p
elif self.fcontext_value('pathing') == self.PATHING_YYYY_MM_DD:
np = len(pnames)
valid = True
if np > 2:
k = -3
yyyy = pnames[k]
if len(yyyy) != 4:
k = -4
yyyy = pnames[k]
if len(yyyy) != 4:
valid = False
k += 1
mm = pnames[k]
if len(mm) != 2:
valid = False
k += 1
dd = pnames[k]
if len(dd) != 2:
valid = False
if valid == False:
texte = f"Path name {yyyy} {mm} {dd} must be three strings of 4, 2 and 2 characters" + see_rules
raise FileNamesException(FileNamesException.BAD_PATHNAME_RULE, texte)
else:
texte = f"Path {np} name {pnames} must have undercores" + see_rules
raise FileNamesException(FileNamesException.BAD_PATHNAME_RULE, texte)
if self.fcontext_value('pathing') == self.PATHING_YYYYMMDD or self.fcontext_value('pathing') == self.PATHING_YYYY_YYYYMMDD or self.fcontext_value('pathing') == self.PATHING_YYYY_MM_DD or self.fcontext_value('pathing') == self.PATHING_PPPP_YYYYMMDD:
valid = True
if yyyy.isdigit() == False:
valid = False
if mm.isdigit() == False:
valid = False
if dd.isdigit() == False:
valid = False
if valid == False:
texte = "Path name must be strings of YYYY, MM, DD characters of digits" + see_rules
raise FileNamesException(FileNamesException.BAD_PATHNAME_RULE, texte)
param['date'] = yyyy+"-"+mm+"-"+dd+"T00:00:00"
param['night'] = False
#print(f">> {dname:=}")
return param
def pathing_set(self, *args, **kwargs) -> str:
"""Set a path name formed by input parameters according the current pathing
Args:
*args: a pathname if naming is ''.
**kwargs: a dictionnary of parameters that depends on the pathing.
Returns:
The formed path name with no path and no extension.
Example:
::
fn = FileNames()
fn.pathing("YYYY/MM/DD")
fn.longitude = 45.678
param = {}
param['date'] = "2021-10-26T13:45:23"
param['night'] = True
pname = fn.pathing_set(**param)
The answer should be '2021/10/26' (Linux) or '2021\\10\\26' (Windows).
If param['date'] is "*" then the date and time will be the current UTC time.
"""
see_rules = self._see_pathing_rules
if self.fcontext_value('pathing') == self.PATHING_NONE:
pname = args[0]
if self.fcontext_value('pathing') == self.PATHING_YYYYMMDD or self.fcontext_value('pathing') == self.PATHING_YYYY_YYYYMMDD or self.fcontext_value('pathing') == self.PATHING_YYYY_MM_DD or self.fcontext_value('pathing') == self.PATHING_PPPP_YYYYMMDD:
if len(args) > 0:
if isinstance(args[0],dict):
kwargs = args[0]
elif len(kwargs)==0:
return self.pathing_rules()
# -- read kwargs
param = {}
param['date'] = ""
if self.fcontext_value('pathing') == self.PATHING_YYYY_MM_DD:
param['night'] = True
else:
param['night'] = False
if len(kwargs) > 0:
for key, val in kwargs.items():
if key in param.keys():
param[key] = val
# --- verify all params are set
for key, val in param.items():
if val == "":
if key == 'date' and not isinstance(param['night'], bool):
continue
texte = f"param {key} must not be empty string" + see_rules
raise FileNamesException(FileNamesException.EMPTY_STRING, texte)
# --- decode date
if param['night'] == True:
digits = self.get_night(param['date'])
elif param['night'] == False:
date = Date(param['date'])
digits = date.digits(0)
else:
if isinstance(param['night'],str):
suffix = ""
length = len(param['night'])
if length<8:
suffix = "0"*(8-length)
digits = param['night'] + suffix
else:
digits = "0"*8
yyyy = digits[:4]
mm = digits[4:6]
dd = digits[6:8]
pname = ""
if self.fcontext_value('pathing') == self.PATHING_YYYYMMDD:
pname = yyyy+mm+dd
elif self.fcontext_value('pathing') == self.PATHING_YYYY_YYYYMMDD:
pname = os.path.join(yyyy, yyyy+mm+dd)
elif self.fcontext_value('pathing') == self.PATHING_YYYY_MM_DD:
pname = os.path.join(yyyy, mm, dd)
elif self.fcontext_value('pathing') == self.PATHING_PPPP_YYYYMMDD:
pppp = "P000"
if 'period' in kwargs.keys():
if isinstance(kwargs['period'],str):
suffix = ""
length = len(kwargs['period'])
if length<4:
suffix = "X"*(4-length)
pppp = kwargs['period'] + suffix
pname = os.path.join(pppp, yyyy+mm+dd)
# --- update the dict
self.subdir = pname
# --- return the path
return pname
# =============================================
# Managing pathnaming (path + names)
# =============================================
def pathnamings(self):
"""List of pathnamings
Path and file names can be formed using given rules.
This method returns a list of all possible pathnaming rules.
The pathanming should be one amongst the namings (pathnaming and naming shared the same symbols).
"""
return self._naming_list
def pathnaming(self, *args, **kwargs):
"""Get the current pathnaming of files or set a new one
The choice of a pathnaming will set the pathing and the naming.
Args:
*args: args[0] a string with a new pathnaming of files. See the list using pathnamings().
**kwargs: a dictionary of options.
Returns:
The new selected pathnaming.
Example: To get the current pathnaming
::
fn = FileNames()
pathnaming = fn.pathnaming()
Example: To select a new pathnaming
::
fn = FileNames()
fn.pathnaming("PyROS.img.1")
"""
if len(args) >= 1:
new_naming = args[0]
new_namingu = new_naming.upper()
n = len(self._naming_list)
found = False
for k in range(n):
naming = self._naming_list[k]
if naming.upper() == new_namingu:
self.fcontext_value('pathnaming', k)
found = True
if found == False:
texte = f"{new_naming} not found amongst {self._naming_list}"
raise FileNamesException(FileNamesException.NO_NAMING_FOUND, texte)
self.fcontext_value('naming', self.fcontext_value('pathnaming'))
if self.fcontext_value('pathnaming') == self.NAMING_PYROS_IMG1:
self.fcontext_value('pathing', self.PATHING_YYYYMMDD)
elif self.fcontext_value('pathnaming') == self.NAMING_PYROS_EPH1:
self.fcontext_value('pathing', self.PATHING_PPPP_YYYYMMDD)
elif self.fcontext_value('pathnaming') == self.NAMING_PYROS_SEQ1:
self.fcontext_value('pathing', self.PATHING_PPPP_YYYYMMDD)
elif self.fcontext_value('pathnaming') == self.NAMING_PYROS_FIL1:
self.fcontext_value('pathing', self.PATHING_YYYYMMDD)
return self._naming_list[self.fcontext_value('pathnaming')]
def pathnaming_set(self, pkw:dict, nkw:dict, extension="") -> str:
"""Set a full file name formed by input parameters according the current pathnaming
Args:
*args: a pathname if naming is ''.
**kwargs: a dictionnary of parameters that depends on the pathing.
Returns:
The full file name with no extension.
Example:
::
fn = FileNames()
fn.pathnaming("PyROS.img.1")
fn.longitude = 45.678
date = "2021-10-26T13:45:23"
fnd = fn.naming_date(date)
pparam = {}
pparam['date'] = fnd['iso']
pparam['night'] = True
fparam = {}
fparam['ftype'] = "L0"
fparam['date'] = fnd['yyyymmdd']
fparam['time'] = fnd['hhmmssssssss']
fparam['version'] = "1"
fparam['unit'] = "TNC"
fparam['channel'] = "CH1"
fparam['id_seq'] = 123456789
fparam['plane'] = 1
fparam['frame'] = 1
fullname = fn.pathnaming_set(pparam, fparam, ".fits")
The answer should be '/tmp\\2021\\10\\26\\L0_20211026_134522999983_1_TNC_CH1_0123456789_001_001.fits'
"""
path = ""
fname = ""
if self.fcontext_value('pathnaming') == self.NAMING_PYROS_IMG1:
path = self.pathing_set(**pkw)
fname = self.naming_set(**nkw)
if self.fcontext_value('pathnaming') == self.NAMING_PYROS_EPH1:
path = self.pathing_set(**pkw)
fname = self.naming_set(**nkw)
if self.fcontext_value('pathnaming') == self.NAMING_PYROS_SEQ1:
path = self.pathing_set(**pkw)
fname = self.naming_set(**nkw)
if self.fcontext_value('pathnaming') == self.NAMING_PYROS_FIL1:
path = self.pathing_set(**pkw)
fname = self.naming_set(**nkw)
fullname = os.path.join(path, fname) + extension
return fullname
def pathnaming_get(self, filename:str) -> tuple:
"""Returns the dictionaries of naming and pathing
Args:
filename: A file name with or without path or extension.
Returns:
(naming_dict, pathing_dict)
"""
pkw = {}
nkw = {}
if self.fcontext_value('pathnaming') == self.NAMING_PYROS_IMG1:
pkw = self.pathing_get(filename)
nkw = self.naming_get(filename)
if self.fcontext_value('pathnaming') == self.NAMING_PYROS_EPH1:
pkw = self.pathing_get(filename)
nkw = self.naming_get(filename)
if self.fcontext_value('pathnaming') == self.NAMING_PYROS_SEQ1:
pkw = self.pathing_get(filename)
nkw = self.naming_get(filename)
if self.fcontext_value('pathnaming') == self.NAMING_PYROS_FIL1:
pkw = self.pathing_get(filename)
nkw = self.naming_get(filename)
return pkw, nkw
def subdir_from_filename(self, filename:str, outfname:bool = False)->str:
"""Get the subdir from a full file name according to a file context.
Get also the fname if outfname=True.
Args:
filename: A file name with or without path or extension.
outfname: Returns also the fname if True (default value is False).
Returns:
subdir or (subdir, fname) according the outfname value.
"""
if isinstance(filename,list):
texte = f"Filename {filename} is a list instead to be a string"
raise FileNamesException(FileNamesException.LIST_INSTEAD_A_STRING, texte)
subdir = os.path.dirname(filename)
fname = filename
nkw = self.naming_get(filename)
if outfname:
if self.fcontext_value('naming') == self.NAMING_NONE:
fname = nkw['fname']
else:
fname = self.naming_set(nkw)
if self.fcontext_value('pathnaming') == self.NAMING_PYROS_IMG1 or self.fcontext_value('pathnaming') == self.NAMING_PYROS_FIL1:
d = nkw['date']
t = nkw['time']
date = d[0:4]+"-"+d[4:6]+"-"+d[6:8]+"T"+t[0:2]+":"+t[2:4]+":"+t[4:6]
fnd = self.naming_date(date)
pparam = {}
pparam['date'] = fnd['iso']
pparam['night'] = True
fullname = self.pathnaming_set(pparam, nkw)
#print(f"fullname={fullname}")
subdir = os.path.dirname(fullname)
if self.fcontext_value('pathnaming') == self.NAMING_PYROS_SEQ1 or self.fcontext_value('pathnaming') == self.NAMING_PYROS_EPH1:
pparam = {}
pparam['period'] = nkw['period']
pparam['night'] = nkw['date']
fullname = self.pathnaming_set(pparam, nkw)
#print(f"fullname={fullname}")
subdir = os.path.dirname(fullname)
if outfname:
return subdir, fname
return subdir
def update_subdir_fname_from_filename(self, filename:str, update:bool = True)->tuple:
"""Get the subdir and the fname from a full file name according to a file context.
Args:
filename: A file name with or without path or extension.
update: Update the keys 'subdir' and 'fname' if True (default value).
Returns:
subdir, fname
"""
subdir, fname = self.subdir_from_filename(filename, True)
if update:
if self.fcontext_value('pathing') != self.PATHING_NONE:
self.fcontext_value('subdir', subdir)
self.fcontext_value('fname', fname)
return subdir, fname
# =============================================
# Managing nightname
# =============================================
def date2night(self, date: str="now", sampling: int=0)->str:
"""Get the current night identifier as a string of 8 characters: YYYYMMDD.
The night identifier changes at local noon. So it uses the longitude defined in longitude attribute.
Args:
date: Input date to compute the night identifier. Defaut value is "now".
sampling: Compute the index corresponding to the given sampling (0 by default meaning no index calculation)
Returns:
The night identifier string YYYYMMDD.
The index if sampling > 0
Simple case where we compute the night of the current time:
::
fn = FileNames()
fn.longitude = 2.3456
night = fn.get_night("now")
The variable night contains the current night in the format YYYYMMDD.
A more complex case. We ask for the index corresponding to the time inside a given night:
fn = FileNames()
fn.longitude = 2.3456
night, index = fn.get_night("now", 65536)
"""
# night is the truncated part of the date of the previous noon
jd_frac_noon = - self._longiau_deg / 360.0
#print(f"jd_frac_noon={jd_frac_noon}")
# --- UTC JD
jd = Date(date).jd()
if False:
if date.lower()=="now":
date_iso = datetime.datetime.utcnow().isoformat()
#date_iso = '2021-08-16 10:57:00'
#print(f"date_iso={date_iso}")
t = astropy.time.Time(date_iso)
jd = t.jd
else:
jd = Date(date).jd()
#print(f"jd={jd}")
# --- Noon JD
jd_noon = jd - jd_frac_noon
#print(f"jd_noon={jd_noon}")
jd0 = math.floor(jd_noon)
# --- Convert into digits
t = astropy.time.Time(jd0, format='jd')
t_iso = t.iso
night = t_iso[0:4] + t_iso[5:7] + t_iso[8:10]
if sampling == 0:
return night
# --- index
#index = round((jd-jd_noon)*sampling)
index = round((jd-jd0)*sampling)
return night, index
def night2date(self, night: str="now")->str:
"""Get the current julian day limits from a night identifier as a string of 8 characters: YYYYMMDD.
The night identifier changes at local noon. So it uses the longitude defined in longitude attribute.
Args:
date: The night identifier string YYYYMMDD or a date (default is "now").
Returns:
A tupple of two julian days.
::
fn = FileNames()
fn.longitude = 2.3456
jd1, jd2 = fn.night2date("20230320")
The variable night contains the current night in the format YYYYMMDD.
"""
# night is the truncated part of the date of the previous noon
jd_frac_noon = - self._longiau_deg / 360.0
if len(night)!=8:
night = self.date2night(night)
# --- date is a night
date = f"{night[0:4]}-{night[4:6]}-{night[6:8]}T00:00:00"
d = Date(date)
jd = d.jd()
#print(f"jd={jd}")
# --- Noon JD
jd_noon = jd + 0.5 + jd_frac_noon
return (jd_noon, jd_noon+1)
def get_night(self, date: str="now")->str:
"""Obsolete method replaced by date2night
"""
return self.date2night(date)
# =============================================
# Managing context of paths
# =============================================
def _context_get(self):
return self._context_current_key
def _context_set(self, context_key: str):
self._context_verify(context_key)
self._context_current_key = context_key
def _context_del(self):
self.fcontext_delete(self._context_current_key)
def _context_verify(self, context_key: str):
if context_key not in self._context.keys():
texte = f"{context_key} not found amongst {self._context.keys()}"
raise FileNamesException(FileNamesException.NO_CONTEXT_KEY_FOUND, texte)
def _context_list(self):
return list(self._context.keys())
# - context keys
fcontext = property(_context_get, _context_set, _context_del)
fcontexts = property(_context_list)
# - subkey rootdir
def _rootdir_get(self):
key = 'rootdir'
return self._context[self._context_current_key][key]
def _rootdir_set(self, value:str):
key = 'rootdir'
self._context[self._context_current_key][key] = value
rootdir = property(_rootdir_get, _rootdir_set)
# - subkey fname
def _fname_get(self):
key = 'fname'
return self._context[self._context_current_key][key]
def _fname_set(self, value:str):
key = 'fname'
self._context[self._context_current_key][key] = value
fname = property(_fname_get, _fname_set)
# - subkey extension
def _extension_get(self):
key = 'extension'
return self._context[self._context_current_key][key]
def _extension_set(self, value:str):
key = 'extension'
self._context[self._context_current_key][key] = value
extension = property(_extension_get, _extension_set)
# - subkey subdir
def _subdir_get(self):
key = 'subdir'
return self._context[self._context_current_key][key]
def _subdir_set(self, value:str):
key = 'subdir'
self._context[self._context_current_key][key] = value
subdir = property(_subdir_get, _subdir_set)
# - subkey fdescription
def _fdescription_get(self):
key = 'description'
return self._context[self._context_current_key][key]
def _fdescription_set(self, value:str):
key = 'description'
self._context[self._context_current_key][key] = value
fdescription = property(_fdescription_get, _fdescription_set)
# - subkey managment
def fcontext_value(self, key:str="", val=None):
if key == "":
return self._context[self._context_current_key]
if val == None:
return self._context[self._context_current_key][key]
self._context[self._context_current_key][key] = val
# - context key managment
def fcontext_create(self, context_key: str, description: str="No description"):
if context_key not in self._context.keys():
val = {}
val['description'] = description
val['naming'] = self.NAMING_NONE
val['pathing'] = self.PATHING_NONE
val['pathnaming'] = self.NAMING_NONE
val['rootdir'] = self._rootdir0
val['subdir'] = ""
val['fname'] = "noname"
if context_key.find("image") >= 0:
val['extension'] = ".fit"
else:
val['extension'] = ".txt"
self._context[context_key] = val
def fcontext_delete(self, context_key: str):
self._context_verify(context_key)
if context_key != "default":
del self._context[context_key]
self._context_set("default")
else:
raise FileNamesException(FileNamesException.NO_DELETE_CONTEXT_DEFAULT)
def fcontext_delete_all(self):
for context_key in list(self._context.keys()):
if context_key != "default":
del self._context[context_key]
self._context_set("default")
def fcontext_replace(self, fn):
"""Replace all fcontexts of the object by fcontexts from another object.
Args:
fn: Is a FileNames instance.
"""
if id(self) == id(fn):
return
self.fcontext_delete_all()
for context_key in fn.fcontexts:
if context_key != "default":
fn.fcontext = context_key
self.fcontext_create(context_key, fn.fdescription)
self.fcontext = context_key
self.pathnaming(fn.pathnaming())
self.naming(fn.naming())
self.pathing(fn.pathing())
self.rootdir = fn.rootdir
self.subdir = fn.subdir
self.fname = fn.fname
self.extension = fn.extension
self._context_set("default")
def fcontexts_human(self) -> str:
"""Return a human reading description of all file contexts. Each file context is described in one line.
Returns:
Each file context is described in one line.
"""
text = ""
fcname0 = self.fcontext
for fcname in self.fcontexts:
self.fcontext = fcname
text += f"{fcname} : {self.fdescription} {self.rootdir}/[{self.pathing()}]/[{self.naming()}]{self.extension}\n"
self.fcontext = fcname0
return text
# =============================================
# Managing filenames
# =============================================
def _path_get(self):
""" Get the path of images.
If the path does not exists, it is created.
"""
rootdir = self._context[self._context_current_key]['rootdir']
subdir = self._context[self._context_current_key]['subdir']
path = os.path.join(rootdir, subdir)
return path
path = property(_path_get)
def dict(self, fullfilename:str) -> dict:
"""Split the input filename and return a dictionary of the analysis ('dirname', 'fname', 'extension', etc.)
Ther analysis is based on the pathlib library.
Ref: https://docs.python.org/3/library/pathlib.html
Args:
fullfilename: A file name with or without path or extension
Returns:
Dictionary of file name informations
"""
p = pathlib.Path(fullfilename)
try:
p = p.resolve() # eliminate '..' if exist
except:
# p.resolve does not work with '*' characters
pass
absolute = p.absolute()
drive = absolute.drive
cwd = p.cwd()
dirname = str(p.parent)
if '*' in dirname or '?' in dirname:
wildcard_dirname = True
else:
wildcard_dirname = False
basename = p.name # with suffixes
naming = self.naming_ident(basename)
suffixes = p.suffixes
extension = "" # all the suffixes
for suffixe in suffixes:
extension += suffixe
k = basename.find(extension)
if k>0:
name = basename[:k] # supress extension
else:
name = basename # has no extension
if '*' in name or '?' in name:
wildcard_fname = True
else:
wildcard_fname = False
parts = p.parts
dico = {}
# --- Initial input
dico['input'] = str(p)
dico['absolute'] = str(absolute)
# --- Directory
dico['dirname'] = dirname
dico['wildcard_dirname'] = wildcard_dirname
dico['parts'] = parts # dirname as a list
dico['cwd'] = str(cwd) # current working dir (not necessarily dirname)
dico['drive'] = drive
# --- File name
dico['fname'] = name # file name with no dirname and no extension
dico['wildcard_fname'] = wildcard_fname # bool if fname is a wildcard
dico['naming'] = naming
# --- Extension
dico['extension'] = extension
dico['suffixes'] = suffixes # list
# --
return dico
def join(self, filename:str = "") -> str:
"""Join the four parts of a context to get a full file name.
Args:
filename: A file name from which the fname will be extracted and subdir calculated. Initial path and extensions are lost. If filename is "" the current contents of the context is used to generate the output full file name.
Returns:
The full file name in a string (rootdir, subdir, fname, extension)
First consider the following file context:
::
fn = FileNames()
fn.longitude = 165.85944
fn.fcontext_create("my_context", "Test")
fn.fcontext = "my_context"
fn.rootdir = "/tmp"
fn.extension = ".fit"
Use the method update_subdir_fname_from_filename to update 'subdir' and 'fname' in the context from the filename. Then use join whith no parameter:
::
in_fullname = "/home/myuser/messier63.fits.gz"
fn.update_subdir_fname_from_filename(in_fullname)
out_fullname = fn.join()
out_fullname should be '/tmp/messier63.fit'.
The following example do the same thing but with no use of the method update_subdir_fname_from_filename:
::
in_fullname = "/home/myuser/messier63.fits.gz"
out_fullname = fn.join(in_fullname)
"""
if isinstance(filename, list):
fname_ins = filename
fname_outs = []
for filename in fname_ins:
self.update_subdir_fname_from_filename(filename)
fname_out = os.path.join(self.rootdir, self.subdir, self.fname + self.extension)
fname_outs.append(fname_out)
return fname_outs
elif filename != "":
self.update_subdir_fname_from_filename(filename)
fname_out = os.path.join(self.rootdir, self.subdir, self.fname + self.extension)
return fname_out
def joinabs(self, filename:str = ""):
"""Join the four parts of a context to get a full file name with absolute path.
Args:
filename: A file name from which the fname will be extracted and subdir calculated. Initial path and extensions are lost. If filename is "" the current contents of the context is used to generate the output full file name.
Returns:
The full file name in a string with absolute path (rootdir, subdir, fname, extension)
"""
if isinstance(filename, list):
fname_ins = filename
fname_outs = []
for filename in fname_ins:
fname_out = os.path.abspath(self.join(filename))
fname_outs.append(fname_out)
return fname_outs
return os.path.abspath(self.join(filename))
def glob(self, *args, **kwargs) -> list:
"""Glob from a wildcard. Add -R to be recursive.
Args:
*args:
* '-R': Recursive option
* '-fc': Use the current fcontext option
* (str): A wildcard with a complete path. The name must compatible with the current fcontext if the option "-fc" is present.
*kwargs: Options when calling _join() in case of use of fcontext.
Returns:
A filename list of existing files of the disk verifying the wildcard.
Examples:
fn.glob("/tmp/user/M65*.fit", "-R")
"""
recursif = False
use_fcontext = False
for arg in args:
if isinstance(arg, str):
if arg == "-R":
recursif = True
if arg == "-fc":
use_fcontext = True
else:
wildcard = arg
if use_fcontext:
wildcard = self._join(args, kwargs)
p = pathlib.Path()
if recursif:
res = p.rglob(wildcard)
else:
res = p.glob(wildcard)
res = [str(re) for re in res]
return res
def _join(self, *args, **kwargs) -> str:
""" Build the complete any file name (folder and extension) or wildcard compatible with the current fcontext
Args:
*args:
* '-f': Force to update the fcontext attributes
* (str): A file name or wildcard compatible with the current fcontext
**kwargs:
* Any key of the fcontext to force at a given value
Returns:
A filename or a wildcard with the path and extension according the fcontext.
Examples:
fn._join("M65", "-f", sep="-", indexes="*")
"""
# --- Get parameters from *args
fname_input = None
pdict_input = {}
force = False
for arg in args:
if isinstance(arg, str):
if arg == "-f" or arg == "-force":
force = True
else:
fname_input = arg
pdict_input = self.dict(fname_input)
# --- Default wilcard of the current fcontext
param_wildcard = fn.naming_get(self.naming_wildcard())
#print(f"(100) {param_wildcard=}")
# --- Get parameters from *kwargs compatible with the fcontext param keys
param_inputs = {}
for key, val in kwargs.items():
if key in param_wildcard:
param_inputs[key] = val
# --- Extract param from the fname_input
if fname_input == None:
# no file was provided
param = param_wildcard
else:
# no file was provided
param = self.naming_get(fname_input)
#print(f"(200) {param=}")
# --- Set kwargs in the wilcard of the current fcontext
for key, val in param_inputs.items():
param[key] = param_inputs[key]
# --- Modify fcontext attributes if forced
if force:
#print(f"{pdict_input=}")
if pdict_input['wildcard_dirname'] == False and pdict_input['dirname'] != ".":
self.rootdir = pdict_input['dirname']
self.extension = pdict_input['extension']
# --- Build the filename
fname_input = self.naming_set(param)
#print(f"(300) {fname_input=}")
fullname_input = self.joinabs(fname_input)
#print(f"{fullname_input=}")
return fullname_input
def split_dir_name_extension(self, fullfilename:str) -> Tuple[str, str, str]:
"""Split a full filename into three parts: Path, name, extension
Extension starts with the first dot in the filename without path.
Args:
fullfilename: A file name with or without path or extension
Returns:
(path, name, extension)
"""
dico = self.dict(fullfilename)
return dico['dirname'], dico['fname'], dico['extension']
def fullfilename(self,filename: str = "") -> str:
""" Get the full name according any entry.
Args:
filename: Input file name with or without path or extension.
Returns:
The complete name of the file.
::
fn = FileNames()
fullname = fn.fullfilename("m57")
The result could be '/srv/develop/guitastro/test/data/m57.fit'
If you want to change the default path use the method *path*.
To change the default file extension use the method *extension*.
"""
if filename == "":
dirname = self.path
basename = self.fname
file_extension = self.extension
parts = []
else:
dico = self.dict(filename)
dirname, basename, file_extension, parts = dico['dirname'], dico['fname'], dico['extension'], dico['parts']
if dirname == "" or len(parts)==1:
# --- add the current image path
fitsname = os.path.join(self.rootdir, self.subdir, basename)
else:
fitsname = os.path.join(dirname, basename)
# --- add the extension
if file_extension == "":
extension = self.extension
else:
extension = file_extension
fitsname += extension
# --- verify naming
if self.naming != "":
naming = self.naming_ident(fitsname)
if naming != self.naming():
msg = f"File name is {basename}. The file naming {naming} is not {self.naming()}. Print method naming_rules() to display rules of {self.naming()}"
raise FileNamesException(FileNamesException.BAD_NAMING, msg)
# --- update
self.fname = basename
self.extension = extension
return fitsname
def basename(self, fitsname:str)->str:
""" Get the base name according any entry.
Args:
fitsname: Input file name with or without path or extension.
Returns:
The base name of the file (with its extension).
::
fn = FileNames()
fullname = fn.basename("m57")
The result could be 'm57.fit'
To change the default file extension use the method *extension*.
"""
fitsname = self.fullfilename(fitsname)
# --- extract the basename
basename = os.path.basename(fitsname)
return basename
def itername(self, fitsname:str, **kwargs):
"""Get an iterator according a series of files.
The list of file names is generated internally by the method genename().
Args:
fitsname: Input file name of a series with or without path or extension.
**kwargs: a dictionnary of optional parameters:
* 'first': Lower index to keep indexes.
* 'last': Upper index to keep indexes.
* 'indexes': List of indexes to keep (integers).
Returns:
The iterator of the series of files.
For example, you have 3 files m63-1.fit, m63-2.fit and m63-3.fit.
You have to put one of the three file names as input of the method itername:
::
fn = FileNames()
for fitsname in fn.itername("m63-1"):
print(f"fitsname={fitsname}")
"""
dico = self.genename(fitsname)
dirname = dico['dirname']
genename = dico['genename']
sep = dico['sep']
indexes = dico['indexes']
suffix = dico['suffix']
file_extension = dico['file_extension']
for index in indexes:
fitsname = os.path.join(dirname, genename + sep + index + suffix + file_extension)
yield fitsname
def enumname(self, fitsname: str, **kwargs):
"""Get an enumerator according a series of files.
The list of file names is generated internally by the method genename().
Args:
fitsname: Input file name of a series with or without path or extension.
**kwargs: a dictionnary of optional parameters:
* 'first': Lower index to keep indexes.
* 'last': Upper index to keep indexes.
* 'indexes': List of indexes to keep (integers).
Returns:
The iterator of the series of files.
For example, you have 3 files m63-1.fit, m63-2.fit and m63-3.fit.
You have to put one of the three file names as input of the method enumname:
::
fn = FileNames()
for k, fitsname in enumarate(fn.enumname("m63-1")):
print(f"fitsname {k} = {fitsname}")
"""
dico = self.genename(fitsname, **kwargs)
dirname = dico['dirname']
genename = dico['genename']
sep = dico['sep']
indexes = dico['indexes']
suffix = dico['suffix']
file_extension = dico['file_extension']
fitsnames = []
for index in indexes:
fitsname = os.path.join(dirname, genename + sep + index + + suffix + file_extension)
fitsnames.append(fitsname)
return fitsnames
def genenames(self, wildcard: str)-> dict:
"""Generate a dictionnary describing a series of files associated to a wildcard file name.
Generated file names are existing in the disk.
This method is similar as genename() but the input file is a wildcard and the output dictionary is different.
Args:
wildcard: Any wildcard with extension. The path is that defined in the method path() is not in the wildcard.
Returns:
A dictionary containing the following keys:
* 'dirname': Directory name (path only)
* 'shortname': Short name (no path, extension)
* 'filename': Full name of file (no path, shortname, no extension)
* 'ext': Extension of the file
For example, you have 3 files m63-1.fit, m63-2.fit and m63-3.fit.
You have to put one of the three file names as input of the method genename:
::
fn = FileNames()
result = fn.genenames("m63-*.fits")
"""
# fn.genenames("IM_*.fits.gz")
wildcard = self.fullfilename(wildcard)
#print(f"wildcard = {wildcard}")
ftmps = glob.glob(wildcard)
allshortnames = []
for ftmp in ftmps:
basename = os.path.basename(ftmp)
dirname = os.path.dirname(ftmp)
allshortnames.append(basename)
# ---
allshorts = []
for shortname in allshortnames:
dico = {}
#nchar = len(shortname)
dname, filename , file_extension = self.split_dir_name_extension(shortname)
dico['dirname'] = dirname
dico['shortname'] = shortname
dico['filename'] = filename
dico['ext'] = file_extension
#for shortname_ref in allshortnames:
# nchar_ref = len(shortname_ref)
allshorts.append(dico)
return allshorts
def genename(self,fitsname: str, **kwargs)-> dict:
"""Generate a dictionnary describing a series of files associated to a file name.
The algorithm search for files having indexes with a name similar than fitsname.
Generated file names are existing in the disk.
This method adds the possibility to restrict indexes using options 'first', 'last' and 'indexes' (using optional parameters).
Args:
fitsname: Any file name with or without path or extension.
**kwargs: a dictionnary of optional parameters:
* 'first': Lower index to keep indexes.
* 'last': Upper index to keep indexes.
* 'indexes': List of indexes to keep (integers).
Returns:
A dictionary containing the following keys:
* 'dirname': Path name
* 'genename': Generic name of files
* 'sep': Separator between generic name and indexes
* 'indexes': List of indexes sorted increasing
* 'file_extension': File extension
* 'ndigit': Number of digits in case of indexes with leading zeros
For example, you have 3 files m63-1.fit, m63-2.fit and m63-3.fit.
You have to put one of the three file names as input of the method genename:
::
fn = FileNames()
result = fn.genename("m63-1")
The index "1" is not necessary. So the command fn.genename("m63-") gives the same result.
For example, you have 6 files m63-1.fit, m63-2.fit ... m63-6.fit.
You have to put one of the three file names as input of the method genename
and if you want to keep only files after the index 4:
::
fn = FileNames()
result = fn.genename("m63-1", first=4)
Indexes of 'first' and 'last' options can be negative (to start from end to begin).
"""
print(f"STEP 1000 {fitsname=}")
fitsname = self.fullfilename(fitsname)
print(f"STEP 1001 {fitsname=}")
# --- extract the basename
filename, file_extension = os.path.splitext(fitsname)
basename = os.path.basename(filename)
#print(f"0 basename={basename}")
print(f"STEP 1010 {basename=}")
suffix = ""
# --- search for the first index where there is no numeric char
n = len(basename)
indice = ""
sep = ""
k = 0
for k in range(n-1,0,-1):
car = basename[k]
print(f"car={car} k={k}")
if car.isnumeric() == False:
sep = basename[k]
break
indice += car
print(f"1 k={k} indice={indice}")
print(f"1 basename = {basename}")
if indice == "":
genename = basename
sep = ""
else:
# --- valid the sepration between genename and indice
if sep=="-" or sep=="_":
genename = basename[0:k]
else:
genename = basename[0:k]
sep = ""
# --- count the number of files corresponding to the genename
dirname = os.path.dirname(fitsname)
wildcard = os.path.join(dirname, genename + sep + "*" + file_extension)
#print(f"wildcard = {wildcard}")
ftmps = glob.glob(wildcard)
#print(f"ftmps = {ftmps}")
if len(ftmps) == 1:
# no file found
# --- Try a suffix detection
# case : Dypeg brute 60s-001B.fit
# --- search for the first index where there is a numeric char
n = len(genename)
suffix = ""
sep = ""
k = 0
for k in range(n-1,0,-1):
car = basename[k]
#print(f"car={car} k={k}")
if car.isnumeric() == True:
break
suffix = car + suffix
basename = genename[0:k+1]
#print(f"1.1 basename = {basename}")
#print(f"1.1 suffix = {suffix}")
# --- search for the first index where there is no numeric char
n = len(basename)
indice = ""
sep = ""
k = 0
for k in range(n-1,0,-1):
car = basename[k]
#print(f"car={car} k={k}")
if car.isnumeric() == False:
sep = basename[k]
break
indice += car
#print(f"1 k={k} indice={indice}")
#print(f"1 basename = {basename}")
if indice == "":
genename = basename
sep = ""
else:
# --- valid the sepration between genename and indice
if sep=="-" or sep=="_":
genename = basename[0:k]
else:
genename = basename[0:k]
sep = ""
# --- count the number of files corresponding to the genename
dirname = os.path.dirname(fitsname)
wildcard = os.path.join(dirname, genename + sep + "*" + suffix + file_extension)
#print(f"wildcard = {wildcard}")
ftmps = glob.glob(wildcard)
indexes = []
if len(ftmps) > 0:
k = len(genename+sep)
#print(f"2 genename+sep = {genename+sep}")
#print(f"2 k = {k}")
nsuffix = len(suffix)
for ftmp in ftmps:
filename, file_extension = os.path.splitext(ftmp)
basename = os.path.basename(filename)
n = len(basename)
#print(f"2 basename = {basename}")
indice = basename[k:n-nsuffix]
if indice == "":
continue
indexes.append([indice, int(indice)])
indexes = [y[0] for y in sorted(indexes, key = lambda x: x[1])]
# --- verify if there are leading zeros
ndigit = 0
n = len(indexes)
if n > 0:
first = indexes[0]
if first[0] == "0":
ndigit = len(first)
genname = {}
genname["dirname"] = dirname
genname["genename"] = genename
genname["sep"] = sep
genname["indexes"] = indexes
genname["suffix"] = suffix
genname["file_extension"] = file_extension
genname["ndigit"] = ndigit
# --- process optional parameters
if len(indexes) > 0:
first = int(genname["indexes"][0])
n = int(genname["indexes"][-1])
if "first" in kwargs.keys():
bound = first
first = kwargs["first"]
if first < 0:
first = n + first + 1
if first > n:
first = n
if first < bound:
first = bound
last = n
if "last" in kwargs.keys():
last = kwargs["last"]
if last < 0:
last = n + last + 1
if last < first:
last = first
if last > n:
last = n
indexes = []
for index in genname["indexes"]:
rank = int(index)
if rank >= first and rank <= last:
if "indexes" in kwargs.keys():
if rank in kwargs["indexes"]:
indexes.append(index)
else:
indexes.append(index)
genname["indexes"] = indexes
# ---
return genname
def innames(self, fitsname, **kwargs):
"""Same method as genename()
"""
return self.genename(fitsname, **kwargs)
def inoutnames(self, fitsname, outfilename, **kwargs):
"""Generate file names informations to process a series of files.
This method is the same than innames() but add the output names.
Args:
fitsname: Any file name with or without path or extension.
outfilename: Generic name of the files that must be created later.
**kwargs: a dictionnary of optional parameters:
* 'first': Lower index to keep indexes.
* 'last': Upper index to keep indexes.
* 'indexes': List of indexes to keep (integers).
Returns:
A tupple of three elements.
* A dictionary containing the following keys:
* 'dirname': Path name
* 'genename': Generic name of files
* 'sep': Separator between generic name and indexes
* 'indexes': List of indexes sorted increasing
* 'file_extension': File extension
* 'ndigit': Number of digits in case of indexes with leading zeros
* A string that includes the path and the generic shortname.
* The extension of the outpout files.
For example, you have 6 files m63-1.fit, m63-2.fit ... m63-6.fit.
You have to put one of the three file names as input of the method genename
and if you want to keep only files after the index 4. The generic output file names
are 'i'.
::
fn = FileNames()
result = fn.inoutnames("m63-1", "i", first=4)
result can be ({'dirname': '/tmp', 'genename': 'm63', 'sep': '-', 'indexes': ['5', '6'], 'suffix': '', 'file_extension': '.fit', 'ndigit': 0}, '/tmp/i', '.fit')
"""
genename = self.innames(fitsname, **kwargs)
# ---
outfilename = self.fullfilename(outfilename)
outfilegene, outfile_extension = os.path.splitext(outfilename)
return genename, outfilegene, outfile_extension
def outfilename(self, output=""):
"""Get or set the output file name
Store the output current filename. Useful for image series or stacking.
There is no verification if the file exists.
Args:
output: Any file name with or without path or extension.
Returns:
A string containing the full name of the file (path, shortname, extension).
::
fn = FileNames()
fullname = fn.outfilename("j1")
"""
fitsname = output
if fitsname == "":
# --- return the current output name
res = self._outfilename
else:
# --- return a simulation of a output name
genename = self.genename(fitsname)
outfilename_short = genename["genename"] + genename["file_extension"]
outfilename = os.path.join( genename["dirname"], outfilename_short)
res = outfilename
return res
def indexname(self, genename_in, outfilegene, outfile_extension, index, k=""):
"""Get input and output file name of one image after using genename().
Generate input and output full file names.
Before using this method, use genename() or innames() to generate the genename_in dictionary.
There is no verification if the output file exists.
Args:
genename_in: Dictionary generated using the method genename().
outfilegene: Generic name (with ou withou path) of the output file
outfile_extension: Extension of the output file
index: Index if the intput file. Should be one of the elements of genename_in['indexes'].
k: Index of the output file. If k is not given, it will be equal to index.
Returns:
A tupple of four elements.
* A string of the short input file name.
* A string of the short output file name.
* A string of the full input file name.
* A string of the full output file name.
::
fn = FileNames()
fn.path = '/tmp'
gen = fn.innames("m63-1", first=4)
shortin, shortout, fullin, fullout = fn.indexname(gen, "/tmp/res/j", gen['indexes'][0], 1)
The results should be shortin='m63-4.fit', shortout='j1.fit', shortin='/tmp/m63-4.fit', shortout='/tmp/res/j1.fit'
"""
filename_short = genename_in["genename"] + genename_in["sep"] + str(index) + genename_in["suffix"] + genename_in["file_extension"]
filename = os.path.join( genename_in["dirname"], filename_short)
if k=="":
kstr = str(index)
else:
kstr = str(k)
outgen = self.genename(outfilegene)
outfname = os.path.join(outgen['dirname'],outgen['genename']) + kstr + outgen['suffix'] + outfile_extension
basename = os.path.basename(outfname)
#called_by = inspect.stack()[1][3]
#print(f"ImaSeries.{called_by} {k}/{n} : {filename_short} -> {basename}")
return filename_short, basename, filename, outfname
def indexnames(self, genename_in, outfilegene, outfile_extension, k=""):
"""Get input and output file names of a series of images after using genename().
Generate input and output full file names.
Before using this method, use genename() or innames() to generate the genename_in dictionary.
There is no verification if the output file exists.
Args:
genename_in: Dictionary generated using the method genename().
outfilegene: Generic name (with ou withou path) of the output file
outfile_extension: Extension of the output file
k: Index of the first output file. If k is not given, it will be equal to index.
Returns:
A tupple of four elements.
* A list of strings of the full input file name.
* A list of strings of the full output file name.
::
fn = FileNames()
fn.path = '/tmp'
gen = fn.innames("m63-1", first=4)
shortin, shortout, fullin, fullout = fn.indexnames(gen, "/tmp/res/j", 1)
The results should be infnames=['/tmp/m63-4.fit','/tmp/m63-5.fit','/tmp/m63-6.fit'] shortout=['/tmp/res/j1.fit', '/tmp/res/j2.fit', '/tmp/res/j3.fit']
"""
outfnames = []
infnames = []
if k!="":
kk = k
for index in genename_in["indexes"]:
filename_short = genename_in["genename"] + genename_in["sep"] + str(index) + genename_in["suffix"] + genename_in["file_extension"]
filename = os.path.join( genename_in["dirname"], filename_short)
if k=="":
kstr = str(index)
else:
kstr = str(kk)
kk += 1
outgen = self.genename(outfilegene)
outfname = os.path.join(outgen['dirname'],outgen['genename']) + kstr + outgen['suffix'] + outfile_extension
infnames.append(filename)
outfnames.append(outfname)
#called_by = inspect.stack()[1][3]
#print(f"ImaSeries.{called_by} {k}/{n} : {filename_short} -> {basename}")
return infnames, outfnames
def deletenames(self, fitsname, **kwargs):
"""Delete file names from a series of files.
This method get the file names using innames().
Args:
fitsname: Any file name with or without path or extension.
**kwargs: a dictionnary of optional parameters:
* 'first': Lower index to keep indexes.
* 'last': Upper index to keep indexes.
* 'indexes': List of indexes to keep (integers).
Returns:
List of deleted files.
::
fn = FileNames()
result = fn.deletenames("m63-1", first=4)
result can be ({'dirname': '/tmp', 'genename': 'm63', 'sep': '-', 'indexes': ['5', '6'], 'suffix': '', 'file_extension': '.fit', 'ndigit': 0}, '/tmp/j', '.fit')
"""
fnames = []
for fname in self.itername(fitsname, **kwargs):
os.remove(fname)
fnames.append(fname)
return fnames
def _askopenfilename(self, title="", filetypes=""):
root = tk.Tk()
root.withdraw() # To avoid display of the Tk window
initialdir = self.rootdir
if filetypes == "":
filetypes = [("FITS",".fit .fits .fts .gz"),("All", "*")]
fitsname = askopenfilename(title=title, initialdir=initialdir, filetypes = filetypes)
if fitsname != "":
filename, file_extension = os.path.splitext(fitsname)
if file_extension=="":
fitsname += self._fits_extension
self.rootdir = os.path.dirname(fitsname)
root.destroy()
return fitsname
def _asksaveasfilename(self, title="", filetypes=""):
root = tk.Tk()
root.withdraw() # To avoid display of the Tk window
initialdir = self.rootdir
if filetypes == "":
filetypes = [("FITS",".fit .fits .fts .gz"),("All", "*")]
fitsname = asksaveasfilename(title=title, initialdir=initialdir, filetypes = filetypes)
if fitsname != "":
filename, file_extension = os.path.splitext(fitsname)
if file_extension=="":
fitsname += self._fits_extension
self.rootdir = os.path.dirname(fitsname)
root.destroy()
return fitsname
# #####################################################################
# #####################################################################
# #####################################################################
# Main
# #####################################################################
# #####################################################################
# #####################################################################
if __name__ == "__main__":
default = 21
example = input(f"Select the example (0 to 21) ({default}) ")
try:
example = int(example)
except:
example = default
print("Example = {}".format(example))
# --- Get path_images for examples
fn = FileNames()
path_products = fn.copy_data2products()
if example == 0:
"""
Just one file
"""
fn = FileNames()
fn.extension(".fit")
#fn.path(path_images)
fs = fn.fullfilename("m57")
if example == 1:
"""
"""
fn = FileNames()
fn.extension(".fit")
fs = fn.genename("m57")
if example == 2:
"""
"""
fn = FileNames()
fn.path(r"C:\d\grb220427a\night_20220427")
res = fn.genenames("IM_*.fits.gz")
if example == 3:
"""
"""
fn = FileNames()
fn.naming("PyROS.img.1")
print(fn.naming_rules())
param = {}
param['ftype'] = "L0A"
param['date'] = "20221109"
param['time'] = "235406123456"
param['unit'] = "TNC"
param['version'] = 1
param['channel'] = "CH1"
param['id_seq'] = "0123456789"
param['plane'] = 1
param['frame'] = 1
fname = fn.naming_set(param)
print(f"fname={fname}")
param = fn.naming_get(fname)
if example == 4:
"""
"""
fn = FileNames()
for k in range(2, 10, 1):
fname = f"i{k}.fit"
print(fname)
fname = fn.fullfilename(fname)
with open(fname, "wt") as f:
pass
gen, out, outext = fn.inoutnames("i1", 'j', first=3, last=7)
res = fn.indexname(gen, out, outext, '3', 0)
ress = fn.indexnames(gen, out, outext, 0)
if example == 5:
"""
"""
fn = FileNames()
fn.pathing("YYYY/MM/DD")
params = fn.pathing_get("/tmp/2023/01/04")
fn.longitude = 45.678
param = {}
param['date'] = params['date']
param['night'] = False
pname = fn.pathing_set(**param)
#params = fn.pathing_get("/tmp/20230104")
fn = FileNames()
fn.pathing("YYYY/YYYYMMDD")
fn.longitude = 45.678
param = {}
param['date'] = "2021-10-26T13:45:23"
param['night'] = True
pname = fn.pathing_set(**param)
if example == 6:
"""
"""
fn = FileNames()
fn.pathnaming("PyROS.img.1")
fn.longitude = 45.678
date = "2021-10-26T13:45:23"
fnd = fn.naming_date(date)
pparam = {}
pparam['date'] = fnd['iso']
pparam['night'] = True
fparam = {}
fparam['ftype'] = "L0A"
fparam['date'] = fnd['yyyymmdd']
fparam['time'] = fnd['hhmmssssssss']
fparam['version'] = "1"
fparam['unit'] = "TNC"
fparam['channel'] = "CH1"
fparam['id_seq'] = 123456789
fparam['plane'] = 1
fparam['frame'] = 1
fullname = fn.join()
print(f"fullname={fullname}")
if example == 7:
"""
"""
fn = FileNames()
fn.naming("T1M.1")
fn.longitude = 45.678
date = "2021-10-26T13:45:23"
fnd = fn.naming_date(date)
fparam = {}
fparam['date'] = fnd['yyyymmdd']
fparam['time'] = fnd['hhmmss']
fparam['millis'] = fnd['millis']
fparam['target'] = "54UMa"
fparam['filter'] = "672-SII"
fparam['binning'] = 1
fparam['index'] = 1
fullname = fn.naming_set(fparam)
print(f"fullname={fullname}")
param = fn.naming_get(fullname)
print(f"param={param}")
if example == 8:
"""
Get a wildcard to get a glob for a given naming
"""
fn = FileNames()
fn.naming("T1M.1")
fparam = {}
fparam['target'] = "54UMa"
wildcard = fn.naming_set(fparam)
print(f"wildcard={wildcard}")
if example == 9:
"""
Get the julian day limits for a given night
"""
fn = FileNames()
longitude= -90
fn.longitude = longitude
print(f"longitude = {longitude}")
# --- Define a date of the observation
date = "2023-03-20T17:00:00"
print(f"input date = {date}")
jd = Date(date).jd()
print(f"input jd = {jd}")
# --- Compute the night
night = fn.date2night(date)
print(f"night={night} (= last local noon truncated)")
# --- Compute the julian day limits
jds = fn.night2date(night)
print(f"jds={jds}")
if example == 10:
"""
Get path from name
"""
fn = FileNames()
fn.longitude = 45.678
fn.fcontext = "image_raw"
fn.pathnaming("PyROS.img.1")
fn.rootdir = "/tmp"
in_fullname = r"/srv/work/L0A_20211026_134522999983_1_TNC_CH1_0123456789_001_001.fits.gz"
path = fn.subdir_from_filename(in_fullname)
print(f"path={path}")
if example == 11:
"""
Set a filename at the current date
"""
fn = FileNames()
fn.naming("PyROS.img.1")
print(fn.naming_rules())
param = {}
param['ftype'] = "L0A"
param['date'] = "now"
param['unit'] = "TNC"
param['version'] = 1
param['channel'] = "CH1"
param['id_seq'] = "0123456789"
param['plane'] = 1
param['frame'] = 1
fname = fn.naming_set(param)
print(f"fname={fname}")
param = fn.naming_get(fname)
if example == 12:
"""
Set a filename at the current date
"""
fn = FileNames()
fn.naming("PyROS.seq.1")
print(fn.naming_rules())
param = {}
param['period'] = "P001"
param['date'] = "20230423"
param['unit'] = "TNC"
param['version'] = 1
param['id_seq'] = "0123456789"
fname = fn.naming_set(param)
print(f"fname={fname}")
param = fn.naming_get(fname)
if example == 13:
"""
Manage a context
"""
fn = FileNames()
fn.fcontext_create("images") # Give a name of a new context
fn.fcontext = "images" # Select the context name
fn.rootdir = "/tmp"
fn.subdir = "2023/03/21"
fn.fname = "messier63-1"
fn.extension = ".fits"
if example == 14:
"""
Manage many contexts for PyROS
"""
fn = FileNames()
fn.longitude = 165.85944
# --- Create a file context for L0 images
fn.fcontext_create("pyros_img_L0", "Images L0A")
fn.fcontext = "pyros_img_L0"
fn.naming("PyROS.img.1")
fn.rootdir = "/tmp/img/L0"
fn.extension = ".fit"
# --- Create a file context for L1 images
fn.fcontext_create("pyros_img_L1", "Images L1A")
fn.fcontext = "pyros_img_L1"
fn.pathnaming("PyROS.img.1")
fn.rootdir = "/tmp/img/L1"
fn.extension = ".fits"
# --- Create a file context for sequence files
fn.fcontext_create("pyros_seq", "Sequences PyROS")
fn.fcontext = "pyros_seq"
fn.pathnaming("PyROS.seq.1")
fn.rootdir = "/tmp/seq"
fn.extension = ".p"
# --- Place an image at the good place
fn.fcontext = "pyros_img_L0"
in_fullname = r"/srv/work/L0A_20211026_194522999983_1_TNC_CH1_0123456789_001_001.fits.gz"
#fn.update_subdir_fname_from_filename(in_fullname)
out_fullname = fn.join(in_fullname)
print(f"==== Copy an image in the good path (context {fn.fcontext_value('description')}) ====")
print(f"{in_fullname=:}")
print(f"{out_fullname=:}")
# --- Place a sequence at the good place
fn.fcontext = "pyros_seq"
in_fullname = r"/srv/work/P001_20211026_1_TNC_0123456789.p"
#fn.update_subdir_fname_from_filename(in_fullname)
out_fullname = fn.join(in_fullname)
print(f"\n==== Copy sequence in the good path (context {fn.fcontext_value('description')}) ====")
print(f"{in_fullname=:}")
print(f"{out_fullname=:}")
# --- Save an image from a camera
fn.fcontext = "pyros_img_L0"
param = {}
param['ftype'] = "L0A"
param['date'] = "now"
param['unit'] = "TNC"
param['version'] = 1
param['channel'] = "CH1"
param['id_seq'] = 123456789
param['plane'] = 1
param['frame'] = 1
fname = fn.naming_set(param)
#fn.update_subdir_fname_from_filename(fname)
out_fullname = fn.join(fname)
print(f"\n==== Create an image in the good path (context {fn.fcontext_value('description')}) ====")
print(f"{out_fullname=:}")
# --- Save an image L1 after image processing
fn.fcontext = "pyros_img_L0"
# --- load the L0 file
param = fn.naming_get(out_fullname)
# --- save the L1 file
fn.fcontext = "pyros_img_L1"
param['ftype'] = "L1A"
fname = fn.naming_set(param)
#fn.update_subdir_fname_from_filename(fname)
out_fullname = fn.joinabs(fname)
print(f"\n==== Process an image L0 and save in the good path (context {fn.fcontext_value('description')}) ====")
print(f"{out_fullname=:}")
if example == 15:
"""
Manage default context
"""
fn = FileNames()
fn.fcontext_create("my_context", "Test")
fn.fcontext = "my_context"
fn.rootdir = "/tmp"
fn.extension = ".fit"
in_fullname = "/home/myuser/messier63.fits.gz"
out_fullname = fn.join(in_fullname)
print(out_fullname)
if example == 16:
"""
Create many contexts
"""
contexts = []
contexts.append({'context':"sequences", 'description':"Sequence files (.p, .f)", 'rootdir':"/tmp/pyros/sequences", 'pathnaming':"PyROS.seq.1"})
contexts.append({'context':"img/darks/L0", 'description':"Dark images L0 (individuals)", 'rootdir':"/tmp/pyros/img/darks/l0", 'pathnaming':"PyROS.img.1", 'extension':".fit"})
contexts.append({'context':"img/darks/L1", 'description':"Dark images L1 (stacks)", 'rootdir':"/tmp/pyros/img/darks/l1", 'pathnaming':"PyROS.img.1", 'extension':".fit"})
fn = FileNames()
for context in fn.fcontexts:
fn.fcontext = context # select the context
if fn.fcontext == "default":
continue
del fn.fcontext
for context in contexts:
fn.fcontext_create(context['context'], context['description'])
fn.fcontext = context['context'] # select the context
if context.get('rootdir') != None:
fn.rootdir = context.get('rootdir')
if context.get('naming') != None:
fn.naming = context.get('naming')
if context.get('pathing') != None:
fn.pathing = context.get('pathing')
if context.get('pathnaming') != None:
fn.pathnaming(context.get('pathnaming'))
if context.get('extension') != None:
fn.extension = context.get('extension')
for context in fn.fcontexts:
fn.fcontext = context # select the context
if fn.fcontext == "default":
continue
print(f"{fn.fcontext} : {fn.fcontext_value('description')}")
if example == 17:
"""
Test PyROS sequences
"""
fn = FileNames()
# --- Create a file context for sequence files
fn.fcontext_create("pyros_seq", "Sequences PyROS")
fn.fcontext = "pyros_seq"
fn.pathnaming("PyROS.seq.1")
fn.rootdir = "/tmp/seq"
fn.extension = ".p"
param = {}
param['period'] = "P001"
param['date'] = "20230628"
param['unit'] = "TNC"
param['version'] = 1
param['id_seq'] = 123456789
fname = fn.naming_set(param)
out_fullname = fn.join(fname)
print(f"\n==== Create a file in the good path (context {fn.fcontext_value('description')}) ====")
print(f"{out_fullname=:}")
if example == 18:
"""
Test PyROS ephemeris
"""
fn = FileNames()
# --- Create a file context for ephemeris files
fn.fcontext_create("pyros_eph", "Ephemeris PyROS")
fn.fcontext = "pyros_eph"
fn.pathnaming("PyROS.eph.1")
fn.rootdir = "/tmp/eph"
fn.extension = ".f"
param = {}
param['period'] = "P001"
param['date'] = "20230628"
param['unit'] = "TNC"
param['version'] = 1
param['target'] = "sun_yui"
fname = fn.naming_set(param)
out_fullname = fn.join(fname)
print(f"\n==== Create a file in the good path (context {fn.fcontext_value('description')}) ====")
print(f"{out_fullname=:}")
if example == 19:
"""
Test fcontext Indexed.1
"""
fn = FileNames()
# --- Create a file context
fn.fcontext_create("findex", "Files with indexes")
fn.fcontext = "findex"
fn.pathnaming("Indexed.1")
fn.rootdir = "/tmp/eph"
fn.extension = ".f"
param = {}
param['genename'] = "M63-078"
param['sep'] = "-"
#param['indexes'] = ['001', '002']
param['indexes'] = '*'
param['suffix'] = "R"
fname = fn.naming_set(param)
print(f"FINAL {fname=}")
param = fn.naming_get(fname)
print(f"FINAL {param=}")
out_fullname = fn.join(fname)
print(f"==== Create a file in the good path (context = {fn.fdescription}) ====")
print(f"{out_fullname=:}")
if example == 20:
"""
Test the method _naming_get_indexed1() of fcontext Indexed.1
"""
fn = FileNames()
# --- Create a file context
fn.fcontext_create("findex", "Files with indexes")
fn.fcontext = "findex"
fn.pathnaming("Indexed.1")
#file_in = os.path.join("c:","srv","develop","pyros_soft","pyros","vendor","guitastro","tests","data","m57.fit")
file_in = "M-57"
param = fn._naming_get_indexed1(file_in)
print(f"{param=}")
gn = FileNames()
# --- Create a file context
gn.fcontext_create("gindex", "Files with indexes")
if example == 21:
"""
Test the method naming_wildcard of various fcontexts
"""
fn = FileNames()
# --- Create a file context
fn.fcontext_create("pf", "Files with indexes")
fn.fcontext = "pf"
fn.pathnaming("PyROS.img.1")
# ---
wildcard = fn.naming_wildcard(ftype="L0A", unit="TNC", channel="CH1")
print(f"{wildcard=}")
# ---
in_fullname = r"/srv/work/L1B_20211026_194522999983_1_TNC_CH1_0123456789_001_001.fits.gz"
wildcard = fn.naming_wildcard(in_fullname, i=True)
print(f"{wildcard=}")
# ---
fn.pathnaming("Indexed.1")
in_fullname = r"/srv/work/i.fits.gz"
wildcard = fn.naming_wildcard(in_fullname, i=True)
print(f"{wildcard=}")