Exemplo n.º 1
0
def test_init():
    telescope = telescopes.Telescope()

    assert telescope.name == 'NDG'
    assert telescope.filter == 'I'
    assert len(telescope.lightcurve_magnitude) == 0
    assert telescope.location == 'Earth'

    assert telescope.location == 'Earth'
    assert len(telescope.lightcurve_flux) == 0
    assert telescope.altitude == 0.0
    assert telescope.longitude == 0.57
    assert telescope.latitude == 49.49
    assert telescope.gamma == 0.0
    assert len(telescope.deltas_positions) == 0

    telescope2 = telescopes.Telescope('Goleta', 'sdss_i',
                                      light_curve_magnitude=np.array([[0, 1, 0.1], [3, 4, 0.1]]))

    assert telescope2.name == 'Goleta'
    assert telescope2.filter == 'sdss_i'
    assert telescope2.lightcurve_magnitude.shape == (2, 3)
    assert telescope2.lightcurve_flux.shape == (2, 3)
    telescope2.location = 'Space'
    telescope2.altitude = 1.0
    telescope2.longitude = -150.0
    telescope2.latitude = 35.0
    telescope2.gamma = 0.6

    assert telescope2.location == 'Space'
    assert telescope2.altitude == 1.0
    assert telescope2.longitude == -150.0
    assert telescope2.latitude == 35.0
    assert telescope2.gamma == 0.6
Exemplo n.º 2
0
def main():
    my_event = event.Event()
    my_event.name = 'my_event'
    #my_event.ra = 269.39166666666665
    #my_event.dec = -29.22083333333333

    data_K0 = np.loadtxt("./fits_files/lightcurve_gen_K0_text_2.txt")
    data_V0 = np.loadtxt("./fits_files/lightcurve_gen_V0_text_2.txt")

    telescope_K0 = telescopes.Telescope(name="LSST", camera_filter="K", light_curve_magnitude=data_K0)
    telescope_V0 = telescopes.Telescope(name="LSST", camera_filter="V", light_curve_magnitude=data_V0)

    my_event.telescopes.append(telescope_K0)
    #my_event.telescopes.append(telescope_V0)

    my_event.check_event()

    model = microlmodels.create_model("PSPL", my_event)

    my_event.fit(model, "LM")
    my_event.fits[0].produce_outputs()

    chi2_LM = my_event.fits[0].outputs.fit_parameters.chichi
    print("Chi2_LM: {}".format(chi2_LM))

    figure =  my_event.fits[0].outputs.figure_lightcurve
    #print "Other output:",figure.as_list()
    plt.show()
Exemplo n.º 3
0
def pyLIMAfit(filename):

    ML_event = event.Event()
    ML_event.name = str(filename).replace(".dat", "")
    ML_event.ra = 269.39166666666665
    ML_event.dec = -29.22083333333333

    fileDirectoryR = lightcurve_path + 'Rfilter/' + str(filename)
    fileDirectoryG = lightcurve_path + 'Gfilter/' + str(filename)
    if ML_event.name.endswith('R'):  #color == 'R':
        data_1 = np.loadtxt(fileDirectoryR)
        telescope_1 = telescopes.Telescope(name='LCOGT',
                                           camera_filter='R',
                                           light_curve_magnitude=data_1)
        ML_event.telescopes.append(telescope_1)

    if ML_event.name.endswith('G'):  #color == 'G':
        data_2 = np.loadtxt(fileDirectoryG)
        telescope_2 = telescopes.Telescope(name='LCOGT',
                                           camera_filter='G',
                                           light_curve_magnitude=data_2)
        ML_event.telescopes.append(telescope_2)

    ML_event.find_survey('LCOGT')
    ML_event.check_event()
    PSPL_model = microlmodels.create_model('PSPL', ML_event)
    ML_event.fit(PSPL_model, 'DE')
    ML_event.fits[-1].produce_outputs()
    try:
        initial_parameters = [
            getattr(ML_event.fits[-2].outputs.fit_parameters, key)
            for key in ML_event.fits[-2].outputs.fit_parameters._fields[:4]
        ]

        PSPL_model.parameters_guess = initial_parameters
        ML_event.fit(PSPL_model, 'LM')
        ML_event.fits[-1].produce_outputs()

    except:
        pass

    output1 = plt.figure(1)
    plt.savefig(lightcurve_path + 'pyLIMA_fits/' +
                str(filename).replace(".dat", "") + '_pyLIMA_fit.png')
    output2 = plt.figure(2)
    plt.savefig(lightcurve_path + 'pyLIMA_fits/' +
                str(filename).replace(".dat", "") + '_pyLIMA_parameters.png')
    plt.close('all')

    return 0
