rinex-cli 0.3.0

Command line tool parse and analyze RINEX data
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
//! Command line tool to parse and analyze `RINEX` files.    
//! Refer to README for command line arguments.    
//! Based on crate <https://github.com/gwbres/rinex>     
//! Homepage: <https://github.com/gwbres/rinex-cli>
use clap::App;
use clap::load_yaml;
use std::str::FromStr;
use gnuplot::{Figure}; // Caption};
//use gnuplot::{Color, PointSymbol, LineStyle, DashType};
//use gnuplot::{PointSize, LineWidth}; // AxesCommon};

use thiserror::Error;
use rinex::Rinex;
use rinex::sv::Sv;
use rinex::observation;
use rinex::types::Type;
use rinex::epoch;
use rinex::constellation::{Constellation, augmentation::sbas_selection_helper};

#[derive(Error, Debug)]
pub enum Error {
    #[error("failed to parse datetime")]
    ChronoParseError(#[from] chrono::format::ParseError),
    #[error("std::io error")]
    IoError(#[from] std::io::Error),
}

/// Parses an std::time::Duration from user input
fn parse_duration (content: &str) -> Result<std::time::Duration, std::io::Error> {
    let hms : Vec<_> = content.split(":").collect();
    if hms.len() == 3 {
        if let Ok(h) =  u64::from_str_radix(hms[0], 10) {
            if let Ok(m) =  u64::from_str_radix(hms[1], 10) {
                if let Ok(s) =  u64::from_str_radix(hms[2], 10) {
                    return Ok(std::time::Duration::from_secs(h*3600 + m*60 +s))
                }
            }
        }
    }
    Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "failed to parse %HH:%MM:%SS"))
}

/// Parses an chrono::NaiveDateTime from user input
fn parse_datetime (content: &str) -> Result<chrono::NaiveDateTime, chrono::format::ParseError> {
    chrono::NaiveDateTime::parse_from_str(content, "%Y-%m-%d %H:%M:%S")
}

/// Parses an `epoch` from user input
fn parse_epoch (content: &str) -> Result<epoch::Epoch, Error> {
    let format = "YYYY-MM-DD HH:MM:SS";
    if content.len() > format.len() { // an epoch flag was given
        Ok(epoch::Epoch {
            date: parse_datetime(&content[0..format.len()])?,
            flag: epoch::EpochFlag::from_str(&content[format.len()..].trim())?,
        })
    } else { // no epoch flag given
        // --> we associate an Ok flag
        Ok(epoch::Epoch {
            date: parse_datetime(content)?,
            flag: epoch::EpochFlag::Ok,
        })
    }
}

