def test_long_cadence(self): lc_build = LcBuilder().build(MissionFfiIdObjectInfo("TIC 352315023", 'all'), "./") self.assertEqual(lc_build.cadence, 600) self.assertGreater(len(lc_build.lc), 0) self.__test_tess_star_params(lc_build.star_info)
def test_long_cadence_coords(self): lc_build = LcBuilder().build(MissionFfiCoordsObjectInfo(300.47, -71.96, 'all'), "./") self.assertEqual(lc_build.cadence, 600) self.assertGreater(len(lc_build.lc), 0) self.__test_tess_star_params(lc_build.star_info)
def test_short_cadence_kic(self): lc_build = LcBuilder().build(MissionObjectInfo("KIC 12557548", 'all'), "./") self.assertEqual(lc_build.cadence, 59) self.assertGreater(len(lc_build.lc), 0) self.__test_kepler_star_params(lc_build.star_info)
def test_short_cadence_epic(self): lc_build = LcBuilder().build(MissionObjectInfo("EPIC 211945201", 'all'), "./") self.assertEqual(lc_build.cadence, 59) self.assertGreater(len(lc_build.lc), 0) self.__test_k2_star_params(lc_build.star_info)
def create_observation_observables(object_id, object_dir, since, name, epoch, epoch_low_err, epoch_up_err, period, period_low_err, period_up_err, duration, observatories_file, timezone, latitude, longitude, altitude, max_days, min_altitude, moon_min_dist, moon_max_dist, transit_fraction, baseline, error_alert=True): """ @param object_id: the candidate id @param object_dir: the candidate directory @param since: starting plan date @param name: the name given to the candidate @param epoch: the candidate epoch @param epoch_low_err: the candidate epoch's lower error @param epoch_up_err: the candidate epoch's upper error @param period: the candidate period @param period_low_err: the candidate period's lower error @param period_up_err: the candidate period's upper error @param duration: the candidate duration @param observatories_file: the file containing the observatories file (csv format) @param timezone: the timezone of the observatory (if observatories_file=None) @param latitude: the latitude of the observatory (if observatories_file=None) @param longitude: the longitude of the observatory (if observatories_file=None) @param altitude: the altitude of the observatory (if observatories_file=None) @param max_days: the maximum number of days to compute the observables @param min_altitude: the minimum altitude of the target above the horizon @param moon_min_dist: the minimum moon distance for moon illumination = 0 @param moon_max_dist: the minimum moon distance for moon illumination = 1 @param transit_fraction: the minimum transit observability (0.25 for at least ingress/egress, 0.5 for ingress/egress + midtime, 1 for ingress, egress and midtime). @param baseline: the required baseline in hours. @param: error_alert: whether to create the alert date to signal imprecise observations @return: the generated data and target folders """ if observatories_file is not None: observatories_df = pd.read_csv(observatories_file, comment='#') else: observatories_df = pd.DataFrame( columns=['name', 'tz', 'lat', 'long', 'alt']) observatories_df = observatories_df.append("Obs-1", timezone, latitude, longitude, altitude) # TODO probably convert epoch to proper JD mission, mission_prefix, id_int = LcBuilder().parse_object_info(object_id) if mission == "TESS": primary_eclipse_time = Time(epoch, format='btjd', scale="tdb") elif mission == "Kepler" or mission == "K2": primary_eclipse_time = Time(epoch, format='bkjd', scale="tdb") else: primary_eclipse_time = Time(epoch, format='jd') target = FixedTarget(SkyCoord(coords, unit=(u.deg, u.deg))) n_transits = int(max_days // period) system = EclipsingSystem(primary_eclipse_time=primary_eclipse_time, orbital_period=u.Quantity(period, unit="d"), duration=u.Quantity(duration, unit="h"), name=name) observables_df = pd.DataFrame(columns=[ 'observatory', 'timezone', 'start_obs', 'end_obs', 'ingress', 'egress', 'midtime', "midtime_up_err_h", "midtime_low_err_h", 'twilight_evening', 'twilight_morning', 'observable', 'moon_phase', 'moon_dist' ]) plan_dir = object_dir + "/plan" images_dir = plan_dir + "/images" if os.path.exists(plan_dir): shutil.rmtree(plan_dir, ignore_errors=True) os.mkdir(plan_dir) if os.path.exists(images_dir): shutil.rmtree(images_dir, ignore_errors=True) os.mkdir(images_dir) alert_date = None for index, observatory_row in observatories_df.iterrows(): observer_site = Observer(latitude=observatory_row["lat"], longitude=observatory_row["lon"], elevation=u.Quantity(observatory_row["alt"], unit="m")) midtransit_times = system.next_primary_eclipse_time( since, n_eclipses=n_transits) ingress_egress_times = system.next_primary_ingress_egress_time( since, n_eclipses=n_transits) constraints = [ AtNightConstraint.twilight_nautical(), AltitudeConstraint(min=min_altitude * u.deg), MoonIlluminationSeparationConstraint( min_dist=moon_min_dist * u.deg, max_dist=moon_max_dist * u.deg) ] moon_for_midtransit_times = get_moon(midtransit_times) moon_dist_midtransit_times = moon_for_midtransit_times.separation( SkyCoord(star_df.iloc[0]["ra"], star_df.iloc[0]["dec"], unit="deg")) moon_phase_midtransit_times = np.round( astroplan.moon_illumination(midtransit_times), 2) transits_since_epoch = np.round( (midtransit_times - primary_eclipse_time).jd / period) midtransit_time_low_err = np.round( (((transits_since_epoch * period_low_err)**2 + epoch_low_err**2) **(1 / 2)) * 24, 2) midtransit_time_up_err = np.round( (((transits_since_epoch * period_up_err)**2 + epoch_up_err**2) **(1 / 2)) * 24, 2) low_err_delta = TimeDelta(midtransit_time_low_err * 3600, format='sec') up_err_delta = TimeDelta(midtransit_time_up_err * 3600, format='sec') i = 0 for midtransit_time in midtransit_times: twilight_evening = observer_site.twilight_evening_nautical( midtransit_time) twilight_morning = observer_site.twilight_morning_nautical( midtransit_time) ingress = ingress_egress_times[i][0] egress = ingress_egress_times[i][1] lowest_ingress = ingress - low_err_delta[i] highest_egress = egress + up_err_delta[i] if error_alert and (highest_egress - lowest_ingress).jd > 0.33: alert_date = midtransit_time if (alert_date is None) or ( alert_date is not None and alert_date >= midtransit_time) else alert_date break else: baseline_low = lowest_ingress - baseline * u.hour baseline_up = highest_egress + baseline * u.hour transit_times = baseline_low + ( baseline_up - baseline_low) * np.linspace(0, 1, 100) observable_transit_times = astroplan.is_event_observable( constraints, observer_site, target, times=transit_times)[0] observable_transit_times_true = np.argwhere( observable_transit_times) observable = len(observable_transit_times_true) / 100 if observable < transit_fraction: i = i + 1 continue start_obs = transit_times[observable_transit_times_true[0]][0] end_obs = transit_times[observable_transit_times_true[ len(observable_transit_times_true) - 1]][0] start_plot = baseline_low end_plot = baseline_up if twilight_evening > start_obs: start_obs = twilight_evening if twilight_morning < end_obs: end_obs = twilight_morning moon_dist = round(moon_dist_midtransit_times[i].degree) moon_phase = moon_phase_midtransit_times[i] # TODO get is_event_observable for several parts of the transit (ideally each 5 mins) to get the proper observable percent. Also with baseline if observatory_row["tz"] is not None and not np.isnan( observatory_row["tz"]): observer_timezone = observatory_row["tz"] else: observer_timezone = get_offset(observatory_row["lat"], observatory_row["lon"], midtransit_time.datetime) observables_df = observables_df.append( { "observatory": observatory_row["name"], "timezone": observer_timezone, "ingress": ingress.isot, "start_obs": start_obs.isot, "end_obs": end_obs.isot, "egress": egress.isot, "midtime": midtransit_time.isot, "midtime_up_err_h": str(int(midtransit_time_up_err[i] // 1)) + ":" + str(int(midtransit_time_up_err[i] % 1 * 60)).zfill(2), "midtime_low_err_h": str(int(midtransit_time_low_err[i] // 1)) + ":" + str(int(midtransit_time_low_err[i] % 1 * 60)).zfill(2), "twilight_evening": twilight_evening.isot, "twilight_morning": twilight_morning.isot, "observable": observable, "moon_phase": moon_phase, "moon_dist": moon_dist }, ignore_index=True) plot_time = start_plot + (end_plot - start_plot) * np.linspace( 0, 1, 100) plt.tick_params(labelsize=6) airmass_ax = plot_airmass(target, observer_site, plot_time, brightness_shading=False, altitude_yaxis=True) airmass_ax.axvspan(twilight_morning.plot_date, end_plot.plot_date, color='white') airmass_ax.axvspan(start_plot.plot_date, twilight_evening.plot_date, color='white') airmass_ax.axvspan(twilight_evening.plot_date, twilight_morning.plot_date, color='gray') airmass_ax.axhspan(1. / np.cos(np.radians(90 - min_altitude)), 5.0, color='green') airmass_ax.get_figure().gca().set_title("") airmass_ax.get_figure().gca().set_xlabel("") airmass_ax.get_figure().gca().set_ylabel("") airmass_ax.set_xlabel("") airmass_ax.set_ylabel("") xticks = [] xticks_labels = [] xticks.append(start_obs.plot_date) hour_min_sec_arr = start_obs.isot.split("T")[1].split(":") xticks_labels.append("T1_" + hour_min_sec_arr[0] + ":" + hour_min_sec_arr[1]) plt.axvline(x=start_obs.plot_date, color="violet") xticks.append(end_obs.plot_date) hour_min_sec_arr = end_obs.isot.split("T")[1].split(":") xticks_labels.append("T1_" + hour_min_sec_arr[0] + ":" + hour_min_sec_arr[1]) plt.axvline(x=end_obs.plot_date, color="violet") if start_plot < lowest_ingress < end_plot: xticks.append(lowest_ingress.plot_date) hour_min_sec_arr = lowest_ingress.isot.split("T")[1].split(":") xticks_labels.append("T1_" + hour_min_sec_arr[0] + ":" + hour_min_sec_arr[1]) plt.axvline(x=lowest_ingress.plot_date, color="red") if start_plot < ingress < end_plot: xticks.append(ingress.plot_date) hour_min_sec_arr = ingress.isot.split("T")[1].split(":") xticks_labels.append("T1_" + hour_min_sec_arr[0] + ":" + hour_min_sec_arr[1]) plt.axvline(x=ingress.plot_date, color="orange") if start_plot < midtransit_time < end_plot: xticks.append(midtransit_time.plot_date) hour_min_sec_arr = midtransit_time.isot.split("T")[1].split( ":") xticks_labels.append("T0_" + hour_min_sec_arr[0] + ":" + hour_min_sec_arr[1]) plt.axvline(x=midtransit_time.plot_date, color="black") if start_plot < egress < end_plot: xticks.append(egress.plot_date) hour_min_sec_arr = egress.isot.split("T")[1].split(":") xticks_labels.append("T4_" + hour_min_sec_arr[0] + ":" + hour_min_sec_arr[1]) plt.axvline(x=egress.plot_date, color="orange") if start_plot < highest_egress < end_plot: xticks.append(highest_egress.plot_date) hour_min_sec_arr = highest_egress.isot.split("T")[1].split(":") xticks_labels.append("T4_" + hour_min_sec_arr[0] + ":" + hour_min_sec_arr[1]) plt.axvline(x=highest_egress.plot_date, color="red") airmass_ax.xaxis.set_tick_params(labelsize=5) airmass_ax.set_xticks([]) airmass_ax.set_xticklabels([]) degrees_ax = get_twin(airmass_ax) degrees_ax.yaxis.set_tick_params(labelsize=6) degrees_ax.set_yticks([1., 1.55572383, 2.]) degrees_ax.set_yticklabels([90, 50, 30]) fig = matplotlib.pyplot.gcf() fig.set_size_inches(1.25, 0.75) plt.savefig(plan_dir + "/images/" + observatory_row["name"] + "_" + str(midtransit_time.isot)[:-4] + ".png", bbox_inches='tight') plt.close() i = i + 1 observables_df = observables_df.sort_values(["midtime", "observatory"], ascending=True) observables_df.to_csv(plan_dir + "/observation_plan.csv", index=False) print("Observation plan created in directory: " + object_dir) return observatories_df, observables_df, alert_date, plan_dir, images_dir
self.min_radius = min_radius self.impact_param = impact_param formatter = logging.Formatter('%(message)s') logger = logging.getLogger() while len(logger.handlers) > 0: logger.handlers.pop() logger.setLevel(logging.INFO) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.INFO) handler.setFormatter(formatter) logger.addHandler(handler) target_name = "TIC 350618622" object_dir = target_name + "_EMLS" lc_builder = LcBuilder() object_info = lc_builder.build_object_info(target_name=target_name, author=None, sectors="all", file=None, cadence=120, initial_mask=None, initial_transit_mask=None, star_info=None, aperture=None, eleanor_corr_flux="pdcsap_flux", outliers_sigma=3, high_rms_enabled=False, high_rms_threshold=1.5, high_rms_bin_hours=4, smooth_enabled=False,
def explore_object(self, object_id, input_lc_file=None, time_units=1, auto_detrend_periodic_signals=False, auto_detrend_ratio=1 / 4, detrend_method="cosine", smooth=False, sectors=None, cadence=300): lc_builder = LcBuilder() object_info = lc_builder.build_object_info(object_id, None, sectors, input_lc_file, cadence, None, [{ "P": 0.59925, "D": 200, "T0": 1354.57 }], None, None, None) lc_build = lc_builder.build(object_info, ".") lc = lc_build.lc lc = lc.remove_outliers(sigma_lower=float('inf'), sigma_upper=3) # remove outliers over 3sigma flux = lc.flux.value flux_err = lc.flux_err.value if time_units == 0: time = lc.astropy_time.jd else: time = lc.time.value if smooth: flux = savgol_filter(flux, 11, 2) flux = uniform_filter1d(flux, 11) lc_df = pd.DataFrame(columns=['#time', 'flux', 'flux_err']) lc_df['#time'] = lc.time.value lc_df['flux'] = lc.flux.value lc_df['flux_err'] = lc.flux_err.value lc_df = pd.DataFrame(columns=['flux']) lc_df['flux'] = acf(lc.flux.value, nlags=7200) test_df = pd.DataFrame(lc_df) ax = test_df.plot() ax.set_ylim(lc_df["flux"].min(), lc_df["flux"].max()) #ax.set_xticks(list(range(0, len(ax.get_xticks()))), ax.get_xticks() / 30 / 24) plt.show() #periodogram = lc.to_periodogram(oversample_factor=10) #fig = px.line(x=periodogram.period.astype('<f4'), y=periodogram.power.astype('<f4'), log_x=True) #fig.show() fig = px.scatter(x=lc.time.value, y=lc.flux.value) fig.show() if auto_detrend_periodic_signals: detrend_period = self.__calculate_max_significant_period( lc, periodogram) if detrend_period is not None: flatten_lc, trend_lc = self.__detrend_by_period( lc, detrend_period * auto_detrend_ratio, detrend_method) fig = go.Figure() fig.add_trace( go.Scatter(x=lc.time.value, y=flux, mode='markers', name='Flux')) fig.add_trace( go.Scatter(x=lc.time.value, y=trend_lc, mode='lines+markers', name='Main Trend')) fig.show() if auto_detrend_periodic_signals: fig = px.line(x=lc.time.value, y=flatten_lc) fig.show() lc.flux = flatten_lc bin_means, bin_edges, binnumber = stats.binned_statistic( lc.time.value, lc.flux.value, statistic='mean', bins=len(time) / 5) bin_stds, _, _ = stats.binned_statistic(time, flux, statistic='std', bins=len(time) / 3) bin_width = (bin_edges[1] - bin_edges[0]) bin_centers = bin_edges[1:] - bin_width / 2 time_binned = bin_centers flux_binned = bin_means lc_binned = lk.LightCurve(time=time_binned, flux=flux_binned) fig = px.scatter(x=lc.time.value, y=lc.flux.value) fig.show() while True: try: user_input = input( "Select the period to fold the light curve: ") if user_input.startswith("q"): break period = float(user_input) except ValueError: print("Wrong number.") continue try: user_input = input("Select the t0 to fold the light curve: ") if user_input.startswith("q"): break t0 = float(user_input) except ValueError: print("Wrong number.") continue try: user_input = input("Select the duration (minutes): ") if user_input.startswith("q"): break duration = float(user_input) except ValueError: print("Wrong number.") continue # flux = lc.flux # args_flux_outer = np.argwhere(flux > 1 + depth * 0.001) # flux[args_flux_outer] = np.nan # time[args_flux_outer] = np.nan # args_flux_outer = np.argwhere(flux < 1 + depth * 0.001) # flux[args_flux_outer] = np.nan # time[args_flux_outer] = np.nan j = 0 fig_transit, axs = plt.subplots(4, 4, figsize=(16, 16)) #fig_transit.suptitle("Transit centered plots for TIC " + str(object_id)) for i in np.arange(t0, t0 + period * 16, period)[0:16]: args_plot = np.argwhere((i - 0.1 < time) & (time < i + 0.1)).flatten() plot_time = time[args_plot] plot_flux = flux[args_plot] axs[j // 4][j % 4].scatter(plot_time, plot_flux, color='gray', alpha=1, rasterized=True, label="Flux Transit " + str(j)) j = j + 1 folded_lc = lk.LightCurve(time=lc.time, flux=lc.flux, flux_err=lc.flux_err) folded_lc.remove_nans() # folded_lc.flux_err = np.nan # folded_lc = folded_lc.bin(bins=500) folded_lc.fold(period=period).scatter() plt.title("Phase-folded period: " + format(period, ".2f") + " days") plt.show() fig_transit.show() fig = px.line(x=folded_lc.time.value, y=folded_lc.flux.value) fig.show() mask = wotan.transit_mask(time, period, duration * 2 / 24 / 60, t0) fig = px.scatter(x=time[~mask], y=flux[~mask]) fig.show()
def execute_triceratops(cpus, indir, object_id, sectors, lc_file, transit_depth, period, t0, transit_duration, rp_rstar, a_rstar, bins, scenarios, sigma_mode, contrast_curve_file): """ Calculates probabilities of the signal being caused by any of the following astrophysical sources: TP No unresolved companion. Transiting planet with Porb around target star. (i, Rp) EB No unresolved companion. Eclipsing binary with Porb around target star. (i, qshort) EBx2P No unresolved companion. Eclipsing binary with 2 × Porb around target star. (i, qshort) PTP Unresolved bound companion. Transiting planet with Porb around primary star. (i, Rp, qlong) PEB Unresolved bound companion. Eclipsing binary with Porb around primary star. (i, qshort, qlong) PEBx2P Unresolved bound companion. Eclipsing binary with 2 × Porb around primary star. (i, qshort, qlong) STP Unresolved bound companion. Transiting planet with Porb around secondary star. (i, Rp, qlong) SEB Unresolved bound companion. Eclipsing binary with Porb around secondary star. (i, qshort, qlong) SEBx2P Unresolved bound companion. Eclipsing binary with 2 × Porb around secondary star. (i, qshort, qlong) DTP Unresolved background star. Transiting planet with Porb around target star. (i, Rp, simulated star) DEB Unresolved background star. Eclipsing binary with Porb around target star. (i, qshort, simulated star) DEBx2P Unresolved background star. Eclipsing binary with 2 × Porb around target star. (i, qshort, simulated star) BTP Unresolved background star. Transiting planet with Porb around background star. (i, Rp, simulated star) BEB Unresolved background star. Eclipsing binary with Porb around background star. (i, qshort, simulated star) BEBx2P Unresolved background star. Eclipsing binary with 2 × Porb around background star. (i, qshort, simulated star) NTP No unresolved companion. Transiting planet with Porb around nearby star. (i, Rp) NEB No unresolved companion. Eclipsing binary with Porb around nearby star. (i, qshort) NEBx2P No unresolved companion. Eclipsing binary with 2 × Porb around nearby star. (i, qshort) FPP = 1 - (TP + PTP + DTP) NFPP = NTP + NEB + NEBx2P Giacalone & Dressing (2020) define validated planets as TOIs with NFPP < 10−3 and FPP < 0.015 (or FPP ≤ 0.01, when rounding to the nearest percent) @param cpus: number of cpus to be used @param indir: root directory to store the results @param id_int: the object id for which the analysis will be run @param sectors: the sectors of the tic @param lc_file: the light curve source file @param transit_depth: the depth of the transit signal (ppts) @param period: the period of the transit signal /days) @param t0: the t0 of the transit signal (days) @param transit_duration: the duration of the transit signal (minutes) @param rp_rstar: radius of planet divided by radius of star @param a_rstar: semimajor axis divided by radius of star @param bins: the number of bins to average the folded curve @param scenarios: the number of scenarios to validate @param sigma_mode: the way to calculate the sigma for the validation ['flux_err' | 'binning'] @param contrast_curve_file: the auxiliary contrast curve file to give more information to the validation engine. """ save_dir = indir + "/triceratops" if os.path.exists(save_dir): shutil.rmtree(save_dir, ignore_errors=True) if not os.path.exists(save_dir): os.makedirs(save_dir) duration = transit_duration / 60 / 24 logging.info("----------------------") logging.info("Validation procedures") logging.info("----------------------") logging.info("Pre-processing sectors") mission, mission_prefix, id_int = LcBuilder().parse_object_info( object_id) if mission == "TESS": sectors = np.array(sectors) sectors_cut = TesscutClass().get_sectors("TIC " + str(id_int)) sectors_cut = np.array( [sector_row["sector"] for sector_row in sectors_cut]) if len(sectors) != len(sectors_cut): logging.warning("WARN: Some sectors were not found in TESSCUT") logging.warning("WARN: Sherlock sectors were: " + str(sectors)) logging.warning("WARN: TESSCUT sectors were: " + str(sectors_cut)) sectors = np.intersect1d(sectors, sectors_cut) if len(sectors) == 0: logging.warning( "There are no available sectors to be validated, skipping TRICERATOPS." ) return save_dir, None, None logging.info("Will execute validation for sectors: " + str(sectors)) logging.info("Acquiring triceratops target") target = tr.target(ID=id_int, mission=mission, sectors=sectors) # TODO allow user input apertures logging.info("Reading apertures from directory") apertures = yaml.load(open(object_dir + "/apertures.yaml"), yaml.SafeLoader) apertures = apertures["sectors"] valid_apertures = {} for sector, aperture in apertures.items(): if sector in sectors: valid_apertures[sector] = aperture target.plot_field(save=True, fname=save_dir + "/field_S" + str(sector), sector=sector, ap_pixels=aperture) apertures = np.array( [aperture for sector, aperture in apertures.items()]) valid_apertures = np.array( [aperture for sector, aperture in valid_apertures.items()]) depth = transit_depth / 1000 if contrast_curve_file is not None: logging.info("Reading contrast curve %s", contrast_curve_file) plt.clf() cc = pd.read_csv(contrast_curve_file, header=None) sep, dmag = cc[0].values, cc[1].values plt.plot(sep, dmag, 'k-') plt.ylim(9, 0) plt.ylabel("$\\Delta K_s$", fontsize=20) plt.xlabel("separation ('')", fontsize=20) plt.savefig(save_dir + "/contrast_curve.png") plt.clf() logging.info("Calculating validation closest stars depths") target.calc_depths(depth, valid_apertures) target.stars.to_csv(save_dir + "/stars.csv", index=False) lc = pd.read_csv(lc_file, header=0) time, flux, flux_err = lc["#time"].values, lc["flux"].values, lc[ "flux_err"].values lc_len = len(time) zeros_lc = np.zeros(lc_len) logging.info("Preparing validation light curve for target") if mission == "TESS": lc = TessLightCurve(time=time, flux=flux, flux_err=flux_err, quality=zeros_lc) else: lc = KeplerLightCurve(time=time, flux=flux, flux_err=flux_err, quality=zeros_lc) lc.extra_columns = [] fig, axs = plt.subplots(1, 1, figsize=(8, 4), constrained_layout=True) axs, bin_centers, bin_means, bin_errs = Watson.compute_phased_values_and_fill_plot( object_id, axs, lc, period, t0 + period / 2, depth, duration, rp_rstar, a_rstar, bins=bins) plt.savefig(save_dir + "/folded_curve.png") plt.clf() bin_centers = (bin_centers - 0.5) * period logging.info("Sigma mode is %s", sigma_mode) sigma = np.nanmean( bin_errs) if sigma_mode == 'binning' else np.nanmean(flux_err) logging.info("Computed folded curve sigma = %s", sigma) logging.info("Preparing validation processes inputs") input_n_times = [ ValidatorInput(save_dir, copy.deepcopy(target), bin_centers, bin_means, sigma, period, depth, valid_apertures, value, contrast_curve_file) for value in range(0, scenarios) ] logging.info("Start validation processes") #TODO fix usage of cpus returning same value for all executions with Pool(processes=1) as pool: validation_results = pool.map(TriceratopsThreadValidator.validate, input_n_times) logging.info("Finished validation processes") fpp_sum = 0 fpp2_sum = 0 fpp3_sum = 0 nfpp_sum = 0 probs_total_df = None scenarios_num = len(validation_results[0][4]) star_num = np.zeros((5, scenarios_num)) u1 = np.zeros((5, scenarios_num)) u2 = np.zeros((5, scenarios_num)) fluxratio_EB = np.zeros((5, scenarios_num)) fluxratio_comp = np.zeros((5, scenarios_num)) target = input_n_times[0].target target.star_num = np.zeros(scenarios_num) target.u1 = np.zeros(scenarios_num) target.u2 = np.zeros(scenarios_num) target.fluxratio_EB = np.zeros(scenarios_num) target.fluxratio_comp = np.zeros(scenarios_num) logging.info("Computing final probabilities from the %s scenarios", scenarios) i = 0 with open(save_dir + "/validation.csv", 'w') as the_file: the_file.write("scenario,FPP,NFPP,FPP2,FPP3+\n") for fpp, nfpp, fpp2, fpp3, probs_df, star_num_arr, u1_arr, u2_arr, fluxratio_EB_arr, fluxratio_comp_arr \ in validation_results: if probs_total_df is None: probs_total_df = probs_df else: probs_total_df = pd.concat((probs_total_df, probs_df)) fpp_sum = fpp_sum + fpp fpp2_sum = fpp2_sum + fpp2 fpp3_sum = fpp3_sum + fpp3 nfpp_sum = nfpp_sum + nfpp star_num[i] = star_num_arr u1[i] = u1_arr u2[i] = u2_arr fluxratio_EB[i] = fluxratio_EB_arr fluxratio_comp[i] = fluxratio_comp_arr the_file.write( str(i) + "," + str(fpp) + "," + str(nfpp) + "," + str(fpp2) + "," + str(fpp3) + "\n") i = i + 1 for i in range(0, scenarios_num): target.star_num[i] = np.mean(star_num[:, i]) target.u1[i] = np.mean(u1[:, i]) target.u2[i] = np.mean(u2[:, i]) target.fluxratio_EB[i] = np.mean(fluxratio_EB[:, i]) target.fluxratio_comp[i] = np.mean(fluxratio_comp[:, i]) fpp_sum = fpp_sum / scenarios nfpp_sum = nfpp_sum / scenarios fpp2_sum = fpp2_sum / scenarios fpp3_sum = fpp3_sum / scenarios logging.info("---------------------------------") logging.info("Final probabilities computed") logging.info("---------------------------------") logging.info("FPP=%s", fpp_sum) logging.info("NFPP=%s", nfpp_sum) logging.info("FPP2(Lissauer et al, 2012)=%s", fpp2_sum) logging.info("FPP3+(Lissauer et al, 2012)=%s", fpp3_sum) the_file.write("MEAN" + "," + str(fpp_sum) + "," + str(nfpp_sum) + "," + str(fpp2_sum) + "," + str(fpp3_sum)) probs_total_df = probs_total_df.groupby("scenario", as_index=False).mean() probs_total_df["scenario"] = pd.Categorical( probs_total_df["scenario"], [ "TP", "EB", "EBx2P", "PTP", "PEB", "PEBx2P", "STP", "SEB", "SEBx2P", "DTP", "DEB", "DEBx2P", "BTP", "BEB", "BEBx2P", "NTP", "NEB", "NEBx2P" ]) probs_total_df = probs_total_df.sort_values("scenario") probs_total_df.to_csv(save_dir + "/validation_scenarios.csv", index=False) target.probs = probs_total_df # target.plot_fits(save=True, fname=save_dir + "/scenario_fits", time=lc.time.value, flux_0=lc.flux.value, # flux_err_0=sigma) return save_dir
action='store_true', help="Whether to run using mcmc or ns. Default is ns.") args = ap.parse_args() resources_dir = path.join(path.dirname(__file__)) file_dir = resources_dir + "/" + 'properties.yaml' if resources_dir != "" and resources_dir is not None \ else 'properties.yaml' print(resources_dir) sherlock_user_properties = yaml.load(open(file_dir), yaml.SafeLoader) user_properties = yaml.load(open(args.properties), yaml.SafeLoader) sherlock_user_properties.update(user_properties) sherlock.Sherlock([], args.explore, sherlock_user_properties["UPDATE_OIS"], sherlock_user_properties["UPDATE_FORCE"], sherlock_user_properties["UPDATE_CLEAN"]).run() sherlock_targets = [] mission_lightcurve_builder = MissionLightcurveBuilder() lcbuilder = LcBuilder() cache_dir = get_from_user_or_default(sherlock_user_properties, "CACHE_DIR", os.path.expanduser('~') + "/") for target, target_configs in sherlock_user_properties["TARGETS"].items(): try: aperture = get_from_user(target_configs, "APERTURE") file = get_from_user_or_config(target_configs, sherlock_user_properties, "FILE") author = get_from_user_or_config(target_configs, sherlock_user_properties, "AUTHOR") star_info = get_star_info(target, target_configs) min_sectors = get_from_user_or_config(target_configs, sherlock_user_properties, "MIN_SECTORS") max_sectors = get_from_user_or_config(target_configs,