Exemplo n.º 4
0
    def read_dataset_to_telescope(self, model_type):

        if 'p.t' in self.data_file:
            lightcurve = np.loadtxt(self.data_file, dtype=str)
            lightcurve = np.c_[lightcurve[:, 1], lightcurve[:, 6],
                               lightcurve[:, 7]].astype(float)

        if 'cal.t' in self.data_file:
            lightcurve = np.loadtxt(self.data_file, dtype=str)
            lightcurve = np.c_[lightcurve[:, 1], lightcurve[:, 8],
                               lightcurve[:, 9]].astype(float)

        if 'DK-1.54' in self.data_file:
            lightcurve = np.loadtxt(self.data_file, dtype=str)
            lightcurve = np.c_[lightcurve[:, 1], lightcurve[:, 6],
                               lightcurve[:, 7]].astype(float)

        self.tel = telescopes.Telescope(name=self.name,
                                        camera_filter=self.filter,
                                        light_curve_magnitude=lightcurve,
                                        light_curve_magnitude_dictionnary={
                                            'time': 0,
                                            'mag': 1,
                                            'err_mag': 2
                                        })
        if 'FS' in model_type:
            self.tel.gamma = self.gamma
            print(self.tel.name, self.tel.gamma)
Exemplo n.º 5
0
def test_clean_data_not_clean():
    telescope = telescopes.Telescope(light_curve_magnitude=np.array(
        [[0, 1, 0.1], [3, np.nan, 0.1], [5, 6, 0.1], [7, np.nan, np.nan],
         [8, 1, 27.0], [9, 2, 0.03]]))
    clean_lightcurve = telescope.clean_data_magnitude()
    assert np.allclose(clean_lightcurve,
                       np.array([[0, 1, 0.1], [5, 6, 0.1], [9, 2, 0.03]]))
Exemplo n.º 6
0
def test_clean_data_already_clean():
    telescope = telescopes.Telescope(light_curve_magnitude=np.array(
        [[0, 1, 0.1], [3, 4, 0.1], [5, 6, 0.1]]))

    clean_lightcurve = telescope.clean_data_magnitude()
    assert np.allclose(clean_lightcurve,
                       np.array([[0, 1, 0.1], [3, 4, 0.1], [5, 6, 0.1]]))
Exemplo n.º 7
0
def test_n_data():
    telescope = telescopes.Telescope(light_curve_magnitude=np.array(
        [[0, 1, 0.1], [3, np.nan, 0.1], [5, 6, 0.1], [7, np.nan, np.nan],
         [8, 1, 27.0], [9, 2, 0.03]]))
    telescope.lightcurve_flux = telescope.lightcurve_in_flux()

    assert telescope.n_data() == 3
    assert telescope.n_data('flux') == 3
Exemplo n.º 8
0
def test_arrange_the_lightcurve_columns_invert_time_magnitude():
    telescope = telescopes.Telescope(light_curve_magnitude=np.array(
        [[0, 1, 0.1], [3, 0.0, 0.1], [5, 6, 0.1], [7, 0.0, 0.0], [8, 1, 27.0], [9, 2, 0.03]]),
        light_curve_magnitude_dictionnary={'time': 1, 'mag': 0,
                                           'err_mag': 2}, clean_the_lightcurve='No')

    assert np.allclose(telescope.lightcurve_magnitude, np.array(
        [[1, 0, 0.1], [0.0, 3, 0.1], [6, 5, 0.1], [0.0, 7, 0.0], [1, 8, 27.0], [2, 9, 0.03]]))
Exemplo n.º 9
0
def test_find_gamma():
    telescope = telescopes.Telescope(camera_filter="z'")
    full_path = os.path.abspath(__file__)
    directory, filename = os.path.split(full_path)

    telescope.find_gamma(32000.0, 4.5, os.path.join(directory, '../data/'))
    EPSILON = 0.001

    assert np.abs(telescope.gamma - 0.127056) <= EPSILON
Exemplo n.º 10
0
def test_find_gamma():
    telescope = telescopes.Telescope(camera_filter="z'")


    star = stars.Star()
    telescope.find_gamma(star)
    EPSILON = 0.001

    assert np.abs(telescope.gamma - 0.370885527486) <= EPSILON
