ridal 0.5.1

Speeding up Ground Penetrating Radar (GPR) processing
Documentation
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
use crate::{formats, gpr, tools, user_metadata};
use clap::{ArgGroup, Parser, Subcommand};
use std::collections::BTreeMap;
use std::path::PathBuf;

#[derive(Debug, Parser)]
#[command(author, version, about, long_about = None)]
pub struct Args {
    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Debug, Subcommand)]
pub enum Commands {
    /// Process one or more GPR profiles into one final output
    Process(ProcessArgs),
    /// Batch-process one or more GPR profiles into many outputs
    BatchProcess(BatchProcessArgs),
    /// Show metadata/location information for one or more GPR profiles
    Info(InfoArgs),
    /// Inspect available processing steps
    Steps(StepsArgs),
    /// Inspect supported formats
    Formats(FormatsArgs),
}

#[derive(Debug, clap::Args)]
#[command(group(
    ArgGroup::new("step_choice")
        .required(false)
        .args(["steps", "default", "default_with_topo"]),
))]
pub struct ProcessArgs {
    /// Input header/data path(s). Explicit paths are preferred, but glob patterns are also expanded.
    #[arg(required = true)]
    pub inputs: Vec<PathBuf>,

    /// Velocity of the medium in m/ns. Defaults to the typical velocity of ice.
    #[arg(short, long, default_value = "0.168")]
    pub velocity: f32,

    /// Load a separate ".cor" file (RAMAC only). If not given, it will be searched for automatically.
    #[arg(short, long)]
    pub cor: Option<PathBuf>,

    /// Correct elevation values with a DEM
    #[arg(short, long)]
    pub dem: Option<PathBuf>,

    /// Which coordinate reference system to project coordinates in.
    #[arg(long)]
    pub crs: Option<String>,

    /// Export the location track to CSV. If no value is given, a sidecar path is derived from the output path.
    #[arg(short, long)]
    pub track: Option<Option<PathBuf>>,

    /// Process with the default profile.
    #[arg(long)]
    pub default: bool,

    /// Process with the default profile plus topographic correction.
    #[arg(long = "default-with-topo")]
    pub default_with_topo: bool,

    /// Processing steps to run, separated by commas. Can also be a filepath to a newline-separated step file.
    #[arg(long)]
    pub steps: Option<String>,

    /// Output filename or directory. Defaults to the first input with a ".nc" extension.
    #[arg(short, long)]
    pub output: Option<PathBuf>,

    /// Suppress progress messages
    #[arg(short, long)]
    pub quiet: bool,

    /// Render an image of the profile and save it to the specified path. If no path is given, a JPG sidecar is used.
    #[arg(short, long)]
    pub render: Option<Option<PathBuf>>,

    /// Don't export an nc file
    #[arg(long)]
    pub no_export: bool,

    /// Override the antenna center frequency (in MHz) from file metadata
    #[arg(long)]
    pub override_antenna_mhz: Option<f32>,

    /// Add user metadata as key=value. Repeatable.
    #[arg(long = "metadata", value_name = "KEY=VALUE", action = clap::ArgAction::Append)]
    pub metadata: Vec<String>,
}

#[derive(Debug, clap::Args)]
#[command(group(
    ArgGroup::new("step_choice")
        .required(false)
        .args(["steps", "default", "default_with_topo"]),
))]
pub struct BatchProcessArgs {
    /// Input header/data path(s). Explicit paths are preferred, but glob patterns are also expanded.
    #[arg(required = true)]
    pub inputs: Vec<PathBuf>,

    /// Output directory. Must already exist.
    #[arg(short, long, required = true)]
    pub output: PathBuf,

    /// Velocity of the medium in m/ns. Defaults to the typical velocity of ice.
    #[arg(short, long, default_value = "0.168")]
    pub velocity: f32,

    /// Load a separate ".cor" file (RAMAC only). If not given, it will be searched for automatically.
    #[arg(short, long)]
    pub cor: Option<PathBuf>,

    /// Correct elevation values with a DEM
    #[arg(short, long)]
    pub dem: Option<PathBuf>,

    /// Which coordinate reference system to project coordinates in.
    #[arg(long)]
    pub crs: Option<String>,

    /// Export location tracks to CSV in the given directory.
    #[arg(short, long)]
    pub track: Option<Option<PathBuf>>,

    /// Process with the default profile.
    #[arg(long)]
    pub default: bool,

    /// Process with the default profile plus topographic correction.
    #[arg(long = "default-with-topo")]
    pub default_with_topo: bool,

    /// Processing steps to run, separated by commas. Can also be a filepath to a newline-separated step file.
    #[arg(long)]
    pub steps: Option<String>,

    /// Suppress progress messages
    #[arg(short, long)]
    pub quiet: bool,

