Skip to content

Kalman Filter Module Documentation

This module provides functions to work with Kalman filters.

Functions:

Name Description
kf_lti_discretize

Discretize a Linear Time-Invariant (LTI) system using the matrix fraction decomposition.

kf_predict

Prediction step of the Kalman filter.

kf_update

Update step of the Kalman filter.

Classes:

Name Description
UUV_EKF

Extended Kalman Filter (EKF) class for uncrewed underwater vehicles.

Extended Kalman Filter (EKF) class for uncrewed underwater vehicles. This class implements the Extended Kalman Filter (EKF) algorithm for state estimation of an uncrewed underwater vehicle using AHRS, DVL, Depth sensors, and USBL asynchronous measurements.

State Vector Structure

[t, x, y, z, qx, qy, qz, qw, vx, vy, vz, wx, wy, wz, bh (optional)] - t: Timestamp - x, y, z: Position in the world frame - qx, qy, qz, qw: Quaternion representing orientation - vx, vy, vz: Linear velocity in the world frame - wx, wy, wz: Angular velocity in the body frame - bh: Bottom height (optional, if enabled)

Extended Kalman Filter (EKF) class.

This class implements the Extended Kalman Filter (EKF) algorithm for state estimation of an uncrewed underwater vehicle using AHRS, DVL and Depth sensor asynchronous measurements.

Parameters:

Name Type Description Default
bottom_height bool

If True, the EKF will estimate the bottom height. If False, the EKF will not estimate the bottom height.

False
covariance_dvl_velocity Union[float, ndarray, List[float]]

Covariance for DVL velocity measurements. It must be a float or a (3, ) array. If it is a float, it will be used as a scaling factor for the identity matrix. If it is a (3, ) array, it will be used as the diagonal of the covariance matrix.

0.01
covariance_dvl_bottom_height float

Covariance for DVL bottom height measurements.

0.01
covariance_ahrs_quaternion float

Covariance for AHRS quaternion measurements. It must be a (3, ) array. If it is a float, it will be used as a scaling factor for the identity matrix. If it is a (3, ) array, it will be used as the diagonal of the covariance matrix. It uses the small angle approximation, where the covariance for qx, qy, qz is approximated with the covariance for roll, pitch and yaw angles.

0.1
covariance_ahrs_angular_rate Union[float, ndarray, List[float]]

Covariance for AHRS angular rate measurements. It must be a float or a (3, ) array. If it is a float, it will be used as a scaling factor for the identity matrix. If it is a (3, ) array, it will be used as the diagonal of the covariance matrix.

0.1
covariance_depth float

Covariance for depth measurements.

0.001
covariance_position Union[float, ndarray, List[float]]

Covariance for position measurements. It must be a float or a (2, ) array. If it is a float, it will be used as a scaling factor for the identity matrix. If it is a (2, ) array, it will be used as the diagonal of the covariance matrix.

10.0
process_noise_velocity float

Process noise covariance for velocity. This value will scale an identity 3x3 matrix. The default value is 0.001. Guidance to tune this value is in the note below.

0.001
Note

The process noise covariance for velocity is a scaling factor for the identity matrix. This value is used to propagate the velocity, position and bottom height (if enabled) states. An initial guess for this value for a DVL with a typical standard deviation of >=1%. The magnitude for this value can be computed based on a magnitude computation based on the following equation:

\[ Q_{v}^0 \propto \frac{y_{dvl}^2}{n \cdot dt} \]

Where, \(y_{dvl}\) is the average innovation for the DVL, \(n\) is the number predictions between correction steps and \(dt\) is the time step of the predictions.

Source code in navlib/nav/kalman_filter.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
def __init__(
    self,
    bottom_height: bool = False,
    covariance_dvl_velocity: Union[float, np.ndarray, List[float]] = 0.01,
    covariance_dvl_bottom_height: float = 0.01,
    covariance_ahrs_quaternion: Union[float, np.ndarray, List[float]] = 0.1,
    covariance_ahrs_angular_rate: Union[float, np.ndarray, List[float]] = 0.1,
    covariance_depth: float = 0.001,
    covariance_position: Union[float, np.ndarray, List[float]] = 10.0,
    process_noise_velocity: float = 0.001,
) -> None:
    """
    Extended Kalman Filter (EKF) class.

    This class implements the Extended Kalman Filter (EKF) algorithm for state estimation
    of an uncrewed underwater vehicle using AHRS, DVL and Depth sensor asynchronous measurements.

    Args:
        bottom_height (bool): If True, the EKF will estimate the bottom height.
            If False, the EKF will not estimate the bottom height.
        covariance_dvl_velocity (Union[float, np.ndarray, List[float]]): Covariance for DVL velocity measurements.
            It must be a float or a (3, ) array. If it is a float, it will be used as a scaling factor for the
            identity matrix. If it is a (3, ) array, it will be used as the diagonal of the covariance matrix.
        covariance_dvl_bottom_height (float): Covariance for DVL bottom height measurements.
        covariance_ahrs_quaternion (float): Covariance for AHRS quaternion measurements. It must be a (3, ) array.
            If it is a float, it will be used as a scaling factor for the identity matrix. If it is a (3, ) array,
            it will be used as the diagonal of the covariance matrix. It uses the small angle approximation, where
            the covariance for qx, qy, qz is approximated with the covariance for roll, pitch and yaw angles.
        covariance_ahrs_angular_rate (Union[float, np.ndarray, List[float]]): Covariance for AHRS angular rate measurements.
            It must be a float or a (3, ) array. If it is a float, it will be used as a scaling factor for the
            identity matrix. If it is a (3, ) array, it will be used as the diagonal of the covariance matrix.
        covariance_depth (float): Covariance for depth measurements.
        covariance_position (Union[float, np.ndarray, List[float]]): Covariance for position measurements.
            It must be a float or a (2, ) array. If it is a float, it will be used as a scaling factor for the
            identity matrix. If it is a (2, ) array, it will be used as the diagonal of the covariance matrix.
        process_noise_velocity (float): Process noise covariance for velocity. This value will scale an identity 3x3
            matrix. The default value is 0.001. Guidance to tune this value is in the note below.

    Note:
        The process noise covariance for velocity is a scaling factor for the identity matrix. This value is used to
        propagate the velocity, position and bottom height (if enabled) states. An initial guess for this value for
        a DVL with a typical standard deviation of >=1%. The magnitude for this value can be computed based on a magnitude
        computation based on the following equation:

        $$ Q_{v}^0 \\propto \\frac{y_{dvl}^2}{n \\cdot dt} $$

        Where, $y_{dvl}$ is the average innovation for the DVL, $n$ is the number predictions between correction steps
        and $dt$ is the time step of the predictions.
    """
    # Convert to a numpy arrays if they are lists
    if isinstance(covariance_dvl_velocity, list):
        covariance_dvl_velocity = np.array(covariance_dvl_velocity)
    if isinstance(covariance_ahrs_quaternion, list):
        covariance_ahrs_quaternion = np.array(covariance_ahrs_quaternion)
    if isinstance(covariance_ahrs_angular_rate, list):
        covariance_ahrs_angular_rate = np.array(covariance_ahrs_angular_rate)
    if isinstance(covariance_position, list):
        covariance_position = np.array(covariance_position)

    # Types checking
    if not isinstance(bottom_height, bool):
        raise TypeError("bottom_height must be a boolean")
    if not isinstance(covariance_dvl_velocity, (float, np.ndarray, list)):
        raise TypeError("covariance_dvl_velocity must be a float or a (3, ) array")
    if not isinstance(covariance_dvl_velocity, float):
        covariance_dvl_velocity = covariance_dvl_velocity.squeeze()
        if covariance_dvl_velocity.ndim != 1:
            raise ValueError("covariance_dvl_velocity must be a (3, ) array")
        if covariance_dvl_velocity.shape[0] != 3:
            raise ValueError("covariance_dvl_velocity must be a (3, ) array")
    if not isinstance(covariance_dvl_bottom_height, float):
        raise TypeError("covariance_dvl_bottom_height must be a float")
    if not isinstance(covariance_ahrs_quaternion, (float, np.ndarray)):
        raise TypeError(
            "covariance_ahrs_quaternion must be a float or a (3, ) array"
        )
    if not isinstance(covariance_ahrs_angular_rate, (float, np.ndarray)):
        raise TypeError(
            "covariance_ahrs_angular_rate must be a float or a (3, ) array"
        )
    if not isinstance(covariance_ahrs_angular_rate, float):
        covariance_ahrs_angular_rate = covariance_ahrs_angular_rate.squeeze()
        if covariance_ahrs_angular_rate.ndim != 1:
            raise ValueError("covariance_ahrs_angular_rate must be a (3, ) array")
        if covariance_ahrs_angular_rate.shape[0] != 3:
            raise ValueError("covariance_ahrs_angular_rate must be a (3, ) array")
    if not isinstance(covariance_ahrs_quaternion, float):
        covariance_ahrs_quaternion = covariance_ahrs_quaternion.squeeze()
        if covariance_ahrs_quaternion.ndim != 1:
            raise ValueError("covariance_ahrs_quaternion must be a (3, ) array")
        if covariance_ahrs_quaternion.shape[0] != 3:
            raise ValueError("covariance_ahrs_quaternion must be a (3, ) array")
    if not isinstance(covariance_depth, float):
        raise TypeError("covariance_depth must be a float")
    if not isinstance(covariance_position, (float, np.ndarray)):
        raise TypeError("covariance_position must be a float or a (2, ) array")
    if not isinstance(covariance_position, float):
        covariance_position = covariance_position.squeeze()
        if covariance_position.ndim != 1:
            raise ValueError("covariance_position must be a (2, ) array")
        if covariance_position.shape[0] != 2:
            raise ValueError("covariance_position must be a (2, ) array")

    # State Vector: [t, x, y, z, qx, qy, qz, qw, vx, vy, vz, wx, wy, wz, bh (optional)]
    self._current_state = np.r_[np.zeros(7), np.ones(1), np.zeros(6)]
    if bottom_height:
        self._current_state = np.r_[self._current_state, np.zeros(1)]
    self._state_dim = (
        self._current_state.shape[0] - 1
    )  # state dim doesn't include time

    # Process noise covariance
    self._q0_velocity = process_noise_velocity * np.eye(3, dtype=np.float64)

    # Measurements
    # XY position - Measurement model matrix
    H_position = np.zeros((2, self.state_dim))
    H_position[:, :2] = np.eye(2, dtype=np.float64)
    self._H_position = H_position
    # XY position - Measurement noise covariance
    if isinstance(covariance_position, float):
        self._R_position = np.eye(2, dtype=np.float64) * covariance_position
    else:
        self._R_position = np.diag(covariance_position)
    # Depth - Measurement model matrix
    H_depth = np.zeros((1, self.state_dim))
    H_depth[0, 2] = 1
    self._H_depth = H_depth
    # Depth - Measurement noise covariance
    self._R_depth = np.eye(1, dtype=np.float64) * covariance_depth
    # Attitude - Measurement model matrix
    H_attitude = np.zeros((3, self.state_dim))
    H_attitude[:, 3:6] = np.eye(3, dtype=np.float64)
    self._H_attitude = H_attitude
    # Attitude - Measurement noise covariance
    # Quaternion covariance: we will use the small angle approximation;
    # therefore, we will use the covariance of roll, pitch and yaw angles
    # and leave the scalar component as 0.0.
    self._R_attitude = np.zeros((3, 3), dtype=np.float64)
    if isinstance(covariance_ahrs_quaternion, float):
        self._R_attitude = np.eye(3, dtype=np.float64) * covariance_ahrs_quaternion
    else:
        self._R_attitude = np.diag(covariance_ahrs_quaternion)
    # Angular rates - Measurement model matrix
    H_angrate = np.zeros((3, self.state_dim))
    H_angrate[:, 10:13] = np.eye(3, dtype=np.float64)
    self._H_angrate = H_angrate
    # Angular rate - Measurement noise covariance
    self._R_angrate = np.zeros((3, 3), dtype=np.float64)
    if isinstance(covariance_ahrs_angular_rate, float):
        self._R_angrate = np.eye(3, dtype=np.float64) * covariance_ahrs_angular_rate
    else:
        self._R_angrate = np.diag(covariance_ahrs_angular_rate)
    # Linear velocity - Measurement model matrix
    H_vel = np.zeros((3, self.state_dim))
    H_vel[:, 7:10] = np.eye(3, dtype=np.float64)
    self._H_vel = H_vel
    # Linear velocity - Measurement noise covariance
    if isinstance(covariance_dvl_velocity, float):
        self._R_vel = np.eye(3, dtype=np.float64) * covariance_dvl_velocity
    else:
        self._R_vel = np.diag(covariance_dvl_velocity)
    # Bottom height - Measurement model matrix
    H_bottom_height = np.zeros((1, self.state_dim))
    H_bottom_height[0, -1] = 1
    self._H_bottom_height = H_bottom_height
    # Bottom height - Measurement noise covariance
    self._R_bottom_height = (
        np.eye(1, dtype=np.float64) * covariance_dvl_bottom_height
    )

    # Velocity Filtering
    self._velocity_d_squared_acummulted = 0.0
    self._velocity_d_squared_count = 0
    self._velocity_q_tuner = _QTuner()

    # Maximum time step considered stable for EKF prediction
    self._max_stable_time_step = 5.0

    # Process noise covariance
    initial_dt = 0.01
    self._current_covariance = self._process_noise_covariance(initial_dt)

