-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfind_pcs.py
More file actions
2810 lines (2212 loc) · 99.5 KB
/
find_pcs.py
File metadata and controls
2810 lines (2212 loc) · 99.5 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 python3
# local
from importer import *
import csp
import cov_obs
import figures_tools
from spectrophot import (lumspec2lsun, color, C_ML_conv_t as CML,
Spec2Phot, absmag_sun_band as Msun)
import utils as ut
from fakedata import FakeData, SkyContamination
from linalg import *
from param_estimate import *
from rectify import MaNGA_deredshift
import pca_status
# personal
import manga_tools as m
import numpy as np
# plotting
import matplotlib.pyplot as plt
from matplotlib import cm as mplcm
from matplotlib import gridspec
import matplotlib.ticker as mticker
from cycler import cycler
# astropy ecosystem
from astropy import constants as c, units as u, table as t
from astropy.io import fits
from astropy import wcs
from astropy.utils.console import ProgressBar
from astropy.cosmology import WMAP9
from astropy import coordinates as coord
from astropy.wcs.utils import pixel_to_skycoord
import os
import sys
from warnings import warn, filterwarnings, catch_warnings, simplefilter
from traceback import print_exception
from functools import lru_cache
import pickle
# scipy
from scipy.interpolate import interp1d
from scipy.optimize import minimize
from scipy.integrate import quad
from scipy.ndimage.filters import gaussian_filter1d
from scipy.stats import entropy
# statsmodels
# removing to avoid scipy import error
# from statsmodels.nonparametric.kde import KDEUnivariate
eps = np.finfo(float).eps
class StellarPop_PCA(object):
'''
class for determining PCs of a library of synthetic spectra
'''
def __init__(self, l, trn_spectra, gen_dicts, metadata, K_obs, src,
sfh_fnames, nsubpersfh, nsfhperfile, basedir,
dlogl=None, lllim=3700. * u.AA, lulim=7400. * u.AA):
'''
params:
- l: length-n array-like defining the wavelength bin centers
(should be log-spaced)
- spectra: m-by-n array of spectra (individual spectrum contained
along one index in dimension 0), in units of 1e-17 erg/s/cm2/AA
- gen_dicts: length-m list of FSPS_SFHBuilder.FSPS_args dicts,
ordered the same as `spectra`
- metadata: table of derived SSP properties used for regression
(D4000 index, Hd_A index, r-band luminosity-weighted age,
mass-weighted age, i-band mass-to-light ratio,
z-band mass-to-light ratio, mass fraction formed in past 1Gyr,
formation time, eftu, metallicity, tau_V, mu, sigma)
this somewhat replicates data in `gen_dicts`, but that's ok
'''
self.basedir = basedir
l_good = np.ones_like(l, dtype=bool)
if lllim is not None:
l_good *= (l >= lllim)
if lulim is not None:
l_good *= (l <= lulim)
self.l = l[l_good]
self.logl = np.log10(self.l.to('AA').value)
if not dlogl:
dlogl = np.round(np.mean(self.logl[1:] - self.logl[:-1]), 8)
self.dlogl = dlogl
self.trn_spectra = trn_spectra[:, l_good]
self.metadata = metadata
# metadata array is anything with a 'TeX' metadata entry
metadata_TeX = [metadata[n].meta.get('TeX', False)
for n in metadata.colnames]
metadata_incl = np.array([True if m is not False else False
for m in metadata_TeX])
self.metadata_TeX = [m for m, n in zip(metadata_TeX, metadata.colnames)
if m is not False]
# a kludgey conversion from structured array to regular array
metadata_a = np.array(self.metadata)
metadata_a = metadata_a.view((metadata_a.dtype[0],
len(metadata_a.dtype.names)))
self.metadata_a = metadata_a[:, metadata_incl]
self.src = src
self.sfh_fnames = sfh_fnames
self.nsubpersfh = nsubpersfh
self.nsfhperfile = nsfhperfile
self.important_params = ['MLi', 'Dn4000', 'Hdelta_A',
'MWA', 'sigma', 'logzsol',
'tau_V', 'mu', 'tau_V mu',
'Mg_b', 'Ca_HK', 'F_1G',
'logQHpersolmass']
self.importantplus_params = self.important_params + \
['F_200M', 'tf', 'd1', 'tt', 'MLV']
self.confident_params = ['MLi', 'logzsol',
'tau_V', 'mu', 'tau_V mu', 'tau_V (1 - mu)',
'logQHpersolmass', 'uv_slope']
# observational covariance matrix
if not isinstance(K_obs, cov_obs.Cov_Obs):
raise TypeError('incorrect observational covariance matrix class!')
if not np.isclose(K_obs.dlogl, self.dlogl, rtol=1.0e-3):
raise PCAError('non-matching log-lambda spacing ({}, {})'.format(
K_obs.dlogl, self.dlogl))
@classmethod
def from_FSPS(cls, K_obs, lsf, base_dir, nfiles=None,
log_params=['MWA', 'MLr', 'MLi', 'MLz', 'MLV',
'F_20M', 'F_100M', 'F_200M', 'F_500M', 'F_1G'],
inf_replace=dict(zip(['F_20M', 'F_100M', 'F_200M', 'F_500M', 'F_1G'],
[-20., -20., -20., -20., -20.])),
vel_params={}, dlogl=1.0e-4, z0_=.04,
preload_llims=[3000. * u.AA, 10000. * u.AA], **kwargs):
'''
Read in FSPS outputs (dicts & metadata + spectra) from some directory
'''
from glob import glob
from utils import pickle_loader, add_losvds
from itertools import chain
csp_fnames = glob(os.path.join(base_dir,'CSPs_*.fits'))
sfh_fnames = glob(os.path.join(base_dir,'SFHs_*.fits'))
print('Building training library in directory: {}'.format(base_dir))
print('CSP files used: {}'.format(' '.join(tuple(csp_fnames))))
if nfiles is not None:
csp_fnames = csp_fnames[:nfiles]
sfh_fnames = sfh_fnames[:nfiles]
l = fits.getdata(csp_fnames[0], 'lam') * u.AA
logl = np.log10(l.value)
Nsubsample = fits.getval(sfh_fnames[0], ext=0, keyword='NSUBPER')
Nsfhper = fits.getval(sfh_fnames[0], ext=0, keyword='NSFHPER')
meta = t.vstack([t.Table.read(f, format='fits', hdu=1)
for f in csp_fnames])
spec = np.row_stack(list(map(
lambda fn: fits.getdata(fn, 'flam'), csp_fnames)))
in_lrange = (l >= preload_llims[0]) * (l <= preload_llims[1])
spec = spec[:, in_lrange]
l = l[in_lrange]
logl = logl[in_lrange]
meta['tau_V mu'] = meta['tau_V'] * meta['mu']
meta['tau_V (1 - mu)'] = meta['tau_V'] * (1. - meta['mu'])
meta['QLi'] = 10.**meta['logQHpersolmass'] * meta['MLi']
for k in meta.colnames:
if len(meta[k].shape) > 1:
del meta[k]
del meta['mstar']
meta['MWA'].meta['TeX'] = r'MWA'
meta['Dn4000'].meta['TeX'] = r'D$_{n}$4000'
meta['Hdelta_A'].meta['TeX'] = r'H$\delta_A$'
meta['Hdelta_F'].meta['TeX'] = r'H$\delta_F$'
meta['Hgamma_A'].meta['TeX'] = r'H$\gamma_A$'
meta['Hgamma_F'].meta['TeX'] = r'H$\gamma_F$'
meta['H_beta'].meta['TeX'] = r'H$\beta$'
meta['Mg_1'].meta['TeX'] = r'Mg$_1$'
meta['Mg_2'].meta['TeX'] = r'Mg$_2$'
meta['Mg_b'].meta['TeX'] = r'Mg$_b$'
meta['Ca_HK'].meta['TeX'] = r'CaHK'
meta['Na_D'].meta['TeX'] = r'Na$_D$'
meta['CN_1'].meta['TeX'] = r'CN$_1$'
meta['CN_2'].meta['TeX'] = r'CN$_2$'
meta['TiO_1'].meta['TeX'] = r'TiO$_1$'
meta['TiO_2'].meta['TeX'] = r'TiO$_2$'
meta['logzsol'].meta['TeX'] = r'$\log{\frac{Z}{Z_{\odot}}}$'
meta['tau_V'].meta['TeX'] = r'$\tau_V$'
meta['mu'].meta['TeX'] = r'$\mu$'
meta['tau_V mu'].meta['TeX'] = r'$\tau_V ~ \mu$'
meta['tau_V (1 - mu)'].meta['TeX'] = r'$\tau_V ~ (1 - \mu)$'
meta['MLr'].meta['TeX'] = r'$\log \Upsilon^*_r$'
meta['MLi'].meta['TeX'] = r'$\log \Upsilon^*_i$'
meta['MLz'].meta['TeX'] = r'$\log \Upsilon^*_z$'
meta['MLV'].meta['TeX'] = r'$\log \Upsilon^*_V$'
meta['sigma'].meta['TeX'] = r'$\sigma$'
meta['F_20M'].meta['TeX'] = r'$F_m^{\rm .02G}$'
meta['F_50M'].meta['TeX'] = r'$F_m^{\rm .05G}$'
meta['F_100M'].meta['TeX'] = r'$F_m^{\rm .1G}$'
meta['F_200M'].meta['TeX'] = r'$F_m^{\rm .2G}$'
meta['F_500M'].meta['TeX'] = r'$F_m^{\rm .5G}$'
meta['F_1G'].meta['TeX'] = r'$F_m^{\rm 1G}$'
meta['gamma'].meta['TeX'] = r'$\gamma$'
meta['theta'].meta['TeX'] = r'$\Theta$'
meta['d1'].meta['TeX'] = r'$\tau_{\rm SFH}$'
meta['tf'].meta['TeX'] = r'$t_{\rm form}$'
meta['tt'].meta['TeX'] = r'$t_{\rm trans}$'
meta['nburst'].meta['TeX'] = r'$N_{\rm burst}$'
meta['Cgr'].meta['TeX'] = r'$C_{gr}$'
meta['Cri'].meta['TeX'] = r'$C_{ri}$'
meta['Cgr_z015'].meta['TeX'] = r'$C^{.15}_{gr}$'
meta['Cri_z015'].meta['TeX'] = r'$C^{.15}_{ri}$'
meta['sbss'].meta['TeX'] = r'$S_{\rm BSS}$'
meta['fbhb'].meta['TeX'] = r'$f_{\rm BHB}$'
meta['logQHpersolmass'].meta['TeX'] = r'$\log{\frac{Q_H}{M_{\odot}}}$'
meta['QLi'].meta['TeX'] = r'$\log \frac{Q_H}{\mathcal{L}_i}$'
meta['uv_slope'].meta['TeX'] = r'$\beta_{UV}$'
for n in meta.colnames:
if n in log_params:
meta[n] = np.log10(meta[n])
meta[n].meta['scale'] = 'log'
if n in inf_replace.keys():
meta[n][~np.isfinite(meta[n])] = inf_replace[n]
if 'ML' in n:
meta[n].meta['unc_incr'] = .008
#spec, meta = spec[models_good, :], meta[models_good]
# convolve spectra with instrument LSF
dlogl_hires = ut.determine_dlogl(logl)
spec_lsf = lsf(y=spec, lam=(l.value) * (1. + z0_),
dlogl=dlogl_hires, z=z0_)
# interpolate models to desired l range
logl_final = np.arange(np.log10(l.value.min()),
np.log10(l.value.max()), dlogl)
l_final = 10.**logl_final
spec_lores = ut.interp_large(x0=logl, y0=spec_lsf, xnew=logl_final,
axis=-1, kind='linear')
spec_lores /= spec_lores.max(axis=1)[..., None]
for k in meta.colnames:
meta[k] = meta[k].astype(np.float32)
return cls(l=l_final * l.unit, trn_spectra=spec_lores,
gen_dicts=None, metadata=meta, sfh_fnames=sfh_fnames,
K_obs=K_obs, dlogl=None, src='FSPS',
nsubpersfh=Nsubsample, nsfhperfile=Nsfhper, basedir=base_dir,
**kwargs)
# =====
# methods
# =====
def xval(self, specs, qmax=30):
# reconstruction error
qs = np.linspace(1, qmax, qmax, dtype=int)
err = np.empty_like(qs, dtype=float)
# normalize mean of each training spectrum to 1
specs_norm, a = self.scaler(specs, lam_axis=1)
S = specs_norm - self.M
def recon_rms(q):
A = quick_data_to_PC(S, self.evecs_[:q])
# reconstructed spectra
S_recon = np.dot(A, self.evecs_[:q])
resid = S_recon - S
# fractional reconstruction error
e = np.sqrt(np.mean(resid**2.))
return e
for i, q in enumerate(qs):
try:
err[i] = recon_rms(q)
except:
err[i] = 1.
continue
return qs, err
def xval_fromfile(self, fname, lsf, z0, qmax=50, target=.01):
hdulist = fits.open(fname)
specs_full = hdulist['flam'].data
l_full = hdulist['lam'].data
logl_full = np.log10(l_full)
# convolve spectra with instrument LSF
dlogl_hires = ut.determine_dlogl(logl_full)
specs_lsf = lsf(y=specs_full, lam=(l_full) * (1. + z0),
dlogl=dlogl_hires, z=z0)
specs_interp = interp1d(x=logl_full, y=specs_lsf, kind='linear', axis=-1)
specs = specs_interp(self.logl)
qs, err = self.xval(specs, qmax)
fig = plt.figure(figsize=(4, 4), dpi=300)
ax = fig.add_subplot(111)
ax.plot(qs, err)
ax.set_yscale('log')
loc = mticker.MaxNLocator(nbins=5, integer=True, steps=[1, 2, 5, 10])
ax.xaxis.set_major_locator(loc)
ax.set_xlabel('Number of PCs')
ax.set_ylabel('Frac. Recon. Err.')
fig.tight_layout()
# return smallest q value for which target FRE is reached
try:
q = np.min(qs[err <= target])
except ValueError:
q = None
hdulist.close()
fig.savefig(os.path.join(self.basedir, 'xval_test.png'))
return q
def run_pca_models(self, q):
'''
run PCA on library of model spectra
'''
self.scaler = ut.MedianSpecScaler(X=self.trn_spectra)
self.normed_trn = self.scaler.X_sc
self.M = np.median(self.normed_trn, axis=0)
self.S = self.normed_trn - self.M
self.evals_, self.evals, self.evecs_, self.PCs = run_pca(self.S, q)
self.trn_PC_wts = quick_data_to_PC(self.S, self.PCs)
# reconstruct the best approximation for the spectra from PCs
self.trn_recon = np.dot(self.trn_PC_wts, self.PCs)
# calculate covariance using reconstruction residuals
self.trn_resid = self.normed_trn - self.trn_recon
# percent variance explained
self.PVE = (self.evals_ / self.evals_.sum())[:q]
self.cov_th = np.cov(self.trn_resid, rowvar=False)
def project_cube(self, f, ivar, mask_spax=None, mask_spec=None,
mask_cube=None, ivar_as_weights=True):
'''
project real spectra onto principal components, given a
flux array & inverse-variance array, plus optional
additional masks
params:
- f: flux array (should be regridded to rest, need not be normalized)
with shape (nl, m, m) (shape of IFU datacube)
- ivar: inverse-variance (same shape as f)
- mask_spax: sets ivar in True spaxels to zero at all wavelengths
within a given spaxel
- mask_spec: sets ivar in True elements to zero in all spaxels
- mask_cube: sets ivar in True elements to zero in only the
corresponding elements
Note: all three masks can be used simultaneously, but mask_spax
is applied first, then mask_spec, then mask_cube
'''
assert ivar.shape == f.shape, \
'cube shapes must be equal, are {}, {}'.format(ivar.shape, f.shape)
cube_shape = f.shape
# manage masks
if mask_spax is not None:
ivar = ivar * (~mask_spax).astype(float)
if mask_spec is not None:
ivar = ivar * (~mask_spec[:, None, None]).astype(float)
if mask_cube is not None:
ivar = ivar * (~mask_cube).astype(float)
# run through same scaling normalization as training data
O_norm, a = self.scaler(f)
ivar_sc = ivar * a**2.
O_sub = O_norm - self.M[:, None, None]
if ivar_as_weights:
w = ivar_sc + eps
else:
w = None
A = robust_project_onto_PCs(e=self.PCs, f=O_sub, w=w)
return A, self.M, a, O_sub, O_norm, ivar_sc
def write_pcs_fits(self):
'''
write training data mean and PCs to fits
'''
hdulist = fits.HDUList([fits.PrimaryHDU()])
lam_hdu = fits.ImageHDU(self.l.value)
lam_hdu.header['EXTNAME'] = 'LAM'
lam_hdu.header['BUNIT'] = 'AA'
hdulist.append(lam_hdu)
mean_hdu = fits.ImageHDU(self.M)
mean_hdu.header['EXTNAME'] = 'MEAN'
hdulist.append(mean_hdu)
pc_hdu = fits.ImageHDU(self.PCs)
pc_hdu.header['EXTNAME'] = 'EVECS'
hdulist.append(pc_hdu)
hdulist.writeto(os.path.join(self.basedir, 'pc_vecs.fits'), overwrite=True)
def reconstruct_normed(self, A):
'''
reconstruct spectra to (one-normalized) cube
params:
- A: array of weights per spaxel
'''
R = np.einsum('nij,nl->lij', A, self.PCs) + self.M[:, None, None]
return R
def reconstruct_full(self, A, a):
'''
reconstruct spectra to properly-scaled cube
params:
- A: array of weights per spaxel
- a: "surface-brightness" multiplier, used to scale the cube
'''
# R = a * (S + M)
# S = A dot E
R = a[None, ...] * (np.einsum('nij,nl->lij', A, self.PCs) +
self.M[:, None, None])
return R
def _compute_i0_map(self, cov_logl, z_map):
'''
compute the index of some array corresponding to the given
wavelength at some redshift
params:
- tem_logl0: the smallest wavelength of the fixed-grid template
that will be the destination of the bin-shift
- logl: the wavelength grid that will be transformed
- z_map: the 2D array of redshifts used to figure out the offset
'''
l0_map = 10.**self.logl[0] * np.ones(z_map.shape)[None, ...]
rules = [dict(name='l', exponent=+1, array_in=l0_map)]
ll0z_map = np.log10(
ut.slrs(rules=rules, z_in=0., z_out=z_map)['l'])
# find the index for the wavelength that best corresponds to
# an appropriately redshifted wavelength grid
ll_d = ll0z_map - np.tile(cov_logl[..., None, None],
(1, ) + z_map.shape)
i0_map = np.argmin(np.abs(ll_d), axis=0)
return i0_map
def compute_model_weights(self, P, A):
'''
compute model weights for each combination of spaxel (PC fits)
and model
params:
- P: inverse of PC covariance matrix, shape (q, q)
- A: PC weights OF OBSERVED DATA obtained from weighted PC
projection routine (robust_project_onto_PCs),
shape (q, NX, NY)
NOTE: this is the equivalent of taking model weights a = A[n, x, y]
in some spaxel (x, y), and the corresp. inv-cov matrix
p = P[..., x, y], training data PC weights C; constructing
D = C - a; and taking D \dot p \dot D
'''
C = self.trn_PC_wts
# C shape: [MODELNUM, PCNUM]
# A shape: [PCNUM, XNUM, YNUM]
D = C[..., None, None] - A[None, ...]
# D shape: [MODELNUM, PCNUM, XNUM, YNUM]
dist2 = np.einsum('cixy,ijxy,cjxy->cxy', D, P, D)
det_K = 1. / np.linalg.det(np.moveaxis(P, [0, 1, 2, 3], [2, 3, 0, 1]))
c = 0.5 * (np.log(det_K) + self.PCs.shape[0] * np.log(2. * np.pi))
w = np.exp(-0.5 * dist2 - c)
return w
def param_pct_map(self, qty, W, P, mask, order=None, factor=None, add=None):
'''
This is no longer iteration based, which is awesome.
params:
- qty: string, specifying which quantity you want (qty must be
an element of self.metadata.colnames)
- W: cube of shape (nmodels, NX, NY), with weights for each
combination of spaxel and model
- P: percentile(s)
- factor: array to multiply metadata[qty] by. This basically
lets you get M by multiplying M/L by L
- add: array to add to metadata[qty]. Equivalent to factor for
log-space data
'''
cubeshape = W.shape[-2:]
Q = self.metadata[qty][np.isfinite(self.metadata[qty])]
W = W[np.isfinite(self.metadata[qty])]
if factor is None:
factor = np.ones(cubeshape)
if add is None:
add = np.zeros(cubeshape)
A = param_interp_map(v=Q, w=W, pctl=np.array(P), mask=mask, order=order)
return (A + add[None, ...]) * factor[None, ...]
def param_cred_intvl(self, qty, W, mask, order=None, factor=None):
'''
find the median and Bayesian credible interval size (two-sided)
of some param's PDF
'''
P = [16., 50., 84.]
# get scale for qty, default to linear
scale = self.metadata[qty].meta.get('scale', 'linear')
if scale == 'log':
# it's CRITICAL that factor is in compatible units to qty
if factor is not None:
add, factor = np.log10(factor), None
else:
add, factor = None, None
else:
add = None
# get uncertainty increase
unc_incr = self.metadata[qty].meta.get('unc_incr', 0.)
# get param pctl maps
P = self.param_pct_map(qty=qty, W=W, P=P, mask=mask, order=order,
factor=factor, add=add)
P16, P50, P84 = tuple(map(np.squeeze, np.split(P, 3, axis=0)))
if scale == 'log':
l_unc, u_unc = (np.abs(P50 - P16) + unc_incr,
np.abs(P84 - P50) + unc_incr)
else:
l_unc, u_unc = (np.abs(P50 - P16) + unc_incr,
np.abs(P84 - P50) + unc_incr)
return P50, l_unc, u_unc, scale
def make_PCs_fig(self):
'''
plot eigenspectra
'''
q = self.PCs.shape[0]
wdim, hdim = (6, 0.8 + 0.5 * (q + 1.))
fig = plt.figure(figsize=(wdim, hdim), dpi=300)
gs = gridspec.GridSpec((q + 1), 1)
hborder = (0.55 / hdim, 0.35 / hdim) # height border
wborder = (0.55 / wdim, 0.25 / hdim) # width border
hspace = (hdim - 1.) / 20.
gs.update(left=wborder[0], right=1. - wborder[1], wspace=0.,
bottom=hborder[0], top=1. - hborder[1], hspace=hspace)
PCs = np.row_stack([self.M, self.PCs])
for i in range(q + 1):
ax = plt.subplot(gs[i])
ax.plot(self.l, PCs[i, :], color='k', linestyle='-',
drawstyle='steps-mid', linewidth=0.5)
if i == 0:
pcnum = 'Median'
else:
pcnum = 'PC{}'.format(i)
ax.set_ylabel(pcnum, size=6)
loc = mticker.MaxNLocator(nbins=5, prune='upper')
ax.yaxis.set_major_locator(loc)
if i != q:
ax.tick_params(axis='x', labelbottom=False)
else:
ax.tick_params(axis='x', color='k', labelsize=8)
ax.tick_params(axis='y', color='k', labelsize=6)
# use last axis to give wavelength
ax.set_xlabel(r'$\lambda~[\textrm{\AA}]$')
plt.suptitle('Eigenspectra')
fig.savefig(os.path.join(self.basedir, 'PCs_{}.png'.format(self.src)),
dpi=300)
def make_params_vs_PCs_fig(self):
'''
make a triangle-plot-like figure with PC amplitudes plotted against components
'''
from astropy.visualization import hist as ahist
from itertools import product as iproduct
q = ncols = self.PCs.shape[0]
nparams = nrows = self.metadata_a.shape[1]
# dimensions of component subplots
sc_ht, sc_wid = 1., 1.
pch_ht, pch_wid = .6, 1.
pah_ht, pah_wid = 1., .6
lbord, rbord, ubord, dbord = 0.8, 0.4, 0.6, 0.6
wspace, hspace = 0.5, 0.5
wdim = lbord + rbord + pah_wid + ncols * sc_wid
hdim = ubord + dbord + pch_ht + nrows * sc_ht
wrs = [1 for _ in range(ncols)]
hrs = [1 for _ in range(nrows)]
wrs.append(pch_wid / sc_wid)
hrs.append(pah_ht / sc_ht)
fig = plt.figure(figsize=(wdim, hdim), dpi=300)
gs = gridspec.GridSpec(ncols=(ncols + 1), nrows=(nrows + 1),
left=(lbord / wdim), right=(1. - rbord / wdim),
bottom=(dbord / hdim), top=(1. - ubord / hdim),
wspace=(wspace / wdim), hspace=(hspace / hdim),
width_ratios=wrs, height_ratios=hrs)
# lists of hist axes, to allow sharex and sharey
PC_hist_axes = [None for _ in range(q)]
param_hist_axes = [None for _ in range(nparams)]
# PC histograms in top row
for i in range(q):
ax = fig.add_subplot(gs[0, i])
try:
ahist(self.trn_PC_wts[:, i], bins='knuth', ax=ax,
histtype='step', orientation='vertical',
linewidth=0.5)
# handle when there are tons and tons of models
except MemoryError:
ahist(self.trn_PC_wts[:, i], bins=50, ax=ax,
histtype='step', orientation='vertical',
linewidth=0.5)
except ValueError:
pass
ax.tick_params(axis='x', labelbottom=False)
ax.tick_params(axis='y', labelleft=False)
PC_hist_axes[i] = ax
# param histograms in right column
for i in range(nrows):
ax = fig.add_subplot(gs[i + 1, -1])
try:
ahist(self.metadata_a[:, i], bins='knuth', ax=ax,
histtype='step', orientation='horizontal',
linewidth=0.5)
# handle when there are tons and tons of models
except MemoryError:
ahist(self.metadata_a[:, i], bins=50, ax=ax,
histtype='step', orientation='horizontal',
linewidth=0.5)
except ValueError:
pass
ax.tick_params(axis='x', labelbottom=False)
yloc = mticker.MaxNLocator(nbins=5, prune='upper')
# tick labels on RHS of hists
ax.yaxis.set_major_locator(yloc)
ax.tick_params(axis='y', labelleft=False, labelright=True,
labelsize=6)
param_hist_axes[i] = ax
# scatter plots everywhere else
for i, j in iproduct(range(nrows), range(ncols)):
# i is param number
# j is PC number
ax = fig.add_subplot(gs[i + 1, j], sharex=PC_hist_axes[j],
sharey=param_hist_axes[i])
ax.scatter(self.trn_PC_wts[:, j], self.metadata_a[:, i],
facecolor='k', edgecolor='None', marker='.',
s=1., alpha=0.4)
# suppress x axis and y axis tick labels
# (except in bottom row and left column, respectively)
if i != nparams - 1:
ax.tick_params(axis='x', labelbottom=False)
else:
xloc = mticker.MaxNLocator(nbins=5, prune='upper')
ax.xaxis.set_major_locator(xloc)
ax.tick_params(axis='x', labelsize=6)
ax.set_xlabel('PC{}'.format(j + 1), size=8)
if j != 0:
ax.tick_params(axis='y', labelleft=False)
else:
yloc = mticker.MaxNLocator(nbins=5, prune='upper')
ax.yaxis.set_major_locator(yloc)
ax.tick_params(axis='y', labelsize=6)
ax.set_ylabel(self.metadata_TeX[i], size=8)
fig.suptitle('PCs vs params')
plt.savefig(os.path.join(self.basedir, 'PCs_params_{}.png'.format(self.src)),
dpi=300)
def find_PC_param_coeffs(self):
'''
find the combination of PC amplitudes that predict the parameters
a X + Z = b
'''
# dependent variable (the parameter values)
b_ = self.metadata_a
# independent variable (the PC weights)
a_ = np.column_stack(
[self.trn_PC_wts,
np.ones(self.trn_PC_wts.shape[0])])
X = np.stack([np.linalg.lstsq(a=a_, b=b_[:, i], rcond=None)[0]
for i in range(b_.shape[-1])])
# X has shape (nparams, q)
return X
def make_PC_param_regr_fig(self):
'''
make a figure that compares each parameter against the PC
combination that most closely predicts it
'''
# how many params are there?
# try to make a square grid, but if impossible, add another row
nparams = self.metadata_a.shape[1]
gs, fig = figures_tools.gen_gridspec_fig(N=nparams)
# regression result
A = self.find_PC_param_coeffs()
for i in range(nparams):
# set up subplots
ax = fig.add_subplot(gs[i])
x = np.column_stack([self.trn_PC_wts,
np.ones(self.trn_PC_wts.shape[0])])
y = self.metadata_a[:, i]
y_regr = A[i].dot(x.T).flatten()
ax.scatter(y_regr, y, marker='.', facecolor='b', edgecolor='None',
s=1., alpha=0.4)
xgrid = np.linspace(y.min(), y.max())
ax.plot(xgrid, xgrid, linestyle='--', c='g', linewidth=1)
ax_ = ax.twinx()
ax_.set_ylim([0., 1.])
ax_.text(x=y_regr.min(), y=0.85, s=self.metadata_TeX[i], size=6)
# rms
rms = np.sqrt(np.mean((y_regr - y)**2))
ax_.text(x=y_regr.min(), y=0.775, s='rms = {:.3f}'.format(rms),
size=6)
locx = mticker.MaxNLocator(nbins=5, steps=[1, 2, 5, 10])
locy = mticker.MaxNLocator(nbins=5, steps=[1, 2, 5, 10])
locy_ = mticker.NullLocator()
ax.xaxis.set_major_locator(locx)
ax.yaxis.set_major_locator(locy)
ax_.yaxis.set_major_locator(locy_)
ax.tick_params(axis='both', color='k', labelsize=6)
fig.suptitle(t=r'$Z + A \cdot X$ vs $\{P_i\}$')
fig.savefig(os.path.join(self.basedir, 'param_regr_{}.png'.format(self.src)),
dpi=300)
def make_PC_param_importance_fig(self):
fig = plt.figure(figsize=(4, 3), dpi=300)
ax = fig.add_subplot(111)
X = self.find_PC_param_coeffs()[:, :-1] # (p, q)
C = self.trn_PC_wts # (n, q)
P = self.metadata_a # (n, p)
N_PC_a = np.abs(X[:, None, :] * C[None, :, :]).sum(axis=1)
F_PC_a = N_PC_a / N_PC_a.sum(axis=1)[:, None]
cyc_color = cycler(color=['#1b9e77','#d95f02','#7570b3'])
# qualitative colorblind cycle from ColorBrewer
cyc_marker = cycler(marker=['o', '>', 's', 'd', 'x'])
cyc_prop = cyc_marker * cyc_color
p, q = X.shape
for i, (sty, k) in enumerate(zip(cyc_prop,
self.metadata.colnames)):
# plot each param's dependence on each PC
TeX = self.metadata[k].meta.get('TeX', k)
pc_num = np.linspace(1, q, q)
fpc = F_PC_a[i, :]
ax.plot(pc_num, fpc, label=TeX, markersize=2,
**sty)
ax.set_xlabel('PC')
ax.set_xticks(np.linspace(1, q, q).astype(int))
ax.set_ylabel(r'$F_{PC}(\alpha)$')
ax.legend(loc='best', prop={'size': 5})
ax2 = ax.twinx()
ax2.plot(np.linspace(1, q, q), (1. - self.PVE.cumsum()),
c='c', linestyle='--', marker='None')
ax2.set_yscale('log')
ax2.set_ylim([1.0e-3, 1.])
ax2.set_ylabel('fraction unexplained variance', size=5)
ax2.yaxis.label.set_color('c')
ax2.tick_params(axis='y', colors='c', labelsize=5)
ax.set_xlim([0, q + 1.5])
plt.tight_layout()
plt.savefig(
os.path.join(
self.basedir, 'PC_param_importance_{}.png'.format(self.src)),
dpi=300)
def make_prior_fig(self):
nparams = len(self.metadata.colnames)
gs, fig = figures_tools.gen_gridspec_fig(N=nparams)
for i, n in enumerate(self.metadata.colnames):
# set up subplots
ax = fig.add_subplot(gs[i])
label = self.metadata[n].meta.get('TeX', n)
ax.hist(self.metadata[n].flatten(), bins=50, histtype='step',
linewidth=0.5)
ax.tick_params(labelsize='xx-small')
ax.set_yticks([])
ax.set_xlabel(label, size='x-small')
plt.tight_layout()
plt.savefig(
os.path.join(
self.basedir, 'prior_allparams.png'))
# =====
# properties
# =====
@property
def Cov_th(self):
R = (self.normed_trn_spectra - self.mean_trn_spectrum) - \
self.trn_recon
return np.cov(R)
@property
def l_lower(self):
return 10.**(self.logl - self.dlogl / 2)
@property
def l_upper(self):
return 10.**(self.logl + self.dlogl / 2)
@property
def dl(self):
return self.l_upper - self.l_lower
# =====
# under the hood
# =====
def __str__(self):
return 'PCA object: q = {0[0]}, l = {0[1]}'.format(self.PCs.shape)
class PCAError(Exception):
'''
general error for PCA
'''
pass
class PCProjectionWarning(UserWarning):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class HistFailedWarning(UserWarning):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def select_cubesequence_from_start(a, i0, nl):
'''
select sequence along axis of cube with different starting indices
'''
mapshape = a.shape[-2:]
# construct map indexing arrays
II, JJ = np.meshgrid(*map(range, mapshape), indexing='ij')
II, JJ = II[None, ...], JJ[None, ...]
# all axis-0 indices for left-contributors
LL_all = np.arange(nl, dtype=int)[:, None, None] + i0[None, :, :]
LL_all_split = np.array_split(LL_all, 100, axis=0)
# contributor arrays: we extract all at once because advanced indexing
# copies data, and this means we only have to do it once per flux or ivar
a_all = np.concatenate([a[LL_sect, II, JJ] for LL_sect in LL_all_split], axis=0)
return a_all
def conservative_maskprop(a, i0, nl):
'''
propagate masks in most conservative fashion: masked pixels,
and their neighbors, are all masked
'''
mask = np.logical_or.reduce(
[select_cubesequence_from_start(a, i0 + m, nl) for m in [-1, 0, 1]])
return mask
class PCA_Result(object):
'''
store results of PCA for one galaxy using this
'''
def __init__(self, pca, dered, K_obs, z, cosmo, figdir='.',
truth=None, truth_sfh=None, dered_method='nearest',
dered_kwargs={}, pc_cov_method='full_iter',
cov_sys_incr=4.0e-4):
self.objname = dered.drp_hdulist[0].header['plateifu']
self.pca = pca
self.dered = dered
self.cosmo = cosmo
self.z = z
self.K_obs = K_obs
self.truth = truth # known-truth parameters for fake data
self.truth_sfh = truth_sfh # known-true SFH for fake data
# where to save all figures
self.figdir = figdir
self.__setup_figdir__()
self.E = pca.PCs
self.l = 10.**self.pca.logl
self.M = self.pca.M
self.O, self.ivar, self.mask_spax = dered.correct_and_match(
template_logl=pca.logl, template_dlogl=pca.dlogl,
method=dered_method, dered_kwargs=dered_kwargs)
# compute starting index of obs cov for each spaxel
self.i0_map = self.pca._compute_i0_map(self.K_obs.logl, self.dered.z_map)