rinex-cli 0.15.0

GNSS data post processing and quality control, powered by GNSS-Qc
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
//! Command line interface
use std::{path::PathBuf, str::FromStr};

use clap::{Args, Parser, Subcommand, ValueEnum};

use gnss_qc::prelude::{Epoch, QcIndexingConfig};

use crate::error::Error;

#[derive(Debug, Parser)]
#[command(
    name = "rinex-cli",
    author,
    version,
    about = "GNSS post processing and quality control, powered by GNSS-Qc",
    long_about = "RINEX-Cli deploys the GNSS-Qc engine on your data:
input products are indexed (receivers, agencies, aliases), synchronized,
processed (quality control, navigation, CGGTTS, residuals..) and the results
are written into a session workspace: data files (CSV, JSON lines, CGGTTS..)
and reports (HTML, PDF).

Start with the index command, to verify how your files are identified:

  rinex-cli -d DATA/ index"
)]
pub struct Cli {
    #[command(flatten)]
    pub inputs: InputArgs,

    #[command(flatten)]
    pub preprocessing: PreprocessingArgs,

    #[command(flatten)]
    pub outputs: OutputArgs,

    /// Opmode
    #[command(subcommand)]
    pub command: Command,
}

/// Input products definition and indexing
#[derive(Debug, Args)]
#[command(next_help_heading = "Inputs")]
pub struct InputArgs {
    /// Load one file: RINEX (observation, navigation, meteo, clock), CRINEX, SP3,
    /// IONEX (ionex feature), gzip compressed or not. Repeat as needed.
    /// Prefix with ALIAS= to index this file (and merge it) under a custom alias,
    /// for example: -f base=MOJN00DNK_R_20201770000_01D_30S_MO.crx.gz
    #[arg(short = 'f', long = "file", value_name = "[ALIAS=]FILE", global = true)]
    pub files: Vec<String>,

    /// Load every file of a directory (recursively). Repeat as needed.
    /// Prefix with ALIAS= to index every file of this directory under a custom alias.
    #[arg(short = 'd', long = "dir", value_name = "[ALIAS=]DIR", global = true)]
    pub directories: Vec<String>,

    /// Maximal recursion depth of -d
    #[arg(long, default_value_t = 5, global = true)]
    pub depth: usize,

    /// Indexing method of observation RINEX (signal sources):
    /// receiver (default), antenna, operator, filename, auto, alias:NAME
    #[arg(long, value_name = "METHOD", global = true)]
    pub obs_index: Option<IndexingMethod>,

    /// Indexing method of navigation RINEX: agency (default), filename, auto, alias:NAME
    #[arg(long, value_name = "METHOD", global = true)]
    pub nav_index: Option<IndexingMethod>,

    /// Indexing method of SP3 files: agency (default), filename, auto, alias:NAME
    #[arg(long, value_name = "METHOD", global = true)]
    pub sp3_index: Option<IndexingMethod>,

    /// Indexing method of meteo RINEX: agency (default), filename, auto, alias:NAME
    #[arg(long, value_name = "METHOD", global = true)]
    pub meteo_index: Option<IndexingMethod>,

    /// Indexing method of clock RINEX: agency (default), filename, auto, alias:NAME
    #[arg(long, value_name = "METHOD", global = true)]
    pub clk_index: Option<IndexingMethod>,

    /// Indexing method of IONEX files: agency (default), filename, auto, alias:NAME
    #[arg(long, value_name = "METHOD", global = true)]
    pub ionex_index: Option<IndexingMethod>,

    /// Input preferences (QcInputConfig) as JSON file.
    /// The --*-index options take precedence.
    #[arg(long, value_name = "JSON", global = true)]
    pub input_cfg: Option<PathBuf>,

    /// Processing window: first epoch (for example "2020-06-25T00:00:00 GPST")
    #[arg(long, value_name = "EPOCH", global = true)]
    pub start: Option<Epoch>,

    /// Processing window: last epoch
    #[arg(long, value_name = "EPOCH", global = true)]
    pub end: Option<Epoch>,
}

