mirror of
https://github.com/firestar5683/StarPilot.git
synced 2026-12-02 04:53:40 +08:00
Preserve Qualified FLM Producer Sources
This commit is contained in:
-10
@@ -8,8 +8,6 @@ import importlib
|
||||
import re
|
||||
import stat
|
||||
import numpy as np
|
||||
import eigen
|
||||
import nanobind
|
||||
|
||||
import SCons.Errors
|
||||
from SCons.Defaults import _stripixes
|
||||
@@ -251,14 +249,6 @@ 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
|
||||
|
||||
@@ -97,12 +97,13 @@ void *alloc_w_mmu_hdl(int video0_fd, int len, uint32_t *handle, int align, int f
|
||||
mem_mgr_alloc_cmd.align = align;
|
||||
mem_mgr_alloc_cmd.flags = flags;
|
||||
mem_mgr_alloc_cmd.num_hdl = 0;
|
||||
// -1 is the only invalid IOMMU handle: the kernel makes them (context bank index << 16) | 16 random bits, and the
|
||||
// ISP's bank is index 0, so its handle is 0 on 1 boot in 65536
|
||||
for (int hdl : {mmu_hdl, mmu_hdl2}) {
|
||||
if (hdl != -1) {
|
||||
mem_mgr_alloc_cmd.mmu_hdls[mem_mgr_alloc_cmd.num_hdl++] = hdl;
|
||||
}
|
||||
if (mmu_hdl != 0) {
|
||||
mem_mgr_alloc_cmd.mmu_hdls[0] = mmu_hdl;
|
||||
mem_mgr_alloc_cmd.num_hdl++;
|
||||
}
|
||||
if (mmu_hdl2 != 0) {
|
||||
mem_mgr_alloc_cmd.mmu_hdls[1] = mmu_hdl2;
|
||||
mem_mgr_alloc_cmd.num_hdl++;
|
||||
}
|
||||
|
||||
do_cam_control(video0_fd, CAM_REQ_MGR_ALLOC_BUF, &mem_mgr_alloc_cmd, sizeof(mem_mgr_alloc_cmd));
|
||||
@@ -1220,7 +1221,7 @@ void SpectraCamera::configICP() {
|
||||
release(m->video0_fd, cfg_handle);
|
||||
|
||||
// BPS has a lot of buffers to init
|
||||
bps_cmd.init(m, 464, 0x20, true, m->icp_device_iommu, -1, ife_buf_depth);
|
||||
bps_cmd.init(m, 464, 0x20, true, m->icp_device_iommu, 0, ife_buf_depth);
|
||||
|
||||
// BPSIQSettings struct
|
||||
uint32_t settings_size = sizeof(bps_settings[0]) / sizeof(bps_settings[0][0]);
|
||||
@@ -1557,21 +1558,8 @@ bool SpectraCamera::processFrame(int buf_idx, uint64_t request_id, uint64_t ife_
|
||||
bool SpectraCamera::syncFirstFrame(int camera_id, uint64_t request_id, uint64_t ife_frame_id, uint64_t timestamp, bool staggered) {
|
||||
if (first_frame_synced) return true;
|
||||
|
||||
// The sensors free-run for their first frames, then each jumps onto its FSIN pulse. The frame that lands on FSIN
|
||||
// isn't settled yet: rarely a stray frame start follows it (CSID UNBOUNDED_FRAME), and the sensor slips a frame
|
||||
// getting back onto FSIN. Syncing on that landing frame leaves the camera's frame IDs off by one for the whole
|
||||
// session. Only sync on a frame that came one frame period after the camera's previous frame.
|
||||
const uint64_t period_ns = 50 * 1000000ULL; // 50ms
|
||||
const uint64_t tolerance_ns = 200000ULL; // 0.2ms
|
||||
bool settled = false;
|
||||
if (auto prev = camera_sync_data.find(camera_id); prev != camera_sync_data.end() &&
|
||||
ife_frame_id == prev->second.frame_id_offset && timestamp > prev->second.timestamp) {
|
||||
uint64_t dt = timestamp - prev->second.timestamp;
|
||||
settled = (dt > period_ns ? dt - period_ns : period_ns - dt) <= tolerance_ns;
|
||||
}
|
||||
|
||||
// Store the frame data for this camera
|
||||
camera_sync_data[camera_id] = SyncData{timestamp, ife_frame_id + 1, staggered, settled};
|
||||
camera_sync_data[camera_id] = SyncData{timestamp, ife_frame_id + 1, staggered};
|
||||
|
||||
// Ensure all cameras are up
|
||||
int enabled_camera_count = std::count_if(std::begin(ALL_CAMERA_CONFIGS), std::end(ALL_CAMERA_CONFIGS),
|
||||
@@ -1581,12 +1569,10 @@ bool SpectraCamera::syncFirstFrame(int camera_id, uint64_t request_id, uint64_t
|
||||
// Check that camera timestamps are properly aligned:
|
||||
// - non-staggered cameras should be within 0.2ms of each other
|
||||
// - staggered cameras should be within 0.2ms of a 25ms offset from non-staggered cameras
|
||||
const uint64_t half_period_ns = period_ns / 2; // 25ms
|
||||
const uint64_t half_period_ns = 25 * 1000000ULL; // 25ms
|
||||
const uint64_t tolerance_ns = 200000ULL; // 0.2ms
|
||||
bool all_cams_synced = true;
|
||||
for (const auto &[cam, sync_data] : camera_sync_data) {
|
||||
if (!sync_data.settled) {
|
||||
all_cams_synced = false;
|
||||
}
|
||||
if (cam == camera_id) continue;
|
||||
uint64_t diff = std::max(timestamp, sync_data.timestamp) -
|
||||
std::min(timestamp, sync_data.timestamp);
|
||||
|
||||
@@ -3,7 +3,10 @@ generated/
|
||||
*.swp
|
||||
*.tmp
|
||||
|
||||
# SCons objects
|
||||
# Cython intermediates
|
||||
*_pyx.cpp
|
||||
*_pyx.h
|
||||
*_pyx_api.h
|
||||
*.os
|
||||
|
||||
# Byte-compiled / optimized / DLL files
|
||||
@@ -145,5 +148,5 @@ dmypy.json
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Generated binding stubs
|
||||
rednose/helpers/ekf_sym_pyx.pyi
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
+12
-16
@@ -2,7 +2,7 @@ import os
|
||||
import platform
|
||||
import subprocess
|
||||
import sysconfig
|
||||
import nanobind
|
||||
import numpy as np
|
||||
import eigen
|
||||
|
||||
arch = subprocess.check_output(["uname", "-m"], encoding='utf8').rstrip()
|
||||
@@ -16,6 +16,7 @@ cpppath = [
|
||||
'#rednose/examples/generated',
|
||||
'/usr/lib/include',
|
||||
python_path,
|
||||
np.get_include(),
|
||||
eigen.INCLUDE_DIR,
|
||||
]
|
||||
|
||||
@@ -37,28 +38,23 @@ env = Environment(
|
||||
CXXFLAGS="-std=c++1z",
|
||||
CPPPATH=cpppath,
|
||||
REDNOSE_ROOT=Dir("#").abspath,
|
||||
tools=["default", "rednose_filter"],
|
||||
tools=["default", "cython", "rednose_filter"],
|
||||
)
|
||||
|
||||
# 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")
|
||||
# Cython build enviroment
|
||||
envCython = env.Clone()
|
||||
envCython["CCFLAGS"] += ["-Wno-#warnings", "-Wno-cpp", "-Wno-shadow", "-Wno-deprecated-declarations"]
|
||||
|
||||
envNanobind["LIBS"] = []
|
||||
envCython["LIBS"] = []
|
||||
if platform.system() == "Darwin":
|
||||
envNanobind["LINKFLAGS"] = ["-bundle", "-undefined", "dynamic_lookup"]
|
||||
envCython["LINKFLAGS"] = ["-bundle", "-undefined", "dynamic_lookup"]
|
||||
elif arch == "aarch64":
|
||||
envNanobind["LINKFLAGS"] = ["-shared"]
|
||||
envNanobind["LIBS"] = [os.path.basename(python_path)]
|
||||
envCython["LINKFLAGS"] = ["-shared"]
|
||||
envCython["LIBS"] = [os.path.basename(python_path)]
|
||||
else:
|
||||
envNanobind["LINKFLAGS"] = ["-pthread", "-shared"]
|
||||
envCython["LINKFLAGS"] = ["-pthread", "-shared"]
|
||||
|
||||
Export('env', 'envNanobind', 'common')
|
||||
Export('env', 'envCython', 'common')
|
||||
|
||||
SConscript(['#rednose/SConscript'])
|
||||
SConscript(['#examples/SConscript'])
|
||||
|
||||
@@ -266,7 +266,7 @@ class LiveKalman():
|
||||
|
||||
@property
|
||||
def t(self):
|
||||
return self.filter.get_filter_time()
|
||||
return self.filter.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.state()[States.ECEF_ORIENTATION])
|
||||
quat_norm = np.linalg.norm(self.filter.x[3:7, 0])
|
||||
|
||||
# Should not continue if the quats behave this weirdly
|
||||
if not (0.1 < quat_norm < 10):
|
||||
raise KalmanError("Kalman filter quaternions unstable")
|
||||
|
||||
self.filter.normalize_slice(States.ECEF_ORIENTATION.start, States.ECEF_ORIENTATION.stop)
|
||||
self.filter.x[States.ECEF_ORIENTATION, 0] = self.filter.x[States.ECEF_ORIENTATION, 0] / quat_norm
|
||||
|
||||
return r
|
||||
|
||||
|
||||
@@ -84,29 +84,6 @@ 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 # ty: ignore[import-not-found]
|
||||
import matplotlib.pyplot as plt # pylint: disable=import-error
|
||||
plt.figure()
|
||||
plt.subplot(2, 1, 1)
|
||||
plt.plot(ts, xs, 'k', label='Simulation')
|
||||
|
||||
@@ -11,7 +11,7 @@ dependencies = [
|
||||
"cffi",
|
||||
"sympy",
|
||||
"comma-deps-eigen",
|
||||
"nanobind>=2.0",
|
||||
"Cython",
|
||||
"scons",
|
||||
"setuptools",
|
||||
]
|
||||
@@ -31,7 +31,7 @@ build-backend = "setuptools.build_meta"
|
||||
include = ["rednose*"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
"*" = ["*.so", "py.typed", "helpers/*.pyi", "helpers/chi2_lookup_table.npy", "templates/*"]
|
||||
"*" = ["*.so", "helpers/chi2_lookup_table.npy", "templates/*"]
|
||||
|
||||
# https://beta.ruff.rs/docs/configuration/#using-pyprojecttoml
|
||||
[tool.ruff]
|
||||
@@ -42,3 +42,7 @@ 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,13 +1,11 @@
|
||||
import sys
|
||||
|
||||
import eigen
|
||||
|
||||
Import('env', 'envNanobind', 'common')
|
||||
Import('env', 'envCython', 'common')
|
||||
|
||||
env = env.Clone()
|
||||
env.Append(CPPPATH=[eigen.INCLUDE_DIR])
|
||||
envNanobind = envNanobind.Clone()
|
||||
envNanobind.Append(CPPPATH=[eigen.INCLUDE_DIR])
|
||||
envCython = envCython.Clone()
|
||||
envCython.Append(CPPPATH=[eigen.INCLUDE_DIR])
|
||||
|
||||
cc_sources = [
|
||||
"helpers/ekf_load.cc",
|
||||
@@ -20,15 +18,7 @@ if common != "":
|
||||
|
||||
ekf_objects = env.SharedObject(cc_sources)
|
||||
rednose = env.Library("helpers/ekf_sym", ekf_objects, LIBS=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"]],
|
||||
)
|
||||
rednose_python = envCython.Program("helpers/ekf_sym_pyx.so", ["helpers/ekf_sym_pyx.pyx", ekf_objects],
|
||||
LIBS=libs + envCython["LIBS"])
|
||||
|
||||
Export('rednose', 'rednose_python')
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
#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,37 +0,0 @@
|
||||
from collections.abc import Sequence
|
||||
from typing import Annotated
|
||||
|
||||
import numpy
|
||||
from numpy.typing import NDArray
|
||||
|
||||
|
||||
class EKF_sym_pyx:
|
||||
def __init__(self, gen_dir: str, name: str, Q: Annotated[NDArray[numpy.float64], dict(shape=(None, None), order='C')], x_initial: Annotated[NDArray[numpy.float64], dict(shape=(None,), order='C')], P_initial: Annotated[NDArray[numpy.float64], dict(shape=(None, None), order='C')], dim_main: int, dim_main_err: int, N: int = 0, dim_augment: int = 0, dim_augment_err: int = 0, maha_test_kinds: Sequence[int] = [], quaternion_idxs: Sequence[int] = [], global_vars: Sequence[str] = [], max_rewind_age: float = 1.0, logger: object | None = None) -> None: ...
|
||||
|
||||
def init_state(self, state: Annotated[NDArray[numpy.float64], dict(shape=(None,), order='C')], covs: Annotated[NDArray[numpy.float64], dict(shape=(None, None), order='C')], filter_time: object | None) -> None: ...
|
||||
|
||||
def state(self) -> Annotated[NDArray[numpy.float64], dict(shape=(None,), order='C')]: ...
|
||||
|
||||
def covs(self) -> Annotated[NDArray[numpy.float64], dict(shape=(None, None), order='C')]: ...
|
||||
|
||||
def set_filter_time(self, t: float) -> None: ...
|
||||
|
||||
def get_filter_time(self) -> float: ...
|
||||
|
||||
def set_global(self, global_var: str, val: float) -> None: ...
|
||||
|
||||
def normalize_slice(self, slice_start: int, slice_end_ex: int) -> None: ...
|
||||
|
||||
def reset_rewind(self) -> None: ...
|
||||
|
||||
def predict(self, t: float) -> None: ...
|
||||
|
||||
def predict_and_update_batch(self, t: float, kind: int, z: object, R: object, extra_args: object = [[]], augment: bool = False) -> tuple | None: ...
|
||||
|
||||
def augment(self) -> None: ...
|
||||
|
||||
def get_augment_times(self) -> None: ...
|
||||
|
||||
def rts_smooth(self, estimates: object, norm_quats: bool = False) -> None: ...
|
||||
|
||||
def maha_test(self, x: object, P: object, kind: int, z: object, R: object, extra_args: object = [], maha_thresh: float = 0.95) -> None: ...
|
||||
@@ -0,0 +1,195 @@
|
||||
# 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
|
||||
Binary file not shown.
@@ -1,13 +1,8 @@
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from typing import 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)
|
||||
@@ -15,8 +10,8 @@ class KalmanFilter:
|
||||
Q: np.ndarray = np.zeros((0, 0))
|
||||
obs_noise: dict[int, Any] = {}
|
||||
|
||||
# Initialized by each KalmanFilter implementation.
|
||||
filter: "EKF_sym | EKF_sym_pyx"
|
||||
# Should be initialized when initializating a KalmanFilter implementation
|
||||
filter = None
|
||||
|
||||
@property
|
||||
def x(self):
|
||||
|
||||
Binary file not shown.
@@ -1,7 +1,7 @@
|
||||
import platform
|
||||
|
||||
import eigen
|
||||
from SCons.Script import Dir, File # ty: ignore[import-not-found]
|
||||
from SCons.Script import Dir, File
|
||||
|
||||
|
||||
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": "e60428b2e52f139d5fe5466d4d9fa3c6adeadad8",
|
||||
"tree": "73e14774a5000d33df8b59b68c42275e5b419d21",
|
||||
"commit": "d7c66e80d2d28a63d0720692ccaa029d504751ba",
|
||||
"tree": "9f000b8db090de568e6111f2d2861445708e7b27",
|
||||
"exclude": []
|
||||
},
|
||||
{
|
||||
|
||||
@@ -648,6 +648,8 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/36/c1/6fd56f7a02a478d54a1a3e6000eccd34b446b1c45cbf0d002fe5d2937126/nanobind-3.1.0-py3-none-any.whl", hash = "sha256:96984dbe8154ffb86e653b1b60aaeed6985c710c5e75ad0279eb87943c66292d", size = 316917, upload-time = "2026-09-18T15:59:37.796Z" },
|
||||
]
|
||||
|
||||
|
||||
|
||||
[[package]]
|
||||
name = "numpy"
|
||||
version = "2.5.3"
|
||||
@@ -717,7 +719,6 @@ dependencies = [
|
||||
{ name = "comma-deps-json11" },
|
||||
{ name = "comma-deps-raylib" },
|
||||
{ name = "comma-deps-zstd" },
|
||||
{ name = "cython" },
|
||||
{ name = "inputs" },
|
||||
{ name = "jeepney" },
|
||||
{ name = "numpy" },
|
||||
@@ -762,9 +763,9 @@ tools = [
|
||||
{ name = "matplotlib" },
|
||||
]
|
||||
vendored = [
|
||||
{ name = "nanobind" },
|
||||
{ name = "jetlink" },
|
||||
{ name = "msgq-ipc", extra = ["build"] },
|
||||
{ name = "nanobind" },
|
||||
{ name = "opendbc" },
|
||||
{ name = "pandacan" },
|
||||
{ name = "rednose" },
|
||||
@@ -779,6 +780,7 @@ standalone = [
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "nanobind", marker = "extra == 'vendored'", specifier = "==3.1.0" },
|
||||
{ name = "cffi", marker = "extra == 'safety'" },
|
||||
{ name = "codespell", marker = "extra == 'testing'" },
|
||||
{ name = "comma-deps-acados" },
|
||||
@@ -794,14 +796,12 @@ requires-dist = [
|
||||
{ name = "comma-deps-zstd" },
|
||||
{ name = "coverage", marker = "extra == 'testing'" },
|
||||
{ name = "cppcheck", marker = "extra == 'safety'", git = "https://github.com/commaai/dependencies.git?subdirectory=cppcheck&rev=b7253ddb101ed6add04fc2a2ce0688d5e21a55ee" },
|
||||
{ name = "cython" },
|
||||
{ name = "gcovr", marker = "extra == 'safety'", specifier = "==8.6" },
|
||||
{ name = "inputs" },
|
||||
{ name = "jeepney" },
|
||||
{ name = "jetlink", marker = "extra == 'vendored'", editable = "jetlink_repo" },
|
||||
{ name = "matplotlib", marker = "extra == 'tools'" },
|
||||
{ name = "msgq-ipc", extras = ["build"], marker = "extra == 'vendored'", virtual = "msgq_repo" },
|
||||
{ name = "nanobind", marker = "extra == 'vendored'", specifier = "==3.1.0" },
|
||||
{ name = "numpy", specifier = ">=2.0" },
|
||||
{ name = "opendbc", marker = "extra == 'vendored'", editable = "opendbc_repo" },
|
||||
{ name = "pandacan", marker = "extra == 'vendored'", editable = "panda" },
|
||||
@@ -1053,7 +1053,7 @@ source = { editable = "rednose_repo" }
|
||||
dependencies = [
|
||||
{ name = "cffi" },
|
||||
{ name = "comma-deps-eigen" },
|
||||
{ name = "nanobind" },
|
||||
{ name = "cython" },
|
||||
{ name = "numpy" },
|
||||
{ name = "scons" },
|
||||
{ name = "setuptools" },
|
||||
@@ -1064,7 +1064,7 @@ dependencies = [
|
||||
requires-dist = [
|
||||
{ name = "cffi" },
|
||||
{ name = "comma-deps-eigen" },
|
||||
{ name = "nanobind", specifier = ">=2.0" },
|
||||
{ name = "cython" },
|
||||
{ name = "numpy" },
|
||||
{ name = "ruff", marker = "extra == 'dev'" },
|
||||
{ name = "scipy", marker = "extra == 'dev'" },
|
||||
@@ -1242,7 +1242,7 @@ requires-dist = [
|
||||
{ name = "mkdocs", marker = "extra == 'docs'" },
|
||||
{ name = "mkdocs-material", marker = "extra == 'docs'" },
|
||||
{ name = "mkdocstrings", extras = ["python"], marker = "extra == 'docs'" },
|
||||
{ name = "mypy", marker = "extra == 'linting'", specifier = "==2.3.1" },
|
||||
{ name = "mypy", marker = "extra == 'linting'", specifier = "==1.19.1" },
|
||||
{ name = "networkx", marker = "extra == 'testing'" },
|
||||
{ name = "nibabel", marker = "extra == 'testing'" },
|
||||
{ name = "numba", marker = "extra == 'testing'", specifier = ">=0.55" },
|
||||
@@ -1263,7 +1263,7 @@ requires-dist = [
|
||||
{ name = "pytest-split", marker = "extra == 'testing-minimal'" },
|
||||
{ name = "pytest-xdist", marker = "extra == 'testing-minimal'" },
|
||||
{ name = "pyyaml", marker = "extra == 'autogen'" },
|
||||
{ name = "ruff", marker = "extra == 'linting'", specifier = "==0.16.4" },
|
||||
{ name = "ruff", marker = "extra == 'linting'", specifier = "==0.14.10" },
|
||||
{ name = "safetensors", marker = "extra == 'testing-unit'" },
|
||||
{ name = "sentencepiece", marker = "extra == 'testing'" },
|
||||
{ name = "tabulate", marker = "extra == 'testing-unit'" },
|
||||
@@ -1276,7 +1276,7 @@ requires-dist = [
|
||||
{ name = "transformers", marker = "extra == 'testing'" },
|
||||
{ name = "typeguard", marker = "extra == 'linting'" },
|
||||
{ name = "typing-extensions", marker = "extra == 'linting'" },
|
||||
{ name = "z3-solver", marker = "extra == 'testing-minimal'", specifier = "==5.1.0.0" },
|
||||
{ name = "z3-solver", marker = "extra == 'testing-minimal'", specifier = "<4.15.4" },
|
||||
]
|
||||
provides-extras = ["linting", "testing-minimal", "testing-unit", "testing", "docs", "mesa", "autogen"]
|
||||
|
||||
|
||||
Reference in New Issue
Block a user