Repository navigation
Expand file tree
/
Copy pathclean.py
More file actions
1282 lines (1127 loc) · 44.4 KB
/
Copy pathclean.py
File metadata and controls
1282 lines (1127 loc) · 44.4 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 datetime import datetime
import os
import time
from typing import Callable, Dict, List, Optional
import sys, argparse
import pandas as pd
import numpy as np
from copy import deepcopy
from lightcurve import (
LimCutsTable,
Supernova,
AveragedSupernova,
)
from download import (
Credentials,
)
from plot import PlotPdf
from utils import (
CONFIG_CUT_NAMES,
DISC_DATE_BUFFER,
BadDayCut,
ChiSquareCut,
ControlLightCurveCut,
CustomCut,
CustomLogger,
UncertaintyCut,
UncertaintyEstimation,
check_filts_against_preset,
find_all_filts,
format_float_string,
get_config_custom_cuts,
hexstring_to_int,
Cut,
CutList,
SnInfoTable,
get_allowed_presets,
resolve_mjd0,
PresetColumnNames,
load_preset_column_names_from_config,
new_row,
parse_config_str,
load_config,
make_dir_if_not_exists,
parse_comma_separated_string,
)
class OutputReadMe:
def __init__(self, output_dir, tnsname, cut_list, num_controls=0):
self.logger = CustomLogger(self.__class__.__name__)
self.cut_list: CutList = cut_list
timestamp = datetime.now()
self.filename = self.get_filename(output_dir, tnsname, timestamp)
self.file = None
self._open_file()
self._write_intro_text(tnsname, timestamp, num_controls=num_controls)
def _open_file(self):
self.logger.loading(
f"Creating new README file for outputting cut information at {self.filename}",
newline=True,
)
try:
os.makedirs(os.path.dirname(self.filename), exist_ok=True)
self.file = open(self.filename, "w", encoding="utf-8")
except Exception as e:
raise RuntimeError(f"Failed to open output README file: {str(e)}")
self.logger.success()
def get_filename(self, output_dir: str, tnsname: str, timestamp: datetime):
return os.path.join(
output_dir, tnsname, f"README_{timestamp.strftime('%Y%m%d_%H%M%S')}.md"
)
def get_header_str(self, text: str, level=1) -> str:
hashtags = "#" * level
return f"\n{hashtags} {text}"
def get_applicable_cut_lines(self, cut: Cut) -> List[str]:
lines = [f"Column: '{cut.column}'", f"Flag: {hex(cut.flag)}"]
if cut.min_value is not None:
lines.append(f"Min value: {cut.min_value}")
if cut.max_value is not None:
lines.append(f"Max value: {cut.max_value}")
return lines
def get_percent_cut_str(
self,
flag: int,
percent_cut: float,
lc_type: str = "SN",
flagged_as: str = "bad",
) -> str:
"""
Return an informative string describing the percentage of data flagged with a certain hex value.
"""
return f"Percent of {lc_type} light curve flagged as {flagged_as} ({hex(flag)}): {percent_cut:0.2f}%"
def write_line(self, text: str = ""):
try:
self.file.write(f"{text}\n")
except Exception as e:
raise RuntimeError(f"Failed to write line to output README: {str(e)}")
def write_lines(self, lines: List[str]):
for line in lines:
self.write_line(line)
def save(self):
if self.file:
try:
self.logger.saving(f"Saving output README file at {self.filename}")
self.file.close()
except Exception as e:
self.logger.warning(
f"Failed to properly close output README file: {str(e)}"
)
else:
self.logger.warning(
f"Output readme file (self.file) cannot be None; skipping saving",
dots=True,
)
def _write_intro_text(
self, tnsname, timestamp: datetime, num_controls: int = 0
) -> List[str]:
badday_cut = self.cut_list.get(BadDayCut.name())
mjdbinsize = 1.0 if badday_cut is None else badday_cut.mjd_bin_size
self.write_line(
f"""# SN {tnsname} Light Curve Cleaning and Averaging
Timestamp: {timestamp.strftime('%B %d, %Y at %I:%M:%S %p')}
Full command: `{' '.join(sys.argv)}`
The SN light curves are separated by filter and labelled as such in the file name. Averaged light curves contain an additional number in the file name that represents the MJD bin size used. Control light curves are located in the "controls" subdirectory and follow the same naming scheme, only with their control index added after the SN name.
The following details the file names for each of the light curve versions:
- Original SN light curves: {tnsname}.o.lc.txt and {tnsname}.c.lc.txt
- Cleaned SN light curves: {tnsname}.o.clean.lc.txt and {tnsname}.c.clean.lc.txt"""
)
if num_controls > 0:
self.write_line(
f"- Control light curves: {tnsname}_i{1:03d}.o.lc.txt, ..., {tnsname}_i{num_controls:03d}.c.lc.txt"
)
if self.cut_list.has(BadDayCut.name()):
self.write_line(
f"- Averaged light curves (for MJD bin size {format_float_string(mjdbinsize)} days): {tnsname}.o.{format_float_string(mjdbinsize)}days.lc.txt and {tnsname}.c.{format_float_string(mjdbinsize)}days.lc.txt"
)
self.write_line(
f'\nThe following summarizes the hex values in the "Mask" column of each light curve for each cut applied (see below sections for more information on each cut):'
)
lines = []
if self.cut_list.has(UncertaintyCut.name()):
lines.append(
f"- Uncertainty cut: {hex(self.cut_list.get(UncertaintyCut.name()).flag)}"
)
if self.cut_list.has(ChiSquareCut.name()):
lines.append(
f"- Chi-square cut: {hex(self.cut_list.get(ChiSquareCut.name()).flag)}"
)
if self.cut_list.has(ControlLightCurveCut.name()):
lines.append(
f"- Control light curve cut: {hex(self.cut_list.get(ControlLightCurveCut.name()).flag)}"
)
custom_cuts = self.cut_list.get_custom_cuts()
for cut in custom_cuts.values():
lines.append(f'- Custom cut on "{cut.column}" column: {hex(cut.flag)}')
if badday_cut is not None:
lines.append(f"- Bad day cut (averaging): {hex(badday_cut.flag)}")
self.write_lines(lines)
def add_filter_section(self, filt: str):
self.write_line(self.get_header_str(f"Filter: {filt}", level=2))
def add_standard_cut_section(
self,
title: str,
cut: Cut,
percent_cut: float,
additional_lines: Optional[List[str]] = None,
):
self.write_line(self.get_header_str(title, level=3))
self.write_line()
self.write_lines(self.get_applicable_cut_lines(cut))
if additional_lines is not None:
self.write_lines(additional_lines)
self.write_line(self.get_percent_cut_str(cut.flag, percent_cut))
def add_template_correction_section(self, lines: List[str]):
self.write_line(
self.get_header_str(f"ATLAS template change correction", level=3)
)
self.write_line()
self.write_lines(lines)
def add_uncert_est_section(
self,
sigma_typical_old: float,
sigma_typical_new: float,
final_sigma_extra: float,
percent_greater: float,
apply: bool,
):
self.write_line(self.get_header_str(f"True uncertainties estimation", level=3))
self.write_line()
lines = [
f"Apply true uncertainties estimation: {apply}.",
f"We can increase the typical uncertainties from {sigma_typical_old:0.2f} to {sigma_typical_new:0.2f} by adding an additional systematic uncertainty of {final_sigma_extra:0.2f} in quadrature.",
f"The new typical uncertainty is {percent_greater:0.2f}% greater than old typical uncertainty.",
]
if percent_greater >= 10:
lines[-1] += "True uncertainties estimation recommended."
if apply:
lines.append(
"The extra noise was added to the uncertainties of the SN light curve and put in a new uncertainties column."
)
else:
lines.append("True uncertainties estimation not needed; procedure skipped.")
self.write_lines(lines)
def add_uncert_cut_section(self, cut: UncertaintyCut, percent_cut: str):
self.add_standard_cut_section("Uncertainty cut", cut, percent_cut)
def add_x2_cut_section(
self,
cut: ChiSquareCut,
percent_contamination: float,
percent_loss: float,
percent_cut: float,
):
self.add_standard_cut_section(
f"PSF chi-square cut",
cut,
percent_cut,
additional_lines=[
f"Selected chi-square cut has {percent_contamination:0.2f}% contamination and {percent_loss:0.2f}% loss"
],
)
def add_controls_cut_section(
self,
cut: ControlLightCurveCut,
x2_percent_cut: float,
snr_percent_cut: float,
Nclip_percent_cut: float,
Ngood_percent_cut: float,
questionable_percent_cut: float,
percent_cut: float,
):
self.write_line(self.get_header_str(f"Control light curve cut", level=3))
self.write_line()
self.write_line(
self.get_percent_cut_str(
cut.x2_flag,
x2_percent_cut,
flagged_as=f"above x2_max bound of {cut.x2_max}",
)
)
self.write_line(
self.get_percent_cut_str(
cut.snr_flag,
snr_percent_cut,
flagged_as=f"above snr_max bound of {cut.snr_max}",
)
)
self.write_line(
self.get_percent_cut_str(
cut.Nclip_flag,
Nclip_percent_cut,
flagged_as=f"above Nclip_max bound of {cut.Nclip_max}",
)
)
self.write_line(
self.get_percent_cut_str(
cut.Ngood_flag,
Ngood_percent_cut,
flagged_as=f"above Ngood_min bound of {cut.Ngood_min}",
)
)
self.write_line(
self.get_percent_cut_str(
cut.questionable_flag,
questionable_percent_cut,
flagged_as=f"questionable (not masked with control light curve cut flags but Nclip > 0)",
)
)
self.write_line(self.get_percent_cut_str(cut.flag, percent_cut))
def add_badday_cut_section(self, cut: BadDayCut, percent_cut: float):
self.write_line(self.get_header_str("Bad day cut (averaging)", level=3))
self.write_line()
self.write_line(
self.get_percent_cut_str(cut.flag, percent_cut, lc_type="binned SN")
)
def add_custom_cut_section(self, cut: CustomCut, percent_cut: float):
self.add_standard_cut_section(
f"Custom cut on '{cut.column}' column", cut, percent_cut
)
class UncertEstTable:
def __init__(self, directory, filename=None):
self.logger = CustomLogger(self.__class__.__name__)
if filename is None:
self.filename = f"{directory}/uncert_est_info.txt"
else:
self.filename = f"{directory}/{filename}"
try:
self.logger.loading(
f"Loading true uncertainties estimation table at {self.filename}",
newline=True,
)
self.t = pd.read_table(self.filename, sep="\s+")
self.logger.success()
except:
self.logger.body(
f"No existing true uncertainties estimation table; creating blank table"
)
self.t = pd.DataFrame(
columns=[
"tnsname",
"filter",
"sigma_extra",
"sigma_typical_old",
"sigma_typical_new",
"sigma_typical_new_pct_greater",
"recommended",
"applied",
]
)
def add_row(self, row):
tnsname = row["tnsname"]
filt = row["filter"]
if len(self.t) > 0:
matching_ix = np.where(
self.t["tnsname"].eq(tnsname) & self.t["filter"].eq(filt)
)[0]
if len(matching_ix) > 1:
raise RuntimeError(
f"true uncertainties estimation table has {len(matching_ix)} matching rows for TNS name {tnsname} and filter {filt}"
)
if len(matching_ix) > 0:
# update existing row
idx = matching_ix[0]
self.t.loc[idx, :] = row
else:
self.t = new_row(self.t, row)
else:
self.t = new_row(self.t, row)
def save(self):
self.logger.saving(
f"Saving true uncertainties estimation table at {self.filename}",
newline=True,
)
self.t.to_string(self.filename)
class ChiSquareCutTable:
def __init__(self, directory, filename=None):
self.logger = CustomLogger(self.__class__.__name__)
if filename is None:
self.filename = f"{directory}/x2_cut_info.txt"
else:
self.filename = f"{directory}/{filename}"
try:
self.logger.loading(
f"Loading chi-square cut table at {self.filename}", newline=True
)
self.t = pd.read_table(self.filename, sep="\s+")
self.logger.success()
except:
self.logger.body(f"No existing chi-square cut table; creating blank table")
self.t = pd.DataFrame(
columns=[
"tnsname",
"filter",
"x2_cut",
"use_preSN_lc",
"snr_bound",
"pct_contamination",
"pct_loss",
]
)
def add_row(self, row):
tnsname = row["tnsname"]
filt = row["filter"]
if len(self.t) > 0:
matching_ix = np.where(
self.t["tnsname"].eq(tnsname) & self.t["filter"].eq(filt)
)[0]
if len(matching_ix) > 1:
raise RuntimeError(
f"chi-square cut table has {len(matching_ix)} matching rows for TNS name {tnsname} and filter {filt}"
)
if len(matching_ix) > 0:
# update existing row
idx = matching_ix[0]
self.t.loc[idx, :] = row
else:
self.t = new_row(self.t, row)
else:
self.t = new_row(self.t, row)
def save(self):
self.logger.saving(
f"Saving chi-square cut table at {self.filename}", newline=True
)
self.t.to_string(self.filename)
class CleanLoop:
def __init__(
self,
colnames: PresetColumnNames,
input_dir: str,
output_dir: str,
credentials: Credentials,
sninfo_filename: Optional[str] = None,
flux2mag_sigmalimit: float = 3.0,
overwrite: bool = False,
):
self.logger = CustomLogger()
self.colnames = colnames
self.sn: Optional[Supernova] = None
self.avg_sn: Optional[AveragedSupernova] = None
self.cut_list: Optional[CutList] = None
self.f: Optional[OutputReadMe] = None
self.p: Optional[PlotPdf] = None
self.credentials: Credentials = credentials
self.input_dir: str = input_dir
self.output_dir: str = output_dir
self.flux2mag_sigmalimit: float = flux2mag_sigmalimit
self.overwrite: bool = overwrite
self.sninfo: SnInfoTable = SnInfoTable(
self.output_dir, filename=sninfo_filename
)
self.uncert_est_info: UncertEstTable = UncertEstTable(self.output_dir)
if cut_list.has(ChiSquareCut.name()):
self.x2_cut_info: ChiSquareCutTable = ChiSquareCutTable(self.output_dir)
def apply_template_correction(
self,
maskval=None,
region1_offset=None,
region2_offset=None,
region3_offset=None,
num_measurements=40,
plot: bool = False,
):
self.logger.step(f"Applying ATLAS template change correction")
if self.sn is None:
raise RuntimeError("Supernova (self.sn) cannot be None")
output = self.sn.apply_template_correction(
maskval=maskval,
region1_offset=region1_offset,
region2_offset=region2_offset,
region3_offset=region3_offset,
num_measurements=num_measurements,
)
print("\n".join(output))
if self.f is None:
raise RuntimeError("Output README file (self.f) cannot be None")
self.f.add_template_correction_section(output)
if plot:
if self.p is None:
raise RuntimeError("Output plots (self.p) cannot be None")
self.p.plot_template_correction(self.sn.lcs[0])
def check_uncert_est(
self, cut: UncertaintyEstimation, apply_function: Callable, plot: bool = False
):
self.logger.step(f"Checking true uncertainties estimation")
if self.sn is None:
raise RuntimeError("Supernova (self.sn) cannot be None")
stats = self.sn.get_uncert_est_stats(cut)
final_sigma_extra = np.median(stats["sigma_extra"])
sigma_typical_old = np.median(stats["median_dflux"])
sigma_typical_new = np.sqrt(final_sigma_extra**2 + sigma_typical_old**2)
percent_greater = 100 * (
(sigma_typical_new - sigma_typical_old) / sigma_typical_old
)
self.logger.body(
f"We can increase the typical uncertainties from {sigma_typical_old:0.2f} to {sigma_typical_new:0.2f} by adding an additional systematic uncertainty of {final_sigma_extra:0.2f} in quadrature"
)
self.logger.body(
f"New typical uncertainty is {percent_greater:0.2f}% greater than old typical uncertainty"
)
apply = apply_function()
self.logger.info(f"Apply true uncertainties estimation: {apply}")
if percent_greater >= 10:
self.logger.body("True uncertainties estimation recommended")
self.logger.body(
f'{"Applying" if apply else "Skipping"} procedure', dots=True
)
if apply:
self.sn.add_noise_to_dflux(final_sigma_extra)
self.logger.success()
self.logger.body(
'The extra noise was added to the uncertainties of the SN light curve and copied to the "duJy_new" column'
)
if plot:
if self.p is None:
raise RuntimeError("Output plots (self.p) cannot be None")
self.p.plot_uncert_est(self.sn)
else:
self.logger.body(
"True uncertainties estimation not needed; skipping procedure",
dots=True,
)
if self.f is None:
raise RuntimeError("Output README file (self.f) cannot be None")
self.f.add_uncert_est_section(
sigma_typical_old,
sigma_typical_new,
final_sigma_extra,
percent_greater,
apply,
)
uncert_est_info_row = {
"tnsname": self.sn.tnsname,
"filter": self.sn.filt,
"sigma_extra": final_sigma_extra,
"sigma_typical_old": sigma_typical_old,
"sigma_typical_new": sigma_typical_new,
"sigma_typical_new_pct_greater": percent_greater,
"recommended": percent_greater >= 10,
"applied": apply,
}
return apply, uncert_est_info_row
def apply_uncert_cut(self, cut: UncertaintyCut | None, plot: bool = False):
if cut is None:
return
self.logger.step(f"Applying uncertainty cut ({cut})")
if self.sn is None:
raise RuntimeError("Supernova (self.sn) cannot be None")
percent_cut = self.sn.apply_cut(cut)
self.logger.success()
self.logger.body(
f"Total percent of SN light curve flagged with {hex(cut.flag)}: {percent_cut:0.2f}%"
)
if self.f is None:
raise RuntimeError("Output README file (self.f) cannot be None")
self.f.add_uncert_cut_section(cut, percent_cut)
if plot:
if self.p is None:
raise RuntimeError("Output plots (self.p) cannot be None")
self.p.plot_cut(self.sn, cut.flag, title=UncertaintyCut.name())
def apply_x2_cut(self, cut: ChiSquareCut | None, plot: bool = False):
if cut is None:
return None
self.logger.step(f"Applying chi-square cut ({cut})")
if self.sn is None:
raise RuntimeError("Supernova (self.sn) cannot be None")
if self.sn.colnames.chisquare is None:
self.logger.warning(
"No chi-square column name provided in config file; skipping", dots=True
)
return None
if cut.use_pre_mjd0_lc:
self.logger.body(
"Using pre-MJD0 light curve to determine contamination and loss"
)
if self.sn.mjd0 is None:
raise RuntimeError(
"MJD0 cannot be None. Please provide MJD0 throught the SN info table or --mjd0 argument, or set the use_pre_MJD0_lc field in the config file to False."
)
lc_temp = deepcopy(self.sn.lcs[0])
ix = lc_temp.ix_inrange(lc_temp.colnames.mjd, uplim=self.sn.mjd0)
if len(ix) < 1:
raise RuntimeError("no pre-MJD0 light curve available")
else:
self.logger.body(
"Using control light curves to determine contamination and loss"
)
if self.sn.num_controls < 1:
raise RuntimeError(
"No control light curves loaded. Use the --num_controls argument to load control light curves, or change the [x2_cut][use_pre_mjd0_lc] field to True."
)
lc_temp = self.sn.get_all_controls()
ix = lc_temp.t.index.values
limcuts = LimCutsTable(lc_temp, cut.snr_bound, indices=ix)
limcuts.calculate_table(cut.min_cut, cut.max_cut, cut.cut_step)
data = limcuts.calculate_row(cut.max_value)
self.logger.body(
f'Applying chi-square cut of {cut.max_value:0.2f} with {data["Pcontamination"]:0.2f}% contamination and {data["Ploss"]:0.2f}% loss'
)
percent_cut = self.sn.apply_cut(cut)
self.logger.success()
self.logger.body(
f"Total percent of SN light curve flagged with {hex(cut.flag)}: {percent_cut:0.2f}%"
)
if plot:
if self.p is None:
raise RuntimeError("Output plots (self.p) cannot be None")
self.p.plot_limcuts(limcuts, cut)
self.p.plot_cut(self.sn, cut.flag, title=ChiSquareCut.name())
if self.f is None:
raise RuntimeError("Output README file (self.f) cannot be None")
self.f.add_x2_cut_section(
cut, data["Pcontamination"], data["Ploss"], percent_cut
)
x2_info_row = {
"tnsname": self.sn.tnsname,
"filter": self.sn.filt,
"x2_cut": cut.max_value,
"use_pre_mjd0_lc": cut.use_pre_mjd0_lc,
"snr_bound": cut.snr_bound,
"pct_contamination": round(data["Pcontamination"], 2),
"pct_loss": round(data["Ploss"], 2),
}
return x2_info_row
def apply_controls_cut(
self, cut: ControlLightCurveCut | None, previous_flags: int, plot: bool = False
):
if cut is None:
return
self.logger.step(f"Applying control light curve cut ({cut})")
if self.sn is None:
raise RuntimeError("Supernova (self.sn) cannot be None")
(
x2_percent_cut,
snr_percent_cut,
Nclip_percent_cut,
Ngood_percent_cut,
questionable_percent_cut,
percent_cut,
) = self.sn.apply_controls_cut(cut, previous_flags)
if self.f is None:
raise RuntimeError("Output README file (self.f) cannot be None")
self.logger.body(
self.f.get_percent_cut_str(
cut.x2_flag,
x2_percent_cut,
flagged_as=f"above x2_max bound of {cut.x2_max}",
)
)
self.logger.body(
self.f.get_percent_cut_str(
cut.snr_flag,
snr_percent_cut,
flagged_as=f"above snr_max bound of {cut.snr_max}",
)
)
self.logger.body(
self.f.get_percent_cut_str(
cut.Nclip_flag,
Nclip_percent_cut,
flagged_as=f"above Nclip_max bound of {cut.Nclip_max}",
)
)
self.logger.body(
self.f.get_percent_cut_str(
cut.Ngood_flag,
Ngood_percent_cut,
flagged_as=f"above Ngood_min bound of {cut.Ngood_min}",
)
)
self.logger.body(
self.f.get_percent_cut_str(
cut.questionable_flag,
questionable_percent_cut,
flagged_as=f"questionable (not masked with control light curve cut flags but Nclip > 0)",
)
)
self.logger.body(self.f.get_percent_cut_str(cut.flag, percent_cut))
self.f.add_controls_cut_section(
cut,
x2_percent_cut,
snr_percent_cut,
Nclip_percent_cut,
Ngood_percent_cut,
questionable_percent_cut,
percent_cut,
)
if plot:
if self.p is None:
raise RuntimeError("Output plots (self.p) cannot be None")
self.p.plot_cut(self.sn, cut.flag, title=ControlLightCurveCut.name())
def apply_badday_cut(
self, cut: BadDayCut | None, previous_flags, plot: bool = False
):
if cut is None:
return
self.logger.step(
f"Applying bad day cut (averaging) with MJD bin size of {cut.mjd_bin_size} days ({cut})"
)
if self.sn is None:
raise RuntimeError("Supernova (self.sn) cannot be None")
self.avg_sn, percent_cut = self.sn.apply_badday_cut(
cut, previous_flags, flux2mag_sigmalimit=self.flux2mag_sigmalimit
)
self.logger.success()
self.logger.body(
f"Percent of binned SN light curve flagged as bad ({hex(cut.flag)}): {percent_cut:0.2f}%"
)
if self.f is None:
raise RuntimeError("Output README file (self.f) cannot be None")
self.f.add_badday_cut_section(cut, percent_cut)
if plot:
if self.p is None:
raise RuntimeError("Output plots (self.p) cannot be None")
self.p.plot_cut(self.avg_sn, cut.flag, title=BadDayCut.name())
self.p.plot_averaged_SN(
self.avg_sn, cut.flag, plot_controls=True, plot_flagged=False
)
def apply_custom_cut(self, cut: CustomCut, plot: bool = False):
self.logger.step(f"Applying custom cut ({cut})")
if self.sn is None:
raise RuntimeError("Supernova (self.sn) cannot be None")
percent_cut = self.sn.apply_cut(cut)
self.logger.success()
self.logger.body(
f"Total percent of SN light curve flagged with {hex(cut.flag)}: {percent_cut:0.2f}%"
)
if self.f is None:
raise RuntimeError("Output README file (self.f) cannot be None")
self.f.add_custom_cut_section(cut, percent_cut)
if plot:
if self.p is None:
raise RuntimeError("Output plots (self.p) cannot be None")
self.p.plot_cut(self.sn, cut.flag, title=cut.name())
def clean_lcs(
self,
tnsname: str,
mjd0,
filt: str,
apply_uncert_est_function: Callable,
num_controls: int = 0,
apply_template_correction: bool = False,
plot: bool = False,
):
self.logger.subheader(f"Cleaning filter: '{filt}'")
# load the SN and control light curves
self.sn = Supernova(self.colnames, tnsname=tnsname, mjd0=mjd0, filt=filt)
try:
self.sn.load_all(self.input_dir, num_controls=num_controls)
except Exception as e:
raise RuntimeError(f"Could not load light curves: {str(e)}")
# prepare the light curves for cleaning
print()
self.sn.prep_for_cleaning(verbose=True)
if plot:
# initialize PDF of diagnostic plots
self.p = PlotPdf(f"{self.output_dir}/{tnsname}", tnsname, filt=filt)
# plot original SN light curve and control light curves
self.p.plot_SN(self.sn, plot_controls=True, plot_template_changes=True)
self.p.plot_all_controls(self.sn, include_sn=True)
if self.cut_list is None:
raise RuntimeError("CutList (self.cut_list) cannot be None")
# template correction
if apply_template_correction:
self.apply_template_correction()
# uncertainty cut
self.apply_uncert_cut(self.cut_list.get(UncertaintyCut.name()), plot=plot)
# true uncertainties estimation
_, uncert_est_info_row = self.check_uncert_est(
self.cut_list.get(UncertaintyEstimation.name()),
apply_function=apply_uncert_est_function,
plot=plot,
)
self.uncert_est_info.add_row(uncert_est_info_row)
# chi-square cut
x2_info_row = self.apply_x2_cut(
self.cut_list.get(ChiSquareCut.name()), plot=plot
)
if x2_info_row is not None and self.cut_list.has(ChiSquareCut.name()):
self.x2_cut_info.add_row(x2_info_row)
# control light curve cut
self.apply_controls_cut(
self.cut_list.get(ControlLightCurveCut.name()),
previous_flags=self.cut_list.get_previous_flags(
ControlLightCurveCut.name()
),
plot=plot,
)
# custom cuts
custom_cuts = self.cut_list.get_custom_cuts()
for cut in custom_cuts.values():
self.apply_custom_cut(cut, plot=plot)
# plot the cleaned light curves so far
previous_flags = self.cut_list.get_previous_flags(BadDayCut.name())
if plot and previous_flags > 0:
print()
self.p.plot_cut(self.sn, previous_flags, title="All previous cuts")
self.p.plot_cleaned_SN(
self.sn, previous_flags, plot_controls=True, plot_flagged=False
)
# bad day cut (averaging)
self.apply_badday_cut(
self.cut_list.get(BadDayCut.name()),
previous_flags=previous_flags,
plot=plot,
)
# save cleaned SN and control light curves
self.sn.save_all(self.output_dir, overwrite=self.overwrite)
if self.cut_list.has(BadDayCut.name()):
if self.avg_sn is None:
raise RuntimeError("Averaged supernova (self.avg_sn) cannot be None")
# save averaged SN and control light curves
self.avg_sn.save_all(self.output_dir, overwrite=self.overwrite)
if self.cut_list.has(UncertaintyEstimation.name()):
# save uncertainty estimation table
self.uncert_est_info.save()
if self.cut_list.has(ChiSquareCut.name()):
# save chi-square cut table
self.x2_cut_info.save()
# save the SN info table
self.sninfo.save()
if plot:
# save the PDF of diagnostic plots
self.p.save_pdf()
def loop(
self,
tnsnames: List[str],
apply_uncert_est_function: Callable,
num_controls: int = 0,
mjd0=None,
filts: Optional[List[str]] = None,
cut_list: Optional[CutList] = None,
apply_template_correction: bool = False,
plot: bool = False,
):
self.cut_list = cut_list
l = len(tnsnames)
for obj_index in range(l):
tnsname = tnsnames[obj_index]
self.logger.header(
f"Cleaning light curves for {tnsname} ({obj_index+1}/{l})"
)
make_dir_if_not_exists(f"{output_dir}/{tnsname}")
self.f = OutputReadMe(
self.output_dir, tnsname, cut_list, num_controls=num_controls
)
if (
mjd0 is None
and cut_list.has(ChiSquareCut.name())
and cut_list.get(ChiSquareCut.name()).use_pre_mjd0_lc
):
use_disc_date_buffer = True
mjd0 = resolve_mjd0(
tnsname,
self.sninfo,
self.credentials,
use_disc_date_buffer=use_disc_date_buffer,
)
if mjd0 is not None:
self.logger.info(
f"Setting MJD0 to TNS discovery date{f' - {DISC_DATE_BUFFER}' if use_disc_date_buffer else ''}:: {mjd0} MJD",
newline=True,
)
self.sninfo.update_row(tnsname, mjd0=mjd0)
else:
self.logger.info(f"Setting MJD0: {mjd0} MJD", newline=True)
if filts is None:
self.logger.loading(
"Searching for filters in input directory", newline=True
)
filts = find_all_filts(self.input_dir, tnsname)
self.logger.success(f"Filters found: {filts}")
# TODO: fix
# allowed_presets = get_allowed_presets(config)
# check_filts_against_preset(self.colnames.preset, allowed_presets, filts)
for filt in filts:
self.f.add_filter_section(filt)
self.clean_lcs(
tnsname,
mjd0,
filt,
apply_uncert_est_function,
num_controls=num_controls,
apply_template_correction=apply_template_correction,
plot=plot,
)
def parse_config_cuts(args, config, colnames):
logger = CustomLogger()
cut_list = CutList()
if args.custom_cuts:
config_custom_cuts = get_config_custom_cuts(config)
logger.info(f"Procedures parsed from config:", newline=True)
# always check true uncertainties estimation, but will only apply if args.true_uncert_est
temp_x2_max_value = float(config["uncert_est"]["temp_x2_max_value"])
logger.listitem(
f"True uncertainties estimation check (using temporary chi-square cut at {temp_x2_max_value})"
)
uncert_est = UncertaintyEstimation(
temp_x2_max_value,
hexstring_to_int(config["uncert_cut"]["flag"]),
)
cut_list.add(uncert_est)
if args.uncert_cut:
uncert_cut = UncertaintyCut(
colnames.dflux,
flag=hexstring_to_int(config["uncert_cut"]["flag"]),
max_value=float(config["uncert_cut"]["max_value"]),
)
cut_list.add(uncert_cut)
logger.listitem(f"{uncert_cut}")
if args.x2_cut:
use_pre_mjd0_lc = parse_config_str(config["x2_cut"]["use_pre_mjd0_lc"])