Skip to content

adaptive.AsyncRunner

AsyncRunner

AsyncRunner(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, executor: ExecutorTypes | None = None, ntasks: int | None = None, log: bool = False, shutdown_executor: bool = False, ioloop=None, retries: int = 0, raise_if_retries_exceeded: bool = True)

Bases: BaseRunner

Run a learner asynchronously in an executor using asyncio.

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. If not provided, the runner will run forever (or stop when no more points can be added), or until runner.task.cancel() is called.

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
executor (Executor, Client, MPIPoolExecutor, Client or get_reusable_executor)

The executor in which to evaluate the function to be learned. If not provided, a new loky.get_reusable_executor is used.

None
ntasks int

The number of concurrent function evaluations. Defaults to the number of cores available in executor.

None
log bool

If True, record the method calls made to the learner by this runner.

False
shutdown_executor bool

If True, shutdown the executor when the runner has completed. If executor is not provided then the runner uses loky's reusable executor, which is shared between runners and is therefore not shut down unless this parameter is True.

False
ioloop AbstractEventLoop

The ioloop in which to run the learning algorithm. If not provided, the default event loop is used.

None
retries int

Maximum amount of retries of a certain point x in learner.function(x). After retries is reached for x the point is present in runner.failed.

0
raise_if_retries_exceeded bool

Raise the error after a point x failed retries.

True
allow_running_forever bool

If True, the runner will run forever if the goal is not provided.

True

Attributes:

Name Type Description
task Task

The underlying task. May be cancelled in order to stop the runner.

learner adaptive.BaseLearner instance

The underlying learner. May be queried for its state.

log list or None

Record of the method calls made to the learner, in the format (method_name, *args).

to_retry list of tuples

List of (point, n_fails). When a point has failed runner.retries times it is removed but will be present in runner.tracebacks.

tracebacks list of tuples

List of of (point, tb) for points that failed.

pending_points list of tuples

A list of tuples with (concurrent.futures.Future, point).

Methods:

Name Description
elapsed_time : callable

A method that returns the time elapsed since the runner was started.

overhead : callable

The overhead in percent of using Adaptive. This includes the overhead of the executor. Essentially, this is 100 * (1 - total_elapsed_function_time / self.elapsed_time()).

Notes

This runner can be used when an async function (defined with async def) has to be learned. In this case the function will be run directly on the event loop (and not in the executor).

Source code in adaptive/runner.py
def __init__(
    self,
    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,
    executor: ExecutorTypes | None = None,
    ntasks: int | None = None,
    log: bool = False,
    shutdown_executor: bool = False,
    ioloop=None,
    retries: int = 0,
    raise_if_retries_exceeded: bool = True,
) -> None:
    super().__init__(
        learner,
        goal=goal,
        loss_goal=loss_goal,
        npoints_goal=npoints_goal,
        end_time_goal=end_time_goal,
        duration_goal=duration_goal,
        executor=executor,
        ntasks=ntasks,
        log=log,
        shutdown_executor=shutdown_executor,
        retries=retries,
        raise_if_retries_exceeded=raise_if_retries_exceeded,
        allow_running_forever=True,
    )
    self.ioloop = ioloop if ioloop is not None else _get_or_create_event_loop()

    # When the learned function is 'async def', we run it
    # directly on the event loop, and not in the executor.
    # The *whole point* of allowing learning of async functions is so that
    # the user can have more fine-grained control over the parallelism.
    if inspect.iscoroutinefunction(learner.function):
        if executor:  # user-provided argument
            raise RuntimeError(
                "Cannot use an executor when learning an async function."
            )
        self.executor.shutdown()  # Make sure we don't shoot ourselves later

    self.task = self.ioloop.create_task(self._run())
    self.saving_task: asyncio.Task | None = None
    if in_ipynb() and not self.ioloop.is_running():
        warnings.warn(
            "The runner has been scheduled, but the asyncio "
            "event loop is not running! If you are "
            "in a Jupyter notebook, remember to run "
            "'adaptive.notebook_extension()'",
            stacklevel=2,
        )

ioloop instance-attribute

ioloop = ioloop if ioloop is not None else _get_or_create_event_loop()

task instance-attribute