Get the measurement model matrix for angular rates.

Returns:

Name Type Description
H_angrate ndarray

Measurement model matrix for angular rates.

Get the measurement model matrix for attitude.

Returns:

Name Type Description
H_attitude ndarray

Measurement model matrix for attitude.

Get the measurement model matrix for bottom height.

Returns:

Name Type Description
H_bottom_height ndarray

Measurement model matrix for bottom height.

Get the measurement model matrix for depth.

Returns:

Name Type Description
H_depth ndarray

Measurement model matrix for depth.

Get the measurement model matrix for cartesian position.

Returns:

Name Type Description
H_position ndarray

Measurement model matrix for cartesian position.

Get the measurement model matrix for linear velocity.

Returns:

Name Type Description
H_vel ndarray

Measurement model matrix for linear velocity.

Get the measurement noise covariance for angular rates.

Returns:

Name Type Description
R_angrate ndarray

Measurement noise covariance for angular rates.

Get the measurement noise covariance for attitude.

Returns:

Name Type Description
R_attitude ndarray

Measurement noise covariance for attitude.

Get the measurement noise covariance for bottom height.

Returns:

Name Type Description
R_bottom_height ndarray

Measurement noise covariance for bottom height.

Get the measurement noise covariance for depth.

Returns:

Name Type Description
R_depth ndarray

Measurement noise covariance for depth.

Get the measurement noise covariance for cartesian position.

Returns:

Name Type Description
R_position ndarray

Measurement noise covariance for cartesian position.

Get the measurement noise covariance for linear velocity.

Returns:

Name Type Description
R_vel ndarray

Measurement noise covariance for linear velocity.

Get the current covariance (\(P_t\)) of the EKF.

Returns:

Name Type Description
current_covariance ndarray

Current covariance matrix.

Get the current state (\(x_t\)) of the EKF.

Returns:

Name Type Description
current_state ndarray

Current state vector.

Get the dimension of the state vector.

Returns:

Name Type Description
state_dim int

Dimension of the state vector.

Correct the state of the EKF using angular velocity measurements.

Parameters:

Name Type Description Default
angular_velocity Union[List[Union[int, float]], ndarray]

Angular velocity measurement.

required
measurement_covariance ndarray

Optional custom measurement covariance matrix. If this is provided, it will override the default measurement noise covariance provided in the constructor.

None
Source code in navlib/nav/kalman_filter.py
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
def correction_angular_rate(
    self,
    angular_velocity: Union[List[Union[int, float]], np.ndarray],
    measurement_covariance: np.ndarray = None,
) -> None:
    """
    Correct the state of the EKF using angular velocity measurements.

    Args:
        angular_velocity (Union[List[Union[int, float]], np.ndarray]): Angular velocity measurement.
        measurement_covariance (np.ndarray): Optional custom measurement covariance matrix. If this is provided,
            it will override the default measurement noise covariance provided in the constructor.
    """
    # Convert to numpy array
    if isinstance(angular_velocity, list):
        angular_velocity = np.array(angular_velocity)

    # Check inputs type
    if not isinstance(angular_velocity, np.ndarray):
        raise TypeError("Angular velocity must be a numpy array")
    angular_velocity = angular_velocity.squeeze()
    if angular_velocity.ndim != 1:
        raise ValueError("Angular velocity must be a 1D array")
    if angular_velocity.shape[0] != 3:
        raise ValueError("Angular velocity must have 3 elements")
    if measurement_covariance is not None:
        if not isinstance(measurement_covariance, np.ndarray):
            raise TypeError("Measurement covariance must be a numpy array")
        if measurement_covariance.ndim != 2:
            raise ValueError("Measurement covariance must be a 2D matrix")
        if measurement_covariance.shape[0] != measurement_covariance.shape[1]:
            raise ValueError("Measurement covariance must be a square matrix")

    # Measurement (z, shape=(3, 1))
    z = np.vstack(angular_velocity)

    # Innovation or residual (y, shape=(3, 1))
    y = z - self._H_angrate @ np.vstack(self._current_state[1:])

    # Measurement noise covariance (R, shape=(3, 3))
    if measurement_covariance is None:
        R = self._R_angrate
    else:
        if measurement_covariance.shape[0] != z.shape[0]:
            raise ValueError(
                "Measurement covariance must have the same number of rows as the measurement"
            )
        R = measurement_covariance

    # Measurement prediction covariance (S, shape=(3, 3))
    S = self._H_angrate @ self._current_covariance @ self._H_angrate.T + R
    S_inv = np.linalg.inv(S)

    # Kalman gain (K, shape=(n, 3))
    K = self._current_covariance @ self._H_angrate.T @ S_inv

    # Update state estimate (x, shape=(n, 1))
    self._current_state[1:] = np.squeeze(np.vstack(self._current_state[1:]) + K @ y)

    # Normalize quaternion and force it to have positive scalar part
    self._check_state_attitude()

    # Update covariance estimate (P, shape=(n, n))
    self._current_covariance = (
        np.eye(self._state_dim, dtype=np.float64) - K @ self._H_angrate
    ) @ self._current_covariance
    self._symmetrize_covariance()