Exemplo n.º 11
0
def test_find_gamma():
    telescope = telescopes.Telescope(camera_filter="z'")
    full_path = os.path.abspath(__file__)
    directory, filename = os.path.split(full_path)

    star = stars.Star()
    telescope.find_gamma(star)
    EPSILON = 0.001

    assert np.abs(telescope.gamma - 0.370885527486) <= EPSILON
Exemplo n.º 12
0
def test_lightcurve_in_flux():
    telescope = telescopes.Telescope(
        light_curve_magnitude=np.array([[0, 1, 0.1], [3, 4, 0.1], [5, 6, 0.1]]))

    telescope.lightcurve_flux = telescope.lightcurve_in_flux()

    assert np.allclose(telescope.lightcurve_flux,
                       np.array([[0.00000000e+00, 3.63078055e+10, 3.34407247e+09],
                                 [3.00000000e+00, 2.29086765e+09, 2.10996708e+08],
                                 [5.00000000e+00, 3.63078055e+08, 3.34407247e+07]]))
Exemplo n.º 13
0
def test_input_lightcurve_flux():
    telescope = telescopes.Telescope(light_curve_flux=np.array(
        [[0, 10.0, 0.1], [3, 5.0, 0.1], [5, 7.0, 0.1], [7, 5.0, 0.0], [8, 1.0, 27.0],
         [9, 2.0, 0.03]]), light_curve_flux_dictionnary={'time': 1, 'flux': 0,
                                      'err_flux': 2}, reference_flux=10000.0, clean_the_lightcurve='Yes')

    assert np.allclose(telescope.lightcurve_magnitude,
                       np.array([[1.00000000e+01, 1.74000000e+01, 1.08573620e-05],
                                 [5.00000000e+00, 1.73996743e+01, 1.08541058e-05],
                                 [7.00000000e+00, 1.73994573e+01, 1.08519361e-05],
                                 [5.00000000e+00, 1.73992403e+01, 0.00000000e+00],
                                 [1.00000000e+00, 1.73991318e+01, 2.92914444e-03],
                                 [2.00000000e+00, 1.73990233e+01, 3.25427976e-06]]))
Exemplo n.º 14
0
def fit_PSPL(photometry, emag_limit=None, cores=None):

    current_event = event.Event()
    current_event.name = 'MOP_to_fit'
    filters = np.unique(photometry[:, -1])

    for ind, filt in enumerate(filters):

        if emag_limit:

            mask = (photometry[:, -1] == filt) & (np.abs(
                photometry[:, -2].astype(float)) < emag_limit)

        else:

            mask = (photometry[:, -1] == filt)
        lightcurve = photometry[mask, :-1].astype(float)

        telescope = telescopes.Telescope(name='Tel_' + str(ind),
                                         camera_filter=filt,
                                         light_curve_magnitude=lightcurve,
                                         light_curve_magnitude_dictionnary={
                                             'time': 0,
                                             'mag': 1,
                                             'err_mag': 2
                                         },
                                         clean_the_lightcurve='Yes')

        if len(lightcurve) > 5:
            current_event.telescopes.append(telescope)

    Model = microlmodels.create_model('PSPL',
                                      current_event,
                                      parallax=['None', 0])
    Model.parameters_boundaries[0] = [
        Model.parameters_boundaries[0][0],
        Model.parameters_boundaries[0][-1] + 500
    ]
    Model.parameters_boundaries[1] = [0, 2]

    if cores != 0:

        import multiprocessing
        with multiprocessing.Pool(processes=cores) as pool:
            current_event.fit(Model,
                              'DE',
                              DE_population_size=10,
                              flux_estimation_MCMC='polyfit',
                              computational_pool=pool)

    else:

        current_event.fit(Model,
                          'DE',
                          DE_population_size=10,
                          flux_estimation_MCMC='polyfit')

    t0_fit = current_event.fits[-1].fit_results[0]
    u0_fit = current_event.fits[-1].fit_results[1]
    tE_fit = current_event.fits[-1].fit_results[2]
    chi2_fit = current_event.fits[-1].fit_results[-1]

    mag_source_fit = flux_to_mag(current_event.fits[-1].fit_results[3])
    mag_blend_fit = flux_to_mag(current_event.fits[-1].fit_results[3] *
                                current_event.fits[-1].fit_results[4])
    mag_baseline_fit = flux_to_mag(current_event.fits[-1].fit_results[3] *
                                   (1 + current_event.fits[-1].fit_results[4]))

    if np.isnan(mag_blend_fit):
        mag_blend_fit = "null"

    return [
        t0_fit, u0_fit, tE_fit, mag_source_fit, mag_blend_fit,
        mag_baseline_fit, chi2_fit
    ]