task = self.ioloop.create_task(self._run())

saving_task instance-attribute

saving_task: Task | None = None

status

status() -> str

Return the runner status as a string.

The possible statuses are: running, cancelled, failed, and finished.

Source code in adaptive/runner.py
def status(self) -> str:
    """Return the runner status as a string.

    The possible statuses are: running, cancelled, failed, and finished.
    """
    try:
        self.task.result()
    except asyncio.CancelledError:
        return "cancelled"
    except asyncio.InvalidStateError:
        return "running"
    except Exception:
        return "failed"
    else:
        return "finished"

cancel

cancel() -> None

Cancel the runner.

This is equivalent to calling runner.task.cancel().

Source code in adaptive/runner.py
def cancel(self) -> None:
    """Cancel the runner.

    This is equivalent to calling ``runner.task.cancel()``.
    """
    self.task.cancel()

block_until_done

block_until_done() -> None
Source code in adaptive/runner.py
def block_until_done(self) -> None:
    if in_ipynb():
        raise RuntimeError(
            "Cannot block the event loop when running in a Jupyter notebook."
            " Use `await runner.task` instead."
        )
    self.ioloop.run_until_complete(self.task)

live_plot

live_plot(*, plotter: Callable[[LearnerType], Element] | None = None, update_interval: float = 2.0, name: str | None = None, normalize: bool = True) -> DynamicMap

Live plotting of the learner's data.

Parameters:

Name Type Description Default
runner Runner
required
plotter function

A function that takes the learner as a argument and returns a holoviews object. By default learner.plot() will be called.

None
update_interval int

Number of second between the updates of the plot.

2.0
name hasable

Name for the live_plot task in adaptive.active_plotting_tasks. By default the name is None and if another task with the same name already exists that other live_plot is canceled.

None
normalize bool

Normalize (scale to fit) the frame upon each update.

True

Returns:

Name Type Description
dm DynamicMap

The plot that automatically updates every update_interval.

Source code in adaptive/runner.py
def live_plot(
    self,
    *,
    plotter: Callable[[LearnerType], holoviews.Element] | None = None,
    update_interval: float = 2.0,
    name: str | None = None,
    normalize: bool = True,
) -> holoviews.DynamicMap:
    """Live plotting of the learner's data.

    Parameters
    ----------
    runner : `~adaptive.Runner`
    plotter : function
        A function that takes the learner as a argument and returns a
        holoviews object. By default ``learner.plot()`` will be called.
    update_interval : int
        Number of second between the updates of the plot.
    name : hasable
        Name for the `live_plot` task in `adaptive.active_plotting_tasks`.
        By default the name is None and if another task with the same name
        already exists that other `live_plot` is canceled.
    normalize : bool
        Normalize (scale to fit) the frame upon each update.

    Returns
    -------
    dm : `holoviews.core.DynamicMap`
        The plot that automatically updates every `update_interval`.
    """
    return live_plot(
        self,
        plotter=plotter,
        update_interval=update_interval,
        name=name,
        normalize=normalize,
    )

live_info

live_info(*, update_interval: float = 0.1) -> None

Display live information about the runner.

Returns an interactive ipywidget that can be visualized in a Jupyter notebook.

Source code in adaptive/runner.py
def live_info(self, *, update_interval: float = 0.1) -> None:
    """Display live information about the runner.

    Returns an interactive ipywidget that can be
    visualized in a Jupyter notebook.
    """
    return live_info(self, update_interval=update_interval)

live_info_terminal

live_info_terminal(*, update_interval: float = 0.5, overwrite_previous: bool = True) -> Task

Display live information about the runner in the terminal.

This function provides a live update of the runner's status in the terminal. The update can either overwrite the previous status or be printed on a new line.

Parameters:

Name Type Description Default
update_interval float

The time interval (in seconds) at which the runner's status is updated in the terminal. Default is 0.5 seconds.

0.5
overwrite_previous bool

If True, each update will overwrite the previous status in the terminal. If False, each update will be printed on a new line. Default is True.

True

Returns:

Type Description
Task

The asynchronous task responsible for updating the runner's status in the terminal.

Examples:

