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.0/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.999883  ],
       [-0.75      , -0.74978022],
       [-0.5       , -0.49944526],
       [-0.375     , -0.37388611],
       [-0.25      , -0.24672517],
       [-0.1875    , -0.17958537],
       [-0.15625   , -0.14113044],
       [-0.140625  , -0.11756191],
       [-0.125     , -0.08572574],
       [-0.109375  , -0.02903708],
       [-0.1015625 ,  0.02711767],
       [-0.09375   ,  0.13796259],
       [-0.08984375,  0.23848822],
       [-0.0859375 ,  0.39462832],
       [-0.08203125,  0.62158036],
       [-0.078125  ,  0.85928189],
       [-0.07617188,  0.91986337],
       [-0.07421875,  0.90859924],
       [-0.0703125 ,  0.71500646],
       [-0.06640625,  0.47872242],
       [-0.0625    ,  0.30777898],
       [-0.05859375,  0.19966542],
       [-0.0546875 ,  0.13227494],
       [-0.046875  ,  0.06161578],
       [-0.0390625 ,  0.03083443],
       [-0.03125   ,  0.01725392],
       [-0.015625  ,  0.01147584],
       [ 0.        ,  0.01722227],
       [ 0.03125   ,  0.0399424 ],
       [ 0.0625    ,  0.06772049],
       [ 0.125     ,  0.12748036],
       [ 0.25      ,  0.25094271],
       [ 0.375     ,  0.3754924 ],
       [ 0.5       ,  0.5003018 ],
       [ 0.75      ,  0.75014671],
       [ 1.        ,  1.00008644]])

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.999883 -0.075541 True
1 -0.750000 -0.749780 -0.075541 True
2 -0.500000 -0.499445 -0.075541 True
3 -0.375000 -0.373886 -0.075541 True
4 -0.250000 -0.246725 -0.075541 True
5 -0.187500 -0.179585 -0.075541 True
6 -0.156250 -0.141130 -0.075541 True
7 -0.140625 -0.117562 -0.075541 True
8 -0.125000 -0.085726 -0.075541 True
9 -0.109375 -0.029037 -0.075541 True
10 -0.101562 0.027118 -0.075541 True
11 -0.093750 0.137963 -0.075541 True
12 -0.089844 0.238488 -0.075541 True
13 -0.085938 0.394628 -0.075541 True
14 -0.082031 0.621580 -0.075541 True
15 -0.078125 0.859282 -0.075541 True
16 -0.076172 0.919863 -0.075541 True
17 -0.074219 0.908599 -0.075541 True
18 -0.070312 0.715006 -0.075541 True
19 -0.066406 0.478722 -0.075541 True
20 -0.062500 0.307779 -0.075541 True
21 -0.058594 0.199665 -0.075541 True
22 -0.054688 0.132275 -0.075541 True
23 -0.046875 0.061616 -0.075541 True
24 -0.039062 0.030834 -0.075541 True
25 -0.031250 0.017254 -0.075541 True
26 -0.015625 0.011476 -0.075541 True
27 0.000000 0.017222 -0.075541 True
28 0.031250 0.039942 -0.075541 True
29 0.062500 0.067720 -0.075541 True
30 0.125000 0.127480 -0.075541 True
31 0.250000 0.250943 -0.075541 True
32 0.375000 0.375492 -0.075541 True
33 0.500000 0.500302 -0.075541 True
34 0.750000 0.750147 -0.075541 True
35 1.000000 1.000086 -0.075541 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.