Correct the state of the EKF using orientation measurements.

Parameters:

Name Type Description Default
quaternion Union[List[Union[int, float]], ndarray]

Quaternion measurement. Order: (x, y, z, w).

required
measurement_covariance ndarray

Optional custom measurement covariance matrix. If this is provided, it will override the default measurement noise covariance provided in the constructor.

None
Source code in navlib/nav/kalman_filter.py
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
def correction_attitude(
    self,
    quaternion: Union[List[Union[int, float]], np.ndarray],
    measurement_covariance: np.ndarray = None,
) -> None:
    """
    Correct the state of the EKF using orientation measurements.

    Args:
        quaternion (Union[List[Union[int, float]], np.ndarray]): Quaternion measurement. Order: (x, y, z, w).
        measurement_covariance (np.ndarray): Optional custom measurement covariance matrix. If this is provided,
            it will override the default measurement noise covariance provided in the constructor.
    """
    # Convert to numpy array
    if isinstance(quaternion, list):
        quaternion = np.array(quaternion)

    # Check inputs type
    if not isinstance(quaternion, np.ndarray):
        raise TypeError("Quaternion must be a numpy array")
    quaternion = quaternion.squeeze()
    if quaternion.ndim != 1:
        raise ValueError("Quaternion must be a 1D array")
    if quaternion.shape[0] != 4:
        raise ValueError("Quaternion must have 4 elements")
    if np.abs(norm(quaternion) - 1.0) > 1e-6:
        raise ValueError("Quaternion must be a unit quaternion")
    if measurement_covariance is not None:
        if not isinstance(measurement_covariance, np.ndarray):
            raise TypeError("Measurement covariance must be a numpy array")
        if measurement_covariance.ndim != 2:
            raise ValueError("Measurement covariance must be a 2D matrix")
        if measurement_covariance.shape[0] != measurement_covariance.shape[1]:
            raise ValueError("Measurement covariance must be a square matrix")

    # Force the input quaternion to be unit and with a positive scalar part
    quaternion /= norm(quaternion)
    if quaternion[3] < 0:
        quaternion *= -1

    # Use relative quaternion error and extract small angle error
    q_est = self._current_state[4:8]
    q_meas = quaternion

    # Quaternion residual
    delta_q = left_qmatrix(quat_conj(q_est)) @ q_meas
    delta_theta = 2 * delta_q[:3]  # Small angle approximation

    # Innovation or residual (y, shape=(3, 1))
    y = np.vstack(delta_theta)

    # Measurement noise covariance (R, shape=(3, 3))
    if measurement_covariance is None:
        R = self._R_attitude
    else:
        if measurement_covariance.shape[0] != y.shape[0]:
            raise ValueError(
                "Measurement covariance must have the same number of rows as the innovation"
            )
        R = measurement_covariance

    # Measurement prediction covariance (S, shape=(4, 4))
    S = self._H_attitude @ self._current_covariance @ self._H_attitude.T + R
    S_inv = np.linalg.inv(S)

    # Kalman gain (K, shape=(n, 4))
    K = self._current_covariance @ self._H_attitude.T @ S_inv

    # Update state estimate (x, shape=(n, 1))
    self._current_state[1:] = np.squeeze(np.vstack(self._current_state[1:]) + K @ y)

    # Normalize quaternion and force it to have positive scalar part
    self._check_state_attitude()

    # Update covariance estimate (P, shape=(n, n))
    self._current_covariance = (
        np.eye(self._state_dim, dtype=np.float64) - K @ self._H_attitude
    ) @ self._current_covariance
    self._symmetrize_covariance()

Correct the state of the EKF using bottom height measurements.

Parameters:

Name Type Description Default
bottom_height Union[float, int]

Bottom height measurement.

required
scaling_strength Union[float, int]

Scaling strength for the adaptive measurement noise covariance. scale_factor = np.exp(scaling_strength * (d_squared / threshold - 1.0))

1.0
threshold float

Threshold for the adaptive measurement noise covariance indicating the confidence level. The default value is 0.99, which corresponds to a 99% confidence level.

0.99
measurement_covariance ndarray

Optional custom measurement covariance matrix. If this is provided, it will override the default measurement noise covariance provided in the constructor.

None

Returns:

Name Type Description
d_squared float

Mahalanobis distance squared.

success bool

True if the correction was used, False if the correction was scaled.

Raises:

Type Description
TypeError

If bottom_height, scaling_strength or threshold are not of the expected type.

ValueError

If threshold is not between 0.0 and 1.0.

Source code in navlib/nav/kalman_filter.py
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
def correction_bottom_height(
    self,
    bottom_height: Union[float, int],
    scaling_strength: Union[float, int] = 1.0,
    threshold: float = 0.99,
    measurement_covariance: np.ndarray = None,
) -> Tuple[float, bool]:
    """
    Correct the state of the EKF using bottom height measurements.

    Args:
        bottom_height (Union[float, int]): Bottom height measurement.
        scaling_strength (Union[float, int]): Scaling strength for the adaptive measurement noise covariance.
            scale_factor = np.exp(scaling_strength * (d_squared / threshold - 1.0))
        threshold (float): Threshold for the adaptive measurement noise covariance indicating the confidence level.
            The default value is 0.99, which corresponds to a 99% confidence level.
        measurement_covariance (np.ndarray): Optional custom measurement covariance matrix. If this is provided,
            it will override the default measurement noise covariance provided in the constructor.

    Returns:
        d_squared (float): Mahalanobis distance squared.
        success (bool): True if the correction was used, False if the correction was scaled.

    Raises:
        TypeError: If bottom_height, scaling_strength or threshold are not of the expected type.
        ValueError: If threshold is not between 0.0 and 1.0.
    """
    # Check typing
    if not isinstance(bottom_height, (float, int)):
        raise TypeError("Bottom height must be a float or an int")
    if not isinstance(scaling_strength, (float, int)):
        raise TypeError("Scaling strength must be a float or an int")
    if not isinstance(threshold, (float, int)):
        raise TypeError("Threshold must be a float or an int")
    if threshold <= 0.0 or threshold >= 1.0:
        raise ValueError("Threshold must be between 0.0 and 1.0")
    if measurement_covariance is not None:
        if not isinstance(measurement_covariance, np.ndarray):
            raise TypeError("Measurement covariance must be a numpy array")
        if measurement_covariance.ndim != 2:
            raise ValueError("Measurement covariance must be a 2D matrix")
        if measurement_covariance.shape[0] != measurement_covariance.shape[1]:
            raise ValueError("Measurement covariance must be a square matrix")

    if self._state_dim != 14:
        return np.nan, False

    # Measurement (z, shape=(1, 1))
    z = np.array([[bottom_height]])

    # Measurement covariance
    if measurement_covariance is None:
        R = self._R_bottom_height
    else:
        if measurement_covariance.shape[0] != z.shape[0]:
            raise ValueError(
                "Measurement covariance must have the same number of rows as the measurement"
            )
        R = measurement_covariance

    # H matrix
    H = self._H_bottom_height

    # Innovation or residual (y, shape=(1, 1))
    y = z - H @ np.vstack(self._current_state[1:])

    # Innovation covariance
    S = H @ self._current_covariance @ H.T + R

    # Mahalanobis distance-based adaptive covariance matrix scaling
    S_inv, d_squared, scaled = self._adaptive_covariance(
        y, S, R, threshold, scaling_strength
    )

    # Kalman gain (K, shape=(n, 1))
    K = self._current_covariance @ H.T @ S_inv

    # Update state estimate (x, shape=(n, 1) or (n, 4))
    self._current_state[1:] = np.squeeze(np.vstack(self._current_state[1:]) + K @ y)

    # Update covariance estimate (P, shape=(n, n))
    self._current_covariance = (
        np.eye(self._state_dim, dtype=np.float64) - K @ H
    ) @ self._current_covariance
    self._symmetrize_covariance()

    # Normalize quaternion and force it to have positive scalar part
    self._check_state_attitude()

    return d_squared, scaled

