rinex-cli 0.11.1

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
use crate::cli::Context;
use crate::Error;
use clap::ArgMatches;

use std::path::PathBuf;
use std::process::Command;
use std::str::FromStr;

use rinex::{
    prelude::{Duration, Epoch, ProductType, Rinex, RinexType},
    preprocessing::*,
    prod::{DataSource, DetailedProductionAttributes, ProductionAttributes, FFU, PPU},
    Merge, Split,
};

/*
 * Parses share RINEX production attributes.
 * This helps accurate file production,
 * and also allows customization from files that did not originally follow
 * standard naming conventions
 */
fn custom_prod_attributes(rinex: &Rinex, matches: &ArgMatches) -> ProductionAttributes {
    // Start from smartly guessed attributes and replace
    // manually customized fields
    let mut opts = rinex.guess_production_attributes();
    if let Some(agency) = matches.get_one::<String>("agency") {
        opts.name = agency.to_string();
    }
    if let Some(country) = matches.get_one::<String>("country") {
        if let Some(ref mut details) = opts.details {
            details.country = country[..3].to_string();
        } else {
            let mut default = DetailedProductionAttributes::default();
            default.country = country[..3].to_string();
            opts.details = Some(default);
        }
    }
    if let Some(batch) = matches.get_one::<u8>("batch") {
        if let Some(ref mut details) = opts.details {
            details.batch = *batch;
        } else {
            let mut default = DetailedProductionAttributes::default();
            default.batch = *batch;
            opts.details = Some(default);
        }
    }
    if let Some(src) = matches.get_one::<DataSource>("source") {
        if let Some(ref mut details) = opts.details {
            details.data_src = *src;
        } else {
            let mut default = DetailedProductionAttributes::default();
            default.data_src = *src;
            opts.details = Some(default);
        }
    }
    if let Some(ppu) = matches.get_one::<PPU>("ppu") {
        if let Some(ref mut details) = opts.details {
            details.ppu = *ppu;
        } else {
            let mut default = DetailedProductionAttributes::default();
            default.ppu = *ppu;
            opts.details = Some(default);
        }
    }
    if let Some(ffu) = matches.get_one::<FFU>("ffu") {
        if let Some(ref mut details) = opts.details {
            details.ffu = Some(*ffu);
        } else {
            let mut default = DetailedProductionAttributes::default();
            default.ffu = Some(*ffu);
            opts.details = Some(default);
        }
    }
    opts
}

/*
 * Returns output filename to be generated, for this kind of Product
 * TODO: some customization might impact the Header section
 *       that we should slightly rework, to be 100% correct
 */
fn output_filename(rinex: &Rinex, matches: &ArgMatches, prod: ProductionAttributes) -> String {
    // Parse possible custom opts
    let short = matches.get_flag("short");
    let gzip = if matches.get_flag("gzip") {
        Some(".gz")
    } else {
        None
    };

    debug!("{:?}", prod);

    // Use smart determination
    rinex.standard_filename(short, gzip, Some(prod))
}

/*
 * Dumps current context (usually preprocessed)
 * into RINEX format maintaining consistent format
 */
pub fn filegen(ctx: &Context, matches: &ArgMatches) -> Result<(), Error> {
    let ctx_data = &ctx.data;

    for product in [
        ProductType::Observation,
        ProductType::MeteoObservation,
        ProductType::BroadcastNavigation,
        ProductType::HighPrecisionClock,
        ProductType::Ionex,
        ProductType::Antex,
    ] {
        if let Some(rinex) = ctx_data.rinex(product) {
            let prod = custom_prod_attributes(rinex, matches);
            let filename = output_filename(rinex, matches, prod);

            let output_path = ctx.workspace.join(filename).to_string_lossy().to_string();

            rinex.to_file(&output_path).unwrap_or_else(|_| {
                panic!("failed to generate {} RINEX \"{}\"", product, output_path)
            });

            info!("{} RINEX \"{}\" has been generated", product, output_path);
        }
    }
    Ok(())
}

/*
 * Merges proposed (single) file and generates resulting output, into the workspace
 */
