/
average_overlay.rs
262 lines (231 loc) · 9.71 KB
/
average_overlay.rs
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
/*
This tool is part of the WhiteboxTools geospatial analysis library.
Authors: Dr. John Lindsay
Created: June 22 2017
Last Modified: December 14, 2017
License: MIT
*/
use time;
use std::env;
use std::path;
use std::i16;
use std::f64;
use raster::*;
use std::io::{Error, ErrorKind};
use structures::Array2D;
use tools::*;
pub struct AverageOverlay {
name: String,
description: String,
toolbox: String,
parameters: Vec<ToolParameter>,
example_usage: String,
}
impl AverageOverlay {
pub fn new() -> AverageOverlay { // public constructor
let name = "AverageOverlay".to_string();
let toolbox = "GIS Analysis/Overlay Tools".to_string();
let description = "Calculates the average for each grid cell from a group of raster images.".to_string();
// let mut parameters = "-i, --inputs Input raster files, separated by commas or semicolons.\n".to_owned();
// parameters.push_str("-o, --output Output raster file.\n");
let mut parameters = vec![];
parameters.push(ToolParameter{
name: "Input Files".to_owned(),
flags: vec!["-i".to_owned(), "--inputs".to_owned()],
description: "Input raster files.".to_owned(),
parameter_type: ParameterType::FileList(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 raster file.".to_owned(),
parameter_type: ParameterType::NewFile(ParameterFileType::Raster),
default_value: None,
optional: false
});
let sep: String = path::MAIN_SEPARATOR.to_string();
let p = format!("{}", env::current_dir().unwrap().display());
let e = format!("{}", env::current_exe().unwrap().display());
let mut short_exe = e.replace(&p, "").replace(".exe", "").replace(".", "").replace(&sep, "");
if e.contains(".exe") {
short_exe += ".exe";
}
let usage = format!(">>.*{} -r={} -v --wd='*path*to*data*' -i='image1.dep;image2.dep;image3.tif' -o=output.tif", short_exe, name).replace("*", &sep);
AverageOverlay {
name: name,
description: description,
toolbox: toolbox,
parameters: parameters,
example_usage: usage
}
}
}
impl WhiteboxTool for AverageOverlay {
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 {
match serde_json::to_string(&self.parameters) {
Ok(json_str) => return format!("{{\"parameters\":{}}}", json_str),
Err(err) => return format!("{:?}", err),
}
}
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_files = String::new();
let mut output_file = String::new();
if args.len() == 0 {
return Err(Error::new(ErrorKind::InvalidInput,
"Tool run with no paramters."));
}
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;
}
if vec[0].to_lowercase() == "-i" || vec[0].to_lowercase() == "--inputs" {
if keyval {
input_files = vec[1].to_string();
} else {
input_files = args[i+1].to_string();
}
} else if vec[0].to_lowercase() == "-o" || vec[0].to_lowercase() == "--output" {
if keyval {
output_file = vec[1].to_string();
} else {
output_file = args[i+1].to_string();
}
}
}
if verbose {
println!("***************{}", "*".repeat(self.get_tool_name().len()));
println!("* Welcome to {} *", self.get_tool_name());
println!("***************{}", "*".repeat(self.get_tool_name().len()));
}
let sep: String = path::MAIN_SEPARATOR.to_string();
let mut progress: usize;
let mut old_progress: usize = 1;
if !output_file.contains(&sep) && !output_file.contains("/") {
output_file = format!("{}{}", working_directory, output_file);
}
let mut cmd = input_files.split(";");
let mut vec = cmd.collect::<Vec<&str>>();
if vec.len() == 1 {
cmd = input_files.split(",");
vec = cmd.collect::<Vec<&str>>();
}
let num_files = vec.len();
if num_files < 2 {
return Err(Error::new(ErrorKind::InvalidInput,
"There is something incorrect about the input files. At least two inputs are required to operate this tool."));
}
let start = time::now();
// We need to initialize output and n here, but in reality this can't be done
// until we know the size of rows and columns, which occurs during the first loop.
let mut output: Raster = Raster::new(&output_file, "w")?;
let mut n: Array2D<i16> = Array2D::new(0, 0, 0i16, i16::MIN)?; // use i16::MIN as the nodata value
let mut rows = 0isize;
let mut columns = 0isize;
let mut out_nodata = f64::MIN;
let mut in_nodata: f64;
let mut z: f64;
let mut read_first_file = false;
let mut i = 1;
for value in vec {
if !value.trim().is_empty() {
if verbose { println!("Reading data...") };
let mut input_file = value.trim().to_owned();
if !input_file.contains(&sep) && !input_file.contains("/") {
input_file = format!("{}{}", working_directory, input_file);
}
let input = Raster::new(&input_file, "r")?;
in_nodata = input.configs.nodata;
if !read_first_file {
read_first_file = true;
rows = input.configs.rows as isize;
columns = input.configs.columns as isize;
out_nodata = in_nodata;
// initialize the output file and n
output = Raster::initialize_using_file(&output_file, &input);
n = Array2D::new(rows, columns, 0i16, i16::MIN)?;
}
// check to ensure that all inputs have the same rows and columns
if input.configs.rows as isize != rows || input.configs.columns as isize != columns {
return Err(Error::new(ErrorKind::InvalidInput,
"The input files must have the same number of rows and columns and spatial extent."));
}
for row in 0..rows {
for col in 0..columns {
z = input[(row, col)];
if z != in_nodata {
if output[(row, col)] != out_nodata {
output.increment(row, col, z);
n.increment(row, col, 1i16);
} else {
output[(row, col)] = z;
n[(row, col)] = 1i16;
}
}
}
if verbose {
progress = (100.0_f64 * row as f64 / (rows - 1) as f64) as usize;
if progress != old_progress {
println!("Progress (loop {} of {}): {}%", i, num_files + 1, progress);
old_progress = progress;
}
}
}
}
i += 1;
}
for row in 0..rows {
for col in 0..columns {
z = output[(row, col)];
if z != out_nodata {
if n[(row, col)] > 0i16 {
output[(row, col)] = z / n[(row, col)] as f64;
} else {
output[(row, col)] = 0.0f64;
}
}
}
if verbose {
progress = (100.0_f64 * row as f64 / (rows - 1) as f64) as usize;
if progress != old_progress {
println!("Progress (loop {} of {}): {}%", num_files + 1, num_files + 1, progress);
old_progress = progress;
}
}
}
let end = time::now();
let elapsed_time = end - start;
output.add_metadata_entry(format!("Created by whitebox_tools\' {} tool", self.get_tool_name()));
output.add_metadata_entry(format!("Elapsed Time (including I/O): {}", elapsed_time).replace("PT", ""));
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 (including I/O): {}", elapsed_time).replace("PT", ""));
}
Ok(())
}
}