>>> runner = AsyncRunner(...)
>>> runner.live_info_terminal(update_interval=1.0, overwrite_previous=False)
Notes

This function uses ANSI escape sequences to control the terminal's cursor position. It might not work as expected on all terminal emulators.

Source code in adaptive/runner.py
def live_info_terminal(
    self, *, update_interval: float = 0.5, overwrite_previous: bool = True
) -> asyncio.Task:
    """
    Display live information about the runner in the terminal.

    This function provides a live update of the runner's status in the terminal.
    The update can either overwrite the previous status or be printed on a new line.

    Parameters
    ----------
    update_interval : float, optional
        The time interval (in seconds) at which the runner's status is updated
        in the terminal. Default is 0.5 seconds.
    overwrite_previous : bool, optional
        If True, each update will overwrite the previous status in the terminal.
        If False, each update will be printed on a new line.
        Default is True.

    Returns
    -------
    asyncio.Task
        The asynchronous task responsible for updating the runner's status in
        the terminal.

    Examples
    --------
    >>> runner = AsyncRunner(...)
    >>> runner.live_info_terminal(update_interval=1.0, overwrite_previous=False)

    Notes
    -----
    This function uses ANSI escape sequences to control the terminal's cursor
    position. It might not work as expected on all terminal emulators.
    """

    async def _update(runner: AsyncRunner) -> None:
        try:
            while not runner.task.done():
                if overwrite_previous:
                    # Clear the terminal
                    print("\033[H\033[J", end="")
                print(_info_text(runner, separator="\t"))
                await asyncio.sleep(update_interval)

        except asyncio.CancelledError:
            print("Live info display cancelled.")

    return self.ioloop.create_task(_update(self))

elapsed_time

elapsed_time() -> float

Return the total time elapsed since the runner was started.

Source code in adaptive/runner.py
def elapsed_time(self) -> float:
    """Return the total time elapsed since the runner
    was started."""
    if self.task.done():
        end_time = self.end_time
        if end_time is None:
            # task was cancelled before it began
            assert self.task.cancelled()
            return 0
    else:
        end_time = time.time()
    return end_time - self.start_time

start_periodic_saving

start_periodic_saving(save_kwargs: dict[str, Any] | None = None, interval: int = 30, method: Callable[[LearnerType], None] | None = None)

Periodically save the learner's data.

Parameters:

Name Type Description Default
save_kwargs dict

Key-word arguments for learner.save(**save_kwargs). Only used if method=None.

None
interval int

Number of seconds between saving the learner.

30
method callable

The method to use for saving the learner. If None, the default saves the learner using "pickle" which calls learner.save(**save_kwargs). Otherwise provide a callable that takes the learner and saves the learner.

None
Example

runner = Runner(learner) runner.start_periodic_saving( ... save_kwargs=dict(fname='data/test.pickle'), ... interval=600)

Source code in adaptive/runner.py
def start_periodic_saving(
    self,
    save_kwargs: dict[str, Any] | None = None,
    interval: int = 30,
    method: Callable[[LearnerType], None] | None = None,
):
    """Periodically save the learner's data.

    Parameters
    ----------
    save_kwargs : dict
        Key-word arguments for ``learner.save(**save_kwargs)``.
        Only used if ``method=None``.
    interval : int
        Number of seconds between saving the learner.
    method : callable
        The method to use for saving the learner. If None, the default
        saves the learner using "pickle" which calls
        ``learner.save(**save_kwargs)``. Otherwise provide a callable
        that takes the learner and saves the learner.

    Example
    -------
    >>> runner = Runner(learner)
    >>> runner.start_periodic_saving(
    ...     save_kwargs=dict(fname='data/test.pickle'),
    ...     interval=600)
    """

    def default_save(learner):
        learner.save(**save_kwargs)

    if method is None:
        method = default_save
        if save_kwargs is None:
            raise ValueError("Must provide `save_kwargs` if method=None.")

    async def _saver():
        while self.status() == "running":
            method(self.learner)
            # No asyncio.shield needed, as 'wait' does not cancel any tasks.
            await asyncio.wait([self.task], timeout=interval)
        method(self.learner)  # one last time

    self.saving_task = self.ioloop.create_task(_saver())
    return self.saving_task