" return hv.Contours([p for p in tri.points[tri.vertices]])\n",
"def plot(learner):\n",
" tri = learner.ip().tri\n",
" return hv.Contours([p for p in learner.unscale(tri.points[tri.vertices])])\n",
"\n",
"def plot_poly(self):\n",
" tri = self.ip().tri\n",
" return hv.Polygons([p for p in tri.points[tri.vertices]])\n",
"def plot_poly(learner):\n",
" tri = learner.ip().tri\n",
" return hv.Polygons([p for p in learner.unscale(tri.points[tri.vertices])])\n",
"\n",
"\n",
"(adaptive.live_plot(runner) +\n",
...
...
@@ -614,7 +614,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.2"
"version": "3.6.3"
}
},
"nbformat": 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 the following packages:
+ Python 3.6
+ holowiews
+ bokeh
%% Cell type:code id: tags:
``` python
importadaptive
adaptive.notebook_extension()
```
%% 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:
``` python
fromfunctoolsimportpartial
fromrandomimportrandom
offset=random()-0.5
deff(x,offset=0,wait=True):
fromtimeimportsleep
fromrandomimportrandom
a=0.01
ifwait:
sleep(random()*10)
returnx+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.
Next we create a "runner" that will request points from the learner and evaluate 'f' on them.
By default the runner will evaluate the points in parallel using local processes ([`concurrent.futures.ProcessPoolExecutor`](https://docs.python.org/3/library/concurrent.futures.html#processpoolexecutor)).
%% Cell type:code id: tags:
``` python
# 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.
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).
The balancing learner is a "meta-learner" that takes a list of multiple leaners. The runner wil find find out which points of which child learner will improve the loss the most and send those to the executor.
The balancing learner can for example be used to implement a poor-man's 2D learner by using the `Learner1D`.
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`
%% Cell type:markdown id: tags:
By default a runner creates a `ProcessPoolExecutor`, but you can also pass one explicitly e.g. to limit the number of workers:
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:
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:
``` python
defwill_raise(x):
fromrandomimportrandom
fromtimeimportsleep
sleep(random())
ifrandom()<0.1:
raiseRuntimeError('something went wrong!')
returnx**2
learner=adaptive.Learner1D(will_raise,(-1,1))
runner=adaptive.Runner(learner)# without 'goal' the runner will run forever unless cancelled
adaptive.live_plot(runner)
```
%% 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:
``` python
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:
``` python
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`:
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:
Under the hood the runner uses [`asyncio`](https://docs.python.org/3/library/asyncio.html). You don't need to worry about this most of the time, unless your script uses asyncio itself. If this is the case you should be aware that instantiating a `Runner` schedules a new task on the current event loop, and you can simply
```python
awaitrunner.task
```
inside a coroutine to await completion of the runner.