pub fn main () -> Result<(), Error> {
	let yaml = load_yaml!("cli.yml");
    let app = App::from_yaml(yaml);
	let matches = app.get_matches();

    // General 
    let plot = matches.is_present("plot");
    let pretty = matches.is_present("pretty");

    // files
    let filepaths : Option<Vec<&str>> = match matches.is_present("filepath") {
        true => {
            Some(matches.value_of("filepath")
                .unwrap()
                    .split(",")
                    .collect())
        },
        false => None,
    };

    let _output : Option<Vec<&str>> = match matches.is_present("output") {
        true => {
            Some(matches.value_of("output")
                .unwrap()
                    .split(",")
                    .collect())
        },
        false => None,
    };

    let mut fig = Figure::new();

    // RINEX 
    let header = matches.is_present("header");
    let decimate_ratio = matches.is_present("decim-ratio");
    let decimate_interval = matches.is_present("decim-interval");
    let obscodes_display = matches.is_present("obscodes");

    // teqc ops
    let merge = matches.is_present("merge");
    let splice = matches.is_present("splice");
    let split = matches.is_present("split");
    let split_epoch : Option<epoch::Epoch> = match matches.value_of("split") {
        Some(s) => {
            if let Ok(e) = parse_epoch(s) {
                Some(e)
            } else {
                None
            }
        },
        None => None,
    };
    
    let teqc_ops = merge | split | splice;
    
    ///////////////////////////////////////////////////////////////
    // Filters 
    ///////////////////////////////////////////////////////////////
    // `Epoch`
    let epoch_display = matches.is_present("epoch");
    let epoch_ok_filter = matches.is_present("epoch-ok");
    let epoch_nok_filter = matches.is_present("epoch-nok");
    
    // Constell
    let constell_filter : Option<Vec<Constellation>> = match matches.value_of("constellation") {
        Some(s) => {
            let constellations: Vec<&str> = s.split(",").collect();
            let mut c_filters : Vec<Constellation> = Vec::new();
            for c in constellations {
                if let Ok(constell) = Constellation::from_3_letter_code(c) {
                    c_filters.push(constell)
                } else if let Ok(constell) = Constellation::from_1_letter_code(c) {
                    c_filters.push(constell)
                }
            }
            Some(c_filters)
        },
        _ => None,
    };
    
    // `Sv`
    let sv_filter : Option<Vec<Sv>> = match matches.value_of("sv") {
        Some(s) => {
            let sv: Vec<&str> = s.split(",").collect();
            let mut sv_filters : Vec<Sv> = Vec::new();
            for s in sv {
                let constell = Constellation::from_str(&s[0..1])
                    .unwrap();
                let prn = u8::from_str_radix(&s[1..], 10)
                    .unwrap();
                sv_filters.push(Sv::new(constell,prn))
            }
            Some(sv_filters)
        },
        _ => None,
    };

    let obscode_filter : Option<Vec<&str>> = match matches.value_of("codes") {
        Some(s) => Some(s.split(",").collect()),
        _ => None,
    };
    let lli : Option<u8> = match matches.value_of("lli") {
        Some(s) => Some(u8::from_str_radix(s,10).unwrap()),
        _ => None,
    };
    let ssi : Option<observation::record::Ssi> = match matches.value_of("ssi") {
        Some(s) => Some(observation::record::Ssi::from_str(s).unwrap()),
        _ => None,
    };
    
    // Other
    let sbas = matches.is_present("sbas"); 

    ////////////////////////////////////////
    // Process arguments that do not require 
    // the parser
    //   - sbas
    ////////////////////////////////////////
    if sbas {
        let sbas = matches.value_of("sbas")
            .unwrap();
        let items :Vec<&str> = sbas.split(",").collect();
        if items.len() != 2 {
            panic!("Command line error: \"--sbas latitude, longitude\" expected");
        }
        let coordinates :Vec<f64> = items
            .iter()
            .map(|s| {
                if let Ok(f) = f64::from_str(s.trim()) {
                    f
                } else {
                    panic!("Command line error: expecting coordinates in decimal degrees")
                }
            })
            .collect();
        let sbas = sbas_selection_helper(coordinates[0], coordinates[1]);
        if let Some(sbas) = sbas {
            println!("SBAS for given coordinates: {:?}", sbas);
        } else {
            println!("No SBAS augmentation for given coordinates");
        }
        return Ok(()); // interrupt before parser section
            // to make --fp optional
    }

    /////////////////////////////////////////
    // from now on: parser is always involved
    //  --fp is a requirement
    /////////////////////////////////////////
    let filepaths = filepaths.unwrap();

    let mut index : usize = 0;
    let mut merged: Rinex = Rinex::default();
    let mut to_merge : Vec<Rinex> = Vec::new(); 

for fp in &filepaths {
    let path = std::path::PathBuf::from(fp);
    fig.set_title(path.file_name().unwrap().to_str().unwrap());
    let mut rinex = match path.exists() {
        true => {
            if let Ok(r) = Rinex::from_file(fp) {
                r
            } else {
                println!("Failed to parse file \"{}\"", fp); 
                continue
            }
        },
        false => {
            println!("File \"{}\" does not exist", fp);
            continue
        },
    };

    if index == 0 {
        merged = rinex.clone()
    } else {
        to_merge.push(rinex.clone())
    }
    index += 1;

    ///////////////////////////////////////////////////
    // [1] resampling: reduce data quantity 
    ///////////////////////////////////////////////////
    if decimate_interval {
        let hms = matches.value_of("decim-interval").unwrap();
        let interval = parse_duration(hms)?;
        rinex.decimate_by_interval_mut(interval)
    }
    if decimate_ratio {
        let r = u32::from_str_radix(matches.value_of("decim-ratio").unwrap(), 10).unwrap();
        rinex.decimate_by_ratio_mut(r)
    }

    ///////////////////////////////////////////////////////////
    // [2] filtering: reduce data quantity,
    //  focus on data of interest
    //  Doing this prior anything else,
    //  makes merge() or production work on the resulting data
    ///////////////////////////////////////////////////////////
    if epoch_ok_filter {
        rinex
            .epoch_ok_filter_mut()
    }
    if epoch_nok_filter {
        rinex
            .epoch_nok_filter_mut()
    }
    if let Some(ref filter) = constell_filter {
        rinex
            .constellation_filter_mut(filter.to_vec())
    }
    if let Some(ref filter) = sv_filter {
        rinex
            .space_vehicule_filter_mut(filter.to_vec())
    }
    if let Some(ref filter) = obscode_filter {
        rinex
            .observable_filter_mut(filter.to_vec())
    }
    if let Some(lli) = lli {
        let mask = rinex::observation::record::LliFlags::from_bits(lli)
            .unwrap();
        rinex
            .lli_filter_mut(mask)
    }
    if let Some(ssi) = ssi {
        rinex
            .minimum_sig_strength_filter_mut(ssi)
    }
        
    if split {
        if let Some(epoch) = split_epoch {
            let s = rinex.split_at_epoch(epoch);
            if let Ok((r0, r1)) = s {
                if r0.to_file("split1.txt").is_err() {
                    panic!("failed to produce split1.txt")
                }
                if r1.to_file("split2.txt").is_err() {
                    panic!("failed to produce split1.txt")
                }
            } else {
                panic!("split_at_epoch failed with {:#?}", s);
            }
        }
    }

    if splice {
       println!("splice is WIP"); 
    }
    
    if !teqc_ops {
        // User did not request a `teqc` like / special ops
        // We generate desired output on each --fp entry
        if header {
            if pretty {
                println!("{}", serde_json::to_string_pretty(&rinex.header).unwrap())
            } else {
                println!("{}", serde_json::to_string_pretty(&rinex.header).unwrap())
            }
        }
        if epoch_display {
            let epochs = rinex.epochs();
            if pretty {
                println!("{}", serde_json::to_string_pretty(&epochs).unwrap())
            } else {
                println!("{}", serde_json::to_string(&epochs).unwrap())
            }
        }
        if obscodes_display {
            let observables = rinex.observables();
            if pretty {
                println!("{}", serde_json::to_string_pretty(&observables).unwrap())
            } else {
                println!("{}", serde_json::to_string(&observables).unwrap())
            }
        }
        if !epoch_display && !obscodes_display && !header { 
            match rinex.header.rinex_type {
                // display somehow (either graphically or print())
                // remaining data
                // TODO: improve please
                Type::ObservationData => {
                    let r = rinex.record.as_obs().unwrap();
                    if pretty {
                        println!("{}", serde_json::to_string_pretty(r).unwrap())
                    } else {
                        println!("{}", serde_json::to_string(r).unwrap())
                    }
                    if plot {
                        ///////////////////////////////////
                        // determine remaining OBS codes
                        ///////////////////////////////////
                        let mut codes : Vec<String> = Vec::new();
                        r.iter()
                            .for_each(|(_, (_,data))| {
                                data.iter()
                                    .for_each(|(_, data)| {
                                        data.iter()
                                            .for_each(|(code, _)| {
                                                if !codes.contains(code) {
                                                    codes.push(code.to_string())
                                                }
                                            })
                                    })
                                });
                        for code in codes { // for all remaining OBS/physics
                            let _data: Vec<Vec<Vec<f32>>> = Vec::new();// PerSV,PerEpoch,Data
                            r.iter()
                                .for_each(|(_e, (_, sv))| {
                                    sv.iter()
                                        .for_each(|(_sv, _data)| {
                                            
                                        })
                                });
                            fig.save_to_png(&format!("{}.png", code),640,480).unwrap()
                        } // for all remaining OBS/physics
                        /*
                        // for all constellations 
                        for constellation in constellations {
                            // all codes available for this constellation
                            let codes = &obscodes[&constellation]; 
                            // [1] Determine available (remaining) 
                            // types of OBS for this constellation
                            let mut obs_types : Vec<String> = Vec::new();
                            r.iter()
                                .for_each(|(e, (ck, sv))| {
                                    sv.iter()
                                        .for_each(|(sv, data)| {
                                        if sv.constellation == constellation {
                                            data.iter()
                                                .for_each(|(code, _)| {
                                                if !obs_types.contains(code) {
                                                    obs_types.push(code.to_string())
                                                }
                                            })
                                        }
                                    })
                                });
                            for obs_type in obs_types { // for all available OBS
                                // grab OBS raw data
                                let data : HashMap<Sv, f32> = HashMap::new();
                                 r
                                    .iter()
                                    .map(|(_, (_, sv))| {
                                        sv.iter()
                                            .find(|(k,_)| k.constellation == constellation)
                                            .map(|(sv, data)| {
                                                data.iter()
                                                    .find(|(code, _)| *code == &obs_type)
                                                    .map(|(_, data)| {
                                                        data.obs
                                                    })
                                            })
                                            .flatten()
                                    })
                                    .flatten()
                                    .collect();
                                let y : Vec<f32> = (0..z.len()).map(|x| x as f32).collect();
                                let mut axes = fig.axes3d()
                                    .set_x_grid(true)
                                    .set_y_grid(true)
                                    .set_z_grid(true);
                                axes
                                    .lines(x, y.clone(), y.clone(), &[
                                        Caption(&obs_type),
                                        Color("blue"),
                                        PointSize(10.0),
                                        PointSymbol('x'),
                                    ]);
                            }
                        }*/
                    }
                },
                Type::NavigationData => {
                    let r = rinex.record.as_nav().unwrap();
                    if pretty {
                        println!("{}", serde_json::to_string_pretty(r).unwrap())
                    } else {
                        println!("{}", serde_json::to_string(r).unwrap())
                    }
                },
                Type::MeteoData => {
                    let r = rinex.record.as_meteo().unwrap();
                    if pretty {
                        println!("{}", serde_json::to_string_pretty(r).unwrap())
                    } else {
                        println!("{}", serde_json::to_string(r).unwrap())
                    }
                },
                _ => todo!("RINEX type not fully suppported yet"),
            }
        }
    }
}// for all files
    
    // Merge() opt
    for i in 0..to_merge.len() {
        if merged.merge_mut(&to_merge[i]).is_err() {
            panic!("Failed to merge {} into {}", filepaths[i], filepaths[0])
        }
    }

    if merge {
        // User requested teqc::merge()
        // we extract desired information off the merged record
        if header {
            if pretty {
                println!("{}", serde_json::to_string_pretty(&merged.header).unwrap())
            } else {
                println!("{}", serde_json::to_string(&merged.header).unwrap())
            }
        }
        if obscodes_display {
            let observables = merged.observables();
            if pretty {
                println!("{}", serde_json::to_string_pretty(&observables).unwrap())
            } else {
                println!("{}", serde_json::to_string(&observables).unwrap())
            }
        }
        if epoch_display {
            let e = merged.epochs();
            if pretty {
                println!("{}", serde_json::to_string_pretty(&e).unwrap())
            } else {
                println!("{}", serde_json::to_string(&e).unwrap())
            }
        }
        if merged.to_file("merged.txt").is_err() {
            panic!("Failed to write MERGED RINEX to \"merged.txt\"")
        }
    }
    Ok(())
}// main

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn test_duration_parser() {
        let duration = parse_duration("00:30:00");
        assert_eq!(duration.is_ok(), true);
        let duration = duration.unwrap();
        assert_eq!(duration, std::time::Duration::from_secs(30*60));
        let duration = parse_duration("30:00");
        assert_eq!(duration.is_err(), true);
        let duration = parse_duration("00 30 00");
        assert_eq!(duration.is_err(), true);
    }
    #[test]
    fn test_epoch_parser() {
        let epoch = parse_epoch("2022-03-01 00:30:00");
        assert_eq!(epoch.is_ok(), true);
        let epoch = epoch.unwrap();
        assert_eq!(epoch, epoch::Epoch {
            date: parse_datetime("2022-03-01 00:30:00").unwrap(),
            flag: epoch::EpochFlag::Ok,
        });
    }
}