/// Preprocessing, applied to each file before indexing
#[derive(Debug, Default, Args)]
#[command(next_help_heading = "Preprocessing")]
pub struct PreprocessingArgs {
    /// Filter out GPS
    #[arg(short = 'G', global = true)]
    pub no_gps: bool,

    /// Filter out Glonass
    #[arg(short = 'R', global = true)]
    pub no_glonass: bool,

    /// Filter out Galileo
    #[arg(short = 'E', global = true)]
    pub no_galileo: bool,

    /// Filter out BeiDou
    #[arg(short = 'C', global = true)]
    pub no_beidou: bool,

    /// Filter out BeiDou GEO satellites
    #[arg(long = "CG", global = true)]
    pub no_beidou_geo: bool,

    /// Filter out QZSS
    #[arg(short = 'J', global = true)]
    pub no_qzss: bool,

    /// Filter out IRNSS
    #[arg(short = 'I', global = true)]
    pub no_irnss: bool,

    /// Filter out SBAS
    #[arg(short = 'S', global = true)]
    pub no_sbas: bool,

    /// Preprocessing filter (GNSS-Qc filter designer), ';' separated.
    /// For example: -P "GPS;>E05" or -P "decim:30s"
    #[arg(short = 'P', value_delimiter = ';', global = true)]
    pub filters: Vec<String>,

    /// Remove null observations (zero repair)
    #[arg(short = 'z', long = "zero-repair", global = true)]
    pub zero_repair: bool,

    /// Snap the epochs of the observation RINEX to the nearest second, correcting the
    /// pseudo ranges (c·Δt) and phase ranges (f·Δt). Aligns the free running time tags of
    /// low cost receivers (16:25:42.999) on those of a reference station (16:25:43): required
    /// for RTK. Applied before the filters.
    #[arg(long, global = true)]
    pub snap_epochs: bool,

    /// Keep the observation epochs that are multiples of this period (for example "30 s"),
    /// to match the sampling of a reference station. Unlike a decimation (-P "decim:30 s"),
    /// the retained instants do not depend on the first epoch of each file.
    /// Applied after --snap-epochs, before the filters.
    #[arg(long, value_name = "PERIOD", global = true, value_parser = parse_duration)]
    pub align_sampling: Option<gnss_qc::prelude::Duration>,
}

/// Report format
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum ReportFormat {
    /// Interactive, self-contained HTML page
    Html,
    /// Static PDF document (requires the pdf feature)
    Pdf,
    /// No report
    None,
}

/// Data format
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum DataFormat {
    /// One CSV file per kind of result
    Csv,
    /// The complete stream of results, one JSON object per line
    Jsonl,
    /// No data file
    None,
}

/// Outputs definition
#[derive(Debug, Args)]
#[command(next_help_heading = "Outputs")]
pub struct OutputArgs {
    /// Output folder. Each session is written in its own subfolder.
    #[arg(
        short = 'o',
        long = "output",
        value_name = "DIR",
        env = "RINEX_WORKSPACE",
        default_value = "WORKSPACE",
        global = true
    )]
    pub output: PathBuf,

    /// Session name (subfolder). Default: name of the primary input file.
    #[arg(long, value_name = "NAME", global = true)]
    pub session: Option<String>,

    /// Report formats, comma separated: html (default), pdf, none
    #[arg(
        long,
        value_enum,
        value_delimiter = ',',
        default_value = "html",
        global = true
    )]
    pub report: Vec<ReportFormat>,

    /// Data formats, comma separated: csv (default), jsonl, none
    #[arg(
        long,
        value_enum,
        value_delimiter = ',',
        default_value = "csv",
        global = true
    )]
    pub data: Vec<DataFormat>,

    /// Also export the raw signal observations and TEC map nodes (large)
    #[arg(long, global = true)]
    pub raw: bool,

    /// Stream the results on stdout (JSON lines). Logs go to stderr.
    #[arg(long, global = true)]
    pub stdout: bool,

    /// Processing commands (nav, cggtts, ipp, residuals obs): do not add the quality
    /// control of the observations (signal sources, sky view, data gaps) to the report
    #[arg(long, global = true)]
    pub no_qc: bool,

    /// Report title. Default: session name.
    #[arg(long, global = true)]
    pub title: Option<String>,

    /// Open the report once generated
    #[arg(long, global = true)]
    pub open: bool,

    /// Only report warnings and errors
    #[arg(short = 'q', long, global = true)]
    pub quiet: bool,
}

