-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlensing_etc.py
1684 lines (1422 loc) · 66 KB
/
lensing_etc.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
# -*- coding: utf-8 -*-
"""
"""
import matplotlib.pyplot as plt
import numpy as np
import copy
import pickle
from tqdm.auto import trange
from scipy.ndimage import binary_dilation
from mpl_toolkits.axes_grid1 import make_axes_locatable
import lenstronomy.Util.data_util as data_util
import lenstronomy.Util.util as util
import lenstronomy.Plots.plot_util as plot_util
from lenstronomy.Util.param_util import phi_q2_ellipticity
from lenstronomy.SimulationAPI.sim_api import SimAPI
from lenstronomy.Workflow.fitting_sequence import FittingSequence
from lenstronomy.Plots.model_plot import ModelPlot
from lenstronomy.LightModel.light_model import LightModel
from lenstronomy.LensModel.lens_model import LensModel
from lenstronomy.LensModel.lens_model_extensions import LensModelExtensions
from lenstronomy.LensModel.Solver.lens_equation_solver import LensEquationSolver
# plot settings
import seaborn as sns
# to change tex to Times New Roman in mpl
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = 'Times New Roman'
plt.rcParams['mathtext.rm'] = 'serif'
plt.rcParams['mathtext.it'] = 'serif:italic'
plt.rcParams['mathtext.bf'] = 'serif:bold'
plt.rcParams['mathtext.fontset'] = 'custom'
def set_fontscale(font_scale=1):
sns.set(style='ticks', context=None,
font='Times New Roman',
rc={#"text.usetex": True,
#"font.family": 'serif',
#"font.serif": 'Times New Roman',
#"mathtext.rm": 'serif',
#"mathtext.it": 'serif:italic',
#"mathtext.bf": 'serif:bold',
#"mathtext.fontset": 'custom',
"xtick.direction": "in",
"ytick.direction": "in",
"axes.linewidth": 0.5*font_scale,
"axes.labelsize": 9*font_scale,
"font.size": 9*font_scale,
"axes.titlesize": 9*font_scale,
"legend.fontsize": 8*font_scale,
"xtick.labelsize": 8*font_scale,
"ytick.labelsize": 8*font_scale,
})
set_fontscale(2.)
palette = sns.color_palette('muted', 8)
palette.as_hex()
class LensingETC(object):
"""
Contains all the methods to simulate and model mock lenses, and plot the
results.
"""
def __init__(self, lens_specifications=None, filter_specifications=None,
observing_scenarios=None, psfs=None,
magnitude_distributions=None, use_pemd=False,
source_galaxy_indices=[], source_galaxy_shapelet_coeffs=None
):
"""
Setup the `LensingETC` class for simulation if arguments are provided.
It is possible to create an instance without passing any argument to
plot and examine the outputs.
:param lens_specifications: description of the lens sample
:type lens_specifications: `dict`
:param filter_specifications: description of the filters
:type filter_specifications: `dict`
:param observing_scenarios: description of the observing scenarios
:type observing_scenarios: `list`
:param psfs: PSFs for simulation and modeling
:type psfs: `dict`
:param magnitude_distributions: sampling functions for the magnitudes
:type magnitude_distributions: `dict`
:param use_pemd: if `True`, use FASTELL code, requires installation
of fastell4py package
:type use_pemd: `bool`
:param source_galaxy_indices: (optional) list of indices can be
provided to
select specific galaxy morphologies as sources, this list can be
curated by inspecting the galaxy structures with the notebook
source_galaxies/Inspect source galaxy structure.ipynb. If
source_galaxy_indices=None, then source galaxies wll be randomly
selected. If not provided, random source galaxies will be used.
:type source_galaxy_indices: `list`
:param source_galaxy_shapelet_coeffs: (optional) array containing
shapelet coefficients for source galaxies. If not provided,
a pre-existing library of galaxies will be used.
:type source_galaxy_shapelet_coeffs: `numpy.array`
"""
do_simulation = False
if np.any([a is not None for a in
[lens_specifications, filter_specifications,
observing_scenarios, magnitude_distributions]]
):
if np.any([a is None for a in
[lens_specifications, filter_specifications,
observing_scenarios, magnitude_distributions]]
):
raise ValueError("One/more from lens_specifications, "
"filter_specifications, "
"observing_scenarios, "
"magnitude_distributions is not provided!")
else:
do_simulation = True
if do_simulation:
self.num_lenses = lens_specifications['num_lenses']
self._with_point_source = lens_specifications['with_point_source']
self.filter_specifications = filter_specifications
self.observing_scenarios = observing_scenarios
self.simulation_psfs = psfs['simulation']
self.modeling_psfs = psfs['modeling']
if 'psf_uncertainty_level' in psfs:
self._psf_uncertainty_level = psfs['psf_uncertainty_level']
else:
self._psf_uncertainty_level = 0.5
self.lens_magnitude_distributions = magnitude_distributions['lens']
self.source_magnitude_distributions = magnitude_distributions['source']
if self._with_point_source:
self.quasar_magnitude_distributions = magnitude_distributions[
'quasar']
self.num_pixels = self.filter_specifications['num_pixel']
self.pixel_scales = self.filter_specifications['pixel_scale']
self.num_filters = self.filter_specifications['num_filter']
self.num_scenarios = len(self.observing_scenarios)
self._kwargs_model = {
'lens_model_list': ['PEMD' if use_pemd else 'EPL', 'SHEAR'],
'lens_light_model_list': ['SERSIC_ELLIPSE'],
'source_light_model_list': ['SHAPELETS'],
'point_source_model_list': ['SOURCE_POSITION'] if
self._with_point_source else []
}
self._kwargs_model_smooth_source = {
'lens_model_list': ['PEMD' if use_pemd else 'EPL', 'SHEAR'],
'lens_light_model_list': ['SERSIC_ELLIPSE'],
'source_light_model_list': ['SERSIC_ELLIPSE'],
'point_source_model_list': ['SOURCE_POSITION'] if
self._with_point_source else []
}
self._shapelet_coeffs = np.load(
'source_galaxy_shapelet_coefficients_nmax50.npz')['arr_0']
self._kwargs_lenses = []
self._source_positions = []
self._lens_ellipticities = []
self._source_ellipticities = []
if self._with_point_source:
self._image_positions = []
else:
self._image_positions = None
if not source_galaxy_indices:
source_galaxy_indices = np.random.randint(0,
len(self._shapelet_coeffs), self.num_lenses)
if source_galaxy_shapelet_coeffs is None:
self._source_galaxy_shapelet_coeffs = self._shapelet_coeffs[
source_galaxy_indices]
else:
self._source_galaxy_shapelet_coeffs = \
source_galaxy_shapelet_coeffs
for j in range(self.num_lenses):
q = np.random.uniform(0.7, 0.9)
phi = np.random.uniform(-90, 90)
self._lens_ellipticities.append([q, phi])
e1, e2 = phi_q2_ellipticity(phi*np.pi/180, q)
theta_E = np.random.uniform(1.2, 1.6)
self._kwargs_lenses.append([
{'theta_E': theta_E,
'gamma': np.random.uniform(1.9, 2.1),
'e1': e1,
'e2': e2,
'center_x': 0, 'center_y': 0},
{'gamma1': np.random.uniform(-0.08, 0.08),
'gamma2': np.random.uniform(-0.08, 0.08),
'ra_0': 0,
'dec_0': 0}
])
r = np.random.uniform(0.05, 0.35) * theta_E
phi = np.random.uniform(-np.pi, np.pi)
self._source_positions.append([r * np.cos(phi), r * np.sin(phi)])
self._source_ellipticities.append([
np.random.uniform(-0.3, 0.3), np.random.uniform(-0.3, 0.3)
])
if self._with_point_source:
self._image_positions.append(
self._get_point_image_positions(
self._kwargs_lenses[-1],
self._source_positions[-1]
))
self._weighted_exposure_time_maps = \
self._get_weighted_exposure_time_maps()
self.sim_apis = self._get_sim_apis(self._kwargs_model)
self.sim_apis_smooth_source = self._get_sim_apis(
self._kwargs_model_smooth_source)
self.image_sims = self._get_image_sims(self.sim_apis)
self._kwargs_light = self._get_kwargs_light()
self.simulated_data = self._simulate_data()
self._walker_ratio = 8
def _get_point_image_positions(self, kwargs_lens,
source_position):
"""
Solve the lens equation to get the image position.
:param kwargs_lens: lens model parameters in lenstronomy convention
:type kwargs_lens:
:param source_position: x and y positions of source
:type source_position: `tuple`
:return:
:rtype:
"""
lens_model = LensModel(self._kwargs_model['lens_model_list'])
lens_equation_solver = LensEquationSolver(lens_model)
x_image, y_image = lens_equation_solver.image_position_from_source(
kwargs_lens=kwargs_lens, sourcePos_x=source_position[0],
sourcePos_y=source_position[1], min_distance=0.01,
search_window=5,
precision_limit=10 ** (-10), num_iter_max=100)
return x_image, y_image
def _get_weighted_exposure_time_maps(self):
"""
Simulate cosmic ray hit map and return the weighted exposure time
map for all combinations of lenses and observing scenarios.
:return:
:rtype:
"""
weighted_exposure_time_maps = []
for j in range(self.num_lenses):
weighted_exposure_time_maps_scenarios = []
for n in range(self.num_scenarios):
weighted_exposure_time_maps_filters = []
for i in range(self.num_filters):
simulate_cosmic_ray = False
if 'simulate_cosmic_ray' in self.observing_scenarios[n]:
if not self.observing_scenarios[n][
'simulate_cosmic_ray'][i]:
simulate_cosmic_ray = False
else:
simulate_cosmic_ray = True
if self.observing_scenarios[n][
'simulate_cosmic_ray'][i]:
cosmic_ray_count_rate = 2.4e-3
else:
cosmic_ray_count_rate = \
self.observing_scenarios[n][
'simulate_cosmic_ray'][i]
if simulate_cosmic_ray:
weighted_exposure_time_maps_filters.append(
self._make_weighted_exposure_time_map(
self.observing_scenarios[n]['exposure_time'][i],
self.num_pixels[i],
self.pixel_scales[i],
self.observing_scenarios[n]['num_exposure'][i],
cosmic_ray_count_rate
)
)
else:
weighted_exposure_time_maps_filters.append(
np.ones((self.num_pixels[i], self.num_pixels[i])) *
self.observing_scenarios[n]['exposure_time'][i])
weighted_exposure_time_maps_scenarios.append(
weighted_exposure_time_maps_filters)
weighted_exposure_time_maps.append(
weighted_exposure_time_maps_scenarios)
return weighted_exposure_time_maps
@property
def walker_ratio(self):
"""
Get the emcee walker ratio.
:return:
:rtype:
"""
if hasattr(self, '_walker_ratio'):
return self._walker_ratio
else:
self._walker_ratio = 8
return self._walker_ratio
def set_walker_ratio(self, ratio):
"""
Set the emcee walker ratio.
:param ratio: walker ratio
:type ratio: `int`
:return:
:rtype:
"""
self._walker_ratio = ratio
def plot_simualated_data(self, vmax=None, vmin=None, figsize=None):
"""
Plot the montage of simulated lenses.
:param vmax: `vmax` for plotted lenses' log_10(flux).
:type vmax: `list`
:param vmin: `vmin` for plotted lenses' log_10(flux).
:type vmin: `list`
:param figsize: figure size
:type figsize: `tuple`
:return:
:rtype:
"""
nrows = self.num_lenses
ncols = self.num_scenarios * self.num_filters
fig, axes = plt.subplots(nrows=nrows,
ncols=ncols,
figsize=figsize if figsize else
(max(nrows * 3, 10), max(ncols * 5, 6))
)
if nrows == 1 and ncols == 1:
axes = [[axes]]
elif nrows == 1:
axes = [axes]
elif ncols == 1:
axes = [[ax] for ax in axes]
if vmax is None:
vmax = [2] * self.num_filters
if vmin is None:
vmin = [-4] * self.num_filters
for j in range(self.num_lenses):
for n in range(self.num_scenarios):
for i in range(self.num_filters):
axes[j][n*self.num_filters+i].matshow(
np.log10(self.simulated_data[j][n][i]),
cmap='cubehelix', origin='lower',
vmin=vmin[i],
vmax=vmax[i]
)
axes[j][n * self.num_filters + i].set_xticks([])
axes[j][n * self.num_filters + i].set_yticks([])
axes[j][n * self.num_filters + i].set_aspect('equal')
if j == 0:
axes[j][n * self.num_filters + i].set_title(
'Scenario: {}, filter: {}'.format(n+1, i+1))
if n == 0 and i == 0:
axes[j][n * self.num_filters + i].set_ylabel('Lens: '
'{}'.format(j+1))
fig.tight_layout()
return fig
def plot_exposure_maps(self, figsize=None):
"""
Plot the exposure map montage for all the combinations of lenses and
scenarios.
:param figsize: figure size
:type figsize: `tuple`
:return:
:rtype:
"""
nrows = self.num_lenses
ncols = self.num_scenarios * self.num_filters
fig, axes = plt.subplots(nrows=nrows,
ncols=ncols,
figsize=figsize if figsize else
(max(nrows*3, 10), max(ncols*5, 6))
)
if nrows == 1 and ncols == 1:
axes = [[axes]]
elif nrows == 1:
axes = [axes]
elif ncols == 1:
axes = [[ax] for ax in axes]
for j in range(self.num_lenses):
for n in range(self.num_scenarios):
for i in range(self.num_filters):
im = axes[j][n*self.num_filters+i].matshow(
self._weighted_exposure_time_maps[j][n][i] *
self.observing_scenarios[n]['num_exposure'][i],
cmap='viridis', origin='lower', vmin=0
)
divider = make_axes_locatable(axes[j][
n*self.num_filters+i])
cax = divider.append_axes("right", size="5%", pad=0.05)
plt.colorbar(im, cax=cax, label='(seconds)')
axes[j][n * self.num_filters + i].set_xticks([])
axes[j][n * self.num_filters + i].set_yticks([])
axes[j][n * self.num_filters + i].set_aspect('equal')
if j == 0:
axes[j][n * self.num_filters + i].set_title(
'Scenario: {}, filter: {}'.format(n+1, i+1))
if n == 0 and i == 0:
axes[j][n * self.num_filters + i].set_ylabel('Lens: '
'{}'.format(j+1))
fig.tight_layout()
return fig
def _simulate_data(self):
"""
Simulate data for all the combinations of lenses and scenarios.
:return:
:rtype:
"""
simulated_data_lenses = []
for j in range(self.num_lenses):
simulated_data_scenarios = []
for n in range(self.num_scenarios):
simulated_data_filters = []
for i in range(self.num_filters):
kwargs_lens_light, kwargs_source, \
kwargs_ps = self._kwargs_light[j][n][i]
simulated_image = self.image_sims[j][n][i].image(
self._kwargs_lenses[j],
kwargs_source, kwargs_lens_light, kwargs_ps,
source_add=True, lens_light_add=True,
point_source_add=True if self._with_point_source else False
)
simulated_image[simulated_image < 0] = 1e-10
simulated_image += self.sim_apis[j][n][i].noise_for_model(
model=simulated_image)
simulated_data_filters.append(simulated_image)
simulated_data_scenarios.append(simulated_data_filters)
simulated_data_lenses.append(simulated_data_scenarios)
return simulated_data_lenses
def _get_image_sims(self, sim_apis):
"""
Call the `image_model_class()` method for all the `SimAPI` class
instances for each combination of lens and scenarios.
:param sim_apis: `SimAPI` class instances
:type sim_apis: `list`
:return:
:rtype:
"""
image_sims = []
for j in range(self.num_lenses):
image_sims_scenarios = []
for n in range(self.num_scenarios):
image_sim_filters = []
for i in range(self.num_filters):
kwargs_numerics = {
'point_source_supersampling_factor':
self.filter_specifications[
'simulation_psf_supersampling_resolution'][i],
'supersampling_factor': 3
}
image_sim_filters.append(
sim_apis[j][n][i].image_model_class(kwargs_numerics)
)
image_sims_scenarios.append(image_sim_filters)
image_sims.append(image_sims_scenarios)
return image_sims
def _get_sim_apis(self, kwargs_model):
"""
Create `SimAPI` class instances for each combination of lenses and
scenarios.
:param kwargs_model:
:type kwargs_model:
:return:
:rtype:
"""
sim_apis = []
for j in range(self.num_lenses):
sim_api_scenarios = []
for n in range(self.num_scenarios):
sim_api_filters = []
kwargs_observation = self._get_filter_kwargs(j, n)
for i in range(self.num_filters):
sim_api_filters.append(SimAPI(numpix=self.num_pixels[i],
kwargs_single_band=kwargs_observation[i],
kwargs_model=kwargs_model))
sim_api_scenarios.append(sim_api_filters)
sim_apis.append(sim_api_scenarios)
return sim_apis
def _make_weighted_exposure_time_map(self, exposure_time, num_pixel,
pixel_scale, num_exposure,
cosmic_ray_count_rate=2.4e-3):
"""
Make weighted exposure time map from simulated cosmic ray hit maps.
:param exposure_time: total exposure time
:type exposure_time: `float`
:param num_pixel: number of pixels along one side
:type num_pixel: `int`
:param pixel_scale: size of pixel in arcsecond unit
:type pixel_scale: `float`
:param num_exposure: number of exposures
:type num_exposure: `int`
:param cosmic_ray_count_rate: cosmic ray count rate in
event/s/arcsec^2 unit
:type cosmic_ray_count_rate: `float`
:return:
:rtype:
"""
exposure_time_map = np.ones((num_pixel, num_pixel)) * exposure_time
cosmic_ray_weight_map = 0.
for i in range(num_exposure):
cosmic_ray_count = cosmic_ray_count_rate * (num_pixel *
pixel_scale)**2 * exposure_time
cosmic_ray_weight_map += self._create_cr_hitmap(num_pixel,
pixel_scale,
cosmic_ray_count
)
exposure_time_map *= cosmic_ray_weight_map / num_exposure
# replace 0's with very small number to avoid divide by 0
exposure_time_map[exposure_time_map == 0.] = 1e-10
return exposure_time_map
def _get_filter_kwargs(self, n_lens, scenario_index):
"""
Get dictionary containing filter specifications for each filter for
one scenario.
:param n_lens: index of lense
:type n_lens: `int`
:param scenario_index: index of observing scenario
:type scenario_index: `int`
:return:
:rtype:
"""
filter_kwargs = []
for i in range(self.num_filters):
exposure_time = self._weighted_exposure_time_maps[n_lens][
scenario_index][i]
filter_kwargs.append(
{
'read_noise': self.filter_specifications['read_noise'][i],
'ccd_gain': self.filter_specifications['ccd_gain'][i],
'sky_brightness': self.filter_specifications[
'sky_brightness'][i],
'magnitude_zero_point':
self.filter_specifications[
'magnitude_zero_point'][i],
'exposure_time': exposure_time,
'num_exposures': self.observing_scenarios[
scenario_index]['num_exposure'][i],
'seeing': self.filter_specifications['seeing'][i],
'pixel_scale': self.filter_specifications[
'pixel_scale'][i],
'psf_type': 'PIXEL',
'kernel_point_source': self.simulation_psfs[i],
'point_source_supersampling_factor': self.filter_specifications[
'simulation_psf_supersampling_resolution'][i]
})
return filter_kwargs
def _get_kwargs_light(self):
"""
Get `kwargs_light` for all lenses for lenstronomy.
:return:
:rtype:
"""
kwargs_light_lenses = []
for j in range(self.num_lenses):
kwargs_light_scenarios = []
lens_magnitudes = self.lens_magnitude_distributions()
source_magnitudes = self.source_magnitude_distributions()
if self._with_point_source:
ps_magnitudes = self.quasar_magnitude_distributions()
source_R_sersic = np.random.uniform(0.1, 0.2)
for n in range(self.num_scenarios):
kwargs_light = []
for i in range(self.num_filters):
q, phi = self._lens_ellipticities[j]
e1, e2 = phi_q2_ellipticity(phi*np.pi/180., q)
kwargs_lens_light_mag = [{
'magnitude': lens_magnitudes[i],
'R_sersic': 1.,
'n_sersic': 4,
'e1': e1, 'e2': e2,
'center_x': 0, 'center_y': 0
}]
kwargs_source_light_mag = [{
'magnitude': source_magnitudes[i],
'R_sersic': source_R_sersic,
'n_sersic': 1,
'e1': self._source_ellipticities[j][0],
'e2': self._source_ellipticities[j][0],
'center_x': self._source_positions[j][0],
'center_y': self._source_positions[j][1]
}]
kwargs_ps_mag = [{
'ra_source': self._source_positions[j][0],
'dec_source': self._source_positions[j][1],
'magnitude': ps_magnitudes[i]
}] if self._with_point_source else []
kwargs_lens_light, kwargs_source_smooth, kwargs_ps = \
self.sim_apis_smooth_source[j][n][
i].magnitude2amplitude(
kwargs_lens_light_mag, kwargs_source_light_mag,
kwargs_ps_mag)
smooth_light_model = LightModel(['SERSIC_ELLIPSE'])
shapelet_light_model = LightModel(['SHAPELETS'])
x, y = util.make_grid(200, 0.01)
smooth_flux = np.sum(smooth_light_model.surface_brightness(
x, y, kwargs_source_smooth))
kwargs_source = [{
'n_max': self.filter_specifications[
'simulation_shapelet_n_max'][i],
'beta': source_R_sersic,
'amp': self._source_galaxy_shapelet_coeffs[j],
'center_x': self._source_positions[j][0],
'center_y': self._source_positions[j][1]
}]
shapelet_flux = np.sum(
shapelet_light_model.surface_brightness(
x, y, kwargs_source))
kwargs_source[0]['amp'] *= smooth_flux / shapelet_flux
kwargs_light.append([kwargs_lens_light, kwargs_source,
kwargs_ps])
kwargs_light_scenarios.append(kwargs_light)
kwargs_light_lenses.append(kwargs_light_scenarios)
return kwargs_light_lenses
def _get_kwargs_data(self, n_lens, n_scenario):
"""
Get `kwargs_data` for lenstronomy for one combination of lens and
scenario.
:param n_lens: index of lens
:type n_lens: `int`
:param n_scenario: index of scenario
:type n_scenario: `int`
:return:
:rtype:
"""
kwargs_data_list = []
for i in range(self.num_filters):
kwargs_data_list.append({
'image_data': self.simulated_data[n_lens][n_scenario][i],
'background_rms': self.sim_apis[n_lens][n_scenario][
i].background_noise,
'noise_map': None,
'exposure_time': (self._weighted_exposure_time_maps[n_lens][
n_scenario][i] *
self.observing_scenarios[n_scenario][
'num_exposure'][i]),
'ra_at_xy_0': -(self.num_pixels[i] - 1)/2. * self.pixel_scales[i],
'dec_at_xy_0': -(self.num_pixels[i] - 1)/2. * self.pixel_scales[i],
'transform_pix2angle': np.array([[self.pixel_scales[i], 0],
[0, self.pixel_scales[i]]
])
})
return kwargs_data_list
def _get_kwargs_psf(self):
"""
Get `kwargs_psf` for all filters for lenstronomy.
:return:
:rtype:
"""
kwargs_psf_list = []
for i in range(self.num_filters):
if self._psf_uncertainty_level > 0.:
max_noise = np.max(self.modeling_psfs[i]) * self._psf_uncertainty_level
exposure_time = np.max(self.modeling_psfs[i]) / max_noise**2
# F*t = (N*t)^2
psf_uncertainty = np.sqrt(self.modeling_psfs[i] *
exposure_time) / exposure_time
else:
psf_uncertainty = None
kwargs_psf_list.append({
'psf_type': "PIXEL",
'kernel_point_source': self.modeling_psfs[i],
'kernel_point_source_init': self.modeling_psfs[i],
'psf_error_map': psf_uncertainty,
'point_source_supersampling_factor': self.filter_specifications[
'modeling_psf_supersampling_resolution'][i]
})
return kwargs_psf_list
def _get_kwargs_params(self, n_lens, n_scenario):
"""
Get `kwargs_params` for lenstronomy for one combination of
lense and scenario.
:param n_lens: index of lens
:type n_lens: `int`
:param n_scenario: index of scenario
:type n_scenario: `int`
:return:
:rtype:
"""
# initial guess of non-linear parameters, starting from the truth
# for fast convergence of the MCMC
kwargs_lens_init = self._kwargs_lenses[n_lens]
kwargs_lens_light_init = [
self._kwargs_light[n_lens][n_scenario][i][0][0] for i in range(
self.num_filters)
]
kwargs_source_init = [
self._kwargs_light[n_lens][n_scenario][i][1][0] for i in range(
self.num_filters)
]
for i in range(self.num_filters):
kwargs_source_init[i]['n_max'] = self.filter_specifications[
'modeling_shapelet_n_max'][i]
kwargs_ps_init = [
self._kwargs_light[n_lens][n_scenario][0][2][0]
] if self._with_point_source else []
if self._with_point_source:
num_image = len(self._image_positions[n_lens][0])
kwargs_ps_init[0]['ra_source'] = kwargs_source_init[0]['center_x']
kwargs_ps_init[0]['dec_source'] = kwargs_source_init[0]['center_y']
# kwargs_ps_init[0]['ra_image'] = self._image_positions[n_lens][0]
# kwargs_ps_init[0]['dec_image'] = self._image_positions[n_lens][1]
# initial spread in parameter estimation
kwargs_lens_sigma = [
{'theta_E': 0.01, 'e1': 0.01, 'e2': 0.01, 'gamma': .02,
'center_x': 0.05, 'center_y': 0.05},
{'gamma1': 0.01, 'gamma2': 0.01}]
kwargs_lens_light_sigma = [
{'R_sersic': 0.05, 'n_sersic': 0.1, 'e1': 0.01, 'e2': 0.01,
'center_x': .01, 'center_y': 0.01} for _ in range(
self.num_filters)]
kwargs_source_sigma = [
{'beta': 0.01,
#'n_sersic': .05, 'e1': 0.05, 'e2': 0.05,
'center_x': 0.05, 'center_y': 0.05} for _ in range(
self.num_filters)]
kwargs_ps_sigma = [{#'ra_image': 5e-5*np.ones(num_image),
#'dec_image': 5e-5*np.ones(num_image),
'ra_source': 5e-5,
'dec_source': 5e-5
}] if self._with_point_source else []
# hard bound lower limit in parameter space
kwargs_lower_lens = [
{'theta_E': 0, 'e1': -0.5, 'e2': -0.5, 'gamma': 1.5,
'center_x': -10., 'center_y': -10},
{'gamma1': -0.5, 'gamma2': -0.5}]
kwargs_lower_source = [
{'beta': 0.001,
#'n_sersic': 0.5, 'e1': -0.5, 'e2': -0.5,
'center_x': -10, 'center_y': -10} for _ in range(
self.num_filters)]
kwargs_lower_lens_light = [
{'R_sersic': 0.001, 'n_sersic': 0.5, 'e1': -0.5, 'e2': -0.5,
'center_x': -10, 'center_y': -10} for _ in range(
self.num_filters)]
kwargs_lower_ps = [{#'ra_image': -1.5*np.ones(num_image),
#'dec_image': -1.5*np.ones(num_image),
'ra_source': -1.5,
'dec_source': -1.5
}] if self._with_point_source else []
# hard bound upper limit in parameter space
kwargs_upper_lens = [
{'theta_E': 10, 'e1': 0.5, 'e2': 0.5, 'gamma': 2.5,
'center_x': 10., 'center_y': 10},
{'gamma1': 0.5, 'gamma2': 0.5}]
kwargs_upper_source = [
{'beta': 10,
#'n_sersic': 5., 'e1': 0.5, 'e2': 0.5,
'center_x': 10, 'center_y': 10} for _ in range(self.num_filters)]
kwargs_upper_lens_light = [
{'R_sersic': 10, 'n_sersic': 5., 'e1': 0.5, 'e2': 0.5,
'center_x': 10, 'center_y': 10} for _ in range(self.num_filters)]
kwargs_upper_ps = [{#'ra_image': 1.5*np.ones(num_image),
#'dec_image': 1.5*np.ones(num_image)
'ra_source': 1.5,
'dec_source': 1.5
}] if self._with_point_source else []
# keeping parameters fixed
kwargs_lens_fixed = [{}, {'ra_0': 0, 'dec_0': 0}]
kwargs_source_fixed = [{'n_max': self.filter_specifications[
'modeling_shapelet_n_max'][i]} for i in range(
self.num_filters)]
kwargs_lens_light_fixed = [{} for _ in range(self.num_filters)]
kwargs_ps_fixed = [{}] if self._with_point_source else []
lens_params = [kwargs_lens_init, kwargs_lens_sigma, kwargs_lens_fixed,
kwargs_lower_lens, kwargs_upper_lens]
source_params = [kwargs_source_init, kwargs_source_sigma,
kwargs_source_fixed, kwargs_lower_source,
kwargs_upper_source]
lens_light_params = [kwargs_lens_light_init, kwargs_lens_light_sigma,
kwargs_lens_light_fixed, kwargs_lower_lens_light,
kwargs_upper_lens_light]
ps_params = [kwargs_ps_init, kwargs_ps_sigma, kwargs_ps_fixed,
kwargs_lower_ps, kwargs_upper_ps]
kwargs_params = {'lens_model': lens_params,
'source_model': source_params,
'lens_light_model': lens_light_params,
'point_source_model': ps_params}
return kwargs_params
def _get_multi_band_list(self, n_lens, n_scenario):
"""
Get `multi_band_list` for lenstronomy for one combination of
lense and scenario.
:param n_lens: index of lens
:type n_lens: `int`
:param n_scenario: index of scenario
:type n_scenario: `int`
:return:
:rtype:
"""
kwargs_data_list = self._get_kwargs_data(n_lens, n_scenario)
kwargs_psf_list = self._get_kwargs_psf()
multi_band_list = []
for i in range(self.num_filters):
psf_supersampling_factor = self.filter_specifications[
'simulation_psf_supersampling_resolution'][i]
kwargs_numerics = {'supersampling_factor': 3,
'supersampling_convolution': True if
psf_supersampling_factor > 1 else False,
'supersampling_kernel_size': 5,
'point_source_supersampling_factor':
psf_supersampling_factor,
'compute_mode': 'adaptive',
}
image_band = [kwargs_data_list[i], kwargs_psf_list[i],
kwargs_numerics]
multi_band_list.append(image_band)
return multi_band_list
def _get_kwargs_constraints(self, n_lens, n_scenario):
"""
Get `kwargs_constraints` for lenstronomy for one combination of
lense and scenario.
:param n_lens: index of lens
:type n_lens: `int`
:param n_scenario: index of scenario
:type n_scenario: `int`
:return:
:rtype:
"""
kwargs_constraints = {
'joint_lens_with_light': [[0, 0, ['center_x',
'center_y'
]]] if not
self._with_point_source else [],
'joint_lens_light_with_lens_light': [[0, i, ['center_x',
'center_y',
'e1', 'e2',
'n_sersic'
]] for i
in range(1,
self.num_filters)],
'joint_source_with_source': [[0, i, ['center_x',
'center_y',
'beta'
]] for i
in range(1, self.num_filters)],
'joint_source_with_point_source': [[0, 0]] if self._with_point_source
else [],
# 'num_point_source_list': None,
# 'solver_type': 'None'
}
if self._with_point_source:
num_images = len(self._image_positions[n_lens][0])
# kwargs_constraints['solver_type'] = 'PROFILE_SHEAR' if \
# num_images == 4 else 'CENTER'
# kwargs_constraints['num_point_source_list'] = [num_images]
return kwargs_constraints
def _get_kwargs_likelihood(self, n_lens, n_scenario):
"""
Get `kwargs_likelihood` for lenstronomy for one combination of
lense and scenario.
:param n_lens: index of lens
:type n_lens: `int`
:param n_scenario: index of scenario
:type n_scenario: `int`
:return:
:rtype:
"""
total_exposure_times = np.array(self.observing_scenarios[n_scenario][
'exposure_time']) \
* np.array(self.observing_scenarios[n_scenario][
'num_exposure'])
bands_compute = []
for i in range(self.num_filters):
bands_compute.append(True if total_exposure_times[i] > 0 else False)
mask_list = []
for i in range(self.num_filters):
if 'simulate_cosmic_ray' in self.observing_scenarios[n_scenario]:
if self.observing_scenarios[n_scenario]['simulate_cosmic_ray'][i]:
weighted_exposure_time_map = \
self._weighted_exposure_time_maps[n_lens][n_scenario][i]
mask = np.ones_like(weighted_exposure_time_map)
mask[weighted_exposure_time_map <= 1e-10] = 0.
mask_list.append(mask)
else:
mask_list.append(None)
else:
mask_list.append(None)