Newer
Older
{
"cells": [
{
"cell_type": "markdown",
"source": [
"# Adaptive"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[`adaptive`](https://gitlab.kwant-project.org/qt/adaptive-evaluation) is a package for adaptively sampling functions with support for parallel evaluation.\n",
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"\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",
"+ holowiews\n",
"+ bokeh"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import adaptive\n",
"adaptive.notebook_extension()"
]
},
{
"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:"
]
},
{
"cell_type": "code",
"execution_count": null,
"import functools\n",
"from random import random\n",
"offset = random() - 0.5\n",
"\n",
"def f(x, offset=0, wait=True):\n",
" sleep(random())\n",
" return x + a**2 / (a**2 + (x - offset)**2)"
]
},
{
"cell_type": "markdown",
"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,
"learner = adaptive.learner.Learner1D(f, bounds=(-1.0, 1.0))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Next we create a \"runner\" that will request points from the learner and evaluate 'func' on them.\n",
"\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))."
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"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",
"runner = adaptive.Runner(learner, goal=lambda l: l.loss() < 0.1)"
]
},
{
"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,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"adaptive.live_plot(runner)"
]
},
{
"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,
"metadata": {
"collapsed": true
},
"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,
"outputs": [],
"source": [
"learner2 = adaptive.learner.Learner1D(f, bounds=(-1.01, 1.0))\n",
"\n",
"xs = np.linspace(-1.0, 1.0, len(learner.data))\n",
"learner2.add_data(xs, map(functools.partial(func, wait=False), xs))\n",
"\n",
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Averaging learner"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The next type of learner averages a function until the uncertainty in the average meets some condition.\n",
"\n",
"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)."
]
},
{
"cell_type": "code",
"execution_count": null,
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
"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"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": false
},
"outputs": [],
"source": [
"learner = adaptive.AverageLearner(g, None, 0.03)\n",
"runner = adaptive.Runner(learner, goal=lambda l: l.loss() < 1)\n",
"adaptive.live_plot(runner)"
]
},
{
"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,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"from concurrent.futures import ProcessPoolExecutor\n",
"\n",
"executor = ProcessPoolExecutor(max_workers=4)\n",
"\n",
"learner = adaptive.learner.Learner1D(f, bounds=(-1, 1))\n",
"runner = adaptive.Runner(learner, executor=executor, goal=lambda l: l.loss() < 0.1)\n",
"adaptive.live_plot(runner)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### IPyparallel"
]
},
{
"cell_type": "code",
"execution_count": null,
"outputs": [],
"source": [
"import ipyparallel\n",
"\n",
"client = ipyparallel.Client()\n",
"# f is a closure, so we have to use cloudpickle -- this is independent of 'adaptive'\n",
"client[:].use_cloudpickle()\n",
"learner = adaptive.learner.Learner1D(f, bounds=(-1, 1))\n",
"runner = adaptive.Runner(learner, executor=client, goal=lambda l: l.loss() < 0.1)\n",
"adaptive.live_plot(runner)"
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
"---"
]
},
{
"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,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"learner = adaptive.learner.Learner1D(f, bounds=(-1.0, 1.0))\n",
"runner = adaptive.Runner(learner)\n",
"adaptive.live_plot(runner)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"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,
"metadata": {
"collapsed": true
},
"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,
"metadata": {
"collapsed": true
},
"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:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": false
},
"outputs": [],
"source": [
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
"runner.task.result()"
]
},
{
"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",
"inside a coroutine to await completion of the runner."
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"language": "python",
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
}
},
"nbformat": 4,
"nbformat_minor": 1
}