From 9ea0f8d9875aa306d7714122e377585e8495018a Mon Sep 17 00:00:00 2001 From: Abhinav Kumar Date: Sun, 11 Feb 2024 19:14:02 +0530 Subject: [PATCH] Eliminated the usage of astropy logging --- stingray/base.py | 15 ++++++++------ stingray/events.py | 5 ++++- stingray/gti.py | 7 +++++-- stingray/io.py | 7 +++++-- stingray/lightcurve.py | 15 ++++++++------ stingray/loggingconfig.py | 20 ++++++++++++------- stingray/modeling/parameterestimation.py | 3 +++ .../tests/test_parameterestimation.py | 3 +++ 8 files changed, 51 insertions(+), 24 deletions(-) diff --git a/stingray/base.py b/stingray/base.py index 954f5ff0c..f9734725a 100644 --- a/stingray/base.py +++ b/stingray/base.py @@ -13,6 +13,7 @@ from astropy.table import Table from astropy.time import Time, TimeDelta from astropy.units import Quantity +from stingray.loggingconfig import setup_logger from .io import _can_save_longdouble, _can_serialize_meta from .utils import ( @@ -58,6 +59,8 @@ "StingrayTimeseries", ] +logger = setup_logger() + def convert_table_attrs_to_lowercase(table: Table) -> Table: """Convert the column names of an Astropy Table to lowercase.""" @@ -1971,7 +1974,7 @@ def _get_all_array_attrs(objs): all_meta_attrs.remove(attr) for attr in ignore_meta: - logging.info(f"The {attr} attribute will be removed from the output ") + logger.info(f"The {attr} attribute will be removed from the output ") if attr in all_meta_attrs: all_meta_attrs.remove(attr) @@ -2242,7 +2245,7 @@ def fill_bad_time_intervals( btis = get_btis(self.gti, self.time[0], self.time[-1]) if len(btis) == 0: - logging.info("No bad time intervals to fill") + logger.info("No bad time intervals to fill") return copy.deepcopy(self) filtered_times = self.time[self.mask] @@ -2255,7 +2258,7 @@ def fill_bad_time_intervals( even_sampling = False if self.dt > 0 and np.isclose(mean_data_separation, self.dt, rtol=0.01): even_sampling = True - logging.info(f"Data are {'not' if not even_sampling else ''} evenly sampled") + logger.info(f"Data are {'not' if not even_sampling else ''} evenly sampled") if even_sampling: est_samples_in_gap = int(max_length / self.dt) @@ -2272,7 +2275,7 @@ def fill_bad_time_intervals( length = bti[1] - bti[0] if length > max_length: continue - logging.info(f"Filling bad time interval {bti} ({length:.4f} s)") + logger.info(f"Filling bad time interval {bti} ({length:.4f} s)") epsilon = 1e-5 * length added_gtis.append([bti[0] - epsilon, bti[1] + epsilon]) filt_low_t, filt_low_idx = find_nearest(filtered_times, bti[0]) @@ -2307,7 +2310,7 @@ def fill_bad_time_intervals( new_attrs[attr].append(np.zeros(nevents) + np.nan) total_filled_time += length - logging.info(f"A total of {total_filled_time} s of data were simulated") + logger.info(f"A total of {total_filled_time} s of data were simulated") new_gtis = join_gtis(self.gti, added_gtis) new_times = np.concatenate(new_times) @@ -2497,7 +2500,7 @@ def estimate_segment_size(self, min_counts=None, min_samples=None, even_sampling and np.isclose(mean_data_separation, self.dt, rtol=0.01) ): even_sampling = True - logging.info(f"Data are {'not' if not even_sampling else ''} evenly sampled") + logger.info(f"Data are {'not' if not even_sampling else ''} evenly sampled") if min_counts is None: if even_sampling and hasattr(self, "counts"): diff --git a/stingray/events.py b/stingray/events.py index a45d0bde3..343bbb255 100644 --- a/stingray/events.py +++ b/stingray/events.py @@ -10,6 +10,7 @@ import numpy as np from stingray.utils import _int_sum_non_zero +from stingray.loggingconfig import setup_logger from .base import StingrayTimeseries from .filters import get_deadtime_mask @@ -21,6 +22,8 @@ __all__ = ["EventList"] +logger = setup_logger() + @njit def _from_lc_numba(times, counts, empty_times): @@ -309,7 +312,7 @@ def to_binned_timeseries(self, dt, array_attrs=None): for attr in array_attrs: if getattr(self, attr, None) is not None: - logging.info(f"Creating the {attr} array") + logger.info(f"Creating the {attr} array") attr_dict[attr] = histogram( self.time, bins=nbins, weights=getattr(self, attr), range=ranges diff --git a/stingray/gti.py b/stingray/gti.py index 22d5d1ec0..99d7689c4 100644 --- a/stingray/gti.py +++ b/stingray/gti.py @@ -10,6 +10,7 @@ from .utils import assign_value_if_none, apply_function_if_none from .utils import check_iterables_close, is_sorted from stingray.exceptions import StingrayError +from stingray.loggingconfig import setup_logger __all__ = [ @@ -38,6 +39,8 @@ "generate_indices_of_segment_boundaries_binned", ] +logger = setup_logger() + def gti_len(gti): """Deprecated, will be removed in version 2.0. Use get_total_gti_length.""" @@ -116,7 +119,7 @@ def load_gtis(fits_file, gtistring=None): """ gtistring = assign_value_if_none(gtistring, "GTI") - logging.info("Loading GTIS from file %s" % fits_file) + logger.info("Loading GTIS from file %s" % fits_file) lchdulist = fits.open(fits_file, checksum=True, ignore_missing_end=True) lchdulist.verify("warn") @@ -624,7 +627,7 @@ def create_gti_from_condition(time, condition, safe_interval=0, dt=None): gtis = [] for idx in idxs: - logging.debug(idx) + logger.debug(idx) startidx = idx[0] stopidx = idx[1] - 1 diff --git a/stingray/io.py b/stingray/io.py index 465394a72..32a6b21d2 100644 --- a/stingray/io.py +++ b/stingray/io.py @@ -14,6 +14,7 @@ import matplotlib.pyplot as plt import stingray.utils as utils +from stingray.loggingconfig import setup_logger from .utils import assign_value_if_none, is_string, order_list_of_arrays, is_sorted from .gti import get_gti_from_all_extensions, load_gtis @@ -35,6 +36,8 @@ except AttributeError: # pragma: no cover HAS_128 = False +logger = setup_logger() + def rough_calibration(pis, mission): """Make a rough conversion between PI channel and energy. @@ -799,7 +802,7 @@ def ref_mjd(fits_file, hdu=1): if isinstance(fits_file, Iterable) and not is_string(fits_file): # pragma: no cover fits_file = fits_file[0] - logging.info("opening %s" % fits_file) + logger.info("opening %s" % fits_file) hdulist = fits.open(fits_file, ignore_missing_end=True) @@ -843,7 +846,7 @@ def common_name(str1, str2, default="common"): common_str = common_str.lstrip("_").lstrip("-") if common_str == "": common_str = default - logging.debug("common_name: %s %s -> %s" % (str1, str2, common_str)) + logger.debug("common_name: %s %s -> %s" % (str1, str2, common_str)) return common_str diff --git a/stingray/lightcurve.py b/stingray/lightcurve.py index 86be3734d..ca597f189 100644 --- a/stingray/lightcurve.py +++ b/stingray/lightcurve.py @@ -34,11 +34,14 @@ from stingray.io import lcurve_from_fits from stingray import bexvar from stingray.base import interpret_times +from stingray.loggingconfig import setup_logger __all__ = ["Lightcurve"] valid_statistics = ["poisson", "gauss", None] +logger = setup_logger() + class Lightcurve(StingrayTimeseries): """ @@ -288,7 +291,7 @@ def __init__( self._time = time if dt is None and time.size > 1: - logging.info( + logger.info( "Computing the bin time ``dt``. This can take " "time. If you know the bin time, please specify it" " at light curve creation" @@ -480,7 +483,7 @@ def bin_hi(self): return self._bin_hi def initial_optional_checks(self, time, counts, err, gti=None): - logging.info( + logger.info( "Checking if light curve is well behaved. This " "can take time, so if you are sure it is already " "sorted, specify skip_checks=True at light curve " @@ -515,11 +518,11 @@ def initial_optional_checks(self, time, counts, err, gti=None): if nonfinite_flag: warnings.warn("There are non-finite points in the data, but they are outside GTIs. ") - logging.info("Checking if light curve is sorted.") + logger.info("Checking if light curve is sorted.") unsorted = not is_sorted(time) if unsorted: - logging.warning("The light curve is unsorted.") + logger.warning("The light curve is unsorted.") return time, counts, err def check_lightcurve(self): @@ -875,14 +878,14 @@ def make_lightcurve(toa, dt, tseg=None, tstart=None, gti=None, mjdref=0, use_his if gti is not None: tseg = np.max(gti) - tstart - logging.info("make_lightcurve: tseg: " + str(tseg)) + logger.info("make_lightcurve: tseg: " + str(tseg)) timebin = int(tseg / dt) # If we are missing the next bin by just 1%, let's round up: if tseg / dt - timebin >= 0.99: timebin += 1 - logging.info("make_lightcurve: timebin: " + str(timebin)) + logger.info("make_lightcurve: timebin: " + str(timebin)) tend = tstart + timebin * dt good = (tstart <= toa) & (toa < tend) diff --git a/stingray/loggingconfig.py b/stingray/loggingconfig.py index caf457d5a..5ac51fec3 100644 --- a/stingray/loggingconfig.py +++ b/stingray/loggingconfig.py @@ -1,5 +1,6 @@ import logging +logger = None class CustomFormatter(logging.Formatter): @@ -25,10 +26,15 @@ def format(self, record): def setup_logger(): - logger = logging.getLogger(__name__) - handler = logging.StreamHandler() - formatter = CustomFormatter() - handler.setFormatter(formatter) - logger.addHandler(handler) - logger.setLevel(logging.DEBUG) - return logger + global logger + + if not logger: + logger = logging.getLogger(__name__) + handler = logging.StreamHandler() + formatter = CustomFormatter() + handler.setFormatter(formatter) + logger.addHandler(handler) + logger.setLevel(logging.DEBUG) + + + return logger \ No newline at end of file diff --git a/stingray/modeling/parameterestimation.py b/stingray/modeling/parameterestimation.py index e5c61d4e4..4113c6cd1 100644 --- a/stingray/modeling/parameterestimation.py +++ b/stingray/modeling/parameterestimation.py @@ -46,6 +46,7 @@ logmin, fitter_to_model_params, ) +from stingray.loggingconfig import CustomFormatter class OptimizationResults(object): @@ -140,6 +141,8 @@ def __init__(self, lpost, res, neg=True, log=None): self.log.setLevel(logging.DEBUG) if not self.log.handlers: ch = logging.StreamHandler() + formatter = CustomFormatter() + ch.setFormatter(formatter) ch.setLevel(logging.DEBUG) self.log.addHandler(ch) diff --git a/stingray/modeling/tests/test_parameterestimation.py b/stingray/modeling/tests/test_parameterestimation.py index 786356079..4e1f44ba7 100644 --- a/stingray/modeling/tests/test_parameterestimation.py +++ b/stingray/modeling/tests/test_parameterestimation.py @@ -11,6 +11,7 @@ from stingray.modeling import ParameterEstimation, PSDParEst, OptimizationResults, SamplingResults from stingray.modeling import PSDPosterior, set_logprior, PSDLogLikelihood, LogLikelihood from stingray.modeling.posterior import fitter_to_model_params +from stingray.loggingconfig import CustomFormatter try: from statsmodels.tools.numdiff import approx_hess @@ -46,6 +47,8 @@ def __init__(self, lpost, res, neg, log=None): self.log.setLevel(logging.DEBUG) if not self.log.handlers: ch = logging.StreamHandler() + formatter = CustomFormatter() + ch.setFormatter(formatter) ch.setLevel(logging.DEBUG) self.log.addHandler(ch)