def simulate_ffp():

    spring = True
    fall = False

    u0 = 0.01
    tE = 1.0
    if spring:
        t0 = 2460394.400000
        start_jd = 2460389.500000       # 2024 March 20
        end_jd = 2460399.500000
    if fall:
        t0 = 2460389.500000
        start_jd = 2460573.500000       # 2024 Aug 20
        end_jd = 2460583.500000        # 2024 Aug 30
    ra = 270.0
    dec = -27.0
    piEN = 0.01
    piEE = 0.01
    blend_ratio = 0.2
    source_flux = mag_to_flux(22.0,1.0,24.0)
    blend_flux = source_flux * blend_ratio

    model_params = [ t0, u0, tE, piEN, piEE ]

    lsst_aperture = 6.68
    lsst_read_noise = 10.0

    wfirst_aperture = 2.4
    wfirst_read_noise = 10.0

    if spring:
        horizons_file = 'wfirst_observer_table_spring.txt'
    if fall:
        horizons_file = 'wfirst_observer_table_fall.txt'

    ffp_lsst = event.Event()
    ffp_lsst.name = 'FFP'
    ffp_lsst.ra = ra
    ffp_lsst.dec = dec

    lsst_lc = simulate_lightcurve(start_jd, end_jd, 0.5/24.0, lsst_aperture,
                                  spring, fall, day_gaps=True )
    lsst = telescopes.Telescope(name='LSST', camera_filter='i',
                               location='Earth',
                               light_curve_magnitude=lsst_lc)

    ffp_lsst.telescopes.append(lsst)

    model_lsst = microlmodels.create_model('PSPL', ffp_lsst,
                                      parallax=['Full', t0])
    model_lsst.define_model_parameters()

    fit_lsst = microlfits.MLFits(ffp_lsst)
    fit_lsst.model = model_lsst
    fit_lsst.fit_results = model_params

    ffp_lsst.fits.append(fit_lsst)

    print('Generated event lightcurve from LSST')
    print('Model parameters:')
    print_fit_params(model_params)


    ffp_wfirst = event.Event()
    ffp_wfirst.name = 'FFP'
    ffp_wfirst.ra = ra
    ffp_wfirst.dec = dec

    horizons_table = jplhorizons_utils.parse_JPL_Horizons_table(horizons_file_path=horizons_file,
                                                                table_type='OBSERVER')

    spacecraft_positions = jplhorizons_utils.extract_spacecraft_positions(horizons_table,t0)

    wfirst_lc = simulate_lightcurve(start_jd, end_jd, 0.25/24.0, wfirst_aperture, spring, fall)

    wfirst = telescopes.Telescope(name='WFIRST', camera_filter='W149',
                               spacecraft_name = 'WFIRST',
                               location='Space',
                               light_curve_magnitude=wfirst_lc)
    wfirst.spacecraft_positions = spacecraft_positions

    ffp_wfirst.telescopes.append(wfirst)

    model_wfirst = microlmodels.create_model('PSPL', ffp_wfirst,
                                      parallax=['Full', t0])

    model_wfirst.define_model_parameters()

    fit_wfirst = microlfits.MLFits(ffp_wfirst)
    fit_wfirst.model = model_wfirst
    fit_wfirst.fit_results = model_params

    ffp_wfirst.fits.append(fit_wfirst)

    print('Generated event lightcurve from WFIRST')
    print('Model parameters:')
    print_fit_params(fit_wfirst)

    parameters = [ t0, u0, tE ]

    lsst_pylima_params = extract_event_parameters(ffp_lsst, fit_lsst, parameters, source_flux, blend_ratio)
    wfirst_pylima_params = extract_event_parameters(ffp_wfirst, fit_wfirst, parameters, source_flux, blend_ratio)

    lsst_lc = add_lensing_event_to_lightcurve(lsst_pylima_params, ffp_lsst,
                                              fit_lsst, lsst_read_noise)

    wfirst_lc = add_lensing_event_to_lightcurve(wfirst_pylima_params, ffp_wfirst,
                                                fit_wfirst, wfirst_read_noise)

    plot_fitted_lightcurves(lsst_lc, wfirst_lc, ffp_lsst, ffp_wfirst,
                            'LSST', 'WFIRST', 'ffp_sim_lightcurve.png',
                            t0=t0,tE=tE)
