def test_create_bad_model():
    # Both tests are equivalent
    event = _create_event()
    # Using a context manager
    with pytest.raises(microlmodels.ModelException) as model_exception:
        microlmodels.create_model('BAD', event)
    assert 'Unknown model "BAD"' in str(model_exception)

    # Manually checking for an exception and error message
    try:
        microlmodels.create_model('BAD', event)
        pytest.fail()
    except microlmodels.ModelException as model_exception:
        assert 'Unknown model "BAD"' in str(model_exception)
Exemple #2
0
def simulate_a_microlensing_model(event,
                                  model='PSPL',
                                  args=(),
                                  parallax=['None', 0.0],
                                  xallarap=['None'],
                                  orbital_motion=['None', 0.0],
                                  source_spots='None'):
    """ Simulate a a microlensing model.

    :param object event: the microlensing event you look at. More details in event module
    :param str model: the microlensing model you want. Default is 'PSPL'. More details in microlmodels module
    :param array_like parallax: the parallax effect you want to add. Default is no parallax.
                                     More details in microlmodels module
    :param array_like xallarap: the xallarap effect you want to add. Default is no parallax.
                                     More details in microlmodels module
    :param str source_spots: If you want to add source spots. Default is no source_spots.
                                     More details in microlmodels module

    :return: a microlmodel object
    :rtype: object
    """

    fake_model = microlmodels.create_model(model, event, args, parallax,
                                           xallarap, orbital_motion,
                                           source_spots)
    fake_model.define_model_parameters()

    return fake_model
Exemple #3
0
def test_define_pyLIMA_standard_parameters_with_xallarap():
    event = _create_event()
    Model = microlmodels.create_model('FSPL', event, xallarap=['Yes', 598.9])

    assert Model.Jacobian_flag == 'No way'
    assert Model.pyLIMA_standards_dictionnary['XiEN'] == 4
    assert Model.pyLIMA_standards_dictionnary['XiEE'] == 5
Exemple #4
0
def test_no_fancy_parameters_to_pyLIMA_standard_parameters():
    event = _create_event()
    Model = microlmodels.create_model('PSPL', event)
    parameters = [42, 51]
    fancy = Model.fancy_parameters_to_pyLIMA_standard_parameters(parameters)

    assert parameters == fancy
Exemple #5
0
def test_create_VariablePL_model():
    event = _create_event()
    varpl_model = microlmodels.create_model('VariablePL',
                                            event,
                                            model_arguments=[1])

    assert isinstance(varpl_model, microlmodels.ModelVariablePL)
Exemple #6
0
def test_align_the_data_to_the_reference_telescope():
    fit = mock.MagicMock()
    even = event.Event()

    telescope_0 = mock.MagicMock()
    telescope_0.name = 'Survey'
    telescope_0.lightcurve_flux = np.random.random((100, 3))
    telescope_0.lightcurve_magnitude = np.random.random((100, 3))
    even.telescopes.append(telescope_0)

    telescope_1 = mock.MagicMock()
    telescope_1.name = 'Followup'
    telescope_1.lightcurve_flux = np.random.random((100, 3)) * 2
    telescope_1.lightcurve_magnitude = np.random.random((100, 3)) * 2
    even.telescopes.append(telescope_1)

    model = microlmodels.create_model('PSPL', even, blend_flux_ratio=True)
    model.define_model_parameters()

    fit.event = even
    fit.model = model

    expected_lightcurves = microltoolbox.align_the_data_to_the_reference_telescope(
        fit, 0, [10, 0.1, 30, 10, 15, 1., 25])

    assert np.allclose(expected_lightcurves[0],
                       even.telescopes[0].lightcurve_magnitude)
Exemple #7
0
def test_define_parameters_boundaries():
    event = _create_event()

    Model = microlmodels.create_model('FSPL', event)

    assert Model.parameters_boundaries == [(-300, 342), (0.0, 2.0), (1.0, 300),
                                           (5 * 1e-5, 0.05)]
