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.99991698],
       [-0.75      , -0.74986079],
       [-0.5       , -0.49971997],
       [-0.375     , -0.37455228],
       [-0.25      , -0.24917256],
       [-0.125     , -0.12298408],
       [-0.0625    , -0.05860883],
       [ 0.        ,  0.01041042],
       [ 0.03125   ,  0.05352802],
       [ 0.046875  ,  0.08443177],
       [ 0.0625    ,  0.13798174],
       [ 0.0703125 ,  0.18949871],
       [ 0.078125  ,  0.2885215 ],
       [ 0.08203125,  0.3768388 ],
       [ 0.0859375 ,  0.51395888],
       [ 0.08984375,  0.72044181],
       [ 0.09179688,  0.84653138],
       [ 0.09375   ,  0.97060744],
       [ 0.09765625,  1.09740424],
       [ 0.09960938,  1.05691277],
       [ 0.1015625 ,  0.95975209],
       [ 0.10546875,  0.7169358 ],
       [ 0.109375  ,  0.52418293],
       [ 0.11328125,  0.39970971],
       [ 0.1171875 ,  0.32223293],
       [ 0.125     ,  0.24176944],
       [ 0.1328125 ,  0.20704326],
       [ 0.140625  ,  0.19164586],
       [ 0.15625   ,  0.18440428],
       [ 0.1875    ,  0.19969445],
       [ 0.21875   ,  0.22550576],
       [ 0.25      ,  0.25428137],
       [ 0.3125    ,  0.31465861],
       [ 0.375     ,  0.37629689],
       [ 0.5       ,  0.50061687],
       [ 0.75      ,  0.75023482],
       [ 1.        ,  1.00012276]])

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.097497 True
1 -0.750000 -0.749861 0.097497 True
2 -0.500000 -0.499720 0.097497 True
3 -0.375000 -0.374552 0.097497 True
4 -0.250000 -0.249173 0.097497 True
5 -0.125000 -0.122984 0.097497 True
6 -0.062500 -0.058609 0.097497 True
7 0.000000 0.010410 0.097497 True
8 0.031250 0.053528 0.097497 True
9 0.046875 0.084432 0.097497 True
10 0.062500 0.137982 0.097497 True
11 0.070312 0.189499 0.097497 True
12 0.078125 0.288522 0.097497 True
13 0.082031 0.376839 0.097497 True
14 0.085938 0.513959 0.097497 True
15 0.089844 0.720442 0.097497 True
16 0.091797 0.846531 0.097497 True
17 0.093750 0.970607 0.097497 True
18 0.097656 1.097404 0.097497 True
19 0.099609 1.056913 0.097497 True
20 0.101562 0.959752 0.097497 True
21 0.105469 0.716936 0.097497 True
22 0.109375 0.524183 0.097497 True
23 0.113281 0.399710 0.097497 True
24 0.117188 0.322233 0.097497 True
25 0.125000 0.241769 0.097497 True
26 0.132812 0.207043 0.097497 True
27 0.140625 0.191646 0.097497 True
28 0.156250 0.184404 0.097497 True
29 0.187500 0.199694 0.097497 True
30 0.218750 0.225506 0.097497 True
31 0.250000 0.254281 0.097497 True
32 0.312500 0.314659 0.097497 True
33 0.375000 0.376297 0.097497 True
34 0.500000 0.500617 0.097497 True
35 0.750000 0.750235 0.097497 True
36 1.000000 1.000123 0.097497 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()