Skip to content

Runner extras

Stopping Criteria

Runners allow you to specify the stopping criterion by providing a goal as a function that takes the learner and returns a boolean: False for "continue running" and True for "stop". This gives you a lot of flexibility for defining your own stopping conditions, however we also provide some common stopping conditions as a convenience. For example, to continue until the loss is below a threshold x, you may specify loss_goal=x. Similarly, to continue until n points have been sampled, you may specify npoints_goal=n. See the Runner docstring for details.

auto_goal

auto_goal(*, loss: float | None = None, npoints: int | None = None, end_time: datetime | None = None, duration: timedelta | int | float | None = None, learner: LearnerType | None = None, allow_running_forever: bool = True) -> Callable[[LearnerType], bool]

Extract a goal from the learners.

Parameters:

Name Type Description Default
loss float

Stop when the loss is smaller than this value.

None
npoints int

Stop when the number of points is larger or equal than this value.

None
end_time datetime

Stop when the current time is larger or equal than this value.

None
duration timedelta or number

Stop when the current time is larger or equal than start_time + duration. duration can be a number indicating the number of seconds.

None
learner LearnerType | None

Learner for which to determine the goal. Only used if the learner type is BalancingLearner, DataSaver, SequenceLearner, or IntegratorLearner.

None
allow_running_forever bool

If True, and the goal is None and the learner is not a SequenceLearner, then a goal that never stops is returned, otherwise an exception is raised.

True

Returns:

Type Description
Callable[[BaseLearner], bool]
Source code in adaptive/runner.py
def auto_goal(
    *,
    loss: float | None = None,
    npoints: int | None = None,
    end_time: datetime | None = None,
    duration: timedelta | int | float | None = None,
    learner: LearnerType | None = None,
    allow_running_forever: bool = True,
) -> Callable[[LearnerType], bool]:
    """Extract a goal from the learners.

    Parameters
    ----------
    loss : float, optional
        Stop when the loss is smaller than this value.
    npoints : int, optional
        Stop when the number of points is larger or equal than this value.
    end_time : datetime, optional
        Stop when the current time is larger or equal than this value.
    duration : timedelta or number, optional
        Stop when the current time is larger or equal than
        ``start_time + duration``. ``duration`` can be a number
        indicating the number of seconds.
    learner
        Learner for which to determine the goal. Only used if the learner type
        is `BalancingLearner`, `DataSaver`, `SequenceLearner`, or `IntegratorLearner`.
    allow_running_forever
        If True, and the goal is None and the learner is not a SequenceLearner,
        then a goal that never stops is returned, otherwise an exception is raised.

    Returns
    -------
    Callable[[adaptive.BaseLearner], bool]
    """
    opts = (loss, npoints, end_time, duration)  # all are mutually exclusive
    if sum(v is not None for v in opts) > 1:
        raise ValueError(
            "Only one of loss, npoints, end_time, duration can be specified."
        )

    if loss is not None:
        return lambda learner: learner.loss() <= loss
    if isinstance(learner, BalancingLearner):
        # Note that the float loss goal is more efficiently implemented in the
        # BalancingLearner itself. That is why the previous if statement is
        # above this one.
        goals = [
            auto_goal(
                learner=lrn,
                loss=loss,
                npoints=npoints,
                end_time=end_time,
                duration=duration,
                allow_running_forever=allow_running_forever,
            )
            for lrn in learner.learners
        ]
        return lambda learner: all(
            goal(lrn)
            for lrn, goal in zip(learner.learners, goals)  # type: ignore[attr-defined]
        )
    if npoints is not None:
        return lambda learner: learner.npoints >= npoints  # type: ignore[operator]
    if end_time is not None:
        return _TimeGoal(end_time)
    if duration is not None:
        return _TimeGoal(duration)
    if isinstance(learner, DataSaver):
        assert learner is not None
        return auto_goal(
            learner=learner.learner,  # type: ignore[arg-type]
            loss=loss,
            npoints=npoints,
            end_time=end_time,
            duration=duration,
            allow_running_forever=allow_running_forever,
        )
    if all(v is None for v in opts):
        if isinstance(learner, SequenceLearner):
            return SequenceLearner.done  # type: ignore[return-value]
        if isinstance(learner, IntegratorLearner):
            return IntegratorLearner.done  # type: ignore[return-value]
        if not allow_running_forever:
            raise ValueError(
                "Goal is None which means the learners"
                " continue forever and this is not allowed."
            )
        warnings.warn(
            "Goal is None which means the learners continue forever!", stacklevel=2
        )
        return lambda _: False
    raise ValueError("Cannot determine goal from {goal}.")

