rinex-cli 0.12.1

RINEX and SP3 data post processing tool
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
use std::{
    collections::hash_map::DefaultHasher,
    hash::{Hash, Hasher},
    path::{Path, PathBuf},
    str::FromStr,
};

use itertools::Itertools;

use clap::{value_parser, Arg, ArgAction, ArgMatches, ColorChoice, Command};
use gnss_qc::prelude::{QcConfig, QcContext, QcReportType};
use rinex::prelude::GroundPosition;

mod fops;
mod positioning;
mod workspace;

pub use workspace::Workspace;

use fops::{diff, filegen, merge, split, time_binning};

pub struct Cli {
    /// Arguments passed by user
    pub matches: ArgMatches,
}

impl Default for Cli {
    fn default() -> Self {
        Self::new()
    }
}

pub struct RemoteReferenceSite {
    pub data: QcContext,
    pub rx_ecef: Option<(f64, f64, f64)>,
}

/// Context defined by User.
pub struct Context {
    /// Quiet option
    pub quiet: bool,
    /// Data context defined by user.
    /// In differential opmode, this is the ROVER.
    pub data: QcContext,
    /// Remote reference site (secondary dataset) defined by User.
    /// Serves as reference point in differential techniques.
    pub reference_site: Option<RemoteReferenceSite>,
    /// Context name is derived from the primary file loaded in Self,
    /// and mostly used in output products generation.
    pub name: String,
    /// Workspace is the place where this session will generate data.
    /// By default it is set to $WORKSPACE/$PRIMARYFILE.
    /// $WORKSPACE is either manually definedd by CLI or we create it (as is).
    /// $PRIMARYFILE is determined from the most major file contained in the dataset.
    pub workspace: Workspace,
    /// (RX) reference position to be used in further analysis.
    /// It is either (priority order is important)
    ///  1. manually defined by CLI
    ///  2. determined from dataset
    pub rx_ecef: Option<(f64, f64, f64)>,
}

impl Context {
    /*
     * Utility to determine the most major filename stem,
     * to be used as the session workspace
     */
    pub fn context_stem(data: &QcContext) -> String {
        let ctx_major_stem: &str = data
            .primary_path()
            .expect("failed to determine a context name")
            .file_stem()
            .expect("failed to determine a context name")
            .to_str()
            .expect("failed to determine a context name");
        /*
         * In case $FILENAME.RNX.gz gz compressed, we extract "$FILENAME".
         * Can use .file_name() once https://github.com/rust-lang/rust/issues/86319  is stabilized
         */
        let primary_stem: Vec<&str> = ctx_major_stem.split('.').collect();
        primary_stem[0].to_string()
    }
    /*
     * Utility to create a file in this session
     */
    fn create_file(&self, path: &Path) -> std::fs::File {
        std::fs::File::create(path).unwrap_or_else(|e| {
            panic!("failed to create {}: {:?}", path.display(), e);
        })
    }
    // Returns True if this context is compatible with RTK positioning
    pub fn rtk_compatible(&self) -> bool {
        if let Some(remote) = &self.reference_site {
            self.data.observation().is_some()
                && self.rx_ecef.is_some()
                && remote.data.observation().is_some()
                && remote.rx_ecef.is_some()
        } else {
            false
        }
    }
}