Exemplo n.º 16
0
def simulate_a_telescope(name,
                         event,
                         time_start,
                         time_end,
                         sampling,
                         location,
                         filter,
                         uniform_sampling=False,
                         altitude=0,
                         longitude=0,
                         latitude=0,
                         spacecraft_name=None,
                         bad_weather_percentage=0.0,
                         minimum_alt=20,
                         moon_windows_avoidance=20,
                         maximum_moon_illumination=100.0):
    """ Simulate a telescope. More details in the telescopes module. The observations simulation are made for the
        full time windows, then limitation are applied :
            - Sun has to be below horizon : Sun< -18
            - Moon has to be more than the moon_windows_avoidance distance from the target
            - Observations altitude of the target have to be bigger than minimum_alt

    :param str name:  the name of the telescope.
    :param object event: the microlensing event you look at
    :param float time_start: the start of observations in JD
    :param float time_end: the end of observations in JD
    :param float sampling: the hour sampling.
    :param str location: the location of the telescope.
    :param str filter: the filter used for observations
    :param boolean uniform_sampling: set it to True if you want no bad weather, no moon avoidance etc....

    :param float altitude: the altitude in meters if the telescope
    :param float longitude: the longitude in degree of the telescope location
    :param float latitude: the latitude in degree of the telescope location

    :param str spacecraft_name: the name of your satellite according to JPL horizons

    :param float bad_weather_percentage: the percentage of bad nights
    :param float minimum_alt: the minimum altitude ini degrees that your telescope can go to.
    :param float moon_windows_avoidance: the minimum distance in degrees accepted between the target and the Moon
    :param float maximum_moon_illumination: the maximum Moon brightness you allow in percentage
    :return: a telescope object
    :rtype: object
    """
    #import pdb; pdb.set_trace()

    # fake lightcurve
    if (uniform_sampling == False) & (location != 'Space'):
        earth_location = EarthLocation(lon=longitude * astropy.units.deg,
                                       lat=latitude * astropy.units.deg,
                                       height=altitude * astropy.units.m)

        target = SkyCoord(event.ra, event.dec, unit='deg')

        minimum_sampling = min(4.0, sampling)
        ratio_sampling = np.round(sampling / minimum_sampling)

        time_of_observations = time_simulation(time_start, time_end,
                                               minimum_sampling,
                                               bad_weather_percentage)

        time_convertion = Time(time_of_observations, format='jd').isot

        telescope_altaz = target.transform_to(
            AltAz(obstime=time_convertion, location=earth_location))
        altazframe = AltAz(obstime=time_convertion, location=earth_location)
        Sun = get_sun(Time(time_of_observations,
                           format='jd')).transform_to(altazframe)
        Moon = get_moon(Time(time_of_observations,
                             format='jd')).transform_to(altazframe)
        Moon_illumination = moon_illumination(Sun, Moon)
        Moon_separation = target.separation(Moon)
        observing_windows = np.where(
            (telescope_altaz.alt > minimum_alt * astropy.units.deg)
            & (Sun.alt < -18 * astropy.units.deg)
            & (Moon_separation > moon_windows_avoidance * astropy.units.deg)
            & (Moon_illumination < maximum_moon_illumination))[0]

        time_of_observations = time_of_observations[observing_windows]

    else:

        time_of_observations = np.arange(time_start, time_end,
                                         sampling / (24.0))

    lightcurveflux = np.ones((len(time_of_observations), 3)) * 42
    lightcurveflux[:, 0] = time_of_observations

    telescope = telescopes.Telescope(name=name,
                                     camera_filter=filter,
                                     light_curve_flux=lightcurveflux,
                                     location=location,
                                     spacecraft_name=spacecraft_name)

    return telescope