impl OutputArgs {
    pub fn html(&self) -> bool {
        self.report.contains(&ReportFormat::Html)
    }

    pub fn pdf(&self) -> bool {
        self.report.contains(&ReportFormat::Pdf)
    }

    pub fn csv(&self) -> bool {
        self.data.contains(&DataFormat::Csv)
    }

    pub fn jsonl(&self) -> bool {
        self.data.contains(&DataFormat::Jsonl)
    }
}

/// Indexing method, as selected on the command line
#[derive(Debug, Clone, PartialEq)]
pub enum IndexingMethod {
    /// Automatic indexing
    Auto,
    /// One of the GNSS-Qc presets
    Preset(QcIndexingConfig),
}

impl FromStr for IndexingMethod {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let method = s.trim();
        match method.to_lowercase().as_str() {
            "auto" => Ok(Self::Auto),
            "receiver" => Ok(Self::Preset(QcIndexingConfig::Receiver)),
            "antenna" => Ok(Self::Preset(QcIndexingConfig::Antenna)),
            "operator" => Ok(Self::Preset(QcIndexingConfig::Operator)),
            "agency" => Ok(Self::Preset(QcIndexingConfig::Agency)),
            "filename" | "file" => Ok(Self::Preset(QcIndexingConfig::FileName)),
            _ => {
                let alias = method
                    .strip_prefix("alias:")
                    .or_else(|| method.strip_prefix("custom:"))
                    .filter(|alias| !alias.is_empty())
                    .ok_or(Error::InvalidIndexingMethod(method.to_string()))?;
                Ok(Self::Preset(QcIndexingConfig::Custom(alias.to_string())))
            },
        }
    }
}

impl IndexingMethod {
    /// Converts to a GNSS-Qc preference
    pub fn to_config(&self) -> Option<QcIndexingConfig> {
        match self {
            Self::Auto => None,
            Self::Preset(cfg) => Some(cfg.clone()),
        }
    }
}

#[derive(Debug, Subcommand)]
pub enum Command {
    /// Lists the input products, as indexed (identity, type, files, time frame).
    /// Nothing is processed.
    Index(IndexArgs),

    /// Quality control of the signal sources: observations, sampling, gaps,
    /// cycle slips, signal strength, ephemeris coverage.
    Qc(QcArgs),

    /// P.V.T solutions (SPP, CPP, PPP, RTK). Requires the navigation feature.
    Nav(NavArgs),

    /// CGGTTS solutions (common view time transfer). Requires the cggtts feature.
    Cggtts(CggttsArgs),

    /// Residual analysis: A − B between two receivers, two orbital products
    /// or two clock products.
    Residuals(ResidualsArgs),

    /// Meteo sensors analysis: statistics and time series of every sensor
    /// (Meteo RINEX).
    Meteo(MeteoArgs),

    /// Signal combinations of the observations: Geometry Free (ionosphere, cycle slips),
    /// Ionosphere Free and code multipath, for every pair of frequencies.
    #[command(visible_alias = "comb")]
    Combinations(CombinationsArgs),

    /// TEC maps analysis (IONEX): statistics per region, map after map; temporal
    /// interpolation and synthesis of new IONEX files. Requires the ionex feature.
    Tec(TecArgs),

    /// Ionospheric Pierce Points of every line of sight. Requires the ionex feature.
    Ipp(IppArgs),

    /// File operation: writes the (preprocessed) input products as RINEX / SP3
    Filegen(FilegenArgs),

    /// File operation: merges a file into the input product of the same kind
    Merge(MergeArgs),

    /// File operation: splits the input products at this epoch
    Split(SplitArgs),

    /// File operation: time binning, a batch of files of this duration
    Tbin(TbinArgs),