pub fn merge(ctx: &Context, matches: &ArgMatches) -> Result<(), Error> {
    let ctx_data = &ctx.data;
    let merge_path = matches.get_one::<PathBuf>("file").unwrap();

    let merge_filepath = merge_path.to_string_lossy().to_string();

    let rinex_b = Rinex::from_file(&merge_filepath)?;

    let rinex_c = match rinex_b.header.rinex_type {
        RinexType::ObservationData => {
            let rinex_a = ctx_data
                .observation()
                .ok_or(Error::MissingObservationRinex)?;
            rinex_a.merge(&rinex_b)?
        },
        RinexType::NavigationData => {
            let rinex_a = ctx_data
                .brdc_navigation()
                .ok_or(Error::MissingNavigationRinex)?;
            rinex_a.merge(&rinex_b)?
        },
        _ => unimplemented!(),
    };

    let suffix = merge_path
        .file_name()
        .expect("failed to determine output path")
        .to_string_lossy()
        .to_string();

    let output_path = ctx.workspace.join(suffix).to_string_lossy().to_string();

    rinex_c.to_file(&output_path)?;

    info!("\"{}\" has been generated", output_path);
    Ok(())
}

/*
 * Splits input files at specified Time Instant
 */
pub fn split(ctx: &Context, matches: &ArgMatches) -> Result<(), Error> {
    let ctx_data = &ctx.data;
    let split_instant = matches
        .get_one::<Epoch>("split")
        .expect("split epoch is required");

    for product in [
        ProductType::Observation,
        ProductType::MeteoObservation,
        ProductType::BroadcastNavigation,
        ProductType::HighPrecisionClock,
        ProductType::Ionex,
    ] {
        if let Some(rinex) = ctx_data.rinex(product) {
            let (rinex_a, rinex_b) = rinex
                .split(*split_instant)
                .unwrap_or_else(|e| panic!("failed to split {} RINEX: {}", product, e));

            let first_epoch = rinex_a
                .first_epoch()
                .unwrap_or_else(|| panic!("failed to determine {} file suffix", product));

            let (y, m, d, hh, mm, ss, _) = first_epoch.to_gregorian_utc();
            let file_suffix = format!(
                "{}{}{}_{}{}{}{}",
                y, m, d, hh, mm, ss, first_epoch.time_scale
            );

            let path = ctx_data
                .files(product)
                .unwrap_or_else(|| panic!("failed to determine output {} filename", product))
                .first()
                .unwrap();

            let filename = path
                .file_stem()
                .unwrap_or_else(|| panic!("failed to determine output {} filename", product))
                .to_string_lossy()
                .to_string();

            let mut extension = String::new();

            let filename = if filename.contains('.') {
                /* .crx.gz case */
                let mut iter = filename.split('.');
                let filename = iter
                    .next()
                    .expect("failed to determine output file name")
                    .to_string();
                extension.push_str(iter.next().expect("failed to determine output file name"));
                extension.push('.');
                filename
            } else {
                filename.clone()
            };

            let file_ext = path
                .extension()
                .expect("failed to determine output file name")
                .to_string_lossy()
                .to_string();

            extension.push_str(&file_ext);

            let output = ctx
                .workspace
                .join(format!("{}-{}.{}", filename, file_suffix, extension))
                .to_string_lossy()
                .to_string();

            rinex_a.to_file(&output)?;
            info!("\"{}\" has been generated", output);

            let first_epoch = rinex_b
                .first_epoch()
                .expect("failed to determine file suffix");

            let (y, m, d, hh, mm, ss, _) = first_epoch.to_gregorian_utc();
            let file_suffix = format!(
                "{}{}{}_{}{}{}{}",
                y, m, d, hh, mm, ss, first_epoch.time_scale
            );

            let path = ctx_data
                .files(product)
                .unwrap_or_else(|| panic!("failed to determine output {} filename", product))
                .first()
                .unwrap();

            let filename = path
                .file_stem()
                .expect("failed to determine output file name")
                .to_string_lossy()
                .to_string();

            let output = ctx
                .workspace
                .join(format!("{}-{}.{}", filename, file_suffix, extension))
                .to_string_lossy()
                .to_string();

            rinex_b.to_file(&output)?;
            info!("{} RINEX \"{}\" has been generated", product, output);
        }
    }
    Ok(())
}

/*
 * Time reframing: subdivde a RINEX into a batch of equal duration
 */