Correct the state of the EKF using depth measurements.

Parameters:

Name Type Description Default
z Union[float, int]

Depth measurement.

required
scaling_strength Union[float, int]

Scaling strength for the adaptive measurement noise covariance. scale_factor (Union[float, int]) = np.exp(scaling_strength * (d_squared / threshold - 1.0))

1.0
threshold float

Threshold for the adaptive measurement noise covariance indicating the confidence level. The default value is 0.99, which corresponds to a 99% confidence level.

0.99
measurement_covariance ndarray

Optional custom measurement covariance matrix. If this is provided, it will override the default measurement noise covariance provided in the constructor.

None

Returns:

Name Type Description
d_squared float

Mahalanobis distance squared.

success bool

True if the correction was used, False if the correction was scaled.

Raises:

Type Description
TypeError

If timestamp, z, scaling_strength or threshold are not of the expected type.

ValueError

If threshold is not between 0.0 and 1.0.

Source code in navlib/nav/kalman_filter.py
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
def correction_depth(
    self,
    z: Union[float, int],
    scaling_strength: Union[float, int] = 1.0,
    threshold: float = 0.99,
    measurement_covariance: np.ndarray = None,
) -> Tuple[float, bool]:
    """
    Correct the state of the EKF using depth measurements.

    Args:
        z (Union[float, int]): Depth measurement.
        scaling_strength (Union[float, int]): Scaling strength for the adaptive measurement noise covariance.
            scale_factor (Union[float, int]) = np.exp(scaling_strength * (d_squared / threshold - 1.0))
        threshold (float): Threshold for the adaptive measurement noise covariance indicating the confidence level.
            The default value is 0.99, which corresponds to a 99% confidence level.
        measurement_covariance (np.ndarray): Optional custom measurement covariance matrix. If this is provided,
            it will override the default measurement noise covariance provided in the constructor.

    Returns:
        d_squared (float): Mahalanobis distance squared.
        success (bool): True if the correction was used, False if the correction was scaled.

    Raises:
        TypeError: If timestamp, z, scaling_strength or threshold are not of the expected type.
        ValueError: If threshold is not between 0.0 and 1.0.
    """
    # Check typing
    if not isinstance(z, (float, int)):
        raise TypeError("Z position must be a float or an int")
    if not isinstance(scaling_strength, (float, int)):
        raise TypeError("Scaling strength must be a float or an int")
    if not isinstance(threshold, (float, int)):
        raise TypeError("Threshold must be a float or an int")
    if threshold <= 0.0 or threshold >= 1.0:
        raise ValueError("Threshold must be between 0.0 and 1.0")
    if measurement_covariance is not None:
        if not isinstance(measurement_covariance, np.ndarray):
            raise TypeError("Measurement covariance must be a numpy array")
        if measurement_covariance.ndim != 2:
            raise ValueError("Measurement covariance must be a 2D matrix")
        if measurement_covariance.shape[0] != measurement_covariance.shape[1]:
            raise ValueError("Measurement covariance must be a square matrix")

    # Measurement (z, shape=(1, 1))
    z = np.array([[z]])

    # Measurement covariance
    if measurement_covariance is None:
        R = self._R_depth
    else:
        if measurement_covariance.shape[0] != z.shape[0]:
            raise ValueError(
                "Measurement covariance must have the same number of rows as the measurement"
            )
        R = measurement_covariance

    # H matrix
    H = self._H_depth

    # Innovation or residual (y, shape=(1, 1))
    y = z - H @ np.vstack(self._current_state[1:])

    # Innovation covariance
    S = H @ self._current_covariance @ H.T + R

    # Mahalanobis distance-based adaptive covariance matrix scaling
    S_inv, d_squared, scaled = self._adaptive_covariance(
        y, S, R, threshold, scaling_strength
    )

    # Kalman gain (K, shape=(n, 1))
    K = self._current_covariance @ H.T @ S_inv

    # Update state estimate (x, shape=(n, 1))
    self._current_state[1:] = np.squeeze(np.vstack(self._current_state[1:]) + K @ y)

    # Update covariance estimate (P, shape=(n, n))
    self._current_covariance = (
        np.eye(self._state_dim, dtype=np.float64) - K @ H
    ) @ self._current_covariance
    self._symmetrize_covariance()

    # Normalize quaternion and force it to have positive scalar part
    self._check_state_attitude()

    return d_squared, scaled

Correct the state of the EKF using position measurements.

Parameters:

Name Type Description Default
x Union[float, int]

X position measurement.

required
y Union[float, int]

Y position measurement.

required
scaling_strength Union[float, int]

Scaling strength for the adaptive measurement noise covariance. scale_factor = np.exp(scaling_strength * (d_squared / threshold - 1.0))

1.0
threshold float

Threshold for the adaptive measurement noise covariance indicating the confidence level. The default value is 0.99, which corresponds to a 99% confidence level. This ensures that measurements falling within the 99% confidence region are trusted, while outliers are adaptively scaled.

0.99
measurement_covariance ndarray

Optional custom measurement covariance matrix. If this is provided, it will override the default measurement noise covariance provided in the constructor.

None

Returns:

Name Type Description
d_squared float

Mahalanobis distance squared.

success bool

True if the correction was used, False if the correction was scaled.

Raises:

Type Description
TypeError

If timestamp, x, y, scaling_strength or threshold are not of the expected type.

ValueError

If threshold is not between 0.0 and 1.0.

Source code in navlib/nav/kalman_filter.py
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
def correction_position_xy(
    self,
    x: Union[float, int],
    y: Union[float, int],
    scaling_strength: Union[float, int] = 1.0,
    threshold: float = 0.99,
    measurement_covariance: np.ndarray = None,
) -> Tuple[float, bool]:
    """
    Correct the state of the EKF using position measurements.

    Args:
        x (Union[float, int]): X position measurement.
        y (Union[float, int]): Y position measurement.
        scaling_strength (Union[float, int]): Scaling strength for the adaptive measurement noise covariance.
            scale_factor =  np.exp(scaling_strength * (d_squared / threshold - 1.0))
        threshold (float): Threshold for the adaptive measurement noise covariance indicating the confidence level.
            The default value is 0.99, which corresponds to a 99% confidence level. This ensures that measurements
            falling within the 99% confidence region are trusted, while outliers are adaptively scaled.
        measurement_covariance (np.ndarray): Optional custom measurement covariance matrix. If this is provided,
            it will override the default measurement noise covariance provided in the constructor.

    Returns:
        d_squared (float): Mahalanobis distance squared.
        success (bool): True if the correction was used, False if the correction was scaled.

    Raises:
        TypeError: If timestamp, x, y, scaling_strength or threshold are not of the expected type.
        ValueError: If threshold is not between 0.0 and 1.0.
    """
    # Check typing
    if not isinstance(x, (float, int)):
        raise TypeError("X position must be a float or an int")
    if not isinstance(y, (float, int)):
        raise TypeError("Y position must be a float or an int")
    if not isinstance(scaling_strength, (float, int)):
        raise TypeError("Scaling strength must be a float or an int")
    if not isinstance(threshold, (float, int)):
        raise TypeError("Threshold must be a float or an int")
    if threshold <= 0.0 or threshold >= 1.0:
        raise ValueError("Threshold must be between 0.0 and 1.0")
    if measurement_covariance is not None:
        if not isinstance(measurement_covariance, np.ndarray):
            raise TypeError("Measurement covariance must be a numpy array")
        if measurement_covariance.ndim != 2:
            raise ValueError("Measurement covariance must be a 2D matrix")
        if measurement_covariance.shape[0] != measurement_covariance.shape[1]:
            raise ValueError("Measurement covariance must be a square matrix")

    # Measurement (z, shape=(2, 1))
    z = np.array([[x], [y]])

    # Measurement covariance
    if measurement_covariance is None:
        R = self._R_position
    else:
        if measurement_covariance.shape[0] != z.shape[0]:
            raise ValueError(
                "Measurement covariance must have the same number of rows as the measurement"
            )
        R = measurement_covariance

    # H matrix
    H = self._H_position

    # Innovation or residual (y, shape=(2, 1))
    y = z - H @ np.vstack(self._current_state[1:])
    if norm(y) > 100.0:
        warn("Position correction: large innovation (> 100 m), skipping correction")
        return np.nan, True

    # Innovation covariance
    S = H @ self._current_covariance @ H.T + R

    # Mahalanobis distance-based adaptive covariance matrix scaling
    S_inv, d_squared, scaled = self._adaptive_covariance(
        y, S, R, threshold, scaling_strength
    )

    # Kalman gain (K, shape=(n, 2))
    K = self._current_covariance @ H.T @ S_inv

    # Update state estimate (x, shape=(n, 2))
    self._current_state[1:] = np.squeeze(np.vstack(self._current_state[1:]) + K @ y)

    # Update covariance estimate (P, shape=(n, n))
    self._current_covariance = (
        np.eye(self._state_dim, dtype=np.float64) - K @ H
    ) @ self._current_covariance
    self._symmetrize_covariance()

    # Normalize quaternion and force it to have positive scalar part
    self._check_state_attitude()

    return d_squared, scaled