    /// Render images into the given directory.
    #[arg(short, long)]
    pub render: Option<Option<PathBuf>>,

    /// Don't export nc files
    #[arg(long)]
    pub no_export: bool,

    /// Merge neighboring chronological profiles that are closer than the given threshold
    /// (e.g. "10 min"). Incompatible neighbors remain separate outputs.
    #[arg(long)]
    pub merge: Option<String>,

    /// Override the antenna center frequency (in MHz) from file metadata
    #[arg(long)]
    pub override_antenna_mhz: Option<f32>,

    /// Add user metadata as key=value. Repeatable.
    #[arg(long = "metadata", value_name = "KEY=VALUE", action = clap::ArgAction::Append)]
    pub metadata: Vec<String>,
}

#[derive(Debug, clap::Args)]
pub struct InfoArgs {
    /// Input header/data path(s). Explicit paths are preferred, but glob patterns are also expanded.
    #[arg(required = true)]
    pub inputs: Vec<PathBuf>,

    /// Emit JSON instead of human-readable text
    #[arg(long)]
    pub json: bool,

    /// Velocity of the medium in m/ns. Defaults to the typical velocity of ice.
    #[arg(short, long, default_value = "0.168")]
    pub velocity: f32,

    /// Load a separate ".cor" file (RAMAC only). If not given, it will be searched for automatically.
    #[arg(short, long)]
    pub cor: Option<PathBuf>,

    /// Correct elevation values with a DEM
    #[arg(short, long)]
    pub dem: Option<PathBuf>,

    /// Which coordinate reference system to project coordinates in.
    #[arg(long)]
    pub crs: Option<String>,

    /// Override the antenna center frequency (in MHz) from file metadata
    #[arg(long)]
    pub override_antenna_mhz: Option<f32>,
}

#[derive(Debug, clap::Args)]
#[command(group(
    ArgGroup::new("steps_mode")
        .required(false)
        .args(["describe_all", "describe", "default"]),
))]
pub struct StepsArgs {
    /// Show descriptions for all steps
    #[arg(long = "describe-all")]
    pub describe_all: bool,

    /// Show the description for one step
    #[arg(long)]
    pub describe: Option<String>,

    /// Show the default processing pipeline
    #[arg(long)]
    pub default: bool,

    /// Emit JSON instead of human-readable text
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, clap::Args)]
pub struct FormatsArgs {
    /// Emit JSON instead of human-readable text
    #[arg(long)]
    pub json: bool,
}

fn resolve_steps(
    default: bool,
    default_with_topo: bool,
    steps: Option<&str>,
) -> Result<Vec<String>, String> {
    let resolved_steps = if default_with_topo {
        let mut profile = gpr::default_processing_profile();
        profile.push("correct_topography".to_string());
        profile
    } else if default {
        gpr::default_processing_profile()
    } else if let Some(step_text) = steps {
        tools::parse_step_list(step_text)?
    } else {
        vec![]
    };

    gpr::validate_steps(&resolved_steps)?;
    Ok(resolved_steps)
}

fn optional_existing_dir(
    value: &Option<Option<PathBuf>>,
    label: &str,
) -> Result<Option<PathBuf>, String> {
    match value {
        None => Ok(None),
        Some(None) => Ok(None),
        Some(Some(path)) => {
            if !path.is_dir() {
                Err(format!(
                    "{label} must be an existing directory in batch mode: {}",
                    path.display()
                ))
            } else {
                Ok(Some(path.clone()))
            }
        }
    }
}

#[cfg(feature = "cli")]
#[allow(dead_code)]
pub fn main(arguments: Args) -> i32 {
    match run(arguments) {
        Ok(()) => 0,
        Err(message) => error(&message, 1),
    }
}

pub fn run(arguments: Args) -> Result<(), String> {
    match arguments.command {
        Commands::Process(args) => process_command(&args),
        Commands::BatchProcess(args) => batch_process_command(&args),
        Commands::Info(args) => info_command(args),
        Commands::Steps(args) => steps_command(args),
        Commands::Formats(args) => formats_command(args),
    }
}