Exemplo n.º 17
0
def plot_mulens(n_clicks, object_data):
    """ Fit for microlensing event

    TODO: implement a fit using pyLIMA
    """
    if n_clicks is not None:
        pdf_ = pd.read_json(object_data)
        cols = [
            'i:jd', 'i:magpsf', 'i:sigmapsf', 'i:fid', 'i:ra', 'i:dec',
            'i:magnr', 'i:sigmagnr', 'i:magzpsci', 'i:isdiffpos', 'i:objectId'
        ]
        pdf = pdf_.loc[:, cols]
        pdf['i:fid'] = pdf['i:fid'].astype(str)
        pdf = pdf.sort_values('i:jd', ascending=False)

        mag_dc, err_dc = np.transpose([
            dc_mag(*args) for args in zip(
                pdf['i:fid'].astype(int).values, pdf['i:magpsf'].astype(
                    float).values, pdf['i:sigmapsf'].astype(float).values,
                pdf['i:magnr'].astype(float).values, pdf['i:sigmagnr'].astype(
                    float).values, pdf['i:magzpsci'].astype(
                        float).values, pdf['i:isdiffpos'].values)
        ])

        current_event = event.Event()
        current_event.name = pdf['i:objectId'].values[0]

        current_event.ra = pdf['i:ra'].values[0]
        current_event.dec = pdf['i:dec'].values[0]

        filts = {'1': 'g', '2': 'r'}
        for fid in np.unique(pdf['i:fid'].values):
            mask = pdf['i:fid'].values == fid
            telescope = telescopes.Telescope(
                name='ztf_{}'.format(filts[fid]),
                camera_filter=format(filts[fid]),
                light_curve_magnitude=np.transpose([
                    pdf['i:jd'].values[mask], pdf['i:magpsf'].values[mask],
                    pdf['i:sigmapsf'].values[mask]
                ]),
                light_curve_magnitude_dictionnary={
                    'time': 0,
                    'mag': 1,
                    'err_mag': 2
                })

            current_event.telescopes.append(telescope)

        # Le modele le plus simple
        mulens_model = microlmodels.create_model('PSPL', current_event)

        current_event.fit(mulens_model, 'DE')

        # 4 parameters
        dof = len(pdf) - 4 - 1

        results = current_event.fits[0]

        normalised_lightcurves = microltoolbox.align_the_data_to_the_reference_telescope(
            results, 0, results.fit_results)

        # Model
        create_the_fake_telescopes(results, results.fit_results)

        telescope_ = results.event.fake_telescopes[0]

        flux_model = mulens_model.compute_the_microlensing_model(
            telescope_,
            results.model.compute_pyLIMA_parameters(results.fit_results))[0]

        time = telescope_.lightcurve_flux[:, 0]
        magnitude = microltoolbox.flux_to_magnitude(flux_model)

        if '1' in np.unique(pdf['i:fid'].values):
            plot_filt1 = {
                'x': [
                    convert_jd(t, to='iso')
                    for t in normalised_lightcurves[0][:, 0]
                ],
                'y':
                normalised_lightcurves[0][:, 1],
                'error_y': {
                    'type': 'data',
                    'array': normalised_lightcurves[0][:, 2],
                    'visible': True,
                    'color': '#1f77b4'
                },
                'mode':
                'markers',
                'name':
                'g band',
                'text': [
                    convert_jd(t, to='iso')
                    for t in normalised_lightcurves[0][:, 0]
                ],
                'marker': {
                    'size': 12,
                    'color': '#1f77b4',
                    'symbol': 'o'
                }
            }
        else:
            plot_filt1 = {}

        if '2' in np.unique(pdf['i:fid'].values):
            plot_filt2 = {
                'x': [
                    convert_jd(t, to='iso')
                    for t in normalised_lightcurves[1][:, 0]
                ],
                'y':
                normalised_lightcurves[1][:, 1],
                'error_y': {
                    'type': 'data',
                    'array': normalised_lightcurves[1][:, 2],
                    'visible': True,
                    'color': '#ff7f0e'
                },
                'mode':
                'markers',
                'name':
                'r band',
                'text': [
                    convert_jd(t, to='iso')
                    for t in normalised_lightcurves[1][:, 0]
                ],
                'marker': {
                    'size': 12,
                    'color': '#ff7f0e',
                    'symbol': 'o'
                }
            }
        else:
            plot_filt2 = {}

        fit_filt = {
            'x': [convert_jd(float(t), to='iso') for t in time],
            'y': magnitude,
            'mode': 'lines',
            'name': 'fit',
            'showlegend': False,
            'line': {
                'color': '#7f7f7f',
            }
        }

        figure = {
            'data': [fit_filt, plot_filt1, plot_filt2],
            "layout": layout_mulens
        }

        # fitted parameters
        names = results.model.model_dictionnary
        params = results.fit_results
        err = np.diag(np.sqrt(results.fit_covariance))

        mulens_params = """
        ```python
        # Fitted parameters
        t0: {} +/- {} (jd)
        tE: {} +/- {} (days)
        u0: {} +/- {}
        chi2/dof: {}
        ```
        ---
        """.format(params[names['to']], err[names['to']], params[names['tE']],
                   err[names['tE']], params[names['uo']], err[names['uo']],
                   params[-1] / dof)
        return figure, mulens_params

    mulens_params = """
    ```python
    # Fitted parameters
    t0: None
    tE: None
    u0: None
    chi2: None
    ```
    ---
    """
    return {'data': [], "layout": layout_mulens}, mulens_params
Exemplo n.º 18
0
import os
import sys
import numpy as np