    /// File operation: constellation binning, one file per constellation
    Cbin(CbinArgs),

    /// File operation: observation RINEX (A) − FILE (B)
    Diff(DiffArgs),
}

impl Command {
    /// True for the file operations, which do not deploy the engine
    pub fn is_file_operation(&self) -> bool {
        matches!(
            self,
            Self::Filegen(_)
                | Self::Merge(_)
                | Self::Split(_)
                | Self::Tbin(_)
                | Self::Cbin(_)
                | Self::Diff(_)
        )
    }
}

/// File production options
#[derive(Debug, Default, Args)]
#[command(next_help_heading = "File production")]
pub struct ProductionArgs {
    /// Gzip compressed output
    #[arg(long)]
    pub gzip: bool,

    /// Prefer (deprecated) V2 short file names
    #[arg(short, long)]
    pub short: bool,

    /// Agency (file name), overriding the input
    #[arg(short, long)]
    pub agency: Option<String>,

    /// Country code (3 letters, V3 file name)
    #[arg(long)]
    pub country: Option<String>,

    /// Batch number (V3 file name)
    #[arg(short, long)]
    pub batch: Option<u8>,

    /// Data source (V3 file name): RCVR, STREAM
    #[arg(long, value_name = "RCVR|STREAM")]
    pub src: Option<String>,

    /// Production periodicity (V3 file name): 15M, 01H, 01D, 01Y
    #[arg(long)]
    pub ppu: Option<String>,

    /// Sampling interval (V3 file name), for example 30S
    #[arg(long)]
    pub ffu: Option<String>,

    /// Compress observations to CRINEX
    #[arg(long)]
    pub rnx2crx: bool,

    /// Decompress CRINEX observations to readable RINEX
    #[arg(long)]
    pub crx2rnx: bool,
}

#[derive(Debug, Args)]
pub struct FilegenArgs {
    #[command(flatten)]
    pub production: ProductionArgs,
}

#[derive(Debug, Args)]
pub struct MergeArgs {
    /// File to merge
    pub file: PathBuf,

    #[command(flatten)]
    pub production: ProductionArgs,
}

#[derive(Debug, Args)]
pub struct SplitArgs {
    /// Split epoch, for example "2020-06-25T12:00:00 GPST"
    pub epoch: Epoch,

    #[command(flatten)]
    pub production: ProductionArgs,
}

#[derive(Debug, Args)]
pub struct TbinArgs {
    /// Batch duration, for example "1 hour" or "15 min"
    pub duration: gnss_qc::prelude::Duration,

    #[command(flatten)]
    pub production: ProductionArgs,
}

#[derive(Debug, Args)]
pub struct CbinArgs {
    /// Express each file in the timescale of its constellation
    #[arg(long)]
    pub timescale: bool,

    #[command(flatten)]
    pub production: ProductionArgs,
}

#[derive(Debug, Args)]
pub struct DiffArgs {
    /// Observation RINEX (B)
    pub file: PathBuf,

    #[command(flatten)]
    pub production: ProductionArgs,
}

#[derive(Debug, Args)]
pub struct IndexArgs {
    /// Prints the index as JSON
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Args)]
pub struct QcArgs {
    /// Do not analyze the ephemeris coverage of the signal sources
    #[arg(long)]
    pub no_coverage: bool,
}

/// Navigation method
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum MethodArg {
    /// Single frequency code
    Spp,
    /// Dual frequency code (iono free)
    Cpp,
    /// Dual frequency code and phase (iono free)
    Ppp,
}

/// Orbital products preference
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum OrbitsArg {
    /// Precise products (SP3) whenever they cover the satellite, broadcast otherwise
    Auto,
    /// Precise products only
    Precise,
    /// Broadcast ephemerides only
    Broadcast,
}

impl OrbitsArg {
    /// GNSS-Qc preference
    #[cfg_attr(not(any(feature = "navigation", feature = "ionex")), allow(dead_code))]
    pub fn to_preference(self) -> gnss_qc::prelude::QcOrbitPreference {
        use gnss_qc::prelude::QcOrbitPreference;
        match self {
            Self::Auto => QcOrbitPreference::Auto,
            Self::Precise => QcOrbitPreference::PreciseOnly,
            Self::Broadcast => QcOrbitPreference::BroadcastOnly,
        }
    }
}

