Skip to content

Reference

Utilities

Output grid

The single shared builder of the uniform, endpoint-inclusive output time grid ([t0, t0+dt, …, tf]) that every integrator samples its results onto.

make_output_grid

Python
make_output_grid(
    t0: float, tf: float, dt: float
) -> ndarray

Build a uniform output grid from t0 to tf (inclusive).

The grid is arange(t0, tf, dt) with tf appended when the last sample would otherwise fall short of it — so the final time is always sampled exactly, regardless of whether dt divides tf - t0.

The endpoint tolerance

A last interior sample within four ULPs of tf is replaced by the exact endpoint, avoiding a duplicate roundoff-sized tail. The slack is capped at a small fraction of dt and never replaces the start sample: short time units are valid, and even a sub-picosecond window must retain both bounds. Building offsets from zero avoids accumulating the rounded t0 + dt increment when the start time is large compared with the sampling interval.

This is the one chokepoint every flow family (ODE / DDE / SDE) and the engine run layer build their grid through, so it is also where the silent-footgun horizons are caught early with a domain message: a non-positive dt (which used to surface as a bare ZeroDivisionError from this helper) and a window that does not run forward in time (which used to yield a one-sample garbage trajectory).

Every bound must additionally be finite. dt and final_time were guarded only by > 0 / > t0, which +inf satisfies: an infinite dt slipped through to a two-sample [t0, tf] grid (a "trajectory" of one giant step, silently nothing like the requested sampling), and an infinite final_time reached :func:numpy.arange, which raised the unhelpful ValueError: Maximum allowed size exceeded. Both are rejected here instead, naming the offending value.

PARAMETER DESCRIPTION
t0

Start and end of the window.

TYPE: float

tf

Start and end of the window.

TYPE: float

dt

Output sampling interval. Must be strictly positive.

TYPE: float

RETURNS DESCRIPTION
ndarray

The output times, with t_arr[0] == t0 and t_arr[-1] == tf.

RAISES DESCRIPTION
InvalidParameterError

If dt is not finite and strictly positive, if t0 is not finite, or if tf is not finite and strictly after t0 (an empty / backwards / unbounded window). All subclass :class:ValueError, so except ValueError still catches them.

Examples:

Python Console Session
>>> make_output_grid(0.0, 1.0, 0.5)
array([0. , 0.5, 1. ])
Source code in src/tsdynamics/_utils/grids.py
Python
def make_output_grid(t0: float, tf: float, dt: float) -> np.ndarray:
    """Build a uniform output grid from ``t0`` to ``tf`` (inclusive).

    The grid is ``arange(t0, tf, dt)`` with ``tf`` appended when the last
    sample would otherwise fall short of it — so the final time is always
    sampled exactly, regardless of whether ``dt`` divides ``tf - t0``.

    The endpoint tolerance
    ----------------------
    A last interior sample within four ULPs of ``tf`` is replaced by the exact
    endpoint, avoiding a duplicate roundoff-sized tail.  The slack is capped at
    a small fraction of ``dt`` and never replaces the start sample: short time
    units are valid, and even a sub-picosecond window must retain both bounds.
    Building offsets from zero avoids accumulating the rounded ``t0 + dt``
    increment when the start time is large compared with the sampling interval.

    This is the one chokepoint every flow family (ODE / DDE / SDE) and the
    engine run layer build their grid through, so it is also where the
    silent-footgun horizons are caught early with a domain message: a
    non-positive ``dt`` (which used to surface as a bare ``ZeroDivisionError``
    from this helper) and a window that does not run forward in time (which used
    to yield a one-sample garbage trajectory).

    Every bound must additionally be **finite**.  ``dt`` and ``final_time`` were
    guarded only by ``> 0`` / ``> t0``, which ``+inf`` satisfies: an infinite
    ``dt`` slipped through to a two-sample ``[t0, tf]`` grid (a "trajectory" of
    one giant step, silently nothing like the requested sampling), and an
    infinite ``final_time`` reached :func:`numpy.arange`, which raised the
    unhelpful ``ValueError: Maximum allowed size exceeded``.  Both are rejected
    here instead, naming the offending value.

    Parameters
    ----------
    t0, tf : float
        Start and end of the window.
    dt : float
        Output sampling interval.  Must be strictly positive.

    Returns
    -------
    ndarray
        The output times, with ``t_arr[0] == t0`` and ``t_arr[-1] == tf``.

    Raises
    ------
    tsdynamics.errors.InvalidParameterError
        If ``dt`` is not finite and strictly positive, if ``t0`` is not finite,
        or if ``tf`` is not finite and strictly after ``t0`` (an empty /
        backwards / unbounded window).  All subclass :class:`ValueError`, so
        ``except ValueError`` still catches them.

    Examples
    --------
    >>> make_output_grid(0.0, 1.0, 0.5)
    array([0. , 0.5, 1. ])
    """
    from tsdynamics.errors import invalid_value

    if not (math.isfinite(dt) and dt > 0):
        raise invalid_value("dt", dt, rule="must be finite and > 0 (the output sampling interval)")
    if not math.isfinite(t0):
        raise invalid_value("t0", t0, rule="must be finite (the start of the window)")
    if not math.isfinite(tf):
        raise invalid_value(
            "final_time",
            tf,
            rule="must be finite (the window has to have an end to sample)",
        )
    if not tf > t0:
        raise invalid_value(
            "final_time",
            tf,
            rule=f"must run forward in time (be > the start time {t0!r})",
            hint="check the sign and that final_time exceeds t0",
        )
    span = tf - t0
    if not math.isfinite(span):
        raise invalid_value("final_time", tf, rule="must give a finite window length from t0")
    # A single requested increment has exactly two distinct representable
    # bounds, even when rounding makes ``tf - t0`` slightly larger than dt.
    # It needs no interior lattice, so the multi-sample resolution guard below
    # must not reject it. This is also the grid used by the live ODE stepper.
    if tf == t0 + dt:
        return np.array([t0, tf], dtype=np.float64)
    if dt < span and dt < max(math.ulp(t0), math.ulp(tf)):
        raise invalid_value(
            "dt", dt, rule=f"is too small to advance time from t0={t0!r} at float64 precision"
        )
    t_arr = np.arange(0.0, span, dt)
    if t0 != 0.0:
        t_arr += t0
    slack = min(4.0 * math.ulp(tf), dt * 1e-9)
    if t_arr.size > 1 and (t_arr[-1] >= tf or tf - float(t_arr[-1]) <= slack):
        t_arr[-1] = tf
        return t_arr
    return np.append(t_arr, tf)