Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

non-neuron-dynamics approach #1

Open
Vejas04 opened this issue Aug 14, 2023 · 0 comments
Open

non-neuron-dynamics approach #1

Vejas04 opened this issue Aug 14, 2023 · 0 comments

Comments

@Vejas04
Copy link

Vejas04 commented Aug 14, 2023

Im kind of new and tried to build an RAUKF model with help of some papers and this python code. Maybe you have some paper suggestions on these RAUKF models with plant dynamics integration, because I have no clue what this is... So here comes my problem:
Traceback (most recent call last):
File "", line 137, in
ukf = Ukf(x0, P0, Q0, R0, kappa=0, sigma=0.5, robust=False)
File "", line 28, in init
self.initialize(x0, P0, Q0, R0)
File "", line 31, in initialize
self.x = np.zeros((self.t_sim, self.L))
TypeError: 'NoneType' object cannot be interpreted as an integer
I'm new to this and removed the neoron dynamics part, in order to be leftover with the pure RAUKF implementation. But Now Im getting this error, maybe it was due to my removals. Here the completed code:

import numpy as np
from scipy.stats.distributions import chi2
from scipy.linalg import sqrtm
from tqdm import tqdm

class Ukf:
"""Unscented Kalman Filter (UKF) estimator"""

def __init__(self, x0, P0, Q0, R0, kappa=0, sigma=0.5, robust=False):
    self.L = x0.shape[1]
    self.y = None
    self.u = None
    self.t_sim = None
    self.robust = robust

    if self.robust:
        self.lambda0 = 0.2
        self.a = 5.0
        self.delta0 = 0.2
        self.b = 5.0
        self.threshold = chi2.ppf(1 - sigma, df=self.y.shape[1])

    self.num_sp = 0
    self.kappa = kappa
    self.alphas = self.get_weights()

    self.initialize(x0, P0, Q0, R0)

def initialize(self, x0, P0, Q0, R0):
    self.x = np.zeros((self.t_sim, self.L))
    self.x[:] = np.nan
    self.x[[0]] = x0
    self.P = np.zeros((self.t_sim * self.L, self.L))
    self.P[:] = np.nan
    self.P[:self.L, :] = P0

    self.Q = Q0
    self.R = R0
    self.Q_diag = np.zeros((self.t_sim * self.L, self.L))
    self.Q_diag[:] = np.nan
    self.Q_diag[:self.L, :] = np.diag(self.Q)[None]

    self.R_diag = np.zeros((self.t_sim * len(self.R), len(self.R)))
    self.R_diag[:] = np.nan
    self.R_diag[:len(self.R), :] = np.diag(self.R)[None]

    self.phi = np.zeros([self.t_sim])
    self.phi[:] = np.nan
    self.mu = np.zeros([self.t_sim])
    self.mu[:] = np.nan

def get_weights(self):
    if self.kappa != 0:
        alphas = 0.5 / (self.L + self.kappa) * np.ones((2 * self.L + 1, 1))
        alphas[0] = self.kappa / (self.L + self.kappa)
        self.num_sp = 2 * self.L + 1
    else:
        alphas = 0.5 / self.L * np.ones((2 * self.L, 1))
        self.num_sp = 2 * self.L
    return alphas

def unscented_transform(self, P, x):
    P = (P + P.T) / 2.0
    sigma_root = np.linalg.cholesky((self.L + self.kappa) * P)
    sigmapoints = x.T * np.ones((2 * self.L, self.L)) + np.concatenate((sigma_root.T, -sigma_root.T))

    if self.kappa != 0:
        sigmapoint0 = x.T
        sigmapoints = np.concatenate((sigmapoint0, sigmapoints))

    return sigmapoints

def run_estimation(self, int_factor=1, resample=False, no_progress=False):
    N_slow = len(self.theta)
    N_fast = self.L - N_slow
    try:
        for k in tqdm(range(1, self.t_sim), disable=no_progress):
            ## PREDICTION STEP
            # Sample sigmapoints by passing in P_k_1 and x_k_1
            z_ = self.unscented_transform(self.P[self.L * (k - 1):self.L * k, :], self.x[[k - 1]].T)
            x_check_z = np.zeros_like(z_)  # transformed sigmapoints
            # Update parameters
            if self.theta:
                self.p[:, self.theta] = z_[:, N_fast:]
    except Exception as e:
        print(repr(e))
    finally:
        return self.x, self.P

def adapt_covariances(self, x_hat, P_hat, y_k, phi, innovation, K):
    """Adapt Q and R covariance matrices"""

    # Update Q
    lambda_ = np.max([self.lambda0, (phi - self.a * self.threshold) / phi])
    self.Q = (1 - lambda_) * self.Q + lambda_ * (K @ innovation.T @ innovation @ K.T)

    # Re-sample sigmapoints with new state estimate
    z = self.unscented_transform(P_hat, x_hat)
    x_cov_diff = z - x_hat.T

    y_check_z = self.plant.observe(z)
    mu_y = np.sum(self.alphas * y_check_z, axis=0, keepdims=True)
    yy_cov_diff = y_check_z - mu_y

    # Update R
    residual_y = y_k - self.plant.observe(x_hat.T)
    sigma_yy = (self.alphas * yy_cov_diff).T @ yy_cov_diff
    delta = np.max([self.delta0, (phi - self.b * self.threshold) / phi])
    self.R = (1 - delta) * self.R + delta * (residual_y @ residual_y.T + sigma_yy)

    # Correct estimates
    P_ = (self.alphas * x_cov_diff).T @ x_cov_diff + self.Q
    sigma_xy = (self.alphas * x_cov_diff).T @ yy_cov_diff
    sigma_yy = sigma_yy + self.R
    K_ = sigma_xy @ np.linalg.inv(sigma_yy)
    innovation_ = y_k - mu_y

    # Corrected beliefs
    x_hat = x_hat + K_ @ innovation_.T
    P_hat = P_ - K_ @ sigma_yy @ K_.T
    P_hat = (P_hat + P_hat.T) / 2.0

    return x_hat, P_hat

Define the dimensions

L = 1 # The state dimension

Initialize variables

x0 = np.random.rand(L, 1) # Initial state estimate
P0 = np.eye(L) # Initial covariance matrix
Q0 = np.eye(L) # Process noise covariance matrix
R0 = np.eye(1) # Measurement noise covariance matrix

Create the Ukf object

ukf = Ukf(x0, P0, Q0, R0, kappa=0, sigma=0.5, robust=False)
ukf.t_sim = len(np.array(measurements)) # Set the value of t_sim before initializing

Ukf.initialize(x0, P0, Q0, R0) # Initialize the UKF

Run the state estimation

x_estimated, P_estimated = ukf.run_estimation() Maybe you could help me out 💯

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant