Skip to content

adaptive.IntegratorLearner

IntegratorLearner

IntegratorLearner(function: Callable, bounds: tuple[int, int], tol: float)

Bases: BaseLearner

Parameters:

Name Type Description Default
function callable: X → Y

The function to learn.

required
bounds pair of reals

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

required
tol float

Relative tolerance of the error to the integral, this means that the learner is done when: tol > err / abs(igral).

required

Attributes:

Name Type Description
approximating_intervals set of intervals

The intervals that can be used in the determination of the integral.

n int

The total number of evaluated points.

igral float

The integral value in self.bounds.

err float

The absolute error associated with self.igral.

max_ivals int, default: 1000

Maximum number of intervals that can be present in the calculation of the integral. If this amount exceeds max_ivals, the interval with the smallest error will be discarded.

Functions:

Name Description
done : bool

Returns whether the tol has been reached.

plot : hv.Scatter

Plots all the points that are evaluated.

Source code in adaptive/learner/integrator_learner.py
def __init__(self, function: Callable, bounds: tuple[int, int], tol: float) -> None:
    """
    Parameters
    ----------
    function : callable: X → Y
        The function to learn.
    bounds : pair of reals
        The bounds of the interval on which to learn 'function'.
    tol : float
        Relative tolerance of the error to the integral, this means that
        the learner is done when: `tol > err / abs(igral)`.

    Attributes
    ----------
    approximating_intervals : set of intervals
        The intervals that can be used in the determination of the integral.
    n : int
        The total number of evaluated points.
    igral : float
        The integral value in `self.bounds`.
    err : float
        The absolute error associated with `self.igral`.
    max_ivals : int, default: 1000
        Maximum number of intervals that can be present in the calculation
        of the integral. If this amount exceeds max_ivals, the interval
        with the smallest error will be discarded.

    Methods
    -------
    done : bool
        Returns whether the `tol` has been reached.
    plot : hv.Scatter
        Plots all the points that are evaluated.
    """
    self.function = function  # type: ignore
    self.bounds = bounds
    self.tol = tol
    self.max_ivals = 1000
    self.priority_split: list[_Interval] = []
    self.data = {}
    self.pending_points = set()
    self._stack: list[float] = []
    self.x_mapping: dict[float, SortedSet] = defaultdict(
        lambda: SortedSet([], key=attrgetter("rdepth"))
    )
    self.ivals: set[_Interval] = set()
    ival = _Interval.make_first(*self.bounds)
    self.add_ival(ival)
    self.first_ival = ival

function instance-attribute

function = function

bounds instance-attribute

bounds = bounds

tol instance-attribute

tol = tol

max_ivals instance-attribute

max_ivals = 1000

priority_split instance-attribute

priority_split: list[_Interval] = []

data instance-attribute

data = {}

pending_points instance-attribute

pending_points = set()

x_mapping instance-attribute

x_mapping: dict[float, SortedSet] = defaultdict(lambda: SortedSet([], key=attrgetter('rdepth')))

ivals instance-attribute

ivals: set[_Interval] = set()

first_ival instance-attribute

first_ival = ival

approximating_intervals property

approximating_intervals: set[_Interval]

npoints property

npoints: int

Number of evaluated points.

igral property

igral: float

err property

err: float

new

Create a copy of Learner2D without the data.

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

tell

tell(point: float, value: float) -> None
Source code in adaptive/learner/integrator_learner.py
def tell(self, point: float, value: float) -> None:
    if point not in self.x_mapping:
        raise ValueError(f"Point {point} doesn't belong to any interval")
    self.data[point] = value
    self.pending_points.discard(point)

    # Select the intervals that have this point
    ivals = self.x_mapping[point]
    for ival in ivals:
        ival.data[point] = value

        if ival.depth_complete is None:
            from_depth = 0 if ival.parent is not None else 2
        else:
            from_depth = ival.depth_complete + 1

        for depth in range(from_depth, ival.depth + 1):
            if ival.refinement_complete(depth):
                force_split, remove = ival.complete_process(depth)

                if remove:
                    # Remove the interval (while remembering the excess
                    # integral and error), since it is either too narrow,
                    # or the estimated relative error is already at the
                    # limit of numerical accuracy and cannot be reduced
                    # further.
                    self.propagate_removed(ival)

                elif force_split and not ival.children:
                    # If it already has children it has already been split
                    assert ival in self.ivals
                    self.priority_split.append(ival)

tell_pending

tell_pending()
Source code in adaptive/learner/integrator_learner.py
def tell_pending(self):
    pass

propagate_removed

propagate_removed(ival: _Interval) -> None
Source code in adaptive/learner/integrator_learner.py
def propagate_removed(self, ival: _Interval) -> None:
    def _propagate_removed_down(ival):
        ival.removed = True
        self.ivals.discard(ival)

        for child in ival.children:
            _propagate_removed_down(child)

    _propagate_removed_down(ival)

add_ival

add_ival(ival: _Interval) -> None
Source code in adaptive/learner/integrator_learner.py
def add_ival(self, ival: _Interval) -> None:
    for x in ival.points():
        # Update the mappings
        self.x_mapping[x].add(ival)
        if x in self.data:
            self.tell(x, self.data[x])
        elif x not in self.pending_points:
            self.pending_points.add(x)
            self._stack.append(x)
    self.ivals.add(ival)

ask

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

Choose points for learners.

Source code in adaptive/learner/integrator_learner.py
def ask(self, n: int, tell_pending: bool = True) -> tuple[list[float], list[float]]:
    """Choose points for learners."""
    if not tell_pending:
        with restore(self):
            return self._ask_and_tell_pending(n)
    else:
        return self._ask_and_tell_pending(n)

pop_from_stack

pop_from_stack(n: int) -> tuple[list[float], list[float]]
Source code in adaptive/learner/integrator_learner.py
def pop_from_stack(self, n: int) -> tuple[list[float], list[float]]:
    points = self._stack[:n]
    self._stack = self._stack[n:]
    loss_improvements = [
        max(ival.err for ival in self.x_mapping[x]) for x in points
    ]
    return points, loss_improvements

remove_unfinished

remove_unfinished()
Source code in adaptive/learner/integrator_learner.py
def remove_unfinished(self):
    pass

done

done()
Source code in adaptive/learner/integrator_learner.py
def done(self):
    err = self.err
    igral = self.igral
    err_excess = sum(i.err for i in self.approximating_intervals if i.removed)
    return (
        err == 0
        or err < abs(igral) * self.tol
        or (err - err_excess < abs(igral) * self.tol < err_excess)
        or not self.ivals
    )

loss

loss(real=True)
Source code in adaptive/learner/integrator_learner.py
@cache_latest
def loss(self, real=True):
    return abs(abs(self.igral) * self.tol - self.err)

plot

plot()
Source code in adaptive/learner/integrator_learner.py
def plot(self):
    hv = ensure_holoviews()
    ivals = sorted(self.ivals, key=attrgetter("a"))
    if not self.data:
        return hv.Path([])
    xs, ys = zip(*[(x, y) for ival in ivals for x, y in sorted(ival.data.items())])
    return hv.Path((xs, ys))

to_numpy

to_numpy()

Data as NumPy array of size (npoints, 2).

Source code in adaptive/learner/integrator_learner.py
def to_numpy(self):
    """Data as NumPy array of size (npoints, 2)."""
    return np.array(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/integrator_learner.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.")
    df = pandas.DataFrame(sorted(self.data.items()), columns=[x_name, y_name])
    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
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'
Source code in adaptive/learner/integrator_learner.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
    ----------
    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"
    """
    raise NotImplementedError