mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-11-29 08:13:53 +08:00
bump rednose (#39279)
This commit is contained in:
committed by
firestar5683
parent
aa2b969c65
commit
dfdee91db4
+10
@@ -8,6 +8,8 @@ import importlib
|
||||
import re
|
||||
import stat
|
||||
import numpy as np
|
||||
import eigen
|
||||
import nanobind
|
||||
|
||||
import SCons.Errors
|
||||
from SCons.Defaults import _stripixes
|
||||
@@ -249,6 +251,14 @@ else:
|
||||
np_version = SCons.Script.Value(np.__version__)
|
||||
Export('envCython', 'np_version')
|
||||
|
||||
envNanobind = envCython.Clone()
|
||||
nanobind_dir = os.path.dirname(nanobind.__file__)
|
||||
envNanobind.Append(CPPPATH=[nanobind.include_dir(), os.path.join(nanobind_dir, "ext", "robin_map", "include"),
|
||||
os.path.join(eigen.INCLUDE_DIR, "eigen3")],
|
||||
CCFLAGS=["-fvisibility=hidden"])
|
||||
envNanobind["NANOBIND_SOURCE"] = os.path.join(nanobind_dir, "src", "nb_combined.cpp")
|
||||
Export('envNanobind')
|
||||
|
||||
Export('env', 'arch', 'acados', 'ffmpeg_libs')
|
||||
|
||||
# Setup cache dir
|
||||
|
||||
@@ -32,6 +32,7 @@ dependencies = [
|
||||
# vendored native dependencies
|
||||
"comma-deps-capnproto",
|
||||
"comma-deps-acados",
|
||||
"cython", # acados and remaining native bindings
|
||||
"comma-deps-ffmpeg",
|
||||
"comma-deps-zstd",
|
||||
"comma-deps-json11",
|
||||
|
||||
@@ -3,10 +3,7 @@ generated/
|
||||
*.swp
|
||||
*.tmp
|
||||
|
||||
# Cython intermediates
|
||||
*_pyx.cpp
|
||||
*_pyx.h
|
||||
*_pyx_api.h
|
||||
# SCons objects
|
||||
*.os
|
||||
|
||||
# Byte-compiled / optimized / DLL files
|
||||
@@ -148,5 +145,5 @@ dmypy.json
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
# Generated binding stubs
|
||||
rednose/helpers/ekf_sym_pyx.pyi
|
||||
|
||||
+16
-12
@@ -2,7 +2,7 @@ import os
|
||||
import platform
|
||||
import subprocess
|
||||
import sysconfig
|
||||
import numpy as np
|
||||
import nanobind
|
||||
import eigen
|
||||
|
||||
arch = subprocess.check_output(["uname", "-m"], encoding='utf8').rstrip()
|
||||
@@ -16,7 +16,6 @@ cpppath = [
|
||||
'#rednose/examples/generated',
|
||||
'/usr/lib/include',
|
||||
python_path,
|
||||
np.get_include(),
|
||||
eigen.INCLUDE_DIR,
|
||||
]
|
||||
|
||||
@@ -38,23 +37,28 @@ env = Environment(
|
||||
CXXFLAGS="-std=c++1z",
|
||||
CPPPATH=cpppath,
|
||||
REDNOSE_ROOT=Dir("#").abspath,
|
||||
tools=["default", "cython", "rednose_filter"],
|
||||
tools=["default", "rednose_filter"],
|
||||
)
|
||||
|
||||
# Cython build enviroment
|
||||
envCython = env.Clone()
|
||||
envCython["CCFLAGS"] += ["-Wno-#warnings", "-Wno-cpp", "-Wno-shadow", "-Wno-deprecated-declarations"]
|
||||
# Python extension build environment
|
||||
envNanobind = env.Clone()
|
||||
nanobind_dir = os.path.dirname(nanobind.__file__)
|
||||
envNanobind.Append(
|
||||
CPPPATH=[os.path.join(eigen.INCLUDE_DIR, "eigen3"), nanobind.include_dir(), os.path.join(nanobind_dir, "ext", "robin_map", "include")],
|
||||
CCFLAGS=["-fvisibility=hidden", "-Wno-shadow"],
|
||||
)
|
||||
envNanobind["NANOBIND_SOURCE"] = os.path.join(nanobind_dir, "src", "nb_combined.cpp")
|
||||
|
||||
envCython["LIBS"] = []
|
||||
envNanobind["LIBS"] = []
|
||||
if platform.system() == "Darwin":
|
||||
envCython["LINKFLAGS"] = ["-bundle", "-undefined", "dynamic_lookup"]
|
||||
envNanobind["LINKFLAGS"] = ["-bundle", "-undefined", "dynamic_lookup"]
|
||||
elif arch == "aarch64":
|
||||
envCython["LINKFLAGS"] = ["-shared"]
|
||||
envCython["LIBS"] = [os.path.basename(python_path)]
|
||||
envNanobind["LINKFLAGS"] = ["-shared"]
|
||||
envNanobind["LIBS"] = [os.path.basename(python_path)]
|
||||
else:
|
||||
envCython["LINKFLAGS"] = ["-pthread", "-shared"]
|
||||
envNanobind["LINKFLAGS"] = ["-pthread", "-shared"]
|
||||
|
||||
Export('env', 'envCython', 'common')
|
||||
Export('env', 'envNanobind', 'common')
|
||||
|
||||
SConscript(['#rednose/SConscript'])
|
||||
SConscript(['#examples/SConscript'])
|
||||
|
||||
@@ -266,7 +266,7 @@ class LiveKalman():
|
||||
|
||||
@property
|
||||
def t(self):
|
||||
return self.filter.filter_time
|
||||
return self.filter.get_filter_time()
|
||||
|
||||
@property
|
||||
def P(self):
|
||||
@@ -297,13 +297,13 @@ class LiveKalman():
|
||||
r = self.filter.predict_and_update_batch(t, kind, data, self.get_R(kind, len(data)))
|
||||
|
||||
# Normalize quats
|
||||
quat_norm = np.linalg.norm(self.filter.x[3:7, 0])
|
||||
quat_norm = np.linalg.norm(self.filter.state()[States.ECEF_ORIENTATION])
|
||||
|
||||
# Should not continue if the quats behave this weirdly
|
||||
if not (0.1 < quat_norm < 10):
|
||||
raise KalmanError("Kalman filter quaternions unstable")
|
||||
|
||||
self.filter.x[States.ECEF_ORIENTATION, 0] = self.filter.x[States.ECEF_ORIENTATION, 0] / quat_norm
|
||||
self.filter.normalize_slice(States.ECEF_ORIENTATION.start, States.ECEF_ORIENTATION.stop)
|
||||
|
||||
return r
|
||||
|
||||
|
||||
@@ -84,6 +84,29 @@ class CompareFilter:
|
||||
|
||||
|
||||
class TestCompare(unittest.TestCase):
|
||||
def test_batch_buffers_and_results(self):
|
||||
kf = CompareFilter(GENERATED_DIR)
|
||||
# Exercise conversion of strided, non-double inputs and multiple observations.
|
||||
z = np.array([[1, 0], [2, 0], [3, 0]], dtype=np.float32)[:, ::2]
|
||||
R = np.full((3, 2, 2), 0.01, dtype=np.float32)[:, ::2, ::2]
|
||||
result = kf.filter_py.predict_and_update_batch(0.0, ObservationKind.POSITION, z, R, [[], [], []])
|
||||
expected = kf.filter_pyx.predict_and_update_batch(0.0, ObservationKind.POSITION, z, R, [[], [], []])
|
||||
assert result is not None
|
||||
assert expected is not None
|
||||
for actual, reference in zip(result[:4], expected[:4]):
|
||||
np.testing.assert_allclose(actual, reference)
|
||||
np.testing.assert_allclose(result[6], expected[6])
|
||||
self.assertIs(result[7], z)
|
||||
saved_state = result[1].copy()
|
||||
state = kf.filter_py.state()
|
||||
state[:] = 100
|
||||
np.testing.assert_allclose(kf.filter_py.state(), saved_state)
|
||||
kf.filter_py.predict_and_update_batch(0.1, ObservationKind.POSITION, z, R, [[], [], []])
|
||||
np.testing.assert_array_equal(result[1], saved_state)
|
||||
# Resetting with None preserves the Python API's uninitialized time semantics.
|
||||
kf.filter_py.init_state(CompareFilter.initial_x, np.eye(2), None)
|
||||
self.assertTrue(np.isnan(kf.filter_py.get_filter_time()))
|
||||
|
||||
def test_compare(self):
|
||||
np.random.seed(0)
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ class TestKinematic(unittest.TestCase):
|
||||
self.assertAlmostEqual(vs_kf_std[-1], 0.6695762270974388)
|
||||
|
||||
if "PLOT" in os.environ:
|
||||
import matplotlib.pyplot as plt # pylint: disable=import-error
|
||||
import matplotlib.pyplot as plt # ty: ignore[import-not-found]
|
||||
plt.figure()
|
||||
plt.subplot(2, 1, 1)
|
||||
plt.plot(ts, xs, 'k', label='Simulation')
|
||||
|
||||
@@ -11,7 +11,7 @@ dependencies = [
|
||||
"cffi",
|
||||
"sympy",
|
||||
"comma-deps-eigen",
|
||||
"Cython",
|
||||
"nanobind>=2.0",
|
||||
"scons",
|
||||
"setuptools",
|
||||
]
|
||||
@@ -31,7 +31,7 @@ build-backend = "setuptools.build_meta"
|
||||
include = ["rednose*"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
"*" = ["*.so", "helpers/chi2_lookup_table.npy", "templates/*"]
|
||||
"*" = ["*.so", "py.typed", "helpers/*.pyi", "helpers/chi2_lookup_table.npy", "templates/*"]
|
||||
|
||||
# https://beta.ruff.rs/docs/configuration/#using-pyprojecttoml
|
||||
[tool.ruff]
|
||||
@@ -42,7 +42,3 @@ target-version = "py311"
|
||||
select = ["E", "F", "W", "PIE", "C4", "ISC", "RUF100", "A"]
|
||||
ignore = ["W292", "E741", "E402", "C408", "ISC003"]
|
||||
flake8-implicit-str-concat.allow-multiline = false
|
||||
|
||||
[tool.ty.rules]
|
||||
unresolved-import = "ignore" # Cython-compiled modules (.pyx) and dynamic SCons exports
|
||||
unresolved-attribute = "ignore" # Cython-backed filter attributes
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import sys
|
||||
|
||||
import eigen
|
||||
|
||||
Import('env', 'envCython', 'common')
|
||||
Import('env', 'envNanobind', 'common')
|
||||
|
||||
env = env.Clone()
|
||||
env.Append(CPPPATH=[eigen.INCLUDE_DIR])
|
||||
envCython = envCython.Clone()
|
||||
envCython.Append(CPPPATH=[eigen.INCLUDE_DIR])
|
||||
envNanobind = envNanobind.Clone()
|
||||
envNanobind.Append(CPPPATH=[eigen.INCLUDE_DIR])
|
||||
|
||||
cc_sources = [
|
||||
"helpers/ekf_load.cc",
|
||||
@@ -18,7 +20,15 @@ if common != "":
|
||||
|
||||
ekf_objects = env.SharedObject(cc_sources)
|
||||
rednose = env.Library("helpers/ekf_sym", ekf_objects, LIBS=libs)
|
||||
rednose_python = envCython.Program("helpers/ekf_sym_pyx.so", ["helpers/ekf_sym_pyx.pyx", ekf_objects],
|
||||
LIBS=libs + envCython["LIBS"])
|
||||
nanobind_objects = envNanobind.SharedObject("helpers/nanobind", envNanobind["NANOBIND_SOURCE"])
|
||||
rednose_python = envNanobind.Program("helpers/ekf_sym_pyx.so", ["helpers/ekf_sym_pyx.cc", ekf_objects, nanobind_objects],
|
||||
LIBS=libs + envNanobind["LIBS"])
|
||||
|
||||
rednose_python_stub = envNanobind.Command(
|
||||
"helpers/ekf_sym_pyx.pyi",
|
||||
rednose_python,
|
||||
[[sys.executable, "-m", "nanobind.stubgen", "-i", Dir("#").abspath,
|
||||
"-m", "rednose.helpers.ekf_sym_pyx", "-o", "$TARGET", "-q"]],
|
||||
)
|
||||
|
||||
Export('rednose', 'rednose_python')
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
#include <limits>
|
||||
#include <new>
|
||||
|
||||
#include <nanobind/nanobind.h>
|
||||
#include <nanobind/eigen/dense.h>
|
||||
#include <nanobind/stl/optional.h>
|
||||
#include <nanobind/stl/string.h>
|
||||
#include <nanobind/stl/vector.h>
|
||||
|
||||
#include "rednose/helpers/ekf_sym.h"
|
||||
|
||||
namespace nb = nanobind;
|
||||
using namespace nb::literals;
|
||||
using EKFS::EKFSym;
|
||||
using EKFS::MatrixXdr;
|
||||
using Eigen::VectorXd;
|
||||
|
||||
NB_MODULE(ekf_sym_pyx, m) {
|
||||
// Keep the historical name for compatibility with existing filter clients.
|
||||
nb::class_<EKFSym>(m, "EKF_sym_pyx")
|
||||
.def("__init__", [](
|
||||
EKFSym *self,
|
||||
const std::string &gen_dir,
|
||||
const std::string &name,
|
||||
MatrixXdr Q,
|
||||
VectorXd x_initial,
|
||||
MatrixXdr P_initial,
|
||||
int dim_main,
|
||||
int dim_main_err,
|
||||
int N,
|
||||
int dim_augment,
|
||||
int dim_augment_err,
|
||||
std::vector<int> maha_test_kinds,
|
||||
std::vector<int> quaternion_idxs,
|
||||
std::vector<std::string> global_vars,
|
||||
double max_rewind_age,
|
||||
nb::object logger
|
||||
) {
|
||||
ekf_load_and_register(gen_dir, name);
|
||||
new (self) EKFSym(
|
||||
name,
|
||||
Eigen::Map<MatrixXdr>(Q.data(), Q.rows(), Q.cols()),
|
||||
Eigen::Map<VectorXd>(x_initial.data(), x_initial.size()),
|
||||
Eigen::Map<MatrixXdr>(P_initial.data(), P_initial.rows(), P_initial.cols()),
|
||||
dim_main,
|
||||
dim_main_err,
|
||||
N,
|
||||
dim_augment,
|
||||
dim_augment_err,
|
||||
maha_test_kinds,
|
||||
quaternion_idxs,
|
||||
global_vars,
|
||||
max_rewind_age
|
||||
);
|
||||
},
|
||||
"gen_dir"_a,
|
||||
"name"_a,
|
||||
"Q"_a,
|
||||
"x_initial"_a,
|
||||
"P_initial"_a,
|
||||
"dim_main"_a,
|
||||
"dim_main_err"_a,
|
||||
"N"_a = 0,
|
||||
"dim_augment"_a = 0,
|
||||
"dim_augment_err"_a = 0,
|
||||
"maha_test_kinds"_a = std::vector<int>{},
|
||||
"quaternion_idxs"_a = std::vector<int>{},
|
||||
"global_vars"_a = std::vector<std::string>{},
|
||||
"max_rewind_age"_a = 1.0,
|
||||
"logger"_a.none() = nb::none())
|
||||
.def("init_state", [](EKFSym &self, VectorXd state, MatrixXdr covs, nb::object filter_time) {
|
||||
self.init_state(
|
||||
Eigen::Map<VectorXd>(state.data(), state.size()),
|
||||
Eigen::Map<MatrixXdr>(covs.data(), covs.rows(), covs.cols()),
|
||||
filter_time.is_none() ? std::numeric_limits<double>::quiet_NaN() : nb::cast<double>(filter_time)
|
||||
);
|
||||
}, "state"_a, "covs"_a, "filter_time"_a.none())
|
||||
.def("state", &EKFSym::state)
|
||||
.def("covs", &EKFSym::covs)
|
||||
.def("set_filter_time", &EKFSym::set_filter_time, "t"_a)
|
||||
.def("get_filter_time", &EKFSym::get_filter_time)
|
||||
.def("set_global", &EKFSym::set_global, "global_var"_a, "val"_a)
|
||||
.def("normalize_slice", &EKFSym::normalize_slice, "slice_start"_a, "slice_end_ex"_a)
|
||||
.def("reset_rewind", &EKFSym::reset_rewind)
|
||||
.def("predict", &EKFSym::predict, "t"_a)
|
||||
.def("predict_and_update_batch", [](
|
||||
EKFSym &self,
|
||||
double t,
|
||||
int kind,
|
||||
nb::object z,
|
||||
nb::object R,
|
||||
nb::object extra_args,
|
||||
bool augment
|
||||
) -> std::optional<nb::tuple> {
|
||||
// Own all converted buffers until the filter has finished using the maps.
|
||||
auto zs = nb::cast<std::vector<VectorXd>>(z);
|
||||
auto Rs = nb::cast<std::vector<MatrixXdr>>(R);
|
||||
std::vector<Eigen::Map<VectorXd>> z_maps;
|
||||
std::vector<Eigen::Map<MatrixXdr>> R_maps;
|
||||
for (auto &zi : zs) {
|
||||
z_maps.emplace_back(zi.data(), zi.size());
|
||||
}
|
||||
for (auto &Ri : Rs) {
|
||||
R_maps.emplace_back(Ri.data(), Ri.rows(), Ri.cols());
|
||||
}
|
||||
auto result = self.predict_and_update_batch(
|
||||
t, kind, z_maps, R_maps,
|
||||
nb::cast<std::vector<std::vector<double>>>(extra_args), augment
|
||||
);
|
||||
if (!result) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return nb::make_tuple(
|
||||
result->xk1, result->xk, result->Pk1, result->Pk, result->t,
|
||||
result->kind, result->y, z, extra_args
|
||||
);
|
||||
}, "t"_a, "kind"_a, "z"_a, "R"_a,
|
||||
"extra_args"_a = std::vector<std::vector<double>>{{}}, "augment"_a = false)
|
||||
.def("augment", [](EKFSym &) {
|
||||
PyErr_SetNone(PyExc_NotImplementedError);
|
||||
throw nb::python_error();
|
||||
})
|
||||
.def("get_augment_times", [](EKFSym &) {
|
||||
PyErr_SetNone(PyExc_NotImplementedError);
|
||||
throw nb::python_error();
|
||||
})
|
||||
.def("rts_smooth", [](EKFSym &, nb::object, bool) {
|
||||
PyErr_SetNone(PyExc_NotImplementedError);
|
||||
throw nb::python_error();
|
||||
}, "estimates"_a, "norm_quats"_a = false)
|
||||
.def("maha_test", [](EKFSym &, nb::object, nb::object, int, nb::object, nb::object, nb::object, double) {
|
||||
PyErr_SetNone(PyExc_NotImplementedError);
|
||||
throw nb::python_error();
|
||||
}, "x"_a, "P"_a, "kind"_a, "z"_a, "R"_a, "extra_args"_a = nb::list(), "maha_thresh"_a = 0.95);
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
# cython: language_level=3
|
||||
# cython: profile=True
|
||||
# distutils: language = c++
|
||||
|
||||
cimport cython
|
||||
|
||||
from libcpp.string cimport string
|
||||
from libcpp.vector cimport vector
|
||||
from libcpp cimport bool
|
||||
cimport numpy as np
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
cdef extern from "<optional>" namespace "std" nogil:
|
||||
cdef cppclass optional[T]:
|
||||
ctypedef T value_type
|
||||
bool has_value()
|
||||
T& value()
|
||||
|
||||
cdef extern from "rednose/helpers/ekf_load.h":
|
||||
cdef void ekf_load_and_register(string directory, string name)
|
||||
|
||||
cdef extern from "rednose/helpers/ekf_sym.h" namespace "EKFS":
|
||||
cdef cppclass MapVectorXd "Eigen::Map<Eigen::VectorXd>":
|
||||
MapVectorXd(double*, int)
|
||||
|
||||
cdef cppclass MapMatrixXdr "Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> >":
|
||||
MapMatrixXdr(double*, int, int)
|
||||
|
||||
cdef cppclass VectorXd "Eigen::VectorXd":
|
||||
VectorXd()
|
||||
double* data()
|
||||
int rows()
|
||||
|
||||
cdef cppclass MatrixXdr "Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>":
|
||||
MatrixXdr()
|
||||
double* data()
|
||||
int rows()
|
||||
int cols()
|
||||
|
||||
ctypedef struct Estimate:
|
||||
VectorXd xk1
|
||||
VectorXd xk
|
||||
MatrixXdr Pk1
|
||||
MatrixXdr Pk
|
||||
double t
|
||||
int kind
|
||||
vector[VectorXd] y
|
||||
vector[VectorXd] z
|
||||
vector[vector[double]] extra_args
|
||||
|
||||
cdef cppclass EKFSym:
|
||||
EKFSym(string name, MapMatrixXdr Q, MapVectorXd x_initial, MapMatrixXdr P_initial, int dim_main,
|
||||
int dim_main_err, int N, int dim_augment, int dim_augment_err, vector[int] maha_test_kinds,
|
||||
vector[int] quaternion_idxs, vector[string] global_vars, double max_rewind_age)
|
||||
void init_state(MapVectorXd state, MapMatrixXdr covs, double filter_time)
|
||||
|
||||
VectorXd state()
|
||||
MatrixXdr covs()
|
||||
void set_filter_time(double t)
|
||||
double get_filter_time()
|
||||
void set_global(string name, double val)
|
||||
void reset_rewind()
|
||||
|
||||
void predict(double t)
|
||||
optional[Estimate] predict_and_update_batch(double t, int kind, vector[MapVectorXd] z, vector[MapMatrixXdr] z,
|
||||
vector[vector[double]] extra_args, bool augment)
|
||||
|
||||
# Functions like `numpy_to_matrix` are not possible, cython requires default
|
||||
# constructor for return variable types which aren't available with Eigen::Map
|
||||
|
||||
@cython.wraparound(False)
|
||||
@cython.boundscheck(False)
|
||||
cdef np.ndarray[np.float64_t, ndim=2, mode="c"] matrix_to_numpy(MatrixXdr arr):
|
||||
cdef double[:,:] mem_view = <double[:arr.rows(),:arr.cols()]>arr.data()
|
||||
return np.copy(np.asarray(mem_view, dtype=np.double, order="C"))
|
||||
|
||||
@cython.wraparound(False)
|
||||
@cython.boundscheck(False)
|
||||
cdef np.ndarray[np.float64_t, ndim=1, mode="c"] vector_to_numpy(VectorXd arr):
|
||||
cdef double[:] mem_view = <double[:arr.rows()]>arr.data()
|
||||
return np.copy(np.asarray(mem_view, dtype=np.double, order="C"))
|
||||
|
||||
cdef class EKF_sym_pyx:
|
||||
cdef EKFSym* ekf
|
||||
def __cinit__(self, str gen_dir, str name, np.ndarray[np.float64_t, ndim=2] Q,
|
||||
np.ndarray[np.float64_t, ndim=1] x_initial, np.ndarray[np.float64_t, ndim=2] P_initial, int dim_main,
|
||||
int dim_main_err, int N=0, int dim_augment=0, int dim_augment_err=0, list maha_test_kinds=[],
|
||||
list quaternion_idxs=[], list global_vars=[], double max_rewind_age=1.0, logger=None):
|
||||
# TODO logger
|
||||
ekf_load_and_register(gen_dir.encode('utf8'), name.encode('utf8'))
|
||||
|
||||
cdef np.ndarray[np.float64_t, ndim=2, mode='c'] Q_b = np.ascontiguousarray(Q, dtype=np.double)
|
||||
cdef np.ndarray[np.float64_t, ndim=1, mode='c'] x_initial_b = np.ascontiguousarray(x_initial, dtype=np.double)
|
||||
cdef np.ndarray[np.float64_t, ndim=2, mode='c'] P_initial_b = np.ascontiguousarray(P_initial, dtype=np.double)
|
||||
self.ekf = new EKFSym(
|
||||
name.encode('utf8'),
|
||||
MapMatrixXdr(<double*> Q_b.data, Q.shape[0], Q.shape[1]),
|
||||
MapVectorXd(<double*> x_initial_b.data, x_initial.shape[0]),
|
||||
MapMatrixXdr(<double*> P_initial_b.data, P_initial.shape[0], P_initial.shape[1]),
|
||||
dim_main,
|
||||
dim_main_err,
|
||||
N,
|
||||
dim_augment,
|
||||
dim_augment_err,
|
||||
maha_test_kinds,
|
||||
quaternion_idxs,
|
||||
[x.encode('utf8') for x in global_vars],
|
||||
max_rewind_age
|
||||
)
|
||||
|
||||
def init_state(self, np.ndarray[np.float64_t, ndim=1] state, np.ndarray[np.float64_t, ndim=2] covs, filter_time):
|
||||
cdef np.ndarray[np.float64_t, ndim=1, mode='c'] state_b = np.ascontiguousarray(state, dtype=np.double)
|
||||
cdef np.ndarray[np.float64_t, ndim=2, mode='c'] covs_b = np.ascontiguousarray(covs, dtype=np.double)
|
||||
self.ekf.init_state(
|
||||
MapVectorXd(<double*> state_b.data, state.shape[0]),
|
||||
MapMatrixXdr(<double*> covs_b.data, covs.shape[0], covs.shape[1]),
|
||||
np.nan if filter_time is None else filter_time
|
||||
)
|
||||
|
||||
def state(self):
|
||||
cdef np.ndarray res = vector_to_numpy(self.ekf.state())
|
||||
return res
|
||||
|
||||
def covs(self):
|
||||
return matrix_to_numpy(self.ekf.covs())
|
||||
|
||||
def set_filter_time(self, double t):
|
||||
self.ekf.set_filter_time(t)
|
||||
|
||||
def get_filter_time(self):
|
||||
return self.ekf.get_filter_time()
|
||||
|
||||
def set_global(self, str global_var, double val):
|
||||
self.ekf.set_global(global_var.encode('utf8'), val)
|
||||
|
||||
def reset_rewind(self):
|
||||
self.ekf.reset_rewind()
|
||||
|
||||
def predict(self, double t):
|
||||
self.ekf.predict(t)
|
||||
|
||||
def predict_and_update_batch(self, double t, int kind, z, R, extra_args=[[]], bool augment=False):
|
||||
cdef vector[MapVectorXd] z_map
|
||||
cdef np.ndarray[np.float64_t, ndim=1, mode='c'] zi_b
|
||||
for zi in z:
|
||||
zi_b = np.ascontiguousarray(zi, dtype=np.double)
|
||||
z_map.push_back(MapVectorXd(<double*> zi_b.data, zi.shape[0]))
|
||||
|
||||
cdef vector[MapMatrixXdr] R_map
|
||||
cdef np.ndarray[np.float64_t, ndim=2, mode='c'] Ri_b
|
||||
for Ri in R:
|
||||
Ri_b = np.ascontiguousarray(Ri, dtype=np.double)
|
||||
R_map.push_back(MapMatrixXdr(<double*> Ri_b.data, Ri.shape[0], Ri.shape[1]))
|
||||
|
||||
cdef vector[vector[double]] extra_args_map
|
||||
cdef vector[double] args_map
|
||||
for args in extra_args:
|
||||
args_map.clear()
|
||||
for a in args:
|
||||
args_map.push_back(a)
|
||||
extra_args_map.push_back(args_map)
|
||||
|
||||
cdef optional[Estimate] res = self.ekf.predict_and_update_batch(t, kind, z_map, R_map, extra_args_map, augment)
|
||||
if not res.has_value():
|
||||
return None
|
||||
|
||||
cdef VectorXd tmpvec
|
||||
return (
|
||||
vector_to_numpy(res.value().xk1),
|
||||
vector_to_numpy(res.value().xk),
|
||||
matrix_to_numpy(res.value().Pk1),
|
||||
matrix_to_numpy(res.value().Pk),
|
||||
res.value().t,
|
||||
res.value().kind,
|
||||
[vector_to_numpy(tmpvec) for tmpvec in res.value().y],
|
||||
z, # TODO: take return values?
|
||||
extra_args,
|
||||
)
|
||||
|
||||
def augment(self):
|
||||
raise NotImplementedError() # TODO
|
||||
|
||||
def get_augment_times(self):
|
||||
raise NotImplementedError() # TODO
|
||||
|
||||
def rts_smooth(self, estimates, norm_quats=False):
|
||||
raise NotImplementedError() # TODO
|
||||
|
||||
def maha_test(self, x, P, kind, z, R, extra_args=[], maha_thresh=0.95):
|
||||
raise NotImplementedError() # TODO
|
||||
|
||||
def __dealloc__(self):
|
||||
del self.ekf
|
||||
@@ -1,8 +1,13 @@
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from rednose.helpers.ekf_sym import EKF_sym
|
||||
from rednose.helpers.ekf_sym_pyx import EKF_sym_pyx
|
||||
|
||||
|
||||
class KalmanFilter:
|
||||
name = "<name>"
|
||||
initial_x: np.ndarray = np.zeros(0)
|
||||
@@ -10,8 +15,8 @@ class KalmanFilter:
|
||||
Q: np.ndarray = np.zeros((0, 0))
|
||||
obs_noise: dict[int, Any] = {}
|
||||
|
||||
# Should be initialized when initializating a KalmanFilter implementation
|
||||
filter = None
|
||||
# Initialized by each KalmanFilter implementation.
|
||||
filter: "EKF_sym | EKF_sym_pyx"
|
||||
|
||||
@property
|
||||
def x(self):
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import platform
|
||||
|
||||
import eigen
|
||||
from SCons.Script import Dir, File
|
||||
from SCons.Script import Dir, File # ty: ignore[import-not-found]
|
||||
|
||||
|
||||
def compile_single_filter(env, target, filter_gen_script, output_dir, extra_gen_artifacts, script_deps):
|
||||
|
||||
+2
-2
@@ -29,8 +29,8 @@
|
||||
{
|
||||
"path": "rednose_repo",
|
||||
"url": "https://github.com/commaai/rednose.git",
|
||||
"commit": "d7c66e80d2d28a63d0720692ccaa029d504751ba",
|
||||
"tree": "9f000b8db090de568e6111f2d2861445708e7b27",
|
||||
"commit": "e60428b2e52f139d5fe5466d4d9fa3c6adeadad8",
|
||||
"tree": "73e14774a5000d33df8b59b68c42275e5b419d21",
|
||||
"exclude": []
|
||||
},
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user