/// User (rover) profile
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum ProfileArg {
    Static,
    Pedestrian,
    Car,
    Airplane,
    Rocket,
}

/// Receiver clock profile
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum ClockArg {
    Quartz,
    Oscillator,
    Atomic,
    HydrogenMaser,
}

/// Options shared by the navigation commands
#[derive(Debug, Args)]
#[command(next_help_heading = "Navigation")]
pub struct NavigationArgs {
    /// Navigation method. Default: cpp (or the configuration file).
    #[arg(short, long, value_enum)]
    pub method: Option<MethodArg>,

    /// Signal source to navigate (identity, as listed by the index command).
    /// Default: the first signal source.
    #[arg(long, value_name = "PRODUCT")]
    pub rover: Option<String>,

    /// Constellations, comma separated (gps,gal,bds,qzss). Default: GPS, Galileo.
    #[arg(short, long, value_delimiter = ',')]
    pub constellations: Vec<String>,

    /// Orbital products preference
    #[arg(long, value_enum)]
    pub orbits: Option<OrbitsArg>,

    /// User profile. Default: pedestrian (or the configuration file).
    #[arg(long, value_enum)]
    pub profile: Option<ProfileArg>,

    /// Static receiver (shortcut for --profile static)
    #[arg(long = "static")]
    pub is_static: bool,

    /// Receiver clock profile. Default: quartz (or the configuration file).
    #[arg(long, value_enum)]
    pub clock: Option<ClockArg>,

    /// A priori position: "x,y,z" ECEF (m), or "header" (RINEX header of the rover).
    /// Default: none, the solver surveys from scratch.
    #[arg(long, value_name = "x,y,z|header")]
    pub apriori: Option<String>,

    /// Reference position to express the errors: "x,y,z" ECEF (m).
    /// Default: the RINEX header of the rover.
    #[arg(long, value_name = "x,y,z")]
    pub reference: Option<String>,

    /// Navigation configuration (QcNavigationConfig) as JSON file.
    /// Command line options take precedence.
    #[arg(long = "cfg", value_name = "JSON")]
    pub cfg: Option<PathBuf>,

    /// Folder of the ANISE dataset (de440s.bsp and pck11.pca).
    /// Default: embedded dataset (embed_ephem feature), downloaded otherwise.
    #[arg(long, value_name = "DIR", env = "GNSS_QC_ANISE_DIR")]
    pub anise_dir: Option<PathBuf>,
}

#[derive(Debug, Args)]
pub struct NavArgs {
    #[command(flatten)]
    pub navigation: NavigationArgs,

    /// Differential navigation (RTK) relative to this signal source
    #[arg(long, value_name = "PRODUCT")]
    pub base: Option<String>,

    /// Position of the RTK base, "x,y,z" ECEF (m). Default: its RINEX header.
    #[arg(long, value_name = "x,y,z")]
    pub base_position: Option<String>,

    /// Do not analyze the signal combinations (Geometry Free, Ionosphere Free,
    /// code multipath) of the rover (and base) in the navigation report
    #[arg(long)]
    pub no_combinations: bool,

    /// Also format the solutions as a GPX track
    #[arg(long)]
    pub gpx: bool,

    /// Also format the solutions as a KML track
    #[arg(long)]
    pub kml: bool,
}

#[derive(Debug, Args)]
pub struct CggttsArgs {
    #[command(flatten)]
    pub navigation: NavigationArgs,

    /// Station name, written in the CGGTTS header. Default: marker name.
    #[arg(long)]
    pub station: Option<String>,

    /// Reference frame of the antenna coordinates, written in the CGGTTS header
    #[arg(long, default_value = "ITRF")]
    pub frame: String,

    /// Minimal track duration (s): shorter tracks are discarded
    #[arg(long, default_value_t = 720.0)]
    pub min_track: f64,

    /// Also stream (and report) the P.V.T solutions
    #[arg(long)]
    pub solutions: bool,