Correct the state of the EKF using position measurements.

Parameters:

Name Type Description Default
x Union[float, int]

X position measurement.

required
y Union[float, int]

Y position measurement.

required
z Union[float, int]

Z position measurement.

required
scaling_strength Union[float, int]

Scaling strength for the adaptive measurement noise covariance. scale_factor = np.exp(scaling_strength * (d_squared / threshold - 1.0))

1.0
threshold float

Threshold for the adaptive measurement noise covariance indicating the confidence level. The default value is 0.99, which corresponds to a 99% confidence level. This ensures that measurements falling within the 99% confidence region are trusted, while outliers are adaptively scaled.

0.99
measurement_covariance ndarray

Optional custom measurement covariance matrix. If this is provided, it will override the default measurement noise covariance provided in the constructor.

None

Returns:

Name Type Description
d_squared float

Mahalanobis distance squared.

success bool

True if the correction was used, False if the correction was scaled.

Raises:

Type Description
TypeError

If timestamp, x, y, z, scaling_strength or threshold are not of the expected type.

ValueError

If threshold is not between 0.0 and 1.0.

Source code in navlib/nav/kalman_filter.py
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
def correction_position_xyz(
    self,
    x: Union[float, int],
    y: Union[float, int],
    z: Union[float, int],
    scaling_strength: Union[float, int] = 1.0,
    threshold: float = 0.99,
    measurement_covariance: np.ndarray = None,
) -> Tuple[float, bool]:
    """
    Correct the state of the EKF using position measurements.

    Args:
        x (Union[float, int]): X position measurement.
        y (Union[float, int]): Y position measurement.
        z (Union[float, int]): Z position measurement.
        scaling_strength (Union[float, int]): Scaling strength for the adaptive measurement noise covariance.
            scale_factor =  np.exp(scaling_strength * (d_squared / threshold - 1.0))
        threshold (float): Threshold for the adaptive measurement noise covariance indicating the confidence level.
            The default value is 0.99, which corresponds to a 99% confidence level. This ensures that measurements
            falling within the 99% confidence region are trusted, while outliers are adaptively scaled.
        measurement_covariance (np.ndarray): Optional custom measurement covariance matrix. If this is provided,
            it will override the default measurement noise covariance provided in the constructor.

    Returns:
        d_squared (float): Mahalanobis distance squared.
        success (bool): True if the correction was used, False if the correction was scaled.

    Raises:
        TypeError: If timestamp, x, y, z, scaling_strength or threshold are not of the expected type.
        ValueError: If threshold is not between 0.0 and 1.0.
    """
    # Check typing
    if not isinstance(x, (float, int)):
        raise TypeError("X position must be a float or an int")
    if not isinstance(y, (float, int)):
        raise TypeError("Y position must be a float or an int")
    if not isinstance(z, (float, int)):
        raise TypeError("Z position must be a float or an int")
    if not isinstance(scaling_strength, (float, int)):
        raise TypeError("Scaling strength must be a float or an int")
    if not isinstance(threshold, (float, int)):
        raise TypeError("Threshold must be a float or an int")
    if threshold <= 0.0 or threshold >= 1.0:
        raise ValueError("Threshold must be between 0.0 and 1.0")
    if measurement_covariance is not None:
        if not isinstance(measurement_covariance, np.ndarray):
            raise TypeError("Measurement covariance must be a numpy array")
        if measurement_covariance.ndim != 2:
            raise ValueError("Measurement covariance must be a 2D matrix")
        if measurement_covariance.shape[0] != measurement_covariance.shape[1]:
            raise ValueError("Measurement covariance must be a square matrix")

    # Measurement (z, shape=(3, 1))
    z = np.array([[x], [y], [z]])

    # Measurement covariance
    if measurement_covariance is None:
        R = np.eye(3, dtype=np.float64)
        R[:2, :2] = self._R_position
        R[2, 2] = self._R_depth[0, 0]
    else:
        if measurement_covariance.shape[0] != z.shape[0]:
            raise ValueError(
                "Measurement covariance must have the same number of rows as the measurement"
            )
        R = measurement_covariance

    # H matrix
    H = np.concatenate([self._H_position, self._H_depth], axis=0)

    # Innovation or residual (y, shape=(3, 1))
    y = z - H @ np.vstack(self._current_state[1:])
    if norm(y) > 100.0:
        warn("Position correction: large innovation (> 100 m), skipping correction")
        return np.nan, True

    # Innovation covariance
    S = H @ self._current_covariance @ H.T + R

    # Mahalanobis distance-based adaptive covariance matrix scaling
    S_inv, d_squared, scaled = self._adaptive_covariance(
        y, S, R, threshold, scaling_strength
    )

    # Kalman gain (K, shape=(n, 3))
    K = self._current_covariance @ H.T @ S_inv

    # Update state estimate (x, shape=(n, 3))
    self._current_state[1:] = np.squeeze(np.vstack(self._current_state[1:]) + K @ y)

    # Update covariance estimate (P, shape=(n, n))
    self._current_covariance = (
        np.eye(self._state_dim, dtype=np.float64) - K @ H
    ) @ self._current_covariance
    self._symmetrize_covariance()

    # Normalize quaternion and force it to have positive scalar part
    self._check_state_attitude()

    return d_squared, scaled

Correct the state of the EKF using velocity measurements.

Parameters:

Name Type Description Default
velocity Union[List[Union[int, float]], ndarray]

Velocity measurement. Order: (vx, vy, vz).

required
body_frame bool

If True, the velocity is in body frame, otherwise in world frame.

True
scaling_strength Union[float, int]

Scaling strength for the adaptive measurement noise covariance. scale_factor = np.exp(scaling_strength * (d_squared / threshold - 1.0))

1.0
threshold float

Threshold for the adaptive measurement noise covariance indicating the confidence level. The default value is 0.99, which corresponds to a 99% confidence level.

0.99
measurement_covariance ndarray

Optional custom measurement covariance matrix. If this is provided, it will override the default measurement noise covariance provided in the constructor.

None

Returns:

Name Type Description
d_squared float

Mahalanobis distance squared.

success bool

True if the correction was used, False if the correction was scaled.

Raises:

Type Description
TypeError

If timestamp, velocity, body_frame, scaling_strength or threshold are not of the expected type.

ValueError

If threshold is not between 0.0 and 1.0.