sys.path.append("/usr/custom/pyLIMA-1.0.0")
from pyLIMA import event, telescopes, microlmodels
from pyLIMA_functions import chi2_telescope

file_1 = "test_10000.txt"
data_1 = np.loadtxt(file_1)
telescope_1 = telescopes.Telescope(light_curve_magnitude=data_1)

your_event = event.Event()
your_event.telescopes.append(telescope_1)
model_1 = microlmodels.create_model('PSPL', your_event)
model_1.define_model_parameters()

t_0 = 2456900.
u_0 = 0.01
t_E = 20.

parameters_list = [t_0, u_0, t_E]
Exemplo n.º 19
0
### Create an event object. You can choose the name and RA,DEC in degrees :

your_event = event.Event()
your_event.name = 'your choice'

#Here RA DEC matters !!
your_event.ra = 266.25624999999997

your_event.dec = -22.261972222222223

## Now we need some observations. That's good, we obtain some data on two
### telescopes. Both are in I band and magnitude units :

data_1 = np.loadtxt('./Survey_parallax.dat')
telescope_1 = telescopes.Telescope(name='OGLE',
                                   camera_filter='I',
                                   light_curve_magnitude=data_1)

### Add the telescopes to your event :
your_event.telescopes.append(telescope_1)

### Sanity check
your_event.check_event()

### Construct the model you want to fit. Let's go basic with a PSPL, without second_order effects :
model_1 = microlmodels.create_model('PSPL', your_event)

### Let's try with the simplest Levenvberg_Marquardt algorithm :
your_event.fit(model_1, 'LM')

### Let's see some plots.
Exemplo n.º 20
0
your_event = event.Event()

your_event.name = 'The_secret_event'

### Now we need some observations. That's good, we obtain some data from somewhere....
directory = '/home/etienne/Work/HackSession/secret_event/'

event_telescopes = [i for i in os.listdir(directory)]

for i, name in enumerate(event_telescopes):

    data_1 = np.loadtxt(directory + name)

    telescope_1 = telescopes.Telescope(name=name[:-4],
                                       camera_filter='I',
                                       light_curve_magnitude=data_1)
    plt.scatter(data_1[:, 0] - 2450000, data_1[:, 1])
    your_event.telescopes.append(telescope_1)
plt.xlabel('HJD')
plt.ylabel('Mag')
plt.gca().invert_yaxis()

plt.show()

### Construct the model you want to fit. Let's go basic with a PSPL, without second_order effects :

model_1 = microlmodels.create_model('PSPL', your_event)

### Let's try with the simplest Levenvberg_Marquardt algorithm :
Exemplo n.º 21
0
from pyLIMA import event
from pyLIMA import telescopes
from pyLIMA import microlmodels

### Create an event object. You can choose the name and RA,DEC in degrees :

your_event = event.Event()
your_event.name = 'your choice'
your_event.ra = 269.39166666666665 
your_event.dec = -29.22083333333333

### Now we need some observations. That's good, we obtain some data on two
### telescopes. Both are in I band and magnitude units :

data_1 = np.loadtxt('./Survey_1.dat')
telescope_1 = telescopes.Telescope(name='OGLE', camera_filter='I', light_curve_magnitude=data_1)

data_2 = np.loadtxt('./Followup_1.dat')
telescope_2 = telescopes.Telescope(name='LCOGT', camera_filter='I', light_curve_magnitude=data_2)

### Add the telescopes to your event :
your_event.telescopes.append(telescope_1)
your_event.telescopes.append(telescope_2)

### Find the survey telescope :
your_event.find_survey('OGLE')

### Sanity check
your_event.check_event()