fn process_command(args: &ProcessArgs) -> Result<(), String> {
    let resolved_steps =
        resolve_steps(args.default, args.default_with_topo, args.steps.as_deref())?;
    let user_metadata = user_metadata::parse_cli_metadata(&args.metadata)?;

    let params = gpr::RunParams {
        filepaths: args.inputs.clone(),
        output_path: args.output.clone(),
        dem_path: args.dem.clone(),
        cor_path: args.cor.clone(),
        medium_velocity: args.velocity,
        crs: args.crs.clone(),
        quiet: args.quiet,
        track_path: args.track.clone(),
        steps: resolved_steps,
        no_export: args.no_export,
        render_path: args.render.clone(),
        override_antenna_mhz: args.override_antenna_mhz,
        user_metadata,
    };

    let result = gpr::run(params).map_err(|e| e.to_string())?;
    if !args.quiet {
        println!("{}", result.output_path.display());
    }
    Ok(())
}
fn batch_process_command(args: &BatchProcessArgs) -> Result<(), String> {
    if !args.output.is_dir() {
        return Err(format!(
            "output must be an existing directory in batch mode: {}",
            args.output.display()
        ));
    }

    let render_dir = optional_existing_dir(&args.render, "render")?;
    let track_dir = optional_existing_dir(&args.track, "track")?;

    let resolved_steps =
        resolve_steps(args.default, args.default_with_topo, args.steps.as_deref())?;
    let user_metadata = user_metadata::parse_cli_metadata(&args.metadata)?;

    let params = gpr::BatchRunParams {
        filepaths: args.inputs.clone(),
        output_dir: args.output.clone(),
        dem_path: args.dem.clone(),
        cor_path: args.cor.clone(),
        medium_velocity: args.velocity,
        crs: args.crs.clone(),
        quiet: args.quiet,
        track_dir,
        steps: resolved_steps,
        no_export: args.no_export,
        render_dir,
        merge: args.merge.clone(),
        override_antenna_mhz: args.override_antenna_mhz,
        user_metadata,
    };

    let result = gpr::run_batch(params)?;
    if !args.quiet {
        for path in result.output_paths {
            println!("{}", path.display());
        }
    }
    Ok(())
}
fn info_command(args: InfoArgs) -> Result<(), String> {
    let params = gpr::InfoParams {
        filepaths: args.inputs,
        dem_path: args.dem,
        cor_path: args.cor,
        medium_velocity: args.velocity,
        crs: args.crs,
        override_antenna_mhz: args.override_antenna_mhz,
    };
    let records = gpr::inspect(params).map_err(|e| format!("{e:?}"))?;
    if args.json {
        if records.len() == 1 {
            println!(
                "{}",
                serde_json::to_string_pretty(&records[0]).map_err(|e| e.to_string())?
            );
        } else {
            println!(
                "{}",
                serde_json::to_string_pretty(&records).map_err(|e| e.to_string())?
            );
        }
    } else {
        for (i, record) in records.iter().enumerate() {
            if i > 0 {
                println!();
            }
            print_info_record(record);
        }
    }
    Ok(())
}

fn steps_command(args: StepsArgs) -> Result<(), String> {
    let all_steps = gpr::all_available_steps();
    if args.json {
        if args.default {
            println!(
                "{}",
                serde_json::to_string_pretty(&gpr::default_processing_profile())
                    .map_err(|e| e.to_string())?
            );
            return Ok(());
        }
        if let Some(step_name) = args.describe {
            let mapping = step_mapping(Some(step_name), &all_steps)?;
            println!(
                "{}",
                serde_json::to_string_pretty(&mapping).map_err(|e| e.to_string())?
            );
            return Ok(());
        }
        if args.describe_all {
            let mapping = step_mapping(None, &all_steps)?;
            println!(
                "{}",
                serde_json::to_string_pretty(&mapping).map_err(|e| e.to_string())?
            );
            return Ok(());
        }
        let names = all_steps
            .into_iter()
            .map(|(name, _)| name)
            .collect::<Vec<String>>();
        println!(
            "{}",
            serde_json::to_string_pretty(&names).map_err(|e| e.to_string())?
        );
        return Ok(());
    }

    if args.default {
        for step in gpr::default_processing_profile() {
            println!("{step}");
        }
        return Ok(());
    }
    if let Some(step_name) = args.describe {
        let mapping = step_mapping(Some(step_name), &all_steps)?;
        for (name, description) in mapping {
            println!("{name}\n{}\n{description}\n", "-".repeat(name.len()));
        }
        return Ok(());
    }
    if args.describe_all {
        for (name, description) in all_steps {
            println!("{name}\n{}\n{description}\n", "-".repeat(name.len()));
        }
        return Ok(());
    }

    for (name, _) in all_steps {
        println!("{name}");
    }
    Ok(())
}

fn formats_command(args: FormatsArgs) -> Result<(), String> {
    let all_formats = formats::all_formats();
    if args.json {
        let payload = serde_json::json!({ "formats": all_formats });
        println!(
            "{}",
            serde_json::to_string_pretty(&payload).map_err(|e| e.to_string())?
        );
        return Ok(());
    }

    for fmt in all_formats {
        println!("{}", fmt.name);
        println!("{}", "-".repeat(fmt.name.len()));
        println!("{}", fmt.description);
        println!("Read:  {}", fmt.capabilities.read);
        println!("Write: {}", fmt.capabilities.write);
        println!(
            "Files:  header={} data={} coordinates={}",
            fmt.files.header, fmt.files.data, fmt.files.coordinates
        );
        println!();
    }
    Ok(())
}