    /// Do not analyze the signal combinations (Geometry Free, Ionosphere Free,
    /// code multipath) of the receiver in the CGGTTS report
    #[arg(long)]
    pub no_combinations: bool,
}

#[derive(Debug, Args)]
pub struct ResidualsArgs {
    #[command(subcommand)]
    pub kind: ResidualsKind,
}

#[derive(Debug, Subcommand)]
pub enum ResidualsKind {
    /// Observation residuals: receiver A − receiver B (same satellite, same observable)
    Obs(ObsResidualsArgs),

    /// Orbit residuals: product A − product B (radial, along track, cross track, clock)
    Orbit(OrbitResidualsArgs),

    /// Clock residuals: clock product A − clock product B (Clock RINEX, SP3, NAV),
    /// for example two analysis centers
    Clock(ClockResidualsArgs),
}

/// Clock datum alignment
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum AlignmentArg {
    /// Raw residuals only
    None,
    /// One datum per epoch
    Epoch,
    /// One datum per epoch and per constellation
    Constellation,
}

#[derive(Debug, Args)]
pub struct ClockResidualsArgs {
    /// Product A: clk, clk:PRODUCT, sp3, sp3:PRODUCT, nav, nav:PRODUCT
    #[arg(long, default_value = "clk")]
    pub lhs: String,

    /// Product B: clk, clk:PRODUCT, sp3, sp3:PRODUCT, nav, nav:PRODUCT
    #[arg(long, default_value = "sp3")]
    pub rhs: String,

    /// Minimal interval between two evaluations (s)
    #[arg(long)]
    pub sampling: Option<f64>,

    /// Clock datum of each product: estimated per epoch and constellation (default),
    /// per epoch, or not estimated
    #[arg(long, value_enum, default_value = "constellation")]
    pub alignment: AlignmentArg,

    /// Satellite clocks only
    #[arg(long, conflicts_with = "stations_only")]
    pub satellites_only: bool,

    /// Ground station clocks only
    #[arg(long)]
    pub stations_only: bool,

    /// Constellations, comma separated. Default: all.
    #[arg(short, long, value_delimiter = ',')]
    pub constellations: Vec<String>,
}

#[derive(Debug, Args)]
pub struct CombinationsArgs {
    /// Geometry Free combinations (phase: Lj − L1, code: C1 − Cj).
    /// When none of --gf, --if, --mp is selected: all of them.
    #[arg(long)]
    pub gf: bool,

    /// Ionosphere Free combinations: (f1² X1 − fj² Xj) / (f1² − fj²)
    #[arg(long = "if")]
    pub iono_free: bool,

    /// Code multipath: MPi = Ci − Li − 2 (Li − Lj) / (αij − 1)
    #[arg(long)]
    pub mp: bool,

    /// GF and IF: combine the pseudo ranges only
    #[arg(long, conflicts_with = "phase_only")]
    pub code_only: bool,

    /// GF and IF: combine the phase ranges only
    #[arg(long)]
    pub phase_only: bool,

    /// Constellations, comma separated. Default: all (Glonass excluded: FDMA).
    #[arg(short, long, value_delimiter = ',')]
    pub constellations: Vec<String>,

    /// Signal sources to analyze (identity or alias), comma separated. Default: all.
    #[arg(long, value_delimiter = ',')]
    pub receivers: Vec<String>,

    /// Multipath: a data gap longer than this (s) ends the phase arc
    #[arg(long, default_value_t = 600.0)]
    pub max_gap: f64,

    /// Multipath: a jump larger than this (m) ends the phase arc (cycle slip)
    #[arg(long, default_value_t = 5.0)]
    pub jump: f64,
}

#[derive(Debug, Args)]
pub struct MeteoArgs {
    /// Observables to analyze, comma separated (PR, TD, HR, ZW, ZD, ZT, WD, WS, RI, HI).
    /// Default: all of them.
    #[arg(long, value_delimiter = ',')]
    pub observables: Vec<String>,
}

