def test_check_event_bad_dec(): current_event = event.Event() current_event.dec = -189 with pytest.raises(event.EventException): current_event.check_event()
def test_fit_bad_event_type(): current_event = event.Event() current_event.kind = 'I am not microlensing' with pytest.raises(event.EventException) as event_exception: current_event.fit('PSPL', 'LM') assert 'Can not fit this event kind' in str(event_exception.value)
def test_check_event_bad_ra(): current_event = event.Event() current_event.ra = -49.49 with pytest.raises(event.EventException): current_event.check_event()
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)
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()
def test_check_event_bad_name(): current_event = event.Event() current_event.name = 49.49 with pytest.raises(event.EventException) as event_exception: current_event.check_event() assert 'The event name (49.49) is not correct, it has to be a string' in str(event_exception.value)
def test_check_event_telescopes_without_lightcurves(): current_event = event.Event() telescope = mock.MagicMock() current_event.telescopes.append(telescope) with pytest.raises(event.EventException): current_event.check_event()
def test_check_event_with_one_telescope_with_flux_lightcurve(): current_event = event.Event() telescope = mock.MagicMock() telescope.name = 'NDG' telescope.lightcurve_flux = np.array([0, 36307805477.010025, -39420698921.705284]) current_event.telescopes.append(telescope) current_event.check_event()
def create_event(params): e = event.Event() e.name = params['name'] e.ra = params['ra'] e.dec = params['dec'] return e
def test_lightcurves_in_flux_calls_telescope_lightcurve_in_flux(): current_event = event.Event() telescopes = [mock.MagicMock(), mock.MagicMock()] current_event.telescopes.extend(telescopes) current_event.lightcurves_in_flux(choice='No') for telescope in telescopes: telescope.lightcurve_in_flux.assert_called_with('No')
def test_fit_bad_method(): current_event = event.Event() with pytest.raises(event.EventException) as event_exception: current_event.fit('PSPL', 'I am not a fitter :)') assert 'Wrong fit method request' in str(event_exception.value) with pytest.raises(event.EventException) as event_exception: current_event.fit('PSPL', 51) assert 'Wrong fit method request' in str(event_exception.value)
def create_event(params): """Function to initialise a pyLIMA event object""" current_event = event.Event() current_event.name = params['name'] current_event.ra = params['ra'] current_event.dec = params['dec'] return current_event
def test_find_survey_no_survey(): current_event = event.Event() telescope1 = mock.MagicMock() telescope2 = mock.MagicMock() telescope1.name = 'telescope1' telescope2.name = 'telescope2' current_event.telescopes.append(telescope1) current_event.telescopes.append(telescope2) assert current_event.find_survey('NDG') == None
def test_telescopes_names(): current_event = event.Event() telescope1 = mock.MagicMock() telescope2 = mock.MagicMock() telescope1.name = 'telescope1' telescope2.name = 'telescope2' current_event.telescopes.append(telescope1) current_event.telescopes.append(telescope2) current_event.telescopes_names()
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
def test_lightcurves_in_flux_sets_telescope_lightcurve_flux(): current_event = event.Event() telescope1 = mock.MagicMock() telescope1.lightcurve_in_flux.return_value = np.array([]) telescope2 = mock.MagicMock() telescope2.lightcurve_magnitude = np.array([0, 1, 1]) telescope2.lightcurve_in_flux.return_value = np.array( [0, 36307805477.010025, -39420698921.705284]) telescopes = [telescope1, telescope2] current_event.telescopes.extend(telescopes) current_event.lightcurves_in_flux() results = [np.array([]), np.array([0, 36307805477.010025, -39420698921.705284])] count = 0 for telescope in telescopes: assert np.allclose(telescope.lightcurve_flux, results[count]) count += 1
def simulate_a_microlensing_event(name='Microlensing pyLIMA simulation', ra=270, dec=-30): """ Simulate a microlensing event. More details in the event module. :param str name: the name of the event. Default is 'Microlensing pyLIMA simulation' :param float ra: the right ascension in degrees of your simulation. Default is 270. :param float dec: the declination in degrees of your simulation. Default is -30. :return: a event object :rtype: object """ fake_event = event.Event() fake_event.name = name fake_event.ra = ra fake_event.dec = dec return fake_event
Let's learn how pyLIMA works by fitting an example. Please help yourself with the pyLIMA documentation ''' ### First import the required libraries import numpy as np import matplotlib.pyplot as plt import os, sys 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)
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)
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
def test_check_event_no_telescopes(): current_event = event.Event() with pytest.raises(event.EventException): current_event.check_event()
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