Tutorial Learner1D#

Note

Because this documentation consists of static html, the live_plot and live_info widget is not live. Download the notebook in order to see the real behaviour. [1]

Hide code cell content
import adaptive

adaptive.notebook_extension()

import random
from functools import partial

import numpy as np

scalar output: f:โ„ โ†’ โ„#

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:

offset = random.uniform(-0.5, 0.5)


def f(x, offset=offset, wait=True):
    from random import random
    from time import sleep

    a = 0.01
    if wait:
        sleep(random() / 10)
    return x + a**2 / (a**2 + (x - offset) ** 2)

We start by initializing a 1D โ€œlearnerโ€, which will suggest points to evaluate, and adapt its suggestions as more and more points are evaluated.

learner = adaptive.Learner1D(f, bounds=(-1, 1))

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.

On Windows systems the runner will use a loky.get_reusable_executor. A ProcessPoolExecutor cannot be used on Windows for reasons.

# The end condition is when the "loss" is less than 0.01. In the context of the
# 1D learner this means that we will resolve features in 'func' with width 0.01 or wider.
runner = adaptive.Runner(learner, loss_goal=0.01)
Hide code cell content
await runner.task  # This is not needed in a notebook environment!

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:

runner.live_info()
runner.live_plot(update_interval=0.1)

We can now compare the adaptive sampling to a homogeneous sampling with the same number of points:

if not runner.task.done():
    raise RuntimeError(
        "Wait for the runner to finish before executing the cells below!"
    )
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()

vector output: f:โ„ โ†’ โ„^N#

Sometimes you may want to learn a function with vector output:

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]
    )

adaptive has you covered! The Learner1D can be used for such functions:

learner = adaptive.Learner1D(f_levels, bounds=(-1, 1))
runner = adaptive.Runner(
    learner, loss_goal=0.01
)  # continue until `learner.loss()<=0.01`
Hide code cell content
await runner.task  # This is not needed in a notebook environment!
runner.live_info()
runner.live_plot(update_interval=0.1)

Looking at curvature#

By default adaptive will sample more points where the (normalized) euclidean distance between the neighboring points is large. You may achieve better results sampling more points in regions with high curvature. To do this, you need to tell the learner to look at the curvature by specifying loss_per_interval.

from adaptive.learner.learner1D import (
    curvature_loss_function,
    default_loss,
    uniform_loss,
)

curvature_loss = curvature_loss_function()
learner = adaptive.Learner1D(f, bounds=(-1, 1), loss_per_interval=curvature_loss)
runner = adaptive.Runner(learner, loss_goal=0.01)
Hide code cell content
await runner.task  # This is not needed in a notebook environment!
runner.live_info()
runner.live_plot(update_interval=0.1)

We may see the difference of homogeneous sampling vs only one interval vs including the nearest neighboring intervals in this plot. We will look at 100 points.

def sin_exp(x):
    from math import exp, sin

    return sin(15 * x) * exp(-(x**2) * 2)


learner_h = adaptive.Learner1D(sin_exp, (-1, 1), loss_per_interval=uniform_loss)
learner_1 = adaptive.Learner1D(sin_exp, (-1, 1), loss_per_interval=default_loss)
learner_2 = adaptive.Learner1D(sin_exp, (-1, 1), loss_per_interval=curvature_loss)

# adaptive.runner.simple is a non parallel blocking runner.
adaptive.runner.simple(learner_h, npoints_goal=100)
adaptive.runner.simple(learner_1, npoints_goal=100)
adaptive.runner.simple(learner_2, npoints_goal=100)

(
    learner_h.plot().relabel("homogeneous")
    + learner_1.plot().relabel("euclidean loss")
    + learner_2.plot().relabel("curvature loss")
).cols(2)

More info about using custom loss functions can be found in Custom adaptive logic for 1D and 2D.

Exporting the data#

We can view the raw data by looking at the dictionary learner.data. Alternatively, we can view the data as NumPy array with