impl Cli {
    /// Build new command line interface
    pub fn new() -> Self {
        let cmd =
                Command::new("rinex-cli")
                    .author("Guillaume W. Bres, <guillaume.bressaix@gmail.com>")
                    .version(env!("CARGO_PKG_VERSION"))
                    .about("RINEX post processing")
                    .long_about("RINEX-Cli is the command line interface
to operate the RINEX/SP3/RTK toolkit, until a GUI is made available.
Use it to analyze data, perform file operations and resolve navigation solutions.")
                    .arg_required_else_help(true)
                    .color(ColorChoice::Always)
                    .next_help_heading("Context")
                    .arg(Arg::new("filepath")
                        .long("fp")
                        .value_name("FILE")
                        .action(ArgAction::Append)
                        .required_unless_present("directory")
                        .help("Load a single file. See --help")
                        .long_help("Use this as many times as needed. 
Available operations and following behavior highly depends on input data. 
Supported formats are:
- Observation RINEX
- Navigation RINEX
- Meteo RINEX
- Clock RINEX (high precision clocks)
- SP3 (high precision orbits)
- IONEX (Ionosphere Maps)
- ANTEX (antenna calibration as RINEX)
- DORIS (special Observation RINEX)

Example (1): Load a single file
rinex-cli \\
    --fp test_resources/CRNX/V3/ESBC00DNK_R_20201770000_01D_30S_MO.crx.gz

Example (2): define a PPP compliant context
rinex-cli \\
    --fp test_resources/CRNX/V3/ESBC00DNK_R_20201770000_01D_30S_MO.crx.gz \\
    --fp test_resources/NAV/V3/ESBC00DNK_R_20201770000_01D_MN.rnx.gz \\
    --fp test_resources/CLK/V3/GRG0MGXFIN_20201770000_01D_30S_CLK.CLK.gz \\ 
    --fp test_resources/SP3/GRG0MGXFIN_20201770000_01D_15M_ORB.SP3.gz
"))
                    .arg(Arg::new("directory")
                        .short('d')
                        .long("dir")
                        .value_name("DIRECTORY")
                        .action(ArgAction::Append)
                        .required_unless_present("filepath")
                        .help("Directory recursivel loader. See --help.")
                        .long_help("Use this as many times as needed. Default recursive depth is set to 5,
but you can extend that with --depth. Refer to -f for more information."))
                    .arg(Arg::new("depth")
                        .long("depth")
                        .action(ArgAction::Set)
                        .required(false)
                        .value_parser(value_parser!(u8))
                        .help("Extend maximal recursive search depth of -d. The default is 5.")
                        .long_help("The default recursive depth already supports hierarchies like:
/YEAR1
     /DOY0
          /STATION1
     /DOY1
          /STATION2
/YEAR2
     /DOY0
          /STATION1"))
                    .arg(Arg::new("quiet")
                        .short('q')
                        .long("quiet")
                        .action(ArgAction::SetTrue)
                        .help("Disable all terminal output. Disables automatic report opener (Web browser)."))
                    .arg(Arg::new("workspace")
                        .short('w')
                        .long("workspace")
                        .value_name("FOLDER")
                        .value_parser(value_parser!(PathBuf))
                        .help("Define custom workspace location. See --help.")
                        .long_help("The Workspace is where Output Products are to be generated.
By default the $RINEX_WORKSPACE variable is prefered if it is defined.
You can also use this flag to customize it. 
If none are defined, we will then try to create a local directory named \"WORKSPACE\" like it is possible in this very repo."))
                .arg(Arg::new("jpl-bpc")
                    .long("jpl-bpc")
                    .action(ArgAction::SetTrue)
                    .help("Force update or request upgrade to highest precision JPL daily model.
Requires internet access on each deployment!
Once downloaded (updated) a model is valid for a couple of days or weeks, but you should regularly update
to obtain highest precision."))
        .next_help_heading("Output customization")
        .arg(
            Arg::new("output-name")
                .short('o')
                .action(ArgAction::Set)
                .help("Customize output file or report name.
In analysis opmode, report is named index.html by default, this will redefine that.
In file operations (filegen, etc..) we can manually define output filenames with this option."))
        .next_help_heading("Report customization")
        .arg(
            Arg::new("report-sum")
                .long("sum")
                .action(ArgAction::SetTrue)
                .help("Restrict report to summary header only (quicker rendition)")
        )
        .arg(
            Arg::new("report-force")
                .short('f')
                .long("force")
                .action(ArgAction::SetTrue)
                .help("Force report synthesis.
By default, report synthesis happens once per input set (file combnation and cli options).
Use this option to force report regeneration.
This has no effect on file operations that do not synthesize a report."))
        .arg(
            Arg::new("report-brdc-sky")
                .long("brdc-sky")
                .action(ArgAction::SetTrue)
                .help("When SP3 and/or BRDC RINEX is present,
the skyplot (compass) projection is only calculated from the SP3 coordinates (highest precision). 
Use this option to also calculate it from radio messages (for comparison purposes for example).")
        )
        .arg(
            Arg::new("report-nostats")
                .long("nostats")
                .action(ArgAction::SetTrue)
                .help("Hide statistical annotations that might be present in some plots.
This has no effect on applications compiled without plot and statistical options.")
        )
        .next_help_heading("Preprocessing")
            .arg(Arg::new("gps-filter")
                .short('G')
                .action(ArgAction::SetTrue)
                .help("Filters out all GPS vehicles"))
            .arg(Arg::new("glo-filter")
                .short('R')
                .action(ArgAction::SetTrue)
                .help("Filters out all Glonass vehicles"))
            .arg(Arg::new("gal-filter")
                .short('E')
                .action(ArgAction::SetTrue)
                .help("Filters out all Galileo vehicles"))
            .arg(Arg::new("bds-filter")
                .short('C')
                .action(ArgAction::SetTrue)
                .help("Filters out all BeiDou vehicles"))
            .arg(Arg::new("bds-geo-filter")
                .long("CG")
                .action(ArgAction::SetTrue)
                .help("Filter out all BeiDou Geo vehicles"))
            .arg(Arg::new("qzss-filter")
                .short('J')
                .action(ArgAction::SetTrue)
                .help("Filters out all QZSS vehicles"))
            .arg(Arg::new("irnss-filter")
                .short('I')
                .action(ArgAction::SetTrue)
                .help("Filters out all IRNSS vehicles"))
            .arg(Arg::new("sbas-filter")
                .short('S')
                .action(ArgAction::SetTrue)
                .help("Filters out all SBAS vehicles"))
            .arg(Arg::new("preprocessing")
                .short('P')
                .num_args(1..)
                .value_delimiter(';')
                .action(ArgAction::Append)
                .help("Filter designer. Refer to []."))
            .next_help_heading("RINEX Repair")
                .arg(Arg::new("zero-repair")
                    .short('z')
                    .action(ArgAction::SetTrue)
                    .help("Remove all zero (=null) values. See --help")
                    .long_help("
Removes all zero (null) values from data records.
Specifically in NAV and OBS RINEX. Null NAV records are forbidden.
Null OBS RINEX are also most likely invalid.
To determine whether some null Observations exist (most likely invalid), simply
generate a first report and study the provided observations.
The `ppp` solver will most likely encounter Physical Non Sense Errors.
Null NAV RINEX content is also invalid by definition."))
            .next_help_heading("Receiver Antenna")
                .arg(Arg::new("rx-ecef")
                    .long("rx-ecef")
                    .value_name("\"x,y,z\" coordinates in ECEF [m]")
                    .help("Define the (RX) antenna position manually, in [m] ECEF.
Especially if your dataset does not define such position. 
Otherwise it gets automatically picked up."))
                .arg(Arg::new("rx-geo")
                    .long("rx-geo")
                    .value_name("\"lat,lon,alt\" coordinates in ddeg [°]")
                    .help("Define the (RX) antenna position manualy, in decimal degrees."))
                .next_help_heading("Exclusive Opmodes: you can only run one at a time.")
                .subcommand(filegen::subcommand());

        let cmd = cmd
            .subcommand(merge::subcommand())
            .subcommand(positioning::ppp_subcommand())
            .subcommand(positioning::rtk_subcommand())
            .subcommand(split::subcommand())
            .subcommand(diff::subcommand())
            .subcommand(time_binning::subcommand());
        Self {
            matches: cmd.get_matches(),
        }
    }
    /// Recursive browser depth
    pub fn recursive_depth(&self) -> usize {
        if let Some(depth) = self.matches.get_one::<u8>("depth") {
            *depth as usize
        } else {
            5
        }
    }
    /// Returns individual input ROVER -d
    pub fn rover_directories(&self) -> Vec<&String> {
        if let Some(dirs) = self.matches.get_many::<String>("directory") {
            dirs.collect()
        } else {
            Vec::new()
        }
    }
    /// Returns individual input ROVER -fp
    pub fn rover_files(&self) -> Vec<&String> {
        if let Some(fp) = self.matches.get_many::<String>("filepath") {
            fp.collect()
        } else {
            Vec::new()
        }
    }
    /// Returns individual input BASE STATION -d
    pub fn base_station_directories(&self) -> Vec<&String> {
        match self.matches.subcommand() {
            Some(("rtk", submatches)) => {
                if let Some(dir) = submatches.get_many::<String>("dir") {
                    dir.collect()
                } else {
                    Vec::new()
                }
            },
            _ => Vec::new(),
        }
    }
    /// Returns individual input BASE STATION -fp
    pub fn base_station_files(&self) -> Vec<&String> {
        match self.matches.subcommand() {
            Some(("rtk", submatches)) => {
                if let Some(fp) = submatches.get_many::<String>("fp") {
                    fp.collect()
                } else {
                    Vec::new()
                }
            },
            _ => Vec::new(),
        }
    }
    /// Returns preproc ops
    pub fn preprocessing(&self) -> Vec<&String> {
        if let Some(filters) = self.matches.get_many::<String>("preprocessing") {
            filters.collect()
        } else {
            Vec::new()
        }
    }
    pub fn gps_filter(&self) -> bool {
        self.matches.get_flag("gps-filter")
    }
    pub fn glo_filter(&self) -> bool {
        self.matches.get_flag("glo-filter")
    }
    pub fn gal_filter(&self) -> bool {
        self.matches.get_flag("gal-filter")
    }
    pub fn bds_filter(&self) -> bool {
        self.matches.get_flag("bds-filter")
    }
    pub fn bds_geo_filter(&self) -> bool {
        self.matches.get_flag("bds-geo-filter")
    }
    pub fn qzss_filter(&self) -> bool {
        self.matches.get_flag("qzss-filter")
    }
    pub fn sbas_filter(&self) -> bool {
        self.matches.get_flag("sbas-filter")
    }
    pub fn irnss_filter(&self) -> bool {
        self.matches.get_flag("irnss-filter")
    }
    pub fn zero_repair(&self) -> bool {
        self.matches.get_flag("zero-repair")
    }
    /*
     * faillible 3D coordinates parsing
     * it's better to panic if the descriptor is badly format
     * then continuing with possible other coordinates than the
     * ones desired by user
     */
    fn parse_3d_coordinates(desc: &String) -> (f64, f64, f64) {
        let content = desc.split(',').collect::<Vec<&str>>();
        if content.len() < 3 {
            panic!("expecting x, y and z coordinates (3D)");
        }
        let x = f64::from_str(content[0].trim())
            .unwrap_or_else(|_| panic!("failed to parse x coordinates"));
        let y = f64::from_str(content[1].trim())
            .unwrap_or_else(|_| panic!("failed to parse y coordinates"));
        let z = f64::from_str(content[2].trim())
            .unwrap_or_else(|_| panic!("failed to parse z coordinates"));
        (x, y, z)
    }
    fn manual_ecef(&self) -> Option<(f64, f64, f64)> {
        let desc = self.matches.get_one::<String>("rx-ecef")?;
        let ecef = Self::parse_3d_coordinates(desc);
        Some(ecef)
    }
    fn manual_geodetic(&self) -> Option<(f64, f64, f64)> {
        let desc = self.matches.get_one::<String>("rx-geo")?;
        let geo = Self::parse_3d_coordinates(desc);
        Some(geo)
    }
    /// Returns RX Position possibly specified by user
    pub fn manual_position(&self) -> Option<(f64, f64, f64)> {
        if let Some(position) = self.manual_ecef() {
            Some(position)
        } else {
            self.manual_geodetic()
                .map(|position| GroundPosition::from_geodetic(position).to_ecef_wgs84())
        }
    }
    /// True if File Operations to generate data is being deployed
    pub fn has_fops_output_product(&self) -> bool {
        matches!(
            self.matches.subcommand(),
            Some(("filegen", _))
                | Some(("merge", _))
                | Some(("split", _))
                | Some(("tbin", _))
                | Some(("diff", _))
        )
    }
    /// True if forced report synthesis is requested
    pub fn force_report_synthesis(&self) -> bool {
        self.matches.get_flag("report-force")
    }
    /*
     * We hash all vital CLI information.
     * This helps in determining whether we need to update an existing report
     * or not.
     */
    pub fn hash(&self) -> u64 {
        let mut hasher = DefaultHasher::new();
        let mut string = self
            .rover_directories()
            .into_iter()
            .sorted()
            .chain(self.rover_files().into_iter().sorted())
            .chain(self.preprocessing().into_iter().sorted())
            .join(",");
        if let Some(custom) = self.custom_output_name() {
            string.push_str(custom);
        }
        if let Some(geo) = self.manual_geodetic() {
            string.push_str(&format!("{:?}", geo));
        }
        if let Some(ecef) = self.manual_ecef() {
            string.push_str(&format!("{:?}", ecef));
        }
        string.hash(&mut hasher);
        hasher.finish()
    }
    /// Returns QcConfig from command line
    pub fn qc_config(&self) -> QcConfig {
        QcConfig {
            manual_reference: if let Some(manual) = self.manual_position() {
                Some(GroundPosition::from_ecef_wgs84(manual))
            } else {
                None
            },
            report: if self.matches.get_flag("report-sum") {
                QcReportType::Summary
            } else {
                QcReportType::Full
            },
            force_brdc_skyplot: self.matches.get_flag("report-brdc-sky"),
        }
    }
    /// Customized / manually defined output to be generated
    pub fn custom_output_name(&self) -> Option<&String> {
        self.matches.get_one::<String>("output-name")
    }

    /// True if jpl_bpc_update is requested
    pub fn jpl_bpc_update(&self) -> bool {
        self.matches.get_flag("jpl-bpc")
    }
}