stop_after

stop_after(*, seconds=0, minutes=0, hours=0) -> Callable[[LearnerType], bool]

Stop a runner after a specified time.

For example, to specify a runner that should stop after 5 minutes, one could do the following:

runner = Runner(learner, goal=stop_after(minutes=5))

To stop a runner after 2 hours, 10 minutes and 3 seconds, one could do the following:

runner = Runner(learner, goal=stop_after(hours=2, minutes=10, seconds=3))

Parameters:

Name Type Description Default
seconds float

If more than one is specified, then they are added together

0
minutes float

If more than one is specified, then they are added together

0
hours float

If more than one is specified, then they are added together

0

Returns:

Name Type Description
goal callable

Can be used as the goal parameter when constructing a Runner.

Notes

The duration specified is only a lower bound on the time that the runner will run for, because the runner only checks its goal when it adds points to its learner

Source code in adaptive/runner.py
def stop_after(*, seconds=0, minutes=0, hours=0) -> Callable[[LearnerType], bool]:
    """Stop a runner after a specified time.

    For example, to specify a runner that should stop after
    5 minutes, one could do the following:

    >>> runner = Runner(learner, goal=stop_after(minutes=5))

    To stop a runner after 2 hours, 10 minutes and 3 seconds,
    one could do the following:

    >>> runner = Runner(learner, goal=stop_after(hours=2, minutes=10, seconds=3))

    Parameters
    ----------
    seconds, minutes, hours : float, default: 0
        If more than one is specified, then they are added together

    Returns
    -------
    goal : callable
        Can be used as the ``goal`` parameter when constructing
        a `Runner`.

    Notes
    -----
    The duration specified is only a *lower bound* on the time that the
    runner will run for, because the runner only checks its goal when
    it adds points to its learner
    """
    stop_time = time.time() + seconds + 60 * minutes + 3600 * hours
    return lambda _: time.time() > stop_time

Simple executor

simple

simple(learner: LearnerType, goal: Callable[[LearnerType], bool] | None = None, *, loss_goal: float | None = None, npoints_goal: int | None = None, end_time_goal: datetime | None = None, duration_goal: timedelta | int | float | None = None, points_per_ask: int = 1)

Run the learner until the goal is reached.

Requests points from the learner, evaluates the function to be learned, and adds the points to the learner, until the goal is reached, blocking the current thread.

This function is useful for extracting error messages, as the learner's function is evaluated in the same thread, meaning that exceptions can simple be caught an inspected.

Parameters:

Name Type Description Default
learner adaptive.BaseLearner instance
required
goal callable

The end condition for the calculation. This function must take the learner as its sole argument, and return True when we should stop requesting more points.

None
loss_goal float

Convenience argument, use instead of goal. The end condition for the calculation. Stop when the loss is smaller than this value.

None
npoints_goal int

Convenience argument, use instead of goal. The end condition for the calculation. Stop when the number of points is larger or equal than this value.

None
end_time_goal datetime

Convenience argument, use instead of goal. The end condition for the calculation. Stop when the current time is larger or equal than this value.

None
duration_goal timedelta or number

Convenience argument, use instead of goal. The end condition for the calculation. Stop when the current time is larger or equal than start_time + duration_goal. duration_goal can be a number indicating the number of seconds.

None
points_per_ask int

