-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsim.rs
More file actions
5311 lines (4963 loc) · 189 KB
/
Copy pathsim.rs
File metadata and controls
5311 lines (4963 loc) · 189 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
//! Simulation utilities and data serialization for strapdown inertial navigation.
//!
//! This module provides tools for simulating and evaluating strapdown inertial navigation systems.
//! It is primarily designed to work with data produced from the [Sensor Logger](https://www.tszheichoi.com/sensorlogger)
//! app, as such it makes assumptions about the data format and structure that that corresponds to
//! how that app records data.
//!
//! ## Data Formats
//!
//! The module supports both CSV and netCDF formats for input and output data:
//!
//! - **CSV format**: Human-readable text format, suitable for quick inspection and editing
//! - **netCDF format**: Binary format optimized for large datasets, better for archival and data interchange
//!
//! Data is represented by the `TestDataRecord` struct (sensor measurements) and `NavigationResult` struct
//! (navigation solutions). Both structs support serialization to/from CSV and netCDF formats.
//!
//! ### Example: Working with netCDF files
//!
//! ```no_run
//! use strapdown::sim::{TestDataRecord, NavigationResult};
//!
//! // Read test data from netCDF file
//! let test_data = TestDataRecord::from_netcdf("input_data.nc")
//! .expect("Failed to read input data");
//!
//! // ... perform navigation simulation ...
//!
//! // Write navigation results to netCDF file
//! # let nav_results: Vec<NavigationResult> = vec![];
//! NavigationResult::to_netcdf(&nav_results, "output_results.nc")
//! .expect("Failed to write navigation results");
//! ```
//!
//! ## Simulation Functions
//!
//! This module also provides basic functionality for analyzing canonical strapdown inertial navigation
//! systems via the `dead_reckoning` and `closed_loop` functions. The `closed_loop` function in particular
//! can also be used to simulate various types of GNSS-denied scenarios, such as intermittent, degraded,
//! or intermittent and degraded GNSS via the measurement models provided in this module. You can install
//! the programs that execute this generic simulation by installing the binary via `cargo install strapdown-rs`.
use core::f64;
use log::{debug, info, warn};
use std::fmt::{Debug, Display};
use std::io::{self, Read, Write};
use std::path::Path;
use std::time::{Duration as StdDuration, Instant};
use anyhow::{Result, bail};
use chrono::{DateTime, Duration, Utc};
use nalgebra::{DMatrix, DVector, Vector3};
use serde::{Deserialize, Deserializer, Serialize};
#[cfg(feature = "clap")]
use clap::{Args, ValueEnum};
use crate::NavigationFilter;
use crate::earth::METERS_TO_DEGREES;
use crate::kalman::{InitialState, UnscentedKalmanFilter};
use crate::messages::{Event, EventStream, GnssFaultModel, GnssScheduler};
use crate::{IMUData, StrapdownState, forward};
use health::HealthMonitor;
// Re-export execution and health types for easier access in tests and external users
pub use execution::{ExecutionLimits, ExecutionMonitor};
pub use health::HealthLimits;
pub const DEFAULT_PROCESS_NOISE: [f64; 15] = [
// Default process noise if not provided
1e-6, // position noise 1e-6
1e-6, // position noise 1e-6
1e-4, // altitude noise
1e-3, // velocity north noise
1e-3, // velocity east noise
1e-3, // velocity down noise
1e-5, // roll noise
1e-5, // pitch noise
1e-5, // yaw noise
1e-6, // acc bias x noise
1e-6, // acc bias y noise
1e-6, // acc bias z noise
1e-8, // gyro bias x noise
1e-8, // gyro bias y noise
1e-8, // gyro bias z noise
];
pub const DEFAULT_MAX_WALL_CLOCK_RATIO: f64 = 0.25;
pub const DEFAULT_MAX_WALL_CLOCK_S: f64 = 1200.0;
pub const DEFAULT_MAX_NO_PROGRESS_S: f64 = 600.0;
fn de_f64_nan<'de, D>(deserializer: D) -> Result<f64, D::Error>
where
D: Deserializer<'de>,
{
// Read whatever the CSV cell was as an Option<String>.
// Missing field -> None; present but empty -> Some(""), etc.
let opt = Option::<String>::deserialize(deserializer)?;
match opt {
None => Ok(f64::NAN),
Some(s) => {
let t = s.trim();
if t.is_empty() || t.eq_ignore_ascii_case("nan") || t.eq_ignore_ascii_case("null") {
return Ok(f64::NAN);
}
t.parse::<f64>().map_err(serde::de::Error::custom)
}
}
}
/// Struct representing a single row of test data from the CSV file.
///
/// Fields correspond to columns in the CSV, with appropriate renaming for Rust style.
/// This struct is setup to capture the data recorded from the [Sensor Logger](https://www.tszheichoi.com/sensorlogger) app.
/// Primarily, this represents IMU data as (relative to the device) and GPS data.
#[derive(Debug, Default, Deserialize, Serialize, Clone)]
pub struct TestDataRecord {
/// Date-time string: YYYY-MM-DD hh:mm:ss+UTCTZ
//#[serde(with = "ts_seconds")]
pub time: DateTime<Utc>,
/// accuracy of the bearing (magnetic heading) in degrees
#[serde(rename = "bearingAccuracy", deserialize_with = "de_f64_nan")]
pub bearing_accuracy: f64,
/// accuracy of the speed in m/s
#[serde(rename = "speedAccuracy", deserialize_with = "de_f64_nan")]
pub speed_accuracy: f64,
/// accuracy of the altitude in meters
#[serde(rename = "verticalAccuracy", deserialize_with = "de_f64_nan")]
pub vertical_accuracy: f64,
/// accuracy of the horizontal position in meters
#[serde(rename = "horizontalAccuracy", deserialize_with = "de_f64_nan")]
pub horizontal_accuracy: f64,
/// Speed in m/s
#[serde(deserialize_with = "de_f64_nan")]
pub speed: f64,
/// Bearing in degrees
#[serde(deserialize_with = "de_f64_nan")]
pub bearing: f64,
/// Altitude in meters
#[serde(deserialize_with = "de_f64_nan")]
pub altitude: f64,
/// Longitude in degrees
#[serde(deserialize_with = "de_f64_nan")]
pub longitude: f64,
/// Latitude in degrees
#[serde(deserialize_with = "de_f64_nan")]
pub latitude: f64,
/// Quaternion component representing the rotation around the z-axis
#[serde(deserialize_with = "de_f64_nan")]
pub qz: f64,
/// Quaternion component representing the rotation around the y-axis
#[serde(deserialize_with = "de_f64_nan")]
pub qy: f64,
/// Quaternion component representing the rotation around the x-axis
#[serde(deserialize_with = "de_f64_nan")]
pub qx: f64,
/// Quaternion component representing the rotation around the w-axis
#[serde(deserialize_with = "de_f64_nan")]
pub qw: f64,
/// Roll angle in radians
#[serde(deserialize_with = "de_f64_nan")]
pub roll: f64,
/// Pitch angle in radians
#[serde(deserialize_with = "de_f64_nan")]
pub pitch: f64,
/// Yaw angle in radians
#[serde(deserialize_with = "de_f64_nan")]
pub yaw: f64,
/// Z-acceleration in m/s^2
#[serde(deserialize_with = "de_f64_nan")]
pub acc_z: f64,
/// Y-acceleration in m/s^2
#[serde(deserialize_with = "de_f64_nan")]
pub acc_y: f64,
/// X-acceleration in m/s^2
#[serde(deserialize_with = "de_f64_nan")]
pub acc_x: f64,
/// Rotation rate around the z-axis in radians/s
#[serde(deserialize_with = "de_f64_nan")]
pub gyro_z: f64,
/// Rotation rate around the y-axis in radians/s
#[serde(deserialize_with = "de_f64_nan")]
pub gyro_y: f64,
/// Rotation rate around the x-axis in radians/s
#[serde(deserialize_with = "de_f64_nan")]
pub gyro_x: f64,
/// Magnetic field strength in the z-direction in micro teslas
#[serde(deserialize_with = "de_f64_nan")]
pub mag_z: f64,
/// Magnetic field strength in the y-direction in micro teslas
#[serde(deserialize_with = "de_f64_nan")]
pub mag_y: f64,
/// Magnetic field strength in the x-direction in micro teslas
#[serde(deserialize_with = "de_f64_nan")]
pub mag_x: f64,
/// Change in altitude in meters
#[serde(rename = "relativeAltitude", deserialize_with = "de_f64_nan")]
pub relative_altitude: f64,
/// pressure in millibars
#[serde(deserialize_with = "de_f64_nan")]
pub pressure: f64,
/// Acceleration due to gravity in the z-direction in m/s^2
#[serde(deserialize_with = "de_f64_nan")]
pub grav_z: f64,
/// Acceleration due to gravity in the y-direction in m/s^2
#[serde(deserialize_with = "de_f64_nan")]
pub grav_y: f64,
/// Acceleration due to gravity in the x-direction in m/s^2
#[serde(deserialize_with = "de_f64_nan")]
pub grav_x: f64,
}
impl TestDataRecord {
/// Reads a CSV file and returns a vector of `TestDataRecord` structs.
///
/// # Arguments
/// * `path` - Path to the CSV file to read.
///
/// # Returns
/// * `Ok(Vec<TestDataRecord>)` if successful.
/// * `Err` if the file cannot be read or parsed.
pub fn from_csv<P: AsRef<std::path::Path>>(
path: P,
) -> Result<Vec<Self>, Box<dyn std::error::Error>> {
let mut rdr = csv::ReaderBuilder::new()
.has_headers(true)
.flexible(true)
.trim(csv::Trim::All)
.from_path(path)?;
let mut records = Vec::new();
for (i, result) in rdr.deserialize::<Self>().enumerate() {
match result {
Ok(r) => records.push(r),
Err(e) => {
// Skip only this row; keep going.
warn!("Skipping row {} due to parse error: {e}", i + 1);
}
}
}
Ok(records)
}
/// Writes a vector of TestDataRecord structs to a CSV file.
///
/// # Arguments
/// * `records` - Vector of TestDataRecord structs to write
/// * `path` - Path where the CSV file will be saved
///
/// # Returns
/// * `io::Result<()>` - Ok if successful, Err otherwise
///
/// # Example
///
/// ```
/// use strapdown::sim::TestDataRecord;
/// use std::path::Path;
///
/// let record = TestDataRecord {
/// time: chrono::Utc::now(),
/// bearing_accuracy: 0.1,
/// speed_accuracy: 0.1,
/// vertical_accuracy: 0.1,
/// horizontal_accuracy: 0.1,
/// speed: 1.0,
/// bearing: 90.0,
/// altitude: 100.0,
/// longitude: -122.0,
/// latitude: 37.0,
/// qz: 0.0,
/// qy: 0.0,
/// qx: 0.0,
/// qw: 1.0,
/// roll: 0.0,
/// pitch: 0.0,
/// yaw: 0.0,
/// acc_z: 9.81,
/// acc_y: 0.0,
/// acc_x: 0.0,
/// gyro_z: 0.01,
/// gyro_y: 0.01,
/// gyro_x: 0.01,
/// mag_z: 50.0,
/// mag_y: -30.0,
/// mag_x: -20.0,
/// relative_altitude: 0.0,
/// pressure: 1013.25,
/// grav_z: 9.81,
/// grav_y: 0.0,
/// grav_x: 0.0,
/// };
/// let records = vec![record];
/// TestDataRecord::to_csv(&records, "data.csv")
/// .expect("Failed to write test data to CSV");
/// // doctest cleanup
/// std::fs::remove_file("data.csv").unwrap();
/// ```
pub fn to_csv<P: AsRef<Path>>(records: &[Self], path: P) -> io::Result<()> {
let mut writer = csv::Writer::from_path(path)?;
for record in records {
writer.serialize(record)?;
}
writer.flush()?;
Ok(())
}
/// Writes a vector of TestDataRecord structs to an HDF5 file.
///
/// # Arguments
/// * `records` - Vector of TestDataRecord structs to write
/// * `path` - Path where the HDF5 file will be saved
///
/// # Returns
/// * `Result<()>` - Ok if successful, Err otherwise
///
/// # Example
///
/// ```no_run
/// use strapdown::sim::TestDataRecord;
/// use std::path::Path;
///
/// let record = TestDataRecord::default();
/// let records = vec![record];
/// TestDataRecord::to_hdf5(&records, "data.h5")
/// .expect("Failed to write test data to HDF5");
/// ```
pub fn to_hdf5<P: AsRef<Path>>(records: &[Self], path: P) -> Result<()> {
use hdf5::File;
let file = File::create(path)?;
let n = records.len();
// Handle empty datasets
if n == 0 {
// Create group to indicate structure even for empty datasets
let _group = file.create_group("test_data")?;
return Ok(());
}
// Create a group for test data records
let group = file.create_group("test_data")?;
// Write timestamps as strings
let timestamps: Result<Vec<hdf5::types::VarLenAscii>> = records
.iter()
.map(|r| {
hdf5::types::VarLenAscii::from_ascii(&r.time.to_rfc3339())
.map_err(|e| anyhow::anyhow!("Failed to encode timestamp as ASCII: {}", e))
})
.collect();
let timestamps = timestamps?;
let ds_time = group
.new_dataset::<hdf5::types::VarLenAscii>()
.shape([n])
.create("time")?;
ds_time.write(×tamps)?;
// Helper macro to write f64 arrays
macro_rules! write_f64_field {
($field_name:literal, $field:ident) => {{
let data: Vec<f64> = records.iter().map(|r| r.$field).collect();
let ds = group.new_dataset::<f64>().shape([n]).create($field_name)?;
ds.write(&data)?;
}};
}
write_f64_field!("bearing_accuracy", bearing_accuracy);
write_f64_field!("speed_accuracy", speed_accuracy);
write_f64_field!("vertical_accuracy", vertical_accuracy);
write_f64_field!("horizontal_accuracy", horizontal_accuracy);
write_f64_field!("speed", speed);
write_f64_field!("bearing", bearing);
write_f64_field!("altitude", altitude);
write_f64_field!("longitude", longitude);
write_f64_field!("latitude", latitude);
write_f64_field!("qz", qz);
write_f64_field!("qy", qy);
write_f64_field!("qx", qx);
write_f64_field!("qw", qw);
write_f64_field!("roll", roll);
write_f64_field!("pitch", pitch);
write_f64_field!("yaw", yaw);
write_f64_field!("acc_z", acc_z);
write_f64_field!("acc_y", acc_y);
write_f64_field!("acc_x", acc_x);
write_f64_field!("gyro_z", gyro_z);
write_f64_field!("gyro_y", gyro_y);
write_f64_field!("gyro_x", gyro_x);
write_f64_field!("mag_z", mag_z);
write_f64_field!("mag_y", mag_y);
write_f64_field!("mag_x", mag_x);
write_f64_field!("relative_altitude", relative_altitude);
write_f64_field!("pressure", pressure);
write_f64_field!("grav_z", grav_z);
write_f64_field!("grav_y", grav_y);
write_f64_field!("grav_x", grav_x);
Ok(())
}
/// Writes a vector of TestDataRecord structs to an MCAP file.
///
/// **Note**: This method uses MessagePack encoding. Due to CSV-specific field deserializers
/// in TestDataRecord, direct MCAP deserialization may have limitations. For production use,
/// consider converting to NavigationResult or using CSV format for TestDataRecord.
///
/// # Arguments
/// * `records` - Vector of TestDataRecord structs to write
/// * `path` - Path where the MCAP file will be saved
///
/// # Returns
/// * `io::Result<()>` - Ok if successful, Err otherwise
pub fn to_mcap<P: AsRef<Path>>(records: &[Self], path: P) -> io::Result<()> {
use mcap::{Writer, records::MessageHeader};
use std::collections::BTreeMap;
use std::fs::File;
use std::io::BufWriter;
let file = File::create(path)?;
let buf_writer = BufWriter::new(file);
let mut writer = Writer::new(buf_writer).map_err(io::Error::other)?;
// Add schema for TestDataRecord (using MessagePack encoding)
let schema_name = "TestDataRecord";
let schema_encoding = "msgpack";
let schema_data = b"TestDataRecord struct serialized with MessagePack";
let schema_id = writer
.add_schema(schema_name, schema_encoding, schema_data)
.map_err(io::Error::other)?;
// Add channel for TestDataRecord messages
let metadata = BTreeMap::new();
let channel_id = writer
.add_channel(schema_id, "sensor_data", "msgpack", &metadata)
.map_err(io::Error::other)?;
// Write each record as a message
for (seq, record) in records.iter().enumerate() {
let data = rmp_serde::to_vec(record)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
let timestamp_nanos = record.time.timestamp_nanos_opt().ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidData, "Timestamp out of range")
})?;
let header = MessageHeader {
channel_id,
sequence: seq as u32,
log_time: timestamp_nanos as u64,
publish_time: timestamp_nanos as u64,
};
writer
.write_to_known_channel(&header, &data)
.map_err(io::Error::other)?;
}
writer.finish().map_err(io::Error::other)?;
Ok(())
}
/// Reads an HDF5 file and returns a vector of TestDataRecord structs.
///
/// # Arguments
/// * `path` - Path to the HDF5 file to read.
///
/// # Returns
/// * `Ok(Vec<TestDataRecord>)` if successful.
/// * `Err` if the file cannot be read or parsed.
///
/// # Example
///
/// ```no_run
/// use strapdown::sim::TestDataRecord;
///
/// let records = TestDataRecord::from_hdf5("data.h5")
/// .expect("Failed to read test data from HDF5");
/// ```
pub fn from_hdf5<P: AsRef<Path>>(path: P) -> Result<Vec<Self>> {
use hdf5::File;
let file = File::open(path)?;
let group = file.group("test_data")?;
// Check if time dataset exists (might be empty dataset)
if let Ok(ds_time) = group.dataset("time") {
// Read timestamps
let timestamps: Vec<hdf5::types::VarLenAscii> = ds_time.read_raw()?;
let n = timestamps.len();
// Handle empty dataset
if n == 0 {
return Ok(Vec::new());
}
// Helper macro to read f64 arrays
macro_rules! read_f64_field {
($field_name:literal) => {{
let ds = group.dataset($field_name)?;
let data: Vec<f64> = ds.read_raw()?;
data
}};
}
let bearing_accuracy = read_f64_field!("bearing_accuracy");
let speed_accuracy = read_f64_field!("speed_accuracy");
let vertical_accuracy = read_f64_field!("vertical_accuracy");
let horizontal_accuracy = read_f64_field!("horizontal_accuracy");
let speed = read_f64_field!("speed");
let bearing = read_f64_field!("bearing");
let altitude = read_f64_field!("altitude");
let longitude = read_f64_field!("longitude");
let latitude = read_f64_field!("latitude");
let qz = read_f64_field!("qz");
let qy = read_f64_field!("qy");
let qx = read_f64_field!("qx");
let qw = read_f64_field!("qw");
let roll = read_f64_field!("roll");
let pitch = read_f64_field!("pitch");
let yaw = read_f64_field!("yaw");
let acc_z = read_f64_field!("acc_z");
let acc_y = read_f64_field!("acc_y");
let acc_x = read_f64_field!("acc_x");
let gyro_z = read_f64_field!("gyro_z");
let gyro_y = read_f64_field!("gyro_y");
let gyro_x = read_f64_field!("gyro_x");
let mag_z = read_f64_field!("mag_z");
let mag_y = read_f64_field!("mag_y");
let mag_x = read_f64_field!("mag_x");
let relative_altitude = read_f64_field!("relative_altitude");
let pressure = read_f64_field!("pressure");
let grav_z = read_f64_field!("grav_z");
let grav_y = read_f64_field!("grav_y");
let grav_x = read_f64_field!("grav_x");
let mut records = Vec::with_capacity(n);
for i in 0..n {
let time = DateTime::parse_from_rfc3339(timestamps[i].as_str())
.map_err(|e| anyhow::anyhow!("Failed to parse timestamp: {}", e))?
.with_timezone(&Utc);
records.push(TestDataRecord {
time,
bearing_accuracy: bearing_accuracy[i],
speed_accuracy: speed_accuracy[i],
vertical_accuracy: vertical_accuracy[i],
horizontal_accuracy: horizontal_accuracy[i],
speed: speed[i],
bearing: bearing[i],
altitude: altitude[i],
longitude: longitude[i],
latitude: latitude[i],
qz: qz[i],
qy: qy[i],
qx: qx[i],
qw: qw[i],
roll: roll[i],
pitch: pitch[i],
yaw: yaw[i],
acc_z: acc_z[i],
acc_y: acc_y[i],
acc_x: acc_x[i],
gyro_z: gyro_z[i],
gyro_y: gyro_y[i],
gyro_x: gyro_x[i],
mag_z: mag_z[i],
mag_y: mag_y[i],
mag_x: mag_x[i],
relative_altitude: relative_altitude[i],
pressure: pressure[i],
grav_z: grav_z[i],
grav_y: grav_y[i],
grav_x: grav_x[i],
});
}
Ok(records)
} else {
// No time dataset means empty file
Ok(Vec::new())
}
}
/// Writes a vector of TestDataRecord structs to a netCDF file.
///
/// # Arguments
/// * `records` - Vector of TestDataRecord structs to write
/// * `path` - Path where the netCDF file will be saved
///
/// # Returns
/// * `Result<()>` - Ok if successful, Err otherwise
pub fn to_netcdf<P: AsRef<Path>>(records: &[Self], path: P) -> Result<()> {
if records.is_empty() {
bail!("Cannot write empty records to netCDF");
}
let n = records.len();
let mut file = netcdf::create(path)?;
// Define dimensions
file.add_dimension("time", n)?;
// Helper macro to add a variable and write data
macro_rules! add_and_write {
($file:expr, $name:expr, $data:expr) => {{
let mut var = $file.add_variable::<f64>($name, &["time"])?;
var.put_values(&$data, ..)?;
}};
}
// Prepare all data arrays first
let times: Vec<f64> = records.iter().map(|r| r.time.timestamp() as f64).collect();
let bearing_accuracy: Vec<f64> = records.iter().map(|r| r.bearing_accuracy).collect();
let speed_accuracy: Vec<f64> = records.iter().map(|r| r.speed_accuracy).collect();
let vertical_accuracy: Vec<f64> = records.iter().map(|r| r.vertical_accuracy).collect();
let horizontal_accuracy: Vec<f64> = records.iter().map(|r| r.horizontal_accuracy).collect();
let speed: Vec<f64> = records.iter().map(|r| r.speed).collect();
let bearing: Vec<f64> = records.iter().map(|r| r.bearing).collect();
let altitude: Vec<f64> = records.iter().map(|r| r.altitude).collect();
let longitude: Vec<f64> = records.iter().map(|r| r.longitude).collect();
let latitude: Vec<f64> = records.iter().map(|r| r.latitude).collect();
let qz: Vec<f64> = records.iter().map(|r| r.qz).collect();
let qy: Vec<f64> = records.iter().map(|r| r.qy).collect();
let qx: Vec<f64> = records.iter().map(|r| r.qx).collect();
let qw: Vec<f64> = records.iter().map(|r| r.qw).collect();
let roll: Vec<f64> = records.iter().map(|r| r.roll).collect();
let pitch: Vec<f64> = records.iter().map(|r| r.pitch).collect();
let yaw: Vec<f64> = records.iter().map(|r| r.yaw).collect();
let acc_z: Vec<f64> = records.iter().map(|r| r.acc_z).collect();
let acc_y: Vec<f64> = records.iter().map(|r| r.acc_y).collect();
let acc_x: Vec<f64> = records.iter().map(|r| r.acc_x).collect();
let gyro_z: Vec<f64> = records.iter().map(|r| r.gyro_z).collect();
let gyro_y: Vec<f64> = records.iter().map(|r| r.gyro_y).collect();
let gyro_x: Vec<f64> = records.iter().map(|r| r.gyro_x).collect();
let mag_z: Vec<f64> = records.iter().map(|r| r.mag_z).collect();
let mag_y: Vec<f64> = records.iter().map(|r| r.mag_y).collect();
let mag_x: Vec<f64> = records.iter().map(|r| r.mag_x).collect();
let relative_altitude: Vec<f64> = records.iter().map(|r| r.relative_altitude).collect();
let pressure: Vec<f64> = records.iter().map(|r| r.pressure).collect();
let grav_z: Vec<f64> = records.iter().map(|r| r.grav_z).collect();
let grav_y: Vec<f64> = records.iter().map(|r| r.grav_y).collect();
let grav_x: Vec<f64> = records.iter().map(|r| r.grav_x).collect();
// Add variables and write data
add_and_write!(file, "time", times);
add_and_write!(file, "bearingAccuracy", bearing_accuracy);
add_and_write!(file, "speedAccuracy", speed_accuracy);
add_and_write!(file, "verticalAccuracy", vertical_accuracy);
add_and_write!(file, "horizontalAccuracy", horizontal_accuracy);
add_and_write!(file, "speed", speed);
add_and_write!(file, "bearing", bearing);
add_and_write!(file, "altitude", altitude);
add_and_write!(file, "longitude", longitude);
add_and_write!(file, "latitude", latitude);
add_and_write!(file, "qz", qz);
add_and_write!(file, "qy", qy);
add_and_write!(file, "qx", qx);
add_and_write!(file, "qw", qw);
add_and_write!(file, "roll", roll);
add_and_write!(file, "pitch", pitch);
add_and_write!(file, "yaw", yaw);
add_and_write!(file, "acc_z", acc_z);
add_and_write!(file, "acc_y", acc_y);
add_and_write!(file, "acc_x", acc_x);
add_and_write!(file, "gyro_z", gyro_z);
add_and_write!(file, "gyro_y", gyro_y);
add_and_write!(file, "gyro_x", gyro_x);
add_and_write!(file, "mag_z", mag_z);
add_and_write!(file, "mag_y", mag_y);
add_and_write!(file, "mag_x", mag_x);
add_and_write!(file, "relativeAltitude", relative_altitude);
add_and_write!(file, "pressure", pressure);
add_and_write!(file, "grav_z", grav_z);
add_and_write!(file, "grav_y", grav_y);
add_and_write!(file, "grav_x", grav_x);
Ok(())
}
/// Reads a netCDF file and returns a vector of `TestDataRecord` structs.
///
/// # Arguments
/// * `path` - Path to the netCDF file to read.
///
/// # Returns
/// * `Ok(Vec<TestDataRecord>)` if successful.
/// * `Err` if the file cannot be read or parsed.
pub fn from_netcdf<P: AsRef<Path>>(path: P) -> Result<Vec<Self>> {
let file = netcdf::open(path)?;
// Read time variable
let time_var = file
.variable("time")
.ok_or_else(|| anyhow::anyhow!("time variable not found"))?;
let times: Vec<f64> = time_var.get_values(..)?;
let n = times.len();
// Helper macro to read a variable
macro_rules! read_var {
($file:expr, $name:expr) => {{
let var = $file
.variable($name)
.ok_or_else(|| anyhow::anyhow!(concat!($name, " variable not found")))?;
let data: Vec<f64> = var.get_values(..)?;
data
}};
}
// Read all variables
let bearing_accuracy = read_var!(file, "bearingAccuracy");
let speed_accuracy = read_var!(file, "speedAccuracy");
let vertical_accuracy = read_var!(file, "verticalAccuracy");
let horizontal_accuracy = read_var!(file, "horizontalAccuracy");
let speed = read_var!(file, "speed");
let bearing = read_var!(file, "bearing");
let altitude = read_var!(file, "altitude");
let longitude = read_var!(file, "longitude");
let latitude = read_var!(file, "latitude");
let qz = read_var!(file, "qz");
let qy = read_var!(file, "qy");
let qx = read_var!(file, "qx");
let qw = read_var!(file, "qw");
let roll = read_var!(file, "roll");
let pitch = read_var!(file, "pitch");
let yaw = read_var!(file, "yaw");
let acc_z = read_var!(file, "acc_z");
let acc_y = read_var!(file, "acc_y");
let acc_x = read_var!(file, "acc_x");
let gyro_z = read_var!(file, "gyro_z");
let gyro_y = read_var!(file, "gyro_y");
let gyro_x = read_var!(file, "gyro_x");
let mag_z = read_var!(file, "mag_z");
let mag_y = read_var!(file, "mag_y");
let mag_x = read_var!(file, "mag_x");
let relative_altitude = read_var!(file, "relativeAltitude");
let pressure = read_var!(file, "pressure");
let grav_z = read_var!(file, "grav_z");
let grav_y = read_var!(file, "grav_y");
let grav_x = read_var!(file, "grav_x");
// Build records
let mut records = Vec::with_capacity(n);
for i in 0..n {
let time = DateTime::from_timestamp(times[i] as i64, 0)
.ok_or_else(|| anyhow::anyhow!("Invalid timestamp"))?
.with_timezone(&Utc);
records.push(TestDataRecord {
time,
bearing_accuracy: bearing_accuracy[i],
speed_accuracy: speed_accuracy[i],
vertical_accuracy: vertical_accuracy[i],
horizontal_accuracy: horizontal_accuracy[i],
speed: speed[i],
bearing: bearing[i],
altitude: altitude[i],
longitude: longitude[i],
latitude: latitude[i],
qz: qz[i],
qy: qy[i],
qx: qx[i],
qw: qw[i],
roll: roll[i],
pitch: pitch[i],
yaw: yaw[i],
acc_z: acc_z[i],
acc_y: acc_y[i],
acc_x: acc_x[i],
gyro_z: gyro_z[i],
gyro_y: gyro_y[i],
gyro_x: gyro_x[i],
mag_z: mag_z[i],
mag_y: mag_y[i],
mag_x: mag_x[i],
relative_altitude: relative_altitude[i],
pressure: pressure[i],
grav_z: grav_z[i],
grav_y: grav_y[i],
grav_x: grav_x[i],
});
}
Ok(records)
}
/// Reads an MCAP file and returns a vector of TestDataRecord structs.
///
/// **Note**: Due to CSV-specific field deserializers in TestDataRecord, MCAP deserialization
/// may fail. For production use, consider using CSV format for TestDataRecord or convert
/// to NavigationResult which fully supports MCAP.
///
/// # Arguments
/// * `path` - Path to the MCAP file to read.
pub fn from_mcap<P: AsRef<Path>>(path: P) -> Result<Vec<Self>, Box<dyn std::error::Error>> {
use mcap::MessageStream;
use std::fs::File;
let file = File::open(path)?;
// Memory-map the file for efficient reading
let mapped = unsafe { memmap2::Mmap::map(&file)? };
let message_stream = MessageStream::new(&mapped)?;
let mut records = Vec::new();
for message_result in message_stream {
let message = message_result?;
let record: Self = rmp_serde::from_slice(&message.data)?;
records.push(record);
}
Ok(records)
}
}
impl Display for TestDataRecord {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"TestDataRecord(time: {}, latitude: {}, longitude: {}, altitude: {}, speed: {}, bearing: {})",
self.time, self.latitude, self.longitude, self.altitude, self.speed, self.bearing
)
}
}
// ==== Helper structs for navigation simulations ====
/// Struct representing the covariance diagonal of a navigation solution in NED coordinates.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct NEDCovariance {
pub latitude_cov: f64,
pub longitude_cov: f64,
pub altitude_cov: f64,
pub velocity_n_cov: f64,
pub velocity_e_cov: f64,
pub velocity_v_cov: f64,
pub roll_cov: f64,
pub pitch_cov: f64,
pub yaw_cov: f64,
pub acc_bias_x_cov: f64,
pub acc_bias_y_cov: f64,
pub acc_bias_z_cov: f64,
pub gyro_bias_x_cov: f64,
pub gyro_bias_y_cov: f64,
pub gyro_bias_z_cov: f64,
}
/// Generic result struct for navigation simulations.
///
/// This structure contains a single row of position, velocity, and attitude vectors
/// representing the navigation solution at a specific timestamp, along with the covariance diagonal,
/// input IMU measurements, and derived geophysical values.
///
/// It can be used across different types of navigation simulations such as dead reckoning,
/// Kalman filtering, or any other navigation algorithm.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct NavigationResult {
/// Timestamp corresponding to the state
pub timestamp: DateTime<Utc>,
// ---- Navigation solution states ----
/// Latitude in radians
pub latitude: f64,
/// Longitude in radians
pub longitude: f64,
/// Altitude in meters
pub altitude: f64,
/// Northward velocity in m/s
pub velocity_north: f64,
/// Eastward velocity in m/s
pub velocity_east: f64,
/// Vertical velocity in m/s
pub velocity_vertical: f64,
/// Roll angle in radians
pub roll: f64,
/// Pitch angle in radians
pub pitch: f64,
/// Yaw angle in radians
pub yaw: f64,
/// IMU accelerometer x-axis bias in m/s^2
pub acc_bias_x: f64,
/// IMU accelerometer y-axis bias in m/s^2
pub acc_bias_y: f64,
/// IMU accelerometer z-axis bias in m/s^2
pub acc_bias_z: f64,
/// IMU gyroscope x-axis bias in radians/s
pub gyro_bias_x: f64,
/// IMU gyroscope y-axis bias in radians/s
pub gyro_bias_y: f64,
/// IMU gyroscope z-axis bias in radians/s
pub gyro_bias_z: f64,
// ---- Covariance values for the navigation solution ----
/// Latitude covariance
pub latitude_cov: f64,
/// Longitude covariance
pub longitude_cov: f64,
/// Altitude covariance
pub altitude_cov: f64,
/// Northward velocity covariance
pub velocity_n_cov: f64,
/// Eastward velocity covariance
pub velocity_e_cov: f64,
/// Vertical velocity covariance
pub velocity_v_cov: f64,
/// Roll covariance
pub roll_cov: f64,
/// Pitch covariance
pub pitch_cov: f64,
/// Yaw covariance
pub yaw_cov: f64,
/// Accelerometer x-axis bias covariance
pub acc_bias_x_cov: f64,
/// Accelerometer y-axis bias covariance
pub acc_bias_y_cov: f64,
/// Accelerometer z-axis bias covariance
pub acc_bias_z_cov: f64,
/// Gyroscope x-axis bias covariance
pub gyro_bias_x_cov: f64,
/// Gyroscope y-axis bias covariance
pub gyro_bias_y_cov: f64,
/// Gyroscope z-axis bias covariance
pub gyro_bias_z_cov: f64,
}
impl Default for NavigationResult {
fn default() -> Self {
NavigationResult {
timestamp: Utc::now(),
latitude: 0.0,
longitude: 0.0,
altitude: 0.0,
velocity_north: 0.0,
velocity_east: 0.0,
velocity_vertical: 0.0,
roll: 0.0,
pitch: 0.0,
yaw: 0.0,
acc_bias_x: 0.0,
acc_bias_y: 0.0,
acc_bias_z: 0.0,
gyro_bias_x: 0.0,
gyro_bias_y: 0.0,
gyro_bias_z: 0.0,
latitude_cov: 1e-6, // default covariance values
longitude_cov: 1e-6,
altitude_cov: 1e-6,
velocity_n_cov: 1e-6,
velocity_e_cov: 1e-6,
velocity_v_cov: 1e-6,
roll_cov: 1e-6,
pitch_cov: 1e-6,
yaw_cov: 1e-6,
acc_bias_x_cov: 1e-6,
acc_bias_y_cov: 1e-6,
acc_bias_z_cov: 1e-6,
gyro_bias_x_cov: 1e-6,
gyro_bias_y_cov: 1e-6,
gyro_bias_z_cov: 1e-6,
}
}
}
impl NavigationResult {
/// Creates a new NavigationResult with default values.
pub fn new() -> Self {
NavigationResult::default() // add in validation
}
/// Writes the NavigationResult to a CSV file.
///
/// # Arguments
/// * `records` - Vector of NavigationResult structs to write
/// * `path` - Path where the CSV file will be saved
///
/// # Returns
/// * `io::Result<()>` - Ok if successful, Err otherwise
pub fn to_csv<P: AsRef<Path>>(records: &[Self], path: P) -> io::Result<()> {
let mut writer = csv::Writer::from_path(path)?;
for record in records {
writer.serialize(record)?;
}
writer.flush()?;
Ok(())
}
/// Reads a CSV file and returns a vector of NavigationResult structs.
///
/// # Arguments
/// * `path` - Path to the CSV file to read.
///
/// # Returns
/// * `Ok(Vec<NavigationResult>)` if successful.
/// * `Err` if the file cannot be read or parsed.
pub fn from_csv<P: AsRef<std::path::Path>>(
path: P,
) -> Result<Vec<Self>, Box<dyn std::error::Error>> {
let mut rdr = csv::Reader::from_path(path)?;
let mut records = Vec::new();
for result in rdr.deserialize() {
let record: Self = result?;
records.push(record);
}
Ok(records)
}
/// Writes a vector of NavigationResult structs to an HDF5 file.
///
/// # Arguments
/// * `records` - Vector of NavigationResult structs to write
/// * `path` - Path where the HDF5 file will be saved
///