Skip to content
Snippets Groups Projects

Cache loss and display it in the live_info widget

Merged Bas Nijholt requested to merge cache_loss into master
+ 1
4
%% Cell type:markdown id: tags:
# Adaptive
%% Cell type:markdown id: tags:
[`adaptive`](https://gitlab.kwant-project.org/qt/adaptive-evaluation) is a package for adaptively sampling functions with support for parallel evaluation.
This is an introductory notebook that shows some basic use cases.
`adaptive` needs at least Python 3.6, and the following packages:
+ `scipy`
+ `sortedcontainers`
Additionally `adaptive` has lots of extra functionality that makes it simple to use from Jupyter notebooks.
This extra functionality depends on the following packages
+ `ipykernel>=4.8.0`
+ `jupyter_client>=5.2.2`
+ `holoviews`
+ `bokeh`
+ `ipywidgets`
%% Cell type:code id: tags:
```
import adaptive
adaptive.notebook_extension()
# Import modules that are used in multiple cells
import holoviews as hv
import numpy as np
from functools import partial
import random
```
%% Cell type:markdown id: tags:
# 1D function learner
%% Cell type:markdown id: tags:
We start with the most common use-case: sampling a 1D function $\ f: ℝ → ℝ$.
We will use the following function, which is a smooth (linear) background with a sharp peak at a random location:
%% Cell type:code id: tags:
```
offset = random.uniform(-0.5, 0.5)
def f(x, offset=offset, wait=True):
from time import sleep
from random import random
a = 0.01
if wait:
sleep(random())
return x + a**2 / (a**2 + (x - offset)**2)
```
%% Cell type:markdown id: tags:
We start by initializing a 1D "learner", which will suggest points to evaluate, and adapt its suggestions as more and more points are evaluated.
%% Cell type:code id: tags:
```
learner = adaptive.Learner1D(f, bounds=(-1, 1))
```
%% Cell type:markdown id: tags:
Next we create a "runner" that will request points from the learner and evaluate 'f' on them.
By default on Unix-like systems the runner will evaluate the points in parallel using local processes ([`concurrent.futures.ProcessPoolExecutor`](https://docs.python.org/3/library/concurrent.futures.html#processpoolexecutor)).
On Windows systems the runner will try to use a [`distributed.Client`](https://distributed.readthedocs.io/en/latest/client.html) if [`distributed`](https://distributed.readthedocs.io/en/latest/index.html) is installed. A `ProcessPoolExecutor` cannot be used on Windows for reasons.
%% Cell type:code id: tags:
```
# The end condition is when the "loss" is less than 0.1. In the context of the
# 1D learner this means that we will resolve features in 'func' with width 0.1 or wider.
runner = adaptive.Runner(learner, goal=lambda l: l.loss() < 0.05)
runner.live_info()
```
%% Cell type:markdown id: tags:
When instantiated in a Jupyter notebook the runner does its job in the background and does not block the IPython kernel.
We can use this to create a plot that updates as new data arrives:
%% Cell type:code id: tags:
```
runner.live_plot(update_interval=0.1)
```
%% Cell type:markdown id: tags:
We can now compare the adaptive sampling to a homogeneous sampling with the same number of points:
%% Cell type:code id: tags:
```
if not runner.task.done():
raise RuntimeError('Wait for the runner to finish before executing the cells below!')
```
%% Cell type:code id: tags:
```
learner2 = adaptive.Learner1D(f, bounds=learner.bounds)
xs = np.linspace(*learner.bounds, len(learner.data))
learner2.tell_many(xs, map(partial(f, wait=False), xs))
learner.plot() + learner2.plot()
```
%% Cell type:markdown id: tags:
# 2D function learner
%% Cell type:markdown id: tags:
Besides 1D functions, we can also learn 2D functions: $\ f: ℝ^2 → ℝ$
%% Cell type:code id: tags:
```
def ring(xy, wait=True):
import numpy as np
from time import sleep
from random import random
if wait:
sleep(random()/10)
x, y = xy
a = 0.2
return x + np.exp(-(x**2 + y**2 - 0.75**2)**2/a**4)
learner = adaptive.Learner2D(ring, bounds=[(-1, 1), (-1, 1)])
```
%% Cell type:code id: tags:
```
runner = adaptive.Runner(learner, goal=lambda l: l.loss() < 0.01)
runner.live_info()
```
%% Cell type:code id: tags:
```
def plot(learner):
plot = learner.plot(tri_alpha=0.2)
title = f'loss={learner._loss:.3f}, n_points={learner.npoints}'
return (plot.Image
+ plot.EdgePaths.I.opts(plot=dict(title_format=title))
+ plot)
return plot.Image + plot.EdgePaths.I + plot
runner.live_plot(plotter=plot, update_interval=0.1)
```
%% Cell type:code id: tags:
```
%%opts EdgePaths (color='w')
import itertools
# Create a learner and add data on homogeneous grid, so that we can plot it
learner2 = adaptive.Learner2D(ring, bounds=learner.bounds)
n = int(learner.npoints**0.5)
xs, ys = [np.linspace(*bounds, n) for bounds in learner.bounds]
xys = list(itertools.product(xs, ys))
learner2.tell_many(xys, map(partial(ring, wait=False), xys))
(learner2.plot(n).relabel('Homogeneous grid') + learner.plot().relabel('With adaptive') +
learner2.plot(n, tri_alpha=0.4) + learner.plot(tri_alpha=0.4)).cols(2)
```
%% Cell type:markdown id: tags:
# Averaging learner
%% Cell type:markdown id: tags:
The next type of learner averages a function until the uncertainty in the average meets some condition.
This is useful for sampling a random variable. The function passed to the learner must formally take a single parameter,
which should be used like a "seed" for the (pseudo-) random variable (although in the current implementation the seed parameter can be ignored by the function).
%% Cell type:code id: tags:
```
def g(n):
import random
from time import sleep
sleep(random.random() / 1000)
# Properly save and restore the RNG state
state = random.getstate()
random.seed(n)
val = random.gauss(0.5, 1)
random.setstate(state)
return val
```
%% Cell type:code id: tags:
```
learner = adaptive.AverageLearner(g, atol=None, rtol=0.01)
runner = adaptive.Runner(learner, goal=lambda l: l.loss() < 2)
runner.live_info()
```
%% Cell type:code id: tags:
```
runner.live_plot(update_interval=0.1)
```
%% Cell type:markdown id: tags:
# 1D integration learner with `cquad`
%% Cell type:markdown id: tags:
This learner learns a 1D function and calculates the integral and error of the integral with it. It is based on Pedro Gonnet's [implementation](https://www.academia.edu/1976055/Adaptive_quadrature_re-revisited).
Let's try the following function with cusps (that is difficult to integrate):
%% Cell type:code id: tags:
```
def f24(x):
return np.floor(np.exp(x))
xs = np.linspace(0, 3, 200)
hv.Scatter((xs, [f24(x) for x in xs]))
```
%% Cell type:markdown id: tags:
Just to prove that this really is a difficult to integrate function, let's try a familiar function integrator `scipy.integrate.quad`, which will give us warnings that it encounters difficulties.
%% Cell type:code id: tags:
```
import scipy.integrate
scipy.integrate.quad(f24, 0, 3)
```
%% Cell type:markdown id: tags:
We initialize a learner again and pass the bounds and relative tolerance we want to reach. Then in the `Runner` we pass `goal=lambda l: l.done()` where `learner.done()` is `True` when the relative tolerance has been reached.
%% Cell type:code id: tags:
```
from adaptive.runner import SequentialExecutor
learner = adaptive.IntegratorLearner(f24, bounds=(0, 3), tol=1e-8)
# We use a SequentialExecutor, which runs the function to be learned in *this* process only. This means we don't pay
# the overhead of evaluating the function in another process.
runner = adaptive.Runner(learner, executor=SequentialExecutor(), goal=lambda l: l.done())
runner.live_info()
```
%% Cell type:markdown id: tags:
Now we could do the live plotting again, but lets just wait untill the runner is done.
%% Cell type:code id: tags:
```
if not runner.task.done():
raise RuntimeError('Wait for the runner to finish before executing the cells below!')
```
%% Cell type:code id: tags:
```
print('The integral value is {} with the corresponding error of {}'.format(learner.igral, learner.err))
learner.plot()
```
%% Cell type:markdown id: tags:
# 1D learner with vector output: `f:ℝ → ℝ^N`
%% Cell type:markdown id: tags:
Sometimes you may want to learn a function with vector output:
%% Cell type:code id: tags:
```
random.seed(0)
offsets = [random.uniform(-0.8, 0.8) for _ in range(3)]
# sharp peaks at random locations in the domain
def f_levels(x, offsets=offsets):
a = 0.01
return np.array([offset + x + a**2 / (a**2 + (x - offset)**2)
for offset in offsets])
```
%% Cell type:markdown id: tags:
`adaptive` has you covered! The `Learner1D` can be used for such functions:
%% Cell type:code id: tags:
```
learner = adaptive.Learner1D(f_levels, bounds=(-1, 1))
runner = adaptive.Runner(learner, goal=lambda l: l.loss() < 0.01)
runner.live_info()
```
%% Cell type:code id: tags:
```
runner.live_plot(update_interval=0.1)
```
%% Cell type:markdown id: tags:
# N-dimensional function learner (beta)
Besides 1 and 2 dimensional functions, we can also learn N-D functions: $\ f: ℝ^N → ℝ, N \ge 2$
Do keep in mind the speed and [effectiveness](https://en.wikipedia.org/wiki/Curse_of_dimensionality) of the learner drops quickly with increasing number of dimensions.
%% Cell type:code id: tags:
```
# this step takes a lot of time, it will finish at about 3300 points, which can take up to 6 minutes
def sphere(xyz):
x, y, z = xyz
a = 0.4
return x + z**2 + np.exp(-(x**2 + y**2 + z**2 - 0.75**2)**2/a**4)
learner = adaptive.LearnerND(sphere, bounds=[(-1, 1), (-1, 1), (-1, 1)])
runner = adaptive.Runner(learner, goal=lambda l: l.loss() < 0.01)
runner.live_info()
```
%% Cell type:markdown id: tags:
Let's plot 2D slices of the 3D function
%% Cell type:code id: tags:
```
def plot_cut(x, direction, learner=learner):
cut_mapping = {'xyz'.index(direction): x}
return learner.plot_slice(cut_mapping, n=100)
dm = hv.DynamicMap(plot_cut, kdims=['value', 'direction'])
dm.redim.values(value=np.linspace(-1, 1), direction=list('xyz'))
```
%% Cell type:markdown id: tags:
Or we can plot 1D slices
%% Cell type:code id: tags:
```
%%opts Path {+framewise}
def plot_cut(x1, x2, directions, learner=learner):
cut_mapping = {'xyz'.index(d): x for d, x in zip(directions, [x1, x2])}
return learner.plot_slice(cut_mapping)
dm = hv.DynamicMap(plot_cut, kdims=['v1', 'v2', 'directions'])
dm.redim.values(v1=np.linspace(-1, 1),
v2=np.linspace(-1, 1),
directions=['xy', 'xz', 'yz'])
```
%% Cell type:markdown id: tags:
The plots show some wobbles while the original function was smooth, this is a result of the fact that the learner chooses points in 3 dimensions and the simplices are not in the same face as we try to interpolate our lines. However, as always, when you sample more points the graph will become gradually smoother.
%% Cell type:markdown id: tags:
# Custom adaptive logic for 1D and 2D
%% Cell type:markdown id: tags:
`Learner1D` and `Learner2D` both work on the principle of subdividing their domain into subdomains, and assigning a property to each subdomain, which we call the *loss*. The algorithm for choosing the best place to evaluate our function is then simply *take the subdomain with the largest loss and add a point in the center, creating new subdomains around this point*.
The *loss function* that defines the loss per subdomain is the canonical place to define what regions of the domain are "interesting".
The default loss function for `Learner1D` and `Learner2D` is sufficient for a wide range of common cases, but it is by no means a panacea. For example, the default loss function will tend to get stuck on divergences.
Both the `Learner1D` and `Learner2D` allow you to specify a *custom loss function*. Below we illustrate how you would go about writing your own loss function. The documentation for `Learner1D` and `Learner2D` specifies the signature that your loss function needs to have in order for it to work with `adaptive`.
Say we want to properly sample a function that contains divergences. A simple (but naive) strategy is to *uniformly* sample the domain:
%% Cell type:code id: tags:
```
def uniform_sampling_1d(interval, scale, function_values):
# Note that we never use 'function_values'; the loss is just the size of the subdomain
x_left, x_right = interval
x_scale, _ = scale
dx = (x_right - x_left) / x_scale
return dx
def f_divergent_1d(x):
return 1 / x**2
learner = adaptive.Learner1D(f_divergent_1d, (-1, 1), loss_per_interval=uniform_sampling_1d)
runner = adaptive.BlockingRunner(learner, goal=lambda l: l.loss() < 0.01)
learner.plot().select(y=(0, 10000))
```
%% Cell type:code id: tags:
```
%%opts EdgePaths (color='w') Image [logz=True]
from adaptive.runner import SequentialExecutor
def uniform_sampling_2d(ip):
from adaptive.learner.learner2D import areas
A = areas(ip)
return np.sqrt(A)
def f_divergent_2d(xy):
x, y = xy
return 1 / (x**2 + y**2)
learner = adaptive.Learner2D(f_divergent_2d, [(-1, 1), (-1, 1)], loss_per_triangle=uniform_sampling_2d)
# this takes a while, so use the async Runner so we know *something* is happening
runner = adaptive.Runner(learner, goal=lambda l: l.loss() < 0.02)
runner.live_info()
runner.live_plot(update_interval=0.2,
plotter=lambda l: l.plot(tri_alpha=0.3).relabel('1 / (x^2 + y^2) in log scale'))
```
%% Cell type:markdown id: tags:
The uniform sampling strategy is a common case to benchmark against, so the 1D and 2D versions are included in `adaptive` as `adaptive.learner.learner1D.uniform_sampling` and `adaptive.learner.learner2D.uniform_sampling`.
%% Cell type:markdown id: tags:
### Doing better
Of course, using `adaptive` for uniform sampling is a bit of a waste!
Let's see if we can do a bit better. Below we define a loss per subdomain that scales with the degree of nonlinearity of the function (this is very similar to the default loss function for `Learner2D`), but which is 0 for subdomains smaller than a certain area, and infinite for subdomains larger than a certain area.
A loss defined in this way means that the adaptive algorithm will first prioritise subdomains that are too large (infinite loss). After all subdomains are appropriately small it will prioritise places where the function is very nonlinear, but will ignore subdomains that are too small (0 loss).
%% Cell type:code id: tags:
```
%%opts EdgePaths (color='w') Image [logz=True]
def resolution_loss(ip, min_distance=0, max_distance=1):
"""min_distance and max_distance should be in between 0 and 1
because the total area is normalized to 1."""
from adaptive.learner.learner2D import areas, deviations
A = areas(ip)
# 'deviations' returns an array of shape '(n, len(ip))', where
# 'n' is the is the dimension of the output of the learned function
# In this case we know that the learned function returns a scalar,
# so 'deviations' returns an array of shape '(1, len(ip))'.
# It represents the deviation of the function value from a linear estimate
# over each triangular subdomain.
dev = deviations(ip)[0]
# we add terms of the same dimension: dev == [distance], A == [distance**2]
loss = np.sqrt(A) * dev + A
# Setting areas with a small area to zero such that they won't be chosen again
loss[A < min_distance**2] = 0
# Setting triangles that have a size larger than max_distance to infinite loss
loss[A > max_distance**2] = np.inf
return loss
loss = partial(resolution_loss, min_distance=0.01)
learner = adaptive.Learner2D(f_divergent_2d, [(-1, 1), (-1, 1)], loss_per_triangle=loss)
runner = adaptive.BlockingRunner(learner, goal=lambda l: l.loss() < 0.02)
learner.plot(tri_alpha=0.3).relabel('1 / (x^2 + y^2) in log scale')
```
%% Cell type:markdown id: tags:
Awesome! We zoom in on the singularity, but not at the expense of sampling the rest of the domain a reasonable amount.
The above strategy is available as `adaptive.learner.learner2D.resolution_loss`.
%% Cell type:markdown id: tags:
# Balancing learner
%% Cell type:markdown id: tags:
The balancing learner is a "meta-learner" that takes a list of learners. When you request a point from the balancing learner, it will query all of its "children" to figure out which one will give the most improvement.
The balancing learner can for example be used to implement a poor-man's 2D learner by using the `Learner1D`.
%% Cell type:code id: tags:
```
def h(x, offset=0):
a = 0.01
return x + a**2 / (a**2 + (x - offset)**2)
learners = [adaptive.Learner1D(partial(h, offset=random.uniform(-1, 1)),
bounds=(-1, 1)) for i in range(10)]
bal_learner = adaptive.BalancingLearner(learners)
runner = adaptive.Runner(bal_learner, goal=lambda l: l.loss() < 0.01)
runner.live_info()
```
%% Cell type:code id: tags:
```
plotter = lambda learner: hv.Overlay([L.plot() for L in learner.learners])
runner.live_plot(plotter=plotter, update_interval=0.1)
```
%% Cell type:markdown id: tags:
Often one wants to create a set of `learner`s for a cartesian product of parameters. For that particular case we've added a `classmethod` called `from_product`. See how it works below
%% Cell type:code id: tags:
```
from scipy.special import eval_jacobi
def jacobi(x, n, alpha, beta): return eval_jacobi(n, alpha, beta, x)
combos = {
'n': [1, 2, 4, 8],
'alpha': np.linspace(0, 2, 3),
'beta': np.linspace(0, 1, 5),
}
learner = adaptive.BalancingLearner.from_product(
jacobi, adaptive.Learner1D, dict(bounds=(0, 1)), combos)
runner = adaptive.BlockingRunner(learner, goal=lambda l: l.loss() < 0.01)
# The `cdims` will automatically be set when using `from_product`, so
# `plot()` will return a HoloMap with correctly labeled sliders.
learner.plot().overlay('beta').grid()
```
%% Cell type:markdown id: tags:
# DataSaver
%% Cell type:markdown id: tags:
If the function that you want to learn returns a value along with some metadata, you can wrap your learner in an `adaptive.DataSaver`.
In the following example the function to be learned returns its result and the execution time in a dictionary:
%% Cell type:code id: tags:
```
from operator import itemgetter
def f_dict(x):
"""The function evaluation takes roughly the time we `sleep`."""
import random
from time import sleep
waiting_time = random.random()
sleep(waiting_time)
a = 0.01
y = x + a**2 / (a**2 + x**2)
return {'y': y, 'waiting_time': waiting_time}
# Create the learner with the function that returns a 'dict'
# This learner cannot be run directly, as Learner1D does not know what to do with the 'dict'
_learner = adaptive.Learner1D(f_dict, bounds=(-1, 1))
# Wrapping the learner with 'adaptive.DataSaver' and tell it which key it needs to learn
learner = adaptive.DataSaver(_learner, arg_picker=itemgetter('y'))
```
%% Cell type:markdown id: tags:
`learner.learner` is the original learner, so `learner.learner.loss()` will call the correct loss method.
%% Cell type:code id: tags:
```
runner = adaptive.Runner(learner, goal=lambda l: l.learner.loss() < 0.05)
runner.live_info()
```
%% Cell type:code id: tags:
```
runner.live_plot(plotter=lambda l: l.learner.plot(), update_interval=0.1)
```
%% Cell type:markdown id: tags:
Now the `DataSavingLearner` will have an dictionary attribute `extra_data` that has `x` as key and the data that was returned by `learner.function` as values.
%% Cell type:code id: tags:
```
learner.extra_data
```
%% Cell type:markdown id: tags:
# `Scikit-Optimize`
%% Cell type:markdown id: tags:
We have wrapped the `Optimizer` class from [`scikit-optimize`](https://github.com/scikit-optimize/scikit-optimize), to show how existing libraries can be integrated with `adaptive`.
The `SKOptLearner` attempts to "optimize" the given function `g` (i.e. find the global minimum of `g` in the window of interest).
Here we use the same example as in the `scikit-optimize` [tutorial](https://github.com/scikit-optimize/scikit-optimize/blob/master/examples/ask-and-tell.ipynb). Although `SKOptLearner` can optimize functions of arbitrary dimensionality, we can only plot the learner if a 1D function is being learned.
%% Cell type:code id: tags:
```
def g(x, noise_level=0.1):
return (np.sin(5 * x) * (1 - np.tanh(x ** 2))
+ np.random.randn() * noise_level)
```
%% Cell type:code id: tags:
```
learner = adaptive.SKOptLearner(g, dimensions=[(-2., 2.)],
base_estimator="GP",
acq_func="gp_hedge",
acq_optimizer="lbfgs",
)
runner = adaptive.Runner(learner, ntasks=1, goal=lambda l: l.npoints > 40)
runner.live_info()
```
%% Cell type:code id: tags:
```
%%opts Overlay [legend_position='top']
xs = np.linspace(*learner.space.bounds[0])
to_learn = hv.Curve((xs, [g(x, 0) for x in xs]), label='to learn')
runner.live_plot().relabel('prediction', depth=2) * to_learn
```
%% Cell type:markdown id: tags:
# Using multiple cores
%% Cell type:markdown id: tags:
Often you will want to evaluate the function on some remote computing resources. `adaptive` works out of the box with any framework that implements a [PEP 3148](https://www.python.org/dev/peps/pep-3148/) compliant executor that returns `concurrent.futures.Future` objects.
%% Cell type:markdown id: tags:
### [`concurrent.futures`](https://docs.python.org/3/library/concurrent.futures.html)
%% Cell type:markdown id: tags:
On Unix-like systems by default `adaptive.Runner` creates a `ProcessPoolExecutor`, but you can also pass one explicitly e.g. to limit the number of workers:
%% Cell type:code id: tags:
```
from concurrent.futures import ProcessPoolExecutor
executor = ProcessPoolExecutor(max_workers=4)
learner = adaptive.Learner1D(f, bounds=(-1, 1))
runner = adaptive.Runner(learner, executor=executor, goal=lambda l: l.loss() < 0.05)
runner.live_info()
runner.live_plot(update_interval=0.1)
```
%% Cell type:markdown id: tags:
### [`ipyparallel`](https://ipyparallel.readthedocs.io/en/latest/intro.html)
%% Cell type:code id: tags:
```
import ipyparallel
client = ipyparallel.Client() # You will need to start an `ipcluster` to make this work
learner = adaptive.Learner1D(f, bounds=(-1, 1))
runner = adaptive.Runner(learner, executor=client, goal=lambda l: l.loss() < 0.01)
runner.live_info()
runner.live_plot()
```
%% Cell type:markdown id: tags:
### [`distributed`](https://distributed.readthedocs.io/en/latest/)
On Windows by default `adaptive.Runner` uses a `distributed.Client`.
%% Cell type:code id: tags:
```
import distributed
client = distributed.Client()
learner = adaptive.Learner1D(f, bounds=(-1, 1))
runner = adaptive.Runner(learner, executor=client, goal=lambda l: l.loss() < 0.01)
runner.live_info()
runner.live_plot(update_interval=0.1)
```
%% Cell type:markdown id: tags:
---
%% Cell type:markdown id: tags:
# Advanced Topics
%% Cell type:markdown id: tags:
## A watched pot never boils!
%% Cell type:markdown id: tags:
`adaptive.Runner` does its work in an `asyncio` task that runs concurrently with the IPython kernel, when using `adaptive` from a Jupyter notebook. This is advantageous because it allows us to do things like live-updating plots, however it can trip you up if you're not careful.
Notably: **if you block the IPython kernel, the runner will not do any work**.
For example if you wanted to wait for a runner to complete, **do not wait in a busy loop**:
```python
while not runner.task.done():
pass
```
If you do this then **the runner will never finish**.
%% Cell type:markdown id: tags:
What to do if you don't care about live plotting, and just want to run something until its done?
The simplest way to accomplish this is to use `adaptive.BlockingRunner`:
%% Cell type:code id: tags:
```
learner = adaptive.Learner1D(partial(f, wait=False), bounds=(-1, 1))
adaptive.BlockingRunner(learner, goal=lambda l: l.loss() < 0.005)
# This will only get run after the runner has finished
learner.plot()
```
%% Cell type:markdown id: tags:
## Reproducibility
%% Cell type:markdown id: tags:
By default `adaptive` runners evaluate the learned function in parallel across several cores. The runners are also opportunistic, in that as soon as a result is available they will feed it to the learner and request another point to replace the one that just finished.
Because the order in which computations complete is non-deterministic, this means that the runner behaves in a non-deterministic way. Adaptive makes this choice because in many cases the speedup from parallel execution is worth sacrificing the "purity" of exactly reproducible computations.
Nevertheless it is still possible to run a learner in a deterministic way with adaptive.
The simplest way is to use `adaptive.runner.simple` to run your learner:
%% Cell type:code id: tags:
```
learner = adaptive.Learner1D(partial(f, wait=False), bounds=(-1, 1))
# blocks until completion
adaptive.runner.simple(learner, goal=lambda l: l.loss() < 0.002)
learner.plot()
```
%% Cell type:markdown id: tags:
Note that unlike `adaptive.Runner`, `adaptive.runner.simple` *blocks* until it is finished.
If you want to enable determinism, want to continue using the non-blocking `adaptive.Runner`, you can use the `adaptive.runner.SequentialExecutor`:
%% Cell type:code id: tags:
```
from adaptive.runner import SequentialExecutor
learner = adaptive.Learner1D(f, bounds=(-1, 1))
# blocks until completion
runner = adaptive.Runner(learner, executor=SequentialExecutor(), goal=lambda l: l.loss() < 0.002)
runner.live_info()
runner.live_plot(update_interval=0.1)
```
%% Cell type:markdown id: tags:
## Cancelling a runner
%% Cell type:markdown id: tags:
Sometimes you want to interactively explore a parameter space, and want the function to be evaluated at finer and finer resolution and manually control when the calculation stops.
If no `goal` is provided to a runner then the runner will run until cancelled.
`runner.live_info()` will provide a button that can be clicked to stop the runner. You can also stop the runner programatically using `runner.cancel()`.
%% Cell type:code id: tags:
```
learner = adaptive.Learner1D(f, bounds=(-1, 1))
runner = adaptive.Runner(learner)
runner.live_info()
runner.live_plot(update_interval=0.1)
```
%% Cell type:code id: tags:
```
runner.cancel()
```
%% Cell type:code id: tags:
```
print(runner.status())
```
%% Cell type:markdown id: tags:
## Debugging Problems
%% Cell type:markdown id: tags:
Runners work in the background with respect to the IPython kernel, which makes it convenient, but also means that inspecting errors is more difficult because exceptions will not be raised directly in the notebook. Often the only indication you will have that something has gone wrong is that nothing will be happening.
Let's look at the following example, where the function to be learned will raise an exception 10% of the time.
%% Cell type:code id: tags:
```
def will_raise(x):
from random import random
from time import sleep
sleep(random())
if random() < 0.1:
raise RuntimeError('something went wrong!')
return x**2
learner = adaptive.Learner1D(will_raise, (-1, 1))
runner = adaptive.Runner(learner) # without 'goal' the runner will run forever unless cancelled
runner.live_info()
runner.live_plot()
```
%% Cell type:markdown id: tags:
The above runner should continue forever, but we notice that it stops after a few points are evaluated.
First we should check that the runner has really finished:
%% Cell type:code id: tags:
```
runner.task.done()
```
%% Cell type:markdown id: tags:
If it has indeed finished then we should check the `result` of the runner. This should be `None` if the runner stopped successfully. If the runner stopped due to an exception then asking for the result will raise the exception with the stack trace:
%% Cell type:code id: tags:
```
runner.task.result()
```
%% Cell type:markdown id: tags:
### Logging runners
%% Cell type:markdown id: tags:
Runners do their job in the background, which makes introspection quite cumbersome. One way to inspect runners is to instantiate one with `log=True`:
%% Cell type:code id: tags:
```
learner = adaptive.Learner1D(f, bounds=(-1, 1))
runner = adaptive.Runner(learner, goal=lambda l: l.loss() < 0.1,
log=True)
runner.live_info()
```
%% Cell type:markdown id: tags:
This gives a the runner a `log` attribute, which is a list of the `learner` methods that were called, as well as their arguments. This is useful because executors typically execute their tasks in a non-deterministic order.
This can be used with `adaptive.runner.replay_log` to perfom the same set of operations on another runner:
%% Cell type:code id: tags:
```
reconstructed_learner = adaptive.Learner1D(f, bounds=learner.bounds)
adaptive.runner.replay_log(reconstructed_learner, runner.log)
```
%% Cell type:code id: tags:
```
learner.plot().Scatter.I.opts(style=dict(size=6)) * reconstructed_learner.plot()
```
%% Cell type:markdown id: tags:
### Timing functions
%% Cell type:markdown id: tags:
To time the runner you **cannot** simply use
```python
now = datetime.now()
runner = adaptive.Runner(...)
print(datetime.now() - now)
```
because this will be done immediately. Also blocking the kernel with `while not runner.task.done()` will not work because the runner will not do anything when the kernel is blocked.
Therefore you need to create an `async` function and hook it into the `ioloop` like so:
%% Cell type:code id: tags:
```
import asyncio
async def time(runner):
from datetime import datetime
now = datetime.now()
await runner.task
return datetime.now() - now
ioloop = asyncio.get_event_loop()
learner = adaptive.Learner1D(f, bounds=(-1, 1))
runner = adaptive.Runner(learner, goal=lambda l: l.loss() < 0.01)
timer = ioloop.create_task(time(runner))
```
%% Cell type:code id: tags:
```
# The result will only be set when the runner is done.
timer.result()
```
%% Cell type:markdown id: tags:
## Using Runners from a script
%% Cell type:markdown id: tags:
Runners can also be used from a Python script independently of the notebook.
The simplest way to accomplish this is simply to use the `BlockingRunner`:
```python
import adaptive
def f(x):
return x
learner = adaptive.Learner1D(f, (-1, 1))
adaptive.BlockingRunner(learner, goal=lambda: l: l.loss() < 0.1)
```
If you use `asyncio` already in your script and want to integrate `adaptive` into it, then you can use the default `Runner` as you would from a notebook. If you want to wait for the runner to finish, then you can simply
```python
await runner.task
```
from within a coroutine.
Loading