/// TEC maps temporal interpolation
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum InterpolationArg {
    /// Nearest map in time
    Nearest,
    /// Linear interpolation of the surrounding maps
    Linear,
    /// Linear interpolation of the surrounding maps rotated with the Sun (IONEX specifications)
    Rotated,
}

#[derive(Debug, Args)]
pub struct TecArgs {
    /// Increases the number of maps by this factor (2: twice as many maps),
    /// intermediate maps being interpolated in time
    #[arg(long, value_name = "FACTOR", conflicts_with = "resample")]
    pub upsample: Option<f64>,

    /// One map every period (for example "15 min"), maps being interpolated in time
    #[arg(long, value_name = "PERIOD")]
    pub resample: Option<gnss_qc::prelude::Duration>,

    /// Temporal interpolation strategy
    #[arg(long, value_enum, default_value = "rotated")]
    pub interpolation: InterpolationArg,

    /// Additional region of the statistics: "NAME:LAT_MIN,LAT_MAX,LON_MIN,LON_MAX"
    /// (degrees), for example "Europe:35,70,-10,30". Repeat as needed.
    #[arg(long, value_name = "NAME:LAT0,LAT1,LON0,LON1")]
    pub region: Vec<String>,

    /// Do not synthesize the IONEX file of the (resampled) maps
    #[arg(long)]
    pub no_ionex: bool,

    /// Gzip compressed IONEX output
    #[arg(long)]
    pub gzip: bool,
}

#[derive(Debug, Args)]
pub struct ObsResidualsArgs {
    /// Receiver A (minuend). Default: the first signal source.
    #[arg(long, value_name = "PRODUCT")]
    pub lhs: Option<String>,

    /// Receiver B (subtrahend). Default: the other signal source.
    #[arg(long, value_name = "PRODUCT")]
    pub rhs: Option<String>,

    /// Differentiate Doppler shifts and signal strengths too
    #[arg(long)]
    pub all: bool,

    /// Maximal time difference between the epochs of both receivers (s)
    #[arg(long)]
    pub tolerance: Option<f64>,
}

#[derive(Debug, Args)]
pub struct OrbitResidualsArgs {
    /// Product A: sp3, sp3:PRODUCT, nav, nav:PRODUCT
    #[arg(long, default_value = "nav")]
    pub lhs: String,

    /// Product B: sp3, sp3:PRODUCT, nav, nav:PRODUCT
    #[arg(long, default_value = "sp3")]
    pub rhs: String,

    /// Minimal interval between two evaluations (s)
    #[arg(long)]
    pub sampling: Option<f64>,

    /// Broadcast ephemerides: maximal distance to their time of clock (s)
    #[arg(long)]
    pub max_age: Option<f64>,

    /// Constellations, comma separated. Default: all.
    #[arg(short, long, value_delimiter = ',')]
    pub constellations: Vec<String>,
}

#[derive(Debug, Args)]
pub struct IppArgs {
    /// Elevation mask (degrees)
    #[arg(long, default_value_t = 10.0)]
    pub elevation_mask: f64,

    /// Altitude of the ionospheric shell (km)
    #[arg(long, default_value_t = 450.0)]
    pub shell_altitude: f64,

    /// Orbital products preference
    #[arg(long, value_enum, default_value = "auto")]
    pub orbits: OrbitsArg,

    /// Constellations, comma separated. Default: all.
    #[arg(short, long, value_delimiter = ',')]
    pub constellations: Vec<String>,
}

/// Parses a duration: "30 s", "30s", "1 min", or a number of seconds ("30")
pub fn parse_duration(text: &str) -> Result<gnss_qc::prelude::Duration, String> {
    use gnss_qc::prelude::Duration;
    let text = text.trim();
    if let Ok(seconds) = f64::from_str(text) {
        return Ok(Duration::from_seconds(seconds));
    }
    if let Ok(duration) = Duration::from_str(text) {
        return Ok(duration);
    }
    // unit glued to the value: "30s", "15min"
    let split = text
        .find(|c: char| c.is_ascii_alphabetic())
        .ok_or(format!("invalid duration \"{}\"", text))?;
    let (value, unit) = text.split_at(split);
    Duration::from_str(&format!("{} {}", value.trim(), unit))
        .map_err(|e| format!("invalid duration \"{}\": {}", text, e))
}

