Skip to content

Commit

Permalink
Refactored logging
Browse files Browse the repository at this point in the history
* Use module-level loggers consistently in entire package
  • Loading branch information
david-zwicker committed Nov 29, 2024
1 parent 787c822 commit b5c9b28
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 34 deletions.
8 changes: 5 additions & 3 deletions droplets/droplet_tracks.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@
from .droplets import SphericalDroplet, droplet_from_data
from .emulsions import Emulsion, EmulsionTimeCourse

_logger = logging.getLogger(__name__)
""":class:`logging.Logger`: Logger instance."""


def contiguous_true_regions(condition: np.ndarray) -> np.ndarray:
"""Finds contiguous True regions in the boolean array "condition".
Expand Down Expand Up @@ -523,7 +526,6 @@ def from_emulsion_time_course(
"""
# get tracks, i.e. clearly overlapping droplets
tracks = cls()
logger = logging.getLogger(cls.__name__)

# determine the tracking method
if method == "overlap":
Expand All @@ -549,7 +551,7 @@ def match_tracks(
tracks.append(DropletTrack(droplets=[droplet], times=[time]))

if found_multiple_overlap:
logger.debug("Found multiple overlapping droplet(s) at t=%g", time)
_logger.debug("Found multiple overlapping droplet(s) at t=%g", time)

Check warning on line 554 in droplets/droplet_tracks.py

View check run for this annotation

Codecov / codecov/patch

droplets/droplet_tracks.py#L554

Added line #L554 was not covered by tests

elif method == "distance":
# track droplets by their physical distance
Expand Down Expand Up @@ -595,7 +597,7 @@ def match_tracks(

# check kwargs
if kwargs:
logger.warning("Unused keyword arguments: %s", kwargs)
_logger.warning("Unused keyword arguments: %s", kwargs)

Check warning on line 600 in droplets/droplet_tracks.py

View check run for this annotation

Codecov / codecov/patch

droplets/droplet_tracks.py#L600

Added line #L600 was not covered by tests

# add all emulsions successively using the given algorithm
t_last = None
Expand Down
13 changes: 7 additions & 6 deletions droplets/droplets.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@
from .tools import spherical
from .tools.misc import enable_scalar_args

_logger = logging.getLogger(__name__)
""":class:`logging.Logger`: Logger instance."""


TDroplet = TypeVar("TDroplet", bound="DropletBase")
DTypeList = list[Union[tuple[str, type[Any]], tuple[str, type[Any], tuple[int, ...]]]]

Expand Down Expand Up @@ -908,8 +912,7 @@ def __init__(
"""
super().__init__(position, radius, interface_width, amplitudes)
if len(self.amplitudes) % 2 != 0:
logger = logging.getLogger(self.__class__.__name__)
logger.warning(
_logger.warning(
"`amplitudes` should be of even length to capture all perturbations of "
"the highest mode."
)
Expand Down Expand Up @@ -1086,10 +1089,9 @@ def __init__(
super().__init__(position, radius, interface_width, amplitudes)
num_modes = len(self.amplitudes) + 1
if not spherical.spherical_index_count_optimal(num_modes):
logger = logging.getLogger(self.__class__.__name__)
l, _ = spherical.spherical_index_lm(num_modes)
opt_modes = spherical.spherical_index_count(l) - 1
logger.warning(
_logger.warning(
"The length of `amplitudes` should be such that all orders are "
"captured for the perturbations with the highest degree (%d). "
"Consider increasing the size of the array to %d.",
Expand Down Expand Up @@ -1304,8 +1306,7 @@ def _load(self):
"""Load the stored resource."""
import h5py

logger = logging.getLogger(__name__)
logger.info("Open resource `%s`", self.path)
_logger.info("Open resource `%s`", self.path)
with h5py.File(self.path, "r") as f:
self.num_list = np.array(f.attrs["num_list"])
self.data = {}
Expand Down
13 changes: 7 additions & 6 deletions droplets/emulsions.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@
from .trackers import DropletTracker


_logger = logging.getLogger(__name__)
""":class:`logging.Logger`: Logger instance."""


class Emulsion(list):
"""Class representing a collection of droplets in a common system."""

Expand Down Expand Up @@ -290,8 +294,7 @@ def data(self) -> np.ndarray:
)
result = np.array([d.data for d in self])
if result.dtype != self.dtype:
logger = logging.getLogger(self.__class__.__name__)
logger.warning("Emulsion had inconsistent dtypes")
_logger.warning("Emulsion had inconsistent dtypes")
return result

def get_linked_data(self) -> np.ndarray:
Expand Down Expand Up @@ -681,8 +684,7 @@ def plot(
f"Plotting emulsions in {self.dim} dimensions is not implemented."
)
elif self.dim > 2 and Emulsion._show_projection_warning:
logger = logging.getLogger(self.__class__.__name__)
logger.warning("A projection on the first two axes is shown.")
_logger.warning("A projection on the first two axes is shown.")
Emulsion._show_projection_warning = False

# plot background and determine bounds for the droplets
Expand Down Expand Up @@ -725,8 +727,7 @@ def plot(
colors: list | np.ndarray = mapper.to_rgba(values)

if kwargs.pop("color", None) is not None:
logger = logging.getLogger(self.__class__.__name__)
logger.warning("`color` is overwritten by `color_value`.")
_logger.warning("`color` is overwritten by `color_value`.")

Check warning on line 730 in droplets/emulsions.py

View check run for this annotation

Codecov / codecov/patch

droplets/emulsions.py#L730

Added line #L730 was not covered by tests

else:
colors = [kwargs.pop("color", None)] * len(drops_finite)
Expand Down
35 changes: 16 additions & 19 deletions droplets/image_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@
)
from .emulsions import Emulsion

_logger = logging.getLogger(__name__)
""":class:`logging.Logger`: Logger instance."""


def threshold_otsu(data: np.ndarray, nbins: int = 256) -> float:
"""Find the threshold value for a bimodal histogram using the Otsu method.
Expand Down Expand Up @@ -107,7 +110,7 @@ def _locate_droplets_in_mask_cartesian(mask: ScalarField) -> Emulsion:

# locate individual clusters in the padded image
labels, num_labels = ndimage.label(mask.data)
grid._logger.info("Found %d cluster(s) in image", num_labels)
_logger.info("Found %d cluster(s) in image", num_labels)
if num_labels == 0:
example_drop = SphericalDroplet(np.zeros(grid.dim), radius=0)
return Emulsion.empty(example_drop)
Expand Down Expand Up @@ -164,11 +167,11 @@ def _locate_droplets_in_mask_cartesian(mask: ScalarField) -> Emulsion:
emulsion = Emulsion(droplets)
num_candidates = len(emulsion)
if num_candidates < num_labels:
grid._logger.info("Only %d candidate(s) inside bounds", num_candidates)
_logger.info("Only %d candidate(s) inside bounds", num_candidates)

emulsion.remove_overlapping(grid=grid)
if len(emulsion) < num_candidates:
grid._logger.info("Only %d candidate(s) not overlapping", num_candidates)
_logger.info("Only %d candidate(s) not overlapping", num_candidates)

return emulsion

Expand Down Expand Up @@ -198,8 +201,7 @@ def _locate_droplets_in_mask_spherical(mask: ScalarField) -> Emulsion:
radius = float(grid.transform(slices[0].stop, "cell", "grid").flat[-1])
droplet = SphericalDroplet(np.zeros(grid.dim), radius=radius)
else:
logger = logging.getLogger(grid.__class__.__module__)
logger.warning("Found object not located at origin")
_logger.warning("Found object not located at origin")

Check warning on line 204 in droplets/image_analysis.py

View check run for this annotation

Codecov / codecov/patch

droplets/image_analysis.py#L204

Added line #L204 was not covered by tests

# return an emulsion of droplets
if droplet:
Expand Down Expand Up @@ -243,8 +245,7 @@ def _locate_droplets_in_mask_cylindrical_single(
# the "droplet" extends the entire z-axis
raise _SpanningDropletSignal
else:
logger = logging.getLogger(grid.__class__.__module__)
logger.warning("Found object not located on symmetry axis")
_logger.warning("Found object not located on symmetry axis")

Check warning on line 248 in droplets/image_analysis.py

View check run for this annotation

Codecov / codecov/patch

droplets/image_analysis.py#L248

Added line #L248 was not covered by tests

# determine position from binary image and scale it to real space
pos = ndimage.center_of_mass(mask, labels, index=indices)
Expand Down Expand Up @@ -297,7 +298,7 @@ def _locate_droplets_in_mask_cylindrical(mask: ScalarField) -> Emulsion:
except _SpanningDropletSignal:
pass
else:
grid._logger.info("Found %d droplet candidates.", len(candidates))
_logger.info("Found %d droplet candidates.", len(candidates))

# keep droplets that are inside the central area
droplets = Emulsion()
Expand All @@ -308,7 +309,7 @@ def _locate_droplets_in_mask_cylindrical(mask: ScalarField) -> Emulsion:
if z_min <= droplet.position[2] <= z_max:
droplets.append(droplet)

grid._logger.info("Kept %d central droplets.", len(droplets))
_logger.info("Kept %d central droplets.", len(droplets))

# filter overlapping droplets (e.g. due to duplicates)
droplets.remove_overlapping()
Expand Down Expand Up @@ -700,8 +701,6 @@ def get_structure_factor(
associated structure factor. Wave numbers :math:`k` are related to distances by
:math:`2\pi/k`.
"""
logger = logging.getLogger(__name__)

if not isinstance(scalar_field, ScalarField):
raise TypeError(
"Length scales can only be calculated for scalar "
Expand All @@ -714,7 +713,7 @@ def get_structure_factor(
"Structure factor can currently only be calculated for Cartesian grids"
)
if not all(grid.periodic):
logger.warning(
_logger.warning(

Check warning on line 716 in droplets/image_analysis.py

View check run for this annotation

Codecov / codecov/patch

droplets/image_analysis.py#L716

Added line #L716 was not covered by tests
"Structure factor calculation assumes periodic boundary "
"conditions, but not all grid dimensions are periodic"
)
Expand Down Expand Up @@ -764,7 +763,7 @@ def get_structure_factor(
sf = sf_smooth(k_mag)

elif not no_wavenumbers:
logger.warning(
_logger.warning(

Check warning on line 766 in droplets/image_analysis.py

View check run for this annotation

Codecov / codecov/patch

droplets/image_analysis.py#L766

Added line #L766 was not covered by tests
"Argument `wave_numbers` is only used when `smoothing` is enabled."
)

Expand Down Expand Up @@ -809,8 +808,6 @@ def get_length_scale(
See Also:
:class:`~droplets.trackers.LengthScaleTracker`: Tracker measuring length scales
"""
logger = logging.getLogger(__name__)

if method == "structure_factor_mean" or method == "structure_factor_average":
# calculate the structure factor
k_mag, sf = get_structure_factor(scalar_field)
Expand All @@ -837,7 +834,7 @@ def get_length_scale(
max_est = k_mag[1 + np.argmax(sf[1:])]
for window_size in [5, 1, 0.2]:
bracket = [max_est / window_size, max_est, max_est * window_size]
logger.debug(
_logger.debug(
"Seek maximal structure factor in interval %s with window_size=%g",
bracket,
window_size,
Expand All @@ -847,11 +844,11 @@ def get_length_scale(
lambda x: -sf_smooth(x), bracket=bracket
)
except Exception:
logger.warning("Could not determine maximal structure factor")
_logger.warning("Could not determine maximal structure factor")

Check warning on line 847 in droplets/image_analysis.py

View check run for this annotation

Codecov / codecov/patch

droplets/image_analysis.py#L847

Added line #L847 was not covered by tests
length_scale = math.nan
else:
if not result.success:
logger.warning(
_logger.warning(

Check warning on line 851 in droplets/image_analysis.py

View check run for this annotation

Codecov / codecov/patch

droplets/image_analysis.py#L851

Added line #L851 was not covered by tests
"Maximization of structure factor resulted in the "
"following message: %s",
result.message,
Expand Down Expand Up @@ -885,7 +882,7 @@ def get_length_scale(

if kwargs:
# raise warning if keyword arguments remain
logger.warning("Unused keyword arguments: %s", ", ".join(kwargs))
_logger.warning("Unused keyword arguments: %s", ", ".join(kwargs))

Check warning on line 885 in droplets/image_analysis.py

View check run for this annotation

Codecov / codecov/patch

droplets/image_analysis.py#L885

Added line #L885 was not covered by tests

# return only the length scale with out any additional information
return length_scale # type: ignore
Expand Down

0 comments on commit b5c9b28

Please sign in to comment.