-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathutils.py
More file actions
2030 lines (1665 loc) · 66.1 KB
/
utils.py
File metadata and controls
2030 lines (1665 loc) · 66.1 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
#!/usr/bin/env python
from abc import ABC, abstractmethod
import bisect
from configparser import ConfigParser
import configparser
from functools import reduce
from getpass import getpass
from typing import Callable, Dict, Any, List, Optional, Self, Set, Tuple, Type
import re, json, requests, time, sys, io, os
from astropy import units as u
from astropy.coordinates import Angle, SkyCoord
from astropy.time import Time
from collections import OrderedDict
from pdastro import pdastrostatsclass
import numpy as np
import pandas as pd
from copy import deepcopy
from pathlib import Path
# number of days to subtract from TNS discovery date to make sure no SN flux before discovery date
DISC_DATE_BUFFER = 20
# ATLAS template change dates
TEMPLATE_CHANGE_1_MJD = 58417
TEMPLATE_CHANGE_2_MJD = 58882
CONFIG_CUT_NAMES = ["uncert_cut", "x2_cut", "controls_cut", "badday_cut", "averaging"]
ATLAS_API_COLUMN_NAMES = [
"MJD",
"m",
"dm",
"uJy",
"duJy",
"F",
"err",
"chi/N",
"RA",
"Dec",
"x",
"y",
"maj",
"min",
"phi",
"apfit",
"Sky",
"ZP",
"Obs",
"Mask",
]
def add_static_methods(cls):
"""
Class decorator that automatically adds static versions of all public instance methods.
For each instance method (not starting with "_" or "s_"), this decorator adds a static method
with the same name prefixed by 's_'. The static version will instantiate the class with default
parameters and call the corresponding instance method.
This is best used when instance methods don't depend on constructor arguments.
Example:
@add_static_methods
class CustomLogger:
def step(self, message):
print(f"⚙️ {message}")
CustomLogger.s_step("This works statically!")
"""
default_instance = cls()
for name, method in list(cls.__dict__.items()):
if callable(method) and not name.startswith("_") and not name.startswith("s_"):
def make_static(meth_name):
def static_method(*args, **kwargs):
return getattr(default_instance, meth_name)(*args, **kwargs)
return static_method
setattr(cls, f"s_{name}", staticmethod(make_static(name)))
return cls
@add_static_methods
class CustomLogger:
def __init__(self, prefix=""):
self.prefix = f"[{prefix}] " if prefix else ""
def _print(
self, message: str, symbol: str = "", newline: bool = False, dots: bool = False
):
newline_part = "\n" if newline else ""
suffix = "..." if dots else ""
# capitalize first letter of message
if message:
message_part = message[0].upper() + message[1:]
symbol_part = f"{symbol} " if symbol else ""
print(f"{newline_part}{symbol_part}{self.prefix}{message_part}{suffix}")
def warning(self, message: str, newline: bool = False, dots: bool = False):
self._print(message, symbol="⚠️ WARNING:", newline=newline, dots=dots)
def error(self, message: str, newline: bool = False, dots: bool = False):
self._print(message, symbol="❌ ERROR:", newline=newline, dots=dots)
def success(
self, message: str = "Success", newline: bool = False, dots: bool = False
):
self._print(message, symbol="✅", newline=newline, dots=dots)
def header(
self,
message: str,
num_dashes: int = 3,
newline: bool = True,
):
prefix_newline = "\n" if newline else ""
dashes = "-" * num_dashes
# no prefix for header
print(f"{prefix_newline}{dashes} {message} {dashes}")
def subheader(self, message: str, newline: bool = True):
self.header(message, num_dashes=2, newline=newline)
def step(self, message: str, newline: bool = True, dots: bool = False):
self._print(message, symbol="⚙️ ", newline=newline, dots=dots)
def body(self, message: str, newline: bool = False, dots: bool = False):
self._print(message, newline=newline, dots=dots)
def listitem(self, message: str, symbol="•", dots: bool = False):
# no prefix for listitem
print(f'{symbol} {message}{"..." if dots else ""}')
def info(self, message: str, newline: bool = False, dots: bool = False):
self._print(message, symbol="🔧", newline=newline, dots=dots)
def secret(self, message: str, newline: bool = False, dots: bool = False):
self._print(message, symbol="🔒", newline=newline, dots=dots)
def loading(self, message: str, newline: bool = False, dots: bool = False):
self._print(message, symbol="🔄", newline=newline, dots=dots)
def saving(self, message: str, newline: bool = False, dots: bool = False):
self._print(message, symbol="💾", newline=newline, dots=dots)
def api(self, message: str, newline: bool = False, dots: bool = False):
self._print(message, symbol="🌐", newline=newline, dots=dots)
def plot(self, message: str, newline: bool = False, dots: bool = False):
self._print(message, symbol="📈", newline=newline, dots=dots)
# convert flux to magnitude
def flux2mag(flux: float):
"""
Convert flux in microjanskeys to apparent magnitude
"""
return -2.5 * np.log10(flux) + 23.9
# convert magnitude to flux
def mag2flux(mag: float):
"""
Convert apparent magnitude to flux in microjanskeys.
"""
return 10 ** ((mag - 23.9) / -2.5)
def mag2count(mag: float, zpt: float = 20.44):
"""
Convert apparent magnitude to TESS counts per second.
"""
return 10 ** ((zpt - mag) / 2.5)
def count2mag(count: float, zpt: float = 20.44):
"""
Convert TESS counts per second to apparent magnitude.
"""
return -2.5 * np.log10(count) + zpt
def AandB(A, B) -> List:
return list(np.intersect1d(A, B, assume_unique=False))
def AnotB(A, B) -> List:
return list(np.setdiff1d(A, B))
def AorB(A, B) -> List:
return list(np.union1d(A, B))
def not_AandB(A, B) -> List:
return list(np.setxor1d(A, B))
# print iterations progress
# from https://stackoverflow.com/questions/3173320/text-progress-bar-in-terminal-with-block-characters
def print_progress_bar(
iteration,
total,
prefix="",
suffix="",
decimals=1,
length=100,
fill="█",
printEnd="\r",
):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
printEnd - Optional : end character (e.g. "\r", "\r\n") (Str)
"""
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + "-" * (length - filledLength)
print(f"\r{prefix} |{bar}| {percent}% {suffix}", end=printEnd)
if iteration == total:
print()
def app2absmag(values: List[float], distance_modulus=29.04, precision=2):
"""
Convert a list of apparent magnitude values to absolute magnitude values.
Parameters:
- values: list or array of apparent magnitude values
- distance_modulus: float, the distance modulus (default 29.04)
- precision: int, number of decimal places to round to
Returns:
- list of converted absolute magnitude values (as floats)
"""
return [round(v - distance_modulus, precision) for v in values]
def load_json_config(filename: str):
try:
CustomLogger.s_loading(f"Loading JSON config file at {filename}", newline=True)
with open(filename) as cfg:
res = json.load(cfg)
CustomLogger.s_success()
return res
except Exception as e:
raise RuntimeError(f"Could not load JSON config file at {filename}: {str(e)}")
def nan_if_none(x):
return x if x is not None else np.nan
def new_row(t: Optional[pd.DataFrame], d: Optional[Dict] = None):
if d is None:
d = {}
new_row_df = pd.DataFrame([d])
if t is None or t.empty:
t = new_row_df
else:
new_row_df = new_row_df.reindex(columns=t.columns)
t = pd.concat([t, new_row_df], axis=0, ignore_index=True)
return t
def abbreviate_list(l: List, max_length: int = 30, abbrev_length: int = 10) -> str:
if len(l) > max_length:
half_abbrev_length = int(abbrev_length / 2)
return (
"["
+ ", ".join(map(str, l[:half_abbrev_length]))
+ ", ..., "
+ ", ".join(map(str, l[-half_abbrev_length:]))
+ f"] (length: {len(l)})"
)
else:
return str(l) + f" (length: {len(l)})"
def get_allowed_presets(config: ConfigParser) -> list[str]:
"""
Extract all preset names from the config that match 'column_name_preset.<PRESET NAME>'.
"""
pattern = re.compile(r"^column_name_preset\.(.+)$")
return [match.group(1) for key in config.keys() if (match := pattern.match(key))]
def parse_config_str(value: str | None):
"""Parse value from config file by converting string to string, None, or boolean."""
if value:
stripped = value.strip().lower()
if stripped == "none":
return None
if stripped == "true":
return True
if stripped == "false":
return False
return value
def parse_comma_separated_string(string: Optional[str]):
if string is None:
return None
try:
return [item.strip() for item in string.split(",")]
except Exception as e:
raise RuntimeError(
f"Could not parse comma-separated string: {string}" f"\nERROR: {str(e)}"
)
def make_dir_if_not_exists(directory):
"""
Creates a directory if it does not exist. Handles permission errors and other exceptions.
:param directory: Path to the directory to create.
"""
if not os.path.isdir(directory):
try:
os.makedirs(directory)
except PermissionError:
raise PermissionError(
f"Permission denied: Cannot create directory at {directory}"
)
except FileExistsError:
# This can occur if the directory is created between the `isdir` check and `makedirs` call.
raise FileExistsError(f"Directory already exists: {directory}")
except Exception as e:
raise RuntimeError(
f"An error occurred while creating directory {directory}: {str(e)}"
)
# load a .ini config file
def load_config(filename):
cfg = configparser.ConfigParser()
try:
CustomLogger.s_loading(f"Loading config file at {filename}", newline=True)
cfg.read(filename)
except Exception as e:
raise RuntimeError(f"Could not load config file at {filename}: {str(e)}")
CustomLogger.s_success()
return cfg
def extract_from_subdir(
directory: str,
pattern: re.Pattern,
group_name: str | int,
convert_function: Callable = lambda x: x,
):
if not os.path.isdir(directory):
CustomLogger.s_warning(
f"Cannot search because the path does not exist: {directory}"
)
return []
extracted_values = set()
for file in os.listdir(directory):
match = pattern.match(file)
if match:
value = match.group(group_name)
extracted_values.add(convert_function(value))
if not extracted_values:
CustomLogger.s_warning(
f"Could not find {group_name} from the files in {directory}"
)
return list(extracted_values)
def has_match(directory: str, pattern: re.Pattern):
if not os.path.isdir(directory):
return False
for file in os.listdir(directory):
if pattern.match(file):
return True
return False
def find_all_filts(directory: str, tnsname: str) -> List[str]:
pattern = re.compile(
rf"^{re.escape(tnsname)}" # tnsname
r"(?:_i\d{3})?" # optional control index
r"\.(?P<filt>\w+)" # filter (captured)
r"(?:\.\d+\.\d+days)?" # optional mjdbinsize
r"(?:\.clean)?" # optional 'clean'
r"\.lc\.txt$" # ends with '.lc.txt'
)
subdir = os.path.join(directory, tnsname)
return extract_from_subdir(subdir, pattern, "filt")
def check_filts_against_preset(
preset: str, allowed_presets: List[str], filts: List[str] | str
):
if isinstance(filts, str):
filts = [filts]
for filt in filts:
if filt in allowed_presets and filt != preset:
ans = (
input(
f"WARNING: Filter '{filt}' is already defined in the config file as a preset, but does not match the current preset '{preset}'. Consider removing the filter from the current list of filters to clean, then running a separate command using the preset '{filt}'. \nCONTINUE (not recommended)? (y/n): "
)
.strip()
.lower()
)
if ans not in ["y", "yes"]:
sys.exit(0)
def find_all_control_indices(directory: str, tnsname: str, filt=None) -> List:
if filt is None:
filt_pattern = r".*"
else:
filt_pattern = re.escape(filt)
pattern = re.compile(
rf"^{re.escape(tnsname)}_i(?P<control_index>\d{{3}})" # captures control index
rf"\.{filt_pattern}" # match specific filt if provided
r"(?:\.\d+\.\d+days)?" # optional mjdbinsize
r"(?:\.clean)?" # optional 'clean'
r"\.lc\.txt$" # ends with '.lc.txt'
)
subdir = os.path.join(directory, tnsname, "controls")
return extract_from_subdir(subdir, pattern, "control_index", convert_function=int)
def is_sn_in_subdir(directory: str, tnsname: str) -> bool:
pattern = re.compile(
rf"^{re.escape(tnsname)}" # tnsname
r"\.[^\.]+" # filter
r"(?:\.clean)?" # optional '.clean'
r"(?:\.\d+\.\d+days)?" # optional mjdbinsize
r"\.lc\.txt$" # ends with '.lc.txt'
)
subdir = os.path.join(directory, tnsname)
return has_match(subdir, pattern)
def validate_mjd_ranges(
ranges: List[List[float]], var_name: str = "MJD_RANGES"
) -> None:
"""
Validates that a list of MJD ranges is properly formatted.
"""
if not isinstance(ranges, list):
raise TypeError(f"{var_name} must be a list, got {type(ranges).__name__}")
for i, r in enumerate(ranges):
if not (isinstance(r, list) and len(r) == 2):
raise TypeError(f"{var_name}[{i}] must be a 2-element list, got: {r}")
if not all(isinstance(x, (int, float, np.integer, np.floating)) for x in r):
raise TypeError(f"{var_name}[{i}] must contain only integers, got: {r}")
if r[0] > r[1]:
raise ValueError(f"{var_name}[{i}] has start > end: {r}")
def _merge_ranges(ranges: List[List[float]]) -> List[List[float]]:
"""
Merges a list of [start, end] MJD ranges that may overlap or be adjacent.
"""
if not ranges:
return []
ranges.sort()
merged = [ranges[0]]
for start, end in ranges[1:]:
last_start, last_end = merged[-1]
if start <= last_end + 1:
merged[-1][1] = max(last_end, end)
else:
merged.append([start, end])
return merged
def _expand_ranges(
ranges: List[List[float]],
min_mjd: int,
max_mjd: int,
expand_edges: Optional[float] = 0.0,
):
if expand_edges == 0.0 or expand_edges is None:
return ranges
CustomLogger.s_body(f"Expanding range edges by {expand_edges}")
expanded = []
for start, end in ranges:
new_start = max(min_mjd, start - expand_edges)
new_end = min(max_mjd, end + expand_edges)
expanded.append([new_start, new_end])
if not expanded:
return []
# merge overlapping or adjacent ranges
return _merge_ranges(expanded)
def get_inverse_mjd_ranges(
mjd_ranges: List[List[float]],
min_mjd: int,
max_mjd: int,
expand_edges: float = 0.0,
exclude_mjd_ranges: Optional[List[List[float]]] = None,
) -> List[List[float]]:
if expand_edges < 0:
raise ValueError(
f"Cannot expand edges of the inverse ranges by a negative amount {expand_edges}"
)
if len(mjd_ranges) < 1:
return [[min_mjd, max_mjd]]
# raise RuntimeError("MJD ranges must contain at least one range")
validate_mjd_ranges(mjd_ranges)
mjd_ranges = sorted(mjd_ranges)
mjd_ranges[0][0] = max(min_mjd, mjd_ranges[0][0])
mjd_ranges[-1][-1] = min(max_mjd, mjd_ranges[-1][-1])
inverse = []
cur = min_mjd
for start, end in mjd_ranges:
if start > cur:
inverse.append([cur, start])
cur = max(cur, end)
# check if there's a gap at the end
if cur < max_mjd:
inverse.append([cur, max_mjd])
# merge exclude_mjd_ranges with the inverse list
if exclude_mjd_ranges is not None:
validate_mjd_ranges(exclude_mjd_ranges, var_name="EXCLUDE_MJD_RANGES")
CustomLogger.s_body(f"Excluding additional MJD ranges {exclude_mjd_ranges}")
if len(exclude_mjd_ranges) > 0:
combined = inverse + exclude_mjd_ranges
inverse = _merge_ranges(combined)
return _expand_ranges(inverse, min_mjd, max_mjd, expand_edges=expand_edges)
class StatParams:
def __init__(self, statparams: Dict[str, int | float | None]):
statparams = deepcopy(statparams)
self.mean: float = nan_if_none(statparams["mean"])
self.mean_err: float = nan_if_none(statparams["mean_err"])
self.stdev: float = nan_if_none(statparams["stdev"])
self.X2norm: float = nan_if_none(statparams["X2norm"])
self.Nclip: int | float = nan_if_none(statparams["Nclip"])
self.Ngood: int | float = nan_if_none(statparams["Ngood"])
# self.Nexcluded: int | float = nan_if_none(statparams["Nexcluded"])
self.ix_good: List[int] = list(statparams["ix_good"])
self.ix_clip: List[int] = list(statparams["ix_clip"])
def __str__(self):
parts = []
for key in [
"mean",
"mean_err",
"stdev",
"X2norm",
"Nclip",
"Ngood",
"ix_good",
"ix_clip",
]:
val = getattr(self, key, None)
if isinstance(val, float):
parts.append(f"{key}={val:.17g}") # Full float precision
else:
parts.append(f"{key}={val}")
return f"StatParams({', '.join(parts)})"
class PlotLimits:
def __init__(self, xlower=None, xupper=None, ylower=None, yupper=None):
self.xlower = xlower
self.xupper = xupper
self.ylower = ylower
self.yupper = yupper
def set_lims(
self,
xlims: Optional[tuple[float | None, float | None]] = None,
ylims: Optional[tuple[float | None, float | None]] = None,
):
if xlims is not None:
self.set_xlims(xlims)
if ylims is not None:
self.set_ylims(ylims)
def set_xlims(self, xlims: tuple[float | None, float | None] | None):
if xlims is None:
return
if len(xlims) != 2:
raise ValueError(f"xlims must be a tuple of length 2, got {len(xlims)}")
if xlims[0] is not None and xlims[1] is not None and xlims[0] >= xlims[1]:
raise ValueError(
f"xlims lower limit {xlims[0]} must be less than upper limit {xlims[1]}"
)
if xlims[0] is not None:
self.xlower = xlims[0]
if xlims[1] is not None:
self.xupper = xlims[1]
def set_ylims(self, ylims: tuple[float | None, float | None] | None):
if ylims is None:
return
if len(ylims) != 2:
raise ValueError(f"ylims must be a tuple of length 2, got {len(ylims)}")
if ylims[0] is not None and ylims[1] is not None and ylims[0] >= ylims[1]:
raise ValueError(
f"ylims lower limit {ylims[0]} must be less than upper limit {ylims[1]}"
)
if ylims[0] is not None:
self.ylower = ylims[0]
if ylims[1] is not None:
self.yupper = ylims[1]
def get_xlims(self) -> tuple[float | None, float | None] | None:
if self.xlower is None and self.xupper is None:
return None
return self.xlower, self.xupper
def get_ylims(self) -> tuple[float | None, float | None] | None:
if self.ylower is None and self.yupper is None:
return None
return self.ylower, self.yupper
def is_empty(self):
return (
self.xlower is None
and self.xupper is None
and self.ylower is None
and self.yupper is None
)
def __str__(self):
return f"Plot limits: x-axis [{self.xlower}, {self.xupper}], y-axis [{self.ylower}, {self.yupper}]"
class FomLimits:
def __init__(self):
self._values = {}
self.logger = CustomLogger(self.__class__.__name__)
def add(self, sigma_kern: float, values: List[float | int] | float | int):
"""
Add new FOM limit(s) to a sigma_kern.
"""
if isinstance(values, list):
sorted_list_to_add = self._validate_flat_list(values)
else:
sorted_list_to_add = [float(values)]
if self.has(sigma_kern):
existing = set(self._values[sigma_kern])
for v in sorted_list_to_add:
if v not in existing:
bisect.insort(self._values[sigma_kern], v)
else:
self._values[sigma_kern] = sorted_list_to_add
def set(
self,
sigma_kerns: List[float],
values: (
List[float]
| List[List[float]]
| Dict[float, float]
| Dict[float, List[float]]
),
):
"""
Overwrite any current sigma_kerns and FOM limits with new ones.
"""
if self._values:
self.logger.warning("Overwriting current FOM limits with new ones")
self._values = self.validate(sigma_kerns, values)
def set_blank(self, sigma_kerns: List[float]):
"""
Overwrite any current sigma_kerns with new ones, and any current FOM limits with 0.0.
"""
self.set(sorted(sigma_kerns), [0.0] * len(sigma_kerns))
def has(self, sigma_kern) -> bool:
return sigma_kern in self._values.keys()
def get(self, sigma_kern: float, index: int = -1) -> float:
"""
Get an FOM limit at a certain index for a specific sigma_kern.
"""
if not self.has(sigma_kern):
raise ValueError(
f"FOM limits for sigma_kern {sigma_kern} not found (existing sigma_kerns: {self._values.keys()})"
)
if index >= len(self._values[sigma_kern]):
raise ValueError(
f"Cannot get FOM limit at index {index}; only {len(self._values[sigma_kern])} FOM limits exist per sigma_kern"
)
return self._values[sigma_kern][index]
def get_multi(self, sigma_kern: float) -> List[float]:
"""
Get all FOM limits for a specific sigma_kern.
"""
if not self.has(sigma_kern):
raise ValueError(
f"FOM limits for sigma_kern {sigma_kern} not found (existing sigma_kerns: {self._values.keys()})"
)
return self._values[sigma_kern]
def get_all_multi(self) -> Dict[float, List[float]]:
"""
Get all FOM limits for each sigma_kern.
"""
return self._values
def get_all_single(self, index: int = -1) -> Dict[float, float]:
"""
Get an FOM limit at a certain index for each sigma_kern.
"""
return {
sigma_kern: self.get(sigma_kern, index=index)
for sigma_kern in self._values.keys()
}
def _validate_flat_list(self, data: List | float) -> List[float]:
"""
Verifies that all entries in a list are numbers and converts them to floats. Sorts the resulting list.
:param data: List of numbers (int or float)
:return: Sorted list of floats
:raises TypeError: If any item is not a number
"""
if isinstance(data, list):
for i, item in enumerate(data):
if not isinstance(item, (int, float)):
raise TypeError(f"Item at index {i} is not a number: {item}")
res = [float(x) for x in data]
res.sort()
return res
else:
return [float(data)]
def validate(
self,
sigma_kerns: List[float],
fom_limits: (
List[float]
| List[List[float]]
| Dict[float, float]
| Dict[float, List[float]]
),
) -> Dict[float, List[float]]:
"""
Validate and convert FOM limits into a dictionary with sigma_kerns as keys.
WARNING: If passing fom_limits as a list, both fom_limits and sigma_kerns must be sorted.
:param fom_limits: FOM limits as a list or dictionary.
Supports:
- List[float]: one FOM limit per sigma_kern
- List[List[float]]: multiple FOM limits per sigma_kern
- Dict[float, float]: one FOM limit per sigma_kern
- Dict[float, List[float]]: multiple FOM limits per sigma_kern, already structured
:param sigma_kerns: Kernel sizes corresponding to the FOM limits.
"""
# List[float] or List[List[float]]
if isinstance(fom_limits, list):
if not fom_limits:
raise ValueError("FOM limits list is empty")
if len(fom_limits) != len(sigma_kerns):
raise ValueError(
f"Length mismatch: got {len(fom_limits)} FOM limits but {len(sigma_kerns)} sigma_kerns"
)
# List[float]
if all(isinstance(v, (int, float)) for v in fom_limits):
# wrap each float in a list
return dict(
zip(
sigma_kerns, [[v] for v in self._validate_flat_list(fom_limits)]
)
)
# List[List[float]]
elif all(isinstance(v, list) for v in fom_limits):
return {
sigma_kern: self._validate_flat_list(sublist)
for sigma_kern, sublist in zip(sigma_kerns, fom_limits)
}
else:
raise TypeError(
"If passing a list, it must contain only numbers or only sublists of numbers"
)
# Dict[float, float] or Dict[float, List[float]]
elif isinstance(fom_limits, dict):
if set(fom_limits.keys()) != set(sigma_kerns):
raise ValueError("FOM limits dict keys must exactly match sigma_kerns")
return {
sigma_kern: self._validate_flat_list(sublist)
for sigma_kern, sublist in fom_limits.items()
}
else:
raise TypeError(
"FOM limits must be a list of floats/sublists or a dict with float/list values"
)
def merge(self, other: Self):
if not isinstance(other, FomLimits):
raise TypeError("Argument must be an instance of FomLimits")
for other_key, other_values in other.get_all_multi().items():
self.add(other_key, other_values)
def __str__(self):
return self.get_all_multi().__str__()
class PresetColumnNames:
"""
Class to handle loading and managing column names for light curve conversion
to ATClean-readable format, as defined in the config file.
"""
def __init__(self, config: ConfigParser, preset: str):
self.preset = preset
self._read_config(config)
def _validate_columns_dict(self, columns_dict: Dict, no_nones: bool = False):
for key, name in columns_dict.items():
name = parse_config_str(name)
if no_nones and name is None:
raise RuntimeError(
f"Column name '{name}' in config preset {self.preset} cannot be None"
)
columns_dict[key] = name
return columns_dict
def _read_config(self, config: ConfigParser):
try:
config_preset_settings = dict(config[f"column_name_preset.{self.preset}"])
except:
raise RuntimeError(
f"Preset '{self.preset}' (field '{f'column_name_preset.{self.preset}'}') not found in config file."
)
self.required_columns: Dict[str, str] = self._validate_columns_dict(
{
"mjd": config_preset_settings.get("mjd_column_name"),
"flux": config_preset_settings.get("flux_column_name"),
"dflux": config_preset_settings.get("dflux_column_name"),
"mjdbin": config["column_name_preset"]["mjd_bin_column_name"],
"mask": config["column_name_preset"]["mask_column_name"],
"fdf": config["column_name_preset"]["snr_column_name"],
},
no_nones=True,
)
self.optional_columns: Dict[str, str | None] = self._validate_columns_dict(
{
"chisquare": config_preset_settings.get("chisquare_column_name"),
"filt": config_preset_settings.get("filter_column_name"),
"mag": config_preset_settings.get("mag_column_name"),
"dmag": config_preset_settings.get("dmag_column_name"),
"ra": config_preset_settings.get("ra_column_name"),
"dec": config_preset_settings.get("dec_column_name"),
"zpt": config_preset_settings.get("zpt_column_name"),
}
)
# extra columns to copy
extra_columns = parse_config_str(config_preset_settings["extra_columns"])
if not isinstance(extra_columns, str):
raise ValueError(
f"Extra columns in config file ({config_preset_settings['extra_columns']}) must be comma-separated list (got {extra_columns})"
)
self.extra_columns: List[str] = (
[]
if extra_columns is None
else [col.strip() for col in extra_columns.split(",")]
)
def add(
self, key: str, name: str, is_required: bool = False, overwrite: bool = False
):
if not isinstance(key, str) or not key.strip():
raise ValueError("Column key must be a non-empty string.")
if not isinstance(name, str) or not name.strip():
raise ValueError(f"Column name for key '{key}' must be a non-empty string.")
# if key exists but the name is different, raise an error
existing_name = self.required_columns.get(key) or self.optional_columns.get(key)
if existing_name and existing_name != name and not overwrite:
raise RuntimeError(
f"Column key '{key}' is already defined with a different name '{existing_name}'."
)
if is_required:
self.required_columns[key] = name
else:
self.optional_columns[key] = name
def add_many(self, coldict: Dict, is_required: bool = False):
for key, name in coldict.items():
self.add(key, name, is_required=is_required)
def update(self, key: str, name: str, is_required: bool = False):
if is_required:
if key not in self.required_columns:
raise RuntimeError(
f"Cannot update non-existing required column name {key} with '{name}'"
)
self.required_columns[key] = name
else:
if key not in self.optional_columns:
raise RuntimeError(
f"Cannot update non-existing optional column name {key} with '{name}'"
)
self.optional_columns[key] = name
def update_many(self, coldict: Dict, is_required: bool = False):
for key, name in coldict.items():
self.update(key, name, is_required=is_required)
def remove(self, key: str):
if key in self.optional_columns:
del self.optional_columns[key]
if key in self.optional_columns:
del self.optional_columns[key]
def get_required_column_names(self, is_averaged: bool = False):
if is_averaged:
return [
self.required_columns["mjdbin"],
self.required_columns["flux"],
self.required_columns["dflux"],
self.required_columns["mask"],
]
return [
self.required_columns["mjd"],
self.required_columns["flux"],
self.required_columns["dflux"],
]
def get_optional_column_names(self):
return list(self.optional_columns.values())
def get_all_columns_to_copy(self) -> List[str]:
"""Return all columns that should be copied into the output light curve."""
colset: Set[str] = (
set(self.required_columns.values())
| set(filter(None, self.optional_columns.values()))
| set(self.extra_columns)
)
return list(colset)
def has(self, name: str):
return name in self.required_columns or name in self.optional_columns