Exemple #8
0
def test_complicated_mixing_fancy_parameters_to_pyLIMA_standard_parameters():
    event = _create_event()
    Model = microlmodels.create_model('FSPL', event)

    Model.fancy_to_pyLIMA_dictionnary = {'tstar': 'tE', 'logrho': 'rho'}
    Model.pyLIMA_to_fancy = {
        'logrho': lambda parameters: np.log10(parameters.rho),
        'tstar': lambda parameters: (parameters.logrho * parameters.tE)
    }
    Model.fancy_to_pyLIMA = {
        'rho': lambda parameters: 10**parameters.logrho,
        'tE': lambda parameters: (parameters.tstar / parameters.logrho)
    }
    Model.define_model_parameters()

    tE = 35.6
    uo = 0.1
    logrho = -1.30102
    Parameters = [0.28, uo, tE * logrho, logrho]
    pyLIMA_parameters = Model.compute_pyLIMA_parameters(Parameters)

    assert pyLIMA_parameters.to == 0.28
    assert pyLIMA_parameters.uo == uo
    assert pyLIMA_parameters.tE == tE
    assert pyLIMA_parameters.tstar == np.log10(pyLIMA_parameters.rho) * tE
    assert pyLIMA_parameters.logrho == logrho
    assert np.allclose(pyLIMA_parameters.rho, 0.05, rtol=0.001, atol=0.001)
def test_create_RRLyraeFS_model():
    event = _create_event()
    rrfs_model = microlmodels.create_model('RRLyraeFS',
                                           event,
                                           model_arguments=[1])

    assert isinstance(rrfs_model, microlmodels.ModelRRLyraeFS)
Exemple #10
0
def test_define_parameters_boundaries():
    event = _create_event()

    Model = microlmodels.create_model('FSPL', event, blend_flux_ratio=False)

    assert Model.parameters_boundaries == [(0, 42), (0.0, 1.0), (1.0, 500),
                                           (5 * 10**-5, 0.05)]
Exemple #11
0
def test_source_trajectory_with_parallax():
    to = 0.28
    tE = 35.6
    uo = 0.1
    piEN = 0.1
    piEE = -0.97

    Parameters = collections.namedtuple('parameters',
                                        ['to', 'uo', 'tE', 'piEN', 'piEE'])
    parameters = Parameters(to, uo, tE, piEN, piEE)

    telescope = mock.MagicMock()
    telescope.lightcurve_flux = np.array([[0, 1, 1], [42, 6, 6]])
    telescope.deltas_positions = np.array([[1, 2], [3, 4]])
    event = _create_event()
    event.telescopes[0] = telescope
    Model = microlmodels.create_model('PSPL', event, parallax=['Annual', 0])

    source_X, source_Y, dseparation = Model.source_trajectory(
        telescope, to, uo, tE, parameters)

    assert len(source_X) == len(source_Y) == 2

    tau = (telescope.lightcurve_flux[:, 0] - to) / tE
    piE = np.array([piEN, piEE])

    delta_tau, delta_beta = microlparallax.compute_parallax_curvature(
        piE, telescope.deltas_positions)

    tau += delta_tau
    beta = uo + delta_beta

    assert np.allclose(source_X, tau)  # rotation of alpha
    assert np.allclose(source_Y, beta)
Exemple #12
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()
Exemple #13
0
def test_magnification_USBL_computation():
    event = _create_event()
    Model = microlmodels.create_model('USBL', event)
    Parameters = collections.namedtuple(
        'parameters', ['to', 'uo', 'tE', 'rho', 'logs', 'logq', 'alpha'])

    tc = 0
    uc = 0.70710678
    tE = 1
    rho = 0.0033
    s = np.log10(1.0)
    q = np.log10(0.02)
    alpha = -np.pi / 4
    parameters = Parameters(tc, uc, tE, rho, s, q, alpha)
    tol = 0.001
    reltol = 0.001
    magnification = Model.model_magnification(event.telescopes[0], parameters)

    assert np.allclose(magnification,
                       np.array([1.6311724868, 1.00005927]),
                       rtol=reltol,
                       atol=tol)

    assert np.allclose(magnification,
                       np.array([1.6311724868, 1.00005927]),
                       rtol=reltol,
                       atol=tol)
