Repository navigation
Expand file tree
/
Copy pathdata_processing.py
More file actions
1413 lines (1084 loc) · 43.7 KB
/
Copy pathdata_processing.py
File metadata and controls
1413 lines (1084 loc) · 43.7 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
from typing import Dict, List, Union
from pathlib import Path
from argparse import ArgumentParser
import glob
from itertools import chain
from functools import lru_cache
from astropy.table import vstack, Table
import astropy.constants as c
import astropy.units as u
import os
import sys
import pickle
import numpy as np
import pandas as pd
import sncosmo
import subprocess
import shlex
from iminuit import Minuit
from iminuit.cost import LeastSquares
import kernel as kern
import time
import shutil
import random
from scipy.interpolate import UnivariateSpline
from scipy.integrate import simpson
def Am_to_Hz(wl):
"""
Convert Ångström to Hertz
Parameters
----------
wl : array
Wave length array
Returns
-------
Array converted to frequency
"""
return c.c.value / (wl * 1e-10)
def generate_plasticc_lcs(object_class, field):
"""
PLAsTiCC lightcurve generator to the correct format.
Apply MWEBV correction to flux and fluxerr
Parameters
----------
object_class: str
Name of the PLAsTiCC class to compute
field: str
LSST cadence to use : 'wfd' or 'ddf'
Yields
------
table : astropytable
Formatted lightcurve table. Ensures that the minimum
number of points from kernel.py is respected
"""
meta = pd.read_csv(f'{kern.plasticc_path}/plasticc_test_metadata.csv.gz', index_col='object_id')
meta = meta[meta['true_target'] == object_class]
if field == 'ddf':
file_indices = ['01']
elif field == 'wfd':
file_indices = [f'{i:02d}' for i in range(2, 12)]
elif field == 'all':
file_indices = [f'{i:02d}' for i in range(1, 12)]
for file_index in file_indices:
file_name = f'{kern.plasticc_path}/plasticc_test_lightcurves_{file_index}.csv.gz'
df = pd.read_csv(file_name, index_col='object_id')
for object_id, table in df.groupby('object_id'):
if object_id not in meta.index:
continue
assert np.all(np.diff(table['mjd']) >= 0), 'Light curve must be time-sorted'
table = Table.from_pandas(table)
table.rename_columns(['mjd', 'flux', 'flux_err'], ['MJD', 'FLUXCAL', 'FLUXCALERR'])
table['BAND'] = kern.PASSBANDS[table['passband']]
table.meta = meta.loc[object_id].to_dict()
table.meta['SIM_PEAKMJD'] = table.meta['true_peakmjd']
table.meta['SNID'] = object_id
detections = table[table['detected_bool'] == 1]
det_per_band = dict(zip(*np.unique(detections["BAND"], return_counts=True)))
if any(det_per_band.get(band, 0) < min_det for band, min_det in kern.min_det_per_band.items()):
continue
if (table.meta['SIM_PEAKMJD'] < detections['MJD'][0]
or table.meta['SIM_PEAKMJD'] > detections['MJD'][-1]):
continue
yield table
def generate_plasticc_YSE(object_class, method):
"""
YSE lightcurve generator to the correct format
Parameters
----------
object_class: str
Name of the YSE class to compute
method : str
Specify the future method of feature extraction to be
used on the data. Impact the minimum number of point per band.
Yields
------
table : astropytable
Formatted lightcurve table. Ensures that the minimum
number of points from kernel.py is respected
"""
meta = pd.read_csv(f'{kern.YSE_path}/YSE_baseline_plasticc_meta.csv', index_col='object_id')
meta = meta[meta['true_target'] == object_class]
file_name = f'{kern.YSE_path}/YSE_baseline_plasticc_data.csv'
df = pd.read_csv(file_name, index_col='object_id')
for object_id, table in df.groupby('object_id'):
if object_id not in meta.index:
continue
assert np.all(np.diff(table['mjd']) >= 0), 'Light curve must be time-sorted'
table = Table.from_pandas(table)
table.rename_columns(['mjd', 'flux', 'flux_err'], ['MJD', 'FLUXCAL', 'FLUXCALERR'])
table.meta = meta.loc[object_id].to_dict()
table.meta['SIM_PEAKMJD'] = table.meta['true_peakmjd']
table.meta['SNID'] = object_id
table2 = table.copy()
for col in ['BAND', 'passband']:
for band in ['g', 'r']:
table2[col][table2[col]==f'PS{band}'] = band + ' '
table2 = table2[table2['BAND']!= 'PSi']
if method == 'bazin':
table = table2
detections = table2[table2['detected_bool'] == 1]
det_per_band = dict(zip(*np.unique(detections["BAND"], return_counts=True)))
if any(det_per_band.get(band, 0) < min_det for band, min_det in kern.min_det_per_band_YSE.items()):
continue
if (table2.meta['SIM_PEAKMJD'] < detections['MJD'][0]
or table2.meta['SIM_PEAKMJD'] > detections['MJD'][-1]):
continue
yield table
def format_plasticc(object_class, max_n, field):
"""
Use plasticc generator and aggregate
the light curves
Parameters
----------
object_class: str
Name of the PLAsTiCC class to compute
max_n: int
Maximum number of light curves to aggregate.
field: str
LSST cadence to use : 'wfd' or 'ddf'
Returns
-------
lcs : list
List of preprocessed and formatted astropy tables.
"""
lcs = []
for idx, lc in zip(range(max_n), generate_plasticc_lcs(object_class, field)):
lcs.append(lc)
# Save preprocessed data as pkl for later use
if not os.path.exists("data_plasticc"):
os.mkdir("data_plasticc")
if not os.path.exists("data_plasticc/formatted"):
os.mkdir("data_plasticc/formatted")
file = f"data_plasticc/formatted/{kern.PLASTICC_TARGET_INV.get(object_class)}_{field}.pkl"
with open(file, "wb") as handle:
pickle.dump(lcs, handle)
def format_YSE(object_class, max_n, field):
"""
Use YSE generator and aggregate
the light curves
Parameters
----------
object_class: str
Name of the PLAsTiCC class to compute
max_n: int
Maximum number of light curves to aggregate.
field: str
fake LSST cadence for file naming only.
Returns
-------
lcs : list
List of preprocessed and formatted astropy tables.
"""
# Save preprocessed data as pkl for later use
if not os.path.exists("data_YSE"):
os.mkdir("data_YSE")
if not os.path.exists("data_YSE/formatted"):
os.mkdir("data_YSE/formatted")
lcs_rainbow, lcs_bazin = [], []
for idx, lc in zip(range(max_n), generate_plasticc_YSE(object_class, 'rainbow')):
lcs_rainbow.append(lc)
for idx, lc in zip(range(max_n), generate_plasticc_YSE(object_class, 'bazin')):
lcs_bazin.append(lc)
for fraction in kern.YSE_fractions:
sub_lcs_rainbow, sub_lcs_bazin = [], []
for idx in range(len(lcs_rainbow)):
table_rainbow, table_bazin = lcs_rainbow[idx], lcs_bazin[idx]
sub_table_rainbow, sub_table_bazin = table_rainbow[4:], table_bazin[4:],
row_index = np.sort(np.random.choice(sub_table_rainbow['Unnamed: 0'], size = round(len(sub_table_rainbow) * fraction), replace=False))
mask_rainbow = [True]*4 + [i in row_index for i in sub_table_rainbow['Unnamed: 0']]
mask_bazin = [True]*4 + [i in row_index for i in sub_table_bazin['Unnamed: 0']]
detections = table_bazin[mask_bazin][table_bazin[mask_bazin]['detected_bool'] == 1]
det_per_band = dict(zip(*np.unique(detections["BAND"], return_counts=True)))
reject = any(det_per_band.get(band, 0) < min_det for band, min_det in kern.min_det_per_band_YSE.items())
if not reject:
sub_lcs_rainbow.append(table_rainbow[mask_rainbow])
sub_lcs_bazin.append(table_bazin[mask_bazin])
file_rainbow = f"data_YSE/formatted/{kern.PLASTICC_TARGET_INV.get(object_class)}_{field}_f{str(round(100*fraction))}_rainbow.pkl"
file_bazin = f"data_YSE/formatted/{kern.PLASTICC_TARGET_INV.get(object_class)}_{field}_f{str(round(100*fraction))}_bazin.pkl"
with open(file_rainbow, "wb") as handle:
pickle.dump(sub_lcs_rainbow, handle)
with open(file_bazin, "wb") as handle:
pickle.dump(sub_lcs_bazin, handle)
def preprocess(dataset, object_class, field):
"""
Normalize each light curve of the dataset.
Saves a pickle file of the preprocessed data.
Parameters
----------
database: str
'plasticc' or 'YSE'
object_class: str
Name of the PLAsTiCC class to compute
field: str
LSST cadence to use : 'wfd' or 'ddf' (always 'wfd' for YSE)
Returns
-------
list
List of normalized astropy tables
"""
path_to_use = kern.main_path + f'/data_{dataset}/formatted/{object_class}_{field}.pkl'
with open(path_to_use, "rb") as handle:
lcs = pickle.load(handle)
new_lcs = [normalize(lc) for lc in lcs]
# Save preprocessed data as pkl for later use
if not os.path.exists(f"data_{dataset}"):
os.mkdir(f"data_{dataset}")
if not os.path.exists(f"data_{dataset}/preprocessed"):
os.mkdir(f"data_{dataset}/preprocessed")
file = f"data_{dataset}/preprocessed/{object_class}_{field}"
with open(f'{file}.pkl' , "wb") as handle:
pickle.dump(new_lcs, handle)
return new_lcs
def normalize(lc):
"""
Apply normalization transformation to
an astropy table light curve
Parameters
----------
lc: astropy table
Light curve
Returns
-------
lc : astropy table
Normalized light curve with :
- Fluxes divided by max r band flux
- Time 0 shifted by time of max r band flux
- Added columns before normalization : max_flux, max_flux_time
"""
normband = lc[(lc["BAND"] == "r ") | (lc["BAND"] == "PSr")]
maxi = normband["FLUXCAL"].max()
lc["max_flux"] = maxi
t_maxi = normband["MJD"][normband["FLUXCAL"].argmax()]
lc["max_flux_time"] = t_maxi
lc["FLUXCAL"] = lc["FLUXCAL"] / maxi
lc["FLUXCALERR"] = lc["FLUXCALERR"] / maxi
lc["MJD"] = lc["MJD"] - t_maxi
return lc
def Fbaz(t, a, t0, tfall, trise):
"""
Compute flux using Bazin with
baseline fixed to 0.
Parameters
----------
t: array
Time value of data points.
a: float
Amplitude.
t0: float
Time phase (related to peak time by : tpeak = t0 + trise × ln(tfall/trise − 1))
tfall: float
Falling factor
trise: float
Rising factor
Returns:
--------
Computed flux at each time t.
"""
return a * np.exp(-(t - t0) / tfall) / (1 + np.exp((t - t0) / trise))
def Tsig(t, Tmin, dT, ksig, t0):
"""
Compute temperature using sigmoid.
Parameters
----------
t: array
Time value of data points.
Tmin: float
Minimum temperature to reach at the end of the sigmoid
dT: float
Difference between beginning and end temperature of the sigmoid.
ksig: float
Slope parameter of the sigmoid.
t0: float
Bazin time value related to time of maximum flux.
Returns:
--------
Computed temperature at each time t.
"""
return Tmin + dT / (1 + np.exp((t - t0) / ksig))
def planck_nu(nu, T):
"""
Compute blackbody intensity from temperature and frequency.
Parameters
----------
nu: array
Frequency for which to compute intensity.
T: array
Temperature values at different times.
Returns:
--------
Computed spectral radiance.
"""
return (2 * c.h.value / c.c.value**2) * nu**3 / np.expm1(c.h.value * nu / (c.k_B.value * T))
@lru_cache(maxsize=64)
def planck_passband_spline(passband, T_min=1e2, T_max=1e6, T_steps=10_000):
"""
Compute spline of passband intensity for the range of temperatures.
Parameters
----------
passband: string
Name of the passband
T_min: float
Minimum temperature to consider
T_max: float
Maximum temperature to consider
T_steps: int
Step between temperatures to consider
Returns
-------
scipy.iterpolate.UnivariateSpline
Spline of the passband intensity versus temperature
"""
passband = sncosmo.get_bandpass(passband)
nu = (c.c / (passband.wave * u.AA)).to_value(u.Hz)
trans = passband.trans # photon counter transmission
T = np.logspace(np.log10(T_min), np.log10(T_max), T_steps)
black_body_integral = simpson(x=nu, y=planck_nu(nu, T[:, None]) * trans / nu, axis=-1)
transmission_integral = simpson(x=nu, y=trans / nu)
return UnivariateSpline(x=T, y=black_body_integral / transmission_integral, s=0, k=3, ext='raise')
def planck_passband(passband, T):
"""
Compute spectral radiance from temperature and passband.
Parameters
----------
passband: array of strings
Names of passband for which to compute intensity.
T: array of floats
Temperature values at different times.
Returns:
--------
array of floats
Computed intensity.
"""
passband, T = np.broadcast_arrays(passband, T)
# Speed up computation if only a single value is passed
if passband.size == 1:
return planck_passband_spline(passband.item())(T)
unique_passbandes, indices = np.unique(passband, return_inverse=True)
output = np.zeros_like(passband, dtype=float)
for index, passband in enumerate(unique_passbandes):
T_passband = T[indices == index]
spline = planck_passband_spline(passband)
output[indices == index] = spline(T_passband)
return output
def planck(nu, T):
"""
Compute intensity from temperature and frequency / passband.
Parameters
----------
nu: array of floats or strings
Frequencies or passband names for which to compute intensity.
T: array of floats
Temperature values at different times.
Returns:
--------
array of floats
Computed intensity.
"""
integrate = False
if np.any(nu < 0):
nu = np.vectorize(sncosmoband_convert.get)(nu)
integrate = True
nu = np.asarray(nu)
if integrate:
return planck_passband(nu, T)
return planck_nu(nu, T)
''' OLD Function used taking into account redshift z
#######################################################
# Flux of lightcurves at any time at any frequency
def Fnuz(x, a, t0, tfall, trise, Tmin, dT, ksig, z):
t, nu = x
T = Tsig(t, Tmin, dT, ksig, t0) * (1+z)
Fbol = Fbaz(t, a, t0, tfall, trise)
amplitude = 1e15
return np.pi / c.sigma_sb.value * Fbol * planckz(nu, T, z) / T**4 * amplitude
def planckz(nu, T, z):
integrate = False
if np.any(nu < 0):
nu = np.vectorize(sncosmoband_convert.get)(nu)
integrate = True
nu = np.asarray(nu)
return planck_passbandz(nu, T, z)
def planck_passbandz(passband, T, z):
passband, T = np.broadcast_arrays(passband, T)
# Speed up computation if only a single value is passed
if passband.size == 1:
return planck_passband_splinez(passband.item(), z)(T)
unique_passbandes, indices = np.unique(passband, return_inverse=True)
output = np.zeros_like(passband, dtype=float)
for index, passband in enumerate(unique_passbandes):
T_passband = T[indices == index]
spline = planck_passband_splinez(passband, z)
output[indices == index] = spline(T_passband)
return output
def planck_passband_splinez(passband, z, T_min=1e2, T_max=1e6, T_steps=10_000):
passband = sncosmo.get_bandpass(passband)
nu = (c.c / (passband.wave * u.AA)).to_value(u.Hz)
nu = nu * (1+z)
trans = passband.trans # photon counter transmission
T = np.logspace(np.log10(T_min), np.log10(T_max), T_steps)
black_body_integral = simpson(x=nu, y=planck_nu(nu, T[:, None]) * trans / nu, axis=-1)
transmission_integral = simpson(x=nu, y=trans / nu)
return UnivariateSpline(x=T, y=black_body_integral / transmission_integral, s=0, k=3, ext='raise')
##################################################################################
'''
# Flux of lightcurves at any time at any frequency
def Fnu(x, a, t0, tfall, trise, Tmin, dT, ksig):
"""
Complete fitting function. Used to compute flux at any
frequency at any time (scaled by an arbitrary amplitude term).
Parameters
----------
x: ndarray
Array of pair time and frequency from which to compute flux.
a: float
Bazin amplitude.
t0: float
Bazin time value related to time of maximum flux.
tfall: float
Bazin value related to length of the falling part of the slope.
trise: float
Bazin value related to length of the rising part slope.
Tmin: float
Minimum temperature to reach at the end of the sigmoid
dT: float
Difference between beginning and end temperature of the sigmoid.
ksig: float
Slope parameter of the sigmoid.
Returns:
--------
Computed flux at any frequency and at any time (scaled by
an arbitrary amplitude term).
"""
t, nu = x
T = Tsig(t, Tmin, dT, ksig, t0)
Fbol = Fbaz(t, a, t0, tfall, trise)
amplitude = 1e15
return np.pi / c.sigma_sb.value * Fbol * planck(nu, T) / T**4 * amplitude
def perform_fit_rainbow(obj):
"""
Find best fit parameters for rainbow method using iminuit.
Adds additionnal values useful for later ML.
Parameters
----------
obj: astropy table
Single object table
Returns
-------
Dict of best fitted values.
And list of values:
fit_error: float
Error between fit and true data
max_flux: float
Maximum observed flux before normalization
max_flux_time: float
Time of maximum observed flux
peak: float
Meta data of ELASTiCC, true time of maximum flux
nb_points: int
Total number of measurements in all bands
"""
global_flux = obj["FLUXCAL"]
global_fluxerr = obj["FLUXCALERR"]
global_nu = obj["NU"]
global_mjd = obj["MJD"]
parameters_dict = {
"a": global_flux.max(),
"t0": global_mjd[np.argmax(global_flux)],
"tfall": 30,
"trise": -5,
"Tmin": 4000,
"dT": 7000,
"ksig": 4,
}
least_squares = LeastSquares(
np.array([global_mjd, global_nu]), global_flux, global_fluxerr, Fnu
)
fit = Minuit(
least_squares,
**parameters_dict,
)
fit.limits['Tmin'] = (100, 100000)
fit.limits['dT'] = (0, 100000)
fit.limits['t0'] = (-1000, 1000)
fit.limits['a'] = (0.1, 1000)
fit.limits['ksig'] = (1.5, 300)
fit.limits['trise'] = (-100, -0.5)
fit.limits['tfall'] = (0.5, 500)
fit.migrad()
max_flux = obj["max_flux"][0]
max_time = obj["max_flux_time"][0]
fit_error = fit.fval
peak = obj.meta["SIM_PEAKMJD"]
nb_points = len(global_mjd)
objid = obj.meta["SNID"]
additionnal = [fit_error, max_flux, max_time, peak, nb_points, objid]
return fit.values, additionnal
def perform_fit_bazin(obj, bands):
"""
Find best fit parameters for Bazin method using iminuit.
Adds additionnal values useful for later ML.
Parameters
----------
obj: astropy table
Single object table
Returns
-------
list of the form [[param_g, extra_g], [param_r, extra_r], [param_i, extra_i]]
With param_* : best fitted value for each passband.
And extra_* : list of additionnal values for each passband:
fit_error: float
Error between fit and true data
max_flux: float
Maximum observed flux before normalization
max_flux_time: float
Time of maximum observed flux
peak: float
Meta data of ELASTiCC, true time of maximum flux
nb_points: int
Number of measurements
"""
all_parameters = []
for band in bands:
lc = obj[obj["BAND"] == band]
global_flux = lc["FLUXCAL"]
global_fluxerr = lc["FLUXCALERR"]
global_mjd = lc["MJD"]
parameters_dict = {
"a": global_flux.max(),
"t0": global_mjd[np.argmax(global_flux)],
"tfall": 30,
"trise": -5,
}
least_squares = LeastSquares(global_mjd, global_flux, global_fluxerr, Fbaz)
fit = Minuit(
least_squares,
**parameters_dict,
)
fit.limits['t0'] = (-1000, 1000)
fit.limits['a'] = (0.1, 1000)
fit.limits['trise'] = (-100, -0.5)
fit.limits['tfall'] = (0.5, 500)
fit.migrad()
max_flux = lc["max_flux"][0]
max_time = lc["max_flux_time"][0]
fit_error = fit.fval
peak = lc.meta["SIM_PEAKMJD"]
nb_points = len(global_mjd)
objid = lc.meta['SNID']
additionnal = [fit_error, nb_points, max_flux, max_time, peak, objid]
all_parameters.append([fit.values, additionnal])
return all_parameters
def extract_rainbow(lcs, object_class, split, database, band_wavelength):
"""
Apply perform_fit_rainbow to each object.
Build and save a parameter dataframe.
Parameters
----------
lcs: list
List of astropy table lightcurves
object_class: str
Name of the ELASTiCC class to compute
split: int
Number of the core computing the extraction
band_wavelength: str
'effective' to use only the effective
wavelength of the filter. Uses "freq_dic" defined below
'integrate' to use the filter wavelength
profile as provided in sncosmo. Uses "sncosmoband_convert_temporary"
and "sncosmoband_convert" because iminuit can only use numerical
values as input.
"""
all_param = []
for obj in lcs:
if band_wavelength=='effective':
obj["NU"] = np.vectorize(freq_dic.get)(list(obj["BAND"]))
elif band_wavelength=='integrate':
obj["NU"] = np.vectorize(sncosmoband_convert_temporary.get)(obj["BAND"])
extraction = perform_fit_rainbow(obj)
all_param.append(list(extraction[0].to_dict().values()) + extraction[1])
features = pd.DataFrame(
columns=Fnu.__code__.co_varnames[1:8] + ("error", "max_flux", "max_time", "true_peak", "nb_points", "object_id"),
data=all_param,
)
features.to_parquet(f"data_{database}/features/rainbow_{band_wavelength}/{object_class}/features_{object_class}_{split}.parquet")
def extract_bazin(lcs, object_class, split, database):
"""
Apply perform_fit_bazin to each object.
Build and save a parameter dataframe.
Parameters
----------
lcs: list
List of astropy table lightcurves
object_class: str
Name of the ELASTiCC class to compute
split: int
Number of the core computing the extraction
"""
bands = ["g ", "r "]
if database != "YSE" :
bands += "i "
all_param = []
name_param = []
for idx, obj in enumerate(lcs):
param = perform_fit_bazin(obj, bands)
obj_param = []
for idx_band, band in enumerate([i[0] for i in bands]):
if idx == 0:
baz_name = [x + f"_{band}" for x in list(Fbaz.__code__.co_varnames[1:]) + ["error", "nb_points"]]
name_param.append(baz_name)
obj_param.append(
list(param[idx_band][0].to_dict().values()) + [param[idx_band][1][0]] + [param[idx_band][1][1]]
)
flat_obj_param = [x for xs in obj_param for x in xs] + param[0][1][
2:
]
all_param.append(flat_obj_param)
flat_name_param = [x for xs in name_param for x in xs] + [
"max_flux",
"max_time",
"true_peak",
"object_id"
]
features = pd.DataFrame(columns=flat_name_param, data=all_param)
features.to_parquet(f"data_{database}/features/bazin/{object_class}/features_{object_class}_{split}.parquet")
def train_test_cutting_generator_YSE_rainbow(sub_formatted, formatted_test):
"""
Function used once test dataset has been generated for YSE dataset
Use every point non selected in test, including PS-i band !!
Parameters
----------
sub_formatted: list
List of astropy table lightcurves
formatted_test: list
List of testing sample astropy table
Yields
------
train, test
astropy table, astropy table
"""
for idx in range(len(sub_formatted)):
obj, bazin_test = sub_formatted[idx], formatted_test[idx]
obj_train = obj[[not i in (bazin_test['Unnamed: 0']) for i in obj['Unnamed: 0']]]
obj_test = obj[[i in (bazin_test['Unnamed: 0']) for i in obj['Unnamed: 0']]]
yield obj_train, obj_test
def train_test_cutting_generator(formatted, bands = ['g ', 'r ', 'i '], mdpb=kern.min_det_per_band,\
mtot=sum(list(kern.min_det_per_band.values())), seed=kern.default_seed):
"""
Remove random windows of detected points.
Use removed points to create testing dataset.
Use remaining points to create training dataset
Ensures that the training datasets has enough points.
Parameters
----------
formatted: list
List of astropy table lightcurves
bands: list
Name of the passbands used in the dataset
Default is ['g ', 'r ', 'i ']
mdpb: dict
Minimum detection per passband cut condition.
Default value is defined in kernel
mtot: int
Total number of points required throught the passbands
Defaut is the sum of the minimum number of points
for each band as defined kernel
seed: int
Seed used to randomly generate the bins
Yields
------
train, test
astropy table, astropy table
"""
random.seed(seed)
for obj in formatted:
all_bands_train, all_bands_test = [], []
mask = [False] * len(obj)
for band in bands:
mask = mask | (obj['BAND'] == band)
sub_obj = obj[mask]
bins = np.arange(sub_obj['MJD'].min(), sub_obj['MJD'].max(), kern.point_cut_window)
valid = []
for idx in range(len(bins)-1):
if ((sub_obj['MJD'] >= bins[idx]) &\
(sub_obj['MJD'] <= bins[idx + 1]) &\
(sub_obj['detected_bool'] == 1)).sum()>0:
valid.append(idx)
if len(valid)<=2:
continue
chosen = random.sample(valid, 2)
mask = (((sub_obj['MJD']>=bins[chosen[0]]) &\
(sub_obj['MJD']<bins[chosen[0] + 1])) |\
((sub_obj['MJD']>=bins[chosen[1]]) &\
(sub_obj['MJD']<bins[chosen[1] + 1])))
invalid = False
for band in bands:
pointperband = len(sub_obj[(~mask) & (sub_obj['BAND'] == band)])
if pointperband < mdpb.get(band):
invalid = True
if len(sub_obj[~mask]) < mtot:
invalid = True
if invalid:
continue
yield sub_obj[~mask], sub_obj[mask]
def train_test_rising_cutting_generator(prepro, bands = ['g ', 'r ', 'i '], mdpb=kern.min_det_per_band):
"""
Remove all points after true peak.
Use removed points to create testing dataset.
Use remaining points to create training dataset
Ensures that the training datasets has enough points.
Parameters
----------
prepro: list
List of astropy table lightcurves
bands: list
Name of the passbands used in the dataset
Default is ['g ', 'r ', 'i ']
mdpb: dict
Minimum detection per passband cut condition.
Default value is defined in kernel
Yields
------
train, test
astropy table, astropy table
"""
for obj in prepro:
band_mask = [False] * len(obj)
for band in bands:
band_mask = band_mask | (obj['BAND'] == band)
obj = obj[band_mask]
invalid = False
all_bands_train, all_bands_test = [], []
threshold = obj.meta['true_peakmjd']
detec_before = (obj[obj['MJD'] < threshold]['detected_bool']).sum()
if detec_before == 0:
continue
for band in bands:
if invalid:
continue
sub_obj = obj[obj['BAND'] == band]
mask = sub_obj['MJD'] > threshold
if ((~mask).sum() < mdpb.get(band)) |\
((mask).sum() < 1):
invalid = True
continue
all_bands_train.append(sub_obj[~mask])
all_bands_test.append(sub_obj[mask])
if invalid:
continue
yield vstack(all_bands_train), vstack(all_bands_test)
def check_inputs(database, field):
"""
Verify that inputs correspond to possible inputs
Parameters