bqplot and ipywidget slider, maximum recursion depth

482 Views Asked by At

If I execute the following Notebook everything seems to work fine. However, when I move the slider, the responsiveness of the notebook drops to almost to zero and after a while I get following error:

RecursionError: maximum recursion depth exceeded in comparison

Can you tell me why ?

# We'll start with bqplot's matplotlib inspired API

from bqplot import pyplot as plt

# Let's begin by importing some libraries we'll need
import numpy as np

import ipywidgets as wi

def make_data(x, sigma_noise):
    """
    Generates a sine wave

    :param x: x value, scalar or vector between 0 and ..
    :param sigma_noise: standard deviation of the noise added to the data
    """
    y = np.sin(x)
    noise = np.random.normal(loc=0, scale=sigma_noise, size=len(x))
    y_noise = y + noise   
    return y_noise


def update_plot(message):
    y_noise = make_data(x, slider.value)
    plot_1.y = y_noise

x = np.linspace(0, 10)
y = make_data(x, noise)

figure = plt.figure(title='Test', animation_duration=100)
#figure.animation_duration = 250
plot_1 = plt.scatter(x, y)
plot_1.observe(update_plot, ['x','y'])

slider = wi.FloatSlider(description='noise', value=0.001, min=0, max=1)
slider.observe(update_plot, 'value')

wi.VBox([slider, figure])

Edit: The Solution provided by DougR works. Additionally I found another solution: figure.observe(update_plot, ['x','y']) instead of plot_1.observe(update_plot, ['x','y'])

1

There are 1 best solutions below

1
On

You have an observe call on the plot1 figure which subsequently updates the plot1 figure... which results in a recursive loop. If you put an if statement in the function then it can be set so it only runs after the first operation only.

# We'll start with bqplot's matplotlib inspired API

from bqplot import pyplot as plt

# Let's begin by importing some libraries we'll need
import numpy as np

import ipywidgets as wi

def make_data(x, sigma_noise):
    """
    Generates a sine wave

    :param x: x value, scalar or vector between 0 and ..
    :param sigma_noise: standard deviation of the noise added to the data
    """
    y = np.sin(x)
    noise = np.random.normal(loc=0, scale=sigma_noise, size=len(x))
    y_noise = y + noise   
    return y_noise


def update_plot(message):
#     print(message)
    if message['name'] == 'value':
        y_noise = make_data(x, slider.value)
        plot_1.y = y_noise

noise = 2
x = np.linspace(0, 10)
y = make_data(x, noise)

figure = plt.figure(title='Test', animation_duration=100)
#figure.animation_duration = 250
plot_1 = plt.scatter(x, y)
plot_1.observe(update_plot, ['x','y'])

slider = wi.FloatSlider(description='noise', value=0.001, min=0, max=1)
slider.observe(update_plot, 'value')

wi.VBox([slider, figure])