Production-ready MoonBit state estimation, smoothing, and sensor fusion library
moon add Lyllyl789/moon-kalman@0.2.1import {
"Lyllyl789/moon-kalman" @kalman,
}fn main {
let filter = @kalman.Kalman1D::new(0.0, 1.0, 0.02, 0.1)
filter.set_gate_threshold(9.210340371976184)
filter.predict_without_control()
let result = filter.update_if_valid(1.0)
println(
"result=\{@kalman.update_result_to_string(result)}, state=\{filter.state()}, variance=\{filter.uncertainty()}",
)
}# 运行两路传感器融合示例
moon run examples/sensor_fusion
# 运行 native release 基准
moon run --target native --release benchmarks| 范围 | 文件数 | 行数 |
|---|---|---|
| 根库非测试 MoonBit 源码 | 46 | 19,963 |
| 示例与基准入口 | 2 | 81 |
| 仓库非测试 MoonBit 源码合计 | 48 | 20,044 |
| 测试 MoonBit 源码 | 16 | 2,418 |
moon run --target native --release benchmarks| 场景 | 工作量 | 记录耗时 | 记录吞吐 |
|---|---|---|---|
| 标量更新 | 1,000,000 次 | 14–15 ms | 66.67–71.43 M updates/s |
| 4×2 矩阵更新 | 10,000 次 | 143–195 ms | 51.28–69.93 k updates/s |
moon check --target all --deny-warn
moon build --target all --deny-warn
moon test --target all --deny-warnmoon test --target native --deny-warn --enable-coverage
moon coverage report -f summarymoon version --all
moon update
moon check --target all --deny-warn
moon build --target all --deny-warn
moon test --target all --deny-warn
moon run examples/sensor_fusion
moon fmt && git diff --exit-code
moon info && git diff --exit-codepub struct AdaptiveNoiseController {
process_scale : Double
measurement_scale : Double
minimum_scale : Double
maximum_scale : Double
target_nis : Double
learning_rate : Double
}fn AdaptiveNoiseController::new(minimum_scale : Double, maximum_scale : Double, target_nis : Double, learning_rate : Double) -> AdaptiveNoiseControllerpub struct AlignedVector {
timestamp : Int
values : Array[Double]
status : AlignmentStatus
source_timestamp : Int
quality : Double
distance : Int
} derive(Debug)fn AlignedVector::new(timestamp : Int, values : Array[Double], status : AlignmentStatus, source_timestamp : Int, quality : Double, distance : Int) -> AlignedVectorpub struct AlignmentPolicy {
tolerance : Int
max_gap : Int
allow_extrapolation : Bool
minimum_quality : Double
} derive(Debug)fn AlignmentPolicy::new(tolerance : Int, max_gap : Int, allow_extrapolation : Bool, minimum_quality : Double) -> AlignmentPolicypub struct AlignmentReport {
requested : Int
produced : Int
exact : Int
nearest : Int
interpolated : Int
extrapolated : Int
missing : Int
invalid : Int
maximum_distance : Int
mean_distance : Double
} derive(Debug)pub struct AssociationBatch {
decisions : Array[AssociationDecision]
candidates : Array[AssociationCandidate]
unmatched_measurements : Array[Int]
total_cost : Double
accepted_count : Int
} derive(Debug)fn AssociationBatch::new(decisions : Array[AssociationDecision], candidates : Array[AssociationCandidate], unmatched_measurements : Array[Int]) -> AssociationBatchpub struct AssociationCandidate {
track_id : Int
measurement_id : Int
distance : Double
likelihood : Double
gated : Bool
metric : String
} derive(Debug)fn AssociationCandidate::new(track_id : Int, measurement_id : Int, distance : Double, likelihood : Double, gated : Bool, metric : String) -> AssociationCandidatepub struct AssociationConfig {
gate_threshold : Double
minimum_likelihood : Double
miss_cost : Double
allow_reuse : Bool
prefer_likelihood : Bool
} derive(Debug)fn AssociationConfig::new(gate_threshold : Double, minimum_likelihood : Double, miss_cost : Double) -> AssociationConfigfn AssociationConfig::with_likelihood_priority(self : AssociationConfig, enabled : Bool) -> AssociationConfigpub struct AssociationDecision {
track_id : Int
measurement_id : Int?
distance : Double
confidence : Double
accepted : Bool
reason : String
} derive(Debug)fn AssociationDecision::accepted(track_id : Int, measurement_id : Int, distance : Double, confidence : Double, reason : String) -> AssociationDecisionpub struct BatchGate {
policy : ResidualPolicy
inspected : Int
accepted : Int
downweighted : Int
rejected : Int
}fn BatchObservation::new(features : Array[Double], value : Double, weight : Double, timestamp : Int) -> BatchObservationfn CalibrationTransform::apply(self : CalibrationTransform, values : Array[Double]) -> Array[Double]fn CalibrationTransform::inverse(self : CalibrationTransform, values : Array[Double]) -> Array[Double]pub struct ConfidenceBand {
estimate : Double
lower : Double
upper : Double
standard_deviation : Double
multiplier : Double
valid : Bool
} derive(Debug)fn ConfidenceBand::new(estimate : Double, standard_deviation : Double, multiplier : Double) -> ConfidenceBandpub struct ConsistencyReport {
count : Int
average_nees : Double
average_nis : Double
accepted_rate : Double
covariance_failures : Int
} derive(Debug)pub struct ConstantVelocityTracker2D {
filter : KalmanND
acceleration_variance : Double
position_variance : Double
last_timestamp : Int
initialized_timestamp : Bool
}fn ConstantVelocityTracker2D::new(initial_position : Array[Double], initial_velocity : Array[Double], initial_variance : Double, acceleration_variance : Double, position_variance : Double) -> ConstantVelocityTracker2Dfn ConstantVelocityTracker2D::set_gate_threshold(self : ConstantVelocityTracker2D, threshold : Double) -> Unitfn ConstantVelocityTracker2D::step(self : ConstantVelocityTracker2D, timestamp : Int, position : Array[Double], covariance : Matrix) -> UpdateResultfn ConstantVelocityTracker2D::step_position(self : ConstantVelocityTracker2D, timestamp : Int, x : Double, y : Double) -> UpdateResultpub struct ContractIssue {
code : String
severity : ContractSeverity
message : String
} derive(Debug)fn ContractIssue::new(code : String, severity : ContractSeverity, message : String) -> ContractIssuefn ControlCommand::new(timestamp : Int, values : Array[Double], duration : Double) -> ControlCommandpub struct ControlIntegrator {
dimension : Int
state : Array[Double]
limits : ControlLimits
response : Double
}fn ControlIntegrator::new(dimension : Int, limits : ControlLimits, response : Double) -> ControlIntegratorfn ControlIntegrator::step(self : ControlIntegrator, command : Array[Double], dt : Double) -> Array[Double]pub struct CovarianceReport {
health : CovarianceHealth
dimension : Int
symmetry_error : Double
minimum_eigenvalue : Double
maximum_eigenvalue : Double
condition_estimate : Double
finite : Bool
positive_diagonal : Bool
} derive(Debug)pub struct CovarianceSummary {
dimension : Int
trace : Double
determinant : Double
minimum_diagonal : Double
maximum_diagonal : Double
condition : Double
rank : Int
symmetric : Bool
positive_diagonal : Bool
finite : Bool
} derive(Debug)pub struct DataQualityReport {
total : Int
valid : Int
missing : Int
non_finite : Int
non_monotonic_timestamps : Int
duplicate_timestamps : Int
finite_fraction : Double
} derive(Debug)pub struct DeterministicRng {
state : Int
}pub struct DiagnosticAccumulator {
reports : Array[DiagnosticReport]
capacity : Int
discarded : Int
} derive(Debug)pub struct DiagnosticEvent {
timestamp : Int
code : String
severity : DiagnosticSeverity
message : String
value : Double
acknowledged : Bool
} derive(Debug)fn DiagnosticEvent::new(timestamp : Int, code : String, severity : DiagnosticSeverity, message : String, value : Double) -> DiagnosticEventpub struct DiagnosticField {
name : String
value : Double
unit : String
category : String
healthy : Bool
} derive(Debug)fn DiagnosticField::new(name : String, value : Double, unit : String, category : String, healthy : Bool) -> DiagnosticFieldpub struct DiagnosticReport {
run_id : String
started_at : Int
finished_at : Int?
snapshots : Array[DiagnosticSnapshot]
events : Array[DiagnosticEvent]
closed : Bool
} derive(Debug)pub struct DiagnosticSnapshot {
timestamp : Int
source : String
fields : Array[DiagnosticField]
state_dimension : Int
covariance_dimension : Int
healthy : Bool
score : Double
} derive(Debug)fn DiagnosticSnapshot::new(timestamp : Int, source : String, fields : Array[DiagnosticField], state_dimension : Int, covariance_dimension : Int) -> DiagnosticSnapshotpub struct EKF {
x : Array[Double]
p : Matrix
q : Matrix
r : Matrix
initial_state : Array[Double]
initial_covariance : Matrix
last_innovation : Array[Double]
last_innovation_covariance : Matrix
last_gain : Matrix
last_nis : Double
gate_threshold : Double
predict_count : Int
accepted_count : Int
rejected_count : Int
missing_count : Int
}pub(all) struct ErrorMetrics {
count : Int
rmse : Double
mae : Double
max_error : Double
final_error : Double
} derive(Debug)pub struct ExponentialStats {
alpha : Double
count : Int
mean : Double
variance : Double
minimum : Double
maximum : Double
}pub struct FeatureVector {
mean : Double
variance : Double
slope : Double
minimum : Double
maximum : Double
energy : Double
} derive(Debug)fn FilterCheckpoint::new(state : Array[Double], covariance : Matrix, timestamp : Int) -> FilterCheckpointfn FixedLagSmoother::push(self : FixedLagSmoother, filtered_state : Array[Double], filtered_covariance : Matrix, predicted_state : Array[Double], predicted_covariance : Matrix, transition : Matrix) -> Unitpub struct FusionEvent {
timestamp : Int
sensor : String
result : UpdateResult
state : Array[Double]
covariance : Matrix
nis : Double
} derive(Debug)fn FusionMeasurement::new(sensor : String, timestamp : Int, values : Array[Double], covariance : Matrix, confidence : Double) -> FusionMeasurementpub struct FusionPolicy {
gate_threshold : Double
max_time_gap : Int
covariance_inflation : Double
reject_non_finite : Bool
predict_on_missing : Bool
} derive(Debug)fn FusionPolicy::new(gate_threshold : Double, max_time_gap : Int, covariance_inflation : Double, reject_non_finite : Bool, predict_on_missing : Bool) -> FusionPolicypub struct FusionResult {
strategy : FusionStrategy
timestamp : Int
values : Array[Double]
covariance : Matrix
used : Int
rejected : Int
} derive(Debug)pub struct FusionStatistics {
total_packets : Int
accepted_packets : Int
rejected_packets : Int
missing_packets : Int
last_timestamp : Int
} derive(Debug)pub struct GateSchedule {
base_threshold : Double
minimum_threshold : Double
maximum_threshold : Double
consecutive_rejections : Int
recovery_steps : Int
}fn GateSchedule::new(base_threshold : Double, minimum_threshold : Double, maximum_threshold : Double, recovery_steps : Int) -> GateSchedulepub struct Histogram {
minimum : Double
maximum : Double
buckets : Array[HistogramBucket]
underflow : Int
overflow : Int
samples : Int
}pub struct InnovationMonitor {
dimension : Int
threshold : Double
samples : Int
accepted : Int
rejected : Int
nis_stats : RunningStats
last_nis : Double
}fn InnovationMonitor::observe(self : InnovationMonitor, innovation : Array[Double], covariance : Matrix) -> Boolpub struct Kalman1D {
x : Double
p : Double
q : Double
r : Double
initial_state : Double
initial_uncertainty : Double
last_innovation : Double
last_innovation_variance : Double
last_gain : Double
last_nis : Double
gate_threshold : Double
predict_count : Int
accepted_count : Int
rejected_count : Int
missing_count : Int
}fn KalmanDiagnostics::check_covariance(self : KalmanDiagnostics, covariance : Array[Array[Double]]) -> Boolpub struct KalmanND {
x : Array[Double]
p : Matrix
q : Matrix
r : Matrix
f : Matrix
h : Matrix
initial_state : Array[Double]
initial_covariance : Matrix
last_innovation : Array[Double]
last_innovation_covariance : Matrix
last_gain : Matrix
last_nis : Double
gate_threshold : Double
predict_count : Int
accepted_count : Int
rejected_count : Int
missing_count : Int
}fn KalmanND::from_model(model : LinearModel, initial_state : Array[Double], initial_covariance : Matrix) -> KalmanNDfn KalmanND::update_gated(self : KalmanND, measurement : Array[Double], threshold : Double) -> UpdateResultfn LinearModel::new(transition : Matrix, process_noise : Matrix, observation : Matrix, measurement_noise : Matrix, control : Matrix) -> LinearModelfn Matrix::regularized_least_squares(self : Matrix, rhs : Array[Double], regularization : Double) -> MatrixSolveResultpub struct MeasurementSchedule {
period : Int
elapsed : Int
}pub struct MeasurementWindow {
measurements : Array[FusionMeasurement]
capacity : Int
dimension : Int
}pub struct MissingObservationPolicy {
max_consecutive : Int
inflate_factor : Double
action : MissingObservationAction
} derive(Debug)fn MissingObservationPolicy::new(max_consecutive : Int, inflate_factor : Double, action : MissingObservationAction) -> MissingObservationPolicypub struct ModelCatalog {
entries : Array[ModelCatalogEntry]
active_identity : String?
max_entries : Int
registrations : Int
selections : Int
} derive(Debug)fn ModelCatalog::select_or_active(self : ModelCatalog, policy : ModelSelectionPolicy) -> ModelSelectionResultfn ModelCatalogEntry::compatible(self : ModelCatalogEntry, dimension : Int, required_tags : Array[String]) -> Boolfn ModelCatalogEntry::new(name : String, version : String, dimension : Int, metric : String, score : Double, latency_ms : Double, memory_bytes : Int, tags : Array[String]) -> ModelCatalogEntryfn ModelCatalogEntry::with_score(self : ModelCatalogEntry, score : Double, latency_ms : Double) -> ModelCatalogEntryfn ModelEvaluation::new(entry : ModelCatalogEntry, eligible : Bool, normalized_score : Double, reasons : Array[String]) -> ModelEvaluationpub struct ModelScore {
name : String
rmse : Double
mae : Double
complexity : Int
consistency : Double
} derive(Debug)fn ModelScore::new(name : String, rmse : Double, mae : Double, complexity : Int, consistency : Double) -> ModelScorefn ModelSelectionPolicy::for_dimension(self : ModelSelectionPolicy, dimension : Int) -> ModelSelectionPolicyfn ModelSelectionPolicy::new(metric : String, higher_is_better : Bool, max_latency_ms : Double, max_memory_bytes : Int, minimum_score : Double) -> ModelSelectionPolicyfn ModelSelectionPolicy::with_tags(self : ModelSelectionPolicy, tags : Array[String]) -> ModelSelectionPolicypub struct ModelSelectionResult {
selected : ModelCatalogEntry?
evaluations : Array[ModelEvaluation]
fallback_used : Bool
reason : String
} derive(Debug)fn ModelSelectionResult::none(evaluations : Array[ModelEvaluation], reason : String) -> ModelSelectionResultfn ModelSelectionResult::selected(entry : ModelCatalogEntry, evaluations : Array[ModelEvaluation], fallback_used : Bool, reason : String) -> ModelSelectionResultpub struct NoiseEstimate {
variance : Double
standard_deviation : Double
samples : Int
confidence : Double
} derive(Debug)pub struct NoiseSchedule {
nominal : Double
minimum : Double
maximum : Double
growth : Double
decay : Double
factor : Double
stressed_steps : Int
}fn NoiseSchedule::new(nominal : Double, minimum : Double, maximum : Double, growth : Double, decay : Double) -> NoiseSchedulefn ObservationPacket::new(timestamp : Int, sensor : String, values : Array[Double], covariance : Matrix) -> ObservationPacketfn ObservationPacket::with_inflated_noise(self : ObservationPacket, factor : Double) -> ObservationPacketpub struct OperationalMonitor {
samples : Int
accepted : Int
failures : Int
covariance_failures : Int
consecutive_failures : Int
worst_nis : Double
score : Double
warmup_samples : Int
failure_limit : Int
nis_limit : Double
}fn OperationalMonitor::new(warmup_samples : Int, failure_limit : Int, nis_limit : Double) -> OperationalMonitorfn OperationalMonitor::observe(self : OperationalMonitor, timestamp : Int, filter : KalmanND, result : UpdateResult) -> OperationalSnapshotpub struct OperationalSnapshot {
timestamp : Int
result : UpdateResult
status : FilterStatus
score : Double
nis : Double
state : Array[Double]
covariance : Matrix
} derive(Debug)pub struct PacketQuality {
sensor : String
report : DataQualityReport
accepted : Bool
reason : String
} derive(Debug)pub struct PipelineEvent {
fusion : FusionEvent
lifecycle : TrackLifecycle
sensor_score : Double
rolling_mean : Double
rolling_variance : Double
} derive(Debug)pub struct PipelineReport {
events : Int
accepted : Int
rejected : Int
missing : Int
final_lifecycle : TrackLifecycle
final_sensor_score : Double
} derive(Debug)fn RangeMeasurement::new(reference : Array[Double], value : Double, variance : Double) -> RangeMeasurementfn RecursiveLeastSquares::new(dimension : Int, initial_covariance : Double, forgetting : Double) -> RecursiveLeastSquaresfn RecursiveLeastSquares::update(self : RecursiveLeastSquares, features : Array[Double], value : Double) -> Double?pub(all) enum ReplayEvent {
Predict(Int)
Measure(Int, Array[Double])
Missing(Int)
Restore(FilterCheckpoint)
} derive(Debug)pub struct ReplayRecord {
timestamp : Int
result : UpdateResult
state : Array[Double]
covariance : Matrix
nis : Double
} derive(Debug)fn ReplayRecord::new(timestamp : Int, result : UpdateResult, state : Array[Double], covariance : Matrix, nis : Double) -> ReplayRecordpub struct ReplaySession {
filter : KalmanND
trace : ReplayTrace
timestamp : Int
steps : Int
accepted : Int
rejected : Int
missing : Int
invalid : Int
}pub struct ResidualPolicy {
soft_limit : Double
hard_limit : Double
minimum_weight : Double
accepted : Int
downweighted : Int
rejected : Int
}fn ResidualPolicy::new(soft_limit : Double, hard_limit : Double, minimum_weight : Double) -> ResidualPolicypub struct RobustEstimatorConfig {
loss : RobustLossKind
tuning : Double
iterations : Int
tolerance : Double
minimum_weight : Double
} derive(Debug)fn RobustEstimatorConfig::new(loss : RobustLossKind, tuning : Double, iterations : Int, tolerance : Double, minimum_weight : Double) -> RobustEstimatorConfigpub struct RobustResidualSummary {
count : Int
finite : Int
rejected : Int
mean : Double
median : Double
mad : Double
rms : Double
maximum : Double
positive : Int
negative : Int
} derive(Debug)pub struct RunningStats {
count : Int
mean : Double
second_moment : Double
minimum : Double
maximum : Double
}pub struct SafetyCheckResult {
status : SafetyCheckStatus
value : Double
margin : Double
violation : SafetyViolation?
} derive(Debug)fn SafetyCheckResult::violated(value : Double, margin : Double, violation : SafetyViolation) -> SafetyCheckResultpub struct SafetyConstraint {
name : String
kind : SafetyConstraintKind
threshold : Double
tolerance : Double
severity : Double
enabled : Bool
} derive(Debug)fn SafetyConstraint::new(name : String, kind : SafetyConstraintKind, threshold : Double, tolerance : Double, severity : Double) -> SafetyConstraintfn SafetyEnvelope::check_acceleration(self : SafetyEnvelope, acceleration : Vec3D, timestamp : Int?) -> SafetyCheckResultfn SafetyEnvelope::check_pose(self : SafetyEnvelope, pose : Pose3D, velocity : Vec3D, covariance : Matrix, timestamp : Int?) -> Array[SafetyCheckResult]fn SafetyEnvelope::check_position(self : SafetyEnvelope, position : Vec3D, timestamp : Int?) -> SafetyCheckResultfn SafetyEnvelope::check_uncertainty(self : SafetyEnvelope, covariance : Matrix, timestamp : Int?) -> SafetyCheckResultfn SafetyEnvelope::check_velocity(self : SafetyEnvelope, velocity : Vec3D, timestamp : Int?) -> SafetyCheckResultfn SafetyEnvelope::new(name : String, position_min : Vec3D, position_max : Vec3D, velocity_limit : Double, acceleration_limit : Double, uncertainty_limit : Double) -> SafetyEnvelopepub struct SafetyViolation {
name : String
kind : SafetyConstraintKind
value : Double
threshold : Double
excess : Double
severity : Double
timestamp : Int?
} derive(Debug)fn SafetyViolation::new(constraint : SafetyConstraint, value : Double, excess : Double, timestamp : Int?) -> SafetyViolationpub struct ScalarCalibration {
measurement : NoiseEstimate
process : NoiseEstimate
recommended_process_noise : Double
recommended_measurement_noise : Double
} derive(Debug)fn SensorCalibrator::add(self : SensorCalibrator, raw : Array[Double], reference : Array[Double]) -> Boolpub struct SensorClock {
period : Int
last_timestamp : Int?
samples : Int
late : Int
early : Int
jitter : RunningStats
}pub struct SensorClockFit {
offset : Double
drift : Double
reference : Int
residual_rms : Double
samples : Int
valid : Bool
} derive(Debug)fn SensorConfiguration::new(name : String, dimension : Int, period : Int, timeout : Int, covariance : Matrix) -> SensorConfigurationfn SensorConfiguration::with_covariance(self : SensorConfiguration, covariance : Matrix) -> SensorConfigurationpub struct SensorFusion {
filter : KalmanND
policy : FusionPolicy
statistics : FusionStatistics
consecutive_missing : Int
}fn SensorFusion::process_missing(self : SensorFusion, timestamp : Int, sensor : String) -> FusionEventpub struct SensorHealth {
name : String
score : Double
decay : Double
recovery : Double
minimum_score : Double
accepted : Int
rejected : Int
}fn SensorModelPair::constant_velocity(dimensions : Int, dt : Double, acceleration_variance : Double, position_variance : Double, velocity_variance : Double) -> SensorModelPairpub struct SensorPacketBuilder {
configuration : SensorConfiguration
calibration : CalibrationTransform
built : Int
rejected : Int
}fn SensorPacketBuilder::build(self : SensorPacketBuilder, timestamp : Int, values : Array[Double]) -> ObservationPacket?fn SensorPacketBuilder::set_calibration(self : SensorPacketBuilder, calibration : CalibrationTransform) -> Boolpub struct SensorPipeline {
fusion : SensorFusion
tracker : TrackManager
health : Map[String, SensorHealth]
windows : Map[String, RollingWindow]
window_capacity : Int
}fn SensorPipeline::new(fusion : SensorFusion, confirmation_hits : Int, deletion_misses : Int, window_capacity : Int) -> SensorPipelinefn SensorPipeline::process_missing(self : SensorPipeline, timestamp : Int, sensor : String) -> PipelineEventfn SensorPipeline::run(self : SensorPipeline, packets : Array[ObservationPacket]) -> Array[PipelineEvent]fn SensorSample::new(timestamp : Int, truth : Array[Double], measurement : Array[Double], missing : Bool, outlier : Bool) -> SensorSamplepub struct SimulationResult {
samples : Array[SensorSample]
truth : Array[Array[Double]]
estimates : Array[Array[Double]]
metrics : ErrorMetrics
} derive(Debug)pub struct StateCandidate {
name : String
state : Array[Double]
covariance : Matrix
weight : Double
result : UpdateResult
} derive(Debug)fn StateCandidate::new(name : String, state : Array[Double], covariance : Matrix, weight : Double, result : UpdateResult) -> StateCandidatepub struct StateGuard {
rules : Array[StateGuardRule]
reject_invalid : Bool
reject_excess : Double
checks : Int
rejected : Int
clipped : Int
} derive(Debug)fn StateGuard::new(rules : Array[StateGuardRule], reject_invalid : Bool, reject_excess : Double) -> StateGuardpub struct StateGuardIssue {
index : Int
name : String
value : Double
projected : Double
excess : Double
status : StateGuardStatus
} derive(Debug)fn StateGuardIssue::new(rule : StateGuardRule, value : Double, projected : Double, status : StateGuardStatus) -> StateGuardIssuepub struct StateGuardReport {
original : Array[Double]
repaired : Array[Double]
issues : Array[StateGuardIssue]
accepted : Bool
changed : Bool
score : Double
} derive(Debug)fn StateGuardReport::new(original : Array[Double], repaired : Array[Double], issues : Array[StateGuardIssue], accepted : Bool) -> StateGuardReportpub struct StateGuardRule {
index : Int
name : String
minimum : Double
maximum : Double
tolerance : Double
enabled : Bool
} derive(Debug)fn StateGuardRule::new(index : Int, name : String, minimum : Double, maximum : Double, tolerance : Double) -> StateGuardRulepub struct StreamCursor {
next_sequence : Int
last_timestamp : Int?
accepted : Int
rejected : Int
duplicate : Int
out_of_order : Int
} derive(Debug)pub struct StreamRecord {
timestamp : Int
value : Double
source : String
sequence : Int
valid : Bool
} derive(Debug)fn StreamRecord::new(timestamp : Int, value : Double, source : String, sequence : Int) -> StreamRecordpub struct StreamRuntime {
window : StreamWindow
cursor : StreamCursor
max_queue : Int
queue : Array[StreamRecord]
processed : Int
dropped : Int
emitted : Int
backpressure : Int
} derive(Debug)fn StreamRuntime::new(spec : StreamWindowSpec, start_sequence : Int, max_queue : Int) -> StreamRuntimepub struct StreamStatistics {
count : Int
mean : Double
variance : Double
minimum : Double
maximum : Double
first_timestamp : Int?
last_timestamp : Int?
slope : Double
valid : Bool
} derive(Debug)pub struct StreamWindow {
spec : StreamWindowSpec
records : Array[StreamRecord]
watermark : Int?
max_timestamp : Int?
late_count : Int
invalid_count : Int
evicted_count : Int
} derive(Debug)pub struct StreamWindowSpec {
width : Int
lateness : Int
capacity : Int
min_samples : Int
allow_out_of_order : Bool
} derive(Debug)fn StreamWindowSpec::new(width : Int, lateness : Int, capacity : Int, min_samples : Int) -> StreamWindowSpecpub struct Synchronizer {
tolerance : Int
last_timestamp : Int?
accepted : Int
rejected : Int
}pub struct TelemetrySample {
timestamp : Int
channel : String
value : Double
quality : Double
result : UpdateResult
} derive(Debug)fn TelemetrySample::new(timestamp : Int, channel : String, value : Double, quality : Double, result : UpdateResult) -> TelemetrySamplepub struct TelemetrySummary {
samples : Int
accepted : Int
missing : Int
rejected : Int
mean : Double
variance : Double
quality : Double
status : FilterStatus
} derive(Debug)pub struct TrackLedger {
entries : Array[TrackLedgerEntry]
capacity : Int
miss_limit : Int
evictions : Int
} derive(Debug)fn TrackLedger::observe(self : TrackLedger, timestamp : Int, decisions : Array[AssociationDecision]) -> Unitpub struct TrackLedgerEntry {
id : Int
hits : Int
misses : Int
age : Int
score : Double
last_timestamp : Int?
last_measurement : Int?
active : Bool
} derive(Debug)fn TrackLedgerEntry::observe(self : TrackLedgerEntry, timestamp : Int, measurement_id : Int?, confidence : Double, miss_limit : Int) -> Unitpub struct TrackManager {
lifecycle : TrackLifecycle
confirmation_hits : Int
deletion_misses : Int
hits : Int
misses : Int
age : Int
}pub struct TrajectoryEvent {
timestamp : Int
flag : TrajectoryQualityFlag
severity : Double
index : Int
message : String
} derive(Debug)fn TrajectoryEvent::new(timestamp : Int, flag : TrajectoryQualityFlag, severity : Double, index : Int, message : String) -> TrajectoryEventpub struct TrajectoryInterval {
start_timestamp : Int
end_timestamp : Int
duration : Double
displacement : Double
speed : Double
acceleration : Double
jerk : Double
valid : Bool
} derive(Debug)fn TrajectoryPoint::new(timestamp : Int, position : Array[Double], velocity : Array[Double], covariance : Matrix) -> TrajectoryPointpub struct TrajectoryQualityReport {
point_count : Int
valid_points : Int
interval_count : Int
valid_intervals : Int
total_length : Double
duration : Int
mean_speed : Double
max_speed : Double
max_acceleration : Double
max_jerk : Double
mean_uncertainty : Double
score : Double
events : Array[TrajectoryEvent]
} derive(Debug)pub struct TrajectorySegment {
start_index : Int
end_index : Int
start_timestamp : Int
end_timestamp : Int
length : Double
mean_speed : Double
max_speed : Double
max_acceleration : Double
max_jerk : Double
mean_uncertainty : Double
quality : Double
valid : Bool
} derive(Debug)pub struct UKF {
x : Array[Double]
p : Matrix
q : Matrix
r : Matrix
initial_state : Array[Double]
initial_covariance : Matrix
alpha : Double
beta : Double
kappa : Double
predicted_sigma_points : Array[Array[Double]]
last_innovation : Array[Double]
last_innovation_covariance : Matrix
last_gain : Matrix
last_nis : Double
gate_threshold : Double
predict_count : Int
accepted_count : Int
rejected_count : Int
missing_count : Int
}fn UncertaintyBox3D::from_half_width(center : Vec3D, half_width : Vec3D, confidence : Double) -> UncertaintyBox3Dfn UncertaintyBox3D::new(center : Vec3D, standard_deviations : Vec3D, multiplier : Double) -> UncertaintyBox3Dpub struct UncertaintyBudget {
contributions : Array[UncertaintyContribution]
total_variance : Double
total_standard_deviation : Double
} derive(Debug)pub struct UncertaintyContribution {
name : String
variance : Double
fraction : Double
enabled : Bool
} derive(Debug)fn UncertaintyContribution::new(name : String, variance : Double, enabled : Bool) -> UncertaintyContributionpub struct UpdateSummary {
result : UpdateResult
innovation : Array[Double]
innovation_covariance : Matrix
normalized_innovation_squared : Double
} derive(Debug)pub struct ValidationReport {
name : String
checks : Int
passed : Int
issues : Array[ContractIssue]
}fn ValidationReport::check(self : ValidationReport, code : String, condition : Bool, severity : ContractSeverity, message : String) -> Boolfn VectorConfidenceBand::new(estimates : Array[Double], covariance : Matrix, multiplier : Double) -> VectorConfidenceBandpub struct WeightedAccumulator {
dimension : Int
total_weight : Double
weighted_sum : Array[Double]
}fn WeightedAccumulator::add(self : WeightedAccumulator, value : Array[Double], weight : Double) -> Boolfn align_timed_vectors(samples : Array[TimedVector], timestamps : Array[Int], policy : AlignmentPolicy) -> (Array[AlignedVector], AlignmentReport)fn alignment_quality_score(report : AlignmentReport, average_quality : Double, distance_limit : Int) -> Doublefn assess_trajectory_quality(points : Array[TrajectoryPoint], max_gap : Int, max_speed_limit : Double, max_acceleration_limit : Double, max_jerk_limit : Double, uncertainty_limit : Double) -> TrajectoryQualityReportfn associate_candidates(track_ids : Array[Int], measurement_ids : Array[Int], candidates : Array[AssociationCandidate], config : AssociationConfig) -> AssociationBatchfn associate_vectors(track_ids : Array[Int], measurement_ids : Array[Int], predictions : Array[Array[Double]], observations : Array[Array[Double]], variances : Array[Double], config : AssociationConfig) -> AssociationBatchfn association_candidate_from_vectors(track_id : Int, measurement_id : Int, expected : Array[Double], observed : Array[Double], variances : Array[Double], config : AssociationConfig) -> AssociationCandidatefn association_confidence_margin(best : AssociationCandidate, second : AssociationCandidate?) -> Doublefn association_gate_probability(distance : Double, threshold : Double) -> Doublefn association_likelihood(distance : Double, scale : Double) -> Doublefn association_pairwise_candidates(track_ids : Array[Int], measurement_ids : Array[Int], predictions : Array[Array[Double]], observations : Array[Array[Double]], variances : Array[Double], config : AssociationConfig) -> Array[AssociationCandidate]fn attenuate_timed_vector_quality(samples : Array[TimedVector], reference : Int, time_constant : Double) -> Array[TimedVector]fn batch_design_matrix(observations : Array[BatchObservation]) -> (Matrix, Array[Double], Array[Double])fn batch_fit_is_usable(fit : BatchFitResult, maximum_condition : Double, maximum_rmse : Double) -> Boolfn batch_polynomial_fit(x : Array[Double], y : Array[Double], degree : Int, center : Double, scale : Double) -> BatchFitResultfn batch_prediction_interval(fit : BatchFitResult, prediction : Double, confidence_scale : Double) -> (Double, Double)fn batch_robust_fit(observations : Array[BatchObservation], config : RobustEstimatorConfig) -> BatchFitResultfn batch_weighted_least_squares(observations : Array[BatchObservation], regularization : Double) -> BatchFitResultfn batch_weighted_line_fit(x : Array[Double], y : Array[Double], weights : Array[Double]) -> BatchFitResultfn calibrate_scalar(measurements : Array[Double], expected : Array[Double], spacing : Double, minimum_noise : Double) -> ScalarCalibrationfn candidate_from_filter(name : String, filter : KalmanND, result : UpdateResult, confidence : Double) -> StateCandidatefn candidate_from_scalar(name : String, filter : Kalman1D, result : UpdateResult, confidence : Double) -> StateCandidatefn check_safety_constraint(constraint : SafetyConstraint, value : Double, timestamp : Int?) -> SafetyCheckResultfn combine_independent_estimates(estimates : Array[Double], variances : Array[Double]) -> ConfidenceBandfn confidence_band_from_variance(estimate : Double, variance : Double, multiplier : Double) -> ConfidenceBandfn constant_acceleration_process_noise(dimensions : Int, dt : Double, jerk_variance : Double) -> Matrixfn constant_velocity_model(dimensions : Int, dt : Double, acceleration_variance : Double, measurement_variance : Double) -> LinearModelfn constant_velocity_process_noise(dimensions : Int, dt : Double, acceleration_variance : Double) -> Matrixfn control_interpolate(left : ControlCommand, right : ControlCommand, timestamp : Int) -> ControlCommandfn correct_sensor_clock_values(samples : Array[TimedVector], fit : SensorClockFit) -> Array[TimedVector]fn diagnostic_field_from_covariance(name : String, covariance : Matrix, unit : String) -> DiagnosticFieldfn diagnostic_field_from_state(name : String, state : Array[Double], unit : String, index : Int, minimum : Double, maximum : Double) -> DiagnosticFieldfn diagnostic_merge_reports(left : DiagnosticReport, right : DiagnosticReport, run_id : String) -> DiagnosticReportfn diagnostic_report_from_quality(run_id : String, timestamp : Int, report : TrajectoryQualityReport) -> DiagnosticReportfn diagnostic_snapshot_from_filter(timestamp : Int, source : String, state : Array[Double], covariance : Matrix) -> DiagnosticSnapshotfn diagnostic_value_within(value : Double, minimum : Double, maximum : Double) -> Boolfn estimate_stream_lag(source : Array[TimedVector], reference : Array[TimedVector], candidate_lags : Array[Int], policy : AlignmentPolicy) -> Intfn evaluate_polynomial(coefficients : Array[Double], x : Double, center : Double, scale : Double) -> Doublefn filter_quality_score(metrics : ErrorMetrics, rejected : Int, covariance_failures : Int) -> Doublefn filter_timed_vectors(samples : Array[TimedVector], minimum_quality : Double) -> Array[TimedVector]fn fit_sensor_clock(local_timestamps : Array[Int], reference_timestamps : Array[Int]) -> SensorClockFitfn fuse_measurements(measurements : Array[FusionMeasurement], strategy : FusionStrategy, covariance_floor : Double) -> FusionResultfn huber_clip_residual(residual : Double, threshold : Double) -> Doublefn inflate_for_residual(covariance : Matrix, residual : Array[Double], policy : ResidualPolicy) -> Matrixfn interpolate_timed_vectors(left : TimedVector, right : TimedVector, timestamp : Int) -> AlignedVectorfn interpolate_trajectory_point(left : TrajectoryPoint, right : TrajectoryPoint, timestamp : Int) -> TrajectoryPointfn join_alignment_report(left : Array[TimedVector], right : Array[TimedVector], policy : AlignmentPolicy) -> AlignmentReportfn join_timed_vectors(left : Array[TimedVector], right : Array[TimedVector], policy : AlignmentPolicy) -> Array[(Int, Array[Double], Array[Double], Double)]fn make_innovation_diagnostics(innovation : Array[Double], covariance : Matrix, gate_threshold : Double) -> InnovationDiagnosticsfn make_replay_events(start_timestamp : Int, count : Int, first_value : Double, velocity : Double, missing_period : Int) -> Array[ReplayEvent]fn model_catalog_compatible(catalog : ModelCatalog, dimension : Int, tags : Array[String]) -> Array[ModelCatalogEntry]fn model_catalog_has_regression(baseline : ModelCatalogEntry, candidate : ModelCatalogEntry, tolerance : Double, higher_is_better : Bool) -> Boolfn model_catalog_rank(catalog : ModelCatalog, policy : ModelSelectionPolicy) -> Array[ModelEvaluation]fn model_entry_preferred(left : ModelCatalogEntry, right : ModelCatalogEntry, higher_is_better : Bool) -> Boolfn model_metric_regression_score(baseline : Double, candidate : Double, higher_is_better : Bool) -> Doublefn polynomial_observations(x : Array[Double], y : Array[Double], basis : PolynomialBasis) -> Array[BatchObservation]fn predict_time_series_trend(fit : BatchFitResult, origin : Int, timestamps : Array[Int]) -> Array[Double]fn proportional_control(state : Array[Double], target : Array[Double], gain : Double, limits : ControlLimits) -> Array[Double]fn quality_adjusted_covariance(covariance : Matrix, report : DataQualityReport, floor : Double) -> Matrixfn recursive_least_squares_fit(observations : Array[BatchObservation], initial_covariance : Double, forgetting : Double) -> RecursiveLeastSquaresfn resample_timed_vectors(samples : Array[TimedVector], start : Int, end : Int, period : Int, policy : AlignmentPolicy) -> (Array[AlignedVector], AlignmentReport)fn resample_trajectory(points : Array[TrajectoryPoint], timestamps : Array[Int]) -> Array[TrajectoryPoint]fn robust_line_fit(x : Array[Double], y : Array[Double], config : RobustEstimatorConfig) -> RobustLineFitfn robust_loss_weight(kind : RobustLossKind, residual : Double, tuning : Double, minimum_weight : Double) -> Doublefn robust_scale_from_mad(mad : Double) -> Doublefn robust_weight(residual : Double, tuning : Double) -> Doublefn robust_weighted_location(values : Array[Double], base_weights : Array[Double], config : RobustEstimatorConfig) -> RobustEstimatefn robust_weights_for_residuals(residuals : Array[Double], config : RobustEstimatorConfig, scale : Double) -> Array[Double]fn run_constant_velocity_2d_simulation(steps : Int, dt : Double, measurement_noise : Double, missing_period : Int, outlier_period : Int, seed : Int) -> SimulationResultfn run_scalar_simulation(steps : Int, measurement_noise : Double, missing_period : Int, outlier_period : Int, seed : Int) -> SimulationResultfn safety_check_all(constraints : Array[SafetyConstraint], value : Double, timestamp : Int?) -> Array[SafetyCheckResult]fn safety_distance_bound(name : String, threshold : Double, tolerance : Double, severity : Double) -> SafetyConstraintfn safety_distance_constraint(constraint : SafetyConstraint, point : Vec3D, reference : Vec3D, timestamp : Int?) -> SafetyCheckResultfn safety_mahalanobis_constraint(constraint : SafetyConstraint, error : Array[Double], covariance : Matrix, timestamp : Int?) -> SafetyCheckResultfn safety_timestamp_consistent(previous : Int?, current : Int) -> Boolfn score_model(name : String, residuals : Array[Array[Double]], parameter_count : Int, consistency : Double) -> ModelScorefn simulate_constant_velocity_2d(steps : Int, dt : Double, initial_position : Array[Double], velocity : Array[Double], measurement_noise : Double, missing_period : Int, outlier_period : Int, seed : Int) -> Array[SensorSample]fn simulate_scalar_measurements(steps : Int, initial_value : Double, drift : Double, noise : Double, missing_period : Int, outlier_period : Int, seed : Int) -> Array[SensorSample]fn state_confidence_bands(state : Array[Double], covariance : Matrix, multiplier : Double) -> Array[ConfidenceBand]fn state_guard_from_covariance(state : Array[Double], covariance : Matrix, multiplier : Double, minimum : Array[Double], maximum : Array[Double]) -> StateGuardfn state_guard_merge_rules(left : Array[StateGuardRule], right : Array[StateGuardRule]) -> Array[StateGuardRule]fn state_guard_rules_for_dimension(minimum : Array[Double], maximum : Array[Double], tolerance : Double) -> Array[StateGuardRule]fn stream_outlier_fraction(records : Array[StreamRecord], center : Double, scale : Double) -> Doublefn stream_records_between(records : Array[StreamRecord], start : Int, end : Int) -> Array[StreamRecord]fn telemetry_from_filter(timestamp : Int, channel : String, filter : Kalman1D, result : UpdateResult) -> TelemetrySamplefn telemetry_merge(left : Array[TelemetrySample], right : Array[TelemetrySample]) -> Array[TelemetrySample]fn telemetry_resample(samples : Array[TelemetrySample], timestamps : Array[Int]) -> Array[TelemetrySample]fn time_series_observations(timestamps : Array[Int], values : Array[Double]) -> Array[BatchObservation]fn timed_vector_interpolate(samples : Array[TimedVector], timestamp : Int, policy : AlignmentPolicy) -> AlignedVectorfn timed_vector_nearest(samples : Array[TimedVector], timestamp : Int, policy : AlignmentPolicy) -> AlignedVectorfn trajectory_interval(previous : TrajectoryPoint, current : TrajectoryPoint, prior_speed : Double) -> TrajectoryIntervalfn trajectory_segment(points : Array[TrajectoryPoint], start_index : Int, end_index : Int, max_speed_limit : Double, max_acceleration_limit : Double, max_jerk_limit : Double) -> TrajectorySegmentfn uncertainty_overconfidence(coverage : Double, target : Double, tolerance : Double) -> Boolfn uncertainty_underconfidence(coverage : Double, target : Double, tolerance : Double) -> Boolfn validate_matrix(name : String, matrix : Matrix, expected_rows : Int, expected_cols : Int) -> ValidationReportProduction-ready MoonBit state estimation, smoothing, and sensor fusion library