filenames.py
94.9 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
# -*- 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
errors = [""]*7
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"
class FileNames(FileNamesException, GuitastroTools):
""" Class to manage file names
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.
:Usage:
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 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).
**Night directory:**
As astronomical images are often dispatched into night directories,
the method get_night() return a string corresponding to the night
directory according an input date (i.e. DATE-OBS). The method get_night()
consider a night as from noon to noon. To do that, before using get_night()
you must specify the longitude of the observatory with the methos longitude().
**Naming:**
Naming rules can be applied to verify a structured file name structure.
By default, there is no naming rule.
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.
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().
**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.
"""
VERBOSE_NONE = 0
VERBOSE_SPECIFIC = 1
VERBOSE_DEBUG = 2
VERBOSE_ESSENTIAL = 4
VERBOSE_ALL = 8
NAMING_NONE = 0
NAMING_PYROS1 = 1
NAMING_ROS1 = 2
NAMING_T1M1 = 3
_naming_list = ["", "PyROS.1", "ROS.1", "T1M.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_list = ["", "YYYYMMDD", "YYYY/YYYYMMDD", "YYYY/MM/DD"]
_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._image_dir = guitastrotools.conf_guitastro['path_products']
self._fits_extension = ".fit"
self._verbose_level = self.VERBOSE_NONE
self._longiau_deg = 0.0
self._naming = self.NAMING_NONE
self._pathing = self.PATHING_NONE
self._pathnaming = self._naming
self._outfilename = os.path.join(self._image_dir, "noname"+self.extension())
# --- naming_rule
if len(args) > 0 :
self.naming(args[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"\nNaming: {self.naming()}."
msg += f"\nPath: {self._image_dir}."
msg += f"\nExtension: {self._fits_extension}."
msg += f"\nOut file name: {self._outfilename}."
return msg
def 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
# =============================================
# 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.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._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._naming]
def __naming_rules_pyros1(self, section):
name = self._naming_list[self._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 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_ros1(self, section):
name = self._naming_list[self._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._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(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._naming]
texte = ""
if self._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._naming == self.NAMING_PYROS1:
dat = self.__naming_rules_pyros1(self._NAMING_RULES_SECTION_DATE)
elif self._naming == self.NAMING_ROS1:
dat = self.__naming_rules_ros1(self._NAMING_RULES_SECTION_DATE)
elif self._naming == self.NAMING_T1M1:
dat = self.__naming_rules_t1m1(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._naming == self.NAMING_NONE:
texte += "No specific rule. File names can be formed as you want.\n"
return texte
elif self._naming == self.NAMING_PYROS1:
texte += self.__naming_rules_pyros1(self._NAMING_RULES_SECTION_INTRO)
elif self._naming == self.NAMING_ROS1:
texte += self.__naming_rules_ros1(self._NAMING_RULES_SECTION_INTRO)
elif self._naming == self.NAMING_T1M1:
texte += self.__naming_rules_t1m1(self._NAMING_RULES_SECTION_INTRO)
# ---
h1 = "2. Format of the file names"
texte +=f"\n{h1}\n" + "="*len(h1) + "\n\n"
if self._naming == self.NAMING_PYROS1:
texte += self.__naming_rules_pyros1(self._NAMING_RULES_SECTION_FORMAT)
if self._naming == self.NAMING_ROS1:
texte += self.__naming_rules_ros1(self._NAMING_RULES_SECTION_FORMAT)
if self._naming == self.NAMING_T1M1:
texte += self.__naming_rules_t1m1(self._NAMING_RULES_SECTION_FORMAT)
# ---
h1 = "3. Remarks"
texte +=f"\n{h1}\n" + "="*len(h1) + "\n\n"
if self._naming == self.NAMING_PYROS1:
texte += self.__naming_rules_pyros1(self._NAMING_RULES_SECTION_REMARKS)
if self._naming == self.NAMING_ROS1:
texte += self.__naming_rules_ros1(self._NAMING_RULES_SECTION_REMARKS)
if self._naming == self.NAMING_T1M1:
texte += self.__naming_rules_t1m1(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.1'
"""
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._naming
self._naming = self.NAMING_PYROS1
try:
fname_verified = self.naming_set(**param)
if fname == fname_verified:
naming = self.NAMING_PYROS1
except:
pass
self._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._naming
self._naming = self.NAMING_ROS1
try:
fname_verified = self.naming_set(**param)
if fname == fname_verified:
naming = self.NAMING_ROS1
except:
pass
self._naming = old_naming
if naming == self.NAMING_NONE and n>3:
if fname[:3] == "T1M":
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._naming
self._naming = self.NAMING_T1M1
try:
fname_verified = self.naming_set(**param)
print(f"{fname=:}")
print(f"{fname_verified=:}")
if fname == fname_verified:
naming = self.NAMING_T1M1
except:
pass
self._naming = old_naming
return self._naming_list[naming]
def naming_get(self, fname:str) -> dict:
"""Get parameters that form the file name according the current naming
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.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
fnames = pathlib.Path(fname).parts
#print(f"{fnames=:}")
fname = fnames[len(fnames)-1]
fname_verified = ""
if self._naming == self.NAMING_NONE:
param['fname'] = fname
elif self._naming == self.NAMING_PYROS1:
fname = os.path.splitext(fname)[0]
n = len(fname)
nn = 54
if n != nn:
texte =f"File name 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 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._naming == self.NAMING_ROS1:
fname = os.path.splitext(fname)[0]
n = len(fname)
nn = 37
if n != nn:
texte =f"File name 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 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._naming == self.NAMING_T1M1:
if fname[:3] == "T1M":
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)
return param
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.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.1", if param['date'] is "*" 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
if self._naming == self.NAMING_NONE:
wildcard = "*"
elif self._naming == self.NAMING_PYROS1:
wildcard = "???_????????_????????????_?_???_???_??????????_???_???"
elif self._naming == self.NAMING_ROS1:
wildcard = "??_????????_?????????_??????_????????"
elif self._naming == self.NAMING_T1M1:
wildcard = "T1M_????????_??????_???_*_Filtre_*_bin?x?.*"
# ---
na = len(args)
nk = len(kwargs)
if self._naming == self.NAMING_NONE:
if na > 0:
fname = args[0]
if self._naming == self.NAMING_PYROS1:
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]
param['frame'] = 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'] == "*":
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 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)
# --- form final file name
fname = param['ftype']+"_"+param['date']+"_"+param['time']+"_"+param['version']+"_"+param['unit']+"_"+param['channel']+"_"+param['id_seq']+"_"+param['plane']+"_"+param['frame']
if self._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'] == "*":
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._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'] == "*":
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"Frame {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']
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['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):
"""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._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._pathing]
def __pathing_rules_yyyymmdd(self, section):
name = self._pathing_list[self._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._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._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(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._pathing]
texte = ""
if self._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._pathing == self.PATHING_NONE:
texte += "No specific rule. Path names can be formed as you want.\n"
return texte
elif self._pathing == self.PATHING_YYYYMMDD:
texte += self.__pathing_rules_yyyymmdd(self._PATHING_RULES_SECTION_INTRO)
elif self._pathing == self.PATHING_YYYY_YYYYMMDD:
texte += self.__pathing_rules_yyyy_yyyymmdd(self._PATHING_RULES_SECTION_INTRO)
elif self._pathing == self.PATHING_YYYY_MM_DD:
texte += self.__pathing_rules_yyyy_mm_dd(self._PATHING_RULES_SECTION_INTRO)
# ---
h1 = "2. Format of the path names"
texte +=f"\n{h1}\n" + "="*len(h1) + "\n\n"
if self._pathing == self.PATHING_YYYYMMDD:
texte += self.__pathing_rules_yyyymmdd(self._PATHING_RULES_SECTION_FORMAT)
if self._pathing == self.PATHING_YYYY_YYYYMMDD:
texte += self.__pathing_rules_yyyy_yyyymmdd(self._PATHING_RULES_SECTION_FORMAT)
if self._pathing == self.PATHING_YYYY_MM_DD:
texte += self.__pathing_rules_yyyy_mm_dd(self._PATHING_RULES_SECTION_FORMAT)
# ---
h1 = "3. Remarks"
texte +=f"\n{h1}\n" + "="*len(h1) + "\n\n"
if self._pathing == self.PATHING_YYYYMMDD:
texte += self.__pathing_rules_yyyymmdd(self._PATHING_RULES_SECTION_REMARKS)
if self._pathing == self.PATHING_YYYY_YYYYMMDD:
texte += self.__pathing_rules_yyyy_yyyymmdd(self._PATHING_RULES_SECTION_REMARKS)
if self._pathing == self.PATHING_YYYY_MM_DD:
texte += self.__pathing_rules_yyyy_mm_dd(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
pnames = pathlib.Path(pname).parts
print(f"{pnames=:}")
if self._pathing == self.PATHING_NONE:
param['fname'] = fname
elif self._pathing == self.PATHING_YYYYMMDD or self._pathing == self.PATHING_YYYY_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._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)
elif self._pathing == self.PATHING_YYYY_MM_DD:
np = len(pnames)
if np == 1:
valid = True
if np > 2:
yyyy = pnames[-3]
if len(yyyy) != 4:
valid = False
mm = pnames[-2]
if len(mm) != 2:
valid = False
dd = pnames[-1]
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._pathing == self.PATHING_YYYYMMDD or self._pathing == self.PATHING_YYYY_YYYYMMDD or self._pathing == self.PATHING_YYYY_MM_DD:
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
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._pathing == self.PATHING_NONE:
pname = args[0]
if self._pathing == self.PATHING_YYYYMMDD or self._pathing == self.PATHING_YYYY_YYYYMMDD or self._pathing == self.PATHING_YYYY_MM_DD:
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'] = ""
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 == "":
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'])
else:
date = Date(param['date'])
digits = date.digits(0)
yyyy = digits[:4]
mm = digits[4:6]
dd = digits[6:8]
pname = ""
if self._pathing == self.PATHING_YYYYMMDD:
pname = yyyy+mm+dd
elif self._pathing == self.PATHING_YYYY_YYYYMMDD:
pname = os.path.join(yyyy, yyyy+mm+dd)
elif self._pathing == self.PATHING_YYYY_MM_DD:
pname = os.path.join(yyyy, mm, dd)
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):
"""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: a string with a new pathnaming of files.
See the list using pathnamings().
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.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._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._naming = self._pathnaming
if self._pathnaming == self.NAMING_PYROS1:
self._pathing = self.PATHING_YYYY_MM_DD
return self._naming_list[self._pathnaming]
def pathnaming_set(self, prepath, 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.1")
fn.longitude(45.678)
prepath = "/tmp"
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(prepath, pparam, fparam, ".fits")
The answer should be '/tmp\\2021\\10\\26\\L0_20211026_134522999983_1_TNC_CH1_0123456789_001_001.fits'
"""
if self._pathnaming == self.NAMING_PYROS1:
path = self.pathing_set(**pkw)
fname = self.naming_set(**nkw)
fullname = os.path.join(prepath, path, fname) + extension
return fullname
def pathnaming_get(self, fname:str) -> dict:
if self._pathnaming == self.NAMING_PYROS1:
pkw = self.pathing_get(fname)
nkw = self.naming_get(fname)
return pkw, nkw
# =============================================
# Managing filenames
# =============================================
def path(self, path: str=""):
""" Get/set the path of images.
If the path does not exists, it is created.
"""
if path != "":
path = os.path.normpath(path)
if not os.path.exists(path):
message = f"Create a new path {path}"
self.print_msg(self.VERBOSE_ESSENTIAL, message)
os.makedirs(path)
if os.path.exists(path):
self._image_dir = path
return self._image_dir
def extension(self, extension: str="") -> str:
"""Set/Get the extension of the files.
Args:
extension: Set the file extension to (usefull add automatically to files when record). Defaut value is ".fit".
Returns:
The current extension added to files.
"""
if extension != "":
if "." not in extension:
extension = "." + extension
self._fits_extension = extension
return self._fits_extension
def date2night(self, date: str="now")->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() method.
Args:
date: Input date to compute the night identifier. Defaut value is "now".
Returns:
The night identifier string YYYYMMDD.
::
fn = FileNames()
fn.longitude = 2.3456
night = fn.get_night("now")
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
#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]
return night
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() method.
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)
def fullfilename(self,fitsname: str) -> str:
""" Get the full name according any entry.
Args:
fitsname: 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*.
"""
dirname = os.path.dirname(fitsname)
basename = os.path.basename(fitsname)
filename, file_extension = os.path.splitext(fitsname)
if dirname == "" :
# --- add the current image path
fitsname = os.path.join(self._image_dir, basename)
if file_extension == "":
# --- add the extension
fitsname += self._fits_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 _split_extension(self, filename: str) -> Tuple[str, str]:
# split at the first .
basename = os.path.basename(filename)
k = basename.find(".")
if k >= 0:
filename = basename[:k]
file_extension = basename[k:]
else:
filename = basename
file_extension = ""
return filename, file_extension
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)
filename , file_extension = self._split_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).
"""
fitsname = self.fullfilename(fitsname)
# --- extract the basename
filename, file_extension = os.path.splitext(fitsname)
basename = os.path.basename(filename)
#print(f"0 basename={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() # pour ne pas afficher la fenêtre Tk
initialdir = self._image_dir
if filetypes == "":
filetypes = [("FITS","*.fit;*.fits;*.fts"),("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._image_dir = os.path.dirname(fitsname)
root.destroy()
return fitsname
def _asksaveasfilename(self, title="", filetypes=""):
root = tk.Tk()
root.withdraw() # pour ne pas afficher la fenêtre Tk
initialdir = self._image_dir
if filetypes == "":
filetypes = [("FITS","*.fit;*.fits;*.fts"),("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._image_dir = os.path.dirname(fitsname)
root.destroy()
return fitsname
# #####################################################################
# #####################################################################
# #####################################################################
# Main
# #####################################################################
# #####################################################################
# #####################################################################
if __name__ == "__main__":
default = 9
example = input(f"Select the example (0 to 9) ({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.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.1")
fn.longitude(45.678)
prepath = "/tmp"
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.pathnaming_set(prepath, pparam, fparam)
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}")