surtgis 0.7.0

High-performance geospatial analysis CLI
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
//! Handler for hydrology subcommands.

use anyhow::{Context, Result};
use std::time::Instant;

use surtgis_algorithms::hydrology::{
    basin_morphometry, breach_depressions, drainage_density, fill_sinks, flow_accumulation,
    flow_accumulation_mfd, flow_direction, flow_direction_dinf, hand, hypsometric_integral,
    priority_flood, sediment_connectivity, stream_network, watershed,
    BreachParams, DrainageDensityParams,
    FillSinksParams, HandParams, MfdParams, PriorityFloodParams, SedimentConnectivityParams,
    StreamNetworkParams, WatershedParams,
};
use surtgis_algorithms::terrain::{slope, twi, SlopeParams, SlopeUnits};

use crate::commands::HydrologyCommands;
use crate::helpers::{
    done, parse_pour_points, read_dem, read_u8, write_result, write_result_i32, write_result_u8,
};
use crate::memory;

pub fn handle(algorithm: HydrologyCommands, compress: bool, mem_limit_bytes: Option<u64>) -> Result<()> {
    match algorithm {
        HydrologyCommands::FillSinks {
            input,
            output,
            min_slope,
        } => {
            let dem = read_dem(&input)?;
            let start = Instant::now();
            let result = fill_sinks(&dem, FillSinksParams { min_slope })
                .context("Failed to fill sinks")?;
            let elapsed = start.elapsed();
            write_result(&result, &output, compress)?;
            done("Fill sinks", &output, elapsed);
        }

        HydrologyCommands::FlowDirection { input, output } => {
            let dem = read_dem(&input)?;
            let start = Instant::now();
            let result =
                flow_direction(&dem).context("Failed to calculate flow direction")?;
            let elapsed = start.elapsed();
            write_result_u8(&result, &output, compress)?;
            done("Flow direction", &output, elapsed);
        }

        HydrologyCommands::FlowAccumulation { input, output } => {
            let flow_dir = read_u8(&input)?;
            let start = Instant::now();
            let result = flow_accumulation(&flow_dir)
                .context("Failed to calculate flow accumulation")?;
            let elapsed = start.elapsed();
            write_result(&result, &output, compress)?;
            done("Flow accumulation", &output, elapsed);
        }

        HydrologyCommands::Watershed {
            input,
            output,
            pour_points,
        } => {
            let points = parse_pour_points(&pour_points)?;
            if points.is_empty() {
                anyhow::bail!("At least one pour point is required");
            }
            let flow_dir = read_u8(&input)?;
            let start = Instant::now();
            let result = watershed(
                &flow_dir,
                WatershedParams {
                    pour_points: points,
                },
            )
            .context("Failed to delineate watersheds")?;
            let elapsed = start.elapsed();
            write_result_i32(&result, &output, compress)?;
            done("Watershed", &output, elapsed);
        }

        HydrologyCommands::PriorityFlood {
            input,
            output,
            epsilon,
        } => {
            let dem = read_dem(&input)?;
            let start = Instant::now();
            let result = priority_flood(&dem, PriorityFloodParams { epsilon })
                .context("Failed to run priority flood")?;
            let elapsed = start.elapsed();
            write_result(&result, &output, compress)?;
            done("Priority flood", &output, elapsed);
        }

        HydrologyCommands::Breach {
            input,
            output,
            max_depth,
            max_length,
            fill_remaining,
        } => {
            let dem = read_dem(&input)?;
            let start = Instant::now();
            let result = breach_depressions(
                &dem,
                BreachParams {
                    max_depth,
                    max_length,
                    fill_remaining,
                },
            )
            .context("Failed to breach depressions")?;
            let elapsed = start.elapsed();
            write_result(&result, &output, compress)?;
            done("Breach depressions", &output, elapsed);
        }

        HydrologyCommands::FlowDirectionDinf { input, output } => {
            let dem = read_dem(&input)?;
            let start = Instant::now();
            let result = flow_direction_dinf(&dem)
                .context("Failed to compute D-infinity flow direction")?;
            let elapsed = start.elapsed();
            write_result(&result, &output, compress)?;
            done("Flow direction (D-inf)", &output, elapsed);
        }

        HydrologyCommands::FlowAccumulationMfd {
            input,
            output,
            exponent,
        } => {
            let dem = read_dem(&input)?;
            let start = Instant::now();
            let result = flow_accumulation_mfd(&dem, MfdParams { exponent })
                .context("Failed to compute MFD accumulation")?;
            let elapsed = start.elapsed();
            write_result(&result, &output, compress)?;
            done("Flow accumulation (MFD)", &output, elapsed);
        }

        HydrologyCommands::Twi { input, output } => {
            let dem = read_dem(&input)?;
            let start = Instant::now();
            // Internal pipeline: fill -> flow_dir -> flow_acc -> slope -> twi
            let filled =
                priority_flood(&dem, PriorityFloodParams { epsilon: 0.0001 })
                    .context("Failed to fill depressions")?;
            let fdir =
                flow_direction(&filled).context("Failed to compute flow direction")?;
            let facc = flow_accumulation(&fdir)
                .context("Failed to compute flow accumulation")?;
            let slope_rad = slope(
                &filled,
                SlopeParams {
                    units: SlopeUnits::Radians,
                    z_factor: 1.0,
                },
            )
            .context("Failed to compute slope")?;
            let result = twi(&facc, &slope_rad).context("Failed to compute TWI")?;
            let elapsed = start.elapsed();
            write_result(&result, &output, compress)?;
            done("TWI", &output, elapsed);
        }

        HydrologyCommands::Hand {
            input,
            output,
            threshold,
        } => {
            let dem = read_dem(&input)?;
            let start = Instant::now();
            let filled =
                priority_flood(&dem, PriorityFloodParams { epsilon: 0.0001 })
                    .context("Failed to fill depressions")?;
            let fdir =
                flow_direction(&filled).context("Failed to compute flow direction")?;
            let facc = flow_accumulation(&fdir)
                .context("Failed to compute flow accumulation")?;
            let result = hand(
                &dem,
                &fdir,
                &facc,
                HandParams {
                    stream_threshold: threshold,
                },
            )
            .context("Failed to compute HAND")?;
            let elapsed = start.elapsed();
            write_result(&result, &output, compress)?;
            done("HAND", &output, elapsed);
        }

        HydrologyCommands::StreamNetwork {
            input,
            output,
            threshold,
        } => {
            let dem = read_dem(&input)?;
            let start = Instant::now();
            let filled =
                priority_flood(&dem, PriorityFloodParams { epsilon: 0.0001 })
                    .context("Failed to fill depressions")?;
            let fdir =
                flow_direction(&filled).context("Failed to compute flow direction")?;
            let facc = flow_accumulation(&fdir)
                .context("Failed to compute flow accumulation")?;
            let result = stream_network(&facc, StreamNetworkParams { threshold })
                .context("Failed to extract stream network")?;
            let elapsed = start.elapsed();
            write_result_u8(&result, &output, compress)?;
            done("Stream network", &output, elapsed);
        }

        HydrologyCommands::DrainageDensity { input, output, radius, cell_size } => {
            let streams = read_dem(&input)?;
            let start = Instant::now();
            let result = drainage_density(&streams, DrainageDensityParams { radius, cell_size })
                .context("Failed to compute drainage density")?;
            let elapsed = start.elapsed();
            write_result(&result, &output, compress)?;
            done("Drainage density", &output, elapsed);
        }

        HydrologyCommands::HypsometricIntegral { dem, watersheds } => {
            let dem_r = read_dem(&dem)?;
            let ws_r: surtgis_core::Raster<i32> = surtgis_core::io::read_geotiff(&watersheds, None)
                .context("Failed to read watershed raster")?;
            let start = Instant::now();
            let hi = hypsometric_integral(&dem_r, &ws_r)
                .context("Failed to compute hypsometric integral")?;
            let elapsed = start.elapsed();
            println!("{:<12} {:>10}", "Watershed", "HI");
            println!("{}", "-".repeat(24));
            let mut sorted: Vec<_> = hi.iter().collect();
            sorted.sort_by_key(|&(&k, _)| k);
            for &(&id, &val) in &sorted {
                println!("{:<12} {:>10.4}", id, val);
            }
            println!("\n  Processing time: {:.2?}", elapsed);
        }

        HydrologyCommands::SedimentConnectivity { slope, flow_acc, flow_dir, output, threshold } => {
            let slp = read_dem(&slope)?;
            let facc = read_dem(&flow_acc)?;
            let fdir: surtgis_core::Raster<u8> = surtgis_core::io::read_geotiff(&flow_dir, None)
                .context("Failed to read flow direction")?;
            let start = Instant::now();
            let result = sediment_connectivity(
                &slp, &facc, &fdir,
                SedimentConnectivityParams { stream_threshold: threshold },
                None,
            ).context("Failed to compute sediment connectivity")?;
            let elapsed = start.elapsed();
            write_result(&result, &output, compress)?;
            done("Sediment connectivity", &output, elapsed);
        }

        HydrologyCommands::BasinMorphometry { input, cell_size } => {
            let ws_r: surtgis_core::Raster<i32> = surtgis_core::io::read_geotiff(&input, None)
                .context("Failed to read watershed raster")?;
            let start = Instant::now();
            let metrics = basin_morphometry(&ws_r, cell_size)
                .context("Failed to compute basin morphometry")?;
            let elapsed = start.elapsed();
            println!("{:<8} {:>10} {:>10} {:>10} {:>10} {:>10}",
                "Basin", "Area(m2)", "Perim(m)", "Circular", "Elongat", "Compact");
            println!("{}", "-".repeat(68));
            for m in &metrics {
                println!("{:<8} {:>10.1} {:>10.1} {:>10.4} {:>10.4} {:>10.4}",
                    m.watershed_id, m.area_m2, m.perimeter_m,
                    m.circularity, m.elongation, m.compactness);
            }
            println!("\n  Processing time: {:.2?}", elapsed);
        }

        HydrologyCommands::All {
            input,
            outdir,
            threshold,
        } => {
            std::fs::create_dir_all(&outdir)
                .context("Failed to create output directory")?;

            // Check if DEM exceeds memory limit
            if let Some(limit) = mem_limit_bytes {
                if let Ok(est_size) = memory::estimate_decompressed_size(&input) {
                    if est_size > limit {
                        eprintln!("Warning: DEM size ({:.2} GB) exceeds --max-memory limit ({:.2} GB)",
                                 est_size as f64 / 1e9, limit as f64 / 1e9);
                        eprintln!("Note: Hydrology 'all' pipeline requires full in-memory processing");
                    }
                }
            }

            let dem = read_dem(&input)?;
            let start = Instant::now();

            println!("Computing full hydrology pipeline...");

            let filled =
                priority_flood(&dem, PriorityFloodParams { epsilon: 0.0001 })
                    .context("fill")?;
            write_result(&filled, &outdir.join("filled.tif"), compress)?;
            println!("  filled.tif");

            let fdir = flow_direction(&filled).context("flow direction")?;
            write_result_u8(&fdir, &outdir.join("flow_direction_d8.tif"), compress)?;
            println!("  flow_direction_d8.tif");

            let fdir_dinf =
                flow_direction_dinf(&filled).context("flow direction dinf")?;
            write_result(
                &fdir_dinf,
                &outdir.join("flow_direction_dinf.tif"),
                compress,
            )?;
            println!("  flow_direction_dinf.tif");

            let facc = flow_accumulation(&fdir).context("flow accumulation")?;
            write_result(&facc, &outdir.join("flow_accumulation.tif"), compress)?;
            println!("  flow_accumulation.tif");

            let facc_mfd = flow_accumulation_mfd(&filled, MfdParams { exponent: 1.1 })
                .context("mfd accumulation")?;
            write_result(
                &facc_mfd,
                &outdir.join("flow_accumulation_mfd.tif"),
                compress,
            )?;
            println!("  flow_accumulation_mfd.tif");

            let slope_rad = slope(
                &filled,
                SlopeParams {
                    units: SlopeUnits::Radians,
                    z_factor: 1.0,
                },
            )
            .context("slope")?;
            let twi_r = twi(&facc, &slope_rad).context("twi")?;
            write_result(&twi_r, &outdir.join("twi.tif"), compress)?;
            println!("  twi.tif");

            let streams = stream_network(&facc, StreamNetworkParams { threshold })
                .context("streams")?;
            write_result_u8(&streams, &outdir.join("stream_network.tif"), compress)?;
            println!("  stream_network.tif");

            let hand_r = hand(
                &dem,
                &fdir,
                &facc,
                HandParams {
                    stream_threshold: threshold,
                },
            )
            .context("hand")?;
            write_result(&hand_r, &outdir.join("hand.tif"), compress)?;
            println!("  hand.tif");

            let elapsed = start.elapsed();
            println!(
                "\nFull hydrology pipeline saved to: {}",
                outdir.display()
            );
            println!("  8 products, processing time: {:.2?}", elapsed);
        }
    }

    Ok(())
}

