Source code for piazzi._progress

"""A ready-made progress printer for the solvers' ``callback``."""

from __future__ import annotations

import math
import sys
from collections.abc import Callable
from typing import TextIO

from ._common import Callback, IterationInfo

__all__ = ["print_progress"]

_HEADER = (
    f"{'iter':>5}  {'fun':>13}  {'rel_decrease':>12}  {'step':>8}  {'n_fun_grad':>10}  {'n_fun':>6}  {'n_system':>8}"
)






def with_progress(callback: Callback | None, verbose: bool | int) -> Callback | None:
    """``callback``, preceded by :func:`print_progress` when ``verbose`` asks for it.

    Every solver and wrapper calls this on its ``callback`` and ``verbose`` arguments:
    ``False`` or ``0`` leaves ``callback`` as it is, ``True`` prints every iteration and an
    integer ``k`` every ``k``-th one. The user's callback still runs after the printer, and its
    return value still decides whether to stop the run.
    """
    if isinstance(verbose, bool):
        every = int(verbose)
    elif isinstance(verbose, int) and verbose >= 0:
        every = verbose
    else:
        raise ValueError(f"verbose must be a bool or a non-negative integer, got {verbose!r}")
    if every == 0:
        return callback
    printer = print_progress(every=every)
    if callback is None:
        return printer
    user_callback = callback

    def chained(info: IterationInfo) -> bool | None:
        printer(info)
        return user_callback(info)

    return chained