Skip to content

Commit

Permalink
fix: 💄 stylize
Browse files Browse the repository at this point in the history
  • Loading branch information
ivaquero committed Aug 16, 2024
1 parent 20fc7c2 commit 12b8d62
Show file tree
Hide file tree
Showing 47 changed files with 143 additions and 100 deletions.
4 changes: 2 additions & 2 deletions filters-kf-basic.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@
"metadata": {},
"outputs": [],
"source": [
"from numpy import random\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np"
"import numpy as np\n",
"from numpy import random"
]
},
{
Expand Down
3 changes: 1 addition & 2 deletions filters/bayes.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,7 @@ def prior_estimate(x0, model, zs, R, show_steps=False):
priors[i], estimates[i], ps[i] = prior, x.mean, x.var
if show_steps:
if i == 0:
print_header
print_steps(prior, z, x)
print_steps(prior, z, x)
if i == len(zs) - 1:
print_conclusion(z, x)
return (priors, estimates, ps)
Expand Down
3 changes: 2 additions & 1 deletion filters/fusion.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import sys

from numpy import random
import numpy as np
from numpy import random

from .helpers import KFSaver
from .kalman import KalmanFilter
from .kalman_ukf import UnscentedKalmanFilter
from .sigma_points import JulierSigmas


sys.path.append('..')
from models.const_vel import FCV

Expand Down
6 changes: 4 additions & 2 deletions filters/ghk.py
Original file line number Diff line number Diff line change
Expand Up @@ -490,7 +490,8 @@ def critical_damping_params(theta, order=2):
"""

if theta < 0 or theta > 1:
raise ValueError('theta must be between 0 and 1')
error_message = 'theta must be between 0 and 1'
raise ValueError(error_message)

if order == 2:
return (1.0 - theta**2, (1.0 - theta) ** 2)
Expand All @@ -502,7 +503,8 @@ def critical_damping_params(theta, order=2):
0.5 * (1 - theta) ** 3,
)

raise ValueError(f'bad order specified: {order}')
error_message = f'bad order specified: {order}'
raise ValueError(error_message)


def benedict_bornder_constants(g, critical=False):
Expand Down
2 changes: 1 addition & 1 deletion filters/ghq.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import numpy as np
from scipy import linalg
from scipy import stats
import numpy as np


def gh_packed_pc(x, fmm_param):
Expand Down
5 changes: 3 additions & 2 deletions filters/helpers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from collections import defaultdict
from collections import deque
from copy import deepcopy
import contextlib
from copy import deepcopy
import inspect

import numpy as np
Expand Down Expand Up @@ -75,7 +75,8 @@ def to_array(self, flatten=False):
except Exception as e:
# get back to lists so we are in a valid state
self.__dict__.update(self._DL)
raise ValueError(f'could not convert {key} into np.array') from e
error_message = f'could not convert {key} into np.array'
raise ValueError(error_message) from e
if flatten:
self.flatten()

Expand Down
11 changes: 7 additions & 4 deletions filters/imm.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ class IMMEstimator:
def __init__(self, filters, mu, M):
self.num_f = len(filters)
if self.num_f < 2:
raise ValueError('filters must contain at least two filters')
error_message = 'filters must contain at least two filters'
raise ValueError(error_message)

self.filters = filters
self.mu = np.asarray(mu) / np.sum(mu)
Expand Down Expand Up @@ -70,7 +71,7 @@ def predict(self, u=None):

# compute mixed initial conditions
xs, Ps = [], []
for i, (f, w) in enumerate(zip(self.filters, self.omega.T)):
for _, (_, w) in enumerate(zip(self.filters, self.omega.T)):
x = np.zeros(self.x.shape)
for kf, wj in zip(self.filters, w):
x += kf.x * wj
Expand Down Expand Up @@ -141,10 +142,12 @@ class MMAEFilterBank:

def __init__(self, filters, p, dim_x, H=None):
if len(filters) != len(p):
raise ValueError('length of filters and p must be the same')
error_message = 'length of filters and p must be the same'
raise ValueError(error_message)

if dim_x < 1:
raise ValueError('dim_x must be >= 1')
error_message = 'dim_x must be >= 1'
raise ValueError(error_message)

self.filters = filters
self.p = np.asarray(p)
Expand Down
29 changes: 18 additions & 11 deletions filters/kalman.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
from __future__ import annotations

from copy import deepcopy
from typing import Union
import math
import sys
from typing import Union

import numpy as np
from numpy import linalg
from scipy import stats
import numpy as np

from .helpers import pretty_str
from .transformers import reshape_z
Expand Down Expand Up @@ -65,11 +67,14 @@ def __init__(self, dim_x: int, dim_z: int, dim_u: int = 0, _alpha_sq: float = 1.
Dan Simon. "Optimal State Estimation." John Wiley & Sons. p. 208-212. (2006)
"""
if dim_x < 1:
raise ValueError('dim_x ≥ 1')
error_message = 'dim_x ≥ 1'
raise ValueError(error_message)
if dim_z < 1:
raise ValueError('dim_z ≥ 1')
error_message = 'dim_z ≥ 1'
raise ValueError(error_message)
if dim_u < 0:
raise ValueError('dim_u ≥ 0')
error_message = 'dim_u ≥ 0'
raise ValueError(error_message)

self.dim_x = dim_x
self.dim_z = dim_z
Expand Down Expand Up @@ -122,10 +127,10 @@ def __init__(self, dim_x: int, dim_z: int, dim_u: int = 0, _alpha_sq: float = 1.

def predict(
self,
F: Union[bool, np.ndarray] = None,
G: Union[bool, np.ndarray] = None,
u: Union[bool, np.array] = None,
Q: Union[bool, np.ndarray] = None,
F: bool | np.ndarray = None,
G: bool | np.ndarray = None,
u: bool | np.array = None,
Q: bool | np.ndarray = None,
):
"""Predict next state using the Kalman filter state propagation equations.
Expand Down Expand Up @@ -318,7 +323,8 @@ def rts_smoother(self, Xs, Ps, Fs=None, Qs=None, inv=linalg.inv):
means and covariances computed by a Kalman filter. The usual input would come from the output of `batch_filter()`.
"""
if len(Xs) != len(Ps):
raise ValueError('length of Xs and Ps must be the same')
error_message = 'length of Xs and Ps must be the same'
raise ValueError(error_message)

n = Xs.shape[0]
dim_x = Xs.shape[1]
Expand Down Expand Up @@ -402,7 +408,8 @@ def alpha(self):
@alpha.setter
def alpha(self, value):
if not np.isscalar(value) or value < 1:
raise ValueError('alpha must be a float greater than 1')
error_message = 'alpha must be a float greater than 1'
raise ValueError(error_message)

self._alpha_sq = value**2

Expand Down
2 changes: 1 addition & 1 deletion filters/kalman_ckf.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
import math
import sys

import numpy as np
from numpy import linalg
from scipy import stats
import numpy as np

from .helpers import pretty_str
from .sigma_points import SphericalRadialSigmas
Expand Down
5 changes: 2 additions & 3 deletions filters/kalman_ekf.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
from __future__ import annotations

from copy import deepcopy
from typing import Callable
from typing import Union
import math
import sys
from typing import Callable

import numpy as np
from numpy import linalg
from scipy import stats
import numpy as np

from .helpers import pretty_str
from .transformers import reshape_z
Expand Down
2 changes: 1 addition & 1 deletion filters/kalman_enkf.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from copy import deepcopy

import numpy as np
from numpy import linalg
from numpy import random
import numpy as np

from .helpers import pretty_str

Expand Down
3 changes: 2 additions & 1 deletion filters/kalman_fm.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ class FadingMemoryFilter:

def __init__(self, x0, dt, order, beta):
if order < 0 or order > 2:
raise ValueError('order must be between 0 and 2')
error_message = 'order must be between 0 and 2'
raise ValueError(error_message)

if np.isscalar(x0):
self.x = np.zeros(order + 1)
Expand Down
2 changes: 1 addition & 1 deletion filters/kalman_hinf.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from copy import deepcopy

from numpy import linalg
import numpy as np
from numpy import linalg

from .helpers import pretty_str

Expand Down
2 changes: 1 addition & 1 deletion filters/kalman_ukf.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
import math
import sys

import numpy as np
from numpy import linalg
from scipy import stats
import numpy as np

from .helpers import pretty_str
from .kalman import KalmanFilter
Expand Down
3 changes: 2 additions & 1 deletion filters/lsq.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ class LeastSquaresFilter:

def __init__(self, dt, order, noise_sigma=0.0):
if order < 0 or order > 2:
raise ValueError('order must be between 0 and 2')
error_message = 'order must be between 0 and 2'
raise ValueError(error_message)

self.dt = dt

Expand Down
2 changes: 1 addition & 1 deletion filters/particle.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import numpy as np
from numpy import random
from scipy import stats
import numpy as np


class ParticleFilter:
Expand Down
2 changes: 1 addition & 1 deletion filters/resamplers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from numpy import random
import numpy as np
from numpy import random


def resample_from_index(particles, weights, indexes):
Expand Down
17 changes: 10 additions & 7 deletions filters/sigma_points.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from scipy import linalg
import numpy as np
from scipy import linalg

from .helpers import pretty_str

Expand Down Expand Up @@ -50,7 +50,8 @@ def sigma_points(self, x, P):
"""

if self.n != np.size(x):
raise ValueError(f'expected size(x) {self.n}, but size is {np.size(x)}')
error_message = f'expected size(x) {self.n}, but size is {np.size(x)}'
raise ValueError(error_message)

n = self.n

Expand Down Expand Up @@ -121,7 +122,8 @@ def sigma_points(self, x, P):
"""

if self.n != np.size(x):
raise ValueError(f'expected size(x) {self.n}, but size is {np.size(x)}')
error_message = f'expected size(x) {self.n}, but size is {np.size(x)}'
raise ValueError(error_message)

if np.isscalar(x):
x = np.asarray([x])
Expand Down Expand Up @@ -205,7 +207,8 @@ def sigma_points(self, x, P):
"""

if self.n != np.size(x):
raise ValueError(f'expected size(x) {self.n}, but size is {np.size(x)}')
error_message = f'expected size(x) {self.n}, but size is {np.size(x)}'
raise ValueError(error_message)

n = self.n

Expand All @@ -220,9 +223,8 @@ def sigma_points(self, x, P):
Istar = np.array([[-1 / np.sqrt(2 * λ), 1 / np.sqrt(2 * λ)]])

for d in range(2, n + 1):
row = np.ones((1, Istar.shape[1] + 1)) * 1.0 / np.sqrt(λ * d * (d + 1)) # pylint: disable=unsubscriptable-object
row = np.ones((1, Istar.shape[1] + 1)) * 1.0 / np.sqrt(λ * d * (d + 1))
row[0, -1] = -d / np.sqrt(λ * d * (d + 1))
Istar = np.r_[np.c_[Istar, np.zeros((Istar.shape[0]))], row] # pylint: disable=unsubscriptable-object

_I = np.sqrt(n) * Istar
scaled_unitary = U.T @ _I
Expand Down Expand Up @@ -282,7 +284,8 @@ def sigma_points(self, x, P):
Arasaratnam, I, Haykin, S. "Cubature Kalman Filters," IEEE Transactions on Automatic Control, 2009, pp 1254-1269, vol 54, No 6
"""
if self.n != np.size(x):
raise ValueError(f'expected size(x) {self.n}, but size is {np.size(x)}')
error_message = f'expected size(x) {self.n}, but size is {np.size(x)}'
raise ValueError(error_message)

# dimension of P is
n = self.n
Expand Down
2 changes: 1 addition & 1 deletion filters/smoothers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from numpy import linalg
import numpy as np
from numpy import linalg

from .helpers import pretty_str
from .kalman import KalmanFilter
Expand Down
3 changes: 2 additions & 1 deletion filters/stats.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from collections import namedtuple

from numpy import linalg
import numpy as np
from numpy import linalg


gaussian = namedtuple('Gaussian', ['mean', 'var']) # noqa: PYI024
gaussian.__repr__ = lambda s: f'N(μ={s[0]:.3f}, σ²={s[1] ** 2:.3f})'
Expand Down
7 changes: 3 additions & 4 deletions filters/transformers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from scipy import linalg
import numpy as np
from scipy import linalg


def reshape_z(z, dim_z, ndim):
Expand Down Expand Up @@ -30,9 +30,8 @@ def reshape_z(z, dim_z, ndim):
z = z.T

if z.shape != (dim_z, 1):
raise ValueError(
f'z (shape {z.shape}) must be convertible to shape ({dim_z}, 1)'
)
error_message = f'z (shape {z.shape}) must be convertible to shape ({dim_z}, 1)'
raise ValueError(error_message)

if ndim == 1:
z = z[:, 0]
Expand Down
5 changes: 3 additions & 2 deletions models/const_acc.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import sys

from scipy import linalg
import numpy as np
from scipy import linalg

from .noise import white_noise_discrete


sys.path.append('..')
from filters.kalman import KalmanFilter

Expand Down Expand Up @@ -41,7 +42,7 @@ def FCA(dim, dt):
return F


def KFCA3d(P, R, Q=0, dt=1, x=[0, 0, 0]):
def KFCA3d(P, R, Q=0, dt=1, x=(0, 0, 0)):
if type(x) == list:
x = np.array(x)
dim_x = len(x)
Expand Down
Loading

0 comments on commit 12b8d62

Please sign in to comment.