/
compactness_ratio.rs
executable file
·261 lines (230 loc) · 8.54 KB
/
compactness_ratio.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
/*
This tool is part of the WhiteboxTools geospatial analysis library.
Authors: Dr. John Lindsay
Created: 27/09/2018
Last Modified: 13/10/2018
License: MIT
*/
use whitebox_common::algorithms::{polygon_area, polygon_perimeter};
use crate::tools::*;
use whitebox_vector::*;
use std::env;
use std::f64;
use std::io::{Error, ErrorKind};
use std::path;
/// The compactness ratio is an indicator of polygon shape complexity. The compactness
/// ratio is defined as the polygon area divided by its perimeter. Unlike some other
/// shape parameters (e.g. `ShapeComplexityIndex`), compactness ratio does not standardize
/// to a simple Euclidean shape. Although widely used for landscape analysis, compactness
/// ratio, like its inverse, the `PerimeterAreaRatio`, exhibits the undesirable property
/// of polygon size dependence (Mcgarigal et al. 2002). That is, holding shape constant,
/// an increase in polygon size will cause a change in the compactness ratio.
///
/// The output data will be contained in the input vector's attribute table as a new field
/// (COMPACT).
///
/// # See Also
/// `PerimeterAreaRatio`, `ShapeComplexityIndex`, `RelatedCircumscribingCircle`
pub struct CompactnessRatio {
name: String,
description: String,
toolbox: String,
parameters: Vec<ToolParameter>,
example_usage: String,
}
impl CompactnessRatio {
pub fn new() -> CompactnessRatio {
// public constructor
let name = "CompactnessRatio".to_string();
let toolbox = "GIS Analysis/Patch Shape Tools".to_string();
let description = "Calculates the compactness ratio (A/P), a measure of shape complexity, for vector polygons.".to_string();
let mut parameters = vec![];
parameters.push(ToolParameter {
name: "Input Vector Polygon File".to_owned(),
flags: vec!["-i".to_owned(), "--input".to_owned()],
description: "Input vector polygon file.".to_owned(),
parameter_type: ParameterType::ExistingFile(ParameterFileType::Vector(
VectorGeometryType::Polygon,
)),
default_value: None,
optional: false,
});
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*\" --input=polygons.shp",
short_exe, name
)
.replace("*", &sep);
CompactnessRatio {
name: name,
description: description,
toolbox: toolbox,
parameters: parameters,
example_usage: usage,
}
}
}
impl WhiteboxTool for CompactnessRatio {
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();
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 == "-input" {
input_file = if keyval {
vec[1].to_string()
} else {
args[i + 1].to_string()
};
}
}
let mut progress: usize;
let mut old_progress: usize = 1;
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();
if !input_file.contains(&sep) && !input_file.contains("/") {
input_file = format!("{}{}", working_directory, input_file);
}
if verbose {
println!("Reading data...")
};
let input = Shapefile::read(&input_file)?;
let start = Instant::now();
// make sure the input vector file is of points type
if input.header.shape_type.base_shape_type() != ShapeType::Polygon {
return Err(Error::new(
ErrorKind::InvalidInput,
"The input vector data must be of POLYGON base shape type.",
));
}
// create output file
let mut output =
Shapefile::initialize_using_file(&input_file, &input, input.header.shape_type, true)?;
// add the attributes
output.attributes.add_field(&AttributeField::new(
"COMPACT",
FieldDataType::Real,
12u8,
6u8,
));
let mut part_start: usize;
let mut part_end: usize;
let mut area: f64;
let mut perimeter: f64;
for record_num in 0..input.num_records {
let record = input.get_record(record_num);
area = 0f64;
perimeter = 0f64;
for part in 0..record.num_parts as usize {
part_start = record.parts[part] as usize;
part_end = if part < record.num_parts as usize - 1 {
record.parts[part + 1] as usize - 1
} else {
record.num_points as usize - 1
};
if !record.is_hole(part as i32) {
area += polygon_area(&record.points[part_start..part_end]);
} else {
area -= polygon_area(&record.points[part_start..part_end]);
}
perimeter += polygon_perimeter(&record.points[part_start..part_end]);
}
let record_out = record.clone();
output.add_record(record_out);
let mut atts = input.attributes.get_record(record_num);
atts.push(FieldData::Real(area / perimeter));
output.attributes.add_record(atts, false);
if verbose {
progress =
(100.0_f64 * (record_num + 1) as f64 / input.num_records as f64) as usize;
if progress != old_progress {
println!("Progress: {}%", progress);
old_progress = progress;
}
}
}
if verbose {
println!("Saving data...")
};
let _ = match output.write() {
Ok(_) => {
if verbose {
println!("Output file written")
}
}
Err(e) => return Err(e),
};
let elapsed_time = get_formatted_elapsed_time(start);
if verbose {
println!("{}", &format!("Elapsed Time: {}", elapsed_time));
}
Ok(())
}
}