Пример #1
0
def read_data(filename='', N=None):

    with open(filename, 'r') as f:
        lines = f.readlines()

    dsets = []

    for line in lines:

        line = line.split(' ')

        n = int(line[0])

        try:
            srcx, srcy = float(line[1]), float(line[2])
        except:
            srcx, srcy = None, None

        x1,x2,x3,x4,y1,y2,y3,y4 = float(line[3]),float(line[7]),float(line[11]),float(line[15]),float(line[4]),\
                                  float(line[8]),float(line[12]),float(line[16])
        m1, m2, m3, m4 = float(line[5]), float(line[9]), float(
            line[13]), float(line[17])
        t1, t2, t3, t4 = float(line[6]), float(line[10]), float(
            line[14]), float(line[18])
        dsets.append(
            Data(x=[x1, x2, x3, x4],
                 y=[y1, y2, y3, y4],
                 m=[m1, m2, m3, m4],
                 t=[t1, t2, t3, t4],
                 source=[srcx, srcy]))
        if N is not None and len(dsets) >= N:
            break

    return dsets
Пример #2
0
class Lens1413_midIR(Quad):

    _xref, _yref = -0.142, 0.561
    x = np.array([0., -0.744, 0.492, -0.354]) - _xref
    y = np.array([0., 0.168, 0.713, 1.040]) - _yref
    m = np.array([1., 0.84, 0.72, 0.4])  # technically flux ratios

    sigma_x = np.array([0.008] * 4)
    sigma_y = np.array([0.008] * 4)
    sigma_m = np.zeros_like(sigma_x)
    zlens, zsrc = 0.9, 2.56

    data = Data(x,
                y,
                m,
                None,
                None,
                sigma_x=sigma_x,
                sigma_y=sigma_y,
                sigma_m=sigma_m)

    identifier = 'lens1413'

    flux_ratio_index = 0

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    gamma_min = 1.9
    gamma_max = 2.2

    srcmin = 0.02
    srcmax = 0.05

    has_satellite = True

    satellite_mass_model = ['SIS']
    satellite_redshift = [zlens]

    satellite_convention = ['phys']
    # from mass center
    satellite_pos_mass = np.array([-1.87, 4.15]) - np.array([_xref, _yref])
    satellite_pos_mass_effective = satellite_pos_mass
    # from light center
    # satellite_pos_light = [-0.1255, -1.3517]
    satellite_kwargs = [{
        'theta_E': 0.63,
        'center_x': satellite_pos_mass_effective[0],
        'center_y': satellite_pos_mass_effective[1]
    }]
Пример #3
0
    def _setup_data(self):

        delta_x = [np.random.normal(0, delta) for delta in self.data.sigma_x]
        delta_y = [np.random.normal(0, delta) for delta in self.data.sigma_x]

        new_m = []
        for i in range(0, len(delta_x)):
            dm = np.random.normal(0, self.data.sigma_m[i])
            new_m.append(self.data.m[i] + dm)

        delta_x, delta_y = np.array(delta_x), np.array(delta_y)

        new_m = np.array(new_m)
        new_x = np.array(self.data.x) + delta_x
        new_y = np.array(self.data.y) + delta_y

        return Data(x=new_x, y=new_y, m=new_m, t=None, source=None, sigma_x=self.data.sigma_x,
                    sigma_y=self.data.sigma_y,
                    sigma_m=self.data.sigma_m)
Пример #4
0
    def export_data(self):

        lens_data = Data(self.x,
                         self.y,
                         self.m,
                         None,
                         None,
                         sigma_x=self.sigma_x,
                         sigma_y=self.sigma_y,
                         sigma_m=None)

        if self.has_satellite:
            satellites = {}
            satellites['lens_model_name'] = self.satellite_mass_model
            satellites['z_satellite'] = self.satellite_redshift
            satellites['kwargs_satellite'] = self.satellite_kwargs
            satellites['position_convention'] = self.satellite_convention

        else:
            satellites = None

        return lens_data, satellites