def test_mlfit_PSPL_LM_without_guess():
    current_event = _create_event()
    model = model = microlmodels.create_model('PSPL',current_event)
    fit = microlfits.MLFits(current_event)
    fit.mlfit(model, 'LM')

    assert fit.fit_covariance.shape == (3 + 2 * len(current_event.telescopes), 3 + 2 * len(current_event.telescopes))
    assert len(fit.fit_results) == 3 + 2 * len(current_event.telescopes) + 1
Exemple #15
0
def test_define_pyLIMA_standard_parameters_with_orbital_motion():
    event = _create_event()
    Model = microlmodels.create_model('FSPL',
                                      event,
                                      orbital_motion=['2D', 598.9])

    assert Model.Jacobian_flag == 'No way'
    assert Model.pyLIMA_standards_dictionnary['dsdt'] == 4
    assert Model.pyLIMA_standards_dictionnary['dalphadt'] == 5
Exemple #16
0
def test_define_parameters_model_dictionnary():
    event = _create_event()

    Model = microlmodels.create_model('FSPL', event, blend_flux_ratio=False)
    Model.define_model_parameters()
    assert list(Model.model_dictionnary.keys()) == [
        'to', 'uo', 'tE', 'rho', 'fs_Test', 'fb_Test'
    ]
    assert list(Model.model_dictionnary.values()) == [0, 1, 2, 3, 4, 5]
Exemple #17
0
def test_define_parameters_model_dictionnary():
    event = _create_event()

    Model = microlmodels.create_model('FSPL', event)
    Model.define_model_parameters()
    assert Model.model_dictionnary.keys() == [
        'to', 'uo', 'tE', 'rho', 'fs_Test', 'g_Test'
    ]
    assert Model.model_dictionnary.values() == [0, 1, 2, 3, 4, 5]
def test_mlfit_FSPL_LM_with_guess():
    current_event = _create_event()
    model = microlmodels.create_model('FSPL',current_event)

    model.parameters_boundaries = [[0, 100], [0, 1], [0, 300], [0, 1]]
    fit = microlfits.MLFits(current_event)
    fit.mlfit(model, 'LM')

    assert fit.fit_covariance.shape == (4 + 2 * len(current_event.telescopes), 4 + 2 * len(current_event.telescopes))
    assert len(fit.fit_results) == 4 + 2 * len(current_event.telescopes) + 1
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
Exemple #20
0
def test_magnification_PSPL_computation():
    event = _create_event()

    Model = microlmodels.create_model('PSPL', event)
    Parameters = collections.namedtuple('parameters', ['to', 'uo', 'tE'])

    to = 0.0
    uo = 0.1
    tE = 1.0

    parameters = Parameters(to, uo, tE)

    amplification = Model.model_magnification(event.telescopes[0], parameters)
    assert np.allclose(amplification, np.array([10.03746101, 1.00]))
Exemple #21
0
def test_magnification_FSPL_computation():
    event = _create_event()

    Model = microlmodels.create_model('FSPL', event)
    Parameters = collections.namedtuple('parameters',
                                        ['to', 'uo', 'tE', 'rho'])

    to = 0.0
    uo = 0.1
    tE = 1.0
    rho = 0.05
    parameters = Parameters(to, uo, tE, rho)

    amplification = Model.model_magnification(event.telescopes[0], parameters)

    assert np.allclose(amplification, np.array([10.34817883, 1.00000064]))
Exemple #22
0
def test_default_microlensing_model_no_fluxes():
    event = _create_event()

    Model = microlmodels.create_model('PSPL', event)
    Parameters = collections.namedtuple(
        'parameters', ['to', 'uo', 'tE', 'fs_Test', 'fb_Test'])

    to = 0.0
    uo = 0.1
    tE = 1.0

    parameters = Parameters(to, uo, tE, 'ihih', None)

    microlensing_model, fs, fb = Model.compute_the_microlensing_model(
        event.telescopes[0], parameters)

    assert np.allclose(microlensing_model, np.array([1, 6]))
