de7ba87d |
{
"cells": [
{
"cell_type": "markdown",
|
c395daf0 |
"metadata": {},
|
de7ba87d |
"source": [
"# Adaptive"
]
},
|
9e091088 |
{
"cell_type": "markdown",
"metadata": {},
"source": [
|
7b2e3a4f |
"[`adaptive`](https://gitlab.kwant-project.org/qt/adaptive-evaluation) is a package for adaptively sampling functions with support for parallel evaluation.\n",
|
9e091088 |
"\n",
"This is an introductory notebook that shows some basic use cases.\n",
"\n",
"`adaptive` needs the following packages:\n",
"\n",
"+ Python 3.6\n",
|
60589534 |
"+ `holoviews`\n",
"+ `bokeh`"
|
9e091088 |
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import adaptive\n",
|
60589534 |
"adaptive.notebook_extension()\n",
"\n",
"# Import modules that are used in multiple cells\n",
"import holoviews as hv\n",
"import numpy as np\n",
"from functools import partial\n",
"import random"
|
9e091088 |
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 1D function learner"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We start with the most common use-case: sampling a 1D function $\\ f: ℝ → ℝ$.\n",
"\n",
"We will use the following function, which is a smooth (linear) background with a sharp peak at a random location:"
]
},
|
e3a7009c |
{
"cell_type": "code",
"execution_count": null,
|
08a1ae93 |
"metadata": {},
|
e3a7009c |
"outputs": [],
"source": [
|
60589534 |
"offset = random.uniform(-0.5, 0.5)\n",
|
e3a7009c |
"\n",
|
60589534 |
"def f(x, offset=offset, wait=True):\n",
|
18212a81 |
" from time import sleep\n",
|
9e091088 |
" from random import random\n",
|
18212a81 |
"\n",
|
9e091088 |
" a = 0.01\n",
|
de7ba87d |
" if wait:\n",
|
8faeb420 |
" sleep(random()*10)\n",
|
9e091088 |
" return x + a**2 / (a**2 + (x - offset)**2)"
|
de7ba87d |
]
},
{
"cell_type": "markdown",
|
9e091088 |
"metadata": {},
"source": [
"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",
"execution_count": null,
|
08a1ae93 |
"metadata": {},
|
9e091088 |
"outputs": [],
|
de7ba87d |
"source": [
|
60589534 |
"learner = adaptive.Learner1D(f, bounds=(-1, 1))"
|
9e091088 |
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
|
1f0e04fa |
"Next we create a \"runner\" that will request points from the learner and evaluate 'f' on them.\n",
|
9e091088 |
"\n",
"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))."
|
de7ba87d |
]
},
|
ea41ee7a |
{
"cell_type": "code",
"execution_count": null,
|
08a1ae93 |
"metadata": {},
|
9e091088 |
"outputs": [],
"source": [
"# The end condition is when the \"loss\" is less than 0.1. In the context of the\n",
"# 1D learner this means that we will resolve features in 'func' with width 0.1 or wider.\n",
|
beead16a |
"runner = adaptive.Runner(learner, goal=lambda l: l.loss() < 0.01)"
|
9e091088 |
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When instantiated in a Jupyter notebook the runner does its job in the background and does not block the IPython kernel.\n",
"We can use this to create a plot that updates as new data arrives:"
]
},
{
"cell_type": "code",
"execution_count": null,
|
08a1ae93 |
"metadata": {},
|
ea41ee7a |
"outputs": [],
"source": [
"adaptive.live_plot(runner)"
]
},
|
9e091088 |
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can now compare the adaptive sampling to a homogeneous sampling with the same number of points:"
]
},
{
"cell_type": "code",
"execution_count": null,
|
08a1ae93 |
"metadata": {},
|
9e091088 |
"outputs": [],
"source": [
"if not runner.task.done():\n",
" raise RuntimeError('Wait for the runner to finish before executing the cells below!')"
]
},
|
de7ba87d |
{
"cell_type": "code",
"execution_count": null,
|
08a1ae93 |
"metadata": {},
|
de7ba87d |
"outputs": [],
"source": [
|
60589534 |
"learner2 = adaptive.Learner1D(f, bounds=learner.bounds)\n",
|
c395daf0 |
"\n",
|
60589534 |
"xs = np.linspace(*learner.bounds, len(learner.data))\n",
|
31b99e9d |
"learner2.add_data(xs, map(partial(f, wait=False), xs))\n",
|
9e091088 |
"\n",
|
8faeb420 |
"learner.plot() + learner2.plot()"
|
18212a81 |
]
},
{
"cell_type": "markdown",
|
9e091088 |
"metadata": {},
"source": [
|
569168f5 |
"# 2D function learner"
|
9e091088 |
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
|
569168f5 |
"Besides 1D functions, we can also learn 2D functions: $\\ f: ℝ^2 → ℝ$"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
|
60589534 |
"def ring(xy, wait=True):\n",
|
569168f5 |
" import numpy as np\n",
|
beead16a |
" from time import sleep\n",
" from random import random\n",
|
39fca22a |
" if wait:\n",
" sleep(random())\n",
|
569168f5 |
" x, y = xy\n",
" a = 0.2\n",
" return x + np.exp(-(x**2 + y**2 - 0.75**2)**2/a**4)\n",
|
9e091088 |
"\n",
|
60589534 |
"learner = adaptive.Learner2D(ring, bounds=[(-1, 1), (-1, 1)])"
|
9e091088 |
]
},
{
"cell_type": "code",
"execution_count": null,
|
08a1ae93 |
"metadata": {},
|
9e091088 |
"outputs": [],
|
18212a81 |
"source": [
|
8faeb420 |
"runner = adaptive.Runner(learner, goal=lambda l: l.loss() < 0.01)"
|
9e091088 |
]
},
{
"cell_type": "code",
"execution_count": null,
|
08a1ae93 |
"metadata": {},
|
9e091088 |
"outputs": [],
"source": [
|
beead16a |
"(adaptive.live_plot(runner) +\n",
|
197d2d7e |
" adaptive.live_plot(runner, plotter=lambda l: l.plot(triangles_alpha=1).Contours) +\n",
" adaptive.live_plot(runner, plotter=lambda l: l.plot(triangles_alpha=0.2)))"
|
9e091088 |
]
},
|
569168f5 |
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
|
60589534 |
"import itertools\n",
"learner2 = adaptive.Learner2D(ring, bounds=learner.bounds)\n",
"xs = np.linspace(*learner.bounds[0], learner.n**0.5)\n",
"ys = np.linspace(*learner.bounds[1], learner.n**0.5)\n",
"xys = list(itertools.product(xs, ys))\n",
"learner2.add_data(xys, map(partial(ring, wait=False), xys))\n",
|
569168f5 |
"learner2.plot().relabel('Homogeneous grid') + learner.plot().relabel('With adaptive')"
]
},
|
31b99e9d |
{
"cell_type": "markdown",
"metadata": {},
"source": [
|
569168f5 |
"# Averaging learner"
|
31b99e9d |
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
|
569168f5 |
"The next type of learner averages a function until the uncertainty in the average meets some condition.\n",
|
31b99e9d |
"\n",
|
569168f5 |
"This is useful for sampling a random variable. The function passed to the learner must formally take a single parameter,\n",
"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)."
|
31b99e9d |
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
|
569168f5 |
"def g(n):\n",
" import random\n",
" from time import sleep\n",
" sleep(random.random() / 5)\n",
" # Properly save and restore the RNG state\n",
" state = random.getstate()\n",
" random.seed(n)\n",
" val = random.gauss(0.5, 1)\n",
" random.setstate(state)\n",
" return val"
|
31b99e9d |
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
|
60589534 |
"learner = adaptive.AverageLearner(g, atol=None, rtol=0.01)\n",
|
569168f5 |
"runner = adaptive.Runner(learner, goal=lambda l: l.loss() < 1)\n",
"adaptive.live_plot(runner)"
|
31b99e9d |
]
},
|
0cc979de |
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 1D integration learner with `cquad`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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).\n",
"\n",
"Let's try the following function with cusps (that is difficult to integrate):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def f24(x):\n",
" return np.floor(np.exp(x))\n",
"\n",
"xs = np.linspace(0, 3, 200)\n",
"hv.Scatter((xs, [f24(x) for x in xs]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import scipy.integrate\n",
"scipy.integrate.quad(f24, 0, 3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
|
60589534 |
"from adaptive.runner import SequentialExecutor\n",
"learner = adaptive.IntegratorLearner(f24, bounds=(0, 3), tol=1e-10)\n",
"runner = adaptive.Runner(learner, executor=SequentialExecutor(), goal=lambda l: l.done())"
|
0cc979de |
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we could do the live plotting again, but lets just wait untill the runner is done."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"if not runner.task.done():\n",
" raise RuntimeError('Wait for the runner to finish before executing the cells below!')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print('The integral value is {} with the corresponding error of {}'.format(learner.igral, learner.err))\n",
"learner.plot()"
]
},
|
71f79367 |
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 1D learner with vector output: `f:ℝ → ℝ^N`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Some 1D functions return multiple numbers, such as the following function:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"random.seed(0)\n",
"offsets = [random.uniform(-0.8, 0.8) for _ in range(3)]\n",
"def f_levels(x, offsets=offsets):\n",
" a = 0.01\n",
" return np.array([offset + x + a**2 / (a**2 + (x - offset)**2)\n",
" for offset in offsets])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
|
e2c879af |
"This is again a function with sharp peaks at different x-values and with different constant backgrounds. To learn this function we can use a `Learner1D` as well."
|
71f79367 |
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from adaptive.runner import SequentialExecutor\n",
"\n",
|
e2c879af |
"learner = adaptive.Learner1D(f_levels, bounds=(-1, 1))\n",
|
71f79367 |
"runner = adaptive.Runner(learner, SequentialExecutor(), goal=lambda l: l.loss() < 0.05)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In the plot below we see that the function gets more densely sampled around the peaks, which is the behaviour we want."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"adaptive.live_plot(runner)"
]
},
|
42dac9a1 |
{
"cell_type": "markdown",
"metadata": {},
"source": [
|
569168f5 |
"# Balancing learner"
|
42dac9a1 |
]
},
{
|
569168f5 |
"cell_type": "markdown",
|
42dac9a1 |
"metadata": {},
"source": [
|
569168f5 |
"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.\n",
|
42dac9a1 |
"\n",
|
569168f5 |
"The balancing learner can for example be used to implement a poor-man's 2D learner by using the `Learner1D`."
|
42dac9a1 |
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
|
60589534 |
"def f(x, offset):\n",
" a = 0.01\n",
" return x + a**2 / (a**2 + (x - offset)**2)\n",
"\n",
"learners = [adaptive.Learner1D(partial(f, offset=random.uniform(-1, 1)),\n",
" bounds=(-1, 1)) for i in range(10)]\n",
|
569168f5 |
"\n",
|
60589534 |
"bal_learner = adaptive.BalancingLearner(learners)\n",
"runner = adaptive.Runner(bal_learner, goal=lambda l: l.loss() < 0.01)"
|
42dac9a1 |
]
},
|
b2260aef |
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
|
60589534 |
"plotter = lambda learner: hv.Overlay([L.plot() for L in learner.learners])\n",
"adaptive.live_plot(runner, plotter=plotter)"
|
b2260aef |
]
},
|
642d7f59 |
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# DataSaver"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Sometimes we want to learn functions that do not only return a single `float`, but instead return multiple values (even though we only want to learn one value.)\n",
"\n",
"We can wrap our learners with a `adaptive.DataSaver` such that the learner will be able to handle functions that return results.\n",
"\n",
"Take for example this function where we want to remember the time that every point took:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from operator import itemgetter\n",
"\n",
|
60589534 |
"def f_dict(x):\n",
|
642d7f59 |
" \"\"\"The function evaluation takes roughly the time we `sleep`.\"\"\"\n",
" import random\n",
" from time import sleep\n",
"\n",
" waiting_time = random.random()\n",
" sleep(waiting_time)\n",
" a = 0.01\n",
" y = x + a**2 / (a**2 + x**2)\n",
" return {'y': y, 'waiting_time': waiting_time}\n",
"\n",
"# Create the learner with the function that returns a `dict`\n",
"# Note that this learner cannot be passed to a runner.\n",
|
60589534 |
"_learner = adaptive.Learner1D(f_dict, bounds=(-1, 1))\n",
|
642d7f59 |
"\n",
"# Wrap the learner in the `DataSavingLearner` and tell it which key it needs to learn\n",
|
60589534 |
"learner = adaptive.DataSaver(_learner, arg_picker=itemgetter('y'))"
|
642d7f59 |
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`learner.learner` is the original learner, so `learner.learner.loss()` will call the correct loss method."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"runner = adaptive.Runner(learner, goal=lambda l: l.learner.loss() < 0.01)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Because `learner` doesn't have a `plot` function we need to copy `_learner.plot` (or `learner.learner.plot`)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"learner.plot = _learner.plot\n",
"adaptive.live_plot(runner)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
|
e34c88a7 |
"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."
|
642d7f59 |
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
|
e34c88a7 |
"learner.extra_data"
|
642d7f59 |
]
},
|
9e091088 |
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"## Alternative executors"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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",
"metadata": {},
"source": [
"### `concurrent.futures`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"By default a runner creates a `ProcessPoolExecutor`, but you can also pass one explicitly e.g. to limit the number of workers:"
]
},
{
"cell_type": "code",
"execution_count": null,
|
08a1ae93 |
"metadata": {},
|
9e091088 |
"outputs": [],
"source": [
"from concurrent.futures import ProcessPoolExecutor\n",
"\n",
"executor = ProcessPoolExecutor(max_workers=4)\n",
"\n",
|
60589534 |
"learner = adaptive.Learner1D(f, bounds=(-1, 1))\n",
|
9e091088 |
"runner = adaptive.Runner(learner, executor=executor, goal=lambda l: l.loss() < 0.1)\n",
"adaptive.live_plot(runner)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### IPyparallel"
|
de7ba87d |
]
},
{
"cell_type": "code",
"execution_count": null,
|
08a1ae93 |
"metadata": {},
|
de7ba87d |
"outputs": [],
"source": [
|
18212a81 |
"import ipyparallel\n",
"\n",
"client = ipyparallel.Client()\n",
|
9e091088 |
"# f is a closure, so we have to use cloudpickle -- this is independent of 'adaptive'\n",
"client[:].use_cloudpickle()\n",
|
18212a81 |
"\n",
|
60589534 |
"learner = adaptive.Learner1D(f, bounds=(-1, 1))\n",
|
9e091088 |
"runner = adaptive.Runner(learner, executor=client, goal=lambda l: l.loss() < 0.1)\n",
|
73fa8d28 |
"adaptive.live_plot(runner)"
|
e3a7009c |
]
|
ea41ee7a |
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
|
9e091088 |
"---"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Advanced Topics"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Cancelling a runner"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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.\n",
"\n",
"If no `goal` is provided to a runner then the runner will run until cancelled:"
]
},
{
"cell_type": "code",
"execution_count": null,
|
08a1ae93 |
"metadata": {},
|
9e091088 |
"outputs": [],
"source": [
|
60589534 |
"learner = adaptive.Learner1D(f, bounds=(-1, 1))\n",
|
9e091088 |
"runner = adaptive.Runner(learner)\n",
"adaptive.live_plot(runner)"
]
},
{
"cell_type": "code",
"execution_count": null,
|
08a1ae93 |
"metadata": {},
|
9e091088 |
"outputs": [],
"source": [
"runner.task.cancel()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Debugging Problems "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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.\n",
"\n",
"Let's look at the following example, where the function to be learned will raise an exception 10% of the time."
]
},
{
"cell_type": "code",
"execution_count": null,
|
08a1ae93 |
"metadata": {},
|
9e091088 |
"outputs": [],
"source": [
"def will_raise(x):\n",
" from random import random\n",
" from time import sleep\n",
" \n",
" sleep(random())\n",
" if random() < 0.1:\n",
" raise RuntimeError('something went wrong!')\n",
" return x**2\n",
" \n",
"learner = adaptive.Learner1D(will_raise, (-1, 1))\n",
"runner = adaptive.Runner(learner) # without 'goal' the runner will run forever unless cancelled\n",
"adaptive.live_plot(runner)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The above runner should continue forever, but we notice that it stops after a few points are evaluated.\n",
"\n",
"First we should check that the runner has really finished:"
]
},
{
"cell_type": "code",
"execution_count": null,
|
08a1ae93 |
"metadata": {},
|
9e091088 |
"outputs": [],
"source": [
"runner.task.done()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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:"
|
ea41ee7a |
]
},
{
"cell_type": "code",
"execution_count": null,
|
08a1ae93 |
"metadata": {},
|
ea41ee7a |
"outputs": [],
"source": [
|
9e091088 |
"runner.task.result()"
]
},
|
9ba68ad1 |
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Logging runners"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
|
60589534 |
"learner = adaptive.Learner1D(f, bounds=(-1, 1))\n",
|
9ba68ad1 |
"runner = adaptive.Runner(learner, goal=lambda l: l.loss() < 0.1,\n",
" log=True)\n",
"adaptive.live_plot(runner)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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.\n",
"\n",
"This can be used with `adaptive.runner.replay_log` to perfom the same set of operations on another runner:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
|
8dcfaff1 |
"reconstructed_learner = adaptive.Learner1D(f, bounds=learner.bounds)\n",
|
9ba68ad1 |
"adaptive.runner.replay_log(reconstructed_learner, runner.log)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"learner.plot().opts(style=dict(size=6)) * reconstructed_learner.plot()"
]
},
|
0cd9011f |
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Timing functions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To time the runner you **cannot** simply use \n",
"```python\n",
"now = datetime.now()\n",
"runner = adaptive.Runner(...)\n",
"print(datetime.now() - now)\n",
"```\n",
"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.\n",
"\n",
"Therefore you need to create an `async` function and hook it into the `ioloop` like so:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import asyncio\n",
"\n",
"async def time(runner):\n",
" from datetime import datetime\n",
" now = datetime.now()\n",
" await runner.task\n",
" return datetime.now() - now\n",
"\n",
"ioloop = asyncio.get_event_loop()\n",
"\n",
|
60589534 |
"learner = adaptive.Learner1D(f, bounds=(-1, 1))\n",
"runner = adaptive.Runner(learner, goal=lambda l: l.loss() < 0.01)\n",
|
0cd9011f |
"\n",
"timer = ioloop.create_task(time(runner))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# The result will only be set when the runner is done.\n",
"timer.result()"
]
},
|
9e091088 |
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Using Runners from a script "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Runners can also be used from a Python script independently of the notebook:\n",
"\n",
"```python\n",
"import adaptive\n",
"\n",
"def f(x):\n",
" return x\n",
"\n",
"learner = adaptive.Learner1D(f, (-1, 1))\n",
"\n",
"runner = adaptive.Runner(learner, goal=lambda: l: l.loss() < 0.1)\n",
"runner.run_sync() # Block until completion.\n",
"```\n",
"\n",
"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\n",
"\n",
"```python\n",
" await runner.task\n",
"```\n",
|
ea41ee7a |
"\n",
|
9e091088 |
"inside a coroutine to await completion of the runner."
|
ea41ee7a |
]
|
de7ba87d |
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
|
c395daf0 |
"display_name": "Python 3",
|
de7ba87d |
"language": "python",
|
c395daf0 |
"name": "python3"
|
de7ba87d |
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
|
92084364 |
"version": "3.6.3"
|
de7ba87d |
}
},
"nbformat": 4,
"nbformat_minor": 1
}
|