-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtwins_embedding.py
1823 lines (1475 loc) · 66.5 KB
/
twins_embedding.py
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 astropy import table
from hashlib import md5
from idrtools import Dataset, math
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap
from matplotlib.gridspec import GridSpec
from scipy.optimize import minimize
from sklearn.manifold import Isomap
import extinction
import numpy as np
import os
import pickle
import sys
from tqdm.autonotebook import tqdm
from settings import default_settings
from manifold_gp import ManifoldGaussianProcess
import utils
import specind
class TwinsEmbeddingException(Exception):
pass
class TwinsEmbeddingAnalysis:
def __init__(self, **kwargs):
"""Load the dataset and setup the analysis"""
# Update the default settings with any arguments that came in from kwargs.
self.settings = dict(default_settings, **kwargs)
# Set the default matplotlib figure size from the settings.
import matplotlib as mpl
for key, value in self.settings['matplotlib_settings'].items():
mpl.rcParams[key] = value
def run_analysis(self):
"""Run the full analysis"""
self.load_dataset()
self.print_verbose("Estimating the spectra at maximum light...")
self.model_differential_evolution()
if self.settings['test_no_interpolation']:
# As a test, use the spectrum near maximum light directly rather than doing
# interpolation.
self.print_verbose("TEST: Using the spectra closest to maximum light "
"directly, without the time evolution model...")
self.maximum_flux = self.flux[self.center_mask]
self.maximum_fluxerr = self.fluxerr[self.center_mask]
self.print_verbose("Reading between the lines...")
self.read_between_the_lines()
self.print_verbose("Building masks...")
self.build_masks()
self.print_verbose("Generating the manifold learning embedding...")
self.embedding = self.generate_embedding()
self.print_verbose("Loading other indicators of diversity...")
self.load_indicators()
self.print_verbose("Fitting RBTL Twins Manifold GP...")
self.residuals_rbtl_gp = self.fit_gp_magnitude_residuals()
self.print_verbose("Fitting SALT2 Twins Manifold GP...")
self.residuals_salt_gp = self.fit_gp_magnitude_residuals('salt_raw')
self.print_verbose("Calculating SALT2 magnitude residuals...")
self.residuals_salt = self.fit_salt_magnitude_residuals()
self.print_verbose("Done!")
def load_dataset(self):
"""Load the dataset"""
self.print_verbose("Loading dataset...")
self.print_verbose(" IDR: %s" % self.settings['idr'])
self.print_verbose(
" Phase range: [%.1f, %.1f] days"
% (-self.settings['phase_range'], self.settings['phase_range'])
)
self.print_verbose(" Bin velocity: %.1f" % self.settings['bin_velocity'])
self.dataset = Dataset.from_idr(
os.path.join(self.settings['idr_directory'], self.settings['idr']),
load_both_headers=True
)
# Do/load all of the SALT2 fits for this dataset
self.dataset.load_salt_fits()
all_raw_spec = []
center_mask = []
self.attrition_enough_spectra = 0
self.attrition_total_spectra = 0
self.attrition_salt_daymax = 0
self.attrition_range = 0
self.attrition_explicit = 0
self.attrition_usable = 0
for supernova in tqdm(self.dataset.targets):
# Require at least 5 spectra
if len(supernova.spectra) < 5:
self.print_verbose(
"Cutting %s, not enough spectra to guarantee a "
"good LC fit" % supernova,
minimum_verbosity=2,
)
continue
self.attrition_enough_spectra += 1
self.attrition_total_spectra += len(supernova.spectra)
# Require t0 measured to better than 1 day uncertainty.
daymax_err = supernova.salt_fit['t0_err']
if daymax_err > 1.0:
self.print_verbose(
"Cutting %s, day max err %.2f too high" % (supernova, daymax_err),
minimum_verbosity=2,
)
continue
self.attrition_salt_daymax += 1
# Restrict ourselves to near maximum light.
range_spectra = supernova.get_spectra_in_range(
-self.settings['phase_range'], self.settings['phase_range']
)
if len(range_spectra) > 0:
self.attrition_range += 1
used_phases = []
for spectrum in range_spectra:
if self._check_spectrum(spectrum):
all_raw_spec.append(spectrum)
used_phases.append(spectrum.phase)
else:
spectrum.usable = False
used_phases = np.array(used_phases)
if len(used_phases) > 0:
# Figure out which spectrum was closest to the center of the
# bin.
self.attrition_usable += 1
target_center_mask = np.zeros(len(used_phases), dtype=bool)
target_center_mask[np.argmin(np.abs(used_phases))] = True
center_mask.extend(target_center_mask)
all_flux = []
all_fluxerr = []
all_spec = []
for spectrum in all_raw_spec:
bin_spec = spectrum.bin_by_velocity(
self.settings['bin_velocity'],
self.settings['bin_min_wavelength'],
self.settings['bin_max_wavelength'],
)
all_flux.append(bin_spec.flux)
all_fluxerr.append(bin_spec.fluxerr)
all_spec.append(bin_spec)
# All binned spectra have the same wavelengths, so save the wavelengths
# from an arbitrary one of them.
self.wave = all_spec[0].wave
# Save the rest of the info
self.flux = np.array(all_flux)
self.fluxerr = np.array(all_fluxerr)
self.raw_spectra = np.array(all_raw_spec)
self.spectra = np.array(all_spec)
self.center_mask = np.array(center_mask)
# Pull out variables that we use all the time.
self.helio_redshifts = self.read_meta("host.zhelio")
self.redshifts = self.read_meta("host.zcmb")
self.redshift_errs = self.read_meta("host.zhelio.err")
# Build a list of targets and a map from spectra to targets.
self.targets = np.unique([i.target for i in self.spectra])
self.target_map = np.array(
[self.targets.tolist().index(i.target) for i in self.spectra]
)
# Pull out SALT fit info
self.salt_fits = table.Table([i.salt_fit for i in self.targets])
self.salt_x1 = self.salt_fits['x1'].data
self.salt_colors = self.salt_fits['c'].data
self.salt_phases = np.array([i.phase for i in self.spectra])
self.salt_mask = np.array([i.has_valid_salt_fit() for i in self.targets])
# Record which targets should be in the validation set.
self.train_mask = np.array(
[i["idr.subset"] != "validation" for i in self.targets]
)
# Build a hash that is unique to the dataset that we are working on.
hash_info = (
self.settings['idr']
+ ';' + str(self.settings['phase_range'])
+ ';' + str(self.settings['bin_velocity'])
+ ';' + str(self.settings['bin_min_wavelength'])
+ ';' + str(self.settings['bin_max_wavelength'])
+ ';' + str(self.settings['s2n_cut_min_wavelength'])
+ ';' + str(self.settings['s2n_cut_max_wavelength'])
+ ';' + str(self.settings['s2n_cut_threshold'])
)
self.dataset_hash = md5(hash_info.encode("ascii")).hexdigest()
# Load a dictionary that maps IDR names into IAU ones.
iau_data = np.genfromtxt('./data/iau_name_map.txt', dtype=str)
self.iau_name_map = {i: j for i, j in iau_data}
def _check_spectrum(self, spectrum):
"""Check if a spectrum is valid or not"""
spectrum.do_lazyload()
s2n_start = spectrum.get_signal_to_noise(
self.settings['s2n_cut_min_wavelength'],
self.settings['s2n_cut_max_wavelength'],
)
if s2n_start < self.settings['s2n_cut_threshold']:
# Signal-to-noise cut. We find that a signal-to-noise of < ~100 in the
# U-band leads to an added core dispersion of >0.1 mag in the U-band which
# is much higher than expected from statistics. This is unacceptable for the
# twins analysis that relies on getting the color right for a single
# spectrum.
self.print_verbose(
"Cutting %s, start signal-to-noise %.2f "
"too low." % (spectrum, s2n_start),
minimum_verbosity=2,
)
return False
# We made it!
return True
def read_meta(self, key, center_only=True):
"""Read a key from the meta data of each spectrum/target
This will first attempt to read the key in the spectrum object's meta
data. If it isn't there, then it will try to read from the target
instead.
If center_only is True, then a single value is returned for each
target, from the spectrum closest to the center of the range if
applicable. Otherwise, the values will be returned for each spectrum in
the sample.
"""
if key in self.spectra[0].meta:
read_spectrum = True
elif key in self.spectra[0].target.meta:
read_spectrum = False
else:
raise KeyError("Couldn't find key %s in metadata." % key)
if center_only:
use_spectra = self.spectra[self.center_mask]
else:
use_spectra = self.spectra
res = []
for spec in use_spectra:
if read_spectrum:
val = spec.meta[key]
else:
val = spec.target.meta[key]
res.append(val)
res = np.array(res)
return res
def print_verbose(self, *args, minimum_verbosity=1):
if self.settings['verbosity'] >= minimum_verbosity:
print(*args)
def model_differential_evolution(self, use_cache=True):
"""Estimate the spectra for each of our SNe Ia at maximum light.
This algorithm uses all targets with multiple spectra to model the differential
evolution of Type Ia supernovae near maximum light. This method does not rely on
knowing the underlying model of Type Ia supernovae and only models the
differences. The model is generated in magnitude space, so anything static in
between us and the supernova, like dust, does not affect the model.
The fit is performed using Stan. We only use Stan as a minimizer here,
and we do some analytic tricks inside to speed up the computation. Don't try to
run this in sampling model, the analytic tricks will mess up the uncertainties
of a Bayesian analysis!
If use_cache is True, then the fitted model will be retrieved from a
cache if it exists. Make sure to run with use_cache=False if making
modifications to the model!
If use_x1 is True, a SALT2 x1-dependent term will be included in the
model.
"""
# Load the stan model
model_path = "./stan_models/phase_interpolation_analytic.stan"
model_hash, model = utils.load_stan_model(
model_path,
verbosity=self.settings['verbosity']
)
# Build a hash that is unique to this dataset/analysis
hash_info = (
self.dataset_hash
+ ';' + model_hash
+ ';' + str(self.settings['differential_evolution_num_phase_coefficients'])
+ ';' + str(self.settings['differential_evolution_use_salt_x1'])
)
self.differential_evolution_hash = md5(hash_info.encode("ascii")).hexdigest()
# If we ran this model before, read the cached result if we can.
if use_cache:
cache_result = utils.load_stan_result(self.differential_evolution_hash)
if cache_result is not None:
# Found the cached result. Load it and don't redo the fit.
self.differential_evolution_result = cache_result
self.maximum_flux = cache_result["maximum_flux"]
self.maximum_fluxerr = cache_result["maximum_fluxerr"]
return
num_targets = len(self.targets)
num_spectra = len(self.flux)
num_wave = len(self.wave)
num_phase_coefficients = self.settings[
'differential_evolution_num_phase_coefficients'
]
if num_phase_coefficients % 2 != 0:
raise Exception("ERROR: Must have an even number of phase " "coefficients.")
spectra_targets = [i.target for i in self.spectra]
spectra_target_counts = np.array(
[spectra_targets.count(i.target) for i in self.spectra]
)
phase_coefficients = np.zeros((num_spectra, num_phase_coefficients))
for i, phase in enumerate(self.salt_phases):
phase_scale = np.abs(
(num_phase_coefficients / 2) * (phase / self.settings['phase_range'])
)
full_bins = int(np.floor(phase_scale))
remainder = phase_scale - full_bins
for j in range(full_bins + 1):
if j == full_bins:
weight = remainder
else:
weight = 1
if phase > 0:
phase_bin = num_phase_coefficients // 2 + j
else:
phase_bin = num_phase_coefficients // 2 - 1 - j
phase_coefficients[i, phase_bin] = weight
def stan_init():
init_params = {
"phase_slope": np.zeros(num_wave),
"phase_quadratic": np.zeros(num_wave),
"phase_slope_x1": np.zeros(num_wave),
"phase_quadratic_x1": np.zeros(num_wave),
"phase_dispersion_coefficients": (
0.01 * np.ones((num_phase_coefficients, num_wave))
),
"gray_offsets": np.zeros(num_spectra),
"gray_dispersion_scale": 0.02,
}
return init_params
if self.settings['differential_evolution_use_salt_x1']:
x1 = self.salt_x1
else:
x1 = np.zeros(num_targets)
stan_data = {
"num_targets": num_targets,
"num_spectra": num_spectra,
"num_wave": num_wave,
"measured_flux": self.flux,
"measured_fluxerr": self.fluxerr,
"phases": [i.phase for i in self.spectra],
"phase_coefficients": phase_coefficients,
"num_phase_coefficients": num_phase_coefficients,
"spectra_target_counts": spectra_target_counts,
"target_map": self.target_map + 1, # stan uses 1-based indexing
"maximum_map": np.where(self.center_mask)[0] + 1,
"salt_x1": x1,
}
sys.stdout.flush()
result = model.optimizing(
data=stan_data, init=stan_init, verbose=True, iter=20000, history_size=100
)
self.differential_evolution_result = result
self.maximum_flux = result["maximum_flux"]
self.maximum_fluxerr = result["maximum_fluxerr"]
# Save the output to cache it for future runs.
utils.save_stan_result(self.differential_evolution_hash, result)
def read_between_the_lines(self, use_cache=True):
"""Run the read between the lines algorithm.
This algorithm estimates the brightnesses and colors of every spectrum
and produces dereddened spectra.
The fit is performed using Stan. We only use Stan as a minimizer here.
"""
# Load the fiducial color law.
self.rbtl_color_law = extinction.fitzpatrick99(
self.wave, 1.0, self.settings['rbtl_fiducial_rv']
)
# Load the stan model
model_path = "./stan_models/read_between_the_lines.stan"
model_hash, model = utils.load_stan_model(
model_path,
verbosity=self.settings['verbosity']
)
# Build a hash that is unique to this dataset/analysis
hash_info = (
self.differential_evolution_hash
+ ';' + model_hash
+ ';' + str(self.settings['rbtl_fiducial_rv'])
)
if self.settings['test_no_interpolation']:
hash_info += ';no_interpolation'
self.rbtl_hash = md5(hash_info.encode("ascii")).hexdigest()
# If we ran this model before, read the cached result if we can.
if use_cache:
cache_result = utils.load_stan_result(self.rbtl_hash)
if cache_result is not None:
# Found the cached result. Load it and don't redo the fit.
self._parse_rbtl_result(cache_result)
return
use_targets = self.targets
num_targets = len(use_targets)
num_wave = len(self.wave)
def stan_init():
# Use the spectrum closest to maximum as a first guess of the
# target's spectrum.
start_mean_flux = np.mean(self.maximum_flux, axis=0)
start_fractional_dispersion = 0.1 * np.ones(num_wave)
return {
"mean_flux": start_mean_flux,
"fractional_dispersion": start_fractional_dispersion,
"colors_raw": np.zeros(num_targets - 1),
"magnitudes_raw": np.zeros(num_targets - 1),
}
stan_data = {
"num_targets": num_targets,
"num_wave": num_wave,
"maximum_flux": self.maximum_flux,
"maximum_fluxerr": self.maximum_fluxerr,
"color_law": self.rbtl_color_law,
}
sys.stdout.flush()
result = model.optimizing(data=stan_data, init=stan_init, verbose=True,
iter=5000)
# Save the output to cache it for future runs.
utils.save_stan_result(self.rbtl_hash, result)
# Parse the result
self._parse_rbtl_result(result)
def _calculate_rbtl_uncertainties(self):
mag_errs = []
color_errs = []
for idx in range(len(self.maximum_flux)):
def nll(vals):
dm, dc = vals
max_flux = self.maximum_flux[idx]
model_flux = (
self.rbtl_result['mean_flux'] * 10**(-0.4 * (
(self.rbtl_result['colors'][idx] + dc) * self.rbtl_color_law
+ self.rbtl_result['magnitudes'][idx] + dm
))
)
fluxerr = np.sqrt(
(self.rbtl_result['fractional_dispersion'] * model_flux)**2
+ (self.maximum_fluxerr[idx]**2)
)
nll = 0.5 * np.sum((max_flux - model_flux)**2 / fluxerr**2)
return nll
cov = math.calculate_covariance_finite_difference(
nll, ['dm', 'dc'], [0., 0.], [(None, None), (None, None)]
)
mag_err, color_err = np.sqrt(np.diag(cov))
mag_errs.append(mag_err)
color_errs.append(color_err)
mag_errs = np.array(mag_errs)
color_errs = np.array(color_errs)
return mag_errs, color_errs
def _parse_rbtl_result(self, result):
"""Parse and save the result of a run of the RBTL analysis"""
self.rbtl_result = result
self.rbtl_colors = result["colors"] - np.median(result['colors'])
self.rbtl_mags = result["magnitudes"] - np.median(result['magnitudes'])
self.mean_flux = result["mean_flux"]
if self.settings['blinded']:
# Immediately discard validation magnitudes so that we can't
# accidentally look at them.
self.rbtl_mags[~self.train_mask] = np.nan
# Deredden the real spectra and set them to the same scale as the mean
# spectrum.
self.scale_flux = self.maximum_flux / result['model_scales']
self.scale_fluxerr = self.maximum_fluxerr / result['model_scales']
# Calculate fractional differences from the mean spectrum.
self.fractional_differences = self.scale_flux / self.mean_flux - 1
self.fractional_difference_uncertainties = self.scale_fluxerr / self.mean_flux
def build_masks(self):
"""Build masks that are used in the various manifold learning and magnitude
analyses
"""
# For the manifold learning analysis, we need to make sure that the spectra at
# maximum light have reasonable uncertainties on their spectra at maximum light.
# We define "reasonable" by comparing the variance of each spectrum to the
# size of the intrinsic supernova variation measured in the RBTL analysis.
intrinsic_dispersion = utils.frac_to_mag(
self.rbtl_result["fractional_dispersion"]
)
intrinsic_power = np.sum(intrinsic_dispersion**2)
maximum_uncertainty = utils.frac_to_mag(
self.maximum_fluxerr / self.maximum_flux
)
maximum_power = np.sum(maximum_uncertainty**2, axis=1)
self.maximum_uncertainty_fraction = maximum_power / intrinsic_power
self.uncertainty_mask = (
self.maximum_uncertainty_fraction <
self.settings['mask_uncertainty_fraction']
)
self.print_verbose(
" Masking %d/%d targets whose uncertainty power is \n"
" more than %.3f of the intrinsic power."
% (np.sum(~self.uncertainty_mask), len(self.uncertainty_mask),
self.settings['mask_uncertainty_fraction'])
)
# Mask to select targets that have a magnitude that is expected to have a large
# dispersion in brightness.
with np.errstate(invalid="ignore"):
self.redshift_color_mask = (
(self.redshift_errs < 0.004)
& (self.helio_redshifts > 0.02)
& (self.rbtl_colors < 0.5)
)
def generate_embedding(self, num_neighbors=None, num_components=-1, mask=None,
model=None, data=None):
"""Generate a manifold learning embedding.
By default we use Isomap with hyperparameters as set in the settings, but
this can be overridden by manually specifying any model that follows the
sklearn API or hyperparameters.
"""
if model is None:
if num_neighbors is None:
num_neighbors = self.settings['isomap_num_neighbors']
if num_components == -1:
num_components = self.settings['isomap_num_components']
model = Isomap(n_neighbors=num_neighbors, n_components=num_components)
if mask is None:
good_mask = self.uncertainty_mask
else:
good_mask = mask
if data is None:
data = self.fractional_differences
# Build the embedding using well-measured targets
ref_embedding = model.fit_transform(data[good_mask])
# Evaluate the coordinates in the embedding for the remaining targets.
if not np.all(good_mask):
other_embedding = model.transform(data[~good_mask])
# Combine everything into a single array.
embedding = np.zeros((len(self.targets), ref_embedding.shape[1]))
embedding[good_mask] = ref_embedding
if not np.all(good_mask):
embedding[~good_mask] = other_embedding
# The signs of the embedding are arbitrary... flip the sign of some of them to
# make them match up with well-known indicators in the literature.
for component in self.settings['isomap_flip_components']:
if num_components > component:
embedding[:, component] *= -1
return embedding
def load_indicators(self):
"""Calculate/load a range of different indicators of intrinsic diversity"""
all_indicators = []
# Dummy table with the target name
target_table = table.Table({'name': [i.name for i in self.targets]},
masked=True)
all_indicators.append(target_table)
# Add in all of the different indicators that are available.
all_indicators.append(self.load_isomap_indicators())
all_indicators.append(self.load_salt_indicators())
all_indicators.append(self.calculate_spectral_indicators())
all_indicators.append(self.load_nordin_colors())
all_indicators.append(self.load_sugar_components())
all_indicators.append(self.load_snemo_components())
all_indicators.append(self.load_host_data())
all_indicators.append(self.load_peculiar_data())
all_indicators = table.hstack(all_indicators)
self.indicators = all_indicators
# Extract masks that we will use extensively.
self.peculiar_mask = (self.indicators['peculiar_type'] == 'Normal').filled()
self.host_mask = ~self.indicators['host_lssfr'].mask
def load_isomap_indicators(self):
"""Extract Isomap indicators"""
columns = []
for i in range(self.settings['isomap_num_components']):
columns.append(table.MaskedColumn(
self.embedding[:, i],
name=f'isomap_c{i+1}',
mask=~self.uncertainty_mask,
))
return table.Table(columns)
def load_salt_indicators(self):
"""Extract SALT2.4 indicators from the fits"""
salt_indicators = table.Table(self.salt_fits[['c', 'x1']], masked=True)
salt_indicators['c'].name = 'salt_c'
salt_indicators['x1'].name = 'salt_x1'
salt_indicators['salt_c'].mask = ~self.salt_mask
salt_indicators['salt_x1'].mask = ~self.salt_mask
return salt_indicators
def calculate_spectral_indicators(self):
"""Calculate spectral indicators for all of the features"""
spectral_indicators = []
for idx in range(len(self.scale_flux)):
spec = specind.Spectrum(
self.wave, self.scale_flux[idx], self.scale_fluxerr[idx]**2
)
indicators = spec.get_spin_dict()
spectral_indicators.append(indicators)
spectral_indicators = table.Table(spectral_indicators, masked=True)
# Figure out Branch classifications
all_si6355 = spectral_indicators["EWSiII6355"]
all_si5972 = spectral_indicators["EWSiII5972"]
branch_classifications = []
for si6355, si5972 in zip(all_si6355, all_si5972):
if si5972 >= 30:
branch_classifications.append("Cool")
elif (si5972 < 30) & (si6355 < 70):
branch_classifications.append("Shallow Silicon")
elif (si5972 < 30) & (si6355 >= 70) & (si6355 < 100):
branch_classifications.append("Core Normal")
elif (si5972 < 30) & (si6355 >= 100):
branch_classifications.append("Broad Line")
spectral_indicators['branch_classification'] = branch_classifications
for colname in spectral_indicators.colnames:
# Mask out indicators that we shouldn't be using.
spectral_indicators[colname].mask = ~self.uncertainty_mask
if 'branch' not in colname:
spectral_indicators.rename_column(colname, f'spectrum_{colname}')
return spectral_indicators
def _load_table(self, path, name_key):
"""Read a table from a given path and match it to our list of targets"""
# Read the table
data = table.Table.read(path)
# Make a dummy table with the names of each of our SNe~Ia
name_table = table.Table({name_key: [i.name for i in self.targets]})
# Join the tables
ordered_table = table.join(name_table, data, join_type='left')
return ordered_table
def load_sugar_components(self):
"""Load the SUGAR components from Leget et al. 2019"""
pickle_data = open('./data/sugar_parameters.pkl').read() \
.replace('\r\n', '\n').encode('latin1')
sugar_data = pickle.loads(pickle_data, encoding='latin1')
sugar_keys = ['q1', 'q2', 'q3', 'Av', 'grey']
sugar_rows = []
for target in self.targets:
try:
row = sugar_data[target.name.encode('latin1')]
sugar_rows.append([row[i] for i in sugar_keys])
except KeyError:
sugar_rows.append(np.ma.masked_array([np.nan]*len(sugar_keys),
[1]*len(sugar_keys)))
sugar_components = table.Table(
rows=sugar_rows,
names=[f'sugar_{i}' for i in sugar_keys],
)
return sugar_components
def load_nordin_colors(self):
"""Load the U-band colors from Nordin et al. 2018"""
nordin_table = self._load_table('./data/nordin_2018_colors.csv', 'name')
for colname in nordin_table.colnames:
nordin_table.rename_column(colname, f'nordin_{colname}')
return nordin_table
def load_snemo_components(self):
"""Load the SNEMO components from Saunders et al. 2018"""
snemo_table = self._load_table('./data/snemo_salt_coefficients_snf.csv', 'SN')
for colname in snemo_table.colnames:
if 'snemo' not in colname:
snemo_table.rename_column(colname, f'snemo_{colname}')
continue
return snemo_table
def load_host_data(self):
"""Load host data from Rigault et al. 2019"""
host_data = self._load_table('./data/host_properties_rigault_valid.csv', 'name')
# Note: This list is from private communication and has the same names as our
# dataset. The data table in Rigault et al. 2019 uses IAU names which can be
# converted using self.iau_name_map.get(name, name)
for original_colname in host_data.colnames:
colname = original_colname
if 'host' not in colname:
colname = f'host_{colname}'
colname = colname.replace('.', '_')
host_data.rename_column(original_colname, colname)
return host_data
def load_peculiar_data(self):
"""Load peculiar SNe Ia information from Lin. et al 2020"""
raw_peculiar_data = self._load_table('./data/peculiar_lin_2020.csv', 'name')
peculiar_type = raw_peculiar_data['kind'].filled('Normal')
peculiar_reference = raw_peculiar_data['reference'].filled('')
peculiar_table = table.Table({
'peculiar_type': peculiar_type,
'peculiar_reference': peculiar_reference,
}, masked=True)
return peculiar_table
def find_best_transformation(self, target_indicator,
quadratic_reference_indicators=[],
linear_reference_indicators=[], mask=True,
shuffle=False):
"""Find the best transformation of a set of indicators to reproduce a different
indicator.
The indicators can be either keys corresponding to columns in the
self.indicators table or arrays of values directly. Masks will automatically be
extracted if the indicators are `MaskedColumn` or `numpy.ma.masked_array`
instances. A mask can also be explicitly passed to this function which will be
used in addition to any extracted masks.
Parameters
----------
target_indicator : str or array
The indicator to attempt to reproduce.
quadratic_reference_indicators : list of strs or arrays, optional
Indicators to transform, with up to quadratic terms (including cross-terms)
allowed in each of these indicators.
linear_reference_indicators : list of strs or arrays, optional
Indicators to transform, with only linear terms allowed in each of these
indicators.
mask : array of bools, optional
A mask to apply (in addition to ones extracted from the indicators).
shuffle : bool, optional
If True, shuffle the reference indicators randomly before doing the
transformation. This can be used to determine the significance of any
relations. (default False)
Returns
-------
explained_variance : float
Fraction of variance that is explained by the tranformation.
coefficients : array
Coefficients of the transformation.
best_transformation : array
Transformation of the reference values that best matches the target values.
mask : array
Mask that was used for the transformation
"""
def parse_column(col):
if isinstance(col, str):
return self.indicators[col]
else:
return col
quad_ref_columns = [parse_column(i) for i in quadratic_reference_indicators]
lin_ref_columns = [parse_column(i) for i in linear_reference_indicators]
target_column = parse_column(target_indicator)
# Build the mask taking masked columns into account if applicable.
for column in quad_ref_columns + lin_ref_columns + [target_column]:
try:
mask = mask & ~column.mask
except AttributeError:
continue
# Get basic numpy arrays for everything and apply the masks. This has a
# surprisingly large effect on performance.
quad_ref_values = [np.asarray(i)[mask] for i in quad_ref_columns]
lin_ref_values = [np.asarray(i)[mask] for i in lin_ref_columns]
target_values = np.asarray(target_column)[mask]
if shuffle:
# Reorder the references randomly
order = np.random.permutation(np.arange(len(target_values)))
quad_ref_values = [i[order] for i in quad_ref_values]
lin_ref_values = [i[order] for i in lin_ref_values]
num_linear_terms = len(quad_ref_values) + len(lin_ref_values)
num_quadratic_terms = (len(quad_ref_values) + 1) * len(quad_ref_values) // 2
num_terms = 1 + num_linear_terms + num_quadratic_terms
def evaluate(x):
zeropoint = x[0]
linear_coeffs = x[1:num_linear_terms+1]
quadratic_coeffs = x[num_linear_terms+1:]
# Start the model with the zeropoint
model = zeropoint
# Linear terms. Note that the quadratic terms also have a linear one.
lin_idx = 0
for val in lin_ref_values:
model += linear_coeffs[lin_idx] * val
lin_idx += 1
for val in quad_ref_values:
model += linear_coeffs[lin_idx] * val
lin_idx += 1
# Quadratic terms.
quad_idx = 0
for i, val1 in enumerate(quad_ref_values):
for j, val2 in enumerate(quad_ref_values):
if i > j:
continue
model += quadratic_coeffs[quad_idx] * val1 * val2
quad_idx += 1
return model
norm = 1. / len(target_values) / np.var(target_values)
def calc_unexplained_variance(x):
model = evaluate(x)
diff = target_values - model
return np.sum(diff**2) * norm
res = minimize(calc_unexplained_variance, [0] * num_terms)
best_guess = utils.fill_mask(evaluate(res.x), mask)
explained_variance = 1 - calc_unexplained_variance(res.x)
return explained_variance, res.x, best_guess, mask
def calculate_peculiar_velocity_uncertainties(self, redshifts):
"""Calculate dispersion added to the magnitude due to host galaxy
peculiar velocity
"""
pec_vel_dispersion = (5 / np.log(10)) * (
self.settings['peculiar_velocity'] / 3e5 / redshifts
)
return pec_vel_dispersion
def _get_gp_data(self, kind="rbtl"):
"""Return the data needed for GP fits along with the corresponding masks.
Parameters
----------
kind : {'rbtl', 'salt', 'salt_raw'}
The kind of magnitude data to return. The options are:
- rbtl: RBTL magnitudes and colors.
- salt: Corrected SALT2 magnitudes and colors.
- salt_raw: Uncorrected SALT2 magnitudes and colors.
Returns
-------
coordinates : numpy.array
The coordinates to evaluate the GP over.
mags : numpy.array
A list of magnitudes for each supernova in the sample.
mag_errs : numpy.array
The uncertainties on the magnitudes. This only includes measurement
uncertainties, not model ones (since the GP will handle that). Since we are
dealing with high signal-to-noise light curves/spectra, the color and
magnitude measurement errors are very small and difficult to propagate so I
ignore them. This therefore only includes contributions from peculiar
velocity.
colors : numpy.array
A list of colors for each supernova in the sample.
condition_mask : numpy.array
The mask that should be used for conditioning the GP.
"""
if kind == "rbtl":
mags = self.rbtl_mags
colors = self.rbtl_colors
condition_mask = self.uncertainty_mask & self.redshift_color_mask
# Assume that we can ignore measurement uncertainties for the magnitude
# errors, so the only contribution is from peculiar velocities.
mag_errs = self.calculate_peculiar_velocity_uncertainties(self.redshifts)
elif kind == "salt_raw" or kind == "salt":
if kind == "salt_raw":
# Evaluate the residuals with all model terms set to zero.
mags, mag_errs = self._evaluate_salt_magnitude_residuals(
[], 0., 0., 0., 0.
)
elif kind == "salt":
# Use the standard SALT2 fit as a baseline.
mags = self.residuals_salt['residuals']
mag_errs = self.residuals_salt['raw_residual_uncertainties']
colors = self.salt_colors
condition_mask = (
self.salt_mask
& self.uncertainty_mask
& self.redshift_color_mask
)
else:
raise TwinsEmbeddingException("Unknown kind %s!" % kind)
# Use the Isomap embedding for the GP coordinates.
coordinates = self.embedding
# If the analysis is blinded, only use the training data for conditioning.
if self.settings['blinded']:
condition_mask &= self.train_mask
return coordinates, mags, mag_errs, colors, condition_mask
def fit_gp_magnitude_residuals(self, kind="rbtl", mask=None,
additional_covariates=[], verbosity=None):
"""Calculate magnitude residuals using a GP over a given latent space."""