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,
"offset = random() - 0.5\n",
"\n",
"def f(x, offset=0, wait=True):\n",
]
},
{
"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 'f' 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,
"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.01)"
]
},
{
"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,
"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,
"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(partial(f, wait=False), xs))\n",
]
},
{
"cell_type": "markdown",
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Besides 1D functions, we can also learn 2D functions: $\\ f: ℝ^2 → ℝ$"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def func(xy, wait=True):\n",
" from time import sleep\n",
" from random import random\n",
" if wait:\n",
" sleep(random())\n",
" x, y = xy\n",
" a = 0.2\n",
" return x + np.exp(-(x**2 + y**2 - 0.75**2)**2/a**4)\n",
"learner = adaptive.learner.Learner2D(func, bounds=[(-1, 1), (-1, 1)])"
]
},
{
"cell_type": "code",
"execution_count": null,
"runner = adaptive.Runner(learner, goal=lambda l: l.loss() < 0.01)"
]
},
{
"cell_type": "code",
"execution_count": null,
"%%output size=100\n",
"%%opts Contours (alpha=0.3)\n",
"import holoviews as hv\n",
"def plot(learner):\n",
" tri = learner.ip().tri\n",
" return hv.Contours([p for p in learner.unscale(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",
" adaptive.live_plot(runner, plotter=plot_poly) +\n",
" adaptive.live_plot(runner) * adaptive.live_plot(runner, plotter=plot))"
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"learner2 = adaptive.learner.Learner2D(func, bounds=[(-1, 1), (-1, 1)])\n",
"lin = np.linspace(-1, 1, len(learner.points)**0.5)\n",
"xy = [(x, y) for x in lin for y in lin]\n",
"learner2.add_data(xy, map(partial(func, wait=False), xy))\n",
"learner2.plot().relabel('Homogeneous grid') + learner.plot().relabel('With adaptive')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The next type of learner averages a function until the uncertainty in the average meets some condition.\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,
"metadata": {},
"outputs": [],
"source": [
"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": {},
"outputs": [],
"source": [
"learner = adaptive.learner.AverageLearner(g, None, 0.01)\n",
"runner = adaptive.Runner(learner, goal=lambda l: l.loss() < 1)\n",
"adaptive.live_plot(runner)"
284
285
286
287
288
289
290
291
292
293
294
295
296
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
{
"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": [
"import numpy as np\n",
"import holoviews as hv\n",
"\n",
"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": [
"learner = adaptive.learner.IntegratorLearner(f24, bounds=(0, 3), tol=1e-10)\n",
"runner = adaptive.Runner(learner, executor=adaptive.runner.SequentialExecutor(), goal=lambda l: l.done())"
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
]
},
{
"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()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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",
"The balancing learner can for example be used to implement a poor-man's 2D learner by using the `Learner1D`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from adaptive.learner import Learner1D, BalancingLearner\n",
"\n",
"learners = [Learner1D(partial(f, offset=2*random()-1, wait=False), bounds=(-1.0, 1.0)) for i in range(10)]\n",
"learner = BalancingLearner(learners)\n",
"runner = adaptive.Runner(learner, goal=lambda l: l.loss() < 0.02)"
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import holoviews as hv\n",
"adaptive.live_plot(runner, plotter=lambda learner: hv.Overlay([L.plot() for L in learner.learners]))"
416
417
418
419
420
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
{
"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,
"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": [
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
"---"
]
},
{
"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,
"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,
"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,
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
"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,
"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,
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
{
"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": [
"learner = adaptive.learner.Learner1D(f, bounds=(-1, 1))\n",
"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": [
"reconstructed_learner = adaptive.learner.Learner1D(f, bounds=(-1, 1))\n",
"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()"
]
},
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
{
"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",
"learner = adaptive.learner.IntegratorLearner(f24, bounds=(0, 3), tol=1e-3)\n",
"runner = adaptive.Runner(learner, executor=adaptive.runner.SequentialExecutor(),\n",
" goal=lambda l: l.done())\n",
"\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()"
]
},
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
{
"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
}