-
Notifications
You must be signed in to change notification settings - Fork 95
/
raster_methods.cpp
6242 lines (5520 loc) · 143 KB
/
raster_methods.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
// Copyright (c) 2018-2023 Robert J. Hijmans
//
// This file is part of the "spat" library.
//
// spat is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// spat is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with spat. If not, see <http://www.gnu.org/licenses/>.
#include "spatRasterMultiple.h"
#include "recycle.h"
#include "vecmath.h"
#include "vecmathse.h"
#include <cmath>
#include <functional>
#include "math_utils.h"
#include "file_utils.h"
#include "string_utils.h"
#include "sort.h"
/*
std::vector<double> flat(std::vector<std::vector<double>> v) {
unsigned s1 = v.size();
unsigned s2 = v[0].size();
std::size_t s = s1 * s2;
std::vector<double> result(s);
for (size_t i=0; i<s1; i++) {
for (size_t j=0; j<s2; j++) {
result[i*s2+j] = v[i][j];
}
}
return result;
}
*/
/*
SpatRaster SpatRaster::selectHighest(size_t n, bool low, SpatOptions &opt) {
SpatVector out;
if (nlyr() > 1) {
SpatOptions ops(opt);
out.addWarning("only processing the first layer");
std::vector<unsigned> lyr = {0};
*this = subset(lyr, ops);
}
if (!hasValues()) {
return(out);
}
if (n >= ncell()) {
return isnotnan(opt);
}
std::vector<double> sel;
if (!readStart()) {
return(out);
}
BlockSize bs = getBlockSize(opt);
for (size_t i = 0; i < bs.n; i++) {
std::vector<double> v;
readBlock(v, out.bs, i);
for (size_t j=0; j<v.size(); j++) {
}
readStop();
return(out);
}
*/
SpatExtent SpatRaster::ext_from_rc(int_64 r1, int_64 r2, int_64 c1, int_64 c2) {
SpatExtent e = getExtent();
double xrs = xres();
double yrs = yres();
int_64 nr = nrow();
int_64 nc = ncol();
c1 = std::min(std::max(c1, (int_64)0), nc);
c2 = std::min(std::max(c2, (int_64)0), nc);
if (c1 > c2) {
std::swap(c1, c2);
}
r1 = std::min(std::max(r1, (int_64)0), nr);
r2 = std::min(std::max(r2, (int_64)0), nr);
if (r1 > r2) {
std::swap(r1, r2);
}
double xn = xFromCol(c1) - 0.5 * xrs;
double xx = xFromCol(c2) + 0.5 * xrs;
double yx = yFromRow(r1) + 0.5 * yrs;
double yn = yFromRow(r2) - 0.5 * yrs;
return SpatExtent(xn, xx, yn, yx);
}
SpatExtent SpatRaster::ext_from_cell( double cell) {
std::vector<double> cells = {cell};
std::vector<std::vector<int_64>> rc = rowColFromCell(cells);
return ext_from_rc(rc[0][0], rc[0][0], rc[1][0], rc[1][0]);
}
std::vector<double> SpatRaster::get_tiles_extent(SpatRaster x, bool expand, std::vector<int> buffer) {
x = x.geometry(1, false, false, false);
SpatExtent e = getExtent();
recycle(buffer, 2);
std::vector<double> ebuf = {buffer[0] * xres(), buffer[1] * yres()};
SpatOptions opt;
if (expand) {
x = x.extend(e, "out", NAN, opt);
}
x = x.crop(e, "out", false, opt);
std::vector<size_t> d(x.ncell());
std::iota(d.begin(), d.end(), 1);
std::vector<std::vector<double>> ee(4);
for (size_t i=0; i<4; i++) {
ee[i].reserve(d.size());
}
SpatRaster y = geometry(1, false, false, false);
for (size_t i=0; i<d.size(); i++) {
SpatExtent exi = x.ext_from_cell(i);
SpatRaster out = y.crop(exi, "near", false, opt);
SpatExtent ye = out.getExtent();
ee[0].push_back(ye.xmin);
ee[1].push_back(ye.xmax);
ee[2].push_back(ye.ymin);
ee[3].push_back(ye.ymax);
}
size_t nc = x.ncol();
size_t nr = x.nrow();
//avoid under- and overshoots introduced by rounding, #1564
for (size_t i=0; i<nr; i++) {
for (size_t j=0; j<nc; j++) {
size_t k = (i*nc) + j;
if (j > 0) {
ee[0][k] = ee[1][k-1];
}
if (i > 0) {
ee[3][k] = ee[2][k-nc];
}
}
}
for (size_t i=0; i<ee[0].size(); i++) {
ee[0][i] = ee[0][i] - ebuf[0];
ee[1][i] = ee[1][i] + ebuf[0];
ee[2][i] = ee[2][i] - ebuf[1];
ee[3][i] = ee[3][i] + ebuf[1];
}
std::vector<double> out;
out.reserve(ee[0].size() * 4);
for (size_t i=0; i<4; i++) {
out.insert(out.end(), ee[i].begin(), ee[i].end());
}
return out;
}
std::vector<std::string> SpatRaster::make_tiles(SpatRaster x, bool expand, std::vector<int> buffer, bool narm, std::string filename, SpatOptions &opt) {
std::vector<std::string> ff;
if (!hasValues()) {
setError("input raster has no values");
return ff;
}
x = x.geometry(1, false, false, false);
SpatExtent e = getExtent();
recycle(buffer, 2);
std::vector<double> ebuf = {buffer[0] * xres(), buffer[1] * yres()};
SpatOptions ops(opt);
if (expand) {
x = x.extend(e, "out", NAN, ops);
}
x = x.crop(e, "out", false, ops);
std::vector<size_t> d(x.ncell());
std::iota(d.begin(), d.end(), 1);
std::string fext = getFileExt(filename);
std::string f = noext(filename);
ff.reserve(d.size());
size_t nl = nlyr();
bool overwrite = opt.get_overwrite();
for (size_t i=0; i<d.size(); i++) {
std::string fout = f + std::to_string(d[i]) + fext;
if (file_exists(fout) && (!overwrite)) {
ff.push_back(fout);
continue;
}
SpatExtent exi = x.ext_from_cell(i);
exi.xmin = exi.xmin - ebuf[0];
exi.xmax = exi.xmax + ebuf[0];
exi.ymin = exi.ymin - ebuf[1];
exi.ymax = exi.ymax + ebuf[1];
opt.set_filenames({fout});
SpatRaster out = crop(exi, "near", false, opt);
if (out.hasError()) {
setError(out.getError());
return ff;
}
if ( out.hasValues() ) {
if (narm) {
std::vector<double> rmin = out.range_min();
size_t cnt = 0;
for (double &v : rmin) {
if (std::isnan(v)) cnt++;
}
if (cnt == nl) {
remove(fout.c_str());
continue;
}
}
ff.push_back(fout);
}
}
return ff;
}
std::vector<double> SpatRaster::get_tiles_extent_vect(SpatVector x, bool expand, std::vector<int> buffer) {
std::vector<double> ee;
if (x.type() != "polygons") {
setError("The SpatVector must have a polygons geometry");
return ee;
}
SpatExtent e = getExtent();
std::vector<size_t> d(x.size());
std::iota(d.begin(), d.end(), 1);
ee.reserve(d.size() * 4);
SpatOptions opt;
SpatRaster y = geometry(1, false, false, false);
recycle(buffer, 2);
std::vector<double> ebuf = {buffer[0] * xres(), buffer[1] * yres()};
for (size_t i=0; i<d.size(); i++) {
SpatRaster out;
SpatExtent exi = x.geoms[i].extent;
exi.xmin = exi.xmin - ebuf[0];
exi.xmax = exi.xmax + ebuf[0];
exi.ymin = exi.ymin - ebuf[1];
exi.ymax = exi.ymax + ebuf[1];
if (!e.intersects(exi)) continue;
if (expand) {
out = y.crop(exi, "near", false, opt);
out = out.extend(exi, "out", NAN, opt);
} else {
out = y.crop(exi, "near", false, opt);
}
if (out.hasError()) {
setError(out.getError());
return ee;
}
SpatExtent xe = out.getExtent();
ee.push_back(xe.xmin);
ee.push_back(xe.xmax);
ee.push_back(xe.ymin);
ee.push_back(xe.ymax);
}
return ee;
}
std::vector<std::string> SpatRaster::make_tiles_vect(SpatVector x, bool expand, std::vector<int> buffer, bool narm, std::string filename, SpatOptions &opt) {
std::vector<std::string> ff;
if (!hasValues()) {
setError("input raster has no values");
return ff;
}
if (x.type() != "polygons") {
setError("The SpatVector must have a polygons geometry");
return ff;
}
SpatExtent e = getExtent();
SpatOptions ops(opt);
std::vector<size_t> d(x.size());
std::iota(d.begin(), d.end(), 1);
std::string fext = getFileExt(filename);
std::string f = noext(filename);
ff.reserve(d.size());
size_t nl = nlyr();
bool overwrite = opt.get_overwrite();
recycle(buffer, 2);
std::vector<double> ebuf = {buffer[0] * xres(), buffer[1] * yres()};
for (size_t i=0; i<d.size(); i++) {
std::string fout = f + std::to_string(d[i]) + fext;
if (file_exists(fout) && (!overwrite)) {
ff.push_back(fout);
continue;
}
opt.set_filenames( {fout} );
SpatRaster out;
SpatExtent exi = x.geoms[i].extent;
exi.xmin = exi.xmin - ebuf[0];
exi.xmax = exi.xmax + ebuf[0];
exi.ymin = exi.ymin - ebuf[1];
exi.ymax = exi.ymax + ebuf[1];
if (!e.intersects(exi)) continue;
if (expand) {
out = crop(exi, "near", false, ops);
out = out.extend(exi, "out", NAN, opt);
} else {
out = crop(exi, "near", false, opt);
}
if (out.hasError()) {
setError(out.getError());
return ff;
}
if ( out.hasValues() ) {
if (narm) {
std::vector<double> rmin = out.range_min();
size_t cnt = 0;
for (double &v : rmin) {
if (std::isnan(v)) cnt++;
}
if (cnt == nl) {
remove(fout.c_str());
continue;
}
}
ff.push_back(fout);
}
}
return ff;
}
bool SpatRaster::get_aggregate_dims(std::vector<size_t> &fact, std::string &message ) {
size_t fs = fact.size();
if ((fs > 3) | (fs == 0)) {
message = "argument 'fact' should have length 1, 2, or 3";
return false;
}
auto min_value = *std::min_element(fact.begin(),fact.end());
if (min_value < 1) {
message = "values in argument 'fact' should be > 0";
return false;
}
auto max_value = *std::max_element(fact.begin(),fact.end());
if (max_value == 1) {
message = "all values in argument 'fact' are 1, nothing to do";
return false;
}
fact.resize(6);
if (fs == 1) {
fact[1] = fact[0];
fact[2] = 1;
} else if (fs == 2) {
fact[2] = 1;
}
// int dy = dim[0], dx = dim[1], dz = dim[2];
fact[0] = fact[0] < 1 ? 1 : fact[0];
fact[0] = fact[0] > nrow() ? nrow() : fact[0];
fact[1] = fact[1] < 1 ? 1 : fact[1];
fact[1] = fact[1] > ncol() ? ncol() : fact[1];
fact[2] = std::max(size_t(1), std::min(fact[2], nlyr()));
// new dimensions: rows, cols, lays
fact[3] = std::ceil(double(nrow()) / fact[0]);
fact[4] = std::ceil(double(ncol()) / fact[1]);
fact[5] = std::ceil(double(nlyr()) / fact[2]);
return true;
}
std::vector<size_t> SpatRaster::get_aggregate_dims2(std::vector<size_t> fact) {
// for use with R
std::string message = "";
get_aggregate_dims(fact, message);
return(fact);
}
std::vector<std::vector<double>> SpatRaster::get_aggregates(std::vector<double> &in, size_t nr, std::vector<size_t> dim) {
// dim 0, 1, 2, are the aggregations factors dy, dx, dz
// and 3, 4, 5 are the new nrow, ncol, nlyr
// adjust for chunk
//dim[3] = std::ceil(double(nr) / dim[0]);
//size_t bpC = dim[3];
size_t bpC = std::ceil(double(nr) / dim[0]);
size_t dy = dim[0], dx = dim[1], dz = dim[2];
size_t bpR = dim[4];
size_t bpL = bpR * bpC;
// new number of layers
size_t newNL = dim[5];
// new number of rows, adjusted for additional (expansion) rows
size_t adjnr = bpC * dy;
// number of aggregates
size_t nblocks = (bpR * bpC * newNL);
// cells per aggregate
size_t blockcells = dx * dy * dz;
// output: each row is a block
std::vector< std::vector<double> > a(nblocks, std::vector<double>(blockcells, std::numeric_limits<double>::quiet_NaN()));
size_t nc = ncol();
// size_t ncells = ncell();
size_t ncells = nr * nc;
size_t nl = nlyr();
size_t lstart, rstart, cstart, lmax, rmax, cmax, f, lj, cell;
for (size_t b = 0; b < nblocks; b++) {
lstart = dz * (b / bpL);
rstart = (dy * (b / bpR)) % adjnr;
cstart = dx * (b % bpR);
lmax = std::min(nl, (lstart + dz));
rmax = std::min(nr, (rstart + dy)); // nrow -> nr
cmax = std::min(nc, (cstart + dx));
f = 0;
for (size_t j = lstart; j < lmax; j++) {
lj = j * ncells;
for (size_t r = rstart; r < rmax; r++) {
cell = lj + r * nc;
for (size_t c = cstart; c < cmax; c++) {
a[b][f] = in[cell + c];
f++;
}
}
}
}
return(a);
}
void compute_aggregates(const std::vector<double> &in, std::vector<double> &out, size_t nr, size_t nc, size_t nl, std::vector<size_t> dim, std::function<double(std::vector<double>&, bool)> fun, bool narm) {
// dim 0, 1, 2, are the aggregations factors dy, dx, dz
// and 3, 4, 5 are the new nrow, ncol, nlyr
size_t dy = dim[0], dx = dim[1], dz = dim[2];
// size_t bpC = dim[3];
// adjust for chunk
// size_t bpC = std::ceil(double(nr) / dim[0]);
size_t bpC = std::ceil((double)nr / (double)dim[0]);
size_t bpR = dim[4];
size_t bpL = bpR * bpC;
// new number of layers
size_t newNL = dim[5];
// new number of rows, adjusted for additional (expansion) rows
size_t adjnr = bpC * dy;
// number of aggregates
size_t nblocks = (bpR * bpC * newNL);
// cells per aggregate
size_t blockcells = dx * dy * dz;
// output: each row is a block
out = std::vector<double>(nblocks, NAN);
// size_t nl = nlyr();
// size_t nc = ncol();
size_t ncells = nr * nc;
size_t lstart, rstart, cstart, lmax, rmax, cmax, f, lj, cell;
for (size_t b = 0; b < nblocks; b++) {
lstart = dz * (b / bpL);
rstart = (dy * (b / bpR)) % adjnr;
cstart = dx * (b % bpR);
lmax = std::min(nl, (lstart + dz));
rmax = std::min(nr, (rstart + dy)); // nrow -> nr
cmax = std::min(nc, (cstart + dx));
f = 0;
std::vector<double> a(blockcells, NAN);
for (size_t j = lstart; j < lmax; j++) {
lj = j * ncells;
for (size_t r = rstart; r < rmax; r++) {
cell = lj + r * nc;
for (size_t c = cstart; c < cmax; c++) {
a[f] = in[cell + c];
f++;
}
}
}
out[b] = fun(a, narm);
}
}
SpatRaster SpatRaster::aggregate(std::vector<size_t> fact, std::string fun, bool narm, SpatOptions &opt) {
SpatRaster out;
std::string message = "";
// fact 0, 1, 2, are the aggregation factors dy, dx, dz
// and 3, 4, 5 are the new nrow, ncol, nlyr
if (!get_aggregate_dims(fact, message)) {
if (message.substr(0,3) == "all") {
std::string filename = opt.get_filename();
if (filename.empty()) {
out = *this;
out.addWarning(message);
} else {
out = writeRaster(opt);
}
} else {
out.setError(message);
}
return out;
}
SpatExtent extent = getExtent();
double xmax = extent.xmin + fact[4] * fact[1] * xres();
double ymin = extent.ymax - fact[3] * fact[0] * yres();
SpatExtent e = SpatExtent(extent.xmin, xmax, ymin, extent.ymax);
out = SpatRaster(fact[3], fact[4], fact[5], e, "");
out.source[0].srs = source[0].srs;
// there is much more. categories, time. should use geometry and then
// set extent and row col
if (fact[5] == nlyr()) {
out.setNames(getNames());
}
if (!source[0].hasValues) {
return out;
}
if (!haveFun(fun)) {
out.setError("unknown function argument");
return out;
}
/*
size_t ifun = std::distance(f.begin(), it);
std::string gstring = "";
if (ifun > 0) {
std::vector<std::string> gf {"average", "min", "max", "med", "mode"};
gstring = gf[ifun-1];
}
#ifdef useGDAL
#if GDAL_VERSION_MAJOR >= 3
if (gstring != "") {
out = warper(out, "", gstring, opt);
return out;
}
#endif
#endif
*/
std::function<double(std::vector<double>&, bool)> agFun = getFun(fun);
//BlockSize bs = getBlockSize(4, opt.get_memfrac());
opt.progress *= 300;
BlockSize bs = getBlockSize(opt);
//bs.n = floor(nrow() / fact[0]); # ambiguous on solaris
bs.n = std::floor(static_cast <double> (nrow() / fact[0]));
bs.nrows = std::vector<size_t>(bs.n, fact[0]);
bs.row.resize(bs.n);
for (size_t i =0; i<bs.n; i++) {
bs.row[i] = i * fact[0];
}
size_t lastrow = bs.row[bs.n - 1] + bs.nrows[bs.n - 1]; // + 1;
if (lastrow < nrow()) {
bs.row.push_back(lastrow);
bs.nrows.push_back(std::min(bs.nrows[bs.n-1], nrow()-lastrow));
bs.n += 1;
}
if (!readStart()) {
out.setError(getError());
return(out);
}
opt.steps = bs.n;
opt.minrows = fact[0];
if (fun == "modal") {
if (nlyr() == out.nlyr()) {
out.source[0].hasColors = hasColors();
out.source[0].cols = getColors();
out.source[0].hasCategories = hasCategories();
out.source[0].cats = getCategories();
}
}
if (!out.writeStart(opt, filenames())) {
readStop();
return out;
}
size_t nc = ncol();
//size_t outnc = out.ncol();
for (size_t i = 0; i < bs.n; i++) {
std::vector<double> vin, v;
readValues(vin, bs.row[i], bs.nrows[i], 0, nc);
compute_aggregates(vin, v, bs.nrows[i], nc, nlyr(), fact, agFun, narm);
if (!out.writeValues(v, i, 1)) return out;
//if (!out.writeValuesRect(v, i, 1, 0, outnc)) return out;
}
out.writeStop();
readStop();
return(out);
}
SpatRaster SpatRaster::weighted_mean(SpatRaster w, bool narm, SpatOptions &opt) {
SpatRaster out;
if (nlyr() != w.nlyr()) {
out.setError("nlyr of data and weights are different");
return out;
}
SpatOptions topt(opt);
out = arith(w, "*", false, topt);
out = out.summary("sum", narm, topt);
if (narm) {
w = w.mask(*this, false, NAN, NAN, topt);
}
SpatRaster wsum = w.summary("sum", narm, topt);
if (opt.names.empty()) {
opt.names = {"weighted.mean"};
}
return out.arith(wsum, "/", false, opt);
}
SpatRaster SpatRaster::weighted_mean(std::vector<double> w, bool narm, SpatOptions &opt) {
SpatRaster out;
for (size_t i=0; i<w.size(); i++) {
if (std::isnan(w[i]) || w[i] <= 0) {
out.setError("all weights must be positive values");
return out;
}
}
size_t nl = nlyr();
//if (nl == 1) return *this; this is not consistent if weight is zero
recycle(w, nl);
if (narm) {
if (!hasValues()) {
out.setError("raster has no values");
return out;
}
out = geometry(1);
if (!readStart()) {
out.setError(getError());
return(out);
}
if (!out.writeStart(opt, filenames())) {
readStop();
return out;
}
size_t nc = ncol();
for (size_t i=0; i<out.bs.n; i++) {
std::vector<double> v;
readBlock(v, out.bs, i);
size_t off = out.bs.nrows[i] * nc;
std::vector<double> wm(off, 0);
std::vector<double> wv(off, 0);
for (size_t j=0; j<nl; j++) {
size_t start = j * off;
size_t end = start + off;
for (size_t k=start; k<end; k++) {
if (!std::isnan(v[k])) {
size_t kj = k - start;
wm[kj] += v[k] * w[j];
wv[kj] += w[j];
}
}
}
for (size_t k=0; k<wm.size(); k++) {
if (wv[k] == 0) {
wm[k] = NAN;
} else {
wm[k] /= wv[k];
}
}
if (!out.writeBlock(wm, i)) return out;
}
out.writeStop();
readStop();
return(out);
} else {
SpatOptions topt(opt);
out = arith(w, "*", false, false, topt);
out = out.summary("sum", narm, topt);
double wsum = vsum(w, narm);
return out.arith(wsum, "/", false, false, opt);
}
}
SpatRaster SpatRaster::separate(std::vector<double> classes, double keepvalue, double othervalue, bool round, int digits, SpatOptions &opt) {
SpatRaster out;
if (!hasValues()) {
out.setError("input has no values");
return out;
}
if (nlyr() > 1) {
out.setError("input may only have one layer");
return out;
}
if (classes.empty()) {
SpatOptions topt(opt);
std::vector<std::vector<double>> rc = unique(false, NAN, true, topt);
classes = rc[0];
}
if (round) {
for (size_t i=0; i<classes.size(); i++) {
classes[i] = roundn(classes[i], digits);
}
}
std::sort(classes.begin(), classes.end());
classes.erase(std::unique(classes.begin(), classes.end()), classes.end());
size_t n = classes.size();
if (n == 0) {
out.setError("no valid classes");
return out;
}
out = geometry(n);
std::vector<std::string> snms(n);
for (size_t i=0; i<n; i++) {
snms[i] = double_to_string(classes[i]);
}
out.setNames(snms);
if (!readStart()) {
out.setError(getError());
return(out);
}
if (!out.writeStart(opt, filenames())) {
readStop();
return out;
}
for (size_t i = 0; i < out.bs.n; i++) {
std::vector<double> v;
readBlock(v, out.bs, i);
if (round) {
for(double& d : v) d = roundn(d, digits);
}
size_t nn = v.size();
std::vector<double> vv(nn * n, NAN);
for (size_t j=0; j<nn; j++) {
if (!std::isnan(v[j])) {
for (size_t k=0; k<classes.size(); k++) {
if (v[j] == classes[k]) {
if (keepvalue) {
vv[j + k*nn] = classes[k];
} else {
vv[j + k*nn] = 1; // true
}
} else {
vv[j + k*nn] = othervalue;
}
}
}
}
if (!out.writeBlock(vv, i)) {
readStop();
return out;
}
}
readStop();
out.writeStop();
return(out);
}
SpatRaster SpatRaster::is_in(std::vector<double> m, SpatOptions &opt) {
SpatRaster out = geometry();
if (m.empty()) {
out.setError("no matches supplied");
return(out);
}
if (!hasValues()) {
out.setError("input has no values");
return(out);
}
int hasNAN = 0;
for (size_t i=0; i<m.size(); i++) {
if (std::isnan(m[i])) {
hasNAN = 1;
m.erase(m.begin()+i);
break;
}
}
if (m.empty()) { // only NA
return isnan(false, opt);
}
// if m is very long, perhaps first check if the value is in range?
if (!readStart()) {
out.setError(getError());
return(out);
}
out.setValueType(3);
if (!out.writeStart(opt, filenames())) {
readStop();
return out;
}
for (size_t i = 0; i < out.bs.n; i++) {
std::vector<double> v;
readBlock(v, out.bs, i);
std::vector<double> vv(v.size(), 0);
for (size_t j=0; j<v.size(); j++) {
if (std::isnan(v[j])) {
vv[j] = hasNAN;
} else {
for (size_t k=0; k<m.size(); k++) {
if (v[j] == m[k]) {
vv[j] = 1;
break;
}
}
}
}
if (!out.writeBlock(vv, i)) return out;
}
readStop();
out.writeStop();
return(out);
}
std::vector<std::vector<double>> SpatRaster::is_in_cells(std::vector<double> m, bool keepvalue, SpatOptions &opt) {
std::vector<std::vector<double>> out(nlyr());
std::vector<std::vector<double>> outval(nlyr());
if (m.empty()) {
return(out);
}
if (!hasValues()) {
return(out);
}
bool hasNAN = false;
for (size_t i=0; i<m.size(); i++) {
if (std::isnan(m[i])) {
hasNAN = true;
m.erase(m.begin()+i);
break;
}
}
// if (m.size() == 0) { // only NA
//nanOnly=true;
// }
if (!readStart()) {
return(out);
}
BlockSize bs = getBlockSize(opt);
size_t nc = ncol();
for (size_t i = 0; i < bs.n; i++) {
std::vector<double> v;
readBlock(v, bs, i);
size_t cellperlayer = bs.nrows[i] * nc;
for (size_t j=0; j<v.size(); j++) {
if (std::isnan(v[j])) {
if (hasNAN) {
size_t cell = j % cellperlayer + bs.row[i] * nc;
size_t lyr = j / cellperlayer;
out[lyr].push_back(cell);
if (keepvalue) outval[lyr].push_back(NAN);
}
} else {
for (size_t k=0; k<m.size(); k++) {
if (v[j] == m[k]) {
size_t cell = j % cellperlayer + bs.row[i] * nc;
size_t lyr = j / cellperlayer;
out[lyr].push_back(cell);
if (keepvalue) outval[lyr].push_back(v[j]);
break;
}
}
}
}
}
readStop();
if (keepvalue) {
for (size_t i=0; i<nlyr(); i++) {
out[i].insert( out[i].end(), outval[i].begin(), outval[i].end() );
}
}
return(out);
}
SpatRaster SpatRaster::stretch(std::vector<double> minv, std::vector<double> maxv, std::vector<double> minq, std::vector<double> maxq, std::vector<double> smin, std::vector<double> smax, SpatOptions &opt) {
SpatRaster out = geometry();
if (!hasValues()) return(out);
size_t nl = nlyr();
recycle(minv, nl);
recycle(maxv, nl);
recycle(minq, nl);
recycle(maxq, nl);
recycle(smin, nl);
recycle(smax, nl);
std::vector<std::vector<double>> q(nl);
std::vector<bool> useS(nl, false);
std::vector<double> mult(nl);
for (size_t i=0; i<nl; i++) {
if (minv[i] >= maxv[i]) {
out.setError("maxv must be larger than minv");
return out;
}
if ((!std::isnan(smin[i])) && (!std::isnan(smax[i]))) {
if (smin[i] >= smax[i]) {
out.setError("smax must be larger than smin");
return out;
}
useS[i] = true;
q[i] = {smin[i], smax[i]};
} else {
if (minq[i] >= maxq[i]) {
out.setError("maxq must be larger than minq");
return out;
}
if ((minq[i] < 0) || (maxq[i] > 1)) {
out.setError("minq and maxq must be between 0 and 1");
return out;
}
}
}