Skip to content

adaptive.Learner1D

Learner1D

Learner1D(function: Callable[[Real], Float | ndarray], bounds: tuple[Real, Real], loss_per_interval: Callable[[XsTypeN, YsTypeN], Float] | None = None)

Bases: BaseLearner

Learns and predicts a function 'f:ℝ → ℝ^N'.

Parameters:

Name Type Description Default
function callable

The function to learn. Must take a single real parameter and return a real number or 1D array.

required
bounds pair of reals

The bounds of the interval on which to learn 'function'.

required
loss_per_interval Callable[[XsTypeN, YsTypeN], Float] | None

A function that returns the loss for a single interval of the domain. If not provided, then a default is used, which uses the scaled distance in the x-y plane as the loss. See the notes for more details.

None

Attributes:

Name Type Description
data dict

Sampled points and values.

pending_points set

Points that still have to be evaluated.

Notes

loss_per_interval takes 2 parameters: xs and ys, and returns a scalar; the loss over the interval. xs : tuple of floats The x values of the interval, if nth_neighbors is greater than zero it also contains the x-values of the neighbors of the interval, in ascending order. The interval we want to know the loss of is then the middle interval. If no neighbor is available (at the edges of the domain) then None will take the place of the x-value of the neighbor. ys : tuple of function values The output values of the function when evaluated at the xs. This is either a float or a tuple of floats in the case of vector output.

The loss_per_interval function may also have an attribute nth_neighbors that indicates how many of the neighboring intervals to interval are used. If loss_per_interval doesn't have such an attribute, it's assumed that is uses no neighboring intervals. Also see the uses_nth_neighbors decorator for more information.

Source code in adaptive/learner/learner1D.py
def __init__(
    self,
    function: Callable[[Real], Float | np.ndarray],
    bounds: tuple[Real, Real],
    loss_per_interval: Callable[[XsTypeN, YsTypeN], Float] | None = None,
):
    self.function = function  # type: ignore

    if loss_per_interval is not None and hasattr(
        loss_per_interval, "nth_neighbors"
    ):
        self.nth_neighbors = loss_per_interval.nth_neighbors
    else:
        self.nth_neighbors = 0

    self.loss_per_interval = loss_per_interval or default_loss

    # When the scale changes by a factor 2, the losses are
    # recomputed. This is tunable such that we can test
    # the learners behavior in the tests.
    self._recompute_losses_factor = 2

    self.data: dict[Real, Real] = {}
    self.pending_points: set[Real] = set()

    # A dict {x_n: [x_{n-1}, x_{n+1}]} for quick checking of local
    # properties.
    self.neighbors: NeighborsType = SortedDict()
    self.neighbors_combined: NeighborsType = SortedDict()

    # Bounding box [[minx, maxx], [miny, maxy]].
    self._bbox = [list(bounds), [np.inf, -np.inf]]

    # Data scale (maxx - minx), (maxy - miny)
    self._scale = [bounds[1] - bounds[0], 0]
    self._oldscale = deepcopy(self._scale)

    # A LossManager storing the loss function for each interval x_n.
    self.losses = loss_manager(self._scale[0])
    self.losses_combined = loss_manager(self._scale[0])

    # The precision in 'x' below which we set losses to 0.
    self._dx_eps = 2 * max(np.abs(bounds)) * np.finfo(float).eps

    self.bounds: tuple[float, float] = (float(bounds[0]), float(bounds[1]))
    self.__missing_bounds = set(self.bounds)  # cache of missing bounds

    self._vdim: int | None = None

function instance-attribute

function = function

nth_neighbors instance-attribute

nth_neighbors = loss_per_interval.nth_neighbors

loss_per_interval instance-attribute

loss_per_interval = loss_per_interval or default_loss

data instance-attribute

data: dict[Real, Real] = {}

pending_points instance-attribute

pending_points: set[Real] = set()

neighbors instance-attribute

neighbors: NeighborsType = SortedDict()

neighbors_combined instance-attribute

neighbors_combined: NeighborsType = SortedDict()

losses instance-attribute

losses = loss_manager(self._scale[0])

losses_combined instance-attribute

losses_combined = loss_manager(self._scale[0])

bounds instance-attribute

bounds: tuple[float, float] = (float(bounds[0]), float(bounds[1]))

vdim property

vdim: int

