Skip to content

Commit

Permalink
Eliminated the usage of astropy logging
Browse files Browse the repository at this point in the history
  • Loading branch information
kr-2003 committed Feb 11, 2024
1 parent e5d74c6 commit 9ea0f8d
Show file tree
Hide file tree
Showing 8 changed files with 51 additions and 24 deletions.
15 changes: 9 additions & 6 deletions stingray/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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]

Expand All @@ -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)
Expand All @@ -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])
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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"):
Expand Down
5 changes: 4 additions & 1 deletion stingray/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -21,6 +22,8 @@

__all__ = ["EventList"]

logger = setup_logger()


@njit
def _from_lc_numba(times, counts, empty_times):
Expand Down Expand Up @@ -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
Expand Down
7 changes: 5 additions & 2 deletions stingray/gti.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__ = [
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -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")

Expand Down Expand Up @@ -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

Expand Down
7 changes: 5 additions & 2 deletions stingray/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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


Expand Down
15 changes: 9 additions & 6 deletions stingray/lightcurve.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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 "
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)
Expand Down
20 changes: 13 additions & 7 deletions stingray/loggingconfig.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging

logger = None

class CustomFormatter(logging.Formatter):

Expand All @@ -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
3 changes: 3 additions & 0 deletions stingray/modeling/parameterestimation.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
logmin,
fitter_to_model_params,
)
from stingray.loggingconfig import CustomFormatter


class OptimizationResults(object):
Expand Down Expand Up @@ -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)

Expand Down
3 changes: 3 additions & 0 deletions stingray/modeling/tests/test_parameterestimation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down

0 comments on commit 9ea0f8d

Please sign in to comment.