The number of points to ask for between every interpolation rerun. Defaults to 1, which can introduce significant overhead on long runs.

1
Source code in adaptive/runner.py
def simple(
    learner: LearnerType,
    goal: Callable[[LearnerType], bool] | None = None,
    *,
    loss_goal: float | None = None,
    npoints_goal: int | None = None,
    end_time_goal: datetime | None = None,
    duration_goal: timedelta | int | float | None = None,
    points_per_ask: int = 1,
):
    """Run the learner until the goal is reached.

    Requests points from the learner, evaluates
    the function to be learned, and adds the points to the
    learner, until the goal is reached, blocking the current
    thread.

    This function is useful for extracting error messages,
    as the learner's function is evaluated in the same thread,
    meaning that exceptions can simple be caught an inspected.

    Parameters
    ----------
    learner : ~`adaptive.BaseLearner` instance
    goal : callable, optional
        The end condition for the calculation. This function must take
        the learner as its sole argument, and return True when we should
        stop requesting more points.
    loss_goal : float, optional
        Convenience argument, use instead of ``goal``. The end condition for the
        calculation. Stop when the loss is smaller than this value.
    npoints_goal : int, optional
        Convenience argument, use instead of ``goal``. The end condition for the
        calculation. Stop when the number of points is larger or
        equal than this value.
    end_time_goal : datetime, optional
        Convenience argument, use instead of ``goal``. The end condition for the
        calculation. Stop when the current time is larger or equal than this
        value.
    duration_goal : timedelta or number, optional
        Convenience argument, use instead of ``goal``. The end condition for the
        calculation. Stop when the current time is larger or equal than
        ``start_time + duration_goal``. ``duration_goal`` can be a number
        indicating the number of seconds.
    points_per_ask : int, optional
        The number of points to ask for between every interpolation rerun. Defaults
        to 1, which can introduce significant overhead on long runs.
    """
    goal = _goal(
        learner,
        goal,
        loss_goal,
        npoints_goal,
        end_time_goal,
        duration_goal,
        allow_running_forever=False,
    )
    assert goal is not None
    while not goal(learner):
        xs, _ = learner.ask(points_per_ask)
        for x in xs:
            y = learner.function(x)
            learner.tell(x, y)

Sequential executor

SequentialExecutor

Bases: Executor

A trivial executor that runs functions synchronously.

This executor is mainly for testing.

submit

submit(fn: Callable, *args, **kwargs) -> Future
Source code in adaptive/utils.py
def submit(self, fn: Callable, *args, **kwargs) -> concurrent.Future:  # type: ignore[override]
    fut: concurrent.Future = concurrent.Future()
    try:
        fut.set_result(fn(*args, **kwargs))
    except Exception as e:
        fut.set_exception(e)
    return fut

map

map(fn, *iterable, timeout=None, chunksize=1)
Source code in adaptive/utils.py
def map(self, fn, *iterable, timeout=None, chunksize=1):
    return map(fn, iterable)

shutdown

shutdown(wait=True)
Source code in adaptive/utils.py
def shutdown(self, wait=True):
    pass

Replay log

replay_log

replay_log(learner: LearnerType, log: list[tuple[Literal['tell'], Any, Any] | tuple[Literal['ask'], int]]) -> None

Apply a sequence of method calls to a learner.

This is useful for debugging runners.

Parameters:

Name Type Description Default
learner adaptive.BaseLearner instance

New learner where the log will be applied.

required
log list

contains tuples: (method_name, *args).

required
Source code in adaptive/runner.py
def replay_log(
    learner: LearnerType,
    log: list[tuple[Literal["tell"], Any, Any] | tuple[Literal["ask"], int]],
) -> None:
    """Apply a sequence of method calls to a learner.

    This is useful for debugging runners.

    Parameters
    ----------
    learner : `~adaptive.BaseLearner` instance
        New learner where the log will be applied.
    log : list
        contains tuples: ``(method_name, *args)``.
    """
    for method, *args in log:
        getattr(learner, method)(*args)