Length of the output of learner.function. If the output is unsized (when it's a scalar) then vdim = 1.

As long as no data is known vdim = 1.

npoints property

npoints: int

Number of evaluated points.

new

new() -> Learner1D

Create a copy of Learner1D without the data.

Source code in adaptive/learner/learner1D.py
def new(self) -> Learner1D:
    """Create a copy of `~adaptive.Learner1D` without the data."""
    return Learner1D(self.function, self.bounds, self.loss_per_interval)

to_numpy

to_numpy()

Data as NumPy array of size (npoints, 2) if learner.function returns a scalar and (npoints, 1+vdim) if learner.function returns a vector of length vdim.

Source code in adaptive/learner/learner1D.py
def to_numpy(self):
    """Data as NumPy array of size ``(npoints, 2)`` if ``learner.function`` returns a scalar
    and ``(npoints, 1+vdim)`` if ``learner.function`` returns a vector of length ``vdim``.
    """
    return np.array([(x, *np.atleast_1d(y)) for x, y in sorted(self.data.items())])

to_dataframe

to_dataframe(with_default_function_args: bool = True, function_prefix: str = 'function.', x_name: str = 'x', y_name: str = 'y') -> DataFrame

Return the data as a pandas.DataFrame.

Parameters:

Name Type Description Default
with_default_function_args bool

Include the learner.function's default arguments as a column, by default True

True
function_prefix str

Prefix to the learner.function's default arguments' names, by default "function."

'function.'
x_name str

Name of the input value, by default "x"

'x'
y_name str

Name of the output value, by default "y"

'y'

Returns:

Type Description
DataFrame

Raises:

Type Description
ImportError

If pandas is not installed.

Source code in adaptive/learner/learner1D.py
def to_dataframe(  # type: ignore[override]
    self,
    with_default_function_args: bool = True,
    function_prefix: str = "function.",
    x_name: str = "x",
    y_name: str = "y",
) -> pandas.DataFrame:
    """Return the data as a `pandas.DataFrame`.

    Parameters
    ----------
    with_default_function_args : bool, optional
        Include the ``learner.function``'s default arguments as a
        column, by default True
    function_prefix : str, optional
        Prefix to the ``learner.function``'s default arguments' names,
        by default "function."
    x_name : str, optional
        Name of the input value, by default "x"
    y_name : str, optional
        Name of the output value, by default "y"

    Returns
    -------
    pandas.DataFrame

    Raises
    ------
    ImportError
        If `pandas` is not installed.
    """
    if not with_pandas:
        raise ImportError("pandas is not installed.")
    xs, ys = zip(*sorted(self.data.items())) if self.data else ([], [])
    df = pandas.DataFrame(xs, columns=[x_name])
    df[y_name] = ys
    df.attrs["inputs"] = [x_name]
    df.attrs["output"] = y_name
    if with_default_function_args:
        assign_defaults(self.function, df, function_prefix)
    return df

load_dataframe

load_dataframe(df: DataFrame, with_default_function_args: bool = True, function_prefix: str = 'function.', x_name: str = 'x', y_name: str = 'y') -> None

Load data from a pandas.DataFrame.

If with_default_function_args is True, then learner.function's default arguments are set (using functools.partial) from the values in the pandas.DataFrame.

Parameters:

Name Type Description Default
df DataFrame

The data to load.

required
with_default_function_args bool

The with_default_function_args used in to_dataframe(), by default True

True
function_prefix str

The function_prefix used in to_dataframe, by default "function."

'function.'
x_name str

The x_name used in to_dataframe, by default "x"

'x'
y_name str

The y_name used in to_dataframe, by default "y"

'y'
Source code in adaptive/learner/learner1D.py
def load_dataframe(  # type: ignore[override]
    self,
    df: pandas.DataFrame,
    with_default_function_args: bool = True,
    function_prefix: str = "function.",
    x_name: str = "x",
    y_name: str = "y",
) -> None:
    """Load data from a `pandas.DataFrame`.

    If ``with_default_function_args`` is True, then ``learner.function``'s
    default arguments are set (using `functools.partial`) from the values
    in the `pandas.DataFrame`.

    Parameters
    ----------
    df : pandas.DataFrame
        The data to load.
    with_default_function_args : bool, optional
        The ``with_default_function_args`` used in ``to_dataframe()``,
        by default True
    function_prefix : str, optional
        The ``function_prefix`` used in ``to_dataframe``, by default "function."
    x_name : str, optional
        The ``x_name`` used in ``to_dataframe``, by default "x"
    y_name : str, optional
        The ``y_name`` used in ``to_dataframe``, by default "y"
    """
    self.tell_many(df[x_name].values, df[y_name].values)
    if with_default_function_args:
        self.function = partial_function_from_dataframe(
            self.function, df, function_prefix
        )

loss

loss(real: bool = True) -> float
Source code in adaptive/learner/learner1D.py
@cache_latest
def loss(self, real: bool = True) -> float:
    if self._missing_bounds():
        return np.inf
    losses = self.losses if real else self.losses_combined
    if not losses:
        return np.inf
    max_interval, max_loss = losses.peekitem(0)
    return max_loss

tell

tell(x: float, y: Float | Sequence[Float] | ndarray) -> None
Source code in adaptive/learner/learner1D.py
def tell(self, x: float, y: Float | Sequence[Float] | np.ndarray) -> None:
    if x in self.data:
        # The point is already evaluated before
        return
    if y is None:
        raise TypeError(
            "Y-value may not be None, use learner.tell_pending(x)"
            "to indicate that this value is currently being calculated"
        )

    # either it is a float/int, if not, try casting to a np.array
    if not isinstance(y, float | int):
        y = np.asarray(y, dtype=float)

    # Add point to the real data dict
    self.data[x] = y

    # remove from set of pending points
    self.pending_points.discard(x)

    if not self.bounds[0] <= x <= self.bounds[1]:
        return

    self._update_neighbors(x, self.neighbors_combined)
    self._update_neighbors(x, self.neighbors)
    self._update_scale(x, y)
    self._update_losses(x, real=True)

    # If the scale has increased enough, recompute all losses.
    if self._scale[1] > self._recompute_losses_factor * self._oldscale[1]:
        for interval in reversed(self.losses):
            self._update_interpolated_loss_in_interval(*interval)

        self._oldscale = deepcopy(self._scale)

tell_pending

tell_pending(x: float) -> None
Source code in adaptive/learner/learner1D.py
def tell_pending(self, x: float) -> None:
    if x in self.data:
        # The point is already evaluated before
        return
    self.pending_points.add(x)
    self._update_neighbors(x, self.neighbors_combined)
    self._update_losses(x, real=False)

tell_many

tell_many(xs: Sequence[Float] | ndarray, ys: Sequence[Float] | Sequence[Sequence[Float]] | Sequence[ndarray] | ndarray, *, force: bool = False) -> None
Source code in adaptive/learner/learner1D.py
def tell_many(
    self,
    xs: Sequence[Float] | np.ndarray,
    ys: (
        Sequence[Float]
        | Sequence[Sequence[Float]]
        | Sequence[np.ndarray]
        | np.ndarray
    ),
    *,
    force: bool = False,
) -> None:
    if not force and not (len(xs) > 0.5 * len(self.data) and len(xs) > 2):
        # Only run this more efficient method if there are
        # at least 2 points and the amount of points added are
        # at least half of the number of points already in 'data'.
        # These "magic numbers" are somewhat arbitrary.
        super().tell_many(xs, ys)
        return

    # Add data points
    self.data.update(zip(xs, ys))
    self.pending_points.difference_update(xs)

    # Get all data as numpy arrays
    points = np.array(list(self.data.keys()))
    values = np.array(list(self.data.values()))
    points_pending = np.array(list(self.pending_points))
    points_combined = np.hstack([points_pending, points])

    # Generate neighbors
    self.neighbors = _get_neighbors_from_array(points)
    self.neighbors_combined = _get_neighbors_from_array(points_combined)

    # Update scale
    self._bbox[0] = [points_combined.min(), points_combined.max()]
    self._bbox[1] = [values.min(axis=0), values.max(axis=0)]
    self._scale[0] = self._bbox[0][1] - self._bbox[0][0]
    self._scale[1] = np.max(self._bbox[1][1] - self._bbox[1][0])
    self._oldscale = deepcopy(self._scale)

    # Find the intervals for which the losses should be calculated.
    intervals, intervals_combined = (
        [(x_m, x_r) for x_m, (x_l, x_r) in neighbors.items()][:-1]
        for neighbors in (self.neighbors, self.neighbors_combined)
    )

    # The the losses for the "real" intervals.
    self.losses = loss_manager(self._scale[0])
    for ival in intervals:
        self.losses[ival] = self._get_loss_in_interval(*ival)

    # List with "real" intervals that have interpolated intervals inside
    to_interpolate: list[tuple[Real, Real]] = []

    self.losses_combined = loss_manager(self._scale[0])
    for ival in intervals_combined:
        # If this interval exists in 'losses' then copy it otherwise
        # calculate it.
        if ival in reversed(self.losses):
            self.losses_combined[ival] = self.losses[ival]
        else:
            # Set all losses to inf now, later they might be udpdated if the
            # interval appears to be inside a real interval.
            self.losses_combined[ival] = np.inf
            x_left, x_right = ival
            a, b = to_interpolate[-1] if to_interpolate else (None, None)
            if b == x_left and (a, b) not in self.losses:
                # join (a, b) and (x_left, x_right) → (a, x_right)
                to_interpolate[-1] = (a, x_right)
            else:
                to_interpolate.append((x_left, x_right))

    for ival in to_interpolate:
        if ival in reversed(self.losses):
            # If this interval does not exist it should already
            # have an inf loss.
            self._update_interpolated_loss_in_interval(*ival)

ask

ask(n: int, tell_pending: bool = True) -> tuple[list[float], list[float]]

Return 'n' points that are expected to maximally reduce the loss.

Source code in adaptive/learner/learner1D.py
def ask(self, n: int, tell_pending: bool = True) -> tuple[list[float], list[float]]:
    """Return 'n' points that are expected to maximally reduce the loss."""
    points, loss_improvements = self._ask_points_without_adding(n)

    if tell_pending:
        for p in points:
            self.tell_pending(p)

    return points, loss_improvements

plot

plot(*, scatter_or_line: str = 'scatter')

Returns a plot of the evaluated data.

Parameters:

Name Type Description Default
scatter_or_line str

Plot as a scatter plot ("scatter") or a line plot ("line").

"scatter"

Returns:

Name Type Description
plot Overlay

Plot of the evaluated data.

Source code in adaptive/learner/learner1D.py
def plot(self, *, scatter_or_line: str = "scatter"):
    """Returns a plot of the evaluated data.

    Parameters
    ----------
    scatter_or_line : str, default: "scatter"
        Plot as a scatter plot ("scatter") or a line plot ("line").

    Returns
    -------
    plot : `holoviews.Overlay`
        Plot of the evaluated data.
    """
    if scatter_or_line not in ("scatter", "line"):
        raise ValueError("scatter_or_line must be 'scatter' or 'line'")
    hv = ensure_holoviews()

    xs, ys = zip(*sorted(self.data.items())) if self.data else ([], [])
    if scatter_or_line == "scatter":
        if self.vdim == 1:
            plots = [hv.Scatter((xs, ys))]
        else:
            plots = [hv.Scatter((xs, _ys)) for _ys in np.transpose(ys)]
    else:
        plots = [hv.Path((xs, ys))]

    # Put all plots in an Overlay because a DynamicMap can't handle changing
    # datatypes, e.g. when `vdim` isn't yet known and the live_plot is running.
    p = hv.Overlay(plots)
    # Plot with 5% empty margins such that the boundary points are visible
    margin = 0.05 * (self.bounds[1] - self.bounds[0])
    plot_bounds = (self.bounds[0] - margin, self.bounds[1] + margin)

    return p.redim(x={"range": plot_bounds})

remove_unfinished

remove_unfinished() -> None
Source code in adaptive/learner/learner1D.py
def remove_unfinished(self) -> None:
    self.pending_points = set()
    self.losses_combined = deepcopy(self.losses)
    self.neighbors_combined = deepcopy(self.neighbors)

Custom loss functions

default_loss

default_loss(xs: XsType0, ys: YsType0) -> Float

Calculate loss on a single interval.

Currently returns the rescaled length of the interval. If one of the y-values is missing, returns 0 (so the intervals with missing data are never touched. This behavior should be improved later.

Source code in adaptive/learner/learner1D.py
@uses_nth_neighbors(0)
def default_loss(xs: XsType0, ys: YsType0) -> Float:
    """Calculate loss on a single interval.

    Currently returns the rescaled length of the interval. If one of the
    y-values is missing, returns 0 (so the intervals with missing data are
    never touched. This behavior should be improved later.
    """
    dx = xs[1] - xs[0]
    if isinstance(ys[0], collections.abc.Iterable):
        dy_vec = np.array([abs(a - b) for a, b in zip(*ys)])
        return np.hypot(dx, dy_vec).max()
    else:
        dy = ys[1] - ys[0]
        return np.hypot(dx, dy)

uniform_loss

uniform_loss(xs: XsType0, ys: YsType0) -> Float

Loss function that samples the domain uniformly.

Works with Learner1D only.

Examples:

>>> def f(x):
...     return x**2
>>>
>>> learner = adaptive.Learner1D(f,
...                              bounds=(-1, 1),
...                              loss_per_interval=uniform_sampling_1d)
>>>
Source code in adaptive/learner/learner1D.py
@uses_nth_neighbors(0)
def uniform_loss(xs: XsType0, ys: YsType0) -> Float:
    """Loss function that samples the domain uniformly.

    Works with `~adaptive.Learner1D` only.

    Examples
    --------
    >>> def f(x):
    ...     return x**2
    >>>
    >>> learner = adaptive.Learner1D(f,
    ...                              bounds=(-1, 1),
    ...                              loss_per_interval=uniform_sampling_1d)
    >>>
    """
    dx = xs[1] - xs[0]
    return dx

uses_nth_neighbors

uses_nth_neighbors(n: int)

Decorator to specify how many neighboring intervals the loss function uses.

Wraps loss functions to indicate that they expect intervals together with n nearest neighbors

The loss function will then receive the data of the N nearest neighbors (nth_neighbors) along with the data of the interval itself in a dict. The Learner1D will also make sure that the loss is updated whenever one of the nth_neighbors changes.

Examples:

The next function is a part of the curvature_loss_function function.

>>> @uses_nth_neighbors(1)
... def triangle_loss(xs, ys):
...    xs = [x for x in xs if x is not None]
...    ys = [y for y in ys if y is not None]
...
...    if len(xs) == 2: # we do not have enough points for a triangle
...        return xs[1] - xs[0]
...
...    N = len(xs) - 2 # number of constructed triangles
...    if isinstance(ys[0], Iterable):
...        pts = [(x, *y) for x, y in zip(xs, ys)]
...        vol = simplex_volume_in_embedding
...    else:
...        pts = [(x, y) for x, y in zip(xs, ys)]
...        vol = volume
...    return sum(vol(pts[i:i+3]) for i in range(N)) / N

Or you may define a loss that favours the (local) minima of a function, assuming that you know your function will have a single float as output.

>>> @uses_nth_neighbors(1)
... def local_minima_resolving_loss(xs, ys):
...     dx = xs[2] - xs[1] # the width of the interval of interest
...
...     if not ((ys[0] is not None and ys[0] > ys[1])
...         or (ys[3] is not None and ys[3] > ys[2])):
...         return loss * 100
...
...     return loss
Source code in adaptive/learner/base_learner.py
def uses_nth_neighbors(n: int):
    """Decorator to specify how many neighboring intervals the loss function uses.

    Wraps loss functions to indicate that they expect intervals together
    with ``n`` nearest neighbors

    The loss function will then receive the data of the N nearest neighbors
    (``nth_neighbors``) along with the data of the interval itself in a dict.
    The `~adaptive.Learner1D` will also make sure that the loss is updated
    whenever one of the ``nth_neighbors`` changes.

    Examples
    --------

    The next function is a part of the `curvature_loss_function` function.

    >>> @uses_nth_neighbors(1)
    ... def triangle_loss(xs, ys):
    ...    xs = [x for x in xs if x is not None]
    ...    ys = [y for y in ys if y is not None]
    ...
    ...    if len(xs) == 2: # we do not have enough points for a triangle
    ...        return xs[1] - xs[0]
    ...
    ...    N = len(xs) - 2 # number of constructed triangles
    ...    if isinstance(ys[0], Iterable):
    ...        pts = [(x, *y) for x, y in zip(xs, ys)]
    ...        vol = simplex_volume_in_embedding
    ...    else:
    ...        pts = [(x, y) for x, y in zip(xs, ys)]
    ...        vol = volume
    ...    return sum(vol(pts[i:i+3]) for i in range(N)) / N

    Or you may define a loss that favours the (local) minima of a function,
    assuming that you know your function will have a single float as output.

    >>> @uses_nth_neighbors(1)
    ... def local_minima_resolving_loss(xs, ys):
    ...     dx = xs[2] - xs[1] # the width of the interval of interest
    ...
    ...     if not ((ys[0] is not None and ys[0] > ys[1])
    ...         or (ys[3] is not None and ys[3] > ys[2])):
    ...         return loss * 100
    ...
    ...     return loss
    """

    def _wrapped(loss_per_interval):
        loss_per_interval.nth_neighbors = n
        return loss_per_interval

    return _wrapped

triangle_loss

triangle_loss(xs: XsType1, ys: YsType1) -> Float
Source code in adaptive/learner/learner1D.py
@uses_nth_neighbors(1)
def triangle_loss(xs: XsType1, ys: YsType1) -> Float:
    assert len(xs) == 4
    x = [x for x in xs if x is not None]
    y = [y for y in ys if y is not None]

    if len(x) == 2:  # we do not have enough points for a triangle
        return x[1] - x[0]  # type: ignore[operator]

    N = len(x) - 2  # number of constructed triangles
    if isinstance(y[0], collections.abc.Iterable):
        pts = [(x, *y) for x, y in zip(x, y)]  # type: ignore[misc]
        vol = simplex_volume_in_embedding
    else:
        pts = list(zip(x, y))
        vol = volume
    return sum(vol(pts[i : i + 3]) for i in range(N)) / N

curvature_loss_function

curvature_loss_function(area_factor: Real = 1, euclid_factor: Real = 0.02, horizontal_factor: Real = 0.02) -> Callable[[XsType1, YsType1], Float]
Source code in adaptive/learner/learner1D.py
def curvature_loss_function(
    area_factor: Real = 1, euclid_factor: Real = 0.02, horizontal_factor: Real = 0.02
) -> Callable[[XsType1, YsType1], Float]:
    # XXX: add a doc-string
    @uses_nth_neighbors(1)
    def curvature_loss(xs: XsType1, ys: YsType1) -> Float:
        xs_middle = xs[1:3]
        ys_middle = ys[1:3]

        triangle_loss_ = triangle_loss(xs, ys)
        default_loss_ = default_loss(xs_middle, ys_middle)
        dx = xs_middle[1] - xs_middle[0]  # type: ignore[operator]
        return (
            area_factor * (triangle_loss_**0.5)
            + euclid_factor * default_loss_
            + horizontal_factor * dx
        )

    return curvature_loss

abs_min_log_loss

abs_min_log_loss(xs: XsType0, ys: YsType0) -> Float

Calculate loss of a single interval that prioritizes the absolute minimum.

Source code in adaptive/learner/learner1D.py
@uses_nth_neighbors(0)
def abs_min_log_loss(xs: XsType0, ys: YsType0) -> Float:
    """Calculate loss of a single interval that prioritizes the absolute minimum."""
    ys_log: YsType0 = tuple(np.log(np.abs(y).min()) for y in ys)  # type: ignore[assignment]
    return default_loss(xs, ys_log)

resolution_loss_function

resolution_loss_function(min_length: Real = 0, max_length: Real = 1) -> Callable[[XsType0, YsType0], Float]

Loss function that is similar to the default_loss function, but you can set the maximum and minimum size of an interval.

Works with Learner1D only.

The arguments min_length and max_length should be in between 0 and 1 because the total size is normalized to 1.

Returns:

Name Type Description
loss_function callable

Examples:

>>> def f(x):
...     return x**2
>>>
>>> loss = resolution_loss_function(min_length=0.01, max_length=1)
>>> learner = adaptive.Learner1D(f, bounds=(-1, -1), loss_per_interval=loss)
Source code in adaptive/learner/learner1D.py
def resolution_loss_function(
    min_length: Real = 0, max_length: Real = 1
) -> Callable[[XsType0, YsType0], Float]:
    """Loss function that is similar to the `default_loss` function, but you
    can set the maximum and minimum size of an interval.

    Works with `~adaptive.Learner1D` only.

    The arguments `min_length` and `max_length` should be in between 0 and 1
    because the total size is normalized to 1.

    Returns
    -------
    loss_function : callable

    Examples
    --------
    >>> def f(x):
    ...     return x**2
    >>>
    >>> loss = resolution_loss_function(min_length=0.01, max_length=1)
    >>> learner = adaptive.Learner1D(f, bounds=(-1, -1), loss_per_interval=loss)
    """

    @uses_nth_neighbors(0)
    def resolution_loss(xs: XsType0, ys: YsType0) -> Float:
        loss = uniform_loss(xs, ys)
        if loss < min_length:
            # Return zero such that this interval won't be chosen again
            return 0
        if loss > max_length:
            # Return infinite such that this interval will be picked
            return np.inf
        loss = default_loss(xs, ys)
        return loss

    return resolution_loss