-
Notifications
You must be signed in to change notification settings - Fork 161
/
union.rs
executable file
·2085 lines (1944 loc) · 107 KB
/
union.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
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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
This tool is part of the WhiteboxTools geospatial analysis library.
Authors: Dr. John Lindsay
Created: 05/11/2018
Last Modified: 08/04/2019
License: MIT
*/
extern crate kdtree;
use whitebox_common::algorithms::{
find_split_points_at_line_intersections, interior_point, is_clockwise_order, point_in_poly,
poly_in_poly, poly_overlaps_poly,
};
use whitebox_common::structures::{BoundingBox, MultiPolyline, Polyline, Point2D};
use crate::tools::*;
use whitebox_vector::*;
use kdtree::distance::squared_euclidean;
use kdtree::KdTree;
use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashSet};
use std::env;
use std::io::{Error, ErrorKind};
use std::path;
const EPSILON: f64 = std::f64::EPSILON;
/// This tool splits vector layers at their overlaps, creating a layer containing all the portions from both
/// input and overlay layers. The *Union* is related to the Boolean
/// **OR** operation in set theory and is one of the common vector overlay
/// operations in GIS. The user must specify the names of the input and overlay vector files
/// as well as the output vector file name. The tool operates on vector points,
/// lines, or polygon, but both the input and overlay files must contain the same ShapeType.
///
/// The attributes of the two input vectors will be merged in the output attribute table.
/// Fields that are duplicated between the inputs will share a single attribute in the
/// output. Fields that only exist in one of the two inputs will be populated by `null`
/// in the output table. Multipoint ShapeTypes however will simply contain a single
/// output feature identifier (`FID`) attribute. Also, note that depending on the
/// ShapeType (polylines and polygons), `Measure` and `Z` ShapeDimension data will not
/// be transferred to the output geometries. If the input attribute table contains fields
/// that measure the geometric properties of their associated features (e.g. length or area),
/// these fields will not be updated to reflect changes in geometry shape and size
/// resulting from the overlay operation.
///
/// # See Also
/// `Intersect`, `Difference`, `SymmetricalDifference`, `Clip`, `Erase`
pub struct Union {
name: String,
description: String,
toolbox: String,
parameters: Vec<ToolParameter>,
example_usage: String,
}
impl Union {
pub fn new() -> Union {
// public constructor
let name = "Union".to_string();
let toolbox = "GIS Analysis/Overlay Tools".to_string();
let description = "Splits vector layers at their overlaps, creating a layer containing all the portions from both input and overlay layers.".to_string();
let mut parameters = vec![];
parameters.push(ToolParameter {
name: "Input Vector File".to_owned(),
flags: vec!["-i".to_owned(), "--input".to_owned()],
description: "Input vector file.".to_owned(),
parameter_type: ParameterType::ExistingFile(ParameterFileType::Vector(
VectorGeometryType::Any,
)),
default_value: None,
optional: false,
});
parameters.push(ToolParameter {
name: "Input Overlay Vector File".to_owned(),
flags: vec!["--overlay".to_owned()],
description: "Input overlay vector file.".to_owned(),
parameter_type: ParameterType::ExistingFile(ParameterFileType::Vector(
VectorGeometryType::Any,
)),
default_value: None,
optional: false,
});
parameters.push(ToolParameter {
name: "Output Vector File".to_owned(),
flags: vec!["-o".to_owned(), "--output".to_owned()],
description: "Output vector file.".to_owned(),
parameter_type: ParameterType::NewFile(ParameterFileType::Vector(
VectorGeometryType::Any,
)),
default_value: None,
optional: false,
});
parameters.push(ToolParameter {
name: "Snap Tolerance".to_owned(),
flags: vec!["--snap".to_owned()],
description: "Snap tolerance.".to_owned(),
parameter_type: ParameterType::Float,
default_value: Some("0.0".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*\" -input=layer1.shp --overlay=layer2.shp -o=out_file.shp --snap=0.0000001",
short_exe, name
).replace("*", &sep);
Union {
name: name,
description: description,
toolbox: toolbox,
parameters: parameters,
example_usage: usage,
}
}
}
impl WhiteboxTool for Union {
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 overlay_file = String::new();
let mut output_file = String::new();
let mut precision = std::f64::EPSILON;
// read the arguments
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.contains("-input") {
input_file = if keyval {
vec[1].to_string()
} else {
args[i + 1].to_string()
};
} else if flag_val == "-overlay" {
overlay_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 == "-snap" {
precision = 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))
};
if precision == 0f64 {
precision = std::f64::EPSILON;
}
}
}
let sep: String = path::MAIN_SEPARATOR.to_string();
let mut progress: usize;
let mut old_progress: usize = 1;
let start = Instant::now();
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));
}
if !input_file.contains(&sep) && !input_file.contains("/") {
input_file = format!("{}{}", working_directory, input_file);
}
if !overlay_file.contains(&sep) && !overlay_file.contains("/") {
overlay_file = format!("{}{}", working_directory, overlay_file);
}
if !output_file.contains(&sep) && !output_file.contains("/") {
output_file = format!("{}{}", working_directory, output_file);
}
if verbose {
println!("Reading data...")
};
let overlay = Shapefile::read(&overlay_file)?;
let input = Shapefile::read(&input_file)?;
let projection = input.projection.clone();
// The overlay file must be of the same ShapeType as the input file
if overlay.header.shape_type != input.header.shape_type {
return Err(Error::new(
ErrorKind::InvalidInput,
"The input and overlay vector inputs must be of the same shape type.",
));
}
// create output file
let mut output =
Shapefile::initialize_using_file(&output_file, &input, input.header.shape_type, false)?;
output.projection = projection;
// add the attributes
output
.attributes
.add_field(&AttributeField::new("FID", FieldDataType::Int, 7u8, 0u8));
let mut input_field_mapping = vec![0; input.attributes.get_num_fields()];
for i in 0..input.attributes.get_num_fields() {
let att = input.attributes.get_field(i);
if att.name != "FID" {
if !output.attributes.contains_field(att) {
output.attributes.add_field(&(att.clone()));
input_field_mapping[i] = output.attributes.get_num_fields() - 1;
} else {
input_field_mapping[i] = output.attributes.get_field_num(&att.name).unwrap();
}
}
}
let mut overlay_field_mapping = vec![0; overlay.attributes.get_num_fields()];
for i in 0..overlay.attributes.get_num_fields() {
let att = overlay.attributes.get_field(i);
if att.name != "FID" {
if !output.attributes.contains_field(att) {
output.attributes.add_field(&(att.clone()));
overlay_field_mapping[i] = output.attributes.get_num_fields() - 1;
} else {
overlay_field_mapping[i] = output.attributes.get_field_num(&att.name).unwrap();
}
}
}
let num_attributes = output.attributes.get_num_fields();
match input.header.shape_type.base_shape_type() {
ShapeType::Point => {
// place the points from both files into a KD-tree
let dimensions = 2;
let capacity_per_node = 64;
let mut tree = KdTree::with_capacity(dimensions, capacity_per_node);
let mut p: Point2D;
for record_num in 0..input.num_records {
let record = input.get_record(record_num);
p = record.points[0];
tree.add([p.x, p.y], (1, record_num)).unwrap();
}
for record_num in 0..overlay.num_records {
let record = overlay.get_record(record_num);
p = record.points[0];
tree.add([p.x, p.y], (2, record_num)).unwrap();
}
// now see which ones overlap
let mut fid = 1;
let mut overlay_id: usize = 0;
let num_total_points = (input.num_records + overlay.num_records - 1) as f64;
let mut overlapped_point: bool;
for record_num in 0..input.num_records {
let record = input.get_record(record_num);
p = record.points[0];
let ret = tree
.within(&[p.x, p.y], precision, &squared_euclidean)
.unwrap();
overlapped_point = false;
for a in 0..ret.len() {
if (ret[a].1).0 == 2 {
overlay_id = (ret[a].1).1;
overlapped_point = true;
break;
}
}
if !overlapped_point {
// it is not overlapped by another point in the overlay file.
output.add_record(record.clone());
let mut out_atts = vec![FieldData::Null; num_attributes];
out_atts[0] = FieldData::Int(fid);
fid += 1;
let atts = input.attributes.get_record(record_num);
for att_num in 0..atts.len() {
if input_field_mapping[att_num] != 0 {
out_atts[input_field_mapping[att_num]] = atts[att_num].clone();
}
}
output.attributes.add_record(out_atts, false);
} else {
// it is overlapped by another point in the overlay file.
output.add_record(record.clone());
let mut out_atts = vec![FieldData::Null; num_attributes];
out_atts[0] = FieldData::Int(fid);
fid += 1;
let atts = input.attributes.get_record(record_num);
for att_num in 0..atts.len() {
if input_field_mapping[att_num] != 0 {
out_atts[input_field_mapping[att_num]] = atts[att_num].clone();
}
}
let atts = overlay.attributes.get_record(overlay_id);
for att_num in 0..atts.len() {
if overlay_field_mapping[att_num] != 0 {
out_atts[overlay_field_mapping[att_num]] = atts[att_num].clone();
}
}
output.attributes.add_record(out_atts, false);
}
if verbose {
progress = (100.0_f64 * record_num as f64 / num_total_points) as usize;
if progress != old_progress {
println!("Progress: {}%", progress);
old_progress = progress;
}
}
}
for record_num in 0..overlay.num_records {
let record = overlay.get_record(record_num);
p = record.points[0];
let ret = tree
.within(&[p.x, p.y], precision, &squared_euclidean)
.unwrap();
overlapped_point = false;
for a in 0..ret.len() {
if (ret[a].1).0 == 1 {
overlapped_point = true;
break;
}
}
if !overlapped_point {
// it is not overlapped by another point in the overlay file.
output.add_record(record.clone());
let mut out_atts = vec![FieldData::Null; num_attributes];
out_atts[0] = FieldData::Int(fid);
fid += 1;
let atts = overlay.attributes.get_record(record_num);
for att_num in 0..atts.len() {
if overlay_field_mapping[att_num] != 0 {
out_atts[overlay_field_mapping[att_num]] = atts[att_num].clone();
}
}
output.attributes.add_record(out_atts, false);
}
if verbose {
progress = (100.0_f64 * (record_num + input.num_records) as f64
/ num_total_points) as usize;
if progress != old_progress {
println!("Progress: {}%", progress);
old_progress = progress;
}
}
}
}
ShapeType::MultiPoint => {
// place the points from both files into a KD-tree
let dimensions = 2;
let capacity_per_node = 64;
let mut tree = KdTree::with_capacity(dimensions, capacity_per_node);
let mut p: Point2D;
let mut total_points = 0;
for record_num in 0..input.num_records {
let record = input.get_record(record_num);
for p in &record.points {
tree.add([p.x, p.y], 1).unwrap();
total_points += 1;
}
}
let num_points_input = total_points;
for record_num in 0..overlay.num_records {
let record = overlay.get_record(record_num);
for p in &record.points {
tree.add([p.x, p.y], 2).unwrap();
total_points += 1;
}
}
// now see which ones overlap
let num_total_points = (total_points - 1) as f64;
let mut overlapped_point = vec![false; total_points];
let mut num_out_pnts = total_points;
for record_num in 0..overlay.num_records {
let record = overlay.get_record(record_num);
for i in 0..record.points.len() {
p = record.points[i];
let ret = tree
.within(&[p.x, p.y], precision, &squared_euclidean)
.unwrap();
for j in 0..ret.len() {
if *(ret[j].1) == 1 {
num_out_pnts -= 1;
overlapped_point[i + num_points_input] = true;
break;
}
}
if verbose {
progress = (100.0_f64 * (i + num_points_input) as f64
/ num_total_points) as usize;
if progress != old_progress {
println!("Progress: {}%", progress);
old_progress = progress;
}
}
}
}
if num_out_pnts > 0 {
// attributes aren't provided for multipoints overlay.
output.attributes.reinitialize();
output.attributes.add_field(&AttributeField::new(
"FID",
FieldDataType::Int,
7u8,
0u8,
));
let mut sfg = ShapefileGeometry::new(input.header.shape_type);
match input.header.shape_type.dimension() {
ShapeTypeDimension::XY => {
for record_num in 0..input.num_records {
let record = input.get_record(record_num);
for i in 0..record.points.len() {
sfg.add_point((record.points[i]).clone());
}
}
for record_num in 0..overlay.num_records {
let record = overlay.get_record(record_num);
for i in 0..record.points.len() {
if !overlapped_point[i + num_points_input] {
sfg.add_point((record.points[i]).clone());
}
}
}
}
ShapeTypeDimension::Measure => {
for record_num in 0..input.num_records {
let record = input.get_record(record_num);
for i in 0..record.points.len() {
sfg.add_pointm((record.points[i]).clone(), record.m_array[i]);
}
}
for record_num in 0..overlay.num_records {
let record = overlay.get_record(record_num);
for i in 0..record.points.len() {
if !overlapped_point[i + num_points_input] {
sfg.add_pointm(
(record.points[i]).clone(),
record.m_array[i],
);
}
}
}
}
ShapeTypeDimension::Z => {
for record_num in 0..input.num_records {
let record = input.get_record(record_num);
for i in 0..record.points.len() {
sfg.add_pointz(
(record.points[i]).clone(),
record.m_array[i],
record.z_array[i],
);
}
}
for record_num in 0..overlay.num_records {
let record = overlay.get_record(record_num);
for i in 0..record.points.len() {
if !overlapped_point[i + num_points_input] {
sfg.add_pointz(
(record.points[i]).clone(),
record.m_array[i],
record.z_array[i],
);
}
}
}
}
}
output.add_record(sfg);
output
.attributes
.add_record(vec![FieldData::Int(1i32)], false);
} else {
println!("WARNING: no features were output from the tool.");
}
}
ShapeType::PolyLine => {
output.header.shape_type = ShapeType::PolyLine;
let mut first_point_in_part: usize;
let mut last_point_in_part: usize;
let mut polylines: Vec<Polyline> = vec![];
for record_num in 0..input.num_records {
let record = input.get_record(record_num);
for part in 0..record.num_parts as usize {
first_point_in_part = record.parts[part] as usize;
last_point_in_part = if part < record.num_parts as usize - 1 {
record.parts[part + 1] as usize - 1
} else {
record.num_points as usize - 1
};
// Create a polyline from the part
let mut pl = Polyline::new(
&(record.points[first_point_in_part..=last_point_in_part]),
record_num,
);
pl.source_file = 1;
polylines.push(pl);
}
}
for record_num in 0..overlay.num_records {
let record = overlay.get_record(record_num);
for part in 0..record.num_parts as usize {
first_point_in_part = record.parts[part] as usize;
last_point_in_part = if part < record.num_parts as usize - 1 {
record.parts[part + 1] as usize - 1
} else {
record.num_points as usize - 1
};
// Create a polyline from the part
let mut pl = Polyline::new(
&(record.points[first_point_in_part..=last_point_in_part]),
record_num,
);
pl.source_file = 2;
polylines.push(pl);
}
}
// Break the polylines up into shorter lines at junction points.
let dimensions = 2;
let capacity_per_node = 64;
let mut tree = KdTree::with_capacity(dimensions, capacity_per_node);
let mut p: Point2D;
for i in 0..polylines.len() {
for j in 0..polylines[i].len() {
p = polylines[i][j];
tree.add([p.x, p.y], (i, j)).unwrap();
}
}
let mut num_neighbours: Vec<Vec<u8>> = Vec::with_capacity(polylines.len());
for i in 0..polylines.len() {
let mut line_num_neighbours = Vec::with_capacity(polylines[i].len());
for j in 0..polylines[i].len() {
p = polylines[i][j];
let ret = tree
.within(&[p.x, p.y], precision, &squared_euclidean)
.unwrap();
let mut n = 0u8;
for a in 0..ret.len() {
let k = ret[a].1;
if k.0 != i {
n += 1u8;
}
}
line_num_neighbours.push(n);
}
num_neighbours.push(line_num_neighbours);
if verbose {
progress = (100.0_f64 * (i + 1) as f64 / polylines.len() as f64) as usize;
if progress != old_progress {
println!("Progress: {}%", progress);
old_progress = progress;
}
}
}
let mut features_polylines: Vec<Polyline> = vec![];
let mut id: usize;
for i in 0..polylines.len() {
id = polylines[i].id;
let mut pl = Polyline::new_empty(id);
pl.vertices.push(polylines[i][0]);
pl.source_file = polylines[i].source_file;
for j in 1..polylines[i].len() {
if num_neighbours[i][j] > 1
|| num_neighbours[i][j] == 1 && num_neighbours[i][j - 1] == 0
|| num_neighbours[i][j] == 0 && num_neighbours[i][j - 1] == 1
{
// it's a junction, split the poly
pl.vertices.push(polylines[i][j]);
features_polylines.push(pl.clone());
pl = Polyline::new_empty(id);
pl.vertices.push(polylines[i][j]);
pl.source_file = polylines[i].source_file;
} else {
pl.vertices.push(polylines[i][j]);
}
}
features_polylines.push(pl.clone());
if verbose {
progress = (100.0_f64 * (i + 1) as f64 / polylines.len() as f64) as usize;
if progress != old_progress {
println!("Progress: {}%", progress);
old_progress = progress;
}
}
}
// Remove any zero-length line segments
for i in 0..features_polylines.len() {
for j in (1..features_polylines[i].len()).rev() {
if features_polylines[i][j].nearly_equals(&features_polylines[i][j - 1]) {
features_polylines[i].remove(j);
}
}
}
// Remove any single-point lines result from above.
let mut features_polylines2: Vec<Polyline> = vec![];
for i in (0..features_polylines.len()).rev() {
if features_polylines[i].len() > 1 {
features_polylines2.push(features_polylines[i].clone());
}
}
features_polylines = features_polylines2.clone();
drop(features_polylines2);
// Find duplicate polylines and remove them
let mut duplicate = vec![false; features_polylines.len()];
let mut duplicate_partner = vec![0; features_polylines.len()];
let mut num_duplicates = 0;
// let mut source_file: usize;
// let mut first_vertex1: Point2D;
// let mut first_vertex2: Point2D;
// for i in 0..features_polylines.len() {
// if !duplicate[i] {
// source_file = features_polylines[i].source_file;
// // first_vertex1 = features_polylines[i].first_vertex();
// for j in (i + 1)..features_polylines.len() {
// if source_file != features_polylines[j].source_file {
// if lines_are_equal(&features_polylines[i].vertices, &features_polylines[j].vertices) {
// num_duplicates += 1;
// }
// // first_vertex2 = features_polylines[j].first_vertex();
// // if first_vertex1.x == first_vertex2.x && first_vertex1.y == first_vertex2.y {
// // num_duplicates += 1;
// // }
// // if features_polylines[i] == features_polylines[j] {
// // // if features_polylines[i].equals(&features_polylines[j]) {
// // duplicate[i] = true;
// // duplicate[j] = true;
// // duplicate_partner[i] = j;
// // duplicate_partner[j] = i;
// // num_duplicates += 1;
// // }
// }
// }
// }
// if verbose {
// progress = (100.0_f64 * (i + 1) as f64 / features_polylines.len() as f64) as usize;
// if progress != old_progress {
// println!("Finding duplicate polylines ({}): {}%", num_duplicates, progress);
// old_progress = progress;
// }
// }
// }
let mut tree = KdTree::with_capacity(dimensions, capacity_per_node);
let mut p1: Point2D;
let mut p2: Point2D;
for i in 0..features_polylines.len() {
p1 = features_polylines[i].first_vertex();
tree.add([p1.x, p1.y], first_node_id(i)).unwrap();
p2 = features_polylines[i].last_vertex();
tree.add([p2.x, p2.y], last_node_id(i)).unwrap();
}
let mut j: usize;
let mut index: usize;
for i in 0..features_polylines.len() {
if !duplicate[i] {
p = features_polylines[i].first_vertex();
let ret = tree
.within(&[p.x, p.y], precision, &squared_euclidean)
.unwrap();
if ret.len() > 1 {
for a in 0..ret.len() {
index = *ret[a].1;
j = index / 2;
if j != i
&& features_polylines[j].source_file
!= features_polylines[i].source_file
{
if features_polylines[i]
.nearly_equals(&features_polylines[j], precision)
{
duplicate[i] = true;
duplicate[j] = true;
duplicate_partner[i] = j;
duplicate_partner[j] = i;
num_duplicates += 1;
}
}
}
}
}
if verbose {
progress =
(100.0_f64 * (i + 1) as f64 / features_polylines.len() as f64) as usize;
if progress != old_progress {
println!(
"Finding duplicate polylines ({}): {}%",
num_duplicates, progress
);
old_progress = progress;
}
}
}
let mut fid = 1i32;
for i in 0..features_polylines.len() {
if duplicate[i] && features_polylines[i].source_file == 1 {
let mut sfg = ShapefileGeometry::new(ShapeType::PolyLine);
sfg.add_part(&features_polylines[i].vertices);
output.add_record(sfg);
let mut out_atts = vec![FieldData::Null; num_attributes];
out_atts[0] = FieldData::Int(fid);
fid += 1;
let atts = input.attributes.get_record(features_polylines[i].id);
for att_num in 0..atts.len() {
if input_field_mapping[att_num] != 0 {
out_atts[input_field_mapping[att_num]] = atts[att_num].clone();
}
}
let atts = overlay
.attributes
.get_record(features_polylines[duplicate_partner[i]].id);
for att_num in 0..atts.len() {
if overlay_field_mapping[att_num] != 0 {
out_atts[overlay_field_mapping[att_num]] = atts[att_num].clone();
}
}
output.attributes.add_record(out_atts, false);
} else if !duplicate[i] {
let mut sfg = ShapefileGeometry::new(ShapeType::PolyLine);
sfg.add_part(&features_polylines[i].vertices);
output.add_record(sfg);
let mut out_atts = vec![FieldData::Null; num_attributes];
out_atts[0] = FieldData::Int(fid);
fid += 1;
if features_polylines[i].source_file == 2 {
let atts = overlay.attributes.get_record(features_polylines[i].id);
for att_num in 0..atts.len() {
if overlay_field_mapping[att_num] != 0 {
out_atts[overlay_field_mapping[att_num]] =
atts[att_num].clone();
}
}
} else {
let atts = input.attributes.get_record(features_polylines[i].id);
for att_num in 0..atts.len() {
if input_field_mapping[att_num] != 0 {
out_atts[input_field_mapping[att_num]] = atts[att_num].clone();
}
}
}
output.attributes.add_record(out_atts, false);
}
}
}
ShapeType::Polygon => {
// The polyline splitline method makes keeping track of
// measure and z data for split lines difficult. Regardless
// of the input shapefile dimension, the output will be XY only.
output.header.shape_type = ShapeType::Polygon;
let mut multipolylines: Vec<MultiPolyline> = vec![];
let mut is_part_a_hole: Vec<Vec<bool>> = vec![];
let mut first_point_in_part: usize;
let mut last_point_in_part: usize;
// Read in the features
for record_num in 0..overlay.num_records {
let record = overlay.get_record(record_num);
let mut mpl = MultiPolyline::new(record_num);
let mut holes = vec![false; record.num_parts as usize];
for part in 0..record.num_parts as usize {
first_point_in_part = record.parts[part] as usize;
last_point_in_part = if part < record.num_parts as usize - 1 {
record.parts[part + 1] as usize - 1
} else {
record.num_points as usize - 1
};
// Create a polyline from the part
let mut pl = Polyline::new(
&(record.points[first_point_in_part..=last_point_in_part]),
record_num,
);
pl.source_file = 1;
mpl.push(&pl);
if record.is_hole(part as i32) {
holes[part] = true;
}
}
multipolylines.push(mpl);
is_part_a_hole.push(holes);
}
for record_num in 0..input.num_records {
let record = input.get_record(record_num);
let mut mpl = MultiPolyline::new(record_num);
let mut holes = vec![false; record.num_parts as usize];
for part in 0..record.num_parts as usize {
first_point_in_part = record.parts[part] as usize;
last_point_in_part = if part < record.num_parts as usize - 1 {
record.parts[part + 1] as usize - 1
} else {
record.num_points as usize - 1
};
// Create a polyline from the part
let mut pl = Polyline::new(
&(record.points[first_point_in_part..=last_point_in_part]),
record_num,
);
pl.source_file = 2;
mpl.push(&pl);
if record.is_hole(part as i32) {
holes[part] = true;
}
}
multipolylines.push(mpl);
is_part_a_hole.push(holes);
}
// Perform the overlay on individual features.
let mut fid = 1i32;
for record_num in 0..multipolylines.len() {
let mut polygons: Vec<Polyline> = vec![];
let mut is_part_a_hole2: Vec<bool> = vec![];
// find overlapping features in other file
let mut overlaps_with_feature: bool;
for i in 0..multipolylines.len() {
overlaps_with_feature = false;
if multipolylines[i][0].source_file
!= multipolylines[record_num][0].source_file
{
if multipolylines[record_num]
.get_bounding_box()
.overlaps(multipolylines[i].get_bounding_box())
{
for j in 0..multipolylines[record_num].len() {
for k in 0..multipolylines[i].len() {
if poly_overlaps_poly(
&(multipolylines[record_num][j].vertices),
&(multipolylines[i][k].vertices),
) {
overlaps_with_feature = true;
break;
}
}
}
}
}
if overlaps_with_feature {
for j in 0..multipolylines[i].len() {
polygons.push(multipolylines[i][j].clone());
is_part_a_hole2.push(is_part_a_hole[i][j]);
}
}
}
if polygons.len() > 0 {
let feature_source_file = multipolylines[record_num][0].source_file;
for j in 0..multipolylines[record_num].len() {
polygons.push(multipolylines[record_num][j].clone());
is_part_a_hole2.push(is_part_a_hole[record_num][j]);
}
// Break the polygons up into line segments at junction points and endnodes.
let mut p: Point2D;
const DIMENSIONS: usize = 2;
const CAPACITY_PER_NODE: usize = 64;
let mut tree = KdTree::with_capacity(DIMENSIONS, CAPACITY_PER_NODE);
for i in 0..polygons.len() {
for j in 0..polygons[i].len() {
p = polygons[i][j];
if j > 0 && j < polygons[i].len() - 1 {
tree.add([p.x, p.y], (i, j, false)).unwrap();
} else {
// end node
tree.add([p.x, p.y], (i, j, true)).unwrap();
}
}
}
let mut features_polylines: Vec<Polyline> = vec![];
let mut id: usize;
let mut jn: usize;
let mut endnode_n: bool;
let mut dist1: f64;
let mut dist2: f64;
let mut num_neighbours: usize;
let mut neighbour_set = HashSet::new();
for i in 0..polygons.len() {
let mut line_node = vec![false; polygons[i].len()];
line_node[0] = true;
line_node[polygons[i].len() - 1] = true;
for j in 1..polygons[i].len() - 1 {
p = polygons[i][j];
let ret = tree