Пример #5
0
class Lens1413_NL(Quad):

    x = np.array([-0.6, -0.22, 0.137, 0.629])
    y = np.array([-0.418, 0.448, -0.588, 0.117])
    m = np.array([0.93, 0.94, 1, 0.41])

    sigma_x = np.array([0.008] * 4)
    sigma_y = np.array([0.008] * 4)
    sigma_m = np.zeros_like(sigma_x)
    zlens, zsrc = 0.9, 2.56

    data = Data(x,
                y,
                m,
                None,
                None,
                sigma_x=sigma_x,
                sigma_y=sigma_y,
                sigma_m=sigma_m)

    identifier = 'lens1413'

    flux_ratio_index = 0

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    gamma_min = 1.9
    gamma_max = 2.2

    srcmin = 0.02
    srcmax = 0.05

    has_satellite = False

    #satellite_mass_model = ['SIS']
    #satellite_redshift = [2]

    #satellite_convention = ['lensed']
    # from mass center
    #satellite_pos_mass = np.array([2.007, 3.552])
    #satellite_pos_mass_effective = np.array([-2.37, 2.08])
    # from light center
    #satellite_pos_light = [-0.1255, -1.3517]
    #satellite_kwargs = [{'theta_E': 1, 'center_x': satellite_pos_mass[0],
    #                     'center_y': satellite_pos_mass[1]}]

    def optimize_fit(self, kwargs_fit={}, macro_init=None, print_output=False):

        if 'datatofit' in kwargs_fit.keys():
            data = kwargs_fit['datatofit']
            del kwargs_fit['datatofit']
        else:
            data = self.data

        satellites = None
        #satellites['lens_model_name'] = self.satellite_mass_model
        #satellites['z_satellite'] = self.satellite_redshift
        #satellites['kwargs_satellite'] = self.satellite_kwargs
        #satellites['position_convention'] = self.satellite_convention

        kwargs_fit.update({'satellites': satellites})

        kwargs_fit.update({'multiplane': True})

        optdata, optmodel = self._fit(data,
                                      self.solver,
                                      kwargs_fit,
                                      macromodel_init=macro_init,
                                      sat_pos_lensed=True)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def optimize_fit_lensmodel(self,
                               kwargs_fit={},
                               macro_init=None,
                               print_output=False):

        kwargs_fit.update({'identifier': self.identifier})
        optdata, optmodel = self._fit_lensmodel(self.data,
                                                self.solver,
                                                kwargs_fit,
                                                macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def _print_output(self, optdata, optmodel):

        macromodel = optmodel.lens_components[0]

        print('optimized mags: ', optdata.m)
        print('observed mags: ', self.data.m)
        print('lensmodel fit: ')
        print('Einstein radius: ', macromodel.lenstronomy_args['theta_E'])
        print('shear, shear_theta:', macromodel.shear, macromodel.shear_theta)
        print('ellipticity, PA:',
              macromodel.ellip_PA_polar()[0],
              macromodel.ellip_PA_polar()[1])
        print('centroid: ', macromodel.lenstronomy_args['center_x'],
              macromodel.lenstronomy_args['center_y'])
        print('\n')
        print('flux ratios w.r.t. image ' + str(self.fluximg) + ':')
        print('observed: ',
              self.data.compute_flux_ratios(index=self.flux_ratio_index))
        print('recovered: ',
              optdata.compute_flux_ratios(index=self.flux_ratio_index))
Пример #6
0
def compute_fluxratio_distributions(halo_model='', model_args={},
                                    data2fit=None, Ntotal=int, outfilename='', zlens=None, zsrc=None,
                                    start_macromodel=None, identifier=None, satellites=None,
                                    source_size_kpc=None, write_to_file=False, outfilepath=None,
                                    n_restart=1, pso_conv_mean = 100,
                                    source_x = 0, source_y = 0, grid_res = 0.002,
                                    LOS_mass_sheet_front = 7.7,
                                    LOS_mass_sheet_back = 8,
                                    multiplane=True, **kwargs):
    tstart = time()

    data = Data(x=data2fit[0],y=data2fit[1],m=data2fit[2],t=data2fit[3],source=[source_x, source_y])

    if write_to_file:
        assert outfilepath is not None
        assert os.path.exists(outfilepath)

    if start_macromodel is None:
        start_macromodel = get_default_SIE(zlens)
        start_macromodel.redshift = zlens

    if start_macromodel is None:
        start_macromodel = get_default_SIE(zlens)
        start_macromodel.redshift = zlens

    solver = SolveRoutines(zlens=zlens, zsrc=zsrc, temp_folder=identifier)

    # initialize macromodel
    fit_fluxes = []
    shears, shear_pa, xcen, ycen = [], [], [], []

    pyhalo = pyHalo(zlens,zsrc)

    while len(fit_fluxes)<Ntotal:

        #print(str(len(fit_fluxes)) +' of '+str(Ntotal))
        print('rendering... ')
        realization = pyhalo.render(halo_model,model_args)[0]
        print('done.')
        realization = realization.shift_background_to_source(source_x, source_y)

        model_data, system, outputs, _ = solver.hierarchical_optimization(datatofit=data, macromodel=start_macromodel,
                                                                   realization=realization,
                                                                   multiplane=multiplane, n_particles=20,
                                                                   simplex_n_iter=400, n_iterations=300,
                                                                   source_size_kpc=source_size_kpc,
                                                                   optimize_routine='fixed_powerlaw_shear',
                                                                   verbose=True, pso_convergence_mean=pso_conv_mean,
                                                                   re_optimize=False, particle_swarm=True, tol_mag=None,
                                                                     pso_compute_magnification=700,
                                                                   restart=n_restart, grid_res=grid_res,
                                                                     LOS_mass_sheet_front = LOS_mass_sheet_front,
                                                                     LOS_mass_sheet_back = LOS_mass_sheet_back, satellites=satellites,
                                                                     **kwargs)

        for sys,dset in zip(system,model_data):

            if dset.nimg != data.nimg:
                continue

            astro_error = chi_square_img(data.x,data.y,dset.x,dset.y,0.003,reorder=False)

            if astro_error > 1:
                continue

            fit_fluxes.append(dset.flux_anomaly(data, sum_in_quad=False, index=0))

    write_fluxes(fluxratio_data_path+identifier + 'fluxes_'+outfilename+'.txt', fit_fluxes, summed_in_quad=False)
    tend = time()
    runtime = (tend - tstart)*60**-1
    with open(fluxratio_data_path+identifier +'runtime_'+outfilename+'.txt', 'a') as f:
        f.write(str(np.round(runtime, 2))+'\n')
Пример #7
0
class Lens0128(Quad):

    x = np.array([-0.2046459, -0.1066459, 0.3153541, -0.0966459])
    y = np.array([0.10689306, 0.20089306, -0.06510694, -0.14310694])
    m = np.array([1., 0.584, 0.52, 0.506])

    sigma_x = np.array([0.003] * 4)
    sigma_y = np.array([0.003] * 4)
    sigma_m = np.zeros_like(sigma_x)
    zlens, zsrc = 1.145, 3.12

    data = Data(x,
                y,
                m,
                None,
                None,
                sigma_x=sigma_x,
                sigma_y=sigma_y,
                sigma_m=sigma_m)

    identifier = 'lens0128'
    has_satellite = False

    flux_ratio_index = 0

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    gamma_min = 1.95
    gamma_max = 2.2

    srcmin = 0.005
    srcmax = 0.025

    def optimize_fit(self, kwargs_fit={}, macro_init=None, print_output=False):

        if 'datatofit' in kwargs_fit.keys():
            data = kwargs_fit['datatofit']
            del kwargs_fit['datatofit']
        else:
            data = self.data

        optdata, optmodel = self._fit(data,
                                      self.solver,
                                      kwargs_fit,
                                      macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def optimize_fit_lensmodel(self,
                               kwargs_fit={},
                               macro_init=None,
                               print_output=False):

        kwargs_fit.update({'identifier': self.identifier})
        optdata, optmodel = self._fit_lensmodel(self.data,
                                                self.solver,
                                                kwargs_fit,
                                                macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def _print_output(self, optdata, optmodel):

        macromodel = optmodel.lens_components[0]

        print('optimized mags: ', optdata.m)
        print('observed mags: ', self.data.m)
        print('lensmodel fit: ')
        print('Einstein radius: ', macromodel.lenstronomy_args['theta_E'])
        print('shear, shear_theta:', macromodel.shear, macromodel.shear_theta)
        print('ellipticity, PA:',
              macromodel.ellip_PA_polar()[0],
              macromodel.ellip_PA_polar()[1])
        print('centroid: ', macromodel.lenstronomy_args['center_x'],
              macromodel.lenstronomy_args['center_y'])
        print('\n')
        print('flux ratios w.r.t. image ' + str(self.fluximg) + ':')
        print('observed: ',
              self.data.compute_flux_ratios(index=self.flux_ratio_index))
        print('recovered: ',
              optdata.compute_flux_ratios(index=self.flux_ratio_index))
Пример #8
0
class Lens1330(Quad):

    x = np.array([0.226, -0.188, -1.023, 0.463])
    y = np.array([-0.978, -0.99, 0.189, 0.604])
    m = np.array([1., 0.79, 0.41, 0.25])

    sigma_x = np.array([0.005] * 4)
    sigma_y = np.array([0.005] * 4)
    sigma_m = np.zeros_like(sigma_x)
    zsrc, zlens = 1.38, 0.37

    data = Data(x,
                y,
                m,
                None,
                None,
                sigma_x=sigma_x,
                sigma_y=sigma_y,
                sigma_m=sigma_m)

    identifier = 'lens1330'

    flux_ratio_index = 0

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    gamma_min = 1.9
    gamma_max = 2.2

    srcmin = 0.02
    srcmax = 0.05

    #satellite_mass_model = ['SERSIC_ELLIPSE_KAPPA']
    # from mass center
    satellite_pos_mass = np.array([0, 0])

    has_satellite = False

    disk_q, disk_angle = 0.2, 180 * np.arctan(y[0] / x[0]) / np.pi
    disk_angle += 25

    disk_angle *= np.pi / 180
    e1_disk, e2_disk = phi_q2_ellipticity(disk_angle, disk_q)
    satellite_kwargs = [{
        'k_eff': 0.2,
        'R_sersic': 0.5,
        'n_sersic': 1,
        'e1': e1_disk,
        'e2': e2_disk,
        'center_x': 0,
        'center_y': 0
    }]

    def optimize_fit(self, kwargs_fit={}, macro_init=None, print_output=False):

        if 'datatofit' in kwargs_fit.keys():
            data = kwargs_fit['datatofit']
            del kwargs_fit['datatofit']
        else:
            data = self.data

        satellites = None
        #satellites['lens_model_name'] = self.satellite_mass_model
        #satellites['z_satellite'] = [self.zlens]
        #satellites['kwargs_satellite'] = self.satellite_kwargs

        kwargs_fit.update({'satellites': satellites})

        optdata, optmodel = self._fit(data,
                                      self.solver,
                                      kwargs_fit,
                                      macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def optimize_fit_lensmodel(self,
                               kwargs_fit={},
                               macro_init=None,
                               print_output=False):

        kwargs_fit.update({'identifier': self.identifier})
        optdata, optmodel = self._fit_lensmodel(self.data,
                                                self.solver,
                                                kwargs_fit,
                                                macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def _print_output(self, optdata, optmodel):

        macromodel = optmodel.lens_components[0]

        print('optimized mags: ', optdata.m)
        print('observed mags: ', self.data.m)
        print('lensmodel fit: ')
        print('Einstein radius: ', macromodel.lenstronomy_args['theta_E'])
        print('shear, shear_theta:', macromodel.shear, macromodel.shear_theta)
        print('ellipticity, PA:',
              macromodel.ellip_PA_polar()[0],
              macromodel.ellip_PA_polar()[1])
        print('centroid: ', macromodel.lenstronomy_args['center_x'],
              macromodel.lenstronomy_args['center_y'])
        print('\n')
        print('flux ratios w.r.t. image ' + str(self.fluximg) + ':')
        print('observed: ',
              self.data.compute_flux_ratios(index=self.flux_ratio_index))
        print('recovered: ',
              optdata.compute_flux_ratios(index=self.flux_ratio_index))
Пример #9
0
class Lens0435(Quad):

    x = np.array([1.272, 0.306, -1.152, -0.384])
    y = np.array([0.156, -1.092, -0.636, 1.026])
    m = np.array([0.96, 0.976, 1., 0.65])

    time_delay_AB, delta_AB = -8.8, 0.8
    time_delay_AC, delta_AC = -1.1, 0.7
    time_delay_AD, delta_AD = -13.8, 0.9
    delta_time_delay = np.array([delta_AB, delta_AC, delta_AD])

    relative_arrival_times = -np.array([time_delay_AB, time_delay_AC, time_delay_AD])
    sigma_x = np.array([0.008]*4)
    sigma_y = np.array([0.008]*4)
    sigma_m = np.zeros_like(sigma_x)
    zlens, zsrc = 0.45,1.69

    data = Data(x, y, m, None, None,
                         sigma_x = sigma_x, sigma_y = sigma_y,
                         sigma_m=sigma_m)

    identifier = 'lens0435'

    flux_ratio_index = 0

    kwargs_lens_init = [{'theta_E': 1.1695276026313663, 'center_x': -0.018181247306480245, 'center_y': 0.019397076231183395, 'e1': -0.0334362651181225, 'e2': -0.011254590955755551, 'gamma': 1.93},
                        {'gamma1': 0.0451624454972574, 'gamma2': 0.016066946017755886}]

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    gamma_min = 1.9
    gamma_max = 2.2

    srcmin = 0.02
    srcmax = 0.05

    amp_scale = 1000

    kwargs_lens_light = [{'amp': 1500, 'R_sersic': 0.3, 'n_sersic': 4., 'center_x': 0., 'center_y': 0.}]
    kwargs_source_light = [{'amp': 5000, 'R_sersic': 0.035, 'n_sersic': 3., 'center_x': None, 'center_y': None,
                             'e1': -0.05, 'e2': 0.05}]

    has_satellite = True
    satellite_mass_model = ['SIS']
    satellite_redshift = [0.78]

    satellite_convention = ['phys']
    # from mass center
    satellite_pos_mass_observed = np.array([-2.911, 2.339])
    satellite_pos_mass = np.array([-2.27, 1.98])

    kwargs_satellite_light = [None]
    # from light center
    #satellite_pos_light = [-0.1255, -1.3517]
    satellite_kwargs = [{'theta_E': 0.35, 'center_x': satellite_pos_mass[0],
                         'center_y': satellite_pos_mass[1]}]

    @staticmethod
    def relative_time_delays(arrival_times):

        trel = arrival_times[1:] - arrival_times[0]
        return np.array(trel)

    def optimize_fit(self, kwargs_fit={}, macro_init = None, print_output = False):

        if 'datatofit' in kwargs_fit.keys():
            data = kwargs_fit['datatofit']
            del kwargs_fit['datatofit']
        else:
            data = self.data

        satellites = {}
        satellites['lens_model_name'] = self.satellite_mass_model
        satellites['z_satellite'] = self.satellite_redshift
        satellites['kwargs_satellite'] = self.satellite_kwargs
        satellites['position_convention'] = self.satellite_convention

        kwargs_fit.update({'satellites': satellites})

        kwargs_fit.update({'multiplane': True})

        optdata, optmodel = self._fit(data, self.solver, kwargs_fit, macromodel_init=macro_init,
                                      sat_pos_lensed=True)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def optimize_fit_lensmodel(self, kwargs_fit={}, macro_init = None, print_output = False):

        kwargs_fit.update({'identifier': self.identifier})
        optdata, optmodel = self._fit_lensmodel(self.data, self.solver, kwargs_fit, macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def _print_output(self, optdata, optmodel):

        macromodel = optmodel.lens_components[0]

        print('optimized mags: ', optdata.m)
        print('observed mags: ', self.data.m)
        print('lensmodel fit: ')
        print('Einstein radius: ', macromodel.lenstronomy_args['theta_E'])
        print('shear, shear_theta:', macromodel.shear, macromodel.shear_theta)
        print('ellipticity, PA:', macromodel.ellip_PA_polar()[0], macromodel.ellip_PA_polar()[1])
        print('centroid: ', macromodel.lenstronomy_args['center_x'],
              macromodel.lenstronomy_args['center_y'])
        print('\n')
        print('flux ratios w.r.t. image '+str(self.fluximg)+':')
        print('observed: ', self.data.compute_flux_ratios(index=self.flux_ratio_index))
        print('recovered: ', optdata.compute_flux_ratios(index=self.flux_ratio_index))
Пример #10
0
class Lens0712(Quad):

    x = np.array([-0.785, -0.729, 0.027, 0.389])
    y = np.array([-0.142, -0.298, -0.805, 0.317])
    m = np.array([1., 0.843, 0.418, 0.082])

    sigma_x = np.array([0.005]*4)
    sigma_y = np.array([0.005]*4)
    sigma_m = np.zeros_like(sigma_x)
    zlens, zsrc = 0.5, 1.5

    data = Data(x, y, m, None, None,
                         sigma_x = sigma_x, sigma_y = sigma_y,
                         sigma_m=sigma_m)

    identifier = 'lens0712'

    flux_ratio_index = 0

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    gamma_min = 1.9
    gamma_max = 2.2

    srcmin = 0.001
    srcmax = 0.02

    satellite_mass_model = ['SERSIC_ELLIPSE_GAUSS_DEC']
    # from mass center
    satellite_pos_mass = np.array([0, 0])

    disk_q, disk_angle = 0.23, 90 - 59.7

    disk_angle *= np.pi / 180

    disk_angle *= np.pi / 180
    e1_disk, e2_disk = phi_q2_ellipticity(disk_angle, disk_q)
    satellite_kwargs = [{'k_eff': 0.294, 'R_sersic': 0.389, 'n_sersic': 1, 'e1': e1_disk,
                         'e2': e2_disk, 'center_x':satellite_pos_mass[0], 'center_y':satellite_pos_mass[1]}]

    def optimize_fit(self, kwargs_fit={}, macro_init = None, print_output = False):

        if 'datatofit' in kwargs_fit.keys():
            data = kwargs_fit['datatofit']
            del kwargs_fit['datatofit']
        else:
            data = self.data

        satellites = {}
        satellites['lens_model_name'] = self.satellite_mass_model
        satellites['z_satellite'] = [self.zlens]
        satellites['kwargs_satellite'] = self.satellite_kwargs

        kwargs_fit.update({'satellites': satellites})

        optdata, optmodel = self._fit(data, self.solver, kwargs_fit, macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def optimize_fit_lensmodel(self, kwargs_fit={}, macro_init = None, print_output = False):

        kwargs_fit.update({'identifier': self.identifier})
        optdata, optmodel = self._fit_lensmodel(self.data, self.solver, kwargs_fit, macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def _print_output(self, optdata, optmodel):

        macromodel = optmodel.lens_components[0]

        print('optimized mags: ', optdata.m)
        print('observed mags: ', self.data.m)
        print('lensmodel fit: ')
        print('Einstein radius: ', macromodel.lenstronomy_args['theta_E'])
        print('shear, shear_theta:', macromodel.shear, macromodel.shear_theta)
        print('ellipticity, PA:', macromodel.ellip_PA_polar()[0], macromodel.ellip_PA_polar()[1])
        print('centroid: ', macromodel.lenstronomy_args['center_x'],
              macromodel.lenstronomy_args['center_y'])
        print('\n')
        print('flux ratios w.r.t. image '+str(self.fluximg)+':')
        print('observed: ', self.data.compute_flux_ratios(index=self.flux_ratio_index))
        print('recovered: ', optdata.compute_flux_ratios(index=self.flux_ratio_index))
Пример #11
0
class RXJ0911(Quad):

    x = np.array([0.688, 0.946, 0.672, -2.283])
    y = np.array([-0.517, -0.112, 0.442, 0.274])
    m = np.array([0.56, 1., 0.53, 0.24])
    sigma_x = np.array([0.005] * 4)
    sigma_y = np.array([0.005] * 4)
    sigma_m = np.zeros_like(sigma_x)
    zlens, zsrc = 0.77, 2.76

    data = Data(x,
                y,
                m,
                None,
                None,
                sigma_x=sigma_x,
                sigma_y=sigma_y,
                sigma_m=sigma_m)

    identifier = 'lens0911'

    flux_ratio_index = 1

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    gamma_min = 1.9
    gamma_max = 2.2

    srcmin = 0.02
    srcmax = 0.05
    has_satellite = True
    satellite_mass_model = ['SIS']
    satellite_redshift = [0.78]
    satellite_convention = ['phys']
    satellite_pos_mass = [-0.767, 0.657]
    # satellite einstein radius from Blackburne et al. 2011
    satellite_kwargs = [{
        'theta_E': 0.24,
        'center_x': satellite_pos_mass[0],
        'center_y': satellite_pos_mass[1]
    }]

    def optimize_fit(self, kwargs_fit={}, macro_init=None, print_output=False):

        if 'datatofit' in kwargs_fit.keys():
            data = kwargs_fit['datatofit']
            del kwargs_fit['datatofit']
        else:
            data = self.data

        satellites = {}
        satellites['lens_model_name'] = self.satellite_mass_model
        satellites['z_satellite'] = [self.zlens]
        satellites['kwargs_satellite'] = self.satellite_kwargs

        kwargs_fit.update({'satellites': satellites})

        optdata, optmodel = self._fit(data,
                                      self.solver,
                                      kwargs_fit,
                                      macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def optimize_fit_lensmodel(self,
                               kwargs_fit={},
                               macro_init=None,
                               print_output=False):

        kwargs_fit.update({'identifier': self.identifier})
        optdata, optmodel = self._fit_lensmodel(self.data,
                                                self.solver,
                                                kwargs_fit,
                                                macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def _print_output(self, optdata, optmodel):

        macromodel = optmodel.lens_components[0]

        print('optimized mags: ', optdata.m)
        print('observed mags: ', self.data.m)
        print('lensmodel fit: ')
        print('Einstein radius: ', macromodel.lenstronomy_args['theta_E'])
        print('shear, shear_theta:', macromodel.shear, macromodel.shear_theta)
        print('ellipticity, PA:',
              macromodel.ellip_PA_polar()[0],
              macromodel.ellip_PA_polar()[1])
        print('centroid: ', macromodel.lenstronomy_args['center_x'],
              macromodel.lenstronomy_args['center_y'])
        print('\n')
        print('flux ratios w.r.t. image ' + str(self.fluximg) + ':')
        print('observed: ',
              self.data.compute_flux_ratios(index=self.flux_ratio_index))
        print('recovered: ',
              optdata.compute_flux_ratios(index=self.flux_ratio_index))
Пример #12
0
class MockFold(Quad):

    x = np.array([0.71293773, 1.11756729, 0.35865728, -0.96765226])
    y = np.array([-0.98422971, -0.36175659, 1.35996094, -0.2777054])
    m = np.array([1., 0.98428725, 0.39814757, 0.2427231])
    sigma_x = np.array([0.005] * 4)
    sigma_y = np.array([0.005] * 4)

    relative_arrival_times = np.array([13.76955768, 14.53781908, 35.69955131])
    delta_time_delay = np.array([2.0, 2., 2.])

    sigma_m = np.zeros_like(sigma_x)

    kwargs_lens_init = [{
        'theta_E': 1.2,
        'center_x': 0.,
        'center_y': 0.,
        'e1': 0.06,
        'e2': 0.1,
        'gamma': 2.0
    }, {
        'gamma1': -0.07,
        'gamma2': 0.05
    }]

    amp_scale = 1000.
    kwargs_lens_light = [{
        'amp': amp_scale * 1.1,
        'R_sersic': 0.4,
        'n_sersic': 4.,
        'center_x': 0.,
        'center_y': 0.
    }]
    kwargs_source_light = [{
        'amp': amp_scale * 1.6,
        'R_sersic': 0.12,
        'n_sersic': 3.,
        'center_x': None,
        'center_y': None,
        'e1': -0.1,
        'e2': 0.3
    }]

    zlens, zsrc = 0.5, 1.5

    data = Data(x,
                y,
                m,
                None,
                None,
                sigma_x=sigma_x,
                sigma_y=sigma_y,
                sigma_m=sigma_m)

    identifier = 'mockfold'

    flux_ratio_index = 0

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    has_satellite = False

    gamma_min = 1.95
    gamma_max = 2.2

    srcmin = 0.02
    srcmax = 0.05

    @staticmethod
    def relative_time_delays(arrival_times):

        trel = np.array([arrival_times[0], arrival_times[1], arrival_times[3]
                         ]) - arrival_times[2]

        return trel

    def optimize_fit(self, kwargs_fit={}, macro_init=None, print_output=False):

        if 'datatofit' in kwargs_fit.keys():
            data = kwargs_fit['datatofit']
            del kwargs_fit['datatofit']
        else:
            data = self.data

        optdata, optmodel = self._fit(data,
                                      self.solver,
                                      kwargs_fit,
                                      macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def optimize_fit_lensmodel(self,
                               kwargs_fit={},
                               macro_init=None,
                               print_output=False):

        kwargs_fit.update({'identifier': self.identifier})
        optdata, optmodel = self._fit_lensmodel(self.data,
                                                self.solver,
                                                kwargs_fit,
                                                macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def _print_output(self, optdata, optmodel):

        macromodel = optmodel.lens_components[0]

        print('optimized mags: ', optdata.m)
        print('observed mags: ', self.data.m)
        print('lensmodel fit: ')
        print('Einstein radius: ', macromodel.lenstronomy_args['theta_E'])
        print('shear, shear_theta:', macromodel.shear, macromodel.shear_theta)
        print('ellipticity, PA:',
              macromodel.ellip_PA_polar()[0],
              macromodel.ellip_PA_polar()[1])
        print('centroid: ', macromodel.lenstronomy_args['center_x'],
              macromodel.lenstronomy_args['center_y'])
        print('\n')
        print('flux ratios w.r.t. image ' + str(self.fluximg) + ':')
        print('observed: ',
              self.data.compute_flux_ratios(index=self.flux_ratio_index))
        print('recovered: ',
              optdata.compute_flux_ratios(index=self.flux_ratio_index))
Пример #13
0
    def _solve_4imgs(self,
                     lens_systems=None,
                     method=str,
                     identifier='',
                     srcx=None,
                     srcy=None,
                     res=0.001,
                     source_shape='GAUSSIAN',
                     ray_trace=True,
                     source_size_kpc=float,
                     print_mag=False,
                     raytrace_with='',
                     polar_grid=True,
                     arrival_time=False,
                     shr_coords=1,
                     brightimg=None,
                     adaptive_grid=False):

        lenstronomywrap = LenstronomyWrap(cosmo=self.cosmo.astropy,
                                          z_source=self.zsrc)

        if method == 'lensmodel':

            create_directory(self.paths.gravlens_input_path_dump)

            data = []

            solver = GravlensInput(filename=identifier,
                                   zlens=self.zmain,
                                   zsrc=self.zsrc,
                                   identifier=identifier,
                                   paths=self.paths,
                                   cosmology=self.cosmo,
                                   shr_coords=shr_coords)

            for i, system in enumerate(lens_systems):
                full = FullModel(multiplane=system.multiplane)
                for model in system.lens_components:
                    full.populate(
                        SingleModel(lensmodel=model, shr_coords=shr_coords))
                solver.add_lens_system(full)

            outputfile = solver.write_all(data=None,
                                          zlens=self.zmain,
                                          zsrc=self.zsrc,
                                          srcx=srcx,
                                          srcy=srcy,
                                          shr_coords=shr_coords)

            call_lensmodel(inputfile=solver.outfile_path + solver.filename +
                           '.txt',
                           path_2_lensmodel=self.paths.path_2_lensmodel)

            lens_data = read_gravlens_out(fnames=outputfile)
            t0 = time()

            for i, system in enumerate(lens_systems):

                x, y, m, t, nimg = lens_data[i]

                data.append(Data(x=x, y=y, m=m, t=t, source=[srcx, srcy]))

                if ray_trace:

                    if print_mag:
                        print('computing mag #: ', i + 1)

                    source_scale = self.cosmo.kpc_per_asec(self.zsrc)
                    source_size = source_size_kpc * source_scale**-1
                    min_img_separation = min_img_sep(data[i].x, data[i].y)

                    raytracing = raytrace.RayTrace(
                        xsrc=data[i].srcx,
                        ysrc=data[i].srcy,
                        multiplane=system.multiplane,
                        source_size=source_size,
                        res=res,
                        source_shape=source_shape,
                        polar_grid=polar_grid,
                        minimum_image_sep=min_img_separation,
                        adaptive_grid=adaptive_grid)
                    lensModel, kwargs_lens = lenstronomywrap.get_lensmodel(
                        system)
                    fluxes = raytracing.magnification(data[i].x, data[i].y,
                                                      lensModel, kwargs_lens)

                    data[i].set_mag(fluxes)

            if self.clean_up:
                delete_dir(self.paths.gravlens_input_path_dump)

            return data

        elif method == 'lenstronomy':

            data = []

            lenstronomyWrap = LenstronomyWrap(cosmo=self.cosmo.astropy,
                                              z_source=self.zsrc)

            for i, system in enumerate(lens_systems):

                lensModel, kwargs_lens = lenstronomywrap.get_lensmodel(system)

                x_image, y_image = lenstronomyWrap.solve_leq(
                    srcx, srcy, lensModel, kwargs_lens, brightimg)

                source_scale = self.cosmo.kpc_per_asec(self.zsrc)
                source_size = source_size_kpc * source_scale**-1
                min_img_separation = min_img_sep_ranked(x_image, y_image)

                raytracing = raytrace.RayTrace(
                    xsrc=srcx,
                    ysrc=srcy,
                    multiplane=system.multiplane,
                    source_size=source_size,
                    res=res,
                    source_shape=source_shape,
                    polar_grid=polar_grid,
                    minimum_image_sep=min_img_separation,
                    adaptive_grid=adaptive_grid)

                fluxes = raytracing.magnification(x_image, y_image, lensModel,
                                                  kwargs_lens)

                if arrival_time:

                    if system.multiplane:
                        arrival_times = lensModel.arrival_time(
                            x_image, y_image, kwargs_lens)

                    else:
                        arrival_times = [0, 0, 0, 0]
                        #raise Exception('arrival times not yet implemented for single plane')
                        #fermat_potential = lensModel.fermat_potential(x_image,y_image,x_source=srcx,y_source=srcy,kwargs_lens=lensmodel_params)

                    arrival_times -= np.min(arrival_times)
                else:
                    arrival_times = [0, 0, 0, 0]

                data.append(
                    Data(x=x_image,
                         y=y_image,
                         m=fluxes,
                         t=arrival_times,
                         source=[srcx, srcy]))

            return data
Пример #14
0
    def _optimize_4imgs_lenstronomy(self,
                                    lens_systems,
                                    data2fit=None,
                                    tol_source=None,
                                    tol_mag=None,
                                    tol_centroid=None,
                                    centroid_0=None,
                                    n_particles=50,
                                    n_iterations=400,
                                    res=None,
                                    source_shape='GAUSSIAN',
                                    source_size_kpc=None,
                                    polar_grid=None,
                                    optimizer_routine=str,
                                    verbose=bool,
                                    re_optimize=False,
                                    particle_swarm=True,
                                    restart=1,
                                    constrain_params=None,
                                    return_ray_path=False,
                                    pso_convergence_mean=None,
                                    pso_compute_magnification=None,
                                    tol_simplex_params=None,
                                    tol_simplex_func=None,
                                    simplex_n_iter=None,
                                    optimizer_kwargs={},
                                    finite_source_magnification=True,
                                    chi2_mode='source',
                                    tol_image=None,
                                    adaptive_grid=None,
                                    grid_rmax_scale=1):

        data, opt_sys = [], []

        lenstronomyWrap = LenstronomyWrap(cosmo=self.cosmo.astropy,
                                          z_source=self.zsrc)
        assert len(lens_systems) == 1
        for i, system in enumerate(lens_systems):

            compute_fluxes = True
            kwargs_lens, [xsrc, ysrc], [
                x_opt, y_opt
            ], optimizer = lenstronomyWrap.run_optimize(
                system,
                self.zsrc,
                data2fit.x,
                data2fit.y,
                tol_source,
                data2fit.m,
                tol_mag,
                tol_centroid,
                centroid_0,
                optimizer_routine,
                self.zmain,
                n_particles,
                n_iterations,
                verbose,
                restart,
                re_optimize,
                particle_swarm,
                constrain_params,
                pso_convergence_mean=pso_convergence_mean,
                pso_compute_magnification=pso_compute_magnification,
                tol_simplex_params=tol_simplex_params,
                tol_simplex_func=tol_simplex_func,
                simplex_n_iter=simplex_n_iter,
                optimizer_kwargs=optimizer_kwargs,
                chi2_mode=chi2_mode,
                tol_image=tol_image)

            if len(x_opt) != len(data2fit.x) or len(y_opt) != len(data2fit.y):
                print('Warning: optimization found the wrong number of images')

                x_opt, y_opt = lenstronomyWrap.solve_leq(xsrc,
                                                         ysrc,
                                                         optimizer.lensModel,
                                                         kwargs_lens,
                                                         brightimg=True,
                                                         precision_lim=10**-12,
                                                         nitermax=20)

                if len(x_opt) != len(data2fit.x) or len(y_opt) != len(
                        data2fit.y):
                    x_opt = data2fit.x
                    y_opt = data2fit.y
                    compute_fluxes = False

            lensModel = optimizer.lensModel

            if system.multiplane:
                optimizer_kwargs = {}

                if hasattr(optimizer._optimizer, '_mags'):
                    optimizer_kwargs.update(
                        {'magnification_pointsrc': optimizer._optimizer._mags})
                else:
                    mags = lensModel.magnification(x_opt, y_opt, kwargs_lens)
                    optimizer_kwargs.update({'magnification_pointsrc': mags})

                optimizer_kwargs.update({
                    'precomputed_rays':
                    optimizer.lensModel._foreground._rays
                })

                if return_ray_path:

                    xpath, ypath = [], []
                    for xi, yi in zip(x_opt, y_opt):
                        _x, _y, redshifts, Tzlist = lensModel._full_lensmodel.\
                        lens_model.ray_shooting_partial_steps(0, 0, xi,
                                       yi, 0, self.zsrc, kwargs_lens)

                        xpath.append(_x)
                        ypath.append(_y)
                    nplanes = len(xpath[0])
                    x_path, y_path = [], []
                    for ni in range(0, nplanes):

                        arrx = np.array([
                            xpath[0][ni], xpath[1][ni], xpath[2][ni],
                            xpath[3][ni]
                        ])
                        arry = np.array([
                            ypath[0][ni], ypath[1][ni], ypath[2][ni],
                            ypath[3][ni]
                        ])
                        x_path.append(arrx)
                        y_path.append(arry)

                    optimizer_kwargs.update({'path_x': np.array(x_path)})
                    optimizer_kwargs.update({'path_y': np.array(y_path)})
                    optimizer_kwargs.update({'path_Tzlist': Tzlist})
                    optimizer_kwargs.update({'path_redshifts': redshifts})
                else:
                    optimizer_kwargs = None

            if finite_source_magnification and compute_fluxes:
                fluxes = self._ray_trace_finite(
                    x_opt,
                    y_opt,
                    xsrc,
                    ysrc,
                    system.multiplane,
                    lensModel,
                    kwargs_lens,
                    res,
                    source_shape,
                    source_size_kpc,
                    polar_grid,
                    adaptive_grid=adaptive_grid,
                    grid_rmax_scale=grid_rmax_scale)
            elif compute_fluxes:
                try:
                    fluxes = optimizer_kwargs['magnification_pointsrc']
                except:
                    fluxes = np.absolute(
                        lensModel.magnification(x_opt, y_opt, kwargs_lens))
            else:
                fluxes = np.array([np.nan] * 4)

            optimized_sys = self.update_system(lens_system=system,
                                               newkwargs=kwargs_lens,
                                               method='lenstronomy')

            new_data = Data(x_opt, y_opt, fluxes, None, [xsrc, ysrc])
            new_data.sort_by_pos(data2fit.x, data2fit.y)
            data.append(new_data)
            opt_sys.append(optimized_sys)

        return data, opt_sys, optimizer_kwargs, {
            'kwargs_lens': kwargs_lens,
            'lensModel': lensModel,
            'source_x': xsrc,
            'source_y': ysrc
        }
Пример #15
0
    def _optimize_4imgs_lensmodel(self,
                                  lens_systems=None,
                                  data2fit=[],
                                  method=str,
                                  sigmas=None,
                                  identifier='',
                                  opt_routine=None,
                                  ray_trace=True,
                                  return_positions=False,
                                  res=0.0005,
                                  source_shape='GAUSSIAN',
                                  source_size_kpc=float,
                                  print_mag=False,
                                  raytrace_with=None,
                                  polar_grid=False,
                                  solver_type=None,
                                  shr_coords=1):

        if sigmas is None:
            sigmas = [
                self.default_pos_sigma, self.default_flux_sigma,
                self.default_tdelay_sigma
            ]

        lenstronomywrap = LenstronomyWrap(cosmo=self.cosmo.astropy,
                                          z_source=self.zsrc)
        d2fit = [data2fit.x, data2fit.y, data2fit.m, data2fit.t]
        optimized_systems = []

        if os.path.exists(self.paths.gravlens_input_path):
            pass
        else:
            create_directory(self.paths.gravlens_input_path)

        create_directory(self.paths.gravlens_input_path_dump)

        assert opt_routine is not None

        solver = GravlensInput(filename=identifier,
                               zlens=self.zmain,
                               zsrc=self.zsrc,
                               pos_sigma=sigmas[0],
                               flux_sigma=sigmas[1],
                               tdelay_sigma=sigmas[2],
                               identifier=identifier,
                               paths=self.paths,
                               cosmology=self.cosmo,
                               shr_coords=shr_coords)

        for system in lens_systems:

            full = FullModel(multiplane=system.multiplane)

            for i, model in enumerate(system.lens_components):
                full.populate(
                    SingleModel(lensmodel=model, shr_coords=shr_coords))

            solver.add_lens_system(full)

        outputfile = solver.write_all(data=d2fit,
                                      zlens=self.zmain,
                                      zsrc=self.zsrc,
                                      opt_routine=opt_routine,
                                      shr_coords=shr_coords)

        call_lensmodel(inputfile=solver.outfile_path + solver.filename +
                       '.txt',
                       path_2_lensmodel=self.paths.path_2_lensmodel)

        lensdata = []

        for i, name in enumerate(outputfile):

            xvals, yvals, mag_gravlens, tvals, macrovals, srcvals = read_dat_file(
                fname=name)

            lensdata.append(
                Data(x=xvals, y=yvals, m=mag_gravlens, t=tvals,
                     source=srcvals))

            newmacromodel = gravlens_to_kwargs(macrovals,
                                               shr_coords=shr_coords)

            optimized_sys = self.update_system(lens_system=lens_systems[i],
                                               newkwargs=newmacromodel,
                                               method='lensmodel')

            optimized_systems.append(optimized_sys)

        if ray_trace:

            for i, name in enumerate(outputfile):

                if print_mag:
                    print('computing mag #: ', i + 1)

                source_scale = self.cosmo.kpc_per_asec(self.zsrc)
                source_size = source_size_kpc * source_scale**-1

                raytracing = raytrace.RayTrace(
                    xsrc=lensdata[i].srcx,
                    ysrc=lensdata[i].srcy,
                    multiplane=optimized_systems[i].multiplane,
                    source_size=source_size,
                    res=res,
                    source_shape=source_shape,
                    polar_grid=polar_grid)
                lensModel, kwargs_lens = lenstronomywrap.get_lensmodel(
                    optimized_systems[i])
                fluxes = raytracing.magnification(lensdata[i].x, lensdata[i].y,
                                                  lensModel, kwargs_lens)
                lensdata[i].set_mag(fluxes)

        for dataset in lensdata:
            dataset.sort_by_pos(data2fit.x, data2fit.y)

        if self.clean_up:
            delete_dir(self.paths.gravlens_input_path_dump)

        return lensdata, optimized_systems
Пример #16
0
    def _solve_4imgs_lenstronomy(self,
                                 lens_systems,
                                 data2fit=None,
                                 method=str,
                                 sigmas=None,
                                 ray_trace=True,
                                 res=None,
                                 source_shape='GAUSSIAN',
                                 source_size_kpc=None,
                                 print_mag=False,
                                 raytrace_with=None,
                                 polar_grid=True,
                                 solver_type=None,
                                 N_iter_max=None,
                                 brightimg=None,
                                 adaptive_grid=False,
                                 grid_rmax_scale=1):

        data, opt_sys = [], []

        lenstronomyWrap = LenstronomyWrap(cosmo=self.cosmo.astropy,
                                          z_source=self.zsrc)

        for i, system in enumerate(lens_systems):

            lensModel, kwargs_lens = lenstronomyWrap.get_lensmodel(system)

            kwargs_lens, precision = lenstronomyWrap.fit_lensmodel(
                data2fit.x, data2fit.y, lensModel, solver_type, kwargs_lens)

            xsrc, ysrc = lensModel.ray_shooting(data2fit.x, data2fit.y,
                                                kwargs_lens)
            xsrc, ysrc = np.mean(xsrc), np.mean(ysrc)

            x_img, y_img = lenstronomyWrap.solve_leq(xsrc, ysrc, lensModel,
                                                     solver_type, kwargs_lens,
                                                     brightimg)

            if print_mag:
                print('computing mag # ' + str(i + 1) + ' of ' +
                      str(len(lens_systems)))

            source_scale = self.cosmo.kpc_per_asec(self.zsrc)
            source_size = source_size_kpc * source_scale**-1
            img_sep_small = min_img_sep(x_img, y_img)

            raytracing = raytrace.RayTrace(xsrc=xsrc,
                                           ysrc=ysrc,
                                           multiplane=system.multiplane,
                                           source_size=source_size,
                                           res=res,
                                           source_shape=source_shape,
                                           polar_grid=polar_grid,
                                           minimum_image_sep=img_sep_small,
                                           adaptive_grid=adaptive_grid,
                                           grid_rmax_scale=grid_rmax_scale)

            fluxes = raytracing.magnification(x_img, y_img, lensModel,
                                              kwargs_lens)

            optimized_sys = self.update_system(lens_system=system,
                                               newkwargs=kwargs_lens,
                                               method='lenstronomy')

            new_data = Data(x_img, y_img, fluxes, None, [xsrc, ysrc])
            new_data.sort_by_pos(data2fit.x, data2fit.y)
            data.append(new_data)
            opt_sys.append(optimized_sys)

        return data, opt_sys
Пример #17
0
class Lens1608_nosatellite(Quad):

    g1x, g1y = 0.4161, -1.0581
    g2x, g2y = -0.2897, -0.9243

    g2x -= g1x
    g2y -= g1y
    # from Fassnacht et al. 2002
    x = np.array([-0.000, -0.738, -0.7446, 1.1284]) - g1x
    y = np.array([0.000, -1.961, -0.4537, -1.2565]) - g1y
    m = np.array([1., 0.5, 0.51, 0.35])
    sigma_x = np.array([0.005] * 4)
    sigma_y = np.array([0.005] * 4)

    # from Koopmans et al. 2003
    time_delay_AB, delta_AB = -31.5, 1.5
    time_delay_AC, delta_AC = 4.5, 1.5
    time_delay_AD, delta_AD = 45.5, 2.
    # delta_time_delay = np.array([delta_AB, delta_AC, delta_AD])
    # relative_arrival_times = np.array([time_delay_AB, time_delay_AC, time_delay_AD])

    relative_arrival_times = np.array([31., 36., 76.])
    delta_time_delay = np.array([2.0, 1.5, 2.])

    sigma_m = np.zeros_like(sigma_x)

    kwargs_lens_init = [{
        'theta_E': 1.5645290570341535,
        'center_x': -0.026043918948197867,
        'center_y': 0.043138636998329406,
        'e1': 0.6356893557901389,
        'e2': -0.5567562747618204,
        'gamma': 2.08
    }, {
        'gamma1': 0.24062025181584618,
        'gamma2': -0.13850236642865676
    }]

    amp_scale = 1000.
    kwargs_lens_light = [{
        'amp': amp_scale * 1.1,
        'R_sersic': 0.4,
        'n_sersic': 4.,
        'center_x': 0.,
        'center_y': 0.
    }]
    kwargs_source_light = [{
        'amp': amp_scale * 1.6,
        'R_sersic': 0.12,
        'n_sersic': 3.,
        'center_x': None,
        'center_y': None,
        'e1': -0.1,
        'e2': 0.3
    }]

    zlens, zsrc = 0.61, 1.4

    data = Data(x,
                y,
                m,
                None,
                None,
                sigma_x=sigma_x,
                sigma_y=sigma_y,
                sigma_m=sigma_m)

    identifier = 'lens1608'

    flux_ratio_index = 0

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    has_satellite = False

    gamma_min = 1.95
    gamma_max = 2.2

    srcmin = 0.02
    srcmax = 0.05

    @staticmethod
    def relative_time_delays(arrival_times):

        trel = arrival_times[1:] - arrival_times[0]
        trel = [
            abs(trel[0]),
            abs(trel[0]) + trel[1],
            abs(trel[0]) + abs(trel[2])
        ]
        return np.array(trel)

    def optimize_fit(self, kwargs_fit={}, macro_init=None, print_output=False):

        if 'datatofit' in kwargs_fit.keys():
            data = kwargs_fit['datatofit']
            del kwargs_fit['datatofit']
        else:
            data = self.data

        optdata, optmodel = self._fit(data,
                                      self.solver,
                                      kwargs_fit,
                                      macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def optimize_fit_lensmodel(self,
                               kwargs_fit={},
                               macro_init=None,
                               print_output=False):

        kwargs_fit.update({'identifier': self.identifier})
        optdata, optmodel = self._fit_lensmodel(self.data,
                                                self.solver,
                                                kwargs_fit,
                                                macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def _print_output(self, optdata, optmodel):

        macromodel = optmodel.lens_components[0]

        print('optimized mags: ', optdata.m)
        print('observed mags: ', self.data.m)
        print('lensmodel fit: ')
        print('Einstein radius: ', macromodel.lenstronomy_args['theta_E'])
        print('shear, shear_theta:', macromodel.shear, macromodel.shear_theta)
        print('ellipticity, PA:',
              macromodel.ellip_PA_polar()[0],
              macromodel.ellip_PA_polar()[1])
        print('centroid: ', macromodel.lenstronomy_args['center_x'],
              macromodel.lenstronomy_args['center_y'])
        print('\n')
        print('flux ratios w.r.t. image ' + str(self.fluximg) + ':')
        print('observed: ',
              self.data.compute_flux_ratios(index=self.flux_ratio_index))
        print('recovered: ',
              optdata.compute_flux_ratios(index=self.flux_ratio_index))
Пример #18
0
class WFI2033_nosat(Quad):

    x = np.array([-0.751, -0.039, 1.445, -0.668])
    y = np.array([0.953, 1.068, -0.307, -0.585])
    m = np.array([1., 0.65, 0.5, 0.53])

    time_delay_AB, delta_AB = 0, 100
    time_delay_AC, delta_AC = -36.2, 0.8
    time_delay_AD, delta_AD = 23.3, 1.4
    # delta_time_delay = np.array([delta_AB, delta_AC, delta_AD])
    # relative_arrival_times = np.array([time_delay_AB, time_delay_AC, time_delay_AD])

    relative_arrival_times = np.array([0.01, 36.2, 23.3 + 36.2])
    delta_time_delay = np.array(
        [delta_AB, delta_AC,
         np.sqrt(delta_AC**2 + delta_AD**2)])

    sigma_x = np.array([0.005] * 4)
    sigma_y = np.array([0.005] * 4)
    sigma_m = np.zeros_like(sigma_x)
    zsrc, zlens = 1.66, 0.66
    # source redshift from Motta et al

    data = Data(x,
                y,
                m,
                None,
                None,
                sigma_x=sigma_x,
                sigma_y=sigma_y,
                sigma_m=sigma_m)

    identifier = 'lens2033'

    flux_ratio_index = 0

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    gamma_min = 1.9
    gamma_max = 2.1

    kwargs_lens_init = [{
        'theta_E': 1.1741434797426027,
        'center_x': -0.14201456606451995,
        'center_y': -0.020836241161107733,
        'e1': -0.044760164290518836,
        'e2': 0.3139742426542731,
        'gamma': 1.95
    }, {
        'gamma1': 0.10751925181736302,
        'gamma2': 0.011036722994634627
    }]

    kwargs_lens_light = [{
        'amp': 2500,
        'R_sersic': 0.2,
        'n_sersic': 4.,
        'center_x': None,
        'center_y': None
    }]
    kwargs_source_light = [{
        'amp': 1000,
        'R_sersic': 0.08,
        'n_sersic': 2.5,
        'center_x': None,
        'center_y': None,
        'e1': 0.01,
        'e2': -0.14
    }]

    srcmin = 0.02
    srcmax = 0.05
    has_satellite = True
    satellite_mass_model = ['SIS']
    satellite1_pos_mass = [0.245, 2.037]

    satellite_redshift = [zlens]
    satellite_convention = ['phys']

    kwargs_satellite_light = [{
        'amp': 800,
        'R_sersic': 0.1,
        'n_sersic': 3.,
        'center_x': satellite1_pos_mass[0],
        'center_y': satellite1_pos_mass[1]
    }]

    satellite_kwargs = [
        {
            'theta_E': 0.03,
            'center_x': satellite1_pos_mass[0],
            'center_y': satellite1_pos_mass[1]
        },
    ]

    @staticmethod
    def relative_time_delays(arrival_times):

        trel = arrival_times[1:] - arrival_times[0]
        trel = [abs(trel[0]), abs(trel[1]), abs(trel[1]) + abs(trel[2])]
        return np.array(trel)

    def optimize_fit(self, kwargs_fit={}, macro_init=None, print_output=False):

        if 'datatofit' in kwargs_fit.keys():
            data = kwargs_fit['datatofit']
            del kwargs_fit['datatofit']
        else:
            data = self.data

        if 'satellites' not in kwargs_fit.keys():
            satellites = {}

            satellites['lens_model_name'] = self.satellite_mass_model
            satellites['z_satellite'] = self.satellite_redshift
            satellites['kwargs_satellite'] = self.satellite_kwargs
            satellites['position_convention'] = self.satellite_convention

            kwargs_fit.update({'satellites': satellites})

        optdata, optmodel = self._fit(data,
                                      self.solver,
                                      kwargs_fit,
                                      macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def optimize_fit_lensmodel(self,
                               kwargs_fit={},
                               macro_init=None,
                               print_output=False):

        kwargs_fit.update({'identifier': self.identifier})
        optdata, optmodel = self._fit_lensmodel(self.data,
                                                self.solver,
                                                kwargs_fit,
                                                macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def _print_output(self, optdata, optmodel):

        macromodel = optmodel.lens_components[0]

        print('optimized mags: ', optdata.m)
        print('observed mags: ', self.data.m)
        print('lensmodel fit: ')
        print('Einstein radius: ', macromodel.lenstronomy_args['theta_E'])
        print('shear, shear_theta:', macromodel.shear, macromodel.shear_theta)
        print('ellipticity, PA:',
              macromodel.ellip_PA_polar()[0],
              macromodel.ellip_PA_polar()[1])
        print('centroid: ', macromodel.lenstronomy_args['center_x'],
              macromodel.lenstronomy_args['center_y'])
        print('\n')
        print('flux ratios w.r.t. image ' + str(self.fluximg) + ':')
        print('observed: ',
              self.data.compute_flux_ratios(index=self.flux_ratio_index))
        print('recovered: ',
              optdata.compute_flux_ratios(index=self.flux_ratio_index))
Пример #19
0
def test_solving_leq_single_plane():

    multiplane = False
    identifier = 'test_magnipy'

    from MagniPy.magnipy import Magnipy
    from MagniPy.lensdata import Data
    from MagniPy.LensBuild.main_deflector import Deflector
    from MagniPy.MassModels import SIE
    from MagniPy.Solver.solveroutines import SolveRoutines
    import matplotlib.pyplot as plt

    zmain,zsrc = 0.5,1.5
    srcx,srcy = -0.059,0.0065
    pos_sigma = [[0.003] * 4, [0.003] * 4]
    flux_sigma = [.4] * 4
    tdel_sigma = np.array([0, 2, 2, 2]) * 10
    sigmas = [pos_sigma, flux_sigma, tdel_sigma]
    solver = SolveRoutines(0.5, 1,5)
    init = Magnipy(0.5, 1.5, use_lenstronomy_halos=True)

    datax = [-0.6894179,0.4614137,0.05046926,0.3233231]
    datay = [-0.1448493,0.3844455,0.5901034,-0.4361114]
    datam = [ 0.42598153,1,0.75500025,0.36081329]
    datat = [ 0,6.314742,6.777318,9.38729]

    start = {'R_ein': .7, 'ellip': .05, 'ellip_theta': 0, 'x': 0, 'y': 0, 'shear': 0, 'shear_theta': 0}
    start = Deflector(subclass=SIE.SIE(), redshift=zmain, tovary=True,
                      varyflags=['1', '1', '1', '1', '1', '0', '0', '0', '0', '0'], **start)

    data_to_fit = [Data(x=datax,y=datay,m=datam,t=datat,source=[srcx,srcy])]

    profiles = ['NFW']

    for profile in profiles:

        halo_models2 = ["plaw_"+profile+"_[.005]_6_10_[0,1]_['uniformnfw',[3,500]]_1"]

        realizationsdata = init.generate_halos(halo_models2,Nrealizations=1)

        dx,dy = -.01,0
        if profile=='NFW':
            ks = 0.01
            newparams = {'x':data_to_fit[0].x[1]+dx,'y':data_to_fit[0].y[1]+dy,'ks':ks,'rs':0.02}

        realizationsdata[0][0].update(method='lensmodel',**newparams)
        realizationsdata[0] = [realizationsdata[0][0]]

        optimized_lenstronomy,systems = solver.fit_src_plane(macromodel=start, datatofit=data_to_fit[0],
                                                             realizations=realizationsdata, multiplane=multiplane,
                                                             method='lenstronomy', ray_trace=True, sigmas=sigmas,
                                                             identifier=identifier, srcx=srcx, srcy=srcy, grid_rmax=.05,
                                                             res=.001, source_shape='GAUSSIAN', source_size=0.0012)

        optimized_lensmodel,systems = solver.two_step_optimize(macromodel=start, datatofit=data_to_fit[0],
                                                               realizations=realizationsdata, multiplane=multiplane,
                                                               method='lensmodel', ray_trace=True, sigmas=sigmas,
                                                               identifier=identifier, srcx=srcx, srcy=srcy,
                                                               grid_rmax=.05,
                                                               res=.001, source_shape='GAUSSIAN', source_size=0.0012)

        np.testing.assert_almost_equal(optimized_lensmodel[0].m, optimized_lenstronomy[0].m, decimal=2)
        np.testing.assert_almost_equal(optimized_lensmodel[0].x, optimized_lenstronomy[0].x, decimal=4)
        np.testing.assert_almost_equal(optimized_lensmodel[0].y, optimized_lenstronomy[0].y, decimal=4)
        np.testing.assert_almost_equal(optimized_lensmodel[0].x, optimized_lenstronomy[0].x, decimal=4)
        #plt.scatter(optimized_lenstronomy[0].x,optimized_lenstronomy[0].y,color='r',marker='x',alpha=0.5)
        #lt.scatter(optimized_lensmodel[0].x,optimized_lensmodel[0].y,color='k',alpha=0.5)
        #plt.scatter(data_to_fit[0].x,data_to_fit[0].y,color='k',marker='+',s=70,alpha=0.5)
        #plt.scatter(newparams['x'],newparams['y'],color='m',s=50)
        print optimized_lensmodel[0].m
        print optimized_lenstronomy[0].m
Пример #20
0
class Lens0408(Quad):

    x = np.array([1.981, -1.775, -1.895, 0.141])
    y = np.array([-1.495, 0.369, -0.854, 1.466])
    m = np.array([1, 0.7, 0.5, 0.4])

    time_delay_AB, delta_AB = 112, 2.1
    time_delay_AC, delta_AC = 155.5, 12.8
    time_delay_BD = 42.4
    time_delay_AD, delta_AD = time_delay_AB + time_delay_BD, np.sqrt(17.6 ** 2 + 2.1**2)

    delta_time_delay = np.array([delta_AB, delta_AC, delta_AD])
    relative_arrival_times = np.array([time_delay_AB, time_delay_AC, time_delay_AD])

    sigma_x = np.array([0.003]*4)
    sigma_y = np.array([0.003]*4)
    sigma_m = np.zeros_like(sigma_x)
    zsrc, zlens = 2.375, 0.6

    data = Data(x, y, m, None, None,
                         sigma_x = sigma_x, sigma_y = sigma_y,
                         sigma_m=sigma_m)

    identifier = 'lens0408'

    flux_ratio_index = 0

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    gamma_min = 1.9
    gamma_max = 2.1

    has_satellite = True
    satellite_mass_model = ['SIS', 'SIS', 'SIS', 'SIS', 'SIS']

    sat_1_z, sat_2_z = zlens, 0.769
    sat_1_x, sat_1_y = -1.58, -0.95

    # Satellite Einstein radii
    sat_1_thetaE = 0.22
    sat_2_thetaE = 0.77

    # OBSERVED SATELLITE POSITIONS
    #sat_2_x, sat_2_y = 1.08, -6.52

    # PHYSICAL SATELLITE POSITIONS
    sat_2_x, sat_2_y = 1.13, -7.45

    #satellite2_pos_mass_effective = [-3.63, -0.08]

    kwargs_lens_init = [{'theta_E': 1.7220357060940006, 'center_x': 0.1445702226010889, 'center_y': -3.0844186207127455e-06, 'e1': 0.16516965529124017, 'e2': 0.17318780467502645, 'gamma': 1.91894095496809},
                        {'gamma1': 0.10994375051894104, 'gamma2': 0.018505364037691943},
                        ]

    amp_scale = 1000
    kwargs_lens_light = [{'amp': 2500, 'R_sersic': 0.4, 'n_sersic': 3.9, 'center_x': 0., 'center_y': 0.}]
    kwargs_satellite_light = [{'amp': 700., 'R_sersic': 0.15, 'n_sersic': 3.,
                                'center_x': sat_1_x, 'center_y': sat_1_y},
                              None]

    #kwargs_source_light = [{'amp': 1000., 'R_sersic': 0.2, 'n_sersic': 3., 'center_x': None, 'center_y': None,
    #                        'e1': -0.2, 'e2': 0.2}]
    kwargs_source_light = [{'R_sersic': 0.08, 'n_sersic': 4.9, 'center_x': None,
                            'center_y': None, 'amp': 1400, 'e1': 0.045, 'e2': -0.09}]

    satellite_redshift = [zlens, 0.769]
    satellite_convention = ['phys', 'phys']

    satellite_kwargs = [{'theta_E': sat_1_thetaE, 'center_x': sat_1_x, 'center_y': sat_1_y},
                        {'theta_E': sat_2_thetaE, 'center_x': sat_2_x, 'center_y': sat_2_y},
                        ]

    @staticmethod
    def relative_time_delays(arrival_times):

        trel = arrival_times[1:] - arrival_times[0]
        #trel = [abs(trel[0]), abs(trel[1]), abs(trel[0]) + abs(trel[1])]
        return np.array(trel)

    def optimize_fit(self, kwargs_fit={}, macro_init = None, print_output = False):

        if 'datatofit' in kwargs_fit.keys():
            data = kwargs_fit['datatofit']
            del kwargs_fit['datatofit']
        else:
            data = self.data

        if 'satellites' not in kwargs_fit.keys():
            satellites = {}

            satellites['lens_model_name'] = self.satellite_mass_model
            satellites['z_satellite'] = self.satellite_redshift
            satellites['kwargs_satellite'] = self.satellite_kwargs
            satellites['position_convention'] = self.satellite_convention

            kwargs_fit.update({'satellites': satellites})

        optdata, optmodel = self._fit(data, self.solver, kwargs_fit, macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def optimize_fit_lensmodel(self, kwargs_fit={}, macro_init = None, print_output = False):

        kwargs_fit.update({'identifier': self.identifier})
        optdata, optmodel = self._fit_lensmodel(self.data, self.solver, kwargs_fit, macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def _print_output(self, optdata, optmodel):

        macromodel = optmodel.lens_components[0]

        print('optimized mags: ', optdata.m)
        print('observed mags: ', self.data.m)
        print('lensmodel fit: ')
        print('Einstein radius: ', macromodel.lenstronomy_args['theta_E'])
        print('shear, shear_theta:', macromodel.shear, macromodel.shear_theta)
        print('ellipticity, PA:', macromodel.ellip_PA_polar()[0], macromodel.ellip_PA_polar()[1])
        print('centroid: ', macromodel.lenstronomy_args['center_x'],
              macromodel.lenstronomy_args['center_y'])
        print('\n')
        print('flux ratios w.r.t. image '+str(self.fluximg)+':')
        print('observed: ', self.data.compute_flux_ratios(index=self.flux_ratio_index))
        print('recovered: ', optdata.compute_flux_ratios(index=self.flux_ratio_index))
Пример #21
0
class WFI2033_satlocobs(Quad):

    x = np.array([-0.751, -0.039, 1.445, -0.668])
    y = np.array([0.953, 1.068, -0.307, -0.585])
    m = np.array([1., 0.65, 0.5, 0.53])

    time_delay_AB, delta_AB = 0, 100
    time_delay_AC, delta_AC = -36.2, 0.8
    time_delay_AD, delta_AD = 23.3, 1.4
    # delta_time_delay = np.array([delta_AB, delta_AC, delta_AD])
    # relative_arrival_times = np.array([time_delay_AB, time_delay_AC, time_delay_AD])

    relative_arrival_times = np.array([0.01, 36.2, 23.3 + 36.2])
    delta_time_delay = np.array(
        [delta_AB, delta_AC,
         np.sqrt(delta_AC**2 + delta_AD**2)])

    sigma_x = np.array([0.005] * 4)
    sigma_y = np.array([0.005] * 4)
    sigma_m = np.zeros_like(sigma_x)
    zsrc, zlens = 1.66, 0.66
    # source redshift from Motta et al

    data = Data(x,
                y,
                m,
                None,
                None,
                sigma_x=sigma_x,
                sigma_y=sigma_y,
                sigma_m=sigma_m)

    identifier = 'lens2033'

    flux_ratio_index = 0

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    gamma_min = 1.9
    gamma_max = 2.1

    kwargs_lens_init = [{
        'theta_E': 1.0011161129638548,
        'center_x': 0.0035639468432663527,
        'center_y': 0.022250277854418788,
        'e1': 0.013745407369119727,
        'e2': 0.04242065788101877,
        'gamma': 1.95
    }, {
        'gamma1': 0.1849727326105099,
        'gamma2': -0.07557590574285741
    }]

    kwargs_lens_light = [{
        'amp': 2500,
        'R_sersic': 0.2,
        'n_sersic': 4.,
        'center_x': None,
        'center_y': None
    }]
    kwargs_source_light = [{
        'amp': 1000,
        'R_sersic': 0.08,
        'n_sersic': 2.5,
        'center_x': None,
        'center_y': None,
        'e1': 0.01,
        'e2': -0.14
    }]

    srcmin = 0.02
    srcmax = 0.05
    has_satellite = True
    satellite_mass_model = ['SIS', 'SIS']
    satellite1_pos_mass = [0.245, 2.037]
    satellite2_pos_mass = [-3.965, -0.022]

    satellite2_pos_mass_effective = [-3.63, -0.08]

    satellite_redshift = [zlens, 0.745]
    satellite_convention = ['phys', 'phys']
    theta_E = (0.389 * 0.334)**0.5

    kwargs_satellite_light = [{
        'amp': 800,
        'R_sersic': 0.1,
        'n_sersic': 3.,
        'center_x': satellite1_pos_mass[0],
        'center_y': satellite1_pos_mass[1]
    }, None]

    satellite_kwargs = [{
        'theta_E': 0.03,
        'center_x': satellite1_pos_mass[0],
        'center_y': satellite1_pos_mass[1]
    }, {
        'theta_E': 0.93,
        'center_x': satellite2_pos_mass[0],
        'center_y': satellite2_pos_mass[1]
    }]

    @staticmethod
    def relative_time_delays(arrival_times):

        trel = arrival_times[1:] - arrival_times[0]
        trel = [abs(trel[0]), abs(trel[1]), abs(trel[1]) + abs(trel[2])]
        return np.array(trel)

    def optimize_fit(self, kwargs_fit={}, macro_init=None, print_output=False):

        if 'datatofit' in kwargs_fit.keys():
            data = kwargs_fit['datatofit']
            del kwargs_fit['datatofit']
        else:
            data = self.data

        if 'satellites' not in kwargs_fit.keys():
            satellites = {}

            satellites['lens_model_name'] = self.satellite_mass_model
            satellites['z_satellite'] = self.satellite_redshift
            satellites['kwargs_satellite'] = self.satellite_kwargs
            satellites['position_convention'] = self.satellite_convention

            kwargs_fit.update({'satellites': satellites})

        optdata, optmodel = self._fit(data,
                                      self.solver,
                                      kwargs_fit,
                                      macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def optimize_fit_lensmodel(self,
                               kwargs_fit={},
                               macro_init=None,
                               print_output=False):

        kwargs_fit.update({'identifier': self.identifier})
        optdata, optmodel = self._fit_lensmodel(self.data,
                                                self.solver,
                                                kwargs_fit,
                                                macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def _print_output(self, optdata, optmodel):

        macromodel = optmodel.lens_components[0]

        print('optimized mags: ', optdata.m)
        print('observed mags: ', self.data.m)
        print('lensmodel fit: ')
        print('Einstein radius: ', macromodel.lenstronomy_args['theta_E'])
        print('shear, shear_theta:', macromodel.shear, macromodel.shear_theta)
        print('ellipticity, PA:',
              macromodel.ellip_PA_polar()[0],
              macromodel.ellip_PA_polar()[1])
        print('centroid: ', macromodel.lenstronomy_args['center_x'],
              macromodel.lenstronomy_args['center_y'])
        print('\n')
        print('flux ratios w.r.t. image ' + str(self.fluximg) + ':')
        print('observed: ',
              self.data.compute_flux_ratios(index=self.flux_ratio_index))
        print('recovered: ',
              optdata.compute_flux_ratios(index=self.flux_ratio_index))


# lens = WFI2033()
# x, y = lens.x, lens.y
# col = ['k', 'r', 'm', 'g']
# import matplotlib.pyplot as plt
# for l in range(0, 4):
#     plt.scatter(-x[l], y[l], color=col[l])
# plt.show()
Пример #22
0
class Lens1131(Quad):

    # From Suyu et al. 2016
    # typo in Chen et al. 2016?
    g1x, g1y = 4.420, 3.932
    x = np.array([2.383, 2.344, 2.96, 5.494]) - g1x
    y = np.array([3.412, 4.594, 2.3, 4.288]) - g1y
    m = np.array([1., 0.613497, 0.730061, 0.06135])
    sigma_x = np.array([0.003] * 4)
    sigma_y = np.array([0.003] * 4)

    time_delay_AB, delta_AB = 0.7, 1.2
    time_delay_AC, delta_AC = 1.1, 1.5
    time_delay_AD, delta_AD = -90.6, 1.4
    delta_time_delay = np.array([delta_AB, delta_AC, delta_AD])
    relative_arrival_times = -np.array(
        [time_delay_AB, time_delay_AC, time_delay_AD])

    kwargs_lens_init = [{
        'theta_E': 1.58460356403038,
        'center_x': -0.005270348888552784,
        'center_y': -0.029873551296941633,
        'e1': 0.028027358886809944,
        'e2': 0.0693670602615151,
        'gamma': 1.98
    }, {
        'gamma1': -0.11734572581060929,
        'gamma2': -0.03232611049507928
    }]

    sigma_m = np.zeros_like(sigma_x)
    zlens, zsrc = 0.3, 0.66

    data = Data(x,
                y,
                m,
                None,
                None,
                sigma_x=sigma_x,
                sigma_y=sigma_y,
                sigma_m=sigma_m)

    identifier = 'lens1131'

    flux_ratio_index = 1

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    has_satellite = True
    satellite_mass_model = ['SIS']
    satellite_redshift = [zlens]
    satellite_convention = ['phys']
    satellite_pos_mass = [4.323 - g1x, 4.546 - g1y]

    # From Chen et al. 2016
    amp_scale = 1000
    kwargs_lens_light = [{
        'amp': amp_scale * 1.5,
        'R_sersic': 0.404,
        'n_sersic': 2.,
        'center_x': 0.,
        'center_y': 0.
    }]
    kwargs_source_light = [{
        'amp': amp_scale * 4,
        'R_sersic': 0.1,
        'n_sersic': 2.,
        'center_x': None,
        'center_y': None,
        'e1': -0.2,
        'e2': 0.2
    }]
    kwargs_satellite_light = [{
        'amp': amp_scale * 2,
        'R_sersic': 0.05,
        'n_sersic': 2.,
        'center_x': satellite_pos_mass[0],
        'center_y': satellite_pos_mass[1]
    }]

    # satellite einstein radius from Chen et al. 2016
    satellite_kwargs = [{
        'theta_E': 0.28,
        'center_x': satellite_pos_mass[0],
        'center_y': satellite_pos_mass[1]
    }]

    gamma_min = 1.95
    gamma_max = 2.2

    srcmin = 0.02
    srcmax = 0.05

    @staticmethod
    def relative_time_delays(arrival_times):

        trel = arrival_times[1:] - arrival_times[0]

        return np.array(trel)

    def optimize_fit(self, kwargs_fit={}, macro_init=None, print_output=False):

        if 'datatofit' in kwargs_fit.keys():
            data = kwargs_fit['datatofit']
            del kwargs_fit['datatofit']
        else:
            data = self.data

        optdata, optmodel = self._fit(data,
                                      self.solver,
                                      kwargs_fit,
                                      macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def optimize_fit_lensmodel(self,
                               kwargs_fit={},
                               macro_init=None,
                               print_output=False):

        kwargs_fit.update({'identifier': self.identifier})
        optdata, optmodel = self._fit_lensmodel(self.data,
                                                self.solver,
                                                kwargs_fit,
                                                macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def _print_output(self, optdata, optmodel):

        macromodel = optmodel.lens_components[0]

        print('optimized mags: ', optdata.m)
        print('observed mags: ', self.data.m)
        print('lensmodel fit: ')
        print('Einstein radius: ', macromodel.lenstronomy_args['theta_E'])
        print('shear, shear_theta:', macromodel.shear, macromodel.shear_theta)
        print('ellipticity, PA:',
              macromodel.ellip_PA_polar()[0],
              macromodel.ellip_PA_polar()[1])
        print('centroid: ', macromodel.lenstronomy_args['center_x'],
              macromodel.lenstronomy_args['center_y'])
        print('\n')
        print('flux ratios w.r.t. image ' + str(self.fluximg) + ':')
        print('observed: ',
              self.data.compute_flux_ratios(index=self.flux_ratio_index))
        print('recovered: ',
              optdata.compute_flux_ratios(index=self.flux_ratio_index))
Пример #23
0
class Lens2038(Quad):

    x = np.array([-1.474, 0.832, -0.686, 0.706])
    y = np.array([0.488, -1.22, -1.191, 0.869])
    m = np.array([0.862069, 1., 0.793103, 0.396552])
    sigma_x = np.array([0.005]*4)
    sigma_y = np.array([0.005]*4)

    # TIME DELAYS ESTIMATED FROM A FIT
    time_delay_AB, delta_AB = -2.6, 1.3
    time_delay_AC, delta_AC = -5.73, 0.9
    time_delay_AD, delta_AD = -15.0, 2.5
    delta_time_delay = np.array([delta_AB, delta_AC, delta_AD])
    relative_arrival_times = np.array([time_delay_AB, time_delay_AC, time_delay_AD])

    sigma_m = np.zeros_like(sigma_x)
    zsrc, zlens = 0.78, 0.23

    data = Data(x, y, m, None, None,
                         sigma_x = sigma_x, sigma_y = sigma_y,
                         sigma_m=sigma_m)

    identifier = 'lens2038'

    flux_ratio_index = 0

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    has_satellite = False

    gamma_min = 1.9
    gamma_max = 2.4

    srcmin = 0.02
    srcmax = 0.05

    def optimize_fit(self, kwargs_fit={}, macro_init = None, print_output = False):

        if 'datatofit' in kwargs_fit.keys():
            data = kwargs_fit['datatofit']
            del kwargs_fit['datatofit']
        else:
            data = self.data

        optdata, optmodel = self._fit(data, self.solver, kwargs_fit, macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def optimize_fit_lensmodel(self, kwargs_fit={}, macro_init = None, print_output = False):

        kwargs_fit.update({'identifier': self.identifier})
        optdata, optmodel = self._fit_lensmodel(self.data, self.solver, kwargs_fit, macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def _print_output(self, optdata, optmodel):

        macromodel = optmodel.lens_components[0]

        print('optimized mags: ', optdata.m)
        print('observed mags: ', self.data.m)
        print('lensmodel fit: ')
        print('Einstein radius: ', macromodel.lenstronomy_args['theta_E'])
        print('shear, shear_theta:', macromodel.shear, macromodel.shear_theta)
        print('ellipticity, PA:', macromodel.ellip_PA_polar()[0], macromodel.ellip_PA_polar()[1])
        print('centroid: ', macromodel.lenstronomy_args['center_x'],
              macromodel.lenstronomy_args['center_y'])
        print('\n')
        print('flux ratios w.r.t. image '+str(self.fluximg)+':')
        print('observed: ', self.data.compute_flux_ratios(index=self.flux_ratio_index))
        print('recovered: ', optdata.compute_flux_ratios(index=self.flux_ratio_index))
Пример #24
0
class Lens1115(Quad):

    # x = np.array([0.947, 1.096, -0.722, -0.381])
    # y = np.array([-0.69, -0.232, -0.617, 1.344])
    # m = np.array([1., 0.93, 0.16, 0.21])

    x = np.array([0.947, 1.096, -0.722, -0.381])
    y = np.array([-0.69, -0.232, -0.617, 1.344])
    m = np.array([1., 0.93, 0.16, 0.21])

    # from Impey et al. 1998
    # minus sign is correct
    group_r, group_theta = 10, (-113 + 90) * np.pi / 180
    group_x, group_y = -group_r * np.cos(group_theta), group_r * np.sin(
        group_theta)

    time_delay_AB, delta_AB = 0.01, 10
    time_delay_AC, delta_AC = 8.3, 1.6
    time_delay_AD, delta_AD = -9.9, 1.1

    relative_arrival_times = np.array([0.01, 9.9, 18.8])
    delta_time_delay = np.array([10, 1.1, 1.6])

    sigma_x = np.array([0.003] * 4)
    sigma_y = np.array([0.003] * 4)
    sigma_m = np.zeros_like(sigma_x)
    zlens, zsrc = 0.31, 1.72

    data = Data(x,
                y,
                m,
                None,
                None,
                sigma_x=sigma_x,
                sigma_y=sigma_y,
                sigma_m=sigma_m)

    # From Chen et al. 2019
    amp_scale = 1000
    kwargs_lens_light = [{
        'amp': 1000,
        'R_sersic': 0.2,
        'n_sersic': 4.,
        'center_x': None,
        'center_y': None
    }]
    kwargs_source_light = [{
        'amp': 1700,
        'R_sersic': 0.125,
        'n_sersic': 2.,
        'center_x': None,
        'center_y': None,
        'e1': 0.15,
        'e2': -0.4
    }]

    kwargs_lens_init = [{
        'theta_E': 1.0505876627617852,
        'center_x': 0.0015838433690165622,
        'center_y': 0.0039075583507097575,
        'e1': -0.002140732329506273,
        'e2': -0.0017325116179204988,
        'gamma': 2.2
    }, {
        'gamma1': -0.010208269559630813,
        'gamma2': -0.025988491812216158
    }]

    identifier = 'lens1115'
    has_satellite = True
    satellite_mass_model = ['SIS']
    satellite_redshift = [zlens]
    satellite_convention = ['phys']
    satellite_pos_mass = [group_x, group_y]
    # From Impey et al. 1998 "Einstein ring in..."
    satellite_kwargs = [{
        'theta_E': 2.,
        'center_x': satellite_pos_mass[0],
        'center_y': satellite_pos_mass[1]
    }]

    kwargs_satellite_light = [None]
    flux_ratio_index = 0

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    gamma_min = 1.95
    gamma_max = 2.2

    srcmin = 0.005
    srcmax = 0.025

    @staticmethod
    def relative_time_delays(arrival_times):

        trel = arrival_times[1:] - arrival_times[0]
        trel = [trel[0], abs(trel[2]), trel[1] + abs(trel[2])]
        return np.array(trel)

    def optimize_fit(self, kwargs_fit={}, macro_init=None, print_output=False):

        if 'datatofit' in kwargs_fit.keys():
            data = kwargs_fit['datatofit']
            del kwargs_fit['datatofit']
        else:
            data = self.data

        optdata, optmodel = self._fit(data,
                                      self.solver,
                                      kwargs_fit,
                                      macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def optimize_fit_lensmodel(self,
                               kwargs_fit={},
                               macro_init=None,
                               print_output=False):

        kwargs_fit.update({'identifier': self.identifier})
        optdata, optmodel = self._fit_lensmodel(self.data,
                                                self.solver,
                                                kwargs_fit,
                                                macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def _print_output(self, optdata, optmodel):

        macromodel = optmodel.lens_components[0]

        print('optimized mags: ', optdata.m)
        print('observed mags: ', self.data.m)
        print('lensmodel fit: ')
        print('Einstein radius: ', macromodel.lenstronomy_args['theta_E'])
        print('shear, shear_theta:', macromodel.shear, macromodel.shear_theta)
        print('ellipticity, PA:',
              macromodel.ellip_PA_polar()[0],
              macromodel.ellip_PA_polar()[1])
        print('centroid: ', macromodel.lenstronomy_args['center_x'],
              macromodel.lenstronomy_args['center_y'])
        print('\n')
        print('flux ratios w.r.t. image ' + str(self.fluximg) + ':')
        print('observed: ',
              self.data.compute_flux_ratios(index=self.flux_ratio_index))
        print('recovered: ',
              optdata.compute_flux_ratios(index=self.flux_ratio_index))
Пример #25
0
class J0405(Quad):

    x = np.array([0.708, -0.358, 0.363, -0.515])
    y = np.array([-0.244, -0.567, 0.592, 0.454])
    m = np.array([1., 0.65, 1.25, 1.17]) * 1.25**-1
    sigma_x = np.array([0.005] * 4)
    sigma_y = np.array([0.005] * 4)
    sigma_m = np.zeros_like(sigma_x)
    zlens, zsrc = 0.3, 1.71

    data = Data(x,
                y,
                m,
                None,
                None,
                sigma_x=sigma_x,
                sigma_y=sigma_y,
                sigma_m=sigma_m)

    identifier = 'lens0405'

    flux_ratio_index = 0

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    gamma_min = 1.9
    gamma_max = 2.2
    has_satellite = False
    srcmin = 0.02
    srcmax = 0.05

    def optimize_fit(self, kwargs_fit={}, macro_init=None, print_output=False):

        if 'datatofit' in kwargs_fit.keys():
            data = kwargs_fit['datatofit']
            del kwargs_fit['datatofit']
        else:
            data = self.data

        optdata, optmodel = self._fit(data,
                                      self.solver,
                                      kwargs_fit,
                                      macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def optimize_fit_lensmodel(self,
                               kwargs_fit={},
                               macro_init=None,
                               print_output=False):

        kwargs_fit.update({'identifier': self.identifier})
        optdata, optmodel = self._fit_lensmodel(self.data,
                                                self.solver,
                                                kwargs_fit,
                                                macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def _print_output(self, optdata, optmodel):

        macromodel = optmodel.lens_components[0]

        print('optimized mags: ', optdata.m)
        print('observed mags: ', self.data.m)
        print('lensmodel fit: ')
        print('Einstein radius: ', macromodel.lenstronomy_args['theta_E'])
        print('shear, shear_theta:', macromodel.shear, macromodel.shear_theta)
        print('ellipticity, PA:',
              macromodel.ellip_PA_polar()[0],
              macromodel.ellip_PA_polar()[1])
        print('centroid: ', macromodel.lenstronomy_args['center_x'],
              macromodel.lenstronomy_args['center_y'])
        print('\n')
        print('flux ratios w.r.t. image ' + str(self.fluximg) + ':')
        print('observed: ',
              self.data.compute_flux_ratios(index=self.flux_ratio_index))
        print('recovered: ',
              optdata.compute_flux_ratios(index=self.flux_ratio_index))
Пример #26
0
class Lens1608(Quad):

    g1x, g1y = 0.4161, -1.0581
    g2x, g2y = -0.2897, -0.9243

    g2x -= g1x
    g2y -= g1y
    # from Fassnacht et al. 2002
    x = np.array([-0.000, -0.738, -0.7446, 1.1284]) - g1x
    y = np.array([0.000, -1.961, -0.4537, -1.2565]) - g1y
    m = np.array([1., 0.5, 0.51, 0.35])
    sigma_x = np.array([0.005] * 4)
    sigma_y = np.array([0.005] * 4)

    # from Koopmans et al. 2003
    time_delay_AB, delta_AB = -31.5, 1.5
    time_delay_AC, delta_AC = 4.5, 1.5
    time_delay_AD, delta_AD = 45.5, 2.
    # delta_time_delay = np.array([delta_AB, delta_AC, delta_AD])
    # relative_arrival_times = np.array([time_delay_AB, time_delay_AC, time_delay_AD])

    relative_arrival_times = np.array([31., 36., 76.])
    delta_time_delay = np.array([2., 1.5, 2.])

    sigma_m = np.zeros_like(sigma_x)

    kwargs_lens_init = [{
        'theta_E': 0.9036453181989341,
        'center_x': 0.007600860009089998,
        'center_y': -0.057685769153856994,
        'e1': 0.33480085295892065,
        'e2': -0.05097223221504117,
        'gamma': 2.08
    }, {
        'gamma1': 0.06096918564904592,
        'gamma2': 0.07721907911829631
    }]

    amp_scale = 1000.
    kwargs_lens_light = [{
        'amp': amp_scale * 1.1,
        'R_sersic': 0.4,
        'n_sersic': 4.,
        'center_x': 0.,
        'center_y': 0.
    }]
    kwargs_source_light = [{
        'amp': amp_scale * 1.6,
        'R_sersic': 0.12,
        'n_sersic': 3.,
        'center_x': None,
        'center_y': None,
        'e1': -0.1,
        'e2': 0.3
    }]

    zlens, zsrc = 0.61, 1.4

    data = Data(x,
                y,
                m,
                None,
                None,
                sigma_x=sigma_x,
                sigma_y=sigma_y,
                sigma_m=sigma_m)

    identifier = 'lens1608'

    flux_ratio_index = 0

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    has_satellite = True
    satellite_mass_model = ['SIS']
    satellite_redshift = [zlens]
    satellite_convention = ['phys']
    satellite_pos_mass = [g2x, g2y]
    kwargs_satellite_light = [{
        'amp': amp_scale * 0.7,
        'R_sersic': 0.2,
        'n_sersic': 4.,
        'center_x': g2x,
        'center_y': g2y
    }]
    # satellite einstein radius from Koopmans et al. 2003
    satellite_kwargs = [{
        'theta_E': 0.26,
        'center_x': satellite_pos_mass[0],
        'center_y': satellite_pos_mass[1]
    }]

    gamma_min = 1.95
    gamma_max = 2.2

    srcmin = 0.02
    srcmax = 0.05

    @staticmethod
    def relative_time_delays(arrival_times):

        trel = arrival_times[1:] - arrival_times[0]
        trel = [
            abs(trel[0]),
            abs(trel[0]) + trel[1],
            abs(trel[0]) + abs(trel[2])
        ]
        return np.array(trel)

    def optimize_fit(self, kwargs_fit={}, macro_init=None, print_output=False):

        if 'datatofit' in kwargs_fit.keys():
            data = kwargs_fit['datatofit']
            del kwargs_fit['datatofit']
        else:
            data = self.data

        optdata, optmodel = self._fit(data,
                                      self.solver,
                                      kwargs_fit,
                                      macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def optimize_fit_lensmodel(self,
                               kwargs_fit={},
                               macro_init=None,
                               print_output=False):

        kwargs_fit.update({'identifier': self.identifier})
        optdata, optmodel = self._fit_lensmodel(self.data,
                                                self.solver,
                                                kwargs_fit,
                                                macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def _print_output(self, optdata, optmodel):

        macromodel = optmodel.lens_components[0]

        print('optimized mags: ', optdata.m)
        print('observed mags: ', self.data.m)
        print('lensmodel fit: ')
        print('Einstein radius: ', macromodel.lenstronomy_args['theta_E'])
        print('shear, shear_theta:', macromodel.shear, macromodel.shear_theta)
        print('ellipticity, PA:',
              macromodel.ellip_PA_polar()[0],
              macromodel.ellip_PA_polar()[1])
        print('centroid: ', macromodel.lenstronomy_args['center_x'],
              macromodel.lenstronomy_args['center_y'])
        print('\n')
        print('flux ratios w.r.t. image ' + str(self.fluximg) + ':')
        print('observed: ',
              self.data.compute_flux_ratios(index=self.flux_ratio_index))
        print('recovered: ',
              optdata.compute_flux_ratios(index=self.flux_ratio_index))
Пример #27
0
class Lens1606(Quad):

    x = np.array([0.838, -0.784, 0.048, -0.289])
    y = np.array([0.378, -0.211, -0.527, 0.528])
    m = np.array([1., 1., 0.59, 0.79])

    sigma_x = np.array([0.005]*4)
    sigma_y = np.array([0.005]*4)
    sigma_m = np.zeros_like(sigma_x)
    zlens, zsrc = 0.31, 1.7

    time_delay_AB, delta_AB = 5.6, 1.6
    time_delay_AC, delta_AC = 11.2, 2.6
    time_delay_AD, delta_AD = 9.2, 2.7
    delta_time_delay = np.array([delta_AB, delta_AC, delta_AD])
    relative_arrival_times = np.array([time_delay_AB, time_delay_AC, time_delay_AD])

    data = Data(x, y, m, None, None,
                         sigma_x = sigma_x, sigma_y = sigma_y,
                         sigma_m=sigma_m)

    identifier = 'lens1606'

    flux_ratio_index = 0

    fluximg = ['A', 'B', 'C', 'D'][flux_ratio_index]

    _macromodel = get_default_SIE(zlens)

    _macromodel.lenstronomy_args['theta_E'] = approx_theta_E(x, y)

    gamma_min = 1.9
    gamma_max = 2.2

    srcmin = 0.02
    srcmax = 0.05

    has_satellite = True
    satellite_mass_model = ['SIS']
    satellite_redshift = [zlens]
    satellite_convention = ['phys']
    # from mass center
    satellite_pos_mass = np.array([-0.307, -1.153])
    # from light center
    #satellite_pos_light = [-0.1255, -1.3517]
    satellite_kwargs = [{'theta_E': 0.269, 'center_x': satellite_pos_mass[0], 'center_y': satellite_pos_mass[1]}]

    def optimize_fit(self, kwargs_fit={}, macro_init = None, print_output = False):

        if 'datatofit' in kwargs_fit.keys():
            data = kwargs_fit['datatofit']
            del kwargs_fit['datatofit']
        else:
            data = self.data

        satellites = {}
        satellites['lens_model_name'] = self.satellite_mass_model
        satellites['z_satellite'] = [self.zlens]
        satellites['kwargs_satellite'] = self.satellite_kwargs

        kwargs_fit.update({'satellites': satellites})

        optdata, optmodel = self._fit(data, self.solver, kwargs_fit, macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def optimize_fit_lensmodel(self, kwargs_fit={}, macro_init = None, print_output = False):

        kwargs_fit.update({'identifier': self.identifier})
        optdata, optmodel = self._fit_lensmodel(self.data, self.solver, kwargs_fit, macromodel_init=macro_init)

        if print_output:
            self._print_output(optdata[0], optmodel[0])

        return optdata[0], optmodel[0]

    def _print_output(self, optdata, optmodel):

        macromodel = optmodel.lens_components[0]

        print('optimized mags: ', optdata.m)
        print('observed mags: ', self.data.m)
        print('lensmodel fit: ')
        print('Einstein radius: ', macromodel.lenstronomy_args['theta_E'])
        print('shear, shear_theta:', macromodel.shear, macromodel.shear_theta)
        print('ellipticity, PA:', macromodel.ellip_PA_polar()[0], macromodel.ellip_PA_polar()[1])
        print('centroid: ', macromodel.lenstronomy_args['center_x'],
              macromodel.lenstronomy_args['center_y'])
        print('\n')
        print('flux ratios w.r.t. image '+str(self.fluximg)+':')
        print('observed: ', self.data.compute_flux_ratios(index=self.flux_ratio_index))
        print('recovered: ', optdata.compute_flux_ratios(index=self.flux_ratio_index))