-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.rs
More file actions
2414 lines (2118 loc) · 88.7 KB
/
Copy pathmain.rs
File metadata and controls
2414 lines (2118 loc) · 88.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! STRAPDOWN SIM: A simulation and analysis tool for strapdown inertial navigation systems.
//!
//! This program can operate in three modes: open-loop, closed-loop, and particle-filter.
//!
//! - Open-loop mode: Relies solely on inertial measurements (IMU) and an initial position estimate
//! for dead reckoning. Useful for high-accuracy IMUs with drift rates ≤1 nm per 24 hours.
//!
//! - Closed-loop mode: Incorporates GNSS measurements to correct IMU drift using either an
//! Unscented Kalman Filter (UKF) or Extended Kalman Filter (EKF). Supports GNSS degradation
//! scenarios including jamming, reduced update rates, and spoofing.
//!
//! - Particle-filter mode: Uses particle-based state estimation, supporting both standard and
//! Rao-Blackwellized implementations.
//!
//! You can run simulations either by:
//! 1. Loading all parameters from a configuration file (TOML/JSON/YAML)
//! 2. Specifying parameters via command-line flags
//!
//! For dataset format details, see the documentation or use --help with specific subcommands.
mod common;
#[cfg(feature = "plotting")]
mod plotting;
use clap::{Args, Parser, Subcommand};
use common::{
get_csv_files, init_logger, prompt_config_name, prompt_config_path, prompt_f64_with_default,
prompt_input_path, prompt_output_path, read_user_input, validate_input_path,
validate_output_path,
};
use log::{error, info};
use nalgebra::{Rotation3, Vector3};
use rayon::prelude::*;
use std::error::Error;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use strapdown::messages::{Event, GnssScheduler, build_event_stream};
use strapdown::rbpf::{RaoBlackwellizedParticleFilter, RbpfConfig};
// Geophysical navigation imports (feature-gated)
#[cfg(feature = "geonav")]
use geonav::{
GeoMap, GeophysicalAnomalyMeasurementModel, GeophysicalMeasurementType, GravityMeasurement,
GravityResolution, MagneticAnomalyMeasurement, MagneticResolution,
build_event_stream as geo_build_event_stream, geo_closed_loop_ekf, geo_closed_loop_ukf,
};
#[cfg(feature = "geonav")]
use std::rc::Rc;
#[cfg(feature = "geonav")]
use strapdown::NavigationFilter;
#[cfg(feature = "geonav")]
use strapdown::kalman::{ExtendedKalmanFilter, InitialState};
use strapdown::sim::HealthLimits;
use strapdown::sim::health::HealthMonitor;
#[cfg(feature = "geonav")]
use strapdown::sim::{DEFAULT_PROCESS_NOISE, GeoResolution};
use strapdown::sim::{
ExecutionLimits, ExecutionMonitor, FaultArgs, FilterType, NavigationResult, ParticleFilterType,
SchedulerArgs, SimulationConfig, SimulationMode, TestDataRecord, UkfConfig, build_fault,
build_scheduler, dead_reckoning, initialize_ekf, initialize_eskf, initialize_ukf,
run_closed_loop,
};
const LONG_ABOUT: &str =
"STRAPDOWN SIM: A simulation and analysis tool for strapdown inertial navigation systems.
This program can operate in three modes: open-loop, closed-loop, and particle-filter.
- Open-loop mode: Relies solely on inertial measurements (IMU) and an initial position estimate
for dead reckoning. Useful for high-accuracy IMUs with drift rates ≤1 nm per 24 hours.
- Closed-loop mode: Incorporates GNSS measurements to correct IMU drift using either an
Unscented Kalman Filter (UKF) or Extended Kalman Filter (EKF). Supports GNSS degradation
scenarios including jamming, reduced update rates, and spoofing.
- Particle-filter mode: Uses particle-based state estimation, supporting both standard and
Rao-Blackwellized implementations. CURRENTLY IN DEVELOPMENT!!!
You can run simulations either by:
1. Loading all parameters from a configuration file (TOML/JSON/YAML)
2. Specifying parameters via command-line flags
For dataset format details, see the documentation or use --help with specific subcommands.";
/// Command line arguments
#[derive(Parser)]
#[command(author, version, about = "A simulation and analysis tool for strapdown inertial navigation systems.", long_about = LONG_ABOUT)]
struct Cli {
/// Run simulation from a configuration file (TOML/JSON/YAML)
/// This option overrides any subcommand arguments
#[arg(short, long, global = true)]
config: Option<PathBuf>,
/// Command to execute (ignored if --config is provided)
#[command(subcommand)]
command: Option<Command>,
/// Log level (off, error, warn, info, debug, trace)
#[arg(long, default_value = "info", global = true)]
log_level: String,
/// Log file path (if not specified, logs to stderr)
#[arg(long, global = true)]
log_file: Option<PathBuf>,
/// Run simulations in parallel when processing multiple files
#[arg(long, global = true)]
parallel: bool,
/// Generate performance plot comparing navigation output to GPS measurements
#[arg(long, global = true)]
plot: bool,
}
/// Top-level commands
#[derive(Subcommand, Clone)]
enum Command {
#[command(
name = "dr",
about = "Run simulation in dead reckoning mode",
long_about = "Run INS simulation in dead reckoning mode. In this mode, only inertial measurements (IMU) and an initial position estimate are used to propagate the navigation solution. External measurements like GNSS are not incorporated."
)]
DeadReckoning(SimArgs),
#[command(
name = "ol",
about = "Run simulation in open-loop mode",
long_about = "Run INS simulation in an open-loop (feed-forward) mode. In this mode, an initial position estimate and inertial measurements (IMU) are used to propagate the navigation solution. A Kalman filter (EKF or UKF) is used to estimate the errors to the navigation solution from GNSS measurements and apply the correction. Various GNSS degradation scenarios can be simulated, including jamming, reduced update rates, and spoofing."
)]
OpenLoop(SimArgs),
#[command(
name = "cl",
about = "Run simulation in closed-loop mode",
long_about = "Run INS simulation in a closed-loop (feedback) mode. In this mode, GNSS measurements are incorporated to correct for IMU drift and directly reset or update the navigation states using either an Unscented Kalman Filter (UKF) or Extended Kalman Filter (EKF). Various GNSS degradation scenarios can be simulated, including jamming, reduced update rates, and spoofing."
)]
ClosedLoop(ClosedLoopSimArgs),
#[command(
name = "pf",
about = "Run simulation using particle filter.",
long_about = "Run INS simulation using a particle filter for state estimation. This mode supports both standard and Rao-Blackwellized particle filter implementations. Various GNSS degradation scenarios can be simulated, including jamming, reduced update rates, and spoofing."
)]
ParticleFilter(ParticleFilterSimArgs),
#[command(name = "config", about = "Generate a template configuration file")]
CreateConfig, //(CreateConfigArgs),
}
/// Common simulation arguments for input/output
#[derive(Args, Clone, Debug)]
struct SimArgs {
/// Input CSV file path or directory containing CSV files
/// If a directory is provided, all CSV files in it will be processed
#[arg(short, long, value_parser)]
input: PathBuf,
/// Output CSV file path
/// When processing multiple files, output filenames will be generated as: {output_stem}_{input_stem}.csv
#[arg(short, long, value_parser)]
output: PathBuf,
/// Max wall-clock time as a ratio of simulated duration (<= 0 disables)
#[arg(long, default_value_t = strapdown::sim::DEFAULT_MAX_WALL_CLOCK_RATIO)]
max_wall_clock_ratio: f64,
/// Max wall-clock time per trajectory in seconds (<= 0 disables)
#[arg(long, default_value_t = strapdown::sim::DEFAULT_MAX_WALL_CLOCK_S)]
max_wall_clock_s: f64,
/// Max wall-clock time without progress in seconds (<= 0 disables)
#[arg(long, default_value_t = strapdown::sim::DEFAULT_MAX_NO_PROGRESS_S)]
max_no_progress_s: f64,
}
/// Geophysical measurement arguments (feature-gated)
#[cfg(feature = "geonav")]
#[derive(Args, Clone, Debug)]
struct GeophysicalArgs {
/// Enable geophysical navigation
#[arg(long)]
geo: bool,
/// Gravity map resolution
#[arg(long, value_enum, requires = "geo")]
gravity_resolution: Option<GeoResolution>,
/// Gravity measurement bias (mGal)
#[arg(long, requires = "geo")]
gravity_bias: Option<f64>,
/// Gravity measurement noise std dev (mGal)
#[arg(long, default_value_t = 100.0, requires = "geo")]
gravity_noise_std: f64,
/// Gravity map file path
#[arg(long, requires = "geo")]
gravity_map_file: Option<PathBuf>,
/// Magnetic map resolution
#[arg(long, value_enum, requires = "geo")]
magnetic_resolution: Option<GeoResolution>,
/// Magnetic measurement bias (nT)
#[arg(long, requires = "geo")]
magnetic_bias: Option<f64>,
/// Magnetic measurement noise std dev (nT)
#[arg(long, default_value_t = 150.0, requires = "geo")]
magnetic_noise_std: f64,
/// Magnetic map file path
#[arg(long, requires = "geo")]
magnetic_map_file: Option<PathBuf>,
/// Geophysical measurement frequency (seconds)
#[arg(long, requires = "geo")]
geo_frequency_s: Option<f64>,
}
/// Empty stub when geonav feature is disabled
#[cfg(not(feature = "geonav"))]
#[derive(Args, Clone, Debug, Default)]
struct GeophysicalArgs {}
/// Closed-loop simulation arguments
#[derive(Args, Clone, Debug)]
struct ClosedLoopSimArgs {
/// Common simulation input/output arguments
#[command(flatten)]
sim: SimArgs,
/// Filter type to use for closed-loop navigation
#[arg(long, value_enum, default_value_t = FilterType::Ukf)]
filter: FilterType,
/// UKF alpha parameter (sigma point spread)
#[arg(long, default_value_t = 1e-3)]
ukf_alpha: f64,
/// UKF beta parameter (prior distribution)
#[arg(long, default_value_t = 2.0)]
ukf_beta: f64,
/// UKF kappa parameter (secondary spread control)
#[arg(long, default_value_t = 0.0)]
ukf_kappa: f64,
/// RNG seed for stochastic processes
#[arg(long, default_value_t = 42)]
seed: u64,
/// GNSS scheduler settings (dropouts / reduced rate)
#[command(flatten)]
scheduler: SchedulerArgs,
/// Fault model settings (corrupt measurement content)
#[command(flatten)]
fault: FaultArgs,
/// Geophysical navigation options (optional, requires --features geonav)
#[command(flatten)]
geo: GeophysicalArgs,
}
/// Particle filter simulation arguments
#[derive(Args, Clone, Debug)]
struct ParticleFilterSimArgs {
/// Common simulation input/output arguments
#[command(flatten)]
sim: SimArgs,
/// Particle filter type
#[arg(long, value_enum, default_value_t = ParticleFilterType::Standard)]
filter_type: ParticleFilterType,
/// RNG seed for stochastic processes
#[arg(long, default_value_t = 42)]
seed: u64,
/// Number of particles
#[arg(long, default_value_t = 100)]
num_particles: usize,
/// Position uncertainty standard deviation (meters)
#[arg(long, default_value_t = 10.0)]
position_std: f64,
/// Velocity uncertainty standard deviation (m/s)
#[arg(long, default_value_t = 1.0)]
velocity_std: f64,
/// Attitude uncertainty standard deviation (radians)
#[arg(long, default_value_t = 0.1)]
attitude_std: f64,
/// Accelerometer bias uncertainty standard deviation (m/s²)
#[arg(long, default_value_t = 0.1)]
accel_bias_std: f64,
/// Gyroscope bias uncertainty standard deviation (rad/s)
#[arg(long, default_value_t = 0.01)]
gyro_bias_std: f64,
/// Process noise standard deviation for the velocity-based particle filter (meters)
/// as `[lat_m, lon_m, alt_m]`.
///
/// Examples:
/// - `--process-noise-std-m 1 1 2`
/// - `--process-noise-std-m 1,1,2`
#[arg(long, value_delimiter = ',', num_args = 3, default_value = "1,1,1")]
process_noise_std_m: Vec<f64>,
/// Velocity process noise standard deviation (m/s).
#[arg(long, default_value_t = 1e-3)]
velocity_process_noise_std_mps: f64,
/// Attitude process noise standard deviation (rad).
#[arg(long, default_value_t = 0.01)]
attitude_process_noise_std_rad: f64,
/// GNSS scheduler settings (dropouts / reduced rate)
#[command(flatten)]
scheduler: SchedulerArgs,
/// Fault model settings (corrupt measurement content)
#[command(flatten)]
fault: FaultArgs,
/// Geophysical navigation options (optional, requires --features geonav)
#[command(flatten)]
geo: GeophysicalArgs,
/// Apply zero-vertical-velocity pseudo-measurement (RBPF only).
#[arg(long, default_value_t = true)]
zero_vertical_velocity: bool,
/// Std dev for zero-vertical-velocity pseudo-measurement (m/s).
#[arg(long, default_value_t = 0.1)]
zero_vertical_velocity_std_mps: f64,
/// Initial standard deviation for geophysical bias states.
#[arg(long, default_value_t = 1.0)]
geo_bias_init_std: f64,
/// Random-walk process noise standard deviation for geophysical bias states.
#[arg(long, default_value_t = 1e-3)]
geo_bias_process_noise_std: f64,
}
/// Arguments for create-config command
#[derive(Args, Clone, Debug)]
struct CreateConfigArgs {
/// Output file path for the config file
/// File extension determines format: .json, .yaml/.yml, or .toml (recommended)
#[arg(short, long, value_parser)]
output: PathBuf,
/// Simulation mode for the template
#[arg(short, long, value_enum, default_value_t = SimulationMode::ClosedLoop)]
mode: SimulationMode,
}
fn execution_limits_from_args(args: &SimArgs) -> ExecutionLimits {
ExecutionLimits {
max_wall_clock_ratio: args.max_wall_clock_ratio,
max_wall_clock_s: args.max_wall_clock_s,
max_no_progress_s: args.max_no_progress_s,
}
}
/// Process a single CSV file with the given configuration
fn process_file(
input_file: &Path,
output: &Path,
config: &SimulationConfig,
) -> Result<(), Box<dyn Error>> {
info!("Processing file: {}", input_file.display());
// Load sensor data
let records = TestDataRecord::from_csv(input_file)?;
info!(
"Read {} records from {}",
records.len(),
input_file.display()
);
// Execute based on mode
match config.mode {
SimulationMode::DeadReckoning => {
info!("Running dead reckoning simulation");
let results = dead_reckoning(&records);
info!("Generated {} navigation results", results.len());
let output_file = output.join(input_file.file_name().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("Input file path '{}' has no filename", input_file.display()),
)
})?);
NavigationResult::to_csv(&results, &output_file)?;
info!("Results written to {}", output_file.display());
Ok(())
}
SimulationMode::OpenLoop => {
info!("Open-loop mode is not yet fully implemented");
Err("Open-loop mode is not yet fully implemented".into())
}
SimulationMode::ClosedLoop => {
let filter_config = config.closed_loop.clone().unwrap_or_default();
let event_stream = build_event_stream(&records, &config.gnss_degradation);
info!(
"Initialized event stream with {} events",
event_stream.events.len()
);
let execution_limits = config.execution_limits.clone();
let results = match filter_config.filter {
FilterType::Ukf => {
let mut ukf =
initialize_ukf(records[0].clone(), UkfConfig::default());
info!("Initialized UKF");
run_closed_loop(&mut ukf, event_stream, None, Some(execution_limits.clone()))
}
FilterType::Ekf => {
let mut ekf = initialize_ekf(records[0].clone(), None, None, None, None, true);
info!("Initialized EKF");
run_closed_loop(&mut ekf, event_stream, None, Some(execution_limits.clone()))
}
FilterType::Eskf => {
let mut eskf = initialize_eskf(records[0].clone(), None, None, None, None);
info!("Initialized ESKF");
run_closed_loop(&mut eskf, event_stream, None, Some(execution_limits))
}
};
let output_file = output.join(input_file.file_name().unwrap());
match results {
Ok(ref nav_results) => {
NavigationResult::to_csv(nav_results, &output_file)?;
info!("Results written to {}", output_file.display());
// Generate performance plot if requested
#[cfg(feature = "plotting")]
if config.generate_plot {
let plot_path = output_file.with_extension("png");
info!("Generating performance plot at {}", plot_path.display());
match plotting::plot_performance(nav_results, &records, &plot_path) {
Ok(()) => {
info!("Performance plot generated successfully");
}
Err(e) => {
error!("Failed to generate performance plot: {}", e);
// Don't fail the entire process if plotting fails
}
}
}
#[cfg(not(feature = "plotting"))]
if config.generate_plot {
error!(
"Plotting requested but 'plotting' feature not enabled. Rebuild with --features plotting"
);
}
Ok(())
}
Err(e) => {
error!("Error running closed-loop simulation: {}", e);
Err(e.into())
}
}
}
SimulationMode::ParticleFilter => {
info!("Running particle filter simulation");
#[cfg(feature = "geonav")]
let (gravity_map, magnetic_map, geo_frequency_s, gravity_noise_std, magnetic_noise_std) = {
if let Some(geo_cfg) = &config.geophysical {
let gravity_map = if let Some(res) = geo_cfg.gravity_resolution {
let map_path = match &geo_cfg.gravity_map_file {
Some(path) => PathBuf::from(path),
None => find_gravity_map(input_file)?,
};
let measurement_type =
GeophysicalMeasurementType::Gravity(convert_resolution_gravity(res));
Some(Rc::new(GeoMap::load_geomap(map_path, measurement_type)?))
} else {
None
};
let magnetic_map = if let Some(res) = geo_cfg.magnetic_resolution {
let map_path = match &geo_cfg.magnetic_map_file {
Some(path) => PathBuf::from(path),
None => find_magnetic_map(input_file)?,
};
let measurement_type =
GeophysicalMeasurementType::Magnetic(convert_resolution_magnetic(res));
Some(Rc::new(GeoMap::load_geomap(map_path, measurement_type)?))
} else {
None
};
(
gravity_map,
magnetic_map,
geo_cfg.geo_frequency_s,
geo_cfg.gravity_noise_std.unwrap_or(100.0),
geo_cfg.magnetic_noise_std.unwrap_or(150.0),
)
} else {
(None, None, None, 100.0, 150.0)
}
};
#[cfg(not(feature = "geonav"))]
if config.geophysical.is_some() {
return Err("Geophysical configuration requires the geonav feature".into());
}
#[cfg(feature = "geonav")]
let event_stream = if gravity_map.is_some() || magnetic_map.is_some() {
geo_build_event_stream(
&records,
&config.gnss_degradation,
gravity_map.clone(),
gravity_map.as_ref().map(|_| gravity_noise_std),
magnetic_map.clone(),
magnetic_map.as_ref().map(|_| magnetic_noise_std),
geo_frequency_s,
)
} else {
build_event_stream(&records, &config.gnss_degradation)
};
#[cfg(not(feature = "geonav"))]
let event_stream = build_event_stream(&records, &config.gnss_degradation);
let first = &records[0];
let attitude = Rotation3::from_euler_angles(first.roll, first.pitch, first.yaw);
let nominal = strapdown::StrapdownState {
latitude: first.latitude.to_radians(),
longitude: first.longitude.to_radians(),
altitude: first.altitude,
velocity_north: first.speed * first.bearing.to_radians().cos(),
velocity_east: first.speed * first.bearing.to_radians().sin(),
velocity_vertical: 0.0,
attitude,
is_enu: true,
};
let pf_cfg = config.particle_filter.clone().unwrap_or_default();
let rbpf_defaults = RbpfConfig::default();
let position_init_std_m = if pf_cfg.position_init_std_m.len() == 3 {
Vector3::new(
pf_cfg.position_init_std_m[0],
pf_cfg.position_init_std_m[1],
pf_cfg.position_init_std_m[2],
)
} else {
rbpf_defaults.position_init_std_m
};
let position_process_noise_std_m = if pf_cfg.position_process_noise_std_m.len() == 3 {
Vector3::new(
pf_cfg.position_process_noise_std_m[0],
pf_cfg.position_process_noise_std_m[1],
pf_cfg.position_process_noise_std_m[2],
)
} else {
rbpf_defaults.position_process_noise_std_m
};
#[cfg(feature = "geonav")]
let geo_bias_dim = gravity_map.is_some() as usize + magnetic_map.is_some() as usize;
#[cfg(not(feature = "geonav"))]
let geo_bias_dim = 0usize;
let mut rbpf = RaoBlackwellizedParticleFilter::new(
nominal,
RbpfConfig {
num_particles: pf_cfg.num_particles,
position_init_std_m,
velocity_init_std_mps: pf_cfg.velocity_init_std_mps,
attitude_init_std_rad: pf_cfg.attitude_init_std_rad,
position_process_noise_std_m,
velocity_process_noise_std_mps: pf_cfg.velocity_process_noise_std_mps,
attitude_process_noise_std_rad: pf_cfg.attitude_process_noise_std_rad,
extra_state_dim: geo_bias_dim,
extra_state_init_std: if geo_bias_dim > 0 {
pf_cfg.geo_bias_init_std
} else {
0.0
},
extra_state_process_noise_std: if geo_bias_dim > 0 {
pf_cfg.geo_bias_process_noise_std
} else {
0.0
},
seed: config.seed,
zero_vertical_velocity: pf_cfg.zero_vertical_velocity,
zero_vertical_velocity_std_mps: pf_cfg.zero_vertical_velocity_std_mps,
..rbpf_defaults
},
);
let start_time = event_stream.start_time;
let mut results = Vec::with_capacity(event_stream.events.len());
let mut monitor = HealthMonitor::new(HealthLimits::default());
let sim_duration_s = event_stream
.events
.last()
.map(|event| match event {
Event::Imu { elapsed_s, .. } => *elapsed_s,
Event::Measurement { elapsed_s, .. } => *elapsed_s,
})
.unwrap_or(0.0);
let mut execution_monitor =
ExecutionMonitor::new(config.execution_limits.clone(), sim_duration_s);
// Store the initial state (before processing any events)
let (mean, cov) = rbpf.estimate();
results.push(NavigationResult::from_particle_filter(
&start_time,
&mean,
&cov,
));
let mut last_ts = start_time;
for event in event_stream.events.into_iter() {
let elapsed_s = match &event {
Event::Imu { elapsed_s, .. } => *elapsed_s,
Event::Measurement { elapsed_s, .. } => *elapsed_s,
};
let ts = start_time
+ chrono::Duration::milliseconds((elapsed_s * 1000.0).round() as i64);
match event {
Event::Imu { dt_s, imu, .. } => {
rbpf.predict(&imu, dt_s);
}
Event::Measurement { meas, .. } => {
#[cfg(feature = "geonav")]
if gravity_map.is_some() || magnetic_map.is_some() {
let (mean, _) = rbpf.estimate();
let strapdown: strapdown::StrapdownState =
mean.as_slice().try_into().unwrap();
if let Some(gravity) =
meas.as_any_mut().downcast_mut::<GravityMeasurement>()
{
gravity.set_state(&strapdown);
} else if let Some(magnetic) =
meas.as_any_mut()
.downcast_mut::<MagneticAnomalyMeasurement>()
{
magnetic.set_state(&strapdown);
}
}
rbpf.update(meas.as_ref());
}
}
let (mean, cov) = rbpf.estimate();
if let Err(e) = monitor.check(mean.as_slice(), &cov, None) {
return Err(e.into());
}
execution_monitor.check("particle-filter")?;
execution_monitor.mark_progress();
// Store state when timestamp changes
if ts != last_ts {
results.push(NavigationResult::from_particle_filter(&ts, &mean, &cov));
last_ts = ts;
}
}
let output_file = output.join(input_file.file_name().unwrap());
NavigationResult::to_csv(&results, &output_file)?;
info!("Results written to {}", output_file.display());
#[cfg(feature = "plotting")]
if config.generate_plot {
let plot_path = output_file.with_extension("png");
info!("Generating performance plot at {}", plot_path.display());
match plotting::plot_performance(&results, &records, &plot_path) {
Ok(()) => {
info!("Performance plot generated successfully");
}
Err(e) => {
error!("Failed to generate performance plot: {}", e);
}
}
}
#[cfg(not(feature = "plotting"))]
if config.generate_plot {
error!(
"Plotting requested but 'plotting' feature not enabled. Rebuild with --features plotting"
);
}
Ok(())
}
}
}
/// Execute simulation from a configuration file
fn run_from_config(
config_path: &Path,
cli_parallel: bool,
cli_plot: bool,
) -> Result<(), Box<dyn Error>> {
info!("Loading configuration from {}", config_path.display());
let mut config = SimulationConfig::from_file(config_path)?;
// Override parallel setting if CLI flag is set
if cli_parallel {
config.parallel = true;
}
// Override plot setting if CLI flag is set
if cli_plot {
config.generate_plot = true;
}
info!("Configuration loaded successfully");
info!("Mode: {:?}", config.mode);
info!("Input: {}", config.input);
info!("Output: {}", config.output);
info!("Parallel: {}", config.parallel);
info!("Generate plot: {}", config.generate_plot);
info!(
"Execution limits: ratio {:.2}, wall-clock {:.1}s, no-progress {:.1}s",
config.execution_limits.max_wall_clock_ratio,
config.execution_limits.max_wall_clock_s,
config.execution_limits.max_no_progress_s
);
// Validate paths
let input = Path::new(&config.input);
let output = Path::new(&config.output);
validate_input_path(input)?;
validate_output_path(output)?;
// Get all CSV files to process
let csv_files = get_csv_files(input)?;
let is_multiple = csv_files.len() > 1;
if is_multiple {
info!("Processing {} CSV files from directory", csv_files.len());
if config.parallel {
info!("Running in parallel mode");
}
}
// Process files either sequentially or in parallel
if config.parallel && is_multiple {
// Parallel processing
let errors = Mutex::new(Vec::new());
csv_files.par_iter().for_each(|input_file| {
match process_file(input_file, output, &config) {
Ok(()) => {}
Err(e) => {
error!("Error processing {}: {}", input_file.display(), e);
// Use expect with a descriptive message for mutex operations
errors
.lock()
.expect(
"Failed to acquire lock on error collection - another thread panicked",
)
.push((input_file.clone(), e.to_string()));
}
}
});
let errors = errors
.into_inner()
.expect("Failed to extract errors from mutex - another thread panicked");
if !errors.is_empty() {
error!("{} file(s) failed to process", errors.len());
for (file, err) in &errors {
error!(" {}: {}", file.display(), err);
}
return Err(format!("{} file(s) failed to process", errors.len()).into());
}
} else {
// Sequential processing
let mut failures = 0usize;
for input_file in &csv_files {
if let Err(e) = process_file(input_file, output, &config) {
if !is_multiple {
return Err(e);
}
failures += 1;
error!("Error processing {}: {}", input_file.display(), e);
}
}
if failures > 0 {
error!("{} file(s) failed to process", failures);
}
}
Ok(())
}
/// Execute a single closed-loop simulation run
///
/// This is a helper function that extracts the common logic for running closed-loop simulations
/// with either UKF or EKF filters. It handles event stream creation, filter initialization,
/// simulation execution, and results writing.
#[allow(clippy::too_many_arguments)]
fn run_single_closed_loop_simulation(
filter_type: FilterType,
records: &[TestDataRecord],
gnss_degradation: &strapdown::messages::GnssDegradationConfig,
output_file: &Path,
execution_limits: ExecutionLimits,
ukf_alpha: f64,
ukf_beta: f64,
ukf_kappa: f64,
) -> Result<(), Box<dyn Error>> {
// Build event stream from records and GNSS degradation config
let event_stream = build_event_stream(records, gnss_degradation);
info!(
"Initialized event stream with {} events",
event_stream.events.len()
);
// Initialize and run filter based on type
let results = match filter_type {
FilterType::Ukf => {
let mut ukf = initialize_ukf(
records[0].clone(),
UkfConfig {
ukf_alpha: Some(ukf_alpha),
ukf_beta: Some(ukf_beta),
ukf_kappa: Some(ukf_kappa),
..Default::default()
},
);
info!("Initialized UKF");
run_closed_loop(&mut ukf, event_stream, None, Some(execution_limits.clone()))
}
FilterType::Ekf => {
let mut ekf = initialize_ekf(records[0].clone(), None, None, None, None, true);
info!("Initialized EKF");
run_closed_loop(&mut ekf, event_stream, None, Some(execution_limits.clone()))
}
FilterType::Eskf => {
let mut eskf = initialize_eskf(records[0].clone(), None, None, None, None);
info!("Initialized ESKF");
run_closed_loop(&mut eskf, event_stream, None, Some(execution_limits))
}
};
// Write results to CSV
match results {
Ok(ref nav_results) => {
NavigationResult::to_csv(nav_results, output_file)?;
info!("Results written to {}", output_file.display());
Ok(())
}
Err(e) => {
error!("Error running closed-loop simulation: {}", e);
Err(e.into())
}
}
}
/// Execute dead-reckoning simulation
fn run_dead_reckoning(args: &SimArgs) -> Result<(), Box<dyn Error>> {
validate_input_path(&args.input)?;
validate_output_path(&args.output)?;
info!("Running in dead reckoning mode");
// Get all CSV files to process
let csv_files = get_csv_files(&args.input)?;
let is_multiple = csv_files.len() > 1;
if is_multiple {
info!("Processing {} CSV files from directory", csv_files.len());
}
// Process each CSV file
for input_file in &csv_files {
info!("Processing file: {}", input_file.display());
// Load sensor data records from CSV
let records = TestDataRecord::from_csv(input_file)?;
info!(
"Read {} records from {}",
records.len(),
input_file.display()
);
// Run dead reckoning simulation
info!(
"Running dead reckoning simulation on {} records",
records.len()
);
let results = dead_reckoning(&records);
info!("Generated {} navigation results", results.len());
// Write results to CSV
let output_file =
Path::new(&args.output).join(input_file.file_name().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("Input file path '{}' has no filename", input_file.display()),
)
})?);
NavigationResult::to_csv(&results, &output_file)?;
info!("Results written to {}", output_file.display());
}
Ok(())
}
/// Execute open-loop simulation
fn run_open_loop(args: &SimArgs) -> Result<(), Box<dyn Error>> {
validate_input_path(&args.input)?;
validate_output_path(&args.output)?;
let csv_files = get_csv_files(&args.input)?;
let is_multiple = csv_files.len() > 1;
if is_multiple {
info!("Processing {} CSV files from directory", csv_files.len());
}
for input_file in &csv_files {
info!("Processing file: {}", input_file.display());
// TODO: Implement open-loop processing here
// let records = TestDataRecord::from_csv(input_file)?;
// let output_file = generate_output_path(&args.output, input_file, is_multiple);
// ... process and write results ...
}
info!("Open-loop mode is not yet fully implemented");
println!("Open-loop mode is not yet fully implemented");
Ok(())
}
/// Execute closed-loop simulation
fn run_closed_loop_cli(args: &ClosedLoopSimArgs) -> Result<(), Box<dyn Error>> {
// Check if geophysical navigation is enabled
#[cfg(feature = "geonav")]
if args.geo.geo {
return run_geo_closed_loop_cli(args);
}
validate_input_path(&args.sim.input)?;
validate_output_path(&args.sim.output)?;
let filter_name = match args.filter {
FilterType::Ukf => "Unscented Kalman Filter (UKF)",
FilterType::Ekf => "Extended Kalman Filter (EKF)",
FilterType::Eskf => "Error-State Kalman Filter (ESKF)",
};
info!("Running in closed-loop mode with {}", filter_name);
// Get all CSV files to process
let csv_files = get_csv_files(&args.sim.input)?;
let is_multiple = csv_files.len() > 1;
let execution_limits = execution_limits_from_args(&args.sim);
if is_multiple {
info!("Processing {} CSV files from directory", csv_files.len());
//println!("Processing {} CSV files from directory", csv_files.len());
}
// Process each CSV file
for input_file in &csv_files {
info!("Processing file: {}", input_file.display());
// Load sensor data records from CSV
let records = TestDataRecord::from_csv(input_file)?;
info!(
"Read {} records from {}",
records.len(),
input_file.display()
);
// Build GNSS degradation config from CLI args
let gnss_degradation = strapdown::messages::GnssDegradationConfig {
scheduler: build_scheduler(&args.scheduler),
fault: build_fault(&args.fault),
seed: args.seed,
};
info!("Using GNSS degradation config: {:?}", gnss_degradation);
let output_file = Path::new(&args.sim.output).join(input_file);
// Run simulation using the common helper function
match run_single_closed_loop_simulation(
args.filter,
&records,