learner.to_numpy()
array([[-1.        , -0.99991706],
       [-0.75      , -0.74986096],
       [-0.5       , -0.49972044],
       [-0.375     , -0.37455323],
       [-0.25      , -0.24917494],
       [-0.125     , -0.12299313],
       [-0.0625    , -0.05863304],
       [ 0.        ,  0.01030511],
       [ 0.03125   ,  0.05320145],
       [ 0.046875  ,  0.08372473],
       [ 0.0625    ,  0.13601745],
       [ 0.0703125 ,  0.18570929],
       [ 0.078125  ,  0.28014539],
       [ 0.08203125,  0.36373088],
       [ 0.0859375 ,  0.4932792 ],
       [ 0.08984375,  0.69038012],
       [ 0.09375   ,  0.94078369],
       [ 0.09570312,  1.04560732],
       [ 0.09765625,  1.09647878],
       [ 0.09960938,  1.07435003],
       [ 0.1015625 ,  0.98891889],
       [ 0.10546875,  0.74736558],
       [ 0.109375  ,  0.5452951 ],
       [ 0.11328125,  0.41310527],
       [ 0.1171875 ,  0.33078253],
       [ 0.125     ,  0.24562408],
       [ 0.1328125 ,  0.20903559],
       [ 0.140625  ,  0.19279188],
       [ 0.15625   ,  0.18487779],
       [ 0.1875    ,  0.19982997],
       [ 0.21875   ,  0.22556168],
       [ 0.25      ,  0.25430958],
       [ 0.3125    ,  0.31466871],
       [ 0.375     ,  0.37630159],
       [ 0.5       ,  0.50061841],
       [ 0.625     ,  0.62535993],
       [ 0.75      ,  0.75023518],
       [ 1.        ,  1.00012289]])

If Pandas is installed (optional dependency), you can also run

df = learner.to_dataframe()
df
x y function.offset function.wait
0 -1.000000 -0.999917 0.098 True
1 -0.750000 -0.749861 0.098 True
2 -0.500000 -0.499720 0.098 True
3 -0.375000 -0.374553 0.098 True
4 -0.250000 -0.249175 0.098 True
5 -0.125000 -0.122993 0.098 True
6 -0.062500 -0.058633 0.098 True
7 0.000000 0.010305 0.098 True
8 0.031250 0.053201 0.098 True
9 0.046875 0.083725 0.098 True
10 0.062500 0.136017 0.098 True
11 0.070312 0.185709 0.098 True
12 0.078125 0.280145 0.098 True
13 0.082031 0.363731 0.098 True
14 0.085938 0.493279 0.098 True
15 0.089844 0.690380 0.098 True
16 0.093750 0.940784 0.098 True
17 0.095703 1.045607 0.098 True
18 0.097656 1.096479 0.098 True
19 0.099609 1.074350 0.098 True
20 0.101562 0.988919 0.098 True
21 0.105469 0.747366 0.098 True
22 0.109375 0.545295 0.098 True
23 0.113281 0.413105 0.098 True
24 0.117188 0.330783 0.098 True
25 0.125000 0.245624 0.098 True
26 0.132812 0.209036 0.098 True
27 0.140625 0.192792 0.098 True
28 0.156250 0.184878 0.098 True
29 0.187500 0.199830 0.098 True
30 0.218750 0.225562 0.098 True
31 0.250000 0.254310 0.098 True
32 0.312500 0.314669 0.098 True
33 0.375000 0.376302 0.098 True
34 0.500000 0.500618 0.098 True
35 0.625000 0.625360 0.098 True
36 0.750000 0.750235 0.098 True
37 1.000000 1.000123 0.098 True

and load that data into a new learner with

new_learner = adaptive.Learner1D(learner.function, (-1, 1))  # create an empty learner
new_learner.load_dataframe(df)  # load the pandas.DataFrame's data
new_learner.plot()