Exemple #23
0
def test_magnification_PSBL_computation():
    event = _create_event()
    Model = microlmodels.create_model('PSBL', event)
    Parameters = collections.namedtuple(
        'parameters', ['to', 'uo', 'tE', 'logs', 'logq', 'alpha'])

    tc = 0
    uc = 0.70710678
    tE = 1.0
    s = np.log10(1.0)
    q = np.log10(0.02)
    alpha = -np.pi / 4
    parameters = Parameters(tc, uc, tE, s, q, alpha)

    magnification = Model.model_magnification(event.telescopes[0], parameters)

    assert np.allclose(magnification, np.array([1.63109244, 1.00000063]))
Exemple #24
0
def test_magnification_DSPL_computation():
    event = _create_event()

    Model = microlmodels.create_model('DSPL', event)
    Parameters = collections.namedtuple(
        'parameters', ['to', 'uo', 'delta_to', 'delta_uo', 'tE', 'q_flux_I'])
    to = 0.0
    uo = 0.1
    delta_to = 42.0
    delta_uo = -0.05
    tE = 5.0
    q_flux_I = 0.1

    parameters = Parameters(to, uo, delta_to, delta_uo, tE, q_flux_I)

    amplification = Model.model_magnification(event.telescopes[0], parameters)

    assert np.allclose(amplification, np.array([9.21590819, 2.72932227]))
Exemple #25
0
def test_check_fit_source_flux():
    current_event = _create_event()
    model = microlmodels.create_model('FSPL', current_event)
    model.define_model_parameters()

    fit = microlfits.MLFits(current_event)
    fit.model = model
    fit.fit_results = [0.0, 0.0, 0.0, 0.0, 1.0, 0.0]

    flag = fit.check_fit()

    assert flag == 'Good Fit'

    fit.fit_results = [0.0, 0.0, 0.0, 0.8, -1.0, 0.0]

    flag = fit.check_fit()

    assert flag == 'Bad Fit'
Exemple #26
0
def test_PSPL_Jacobian():
    event = _create_event()

    Model = microlmodels.create_model('PSPL', event, blend_flux_ratio=False)
    Parameters = collections.namedtuple(
        'parameters', ['to', 'uo', 'tE', 'fs_Test', 'fb_Test'])

    to = 0.0
    uo = 0.1
    tE = 1.0
    fs = 10
    g = 1.0

    parameters = Parameters(to, uo, tE, fs, g)

    Jacobian = Model.model_Jacobian(event.telescopes[0], parameters)

    assert Jacobian.shape == (5, len(event.telescopes[0].lightcurve_flux))
Exemple #27
0
def test_FSPL_Jacobian():
    event = _create_event()

    Model = microlmodels.create_model('FSPL', event)
    Parameters = collections.namedtuple(
        'parameters', ['to', 'uo', 'tE', 'rho', 'fs_Test', 'g_Test'])

    to = 0.0
    uo = 0.1
    tE = 1.0
    rho = 0.26
    fs = 10
    g = 1.0

    parameters = Parameters(to, uo, tE, rho, fs, g)

    Jacobian = Model.model_Jacobian(event.telescopes[0], parameters)

    assert Jacobian.shape == (6, len(event.telescopes[0].lightcurve_flux))
Exemple #28
0
def test_PSPL_computate_microlensing_model():
    event = _create_event()

    Model = microlmodels.create_model('PSPL', event, blend_flux_ratio=False)
    Parameters = collections.namedtuple(
        'parameters', ['to', 'uo', 'tE', 'fs_Test', 'fb_Test'])

    to = 0.0
    uo = 0.1
    tE = 1.0
    fs = 10
    fb = 1

    parameters = Parameters(to, uo, tE, fs, fb)

    model, fs, fb = Model.compute_the_microlensing_model(
        event.telescopes[0], parameters)
    assert np.allclose(model,
                       np.array([fs * (10.03746101) + fb, fs * (1.00) + fb]))
Exemple #29
0
def test_one_fancy_parameters_to_pyLIMA_standard_parameters():
    event = _create_event()
    Model = microlmodels.create_model('FSPL', event)

    Model.fancy_to_pyLIMA_dictionnary = {'logrho': 'rho'}
    Model.pyLIMA_to_fancy = {
        'logrho': lambda parameters: np.log10(parameters.rho)
    }
    Model.fancy_to_pyLIMA = {'rho': lambda parameters: 10**parameters.logrho}
    Model.define_model_parameters()

    Parameters = [0.28, 0.1, 35.6, -1.30102]
    pyLIMA_parameters = Model.compute_pyLIMA_parameters(Parameters)

    assert pyLIMA_parameters.to == 0.28
    assert pyLIMA_parameters.uo == 0.1
    assert pyLIMA_parameters.tE == 35.6
    assert pyLIMA_parameters.logrho == -1.30102
    assert np.allclose(pyLIMA_parameters.rho, 0.05, rtol=0.001, atol=0.001)
