Требуется помощь ползунка виджета Matplotlib - PullRequest
0 голосов
/ 23 апреля 2020

У меня проблемы с реализацией ползунка виджета matplotlib в мою структуру кода, и я был бы признателен за некоторые рекомендации.

У меня есть следующий график, и я хотел бы реализовать горизонтальный ползунок, управляющий переменной noise, которая изменяется кривые RTS и KF, как пользователь скользит:

enter image description here

Это мой код:

import numpy as np
from numpy import random
from numpy.random import randn
import matplotlib.pyplot as plt
from filterpy.kalman import KalmanFilter
from numpy import ma
from matplotlib.widgets import Slider
import pandas as pd

def rts_smoother(Xs, Ps, F, Q):
    n, dim_x, _ = Xs.shape

    # smoother gain
    K = zeros((n,dim_x, dim_x))
    x, P, Pp = Xs.copy(), Ps.copy(), Ps.copy

    for k in range(n-2,-1,-1):
        Pp[k] = dot(F, P[k]).dot(F.T) + Q # predicted covariance
        K[k]  = dot(P[k], F.T).dot(inv(Pp[k]))
        x[k] += dot(K[k], x[k+1] - dot(F, x[k]))
        P[k] += dot(K[k], P[k+1] - Pp[k]).dot(K[k].T)
    return (x, P, K, Pp)

def plot_obs(zs):
    plt.plot(zs, 'ko', label='Measurements', lw=1, mfc='none')
    plt.legend(loc=4)
    plt.show()
    #plt.ylim(180, 220)

def plot_rts(zs, noise, Q=0.001):
    random.seed(123)
    fk = KalmanFilter(dim_x=2, dim_z=1)
    fk.x = np.array([0., 1.])  # state (x and dx)
    fk.F = np.array([[1., 1.],
    [0., 1.]])  # state transition matrix

    fk.H = np.array([[1., 0.]])  # Measurement function
    fk.P = 10.  # covariance matrix
    fk.R = noise  # state uncertainty
    fk.Q = Q  # process uncertainty

    # filter data with Kalman filter, than run smoother on it
    mu, cov, _, _ = fk.batch_filter(zs)
    M, P, C, _ = fk.rts_smoother(mu, cov)
    plt.plot(M[:, 0], c='b', label='RTS')
    plt.plot(mu[:, 0], c='m', label='KF')
    plt.legend()
observations = np.asarray([t + randn()*7 for t in range (40)])
plot_obs(observations)
plot_rts(observations, 0.2)

, и это мой Начало попытки реализовать виджет:

noise_min = 0    # the minimial value of the paramater noise
noise_max = 10   # the maximal value of the paramater noise
noise_init = 1   # the value of the parameter noise to be used initially, when the graph is created

fig = plt.figure(figsize=(8,3))

# first we create the general layout of the figure
# with two axes objects: one for the plot of the function
# and the other for the slider
RTS_ax = plt.axes()
slider_ax = plt.axes()

# here we create the slider
noise_slider = Slider(slider_ax,      # the axes object containing the slider
                  'State Uncertainty',            # the name of the slider parameter
                  noise_min,          # minimal value of the parameter
                  noise_max,          # maximal value of the parameter
                  valinit = noise_init  # initial value of the parameter
                 )

Любая помощь очень ценится.

...