-
Notifications
You must be signed in to change notification settings - Fork 303
/
Copy pathgeos.cpp
1416 lines (1308 loc) · 46.9 KB
/
geos.cpp
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
#define GEOS_USE_ONLY_R_API // prevents using non-thread-safe GEOSxx functions without _r extension.
#include <geos_c.h>
#if GEOS_VERSION_MAJOR == 3
# if GEOS_VERSION_MINOR >= 4
# define HAVE340
# endif
# if GEOS_VERSION_MINOR >= 5
# define HAVE350
# endif
# if GEOS_VERSION_MINOR == 6
# if GEOS_VERSION_PATCH >= 1
# define HAVE361
# endif
# endif
# if GEOS_VERSION_MINOR >= 7
# define HAVE361
# define HAVE370
# endif
# if GEOS_VERSION_MINOR >= 8
# define HAVE380
# endif
# if GEOS_VERSION_MINOR >= 9
# define HAVE390
# endif
# if GEOS_VERSION_MINOR == 10
# if GEOS_VERSION_PATCH >= 1
# define HAVE3101
# endif
# endif
# if GEOS_VERSION_MINOR >= 10
# define HAVE310
# define HAVE3101
# endif
# if GEOS_VERSION_MINOR >= 11
# define HAVE311
# endif
#else
# if GEOS_VERSION_MAJOR > 3
# define HAVE340
# define HAVE350
# define HAVE370
# define HAVE361
# define HAVE380
# define HAVE390
# define HAVE310
# define HAVE3101
# define HAVE311
# endif
#endif
#include <Rcpp.h>
#include <memory>
#include <vector>
#include "wkb.h"
#include "hex.h"
typedef int (* dist_fn)(GEOSContextHandle_t, const GEOSGeometry *, const GEOSGeometry *, double *);
typedef int (* dist_parfn)(GEOSContextHandle_t, const GEOSGeometry *, const GEOSGeometry *, double, double *);
typedef char (* log_fn)(GEOSContextHandle_t, const GEOSGeometry *, const GEOSGeometry *);
typedef char (* log_prfn)(GEOSContextHandle_t, const GEOSPreparedGeometry *,
const GEOSGeometry *);
typedef GEOSGeom (* geom_fn)(GEOSContextHandle_t, const GEOSGeom, const GEOSGeom);
typedef GEOSGeom (* geom_fnp)(GEOSContextHandle_t, const GEOSGeom, const GEOSGeom, double grid_size);
static int notice = 0; // global var to silently catch notice of illegal geoms, e.g. non-closed rings
void cb(void *item, void *userdata) { // callback function for tree selection
std::vector<size_t> *ret = (std::vector<size_t> *) userdata;
ret->push_back(*((size_t *) item));
}
static void __errorHandler(const char *fmt, ...) { // #nocov start
char buf[BUFSIZ], *p;
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, (size_t) BUFSIZ, fmt, ap);
va_end(ap);
p = buf + strlen(buf) - 1;
if(strlen(buf) > 0 && *p == '\n') *p = '\0';
Rcpp::Function error(".stop_geos", Rcpp::Environment::namespace_env("sf"));
error(buf);
return; // #nocov end
}
static void __warningHandler(const char *fmt, ...) {
char buf[BUFSIZ], *p;
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, (size_t) BUFSIZ, fmt, ap);
va_end(ap);
p = buf + strlen(buf) - 1;
if(strlen(buf) > 0 && *p == '\n') *p = '\0';
Rcpp::Function warning("warning");
warning(buf);
return;
}
// #nocov start
static void __countErrorHandler(const char *fmt, void *userdata) {
int *i = (int *) userdata;
*i = *i + 1;
}
static void __emptyNoticeHandler(const char *fmt, void *userdata) { }
static void __checkInterruptFn(void*) {
R_CheckUserInterrupt();
}
static void __checkInterrupt() {
// Adapted from Rcpp/Interrupt.h
if (!R_ToplevelExec(__checkInterruptFn, nullptr)) {
GEOS_interruptRequest();
}
}
// #nocov end
GEOSContextHandle_t CPL_geos_init(void) {
#ifdef HAVE350
GEOSContextHandle_t ctxt = GEOS_init_r();
GEOSContext_setNoticeHandler_r(ctxt, __warningHandler);
GEOSContext_setErrorHandler_r(ctxt, __errorHandler);
GEOS_interruptRegisterCallback(__checkInterrupt);
return ctxt;
#else
return initGEOS_r((GEOSMessageHandler) __warningHandler, (GEOSMessageHandler) __errorHandler);
#endif
}
void CPL_geos_finish(GEOSContextHandle_t ctxt) {
#ifdef HAVE350
GEOS_finish_r(ctxt);
#else
finishGEOS_r(ctxt);
#endif
}
using PrepGeomPtr= std::unique_ptr<const GEOSPreparedGeometry, std::function<void(const GEOSPreparedGeometry*)> >;
using GeomPtr= std::unique_ptr<GEOSGeometry, std::function<void(GEOSGeometry*)> >;
using TreePtr= std::unique_ptr<GEOSSTRtree, std::function<void(GEOSSTRtree*)> >;
static GeomPtr geos_ptr(GEOSGeometry* g, GEOSContextHandle_t hGEOSctxt) {
auto deleter = std::bind(GEOSGeom_destroy_r, hGEOSctxt, std::placeholders::_1);
return GeomPtr(g, deleter);
}
static PrepGeomPtr geos_ptr(const GEOSPreparedGeometry* pg, GEOSContextHandle_t hGEOSctxt) {
auto deleter = std::bind(GEOSPreparedGeom_destroy_r, hGEOSctxt, std::placeholders::_1);
return PrepGeomPtr(pg, deleter);
}
static TreePtr geos_ptr(GEOSSTRtree* t, GEOSContextHandle_t hGEOSctxt) {
auto deleter = std::bind(GEOSSTRtree_destroy_r, hGEOSctxt, std::placeholders::_1);
return TreePtr(t, deleter);
}
static std::vector<GEOSGeometry*> to_raw(std::vector<GeomPtr> & g) {
std::vector<GEOSGeometry*> raw(g.size());
std::transform(g.begin(), g.end(), raw.begin(), [](GeomPtr & g) { return g.release(); });
return raw;
}
double geos_grid_size(Rcpp::List x) {
double precision = x.attr("precision");
if (precision != 0.0)
precision = 1. / precision;
return precision;
}
double geos_grid_size_xy(Rcpp::List x, Rcpp::List y) {
return std::max(geos_grid_size(x), geos_grid_size(y));
}
std::vector<GeomPtr> geometries_from_sfc(GEOSContextHandle_t hGEOSCtxt, Rcpp::List sfc, int *dim = NULL, bool stop_on_NULL = true) {
Rcpp::List sfc_cls = get_dim_sfc(sfc);
Rcpp::CharacterVector cls = sfc_cls["_cls"];
if (dim != NULL) {
Rcpp::IntegerVector sfc_dim = sfc_cls["_dim"];
if (sfc_dim.size() == 0)
Rcpp::stop("sfc_dim size 0: should not happen"); // #nocov
*dim = sfc_dim[0];
}
if (cls[0] == "XYM" || cls[0] == "XYZM")
Rcpp::stop("GEOS does not support XYM or XYZM geometries; use st_zm() to drop M\n"); // #nocov
#ifdef HAVE_390
double grid_size = geos_grid_size(sfc);
bool set_precision = grid_size != 0.0;
sfc.attr("precision") = 0.0; // so that CPL_write_wkb doesn't do the rounding;
#endif
Rcpp::List wkblst = CPL_write_wkb(sfc, true);
std::vector<GeomPtr> g(sfc.size());
GEOSWKBReader *wkb_reader = GEOSWKBReader_create_r(hGEOSCtxt);
for (int i = 0; i < sfc.size(); i++) {
Rcpp::RawVector r = wkblst[i];
g[i] = geos_ptr(GEOSWKBReader_read_r(hGEOSCtxt, wkb_reader, &(r[0]), r.size()), hGEOSCtxt);
if (g[i].get() == NULL) {
if (stop_on_NULL) {
Rcpp::Rcout << "While converting geometry of record: " << i << " to GEOS:" << std::endl;
Rcpp::stop("Illegal geometry found: fix manually, or filter out using st_is_valid() and is.na()\n");
}
}
#ifdef HAVE_390
else if (set_precision)
g[i] = geos_ptr(GEOSGeom_setPrecision_r(hGEOSCtxt, g[i].get(), grid_size, GEOS_PREC_VALID_OUTPUT), hGEOSCtxt);
#endif
}
GEOSWKBReader_destroy_r(hGEOSCtxt, wkb_reader);
return g;
}
Rcpp::List sfc_from_geometry(GEOSContextHandle_t hGEOSCtxt, std::vector<GeomPtr> & geom, int dim = 2, bool free = true) {
Rcpp::List out(geom.size());
GEOSWKBWriter *wkb_writer = GEOSWKBWriter_create_r(hGEOSCtxt);
GEOSWKBWriter_setOutputDimension_r(hGEOSCtxt, wkb_writer, dim);
// empty point, binary, with R NA's (not NaN's); GEOS can't WKB empty points,
// so we need to work around; see also https://trac.osgeo.org/postgis/ticket/3031
// > sf:::CPL_raw_to_hex(st_as_binary(st_point()))
// [1] "0101000000a20700000000f07fa20700000000f07f"
Rcpp::RawVector empty_point(CPL_hex_to_raw("0101000000a20700000000f07fa20700000000f07f")[0]);
for (size_t i = 0; i < geom.size(); i++) {
bool is_empty_point = false;
bool is_empty = GEOSisEmpty_r(hGEOSCtxt, geom[i].get()) == 1;
if (is_empty) {
char *geom_type = GEOSGeomType_r(hGEOSCtxt, geom[i].get());
is_empty_point = strcmp("Point", geom_type) == 0;
GEOSFree_r(hGEOSCtxt, geom_type);
}
if (is_empty_point)
out[i] = empty_point;
else {
size_t size;
unsigned char *buf = GEOSWKBWriter_write_r(hGEOSCtxt, wkb_writer, geom[i].get(), &size);
Rcpp::RawVector raw(size);
memcpy(&(raw[0]), buf, size);
GEOSFree_r(hGEOSCtxt, buf);
out[i] = raw;
}
}
GEOSWKBWriter_destroy_r(hGEOSCtxt, wkb_writer);
return CPL_read_wkb(out, true, false);
}
Rcpp::NumericVector get_dim(double dim0, double dim1) {
Rcpp::NumericVector dim(2);
dim(0) = dim0;
dim(1) = dim1;
return dim;
}
Rcpp::IntegerVector get_which(Rcpp::LogicalVector row) {
std::vector<int32_t> v;
for (int i = 0; i < row.length(); i++)
if (row(i))
v.push_back(i + 1);
return Rcpp::wrap(v);
}
bool chk_(char value) {
if (value == 2)
Rcpp::stop("GEOS exception"); // #nocov
return value; // 1: true, 0: false
}
log_fn which_geom_fn(const std::string op) {
if (op == "intersects")
return GEOSIntersects_r;
// else if (op == "disjoint")
// return GEOSDisjoint_r;
else if (op == "touches")
return GEOSTouches_r;
else if (op == "crosses")
return GEOSCrosses_r;
else if (op == "within")
return GEOSWithin_r;
else if (op == "contains")
return GEOSContains_r;
else if (op == "overlaps")
return GEOSOverlaps_r;
else if (op == "equals")
return GEOSEquals_r;
else if (op == "covers")
return GEOSCovers_r;
else if (op == "covered_by")
return GEOSCoveredBy_r;
Rcpp::stop("wrong value for op: please report as issue"); // unlikely to happen unless user wants to #nocov
return GEOSCoveredBy_r; // never reached; satisfy -Wreturn-type #nocov
}
log_prfn which_prep_geom_fn(const std::string op) {
if (op == "intersects")
return GEOSPreparedIntersects_r;
// else if (op == "disjoint")
// return GEOSPreparedDisjoint_r;
else if (op == "touches")
return GEOSPreparedTouches_r;
else if (op == "crosses")
return GEOSPreparedCrosses_r;
else if (op == "within")
return GEOSPreparedWithin_r;
else if (op == "contains")
return GEOSPreparedContains_r;
else if (op == "contains_properly")
return GEOSPreparedContainsProperly_r;
else if (op == "overlaps")
return GEOSPreparedOverlaps_r;
//else if (op == "equals")
// return GEOSPreparedEquals_r;
else if (op == "covers")
return GEOSPreparedCovers_r;
else if (op == "covered_by")
return GEOSPreparedCoveredBy_r;
Rcpp::stop("wrong value for op"); // unlikely to happen unless user wants to #nocov
return GEOSPreparedCoveredBy_r; // never reached; satisfy -Wreturn-type #nocov
}
/*
Rcpp::LogicalVector get_dense(std::vector<size_t> items, int length) {
Rcpp::LogicalVector rowi(length);
for (int j = 0; j < length; j++)
rowi(j) = false;
for (size_t j = 0; j < items.size(); j++)
rowi(items[j] - 1) = true; // items is 1-based
return rowi;
}
*/
// [[Rcpp::export]]
Rcpp::List CPL_geos_binop(Rcpp::List sfc0, Rcpp::List sfc1, std::string op, double par = 0.0,
std::string pattern = "", bool prepared = false) {
GEOSContextHandle_t hGEOSCtxt = CPL_geos_init();
std::vector<GeomPtr> gmv0 = geometries_from_sfc(hGEOSCtxt, sfc0, NULL);
std::vector<GeomPtr> gmv1 = geometries_from_sfc(hGEOSCtxt, sfc1, NULL);
Rcpp::List ret_list;
using namespace Rcpp; // so that later on the (i,_) works
if (op == "relate") { // return character matrix:
Rcpp::CharacterVector out(sfc0.length() * sfc1.length());
for (int i = 0; i < sfc0.length(); i++) {
for (int j = 0; j < sfc1.length(); j++) {
char *cp = GEOSRelate_r(hGEOSCtxt, gmv0[i].get(), gmv1[j].get());
if (cp == NULL) {
GEOSFree_r(hGEOSCtxt, cp); // #nocov
CPL_geos_finish(hGEOSCtxt); // #nocov
Rcpp::stop("GEOS error in GEOSRelate_r"); // #nocov
}
out[j * sfc0.length() + i] = cp;
GEOSFree_r(hGEOSCtxt, cp);
}
Rcpp::checkUserInterrupt();
}
out.attr("dim") = get_dim(sfc0.length(), sfc1.length());
ret_list = Rcpp::List::create(out);
} else if (op == "Euclidean" || op == "distance" || op == "Hausdorff" || op == "Frechet") { // return double matrix:
// dist_fn, dist_parfn
Rcpp::NumericMatrix out(sfc0.length(), sfc1.length());
if (par <= 0.0) {
dist_fn dist_function;
if (op == "Euclidean" || op == "distance")
dist_function = GEOSDistance_r;
else if (op == "Hausdorff")
dist_function = GEOSHausdorffDistance_r;
#ifdef HAVE370
else if (op == "Frechet")
dist_function = GEOSFrechetDistance_r;
#endif
else {
CPL_geos_finish(hGEOSCtxt); // #nocov
Rcpp::stop("distance function not supported"); // #nocov
}
for (size_t i = 0; i < gmv0.size(); i++) {
if (GEOSisEmpty_r(hGEOSCtxt, gmv0[i].get())) {
for (size_t j = 0; j < gmv1.size(); j++) // #nocov
out(i, j) = NA_REAL; // #nocov
} else for (size_t j = 0; j < gmv1.size(); j++) {
if (GEOSisEmpty_r(hGEOSCtxt, gmv1[j].get()))
out(i, j) = NA_REAL;
else {
double dist = -1.0;
if (dist_function(hGEOSCtxt, gmv0[i].get(), gmv1[j].get(), &dist) == 0) {
CPL_geos_finish(hGEOSCtxt); // #nocov
Rcpp::stop("GEOS error in GEOS_xx_Distance_r"); // #nocov
}
out(i, j) = dist;
}
}
Rcpp::checkUserInterrupt();
}
} else {
dist_parfn dist_function = NULL;
if (op == "Hausdorff")
dist_function = GEOSHausdorffDistanceDensify_r;
#ifdef HAVE370
else if (op == "Frechet")
dist_function = GEOSFrechetDistanceDensify_r;
#endif
else {
CPL_geos_finish(hGEOSCtxt); // #nocov
Rcpp::stop("distance function not supported"); // #nocov
}
for (size_t i = 0; i < gmv0.size(); i++) {
if (GEOSisEmpty_r(hGEOSCtxt, gmv0[i].get())) {
for (size_t j = 0; j < gmv1.size(); j++)
out(i, j) = NA_REAL;
} else for (size_t j = 0; j < gmv1.size(); j++) {
if (GEOSisEmpty_r(hGEOSCtxt, gmv1[j].get()))
out(i, j) = NA_REAL;
else {
double dist = -1.0;
if (dist_function(hGEOSCtxt, gmv0[i].get(), gmv1[j].get(), par, &dist) == 0) {
CPL_geos_finish(hGEOSCtxt); // #nocov
Rcpp::stop("GEOS error in GEOS_xx_Distance_r"); // #nocov
}
out(i, j) = dist;
}
}
Rcpp::checkUserInterrupt();
}
}
ret_list = Rcpp::List::create(out);
} else if (op == "is_within_distance") {
Rcpp::List sparsemat(sfc0.length());
for (size_t i = 0; i < gmv0.size(); i++) {
std::vector<size_t> sel;
for (size_t j = 0; j < gmv1.size(); j++) {
double dist = -1.0;
if (GEOSDistance_r(hGEOSCtxt, gmv0[i].get(), gmv1[j].get(), &dist) == 0) {
CPL_geos_finish(hGEOSCtxt); // #nocov
Rcpp::stop("GEOS error in GEOSDistance_r"); // #nocov
}
if (dist <= par)
sel.push_back(j + 1); // 1-based
}
sparsemat[i] = Rcpp::IntegerVector(sel.begin(), sel.end());
Rcpp::checkUserInterrupt();
}
ret_list = sparsemat;
} else if (gmv1.size()) {
// other cases: sparse matrix
Rcpp::List sparsemat(sfc0.length());
std::vector<size_t> items(gmv1.size());
TreePtr tree1 = geos_ptr(GEOSSTRtree_create_r(hGEOSCtxt, 10), hGEOSCtxt);
for (size_t i = 0; i < gmv1.size(); i++) {
items[i] = i;
if (! GEOSisEmpty_r(hGEOSCtxt, gmv1[i].get()))
GEOSSTRtree_insert_r(hGEOSCtxt, tree1.get(), gmv1[i].get(), &(items[i]));
}
if (op == "equals_exact") { // has it's own signature, needing `par':
for (int i = 0; i < sfc0.length(); i++) { // row
Rcpp::LogicalVector rowi(sfc1.length());
for (int j = 0; j < sfc1.length(); j++)
rowi(j) = chk_(GEOSEqualsExact_r(hGEOSCtxt, gmv0[i].get(), gmv1[j].get(), par));
sparsemat[i] = get_which(rowi);
Rcpp::checkUserInterrupt();
}
} else if (op == "relate_pattern") { // needing pattern
if (GEOSRelatePatternMatch_r(hGEOSCtxt, pattern.c_str(), "FF*FF****")) {
CPL_geos_finish(hGEOSCtxt);
Rcpp::stop("use st_disjoint for this pattern");
}
// all remaining can use tree:
for (int i = 0; i < sfc0.length(); i++) { // row
// pre-select sfc1's using tree:
std::vector<size_t> tree_sel, sel;
if (! GEOSisEmpty_r(hGEOSCtxt, gmv0[i].get()))
GEOSSTRtree_query_r(hGEOSCtxt, tree1.get(), gmv0[i].get(), cb, &tree_sel);
for (size_t j = 0; j < tree_sel.size(); j++)
if (chk_(GEOSRelatePattern_r(hGEOSCtxt, gmv0[i].get(), gmv1[tree_sel[j]].get(), pattern.c_str())))
sel.push_back(tree_sel[j] + 1); // 1-based
std::sort(sel.begin(), sel.end());
sparsemat[i] = Rcpp::IntegerVector(sel.begin(), sel.end());
Rcpp::checkUserInterrupt();
}
} else if (op == "disjoint") {
CPL_geos_finish(hGEOSCtxt); // #nocov
Rcpp::stop("disjoint should have been handled in R"); // #nocov
}
else { // anything else:
if (prepared) {
log_prfn logical_fn = which_prep_geom_fn(op);
for (int i = 0; i < sfc0.length(); i++) { // row
// pre-select sfc1's using tree:
std::vector<size_t> tree_sel, sel;
if (! GEOSisEmpty_r(hGEOSCtxt, gmv0[i].get()))
GEOSSTRtree_query_r(hGEOSCtxt, tree1.get(), gmv0[i].get(), cb, &tree_sel);
if (! tree_sel.empty()) {
PrepGeomPtr pr = geos_ptr(GEOSPrepare_r(hGEOSCtxt, gmv0[i].get()), hGEOSCtxt);
for (size_t j = 0; j < tree_sel.size(); j++)
if (chk_(logical_fn(hGEOSCtxt, pr.get(), gmv1[tree_sel[j]].get())))
sel.push_back(tree_sel[j] + 1); // 1-based
std::sort(sel.begin(), sel.end());
}
sparsemat[i] = Rcpp::IntegerVector(sel.begin(), sel.end());
Rcpp::checkUserInterrupt();
}
} else {
log_fn logical_fn = which_geom_fn(op);
for (int i = 0; i < sfc0.length(); i++) { // row
// pre-select sfc1's using tree:
std::vector<size_t> tree_sel, sel;
if (! GEOSisEmpty_r(hGEOSCtxt, gmv0[i].get()))
GEOSSTRtree_query_r(hGEOSCtxt, tree1.get(), gmv0[i].get(), cb, &tree_sel);
for (size_t j = 0; j < tree_sel.size(); j++)
if (chk_(logical_fn(hGEOSCtxt, gmv0[i].get(), gmv1[tree_sel[j]].get())))
sel.push_back(tree_sel[j] + 1); // 1-based
std::sort(sel.begin(), sel.end());
sparsemat[i] = Rcpp::IntegerVector(sel.begin(), sel.end());
Rcpp::checkUserInterrupt();
}
}
}
ret_list = sparsemat;
} else { // gmv1.size() == 0:
Rcpp::List sparsemat(sfc0.length());
for (size_t i = 0; i < gmv0.size(); i++)
sparsemat[i] = Rcpp::IntegerVector();
ret_list = sparsemat;
}
// clean up:
CPL_geos_finish(hGEOSCtxt);
return ret_list;
}
// [[Rcpp::export]]
Rcpp::CharacterVector CPL_geos_is_valid_reason(Rcpp::List sfc) {
GEOSContextHandle_t hGEOSCtxt = CPL_geos_init();
std::vector<GeomPtr> gmv = geometries_from_sfc(hGEOSCtxt, sfc, NULL, false);
Rcpp::CharacterVector out(gmv.size());
for (int i = 0; i < out.length(); i++) {
if (gmv[i].get() == NULL)
out[i] = NA_STRING;
else {
char *buf = GEOSisValidReason_r(hGEOSCtxt, gmv[i].get());
if (buf == NULL)
out[i] = NA_STRING; // #nocov
else {
out[i] = buf;
GEOSFree_r(hGEOSCtxt, buf);
}
}
}
CPL_geos_finish(hGEOSCtxt);
return out;
}
// #nocov start - no GEOS 3.8.0 on travis yet
// [[Rcpp::export]]
Rcpp::List CPL_geos_make_valid(Rcpp::List sfc, std::string method, bool keep_collapsed) {
GEOSContextHandle_t hGEOSCtxt = CPL_geos_init();
std::vector<GeomPtr> gmv = geometries_from_sfc(hGEOSCtxt, sfc, NULL);
std::vector<GeomPtr> out(gmv.size());
#ifdef HAVE380
# ifdef HAVE3101
GEOSMakeValidParams *makeValidParams = GEOSMakeValidParams_create_r(hGEOSCtxt);
if (method == "valid_linework")
GEOSMakeValidParams_setMethod_r(hGEOSCtxt, makeValidParams, GEOS_MAKE_VALID_LINEWORK);
else if (method == "valid_structure")
GEOSMakeValidParams_setMethod_r(hGEOSCtxt, makeValidParams, GEOS_MAKE_VALID_STRUCTURE);
else
Rcpp::stop("geos_method not recognized");
GEOSMakeValidParams_setKeepCollapsed_r(hGEOSCtxt, makeValidParams, (int) keep_collapsed);
for (size_t i = 0; i < gmv.size(); i++)
gmv[i] = geos_ptr(GEOSMakeValidWithParams_r(hGEOSCtxt, gmv[i].get(), makeValidParams), hGEOSCtxt);
GEOSMakeValidParams_destroy_r(hGEOSCtxt, makeValidParams);
# else
for (size_t i = 0; i < gmv.size(); i++)
gmv[i] = geos_ptr(GEOSMakeValid_r(hGEOSCtxt, gmv[i].get()), hGEOSCtxt);
# endif
#else
Rcpp::stop("this shouldn't happen: st_make_valid should use lwgeom");
#endif
Rcpp::List ret = sfc_from_geometry(hGEOSCtxt, gmv);
CPL_geos_finish(hGEOSCtxt);
return ret;
}
// #nocov end
// [[Rcpp::export]]
Rcpp::LogicalVector CPL_geos_is_valid(Rcpp::List sfc, bool NA_on_exception = true) {
GEOSContextHandle_t hGEOSCtxt = CPL_geos_init();
notice = 0;
if (NA_on_exception) {
/*
if (sfc.size() > 1)
Rcpp::stop("NA_on_exception will only work reliably with length 1 sfc objects"); // #nocov
*/
#ifdef HAVE350
GEOSContext_setNoticeMessageHandler_r(hGEOSCtxt,
(GEOSMessageHandler_r) __emptyNoticeHandler, (void *) ¬ice);
GEOSContext_setErrorMessageHandler_r(hGEOSCtxt,
(GEOSMessageHandler_r) __countErrorHandler, (void *) ¬ice);
#endif
}
Rcpp::LogicalVector out(sfc.size());
for (int i = 0; i < out.length(); i++) {
// get geometry i:
Rcpp::List geom_i = Rcpp::List::create(sfc[i]);
geom_i.attr("precision") = sfc.attr("precision");
geom_i.attr("class") = sfc.attr("class");
geom_i.attr("crs") = sfc.attr("crs");
SEXP classes = sfc.attr("classes");
if (classes != R_NilValue) {
Rcpp::CharacterVector cl = sfc.attr("classes");
geom_i.attr("classes") = cl[i];
}
std::vector<GeomPtr> gmv = geometries_from_sfc(hGEOSCtxt, geom_i, NULL, false); // where notice might be set!
int ret;
if (gmv[0].get() == NULL)
ret = 2;
else
ret = GEOSisValid_r(hGEOSCtxt, gmv[0].get());
if (NA_on_exception && (ret == 2 || notice != 0))
out[i] = NA_LOGICAL; // no need to set notice back here, as we only consider 1 geometry #nocov
else
out[i] = chk_(ret);
notice = 0; // reset notice.
}
#ifdef HAVE350
GEOSContext_setNoticeHandler_r(hGEOSCtxt, __warningHandler);
GEOSContext_setErrorHandler_r(hGEOSCtxt, __errorHandler);
#endif
CPL_geos_finish(hGEOSCtxt);
return out;
}
// [[Rcpp::export]]
Rcpp::LogicalVector CPL_geos_is_simple(Rcpp::List sfc) {
GEOSContextHandle_t hGEOSCtxt = CPL_geos_init();
Rcpp::LogicalVector out(sfc.length());
std::vector<GeomPtr> g = geometries_from_sfc(hGEOSCtxt, sfc, NULL);
for (size_t i = 0; i < g.size(); i++) {
out[i] = chk_(GEOSisSimple_r(hGEOSCtxt, g[i].get()));
}
CPL_geos_finish(hGEOSCtxt);
return out;
}
// [[Rcpp::export]]
Rcpp::LogicalVector CPL_geos_is_empty(Rcpp::List sfc) {
GEOSContextHandle_t hGEOSCtxt = CPL_geos_init();
Rcpp::LogicalVector out(sfc.length());
std::vector<GeomPtr> g = geometries_from_sfc(hGEOSCtxt, sfc, NULL);
for (size_t i = 0; i < g.size(); i++) {
out[i] = chk_(GEOSisEmpty_r(hGEOSCtxt, g[i].get()));
}
CPL_geos_finish(hGEOSCtxt);
return out;
}
// [[Rcpp::export]]
Rcpp::List CPL_geos_normalize(Rcpp::List sfc) { // #nocov start
int dim = 2;
GEOSContextHandle_t hGEOSCtxt = CPL_geos_init();
std::vector<GeomPtr> gmv = geometries_from_sfc(hGEOSCtxt, sfc, &dim);
for (int i = 0; i < sfc.size(); i++) {
if (GEOSNormalize_r(hGEOSCtxt, gmv[i].get()) == -1)
Rcpp::stop("normalize: GEOS exception");
}
Rcpp::List out(sfc_from_geometry(hGEOSCtxt, gmv, dim));
CPL_geos_finish(hGEOSCtxt);
out.attr("precision") = sfc.attr("precision");
out.attr("crs") = sfc.attr("crs");
return out;
} // #nocov end
// [[Rcpp::export]]
Rcpp::List CPL_geos_union(Rcpp::List sfc, bool by_feature = false, bool is_coverage = false) {
#ifndef HAVE380
if (is_coverage) {
Rcpp::warning("ignoring 'is_coverage = TRUE' which requires GEOS version 3.8 or greater");
is_coverage = false;
}
#endif
if (sfc.size() == 0)
return sfc; // #nocov
int dim = 2;
GEOSContextHandle_t hGEOSCtxt = CPL_geos_init();
std::vector<GeomPtr> gmv = geometries_from_sfc(hGEOSCtxt, sfc, &dim);
std::vector<GeomPtr> gmv_out(by_feature ? sfc.size() : 1);
if (by_feature) {
for (int i = 0; i < sfc.size(); i++) {
gmv_out[i] = geos_ptr(GEOSUnaryUnion_r(hGEOSCtxt, gmv[i].get()), hGEOSCtxt);
}
} else {
bool all_inputs_same = true;
// check to see if all geometries are identical, as in a call to summarize(..., do_union=TRUE)
for (size_t i = 1; i < gmv.size(); i++) {
if (!GEOSEqualsExact_r(hGEOSCtxt, gmv[0].get(), gmv[i].get(), 0.0)) {
all_inputs_same = false;
break;
}
}
if (all_inputs_same) {
gmv_out[0] = std::move(gmv[0]);
} else {
GeomPtr gc = geos_ptr(GEOSGeom_createCollection_r(hGEOSCtxt, GEOS_GEOMETRYCOLLECTION, to_raw(gmv).data(), gmv.size()), hGEOSCtxt);
#ifdef HAVE380
if (is_coverage)
gmv_out[0] = geos_ptr(GEOSCoverageUnion_r(hGEOSCtxt, gc.get()), hGEOSCtxt);
else
#endif
gmv_out[0] = geos_ptr(GEOSUnaryUnion_r(hGEOSCtxt, gc.get()), hGEOSCtxt);
}
}
Rcpp::List out(sfc_from_geometry(hGEOSCtxt, gmv_out, dim));
CPL_geos_finish(hGEOSCtxt);
out.attr("precision") = sfc.attr("precision");
out.attr("crs") = sfc.attr("crs");
return out;
}
// [[Rcpp::export]]
Rcpp::List CPL_geos_snap(Rcpp::List sfc0, Rcpp::List sfc1, Rcpp::NumericVector tolerance) {
int dim = 2;
GEOSContextHandle_t hGEOSCtxt = CPL_geos_init();
std::vector<GeomPtr> gmv0 = geometries_from_sfc(hGEOSCtxt, sfc0, &dim);
std::vector<GeomPtr> gmv1 = geometries_from_sfc(hGEOSCtxt, sfc1, &dim);
GeomPtr gc;
if (gmv1.size() > 1)
gc = geos_ptr(GEOSGeom_createCollection_r(hGEOSCtxt, GEOS_GEOMETRYCOLLECTION,
to_raw(gmv1).data(), gmv1.size()), hGEOSCtxt);
else
gc = std::move(gmv1[0]);
std::vector<GeomPtr> gmv_out(sfc0.size());
for (int i = 0; i < sfc0.size(); i++) {
gmv_out[i] = geos_ptr(GEOSSnap_r(hGEOSCtxt, gmv0[i].get(), gc.get(), tolerance[i]), hGEOSCtxt);
if (gmv_out[i] == NULL)
Rcpp::stop("snap: GEOS exception"); // #nocov
}
Rcpp::List out(sfc_from_geometry(hGEOSCtxt, gmv_out, dim));
CPL_geos_finish(hGEOSCtxt);
out.attr("precision") = sfc0.attr("precision");
out.attr("crs") = sfc0.attr("crs");
return out;
}
GEOSGeometry *chkNULL(GEOSGeometry *value) {
if (value == NULL)
Rcpp::stop("GEOS exception"); // #nocov
Rcpp::checkUserInterrupt();
return value;
}
// [[Rcpp::export]]
Rcpp::List CPL_geos_op(std::string op, Rcpp::List sfc,
Rcpp::NumericVector bufferDist, Rcpp::IntegerVector nQuadSegs,
Rcpp::NumericVector dTolerance, Rcpp::LogicalVector preserveTopology,
int bOnlyEdges = 1,
Rcpp::IntegerVector endCapStyle = 0, Rcpp::IntegerVector joinStyle = 0,
Rcpp::NumericVector mitreLimit = 1, Rcpp::LogicalVector singleside = 0)
{
int dim = 2;
GEOSContextHandle_t hGEOSCtxt = CPL_geos_init();
std::vector<GeomPtr> g = geometries_from_sfc(hGEOSCtxt, sfc, &dim);
std::vector<GeomPtr> out(sfc.length());
if (op == "buffer") {
if (bufferDist.size() != (int) g.size())
Rcpp::stop("invalid dist argument"); // #nocov
for (size_t i = 0; i < g.size(); i++)
out[i] = geos_ptr(chkNULL(GEOSBuffer_r(hGEOSCtxt, g[i].get(), bufferDist[i], nQuadSegs[i])), hGEOSCtxt);
} else if (op == "buffer_with_style") {
GEOSBufferParams *bufferparams = GEOSBufferParams_create_r(hGEOSCtxt);
for (size_t i = 0; i < g.size(); i++) {
if (GEOSBufferParams_setEndCapStyle_r(hGEOSCtxt, bufferparams, endCapStyle[i]) &&
GEOSBufferParams_setJoinStyle_r(hGEOSCtxt, bufferparams, joinStyle[i]) &&
GEOSBufferParams_setMitreLimit_r(hGEOSCtxt, bufferparams, mitreLimit[i]) &&
GEOSBufferParams_setQuadrantSegments_r(hGEOSCtxt, bufferparams, nQuadSegs[i]) &&
GEOSBufferParams_setSingleSided_r(hGEOSCtxt, bufferparams, singleside[i]))
// out[i] = geos_ptr(chkNULL(GEOSBufferWithStyle_r(hGEOSCtxt, g[i].get(), bufferDist[i], nQuadSegs[i], endCapStyle[i], joinStyle[i], mitreLimit[i])), hGEOSCtxt);
out[i] = geos_ptr(chkNULL(GEOSBufferWithParams_r(hGEOSCtxt, g[i].get(),
bufferparams, bufferDist[i])), hGEOSCtxt);
else
Rcpp::stop("invalid buffer parameters"); // #nocov
}
GEOSBufferParams_destroy_r(hGEOSCtxt, bufferparams);
} else if (op == "boundary") {
for (size_t i = 0; i < g.size(); i++)
out[i] = geos_ptr(chkNULL(GEOSBoundary_r(hGEOSCtxt, g[i].get())), hGEOSCtxt);
} else if (op == "concave_hull") {
#ifdef HAVE311
double ratio = bufferDist[0];
unsigned int allowHoles = preserveTopology[0];
for (size_t i = 0; i < g.size(); i++)
out[i] = geos_ptr(chkNULL(GEOSConcaveHull_r(hGEOSCtxt, g[i].get(), ratio, allowHoles)), hGEOSCtxt);
#else
Rcpp::stop("st_concave_hull requires GEOS >= 3.11");
#endif
} else if (op == "convex_hull") {
for (size_t i = 0; i < g.size(); i++)
out[i] = geos_ptr(chkNULL(GEOSConvexHull_r(hGEOSCtxt, g[i].get())), hGEOSCtxt);
} else if (op == "simplify") {
for (size_t i = 0; i < g.size(); i++)
out[i] = geos_ptr(
preserveTopology[i] ?
chkNULL(GEOSTopologyPreserveSimplify_r(hGEOSCtxt, g[i].get(),
dTolerance[i])) :
chkNULL(GEOSSimplify_r(hGEOSCtxt, g[i].get(), dTolerance[i])), hGEOSCtxt);
} else if (op == "linemerge") {
for (size_t i = 0; i < g.size(); i++)
out[i] = geos_ptr(chkNULL(GEOSLineMerge_r(hGEOSCtxt, g[i].get())), hGEOSCtxt);
} else if (op == "linemergedirected") {
#ifdef HAVE311
for (size_t i = 0; i < g.size(); i++)
out[i] = geos_ptr(chkNULL(GEOSLineMergeDirected_r(hGEOSCtxt, g[i].get())), hGEOSCtxt);
#else
Rcpp::stop("directed line merge requires GEOS >= 3.11");
#endif
} else if (op == "polygonize") {
for (size_t i = 0; i < g.size(); i++) {
const GEOSGeometry* gi = g[i].get();
out[i] = geos_ptr(chkNULL(GEOSPolygonize_r(hGEOSCtxt, &gi, 1)), hGEOSCtxt);
}
} else if (op == "centroid") {
for (size_t i = 0; i < g.size(); i++) {
out[i] = geos_ptr(chkNULL(GEOSGetCentroid_r(hGEOSCtxt, g[i].get())), hGEOSCtxt);
}
} else
if (op == "node") {
for (size_t i = 0; i < g.size(); i++) {
out[i] = geos_ptr(chkNULL(GEOSNode_r(hGEOSCtxt, g[i].get())), hGEOSCtxt);
}
} else if (op == "point_on_surface") {
for (size_t i = 0; i < g.size(); i++) {
out[i] = geos_ptr(chkNULL(GEOSPointOnSurface_r(hGEOSCtxt, g[i].get())), hGEOSCtxt);
}
} else
#ifdef HAVE340
if (op == "triangulate") {
for (size_t i = 0; i < g.size(); i++)
out[i] = geos_ptr(chkNULL(GEOSDelaunayTriangulation_r(hGEOSCtxt, g[i].get(),
dTolerance[i], bOnlyEdges)), hGEOSCtxt);
} else
#endif
#ifdef HAVE310
if (op == "triangulate_constrained") {
for (size_t i = 0; i < g.size(); i++)
out[i] = geos_ptr(chkNULL(GEOSConstrainedDelaunayTriangulation_r(hGEOSCtxt, g[i].get())),
hGEOSCtxt);
} else
#endif
#ifdef HAVE370
if (op == "reverse") {
for (size_t i = 0; i < g.size(); i++) {
out[i] = geos_ptr(chkNULL(GEOSReverse_r(hGEOSCtxt, g[i].get())), hGEOSCtxt);
}
} else
#endif
#ifdef HAVE390
if (op == "inscribed_circle") {
for (size_t i = 0; i < g.size(); i++) {
out[i] = geos_ptr(chkNULL(GEOSMaximumInscribedCircle_r(hGEOSCtxt, g[i].get(),
dTolerance[i])), hGEOSCtxt);
}
} else if (op == "minimum_rotated_rectangle") {
for (size_t i = 0; i < g.size(); i++) {
out[i] = geos_ptr(chkNULL(GEOSMinimumRotatedRectangle_r(hGEOSCtxt, g[i].get())), hGEOSCtxt);
}
} else
#endif
Rcpp::stop("invalid operation"); // #nocov
Rcpp::List ret(sfc_from_geometry(hGEOSCtxt, out, dim));
CPL_geos_finish(hGEOSCtxt);
ret.attr("precision") = sfc.attr("precision");
ret.attr("crs") = sfc.attr("crs");
return ret;
}
// [[Rcpp::export]]
Rcpp::List CPL_geos_voronoi(Rcpp::List sfc, Rcpp::List env, double dTolerance = 0.0, int bOnlyEdges = 1) {
int dim = 2;
GEOSContextHandle_t hGEOSCtxt = CPL_geos_init();
std::vector<GeomPtr> g = geometries_from_sfc(hGEOSCtxt, sfc, &dim);
std::vector<GeomPtr> out(sfc.length());
#ifdef HAVE350
switch (env.size()) {
case 0: ;
case 1: {
std::vector<GeomPtr> g_env = geometries_from_sfc(hGEOSCtxt, env);
for (size_t i = 0; i < g.size(); i++) {
out[i] = geos_ptr(chkNULL(GEOSVoronoiDiagram_r(hGEOSCtxt, g[i].get(),
g_env.size() ? g_env[0].get() : NULL, dTolerance, bOnlyEdges)), hGEOSCtxt);
}
break;
}
default:
Rcpp::stop("env should have length 0 or 1"); // #nocov
}
#else
Rcpp::stop("voronoi diagrams require a GEOS version >= 3.5.0"); // #nocov
#endif
Rcpp::List ret(sfc_from_geometry(hGEOSCtxt, out, dim));
CPL_geos_finish(hGEOSCtxt);
ret.attr("precision") = sfc.attr("precision");
ret.attr("crs") = sfc.attr("crs");
return ret;
}
// [[Rcpp::export]]
Rcpp::List CPL_geos_op2(std::string op, Rcpp::List sfcx, Rcpp::List sfcy) {
using namespace Rcpp; // so that later on the (_,1) works
int dim = 2;
GEOSContextHandle_t hGEOSCtxt = CPL_geos_init();
std::vector<GeomPtr> x = geometries_from_sfc(hGEOSCtxt, sfcx, &dim);
std::vector<GeomPtr> y = geometries_from_sfc(hGEOSCtxt, sfcy, &dim);
std::vector<GeomPtr> out;
std::vector<double> index_x, index_y;
std::vector<size_t> items(x.size());
#ifdef HAVE_390
double grid_size = geos_grid_size_xy(sfcx, sfcy);
#endif
if (op == "intersection") {
bool tree_empty = true;
TreePtr tree = geos_ptr(GEOSSTRtree_create_r(hGEOSCtxt, 10), hGEOSCtxt);
for (size_t i = 0; i < x.size(); i++) {
items[i] = i;
if (! GEOSisEmpty_r(hGEOSCtxt, x[i].get())) {
GEOSSTRtree_insert_r(hGEOSCtxt, tree.get(), x[i].get(), &(items[i]));
tree_empty = false;
}
}
for (size_t i = 0; i < y.size(); i++) {
// select x's using tree:
std::vector<size_t> sel;
sel.reserve(x.size());
if (! GEOSisEmpty_r(hGEOSCtxt, y[i].get()) && ! tree_empty)
GEOSSTRtree_query_r(hGEOSCtxt, tree.get(), y[i].get(), cb, &sel);
std::sort(sel.begin(), sel.end());
for (size_t item = 0; item < sel.size(); item++) {
size_t j = sel[item];
#ifndef HAVE_390
GeomPtr geom = geos_ptr(GEOSIntersection_r(hGEOSCtxt, x[j].get(), y[i].get()), hGEOSCtxt);
#else
GeomPtr geom = geos_ptr(GEOSIntersectionPrec_r(hGEOSCtxt, x[j].get(), y[i].get(), grid_size), hGEOSCtxt);
#endif
if (geom == nullptr)
Rcpp::stop("GEOS exception"); // #nocov
if (! chk_(GEOSisEmpty_r(hGEOSCtxt, geom.get()))) {
index_x.push_back(j + 1);
index_y.push_back(i + 1);
out.push_back(std::move(geom)); // keep
}
Rcpp::checkUserInterrupt();
}
}
} else {
#ifndef HAVE_390
geom_fn geom_function;
if (op == "union")
geom_function = (geom_fn) GEOSUnion_r;
else if (op == "difference")
geom_function = (geom_fn) GEOSDifference_r;