Exemple #30
0
def test_pyLIMA_standard_parameters_to_fancy_parameters():
    event = _create_event()
    Model = microlmodels.create_model('FSPL', event, source_spots='Yes')

    Model.fancy_to_pyLIMA_dictionnary = {'logrho': 'rho'}
    Model.pyLIMA_to_fancy = {
        'logrho': lambda parameters: np.log10(parameters.rho)
    }
    Model.fancy_to_pyLIMA = {'rho': lambda parameters: 10**parameters.logrho}
    Model.define_model_parameters()

    # to, uo ,tE, log10(0.001), spot
    Parameters = [42.0, 56.9, 2.89, -3.0, 0.0]

    pyLIMA_parameters = Model.compute_pyLIMA_parameters(Parameters)

    fancy_parameters = Model.pyLIMA_standard_parameters_to_fancy_parameters(
        pyLIMA_parameters)
    assert pyLIMA_parameters.rho == 0.001
    assert fancy_parameters.logrho == -3.0
Exemple #31
0
### Find the survey telescope :
your_event.find_survey("OGLE")

### Sanity check
your_event.check_event()


### set gamma for each telescopes :

your_event.telescopes[0].gamma = 0.5
your_event.telescopes[1].gamma = 0.5


### Let's go basic for FSPL :
model_1 = microlmodels.create_model("FSPL", your_event)

### Let's cheat and use the results from example_1 :

model_1.parameters_guess = [79.9, 0.008, 10.1, 0.023]

your_event.fit(model_1, "LM")

### Plot the results

your_event.fits[-1].produce_outputs()
print "Chi2_LM :", your_event.fits[-1].outputs.fit_parameters.chichi
print "Fit parameters : ", your_event.fits[-1].fit_results
plt.show()

Exemple #32
0
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()


### 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.

your_event.fits[0].produce_outputs()

print 'Chi2_LM :',your_event.fits[0].outputs.fit_parameters.chichi

plt.show()

### Let's try with differential evolution  algorithm. WAIT UNTIL THE FIGURE POP UP.
Exemple #33
0
                telescope.location = "Space"
            current_event.telescopes.append(telescope)
            count += 1

        print "Start;", current_event.name
        import pdb

        pdb.set_trace()
        current_event.find_survey("OGLE_I")
        current_event.check_event()
        print [i.name for i in current_event.telescopes]
        # Model = microlmodels.MLModels(current_event, command_line.model,
        #                              parallax=['None', 50.0])

        Model = microlmodels.create_model(
            "PSPL", current_event, parallax=["Annual", 2457512], orbital_motion=["None", 2457143]
        )
        # Model.USBL_windows = [2456850, 2457350]

        # Model.parameters_guess = [2457228.6691167313, 0.5504378287491769, 119.57049960671444, 0.12837357112315345, 0.10480898512419343]
        #                          0.007759720542532279, 0.2082247217878811, -0.0894830786973533, -2.810468587634137,
        #                          0.2, -0.1
        #                          ]

        # Model.parameters_guess = [2457118.2589892996, 0.04693224313041394, 97.82343956853856, 0.008179766610627337, 0.19677292474954153,
        # -0.027979987829886924, -2.7820828889654297, 0.10258095275259316, -0.060878335472263845]
        # Model.parameters_guess = [2457124.8648720165, 0.19, 91.73208043047485, 0.0076081975458405365,
        #                        0.21238283769339375, -0.10463980545672134, -2.8938338520787865, 0.23125922595225648,
        #                       -0.08570629277441434, -0.0003936674943793056, -0.0003000986621273718]

        # Model.parameters_guess = [2457123.7393666035, 0.2059, 100.19567145132673,