/// Parses "x,y,z" coordinates
#[cfg_attr(not(feature = "navigation"), allow(dead_code))]
pub fn parse_coordinates(text: &str) -> Result<(f64, f64, f64), Error> {
    let values = text
        .split(',')
        .map(|v| f64::from_str(v.trim()))
        .collect::<Result<Vec<_>, _>>()
        .map_err(|_| Error::InvalidCoordinates(text.to_string()))?;

    match values.as_slice() {
        [x, y, z] => Ok((*x, *y, *z)),
        _ => Err(Error::InvalidCoordinates(text.to_string())),
    }
}

/// Parses a TEC region: "NAME:LAT_MIN,LAT_MAX,LON_MIN,LON_MAX"
#[cfg_attr(not(feature = "ionex"), allow(dead_code))]
pub fn parse_region(text: &str) -> Result<gnss_qc::prelude::QcTecRegion, Error> {
    let invalid = || {
        Error::Config(format!(
            "invalid region \"{}\": NAME:LAT_MIN,LAT_MAX,LON_MIN,LON_MAX",
            text
        ))
    };

    let (name, bounds) = text.split_once(':').ok_or_else(invalid)?;

    let values = bounds
        .split(',')
        .map(|v| f64::from_str(v.trim()))
        .collect::<Result<Vec<_>, _>>()
        .map_err(|_| invalid())?;

    match values.as_slice() {
        [lat0, lat1, lon0, lon1] if !name.trim().is_empty() => Ok(
            gnss_qc::prelude::QcTecRegion::new(name.trim(), (*lat0, *lat1), (*lon0, *lon1)),
        ),
        _ => Err(invalid()),
    }
}

/// Parses a list of constellations
pub fn parse_constellations(
    list: &[String],
) -> Result<Vec<gnss_qc::prelude::Constellation>, Error> {
    list.iter()
        .map(|c| {
            gnss_qc::prelude::Constellation::from_str(c.trim())
                .map_err(|_| Error::Config(format!("unknown constellation \"{}\"", c)))
        })
        .collect()
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn indexing_methods() {
        for (text, expected) in [
            ("auto", IndexingMethod::Auto),
            (
                "receiver",
                IndexingMethod::Preset(QcIndexingConfig::Receiver),
            ),
            ("Agency", IndexingMethod::Preset(QcIndexingConfig::Agency)),
            (
                "filename",
                IndexingMethod::Preset(QcIndexingConfig::FileName),
            ),
            (
                "alias:BRDC",
                IndexingMethod::Preset(QcIndexingConfig::Custom("BRDC".to_string())),
            ),
        ] {
            assert_eq!(IndexingMethod::from_str(text).unwrap(), expected);
        }

        assert!(IndexingMethod::from_str("alias:").is_err());
        assert_eq!(parse_coordinates("1.0, -2.5,3").unwrap(), (1.0, -2.5, 3.0));
        assert!(parse_coordinates("1,2").is_err());
        for text in ["30 s", "30s", "30", " 0.5 min"] {
            assert_eq!(
                parse_duration(text).unwrap(),
                gnss_qc::prelude::Duration::from_seconds(30.0),
                "{}",
                text
            );
        }
        assert!(parse_duration("abc").is_err());
        assert_eq!(
            parse_constellations(&["gps".to_string(), "Gal".to_string()])
                .unwrap()
                .len(),
            2
        );
        assert!(IndexingMethod::from_str("unknown").is_err());

        let europe = parse_region("Europe:35,70,-10,30").unwrap();
        assert_eq!(europe.name, "Europe");
        assert_eq!(europe.latitude_deg, (35.0, 70.0));
        assert_eq!(europe.longitude_deg, (-10.0, 30.0));
        assert!(parse_region("Europe:35,70").is_err());
        assert!(parse_region(":35,70,0,1").is_err());
    }

    #[test]
    fn cli_is_consistent() {
        use clap::CommandFactory;
        Cli::command().debug_assert();
    }
}