-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvisualization_utils.py
2026 lines (1705 loc) · 78.6 KB
/
visualization_utils.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
# began with: https://hst-docs.stsci.edu/hstdhb/files/60242993/67928432/1/1594401324445/HSTDHB.pdf
from astropy.io import fits
from astropy.wcs import WCS
from astropy.coordinates import SkyCoord
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
from astropy.visualization import simple_norm
import pandas as pd
from PIL import Image
import warnings
import matplotlib as mpl
import os
import shutil
from lenstronomy.LightModel.light_model import LightModel
from lenstronomy.Util.data_util import cps2magnitude, magnitude2cps
import pickle
from scipy.ndimage import rotate
from scipy.stats import multivariate_normal
from paltas.Configs.config_handler import ConfigHandler
from paltas.Utils.cosmology_utils import get_cosmology, absolute_to_apparent
from paltas.Analysis import posterior_functions
import corner
import seaborn as sns
import sys
from matplotlib.lines import Line2D
import h5py
# define some global colors to standardize plotting
palette = sns.color_palette('muted').as_hex()
COLORS = {
'prior':palette[7],
'hyperparam':palette[3],
'hyperparam_narrow':palette[1],
'unweighted_NPE':palette[0],
'reweighted_NPE':palette[4]
}
"""
Functions:
print_header(file_name)
header_ab_zeropoint(hdu)
amp_2_apparent_mag(model_name,model_kwargs,ab_zeropoint)
ps_amp_2_apparent_mag(amp,ab_zeropoint)
ps_image2source_magnitude(magnitudes,magnifications,ab_zeropoint)
log_norm(data,min_cutoff=1e-6)
residuals_norm(im_diff)
load_psf_from_pickle(results_file)
matrix_plot(image_folder,df,indices,dim,save_name,PlotCenter=True)
matrix_plot_from_npy(file_list,names,dim,save_name)
plot_compare_prior_datset(params_list,df,priors_dict,title,
df_suffix='_STRIDES_median',special_set=None)
prior_corner_plot(prior_dict,N)
prior_corner_plot_slow(paltas_config_file,N)
plot_coverage(y_pred,y_test,std_pred,parameter_names,
fontsize=20,show_error_bars=True,n_rows=4,bin_min=0.9,bin_max=250)
table_metrics(y_pred,y_test,std_pred,outfile)
"""
#######################
# Ignore wcs warnings
#######################
warnings.filterwarnings("ignore")
#######################
# Print entire header
#######################
def print_header(file_name):
"""
Args:
file_name: path to .fits file
"""
with fits.open(file_name) as hdu:
print(hdu[0].header)
#########################################
# Get AB zeropoint magnitude from header
#########################################
# sources:
# https://hst-docs.stsci.edu/acsdhb/chapter-5-acs-data-analysis/5-1-photometry
# https://www.stsci.edu/hst/instrumentation/acs/data-analysis/zeropoints
def header_ab_zeropoint(hdu):
"""
Args:
hdu: opened .fits file object
"""
# mean flux density (erg*cm^-2*s^-1*angstrom)
photflam = hdu[0].header['PHOTFLAM']
# pivot wavelength (angstrom)
photplam = hdu[0].header['PHOTPLAM']
return -2.5*np.log10(photflam) -5*np.log10(photplam) - 2.408
##################################
# Amplitude to Apparent Magnitude
##################################
# note amplitude is surface brightness at R_sersic
def amp_2_apparent_mag(model_name,model_kwargs,ab_zeropoint):
"""
Args:
model_name (string): lenstronomy SOURCE model name
model_kwargs (dict): lenstronomy source model parameters
ab_zeropoint (float): AB magnitude zeropoint
"""
# get cps from amplitude
sersic_model = LightModel([model_name])
# returns list
integrated_flux = sersic_model.total_flux([model_kwargs])[0]
# get magnitude from cps
magnitude = cps2magnitude(integrated_flux,ab_zeropoint)
return magnitude
##############################################
# Point Source Amplitude to Apparent Magnitude
##############################################
def ps_amp_2_apparent_mag(amp,ab_zeropoint):
"""
Args:
amp (float): Amplitude in cps of point source
ab_zeropoint (float): AB magnitude zeropoint
Returns:
mag (float): Apparent magnitude of point source
"""
mag = cps2magnitude(amp,ab_zeropoint)
return mag
#####################################################################
# Point source image magnitudes + magnifications to source magnitude
#####################################################################
def ps_image2source_magnitude(magnitudes,magnifications,ab_zeropoint):
"""
Args:
magnitudes ([float]): AB magnitudes of point source images
magnifications ([float]): Magnification of each point source image
ab_zeropoint (float): AB magnitude zeropoint
Returns:
magnitude_source (float): apparent magnitude of unlensed point source
"""
# compute counts per second from image magnitudes
cps_magnified = []
for m in magnitudes:
cps = magnitude2cps(m,ab_zeropoint)
cps_magnified.append(cps)
cps_magnified = np.asarray(cps_magnified)
# de-magnify counts per second
magnifications = np.asarray(magnifications)
cps_demagnified = cps_magnified / np.abs(magnifications)
# convert de-magnified cps back to magnitudes
avg_cps = np.average(cps_demagnified)
magnitude_source = cps2magnitude(avg_cps,ab_zeropoint)
return magnitude_source
#############
# log norm
#############
def log_norm(data,min_cutoff=1e-6):
norm = simple_norm(data,stretch='log',min_cut=min_cutoff)
return norm
########################################
# Create blue to red norm for residuals
########################################
def residuals_norm(im_diff):
if np.amin(im_diff) > 0:
norm = colors.TwoSlopeNorm(vmin=-0.001,vcenter=0,vmax=np.amax(im_diff))
elif np.amax(im_diff) < 0:
norm = colors.TwoSlopeNorm(vmin=np.amin(im_diff), vcenter=0, vmax=0.001)
else:
norm = colors.TwoSlopeNorm(vmin=np.amin(im_diff), vcenter=0, vmax=np.amax(im_diff))
return norm
#######################################
# Load psf map from pickle results file
#######################################
def load_psf_from_pickle(results_file):
f = open(results_file,'rb')
(multi_band_list, kwargs_model, kwargs_result,
image_likelihood_mask_list) = pickle.load(f)
f.close()
return multi_band_list[0][1]['kernel_point_source']
#################################
# Function to create matrix plot
#################################
def matrix_plot(image_folder,df,indices,dim,save_name,PlotCenter=True,
show_one_arcsec=True):
"""
Args:
image_folder (string): Name/path of folder storing .fits files
df (pandas dataframe): Dataframe containing all info from lens catalog
.csv file
indices (numpy array): List of indices of which systems to plot
dim (int,int): Tuple of (number rows, number columns), defines shape of
matrix plotted
save_name (string): Filename to save final image to
PlotCenter (boolean): If True, plots small red star in center of image
show_one_arcsec (boolean): If True, plots 1 arcsec bar in top left corner
"""
# extract info from dataframe
filenames = df['file_prefix'].to_numpy()
system_names = df['name'].to_numpy()
ra_adjust = df['ra_adjust'].to_numpy()
dec_adjust = df['dec_adjust'].to_numpy()
cutout_size = df['cutout_size'].to_numpy()
# append -1 to indices to fill empty spots manually
if dim[0]*dim[1] > len(indices):
# num empty spots to fill
num_fill = dim[0]*dim[1] - len(indices)
# append -1 num_fill times
for m in range(0,num_fill):
indices = np.append(indices,-1)
# edge case: not enough spaces given for # of images
if dim[0]*dim[1] < len(indices):
print("Matrix not big enough to display all lens images." +
"Retry with larger matrix dimensions. Exiting matrix_plot()")
return
# initalize loop variables
file_counter = 0
completed_rows = []
# TODO: check to see if this folder already exists
os.mkdir('intermediate_temp')
# prevent matplotlib from showing intermediate plots
backend_ = mpl.get_backend()
mpl.use("Agg") # Prevent showing stuff
# iterate through matrix & fill each image
for i in range(0,dim[0]):
row = []
for j in range(0,dim[1]):
file_idx = int(indices[file_counter])
# fill empty spot (index = -1)
if file_idx == -1:
plt.matshow(np.ones((100,100)),cmap='Greys_r',dpi=300)
plt.axis('off')
plt.savefig(intm_name,bbox_inches='tight',pad_inches=0)
img_data = np.asarray(Image.open(intm_name))
row.append(img_data)
continue
to_open = image_folder + filenames[file_idx] + '_F814W_drc_sci.fits'
with fits.open(to_open) as hdu:
# keep track of which system currently working with
#print(system_names[file_idx])
# read in data
data = hdu[0].data
# reflect dec axis for correct E/W convention
data = np.flip(data,axis=0)
wcs = WCS(hdu[0].header)
ra_targ = hdu[0].header['RA_TARG']
dec_targ = hdu[0].header['DEC_TARG']
#print("ra: %.3f, dec: %.3f"%(ra_targ,dec_targ))
# print zeropoint
#print("zeropoint ", file_idx, ": ", header_ab_zeropoint(hdu))
# apply any needed adjustments to center of lens system
ra_targ = ra_targ + ra_adjust[file_idx]
dec_targ = dec_targ + dec_adjust[file_idx]
# retrieve array coordinates of lens center
x_targ,y_targ = wcs.world_to_array_index(SkyCoord(ra=ra_targ,
dec=dec_targ,unit="deg"))
# transform x_targ to reflected dec coordinates
num_x_pixels = hdu[0].header['NAXIS2']
x_targ = int(x_targ - 2*(x_targ - (num_x_pixels/2)))
# find out # arseconds per pixel
arcseconds_per_pixel = hdu[0].header['D003SCAL']
#print("%.3f arcseconds per pixel"%(arcseconds_per_pixel))
# retreive offset and crop data
offset = int(cutout_size[file_idx]/2)
cropped_data = data[x_targ-offset:x_targ+offset,
y_targ-offset:y_targ+offset]
# normalize data using log and min cutoff
norm = simple_norm(cropped_data,stretch='log',min_cut=1e-6)
# create individual image using plt library
plt.figure(dpi=300)
plt.matshow(cropped_data,cmap='viridis',norm=norm)
if PlotCenter:
plt.scatter(offset,offset,edgecolors='red',marker='*',
facecolors='none',s=100)
# annotate system name
plt.annotate(system_names[file_idx],(2*offset - offset/8,offset/6),color='white',
fontsize=17,horizontalalignment='right')
# show size of 1 arcsec
if show_one_arcsec:
if file_counter == 0:
plt.plot([offset/6,offset/6],[offset/8,
offset/8 + (1/arcseconds_per_pixel)],color='white')
plt.annotate('1"',(offset/6 +2,offset/2),color='white',fontsize=20)
plt.axis('off')
# save intermediate file, then read back in as array, and save to row
intm_name = ('intermediate_temp/'+ df['file_prefix'].to_numpy()[file_idx]
+'.png')
plt.savefig(intm_name,bbox_inches='tight',pad_inches=0)
img_data = np.asarray(Image.open(intm_name))
plt.close()
row.append(img_data)
# manually iterate file index
file_counter += 1
# stack each row horizontally in outer loop
# edge case: one column
if dim[1] == 1:
build_row = row[0]
else:
build_row = np.hstack((row[0],row[1]))
if dim[1] > 2:
for c in range(2,dim[1]):
build_row = np.hstack((build_row,row[c]))
completed_rows.append(build_row)
# reset matplotlib s.t. plots are shown
mpl.use(backend_) # Reset backend
# clean up intermediate files
shutil.rmtree('intermediate_temp')
# stack rows to build final image
# edge case: one row
if dim[0] == 1:
final_image = completed_rows[0]
else:
final_image = np.vstack((completed_rows[0],completed_rows[1]))
if dim[0] > 2:
for r in range(2,dim[0]):
final_image = np.vstack((final_image,completed_rows[r]))
# plot image and save
plt.figure(figsize=(2*dim[1],2*dim[0]),dpi=300)
plt.imshow(final_image)
plt.axis('off')
plt.savefig(save_name,bbox_inches='tight')
plt.show()
def matrix_plot_from_folder(folder_path,save_path):
"""Takes in a folder with .npy images and returns a default grid of images
For more flexibility, see matrix_plot_from_npy
Args:
folder_path (string): path to folder w/ .npy images created by paltas
save_path (string): path to save final image to
Returns:
"""
file_list = []
names=[]
for i in range(0,100):
file_list.append(folder_path+'image_%07d.npy'%(i))
names.append(str(i))
matrix_plot_from_npy(file_list[:40],names,(4,10),save_path,annotate=False)
def matrix_plot_from_h5(file_name,dim,save_name):
"""
Args:
file_name (string): path to .h5 file storing images
dim (int,int): Tuple of (number rows, number columns), defines shape of
matrix plotted
save_name (string): Filename to save final image to
"""
# load in .h5 file
f = h5py.File(file_name, "r")
f_data = f['data'][()]
print('size of dataset: ',f_data.shape)
# TODO: check to see if this folder already exists
os.mkdir('intermediate_temp')
# prevent matplotlib from showing intermediate plots
backend_ = mpl.get_backend()
mpl.use("Agg") # Prevent showing stuff
file_counter = 0
completed_rows = []
offset = 40
for i in range(0,dim[0]):
row = []
for j in range(0,dim[1]):
cropped_data = f_data[file_counter]
# normalize data using log and min cutoff
norm = simple_norm(cropped_data,stretch='log',min_cut=1e-6)
# create individual image using plt library
plt.figure(dpi=300)
plt.matshow(cropped_data,cmap='viridis',norm=norm)
plt.axis('off')
# save intermediate file, then read back in as array, and save to row
intm_name = ('intermediate_temp/'+ str(file_counter)
+'.png')
plt.savefig(intm_name,bbox_inches='tight',pad_inches=0)
img_data = np.asarray(Image.open(intm_name))
plt.close()
row.append(img_data)
# manually iterate file index
file_counter += 1
# stack each row horizontally in outer loop
# edge case: one column
if dim[1] == 1:
build_row = row[0]
else:
build_row = np.hstack((row[0],row[1]))
if dim[1] > 2:
for c in range(2,dim[1]):
build_row = np.hstack((build_row,row[c]))
completed_rows.append(build_row)
# reset matplotlib s.t. plots are shown
mpl.use(backend_) # Reset backend
# clean up intermediate files
shutil.rmtree('intermediate_temp')
# stack rows to build final image
# edge case: one row
if dim[0] == 1:
final_image = completed_rows[0]
else:
final_image = np.vstack((completed_rows[0],completed_rows[1]))
if dim[0] > 2:
for r in range(2,dim[0]):
final_image = np.vstack((final_image,completed_rows[r]))
# plot image and save
plt.figure(figsize=(2*dim[1],2*dim[0]),dpi=300)
plt.imshow(final_image)
plt.axis('off')
plt.savefig(save_name,bbox_inches='tight')
plt.show()
###############################
# Matrix plot from numpy files
###############################
def matrix_plot_from_npy(file_list,names,dim,save_name,annotate=False,
show_one_arcsec=False,rotate_data=False):
"""
Args:
file_list ([string]): paths of .npy files
names ([string]): labels for images
dim (int,int): Tuple of (number rows, number columns), defines shape of
matrix plotted
save_name (string): Filename to save final image to
annotate (bool): If True, plots label at top of image
show_one_arcsec (bool): If True, plots 1" bar at top left of each image
rotate_data (bool): If True, mirrors image & rotates 180 deg. (to account
for a mismatch in ra/dec convention)
"""
# edge case: not enough spaces given for # of images
if dim[0]*dim[1] < len(file_list):
print("Matrix not big enough to display all lens images." +
"Retry with larger matrix dimensions. Exiting matrix_plot()")
return
# TODO: check to see if this folder already exists
os.mkdir('intermediate_temp')
# prevent matplotlib from showing intermediate plots
backend_ = mpl.get_backend()
mpl.use("Agg") # Prevent showing stuff
file_counter = 0
completed_rows = []
offset = 40
for i in range(0,dim[0]):
row = []
for j in range(0,dim[1]):
plt.figure(dpi=300)
if file_list[file_counter] is None:
cropped_data = np.zeros((80,80))
else:
cropped_data = np.load(file_list[file_counter])
if rotate_data:
cropped_data = np.rot90(cropped_data,2)
# normalize data using log and min cutoff
norm = simple_norm(cropped_data,stretch='log',min_cut=1e-6)
# create individual image using plt library
if names[file_counter] is not None:
plt.matshow(cropped_data,cmap='viridis',norm=norm)
else:
plt.matshow(cropped_data,cmap='binary')
if annotate and file_list[file_counter] is not None:
# annotate system name
plt.annotate(names[file_counter],(2*offset - offset/8,offset/6),color='white',
fontsize=17,horizontalalignment='right')
if show_one_arcsec and file_list[file_counter] is not None:
if file_counter == 0:
# show size of 1 arcsec
plt.plot([offset/6,offset/6],[offset/8,
offset/8 + (1/0.04)],color='white')
plt.annotate('1"',(offset/6 +2,offset/2),color='white',fontsize=20)
plt.axis('off')
# save intermediate file, then read back in as array, and save to row
if names[file_counter] is None:
intm_name = 'intermediate_temp/none.png'
else:
intm_name = ('intermediate_temp/'+ names[file_counter]
+'.png')
plt.savefig(intm_name,bbox_inches='tight',pad_inches=0)
img_data = np.asarray(Image.open(intm_name))
plt.close()
row.append(img_data)
# manually iterate file index
file_counter += 1
# stack each row horizontally in outer loop
# edge case: one column
if dim[1] == 1:
build_row = row[0]
else:
build_row = np.hstack((row[0],row[1]))
if dim[1] > 2:
for c in range(2,dim[1]):
build_row = np.hstack((build_row,row[c]))
completed_rows.append(build_row)
# reset matplotlib s.t. plots are shown
mpl.use(backend_) # Reset backend
# clean up intermediate files
shutil.rmtree('intermediate_temp')
# stack rows to build final image
# edge case: one row
print(np.shape(completed_rows[0]))
print(np.shape(completed_rows[1]))
if dim[0] == 1:
final_image = completed_rows[0]
else:
final_image = np.vstack((completed_rows[0],completed_rows[1]))
if dim[0] > 2:
for r in range(2,dim[0]):
final_image = np.vstack((final_image,completed_rows[r]))
# plot image and save
plt.figure(figsize=(2*dim[1],2*dim[0]),dpi=300)
plt.imshow(final_image)
plt.axis('off')
plt.savefig(save_name,bbox_inches='tight')
plt.show()
#############################
# Compare Priors to Eachother
#############################
def plot_compare_priors(params_list,priors_dicts,title):
"""
Args:
params_list (list): list of strings of param names to be plotted
priors_dict ([dictionaries]): dictionaries contain a scipy.stats random
variable for each parameter
(key = param name, value = scipy.stats rv)
and a label for plot legend (key='label', value = string)
title (string): title name for plot, and name of file saved
"""
supported_params = {'theta_E','gamma','q','phi','gamma_ext','phi_ext',
'source_redshift','lens_redshift','lens_n_sersic','lens_R_sersic',
'lens_q','lens_phi','lens_magnitude','source_n_sersic',
'source_R_sersic','point_source_magnitude'}
# TODO: subplots
num_r = 2
num_c = int(np.ceil(np.size(params_list)/2))
fig, ax = plt.subplots(num_r, num_c,figsize=(10*num_c,7.5*num_r))
p_index = 0
for r in range(0,num_r):
for c in range(0,num_c):
if num_c ==1:
axis = ax[r]
else:
axis = ax[r,c]
# skip last box for odd-number params
if p_index >= np.size(params_list):
axis.axis('off')
continue
p = params_list[p_index]
# skip params not in .csv log
if p not in supported_params:
# skip to next iteration
print("Skipping parameter: ", p)
print("Not supported by plot_compare_prior()")
axis.axis('off')
continue
# use .rvs() samples to define x-range of plot
rv = []
rv_samples = []
for dict in priors_dicts:
dist = dict[p]
rv.append(dist)
samples = dist.rvs(100)
rv_samples.append(samples)
# TODO: Debug this
x_min = np.min(np.min(rv_samples))
x_max = np.max(np.max(rv_samples))
x = np.linspace(x_min-0.1,x_max+0.1,100)
# Plot priors
for i,dist in enumerate(rv):
axis.plot(x,dist.pdf(x),label=priors_dicts[i]['label'])
axis.get_yaxis().set_ticks([])
# label axes
axis.set_title(p,fontsize=15)
axis.legend(fontsize=12)
p_index += 1
plt.subplots_adjust(wspace=0.2,hspace=0.4)
plt.suptitle(title)
plt.savefig(title+'.png',bbox_inches='tight')
plt.show()
###########################
# Compare Dataset to Prior
###########################
def plot_compare_prior_dataset(params_list,priors_dict,title,df=None,
df_suffix='_STRIDES_median',special_set=None):
"""
args:
params_list (list): list of strings of param names to be plotted
priors_dict (dictionary): contains a scipy.stats random variable for
each parameter (key = param name, value = scipy.stats rv)
title (string): title name for plot, and name of file saved
df (pandas dataframe): all info from lens catalog .csv. If None, does
not scatter parameter values on top of pdfs
df_suffix (string): suffix that defines which parameter values to use
from the .csv (i.e. from forward modeling, BNN results, etc.)
special_set (list): list of strings of system names that will be
highlighted on scatter plot
"""
supported_params = {'theta_E','gamma','q','phi','gamma_ext','phi_ext',
'source_redshift','lens_redshift','lens_n_sersic','lens_R_sersic',
'lens_q','lens_phi','lens_magnitude','source_n_sersic',
'source_R_sersic','point_source_magnitude'}
# TODO: subplots
num_r = 2
num_c = int(np.ceil(np.size(params_list)/2))
fig, ax = plt.subplots(num_r, num_c,figsize=(6*num_c,4*num_r))
p_index = 0
for r in range(0,num_r):
for c in range(0,num_c):
# skip last box for odd-number params
if p_index >= np.size(params_list):
ax[r,c].axis('off')
continue
p = params_list[p_index]
# skip params not in .csv log
if p not in supported_params:
# skip to next iteration
print("Skipping parameter: ", p)
print("Not supported by plot_compare_prior()")
ax[r,c].axis('off')
continue
# use .rvs() samples to define x-range of plot
rv = priors_dict[p]
rv_samples = rv.rvs(100)
# load in parameter values to scatter
if df is not None:
if p in {'source_redshift','lens_redshift'} :
param_vals = df[p].to_numpy()
# special case for lens magnitude
elif p == 'lens_magnitude':
amplitudes = df['lens_SB_STRIDES_median'].to_numpy()
param_vals = []
for i in range(0,np.size(amplitudes)):
# ellipticity translation
q = df['lens_q_STRIDES_median'][i]
phi = df['lens_phi_STRIDES_median'][i]
e1 = (1 - q)/(1+q) * np.cos(2*phi)
e2 = (1 - q)/(1+q) * np.sin(2*phi)
# lenstronomy key word arguments for SERSIC_ELLIPSE
kwa = {'amp': amplitudes[i],
'R_sersic': df['lens_R_sersic_STRIDES_median'][i],
'n_sersic': df['lens_n_sersic_STRIDES_median'][i],
'e1': e1,
'e2': e2,
'center_x': 0,
'center_y': 0}
# amp 2 mag conversion
mag = amp_2_apparent_mag('SERSIC_ELLIPSE',kwa,
df['AB_zeropoint'][i])
param_vals.append(mag)
# final array of magnitudes
param_vals = np.asarray(param_vals)
# special case for point source magnitude
elif p == 'point_source_magnitude':
param_vals = []
for i in range(0,len(df['name'])):
# skip case where lens not fitted by STRIDES
if df['lens_R_sersic_STRIDES_median'][i] == np.nan:
continue
# load in image magnitudes & magnifications, AB zeropoint
ps_magnitudes = [df['image_A_magnitude_STRIDES_median'][i],
df['image_B_magnitude_STRIDES_median'][i],
df['image_C_magnitude_STRIDES_median'][i],
df['image_D_magnitude_STRIDES_median'][i]]
ps_magnifications = [df['image_A_magnif_STRIDES_median'][i],
df['image_B_magnif_STRIDES_median'][i],
df['image_C_magnif_STRIDES_median'][i],
df['image_D_magnif_STRIDES_median'][i]]
ab_zeropoint = df['AB_zeropoint'][i]
# convert to source apparent magnitude
source_mag = ps_image2source_magnitude(ps_magnitudes,
ps_magnifications,ab_zeropoint)
param_vals.append(source_mag)
# final array of magnitudes
param_vals = np.asarray(param_vals)
# all other parameters
else:
param_vals = df[p+df_suffix].to_numpy()
# get rid of nans from lens w/out fit results
param_vals = param_vals[~np.isnan(param_vals)]
# if q or q_ext, must transform from degrees to radians
if p in {'phi','phi_ext','lens_phi'}:
param_vals = np.radians(param_vals)
# plot prior pdf
if df is None:
x_min = np.min(rv_samples)
x_max = np.max(rv_samples)
else:
x_min = np.min((np.min(rv_samples),np.min(param_vals)))
x_max = np.max((np.max(rv_samples),np.max(param_vals)))
x = np.linspace(x_min-0.1,x_max+0.1,100)
ax[r,c].plot(x,rv.pdf(x),label='Prior')
# highlight 2-component lens light points for lens magnitude
if p == 'lens_magnitude' and df is not None:
n_sersic = df['lens_n_sersic_STRIDES_median'].to_numpy()
n_sersic = n_sersic[~np.isnan(n_sersic)]
ax[r,c].scatter(param_vals[n_sersic==4.0],
rv.pdf(param_vals[n_sersic==4.0]),
color='orange',s=30,
label='2-Component Lens')
ax[r,c].scatter(param_vals[n_sersic!=4.0],
rv.pdf(param_vals[n_sersic!=4.0]),
color='red',s=30,label='Single Component Lens')
# normal scatter for other parameters
elif df is not None:
ax[r,c].scatter(param_vals,rv.pdf(param_vals),color='red',
s=30,label='STRIDES')
# highlight special subset on all scatters
if special_set is not None:
names = df['name'].to_numpy()
names = names[~np.isnan(
df['lens_SB_STRIDES_median'].to_numpy())]
first_name = True
for name in special_set:
if first_name:
ax[r,c].scatter(param_vals[names==name],
rv.pdf(param_vals[names==name]),color='limegreen',
s=100,marker='*',label='Subset')
first_name = False
else:
ax[r,c].scatter(param_vals[names==name],
rv.pdf(param_vals[names==name]),color='limegreen',
s=100,marker='*')
ax[r,c].get_yaxis().set_ticks([])
# label axes
ax[r,c].set_title(p,fontsize=10)
if p_index == 0 or p == 'lens_magnitude':
ax[r,c].legend(fontsize=7)
p_index += 1
plt.subplots_adjust(wspace=0.2,hspace=0.4)
plt.suptitle(title)
plt.savefig(title+'.png',bbox_inches='tight')
plt.show()
def prior_corner_plot(prior_dict,N):
"""
Args:
prior_dict (dictionary): Dictionary containing callable scipy.stats
objects for each parameter
N (int): number of samples
"""
gamma_samples = prior_dict['main_deflector']['gamma_lens'](size=N)
theta_E_samples = prior_dict['main_deflector']['theta_E'](size=N)
q_samples = prior_dict['main_deflector']['q'](size=N)
phi_samples = prior_dict['main_deflector']['phi'](size=N)
gamma_ext_samples = prior_dict['main_deflector']['gamma_ext'](size=N)
phi_ext_samples = prior_dict['main_deflector']['phi_ext'](size=N)
data = np.hstack((gamma_samples.reshape([N,1]),theta_E_samples.reshape([N,1]),
q_samples.reshape([N,1]),phi_samples.reshape([N,1]),
gamma_ext_samples.reshape([N,1]),phi_ext_samples.reshape([N,1])))
corner.corner(data,labels=['$\gamma_{lens}$',
'\u03B8$_E$','$q_{lens}$','$\phi_{lens}$','$\gamma_{ext}$','$\phi_{ext}$'],
color='tab:grey',fill_contours=True,alpha=0.5,smooth=1.5,
plot_datapoints=False,levels=[0.68, 0.95])
plt.savefig('corner_plot.png')
def retrieve_paltas_samples_slow(paltas_config_file,component_param_dict,
num_params,num_samples):
"""
Loops through sampling method used by paltas and returns samples for
chosen parameters
Args:
paltas_config_file (string): path to paltas config file
component_param_dict (dict): dictionary with keys that specify a
paltas component, and values that are a list of params
i.e. dict = {
'main_deflector_parameters':['gamma','theta_E',...],
'source_parameters':['n_sersic',...],
...
}
num_params (int): number parameters (needed to allocate array)
num_samples (int): number desired samples
"""
config_handler = ConfigHandler(paltas_config_file)
samples = np.empty((num_samples,num_params))
for i in range(0,num_samples):
row = []
config_handler.draw_new_sample()
sample = config_handler.get_current_sample()
for k in component_param_dict.keys():
for param in component_param_dict[k]:
row.append(sample[k][param])
samples[i] = np.asarray(row)
return samples
def prior_corner_plot_slow(paltas_config_file,N,doppel_files=None):
"""
Slower verion, loops thru sampling method used by paltas
Args:
paltas_config_file (string): Paltas config file
N (int): number of samples
doppel_files [string]: list of doppelganger paltas config files
"""
config_handler = ConfigHandler(paltas_config_file)
cosmology_params = {
'cosmology_name': 'planck18'
}
cosmo = get_cosmology(cosmology_params)
######################
# Lens Mass Parameters
######################
num_params = 7
data_lm = np.empty((N,num_params))
for i in range(0,N):
row = []
config_handler.draw_new_sample()
sample = config_handler.get_current_sample()
row.append(sample['main_deflector_parameters']['gamma'])
row.append(sample['main_deflector_parameters']['theta_E'])
row.append(sample['main_deflector_parameters']['e1'])
row.append(sample['main_deflector_parameters']['e2'])
row.append(sample['main_deflector_parameters']['gamma1'])
row.append(sample['main_deflector_parameters']['gamma2'])
row.append(sample['main_deflector_parameters']['z_lens'])
data_lm[i] = np.asarray(row)
corner.corner(data_lm,labels=['$\gamma_{lens}$',
'\u03B8$_E$ (")','$e1$','$e2$','$\gamma1$','$\gamma2$','$z_{lens}$'],
label_kwargs={'fontsize': 20},color='tab:grey',fill_contours=True,
alpha=0.5,smooth=1.5,plot_datapoints=False,levels=[0.68, 0.95])
plt.suptitle('Lens Parameters Prior',fontsize=20)
####################
# Source Parameters
####################
num_params = 4
data_b = np.empty((N,num_params))
for i in range(0,N):
row = []
config_handler.draw_new_sample()
sample = config_handler.get_current_sample()
row.append(sample['lens_light_parameters']['R_sersic'])
row.append(sample['lens_light_parameters']['n_sersic'])
row.append(sample['source_parameters']['R_sersic'])
row.append(sample['source_parameters']['n_sersic'])
data_b[i] = np.asarray(row)
figure = corner.corner(data_b,labels=['$R$_$sersic_{lens}$',
'$n$_$sersic_{lens}$','$R$_$sersic_{src}$', '$n$_$sersic_{src}$'],
label_kwargs={'fontsize': 20},color='tab:grey',fill_contours=True,
alpha=0.5,smooth=1.5,
plot_datapoints=False,levels=[0.68, 0.95])
plt.suptitle('Sersic Prior',fontsize=20)
axes_sersic = np.array(figure.axes).reshape((num_params, num_params))
#######################
# Magnitude Parameters
#######################
num_params = 3
data_b = np.empty((N,num_params))
for i in range(0,N):
row = []
config_handler.draw_new_sample()
sample = config_handler.get_current_sample()
row.append(sample['lens_light_parameters']['mag_app'])
row.append(sample['source_parameters']['mag_app'])
row.append(sample['point_source_parameters']['mag_app'])
data_b[i] = np.asarray(row)
figure = corner.corner(data_b,labels=['$app$_$mag_{lens}$',
'$app$_$mag_{src}$','$app$_$mag_{ps}$'],label_kwargs={'fontsize': 20},
color='tab:grey',fill_contours=True,alpha=0.5,smooth=1.5,
plot_datapoints=False,levels=[0.68, 0.95])
plt.suptitle('Magnitudes Prior',fontsize=20)
axes = np.array(figure.axes).reshape((num_params, num_params))
#######################
# Source / Lens Center
#######################
num_params = 4
data_b = np.empty((N,num_params))
for i in range(0,N):
row = []
config_handler.draw_new_sample()
sample = config_handler.get_current_sample()
row.append(sample['main_deflector_parameters']['center_x'])
row.append(sample['main_deflector_parameters']['center_y'])