Source code in navlib/nav/kalman_filter.py
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
def correction_velocity(
    self,
    velocity: Union[List[Union[int, float]], np.ndarray],
    body_frame: bool = True,
    scaling_strength: Union[float, int] = 1.0,
    threshold: float = 0.99,
    measurement_covariance: np.ndarray = None,
) -> Tuple[float, bool]:
    """
    Correct the state of the EKF using velocity measurements.

    Args:
        velocity (Union[List[Union[int, float]], np.ndarray]): Velocity measurement. Order: (vx, vy, vz).
        body_frame (bool): If True, the velocity is in body frame, otherwise in world frame.
        scaling_strength (Union[float, int]): Scaling strength for the adaptive measurement noise covariance.
            scale_factor = np.exp(scaling_strength * (d_squared / threshold - 1.0))
        threshold (float): Threshold for the adaptive measurement noise covariance indicating the confidence level.
            The default value is 0.99, which corresponds to a 99% confidence level.
        measurement_covariance (np.ndarray): Optional custom measurement covariance matrix. If this is provided,
            it will override the default measurement noise covariance provided in the constructor.

    Returns:
        d_squared (float): Mahalanobis distance squared.
        success (bool): True if the correction was used, False if the correction was scaled.

    Raises:
        TypeError: If timestamp, velocity, body_frame, scaling_strength or threshold are not of the expected type.
        ValueError: If threshold is not between 0.0 and 1.0.
    """
    # Convert to numpy array
    if isinstance(velocity, list):
        velocity = np.array(velocity)

    # Check inputs type
    if not isinstance(velocity, np.ndarray):
        raise TypeError("Velocity must be a numpy array")
    velocity = velocity.squeeze()
    if velocity.ndim != 1:
        raise ValueError("Velocity must be a 1D array")
    if velocity.shape[0] != 3:
        raise ValueError("Velocity must have 3 elements")
    if not isinstance(body_frame, bool):
        raise TypeError("body_frame must be a boolean")
    if not isinstance(scaling_strength, (float, int)):
        raise TypeError("Scaling strength must be a float or an int")
    if not isinstance(threshold, (float, int)):
        raise TypeError("Threshold must be a float or an int")
    if threshold <= 0.0 or threshold >= 1.0:
        raise ValueError("Threshold must be between 0.0 and 1.0")
    if measurement_covariance is not None:
        if not isinstance(measurement_covariance, np.ndarray):
            raise TypeError("Measurement covariance must be a numpy array")
        if measurement_covariance.ndim != 2:
            raise ValueError("Measurement covariance must be a 2D matrix")
        if measurement_covariance.shape[0] != measurement_covariance.shape[1]:
            raise ValueError("Measurement covariance must be a square matrix")

    # Extract velocity from current state
    v_world = np.vstack(self._current_state[8:11])

    if body_frame:
        # Rotate into body frame to define the predicted DVL measurement
        q = self._current_state[4:8]
        rot_v_w = quat2rot(q).T
        z_pred = rot_v_w @ v_world

        # Innovation
        y = np.vstack(velocity) - z_pred

        # H matrix
        H = np.zeros((3, self._state_dim))
        H[:, 7:10] = rot_v_w
    else:
        # Innovation
        y = np.vstack(velocity) - v_world

        # H matrix
        H = np.zeros((3, self._state_dim))
        H[:, 7:10] = np.eye(3, dtype=np.float64)

    # Measurement noise covariance
    if measurement_covariance is None:
        R = self._R_vel
    else:
        if measurement_covariance.shape[0] != y.shape[0]:
            raise ValueError(
                "Measurement covariance must have the same number of rows as the measurement"
            )
        R = measurement_covariance

    # Innovation covariance
    S = H @ self._current_covariance @ H.T + R

    # Mahalanobis distance-based adaptive covariance matrix scaling
    S_inv, d_squared, scaled = self._adaptive_covariance(
        y, S, R, threshold, scaling_strength
    )

    # Adaptive Q tuner
    self._velocity_d_squared_acummulted += d_squared
    self._velocity_d_squared_count += 1
    self._velocity_q_tuner.update(
        self._velocity_d_squared_acummulted / self._velocity_d_squared_count
    )

    # Kalman gain (K, shape=(n, 3) or (n, 4))
    K = self._current_covariance @ H.T @ S_inv

    # Update state estimate (x, shape=(n, 1) or (n, 4))
    self._current_state[1:] = np.squeeze(np.vstack(self._current_state[1:]) + K @ y)

    # Update covariance estimate (P, shape=(n, n))
    self._current_covariance = (
        np.eye(self._state_dim, dtype=np.float64) - K @ H
    ) @ self._current_covariance
    self._symmetrize_covariance()

    # Normalize quaternion and force it to have positive scalar part
    self._check_state_attitude()

    return d_squared, scaled

Initialize the state of the EKF.

Parameters:

Name Type Description Default
timestamp float

Timestamp of the measurement.

required
position Union[List[Union[int, float]], ndarray]

Initial position of the vehicle.

required
quaternion Union[List[Union[int, float]], ndarray]

Initial quaternion of the vehicle. Order: (x, y, z, w).

required
velocity Union[List[Union[int, float]], ndarray]

Initial velocity of the vehicle.

required
angular_velocity Union[List[Union[int, float]], ndarray]

Initial angular velocity of the vehicle.

required
bottom_height Union[float, int]

Initial bottom height of the vehicle. Default is 0.0.

0.0
Source code in navlib/nav/kalman_filter.py
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
def initialize_state(
    self,
    timestamp: Union[float, int],
    position: Union[List[Union[int, float]], np.ndarray],
    quaternion: Union[List[Union[int, float]], np.ndarray],
    velocity: Union[List[Union[int, float]], np.ndarray],
    angular_velocity: Union[List[Union[int, float]], np.ndarray],
    bottom_height: Union[float, int] = 0.0,
) -> None:
    """
    Initialize the state of the EKF.

    Args:
        timestamp (float): Timestamp of the measurement.
        position (Union[List[Union[int, float]], np.ndarray]): Initial position of the vehicle.
        quaternion (Union[List[Union[int, float]], np.ndarray]): Initial quaternion of the vehicle. Order: (x, y, z, w).
        velocity (Union[List[Union[int, float]], np.ndarray]): Initial velocity of the vehicle.
        angular_velocity (Union[List[Union[int, float]], np.ndarray]): Initial angular velocity of the vehicle.
        bottom_height (Union[float, int]): Initial bottom height of the vehicle. Default is 0.0.
    """
    # Convert to numpy array
    if isinstance(position, list):
        position = np.array(position)
    if isinstance(quaternion, list):
        quaternion = np.array(quaternion)
    if isinstance(velocity, list):
        velocity = np.array(velocity)
    if isinstance(angular_velocity, list):
        angular_velocity = np.array(angular_velocity)

    # Check inputs type
    if not isinstance(timestamp, (float, int)):
        raise TypeError("Timestamp must be a float or an int")
    if not isinstance(position, np.ndarray):
        raise TypeError("Position must be a numpy array")
    position = position.squeeze()
    if position.ndim != 1:
        raise ValueError("Position must be a 1D array")
    if position.shape[0] != 3:
        raise ValueError("Position must have 3 elements")
    if not isinstance(quaternion, np.ndarray):
        raise TypeError("Quaternion must be a numpy array")
    quaternion = quaternion.squeeze()
    if quaternion.ndim != 1:
        raise ValueError("Quaternion must be a 1D array")
    if quaternion.shape[0] != 4:
        raise ValueError("Quaternion must have 4 elements")
    if np.abs(norm(quaternion) - 1.0) > 1e-6:
        raise ValueError("Quaternion must be a unit quaternion")
    if not isinstance(velocity, np.ndarray):
        raise TypeError("Velocity must be a numpy array")
    velocity = velocity.squeeze()
    if velocity.ndim != 1:
        raise ValueError("Velocity must be a 1D array")
    if velocity.shape[0] != 3:
        raise ValueError("Velocity must have 3 elements")
    if not isinstance(angular_velocity, np.ndarray):
        raise TypeError("Angular velocity must be a numpy array")
    angular_velocity = angular_velocity.squeeze()
    if angular_velocity.ndim != 1:
        raise ValueError("Angular velocity must be a 1D array")
    if angular_velocity.shape[0] != 3:
        raise ValueError("Angular velocity must have 3 elements")
    if not isinstance(bottom_height, (int, float)):
        raise TypeError("Bottom height must be a float or an int")

    current_state = np.concatenate(
        [np.array([timestamp]), position, quaternion, velocity, angular_velocity]
    )
    if self._state_dim == 14:
        current_state = np.concatenate([current_state, np.array([bottom_height])])
    self._current_state = current_state

Predict the next state of the EKF.

Parameters:

Name Type Description Default
timestamp float

Timestamp of the measurement.

required
angular_velocity ndarray

Angular velocity in body frame.

required
Source code in navlib/nav/kalman_filter.py
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
def predict(self, timestamp: float, angular_velocity: np.ndarray) -> None:
    """
    Predict the next state of the EKF.

    Args:
        timestamp (float): Timestamp of the measurement.
        angular_velocity (np.ndarray): Angular velocity in body frame.
    """
    # Compute time step
    dt = timestamp - self._current_state[0]

    if dt < 0:
        warn(
            f"Negative time step in prediction: dt = {dt:.6f}, skipping prediction."
        )
        return
    elif dt > self._max_stable_time_step:
        warn(
            f"Large time step in prediction: dt = {dt:.2f} s, may destabilize EKF."
        )

    # State transition
    current_state = np.empty(self._state_dim + 1, dtype=np.float64)
    current_state[0] = timestamp

    # Position (p <- p + v * dt)
    current_state[1:4] = self._current_state[1:4] + self._current_state[8:11] * dt

    # Quaternion (q <- q * q{omega_body*dt})
    axis, theta = axis_ang3(angular_velocity)
    q_delta = np.array(
        [
            np.sin(dt * theta / 2) * axis[0],
            np.sin(dt * theta / 2) * axis[1],
            np.sin(dt * theta / 2) * axis[2],
            np.cos(dt * theta / 2),
        ]
    )
    current_state[4:8] = left_qmatrix(self._current_state[4:8]) @ q_delta
    current_state[4:8] /= norm(current_state[4:8])
    if current_state[7] < 0:
        current_state[4:8] *= -1

    # Linear velocity (v <- v)
    current_state[8:11] = self._current_state[8:11]
    # Angular rates (w <- omega_body)
    current_state[11:14] = angular_velocity
    # Bottom height (bh <- bh)
    if self._state_dim == 14:
        current_state[14] = self._current_state[14]

    # Update state
    self._current_state = current_state

    # Process noise covariance and state transition jacobian
    Q = self._process_noise_covariance(dt)
    J = self._state_transition_jacobian(dt, angular_velocity)

    # Predict covariance
    self._current_covariance = J @ self._current_covariance @ J.T + Q
    self._symmetrize_covariance()

