Source code for kaxanuk.attribution_analysis.modules.diagnostics

"""
Run diagnostics: the warnings an attribution run logs, kept as data as well.

Each warning site calls :func:`log_diagnostic` instead of logging directly. It
writes the same log line, from the same logger and at the same level, and,
while a run collects (:func:`collect_diagnostics`), records the line as a
:class:`~kaxanuk.attribution_analysis.entities.attribution_result.Diagnostic`
built from the values the line is made of. The run's entry points put what was
collected on ``AttributionResult.diagnostics``.

Collection is per context (``contextvars``): runs in different threads or tasks
never see each other's diagnostics, and outside a run (a method class used on
its own) only the log line is written. Recording reads the values the warning
already computed, so it changes no number.
"""

import contextlib
import contextvars
import datetime
import logging
from collections.abc import Iterator, Mapping

from kaxanuk.attribution_analysis.entities.attribution_result import (
    Diagnostic,
    DiagnosticCode,
    DiagnosticLevel,
    ReadOnlyMapping,
)

_LOGGING_LEVELS = {
    DiagnosticLevel.INFO: logging.INFO,
    DiagnosticLevel.WARNING: logging.WARNING,
}

_collected: contextvars.ContextVar[list[Diagnostic] | None] = contextvars.ContextVar(
    "kaxanuk_attribution_analysis_diagnostics", default=None
)
"""The list the current run records into; ``None`` outside a run."""


[docs] @contextlib.contextmanager def collect_diagnostics() -> Iterator[list[Diagnostic]]: """ Record the diagnostics logged inside the block, in order. Nested blocks share the outermost block's list, so an entry point that loads inputs and then calls the attribution core collects both stages in one list. Yields ------ list[Diagnostic] The list the block records into; read it after the block (or at its end) for everything logged so far. """ current = _collected.get() if current is not None: yield current return collected: list[Diagnostic] = [] token = _collected.set(collected) try: yield collected finally: _collected.reset(token)
[docs] def log_diagnostic( logger: logging.Logger, code: DiagnosticCode, message: str, *args: object, level: DiagnosticLevel = DiagnosticLevel.WARNING, count: int | None = None, total: int | None = None, first_date: object = None, details: Mapping[str, object] | None = None, ) -> None: """ Log a line as before and, inside :func:`collect_diagnostics`, record it. Parameters ---------- logger : logging.Logger The logger the line has always been logged with. code : DiagnosticCode What the line reports. message : str ``%``-style format of the line, as passed to ``logger.warning``. *args : object Its arguments. level : DiagnosticLevel, default WARNING The level the line is logged at. count, total : int or None How many items the line concerns and out of how many (see :class:`~kaxanuk.attribution_analysis.entities.attribution_result.Diagnostic`). first_date : object The first date concerned: a ``datetime.date``, ``datetime.datetime``, ``pandas.Timestamp`` or ISO-8601 string, stored as a ``datetime.date``; anything else is stored as ``None``. details : Mapping[str, object] or None The line's other values by name. """ # stacklevel=2: the record names the warning site, as when it logged directly. logger.log(_LOGGING_LEVELS[level], message, *args, stacklevel=2) collected = _collected.get() if collected is None: return collected.append(Diagnostic( code=code, level=level, message=message % args if args else message, count=None if count is None else int(count), total=None if total is None else int(total), first_date=_as_date(first_date), details=ReadOnlyMapping(details or {}), ))
def _as_date(value: object) -> datetime.date | None: """ `value` as a ``datetime.date``, or ``None`` when it is not a date. Parameters ---------- value : object A ``datetime.date`` or ``datetime.datetime`` (``pandas.Timestamp`` is one), an ISO-8601 string, or anything else. Returns ------- datetime.date or None The calendar date, without time or time zone. """ if isinstance(value, datetime.datetime): # pandas.NaT is a datetime too, the only one unequal to itself, and it has no date. return None if value != value else value.date() # noqa: PLR0124 if isinstance(value, datetime.date): return value if isinstance(value, str): try: return datetime.date.fromisoformat(value[:10]) except ValueError: return None return None