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

import adaptive

adaptive.notebook_extension()

import numpy as np
from functools import partial
import random

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 time import sleep
    from random import random

    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)
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`
await runner.task  # This is not needed in a notebook environment!
/home/docs/checkouts/readthedocs.org/user_builds/adaptive/conda/v0.15.1/lib/python3.9/site-packages/numpy/lib/nanfunctions.py:96: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  a = np.asanyarray(a)
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,
    uniform_loss,
    default_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)
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.99993019],
       [-0.75      , -0.74988846],
       [-0.5       , -0.49979409],
       [-0.25      , -0.24949937],
       [-0.125     , -0.12403539],
       [ 0.        ,  0.00257477],
       [ 0.0625    ,  0.06801205],
       [ 0.125     ,  0.14401782],
       [ 0.140625  ,  0.17131898],
       [ 0.15625   ,  0.21352411],
       [ 0.171875  ,  0.31032302],
       [ 0.17578125,  0.36005786],
       [ 0.1796875 ,  0.43378494],
       [ 0.18359375,  0.54728998],
       [ 0.1875    ,  0.72261067],
       [ 0.19140625,  0.96469796],
       [ 0.19335938,  1.08636456],
       [ 0.1953125 ,  1.17306897],
       [ 0.19921875,  1.14484357],
       [ 0.203125  ,  0.91872439],
       [ 0.20703125,  0.69661924],
       [ 0.2109375 ,  0.54507126],
       [ 0.21484375,  0.45023375],
       [ 0.21875   ,  0.39089963],
       [ 0.2265625 ,  0.32812979],
       [ 0.234375  ,  0.30058621],
       [ 0.25      ,  0.28415268],
       [ 0.28125   ,  0.29508453],
       [ 0.3125    ,  0.31991747],
       [ 0.375     ,  0.37813993],
       [ 0.5       ,  0.50108675],
       [ 0.625     ,  0.62554515],
       [ 0.75      ,  0.75032668],
       [ 1.        ,  1.00015499]])

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.999930 0.196821 True
1 -0.750000 -0.749888 0.196821 True
2 -0.500000 -0.499794 0.196821 True
3 -0.250000 -0.249499 0.196821 True
4 -0.125000 -0.124035 0.196821 True
5 0.000000 0.002575 0.196821 True
6 0.062500 0.068012 0.196821 True
7 0.125000 0.144018 0.196821 True
8 0.140625 0.171319 0.196821 True
9 0.156250 0.213524 0.196821 True
10 0.171875 0.310323 0.196821 True
11 0.175781 0.360058 0.196821 True
12 0.179688 0.433785 0.196821 True
13 0.183594 0.547290 0.196821 True
14 0.187500 0.722611 0.196821 True
15 0.191406 0.964698 0.196821 True
16 0.193359 1.086365 0.196821 True
17 0.195312 1.173069 0.196821 True
18 0.199219 1.144844 0.196821 True
19 0.203125 0.918724 0.196821 True
20 0.207031 0.696619 0.196821 True
21 0.210938 0.545071 0.196821 True
22 0.214844 0.450234 0.196821 True
23 0.218750 0.390900 0.196821 True
24 0.226562 0.328130 0.196821 True
25 0.234375 0.300586 0.196821 True
26 0.250000 0.284153 0.196821 True
27 0.281250 0.295085 0.196821 True
28 0.312500 0.319917 0.196821 True
29 0.375000 0.378140 0.196821 True
30 0.500000 0.501087 0.196821 True
31 0.625000 0.625545 0.196821 True
32 0.750000 0.750327 0.196821 True
33 1.000000 1.000155 0.196821 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()

1

This notebook can be downloaded as tutorial.Learner1D.ipynb and tutorial.Learner1D.md.