Reset the EKF state after a discontinuity (e.g., time jump).

This method reinitializes the state vector and optionally resets the covariance matrix to reflect increased uncertainty after a time jump or data gap.

Parameters:

Name Type Description Default
timestamp float

Timestamp of the measurement.

required
position Union[List[Union[int, float]], ndarray]

Reset position of the vehicle.

required
quaternion Union[List[Union[int, float]], ndarray]

Reset quaternion of the vehicle. Order: (x, y, z, w).

required
velocity Union[List[Union[int, float]], ndarray]

Reset velocity of the vehicle.

required
angular_velocity Union[List[Union[int, float]], ndarray]

Reset angular velocity of the vehicle.

required
bottom_height Union[float, int]

Reset bottom height of the vehicle. Default is 0.0.

0.0
Source code in navlib/nav/kalman_filter.py
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
def reset(
    self,
    timestamp: Union[float, int],
    position: Union[List[Union[int, float]], np.ndarray],
    quaternion: Union[List[Union[int, float]], np.ndarray],
    velocity: Union[List[Union[int, float]], np.ndarray],
    angular_velocity: Union[List[Union[int, float]], np.ndarray],
    bottom_height: Union[float, int] = 0.0,
) -> None:
    """
    Reset the EKF state after a discontinuity (e.g., time jump).

    This method reinitializes the state vector and optionally resets the covariance
    matrix to reflect increased uncertainty after a time jump or data gap.

    Args:
        timestamp (float): Timestamp of the measurement.
        position (Union[List[Union[int, float]], np.ndarray]): Reset position of the vehicle.
        quaternion (Union[List[Union[int, float]], np.ndarray]): Reset quaternion of the vehicle. Order: (x, y, z, w).
        velocity (Union[List[Union[int, float]], np.ndarray]): Reset velocity of the vehicle.
        angular_velocity (Union[List[Union[int, float]], np.ndarray]): Reset angular velocity of the vehicle.
        bottom_height (Union[float, int]): Reset bottom height of the vehicle. Default is 0.0.
    """
    # Reuse the validation and state setting from initialize_state
    self.initialize_state(
        timestamp, position, quaternion, velocity, angular_velocity, bottom_height
    )

    # Reset covariance to initial uncertainty
    initial_dt = 0.01
    self._current_covariance = self._process_noise_covariance(initial_dt)

    # Optionally add higher initial uncertainty for position and velocity
    # since we're resetting after a discontinuity
    self._current_covariance[:3, :3] *= 10.0  # Position uncertainty
    self._current_covariance[7:10, 7:10] *= 5.0  # Velocity uncertainty

    # Reset velocity filtering statistics
    self._velocity_d_squared_acummulted = 0.0
    self._velocity_d_squared_count = 0
    self._velocity_q_tuner = _QTuner()

Discretize a Linear Time-Invariant (LTI) system using the matrix fraction decomposition for use in a discrete-time Kalman filter.

Parameters:

Name Type Description Default
Ac ndarray

Continuos state transition matrix.

required
Bc ndarray

Continuos input matrix, by default None.

None
Qc ndarray

Continuos covariance matrix, by default None.

None
dt float

Time step, by default 1.

1

Returns:

Name Type Description
transition_mat ndarray

Discrete state transition matrix.

inpu_mat ndarray

Discrete input matrix.

covariance_mat ndarray

Discrete covariance matrix.

Raises:

Type Description
TypeError

If Ac, Bc or Qc are not numpy arrays.

ValueError

If Ac is not a 2D matrix, if Ac and Bc do not have the same number of rows, if Qc is not a square matrix, if Qc does not have the same number of rows as Ac.

