Repository navigation
Expand file tree
/
Copy pathstochastic_depression_analysis.rs
More file actions
executable file
·825 lines (751 loc) · 31.9 KB
/
Copy pathstochastic_depression_analysis.rs
File metadata and controls
executable file
·825 lines (751 loc) · 31.9 KB
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
/*
This tool is part of the WhiteboxTools geospatial analysis library.
Authors: Dr. John Lindsay
Created: 11/05/2018
Last Modified: 29/03/2019
License: MIT
*/
use whitebox_raster::*;
use whitebox_common::structures::Array2D;
use crate::tools::*;
use rand::prelude::*;
use rand::rngs::SmallRng;
use rand_distr::StandardNormal;
use std::cmp::Ordering;
use std::collections::{BinaryHeap, VecDeque};
use std::env;
use std::f64;
use std::f64::consts::PI;
use std::io::{Error, ErrorKind};
use std::path;
use std::sync::mpsc;
use std::sync::Arc;
use std::thread;
/// This tool performs a stochastic analysis of depressions within a DEM, calculating the
/// probability of each cell belonging to a depression. This land-surface parameter
/// (p<sub>dep</sub>) has been widely applied in wetland and bottom-land mapping applications.
///
/// This tool differs from the original Whitebox GAT tool in a few significant ways:
///
/// 1. The Whitebox GAT tool took an error histogram as an input. In practice people found
/// it difficult to create this input. Usually they just generated a normal distribution
/// in a spreadsheet using information about the DEM root-mean-square-error (RMSE). As
/// such, this tool takes a RMSE input and generates the histogram internally. This is
/// more convienent for most applications but loses the flexibility of specifying the
/// error distribution more completely.
///
/// 2. The Whitebox GAT tool generated the error fields using the turning bands method.
/// This tool generates a random Gaussian error field with no spatial autocorrelation
/// and then applies local spatial averaging using a Gaussian filter (the size of
/// which depends of the error autocorrelation length input) to increase the level of
/// autocorrelation. We use the Fast Almost Gaussian Filter of Peter Kovesi (2010),
/// which uses five repeat passes of a mean filter, based on an integral image. This
/// filter method is highly efficient. This results in a significant performance
/// increase compared with the original tool.
///
/// 3. Parts of the tool's workflow utilize parallel processing. However, the depression
/// filling operation, which is the most time-consuming part of the workflow, is
/// not parallelized.
///
/// In addition to the input DEM (`--dem`) and output p<sub>dep</sub> file name (`--output`), the user
/// must specify the nature of the error model, including the root-mean-square error (`--rmse`) and
/// the error field correlation length (`--range`, in map units). These parameters determine the statistical frequency
/// distribution and spatial characteristics of the modeled error fields added to the DEM in each
/// iteration of the simulation. The user must also specify the number of iterations (`--iterations`).
/// A larger number of iterations will produce a smoother p<sub>dep</sub> raster.
///
/// This tool creates several temporary rasters in memory and, as a result, is very memory hungry.
/// This will necessarily limit the size of DEMs that can be processed on more memory-constrained
/// systems. As a rough guide for usage, **the computer system will need 6-10 times more memory than
/// the file size of the DEM**. If your computer possesses insufficient memory, you may consider
/// splitting the input DEM apart into smaller tiles.
///
/// 
///
/// For a video demonstrating the application of the `StochasticDepressionAnalysis` tool, see
/// [this YouTube video](https://www.youtube.com/watch?v=pg8puYYbSzU).
///
/// # Reference
/// Lindsay, J. B., & Creed, I. F. (2005). Sensitivity of digital landscapes to artifact depressions in
/// remotely-sensed DEMs. Photogrammetric Engineering & Remote Sensing, 71(9), 1029-1036.
///
/// # See Also
/// `ImpoundmentSizeIndex`, `FastAlmostGaussianFilter`
pub struct StochasticDepressionAnalysis {
name: String,
description: String,
toolbox: String,
parameters: Vec<ToolParameter>,
example_usage: String,
}
impl StochasticDepressionAnalysis {
pub fn new() -> StochasticDepressionAnalysis {
// public constructor
let name = "StochasticDepressionAnalysis".to_string();
let toolbox = "Hydrological Analysis".to_string();
let description = "Performs a stochastic analysis of depressions within a DEM.".to_string();
let mut parameters = vec![];
parameters.push(ToolParameter {
name: "Input DEM File".to_owned(),
flags: vec!["-i".to_owned(), "--dem".to_owned()],
description: "Input raster DEM file.".to_owned(),
parameter_type: ParameterType::ExistingFile(ParameterFileType::Raster),
default_value: None,
optional: false,
});
parameters.push(ToolParameter {
name: "Output File".to_owned(),
flags: vec!["-o".to_owned(), "--output".to_owned()],
description: "Output file.".to_owned(),
parameter_type: ParameterType::NewFile(ParameterFileType::Raster),
default_value: None,
optional: false,
});
parameters.push(ToolParameter{
name: "DEM root-mean-square-error (z units)".to_owned(),
flags: vec!["--rmse".to_owned()],
description: "The DEM's root-mean-square-error (RMSE), in z units. This determines error magnitude.".to_owned(),
parameter_type: ParameterType::Float,
default_value: None,
optional: false
});
parameters.push(ToolParameter {
name: "Range of Autocorrelation (map units)".to_owned(),
flags: vec!["--range".to_owned()],
description: "The error field's correlation length, in xy-units.".to_owned(),
parameter_type: ParameterType::Float,
default_value: None,
optional: false,
});
parameters.push(ToolParameter {
name: "Iterations".to_owned(),
flags: vec!["--iterations".to_owned()],
description: "The number of iterations.".to_owned(),
parameter_type: ParameterType::Integer,
default_value: Some("100".to_owned()),
optional: true,
});
let sep: String = path::MAIN_SEPARATOR.to_string();
let e = format!("{}", env::current_exe().unwrap().display());
let mut parent = env::current_exe().unwrap();
parent.pop();
let p = format!("{}", parent.display());
let mut short_exe = e
.replace(&p, "")
.replace(".exe", "")
.replace(".", "")
.replace(&sep, "");
if e.contains(".exe") {
short_exe += ".exe";
}
let usage = format!(">>.*{0} -r={1} -v --wd=\"*path*to*data*\" --dem=DEM.tif -o=out.tif --rmse=10.0 --range=850.0 --iterations=2500", short_exe, name).replace("*", &sep);
StochasticDepressionAnalysis {
name: name,
description: description,
toolbox: toolbox,
parameters: parameters,
example_usage: usage,
}
}
}
impl WhiteboxTool for StochasticDepressionAnalysis {
fn get_source_file(&self) -> String {
String::from(file!())
}
fn get_tool_name(&self) -> String {
self.name.clone()
}
fn get_tool_description(&self) -> String {
self.description.clone()
}
fn get_tool_parameters(&self) -> String {
let mut s = String::from("{\"parameters\": [");
for i in 0..self.parameters.len() {
if i < self.parameters.len() - 1 {
s.push_str(&(self.parameters[i].to_string()));
s.push_str(",");
} else {
s.push_str(&(self.parameters[i].to_string()));
}
}
s.push_str("]}");
s
}
fn get_example_usage(&self) -> String {
self.example_usage.clone()
}
fn get_toolbox(&self) -> String {
self.toolbox.clone()
}
fn run<'a>(
&self,
args: Vec<String>,
working_directory: &'a str,
verbose: bool,
) -> Result<(), Error> {
let mut input_file = String::new();
let mut output_file = String::new();
let mut rmse = 1f64;
let mut range = 1f64;
let mut iterations = 100;
if args.len() == 0 {
return Err(Error::new(
ErrorKind::InvalidInput,
"Tool run with no parameters.",
));
}
for i in 0..args.len() {
let mut arg = args[i].replace("\"", "");
arg = arg.replace("\'", "");
let cmd = arg.split("="); // in case an equals sign was used
let vec = cmd.collect::<Vec<&str>>();
let mut keyval = false;
if vec.len() > 1 {
keyval = true;
}
let flag_val = vec[0].to_lowercase().replace("--", "-");
if flag_val == "-i" || flag_val == "-dem" {
input_file = if keyval {
vec[1].to_string()
} else {
args[i + 1].to_string()
};
} else if flag_val == "-o" || flag_val == "-output" {
output_file = if keyval {
vec[1].to_string()
} else {
args[i + 1].to_string()
};
} else if flag_val == "-rmse" {
rmse = if keyval {
vec[1]
.to_string()
.parse::<f64>()
.expect(&format!("Error parsing {}", flag_val))
} else {
args[i + 1]
.to_string()
.parse::<f64>()
.expect(&format!("Error parsing {}", flag_val))
};
} else if flag_val == "-range" {
range = if keyval {
vec[1]
.to_string()
.parse::<f64>()
.expect(&format!("Error parsing {}", flag_val))
} else {
args[i + 1]
.to_string()
.parse::<f64>()
.expect(&format!("Error parsing {}", flag_val))
};
} else if flag_val == "-iterations" {
iterations = if keyval {
vec[1]
.to_string()
.parse::<f32>()
.expect(&format!("Error parsing {}", flag_val)) as usize
} else {
args[i + 1]
.to_string()
.parse::<f32>()
.expect(&format!("Error parsing {}", flag_val)) as usize
};
}
}
if verbose {
let tool_name = self.get_tool_name();
let welcome_len = format!("* Welcome to {} *", tool_name).len().max(28);
// 28 = length of the 'Powered by' by statement.
println!("{}", "*".repeat(welcome_len));
println!("* Welcome to {} {}*", tool_name, " ".repeat(welcome_len - 15 - tool_name.len()));
println!("* Powered by WhiteboxTools {}*", " ".repeat(welcome_len - 28));
println!("* www.whiteboxgeo.com {}*", " ".repeat(welcome_len - 23));
println!("{}", "*".repeat(welcome_len));
}
let sep: String = path::MAIN_SEPARATOR.to_string();
let mut progress: usize;
let mut old_progress: usize = 1;
if !input_file.contains(&sep) && !input_file.contains("/") {
input_file = format!("{}{}", working_directory, input_file);
}
if !output_file.contains(&sep) && !output_file.contains("/") {
output_file = format!("{}{}", working_directory, output_file);
}
let mut reference_cdf: Vec<Vec<f64>> = vec![];
let mu = 0f64; // assume the mean error is zero
let p_step = 6.0 * rmse / 99.0;
for a in 0..100 {
let x = -3.0 * rmse + a as f64 * p_step;
// (1 / sqrt(2σ^2 * π)) * e^(-(x - μ)^2 / 2σ^2)
let p = (1.0 / (2.0 * PI * rmse.powi(2)).sqrt())
* (-(x - mu).powi(2) / (2.0 * rmse.powi(2))).exp();
reference_cdf.push(vec![x, p]);
}
// convert the reference histogram to a cdf.
let num_lines = reference_cdf.len();
for i in 1..num_lines {
reference_cdf[i][1] += reference_cdf[i - 1][1];
}
let total_frequency = reference_cdf[num_lines - 1][1];
for i in 0..num_lines {
reference_cdf[i][1] = reference_cdf[i][1] / total_frequency;
}
let mut starting_vals = [0usize; 11];
let mut p_val: f64;
for i in 0..num_lines {
p_val = reference_cdf[i][1];
if p_val < 0.1 {
starting_vals[1] = i;
}
if p_val < 0.2 {
starting_vals[2] = i;
}
if p_val < 0.3 {
starting_vals[3] = i;
}
if p_val < 0.4 {
starting_vals[4] = i;
}
if p_val < 0.5 {
starting_vals[5] = i;
}
if p_val < 0.6 {
starting_vals[6] = i;
}
if p_val < 0.7 {
starting_vals[7] = i;
}
if p_val < 0.8 {
starting_vals[8] = i;
}
if p_val < 0.9 {
starting_vals[9] = i;
}
if p_val <= 1.0 {
starting_vals[10] = i;
}
}
if iterations > i16::max_value() as usize {
if verbose {
println!(
"Warning: Iterations cannot be higher than {}.",
i16::max_value()
);
}
iterations = i16::max_value() as usize;
}
let input1 = Raster::new(&input_file, "r")?;
let start = Instant::now();
let rows = input1.configs.rows as isize;
let columns = input1.configs.columns as isize;
let nodata = input1.configs.nodata;
let sigma = range / input1.configs.resolution_x;
let resolution = (input1.configs.resolution_x + input1.configs.resolution_y) / 2f64;
let range_in_cells = range / resolution;
let mut output_config = input1.configs.clone();
output_config.data_type = DataType::F32;
let mut freq_dep: Array2D<i16> = Array2D::new(rows, columns, 0i16, -1i16).unwrap();
let nodata_i32 = i32::min_value();
let mut input: Array2D<i32> = Array2D::new(rows, columns, nodata_i32, nodata_i32).unwrap();
let mut z: f64;
let multiplier = 1000f64;
let mut num_nodata = 0usize;
for row in 0..rows {
for col in 0..columns {
z = input1.get_value(row, col);
if z != nodata {
input.set_value(row, col, (z * multiplier) as i32);
} else {
num_nodata += 1;
}
}
}
drop(input1);
// num_nodata is used by the queue used to initialize the depression filling op.
// It needs to be able to hold all of the edge cells in the very least.
if num_nodata < ((rows + 2) * 2 + (columns + 2) * 2) as usize {
num_nodata = ((rows + 2) * 2 + (columns + 2) * 2) as usize;
}
// let mut error_model: Array2D<i32> = Array2D::new(rows, columns, nodata_i32, nodata_i32).unwrap();
let background_val = i32::min_value() + 1;
let mut num_procs = num_cpus::get() as isize;
let configs = whitebox_common::configs::get_configs()?;
let max_procs = configs.max_procs;
if max_procs > 0 && max_procs < num_procs {
num_procs = max_procs;
}
let numcells: f64 = (rows * columns) as f64; // used by the histogram matching
let dx = [1, 1, 1, 0, -1, -1, -1, 0];
let dy = [-1, 0, 1, 1, 1, 0, -1, -1];
for iter_num in 0..iterations {
if verbose {
println!("Iteration {}...", iter_num + 1);
}
/////////////////////////////
// Generate a random field //
/////////////////////////////
let (tx, rx) = mpsc::channel();
for tid in 0..num_procs {
let tx = tx.clone();
thread::spawn(move || {
let mut rng = SmallRng::from_entropy();
let mut sn_val: f64;
for row in (0..rows).filter(|r| r % num_procs == tid) {
let mut data = vec![0i32; columns as usize];
for col in 0..columns {
sn_val = rng.sample(StandardNormal);
data[col as usize] =
(sn_val * multiplier * range_in_cells * 2f64) as i32;
}
tx.send((row, data)).unwrap();
}
});
}
let mut error_model: Array2D<i32> =
Array2D::new(rows, columns, nodata_i32, nodata_i32).unwrap();
for _ in 0..rows {
let (row, data) = rx.recv().expect("Error receiving data from thread.");
error_model.set_row_data(row, data);
}
////////////////////////////////////////
// Perform a FastAlmostGaussianFilter //
////////////////////////////////////////
let n = 5;
let w_ideal = (12f64 * sigma * sigma / n as f64 + 1f64).sqrt();
let mut wl = w_ideal.floor() as isize;
if wl % 2 == 0 {
wl -= 1;
} // must be an odd integer
let wu = wl + 2;
let m = ((12f64 * sigma * sigma
- (n * wl * wl) as f64
- (4 * n * wl) as f64
- (3 * n) as f64)
/ (-4 * wl - 4) as f64)
.round() as isize;
let mut val: i32;
let mut sum: i32;
let mut i_prev: i32;
// Find the min and max values.
let mut min_value = i32::max_value();
let mut max_value = i32::min_value();
let mut z: i32;
for iteration_num in 0..n {
let midpoint = if iteration_num <= m {
(wl as f64 / 2f64).floor() as isize
} else {
(wu as f64 / 2f64).floor() as isize
};
// Create the integral image.
let mut integral: Array2D<i32> =
Array2D::new(rows, columns, 0, nodata_i32).unwrap();
for row in 0..rows {
sum = 0;
for col in 0..columns {
val = error_model.get_value(row, col);
sum += val;
if row > 0 {
i_prev = integral.get_value(row - 1, col);
integral.set_value(row, col, sum + i_prev);
} else {
integral.set_value(row, col, sum);
}
}
}
// Perform Filter
let integral = Arc::new(integral);
let (tx, rx) = mpsc::channel();
for tid in 0..num_procs {
let tx = tx.clone();
let integral = integral.clone();
thread::spawn(move || {
let mut z: i32;
let mut sum: i32;
let (mut x1, mut x2, mut y1, mut y2): (isize, isize, isize, isize);
let mut num_cells: i32;
for row in (0..rows).filter(|r| r % num_procs == tid) {
y1 = row - midpoint - 1;
if y1 < 0 {
y1 = 0;
}
y2 = row + midpoint;
if y2 >= rows {
y2 = rows - 1;
}
let mut data = vec![0i32; columns as usize];
let mut min_value = i32::max_value();
let mut max_value = i32::min_value();
for col in 0..columns {
x1 = col - midpoint - 1;
if x1 < 0 {
x1 = 0;
}
x2 = col + midpoint;
if x2 >= columns {
x2 = columns - 1;
}
num_cells = ((y2 - y1) * (x2 - x1)) as i32;
if num_cells > 0 {
sum = integral[(y2, x2)] + integral[(y1, x1)]
- integral[(y1, x2)]
- integral[(y2, x1)];
z = sum / num_cells;
data[col as usize] = z;
if z < min_value {
min_value = z;
}
if z > max_value {
max_value = z;
}
}
}
tx.send((row, data, min_value, max_value)).unwrap();
}
});
}
for _ in 0..rows {
let (row, data, val1, val2) =
rx.recv().expect("Error receiving data from thread.");
error_model.set_row_data(row, data);
if val1 < min_value {
min_value = val1;
}
if val2 > max_value {
max_value = val2;
}
}
drop(integral);
}
////////////////////////////////////////////
// Perform a histogram matching operation //
////////////////////////////////////////////
let num_bins = (max_value - min_value + 1) as usize;
let mut histogram = vec![0f64; num_bins];
let mut bin_num: usize;
for row in 0..rows {
for col in 0..columns {
z = error_model.get_value(row, col);
bin_num = (z - min_value) as usize;
histogram[bin_num] += 1f64;
}
}
let mut cdf = vec![0f64; num_bins];
cdf[0] = histogram[0];
for i in 1..num_bins {
cdf[i] = cdf[i - 1] + histogram[i];
}
for i in 0..num_bins {
cdf[i] = cdf[i] / numcells;
}
drop(histogram);
let mut j: usize;
let mut x_val = 0f64;
let mut p_val: f64;
let (mut x1, mut x2, mut p1, mut p2): (f64, f64, f64, f64);
for row in 0..rows {
for col in 0..columns {
z = error_model.get_value(row, col);
bin_num = (z - min_value) as usize;
p_val = cdf[bin_num];
j = ((p_val * 10f64).floor()) as usize;
for i in starting_vals[j]..num_lines {
if reference_cdf[i][1] > p_val {
if i > 0 {
x1 = reference_cdf[i - 1][0];
x2 = reference_cdf[i][0];
p1 = reference_cdf[i - 1][1];
p2 = reference_cdf[i][1];
x_val = if p1 != p2 {
x1 + ((x2 - x1) * ((p_val - p1) / (p2 - p1)))
} else {
x1
};
} else {
x_val = reference_cdf[i][0];
}
break;
}
}
error_model.set_value(row, col, (x_val * multiplier) as i32);
}
}
drop(cdf);
/////////////////////////////////////
// Add the DEM to the error model. //
/////////////////////////////////////
let mut e: i32;
for row in 0..rows {
for col in 0..columns {
z = input.get_value(row, col);
if z != nodata_i32 {
e = error_model.get_value(row, col);
error_model.set_value(row, col, z + e);
} else {
error_model.set_value(row, col, nodata_i32);
}
}
}
/////////////////////////////////////////////////
// Fill the depressions in the error-added DEM //
/////////////////////////////////////////////////
/*
Find the data edges. This is complicated by the fact that DEMs frequently
have nodata edges, whereby the DEM does not occupy the full extent of
the raster. One approach to doing this would be simply to scan the
raster, looking for cells that neighbour nodata values. However, this
assumes that there are no interior nodata holes in the dataset. Instead,
the approach used here is to perform a region-growing operation, looking
for nodata values along the raster's edges.
*/
let mut queue: VecDeque<(isize, isize)> = VecDeque::with_capacity(num_nodata);
for row in 0..rows {
/*
Note that this is only possible because Whitebox rasters
allow you to address cells beyond the raster extent but
return the nodata value for these regions.
*/
queue.push_back((row, -1));
queue.push_back((row, columns));
}
for col in 0..columns {
queue.push_back((-1, col));
queue.push_back((rows, col));
}
let mut dep_filled: Array2D<i32> =
Array2D::new(rows, columns, background_val, nodata_i32).unwrap();
let mut minheap = BinaryHeap::with_capacity((rows * columns) as usize - num_nodata);
let mut zin_n: i32; // value of neighbour of row, col in input raster
let mut zout: i32; // value of row, col in output raster
let mut zout_n: i32; // value of neighbour of row, col in output raster
let (mut row, mut col): (isize, isize);
let (mut row_n, mut col_n): (isize, isize);
while !queue.is_empty() {
let cell = queue.pop_front().unwrap();
row = cell.0;
col = cell.1;
for n in 0..8 {
row_n = row + dy[n];
col_n = col + dx[n];
zin_n = error_model.get_value(row_n, col_n);
zout_n = dep_filled.get_value(row_n, col_n);
if zout_n == background_val {
if zin_n == nodata_i32 {
dep_filled.set_value(row_n, col_n, nodata_i32);
queue.push_back((row_n, col_n));
} else {
dep_filled.set_value(row_n, col_n, zin_n);
// Push it onto the priority queue for the priority flood operation
minheap.push(GridCell {
id: row_n * columns + col_n,
priority: zin_n,
});
}
}
}
}
drop(queue);
// Perform the priority flood operation.
while !minheap.is_empty() {
let cell = minheap.pop().expect("Error during pop operation.");
row = cell.id / columns;
col = cell.id % columns;
zout = dep_filled.get_value(row, col);
for n in 0..8 {
row_n = row + dy[n];
col_n = col + dx[n];
zout_n = dep_filled.get_value(row_n, col_n);
if zout_n == background_val {
zin_n = error_model.get_value(row_n, col_n);
if zin_n != nodata_i32 {
if zin_n < zout {
zin_n = zout;
// Depression cell; increase its value in output
freq_dep.increment(row_n, col_n, 1i16);
} // We're in a depression. Raise the elevation.
dep_filled.set_value(row_n, col_n, zin_n);
minheap.push(GridCell {
id: row_n * columns + col_n,
priority: zin_n,
});
} else {
// Interior nodata cells are still treated as nodata and are not filled.
dep_filled.set_value(row_n, col_n, nodata_i32);
}
}
}
}
drop(minheap);
drop(dep_filled);
if verbose {
progress = (100.0_f64 * (iter_num + 1) as f64 / iterations as f64) as usize;
if progress != old_progress {
println!("Progress: {}%", progress);
old_progress = progress;
}
}
}
let iters = iterations as f64;
let mut output = Raster::initialize_using_config(&output_file, &output_config);
for row in 0..rows {
for col in 0..columns {
if input.get_value(row, col) != nodata_i32 {
output.set_value(row, col, freq_dep.get_value(row, col) as f64 / iters);
} else {
output.set_value(row, col, nodata);
}
}
}
output.configs.palette = "spectrum.plt".to_string();
output.configs.photometric_interp = PhotometricInterpretation::Continuous;
output.add_metadata_entry(format!(
"Created by whitebox_tools\' {} tool",
self.get_tool_name()
));
output.add_metadata_entry(format!("Input base raster file: {}", input_file));
output.add_metadata_entry(format!("RMSE: {}", rmse));
output.add_metadata_entry(format!("Range: {}", range));
output.add_metadata_entry(format!("Iterations: {}", iterations));
let elapsed_time = get_formatted_elapsed_time(start);
output.add_metadata_entry(format!("Elapsed Time (excluding I/O): {}", elapsed_time));
if verbose {
println!("Saving data...")
};
let _ = match output.write() {
Ok(_) => {
if verbose {
println!("Output file written")
}
}
Err(e) => return Err(e),
};
if verbose {
println!(
"{}",
&format!("Elapsed Time (excluding I/O): {}", elapsed_time)
);
}
Ok(())
}
}
struct GridCell {
id: isize,
priority: i32,
}
impl Eq for GridCell {}
impl PartialOrd for GridCell {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
other.priority.partial_cmp(&self.priority)
}
}
impl Ord for GridCell {
fn cmp(&self, other: &GridCell) -> Ordering {
self.partial_cmp(other).unwrap()
}
}
impl PartialEq for GridCell {
fn eq(&self, other: &GridCell) -> bool {
self.priority == other.priority
}
}