pub fn time_binning(ctx: &Context, matches: &ArgMatches) -> Result<(), Error> {
    let ctx_data = &ctx.data;
    let duration = matches
        .get_one::<Duration>("interval")
        .expect("duration is required");

    if *duration == Duration::ZERO {
        panic!("invalid (null) duration");
    }

    for product in [
        ProductType::Observation,
        ProductType::MeteoObservation,
        ProductType::BroadcastNavigation,
        ProductType::HighPrecisionClock,
        ProductType::Ionex,
    ] {
        // input data determination
        if let Some(rinex) = ctx_data.rinex(product) {
            // time framing determination
            let (mut first, end) = (
                rinex
                    .first_epoch()
                    .expect("failed to determine first epoch"),
                rinex.last_epoch().expect("failed to determine last epoch"),
            );

            let mut last = first + *duration;

            // production attributes: initialize Batch counter
            let mut prod = custom_prod_attributes(rinex, matches);
            if let Some(ref mut details) = prod.details {
                details.batch = 0_u8;
            } else {
                let mut details = DetailedProductionAttributes::default();
                details.batch = 0_u8;
                prod.details = Some(details);
            };

            // run time binning algorithm
            while last <= end {
                let rinex = rinex
                    .filter(Filter::from_str(&format!("< {:?}", last)).unwrap())
                    .filter(Filter::from_str(&format!(">= {:?}", first)).unwrap());

                // generate standardized name
                let filename = output_filename(&rinex, matches, prod.clone());

                let output = ctx.workspace.join(&filename).to_string_lossy().to_string();

                rinex.to_file(&output)?;
                info!("{} RINEX \"{}\" has been generated", product, output);

                first += *duration;
                last += *duration;
                if let Some(ref mut details) = prod.details {
                    details.batch += 1;
                }
            }
        }
    }
    Ok(())
}

/*
 * Substract RINEX[A]-RINEX[B]
 */
pub fn substract(ctx: &Context, matches: &ArgMatches) -> Result<(), Error> {
    let ctx_data = &ctx.data;
    let path_a = ctx_data
        .files(ProductType::Observation)
        .expect("failed to determine output file name")
        .first()
        .unwrap();

    let path_b = matches.get_one::<PathBuf>("file").unwrap();

    let path_b = path_b.to_string_lossy().to_string();
    let rinex_b = Rinex::from_file(&path_b)
        .unwrap_or_else(|_| panic!("failed to load {}: invalid RINEX", path_b));

    let rinex_c = match rinex_b.header.rinex_type {
        RinexType::ObservationData => {
            let rinex_a = ctx_data
                .observation()
                .expect("RINEX (A) - (B) requires OBS RINEX files");

            //TODO: change this to crnx2rnx_mut()
            rinex_a.crnx2rnx().substract(&rinex_b.crnx2rnx())
        },
        t => panic!("operation not feasible for {}", t),
    };

    let mut extension = String::new();

    let filename = path_a
        .file_stem()
        .expect("failed to determine output file name")
        .to_string_lossy()
        .to_string();

    if filename.contains('.') {
        /* .crx.gz case */
        let mut iter = filename.split('.');
        let _filename = iter
            .next()
            .expect("failed to determine output file name")
            .to_string();
        extension.push_str(iter.next().expect("failed to determine output file name"));
        extension.push('.');
    }

    let file_ext = path_a
        .extension()
        .expect("failed to determine output file name")
        .to_string_lossy()
        .to_string();

    extension.push_str(&file_ext);

    let fullpath = ctx
        .workspace
        .join(format!("DIFFERENCED.{}", extension))
        .to_string_lossy()
        .to_string();

    rinex_c.to_file(&fullpath)?;

    info!("OBS RINEX \"{}\" has been generated", fullpath);
    Ok(())
}

#[cfg(target_os = "linux")]
pub fn open_with_web_browser(path: &str) {
    let web_browsers = vec!["firefox", "chromium"];
    for browser in web_browsers {
        let child = Command::new(browser).args([path]).spawn();
        if child.is_ok() {
            return;
        }
    }
}

#[cfg(target_os = "macos")]
pub fn open_with_web_browser(path: &str) {
    Command::new("open")
        .args(&[path])
        .output()
        .expect("open() failed, can't open HTML content automatically");
}

#[cfg(target_os = "windows")]
pub fn open_with_web_browser(path: &str) {
    Command::new("cmd")
        .arg("/C")
        .arg(format!(r#"start {}"#, path))
        .output()
        .expect("failed to open generated HTML content");
}