/// Compute all hydrology factors from DEM (public for pipeline use)
pub fn handle_hydrology_all(
    input: &std::path::Path,
    outdir: &std::path::Path,
    compress: bool,
    mem_limit_bytes: Option<u64>,
) -> Result<()> {
    std::fs::create_dir_all(outdir)
        .context("Failed to create output directory")?;

    // Check if DEM exceeds memory limit
    if let Some(limit) = mem_limit_bytes {
        if let Ok(est_size) = memory::estimate_decompressed_size(input) {
            if est_size > limit {
                eprintln!("Warning: DEM size ({:.2} GB) exceeds --max-memory limit ({:.2} GB)",
                         est_size as f64 / 1e9, limit as f64 / 1e9);
                eprintln!("Note: Hydrology 'all' pipeline requires full in-memory processing");
            }
        }
    }

    let dem = read_dem(&input.to_path_buf())?;
    let start = std::time::Instant::now();

    println!("Computing full hydrology pipeline...");

    let filled =
        priority_flood(&dem, PriorityFloodParams { epsilon: 0.0001 })
            .context("fill")?;
    write_result(&filled, &outdir.join("filled.tif"), compress)?;
    println!("  filled.tif");

    let fdir = flow_direction(&filled).context("flow direction")?;
    write_result_u8(&fdir, &outdir.join("flow_direction_d8.tif"), compress)?;
    println!("  flow_direction_d8.tif");

    let fdir_dinf =
        flow_direction_dinf(&filled).context("flow direction dinf")?;
    write_result(
        &fdir_dinf,
        &outdir.join("flow_direction_dinf.tif"),
        compress,
    )?;
    println!("  flow_direction_dinf.tif");

    let facc = flow_accumulation(&fdir).context("flow accumulation")?;
    write_result(&facc, &outdir.join("flow_accumulation.tif"), compress)?;
    println!("  flow_accumulation.tif");

    let facc_mfd = flow_accumulation_mfd(&filled, MfdParams { exponent: 1.1 })
        .context("mfd accumulation")?;
    write_result(
        &facc_mfd,
        &outdir.join("flow_accumulation_mfd.tif"),
        compress,
    )?;
    println!("  flow_accumulation_mfd.tif");

    let slope_rad = slope(
        &filled,
        SlopeParams {
            units: SlopeUnits::Radians,
            z_factor: 1.0,
        },
    )
    .context("slope")?;
    let twi_r = twi(&facc, &slope_rad).context("twi")?;
    write_result(&twi_r, &outdir.join("twi.tif"), compress)?;
    println!("  twi.tif");

    let streams = stream_network(&facc, StreamNetworkParams { threshold: 1000.0 })
        .context("streams")?;
    write_result_u8(&streams, &outdir.join("stream_network.tif"), compress)?;
    println!("  stream_network.tif");

    let hand_r = hand(
        &dem,
        &fdir,
        &facc,
        HandParams {
            stream_threshold: 1000.0,
        },
    )
    .context("hand")?;
    write_result(&hand_r, &outdir.join("hand.tif"), compress)?;
    println!("  hand.tif");

    let elapsed = start.elapsed();
    println!(
        "\nFull hydrology pipeline saved to: {}",
        outdir.display()
    );
    println!("  8 products, processing time: {:.2?}", elapsed);

    Ok(())
}