// TODO: Might not be used anywhere (2026-03-28)
#[allow(dead_code)]
fn choose_steps(
    default: bool,
    default_with_topo: bool,
    steps: Option<&str>,
) -> Result<Vec<String>, String> {
    if default_with_topo {
        let mut profile = gpr::default_processing_profile();
        profile.push("correct_topography".to_string());
        return Ok(profile);
    }
    if default {
        return Ok(gpr::default_processing_profile());
    }
    match steps {
        Some(step_text) => tools::parse_step_list(step_text),
        None => Ok(vec![]),
    }
}

fn step_mapping(
    only_name: Option<String>,
    all_steps: &[(String, String)],
) -> Result<BTreeMap<String, String>, String> {
    let mut out = BTreeMap::<String, String>::new();
    for (name, description) in all_steps {
        if let Some(target) = &only_name {
            if name != target {
                continue;
            }
        }
        out.insert(name.clone(), description.clone());
    }
    if let Some(target) = only_name {
        if out.is_empty() {
            return Err(format!("Unknown step: {target}"));
        }
    }
    Ok(out)
}

fn print_info_record(record: &gpr::InfoRecord) {
    println!("Input:\t\t{}", record.input);
    println!(
        "Format:\t\t{} ({})",
        record.format.name, record.format.description
    );
    println!("Header:\t\t{}", record.related_files.header);
    println!("Data:\t\t{}", record.related_files.data);
    println!("Coordinates:\t{}", record.related_files.coordinates);
    println!();
    println!("Metadata");
    println!("--------");
    println!("Samples:\t{}", record.metadata.samples);
    println!("Traces:\t\t{}", record.metadata.last_trace);
    println!("Time window:\t{} ns", record.metadata.time_window_ns);
    println!(
        "Velocity:\t{} m/ns",
        record.metadata.medium_velocity_m_per_ns
    );
    println!(
        "Sampling freq:\t{} MHz",
        record.metadata.sampling_frequency_mhz
    );
    println!("Antenna:\t{}", record.metadata.antenna_name);
    println!("Antenna MHz:\t{}", record.metadata.antenna_mhz);
    println!("Antenna sep:\t{} m", record.metadata.antenna_separation_m);
    println!();
    println!("Location");
    println!("--------");
    println!("Points:\t\t{}", record.location.n_points);
    println!("CRS:\t\t{}", record.location.crs);
    println!("Start:\t\t{}", record.location.start_time);
    println!("Stop:\t\t{}", record.location.stop_time);
    println!("Duration:\t{:.3} s", record.location.duration_s);
    println!("Track length:\t{:.3} m", record.location.track_length_m);
    println!(
        "Altitude:\t{:.3} - {:.3} m",
        record.location.altitude_min_m, record.location.altitude_max_m
    );
    println!(
        "Centroid:\tE {:.3}, N {:.3}, Z {:.3}",
        record.location.centroid.easting,
        record.location.centroid.northing,
        record.location.centroid.altitude
    );
    println!(
        "Correction:\t{}{}",
        record.location.correction.kind,
        record
            .location
            .correction
            .source
            .as_ref()
            .map(|s| format!(" ({s})"))
            .unwrap_or_default()
    );
}

#[cfg(feature = "cli")]
#[allow(dead_code)]
fn error(message: &str, code: i32) -> i32 {
    eprintln!("{message}");
    code
}

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

    #[test]
    fn test_parse_process_command() {
        let args = Args::parse_from([
            "ridal",
            "process",
            "a.rad",
            "b.rad",
            "--default",
            "-o",
            "out.nc",
        ]);
        match args.command {
            Commands::Process(process) => {
                assert_eq!(
                    process.inputs,
                    vec![PathBuf::from("a.rad"), PathBuf::from("b.rad")]
                );
                assert!(process.default);
                assert_eq!(process.output, Some(PathBuf::from("out.nc")));
            }
            _ => panic!("Expected process command"),
        }
    }

    #[test]
    fn test_parse_info_command() {
        let args = Args::parse_from(["ridal", "info", "line01.rad", "--json"]);
        match args.command {
            Commands::Info(info) => {
                assert_eq!(info.inputs, vec![PathBuf::from("line01.rad")]);
                assert!(info.json);
            }
            _ => panic!("Expected info command"),
        }
    }

    #[test]
    fn test_choose_steps_default_with_topo() {
        let steps = choose_steps(false, true, None).unwrap();
        assert!(steps.iter().any(|step| step == "correct_topography"));
    }
}