Exemplo n.º 22
0
def fit_PSPL_parallax(ra, dec, photometry, emag_limit=None, cores=None):

    # Filter orders
    filters_order = ['I', 'ip', 'i_ZTF', 'r_ZTF', 'R', 'g_ZTF', 'gp', 'G']

    filters = np.unique(photometry[:, -1])
    order = []
    for fil in filters_order:

        mask = np.where(filters == fil)[0]
        if len(mask) != 0:
            order += mask.tolist()

    for fil in filters:

        if fil not in filters_order:
            mask = np.where(filters == fil)[0]
            if len(mask) != 0:
                order += mask.tolist()
    filters = filters[order]

    t0_fit, u0_fit, tE_fit, mag_source_fit, mag_blend_fit, mag_baseline_fit, chi2_fit = fit_PSPL(
        photometry, emag_limit=None, cores=cores)

    current_event = event.Event()
    current_event.name = 'MOP_to_fit'

    current_event.ra = ra
    current_event.dec = dec

    for ind, filt in enumerate(filters):

        if emag_limit:

            mask = (photometry[:, -1] == filt) & (np.abs(
                photometry[:, -2].astype(float)) < emag_limit)

        else:

            mask = (photometry[:, -1] == filt)
        lightcurve = photometry[mask, :-1].astype(float)

        telescope = telescopes.Telescope(name='Tel_' + str(ind),
                                         camera_filter=filt,
                                         light_curve_magnitude=lightcurve,
                                         light_curve_magnitude_dictionnary={
                                             'time': 0,
                                             'mag': 1,
                                             'err_mag': 2
                                         },
                                         clean_the_lightcurve='Yes')

        if len(lightcurve) > 5:
            current_event.telescopes.append(telescope)

    t0_par = t0_fit

    Model_parallax = microlmodels.create_model('PSPL',
                                               current_event,
                                               parallax=['Full', t0_par])
    Model_parallax.parameters_boundaries[0] = [t0_fit - 100, t0_fit + 100]

    Model_parallax.parameters_boundaries[1] = [-2, 2]
    Model_parallax.parameters_boundaries[2] = [0.1, 500]
    #Model_parallax.parameters_boundaries[3] = [-1,1]
    #Model_parallax.parameters_boundaries[4] = [-1,1]
    Model_parallax.parameters_guess = [t0_fit, u0_fit, tE_fit, 0, 0]

    if cores != 0:

        import multiprocessing
        with multiprocessing.Pool(processes=cores) as pool:
            current_event.fit(Model_parallax,
                              'DE',
                              DE_population_size=10,
                              flux_estimation_MCMC='polyfit',
                              computational_pool=pool)

    else:

        current_event.fit(Model_parallax,
                          'DE',
                          DE_population_size=10,
                          flux_estimation_MCMC='polyfit')

    #if (chi2_fit-current_event.fits[-1].fit_results[-1])/current_event.fits[-1].fit_results[-1]<0.1:

    #return [t0_fit,u0_fit,tE_fit,None,None,mag_source_fit,mag_blend_fit,mag_baseline_fit]

    t0_fit = current_event.fits[-1].fit_results[0]
    u0_fit = current_event.fits[-1].fit_results[1]
    tE_fit = current_event.fits[-1].fit_results[2]
    piEN_fit = current_event.fits[-1].fit_results[3]
    piEE_fit = current_event.fits[-1].fit_results[4]

    mag_source_fit = flux_to_mag(current_event.fits[-1].fit_results[5])
    mag_blend_fit = flux_to_mag(current_event.fits[-1].fit_results[5] *
                                current_event.fits[-1].fit_results[6])
    mag_baseline_fit = flux_to_mag(current_event.fits[-1].fit_results[5] *
                                   (1 + current_event.fits[-1].fit_results[6]))

    if np.isnan(mag_blend_fit):
        mag_blend_fit = "null"

    microloutputs.create_the_fake_telescopes(
        current_event.fits[0], current_event.fits[0].fit_results[:-1])
    model_telescope = current_event.fits[0].event.fake_telescopes[0]
    pyLIMA_parameters = Model_parallax.compute_pyLIMA_parameters(
        current_event.fits[0].fit_results[:-1])
    flux_model = current_event.fits[0].model.compute_the_microlensing_model(
        model_telescope, pyLIMA_parameters)[0]
    magnitude = microltoolbox.flux_to_magnitude(flux_model)
    model_telescope.lightcurve_magnitude[:, 1] = magnitude

    mask = ~np.isnan(magnitude)
    model_telescope.lightcurve_magnitude = model_telescope.lightcurve_magnitude[
        mask]

    try:
        to_return = [
            np.around(t0_fit, 3),
            np.around(u0_fit, 5),
            np.around(tE_fit, 3),
            np.around(piEN_fit, 5),
            np.around(piEE_fit, 5),
            np.around(mag_source_fit, 3),
            np.around(mag_blend_fit, 3),
            np.around(mag_baseline_fit, 3),
            current_event.fits[-1].fit_covariance, model_telescope
        ]
    except:
        to_return = [
            np.around(t0_fit, 3),
            np.around(u0_fit, 5),
            np.around(tE_fit, 3),
            np.around(piEN_fit, 5),
            np.around(piEE_fit, 5),
            np.around(mag_source_fit, 3), mag_blend_fit,
            np.around(mag_baseline_fit, 3),
            current_event.fits[-1].fit_covariance, model_telescope
        ]
    return to_return