Source code in navlib/nav/kalman_filter.py
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def kf_lti_discretize(
    Ac: np.ndarray,
    Bc: np.ndarray = None,
    Qc: np.ndarray = None,
    dt: float = 1,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Discretize a Linear Time-Invariant (LTI) system using the matrix fraction decomposition
    for use in a discrete-time Kalman filter.

    Args:
        Ac (np.ndarray): Continuos state transition matrix.
        Bc (np.ndarray): Continuos input matrix, by default None.
        Qc (np.ndarray): Continuos covariance matrix, by default None.
        dt (float): Time step, by default 1.

    Returns:
        transition_mat (np.ndarray): Discrete state transition matrix.
        inpu_mat (np.ndarray): Discrete input matrix.
        covariance_mat (np.ndarray): Discrete covariance matrix.

    Raises:
        TypeError: If Ac, Bc or Qc are not numpy arrays.
        ValueError: If Ac is not a 2D matrix, if Ac and Bc do not have the same number of rows,
            if Qc is not a square matrix, if Qc does not have the same number of rows as Ac.
    """
    # Convert to numpy array
    if isinstance(Ac, list):
        Ac = np.array(Ac)
    if isinstance(Bc, list):
        Bc = np.array(Bc)
    if isinstance(Qc, list):
        Qc = np.array(Qc)

    # Check inputs type
    if not isinstance(Ac, np.ndarray):
        raise TypeError("Ac must be a numpy array")
    if Bc is not None and not isinstance(Bc, np.ndarray):
        raise TypeError("Bc must be a numpy array")
    if Qc is not None and not isinstance(Qc, np.ndarray):
        raise TypeError("Qc must be a numpy array")
    if not isinstance(dt, (int, float)):
        raise TypeError("dt must be a number")

    # Force the input matrix to be a column vector
    if Bc is not None and Bc.ndim == 1:
        Bc = Bc[:, np.newaxis] if Bc.ndim == 1 else np.vstack(Bc)

    # Check that the shape of the matrices is correct
    if Ac.ndim != 2:
        raise ValueError("Ac must be a 2D matrix")
    if Bc is not None and Bc.shape[0] != Ac.shape[0]:
        raise ValueError("Ac and Bc must have the same number of rows")
    if Qc is not None and Qc.shape[0] != Qc.shape[1]:
        raise ValueError("Qc must be a square matrix")
    if Qc is not None and Qc.shape[0] != Ac.shape[0]:
        raise ValueError("Qc must have the same number of rows as Ac")

    # Check the number of states
    n = Ac.shape[0]

    # Default to zero non provided matrices
    if Bc is None:
        Bc = np.zeros([n, 1])

    if Qc is None:
        Qc = np.zeros([n, n])

    # Discretize state transition and input matrix (close form)
    # Ad = expm(Ac*dt)
    M = np.vstack([np.hstack([Ac, Bc]), np.zeros([1, n + 1])])
    ME = expm(M * dt)

    # Discretize state transition and input matrix
    Ad = ME[:n, :n]
    Bd = ME[:n, n:]

    # Discretize Covariance: by (Van Loan, 1978)
    F = np.vstack([np.hstack([-Ac, Qc]), np.hstack([np.zeros([n, n]), Ac.T])])
    G = expm(F * dt)
    Qd = np.dot(G[n:, n:].T, G[:n, n:])

    # # Discretize Covariance: by matrix fraction decomposition
    # Phi = vstack([hstack([Ac,            Qc]),
    #               hstack([np.zeros([n,n]),-Ac.T])])
    # AB  = np.dot (scipy.linalg.expm(Phi*dt), vstack([np.zeros([n,n]),np.eye(n)]))
    # Qd  = np.linalg.solve(AB[:n,:].T, AB[n:2*n,:].T).T

    return Ad, Bd, Qd

Prediction step of the Kalman filter.

Parameters:

Name Type Description Default
x ndarray

State mean.

required
P ndarray

State covariance.

required
A ndarray

State transition matrix, by default None.

None
Q ndarray

Process noise covariance, by default None.

None
B ndarray

Input matrix, by default None.

None
u ndarray

Input vector, by default None.

None

Returns:

Name Type Description
updated_state_mean ndarray

Updated state mean.

updated_state_cov ndarray

Updated state covariance.

Raises:

Type Description
TypeError

If A, Q, B, u, x or P are not numpy arrays.

ValueError

If A is not a 2D matrix, if x and A do not have the same number of rows, if B is not a 2D matrix, if the number of columns in B is not equal to the number of rows in u, if B does not have the same number of rows as x, if P is not a square matrix, if P is not a square matrix, if Q is not a square matrix, if Q does not have the same number of rows as A.

Source code in navlib/nav/kalman_filter.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
def kf_predict(
    x: np.ndarray,
    P: np.ndarray,
    A: np.ndarray = None,
    Q: np.ndarray = None,
    B: np.ndarray = None,
    u: np.ndarray = None,
) -> Tuple[np.ndarray, np.ndarray]:
    """
    Prediction step of the Kalman filter.

    Args:
        x (np.ndarray): State mean.
        P (np.ndarray): State covariance.
        A (np.ndarray): State transition matrix, by default None.
        Q (np.ndarray): Process noise covariance, by default None.
        B (np.ndarray): Input matrix, by default None.
        u (np.ndarray): Input vector, by default None.

    Returns:
        updated_state_mean (np.ndarray): Updated state mean.
        updated_state_cov (np.ndarray): Updated state covariance.

    Raises:
        TypeError: If A, Q, B, u, x or P are not numpy arrays.
        ValueError: If A is not a 2D matrix, if x and A do not have the same number of rows,
            if B is not a 2D matrix, if the number of columns in B is not equal to the number of rows in u,
            if B does not have the same number of rows as x, if P is not a square matrix,
            if P is not a square matrix, if Q is not a square matrix, if Q does not have the same number of rows as A.
    """
    # Convert to numpy array
    if isinstance(A, list):
        A = np.array(A)
    if isinstance(Q, list):
        Q = np.array(Q)
    if isinstance(B, list):
        B = np.array(B)
    if isinstance(u, list):
        u = np.array(u)
    if isinstance(x, list):
        x = np.array(x)
    if isinstance(P, list):
        P = np.array(P)

    # Check inputs type
    if A is not None and not isinstance(A, np.ndarray):
        raise TypeError("A must be a numpy array")
    if Q is not None and not isinstance(Q, np.ndarray):
        raise TypeError("Q must be a numpy array")
    if B is not None and not isinstance(B, np.ndarray):
        raise TypeError("B must be a numpy array")
    if u is not None and not isinstance(u, np.ndarray):
        raise TypeError("u must be a numpy array")
    if not isinstance(x, np.ndarray):
        raise TypeError("x must be a numpy array")
    if not isinstance(P, np.ndarray):
        raise TypeError("P must be a numpy array")

    # Force the state, input and control matrices to be column vectors
    x = x[:, np.newaxis] if x.ndim == 1 else x
    if u is not None:
        u = u[:, np.newaxis] if u.ndim == 1 else u

    # Check that the shape of the matrices is correct
    if A is not None and A.ndim != 2:
        raise ValueError("A must be a 2D matrix")
    if A is not None and x.shape[0] != A.shape[0]:
        raise ValueError("x and A must have the same number of rows")
    if B is not None and B.ndim != 2:
        raise ValueError("B must be a 2D matrix")
    if u is not None and B is not None and u.shape[0] != B.shape[1]:
        raise ValueError(
            "The number of columns in B must be equal to the number of rows in u"
        )
    if B is not None and B.shape[0] != x.shape[0]:
        raise ValueError("B must have the same number of rows as x")
    if P.ndim != 2 or P.shape[0] != P.shape[1]:
        raise ValueError("P must be a square matrix")
    if A is not None and P.shape[0] != A.shape[0]:
        raise ValueError("P must have the same number of rows as A")
    if Q is not None and (Q.ndim != 2 or Q.shape[0] != Q.shape[1]):
        raise ValueError("Q must be a square matrix")
    if Q is not None and A is not None and Q.shape[0] != A.shape[0]:
        raise ValueError("Q must have the same number of rows as A")

    # Check Arguments
    n = A.shape[0] if A is not None else x.shape[0]

    # Default state transition matrix to the identity matrix if not provided
    if A is None:
        A = np.eye(n)

    # Default process noise covariance to zero matrix if not provided
    if Q is None:
        Q = np.zeros((n, n))

    # Default input matrix to the identity matrix if not provided
    if B is None and u is not None:
        B = np.eye(n, u.shape[0])

    # Prediction step
    # State
    if u is None:
        x = A @ x
    else:
        x = A @ x + B @ u

    # Covariance
    P = A @ P @ A.T + Q

    return x.squeeze(), P.squeeze()

Update step of the Kalman filter.

Parameters:

Name Type Description Default
x ndarray

State mean.

required
P ndarray

State covariance.

required
y ndarray

Measurement.

required
H ndarray

Measurement matrix.

required
R ndarray

Measurement noise covariance.

required

Returns:

Name Type Description
x ndarray

Updated state mean.

P ndarray

Updated state covariance.

K ndarray

Kalman Gain.

dy ndarray

Measurement residual.

S ndarray

Covariance residual.

Raises:

Type Description
TypeError

If x, P, y, H or R are not numpy arrays.

ValueError

If x is not a numpy array, if P is not a numpy array, if y is not a numpy array, if H is not a 2D matrix, if R is not a square matrix, if P is not a square matrix, if P does not have the same number of rows as x, if H does not have the same number of columns as rows in x, if x and y do not have the same number of rows, if R does not have the same number of rows as y.

Source code in navlib/nav/kalman_filter.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
def kf_update(
    x: np.ndarray,
    P: np.ndarray,
    y: np.ndarray,
    H: np.ndarray,
    R: np.ndarray,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
    """
    Update step of the Kalman filter.

    Args:
        x (np.ndarray): State mean.
        P (np.ndarray): State covariance.
        y (np.ndarray): Measurement.
        H (np.ndarray): Measurement matrix.
        R (np.ndarray): Measurement noise covariance.

    Returns:
        x (np.ndarray): Updated state mean.
        P (np.ndarray): Updated state covariance.
        K (np.ndarray): Kalman Gain.
        dy (np.ndarray): Measurement residual.
        S (np.ndarray): Covariance residual.

    Raises:
        TypeError: If x, P, y, H or R are not numpy arrays.
        ValueError: If x is not a numpy array, if P is not a numpy array, if y is not a numpy array,
            if H is not a 2D matrix, if R is not a square matrix, if P is not a square matrix,
            if P does not have the same number of rows as x, if H does not have the same number of columns as rows in x,
            if x and y do not have the same number of rows, if R does not have the same number of rows as y.
    """
    # Convert to numpy array
    if isinstance(x, list):
        x = np.array(x)
    if isinstance(P, list):
        P = np.array(P)
    if isinstance(y, list):
        y = np.array(y)
    if isinstance(H, list):
        H = np.array(H)
    if isinstance(R, list):
        R = np.array(R)

    # Check inputs type
    if not isinstance(x, np.ndarray):
        raise TypeError("x must be a numpy array")
    if not isinstance(P, np.ndarray):
        raise TypeError("P must be a numpy array")
    if not isinstance(y, np.ndarray):
        raise TypeError("y must be a numpy array")
    if not isinstance(H, np.ndarray):
        raise TypeError("H must be a numpy array")
    if not isinstance(R, np.ndarray):
        raise TypeError("R must be a numpy array")

    # Force the state and measurements to be column vectors
    x = x[:, np.newaxis] if x.ndim == 1 else x
    y = y[:, np.newaxis] if y.ndim == 1 else y

    # Check dimensions
    if P.ndim != 2 or P.shape[0] != P.shape[1]:
        raise ValueError("P must be a square matrix")
    if P.shape[0] != x.shape[0]:
        raise ValueError("P must have the same number of rows as x")
    if H.ndim != 2:
        raise ValueError("H must be a 2D matrix")
    if x.shape[0] != H.shape[1]:
        raise ValueError("H must have the same number of columns as rows in x")
    if R.ndim != 2 or R.shape[0] != R.shape[1]:
        raise ValueError("R must be a square matrix")
    if R.shape[0] != y.shape[0]:
        raise ValueError("R must have the same number of rows as y")

    # Compute measurement residual
    dy = y - H @ x
    # Compute covariance residual
    S = R + H @ P @ H.T
    # Compute Kalman Gain
    K = P @ H.T @ np.linalg.inv(S)

    # Update state estimate
    x = x + K @ dy
    P = P - K @ H @ P

    return x.squeeze(), P.squeeze(), K.squeeze(), dy.squeeze(), S.squeeze()