terra/ 0000755 0001762 0000144 00000000000 14757546132 011405 5 ustar ligges users terra/tests/ 0000755 0001762 0000144 00000000000 14536376240 012543 5 ustar ligges users terra/tests/tinytest.R 0000644 0001762 0000144 00000000127 14536376240 014551 0 ustar ligges users
if ( requireNamespace("tinytest", quietly=TRUE) ){
tinytest::test_package("terra")
}
terra/MD5 0000644 0001762 0000144 00000062044 14757546132 011723 0 ustar ligges users 71637b00c28e55149cbef12f882c0ff1 *DESCRIPTION
4757c95e7e6b0b93c99f856788f7a096 *NAMESPACE
c027c711b6b5b3f6d0495224e2f00a2c *NEWS.md
d7f44345499d08d1737e4d8d1255b3f2 *R/Aclasses.R
fa9197cfd153c4b5b319f2707a3f7222 *R/Agenerics.R
9b12c2d48a965372b09999bb5481d970 *R/Arith_generics.R
b23faa7dfc5ab4b894d87d60af83bb1a *R/RGB.R
33fdcea8d3b95cd8a9fb60688a260869 *R/RcppExports.R
3de3105cbf1bbf08ee9784c89dbbbddd *R/SpatRasterDataset.R
80f4b6ed2917f5743f7500b0dc720d6b *R/SpatVectorCollection.R
5e5df58b70afc494698a70bd34d42268 *R/Zdeprecated.R
06715190fa2c6bd79c0c505c01ea3378 *R/aggregate.R
5b3e8c8469a823aa2d04eaca168601cb *R/animate.R
6cb58e9ecea254da819577b896ac99bf *R/app.R
c3793596a26b156060f43c5d810af061 *R/approximate.R
1789f11fadb4b32d7eed963949af0379 *R/arith.R
41eecbbb53cb5ee398922900e4c851b7 *R/autocor.R
ca752b4ddee117c641774b5afb52d3a4 *R/cells.R
96f499d9b758fd41c377ee7eb8712ec5 *R/clean.R
0d3b4153c53ad1294c5d9e933f277463 *R/click.R
b09c318d117700588ab59125d0a28721 *R/clip.R
7cab73c1e264764fe0df8e4737654e35 *R/coerce.R
a6ad768dc75900cf2086d7e5a2721d37 *R/colors.R
6b3269181e846a95fae070e45b1dcbf8 *R/connect.R
41816125231cffbd7f1136749e703484 *R/crosstab.R
e469eea66bc1c9fec20cee6537d1bdb4 *R/crs.R
fc6cb5db30bc67cd0f0a05683977d903 *R/dimensions.R
3da52e0ca72e8540548ccf7ced8c1baf *R/distance.R
4d99540b31df6858ab5cc970ea3654b9 *R/divide.R
0039da85e5a490127955d8407b42319e *R/draw.R
b7465750d324b9bcca804257dca977a3 *R/expand.R
af82491cf078752961ed7cbefe456499 *R/extent.R
68bdc0ed7f7a7fd1db3385e563e4db24 *R/extract.R
28ef0764008552c098682133220108fe *R/extract_single.R
243cf3f925befbdaf803713f4b0c5b99 *R/focal.R
add8bcb355f28e78c6d7bb44653dca82 *R/focalMat.R
cd79f2eec85e0dfbac38e754527c0eb9 *R/gcp.R
ea5cad6f19806a81bafa89506caaaa22 *R/gdal.R
f905e732fa4f7571b6c96a60f0288b38 *R/generics.R
3aed44b7ad5bbca65b5e3e546a29847a *R/geocolors.R
d2be4d352fc5d434360fe71437a01860 *R/geom.R
a912144edd5a89c7d5df9a06835b2ed8 *R/graticule.R
5da50bd54d43a39c6bd3dd6818eaf168 *R/hist.R
b05d6fc85926ac55a5302ab45862f56f *R/ifelse.R
1a389daa4a402653f2af4e6e4eb9e428 *R/image.R
2a7bc7ae0467b6dd99985f1c0f40f76c *R/init.R
e5a6a689135700622028eee5f29168d7 *R/inset.R
5516056a89de1642f4bb46f2d470c45f *R/interpolate.R
822e4fd6a34599fba94a10ed7a84f272 *R/k_means.R
79df249930fe7a94644fd28c1f929b75 *R/lapp.R
32ba058ba8058e1db337cc2f5aa2b71f *R/layerCor.R
92631634a51a42b8ab37dd311a3670eb *R/levels.R
09f0a173ec7d9248c9b2f5d23d0eba8d *R/lines.R
37a83c6db763b60ca8642fead8eb986f *R/makeVRT.R
0bb0b8d4d0fe1f5f997f7cf09449a180 *R/match.R
8b072ca7e634250163a2cfdad529ae1e *R/math.R
9ce28577c49fb5834b7ebb0b9adfc92f *R/merge.R
2caa145a80e5e837356b83391ee04f3d *R/mergeTime.R
ca4f961028f6ab0b83197e1beb951664 *R/messages.R
5e65cd0320b4d60fd37005c7b5c342aa *R/names.R
e594c40a3c82a04d920f1cb6b716bf57 *R/ncdf.R
aac84fc82ed9e373736483d28715e392 *R/options.R
4f18aeadc9e87bdbae91649b0d94bd98 *R/panel.R
9e742b984b71d45923982e444fa62c66 *R/plot.R
90f74689ff6da4a2409da41229594bd6 *R/plotExtent.R
0704ab1745345cbaf4e88535fb2393d4 *R/plotRGB.R
a79377686287e9f10f275cd0c426b7ce *R/plot_2rasters.R
ffbfa9b92467b610f18614a2d5fa4fc2 *R/plot_axes.R
ae3f934129a27b1b86e4c2e0f1a14560 *R/plot_cartogram.R
30271689b7289ee3792a538ae22c5416 *R/plot_legend.R
94d5e04a1e4afe9077135eb76503d5fb *R/plot_let.R
384da1bc054c8f185e90bc4a1ac840a9 *R/plot_raster.R
3988c82c521c6e7d70b5788b070df957 *R/plot_scale.R
a00b3eaf44dc741939acd6bfad6f3f22 *R/plot_vector.R
d41d8cd98f00b204e9800998ecf8427e *R/polygons.R
1ad20e39fc1488d7f997514e27d1dd79 *R/predict.R
c9b80ddc621f7ed26b9c6cf7dcd51b12 *R/princomp.R
c9adacfaee78f3e1d26bc3ec9cee089b *R/rapp.R
c79afbe06cfe6e0ebc606b450436c6c7 *R/rast.R
3bec2f3f6a4ace28837c6a81dbe2c5c4 *R/rasterize.R
d49fa94132ab1f7b5364a4512b087cf9 *R/rasterizeWin.R
0961701948dbf1d11df6b7548776bf2f *R/read.R
d23bbd02ea2747dabac1c80c617b7bb0 *R/readsvg.R
32108a0fa3606c15f2f7ad746ea5d5c5 *R/regress.R
5bbf2002fad3612f269e63d6e60d84b3 *R/relate.R
87fb82f73868dd11ca2f5071ba1344e0 *R/replace.R
3ab5da63ea95a4156a6257bcc4e154bd *R/replace_layer.R
e97fba9936ad40bae07694f04ef5b933 *R/replace_values.R
54ed50d797891bdbfa2e7647ce65d585 *R/roll.R
7abc342437102cef445231ee492d4cfc *R/rowSums.R
347ff9bbf956f39f3c9b05e1e440273f *R/sample.R
4a54212728cfc104ff13c2d79c19648f *R/select.R
b819e1fcfcbb607c2878b7cb6adfd66b *R/selectHigh.R
42a133618af864d34055690ea81c1a1f *R/show.R
28eb0b982172d2400cbc8064327a8350 *R/spatDF.R
0044020faff9a42ea66cb4642947e92c *R/spatvec.R
3b99f4edd9e33f117a63c1ee3378b4f3 *R/subset.R
5e4c6b522389c534ddb659404b48bc68 *R/tags.R
087c09aa4281d86c742a2e5148d77c53 *R/tapp.R
1d79ff4e2b0945f738501f7de1fca1b2 *R/tempfiles.R
594ce8cc83c5a39b1332076d34fcf1cb *R/tiles.R
717abd4acb240ed1297e5736e6dc41b4 *R/time.R
e192b1ec65e3b16bf289a65ca67746c0 *R/twoClasses.R
81acb963cb7377e1731cf11a7ad656e7 *R/update.R
a6f9304937cfa40d002c176ea4ee97df *R/values.R
1f4b3759cf60946ef3127636a10e5d9b *R/vect.R
2bfc16242e9baa246ee18c876c2dcc22 *R/watershed.R
1e01e02d712240b55262cfd653270840 *R/window.R
19b7dc657be2860a0000d90c08685de9 *R/wrap.R
a093b3d631787ab84bea42d8e391339e *R/write.R
8a64d6f4cbb56f114a7c19d3a12fa046 *R/xapp.R
7241e67e96b1a447717d97b19e119399 *R/xyRowColCell.R
904a380f2c8090fb4ad90d5e41698c96 *R/zonal.R
23d0f1bef55918a24b3cf2a5888b034f *R/zoom.R
eb6176550a52650a82f32d0ffd8b8266 *R/zzz.R
1dda19015f0aa969acee990c150e3ac9 *build/partial.rdb
0513ced67884bcb39614d15070870521 *cleanup
fc19b75c7b894ce0f46e1991370bbbf9 *configure
37fd8885d102ea5890eab19ba6d23763 *configure.ac
aaead9a66071620fc36f67a7bfbc46d8 *inst/colors/legends.rds
a94e0497c4ee7b653400f10409c30386 *inst/colors/palettes.rds
9f0ba0023d2db45f72e80f55a14f63cb *inst/ex/countries.rds
d069a3466d5ca118b4330b322793b821 *inst/ex/elev.tif
8f96ed774ae7d7044e223b2d3b3fa3b8 *inst/ex/elev_vinschgau.tif
0d72b29353f0f26827006b4295a9c7b9 *inst/ex/logo.tif
c257dbd91925dd42614dda2cf19a58a3 *inst/ex/lux.dbf
c742bee3d4edfc2948a2ad08de1790a5 *inst/ex/lux.prj
4ae2847099f7574e36516738dc411a0f *inst/ex/lux.shp
5d6304a3bc11ffe01ffdda30514d15df *inst/ex/lux.shx
17cef336212cebba7255c8b6192d882f *inst/ex/meuse.rds
73eb1eb43061189bcd5bcfedbe9b7104 *inst/ex/meuse.tif
12452890a939a5a22757e2ea328bbb3b *inst/ex/rds_tst.rds
92e7d96043d934c23d2ebab93c560c77 *inst/ex/test.grd
cb22d2072ca597b022e481bb86f9f989 *inst/ex/test.gri
7e139df30fc4070d1281d4d12e0ea25a *inst/tinytest/test_aggregate.R
c8edb96a09580b019da6a97cdc4bfefa *inst/tinytest/test_arith.R
8feaeafa1f722c34a1c743a233c04753 *inst/tinytest/test_cats.R
26c88abde5cc4082f718d07933b7ea94 *inst/tinytest/test_classify.R
d03f43d82734f6bed9399cdd2e995789 *inst/tinytest/test_crds.R
b8b1169ae28677221212dabc9281cb55 *inst/tinytest/test_crop.R
131a6e2201fb9ea6bdd8d65053f2cbf8 *inst/tinytest/test_equal.R
5fcf057bdf52c231b56e76ab1ef03458 *inst/tinytest/test_extent.R
f2b7c0f74fa473e7fa044e39dd33b4fb *inst/tinytest/test_extract.R
83eb1a390f2bb92eb4bbe01aa6b766b0 *inst/tinytest/test_flowAccumulation.R
094660742a88d0a2128555817154981f *inst/tinytest/test_focal.R
a6040097da9aeb00d2ae773481fbab50 *inst/tinytest/test_geom.R
18ecfddfd917b4364468cbe2ce250760 *inst/tinytest/test_global.R
cfeebf4bd2c785e3e94a99b52e9f5018 *inst/tinytest/test_matrix-input.R
a00e19ade355713974ac0175f2becbf0 *inst/tinytest/test_merge.R
f8be1984b0fe280937809e7d03120224 *inst/tinytest/test_multivariate.R
513ac5699d994e56fa629fe3ddeadb02 *inst/tinytest/test_patches.R
66a836ca5c9e527b65df28dec2a4ff42 *inst/tinytest/test_pitfinder.R
d7cbdd3f9f9cc1fc2348ebaac5ea516f *inst/tinytest/test_plot.R
a01557e9bb896b93da4c35142b6de28c *inst/tinytest/test_raster-vector.R
f1a10f8fc4afb5adce3911c22bf06963 *inst/tinytest/test_rasterize.R
b9bcb937bf5f83855c8ac5a619a46e82 *inst/tinytest/test_rds.R
2d8c1c8cf9c32b2f38ddc5d9f714e841 *inst/tinytest/test_replace.R
adace6cae72c80c444a8e20a3314bfab *inst/tinytest/test_time.R
fb2dbd201e5160e88ba1e7b3effe5a11 *inst/tinytest/test_vect-geom.R
66c734dcf4b0da9a4ec506c5d2cd4b54 *inst/tinytest/test_vector-subset.R
8c24b7beb04ec3a113af32799959bf43 *inst/tinytest/test_weighted-mean.R
c70af37ab5349e47ebcb776dd697aee4 *inst/tinytest/test_window.R
546aa29e861d525111f4d3c0b2ce7d80 *inst/tinytest/test_wkt_grd.R
088e2ab7721082563d4439ed72a71075 *inst/tinytest/test_zonal.R
a6a6d9ea4118f5c809396420826a3d35 *inst/tinytest/tinytest.R
321a8ad6e1183e23526e8c49b09f7ffa *man/NAflag.Rd
a23b4344e1df236a2535f18f40c3a519 *man/NIPD.Rd
a53dd4fbbf7e78fb796b631c4d33cd98 *man/RGB.Rd
6b5a6c14e696b8f2ed4de9bdb5f978b0 *man/SpatExtent-class.Rd
4dc61bfb7fe5c6f93208bff6cf8b9ae0 *man/SpatRaster-class.Rd
05350d9d6e1be8e30382586c8427c204 *man/SpatVector-class.Rd
118d132641ef7d707bf74954f7705093 *man/activeCat.Rd
8fd23006e2b5a0276d4a318fb7c856c6 *man/add.Rd
613c3405302dd65c7e031e651ceb4a82 *man/add_mtext.Rd
acda543eef815af237834f05f73d8966 *man/adjacent.Rd
274a591787b147fc98a78afab74550f1 *man/aggregate.Rd
061fdc6453489ba9635945f103c1750a *man/align.Rd
76cc107de34e4b269c405398ed72a172 *man/all.equal.Rd
3a6083346d4d254394c74c5fd13fe70e *man/animate.Rd
6c81caf77e2b0d4319eedb27302c1d03 *man/app.Rd
1c90c781330d1b64a31e15c6a10505a6 *man/approximate.Rd
69ed9fbc8665a62ad9effdfb41211d2a *man/arith-generic.Rd
0705871cfef34b24c39f5797ede5ddcb *man/as.character.Rd
ca4ff548bd76bd7529f52e9283065d67 *man/as.data.frame.Rd
8a3b81c94d148cb608fa64c11cf042e7 *man/as.lines.Rd
a60010d647f00a02cbceada18a7e193a *man/as.list.Rd
948f3321a26266ef5321394de2fa7198 *man/as.points.Rd
17368ea9f91168df3fdd85faae008446 *man/as.polygons.Rd
cbfbc0bc5e83a7d11588032c78a53050 *man/as.raster.Rd
d423e2ecb6c6a2cc19798dca7572c1fb *man/atan2.Rd
83e8404f596acf01ca160f2fdbcca6a5 *man/autocor.Rd
8614a7923698984e48afdb03d575c22d *man/barplot.Rd
6042b7dd3ebb7caec03a161ab16c36ff *man/bestMatch.Rd
f36c3984f0ffad80d76b64b483b8780b *man/boundaries.Rd
568fab14b3e52555d37daaf12e158e9d *man/box.Rd
199831f20e422396c648850549256fe6 *man/boxplot.Rd
2cbc8b3be2befd82d5edc8cb572578a0 *man/buffer.Rd
183820d00930f52c500991819622298d *man/c.Rd
3dead3a716ff5f508cb57ba9a41eb572 *man/cartogram.Rd
7794859ad2e9953aeb1125b6233f44f9 *man/catalyze.Rd
448f9aa1aa56c0c09a399b5ce9fa0699 *man/cellSize.Rd
c7421526d1abcb0e3644d4a7ca8c342e *man/cells.Rd
51cf38969dbd92e2c18ccb3bbfe2b2d8 *man/centroids.Rd
454c1d1cc94136a3678fc855d1e76678 *man/clamp.Rd
6e2642f3a5d9d030447b548d77e839fa *man/clamp_ts.Rd
f260bbe7e11a92f979bc06bb7098336c *man/classify.Rd
ca0663d2cd69d8b44c69383eeadc1a9b *man/click.Rd
984291f794cefdf329cd7f16520aaff2 *man/coerce.Rd
185dc0ce9675fdf4f012aadffe31aae3 *man/collapse.Rd
b99b1129faa82d48e97ece771aefaeac *man/colors.Rd
7914610933fbccfe62d7e890b39faa37 *man/combineGeoms.Rd
0a27e22180073cf675c07bbf64b6f434 *man/compare-generics.Rd
6d055f9e010575f85dc922988d906f93 *man/compareGeom.Rd
26820d945ed3742a07b34ef56b40cfaa *man/concats.Rd
83b3adfd5111096113583fea8a5e7dd0 *man/contour.Rd
e5612a2268375b78b46b3bd39d0539bf *man/convhull.Rd
f1197dbea22cf30a61a096321aca606a *man/costDist.Rd
f9a3ae571230e63ba791370f172cdd55 *man/cover.Rd
c322c89f9aa9a911234407c4a0dabaed *man/crds.Rd
6704d7ed6803d495e02223eb222e1963 *man/crop.Rd
32e284b3d6118e9180e712339788988f *man/crosstab.Rd
7d7b927ba90065e602015e9f9eb0ec79 *man/crs.Rd
7a61ae45235eefcef217ea7ed3217693 *man/datatype.Rd
0d2278667be3679be4d1bcca6cf517b1 *man/deepcopy.Rd
cd87a135b0446ea63fad43a326814464 *man/densify.Rd
faf1c4471cff59222f6c6d4a20463466 *man/density.Rd
e4eb50a546a7182eadbce6e01b6b4b9a *man/deprecated.Rd
2a4dae82f7c9b8bd31802b5c66c089d6 *man/depth.Rd
61afe26c0de046b6fa80e480f9019da7 *man/describe.Rd
24b0b04945df9309f1cef04e010060c1 *man/diff.Rd
59c7eef11e2762a0d8c464f197b0a9ce *man/dimensions.Rd
7b07ea19288c1c099edd6676b70a176b *man/direction.Rd
6eb62722bfff62ba87275f21dfa36575 *man/disaggregate.Rd
b99103ebd418b40ce044cce3678be889 *man/distance.Rd
d24b9dd182be8ff46ca3f9fbdaaed995 *man/divide.Rd
8b0b99ecdc05b8d6362f3134c661a2ce *man/dots.Rd
b203545f0c838dcec19e09023cdfca40 *man/draw.Rd
cb6dbd29fc799ea43bb6a6f5e4b5bf6e *man/elongate.Rd
6ab38fce4d104819e61bd5b62bf66f25 *man/erase.Rd
faab5ebf4398dbd41864ce719bf87af8 *man/expanse.Rd
59b4edf964c460e4857fd4e5c07f676d *man/ext.Rd
41b50a6b62704032d5c24f6f2c670e0d *man/extend.Rd
df556d8bd515afba61093bbf2b2afba2 *man/extract.Rd
4fb4772021da92fde9082acfb4032e50 *man/extractAlong.Rd
e96d4299dfd04abd16915e194e798949 *man/extractRange.Rd
e143c9e03131bbb5bc1036f9dfbeacec *man/factors.Rd
97d6828fc02dbd2cf107273bc05defa5 *man/figures/logo.png
e30e0f9d952ab6159b275cf5d0a1e98e *man/fill.Rd
5c89c58d1472a836cba05c4420e98a14 *man/fillTime.Rd
cc3af891673343eeec393bdbaf362757 *man/flip.Rd
f6a004bcd30726d57fde262192e6f41e *man/flowAccumulation.Rd
295e7d5a52ddd0ecc045364823277dde *man/focal.Rd
e2c5e09ce90b8e2a59b971b6a77c6859 *man/focal3D.Rd
e314829650b7eedee663eaf86e0c4843 *man/focalCpp.Rd
47803e42efab08728739a19d5ddf4aed *man/focalMat.Rd
93ac1004dda64196173b1e632720cd43 *man/focalPairs.Rd
66169557d93e330928a1c3f9f40f1100 *man/focalReg.Rd
9533accb9a815f4c10aa88267e4a588b *man/focalValues.Rd
aef2f484b01cfef5ed788c8875af87d2 *man/forceCCW.Rd
36116899147b5b77f5f150cce362900c *man/freq.Rd
42f1051c62125b9422683af679898855 *man/gaps.Rd
c6e0ac3565f04bddeca88942cd5e6d35 *man/gdal.Rd
675161335618fc80ba8ed23080d10ead *man/geometry.Rd
c6c2cad8351984875ffbee1e340adfd9 *man/geomtype.Rd
39e005935207fb90b6ec91e0ead34bff *man/global.Rd
596ae9b2f7ca20058491d7b62b5867a0 *man/graticule.Rd
a0877f8dde70295635f8d583ef880c94 *man/grid.Rd
5afeb76c6a866389dda4120ac20909c3 *man/gridDist.Rd
694b074b3ce6ab67aae71f7cd9e01e50 *man/halo.Rd
925193bba602f6c94b6d14c0eeebe749 *man/headtail.Rd
0b9de826e4d6987350dcd1963415628a *man/hist.Rd
74252558e170b4dc5fa1f381fda5ced4 *man/identical.Rd
6aae87cfcb10b9a1ee69727b6b5b5a85 *man/ifelse.Rd
e65ea2e69d005685b88b8c7d48069241 *man/image.Rd
43c208bb26e1e75bf1d8a6714b5d1267 *man/impose.Rd
0040863c4ea2b35731080d328356b2ae *man/init.Rd
d4be5ec342be8138b4f7d566f4587205 *man/inplace.Rd
2959cf1e97af288ac31143f5e433c5c8 *man/inset.Rd
a710d899c2abf432feabdcaf226dd601 *man/interpIDW.Rd
f3b63254fc87d7cd0b9d8e3723ef538a *man/interpNear.Rd
4b514833da02f9f1a25873a6400dee98 *man/interpolate.Rd
d294ce0c182e4b313281360726c16273 *man/intersect.Rd
21ab0604cc21e837a0ceee7803fa4ef8 *man/is.bool.Rd
96fbca86ffc372143244ffbfbba1a494 *man/is.empty.Rd
e042199c2ec6fb8cdbbadbea46fc16c9 *man/is.flipped.Rd
2db0c24e9ce375b6b35da508c434f2cf *man/is.lonlat.Rd
2d258edc3ac30eb8765aa7294e55ad9f *man/is.rotated.Rd
d8b0e91c600b96e3b77971a8e217521a *man/is.valid.Rd
2694dfdae0c96d32e4be224ef58eef40 *man/k_means.Rd
f2647dc9f2cff2fcdd6a3346cdaf23f5 *man/lapp.Rd
598933747a63404a75bc6be6734bf1fa *man/layerCor.Rd
a8109a4b29b32e7a5828962aa5e07237 *man/legend.Rd
d16d5b8e7f00c06b9435eaf8af4d2fdd *man/linearUnits.Rd
73a63cc128a83ef18e4fb8c3e6319ea6 *man/lines.Rd
fe3af65fa878cde3aa9a1be82ca28244 *man/makeTiles.Rd
f722621bda82818d8f26908770483be6 *man/makeVRT.Rd
282273552dfcbf95ac4e8fc7a065bb48 *man/map_extent.Rd
4f71d2f3e74465df2ed673dd063548c9 *man/mappal.Rd
9b73e09bebb92db5fa1de14bd519776a *man/mask.Rd
1a3c94d517fc6408dccfe2115a52ae8e *man/match.Rd
587dec10aee5fdf467bfc6e611f7d51e *man/math-generics.Rd
20cd6cee7690b02d8795d475f2f7120d *man/mem.Rd
085753ad3e4d1d7764dfa202fd1c632c *man/merge.Rd
b98d26a8dd480a7284d5ff9752ef29a2 *man/mergeTime.Rd
4d95a5ee1d7967693ada6923218ab87e *man/meta.Rd
94dd46c44f6372bd78e8ad77248ac00b *man/metags.Rd
ab4e5fe24aced14afac858d877d2b5bc *man/minmax.Rd
8de5bdfef13bf2c64fb8e43f3dba8f8a *man/modal.Rd
b05e7a2dcddc21b7045c3fa71de99851 *man/mosaic.Rd
4e8f5ff85d378747f6af287d013c206a *man/na.omit.Rd
e68f3e58dfc462d1cbeb63741ce81b35 *man/names.Rd
95a9aded1e7b26ee368ff58fa0df8699 *man/nearby.Rd
526c2587a72cb8b8745181042ae44c2d *man/normalize.longitude.Rd
db47941dce499568738a2eda6903b781 *man/north.Rd
fd58934e5aec292191a1a49b6d3c3d56 *man/not.na.Rd
d237565e037a0718c86e9d9898f44b88 *man/nseg.Rd
60df38237628e8eac85da0ae9845d1bc *man/origin.Rd
c93380632eae621f097bbef64b44beb4 *man/pairs.Rd
607c426cc96fcc3b2930039cec563645 *man/panel.Rd
ad922989d79013e144d184c55df80c6a *man/patches.Rd
1d98b01c9a77080691ba899f2f5cc84e *man/perim.Rd
e357456cf972f6c184aa0b44cc5bd51d *man/persp.Rd
ec9c28967a754a03d4b9ba4d7125d8d8 *man/pitfinder.Rd
a5f60de7a354bb50e0eb82debd8feb44 *man/plet.Rd
3f74aedeeba268763d3961c17fa3f91b *man/plot.Rd
0969099c51421506af5ff407b8316408 *man/plotRGB.Rd
11420b226613b5d74cd878f9e93a3f8b *man/plot_extent.Rd
930d41510d506976de052e3ca0f73415 *man/plot_graticule.Rd
f0fa744f22aac76f46b2d8685cd0f710 *man/prcomp.Rd
2907a928ee2f2f8616cbb53d7dd5d89a *man/predict.Rd
875c96bc2e390bcdd1e3e37077087495 *man/princomp.Rd
234df1daf878bbf8310de2d362a1056c *man/project.Rd
6afc9583c42bf2bd31b998d52dde7506 *man/quantile.Rd
432cdd2dc3c1d3e0a0bce6f650dbfa9a *man/query.Rd
bbe85d85c9f56816db51c00cbf721f1a *man/rangeFill.Rd
0bde183d3253871b652028c966efaa8f *man/rapp.Rd
54e65e7fe54833e865c51b00ebd92118 *man/rast.Rd
0021a3764815218015c8dd1fb9f537ac *man/rasterize.Rd
0970d39129e32c18f67da4ac61bd5ddb *man/rasterizeGeom.Rd
b66a73b8867b7f9982ecdfd81e8625f6 *man/rasterizeWin.Rd
608806347d8adf840963d3ccbefff538 *man/rcl.Rd
c0aca51ebb2c95ed49fb4482b401c907 *man/readwrite.Rd
50a7c5d8d96931c4a4410520dc86d7d0 *man/rectify.Rd
bd8aa9eb83d0d8c77e7dbf21d935fa10 *man/regress.Rd
af0e711d038d3fca486eeb07c2da9519 *man/relate.Rd
e81f21854d60782f0dad55ebf451cf28 *man/rep.Rd
15c37cb56b2bb8b062686a669d9b8664 *man/replace_dollar.Rd
0d508b23dc915d99bafad9bdd5daa7b6 *man/replace_layers.Rd
e4d9b292bb94d60300213788fe5a30cd *man/replace_values.Rd
2f8be6d5fa2f83e788adf8295dad781b *man/resample.Rd
278d35322fb401a3fed3a262a0c6ba60 *man/rescale.Rd
d56f78dd23a20215dd72f4cf4671e2d8 *man/roll.Rd
6cf69cf2625d1ca0b9b617315ffc4b3a *man/rotate.Rd
36ed7d949f5c2ebabd816716ce0adca1 *man/rowSums.Rd
8eeaa03c92f4ca7c995a9c238039c4ff *man/same.crs.Rd
6b194bc44b821f162ff86c10b3b6afb5 *man/sample.Rd
02a8a45f1f1de184e40efc11d1db567c *man/sapp.Rd
08229374a7b2f4a5f6bbaa4f379949e8 *man/sbar.Rd
273c5344b5de00762784d54c212b65aa *man/scale.Rd
3f78b533206bec0eff1c300a73813b79 *man/scale_linear.Rd
d3220149ddfbefc0ba4a5809ca311ded *man/scatter.Rd
fe02d9ab735741761c8be070f452c835 *man/scoff.Rd
ef386f6ecfc821437554268e1fc1b99b *man/sds.Rd
d27839336a11fc40860f8aaef7d11f1d *man/segregate.Rd
f3bfd4893087ddf49e19c4ff8224cc3e *man/select.Rd
489452d97aa215dbb5f649cea6dcc6aa *man/selectHigh.Rd
2dd23b1e5be856bb0ff420b880c6df78 *man/selectRange.Rd
e3738b704a5f726ab70e381333b7ea4f *man/serialize.Rd
937c7948e436b535a9a54c618d60dcd5 *man/setValues.Rd
6f806895bd965b626a5c9c38f4397fef *man/shade.Rd
db50cdd7e9cb2a20e1147061132a298b *man/sharedPaths.Rd
01482a352d2297423e55171eb2df26ec *man/shift.Rd
8d7c8998e764b886f5d4a98f3d69d352 *man/sieve.Rd
9d77318817e6696d84ecec29c8c097a2 *man/simplify.Rd
11e3386c36a54d84b18170161f85827d *man/sort.Rd
80141a8dbeef6a9b40bdc04c2e8b05a0 *man/sources.Rd
807af9be8bd68eb45f76fec13a578fa7 *man/spin.Rd
0bee5141a6f76aec9d7b74944eaa5d43 *man/split.Rd
9d689b5b8d63e24f077099f9ff93fc79 *man/sprc.Rd
c2a9b0773125bb99f2bb7a915915c440 *man/stretch.Rd
a77164321364a30a923799f0101bc36e *man/subset.Rd
c8534fe735f7f538cd950af63da61b88 *man/subset_dollar.Rd
9fb79c3450e7f010d4b38fdddde63f05 *man/subset_double.Rd
614af029059cd625c03bdde5be5c2857 *man/subset_single.Rd
af4940ab004733b520c115defaf83469 *man/subst.Rd
bae89dbea4405a31b79263c7552c5517 *man/summarize-generics.Rd
9e9bb2ae7ac1c9b37eb18eee2f575f31 *man/summary.Rd
10b0f361feb8dff93ae8bb9e01f6119b *man/surfArea.Rd
b244c8dedb350346bfac83871dd5bd25 *man/svc.Rd
0c1ba336644bd0a82809bbee5c349c0a *man/symdif.Rd
04e97d5d195dc68699874c2b4bd37938 *man/tapp.Rd
67ee33ba76c98441f209158231b6495d *man/terra-package.Rd
9d76b2b088fd55a5343a4430bfb2cbba *man/terraOptions.Rd
7a7e171b01ab272b493786beaac725ed *man/terrain.Rd
81c9107bd3a9b460d5e6d6979d5a1994 *man/text.Rd
7e5167462782680e12b963356cb03f9f *man/thresh.Rd
faa42eb1d6f2bd3b92d019185d309c44 *man/time.Rd
ae88830dbecb413f40f443481bb14185 *man/tmpFile.Rd
d8f8fae10dec8538b0bc3ba11c5f9d98 *man/toMemory.Rd
f58714e38430b02be79824bfc4d34eed *man/topology.Rd
1525964261b9fb412511f9502041cb5b *man/transpose.Rd
3cf14b93c4f4a2827706bd454aec0158 *man/trim.Rd
3dd2993f1a7e34ead75c145c2d8b9b96 *man/union.Rd
8962724a7ce4d7054b9f4eab6298fa27 *man/unique.Rd
2650f9770acd68a577abdf12225244a9 *man/units.Rd
cfef00666cd46111df5e813a91fefcd9 *man/update.Rd
828b00e844ccd21d1820b9d91c7cbcba *man/values.Rd
aea4e041d5597a60d6e816be3e567b12 *man/varnames.Rd
35ff519fb38777f5e453ec5d99040a94 *man/vect.Rd
760ff35a4177d540edd596c94c1e0a13 *man/vector_layers.Rd
094485ef6bba83695786032b91333998 *man/viewshed.Rd
2bb66d8ff15e7bb8edad474353f58b3d *man/voronoi.Rd
2a54e35b77cdd8d46facbc1604f3e654 *man/vrt.Rd
bc605ee87b968b8040c98188be3706df *man/vrt_tiles.Rd
dc482c611786ff5d4334c89adf6c855d *man/watershed.Rd
bff544bda735421c8d7e3b0651551cdf *man/weighted.mean.Rd
eae88e03678f2292908e2c1af0f62f77 *man/where.Rd
bce7d4d8f571269f439e622baa9561e9 *man/which.Rd
7948cc222f59a33da3275297344ccf34 *man/width.Rd
3eed9594e44e8a75efb07e0a1adb3de0 *man/window.Rd
dd05d05523a22f7351deb0a2aca42692 *man/wrap.Rd
f895544f09351d5b020f1f5e78ebea68 *man/wrapCache.Rd
061b19dbc51cd989716bf8bb7ac19541 *man/writeCDF.Rd
d7e8639d995cd288cca6ada9804e36fd *man/writeRaster.Rd
224cd1125f6f24bd4c3f8e8077b5086c *man/writeVector.Rd
d2a8eb7019dad0ff2f1f28c6dd94e4db *man/xapp.Rd
d9539616f11511e03e98b9480329d7dd *man/xmin.Rd
b099812d99636e5471c906277c31a0d8 *man/xyCellFrom.Rd
acd6392aa66b624f157cde2b35ba56df *man/zonal.Rd
c0daf4b5eab6db54cb42b76e7dcc6402 *man/zoom.Rd
ea9e4cdf5ff0217b94ffb7ba6663bb90 *src/Makevars.in
867989920ee5e94a1a22334827bc604d *src/Makevars.ucrt
ee336a2cba1048d73e746db66c8cf0e4 *src/Makevars.win
4b35eab705c5561f987af28d368ed72b *src/NA.h
4ad9c71c26797488332b6a2e34af3f28 *src/RcppExports.cpp
c974412ae34bbc3b188fae32f76c5f1e *src/RcppFunctions.cpp
c18da85fae44cb0ae08d8411dd7f1090 *src/RcppModule.cpp
4c1a81c345e9bddc484310d805dfb061 *src/arith.cpp
7f3d6c5a21d4d67f49a236d4d1032613 *src/common.h
7fd83fcefcfcef5f9c9246693403a8ab *src/crs.cpp
de659796a8789d05c6fbf3ef24cfbe82 *src/crs.h
1b8482f0bce855911081772c074b4ccc *src/date.h
4374586bc7f17d7544a3804e6cb8caa5 *src/distRaster.cpp
f64401e8747c1fb6ce1bda8ca8b66fd6 *src/distValueRaster.cpp
d1286366d27e5417053f514636869011 *src/distVector.cpp
165a71e17d9f0166a7f20f66bafb85a4 *src/distance.cpp
91af5eb8f1fd7fc778e4dbc9e299658d *src/distance.h
a38f5c004a24e33aff016faf23353248 *src/extract.cpp
b98245f7f34509d95955a0696e9af713 *src/file_utils.cpp
ddd2a1c0d715fbd6e9aae454a475351d *src/file_utils.h
ea659d68dd1d329cae534dcb8917bc32 *src/focal.cpp
d3edfb952cc538d55bc27c3adaf40235 *src/gcp.cpp
a14270a28abce4f3d4feb859204a95cb *src/gdal_algs.cpp
81171ea0bd83d4f4b58d1ab3bb53b3ff *src/gdal_multidimensional.cpp
9f681dfc10cf545bf43e65d6d3c40ec6 *src/gdalio.cpp
879382455567cd0cf1a1c09482557f1c *src/gdalio.h
4f277083c49bd086621abc203160e993 *src/geodesic.c
598c2f9f280f518436b2f8876df17a81 *src/geodesic.h
d19b30117c31fbdd02984b5b147e5d33 *src/geos_methods.cpp
44fedf6a1a78342636e8335aa76bf831 *src/geos_spat.h
aeb79f248f5aaff5de2fb72bdace2c27 *src/geosphere.cpp
3f3aa5a717765c99d893954f8f88f3bd *src/geosphere.h
931af2f8b47c60e7da1e76eb5a8e9c12 *src/math_utils.cpp
c007021906d28ea503266237ab7e6bf3 *src/math_utils.h
7e5be69595d9214130a17fc1e03fc38f *src/mediancut.cpp
e66941c02181837472bd165bf0abb97e *src/memory.cpp
711bd99d414fc12792dc05e6942300dc *src/movingWindow.cpp
a990f9287b3a90b018277efcd5208e4e *src/ncdf.cpp
ef6d96caf8010782499d4d25e7e8d981 *src/nearest.cpp
a6f8ae71d4fabec722fc5bed0e7173c0 *src/patches.cpp
fbbbf921bfa4cc8e2480ad631229e8ee *src/ram.cpp
24dd35fc3503bf56e551bf7e93464aff *src/ram.h
72f680717856ad8ae181033b01af4a4b *src/raster_methods.cpp
fb903e29f74f918872215e185df8f6b0 *src/raster_stats.cpp
7df99edb124e766c4f31d1f0ff56d777 *src/rasterize.cpp
9848700fe92a40b539a9ec22e0f36d79 *src/read.cpp
b4453328091fbd74a05797c66c5d7b7e *src/read_gdal.cpp
b2668b5918f391540323f21589d5eb57 *src/read_ogr.cpp
6e8eafe468bdb7cd2971df858e54ebff *src/recycle.h
fdd096dce7bf9418bf53b9f0cccd4441 *src/sample.cpp
80ba0afdf0cb574d93fe5f7ec6b8a44e *src/sort.cpp
7eae6701d6fcb5aaa3ae2923cff52dd5 *src/sort.h
04a64ff00e1049db115516c4ccb82a71 *src/spatBase.cpp
97c681a3227680a38ed0eebd8c98d05a *src/spatBase.h
fbb0c120ea1864ef2401f282caf89657 *src/spatDataframe.cpp
7cbb453fa7763f3a55437b3f47f5ce91 *src/spatDataframe.h
a79edef25a4f21bfa0f371d21ea3fe8c *src/spatFactor.cpp
73aad8949ac811fdb3f862bae9156dd1 *src/spatFactor.h
3357ec025b3f93f17e3b8f4ca889d412 *src/spatGraph.h
9b8887f819ce65aaecce6f73f614a26f *src/spatRaster.cpp
39237302bab1502ff42878d5e8bfda24 *src/spatRaster.h
4192e49304bcb39143bf8f2ddbdaba3f *src/spatRasterMultiple.cpp
7d4ebc2309bb120f31fb6516d3afcdc0 *src/spatRasterMultiple.h
532d90eeaf345ddbfca1cf043c00ebe1 *src/spatSources.cpp
fa6011bbd96d68913be19cf3903e0a28 *src/spatTime.cpp
d5b666b9ff06031f0edc40ce889e93ff *src/spatTime.h
4d4426258ac79bcc648daee3f9b563b2 *src/spatVector.cpp
cd75c5e8f0f293e6e6bb547b4f40d25d *src/spatVector.h
e646cc146edacd776714bc342c8ab26f *src/spatVector2.cpp
47282d3135ae24daa13302bd80c35c30 *src/spatVector2.h
44139367d4fd7090431af8392a277b41 *src/string_utils.cpp
8ed2ff99c1a429606cc725c15fb7076c *src/string_utils.h
0a19b1dc50e51f9087e3ec389495b95c *src/surfArea.cpp
e652316257a89e196195bc21749e6ee3 *src/vecmath.cpp
c7ba2153430978f4d1ac306aa75f7f35 *src/vecmath.h
3bd60fc636b2de507549ec4f8249fbab *src/vecmathse.cpp
445b7456d033e07766fc1a17fe0b8a2b *src/vecmathse.h
45384676e1f54eedf3cd5f94ee39533d *src/vector_methods.cpp
34796d2a5d565bf5675947e8eed9a58b *src/watershed_internal.cpp
90ea0c1db389e9259ead0e4beb6b7c17 *src/watershed_internal.h
35f2d76ce320f8d9ee555585787ed8ce *src/write.cpp
a2993ec81ea596bf40a04bdcc7bd482f *src/write_gdal.cpp
03fc3ed223cf273c03117c9c16e98749 *src/write_ogr.cpp
a6a6d9ea4118f5c809396420826a3d35 *tests/tinytest.R
terra/R/ 0000755 0001762 0000144 00000000000 14757467211 011606 5 ustar ligges users terra/R/plot_raster.R 0000644 0001762 0000144 00000066062 14736572530 014277 0 ustar ligges users
hexcols <- function(out) {
get_col <- function(cols, alpha) {
if (isTRUE(alpha < 255)) {
grDevices::rgb(t(grDevices::col2rgb(cols, alpha=TRUE)), alpha=alpha, maxColorValue=255)
} else {
i <- !grepl("^#", cols)
cols[i] <- grDevices::rgb(t(grDevices::col2rgb(cols[i], alpha=FALSE)), maxColorValue=255)
cols
}
}
if (NCOL(out$cols) == 1) {
out$cols <- get_col(out$cols, out$alpha)
} else if (NCOL(out$cols) == 2) {
out$cols[,2] <- get_col(out$cols[,2], out$alpha)
} else if (NCOL(out$cols) == 3) {
out$cols[,3] <- get_col(out$cols[,3], out$alpha)
}
out
}
.default.pal <- function() {
opt.pal <- options("terra.pal")[[1]]
if (is.null(opt.pal)) {
map.pal("viridis", 100)
} else {
opt.pal
}
}
.as.raster.rgb <- function(out, x) {
if (is.null(out$rgb$scale)) {
scale <- 255
if ( all(hasMinMax(x)) ) {
rng <- minmax(x)[, 1:3]
scale <- max(max(rng[2]), 255)
}
} else {
scale <- out$rgb$scale
}
if (!is.null(out$rgb$zlim)) {
if (length(out$rgb$zlim) == 2) {
out$rgb$zlim <- sort(out$rgb$zlim)
if (isTRUE(out$rgb$zcol)) {
x <- clamp(x, out$rgb$zlim[1], out$rgb$zlim[2], values=TRUE)
} else { #if (is.na(zlimcol)) {
x <- clamp(x, out$rgb$zlim[1], out$rgb$zlim[2], values=FALSE)
}
} else if (NROW(out$rgb$zlim) == 3 & NCOL(out$rgb$zlim) == 2) {
for (i in 1:3) {
zmin <- min(out$rgb$zlim[i,])
zmax <- max(out$rgb$zlim[i,])
if (isTRUE(out$rgb$zcol)) {
x[[i]] <- clamp(x[[i]], zmin, zmax, values=TRUE)
} else { #if (is.na(zlimcol)) {
x[[i]] <- clamp(x[[i]], zmin, zmax, values=FALSE)
}
}
} else {
error('zlim should be a vector of two numbers or a 3x2 matrix (one row for each color)')
}
}
if (!is.null(out$rgb$stretch)) {
if (out$rgb$stretch == "lin") {
if ((!is.null(out$rgb$zlim)) && (length(out$rgb$zlim) == 2)) {
x <- stretch(x, smin=out$rgb$zlim[1], smax=out$rgb$zlim[2])
} else {
x <- stretch(x, minq=0.02, maxq=0.98)
}
} else {
x <- stretch(x, histeq=TRUE, scale=255)
}
scale <- 255
}
RGB <- values(x)
RGB <- stats::na.omit(RGB)
naind <- as.vector( attr(RGB, "na.action") )
if (ncol(RGB) == 4) {
alpha <- RGB[,4]
RGB <- RGB[,-4]
} else {
alpha <- out$alpha
}
if (!is.null(naind)) {
bg <- grDevices::col2rgb(out$rgb$colNA)
if (is.null(out$rgb$bgalpha)) out$rgb$bgalpha <- 255
bg <- grDevices::rgb(bg[1], bg[2], bg[3], alpha=out$rgb$bgalpha, maxColorValue=255)
z <- rep( bg, times=ncell(x))
z[-naind] <- grDevices::rgb(RGB[,1], RGB[,2], RGB[,3], alpha=alpha, maxColorValue=scale)
} else {
z <- grDevices::rgb(RGB[,1], RGB[,2], RGB[,3], alpha=alpha, maxColorValue=scale)
}
out$r <- matrix(z, nrow=nrow(x), ncol=ncol(x), byrow=TRUE)
out
}
.as.raster.continuous <- function(out, x, type) {
Z <- as.matrix(x, wide=TRUE)
Z[is.nan(Z) | is.infinite(Z)] <- NA
Z[] <- round(Z, 12)
# loss of precision
# z <- stats::na.omit(round(as.vector(Z), 12))
z <- stats::na.omit(as.vector(Z))
n <- length(z)
if (n == 0) {
#out$values = FALSE
out$range <- c(NA, NA)
out$legend_draw <- FALSE
return(out)
}
uzi <- unique(z)
if (type == "depends") {
if (length(uzi) < 9) {
return (.as.raster.classes(out, x, Z=Z))
}
} else if ((length(uzi) == 1) && is.null(out$range)) {
return (.as.raster.classes(out, x, Z=Z))
}
if (is.null(out$range)) {
out$range <- range(z)
# out$fill_range <- FALSE
} else {
stopifnot(length(out$range) == 2)
if (out$fill_range) {
out$range_filled <- c(FALSE, FALSE)
if (!is.na(out$range[1])) {
if (out$range[1] > min(z)) {
out$range_filled[1] <- TRUE
Z[ Z < out$range[1] ] <- out$range[1]
}
} else {
out$range[1] <- min(z, na.rm=TRUE)
}
if (!is.na(out$range[2])) {
if (out$range[2] < max(z)) {
Z[ Z > out$range[2] ] <- out$range[2]
out$range_filled[2] <- TRUE
}
} else {
out$range[2] <- max(z, na.rm=TRUE)
}
} else {
if (all(is.na(out$range))) {
out$range <- range(z)
} else if (is.na(out$range[1])) {
out$range[1] <- min(z)
} else if (is.na(out$range[2])) {
out$range[2] <- max(z)
}
}
if (!any(out$range_filled)) out$fill_range <- FALSE
}
breaks <- .get_breaks(z, length(out$cols), "eqint", out$range)
# if (isTRUE(out$fill_range)) {
# zrng <- range(z)
# breaks[1] <- zrng[1]
# breaks[length(breaks)] <- zrng[2]
# out$frange <- zrng
# } else {
# out$frange <- out$range
# }
if (length(breaks) == 1) {
Z[] <- out$cols[ceiling(length(out$cols)/2)]
} else {
Z[] <- out$cols[as.integer(cut(as.numeric(Z), breaks, include.lowest=TRUE, right=FALSE))]
}
out$r <- as.raster(Z)
out$legend_type <- "continuous"
if (is.null(out$levels)) {
out$levels <- 5
}
if (is.null(out$leg$digits)) {
dif <- diff(out$range)
if ((dif == 0) || (length(dif) ==0)) {
out$leg$digits <- 0;
} else {
out$leg$digits <- max(0, -floor(log10(dif/10)))
}
}
if (is.null(out$leg$x)) out$leg$x <- "right"
out
}
prettyNumbs <- function(x, digits) {
x <- formatC(x, digits=digits, format = "f", flag="#")
x <- substr(x, 1, digits+1)
gsub("\\.$", "", x)
}
.as.raster.classes <- function(out, x, Z=NULL, ...) {
if (is.null(Z)) {
Z <- as.matrix(x, wide=TRUE)
Z[is.nan(Z) | is.infinite(Z)] <- NA
}
if (all(is.na(Z))) {
#out$values = FALSE
out$range <- c(NA, NA)
out$legend_draw <- FALSE
return(out)
}
fz <- as.factor(Z)
if (!is.null(out$levels)) {
if (is.null(out$leg$legend)) {
out$leg$legend <- as.character(out$levels)
}
levs <- out$levels
} else {
levs <- as.numeric(levels(fz))
digits <- out$leg$digits
if (is.null(digits)) {
if (length(levs) > 1) {
d <- ceiling(1 / min(diff(sort(levs))))
decimals <- round(log10(d) + 1)
} else {
txt <- format(levs, scientific = FALSE, digits=18)
txt <- unlist(strsplit(txt, "\\."))
if (nchar(txt[1]) > 3) decimals <- 0
else if (nchar(txt[1]) > 2) decimals <- 1
else if (nchar(txt[1]) > 1) decimals <- 2
else if (txt[1] != "0") decimals <- 3
else if (length(txt) > 1) {
txt <- unlist(strsplit(txt[2], ""))
i <- which(txt != "0")[1]
if (length(i) > 0) decimals <- i+2
else decimals <- 9;
} else {
decimals <- 0
}
}
levs <- round(levs, decimals)
}
out$levels <- levs
if (is.null(out$leg$legend)) {
if (!is.null(out$leg$digits)) {
out$leg$legend <- prettyNumbs(levs, digits)
} else {
out$leg$legend <- levs
}
}
}
out$leg$digits <- NULL
stopifnot(length(out$leg$legend) == length(out$levels))
nlevs <- length(levs)
if (NCOL(out$cols) == 2) {
i <- match(Z, as.numeric(levs))
Z[] <- out$cols[,2][i]
i <- match(as.numeric(levs), out$cols[,1])
out$leg$fill <- out$cols[i,2]
} else {
ncols <- length(out$cols)
if (nlevs == 1) {
cols <- out$cols[length(out$cols)]
} else if (nlevs < ncols) {
i <- round(seq(1, ncols, length.out = nlevs))
cols <- out$cols[i]
} else {
cols <- rep_len(out$cols, nlevs)
}
out$leg$fill <- cols
Z[] <- cols[as.numeric(fz)]
}
out$r <- as.raster(Z)
out$legend_type <- "classes"
if (is.null(out$leg$x)) {
if (is.null(out$leg$ext)) {
out$leg$x = "default"
out$leg$y = NULL
} else {
if (length(out$leg$ext) == 4) {
out$leg$x = out$leg$ext[1]
out$leg$y = out$leg$ext[4]
} else {
out$leg$x = "default"
out$leg$y = NULL
}
}
}
out
}
.as.raster.factor <- function(out, x, ...) {
z <- round(values(x))
#z[z<1 | z>256] <- NA
z[is.nan(z) | is.infinite(z)] <- NA
if (all(is.na(z))) {
#out$values = FALSE
out$range <- c(NA, NA)
out$legend_draw <- FALSE
return(out)
}
out$levels <- sort(stats::na.omit(unique(z)))
if (out$all_levels) {
ilevels <- 1:nrow(out$cats)
out$levels <- out$cats[,1]
} else {
ilevels <- match(out$levels, out$cats[[1]])
if (any(is.na(ilevels))) {
warn("plot", "unknown categories in raster values")
}
}
if (!is.null(out$coltab)) {
# avoid multiple colors for the same category
ilevs <- stats::na.omit(ilevels)
ulevs <- unique(out$cats[ilevs,2])
if (length(ulevs) < length(ilevs)) {
z <- out$cats[match(z, out$cats[,1]),2]
i <- match(ulevs, out$cats[ilevels,2])
j <- out$cats[ilevs[i],]
z <- j[match(z, j[,2]), 1]
out$cats <- j
out$levels <- sort(stats::na.omit(unique(z)))
#out$coltabt = out$coltab[match(j[,1], out$coltab[,1]), ]
if (out$all_levels) {
ilevels <- 1:nrow(out$cats)
out$levels <- out$cats[,1]
} else {
ilevels <- match(out$levels, out$cats[[1]])
}
}
if (out$all_levels) {
mi <- match(out$cats[[1]], out$coltab[,1])
mi[is.na(mi)] <- 1
mc <- out$coltab[mi, ,drop=FALSE]
out$leg$fill <- grDevices::rgb(mc[,2], mc[,3], mc[,4], mc[,5], maxColorValue=255)
if (is.null(out$leg$legend)) out$leg$legend <- stats::na.omit(out$cats[, 2])
} else {
out$levels <- out$levels[!is.na(ilevels)]
m <- stats::na.omit(match(out$cats[[1]][ilevels], out$coltab[,1]))
if (is.null(out$leg$legend)) out$leg$legend <- stats::na.omit(out$cats[ilevels, 2])
out$coltab <- out$coltab[m, ,drop=FALSE]
}
out$cols <- grDevices::rgb(out$coltab[,2], out$coltab[,3], out$coltab[,4], out$coltab[,5], maxColorValue=255)
i <- match(z, out$coltab[,1])
z <- out$cols[i]
} else {
if (is.null(out$leg$legend)) out$leg$legend <- unique(stats::na.omit(out$cats[ilevels, 2]))
levlab <- data.frame(id=out$levels, lab=out$cats[ilevels, 2], stringsAsFactors=FALSE)
leglevs <- stats::na.omit(unique(levlab[,2]))
if (length(leglevs) == 0) {
error("plot", "something is wrong with the categories")
}
nlevs <- length(leglevs)
ncols <- length(out$cols)
#ncats <- nrow(out$cats)
if (nlevs < ncols) {
i <- round(seq(1, ncols, length.out = nlevs))
out$cols <- out$cols[i]
} else if (nlevs > ncols) {
out$cols <- rep_len(out$cols, nlevs)
}
out$leg$fill <- out$cols
#out$cols <- out$cols[ilevels]
dd <- data.frame(lab=leglevs, out$cols)
m <- merge(levlab, dd)
z <- m$out.cols[match(z, m$id)]
}
if (!out$all_levels) {
out$leg$fill <- out$cols
}
z <- matrix(z, nrow=nrow(x), ncol=ncol(x), byrow=TRUE)
out$r <- as.raster(z)
out$legend_type <- "classes"
if (is.null(out$leg$x)) {
if (is.null(out$leg$ext)) {
out$leg$x = "default"
out$leg$y = NULL
} else {
if (length(out$leg$ext) == 4) {
out$leg$x = out$leg$ext[1]
out$leg$y = out$leg$ext[4]
} else {
out$leg$x = "default"
out$leg$y = NULL
}
}
}
if (!is.null(out$legend_order)) {
ord <- match(out$legend_order, out$leg$legend)
out$leg$legend <- out$leg$legend[ord]
out$leg$fill <- out$leg$fill[ord]
} else if (isTRUE(out$legend_sort)) {
ord <- order(out$leg$legend, decreasing=out$legend_sort_decreasing)
out$leg$legend <- out$leg$legend[ord]
out$leg$fill <- out$leg$fill[ord]
}
out
}
# to be merged with the vector variant.
.generic.interval <- function(out, Z) {
if (is.null(out$breaks)) {
out$breaks <- 5
}
if (length(out$breaks) == 1) {
out$breaks <- .get_breaks(Z, out$breaks, out$breakby, out$range)
}
if (!is.null(out$leg$digits)) {
# out$leg$legend <- substr(formatC(levs, digits=digits, format = "f", flag="#"), 1, digits+1)
fz <- cut(as.numeric(Z), out$breaks, include.lowest=TRUE, right=FALSE, dig.lab=out$leg$digits)
} else {
fz <- cut(as.numeric(Z), out$breaks, include.lowest=TRUE, right=FALSE)
}
out$vcut <- as.integer(fz)
levs <- levels(fz)
nlevs <- length(levs)
cols <- out$cols
ncols <- length(cols)
if (nlevs < ncols) {
i <- trunc((ncols / nlevs) * 1:nlevs)
cols <- cols[i]
} else {
cols <- rep_len(cols, nlevs)
}
#out$cols <- cols
out$leg$fill <- cols
#out$leg$levels <- levels(fz)
if (!is.null(out$leg$legend)) {
stopifnot(length(out$leg$legend) == nlevs)
} else {
levs <- gsub("]", "", gsub(")", "", gsub("\\[", "", levs)))
levs <- paste(levs, collapse=",")
m <- matrix(as.numeric(unlist(strsplit(levs, ","))), ncol=2, byrow=TRUE)
if (!is.null(out$leg$digits)) {
m <- prettyNumbs(m, out$leg$digits)
}
m <- apply(m, 1, function(i) paste(i, collapse=" - "))
m <- gsub("-Inf -", "<=", m)
i <- grep("- Inf", m)
if (length(i) == 1) {
m[i] <- gsub("- Inf", "", m[i])
m[i] <- paste(">", m[i])
}
out$leg$legend <- m
}
out$leg$digits <- NULL
out
}
.as.raster.interval <- function(out, x, ...) {
out$legend_type <- "classes"
if (NCOL(out$cols) == 3) {
rcl <- cbind(as.matrix(out$cols[,1:2]), 1:nrow(out$cols))
x <- classify(x, rcl, include.lowest=TRUE, others=NA)
m <- apply(out$cols[,1:2], 1, function(i) paste(i, collapse=" - "))
out$leg$legend <- m
out$leg$fill <- out$cols[,3]
Z <- as.matrix(x, wide=TRUE)
Z[is.nan(Z) | is.infinite(Z)] <- NA
Z[] <- out$leg$fill[Z]
} else {
Z <- as.matrix(x, wide=TRUE)
Z[is.nan(Z) | is.infinite(Z)] <- NA
out <- .generic.interval(out, Z)
Z[] <- out$leg$fill[out$vcut]
}
if (is.null(out$leg$x)) { # && is.null(out$leg$ext)) {
out$leg$x <- "default"
}
out$r <- as.raster(Z)
out
}
# leg.shrink=c(0,0), leg.main=NULL, leg.main.cex = 1, leg.digits=NULL, leg.loc=NULL, leg.ext=NULL, leg.levels=NULL, leg.labels=NULL, leg.at=NULL,
.as.raster.colortable <- function(out, x, ...) {
z <- round(values(x))
#z[z<0 | z>255] <- NA
z[is.nan(z) | is.infinite(z)] <- NA
if (all(is.na(z))) {
out$values = FALSE
return(out)
}
out$cols <- grDevices::rgb(out$coltab[,2], out$coltab[,3], out$coltab[,4], out$coltab[,5], maxColorValue=255)
i <- match(z, out$coltab[,1])
z <- out$cols[i]
z <- matrix(z, nrow=nrow(x), ncol=ncol(x), byrow=TRUE)
out$r <- as.raster(z)
out
}
.plotit <- function(x) {
if (is.null(x$r)) {
x$values = FALSE
}
if (x$add) {
reset.clip()
} else if (!x$legend_only) {
old.mar <- graphics::par()$mar
if (!any(is.na(x$mar))) { graphics::par(mar=x$mar) }
if (x$reset) on.exit(graphics::par(mar=old.mar))
arglist <- c(list(x=x$lim[1:2], y=x$lim[3:4], type="n", xlab="", ylab="", asp=x$asp, xaxs=x$xaxs, yaxs=x$yaxs, axes=FALSE), x$dots)
do.call(plot, arglist)
if (!is.null(x$background)) {
graphics::rect(x$lim[1], x$lim[3], x$lim[2], x$lim[4], col=x$background, border=TRUE)
}
}
if (!x$values) {
if (!x$add) try(set.clip(x$lim, x$lonlat))
return(x)
}
if (!x$legend_only) {
graphics::rasterImage(x$r, x$ext[1], x$ext[3], x$ext[2], x$ext[4],
angle = 0, interpolate = x$interpolate)
if (x$axes) x <- .plot.axes(x)
}
if (x$legend_draw) {
if (x$legend_type == "continuous") {
x <- do.call(.plot.cont.legend, list(x=x))
# } else if (x$legend_type == "classes") {
} else {
if (x$add) {
if (x$clip) {
x$leg$plotlim <- unlist(get.clip()[1:4])
} else {
x$leg$plotlim <- graphics::par("usr")
}
if (is.null(x$leg$plotlim)) {
x$leg$plotlim <- x$lim
}
} else {
if (x$clip) {
x$leg$plotlim <- x$lim
} else {
x$leg$plotlim <- graphics::par("usr")
}
}
x$leg$used <- do.call(.plot.class.legend, x$leg)
}
}
if (isTRUE(x$box)) {
if (x$clip) {
lines(ext(x$lim))
} else {
lines(ext(graphics::par("usr")))
}
}
if ((x$main != "") && (!x$add) && (!x$legend_only)) {
pos <- 3
if (is.null(x$loc.main)) {
if (isTRUE(x$clip)) {
x$loc.main <- c(x$lim[1] + diff(x$lim[1:2]) / 2, x$lim[4])
} else {
usr <- graphics::par("usr")
x$loc.main <- c(usr[1] + diff(usr[1:2]) / 2, usr[4])
}
} else if (inherits(x$loc.main, "character")) {
xyp <- .txt.loc(x)
x$loc.main <- xyp[1:2]
pos <- xyp[3]
}
if (isTRUE(x$halo.main)) {
.halo(x$loc.main[1], x$loc.main[2], x$main, pos=pos, offset=x$line.main, cex=x$cex.main,
font=x$font.main, col=x$col.main, xpd=TRUE, hc=x$halo.main.hc, hw=x$halo.main.hw)
} else {
text(x$loc.main[1], x$loc.main[2], x$main, pos=pos, offset=x$line.main, cex=x$cex.main,
font=x$font.main, col=x$col.main, xpd=TRUE)
}
}
if (!x$add) {
try(set.clip(x$lim, x$lonlat))
}
invisible(x)
}
.prep.plot.data <- function(x, type, cols, mar=NULL, draw=FALSE,
interpolate=FALSE, legend=TRUE, legend.only=FALSE, pax=list(), plg=list(),
levels=NULL, add=FALSE, range=NULL, fill_range=FALSE, breaks=NULL, breakby="eqint",
coltab=NULL, cats=NULL, xlim=NULL, ylim=NULL, ext=NULL, colNA=NA, alpha=NULL, reset=FALSE,
sort=TRUE, decreasing=FALSE, grid=FALSE, las=0, all_levels=FALSE, decimals=NULL, background=NULL,
xlab="", ylab="", cex.lab=0.8, line.lab=1.5, asp=NULL, yaxs="i", xaxs="i", main="", cex.main=1.2,
line.main=0.5, font.main=graphics::par()$font.main, col.main = graphics::par()$col.main, loc.main=NULL,
halo=FALSE, hc="white", hw=0.1, axes=TRUE, box=TRUE, cex=1, maxcell=500000, buffer=FALSE, clip=TRUE,
# for rgb
stretch=NULL, scale=NULL, bgalpha=NULL, zlim=NULL, zcol=NULL, overview=NULL, ...) {
#cex is catch and kill
out <- list()
e <- out$lim <- out$ext <- as.vector(ext(x))
hadWin <- hasWin <- FALSE
if (add && is.null(ext)) {
ext <- unlist(get.clip())[1:4]
}
if ((!is.null(ext)) || (!is.null(xlim)) || (!is.null(ylim))) {
if (!is.null(ext)) {
ext <- ext(ext)
#e <- as.vector(align(ext, x))
e <- as.vector(ext)
out$lim <- out$ext <- e
}
if (!is.null(xlim)) {
stopifnot(length(xlim) == 2)
e[1:2] <- sort(xlim)
}
if (!is.null(ylim)) {
stopifnot(length(ylim) == 2)
e[3:4] <- sort(ylim)
}
out$lim <- e
hasWin <- TRUE
hadWin <- window(x)
oldWin <- ext(x)
w <- intersect(ext(x), ext(e))
window(x) <- out$ext <- w
}
if (ncell(x) > 1.1 * maxcell) {
if (is.null(overview)) {
if (grepl("https://", tolower(sources(x))[1])) {
overview <- TRUE
} else {
overview <- FALSE
}
}
if (inherits(alpha, "SpatRaster")) {
if (nlyr(alpha) > 1) {
alpha <- alpha[[1]]
}
# alpha <- spatSample(alpha, maxcell, method="regular", as.raster=TRUE, warn=FALSE)
alpha <- sampleRaster(alpha, maxcell, method="regular", replace=FALSE, ext=NULL, warn=FALSE, overview=overview)
}
# x <- spatSample(x, maxcell, method="regular", as.raster=TRUE, warn=FALSE)
x <- sampleRaster(x, maxcell, method="regular", replace=FALSE, ext=NULL, warn=FALSE, overview=overview)
out$lim <- out$ext <- as.vector(ext(x))
}
if (buffer) {
dx <- diff(out$lim[1:2]) / 50
dy <- diff(out$lim[3:4]) / 50
out$lim[1:2] <- out$lim[1:2] + c(-dx, dx)
out$lim[3:4] <- out$lim[3:4] + c(-dy, dy)
}
out$add <- isTRUE(add)
out$axs <- as.list(pax)
if (is.null(out$axs$las)) out$axs$las <- las
if (is.null(out$axs$cex.lab)) out$axs$cex.lab <- cex.lab
if (is.null(out$axs$line.lab)) out$axs$line.lab <- line.lab
out$draw_grid <- isTRUE(grid)
out$leg$digits <- decimals
out$leg <- as.list(plg)
out$all_levels <- isTRUE(all_levels)
if (is.null(asp)) {
out$lonlat <- is.lonlat(x, perhaps=TRUE, warn=FALSE)
if (out$lonlat) {
out$asp <- 1/cos((mean(out$ext[3:4]) * pi)/180)
} else {
out$asp <- 1
}
} else {
out$asp <- asp
out$lonlat <- FALSE
}
out$cols <- cols
if (!is.null(alpha)) {
if (!inherits(alpha, "SpatRaster")) {
out$alpha <- alpha[1]
if ((alpha < 0) || (alpha > 1)) {
warn("plot", "alpha should be between 0 and 1")
out$alpha <- 255
} else {
out$alpha <- out$alpha[1] * 255
}
out <- hexcols(out)
}
} else {
out$alpha <- 255
out <- hexcols(out)
}
out$rgb$stretch <- stretch
out$rgb$scale <- scale
out$rgb$bgalpha <- bgalpha
out$rgb$zlim <- zlim
out$rgb$zcol <- isTRUE(zcol)
if (is.null(colNA) || is.na(colNA)) {
out$rgb$colNA <- "white"
} else {
out$rgb$colNA = colNA
}
out$clip <- isTRUE(clip)
out$dots <- list(...)
out$reset <- reset
out$main <- main
out$halo.main <- halo
out$halo.main.hc <- hc
out$halo.main.hw <- hw
out$loc.main <- loc.main
out$cex.main <- cex.main
out$font.main <- font.main
out$col.main <- col.main
out$line.main <- line.main
out$axes <- axes
out$xaxs <- xaxs
out$yaxs <- yaxs
out$xlab <- xlab
out$ylab <- ylab
out$coltab <- coltab
out$cats <- cats
out$breaks <- breaks
out$breakby <- breakby
out$interpolate <- FALSE
out$background <- background
out$legend_draw <- isTRUE(legend)
out$legend_only <- isTRUE(legend.only)
if (!is.logical(sort)) {
out$legend_order <- sort
out$legend_sort <- FALSE
} else {
out$legend_sort <- isTRUE(sort)
}
out$legend_sort_decreasing <- isTRUE(decreasing)
out$box <- isTRUE(box)
if (!is.null(out$leg$loc)) {
out$leg$x <- out$leg$loc
out$leg$loc <- NULL
}
if (!hasValues(x)) {
out$values <- FALSE
out$legend_draw <- FALSE
#warn("plot", "SpatRaster has no cell values")
} else {
out$values <- TRUE
if (type=="factor") {
out <- .as.raster.factor(out, x)
} else if (type=="rgb") {
out <- .as.raster.rgb(out, x)
out$interpolate <- isTRUE(interpolate)
} else if (type=="colortable") {
out <- .as.raster.colortable(out, x)
} else if (type=="classes") {
out$levels <- levels
out <- .as.raster.classes(out, x)
} else if (type=="interval") {
out <- .as.raster.interval(out, x)
} else {
out$interpolate <- isTRUE(interpolate)
out$range <- range
out$fill_range <- fill_range
out <- .as.raster.continuous(out, x, type)
}
if (is.null(mar)) {
out$mar <- c(2, 2, 2, 2)
if (out$legend_draw) {
if (is.null(out$leg$ext)) {
if (is.null(out$leg$x)) {
out$leg$x <- "default"
out$mar <- c(2, 2, 2, 4)
} else if (out$legend_type == "continuous") {
if (out$leg$x == "top") {
out$mar <- c(2, 2, 4, 2)
} else if (out$leg$x == "bottom") {
out$mar <- c(4, 2, 2, 2)
} else if (out$leg$x == "left") {
out$mar <- c(2, 5, 2, 1)
} else {
out$mar <- c(2, 2, 2, 4)
}
} else if (out$leg$x == "default") {
out$mar <- c(2, 2, 2, 4)
}
}
}
} else {
out$mar <- rep_len(mar, 4)
}
if (!is.null(colNA)) {
if (!is.na(colNA) && out$values) {
out$colNA <- grDevices::rgb(t(grDevices::col2rgb(colNA)), alpha=out$alpha, maxColorValue=255)
out$r[is.na(out$r)] <- out$colNA
}
}
}
if (draw) {
if (inherits(alpha, "SpatRaster")) {
alpha <- clamp(as.vector(alpha[[1]])*255, 0, 255)
out$r <- matrix(grDevices::rgb(t(grDevices::col2rgb(out$r)), alpha=alpha, maxColorValue=255),
nrow=nrow(out$r), byrow=TRUE)
}
out <- .plotit(out)
}
if (any(hasWin)) {
window(x) <- NULL
if (any(hadWin)) {
window(x) <- oldWin
}
}
invisible(out)
}
setMethod("plot", signature(x="SpatRaster", y="numeric"),
function(x, y=1, col, type=NULL, mar=NULL, legend=TRUE, axes=!add, plg=list(), pax=list(), maxcell=500000, smooth=FALSE, range=NULL, fill_range=FALSE, levels=NULL, all_levels=FALSE, breaks=NULL, breakby="eqint", fun=NULL, colNA=NULL, alpha=NULL, sort=FALSE, decreasing=FALSE, grid=FALSE, ext=NULL, reset=FALSE, add=FALSE, buffer=FALSE, background=NULL, box=axes, clip=TRUE, overview=NULL, ...) {
old.mar <- graphics::par()$mar
on.exit(graphics::par(mar=old.mar))
y <- round(y)
hasRGB <- FALSE
if (has.RGB(x) && ((is.null(type) && (y[1] < 0)))) {
type <- "rgb"
legend <- FALSE
if (is.null(mar)) {
mar <- 0
axes <- FALSE
}
hasRGB <- TRUE
y <- RGB(x)
}
nlx <- nlyr(x)
stopifnot((min(y) > 0) & (max(y) <= nlx))
if ((!hasRGB) && (length(y) > 1)) {
x <- x[[y]]
if (inherits(alpha, "SpatRaster")) {
if (nlyr(alpha) > 1) {
alpha <- alpha[[y]]
}
}
plot(x, col=col, type=type, mar=mar, legend=legend, axes=axes, plg=plg, pax=pax, maxcell=2*maxcell/length(y), smooth=smooth, range=range, fill_range=fill_range, levels=levels, all_levels=all_levels, breaks=breaks, breakby=breakby, fun=fun, colNA=colNA, alpha=alpha, grid=grid, sort=sort, decreasing=decreasing, ext=ext, reset=reset, add=add, buffer=buffer, background=background, box=box, clip=clip, overview=overview, ...)
return(invisible())
} else {
x <- x[[y]]
}
if (inherits(alpha, "SpatRaster")) {
if (!compareGeom(x, alpha, crs=FALSE, ext=FALSE, rowcol=TRUE)) {
error("plot", "geometry of alpha does not match x")
}
}
if (is.character(legend)) {
plg$x <- legend
legend <- TRUE
}
if (missing(col)) {
col <- .default.pal()
#col <- rev(grDevices::terrain.colors(255))
} else if (inherits(col, "data.frame")) {
if (ncol(col) == 2) {
type <- "classes"
} else if (ncol(col) == 3) {
type <- "interval"
} else {
error("plot", "number of columns of a col data.frame should be 2 or 3")
}
breaks <- NULL
}
coltab <- NULL
cats <- NULL
if (!is.null(breaks)) {
if (is.null(type)) {
type <- "interval"
} else {
range <- range(breaks)
}
} else {
if (is.null(type)) {
if (has.colors(x)) {
coltab <- coltab(x)[[1]]
if (is.factor(x)) {
if (activeCat(x) >= 0) {
cats <- levels(x)[[1]]
type <- "factor"
} else {
type <- "colortable"
legend <- FALSE
}
} else {
type <- "colortable"
legend <- FALSE
}
} else if (is.factor(x)) {
type <- "factor"
cats <- levels(x)[[1]]
} else if (is.bool(x)) {
type <- "factor"
levels(x) <- data.frame(id=0:1, value=c("False", "True"))
cats <- cats(x)[[1]]
} else {
type <- "depends"
}
} else {
type <- match.arg(type, c("continuous", "classes", "interval", "rgb"))
}
}
if ((type == "classes") && is.null(levels) && is.factor(x)) {
type <- "factor"
cats <- cats(x)[[1]]
if (has.colors(x)) {
coltab <- coltab(x)[[1]]
}
}
x <- .prep.plot.data(x, type=type, cols=col, mar=mar, draw=TRUE, plg=plg, pax=pax, legend=isTRUE(legend), axes=isTRUE(axes), coltab=coltab, cats=cats, interpolate=smooth, levels=levels, range=range, fill_range=fill_range, colNA=colNA, alpha=alpha, reset=reset, grid=grid, sort=sort, decreasing=decreasing, ext=ext, all_levels=all_levels, breaks=breaks, breakby=breakby, add=add, buffer=buffer, background=background, box=box, maxcell=maxcell, clip=clip, overview=overview, ...)
if (!is.null(fun)) {
if (!is.null(formals(fun))) {
fun(y)
} else {
fun()
}
}
invisible(x)
}
)
setMethod("plot", signature(x="SpatRaster", y="missing"),
function(x, y, main, mar=NULL, nc, nr, maxnl=16, maxcell=500000, add=FALSE, ...) {
if (has.RGB(x)) {
if (missing(main)) main = ""
p <- plot(x, -1, main=main, mar=mar, maxcell=maxcell, add=add, ...)
return(invisible(p))
}
nl <- max(1, min(nlyr(x), maxnl))
if (add && (nl > 1)) {
nl <- 1
warn("plot", "adding the first layer of x")
}
if (nl==1) {
if (missing(main)) main = ""
out <- plot(x, 1, maxcell=maxcell, main=main[1], mar=mar, add=add, ...)
return(invisible(out))
}
nrnc <- .get_nrnc(nr, nc, nl)
old.par <- graphics::par(no.readonly = TRUE)
on.exit(graphics::par(old.par))
if (is.null(mar)) {
mar=c(1.5, 1, 2.5, 3)
}
graphics::par(mfrow=nrnc)
maxcell= 2 * maxcell / nl
if (missing("main")) {
tm <- time(x)
if ((!any(is.na(tm))) && (length(unique(tm)) > 1)) {
main <- as.character(time(x))
} else {
main <- names(x)
}
} else {
main <- rep_len(main, nl)
}
for (i in 1:nl) {
plot(x, i, main=main[i], mar=mar, maxcell=maxcell, add=add, ...)
}
}
)
setMethod("plot", signature(x="SpatRaster", y="character"),
function(x, y, ...) {
y <- match(y, names(x))
if (any(is.na(y))) {
error("plot", "y does not match the names in x")
}
plot(x, y, ...)
}
)
setMethod("plotRGB", signature(x="SpatRaster"),
function(x, r=1, g=2, b=3, a=NULL, scale=NULL, mar=0, stretch=NULL, smooth=TRUE,
colNA="white", alpha=NULL, bgalpha=NULL, zlim=NULL, zcol=FALSE, axes=FALSE, ...) {
x <- x[[c(r, g, b, a)]]
RGB(x) <- 1:nlyr(x)
plot(x, -1, scale=scale, mar=mar, stretch=stretch, smooth=smooth, colNA=colNA,
alpha=alpha, bgalpha=bgalpha, zlim=zlim, zcol=zcol, axes=axes, ...)
}
)
terra/R/show.R 0000644 0001762 0000144 00000042003 14726700274 012703 0 ustar ligges users # Author: Robert J. Hijmans
# Date : June 2017
# Version 1.0
# License GPL v3
win_basename <- function(x) {
if (isTRUE(grepl("Windows", utils::osVersion))) {
large <- nchar(x) > 256
if (any(large)) {
for (i in 1:length(large)) {
if (large[i]) {
r <- strsplit(x[i], "[\\/]+")[[1]]
x[i] <- r[[length(r)]]
} else {
x[i] <- basename(x)
}
}
} else {
x <- basename(x)
}
x
} else {
basename(x)
}
}
printDF <- function(x, n=6, first=FALSE) {
n <- min(nrow(x), max(n, 0))
old <- dim(x)
if (old[2] == 0) { return() }
if (old[1] > 0) {
x <- x[1:n, ,drop=FALSE]
}
if (old[2] > 12) {
x <- x[, 1:10]
}
d <- dim(x)
cls <- sapply(x, function(i){ a = class(i); a[length(a)]})
cls <- gsub("integer", "int", cls)
cls <- gsub("numeric", "num", cls)
cls <- gsub("character", "chr", cls)
cls <- gsub("factor", "fact", cls)
cls <- paste0("<", cls, ">")
cls <- data.frame(rbind(class=cls), stringsAsFactors=FALSE)
names(cls) <- NULL
nms <- colnames(x)
nc <- nchar(nms)
mx <- max(15, 100/d[2])
i <- nc > (mx+2)
nms[i] <- paste0(substr(nms[i], 1, (mx-1)), "~")
if (d[1] > 0) {
for (i in 1:ncol(x)) {
if (is.character(x[[i]])) {
x[[i]][is.na(x[[i]])] <- "NA"
n <- nchar(x[[i]])
j <- n > (mx+2)
x[[i]][j] <- paste0(substr(x[[i]][j], 1, (mx-1)), "~")
} else if (is.numeric(x[[i]])) {
x[[i]] <- formatC(x[[i]])
}
}
}
x <- data.frame(lapply(x, as.character), check.names=FALSE, stringsAsFactors=FALSE)
x <- rbind(x[1,,drop=FALSE], x)
x[1,] <- cls
if (nrow(x) < d[1]) {
x <- rbind(x, "...")
}
if (first) {
x <- data.frame("", x, check.names=FALSE, stringsAsFactors=FALSE)
colnames(x)[1] <- "names :"
x[1,1] <- "type :"
if (d[1] > 0) {
x[2,1] <- "values :"
}
}
if (old[2] > d[2]) {
name <- paste0("(and ", old[2] - d[2], " more)")
x[[name]] <- ""
}
print(x, row.names = FALSE)
}
setMethod ("show" , "Rcpp_SpatDataFrame",
function(object) {
cat("class :" , class(object), "\n")
object <- .getSpatDF(object)
d <- dim(object)
cat("dimensions : ", d[1], ", ", d[2], " (nrow, ncol)\n", sep="" )
n <- 6
if (d[1] > 6) {
cat("values (head)\n")
} else {
cat("values\n")
}
printDF(object)
}
)
setMethod ("show" , "Rcpp_SpatCategories",
function(object) {
show(object$df)
}
)
setMethod ("show" , "SpatExtent",
function(object) {
e <- as.vector(object)
e <- paste(e, collapse=", ")
cat("SpatExtent :", e, "(xmin, xmax, ymin, ymax)\n")
}
)
setMethod ("show" , "SpatVectorCollection",
function(object) {
cat(" class :", class(object), "\n")
cat(" length :", length(object), "\n")
n <- nn <- length(object)
if (n > 15) {
nn <- 15
}
if (n > 0) {
for (i in 1:nn) {
v <- object[i]
if (i==1) {
cat(" geometry : ", geomtype(v), " (", nrow(v) , ")\n", sep="")
} else {
cat(" ", geomtype(v), " (", nrow(v) , ")\n", sep="")
}
}
if (n > nn) {
cat(" ", " and ", n-nn, "more\n", sep="")
}
crs <- .name_or_proj4(object[1])
if (crs != "") cat(" crs (first) :", crs, "\n")
nms <- names(object)
if (length(nms) > 10) {
nms <- c(nms[1:9], "...")
}
nms <- paste(nms, collapse=", ")
cat(" names :", nms, "\n")
}
}
)
setMethod ("show" , "SpatVector",
function(object) {
e <- as.vector(ext(object))
d <- dim(object)
cat(" class :", class(object), "\n")
cat(" geometry :", geomtype(object), "\n")
cat(" dimensions : ", d[1], ", ", d[2], " (geometries, attributes)\n", sep="" )
cat(" extent : ", e[1], ", ", e[2], ", ", e[3], ", ", e[4], " (xmin, xmax, ymin, ymax)\n", sep="")
if (object@pntr$source != "") {
if (object@pntr$layer != tools::file_path_sans_ext(win_basename(object@pntr$source))) {
cat(" source : ", win_basename(object@pntr$source), " (", object@pntr$layer, ")\n", sep="")
} else {
cat(" source : ", win_basename(object@pntr$source), "\n", sep="")
}
}
cat(" coord. ref. :", .name_or_proj4(object), "\n")
if (d[2] > 0) {
nr <- min(d[1], 3)
dd <- as.data.frame(object)[1:nr, , drop=FALSE]
printDF(dd, 3, TRUE)
}
}
)
setMethod ("show" , "SpatVectorProxy",
function(object) {
e <- as.vector(ext(object))
d <- dim(object)
cat(" class : SpatVectorProxy\n")
cat(" geometry :", geomtype(object), "\n")
cat(" dimensions : ", d[1], ", ", d[2], " (geometries, attributes)\n", sep="" )
cat(" extent : ", e[1], ", ", e[2], ", ", e[3], ", ", e[4], " (xmin, xmax, ymin, ymax)\n", sep="")
if (object@pntr$v$layer != tools::file_path_sans_ext(win_basename(object@pntr$v$source))) {
cat(" source : ", win_basename(object@pntr$v$source), " (", object@pntr$v$layer, ")\n", sep="")
} else {
cat(" source : ", win_basename(object@pntr$v$source), "\n", sep="")
}
cat(" coord. ref. :", .name_or_proj4(object), "\n")
dd <- get.data.frame(object)
printDF(dd, 0, TRUE)
}
)
setMethod ("show" , "SpatRaster",
function(object) {
cat("class :" , class(object), "\n")
d <- dim(object)
cat("dimensions : ", d[1], ", ", d[2], ", ", d[3], " (nrow, ncol, nlyr)\n", sep="" )
#cat ("ncell :" , ncell(object), "\n")
xyres <- res(object)
cat("resolution : " , xyres[1], ", ", xyres[2], " (x, y)\n", sep="")
hw <- window(object)
if (any(hw)) {
w <- as.vector(ext(object))
if (all(hw)) {
txt <- "window : "
} else {
txt <- "extent (win): "
}
cat(txt, w[1], ", ", w[2], ", ", w[3], ", ", w[4], " (xmin, xmax, ymin, ymax)\n", sep="")
#e <- as.vector(object@pntr$source[[1]]$window$full_extent$vector)
#cat("full extent : " , e[1], ", ", e[2], ", ", e[3], ", ", e[4], " (xmin, xmax, ymin, ymax)\n", sep="")
} else {
e <- as.vector(ext(object))
cat("extent : " , e[1], ", ", e[2], ", ", e[3], ", ", e[4], " (xmin, xmax, ymin, ymax)\n", sep="")
}
cat("coord. ref. :" , .name_or_proj4(object), "\n")
if (hasValues(object)) {
mnr <- 6
ln <- names(object)
nl <- d[3]
if (nl > mnr) {
ln <- c(ln[1:mnr], "...")
}
lnmx <- 60 / min(mnr, length(ln))
b <- nchar(ln) > (lnmx+2)
if (isTRUE(any(b))) {
mid <- floor(lnmx/2)
ln[b] <- paste(substr(ln[b], 1, mid), "~", substr(ln[b], nchar(ln[b])-mid+1, nchar(ln[b])), sep="")
}
nsr <- nsrc(object)
m <- inMemory(object)
f <- sources(object)
nf <- nchar(f)
if (any(nf > 256)) {
for (i in 1:length(nf)) {
if (nf[i] > 256) {
f[i] <- unlist(strsplit(f[i], "\\?"))[1]
if (nchar(f[i]) > 256) {
f[i] <- substr(f[i], nf[i]-255, nf[i])
}
}
}
}
hdf5 <- substr(f, 1, 5) == "HDF5:"
f[!hdf5] <- win_basename(f[!hdf5])
if (any(hdf5)) {
ff <- strsplit(f[hdf5], "://")
ff <- sapply(ff, function(i) paste(win_basename(i), collapse="://"))
ff <- gsub('\"', "", ff)
f[hdf5] <- ff
}
#f <- gsub("\\", "/", f, fixed=TRUE)
f <- gsub("\"", "", f)
sources <- rep("memory", length(m))
sources[!m] <- f[!m]
if (all(m)) {
cat("source(s) : memory\n")
} else {
if (nsr > 1) {
mxsrc <- 3
lbs <- .nlyrBySource(object)
lbsprint <- paste0(" (", lbs, " layers)")
lbsprint[lbs == 1] <- ""
cat("sources :", sources[1], lbsprint[1], "\n")
for (i in 2:(min(mxsrc, nsr))) {
cat(" ", sources[i], lbsprint[i], "\n")
}
if (nsr > mxsrc) {
if (nsr == (mxsrc+1)) {
cat(" ", sources[mxsrc+1], lbsprint[mxsrc+1], "\n")
} else {
cat(" ", "... and", nsr-mxsrc, "more sources\n")
}
}
} else {
cat("source :", sources[1], "\n")
}
}
rgbtype <- object@pntr$rgbtype
if (rgbtype != "") {
rdgb <- RGB(object)
if (is.null(rdgb)) rdgb <- 1:3
cat(paste("colors", toupper(object@pntr$rgbtype), " :"), paste(rdgb, collapse=", "), "\n")
}
hasct <- object@pntr$hasColors()
if (any(hasct)) {
cat("color table :", paste(which(hasct), collapse=", "), "\n")
}
varnms <- varnames(object)
fnms <- tools::file_path_sans_ext(f)
if (any(fnms != varnms) && all(varnms != "")) {
longnms <- longnames(object)
i <- longnms != ""
if (any(i)) {
varnms[i] <- paste0(varnms[i], " (", longnms[i], ")")
}
if (nsr == 1) {
cat("varname :", varnms[1], "\n")
} else {
cat("varnames :", varnms[1], "\n")
for (i in 2:(min(nsr, 3))) {
cat(" ", varnms[i], "\n")
}
}
if (nsr > 3) {
cat(" ...\n")
}
}
uts <- units(object)
hasunits <- !all(uts == "")
if (nl > mnr) {
uts <- c(uts[1:mnr], "...")
}
hMM <- hasMinMax(object)
isB <- is.bool(object)
if (any(hMM) || any(is.factor(object))) {
#r <- minmax(object)
rr <- r <- rbind(object@pntr$range_min, object@pntr$range_max)
r[,!hMM] <- c(Inf, -Inf)
#sc <- scoff(object)
#r <- r * sc[,1] + sc[,2]
r <- sapply(data.frame(r), format)
minv <- r[1,]
maxv <- r[2,]
if (any(isB)) {
minv[isB] <- ifelse(minv[isB]=="0", "FALSE", "TRUE")
maxv[isB] <- ifelse(maxv[isB]=="0", "FALSE", "TRUE")
}
minv <- gsub("Inf", " ? ", minv)
maxv <- gsub("-Inf", " ? ", maxv)
minv[!hMM] <- gsub("NaN", " ? ", minv[!hMM])
maxv[!hMM] <- gsub("NaN", " ? ", maxv[!hMM])
minv[hw] <- paste0(">", minv[hw])
maxv[hw] <- paste0(maxv[hw],"<")
if (nl > mnr) {
minv <- c(minv[1:mnr], "...")
maxv <- c(maxv[1:mnr], "...")
}
isf <- is.factor(object)
if (any(isf)) {
cats <- levels(object)
for (i in which(isf)) {
if (i > mnr) break
levs <- cats[[i]]
j <- match(rr[,i], levs[,1])
levs <- levs[j, 2]
if (length(levs) > 1) {
minv[i] <- levs[1]
maxv[i] <- levs[2]
}
}
}
u8 <- Encoding(ln) == "UTF-8"
wln <- nchar(ln)
if (any(u8)) {
# for Chinese: wln <- wln + u8 * wln
w <- pmax(wln, nchar(minv), nchar(maxv), nchar(uts), na.rm = TRUE)
m <- rbind(paste0(rep(" ", max(wln)), collapse=""), minv, maxv)
if (hasunits) m <- rbind(m, uts)
# a loop because "width" is not recycled by format
for (i in 1:ncol(m)) {
m[,i] <- format(m[,i], width=w[i], justify="right")
addsp <- w[i] - nchar(ln[i])
m[1,i] <- paste0(paste0(rep(" ", addsp), collapse=""), ln[i])
}
} else {
w <- pmax(wln, nchar(minv), nchar(maxv), nchar(uts), na.rm = TRUE)
m <- rbind(ln, minv, maxv)
if (hasunits) m <- rbind(m, uts)
# a loop because "width" is not recycled by format
for (i in 1:ncol(m)) {
m[,i] <- format(m[,i], width=w[i], justify="right")
}
}
if (ncol(m) == 1) {
if (is.factor(object)) {
if (activeCat(object) > -1) {
g <- cats(object)[[1]]
cat("categories :", paste(colnames(g)[-1], collapse=", "), "\n")
}
}
cat("name :", paste(m[1,], collapse=", "), "\n")
cat("min value :", paste(m[2,], collapse=", "), "\n")
cat("max value :", paste(m[3,], collapse=", "), "\n")
} else {
cat("names :", paste(m[1,], collapse=", "), "\n")
cat("min values :", paste(m[2,], collapse=", "), "\n")
cat("max values :", paste(m[3,], collapse=", "), "\n")
}
if (hasunits) cat("unit :", paste(m[4,], collapse=", "), "\n")
} else {
w <- pmax(nchar(ln), nchar(uts))
m <- rbind(ln, uts)
for (i in 1:ncol(m)) {
m[,i] <- format(m[,i], width=w[i], justify="right")
}
if (ncol(m) == 1) {
cat("name :", paste(m[1,], collapse=", "), "\n")
} else {
cat("names :", paste(m[1,], collapse=", "), "\n")
}
if (hasunits) cat("unit :", paste(m[2,], collapse=", "), "\n")
}
}
if (object@pntr$hasTime) {
label <- "time "
rtim <- range(time(object))
tims <- object@pntr$timestep
if (tims == "yearmonths") {
rtim <- format_ym(rtim)
label <- "time (ymnts)"
} else if (tims == "months") {
rtim <- month.abb[rtim]
label <- "time (mnts) "
} else if (tims == "years") {
label <- "time (years)"
} else if (tims == "days") {
label <- "time (days) "
} else if (tims == "raw") {
label <- "time (raw) "
}
utim <- unique(rtim)
if (length(utim) > 1) {
ptim <- paste0(label, ": ", paste(rtim, collapse=" to "))
} else {
ptim <- paste0(label, ": ", as.character(utim))
}
if (tims == "seconds") {
tz <- format(utim[1], format="%Z")
ptim <- paste(ptim, tz)
}
cat(ptim, "\n")
}
# else {
# cat("data sources:", "no data\n")
# cat("names :", paste(ln, collapse=", "), "\n")
# }
}
)
.sources <- function(x) {
#m <- inMemory(x)
f <- sources(x)
f <- gsub("\"", "", win_basename(f))
i <- grep(":", f)
if (length(i) > 0) {
for (j in i) {
ff <- try(win_basename( strsplit(f[j], ':')[[1]][1]), silent=TRUE)
if (!inherits(ff, "try-error")) {
f[j] <- ff
}
}
}
f[f==""] <- "memory"
unique(f)
}
setMethod("show" , "SpatRasterDataset",
function(object) {
cat("class :" , class(object), "\n")
ns <- length(object)
cat("subdatasets :", ns, "\n")
if (ns == 0) return()
d <- dim(object)
cat("dimensions :", paste(d, collapse=", "), "(nrow, ncol)\n")
nss <- nlyr(object)
if (length(nss) > 10) {
nss = c(as.character(nss[1:9], "..."))
}
cat("nlyr :", paste(nss, collapse=", "), "\n")
xyres <- res(object)
cat("resolution : " , xyres[1], ", ", xyres[2], " (x, y)\n", sep="")
e <- as.vector(ext(object))
cat("extent : " , e[1], ", ", e[2], ", ", e[3], ", ", e[4], " (xmin, xmax, ymin, ymax)\n", sep="")
cat("coord. ref. :" , .name_or_proj4(object), "\n")
s <- .sources(object)
if (length(s) > 6) {
s <- c(s[1:6], "...")
}
cat("source(s) :", paste(s, collapse=", "), "\n")
ln <- names(object)
if (any(ln != "")) {
if (length(ln) > 6) {
ln <- c(ln[1:6], "...")
}
cat("names :", paste(ln, collapse=", "), "\n")
}
}
)
setMethod("show" , "SpatRasterCollection",
function(object) {
cat("class :" , class(object), "\n")
nr <- length(object)
cat("length :", nr, "\n")
d <- (t(dim(object)))
d[] <- as.character(d)
if (ncol(d) > 14) {
d <- d[,1:15]
d[,15] <- "..."
}
for (i in 1:ncol(d)) {
d[,i] <- format(d[,i], width=max(nchar(d[,i])), justify="right")
}
cat("nrow :", paste(d[1,], collapse=", "), "\n")
cat("ncol :", paste(d[2,], collapse=", "), "\n")
cat("nlyr :", paste(d[3,], collapse=", "), "\n")
e <- as.vector(ext(object))
cat("extent : " , e[1], ", ", e[2], ", ", e[3], ", ", e[4], " (xmin, xmax, ymin, ymax)\n", sep="")
crs <- .name_or_proj4(object@pntr$x[[1]])
if (crs != "") cat("crs (first) :", crs, "\n")
ln <- names(object)
if (any(ln != "")) {
if (length(ln) > 6) {
ln = c(ln[1:6], "...")
}
cat("names :", paste(ln, collapse=", "), "\n")
}
}
)
setMethod("show" , "SpatGraticule",
function(object) {
cat("class :" , class(object), "\n")
v <- vect()
v@pntr <- object@pntr
cat("lon :" , stats::na.omit(v$lon), "\n")
cat("lat :" , stats::na.omit(v$lat), "\n")
cat("coord. ref. :", .name_or_proj4(v), "\n")
e <- as.vector(ext(v))
cat("extent : ", e[1], ", ", e[2], ", ", e[3], ", ", e[4], " (xmin, xmax, ymin, ymax)\n", sep="")
}
)
setMethod ("head" , "SpatVector",
function(x, n=6L, ...) {
nn <- min(n, nrow(x))
if (nn > 0) {
x <- x[1:nn, ]
} else {
x <- x[0,]
}
as.data.frame(x)
}
)
setMethod ("tail" , "SpatVector",
function(x, n=6L, ...) {
nrx <- nrow(x)
nn <- min(n, nrx)
if (nn > 0) {
start <- nrx - nn + 1
x <- x[start:nrx, ]
} else {
x <- x[0,]
}
x <- as.data.frame(x)
if (nn > 0) {
rownames(x) <- start:nrx
}
x
}
)
setMethod ("head" , "SpatRaster",
function(x, n=6L, ...) {
utils::head(x[1:n], n=n, ...)
}
)
setMethod ("tail" , "SpatRaster",
function(x, n=6L, ...) {
nc = ncell(x)
utils::tail(x[(nc-n+1):nc], n=n, ...)
}
)
str.SpatRaster <- function(object, ...) {
cat("S4 class 'SpatRaster' [package \"terra\"]\n")
}
setMethod("str", signature(object="SpatRaster"), str.SpatRaster)
str.SpatVector <- function(object, ...) {
cat("S4 class 'SpatVector' [package \"terra\"]\n")
}
setMethod("str", signature(object="SpatVector"), str.SpatVector)
str.SpatExtent <- function(object, ...) {
cat("S4 class 'SpatExtent' [package \"terra\"]\n")
}
setMethod("str", signature(object="SpatExtent"), str.SpatExtent)
str.SpatGraticule <- function(object, ...) {
cat("S4 class 'SpatGraticule' [package \"terra\"]\n")
}
setMethod("str", signature(object="SpatGraticule"), str.SpatGraticule)
terra/R/SpatRasterDataset.R 0000644 0001762 0000144 00000022263 14726701411 015321 0 ustar ligges users
setMethod("length", signature(x="SpatRasterDataset"),
function(x) {
x@pntr$nsds()
}
)
setMethod("sds", signature(x="character"),
function(x, ids=0, opts=NULL, raw=FALSE) {
if (length(x) > 1) {
r <- lapply(x, rast, opts=opts, raw=raw)
s <- sds(r)
names(s) <- tools::file_path_sans_ext(basename(x))
return(s)
}
x <- trimws(x[1])
if (nchar(x) == 0) {
error("sds", "provide valid file name(s)")
}
f <- .fullFilename(x)
r <- methods::new("SpatRasterDataset")
ids <- round(ids)-1
if (ids[1] < 0) {
useids <- FALSE
} else {
useids <- TRUE
}
if (is.null(opts)) opts <- ""[0]
if (raw) opts <- c(opts, "so=false")
r@pntr <- SpatRasterStack$new(f, ids, useids, opts)
messages(r, "sds")
}
)
setMethod("sds", signature(x="missing"),
function(x) {
r <- methods::new("SpatRasterDataset")
r@pntr <- SpatRasterStack$new()
r
}
)
setMethod("sds", signature(x="SpatRaster"),
function(x, ...) {
r <- methods::new("SpatRasterDataset")
r@pntr <- SpatRasterStack$new()
r@pntr$add(x@pntr, varnames(x)[1], longnames(x)[1], units(x)[1], FALSE)
dots <- list(...)
nms <- names(dots)
if (is.null(nms)) nms = ""
nms <- rep_len(nms, length(dots))
for (i in seq_along(dots)) {
if (inherits(dots[[i]], "SpatRaster")) {
vname <- nms[i]
if (vname == "") vname = varnames(dots[[i]])[1]
r@pntr$add(dots[[i]]@pntr, vname, longnames(dots[[i]])[1], units(dots[[i]])[1], FALSE)
}
}
messages(r, "sds")
}
)
setMethod("sds", signature(x="list"),
function(x) {
r <- methods::new("SpatRasterDataset")
r@pntr <- SpatRasterStack$new()
nms <- names(x)
if (is.null(nms)) nms <- rep("", length(x))
for (i in seq_along(x)) {
if (inherits(x[[i]], "SpatRaster")) {
r@pntr$add(x[[i]]@pntr, nms[i], "", "", FALSE)
} else if (inherits(x[[i]], "SpatRasterDataset")) {
y <- as.list(x[[i]])
ynms <- names(x[[i]])
s <- sapply(y, function(j) r@pntr$add(j@pntr, ynms[j], "", "", FALSE))
} else {
name <- names(x[[i]])
cls <- paste(class(x[[i]]), collapse=", ")
error("sds", "list element", name, "is a: ", cls)
}
}
messages(r, "sds")
}
)
setMethod("sds", signature(x="array"),
function(x, crs="", extent=NULL) {
dims <- dim(x)
if (length(dims) <= 3) {
return(sds(rast(x, crs=crs, extent=extent)))
}
if (length(dims) > 4) {
if (length(dims) == 5) {
if (dims[5] == 1) {
x <- x[,,,,1]
} else {
error("sds,array", "cannot handle an array with 5 dimensions")
}
} else {
error("sds,array", "cannot handle an array with more than 4 dimensions")
}
}
r <- lapply(1:dims[4], function(i) rast(x[,,,i], crs=crs, extent=extent))
sds(r)
}
)
setMethod("sds", signature(x="stars"),
function(x) {
s <- from_stars(x)
if (inherits(s, "SpatRaster")) {
sds(s)
} else {
s
}
}
)
setMethod("sds", signature(x="stars_proxy"),
function(x) {
s <- from_stars(x)
if (inherits(s, "SpatRaster")) {
sds(s)
} else {
s
}
}
)
setMethod("c", signature(x="SpatRasterDataset"),
function(x, ...) {
x@pntr <- x@pntr$subset((1:x@pntr$nsds()) -1 ) # why? make a copy?
dots <- list(...)
nms <- names(dots)
for (i in seq_along(dots)) {
if (inherits(dots[[i]], "SpatRasterDataset")) {
sdsnms <- names(dots[[i]])
for (j in 1:(length(dots[[i]]))) {
if (!x@pntr$add(dots[[i]][[j]]@pntr, sdsnms[j], "", "", FALSE)) {
messages(x, "c")
}
}
} else if (inherits(dots[[i]], "SpatRaster")) {
if (is.null(nms)) error("c", "arguments must be named")
if (!x@pntr$add(dots[[i]]@pntr, nms[i], "", "", FALSE)) {
messages(x, "c")
}
} else {
error("c", "arguments must be SpatRaster or SpatRasterDataset")
}
}
messages(x, "c")
}
)
setReplaceMethod("[", c("SpatRasterDataset", "numeric", "missing"),
function(x, i, j, value) {
if (any(!is.finite(i)) | any(i<1)) {
error("`[`", "invalid index")
}
stopifnot(inherits(value, "SpatRaster"))
i <- sort(i)
for (j in i) {
if (j == (length(x)+1)) {
x@pntr$add(value@pntr, "", "", "", FALSE)
} else {
x@pntr$replace(j-1, value@pntr, FALSE)
}
}
messages(x, "`[`")
}
)
setMethod("[", c("SpatRasterDataset", "numeric", "missing"),
function(x, i, j, drop=TRUE) {
i <- positive_indices(i, length(x), TRUE, "`[`(i)")
if (drop && (length(i) == 1)) {
tptr <- x@pntr$getsds(i-1)
x <- rast()
x@pntr <- tptr
} else {
x@pntr <- x@pntr$subset(i-1)
}
messages(x, "`[`")
})
setMethod("[", c("SpatRasterDataset", "numeric", "numeric"),
function(x, i, j, drop=TRUE) {
i <- positive_indices(i, length(x))
j <- positive_indices(j, min(nlyr(x)))
nd <- i
if (drop) {
out <- lapply(nd, function(k) x[k][[j]])
out <- rast(out)
} else {
out <- sds()
nms <- x@pntr$names
for (k in nd) {
r <- x[k][[j]]
out@pntr$add(r@pntr, nms[k], "", "", FALSE)
}
}
messages(out, "`[`")
})
setMethod("[", c("SpatRasterDataset", "numeric", "logical"),
function(x, i, j, drop=TRUE) {
j <- positive_indices(j, min(nlyr(x)))
`[`(x, i=i, j=j, drop=drop)
})
setMethod("[", c("SpatRasterDataset", "missing", "numeric"),
function(x, i, j, drop=TRUE) {
`[`(x, i=1:x@pntr$nsds(), j=j, drop=drop)
})
setMethod("[", c("SpatRasterDataset", "missing", "logical"),
function(x, i, j, drop=TRUE) {
j <- positive_indices(j, min(nlyr(x)))
`[`(x, i=1:x@pntr$nsds(), j=j, drop=drop)
})
setMethod("[", c("SpatRasterDataset", "logical", "missing"),
function(x, i, j,drop=TRUE) {
i <- positive_indices(j, length(x))
x[i, drop=drop]
})
setMethod("[", c("SpatRasterDataset", "character", "missing"),
function(x, i, j, drop=TRUE) {
i <- match(i, names(x))
if (any(is.na(i))) {
error("`[`", "unknown name(s) provided")
}
x[i, drop=drop]
})
setMethod("[[", c("SpatRasterDataset", "ANY", "ANY"),
function(x, i, j, drop=TRUE) {
mi <- missing(i)
mj <- missing(j)
if ((mi) && (mj)) {
`[`(x, drop=drop)
} else if (mi) {
`[`(x, j=j, drop=drop)
} else if (mj) {
`[`(x, i=i, drop=drop)
} else {
`[`(x, i=i, j=j, drop=drop)
}
})
setMethod("$", c("SpatRasterDataset"),
function(x, name) {
x[name,drop=TRUE]
})
setMethod("$", "SpatRasterDataset",
function(x, name) {
x[name]
}
)
setMethod("sprc", signature(x="missing"),
function(x) {
r <- methods::new("SpatRasterCollection")
r@pntr <- SpatRasterCollection$new()
r
}
)
setMethod("sprc", signature(x="SpatRaster"),
function(x, ...) {
sprc(list(x, ...))
}
)
setMethod("sprc", signature(x="list"),
function(x) {
n <- length(x)
tptr <- SpatRasterCollection$new()
if (n > 0) {
for (i in 1:n) {
if (inherits(x[[i]], "SpatRaster")) {
tptr$add(x[[i]]@pntr, "")
} else if (inherits(x[[i]], "SpatRasterCollection") |
inherits(x[[i]], "SpatRasterDataset")) {
y <- as.list(x[[i]])
s <- sapply(y, function(j) tptr$add(j@pntr, ""))
} else {
name <- names(x[[i]])
cls <- paste(class(x[[i]]), collapse=", ")
error("sprc", "list element", name, "is a: ", cls)
}
}
}
r <- new("SpatRasterCollection")
r@pntr <- tptr
if (length(r) == length(x)) names(r) <- names(x)
r
}
)
setMethod("sprc", signature(x="character"),
function(x, ids=0, opts=NULL, raw=FALSE) {
if (length(x) > 1) {
r <- lapply(x, rast)
s <- sprc(r)
names(s) <- tools::file_path_sans_ext(basename(x))
return(s)
}
x <- trimws(x[1])
if (nchar(x) == 0) {
error("sprc", "provide valid file name(s)")
}
f <- .fullFilename(x)
r <- methods::new("SpatRasterCollection")
ids <- round(ids)-1
if (ids[1] < 0) {
useids <- FALSE
} else {
useids <- TRUE
}
if (is.null(opts)) opts <- ""[0]
if (raw) opts <- c(opts, "so=false")
r@pntr <- SpatRasterCollection$new(f, ids, useids, opts)
messages(r, "sprc")
}
)
setMethod("length", signature(x="SpatRasterCollection"),
function(x) {
x@pntr$length()
}
)
setMethod("[", c("SpatRasterCollection", "numeric", "missing"),
function(x, i, j, ... ,drop=TRUE) {
i <- positive_indices(i, length(x), TRUE, "`[`(i)")
if (drop && (length(i) == 1)) {
tptr <- x@pntr$x[[i]]
x <- rast()
x@pntr <- tptr
} else {
s <- x@pntr$x[i]
tptr <- SpatRasterCollection$new()
for (i in 1:length(s)) {
tptr$add(s[[i]], "")
}
x@pntr <- tptr
}
messages(x, "`[`")
})
setMethod("add<-", signature("SpatRasterCollection", "SpatRaster"),
function(x, value) {
x@pntr$add(value@pntr, "")
messages(x, "add")
}
)
setMethod("add<-", signature("SpatRasterDataset", "SpatRaster"),
function(x, value) {
x@pntr$add(value@pntr, "")
messages(x, "add")
}
)
setMethod("c", signature(x="SpatRasterCollection"),
function(x, ..., warn=TRUE) {
y <- list(...)
sprc(c(as.list(x), ...))
}
)
setMethod("c", signature(x="SpatRasterCollection"),
function(x, ...) {
x@pntr <- x@pntr$deepcopy()
dots <- list(...)
nms <- names(dots)
for (i in seq_along(dots)) {
if (inherits(dots[[i]], "SpatRasterCollection") | inherits(dots[[i]], "SpatRasterDataset")) {
sdsnms <- names(dots[[i]])
for (j in 1:(length(dots[[i]]))) {
x@pntr$add(dots[[i]][[j]]@pntr, sdsnms[j])
}
} else if (inherits(dots[[i]], "SpatRaster")) {
if (is.null(nms)) {
name <- paste0("d", i)
} else {
name <- nms[i]
}
x@pntr$add(dots[[i]]@pntr, name)
} else {
error("c", "arguments must be SpatRaster, SpatRasterCollection, or SpatRasterDataset")
}
}
messages(x, "c")
}
)
terra/R/xapp.R 0000644 0001762 0000144 00000004150 14551065770 012675 0 ustar ligges users
setMethod("xapp", signature(x="SpatRaster", y="SpatRaster"),
function(x, y, fun, ..., filename="", overwrite=FALSE, wopt=list()) {
compareGeom(x, y, crs=FALSE, warncrs=TRUE)
if (!hasValues(x)) error("xapp", "x does not have values")
if (!hasValues(y)) error("xapp", "y does not have values")
fun <- match.fun(fun)
out <- rast(x)
nc <- ncol(x)
readStart(x)
readStart(y)
on.exit(readStop(x))
on.exit(readStop(y), add=TRUE)
dots <- list(...)
if (length(dots) > 0) {
test <- any(sapply(dots, function(i) inherits(i, "SpatRaster")))
if (test) {
error("app", "additional arguments cannot be a SpatRaster")
}
}
teststart <- max(1, 0.5 * nc - 6)
testend <- min(teststart + 12, nc)
ntest <- 1 + testend - teststart
vx <- readValues(x, round(0.51*nrow(x)), 1, teststart, ntest, mat=TRUE)
vy <- readValues(y, round(0.51*nrow(y)), 1, teststart, ntest, mat=TRUE)
test <- sapply(1:nrow(vx), function(i) fun(vx[i, ], vy[i, ], ...))
if (is.list(test)) {
error("xapp", "'fun' returns a list (should be numeric or matrix)")
}
trans <- FALSE
if (NCOL(test) > 1) {
if (ncol(test) == ntest) {
nlyr(out) <- nrow(test)
trans <- TRUE
nms <- rownames(test)
} else if (nrow(test) == ntest) {
nlyr(out) <- ncol(test)
nms <- colnames(test)
} else {
error("xapp", "the number of values returned by 'fun' is not appropriate\n(it should be the product of the number of cells and and a positive integer)")
}
if (is.null(wopt$names)) {
wopt$names <- nms
}
} else {
if ((length(test) %% ntest) != 0) {
error("xapp", "the number of values returned by 'fun' is not appropriate")
} else {
nlyr(out) <- length(test) / ntest
}
}
ncops <- (nlyr(x)+nlyr(y)) / nlyr(out)
ncops <- ifelse(ncops > 1, ceiling(ncops), 1) * 4
b <- writeStart(out, filename, overwrite, wopt=wopt, n=ncops, sources=sources(x))
for (i in 1:b$n) {
vx <- readValues(x, b$row[i], b$nrows[i], 1, nc, TRUE)
vy <- readValues(y, b$row[i], b$nrows[i], 1, nc, TRUE)
r <- sapply(1:nrow(vx), function(i) fun(vx[i, ], vy[i, ], ...))
if (trans) {
r <- t(r)
}
writeValues(out, r, b$row[i], b$nrows[i])
}
writeStop(out)
}
)
terra/R/plot_let.R 0000644 0001762 0000144 00000051506 14747312555 013561 0 ustar ligges users # these methods require the dev version of leaflet
checkLeafLetVersion <- function() {
v <- utils::packageVersion("leaflet")
if (v < "2.1.2.9000") {
error("plet", "plet needs the development version of leaflet")
}
}
popUp <- function(x) {
nms <- names(x)
if (length(nms) > 0) {
s <- sapply(1:length(nms), function(i) paste0(nms[i], ": ", x[[i, drop=TRUE]]))
if (is.null(dim(s))) {
paste(s, collapse="
")
} else {
apply(s, 1, function(i) paste(i, collapse="
"))
}
} else {
paste("geom", 1:nrow(x), sep="_")
}
}
makelonlat <- function(x) {
geo <- is.lonlat(x)
if (is.na(geo)) {
geo <- is.lonlat(x, TRUE, TRUE)
if (geo) return(x)
error("plet", "coordinate reference system is unknown and does not look like lon/lat")
} else if (!geo) {
project(x, "+proj=longlat")
} else {
x
}
}
setMethod("plet", signature(x="missing"),
function(x) {
leaflet::leaflet()
}
)
#.leaflet-container {
# background: #FFF;
#}
baselayers <- function(tiles, wrap=TRUE) {
map <- leaflet::leaflet()
if ((!is.null(tiles)) && (length(tiles) > 0)) {
if ("Streets" %in% tiles) {
map <- leaflet::addTiles(map, group="Streets",
options=leaflet::tileOptions(noWrap = !wrap))
}
tiles <- tiles[tiles != "Streets"]
if (length(tiles) > 0) {
for (i in 1:length(tiles)) {
map <- leaflet::addProviderTiles(map, tiles[i], group=tiles[i],
options=leaflet::tileOptions(noWrap = !wrap))
}
}
}
map
}
.get_leg <- function(v, type="", dig.lab=3, cols, breaks=NULL, breakby="eqint", sort=TRUE, decreasing=FALSE, ...) {
out <- list(v=v, leg=list())
if (is.null(type)) type <- ""
if (type == "continuous") {
type <- "interval"
} else if (type == "") {
if ((!is.numeric(v)) || (length(unique(v)) < 11)) {
type <- "classes"
} else {
type <- "interval"
}
} else {
type <- match.arg(type, c("interval", "classes"))
}
out$legend_type <- type
out$uv <- unique(v)
if (inherits(cols, "function")) {
cols <- cols(100)
}
out$cols <- cols
if (out$legend_type == "classes") {
out$legend_sort <- sort[1]
out$legend_sort_decreasing <- decreasing[1]
out <- .vect.legend.classes(out)
} else if (out$legend_type == "interval") {
out$breaks <- breaks
out$breakby <- breakby
out$range <- range(v, na.rm=TRUE)
out <- .vect.legend.interval(out, dig.lab=dig.lab)
}
out
}
setMethod("plet", signature(x="SpatVector"),
function(x, y="", col, fill=0.2, main=y, cex=1, lwd=2, border="black", alpha=1, popup=TRUE, label=FALSE, split=FALSE, tiles=c("Streets", "Esri.WorldImagery", "OpenTopoMap"), wrap=TRUE, legend="bottomright", collapse=FALSE, type=NULL, breaks=NULL, breakby="eqint", sort=TRUE, decreasing=FALSE, map=NULL, ...) {
#checkLeafLetVersion()
y <- unique(y)
if (length(y) > 1) {
y = y[1]
# xvc <- svc(lapply(y, function(i) x[,i]))
# if (is.numeric(y)) {
# names(xvc) <- names(x)[y]
# } else {
# names(xvc) <- y
# }
# plet(xvc, col=col, fill=0.2, alpha=alpha, cex=cex, lwd=lwd, border=border, popup=popup, label=label, split=split, tiles=tiles, wrap=wrap, legend=legend, collapse=collapse, map=map, ...)
#type=type, breaks=breaks, breakby=breakby, sort=sort, decreasing=decreasing,
}
if (missing(col)) col <- function(n) grDevices::rainbow(n, start=.2)
alpha <- max(0, min(1, alpha))
fill <- max(0, min(1, fill))
x <- makelonlat(x)
if (is.null(map)) {
tiles <- unique(as.character(tiles))
tiles <- tiles[tiles!=""]
map <- baselayers(tiles, wrap)
} else {
tiles <- NULL
}
g <- geomtype(x)
leg <- NULL
if (y == "") { # no legend
group <- x@pntr$layer
if (group == "") group = g
cols <- .getCols(nrow(x), col)
pop <- lab <- NULL
if (isTRUE(popup[1])) pop <- popUp(x)
if (isTRUE(label[1])) lab <- 1:nrow(x)
if (g == "polygons") {
map <- leaflet::addPolygons(map, data=x, label=lab, group=group,
fillColor=cols, fillOpacity=fill, opacity=alpha,
popup=pop, color=border, weight=lwd, ...)
} else if (g == "lines") {
map <- leaflet::addPolylines(map, data=x, label=lab, group=group,
color=cols, opacity=alpha, popup=pop, weight=lwd, ...)
} else {
map <- leaflet::addCircleMarkers(map, data=x, radius=cex, popup=pop, group=group,
label=lab, opacity=alpha, color=cols, ...)
}
if (length(tiles) > 1) {
map <- leaflet::addLayersControl(map, baseGroups = tiles, overlayGroups=group,
options = leaflet::layersControlOptions(collapsed=collapse))
} else {
map <- leaflet::addLayersControl(map, overlayGroups = group,
options = leaflet::layersControlOptions(collapsed=collapse))
}
map
} else { # legend
y <- y[1]
if (is.numeric(y)) {
y <- round(y)
stopifnot((y > 0) && (y <= nlyr(x)))
y <- names(x)[y]
}
stopifnot(y %in% names(x))
x <- x[, y]
v <- values(x)[,1]
if (split) {
u <- unique(v)
cols <- .getCols(length(u), col)
for (i in seq_along(u)) {
s <- x[v == u[i], ]
pop <- lab <- NULL
if (isTRUE(popup[1])) pop <- popUp(s)
if (isTRUE(label[1])) lab <- u
if (g == "polygons") {
map <- leaflet::addPolygons(map, data=s, label=lab[i], group=u[i],
fillColor=cols[i], fillOpacity=fill, opacity=alpha, popup=pop,
col=border, ...)
} else if (g == "lines") {
map <- leaflet::addPolylines(map, data=s, label=lab[i], group=u[i],
col=cols[i], opacity=alpha, popup=pop, ...)
} else {
map <- leaflet::addCircleMarkers(map, data=s, label=lab[i], group=u[i],
col=cols[i], fillOpacity=fill, opacity=alpha, popup=pop, radius=cex, ...)
}
}
if (length(tiles) > 1) {
map <- leaflet::addLayersControl(map, baseGroups = tiles, overlayGroups = u,
options = leaflet::layersControlOptions(collapsed=collapse))
} else {
map <- leaflet::addLayersControl(map, overlayGroups = u,
options = leaflet::layersControlOptions(collapsed=collapse))
}
} else { # do not split
#vcols <- cols[1:length(v)]
leg <- .get_leg(v, type=type, dig.lab=3, cols=col, breaks=breaks, breakby=breakby, sort=sort, decreasing=decreasing, ...)
pop <- lab <- NULL
if (isTRUE(popup[1])) pop <- popUp(x)
if (isTRUE(label[1])) lab <- v
if (g == "polygons") {
map <- leaflet::addPolygons(map, data=x, label=lab, group=y,
fillColor=leg$main_cols, opacity=alpha, fillOpacity=fill,
col = border, popup=pop, ...)
} else if (g == "lines") {
map <- leaflet::addPolylines(map, data=x, label=lab, group=y,
col=leg$main_cols, popup=pop, opacity=alpha, ...)
} else {
map <- leaflet::addCircleMarkers(map, data=x, label=lab, group=y,
col=leg$main_cols, radius=cex, popup=pop, fillOpacity=fill, opacity=alpha, ...)
}
if (length(tiles) > 1) {
map <- leaflet::addLayersControl(map, baseGroups = tiles, overlayGroups=y,
options = leaflet::layersControlOptions(collapsed=collapse))
} else {
map <- leaflet::addLayersControl(map, overlayGroups = y,
options = leaflet::layersControlOptions(collapsed=collapse))
}
}
if ((!is.null(legend)) && (!is.null(leg))) {
if (leg$legend_type != "") {
main <- gsub("\n", "", main[1])
op = ifelse(g == "polygons", fill, 1)
map <- leaflet::addLegend(map, position=legend, colors=leg$leg$fill,
labels=as.character(leg$leg$legend), opacity=op, title=main)
}
}
map
}
}
)
setMethod("plet", signature(x="SpatVectorCollection"),
function(x, col, fill=0, cex=1, lwd=2, border="black", alpha=1, popup=TRUE, label=FALSE, tiles=c("Streets", "Esri.WorldImagery", "OpenTopoMap"), wrap=TRUE, legend="bottomright", collapse=FALSE, map=NULL) {
#checkLeafLetVersion()
if (is.null(map)) {
tiles <- unique(as.character(tiles))
tiles <- tiles[tiles!=""]
map <- baselayers(tiles, wrap)
} else {
tiles <- NULL
}
nms <- names(x)
nms[nchar(nms) == 0] <- "X"
nms <- make.unique(nms)
if (missing(col)) col <- grDevices::rainbow
n <- length(x)
if (is.function(col)) {
cols <- col(n)
} else {
cols <- rep_len(col, n)
}
lwd <- rep_len(lwd, n)
alpha <- rep_len(alpha, n)
alpha <- pmax(0, pmin(1, alpha))
fill <- rep_len(fill, n)
fill <- pmax(0, pmin(1, fill))
popup <- rep_len(popup, n)
label <- rep_len(label, n)
border <- rep_len(border, n)
for (i in 1:n) {
v <- x[i]
v <- makelonlat(v)
g <- geomtype(v)
pop <- NULL
lab <- NULL
if (popup[i]) {
pop <- popUp(v)
}
if (label[i]) {
lab <- 1:nrow(v)
}
if (g == "polygons") {
map <- leaflet::addPolygons(map, data=v, weight=lwd[i], fillColor=cols[i],
fillOpacity=fill[i], col=border[i], opacity=alpha[i], popup=pop,
label=lab, group=nms[i])
} else if (g == "lines") {
map <- leaflet::addPolylines(map, data=v, weight=lwd[i], opacity=alpha[i],
col=cols[i], group=nms[i], popup=pop, label=lab)
} else {
map <- leaflet::addCircleMarkers(map, data=v, radius=cex[i], popup=pop, label=lab, opacity=alpha[i], col=cols[i], group=nms[i])
}
}
if (length(tiles) > 1) {
map <- leaflet::addLayersControl(map, baseGroups = tiles, overlayGroups = nms,
options = leaflet::layersControlOptions(collapsed=collapse))
} else {
map <- leaflet::addLayersControl(map, overlayGroups = nms,
options = leaflet::layersControlOptions(collapsed=collapse))
}
map
}
)
setMethod("polys", signature(x="leaflet"),
function(x, y, col, fill=0.2, lwd=2, border="black", alpha=1, popup=TRUE, label=FALSE, ...) {
if (inherits(y, "SpatVector")) {
if (nrow(y) == 0) return(x)
y <- makelonlat(y)
if (missing(col)) col <- "black"
if (geomtype(y) != "polygons") {
error("polys", "SpatVector y must have polygons geometry")
}
leaflet::addPolygons(x, data=y, weight=lwd, fillColor=col,
fillOpacity=fill, col=border, opacity=alpha, popup=popup,
label=label, ...)
} else if (inherits(y, "SpatVectorCollection")) {
nms <- names(y)
n <- length(y)
nms[nchar(nms) == 0] <- "X"
nms <- make.unique(nms)
if (is.function(col)) {
cols <- col(n)
} else {
cols <- rep_len(col, n)
}
lwd <- rep_len(lwd, n)
alpha <- rep_len(alpha, n)
fill <- rep_len(fill, n)
border <- rep_len(border, n)
popup <- rep_len(popup, n)
label <- rep_len(label, n)
for (i in 1:length(nms)) {
x <- leaflet::addPolygons(x, data=y[i], weight=lwd[i], fillColor=cols[i],
fillOpacity=fill[i], col=border[i], opacity=alpha[i], popup=popup[i],
label=label[i], group=nms[i], ...)
}
collapse=FALSE
leaflet::addLayersControl(x, overlayGroups = nms, options = leaflet::layersControlOptions(collapsed=collapse))
} else {
error("plet", "y should be a SpatVector or SpatVectorCollection")
}
}
)
setMethod("lines", signature(x="leaflet"),
function(x, y, col, lwd=2, alpha=1, ...) {
if (inherits(y, "SpatVector")) {
if (nrow(y) == 0) return(x)
y <- makelonlat(y)
if (missing(col)) col <- "black"
if (!(geomtype(y) %in% c("lines", "polygons"))) {
error("lines", "SpatVector y must have either lines or polygons geometry")
}
leaflet::addPolylines(x, data=y, weight=lwd, opacity=alpha, col=col, ...)
} else if (inherits(y, "SpatVectorCollection")) {
nms <- names(y)
n <- length(y)
nms[nchar(nms) == 0] <- "X"
nms <- make.unique(nms)
if (is.function(col)) {
cols <- col(n)
} else {
cols <- rep_len(col, n)
}
lwd <- rep_len(lwd, n)
alpha <- rep_len(alpha, n)
for (i in 1:length(nms)) {
x <- leaflet::addPolylines(x, data=y[i], weight=lwd[i], opacity=alpha[i], col=cols[i], group=nms[i], ...)
}
collapse=FALSE
leaflet::addLayersControl(x, overlayGroups = nms, options = leaflet::layersControlOptions(collapsed=collapse))
} else {
error("plet", "y should be a SpatVector or SpatVectorCollection")
}
}
)
setMethod("points", signature(x="leaflet"),
function(x, y, col, cex=1, alpha=1, label=1:nrow(y), popup=FALSE, ...) {
stopifnot(inherits(y, "SpatVector"))
if (nrow(y) == 0) return(x)
y <- makelonlat(y)
if (missing(col)) col <- "black"
if (!(geomtype(y) == "points")) {
if (geomtype(y) == "polygons") {
y <- centroids(y)
} else {
y <- as.points(y)
}
}
if (popup) {
popup=popUp(y)
} else {
popup <- NULL
}
leaflet::addCircleMarkers(x, data=y, radius=cex, popup=popup, label=label, opacity=alpha, col=col, ...)
}
)
make.panel <- function(x, maxcell) {
nl <- nlyr(x)
x <- spatSample(x, maxcell/nl, "regular", as.raster=TRUE, warn=FALSE)
if (is.lonlat(x)) {
asp <- 1/cos((mean(ext(x)[3:4]) * pi)/180)
} else {
asp <- 1
}
crs(x, warn=FALSE) <- "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs"
ext(x) = c(0,1,0,asp)
#if (!is.null(add)) {
# e <- as.vector(ext(x))
# for (i in 1:length(add)) {
# v <- project(v, crs(x))
# add[i] <- rescale(v, fx=1/diff(e[1:2]), fy=1/diff(e[3:4]))
# }
#}
asp <- asp * nrow(x) / ncol(x)
nc <- ceiling(2*sqrt(nl/2) * asp)
nr <- ceiling(nl / nc)
nc <- ceiling(nl / nr)
e <- as.vector(ext(x))
r <- res(x)
skiprow <- -asp - max(1, min(10, trunc(nrow(x)/20))) *r[2]
skipcol <- 1 + max(1, min(10, trunc(ncol(x)/20))) *r[1]
# skipcol <- 1 + max(r[1], min(10, r[1] * trunc(nrow(x)/20)))
labs <- data.frame(x=0, y=0, label=names(x))
rw = cl = 0
y <- vector(mode="list", length=nl)
off <- 0 #.4 / nr
for (i in 1:nl) {
y[[i]] <- shift(x[[i]], cl * skipcol, rw * skiprow)
e <- as.vector(ext(y[[i]]))
labs[i,1:2] <- c(mean(e[1:2]), e[4]-off)
cl <- cl + 1
if (cl == nc) {
cl <- 0
rw <- rw + 1
}
}
labs <- vect(labs, geom=c("x", "y"), crs=crs(x))
labs <- project(labs, "+proj=longlat")
x <- merge(sprc(y))
list(x, labs)
}
.get_cls <- function(x, type="", dig.lab=3, cols, breaks=NULL, breakby="eqint", sort=TRUE, decreasing=FALSE, ...) {
if (is.null(type) ||(type == "")) {
if (is.factor(x) || is.bool(x)) {
type <- "classes"
} else if (is.null(breaks)) {
type <- "continuous"
} else {
type <- "interval"
}
} else {
type <- match.arg(type, c("continuous", "interval", "classes"))
}
if ((type == "interval") && (is.null(breaks))) {
}
if (type == "continuous") {
if (inherits(cols, "function")) {
cols <- cols(100)
}
return(list(type=type, x=x, cols=cols))
}
if (type == "classes") {
if (!is.factor(x)) {
uv <- unique(values(x))
uv <- sort(uv)
uv <- uv[!is.na(uv)]
levels(x) <- data.frame(ID=uv, value=uv)
} else {
uv <- levels(x)[[1]][,2]
}
ncols <- length(uv)
} else {
if (is.null(breaks)) breaks <- 5
if (length(breaks) == 1) {
breaks <- .get_breaks(values(x), n=breaks, breakby, r=NULL)
}
x <- classify(x, breaks)
ncols <- length(breaks)-1
}
if (inherits(cols, "function")) {
cols <- cols(ncols)
} else {
cols <- grDevices::colorRampPalette(cols)(ncols)
}
return(list(type=type, x=x, cols=cols))
# out$legend_type <- type
# out$uv <- unique(v)
}
setMethod("plet", signature(x="SpatRaster"),
function(x, y=1, col, alpha=0.8, main=names(x), tiles=c("Streets", "Esri.WorldImagery", "OpenTopoMap"),
wrap=TRUE, maxcell=500000, stretch=NULL, legend="bottomright", shared=FALSE, panel=FALSE, collapse=TRUE,
type=NULL, breaks=NULL, breakby="eqint", map=NULL, ...) {
#checkLeafLetVersion()
if (is.na(crs(x)) | (grepl("^Cartesian", .name_or_proj4(x)))) {
tiles <- ""
e <- ext(x)
rx <- diff(e[1:2])
ry <- diff(e[3:4])
m <- max(rx, ry)
ext(x) <- c(0, rx/m, 0, ry/m)
crs(x) <- "EPSG:3857"
notmerc <- FALSE
} else {
notmerc <- isTRUE(crs(x, describe=TRUE)$code != "3857")
}
# if (!is.null(add)) {
# if (inherits(add, "SpatVector")) {
# add <- svc(makelonlat(add))
# } else if (inherits(add, "SpatVectorCollection")) {
# for (i in 1:length(add)) {
# add[i] <- makelonlat(add[i])
# }
# } else {
# error("plet", "add should be a SpatVector or a SpatVectorCollection")
# }
# }
alpha <- max(0, min(1, alpha))
hasRGB <- has.RGB(x)
if (hasRGB) {
y <- RGB(x)
legend <- NULL
}
# else if (!is.null(terra::coltab(x)[[1]])) {
# legend <- NULL
#}
e <- ext(x)
if (is.lonlat(x) && ((e$ymin < -85) || (e$ymax > 85))) {
yr1 <- e$ymax - e$ymin
e$ymin <- max(e$ymin, -85)
e$ymax <- min(e$ymax, 85)
yr2 <- e$ymax - e$ymin
x <- spatSample(x[[y]], (yr1/yr2) * maxcell, "regular", as.raster=TRUE, warn=FALSE)
x <- crop(x, e)
}
if (panel) {
tiles <- NULL
p <- make.panel(x, maxcell) #, add)
x <- p[[1]]
p <- p[[2]]
add <- p[[3]]
main <- ""
} else {
x <- spatSample(x[[y]], maxcell, "regular", as.raster=TRUE, warn=FALSE)
}
if (is.null(map)) {
tiles <- unique(as.character(tiles))
tiles <- tiles[tiles!=""]
if (length(tiles) > 1) {
tiles <- tiles[1]
#warn("plet", "only a single tileset can be used with raster data")
}
map <- baselayers(tiles, wrap)
} else {
tiles <- NULL
}
if (missing(col)) {
col <- .default.pal()
#col <- rev(grDevices::terrain.colors(255))
}
main <- gsub("\n", "", main)
if (length(main) != length(y)) {
main <- rep_len(main, length(x))[y]
}
if (hasRGB) {
if (!is.null(stretch)) {
if (stretch == "lin") {
x <- stretch(x, minq=0.02, maxq=0.98)
} else {
x <- stretch(x, histeq=TRUE, scale=255)
}
}
RGB(x) <- 1:length(y)
x <- colorize(x, "col")
} else {
leg <- .get_cls(x, type=type, dig.lab=3, cols=col, breaks=breaks, breakby=breakby, ...)
x <- leg$x
col <- leg$cols
}
if (nlyr(x) == 1) {
map <- leaflet::addRasterImage(map, x, colors=col, opacity=alpha, project=notmerc)
if (!is.null(legend)) {
if (leg$type == "continuous") {
if (!all(hasMinMax(x))) setMinMax(x)
r <- minmax(x)
v <- seq(r[1], r[2], length.out=5)
pal <- leaflet::colorNumeric(col, v, reverse = TRUE)
map <- leaflet::addLegend(map, legend, pal=pal, values=v, opacity=1, title=main[1],
labFormat = leaflet::labelFormat(transform = function(x) sort(x, decreasing = TRUE)))
} else {
map <- leaflet::addLegend(map, position=legend, colors=leg$cols,
labels=levels(x)[[1]][,2], opacity=alpha, title=main)
}
}
if (panel) {
#map <- leaflet::addCircleMarkers(map, data=p, label=p$label, radius=1, opacity=1, col="red")
map <- leaflet::addLabelOnlyMarkers(map, label=p$label, data=p,
labelOptions = leaflet::labelOptions(noHide = T, textOnly = T))
}
} else {
nms <- make.unique(names(x))
many_legends <- one_legend <- FALSE
if (!is.null(legend)) {
if (!all(hasMinMax(x))) setMinMax(x)
r <- minmax(x)
if (shared) {
rr <- range(r)
pal <- leaflet::colorNumeric(col, rr, na.color="#00000000")
one_legend <- TRUE
} else {
many_legends <- TRUE
}
} else {
one_legend <- FALSE
}
for (i in 1:nlyr(x)) {
if (one_legend) {
map <- leaflet::addRasterImage(map, x[[i]], colors=pal, opacity=alpha, group=nms[i], project=notmerc)
} else {
map <- leaflet::addRasterImage(map, x[[i]], colors=col, opacity=alpha, group=nms[i], project=notmerc)
if (many_legends) {
v <- seq(r[1,i], r[2,i], length.out=5)
pal <- leaflet::colorNumeric(col, v, reverse=TRUE)
map <- leaflet::addLegend(map, position=legend, pal=pal, values=v,
title=main[i], opacity=1, group=nms[i],
labFormat = leaflet::labelFormat(transform = function(x) sort(x, decreasing = TRUE)))
}
}
}
map <- leaflet::addLayersControl(map, baseGroups=nms,
options = leaflet::layersControlOptions(collapsed=collapse))
if (many_legends) { # show one legend at a time
map <- htmlwidgets::onRender(map,
"function(el, x) {
var updateLegend = function () {
var selectedGroup = document.querySelectorAll('input:checked')[0].nextSibling.innerText.substr(1);
document.querySelectorAll('.legend').forEach(a => a.hidden=true);
document.querySelectorAll('.legend').forEach(l => {
if (l.children[0].children[0].innerText == selectedGroup) l.hidden=false;
});
};
updateLegend();
this.on('baselayerchange', e => updateLegend());}")
} else if (one_legend) {
v <- seq(rr[1], rr[2], length.out=5)
pal <- leaflet::colorNumeric(col, v, reverse = TRUE)
map <- leaflet::addLegend(map, position=legend, pal=pal, values=v, opacity=1, group=nms[i],
labFormat = leaflet::labelFormat(transform = function(x) sort(x, decreasing = TRUE)))
}
}
map
}
)
terra/R/tags.R 0000644 0001762 0000144 00000012713 14732151132 012654 0 ustar ligges users
setMethod("meta", signature(x="SpatRaster"),
function(x, layers=FALSE) {
f <- function(i) {
if (length(i) == 0) {
matrix(ncol=2, nrow=0)
} else {
matrix(unlist(regmatches(i, regexpr("=", i), invert=TRUE)), ncol=2, byrow=TRUE)
}
}
lapply(x@pntr$metadata(layers), f)
}
)
setMethod("metags", signature(x="SpatRaster"),
function(x, layer=NULL, name=NULL) {
if (!is.null(layer)) {
if (is.character(layer)) layer = match(layer, names(x))
v <- x@pntr$getLyrTags(layer-1)
out <- matrix(v, ncol=3, byrow=TRUE, dimnames = list(NULL, c("layer", "name", "value")))
out <- data.frame(out)
out$layer <- as.numeric(out$layer) + 1
if (!is.null(name)) {
out <- out[out$name == name, , drop=FALSE]
}
} else {
v <- x@pntr$getTags()
m <- matrix(v, ncol=2, byrow=TRUE, dimnames = list(NULL, c("name", "value")))
out <- m[,2]
names(out) <- m[,1]
if (!is.null(name)) {
out <- out[name]
}
}
out
}
)
setMethod("metags<-", signature(x="SpatRaster"),
function(x, ..., layer=NULL, value) {
if (is.null(value)) {
if (!is.null(layer)) {
if (is.character(layer)) layer = match(layer, names(x))
value <- matrix(x@pntr$getLyrTags(layer-1), ncol=2, byrow=TRUE)
} else {
value <- matrix(x@pntr$getTags(), ncol=2, byrow=TRUE)
}
value[,2] <- ""
value[is.na(value)] <- ""
} else if (NCOL(value) == 1) {
if (!is.null(names(value)) && (!any(grepl("=", value)))) {
value <- cbind(names(value), value)
} else {
value <- strsplit(value, "=")
i <- sapply(value, length) == 1
if (length(i) > 0) {
j <- which(i)
for (i in j) value[[i]] <- c(value[[i]], "")
}
i <- sapply(value, length) == 2
value <- do.call(rbind, value[i])
}
} else if (NCOL(value) != 2) {
error("metags<-", "expecting a vector with 'name=value' or a two column matrix")
}
value[is.na(value[,2]), 2] <- ""
value <- na.omit(value)
x <- deepcopy(x)
if (NROW(value) > 0) {
if (!is.null(layer)) {
if (is.character(layer)) layer = match(layer, names(x))
x@pntr$addLyrTags(layer-1, value[,1], value[,2])
} else {
sapply(1:nrow(value), function(i) {
x@pntr$addTag(value[i,1], value[i,2])
})
}
}
x
}
)
setMethod("metags", signature(x="SpatRasterDataset"),
function(x, dataset=NULL, name=NULL) {
if (!is.null(dataset)) {
if (is.character(dataset)) layer = match(dataset, names(x))
return(metags(x[[dataset]], name=name))
} else {
v <- x@pntr$getTags()
m <- matrix(v, ncol=2, byrow=TRUE, dimnames = list(NULL, c("name", "value")))
out <- m[,2]
names(out) <- m[,1]
if (!is.null(name)) {
out <- out[name]
}
}
out
}
)
setMethod("metags<-", signature(x="SpatRasterDataset"),
function(x, ..., dataset=NULL, value) {
if (is.null(value)) {
if (!is.null(dataset)) {
if (is.character(dataset)) layer = match(dataset, names(x))
value <- matrix(x[[dataset]]@pntr$getTags(), ncol=2, byrow=TRUE)
} else {
value <- matrix(x@pntr$getTags(), ncol=2, byrow=TRUE)
}
value[,2] <- ""
value[is.na(value)] <- ""
} else if (NCOL(value) == 1) {
if (!is.null(names(value)) && (!any(grepl("=", value)))) {
value <- cbind(names(value), value)
} else {
value <- strsplit(value, "=")
i <- sapply(value, length) == 1
if (length(i) > 0) {
j <- which(i)
for (i in j) value[[i]] <- c(value[[i]], "")
}
i <- sapply(value, length) == 2
value <- do.call(rbind, value[i])
}
} else if (NCOL(value) != 2) {
error("metags<-", "expecting a vector with 'name=value' or a two column matrix")
}
value[is.na(value[,2]), 2] <- ""
value <- na.omit(value)
x@pntr <- x@pntr$deepcopy()
if (NROW(value) > 0) {
if (!is.null(dataset)) {
if (is.character(dataset)) layer = match(dataset, names(x))
x[[dataset]]@pntr$addTag(value[,1], value[,2])
} else {
sapply(1:nrow(value), function(i) {
x@pntr$addTag(value[i,1], value[i,2])
})
}
}
x
}
)
setMethod("metags", signature(x="SpatRasterCollection"),
function(x, dataset=NULL, name=NULL) {
if (!is.null(dataset)) {
return(metags(x[[dataset]], name=name))
} else {
v <- x@pntr$getTags()
m <- matrix(v, ncol=2, byrow=TRUE, dimnames = list(NULL, c("name", "value")))
out <- m[,2]
names(out) <- m[,1]
if (!is.null(name)) {
out <- out[name]
}
}
out
}
)
setMethod("metags<-", signature(x="SpatRasterCollection"),
function(x, ..., dataset=NULL, value) {
if (is.null(value)) {
if (!is.null(dataset)) {
value <- matrix(x[[dataset]]@pntr$getTags(), ncol=2, byrow=TRUE)
} else {
value <- matrix(x@pntr$getTags(), ncol=2, byrow=TRUE)
}
value[,2] <- ""
value[is.na(value)] <- ""
} else if (NCOL(value) == 1) {
if (!is.null(names(value)) && (!any(grepl("=", value)))) {
value <- cbind(names(value), value)
} else {
value <- strsplit(value, "=")
i <- sapply(value, length) == 1
if (length(i) > 0) {
j <- which(i)
for (i in j) value[[i]] <- c(value[[i]], "")
}
i <- sapply(value, length) == 2
value <- do.call(rbind, value[i])
}
} else if (NCOL(value) != 2) {
error("metags<-", "expecting a vector with 'name=value' or a two column matrix")
}
value[is.na(value[,2]), 2] <- ""
value <- na.omit(value)
x@pntr <- x@pntr$deepcopy()
if (NROW(value) > 0) {
if (!is.null(dataset)) {
x[[dataset]]@pntr$addTag(value[,1], value[,2])
} else {
sapply(1:nrow(value), function(i) {
x@pntr$addTag(value[i,1], value[i,2])
})
}
}
x
}
)
terra/R/plot.R 0000644 0001762 0000144 00000024326 14744355052 012711 0 ustar ligges users
.one.density <- function(x, maxcells=100000, plot=TRUE, ...) {
d <- values(x)
d <- stats::density(stats::na.omit(d))
if (plot) {
plot(d, ...)
return(invisible(d))
} else {
return(d)
}
}
setMethod("density", signature(x="SpatRaster"),
function(x, maxcells=100000, plot=TRUE, main, ...) {
x <- spatSample(x, maxcells, method="regular", as.raster=TRUE, warn=FALSE)
res <- list()
nl <- nlyr(x)
if (missing(main)) {
main=names(x)
} else {
main <- rep(main, length.out=nl)
}
if (nl==1) {
res[[1]] <- .one.density(x, plot=plot, maxcells=maxcells, main=main, ...)
} else {
if (nl > 16) {
warn("density", "only the first 16 layers are plotted")
nl <- 16
x <- x[[1:16]]
}
nc <- ceiling(sqrt(nl))
nr <- ceiling(nl / nc)
mfrow <- graphics::par("mfrow")
spots <- mfrow[1] * mfrow[2]
if (spots < nl) {
old.par <- graphics::par(no.readonly = TRUE)
on.exit(graphics::par(old.par))
graphics::par(mfrow=c(nr, nc))
}
for (i in 1:nlyr(x)) {
res[[i]] <- .one.density(x[[i]], maxcells=maxcells, main=main[i], plot=plot, ...)
}
}
if (plot) return(invisible(res))
else return(res)
}
)
setMethod("persp", signature(x="SpatRaster"),
function(x, maxcells=100000, ...) {
x <- spatSample(x, size=maxcells, method="regular", as.raster=TRUE, warn=FALSE)
value <- t(as.matrix(x, wide=TRUE)[nrow(x):1,])
y <- yFromRow(x, nrow(x):1)
x <- xFromCol(x, 1:ncol(x))
graphics::persp(x=x, y=y, z=value, ...)
}
)
.plot.filled.contour <- function(x, maxcells=100000, ...) {
x <- spatSample(x[[1]], maxcells, method="regular", as.raster=TRUE, warn=FALSE)
X <- xFromCol(x, 1:ncol(x))
Y <- yFromRow(x, nrow(x):1)
Z <- t( matrix( values(x), ncol=ncol(x), byrow=TRUE)[nrow(x):1,] )
if (is.null(list(...)$asp)) {
asp <- ifelse(is.lonlat(x, perhaps=TRUE, warn=FALSE), 1/cos((mean(as.vector(ext(x))[3:4]) * pi)/180), 1)
graphics::filled.contour(x=X, y=Y, z=Z, asp=asp, ...)
} else {
graphics::filled.contour(x=X, y=Y, z=Z,...)
}
}
setMethod("contour", signature(x="SpatRaster"),
function(x, maxcells=100000, filled=FALSE, ...) {
if (filled) {
.plot.filled.contour(x, maxcells=maxcells, ...)
} else {
x <- spatSample(x[[1]], maxcells, method="regular", as.raster=TRUE, warn=FALSE)
if (is.null(list(...)$asp)) {
asp <- ifelse(is.lonlat(x, perhaps=TRUE, warn=FALSE), 1/cos((mean(as.vector(ext(x))[3:4]) * pi)/180), 1)
graphics::contour(x=xFromCol(x,1:ncol(x)), y=yFromRow(x, nrow(x):1), z=t(as.matrix(x, wide=TRUE)[nrow(x):1,]), asp=asp, ...)
} else {
graphics::contour(x=xFromCol(x,1:ncol(x)), y=yFromRow(x, nrow(x):1), z=t(as.matrix(x, wide=TRUE)[nrow(x):1,]), ...)
}
}
}
)
setMethod("as.contour", signature(x="SpatRaster"),
function(x, maxcells=100000, ...) {
x <- spatSample(x[[1]], size=maxcells, method="regular", as.raster=TRUE, warn=FALSE)
z <- grDevices::contourLines(x=xFromCol(x,1:ncol(x)), y=yFromRow(x, nrow(x):1), z=t(as.matrix(x, wide=TRUE)[nrow(x):1,]), ...)
y <- lapply(1:length(z), function(i) cbind(z[[i]]$level, i, z[[i]]$x, z[[i]]$y))
y <- do.call(rbind, y)
y[] <- as.numeric(y)
u <- unique(y[,1])
y[,1] <- match(y[,1], u)
colnames(y)[3:4] <- c("x", "y")
vect(y, "lines", atts=data.frame(level=u), crs=crs(x))
}
)
setMethod("pairs", signature(x="SpatRaster"),
function(x, hist=TRUE, cor=TRUE, use="pairwise.complete.obs", maxcells=100000, ...) {
if (nlyr(x) < 2) {
error("x must have at least two layers")
}
if (nlyr(x) < 2) {
error("x must have at least two layers")
}
panelhist <- function(x,...) {
usr <- graphics::par("usr")
on.exit(graphics::par(usr=usr))
graphics::par(usr = c(usr[1:2], 0, 1.5) )
h <- hist(x, plot = FALSE)
breaks <- h$breaks
nB <- length(breaks)
y <- h$counts
y <- y/max(y)
graphics::rect(breaks[-nB], 0, breaks[-1], y, col="green")
}
panelcor <- function(x, y,...) {
usr <- graphics::par("usr")
on.exit(graphics::par(usr=usr))
graphics::par(usr = c(0, 1, 0, 1))
r <- abs(stats::cor(x, y, use=use))
txt <- format(c(r, 0.123456789), digits=2)[1]
text(0.5, 0.5, txt, cex = max(0.5, r * 2))
}
if (hist) {dp <- panelhist} else {dp <- NULL}
if (cor) {up <- panelcor} else {up <- NULL}
d <- spatSample(x, maxcells, method="regular", as.raster=FALSE, warn=FALSE)
dots <- list(...)
cex <- dots$cex
main <- dots$main
if (is.null(cex)) cex <- 0.5
if (is.null(main)) main <- ""
graphics::pairs(d, main=main, cex=cex, upper.panel=up, diag.panel=dp)
}
)
.textbox <- function(x, y=NULL, labels, col="black", hc="white", hw=0.1, ... ) {
xy <- grDevices::xy.coords(x, y)
hw <- hw[1]
n <- nchar(labels)
x0 <- hw * graphics::strwidth("A")
y0 <- hw * graphics::strheight("A")
x1 <- n * x0
v <- vect(cbind(xy$x + c(0, x1), xy$y), crs="local")
b <- buffer(v, y0)
}
.halo <- function(x, y=NULL, labels, col="black", hc="white", hw=0.1, ... ) {
xy <- grDevices::xy.coords(x, y)
hw <- hw[1]
xo <- hw * graphics::strwidth("A")
yo <- hw * graphics::strheight("A")
n <- nchar(labels)
fact <- 100 * max(1, hw*2)
theta <- seq(pi/4, 2*pi, length.out=hw*fact)
for (i in theta) {
text( xy$x + cos(i)*xo, xy$y + sin(i)*yo, labels, col=hc, ... )
}
graphics::text(xy$x, xy$y, labels, col=col, ... )
}
halo <- function(x, y=NULL, labels, col="black", hc="white", hw=0.1, ... ) {
.halo(x=x, y=y, labels=labels, col=col, hc=hc, hw=hw, ...)
}
setMethod("text", signature(x="SpatRaster"),
function(x, labels, digits=0, halo=FALSE, hc="white", hw=0.1, ...) {
if (missing(labels)) {
labels <- 1
}
if (length(labels) != ncell(x)) {
labels <- labels[1]
if (is.character(labels)) {
i <- which(labels == names(x))
if (i == 0) {
i <- 1
}
}
x <- x[[labels]]
labels <- as.data.frame(x)[,1]
p <- as.points(x, values=TRUE)
} else {
p <- as.points(x, values=FALSE, na.rm=FALSE)
}
xy <- geom(p)[, c("x", "y"), drop=FALSE]
if (is.factor(labels)) {
labels <- substr(as.character(labels), 1, max(1, digits))
} else if (is.numeric(labels)) {
labels <- as.character(round(labels, digits=digits) )
}
if (length(labels) < nrow(xy)) {
labels <- rep(labels, nrow(xy))
}
# if (!overlap) {
# xy <- getLabelXY(xy, labels, cex)
# }
if (halo && (isTRUE(hw > 0))) {
.halo(xy[,1], xy[,2], labels, hc=hc, hw=hw, ...)
} else {
text(xy[,1], xy[,2], labels, ...)
}
}
)
setMethod("text", signature(x="SpatVector"),
function(x, labels, halo=FALSE, inside=FALSE, hc="white", hw=0.1, ...) {
if (missing(labels)) {
labels <- 1:nrow(x)
} else if (length(labels) == 1) {
if (nrow(x) > 1) {
labels <- as.data.frame(x)[,labels]
} else {
if (is.numeric(labels)) {
if (labels %in% 1:ncol(x)) {
labels <- x[[labels]][,1]
}
} else if (labels %in% names(x)) {
labels <- x[[labels]][,1]
}
}
}
xy <- geom(centroids(x, inside=inside))[,c("x","y"),drop=FALSE]
if (halo && (isTRUE(hw > 0))) {
.halo(xy[,1], xy[,2], labels, hc=hc, hw=hw, ...)
} else {
text(xy[,1], xy[,2], labels, ...)
}
}
)
setMethod("boxplot", signature(x="SpatRaster"),
function(x, y=NULL, maxcell=100000, ...) {
if (is.null(y)) {
cn <- names(x)
if ( ncell(x) > maxcell) {
warn("boxplot", "taking a sample of ", maxcell, " cells")
x <- spatSample(x, maxcell, method="regular", as.raster=TRUE, warn=FALSE)
}
names(x) <- cn
boxplot(values(x), ...)
} else {
s <- c(x[[1]], y[[1]])
if ( ncell(x) > maxcell) {
warn("boxplot", "taking a regular sample of ", maxcell, " cells")
s <- spatSample(s, maxcell, method="regular", as.raster=TRUE, warn=FALSE)
}
s <- values(s, dataframe=TRUE)
cn <- colnames(s)
if (is.null(cn)) cn <- c("", "")
colnames(s)[cn==""] <- c("layer1", "layer2")[cn==""]
f <- try(stats::as.formula(paste(cn[1], '~', cn[2])), silent=TRUE)
if (inherits(f, "try-error")) {
colnames(s) <- c("layer1", "layer2")
f <- layer1 ~ layer2
}
boxplot(f, data=s, ...)
}
}
)
setMethod("barplot", "SpatRaster",
function(height, maxcell=1000000, digits=0, breaks=NULL, col, ...) {
if (missing(col)) {
col=grDevices::rainbow
}
height <- height[[1]]
f <- is.factor(height)
# x <- spatSample(height[[1]], maxcell, method="regular", as.raster=FALSE, as.df=f)
x <- spatSample(height[[1]], maxcell, method="regular", as.raster=FALSE, as.df=FALSE, warn=FALSE)
adj <- nrow(x) / ncell(height)
if (adj < 1) {
warn("barplot", "a sample of ", round(100*adj, 1), "% of the raster cells were used to estimate frequencies")
}
if (!f) {
if (!is.null(digits)) {
x <- round(x, digits)
}
if (!is.null(breaks)) {
x <- cut(x, breaks)
}
}
x <- table(x) / adj
if (is.function(col)) {
col <- col(length(x))
}
barplot(x, col=col, ...)
}
)
shade <- function(slope, aspect, angle=45, direction=0, normalize=FALSE, filename="", overwrite=FALSE, ...) {
stopifnot(inherits(slope, "SpatRaster"))
opt <- spatOptions(filename, overwrite=overwrite, ...)
slope@pntr <- slope@pntr$hillshade(aspect@pntr, angle, direction, normalize[1], opt)
messages(slope, "shade")
}
map.pal <- function(name, n=50, ...) {
n <- round(n)
if (n < 1) {
error("map.pal", "n should be >= 1")
}
f <- system.file("colors/palettes.rds", package="terra")
v <- readRDS(f)
if (missing(name)) {
return(names(v))
}
if (name %in% names(v)) {
v <- v[[name]]
if ((n > 0) && ((length(v) != n))) {
grDevices::colorRampPalette(v, ...)(n)
} else {
v
}
} else if (name == "random") {
if (n > 433) {
warning("map.pal", "you cannot get > 433 random colors; using n=433 instead")
n <- 433
}
s <- sample(grDevices::colors()[grep('gr(a|e)y', grDevices::colors(), invert = TRUE)], n)
rgb(t(grDevices::col2rgb(s))/255)
} else {
error("map.pal", paste(name, "is not a known palette"))
}
}
map.leg <- function(name) {
f <- system.file("colors/legends.rds", package="terra")
v <- readRDS(f)
if (name %in% names(v)) {
v[[name]]
} else {
error("map.leg", paste(name, "is not a known legend"))
}
}
terra/R/crosstab.R 0000644 0001762 0000144 00000003610 14732065727 013550 0 ustar ligges users # Author: Robert J. Hijmans
# Date : March 2009
# Version 1.0
# License GPL v3
# revised April 2011
# adapted November 2020
setMethod("crosstab", signature(x="SpatRaster", y="missing"),
function(x, digits=0, long=FALSE, useNA=FALSE) {
nl <- nlyr(x)
if (nl < 2) {
error("crosstab", "needs at least 2 layers")
}
nms <- names(x)
opt <- spatOptions()
b <- blocks(x, 4)
readStart(x)
on.exit(readStop(x))
res <- NULL
nc <- ncol(x)
for (i in 1:b$n) {
d <- readValues(x, b$row[i], b$nrows[i], 1, nc, TRUE)
d <- lapply(1:nl, function(i) round(d[, i], digits=digits))
d <- do.call(table, c(d, useNA="ifany"))
d <- as.data.frame(d)
res <- rbind(res, d)
}
res <- res[res$Freq > 0, ,drop=FALSE]
# some complexity to aggregate keeping
# variables that are NA
if (useNA) {
for (i in 1:(ncol(res)-1)) {
if (any(is.na(res[,i]))) {
res[,i] <- factor(res[,i], levels=c(levels(res[,i]), NA), exclude=NULL)
}
}
}
res <- aggregate(res[, ncol(res), drop=FALSE], res[, 1:(ncol(res)-1), drop=FALSE], sum)
for (i in 1:(ncol(res)-1)) {
# get rid of factors
res[,i] <- as.numeric(as.character(res[,i]))
}
if (nrow(res) == 0) {
res <- data.frame(matrix(nrow=0, ncol=length(nms)+1))
}
nms <- make.names(nms, unique=TRUE)
colnames(res) <- c(nms, "Freq")
if (! useNA ) {
i <- apply(res, 1, function(x) any(is.na(x)))
res <- res[!i, ,drop=FALSE]
}
ff <- is.factor(x)
if (any(ff) && (digits >= 0)) {
ff <- which(ff)
v <- levels(x)
for (i in ff) {
j <- match(res[,i], v[[i]][,1])
res[,i] <- v[[i]][j,2]
}
}
if (!long) {
f <- eval(parse(text=paste("Freq ~ ", paste(nms , collapse="+"))))
res <- stats::xtabs(f, data=res, addNA=useNA)
} else {
res <- res[res$Freq > 0, ,drop=FALSE]
res <- res[order(res[,1], res[,2]), ]
rownames(res) <- NULL
colnames(res)[ncol(res)] <- "n"
}
return(res)
}
)
terra/R/rasterize.R 0000644 0001762 0000144 00000022766 14726700274 013751 0 ustar ligges users
setMethod("rasterizeGeom", signature(x="SpatVector", y="SpatRaster"),
function(x, y, fun="count", unit="m", filename="", ...) {
opt <- spatOptions(filename, ...)
y@pntr <- y@pntr$rasterizeGeom(x@pntr, unit, fun, opt)
messages(y, "rasterizeGeom")
}
)
# now can use
# r@pntr = r@pntr$rasterizePoints(v@pntr, "mean", 1:nrow(v), NA, opt)
.set_names <- function(wopt, cnms, fun, nc) {
if (is.null(wopt$names)) {
if (is.null(cnms)) {
if (nc == 1) {
cnms <- fun
} else {
cnms <- paste0(fun, "_", 1:nc)
}
} else {
cnms <- paste0(cnms, "_", fun)
}
wopt$names <- cnms
}
wopt
}
rasterize_points <- function(x, y, values, fun="last", background=NA, update=FALSE, filename="", overwrite=FALSE, wopt=list(), ...) {
if (missing(fun)) fun <- "last"
if (update && (!hasValues(y))) update <- FALSE
nrx <- nrow(x)
if (!is.data.frame(values)) {
values <- as.data.frame(values)
}
if (nrow(values) == 1) {
values <- sapply(values, function(x) rep_len(x, nrx))
if (!is.data.frame(values)) { # dropped if nrx==1
values <- as.data.frame(values)
}
} else if (nrow(values) != nrx) {
error("rasterize", paste0("the number or rows in values is ", nrow(values), "\nThat does not match the number of points: ", nrx))
}
cnms <- colnames(values)
nl <- ncol(values)
r <- rast(y, nlyrs=nl)
levs <- list()
has_levels <- FALSE
for (i in 1:nl) {
if (is.character(values[,i])) {
f <- as.factor(values[,i])
levs[[i]] <- levels(f)
values[,i] <- as.integer(f) - 1
has_levels <- TRUE
} else if (is.factor(values[,i])) {
f <- values[,i]
levs[[i]] <- levels(f)
values[,i] <- as.integer(f) - 1
has_levels <- TRUE
}
}
if (NCOL(values) == 1 && (!has_levels)) {
txtfun <- .makeTextFun(fun)
if (inherits(txtfun, "character")) {
if (txtfun %in% c("first", "last", "pa", "sum", "mean", "count", "min", "max", "prod")) {
if (is.null(wopt$names)) {
wopt$names <- txtfun
}
if (update) {
ops <- spatOptions("", TRUE, wopt=wopt)
} else {
ops <- spatOptions(filename, overwrite, wopt=wopt)
}
narm <- isTRUE(list(...)$na.rm)
r <- rast()
r@pntr <- y@pntr$rasterizePointsXY(x[,1], x[,2], txtfun, values[[1]], narm, background, ops)
messages(r)
if (update) {
r <- cover(r, y, filename=filename, overwrite=overwrite, wopt=wopt)
}
return(r)
}
}
}
if (inherits(fun, "character")) {
if (fun == "first") {
fun <- function(i, na.rm=FALSE) {
if (na.rm) {
i <- na.omit(i)
}
if (length(i) > 0) {
i[i]
} else {
NA
}
}
} else if (fun == "last") {
fun <- function(i, na.rm=FALSE) {
if (na.rm) {
i <- na.omit(i)
}
if (length(i) > 0) {
i[length(i)]
} else {
NA
}
}
} else if (fun == "count") {
fun <- function(i, na.rm=FALSE) {
if (na.rm) {
i <- na.omit(i)
}
length(i)
}
has_levels <- FALSE
}
} else {
has_levels <- FALSE
}
g <- cellFromXY(y, x)
i <- which(!is.na(g))
g <- g[i]
if (length(g) == 0) {
return(r)
}
values <- values[i, ,drop=FALSE]
values <- aggregate(values, list(g), fun, ...)
#if (!all(values %in% ) ?
#has_levels <- FALSE ??
#levs <- NULL ??
# allow for multiple fields
#r[a[,1]] <- as.matrix(a[,-1])
if (is.null(wopt$names)) {
fun <- .makeTextFun(fun)
if (inherits(fun, "character")) {
wopt <- .set_names(wopt, cnms, fun, NCOL(values))
} else if (!is.null(cnms)) {
wopt$names <- cnms
}
}
values <- as.matrix(values)
nl <- max(1, ncol(values)-1)
r <- rast(r, nlyrs=nl)
if (!update) {
if (has_levels) {
levels(r) <- levs
}
b <- writeStart(r, filename=filename, sources=sources(y), overwrite=overwrite, wopt=wopt)
filename <- ""
} else {
b <- writeStart(r, "")
}
nc <- ncol(r)
for (i in 1:b$n) {
w <- matrix(background, nrow=b$nrows[i] * nc, ncol=nl)
mincell <- cellFromRowCol(r, b$row[i], 1)
maxcell <- cellFromRowCol(r, b$row[i] + b$nrows[i]-1, nc)
vv <- values[values[,1] >= mincell & values[,1] <= maxcell, ,drop=FALSE]
if (nrow(vv) > 0) {
vv[,1] <- vv[,1] - (b$row[i] - 1) * nc
w[vv[,1],] <- vv[,-1]
}
writeValues(r, w, b$row[i], b$nrows[i])
}
r <- writeStop(r)
if (update) {
r <- cover(r, y, filename=filename, overwrite=overwrite, wopt=wopt)
}
return (r)
}
setMethod("rasterize", signature(x="matrix", y="SpatRaster"),
function(x, y, values=1, fun, ..., background=NA, update=FALSE, by=NULL, filename="", overwrite=FALSE, wopt=list()) {
if (!is.null(by)) {
by <- rep_len(by, nrow(x))
values <- rep_len(values, nrow(x))
x <- lapply(split(data.frame(x), by), as.matrix)
values <- split(values, by)
out <- rast(lapply(1:length(x), function(i) rasterize(x[[i]], y, values[[i]], fun, background=background, update=update)))
names(out) <- unique(by)
if (filename != "") {
out <- writeRaster(out, filename, overwrite=overwrite, wopt=wopt)
}
return(out)
}
#lonlat <- .checkXYnames(colnames(x))
if (NCOL(values) <= 1) {
values <- unlist(values)
if (length(values) > nrow(x)) {
error("rasterize", "length(values) > nrow(x)")
}
values=rep_len(values, nrow(x))
} else {
if (nrow(values) > nrow(x)) {
error("rasterize", "nrow(values) > nrow(x)")
}
if (nrow(values) < nrow(x)) {
i <- rep_len(1:nrow(values), nrow(x))
values <- values[i, ]
}
}
rasterize_points(x=x, y=y, values=values, fun=fun, background=background, update=update, filename=filename, overwrite=overwrite, wopt=wopt, ...)
}
)
setMethod("rasterize", signature(x="SpatVector", y="SpatRaster"),
function(x, y, field="", fun, ..., background=NA, touches=FALSE, update=FALSE, cover=FALSE, by=NULL, filename="", overwrite=FALSE, wopt=list()) {
if (!is.null(by)) {
x <- split(x, by)
uby <- names(x)
##uby <- sapply(x, function(i) i[[by]][1])
out <- rast(lapply(x, function(i) rasterize(i, y, field=field, fun, background=background, touches=touches, update=update, cover=cover, ...)))
names(out) <- uby
if (filename != "") {
out <- writeRaster(out, filename, overwrite=overwrite, wopt=wopt)
}
return(out)
}
values <- 1
if (!is.character(field)) {
values <- as.numeric(field)
field <- ""
} else if (is.na(field[1])) {
values <- as.numeric(NA)
field <- ""
} else if (is.null(field) || field[1] == "") {
field <- ""
} else if (!(field[1] %in% names(x))) {
error("rasterize", paste(field, "is not a field in 'x'"))
}
g <- geomtype(x)
if (grepl("points", g)) {
nrx <- nrow(x)
# also allow for multiple columns to multiple layers
xy <- crds(x)
if (field[1] == "") {
values <- matrix(1, ncol=1, nrow=nrx)
} else if (field[1] != "") {
values <- x[, field, drop=TRUE]
if (nrow(xy) != nrx) { # multi-points
g <- geom(x)
values <- values[g[,1], ,drop=FALSE]
}
}
return(
rasterize_points(x=xy, y=y, values=values, fun=fun, background=background, update=update, filename=filename, overwrite=overwrite, wopt=wopt, ...)
)
}
opt <- spatOptions(filename, overwrite, wopt=wopt)
pols <- grepl("polygons", g)
dots <- list(...)
nms <- names(dots)
nms <- nms[!(nms %in% c("na.rm", "fun", "sum"))]
if (length(nms) > 0) {
warn("rasterize", paste("unexpected additional argument(s):", paste(nms, collapse=", ")))
}
if (cover[1] && pols) {
y@pntr <- y@pntr$rasterize(x@pntr, "", 1, background, touches[1], "", TRUE, FALSE, TRUE, opt)
} else {
if (missing(fun)) {
if (!is.null(dots$sum)) {
# backward compatibility
if (isTRUE(dots$sum)) fun <- "sum"
} else {
fun <- ""
}
}
if (!inherits(fun, "character")) {
fun <- .makeTextFun(fun)
if (!inherits(fun, "character")) {
error("rasterize", "'fun' must be 'min', 'max', 'mean', 'count', or 'sum'")
}
}
if (fun != "") {
fun <- tolower(fun)
if (!(fun %in% c("sum", "mean", "min", "max", "count"))) {
error("rasterize", "'fun' must be 'min', 'max' 'mean', 'count', or 'sum'")
}
if (fun == "count") {
fun <- "sum"
field <- ""
values <- 1
} else if (field != "") {
if (fun == "min") {
x <- sort(x[,field], field, TRUE)
fun <- ""
} else if (fun == "max") {
x <- sort(x[,field], field, FALSE)
fun <- ""
}
}
}
if ((field != "") && isTRUE(dots$na.rm)) {
x <- x[!is.na(x[[field]]), ]
}
background <- as.numeric(background[1])
if (fun == "sum") {
xopt = spatOptions()
y@pntr <- y@pntr$rasterize(x@pntr, field, values, background, touches[1], fun, FALSE, update[1], TRUE, xopt)
messages(y, "rasterize")
xopt = spatOptions()
yy <- rast(y)
yy@pntr <- y@pntr$rasterize(x@pntr, "", values, NA, touches[1], "" , FALSE, update[1], TRUE, xopt)
messages(yy, "rasterize")
return(mask(y, yy, updatevalue=background, filename=filename, overwrite=overwrite, wopt=wopt))
} else if (fun == "mean") {
xopt = spatOptions()
y@pntr <- y@pntr$rasterize(x@pntr, field, values, background, touches[1], "sum", FALSE, update[1], TRUE, xopt)
messages(y, "rasterize")
xopt = spatOptions()
yy <- rast(y)
yy@pntr <- y@pntr$rasterize(x@pntr, "", values, NA, touches[1], "sum", FALSE, update[1], TRUE, xopt)
messages(yy, "rasterize")
y <- y / yy
if (filename != "") {
y <- writeRaster(y, filename=filename, overwrite=overwrite, wopt=wopt)
}
return(y)
} else {
y@pntr <- y@pntr$rasterize(x@pntr, field, values, background, touches[1], fun, FALSE, update[1], TRUE, opt)
}
}
messages(y, "rasterize")
}
)
setMethod("rasterize", signature(x="sf", y="SpatRaster"),
function(x, y, ...) {
x <- vect(x)
rasterize(x, y, ...)
}
)
terra/R/relate.R 0000644 0001762 0000144 00000024536 14745061100 013177 0 ustar ligges users
setMethod("is.related", signature(x="SpatVector", y="SpatVector"),
function(x, y, relation) {
out <- x@pntr$is_related(y@pntr, relation)
x <- messages(x, "is.related")
out
}
)
setMethod("is.related", signature(x="SpatVector", y="SpatExtent"),
function(x, y, relation) {
y <- as.polygons(y)
out <- x@pntr$is_related(y@pntr, relation)
x <- messages(x, "is.related")
out
}
)
setMethod("is.related", signature(x="SpatExtent", y="SpatVector"),
function(x, y, relation) {
x <- as.polygons(x)
out <- x@pntr$is_related(y@pntr, relation)
x <- messages(x, "is.related")
out
}
)
setMethod("is.related", signature(x="SpatVector", y="SpatRaster"),
function(x, y, relation) {
y <- as.polygons(y, ext=TRUE)
out <- x@pntr$is_related(y@pntr, relation)
x <- messages(x, "is.related")
out
}
)
setMethod("is.related", signature(x="SpatRaster", y="SpatVector"),
function(x, y, relation) {
x <- as.polygons(x, ext=TRUE)
out <- x@pntr$is_related(y@pntr, relation)
x <- messages(x, "is.related")
out
}
)
setMethod("is.related", signature(x="SpatExtent", y="SpatRaster"),
function(x, y, relation) {
x <- as.polygons(x)
y <- as.polygons(y, ext=TRUE)
out <- x@pntr$is_related(y@pntr, relation)
x <- messages(x, "is.related")
out
}
)
setMethod("is.related", signature(x="SpatRaster", y="SpatExtent"),
function(x, y, relation) {
x <- as.polygons(x, ext=TRUE)
y <- as.polygons(y)
out <- x@pntr$is_related(y@pntr, relation)
x <- messages(x, "is.related")
out
}
)
setMethod("is.related", signature(x="SpatRaster", y="SpatRaster"),
function(x, y, relation) {
x <- as.polygons(x, ext=TRUE)
y <- as.polygons(y, ext=TRUE)
out <- x@pntr$is_related(y@pntr, relation)
x <- messages(x, "is.related")
out
}
)
setMethod("relate", signature(x="SpatVector", y="SpatVector"),
function(x, y, relation, pairs=FALSE, na.rm=TRUE) {
if (pairs) {
out <- x@pntr$related_between(y@pntr, relation[1], na.rm[1])
messages(x, "relate")
if (length(out[[1]]) == 0) {
cbind(id.x=0,id.y=0)[0,,drop=FALSE]
} else {
names(out) <- c("id.x", "id.y")
do.call(cbind, out) + 1
}
} else {
out <- x@pntr$related_between(y@pntr, relation[1], TRUE)
messages(x, "relate")
m <- matrix(FALSE, nrow(x), nrow(y))
if (length(out[[1]]) > 0) {
m[do.call(cbind, out) + 1] <- TRUE
}
m
# out <- x@pntr$relate_between(y@pntr, relation, TRUE, TRUE)
# messages(x, "relate")
# out[out == 2] <- NA
# matrix(as.logical(out), nrow=nrow(x), byrow=TRUE)
}
}
)
#setMethod("which.related", signature(x="SpatVector", y="SpatVector"),
# function(x, y, relation) {
# out <- x@pntr$which_related(y@pntr, relation)
# x <- messages(x, "which.related")
# out <- do.call(cbind, out) + 1
# colnames(out) <- c("id.x", "id.y")
# out
# }
#)
setMethod("relate", signature(x="SpatVector", y="SpatExtent"),
function(x, y, relation, ...) {
y <- as.polygons(y)
relate(x, y, relation, ...)
}
)
setMethod("relate", signature(x="SpatExtent", y="SpatVector"),
function(x, y, relation, ...) {
x <- as.polygons(x)
relate(x, y, relation, ...)
}
)
setMethod("relate", signature(x="SpatVector", y="SpatRaster"),
function(x, y, relation, ...) {
y <- as.polygons(y, ext=TRUE)
relate(x, y, relation, ...)
}
)
setMethod("relate", signature(x="SpatRaster", y="SpatVector"),
function(x, y, relation, ...) {
x <- as.polygons(x, ext=TRUE)
relate(x, y, relation, ...)
}
)
setMethod("relate", signature(x="SpatExtent", y="SpatRaster"),
function(x, y, relation, ...) {
x <- as.polygons(x)
y <- as.polygons(y, ext=TRUE)
relate(x, y, relation, ...)
}
)
setMethod("relate", signature(x="SpatRaster", y="SpatExtent"),
function(x, y, relation, ...) {
x <- as.polygons(x, ext=TRUE)
y <- as.polygons(y)
relate(x, y, relation, ...)
}
)
setMethod("relate", signature(x="SpatRaster", y="SpatRaster"),
function(x, y, relation, ...) {
x <- as.polygons(x, ext=TRUE)
y <- as.polygons(y, ext=TRUE)
relate(x, y, relation, ...)
}
)
setMethod("relate", signature(x="SpatExtent", y="SpatExtent"),
function(x, y, relation, ...) {
x <- as.polygons(x)
y <- as.polygons(y)
relate(x, y, relation, ...)
}
)
setMethod("relate", signature(x="SpatVector", y="missing"),
function(x, y, relation, pairs=FALSE, na.rm=TRUE) {
if (pairs) {
out <- x@pntr$related_within(relation, na.rm[1])
messages(x, "relate")
if (length(out[[1]]) == 0) {
cbind(id.1=0,id.2=0)[0,,drop=FALSE]
} else {
names(out) <- c("id.1", "id.2")
do.call(cbind, out) + 1
}
} else {
out <- x@pntr$related_within(relation, TRUE)
messages(x, "relate")
out <- do.call(cbind, out) + 1
m <- matrix(FALSE, nrow(x), nrow(x))
m[out] <- TRUE
m
#if (symmetrical) {
# as.dist(m)
#} else {
# m
#}
}
#out <- x@pntr$relate_within(relation, symmetrical)
#out[out == 2] <- NA
#if (symmetrical) {
# class(out) <- "dist"
# attr(out, "Size") <- nrow(x)
# attr(out, "Diag") <- FALSE
# attr(out, "Upper") <- FALSE
#} else {
# out <- matrix(as.logical(out), nrow=nrow(x), byrow=TRUE)
#}
#if (pairs) {
# out <- mat2wide(out, symmetrical)
#}
#out
}
)
setMethod("adjacent", signature(x="SpatRaster"),
function(x, cells, directions="rook", pairs=FALSE, include=FALSE, symmetrical=FALSE) {
cells <- cells - 1
if (inherits(directions, "matrix")) {
directions[!is.finite(directions)] <- 0
if (isTRUE(all(directions == 0))) {
error("adjacent", "directions are all FALSE")
}
v <- x@pntr$adjacentMat(cells, as.logical(t(directions)), dim(directions), include)
} else {
#if (pairs) include <- FALSE
v <- x@pntr$adjacent(cells, as.character(directions)[1], include)
}
messages(x, "adjacent")
if (pairs) {
v <- cbind(from=rep(cells, each=length(v)/length(cells)), to=v)
v <- v[!is.na(v[,2]), ]
if (symmetrical) {
#v <- unique(cbind(pmin(v[,1], v[,2]), pmax(v[,1], v[,2])))
v <- .unique_symmetric_rows(v[,1], v[,2])
}
} else {
v <- matrix(v, nrow=length(cells), byrow=TRUE)
if (!include) rownames(v) <- cells
}
v + 1
}
)
setMethod("adjacent", signature(x="SpatVector"),
function(x, type="rook", pairs=TRUE, symmetrical=FALSE) {
type <- match.arg(tolower(type), c("intersects", "touches", "queen", "rook"))
stopifnot(geomtype(x) == "polygons")
a <- x@pntr$relate_within(type, TRUE)
x <- messages(x, "relate")
a[a == 2] <- NA
class(a) <- "dist"
attr(a, "Size") <- nrow(x)
attr(a, "Diag") <- FALSE
attr(a, "Upper") <- FALSE
a <- as.matrix(a)
if (pairs) {
mat2wide(a, symmetrical, 1)
} else {
a
}
}
)
setMethod("nearby", signature(x="SpatVector"),
function(x, y=NULL, distance=0, k=1, centroids=TRUE, symmetrical=TRUE, method="geo") {
k <- round(k)
if (distance <= 0 && k < 1) {
error("nearby", "either distance or k must be a positive number")
}
if (!(method %in% c("geo", "haversine", "cosine"))) {
error("nearby", "not a valid method. Should be one of: 'geo', 'haversine', 'cosine'")
}
if ((geomtype(x) == "polygons") && centroids) {
x <- centroids(x)
}
hasy <- !is.null(y)
if (hasy) {
if ((geomtype(y) == "polygons") && centroids) {
y <- centroids(y)
}
}
if (distance > 0) {
if (hasy) {
d <- distance(x, y, method=method)
d <- cbind(from_id=rep(1:nrow(d), ncol(d)), to_id=rep(1:ncol(d), each=nrow(d)), distance=as.vector(d))
} else {
d <- distance(x, pairs=TRUE, symmetrical=symmetrical, method=method)
}
d[d[,3] <= distance, 1:2, drop=FALSE]
} else {
if (hasy) {
k <- max(1, min(round(k), (nrow(y)-1)))
} else {
k <- max(1, min(round(k), (nrow(x)-1)))
}
# if (k > 1) {
if (hasy) {
d <- distance(x, y)
} else {
d <- as.matrix(distance(x, pairs=FALSE, method=method))
diag(d) <- NA
}
d <- t(apply(d, 1, function(i) order(i)[1:k]))
if (k==1) d <- t(d)
d <- cbind(1:length(x), d)
# } else {
# d <- nearest(x)
# d <- values(d)[, c("from_id", "to_id")]
# }
colnames(d) <- c("id", paste0("k", 1:k))
d
}
}
)
setMethod("nearest", signature(x="SpatVector"),
function(x, y=NULL, pairs=FALSE, centroids=TRUE, lines=FALSE, method="geo") {
if ((geomtype(x) == "polygons") && centroids) {
x <- centroids(x)
}
within <- FALSE
if (is.null(y)) {
within <- TRUE
y <- x
} else if ((geomtype(y) == "polygons") && centroids) {
y <- centroids(y)
}
z <- x
if (!(method %in% c("geo", "haversine", "cosine"))) {
error("nearest", "not a valid method. Should be one of: 'geo', 'haversine', 'cosine'")
}
if (within) {
z@pntr <- x@pntr$near_within(method)
} else {
z@pntr <- x@pntr$near_between(y@pntr, pairs, method)
}
z <- terra:::messages(z, "nearest")
if (geomtype(z) == "points") { #lonlat points
if (lines) {
x <- z[,c(2,5), drop=TRUE]
y <- z[,c(3,6), drop=TRUE]
geom <- cbind(rep(1:nrow(x), each=2), 1, as.vector(t(x)), as.vector(t(y)))
zz <- vect(geom, "lines", crs=crs(z))
values(zz) <- values(z)
zz$to_id = zz$to_id + 1
zz$from_id = zz$from_id + 1
return(zz)
} else {
z$to_id = z$to_id + 1
z$from_id = z$from_id + 1
return(z)
}
} else {
if (lines) return(z)
values(y) <- data.frame(to_id=1:nrow(y))
dis <- perim(z)
zz <- as.points(z)
from <- zz[seq(1, nrow(zz), 2), ]
to <- zz[seq(2, nrow(zz), 2), ]
values(to) <- data.frame(id=1:nrow(to))
to_int <- as.data.frame(intersect(to, y))
to_int <- to_int[!duplicated(to_int[,1]), ]
to_int <- as.data.frame(merge(to, to_int, by="id", all.x=TRUE))
if (any(is.na(to_int$to_id))) {
zz <- as.points(elongate(z, 1))
from2 <- zz[seq(1, nrow(zz), 2), ]
to2 <- zz[seq(2, nrow(zz), 2), ]
values(to2) <- data.frame(id=1:nrow(to2))
to_int2 <- as.data.frame(intersect(to2, y))
colnames(to_int2)[2] <- "to_id2"
to_int <- merge(to_int, to_int2, all.x=TRUE)
i <- is.na(to_int$to_id)
to_int$to_id[i] <- to_int$to_id2[i]
to_int <- to_int[,1:2]
}
to_int <- to_int[order(to_int[["id"]]), ]
if (nrow(to_int) > nrow(to)) {
to_int <- aggregate(to_int[, "to_id",drop=FALSE], to_int[,"id",drop=FALSE], function(x)x[1])
# }
# if (nrow(to_int) < nrow(to)) {
# to_int <- rep(NA, nrow(to))
} else {
to_int <- to_int[,2]
}
from <- geom(from)[, c("x", "y"),drop=FALSE]
to <- geom(to)[, c("x", "y"),drop=FALSE]
d <- data.frame(1:nrow(from), from, to_int, to, dis)
colnames(d) <- c("from_id", "from_x", "from_y", "to_id", "to_x", "to_y", "distance")
vect(d, c("to_x", "to_y"), crs=crs(x))
}
}
)
terra/R/regress.R 0000644 0001762 0000144 00000010377 14536376240 013407 0 ustar ligges users # Author: Robert J. Hijmans
# Date : April 2023
# Version 1.0
# License GPL v3
.reg_constX <- function(formula, X, na.rm=FALSE, nl) {
formula <- eval(stats::as.formula(formula))
nas <- eval(rep(NA, nl))
d <- data.frame(x=X, y=X)
mm <- eval(stats::model.matrix(formula, data=d))
if (na.rm) {
ols <- function(y, ...) {
m <- stats::na.omit(cbind(y, mm))
if (nrow(m) == 0) {
return(nas)
}
stats::.lm.fit(m[,-1,drop=FALSE], m[,1])$coefficients
}
} else {
ols <- function(y, ...) {
if (any(is.na(y))) {
return(nas)
}
stats::.lm.fit(mm, y)$coefficients
}
}
ols
}
setMethod("regress", signature(y="SpatRaster", x="numeric"),
function(y, x, formula=y~x, na.rm=FALSE, cores=1, filename="", overwrite=FALSE, ...) {
if (any(is.na(x))) {
error("regress", "y cannot have NAs")
}
formula <- stats::as.formula(formula)
dat <- data.frame(x=x, y=1)
mm <- stats::model.matrix(formula, data=dat)
outnl <- ncol(mm)
regfun <- .reg_constX(formula, X=x, na.rm=na.rm, nl=outnl)
out <- rast(y)
nlyr(out) <- outnl
names(out) <- colnames(mm)
nc <- ncol(y)
readStart(y)
on.exit(readStop(y))
doclust <- FALSE
if (inherits(cores, "cluster")) {
doclust <- TRUE
} else if (cores > 1) {
doclust <- TRUE
cores <- parallel::makeCluster(cores)
on.exit(parallel::stopCluster(cores), add=TRUE)
}
ncops <- nlyr(y) / nlyr(out)
ncops <- ifelse(ncops > 1, ceiling(ncops), 1) * 4
b <- writeStart(out, filename, overwrite, n=ncops, sources=sources(y), ...)
if (doclust) {
ncores <- length(cores)
#export_args(cores, ...)
for (i in 1:b$n) {
v <- readValues(y, b$row[i], b$nrows[i], 1, nc, TRUE)
icsz <- max(min(100, ceiling(b$nrows[i] / ncores)), b$nrows[i])
r <- parallel::parRapply(cores, v, regfun, chunk.size=icsz)
if (nlyr(out) > 1) {
r <- matrix(r, ncol=nlyr(out), byrow=TRUE)
}
writeValues(out, r, b$row[i], b$nrows[i])
}
} else {
for (i in 1:b$n) {
v <- readValues(y, b$row[i], b$nrows[i], 1, nc, TRUE)
r <- apply(v, 1, regfun)
writeValues(out, t(r), b$row[i], b$nrows[i])
}
}
writeStop(out)
})
.reg_mod <- function(formula, na.rm=FALSE, nl) {
formula <- eval(stats::as.formula(formula))
nas <- eval(rep(NA, nl))
yi <- eval(1:nl)
xi <- eval((nl+1):(nl+nl))
if (na.rm) {
ols <- function(v, ...) {
d <- data.frame(matrix(v, ncol=2, dimnames=list(NULL, c("y", "x"))))
mm <- eval(stats::model.matrix(formula, data=d))
m <- stats::na.omit(cbind(d$y, mm))
if (nrow(m) == 0) {
return(nas)
}
stats::.lm.fit(m[,-1,drop=FALSE], m[,1])$coefficients
}
} else {
ols <- function(v, ...) {
if (any(is.na(v))) {
return(nas)
}
d <- data.frame(matrix(v, ncol=2, dimnames=list(NULL, c("y", "x"))))
mm <- eval(stats::model.matrix(formula, data=d))
stats::.lm.fit(mm, d$y)$coefficients
}
}
ols
}
setMethod("regress", signature(x="SpatRaster", y="SpatRaster"),
function(y, x, formula=y~x, na.rm=FALSE, cores=1, filename="", overwrite=FALSE, ...) {
if (nlyr(y) != nlyr(x)) {
error("regress", "nlyr(x) != nlyr(y)")
}
formula <- stats::as.formula(formula)
dat <- data.frame(x=1:nlyr(x), y=1)
mm <- stats::model.matrix(formula, data=dat)
outnl <- ncol(mm)
regfun <- .reg_mod(formula, na.rm=na.rm, nl=outnl)
out <- rast(y)
nlyr(out) <- outnl
names(out) <- colnames(mm)
nc <- ncol(y)
y <- c(y, x)
readStart(y)
on.exit(readStop(y))
doclust <- FALSE
if (inherits(cores, "cluster")) {
doclust <- TRUE
} else if (cores > 1) {
doclust <- TRUE
cores <- parallel::makeCluster(cores)
on.exit(parallel::stopCluster(cores), add=TRUE)
}
ncops <- nlyr(y) / nlyr(out)
ncops <- ifelse(ncops > 1, ceiling(ncops), 1) * 4
b <- writeStart(out, filename, overwrite, n=ncops, sources=sources(y), ...)
if (doclust) {
ncores <- length(cores)
#export_args(cores, ...)
for (i in 1:b$n) {
v <- readValues(y, b$row[i], b$nrows[i], 1, nc, TRUE)
icsz <- max(min(100, ceiling(b$nrows[i] / ncores)), b$nrows[i])
r <- parallel::parRapply(cores, v, regfun, chunk.size=icsz)
if (nlyr(out) > 1) {
r <- matrix(r, ncol=nlyr(out), byrow=TRUE)
}
writeValues(out, r, b$row[i], b$nrows[i])
}
} else {
for (i in 1:b$n) {
v <- readValues(y, b$row[i], b$nrows[i], 1, nc, TRUE)
r <- apply(v, 1, regfun)
writeValues(out, t(r), b$row[i], b$nrows[i])
}
}
writeStop(out)
})
terra/R/RcppExports.R 0000644 0001762 0000144 00000006105 14756505614 014223 0 ustar ligges users # Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
proj_version <- function() {
.Call(`_terra_proj_version`)
}
hex2rgb <- function(s) {
.Call(`_terra_hex2rgb`, s)
}
rgb2hex <- function(x) {
.Call(`_terra_rgb2hex`, x)
}
.sameSRS <- function(x, y) {
.Call(`_terra_sameSRS`, x, y)
}
.SRSinfo <- function(s) {
.Call(`_terra_getCRSname`, s)
}
.getLinearUnits <- function(s) {
.Call(`_terra_getLinearUnits`, s)
}
.geotransform <- function(fname) {
.Call(`_terra_geotransform`, fname)
}
.gdal_setconfig <- function(option, value) {
invisible(.Call(`_terra_gdal_setconfig`, option, value))
}
.gdal_getconfig <- function(option) {
.Call(`_terra_gdal_getconfig`, option)
}
.gdalinfo <- function(filename, options, oo) {
.Call(`_terra_ginfo`, filename, options, oo)
}
.sdinfo <- function(filename) {
.Call(`_terra_sd_info`, filename)
}
.gdal_version <- function() {
.Call(`_terra_gdal_version`)
}
.geos_version <- function(runtime = FALSE, capi = FALSE) {
.Call(`_terra_geos_version`, runtime, capi)
}
.metadata <- function(filename) {
.Call(`_terra_metatdata`, filename)
}
.sdsmetadata <- function(filename) {
.Call(`_terra_sdsmetatdata`, filename)
}
.parsedsdsmetadata <- function(filename) {
.Call(`_terra_sdsmetatdataparsed`, filename)
}
.gdaldrivers <- function() {
.Call(`_terra_gdal_drivers`)
}
.set_gdal_warnings <- function(level) {
invisible(.Call(`_terra_set_gdal_warnings`, level))
}
.seedinit <- function(seed_val) {
invisible(.Call(`_terra_seed_init`, seed_val))
}
.gdalinit <- function(projpath, datapath) {
invisible(.Call(`_terra_gdal_init`, projpath, datapath))
}
.precRank <- function(x, y, minc, maxc, tail) {
.Call(`_terra_percRank`, x, y, minc, maxc, tail)
}
.clearVSIcache <- function(vsi) {
invisible(.Call(`_terra_clearVSIcache`, vsi))
}
.setGDALCacheSizeMB <- function(x, vsi) {
invisible(.Call(`_terra_setGDALCacheSizeMB`, x, vsi))
}
.getGDALCacheSizeMB <- function(vsi) {
.Call(`_terra_getGDALCacheSizeMB`, vsi)
}
.get_proj_search_paths <- function() {
.Call(`_terra_get_proj_search_paths`)
}
.set_proj_search_paths <- function(paths) {
.Call(`_terra_set_proj_search_paths`, paths)
}
.PROJ_network <- function(enable, url) {
.Call(`_terra_PROJ_network`, enable, url)
}
.pearson <- function(x, y, narm) {
.Call(`_terra_pearson_cor`, x, y, narm)
}
.weighted_pearson <- function(x, y, weights, narm = TRUE) {
.Call(`_terra_weighted_pearson_cor`, x, y, weights, narm)
}
.unique_symmetric_rows <- function(x, y) {
.Call(`_terra_uniqueSymmetricRows`, x, y)
}
dist2segmentPoint_geo <- function(plon, plat, lon1, lat1, lon2, lat2, ilon, ilat) {
.Call(`_terra_dist2segmentPoint_geo`, plon, plat, lon1, lat1, lon2, lat2, ilon, ilat)
}
intermediate <- function(lon1, lat1, lon2, lat2, n, distance) {
.Call(`_terra_intermediate`, lon1, lat1, lon2, lat2, n, distance)
}
terra/R/rast.R 0000644 0001762 0000144 00000033510 14751032423 012667 0 ustar ligges users # Author: Robert J. Hijmans
# Date : October 2017
# Version 1.0
# License GPL v3
new_rast <- function(nrows=10, ncols=10, nlyrs=1, xmin=0, xmax=1, ymin=0, ymax=1, crs, extent, resolution, vals, names, time, units) {
ncols <- round(ncols)
if (ncols < 1) error("rast", "ncols < 1")
nrows <- round(nrows)
if (nrows < 1) error("rast", "nrows < 1")
if (missing(extent)) {
e <- c(xmin, xmax, ymin, ymax)
} else {
extent <- ext(extent)
e <- as.vector(extent)
}
if ((e[1] >= e[2]) || e[3] >= e[4]) {
error("rast,missing", "invalid extent")
}
if (missing(crs)) {
if (e[1] > -360.01 & e[2] < 360.01 & e[3] > -90.01 & e[4] < 90.01) {
crs <- "OGC:CRS84"
} else {
crs <- ""
}
} else {
crs <- character_crs(crs, "rast")
}
#check_proj4_datum(crs)
r <- methods::new("SpatRaster")
r@pntr <- SpatRaster$new(c(nrows, ncols, nlyrs), e, crs)
r <- messages(r, "rast")
if (!missing(resolution)) {
res(r) <- resolution
}
if (!missing(vals)) {
if (length(vals) == 1) {
if (is.na(vals[1])) {
vals <- as.numeric(NA)
}
}
if (!is.null(ncol(vals))) {
nms <- colnames(vals)
if (length(nms) == nlyr(r)) {
names(r) <- nms
}
}
values(r) <- vals
}
if (!missing(names)) {
names(r) <- names
}
if (!missing(time)) {
time(r) <- time
}
if (!missing(units)) {
time(r) <- units
}
r
}
setMethod("rast", signature(x="missing"),
function(x, nrows=180, ncols=360, nlyrs=1, xmin=-180, xmax=180, ymin=-90, ymax=90, crs, extent, resolution, vals, names, time, units) {
new_rast(nrows, ncols, nlyrs, xmin, xmax, ymin, ymax, crs, extent, resolution, vals, names, time, units)
}
)
rast_from_image <- function(x) {
# list representing an "image"
if (! all(dim(x$z) == c(length(x$x), length(x$y)))) {
error("rast", '"z" does not have the right dimensions')
}
# omitted "-1" bug fix by Barry Rowlingson
resx <- ( x$x[length(x$x)] - x$x[1] ) / (length(x$x)-1)
resy <- ( x$y[length(x$y)] - x$y[1] ) / (length(x$y)-1)
xmn <- min(x$x) - 0.5 * resx
xmx <- max(x$x) + 0.5 * resx
ymn <- min(x$y) - 0.5 * resy
ymx <- max(x$y) + 0.5 * resy
dx <- abs(max(abs((x$x[-1] - x$x[-length(x$x)])) / resx) - 1)
dy <- abs(max(abs((x$y[-1] - x$y[-length(x$y)])) / resy) - 1)
if (is.na(dx) | is.na(dy)) {
error("rast", "missing values in coordinates")
}
if (dx > 0.01 | dy > 0.01) {
error("rast", "data are not on a regular grid")
}
# if (xmn > -360.1 & xmx < 360.1 & ymn > -90.1 & ymx < 90.1) {
# crs <- "+proj=longlat +datum=WGS84"
# } else {
# crs <- ""
# }
x <- t(x$z)
x <- x[nrow(x):1, ]
rast(x, extent=ext(xmn, xmx, ymn, ymx), crs="")
}
setMethod("rast", signature(x="list"),
function(x, warn=TRUE) {
i <- sapply(x, function(i) inherits(i, "SpatRaster"))
if (!all(i)) {
if (!any(i)) {
if ((length(x) == 3) && all(c("x", "y", "z") %in% names(x))) {
return(rast_from_image(x))
}
error("rast,list", "none of the elements of x are a SpatRaster")
} else {
warn("rast", sum(!i), " out of ", length(x), " elements of x are not a SpatRaster")
x <- x[i]
}
}
# start with an empty raster (alternatively use a deep copy)
out <- deepcopy(x[[1]])
if (length(x) == 1) {
return(out)
}
opt <- spatOptions()
for (i in 2:length(x)) {
out@pntr$addSource(x[[i]]@pntr, warn, opt)
}
out <- messages(out, "rast")
lnms <- names(x)
if (!is.null(lnms)) {
if (any(lnms != "") && (length(lnms) == nlyr(out))) {
rnms <- names(out)
rnms[lnms != ""] <- lnms[lnms != ""]
names(out) <- rnms
} else if (all(lnms != "")) {
nl <- sapply(x, nlyr)
rnms <- sapply(1:length(nl), function(i) {
if (nl[i] > 1) paste0(lnms[i], "_", 1:nl[i]) else lnms[i]
})
names(out) <- unlist(rnms)
}
}
out
}
)
setMethod("rast", signature(x="SpatExtent"),
function(x, ...) {
dots <- list(...)
dots$xmin=x[1]
dots$xmax=x[2]
dots$ymin=x[3]
dots$ymax=x[4]
r <- do.call(new_rast, dots)
# re-apply extent to avoid mimute differences
ext(r) <- x
r
}
)
setMethod("rast", signature(x="SpatVector"),
function(x, type="", ...) {
if (type == "xyz") {
if (geomtype(x) != "points") {
error("rast", "xyz can only be used with points")
}
x <- data.frame(crds(x), data.frame(x))
return(rast(x, type="xyz", ...))
}
dots <- list(...)
e <- ext(x)
dots$xmin=e[1]
dots$xmax=e[2]
dots$ymin=e[3]
dots$ymax=e[4]
if (all(is.na(pmatch(names(dots), "crs")))) {
dots$crs <- crs(x)
}
do.call(new_rast, dots)
}
)
.fullFilename <- function(x, mustExist=FALSE, vsi=FALSE) {
x <- trimws(x)
x <- x[x != ""]
x <- enc2utf8(x)
i <- substr(x, 1, 5) == "s3://"
x[i] <- paste0("/vsis3/", substr(x[i], 6, nchar(x[i])))
if (all(i)) return(x)
i <- substr(x, 1, 4) == "http"
if (vsi) {
x[i] <- paste0("/vsicurl/", x[i])
}
if (all(i)) return(x)
i <- grepl(":", x)
if (all(i)) return(x)
p <- normalizePath(x[!i], winslash = "/", mustWork = FALSE)
if (mustExist) {
j <- file.exists(dirname(p))
x[j] <- p[j]
} else {
i <- !file.exists(p)
p[i] <- x[i]
return(p)
}
#if (identical(basename(x), x)) {
# x <- file.path(getwd(), x)
#}
#if (expand) {
# x <- path.expand(x)
#}
return(x)
}
setMethod("rast", signature(x="character"),
function(x, subds=0, lyrs=NULL, drivers=NULL, opts=NULL, win=NULL, snap="near", vsi=FALSE, raw=FALSE, noflip=FALSE) {
f <- .fullFilename(x, vsi=vsi)
if (length(f) == 0) {
error("rast", "filename is empty. Provide a valid filename")
}
if ((length(f) == 1) && grepl("\\.rds$", tolower(f[1]))) {
r <- unwrap(readRDS(x))
if (!inherits(r, "SpatRaster")) {
error("rast", "the rds file does not store a SpatRaster")
}
return(r)
}
r <- methods::new("SpatRaster")
#subds <- subds[1]
if (is.null(opts)) opts <- ""[0]
if (raw) opts <- c(opts, "so=false")
if (is.null(drivers)) drivers <- ""[0]
if (length(subds) == 0) subds = 0
if (is.character(subds)) {
#r@pntr <- SpatRaster$new(f, -1, subds, FALSE, 0[])
r@pntr <- SpatRaster$new(f, -1, subds, FALSE, drivers, opts, 0[], noflip)
} else {
r@pntr <- SpatRaster$new(f, subds-1, "", FALSE, drivers, opts, 0[], noflip)
}
r <- messages(r, "rast")
if (r@pntr$getMessage() == "ncdf extent") {
# could have used opts="IGNORE_XY_AXIS_NAME_CHECKS=YES"
test <- try(r <- .ncdf_extent(r, f), silent=TRUE)
if (inherits(test, "try-error")) {
warn("rast", "GDAL did not find an extent. Cells not equally spaced?")
}
}
r <- messages(r, "rast")
if (crs(r) == "") {
if (is.lonlat(r, perhaps=TRUE, warn=FALSE)) {
if (!isTRUE(all(as.vector(ext(r)) == c(0,ncol(r),0,nrow(r))))) {
crs(r) <- "OGC:CRS84"
}
}
}
if (!is.null(lyrs)) {
r <- r[[lyrs]]
}
if (!is.null(win)) {
e <- ext(win)
e <- align(e, r, snap=snap)
window(r) <- e
}
r
}
)
multi <- function(x, subds=0, xyz=3:1, drivers=NULL, opts=NULL) {
noflip <- FALSE
x <- trimws(x)
x <- x[x!=""]
if (length(x) == 0) {
error("rast,character", "provide a valid filename")
}
r <- methods::new("SpatRaster")
f <- .fullFilename(x)
if (is.null(opts)) opts <- ""[0]
if (is.null(drivers)) drivers <- ""[0]
if (length(subds) == 0) subds = 1
subds <- subds[1]
if (is.character(subds)) {
r@pntr <- SpatRaster$new(f, -1, subds, TRUE, drivers, opts, xyz-1, isTRUE(noflip[1]))
} else {
r@pntr <- SpatRaster$new(f, subds-1, ""[0], TRUE, drivers, opts, xyz-1, isTRUE(noflip[1]))
}
if (r@pntr$getMessage() == "ncdf extent") {
test <- try(r <- .ncdf_extent(r), silent=TRUE)
if (inherits(test, "try-error")) {
warn("rast", "GDAL did not find an extent. Cells not equally spaced?")
}
}
r <- messages(r, "rast")
if (crs(r) == "") {
if (is.lonlat(r, perhaps=TRUE, warn=FALSE)) {
crs(r) <- "OGC:CRS84"
}
}
r
}
setMethod("rast", signature(x="SpatRaster"),
function(x, nlyrs=nlyr(x), names, vals, keeptime=TRUE, keepunits=FALSE, props=FALSE, tags=FALSE) {
if (inherits(nlyrs, "SpatRaster")) {
error("rast", "use 'c()' to combine SpatRasters")
}
x@pntr <- x@pntr$geometry(nlyrs, props, keeptime, keepunits, tags)
x <- messages(x, "rast")
if (!missing(names)) {
if (length(names) == nlyr(x)) names(x) <- names
}
if (!missing(vals)) {
values(x) <- vals
}
x
}
)
setMethod("rast", signature(x="SpatRasterDataset"),
function(x) {
if (length(x) == 0) {
error("rast", "empty SpatRasterDataset")
} else if (length(x) == 1) {
x[1]
} else {
r <- methods::new("SpatRaster")
r@pntr <- x@pntr$collapse()
nms <- names(x)
if (any(nms != "")) {
names(r) <- paste(rep(nms, nlyr(x)), names(r), sep="_")
}
r
}
}
)
setMethod("rast", signature(x="array"),
function(x, crs="", extent=NULL) {
dims <- dim(x)
if (length(dims) < 3) {
error("rast,array", "cannot handle an array with less than 3 dimensions")
}
if (length(dims) > 3) {
if (length(dims) == 4) {
if (dims[4] == 1) {
x <- x[,,,1]
} else {
error("rast,array", "rast cannot handle an array with 4 dimensions (try 'sds')")
}
} else {
error("rast,array", "cannot handle an array with more than 3 dimensions")
}
}
r <- methods::new("SpatRaster")
if (!is.null(extent)) {
e <- as.vector(extent)
} else {
e <- c(0, dims[2], 0, dims[1])
}
crs <- character_crs(crs, "rast")
r@pntr <- SpatRaster$new(dims, e, crs)
values(r) <- x
messages(r, "rast")
}
)
setMethod("rast", signature(x="ANY"),
function(x, ...) {
if (inherits(x, "sf")) {
out <- rast(ext(x), ...)
if (is.null(list(...)$crs)) {
sfi <- attr(x, "sf_column")
crs(out, warn=FALSE) <- attr(x[[sfi]], "crs")$wkt
}
} else {
out <- methods::as(x, "SpatRaster")
}
#g <- gc()
out
}
)
.rastFromXYZ <- function(xyz, digits=6, crs="", extent=NULL) {
ln <- colnames(xyz)
## xyz might not have colnames, or might have "" names
if (is.null(ln)) ln <- rep("", ncol(xyz))
if (any(nchar(ln) < 1)) ln <- make.names(ln)
if (inherits(xyz, "data.frame")) {
xyz <- as.matrix(xyz)
xyz <- matrix(as.numeric(xyz), ncol=ncol(xyz), nrow=nrow(xyz))
}
x <- sort(unique(xyz[,1]))
# x <- sort(unique(round(xyz[,1], digits+2)))
if (length(x) == 1) {
error("rast", "cannot create a raster geometry from a single x coordinate")
}
dx <- x[-1] - x[-length(x)]
rx <- min(dx)
for (i in 1:5) {
rx <- rx / i
q <- sum(round(dx / rx, digits=digits) %% 1)
if ( q == 0 ) {
break
}
}
if ( q > 0 ) {
error("raster,matrix(xyz)", "x cell sizes are not regular")
}
y <- sort(unique(xyz[,2]))
# y <- sort(unique(round(xyz[,2], digits+2)))
if (length(y) == 1) {
error("rast", "cannot create a raster geometry from a single y coordinate")
}
dy <- y[-1] - y[-length(y)]
ry <- min(dy)
for (i in 1:5) {
ry <- ry / i
q <- sum(round(dy / ry, digits=digits) %% 1)
if ( q == 0 ) {
break
}
}
if ( q > 0 ) {
error("raster,matrix(xyz)", "y cell sizes are not regular")
}
minx <- min(x) - 0.5 * rx
maxx <- max(x) + 0.5 * rx
miny <- min(y) - 0.5 * ry
maxy <- max(y) + 0.5 * ry
d <- dim(xyz)
r <- rast(xmin=minx, xmax=maxx, ymin=miny, ymax=maxy, crs=crs, nlyrs=d[2]-2)
res(r) <- c(rx, ry)
ext(r) <- round(ext(r), digits+2)
cells <- cellFromXY(r, xyz[,1:2])
if (d[2] > 2) {
names(r) <- ln[-c(1:2)]
v <- try( matrix(NA, nrow=ncell(r), ncol= nlyr(r)) )
if (inherits(v, "try-error")) {
error(paste("cannot make matrix with ", ncell(r), " rows"))
}
v[cells, ] <- xyz[, -c(1:2)]
values(r) <- v
}
if (!is.null(extent)) {
r <- extend(r, extent)
r <- crop(r, extent)
}
return(r)
}
.rastFromXYLZ <- function(x, digits=6, crs="", extent=NULL) {
if (ncol(x) != 4) {
error("rast", "a 'xylz' structure must have 4 columns")
}
nms <- names(x)
names(x)[1:3] <- c("x", "y", "l")
x <- as.data.frame(x) # so that this also works for tibble #1582
w <- stats::reshape(x, timevar="l", idvar=c("x", "y"), direction="wide")
w <- rast(w, type="xyz", digits=digits, crs=crs, extent=extent)
names(w) <- gsub(paste0(nms[4], "."), "", names(w))
if (inherits(x[,3], "Date") || inherits(x[,3], "POSIXlt") || inherits(x[,3], "POSIXct")) {
time(w) <- unique(x[,3])
names(w) <- paste0(nms[4], ".", 1:nlyr(w))
} else if (inherits(x[,3], "numeric")) {
u <- unique(x[,3])
if (all(u == trunc(u))) {
su <- sort(u)
if ((su[1] == 1) && (su[length(su)] == length(su))) {
if (!all(su == u)) {
w <- w[[order(u)]]
}
}
}
}
w
}
setMethod("rast", signature(x="matrix"),
function(x, type="", crs="", digits=6, extent=NULL) {
stopifnot(prod(dim(x)) > 0)
if (type == "xyz") {
r <- .rastFromXYZ(x, crs=crs, digits=digits, extent=extent)
} else if (type == "xylz") {
r <- .rastFromXYLZ(x, crs=crs, digits=digits, extent=extent)
} else if (type != "") {
error("rast", 'argument type should be one of "", "xyz", or "xylz"')
} else {
if (is.null(extent)) {
r <- rast(nrows=nrow(x), ncols=ncol(x), extent=ext(c(0, ncol(x), 0, nrow(x))), crs=crs)
} else {
r <- rast(nrows=nrow(x), ncols=ncol(x), crs=crs, extent=extent)
}
values(r) <- as.vector(t(x))
}
messages(r, "rast")
}
)
setMethod("rast", signature(x="data.frame"),
function(x, type="xyz", crs="", digits=6, extent=NULL) {
if (type == "xyz") {
.rastFromXYZ(x, crs=crs, digits=digits, extent=extent)
} else if (type == "xylz") {
r <- .rastFromXYLZ(x, crs=crs, digits=digits, extent=extent)
} else if (type != "") {
error("rast", 'argument type should be one of "", "xyz", or "xylz"')
} else {
rast(as.matrix(x), type=type, crs=crs, digits=digits, extent=extent)
}
}
)
setMethod("rast", signature(x="stars"),
function(x) {
x <- from_stars(x)
if (inherits(x, "SpatRasterDataset")) {
rast(x)
} else {
x
}
}
)
setMethod("rast", signature(x="stars_proxy"),
function(x) {
x <- from_stars(x)
if (inherits(x, "SpatRasterDataset")) {
rast(x)
} else {
x
}
}
)
setMethod("NAflag<-", signature(x="SpatRaster"),
function(x, value) {
value <- as.numeric(value)
if (!(x@pntr$setNAflag(value))) {
error("NAflag<-", "cannot set this value")
}
x
}
)
setMethod("NAflag", signature(x="SpatRaster"),
function(x) {
x@pntr$getNAflag()
}
)
terra/R/connect.R 0000644 0001762 0000144 00000002742 14536376240 013363 0 ustar ligges users
get_groups <- function(x, y) {
j <- 1
outx <- outy <- list()
for (i in 1:length(x)) {
if (is.na(x[i])) next
gx <- stats::na.omit(x[x[i] == x] )
gy <- y[x %in% gx]
nx <- ny <- 0
while(TRUE) {
if (nx == length(gx)) break
ny <- length(gy)
nx <- length(gx)
if ((ny == length(y) || (nx == length(x)))) break
ux <- unique( x[y %in% gy] )
gy <- y[x %in% ux]
gx <- x[y %in% gy]
}
x[x %in% gx] <- NA
y[y %in% gy] <- NA
outx[[j]] <- gx
outy[[j]] <- gy
j <- j + 1
}
list(outx, outy)
}
connect_dateline <- function(x) {
east <- west <- c()
for (i in 1:nrow(x)) {
e <- ext(x[i,])
if (xmin(e) <= -180) {
west <- c(west, i)
} else if (xmax(e) >= 180) {
east <- c(east, i)
}
}
if ((length(east) == 0) || (length(west) == 0)) {
return(x)
}
xx <- shift(x[west,], 360, 0)
yy <- x[east, ]
#zz <- x[-c(east, west), ]
px <- py <- c()
hasDF <- ncol(x) > 0
for (i in 1:nrow(xx)) {
for (j in 1:nrow(yy)) {
if (hasDF) {
if (all(as.data.frame(xx[i,]) != as.data.frame(yy[j,]))) {
next
}
}
if (is.related(xx[i,], yy[j,], "touches")) {
px <- c(px, i)
py <- c(py, j)
}
}
}
if ((length(px) == 0)) {
return(x)
}
px <- west[px]
py <- east[py]
groups <- get_groups(px, py)
xg <- groups[[1]]
yg <- groups[[2]]
vvv <- list()
for (i in 1:length(xg)) {
vvv[[i]] <- aggregate(x[unique(c(xg[[i]], yg[[i]])), ], dissolve=TRUE)
}
out <- x[-(unique(unlist(groups))), ]
out <- c(vvv, out)
do.call(rbind, out)
}
terra/R/plot_axes.R 0000644 0001762 0000144 00000007304 14624312676 013730 0 ustar ligges users
.plot.axes <- function(x) {
if (is.null(x$axs$cex.axis)) {
x$axs$cex.axis = 1
}
x$axs$cex.axis <- x$axs$cex.axis * 0.7
if (is.null(x$axs$mgp)) {
x$axs$mgp = c(2, .25, 0)
}
if (is.null(x$axs$tcl)) {
x$axs$tcl <- -0.25
}
if ((!x$clip) & x$draw_grid) {
x$axs$tck <- 1
x$axs$mgp <- c(2, .15, 0)
}
xlab <- ylab <- NULL
if (!is.null(x$axs$labels)) {
xlab <- ylab <- x$axs$labels
x$axs$labels <- NULL
}
if (!is.null(x$axs$xlabs)) {
xlab <- x$axs$xlabs
x$axs$xlabs <- NULL
}
if (!is.null(x$axs$ylabs)) {
ylab <- x$axs$ylabs
x$axs$ylabs <- NULL
}
xat <- yat <- NULL
if (!is.null(x$axs$at)) {
xat <- yat <- x$axs$at
}
if (!is.null(x$axs$xat)) {
xat <- x$axs$xat
x$axs$xat <- NULL
}
if (!is.null(x$axs$yat)) {
yat <- x$axs$yat
x$axs$yat <- NULL
}
sides <- unique(x$axs$side)
if (!is.null(sides)) sides <- round(sides)
sides <- sides[sides > 0 & sides < 5]
if (is.null(sides)) {
x$axs$side <- sides <- 1:2
}
ticks <- x$axs$tick
if (is.null(ticks)) {
x$axs$tick <- ticks <- sides
}
labs <- x$axs$lab
if (is.null(labs)) {
x$axs$lab <- labs <- sides
}
if (x$clip) {
usr <- x$lim
} else {
usr <- graphics::par("usr")
}
y <- x$axs
retro <- isTRUE(y$retro)
if (retro && (!x$lonlat)) {
warn("plot", "'retro' labels can only be used with lonlat data")
retro <- FALSE
}
y$retro <- y$lab <- y$tick <- NULL
y$line <- NA
y$outer <- FALSE
y$line.lab <- NULL
if (is.null(y$col)) y$col <- "black"
if (x$clip) {
lnpts <- crds(as.points(ext(x$lim)))
lnpts <- rbind(lnpts[4,], lnpts)
} else {
lnpts <- crds(as.points(ext(usr)))
lnpts <- rbind(lnpts[4,], lnpts)
}
for (s in 1:4) {
y$side <- s
y$labels <- NULL
if (s %in% c(1,3)) {
ur <- usr[2] - usr[1]
edg <- c(usr[1]-10*ur, usr[2]+10*ur)
if (is.null(xat)) {
axt <- graphics::axTicks(s)
y$at <- axt[axt >= usr[1] & axt <= usr[2]]
} else {
y$at <- xat
}
if (is.null(xlab)) {
y$labels <- if (retro) retro_labels(y$at, lat=FALSE) else y$at
} else {
y$labels <- xlab
}
y$pos <- ifelse(s==1, usr[3], usr[4])
if (x$clip && x$draw_grid && s == 1) {
clp <- get.clip()
if (!is.null(clp)) {
for (i in seq_along(y$at)) {
lines(rbind(c(y$at[i], clp[3]), c(y$at[i], clp[4])), col=y$col)
}
}
}
} else {
ur <- usr[4] - usr[3]
edg <- c(usr[3]-10*ur, usr[4]+10*ur)
if (is.null(yat)) {
axt <- graphics::axTicks(s)
y$at <- axt[axt >= usr[3] & axt <= usr[4]]
} else {
y$at <- yat
}
if (is.null(ylab)) {
y$labels <- if (retro) retro_labels(y$at, lat=TRUE) else y$at
} else {
y$labels <- ylab
}
y$pos <- ifelse(s==2, usr[1], usr[2])
if (x$clip && x$draw_grid && s == 2) {
clp <- get.clip()
if (!is.null(clp)) {
for (i in seq_along(y$at)) {
lines(rbind(c(clp[1], y$at[i]), c(clp[2], y$at[i])), col=y$col)
}
}
}
}
z <- y
z$lwd <- 0
if (s %in% labs) {
z$lwd.ticks <- 0
do.call(graphics::axis, z)
}
z$labels <- FALSE
if (s %in% ticks) {
z$lwd <- 0
z$lwd.ticks <- y$lwd.ticks
if (is.null(z$lwd.ticks)) z$lwd.ticks <- 1
do.call(graphics::axis, z)
}
if (s %in% sides) {
lin <- lnpts[s:(s+1), ]
if (is.null(y$lty)) {
lty <- 1
} else {
lty <- y$lty
}
lines(lin, y$lwd, lty=lty, col=y$col)
#d <- diff(edg) * 10
#z$at <- edg + c(-d, d)
#z$lwd.ticks <- 0
#z$lwd <- y$lwd
#do.call(graphics::axis, z)
}
}
if (x$xlab != "") {
posx <- usr[1] + diff(usr[1:2])/2
text(posx, usr[3], x$xlab, pos=1, offset=x$axs$line.lab, cex=x$axs$cex.lab, xpd=TRUE)
}
if (x$ylab != "") {
posy <- usr[3] + diff(usr[3:4])/2
text(usr[1], posy, x$ylab, pos=2, offset=x$axs$line.lab, srt=90, cex=x$axs$cex.lab, xpd=TRUE)
}
x
}
terra/R/geocolors.R 0000644 0001762 0000144 00000000604 14536376240 013721 0 ustar ligges users .geocolors <- function(name, ...) {
if (name == "aspect") {
#0% black, 50% white, 100% black
pal <- grDevices::colorRampPalette(c("black", "white", "black"), ...)
cols <- cbind(1:360, pal(360))
} else if (name == "aspectclr") {
pal <- grDevices::colorRampPalette(c("yellow", "green", "cyan", "red", "yellow"), ...)
cols <- cbind(1:360, pal(360))
cols[1,2] <- "#FFFFFF"
}
}
terra/R/xyRowColCell.R 0000644 0001762 0000144 00000013044 14751764240 014315 0 ustar ligges users # Author: Robert J. Hijmans
# Date : October 2017
# Version 1.0
# License GPL v3
point_on_border <- function(r, x, y, tolerance = sqrt(.Machine$double.eps)) {
v <- h <- (x >= xmin(r)) & (x <= xmax(r)) & (y >= ymin(r)) & (y <= ymax(r))
v[v] <- ((x[v] - xmin(r)) %% res(r)[1]) < tolerance
h[h] <- ((y[h] - ymin(r)) %% res(r)[2]) < tolerance
h | v
}
setMethod("yFromRow", signature(object="SpatRaster", row="numeric"),
function(object, row) {
object@pntr$yFromRow(row - 1)
}
)
setMethod("yFromRow", signature(object="SpatRaster", row="missing"),
function(object, row) {
row <- seq_len(object@pntr$nrow())
object@pntr$yFromRow(row - 1)
}
)
setMethod(xFromCol, signature(object="SpatRaster", col="numeric"),
function(object, col) {
object@pntr$xFromCol(col - 1)
}
)
setMethod(xFromCol, signature(object="SpatRaster", col="missing"),
function(object, col) {
col <- seq_len(object@pntr$ncol())
object@pntr$xFromCol(col - 1)
}
)
setMethod(colFromX, signature(object="SpatRaster", x="numeric"),
function(object, x) {
cols <- object@pntr$colFromX(x) + 1
cols[cols==0] <- NA
cols
}
)
setMethod(rowFromY, signature(object="SpatRaster", y="numeric"),
function(object, y) {
rows <- object@pntr$rowFromY(y) + 1
rows[rows==0] <- NA
rows
}
)
setMethod(cellFromXY, signature(object="SpatRaster", xy="matrix"),
function(object, xy) {
stopifnot(ncol(xy) == 2)
#.checkXYnames(colnames(xy))
object@pntr$cellFromXY(xy[,1], xy[,2], NA) + 1
}
)
setMethod(cellFromXY, signature(object="SpatRaster", xy="data.frame"),
function(object, xy) {
stopifnot(ncol(xy) == 2)
#.checkXYnames(colnames(xy))
object@pntr$cellFromXY(xy[,1], xy[,2], NA) + 1
}
)
setMethod(cellFromRowCol, signature(object="SpatRaster", row="numeric", col="numeric"),
function(object, row, col) {
object@pntr$cellFromRowCol(row-1, col-1) + 1
}
)
setMethod(cellFromRowColCombine, signature(object="SpatRaster", row="numeric", col="numeric"),
function(object, row, col) {
object@pntr$cellFromRowColCombine(row-1, col-1) + 1
}
)
setMethod(rowColCombine, signature(object="SpatRaster", row="numeric", col="numeric"),
function(object, row, col) {
cell <- object@pntr$cellFromRowColCombine(row-1, col-1)
rc <- object@pntr$rowColFromCell(cell)
rc <- do.call(cbind, rc)
rc[rc < 0] <- NA
rc+1
}
)
setMethod(xyFromCell, signature(object="SpatRaster", cell="numeric"),
function(object, cell) {
xy <- object@pntr$xyFromCell(cell-1)
xy <- do.call(cbind, xy)
colnames(xy) <- c("x", "y")
xy
}
)
setMethod(yFromCell, signature(object="SpatRaster", cell="numeric"),
function(object, cell) {
xyFromCell(object, cell)[,2]
}
)
setMethod(xFromCell, signature(object="SpatRaster", cell="numeric"),
function(object, cell) {
xyFromCell(object, cell)[,1]
}
)
setMethod(rowColFromCell, signature(object="SpatRaster", cell="numeric"),
function(object, cell) {
rc <- object@pntr$rowColFromCell(cell-1)
rc <- do.call(cbind, rc)
rc[rc < 0] <- NA
rc+1
}
)
setMethod(rowFromCell, signature(object="SpatRaster", cell="numeric"),
function(object, cell) {
rowColFromCell(object, cell)[,1]
}
)
setMethod(colFromCell, signature(object="SpatRaster", cell="numeric"),
function(object, cell) {
rowColFromCell(object, cell)[,2]
}
)
.rep_fun <- function(v, n, N, m) {
if (is.null(v)) {
v
} else if (n == 1) {
replicate(N, v, FALSE)
} else if (n == N) {
as.list(v)
} else if ((n == m) && all(v==(1:m))) {
NULL
} else {
error("rcl", "if one argument is a list, the others should be a list,\n or a vector of length 1, or have the length of the list argument")
}
}
setMethod(rcl, signature(x="SpatRaster"),
function(x, row=NULL, col=NULL, lyr=NULL) {
lr <- is.list(row)
lc <- is.list(col)
ll <- is.list(lyr)
ln <- sum(lr, lc, ll)
if (ln > 0) {
nr <- length(row)
nc <- length(col)
nl <- length(lyr)
N <- unique(c(nr, nc, nl)[c(lr, lc, ll)])
if (length(N) > 1) {
N <- max(N)
islst <- which(c(lr, lc, ll))
for (i in islst) {
if (i == 1) {
row <- rep_len(row, N)
} else if (i == 2) {
col <- rep_len(col, N)
} else {
lyr <- rep_len(lyr, N)
}
}
}
notlst <- which(!c(lr, lc, ll))
for (i in notlst) {
if (i == 1) {
row <- .rep_fun(row, nr, N, nrow(x))
} else if (i == 2) {
col <- .rep_fun(col, nc, N, ncol(x))
} else {
lyr <- .rep_fun(lyr, nl, N, nlyr(x))
}
}
out <- lapply(1:N, function(i) { rcl(x, row[[i]], col[[i]], lyr[[i]]) })
do.call(rbind, out)
} else {
hr <- !is.null(row)
hc <- !is.null(col)
hl <- !is.null(lyr)
n <- sum(hr, hc, hl)
if (hl) {
lyr[!c(lyr %in% 1:nlyr(x))] <- NA
}
if (n == 0) {
out <- rowColFromCell(x, 1:ncell(x))
out <- cbind(out[,1], out[,2], rep(1:nlyr(x), each=nrow(out)))
colnames(out) <- c("row", "col", "lyr")
return(out)
} else if (hr & hc & hl) {
out <- rowColCombine(x, row, col)
out <- cbind(out[,1], out[,2], rep(lyr, each=nrow(out)))
} else if (!hc) {
out <- rowColCombine(x, row, 1:ncol(x))
if (hl) {
out <- cbind(out[,1], out[,2], rep(lyr, each=nrow(out)))
} else {
out <- cbind(out[,1], out[,2], rep(1:nlyr(x), each=nrow(out)))
}
} else if (!hr) {
out <- rowColCombine(x, 1:nrow(x), col)
if (hl) {
out <- cbind(out[,1], out[,2], rep(lyr, each=nrow(out)))
} else {
out <- cbind(out[,1], out[,2], rep(1:nlyr(x), each=nrow(out)))
}
} else if (!hl) {
out <- rowColCombine(x, row, col)
out <- cbind(out[,1], out[,2], rep(1:nlyr(x), each=nrow(out)))
}
colnames(out) <- c("row", "col", "lyr")
out
}
}
)
terra/R/selectHigh.R 0000644 0001762 0000144 00000000340 14536376240 014001 0 ustar ligges users
setMethod("selectHighest", signature(x="SpatRaster"),
function(x, n, low=FALSE) {
x <- x[[1]]
n <- min(ncell(x), max(1, n))
i <- order(values(x, mat=FALSE), decreasing=!low)[1:n]
x <- rast(x)
x[i] <- 1
x
}
)
terra/R/match.R 0000644 0001762 0000144 00000002700 14726700274 013017 0 ustar ligges users # Author: Robert J. Hijmans
# License GPL v3
getCatIDs <- function(x, table, sender="%in%") {
if (!is.factor(x)) {
error(sender, "Can only match character values if x is categorical")
}
if (nlyr(x) != 1) {
error(sender, "matching with character values is only supported for single layer SpatRaster")
}
d <- cats(x)[[1]]
m <- stats::na.omit(match(table, d[,2]))
d[m,1]
}
setMethod("match", signature(x="SpatRaster"),
function(x, table, nomatch=NA, incomparables=NULL) {
table <- unique(table)
if (is.character(table)) {
table <- getCatIDs(x, table, sender="match")
if (length(table) == 0) {
return(as.logical(x*0))
}
}
app(x, function(i) match(i, table, nomatch, incomparables))
}
)
setMethod("%in%", signature(x="SpatRaster"),
function(x, table) {
table <- unique(table)
if (is.character(table)) {
table <- getCatIDs(x, table)
if (length(table) == 0) {
return(as.logical(x*0))
}
}
opt <- spatOptions("", FALSE, list())
x@pntr <- x@pntr$is_in(table, opt)
messages(x, "%in%")
}
)
#setMethod("%in%", signature(x="SpatRaster", table="ANY"),
# function(x, table) {
# out <- rast(x)
# readStart(x)
# on.exit(readStop(x))
# nc <- ncol(out)
# b <- writeStart(out, filename="", overwrite=FALSE, sources=sources(x), wopt=list())
# for (i in 1:b$n) {
# v <- readValues(x, b$row[i], b$nrows[i], 1, nc, TRUE)
# v <- v %in% table
# writeValues(out, v, b$row[i], b$nrows[i])
# }
# writeStop(out)
# }
#)
terra/R/inset.R 0000644 0001762 0000144 00000006315 14562663313 013053 0 ustar ligges users # Author: Robert J. Hijmans
# Date : December 2020
# Version 1.0
# License GPL v3
setMethod("inext", signature(x="SpatVector"),
function(x, e, y=NULL, gap=0) {
# the area used for scaling
gap <- rep_len(gap, 2)
e <- as.vector(e) + c(gap[1], -gap[1], gap[2], -gap[2])
stopifnot((e[2] > e[1]) && (e[4] > e[3]))
ex <- ext(x)
x <- shift(x, e[1] - ex[1], e[3] - ex[3])
ve <- ext(x)
fx <- (e[2] - e[1]) / (ve[2] - ve[1])
fy <- (e[4] - e[3]) / (ve[4] - ve[3])
if (!is.null(y)) {
y <- shift(y, e[1] - ex[1], e[3] - ex[3])
rescale(y, fx=fx, fy=fy, e[1], e[3])
} else {
rescale(x, fx=fx, fy=fy, e[1], e[3])
}
}
)
.inset <- function(x, e, loc="", scale=0.2, background="white", perimeter=TRUE, pper, box=NULL, pbox, add=TRUE, xpd=NA, offset=0.1, ...) {
usr <- unlist(get.clip()[1:4])
if (missing(e)) {
e <- ext(usr)
xe <- ext(x)
r <- diff(xe[1:2]) / diff(xe[3:4])
n <- scale * diff(e[1:2])
e[2] <- e[1] + n
e[3] <- e[4] - n / r
}
#offset <- 0.9
offset <- 1 - offset
offset <- max(0.1, min(1, offset))
scale <- offset * min(e / ext(x))
y <- rescale(x, scale)
ey <- ext(y)
xy <- c(mean(ey[1:2]), mean(ey[3:4]))
xybox <- c(mean(e[1:2]), mean(e[3:4]))
dx <- xybox[1] - xy[1]
dy <- xybox[2] - xy[2]
y <- shift(y, dx, dy)
if (!is.null(box)) {
ex <- ext(x)
box <- rescale(as.polygons(box), scale, x0=ex[1]+diff(ex[1:2])/2, y0=ex[3]+diff(ex[3:4])/2)
box <- shift(box, dx, dy)
}
if ((loc != "") && (loc != "topleft")) {
stopifnot(loc %in% c("bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", "right", "center"))
ex <- ext(x)
if (grepl("top", loc)) {
dy <- usr[4] - e[4]
} else if (grepl("bottom", loc)) {
dy <- usr[3] - e[3]
} else {
dy <- (usr[3] + diff(usr[3:4])/2) - (e[3] + diff(e[3:4])/2)
}
if (grepl("left", loc)) {
dx <- usr[1] - e[1]
} else if (grepl("right", loc)) {
dx <- usr[2] - e[2]
} else {
dx <- (usr[1] + diff(usr[1:2])/2) - (e[1] + diff(e[1:2])/2)
}
y <- shift(y, dx, dy)
e <- shift(e, dx, dy)
if (!is.null(box)) {
box <- shift(box, dx, dy)
}
}
if (add) {
if (!is.na(background)) {
polys(as.polygons(e), col=background, lty=0, xpd=xpd)
}
plot(y, ..., axes=FALSE, legend=FALSE, add=TRUE, xpd=xpd)
if (isTRUE(perimeter)) {
if (missing(pper) || !is.list(pper)) {
pper <- list()
}
#pper$x <- ext(y)
pper$x <- e
pper$xpd <- xpd
do.call(lines, pper)
#lines(e, col=perimeter)
}
if (!is.null(box)) {
if (missing(pbox) || !is.list(pbox)) {
pbox <- list()
}
pbox$x <- box
pbox$xpd <- xpd
do.call(lines, pbox)
}
}
invisible(y)
}
setMethod("inset", signature(x="SpatVector"),
function(x, e, loc="", scale=0.2, background="white", perimeter=TRUE, box=NULL, pper, pbox, offset=0.1, add=TRUE, ...) {
.inset(x, e, loc=loc, scale=scale, background=background, perimeter=perimeter, pper=pper, box=box, pbox=pbox, offset=offset, add=add, ...)
}
)
setMethod("inset", signature(x="SpatRaster"),
function(x, e, loc="", scale=0.2, background="white", perimeter=TRUE, box=NULL, pper, pbox, offset=0.1, add=TRUE, ...) {
.inset(x, e, loc=loc, scale=scale, background=background, perimeter=perimeter, pper=pper, box=box, pbox=pbox, offset=offset, add=add, ...)
}
)
terra/R/generics.R 0000644 0001762 0000144 00000075774 14754707627 013561 0 ustar ligges users # Author: Robert J. Hijmans
# Date : October 2018
# Version 1.0
# License GPL v3
setMethod("is.rotated", signature(x="SpatRaster"),
function(x) {
x@pntr$is_rotated()
}
)
setMethod("is.flipped", signature(x="SpatRaster"),
function(x) {
x@pntr$is_flipped()
}
)
setMethod("rangeFill", signature(x="SpatRaster"),
function(x, limit, circular=FALSE, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$fill_range(limit, circular, opt)
messages(x, "rangeFill")
}
)
setMethod("weighted.mean", signature(x="SpatRaster", w="numeric"),
function(x, w, na.rm=FALSE, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$wmean_vect(w, na.rm, opt)
messages(x, "weighted.mean")
}
)
setMethod("weighted.mean", signature(x="SpatRaster", w="SpatRaster"),
function(x, w, na.rm=FALSE, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <-x@pntr$wmean_rast(w@pntr, na.rm, opt)
messages(x, "weighted.mean")
}
)
setMethod("patches", signature(x="SpatRaster"),
function(x, directions=4, values=FALSE, zeroAsNA=FALSE, allowGaps=TRUE, filename="", ...) {
if (values) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$patches2(directions, opt)
return(messages(x, "patches"))
}
if (allowGaps) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$patches(directions[1], zeroAsNA[1], opt)
messages(x, "patches")
} else {
opt <- spatOptions()
x@pntr <- x@pntr$patches(directions[1], zeroAsNA[1], opt)
x <- messages(x, "patches")
f <- freq(x)
fr <- cbind(f[,2], 1:nrow(f))
fr <- fr[fr[,1] != fr[,2], ,drop=FALSE]
if (nrow(fr) > 0) {
x <- classify(x, fr, filename=filename, ...)
} else if (filename != "") {
x <- writeRaster(x, filename=filename, ...)
}
x
}
}
)
setMethod("origin", signature(x="SpatRaster"),
function(x) {
x@pntr$origin
}
)
setMethod("origin<-", signature("SpatRaster"),
function(x, value) {
value <- rep(value, length.out=2)
dif <- value - origin(x)
res <- res(x)
dif[1] <- dif[1] %% res[1]
dif[2] <- dif[2] %% res[2]
for (i in 1:2) {
if (dif[i] < 0) {
if ((dif[i] + res[i]) < abs(dif[i])) {
dif[i] <- dif[i] + res[i]
}
} else {
if (abs(dif[i] - res[i]) < dif[i]) {
dif[i] <- dif[i] - res[i]
}
}
}
e <- as.vector(ext(x))
e["xmin"] <- e["xmin"] + dif[1]
e["xmax"] <- e["xmax"] + dif[1]
e["ymin"] <- e["ymin"] + dif[2]
e["ymax"] <- e["ymax"] + dif[2]
ext(x) <- e
return(x)
}
)
setMethod("align", signature(x="SpatExtent", y="SpatRaster"),
function(x, y, snap="near") {
x@pntr <- y@pntr$align(x@pntr, tolower(snap))
#messages(x, "align")
x
}
)
setMethod("align", signature(x="SpatExtent", y="numeric"),
function(x, y) {
x@pntr <- x@pntr$align(y, "")
x
}
)
setMethod("intersect", signature(x="SpatRaster", y="SpatRaster"),
function(x, y) {
opt <- spatOptions()
x@pntr <- x@pntr$intersect(y@pntr, opt)
messages(x)
}
)
setMethod("cellSize", signature(x="SpatRaster"),
function(x, mask=FALSE, lyrs=FALSE, unit="m", transform=TRUE, rcx=100, filename="", ...) {
opt <- spatOptions(filename, ...)
if (!lyrs) x <- x[[1]]
x@pntr <- x@pntr$rst_area(mask, unit, transform, rcx, opt)
messages(x, "cellSize")
}
)
setMethod("surfArea", signature(x="SpatRaster"),
function(x, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$surface_area(opt)
messages(x, "surfArea")
}
)
setMethod("atan2", signature(y="SpatRaster", x="SpatRaster"),
function(y, x) {
opt <- spatOptions(filename="", overwrite=TRUE)
y@pntr <- y@pntr$atan2(x@pntr, opt)
messages(y, "atan2")
}
)
setMethod("atan_2", signature(y="SpatRaster", x="SpatRaster"),
function(y, x, filename="", ...) {
opt <- spatOptions(filename=filename, ...)
y@pntr <- y@pntr$atan2(x@pntr, opt)
messages(y, "atan_2")
}
)
setMethod("boundaries", signature(x="SpatRaster"),
function(x, classes=FALSE, inner=TRUE, directions=8, falseval=0, filename="", ...) {
opt <- spatOptions(filename, ...)
type <- ifelse(inner[1], "inner", "outer")
x@pntr <- x@pntr$boundaries(classes[1], type, directions[1], falseval[1], opt)
messages(x, "boundaries")
}
)
.collapseSources <- function(x) {
x@pntr <- x@pntr$collapse_sources()
messages(x, "tighten")
}
setMethod("deepcopy", signature("SpatRaster"),
function(x) {
x@pntr <- x@pntr$deepcopy()
x
}
)
setMethod("split", signature(x="SpatRaster"),
function(x, f) {
stopifnot(length(f) == nlyr(x))
stopifnot(!any(is.na(f)))
u <- unique(f)
lapply(u, function(i) x[[f==i]])
}
)
setMethod("add<-", signature("SpatRaster", "SpatRaster"),
function(x, value) {
if (x@pntr$same(value@pntr)) {
x@pntr <- x@pntr$deepcopy()
}
opt <- spatOptions()
x@pntr$addSource(value@pntr, FALSE, opt)
messages(x, "add")
}
)
setMethod("tighten", signature("SpatRaster"),
function(x) {
x@pntr <- x@pntr$collapse_sources()
messages(x, "tighten")
}
)
setMethod("tighten", signature("SpatRasterDataset"),
function(x) {
y <- new("SpatRaster")
y@pntr <- x@pntr$collapse()
messages(y, "tighten")
}
)
#setMethod("c", signature(x="SpatRaster"),
# function(x, ...) {
# s <- sds(list(x, ...))
# x@pntr <- s@pntr$collapse()
# x <- messages(x, "c")
# try( x@pntr <- x@pntr$collapse_sources() )
# messages(x, "c")
# }
#)
#cbind.SpatVector <- function(x, y, ...) {
# if (inherits(y, "SpatVector")) {
# y <- y@pntr$df
# } else {
# stopifnot(inherits(y, "data.frame"))
# y <- terra:::.makeSpatDF(y)
# }
# x@pntr <- x@pntr$cbind(y)
# messages(x, "cbind")
#}
cbind.SpatVector <- function(x, y, ...) {
dots <- list(y, ...)
for (y in dots) {
if (inherits(y, "SpatVector")) {
y <- y@pntr$df
} else {
# stopifnot(inherits(y, "data.frame"))
y <- as.data.frame(y)
y <- .makeSpatDF(y)
}
x@pntr <- x@pntr$cbind(y)
x <- messages(x, "cbind")
}
x
}
rbind.SpatVector <- function(x, y, ...) {
skipped <- FALSE
if (missing(y) || is.null(y)) return(x)
stopifnot(inherits(y, "SpatVector"))
s <- svc(x, y, ...)
x@pntr <- s@pntr$append()
messages(x, "rbind")
# dots <- list(...)
# if (is.null(dots)) {
# x@pntr <- x@pntr$rbind(y@pntr, FALSE)
# } else {
#if (!is.null(dots)) {
# for (y in dots) {
# stopifnot(inherits(y, "SpatVector"))
# x@pntr <- x@pntr$rbind(y@pntr, FALSE)
# x <- messages(x, "rbind")
# }
#}
#x
}
# this way names of named arguments are used
setMethod("c", signature(x="SpatRaster"),
function(x, ..., warn=TRUE) {
if (missing(x)) {
rast(list(...), warn=warn)
} else {
rast(list(x, ...), warn=warn)
}
}
)
setMethod("rep", signature(x="SpatRaster"),
function(x, ...) {
i <- rep(1:nlyr(x), ...)
x[[i]]
}
)
setMethod("clamp", signature(x="SpatRaster"),
function(x, lower=-Inf, upper=Inf, values=TRUE, filename="", ...) {
opt <- spatOptions(filename, ...)
rlow <- inherits(lower, "SpatRaster")
rupp <- inherits(upper, "SpatRaster")
r <- rast()
if (rlow & rupp) {
x@pntr <- x@pntr$clamp_raster(lower@pntr, upper@pntr, NA, NA, values[1], opt)
} else if (rlow) {
if (any(is.na(upper))) error("clamp", "upper limit cannot be NA")
x@pntr <- x@pntr$clamp_raster(lower@pntr, r@pntr, NA, upper, values[1], opt)
} else if (rupp) {
if (any(is.na(lower))) error("clamp", "lower limit cannot be NA")
x@pntr <- x@pntr$clamp_raster(r@pntr, upper@pntr, lower, NA, values[1], opt)
} else {
if (any(is.na(lower))) error("clamp", "lower limit cannot be NA")
if (any(is.na(upper))) error("clamp", "upper limit cannot be NA")
x@pntr <- x@pntr$clamp_raster(r@pntr, r@pntr, lower, upper, values[1], opt)
#x@pntr <- x@pntr$clamp(lower, upper, values[1], opt)
}
messages(x, "clamp")
}
)
setMethod("clamp_ts", signature(x="SpatRaster"),
function(x, min=FALSE, max=TRUE, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$clamp_ts(min, max, opt)
messages(x, "clamp_ts")
}
)
setMethod("clamp", signature(x="numeric"),
function(x, lower=-Inf, upper=Inf, values=TRUE, ...) {
stopifnot(lower <= upper)
if (values) {
x[x < lower] <- lower
x[x > upper] <- upper
} else {
x[x < lower] <- NA
x[x > upper] <- NA
}
x
}
)
setMethod("classify", signature(x="SpatRaster"),
function(x, rcl, include.lowest=FALSE, right=TRUE, others=NULL, brackets=TRUE, filename="", ...) {
bylayer = FALSE
if (is.data.frame(rcl)) {
rcl <- as.matrix(rcl)
}
right <- ifelse(is.na(right), 2, ifelse(isTRUE(right), 1, 0))
include.lowest <- as.logical(include.lowest[1])
opt <- spatOptions(filename, ...)
if (is.null(others)) {
others <- FALSE
othersValue <- 0
} else {
othersValue <- others[1]
others <- TRUE
}
keepcats <- FALSE
x@pntr <- x@pntr$classify(as.vector(rcl), NCOL(rcl), right, include.lowest, others, othersValue, bylayer[1], brackets[1], keepcats, opt)
messages(x, "classify")
}
)
setMethod("subst", signature(x="SpatRaster"),
function(x, from, to, others=NULL, raw=FALSE, filename="", ...) {
opt <- spatOptions(filename, ...)
if (inherits(from, "data.frame")) {
from <- as.matrix(from)
}
if (inherits(to, "data.frame")) {
to <- as.matrix(to)
}
tom <- inherits(to, "matrix")
frm <- inherits(from, "matrix")
if (tom && frm) {
error("subst", "either 'to' or 'from' can be a matrix, not both")
}
if (NROW(from) < NROW(to)) {
error("subst", "from is shorter than to")
}
fromc <- inherits(from[1], "character")
toc <- inherits(to[1], "character")
if (raw && fromc) {
error("subst", "if 'raw=TRUE', 'from' cannot have character values")
}
keepcats <- FALSE
if (any(is.factor(x))) {
if (nlyr(x) > 1) {
error("subst", "you can only use 'subst' with categorical layers if x has a single layer")
}
if (inherits(to, "matrix")) {
if (ncol(to) > 1) {
warn("subst", "only the first column of 'to' is used with factors")
}
to <- as.vector(to[,1])
}
levs <- levels(x)[[1]]
if (!raw) {
from <- levs[,1][match(from, levs[,2])]
if (all(is.na(from))) {
warn("subst", "all 'from' values are missing, returning a copy of 'x'")
return(deepcopy(x))
}
}
i <- is.na(from)
if (any(i)) {
to <- rep_len(to, length(from))
from <- from[!i]
to <- to[!i]
}
if (!raw) {
toto <- levs[,1][match(to, levs[,2])]
if (any(is.na(toto))) { # add new levels
i <- which(is.na(toto))
m <- cbind(max(levs[,1]) + 1:length(i), to[i])
colnames(m) <- colnames(levs)
levs <- rbind(levs, m)
to <- levs[,1][match(to, levs[,2])]
levels(x) <- levs
} else {
to <- toto
}
}
keepcats <- TRUE
} else {
if (fromc) {
error("subst", "from has character values but x is not categorical")
}
if (!tom) {
if (toc) {
to <- as.factor(to)
levels(x) <- data.frame(ID=1:length(levels(to)), value=levels(to))
keepcats <- TRUE
} else if (is.factor(to)) {
levels(x) <- data.frame(ID=1:length(levels(to)), value=levels(to))
keepcats <- TRUE
}
}
}
if (is.null(others)) {
setothers <- FALSE
others <- NA
} else {
setothers <- TRUE
others <- others[1]
}
if (tom) {
nms <- colnames(to)
if (!is.null(nms)) opt$names = nms
x@pntr <- x@pntr$replaceValues(from, to, ncol(to), setothers, others, keepcats, opt)
} else if (frm) {
x@pntr <- x@pntr$replaceValues(as.vector(t(from)), to, -ncol(from), setothers, others, keepcats, opt)
} else {
x@pntr <- x@pntr$replaceValues(from, to, 0, setothers, others, keepcats, opt)
}
messages(x, "subst")
}
)
.getExt <- function(y, method="crop") {
if (!inherits(y, "SpatExtent")) {
e <- try(ext(y), silent=TRUE)
if (inherits(e, "try-error")) {
e <- try(ext(vect(y)), silent=TRUE)
if (inherits(e, "try-error")) {
error(method, "cannot get a SpatExtent from y")
}
}
y <- e
}
y
}
setMethod("crop", signature(x="SpatRaster", y="ANY"),
function(x, y, snap="near", mask=FALSE, touches=TRUE, extend=FALSE, filename="", ...) {
opt <- spatOptions(filename, ...)
if (mask) {
if (inherits(y, "SpatVector")) {
x@pntr <- x@pntr$crop_mask(y@pntr, snap[1], touches[1], extend[1], opt)
} else if (inherits(y, "sf")) {
y <- vect(y)
x@pntr <- x@pntr$crop_mask(y@pntr, snap[1], touches[1], extend[1], opt)
} else if (inherits(y, "SpatRaster")) {
mopt <- spatOptions(filename="", ...)
e <- ext(y)
x@pntr <- x@pntr$crop(e@pntr, snap[1], extend[1], mopt)
x <- messages(x, "crop")
if (compareGeom(x, y, lyrs=FALSE, crs=FALSE, warncrs=FALSE, ext=TRUE, rowcol=TRUE, res=FALSE, stopOnError=FALSE, messages=FALSE)) {
return(mask(x, y, filename=filename, ...))
} else {
warn("crop", "cannot mask with a raster that is not aligned to x")
# should check earlier if masking will be possible to avoid writing to disk twice.
if (filename != "") {
x <- writeRaster(x, filename, ...)
}
return(x)
}
} else {
y <- .getExt(y, method="crop")
warn("crop", paste("mask=TRUE is ignored for", class(y)[1], "objects"))
x@pntr <- x@pntr$crop(y@pntr, snap[1], extend[1], opt)
}
} else {
y <- .getExt(y, method="crop")
x@pntr <- x@pntr$crop(y@pntr, snap[1], extend[1], opt)
}
messages(x, "crop")
}
)
setMethod("crop", signature(x="SpatRasterDataset", y="ANY"),
function(x, y, snap="near", extend=FALSE) {
opt <- spatOptions()
y <- .getExt(y, method="crop")
x@pntr <- x@pntr$crop(y@pntr, snap[1], extend[1], opt)
messages(x, "crop")
}
)
setMethod("crop", signature(x="SpatRasterCollection", y="ANY"),
function(x, y, snap="near", extend=FALSE) {
y <- .getExt(y, method="crop")
opt <- spatOptions()
x@pntr <- x@pntr$crop(y@pntr, snap[1], extend[1], double(), opt)
messages(x, "crop")
}
)
setMethod("selectRange", signature(x="SpatRaster"),
function(x, y, z=1, repint=0, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$selRange(y@pntr, z, repint, opt)
messages(x, "selectRange")
}
)
setMethod("cover", signature(x="SpatRaster", y="SpatRaster"),
function(x, y, values=NA, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$cover(y@pntr, values, opt)
messages(x, "cover")
}
)
setMethod("cover", signature(x="SpatRaster", y="missing"),
function(x, y, values=NA, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$cover_self(values, opt)
messages(x, "cover")
}
)
setMethod("diff", signature(x="SpatRaster"),
function(x, lag=1, filename="", ...) {
n <- nlyr(x)
lag <- round(lag)
if ((lag < 1) | (lag >= n)) {
error("diff", "lag must be > 0 and < nlyr(x)")
}
y <- x[[-((n-lag+1):n)]]
x <- x[[-(1:lag)]]
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$arith_rast(y@pntr, "-", FALSE, opt)
messages(x, "diff")
}
)
setMethod("disagg", signature(x="SpatRaster"),
function(x, fact, method="near", filename="", ...) {
method <- match.arg(tolower(method), c("near", "bilinear"))
if (method == "bilinear") {
y <- disagg(rast(x), fact)
r <- resample(x, y, "bilinear", filename=filename, ...)
return(r)
}
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$disaggregate(fact, opt)
messages(x, "disagg")
}
)
setMethod("flip", signature(x="SpatRaster"),
function(x, direction="vertical", filename="", ...) {
d <- match.arg(direction, c("vertical", "horizontal"))
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$flip(d == "vertical", opt)
messages(x, "flip")
}
)
setMethod("mask", signature(x="SpatRaster", mask="SpatRaster"),
function(x, mask, inverse=FALSE, maskvalues=NA, updatevalue=NA, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$mask_raster(mask@pntr, inverse[1], maskvalues, updatevalue[1], opt)
messages(x, "mask")
}
)
setMethod("mask", signature(x="SpatRaster", mask="SpatVector"),
function(x, mask, inverse=FALSE, updatevalue=NA, touches=TRUE, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$mask_vector(mask@pntr, inverse[1], updatevalue[1], touches[1], opt)
messages(x, "mask")
}
)
setMethod("mask", signature(x="SpatRaster", mask="SpatExtent"),
function(x, mask, inverse=FALSE, updatevalue=NA, touches=TRUE, filename="", ...) {
opt <- spatOptions(filename, ...)
mask <- vect(mask, crs=crs(x))
x@pntr <- x@pntr$mask_vector(mask@pntr, inverse[1], updatevalue[1], touches[1], opt)
messages(x, "mask")
}
)
setMethod("mask", signature(x="SpatRaster", mask="sf"),
function(x, mask, inverse=FALSE, updatevalue=NA, touches=TRUE, filename="", ...) {
mask <- vect(mask)
mask(x, mask, inverse=inverse, updatevalue=updatevalue, touches=touches, filename=filename, ...)
}
)
setMethod("project", signature(x="SpatRaster"),
function(x, y, method, mask=FALSE, align_only=FALSE, res=NULL, origin=NULL, threads=FALSE, filename="", ..., use_gdal=TRUE, by_util = FALSE) {
if (missing(method)) {
if (is.factor(x)[1] || isTRUE(x@pntr$rgb)) {
method <- "near"
} else {
method <- "bilinear"
}
} else {
method <- match.arg(tolower(method[1]), c("near", "bilinear", "cubic", "cubicspline", "lanczos", "average", "sum", "mode", "min", "q1", "median", "q3", "max", "rms"))
}
opt <- spatOptions(filename, threads=threads, ...)
if (inherits(y, "SpatRaster")) {
if (use_gdal) {
if (by_util) {
x@pntr <- x@pntr$warp_by_util(y@pntr, "", method, mask[1], align_only[1], FALSE, opt)
} else {
x@pntr <- x@pntr$warp(y@pntr, "", method, mask[1], align_only[1], FALSE, opt)
}
} else {
if (align_only) {
y <- project(rast(x), y, align_only=TRUE)
}
x@pntr <- x@pntr$resample(y@pntr, method, mask[1], TRUE, opt)
}
} else {
if (!is.character(y)) {
warn("project,SpatRaster", "argument y (the crs) should be a character value")
y <- as.character(crs(y))
}
if (!is.null(res) || !is.null(origin)) {
tmp <- project(rast(x), y)
if (!is.null(res)) res(tmp) <- res
if (!is.null(origin)) origin(tmp) <- origin
return(project(x, tmp, method=method, mask=mask, align_only=align_only, filename=filename, use_gdal=use_gdal, by_util=by_util, ...))
}
if (use_gdal) {
if (by_util) {
x@pntr <- x@pntr$warp_by_util(SpatRaster$new(), y, method, mask, FALSE, FALSE, opt)
} else {
x@pntr <- x@pntr$warp(SpatRaster$new(), y, method, mask, FALSE, FALSE, opt)
}
} else {
y <- project(rast(x), y)
x@pntr <- x@pntr$resample(y@pntr, method, mask[1], TRUE, opt)
}
}
messages(x, "project")
}
)
setMethod("project", signature(x="SpatVector"),
function(x, y, partial=FALSE) {
if (!is.character(y)) {
y <- as.character(crs(y))
}
x@pntr <- x@pntr$project(y, partial)
messages(x, "project")
}
)
setMethod("project", signature(x="SpatVectorCollection"),
function(x, y, partial=FALSE) {
x <- lapply(x, function(v) project(v, y, partial=partial))
svc(x)
}
)
setMethod("project", signature(x="SpatExtent"),
function(x, from, to) {
if (missing(from)) error("project", "'from' cannot be missing")
if (missing(to)) error("project", "'to' cannot be missing")
x <- as.polygons(x, crs=from)
x <- densify(x, 10000)
ext(project(x, to))
}
)
setMethod("project", signature(x="matrix"),
function(x, from, to) {
if (ncol(x) != 2) {
error("project", "x must have two columns")
}
if (missing(from)) {
error("project", "'from' cannot be missing")
}
if (missing(to)) {
error("project", "'to' cannot be missing")
}
if (!is.character(from)) {
from <- as.character(crs(from))
}
if (!is.character(to)) {
to <- as.character(crs(to))
}
#v <- vect(x, type="line", crs=from)
#v@pntr <- v@pntr$project(to)
v <- vect()
xy <- v@pntr$project_xy(x[,1], x[,2], from, to)
messages(v, "project")
matrix(xy, ncol=2)
}
)
setMethod("quantile", signature(x="SpatRaster"),
function(x, probs=seq(0, 1, 0.25), na.rm=FALSE, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$quantile(probs, na.rm[1], opt)
messages(x, "quantile")
}
)
setMethod("quantile", signature(x="SpatVector"),
function(x, probs=seq(0, 1, 0.25), ...) {
x <- values(x)
cls <- sapply(x, class)
i <- cls != "character"
if (!any(i)) error("quantile", "no numeric variables")
x <- x[, i, drop=FALSE]
apply(x, 2, function(i) quantile(i, probs=probs, ...))
}
)
setMethod("rectify", signature(x="SpatRaster"),
function(x, method="bilinear", aoi=NULL, snap=TRUE, filename="", ...) {
opt <- spatOptions(filename, ...)
if (!is.null(aoi)) {
if (inherits(aoi, "SpatExtent")) {
aoi <- rast(aoi)
useaoi <- 1
} else if (inherits(aoi, "SpatRaster")) {
aoi <- rast(aoi)
useaoi <- 2
} else {
error("rectify", "ext must be a SpatExtent or SpatRaster")
}
} else {
aoi <- rast()
useaoi <- 0
}
snap <- as.logical(snap)
x@pntr <- x@pntr$rectify(method, aoi@pntr, useaoi, snap, opt)
messages(x, "rectify")
}
)
setMethod("resample", signature(x="SpatRaster", y="SpatRaster"),
function(x, y, method, threads=FALSE, by_util=FALSE, filename="", ...) {
if (missing(method)) {
if (is.factor(x)[1] || isTRUE(x@pntr$rgb)) {
method <- "near"
} else {
method <- "bilinear"
}
} else {
method <- match.arg(tolower(method[1]), c("near", "bilinear", "cubic", "cubicspline", "lanczos", "average", "sum", "mode", "min", "q1", "median", "q3", "max", "rms"))
}
xcrs = crs(x)
ycrs = crs(y)
if ((xcrs == "") && (ycrs != "")) {
crs(x) <- ycrs
}
if ((ycrs == "") && (xcrs != "")) {
crs(y) <- xcrs
}
opt <- spatOptions(filename, threads=threads, ...)
if (by_util) {
x@pntr <- x@pntr$warp_by_util(y@pntr, "", method, FALSE, FALSE, TRUE, opt)
} else {
x@pntr <- x@pntr$warp(y@pntr, "", method, FALSE, FALSE, TRUE, opt)
}
messages(x, "resample")
}
)
setMethod("impose", signature(x="SpatRasterCollection"),
function(x, y, filename="", ...) {
stopifnot(inherits(y, "SpatRaster"))
opt <- spatOptions(filename, ...)
r <- rast()
r@pntr <- x@pntr$morph(y@pntr, opt)
messages(r, "impose")
}
)
setMethod("rev", signature(x="SpatRaster"),
function(x) {
opt <- spatOptions("", FALSE, list())
x@pntr <- x@pntr$reverse(opt)
messages(x, "rev")
}
)
setMethod("rotate", signature(x="SpatRaster"),
function(x, left=TRUE, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$rotate(left, opt)
messages(x, "rotate")
}
)
setMethod("rotate", signature(x="SpatVector"),
function(x, longitude=0, split=TRUE, left=TRUE, normalize=FALSE) {
if (split) {
e <- ext(x)
if ((longitude < e$xmin) || (longitude > e$xmax)) {
if (left) {
return(shift(x, -360))
} else {
return(shift(x, 360))
}
}
e <- as.vector(floor(e) + 1)
ew <- ext(c(e[1], longitude, e[3:4]))
ee <- ext(c(longitude, e[2:4]))
x$unique_id_for_aggregation <- 1:nrow(x)
xcrs <- crs(x)
crs(x) <- NULL # avoid wrapping
xw <- crop(x, ew)
xe <- crop(x, ee)
if (left) {
xe <- shift(xe, -360)
} else {
xw <- shift(xw, 360)
}
out <- rbind(xe, xw)
if (nrow(out) > nrow(x)) {
out <- aggregate(out, "unique_id_for_aggregation", id=F)
i <- match(out$unique_id_for_aggregation, x$unique_id_for_aggregation)
values(out) <- values(x)[i,,drop=FALSE]
x <- out
}
x$unique_id_for_aggregation <- NULL
crs(x) <- xcrs
} else {
x@pntr <- x@pntr$rotate_longitude(longitude, left)
x <- messages(x, "rotate")
}
if (normalize) {
x <- normalize.longitude(x)
}
x
}
)
setMethod("segregate", signature(x="SpatRaster"),
function(x, classes=NULL, keep=FALSE, other=0, round=FALSE, digits=0, filename="", ...) {
opt <- spatOptions(filename, ...)
if (is.null(classes)) classes <- 1[0]
x@pntr <- x@pntr$separate(classes, keep[1], other[1], round[1], digits[1], opt)
messages(x, "segregate")
}
)
setMethod("shift", signature(x="SpatRaster"),
function(x, dx=0, dy=0, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$shift(dx, dy, opt)
messages(x, "shift")
}
)
setMethod("shift", signature(x="SpatExtent"),
function(x, dx=0, dy=0) {
s <- c(dx[1], dx[1], dy[1], dy[1])
ext(as.vector(x) + s)
}
)
setMethod("shift", signature(x="SpatVector"),
function(x, dx=0, dy=0) {
x@pntr <- x@pntr$shift(dx, dy)
messages(x, "shift")
}
)
setMethod("rescale", signature(x="SpatRaster"),
function(x, fx=0.5, fy=fx, x0, y0) {
stopifnot(fx > 0)
stopifnot(fy > 0)
e <- as.vector(ext(x))
if (missing(x0)) {
x0 <- mean(e[1:2])
}
if (missing(y0)) {
y0 <- mean(e[3:4])
}
ex = x0 + fx * (e[1:2] - x0);
ey = y0 + fy * (e[3:4] - y0);
x@pntr <- x@pntr$deepcopy()
ext(x) <- ext(c(ex, ey))
messages(x, "rescale")
}
)
setMethod("rescale", signature(x="SpatVector"),
function(x, fx=0.5, fy=fx, x0, y0) {
stopifnot(fx > 0)
stopifnot(fy > 0)
e <- as.vector(ext(x))
if (missing(x0)) {
x0 <- mean(e[1:2])
}
if (missing(y0)) {
y0 <- mean(e[3:4])
}
x@pntr <- x@pntr$rescale(fx, fy, x0[1], y0[1])
messages(x, "rescale")
}
)
setMethod("scale_linear", signature(x="SpatRaster"),
function(x, min=0, max=1, filename="", ...) {
opt <- spatOptions(filename=filename, ...)
x@pntr <- x@pntr$scale_linear(min, max, opt)
messages(x, "scale_linear")
}
)
setMethod("scale", signature(x="SpatRaster"),
function(x, center=TRUE, scale=TRUE) {
opt <- spatOptions()
if (is.logical(center)) {
docenter = center[1];
center = 1[0]
} else {
docenter = TRUE
}
if (is.logical(scale)) {
doscale = scale[1]
scale = 1[0]
} else {
doscale = TRUE;
}
x@pntr <- x@pntr$scale(center, docenter, scale, doscale, opt)
messages(x, "scale")
}
)
setMethod("stretch", signature(x="SpatRaster"),
function(x, minv=0, maxv=255, minq=0, maxq=1, smin=NA, smax=NA, histeq=FALSE, scale=1, maxcell=500000, filename="", ...) {
if (histeq) {
nms <- names(x)
if (nlyr(x) > 1) {
x <- lapply(1:nlyr(x), function(i) stretch(x[[i]], histeq=TRUE, scale=scale, maxcell=maxcell))
x <- rast(x)
names(x) <- nms
if (filename != "") {
x <- writeRaster(x, filename=filename, ...)
}
return(x)
}
scale <- scale[1]
if (scale == 1) {
ecdfun <- stats::ecdf(na.omit(spatSample(x, maxcell, "regular")[,1]))
} else {
ecdfun <- function(y) {
f <- stats::ecdf(na.omit(spatSample(x, maxcell, "regular")[,1]))
f(y) * scale
}
}
wopt <- list(...)
if (is.null(wopt$names)) {
wopt$names <- nms
}
app(x, ecdfun, filename=filename, wopt=wopt)
} else {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$stretch(minv, maxv, minq, maxq, smin, smax, opt)
messages(x, "stretch")
}
}
)
setMethod("summary", signature(object="SpatRaster"),
function(object, size=100000, warn=TRUE, ...) {
if (!hasValues(object)) {
warn("summary", "SpatRaster has no values")
return(invisible())
}
if (warn && (ncell(object) > size)) {
warn("summary", "used a sample")
}
s <- spatSample(object, size, method="regular", warn=FALSE)
summary(s, ...)
}
)
setMethod("summary", signature(object="SpatVector"),
function(object, ...) {
summary(as.data.frame(object), ...)
}
)
setMethod("t", signature(x="SpatRaster"),
function(x) {
opt <- spatOptions()
x@pntr <- x@pntr$transpose(opt)
messages(x, "t")
}
)
setMethod("t", signature(x="SpatVector"),
function(x) {
x@pntr <- x@pntr$transpose()
messages(x, "t")
}
)
setMethod("terrain", signature(x="SpatRaster"),
function(x, v="slope", neighbors=8, unit="degrees", filename="", ...) {
unit <- match.arg(unit, c("degrees", "radians"))
opt <- spatOptions(filename, ...)
seed <- ifelse("flowdir" %in% v, .seed(), 0)
x@pntr <- x@pntr$terrain(v, neighbors[1], unit=="degrees", seed, opt)
messages(x, "terrain")
}
)
setMethod("viewshed", signature(x="SpatRaster"),
function(x, loc, observer=1.80, target=0, curvcoef=6/7, output="yes/no", filename="", ...) {
opt <- spatOptions(filename, ...)
z <- rast()
if (length(loc) == 1) {
loc <- xyFromCell(x, loc)
}
outops <- c("yes/no", "sea", "land")
output <- match.arg(tolower(output), outops)
output <- match(output, outops)
z@pntr <- x@pntr$view(c(loc[1:2], observer[1], target[1]), c(1,0,2,3), curvcoef, 2, 0, output, opt)
messages(z, "viewshed")
}
)
setMethod("sieve", signature(x="SpatRaster"),
function(x, threshold, directions=8, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$sieve(threshold[1], directions[1], opt)
messages(x, "sieve")
}
)
setMethod("trim", signature(x="SpatRaster"),
function(x, padding=0, value=NA, filename="", ...) {
opt <- spatOptions(filename, ...)
padding <- round(padding[1])
if (padding < 0) {
error("trim", "padding must be a non-negative integer")
}
x@pntr <- x@pntr$trim(value[1], padding, opt)
messages(x, "trim")
}
)
setMethod("trans", signature(x="SpatRaster"),
function(x, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$transpose(opt)
messages(x, "trans")
}
)
setMethod("unique", signature(x="SpatRaster", incomparables="ANY"),
function(x, incomparables=FALSE, digits=NA, na.rm=TRUE, as.raster=FALSE) {
opt <- spatOptions()
if (as.raster) incomparables = FALSE
u <- x@pntr$unique(incomparables, digits, na.rm[1], opt)
if (!as.raster) {
u <- get_labels(x, u)
}
if (!incomparables) {
#if (!length(u)) return(u)
u <- do.call(data.frame, u)
colnames(u) <- names(x)
if (nrow(u) == 0) {
if (as.raster) {
return(deepcopy(x))
} else {
return(NULL)
}
}
}
if ((!incomparables) && (na.rm || as.raster)) {
i <- rowSums(is.na(u)) < ncol(u)
u <- u[i, , drop=FALSE]
}
if (as.raster) {
lab <- apply(get_labels(x, u), 1, function(i) paste(i, collapse="_"))
if (!is.na(digits)) {
x <- round(x, digits)
} else {
levels(x) <- NULL
}
uid <- 1:nrow(u)
x <- subst(x, u, uid-1)
set.cats(x, 1, data.frame(ID=uid-1, label=lab, u))
return(x)
}
u
}
)
setMethod("unique", signature(x="SpatVector", incomparables="ANY"),
function(x, incomparables=FALSE, ...) {
u <- unique(as.data.frame(x, geom="WKT"), incomparables=incomparables, ...)
vect(u, geom="geometry", crs(x))
}
)
setMethod("labels", signature(object="SpatRaster"),
function(object, ...) {
names(object)
}
)
setMethod("scoff", signature(x="SpatRaster"),
function(x) {
out <- x@pntr$getScaleOffset()
names(out) <- c("scale", "offset")
do.call(cbind, out)
}
)
setMethod("scoff<-", signature("SpatRaster"),
function(x, value) {
if (is.null(value)) {
x@pntr <- x@pntr$deepcopy()
x@pntr$setScaleOffset(1, 0)
} else {
if (NCOL(value) != 2) {
error("scoff<-", "value must be a 2-column matrix")
}
x@pntr <- x@pntr$deepcopy()
value[is.na(value[,1]),1] <- 1
value[is.na(value[,2]),2] <- 0
x@pntr$setScaleOffset(value[,1], value[,2])
x@pntr$setValueType(0)
}
messages(x, "scoff<-")
}
)
setMethod("sort", signature(x="SpatRaster"),
function (x, decreasing=FALSE, order=FALSE, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$sort(decreasing[1], order[1], opt)
messages(x, "sort")
}
)
setMethod("sort", signature(x="SpatVector"),
function (x, v, decreasing=FALSE) {
if (is.logical(v)) {
tmp <- v
v <- decreasing
decreasing <- tmp
}
if (length(v) > 1) {
v <- data.frame(x)[,v]
i <- do.call(order, lapply(v, function(i) i))
} else {
i <- order(x[[v]][[1]], decreasing=decreasing)
}
x[i, ]
}
)
setMethod("sort", signature(x="data.frame"),
function (x, v, decreasing=FALSE) {
if (length(v) > 1) {
v <- data.frame(x)[, v]
i <- do.call(order, lapply(v, function(i) i))
} else {
i <- order(x[[v]], decreasing=decreasing)
}
x[i, ]
}
)
terra/R/vect.R 0000644 0001762 0000144 00000027745 14726700274 012704 0 ustar ligges users
#setMethod("row.names", signature(x="SpatVector"),
# function(x) {
# 1:nrow(x)
# }
#)
setMethod("emptyGeoms", signature(x="SpatVector"),
function(x) {
x@pntr$nullGeoms() + 1
}
)
setMethod("as.vector", signature(x="SpatVector"),
function(x, mode="any") {
if (nrow(x) > 0) {
lapply(1:nrow(x), function(i) x[i,])
} else {
x
}
}
)
setMethod("vect", signature(x="missing"),
function(x) {
p <- methods::new("SpatVector")
p@pntr <- SpatVector$new()
messages(p, "vect")
return(p)
}
)
setMethod("vect", signature(x="SpatExtent"),
function(x, crs="") {
as.polygons(x, crs=crs)
}
)
setMethod("vect", signature(x="SpatVectorCollection"),
function(x) {
vect(as.list(x))
}
)
setMethod("vect", signature(x="SpatGraticule"),
function(x) {
v <- vect()
v@pntr <- x@pntr
v
}
)
setMethod("vect", signature(x="character"),
function(x, layer="", query="", extent=NULL, filter=NULL, crs="", proxy=FALSE, what="", opts=NULL) {
what <- trimws(tolower(what))
if (what != "") what <- match.arg(trimws(tolower(what)), c("geoms", "attributes"))
s <- substr(x[1], 1, 5)
if (s %in% c("POINT", "MULTI", "LINES", "POLYG", "EMPTY")) {
p <- methods::new("SpatVector")
# if (all(grepl("\\(", x) & grepl("\\)", x))) {
p@pntr <- SpatVector$new(gsub("\n", "", x))
messages(p, "vect")
crs(p, warn=FALSE) <- crs
return(p)
}
x <- x[1]
nx <- try(normalizePath(x, mustWork=TRUE), silent=TRUE)
if (!inherits(nx, "try-error")) { # skip html
x <- nx
if (grepl("\\.rds$", tolower(x))) {
v <- unwrap(readRDS(x))
if (!inherits(v, "SpatVector")) {
error("vect", "the rds file does not store a SpatVector")
}
return(v)
}
} else if ((substr(x, 1, 4) == "http") & (grepl("\\.shp$", x) | grepl("\\.gpkg$", x))) {
x <- paste0("/vsicurl/", x[1])
}
p <- methods::new("SpatVector")
p@pntr <- SpatVector$new()
proxy <- isTRUE(proxy)
if ((what=="attributes") && proxy) {
error("vect", "you cannot use 'what==attributes' when proxy=TRUE")
}
#if (proxy) query <- ""
if (is.null(filter)) {
filter <- SpatVector$new()
} else {
if (!inherits(filter, "SpatVector")) {
error("vect", "'filter' must be a SpatVector")
}
if (proxy) {
error("vect", "you cannot use 'filter' when proxy=TRUE")
}
filter <- filter@pntr
}
if (is.null(extent)) {
extent <- double()
} else {
extent <- as.vector(ext(extent))
}
if (is.null(opts)) opts <- ""[0]
p@pntr$read(x, layer, query, extent, filter, proxy, what, opts)
if (isTRUE(crs != "")) {
crs(p, warn=FALSE) <- crs
}
if (proxy) {
messages(p, "vect")
pp <- methods::new("SpatVectorProxy")
pp@pntr <- SpatVectorProxy$new()
pp@pntr$v <- p@pntr
return(pp)
}
p <- messages(p, "vect")
if (what == "attributes") {
p <- values(p)
}
p
}
)
setMethod("vect", signature(x="Spatial"),
function(x, ...) {
methods::as(x, "SpatVector")
}
)
setMethod("vect", signature(x="sf"),
function(x) {
methods::as(x, "SpatVector")
}
)
setMethod("vect", signature(x="sfc"),
function(x) {
methods::as(x, "SpatVector")
}
)
setMethod("vect", signature(x="XY"), #sfg
function(x) {
methods::as(x, "SpatVector")
}
)
.checkXYnames <- function(x, warn=FALSE) {
if (is.null(x)) return(TRUE)
if (length(x) != 2) {
error("vect", "coordinate matrix should have 2 columns")
}
z <- tolower(x[1:2])
x <- substr(z, 1, 3)
y <- substr(x, 1, 1)
if ((y[1] == "x") && (y[2] == "y")) return(FALSE)
if ((x[1] == "eas") && (x[2] == "nor")) return(FALSE)
if ((x[1] == "lon") && (x[2] == "lat")) return(TRUE)
if (grepl("lon", z[1]) && grepl("lat", z[2])) return(TRUE)
if ((x[1] == "lat") && (x[2] == "lon")) {
stop("vect", "longitude/latitude in the wrong order")
} else if ((y[1] == "y") && (y[2] == "x")) {
stop("vect", "x/y in the wrong order")
} else if ((x[1] == "nor") && (x[2] == "eas")) {
stop("vect", "easting/northing in the wrong order")
} else if (warn) {
warn("coordinate names not recognized. Expecting lon/lat, x/y, or easting/northing")
}
return(FALSE)
}
setMethod("vect", signature(x="matrix"),
function(x, type="points", atts=NULL, crs="") {
type <- tolower(type)
type <- match.arg(tolower(type), c("points", "lines", "polygons"))
stopifnot(NCOL(x) > 1)
crs <- character_crs(crs, "vect")
p <- methods::new("SpatVector")
p@pntr <- SpatVector$new()
crs(p, warn=FALSE) <- crs
nr <- nrow(x)
if (nr == 0) {
return(p)
}
nc <- ncol(x)
if (nc == 2) {
lonlat <- .checkXYnames(colnames(x))
if (type == "points") {
p@pntr$setPointsXY(as.double(x[,1]), as.double(x[,2]))
} else {
p@pntr$setGeometry(type, rep(1, nr), rep(1, nr), x[,1], x[,2], rep(FALSE, nr))
}
if (lonlat && isTRUE(crs=="")) crs <- "+proj=longlat"
} else if (nc == 3) {
p@pntr$setGeometry(type, x[,1], rep(1, nr), x[,2], x[,3], rep(FALSE, nr))
} else if (nc == 4) {
p@pntr$setGeometry(type, x[,1], x[,2], x[,3], x[,4], rep(FALSE, nr))
} else if (nc == 5) {
p@pntr$setGeometry(type, x[,1], x[,2], x[,3], x[,4], x[,5])
} else {
error("vect", "not an appropriate matrix (too many columns)")
}
if (!is.null(atts)) {
if ((nrow(atts) == nrow(p)) & (ncol(atts) > 0)) {
values(p) <- atts
}
}
messages(p, "vect")
}
)
setMethod("$", "SpatVector", function(x, name) {
if (!(name %in% names(x))) {
return(NULL)
#error("$", paste(name, "is not a variable name in x"))
}
s <- .subset_cols(x, name, drop=TRUE)
s[,1,drop=TRUE]
})
setMethod("[[", c("SpatVector", "numeric", "missing"),
function(x, i, j,drop=FALSE) {
s <- .subset_cols(x, i, drop=TRUE)
s[,,drop=drop]
})
setMethod("[[", c("SpatVector", "character", "missing"),
function(x, i, j, drop=FALSE) {
if (!(any(i %in% names(x)))) {
return(NULL)
}
s <- .subset_cols(x, i, drop=TRUE)
s[,,drop=drop]
})
setReplaceMethod("[", c("SpatVector", "ANY", "ANY"),
function(x, i, j, value) {
v <- values(x)
v[i,j] <- value
if (nrow(v) != nrow(x)) {
error("[<-", "this would create an invalid SpatVector")
}
values(x) <- v
x
}
)
setReplaceMethod("[", c("SpatVector", "ANY", "missing"),
function(x, i, j, value) {
v <- values(x)
if (inherits(value, "SpatVector")) {
value <- values(value)
}
v[i,] <- value
if (nrow(v) != nrow(x)) {
error("[<-", "this would create an invalid SpatVector")
}
values(x) <- v
x
}
)
setReplaceMethod("[", c("SpatVector", "missing", "ANY"),
function(x, i, j, value) {
v <- values(x)
if (inherits(value, "SpatVector")) {
value <- values(value)
}
v[,j] <- value
if (nrow(v) != nrow(x)) {
error("[<-", "this would create an invalid SpatVector")
}
values(x) <- v
x
}
)
setReplaceMethod("[[", c("SpatVector", "character"),
function(x, i, value) {
x@pntr <- x@pntr$deepcopy()
if (is.null(value)) {
for (name in i) {
if (name %in% names(x)) {
x@pntr$remove_column(name)
}
}
return(x);
}
if (inherits(value, "data.frame")) {
if (ncol(value) > 1) {
warn("`[[<-`", "only using the first column")
}
value <- value[,1]
} else if (inherits(value, "list")) {
value <- unlist(value)
}
if (NCOL(value) > 1) {
warn("[[<-,SpatVector", "only using the first column")
value <- value[,1]
}
name <- i[1]
value <- rep(value, length.out=nrow(x))
if (name %in% names(x)) {
d <- values(x)
if (all(is.na(value))) {
#[] to keep type if NA is used
d[[name]][] <- value
} else {
d[[name]] <- value
}
values(x) <- d
} else {
if (inherits(value, "factor")) {
v <- .makeSpatFactor(value)
ok <- x@pntr$add_column_factor(v, name)
} else if (inherits(value, "character")) {
ok <- x@pntr$add_column_string(enc2utf8(value), name)
} else if (inherits(value, "integer")) {
# min long (should query what it is on the system?)
value[is.na(value)] <- -2147483648
ok <- x@pntr$add_column_long(value, name)
} else if (inherits(value, "logical")) {
v <- as.integer(value)
v[is.na(v)] <- 2
ok <- x@pntr$add_column_bool(v, name)
} else if (inherits(value, "numeric")) {
ok <- x@pntr$add_column_double(value, name)
} else if (inherits(value, "Date")) {
ok <- x@pntr$add_column_time(as.numeric(as.POSIXlt(value)), name, "days", "")
} else if (inherits(value, "POSIXt")) {
tz <- if (length(value) > 0) { attr(value[1], "tzone") } else { "" }
if (is.null(tz)) tz <- ""
ok <- x@pntr$add_column_time(as.numeric(value), name, "seconds", tz)
} else {
v <- try(as.character(value))
if (!inherits(v, "try-error")) {
ok <- x@pntr$add_column_string(enc2utf8(v), name)
} else {
ok <- FALSE
}
}
if (!ok) {
error("[[<-,SpatVector", "cannot add these values")
}
}
x
}
)
setReplaceMethod("[[", c("SpatVector", "numeric"),
function(x, i, value) {
stopifnot(i > 0 && i <= ncol(x))
vn <- names(x)[i]
x[[vn]] <- value
x
}
)
setMethod("$<-", "SpatVector",
function(x, name, value) {
x[[name]] <- value
x
}
)
setMethod("vect", signature(x="data.frame"),
function(x, geom=c("lon", "lat"), crs="", keepgeom=FALSE) {
if (!all(geom %in% names(x))) {
error("vect", "the variable name(s) in argument `geom` are not in `x`")
}
crs <- character_crs(crs, "vect")
if (length(geom) == 2) {
geom <- match(geom[1:2], names(x))
if (inherits(x[,geom[1]], "integer")) {
x[,geom[1]] = as.numeric(x[,geom[1]])
}
if (inherits(x[,geom[2]], "integer")) {
x[,geom[2]] = as.numeric(x[,geom[2]])
}
p <- methods::new("SpatVector")
p@pntr <- SpatVector$new()
x <- .makeSpatDF(x)
p@pntr$setPointsDF(x, geom-1, crs, keepgeom)
return(messages(p, "vect"))
} else if (length(geom) == 1) {
v <- vect(unlist(x[,geom]), crs=crs)
if (!keepgeom) {
x[[geom]] <- NULL
}
} else {
error("vect", "the length of 'geom' must be 1 or 2")
}
values(v) <- x
v
}
)
setMethod("vect", signature(x="list"),
function(x, type="points", crs="") {
x <- lapply(x, function(i) {
if (inherits(i, "SpatVector")) return(i)
vect(i, type=type)
})
x <- svc(x)
v <- methods::new("SpatVector")
v@pntr <- x@pntr$append()
if (crs != "") {
crs(v) <- crs
}
messages(v, "vect")
}
)
setMethod("query", signature(x="SpatVectorProxy"),
function(x, start=1, n=nrow(x), vars=NULL, where=NULL, extent=NULL, filter=NULL, sql=NULL, what="") {
f <- x@pntr$v$source
slayer <- x@pntr$v$layer
#1058
layer <- paste0("\"", slayer, "\"")
e <- x@pntr$v$read_extent
if (is.null(extent)) {
if (length(e) == 4) {
extent = ext(e);
}
} else {
if (length(e) == 4) {
extent = intersect(ext(e), extent);
if (is.null(extent)) {
error("query", "extent does not intersect with x")
}
}
}
if (is.null(vars)) {
vars <- "*"
} else {
vars <- stats::na.omit(unique(vars))
nms <- names(x)
if (!all(vars %in% nms)) {
error("query", "not all vars are variable names")
} else if (length(vars) < length(nms)) {
vars <- paste(vars, collapse=", ")
}
}
if (!is.null(sql)) {
qy <- as.character(sql)
} else {
qy <- ""
if (!is.null(where)) {
qy <- paste("SELECT", vars, "FROM", layer, "WHERE", where[1])
} else {
qy <- paste("SELECT", vars, "FROM", layer)
}
nr <- nrow(x)
start <- start-1
if (start > 0) {
if (n >= (nr-start)) {
qy <- paste(qy, "OFFSET", start)
} else {
n <- min(n, nr-start)
qy <- paste(qy, layer, "LIMIT", n, "OFFSET", start)
}
} else if (n < nr) {
n <- min(n, nr)
qy <- paste(qy, "LIMIT", n)
}
}
if (qy != "") {
if (x@pntr$v$read_query != "") {
error("query", "A query was used to create 'x'; you can only subset it with extent or filter")
}
} else {
layer <- slayer
}
p <- vect(f, layer, query=qy, extent=extent, filter=filter, crs="", FALSE, what=what)
if (what == "attributes") {
p <- values(p)
}
p
}
)
vector_layers <- function(filename, delete="", return_error=FALSE) {
p <- SpatVector$new()
if (any(delete != "")) {
delete <- trimws(delete)
ok <- p$delete_layers(filename, delete, return_error[1])
messages(p, "vector_layers")
invisible(ok)
} else {
out <- p$layer_names(filename)
messages(p, "vector_layers")
out
}
}
terra/R/write.R 0000644 0001762 0000144 00000011642 14746206355 013065 0 ustar ligges users
setMethod("blocks", signature(x="SpatRaster"),
function(x, n=4) {
opt <- spatOptions("", FALSE, ncopies=n)
b <- x@pntr$getBlockSizeR(opt)
b$row <- b$row + 1
b
}
)
setMethod("writeStart", signature(x="SpatRaster", filename="character"),
function(x, filename="", overwrite=FALSE, n=4, sources="", ...) {
filename <- path.expand(trimws(filename[1]))
filename <- enc2utf8(filename)
opt <- spatOptions(filename, overwrite, ncopies=n, ...)
ok <- x@pntr$writeStart(opt, unique(sources))
messages(x, "writeStart")
b <- x@pntr$getBlockSizeWrite()
b$row <- b$row + 1
b
}
)
setMethod("writeStop", signature(x="SpatRaster"),
function(x) {
success <- x@pntr$writeStop()
messages(x, "writeStop")
f <- sources(x)
if (f != "") {
x <- rast(f)
}
return(x)
}
)
setMethod("writeValues", signature(x="SpatRaster", v="vector"),
function(x, v, start, nrows) {
success <- x@pntr$writeValues(v, start-1, nrows)
messages(x, "writeValues")
invisible(success)
}
)
setMethod("writeRaster", signature(x="SpatRaster", filename="character"),
function(x, filename="", overwrite=FALSE, ...) {
filename <- trimws(filename)
stopifnot(filename != "")
filename <- enc2utf8(filename)
ftp <- list(...)$filetype[1]
fext <- tools::file_ext(filename)
if (any(fext %in% c("nc", "cdf")) && (is.null(ftp) || isTRUE(ftp=="netCDF"))) {
warn("writeRaster", "consider writeCDF to write ncdf files")
}
#else if ((length(fext)==1) && (any(fext == "rds")) && ((is.null(ftp)) || isTRUE(ftp=="RDS"))) {
# if ((!overwrite) && file.exists(filename)) {
# error("writeRaster", "Use 'overwrite=TRUE' to overwrite an existing file")
# }
# return(saveRDS(x, filename))
#}
opt <- spatOptions(filename, overwrite, ...)
x@pntr <- x@pntr$writeRaster(opt)
x <- messages(x, "writeRaster")
invisible(rast(filename))
}
)
get_filetype <- function(filename) {
fn <- tolower(filename)
ext <- tools::file_ext(fn)
ext2 <- gsub("^[^.]*\\.(.*).*$", "\\1", fn)
if ((ext == "shp") || (ext == "shz") || (ext == "zip" && ext2 == "shp.zip")) {
"ESRI Shapefile"
} else if ((ext == "") || (ext == "gpkg") || (ext == "zip" && ext2 == "gpkg.zip")) {
"GPKG"
} else if (ext == "gdb") {
"OpenFileGDB"
} else if (ext == "gml") {
"GML"
} else if ((ext == "json") || (ext == "geojson")) {
"GeoJSON"
} else if (ext == "cdf") {
"netCDF"
} else if (ext == "svg") {
"SVG"
} else if (ext == "kml") {
"KML"
} else if (ext == "vct") {
"Idrisi"
} else if (ext == "rds") {
"rds"
} else if (ext == "tab") {
"MapInfo File"
} else {
error("writeVector", "cannot guess filetype from filename")
}
}
setMethod("writeVector", signature(x="SpatVector", filename="character"),
function(x, filename, filetype=NULL, layer=NULL, insert=FALSE, overwrite=FALSE, options="ENCODING=UTF-8") {
filename <- path.expand(trimws(filename[1]))
filename <- enc2utf8(filename)
if (filename == "") {
error("writeVector", "provide a filename")
}
if (is.null(filetype)) {
filetype <- get_filetype(filename)
if (filetype == "rds") {
return(saveRDS(x, filename))
}
}
if (is.null(layer)) layer <- tools::file_path_sans_ext(basename(filename))
layer <- trimws(layer)
if (is.null(options)) { options <- ""[0] }
if (filetype == "ESRI Shapefile") {
nms <- names(x)
i <- nchar(nms) > 10
if (any(i)) {
nms[i] <- substr(nms[i], 1, 10)
testnms <- make.unique(nms, sep="")
if (!all(testnms == nms)) {
i <- which(i)
newnms <- substr(nms[i], 1, 9)
newnms <- make.unique(newnms, sep="")
j <- which(nchar(newnms) == 9)
newnms[j] <- paste0(newnms[j], "0")
nms[i] <- newnms
}
x@pntr <- x@pntr$deepcopy()
names(x) <- nms
}
}
success <- x@pntr$write(filename, layer, filetype, insert[1], overwrite[1], options)
messages(x, "writeVector")
invisible(TRUE)
}
)
# setMethod("writeVector", signature(x="SpatVectorProxy", filename="character"),
# function(x, filename, filetype=NULL, layer=NULL, insert=FALSE, overwrite=FALSE, options="ENCODING=UTF-8") {
# filename <- trimws(filename)
# filename <- enc2utf8(filename)
# if (filename == "") {
# error("writeVector", "provide a filename")
# }
# if (is.null(filetype)) {
# filetype <- get_filetype(filename)
# }
# if (is.null(layer)) layer <- tools::file_path_sans_ext(basename(filename))
# layer <- trimws(layer)
# if (is.null(options)) { options <- ""[0] }
# if (filetype == "ESRI Shapefile") {
# nms <- names(x)
# i <- nchar(nms) > 10
# if (any(i)) {
# nms[i] <- substr(nms[i], 1, 10)
# testnms <- make.unique(nms, sep="")
# if (!all(testnms == nms)) {
# i <- which(i)
# newnms <- substr(nms[i], 1, 9)
# newnms <- make.unique(newnms, sep="")
# j <- which(nchar(newnms) == 9)
# newnms[j] <- paste0(newnms[j], "0")
# nms[i] <- newnms
# }
# x@pntr <- x@pntr$deepcopy()
# names(x) <- nms
# }
# }
# success <- x@pntr$write_proxy(filename, layer, filetype, insert[1], FALSE, overwrite[1], options)
# messages(x, "writeVector")
# invisible(TRUE)
# }
# )
terra/R/coerce.R 0000644 0001762 0000144 00000042625 14747272543 013203 0 ustar ligges users # Author: Robert J. Hijmans
# Date : October 2018
# Version 1.0
# License GPL v3
## from stars
#stars:::st_as_raster is used
#setAs("stars", "SpatRaster") is provided by stars via st_as_raster
from_stars <- function(from) {
isProxy <- inherits(from, "stars_proxy")
natts <- length(from)
#from[i] recursion does not work with proxy
if (!isProxy && (natts > 1)) { # not sure what attributes represent
ra <- list()
for (i in 1:natts) {
ra[[i]] <- from_stars(from[i])
}
if (all(sapply(ra, function(i) inherits(i, "SpatRaster")))) {
nl <- sapply(ra, nlyr)
ra <- rast(ra)
nms <- names(ra)
names(ra) <- paste(rep(names(from), nl), nms, sep="_")
} else if (all(sapply(ra, function(i) inherits(i, "SpatRasterDataset")))) {
ra <- do.call(c, ra)
} else {
ra <- lapply(ra, function(i) if (!inherits(i, "SpatRasterDataset")) {sds(i)} else {i})
ra <- do.call(c, ra)
}
return(ra)
}
dims <- attr(from, "dimensions")
dd <- dim(from)
# x, y
hasBands <- "band" %in% names(dd)
hasTime <- "time" %in% names(dd)
timev <- NULL
if (hasTime) {
tim <- dims$time$offset
tseq <- dims$time$from:dims$time$to
if (dims$time$refsys == "Date") {
timev <- as.Date(tim) + tseq
} else { # for now
timev <- tseq
}
}
# no time or variables
if (length(dd) - hasBands == 2) {
return( methods::as(from, "SpatRaster"))
}
# time, perhaps bands or variables
if (length(dd) - (hasTime + hasBands) == 2) {
r <- methods::as(from, "SpatRaster")
if (hasBands) {
timev <- rep(timev, each=dd["band"])
}
time(r) <- timev
return(r)
}
if (isProxy) {
# currently not setting time dim here
if (natts > 1) {
ff <- sapply(from, function(i) from[i][[1]])
s <- sds(ff)
names(s) <- names(from)
} else {
f <- from[[1]]
s <- sds(f)
nms <- names(dd)[3+hasBands]
if (!is.na(nms)) {
names(s) <- paste(nms, 1:length(s), sep="-")
}
}
return(s)
}
xmin <- dims$x$offset
nc <- dims$x$to
xmax <- xmin + nc * dims$x$delta
ymax <- dims$y$offset
nr <- dims$y$to
ymin <- ymax + nr * dims$y$delta
from <- from[[1]]
rr <- list()
if (hasTime && hasBands) {
for (i in 1:dd[5]) {
x <- from[,,,,i]
r <- rast(ncols=nc, nrows=nr, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, crs=dims$x$refsys$wkt, nlyr=dd["band"] * dd["time"])
time(r) <- rep(timev, each=dd["band"])
bandnames <- rep(paste("band", 1:dd["band"], sep="-"), length(timev))
names(r) <- paste(bandnames, rep(timev, each=dd["band"]), sep="_")
r <- setValues(r, as.vector(x))
rr[[i]] <- r
}
} else { #if (hasTime || hasBands) {
for (i in 1:dd[4]) {
x <- from[,,,i]
r <- rast(ncols=nc, nrows=nr, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, crs=dims$x$refsys$wkt, nlyr=dim(x)[3], time=timev)
if (hasBands) {
names(r) <- paste("band", 1:dd["band"], sep="-")
} else {
names(r) <- timev
}
rr[[i]] <- setValues(r, x)
}
}
s <- sds(rr)
names(s) <- paste(names(dd)[4], 1:length(s), sep="-")
s
}
setAs("stars", "SpatRasterDataset",
function(from) {
from_stars(from)
}
)
setAs("ggmap", "SpatRaster",
function(from) {
b <- attr(from, "bb")
e <- ext(b$ll.lon, b$ur.lon, b$ll.lat, b$ur.lat)
r <- rast(nrows=nrow(from), ncols=ncol(from), ext=e, nlyr=3, crs="epsg:4326", names=c("red", "green", "blue"))
values(r) <- t(grDevices::col2rgb(from))
RGB(r) <- 1:3
r
}
)
as.list.SpatRaster <- function(x, geom=NULL, ...) {
if (!is.null(geom)) {
e <- as.vector(ext(x))
d <- crs(x, describe=TRUE)
if (!(is.na(d$authority) || is.na(d$code))) {
crs <- paste0(d$authority, ":", d$code)
} else {
crs <- gsub("\n[ ]+", "", crs(x))
}
list(
ncols=ncol(x),
nrows=nrow(x),
nlyrs=nlyr(x),
xmin=e[1],
xmax=e[2],
ymin=e[3],
ymax=e[4],
xres=xres(x),
yres=yres(x),
nms = paste(names(x), collapse="', '"),
units = paste(units(x), collapse="', '"),
time = paste(time(x), collapse="', '"),
crs=crs
)
} else {
lapply(1:nlyr(x), function(i) x[[i]])
}
}
setMethod("as.list", signature(x="SpatRaster"), as.list.SpatRaster)
as.list.SpatRasterCollection <- function(x, ...) {
out <- lapply(1:length(x), function(i) x[i])
names(out) <- names(x)
out
}
setMethod("as.list", signature(x="SpatRasterCollection"), as.list.SpatRasterCollection)
as.list.SpatRasterDataset <- function(x, ...) {
out <- lapply(1:length(x), function(i) x[i])
names(out) <- names(x)
out
}
setMethod("as.list", signature(x="SpatRasterDataset"), as.list.SpatRasterDataset)
as.list.SpatVectorCollection <- function(x, ...) {
out <- lapply(1:length(x), function(i) x[i])
names(out) <- names(x)
out
}
setMethod("as.list", signature(x="SpatVectorCollection"), as.list.SpatVectorCollection)
# create a "grDevices::raster" (small r) object for use with the rasterImage function
# NOT a raster::Raster* object
setMethod("as.raster", signature(x="SpatRaster"),
function(x, maxcell=500000, col) {
if (missing(col)) {
#col <- rev(grDevices::terrain.colors(255))
col <- .default.pal()
}
x <- spatSample(x, maxcell, method="regular", as.raster=TRUE, warn=FALSE)
x <- as.matrix(x, wide=TRUE)
r <- range(x, na.rm=TRUE)
x <- (x - r[1])/ (r[2] - r[1])
x <- round(x * (length(col)-1) + 1)
x[] <- col[x]
as.raster(x)
}
)
.as.image <- function(x, maxcells=10000) {
x <- spatSample(x, size=maxcells, method="regular", as.raster=TRUE, warn=FALSE)
X <- xFromCol(x, 1:ncol(x))
Y <- yFromRow(x, nrow(x):1)
Z <- t(as.matrix(x, wide=TRUE)[nrow(x):1,])
list(x=X, y=Y, z=Z)
}
get_labels <- function(x, p, dissolve=FALSE) {
ff <- is.factor(x)
if (dissolve) {
ff <- ff[[1]]
}
if (any(ff)) {
ff <- which(ff)
cgs <- levels(x)
for (f in ff) {
cg <- cgs[[f]]
i <- match(unlist(p[[f]]), cg[,1])
p[[f]] <- cg[i, 2]
}
}
p
}
setMethod("as.polygons", signature(x="SpatRaster"),
function(x, round=TRUE, aggregate=TRUE, values=TRUE, na.rm=TRUE, na.all=FALSE, extent=FALSE, digits=0, ...) {
if (isFALSE(list(...)$dissolve)) {
aggregate <- FALSE
}
p <- methods::new("SpatVector")
if (extent) {
p@pntr <- x@pntr$dense_extent(FALSE, FALSE)
x <- messages(x, "as.polygons")
} else {
opt <- spatOptions()
p@pntr <- x@pntr$as_polygons(round[1], aggregate[1], values[1], na.rm[1], na.all[1], digits, opt)
x <- messages(x, "as.polygons")
if (values) {
p <- get_labels(x, p, aggregate[1])
}
}
messages(p, "as.polygons")
}
)
setMethod("as.lines", signature(x="SpatRaster"),
function(x) {
p <- methods::new("SpatVector")
opt <- spatOptions()
p@pntr <- x@pntr$as_lines(opt)
messages(p, "as.lines")
}
)
setMethod("as.polygons", signature(x="SpatExtent"),
function(x, crs="") {
p <- methods::new("SpatVector")
crs <- character_crs(crs, "as.polygons")
p@pntr <- SpatVector$new(x@pntr, crs)
messages(p, "as.polygons")
}
)
setMethod("as.lines", signature(x="SpatExtent"),
function(x, crs="") {
crs <- character_crs(crs, "as.lines")
as.lines(as.polygons(x, crs))
}
)
setMethod("as.points", signature(x="SpatExtent"),
function(x, crs="") {
#vect(do.call(cbind, x@pntr$as.points()), "points", crs=crs)
as.points(as.polygons(x, crs))
}
)
setMethod("as.lines", signature(x="SpatVector"),
function(x) {
x@pntr <- x@pntr$as_lines()
messages(x, "as.lines")
}
)
setMethod("as.lines", signature(x="matrix"),
function(x, crs="") {
p <- vect()
if (ncol(x) == 2) {
nr <- nrow(x)
p@pntr$setGeometry("lines", rep(1, nr), rep(1, nr), x[,1], x[,2], rep(FALSE, nr))
crs(p) <- crs
} else if (ncol(x) == 4) {
p@pntr$setLinesStartEnd(x, crs(crs))
} else {
error("expecting a two or four column matrix", "as.lines")
}
messages(p, "vect")
}
)
setMethod("as.polygons", signature(x="SpatVector"),
function(x, extent=FALSE) {
if (extent) {
as.polygons(ext(x), crs=crs(x))
} else {
x@pntr <- x@pntr$polygonize()
messages(x, "as.polygons")
}
}
)
setMethod("as.points", signature(x="SpatVector"),
function(x, multi=FALSE, skiplast=TRUE) {
opt <- spatOptions()
x@pntr <- x@pntr$as_points(multi, skiplast)
messages(x, "as.points")
}
)
setMethod("as.points", signature(x="SpatRaster"),
function(x, values=TRUE, na.rm=TRUE, na.all=FALSE) {
p <- methods::new("SpatVector")
opt <- spatOptions()
p@pntr <- x@pntr$as_points(values, na.rm, na.all, opt)
x <- messages(x, "as.points")
if (values) {
p <- get_labels(x, p, FALSE)
}
messages(p, "as.points")
}
)
# mode argument is ignored as mode=mode gave an error on R-devel
setMethod("as.vector", signature(x="SpatExtent"),
function(x, mode="any") {
v <- x@pntr$vector
names(v) <- c("xmin", "xmax", "ymin", "ymax")
if (mode == "list") {
v <- as.list(v)
}
v
}
)
setMethod("as.character", signature(x="SpatExtent"),
function(x) {
e <- as.vector(x)
paste0("ext(", paste(e, collapse=", "), ")")
}
)
setMethod("as.vector", signature(x="SpatRaster"),
function(x, mode="any") {
values(x, FALSE)
}
)
as.matrix.SpatRaster <- function(x, wide=FALSE, ...) {
if (!hasValues(x)) {
error("as.matrix", "SpatRaster has no cell values")
}
# wide <- isTRUE(list(...)$wide)
if (wide) {
if (nlyr(x) > 1) {
m <- values(x, mat=TRUE)
m <- lapply(1:ncol(m), function(i) {
matrix(m[,i], nrow=nrow(x), byrow=TRUE)
})
m <- do.call(cbind, m)
} else {
m <- matrix(values(x, mat=FALSE),nrow=nrow(x),byrow=TRUE)
}
} else {
m <- values(x, mat=TRUE)
}
m
}
setMethod("as.matrix", signature(x="SpatRaster"), as.matrix.SpatRaster)
as.matrix.SpatExtent <- function(x, ...) {
v <- matrix(as.vector(x), ncol=2, byrow=TRUE)
colnames(v) <- c("min", "max")
v
}
setMethod("as.matrix", signature(x="SpatExtent"), as.matrix.SpatExtent)
as.data.frame.SpatRaster <- function(x, row.names=NULL, optional=FALSE, xy=FALSE, cells=FALSE, time=FALSE,na.rm=NA, wide=TRUE, ...) {
d <- NULL
if (xy) {
d <- xyFromCell(x, 1:ncell(x))
}
if (cells) {
d <- cbind(cell=1:ncell(x), d)
}
if (is.null(d)) {
d <- values(x, dataframe=TRUE, ... )
} else {
d <- data.frame(d)
d <- cbind(d, values(x, dataframe=TRUE), ...)
}
if (is.na(na.rm)) {
cols <- (1 + cells + xy * 2):ncol(d)
i <- rowSums(is.na(d[,cols,drop=FALSE])) < length(cols)
d <- d[i,,drop=FALSE]
} else if (isTRUE(na.rm)) {
d <- stats::na.omit(d)
attr(d, "na.action") <- NULL
}
if (!wide) {
nr <- nrow(d)
if (!(xy || cells)) {
d <- data.frame(layer=rep(names(x), each=nr), values=as.vector(as.matrix(d)))
} else {
idv <- NULL
if (xy) idv <- c("x", "y", idv)
if (cells) idv <- c("cell", idv)
add <- d[idv]
rownames(add) <- NULL
for (i in 1:length(idv)) {
d[[idv[i]]] <- NULL
}
d <- data.frame(add, layer=rep(names(x), each=nr), values=as.vector(as.matrix(d)))
nms <- names(x)
# d <- stats::reshape(d, direction="long", idvar=idv, varying=nms, v.names="values")
# d$time <- nms[d$time]
# names(d)[names(d) == "time"] <- "layer"
}
rownames(d) <- NULL
if (time) {
# d$time <- NULL
# vals <- d$values
# d$values <- NULL
d$time <- rep(time(x), each=nr)
# d$values <- vals
}
} else if (time && has.time(x)) {
tm <- as.character(time(x))
nc <- ncol(d)
colnames(d)[(1+nc-length(tm)):nc] <- tm
}
d
}
setMethod("as.data.frame", signature(x="SpatRaster"), as.data.frame.SpatRaster)
setAs("SpatRaster", "data.frame",
function(from) {
as.data.frame(from)
}
)
setAs("SpatVector", "data.frame",
function(from) {
as.data.frame(from)
}
)
setMethod("as.array", signature(x="SpatRaster"),
function(x) {
dm <- dim(x)
x <- values(x, TRUE)
a <- array(NA, dm)
for (i in 1:dm[3]) {
a[,,i] <- matrix(x[,i], nrow=dm[1], byrow=TRUE)
}
a
}
)
setMethod("as.array", signature(x="SpatRasterDataset"),
function(x) {
n <- length(x)
if (n < 2) return(as.array(x[1]))
dm <- sapply(x, dim)
udm <- apply(dm, 1, function(i)length(unique))
if (!all(udm) == 1) {
error("as.array", "cannot make an array from rasters with different dimensions")
}
a <- array(NA, c(dm[,1], n))
dimnames(a) <- list(NULL, NULL, NULL, names(x))
for (i in 1:n) {
a[,,,i] <- as.array(x[i])
}
a
}
)
# to sf from SpatVector
# available in sf
#.v2sf <- function(from) {
# txt <- 'sf::st_as_sf(as.data.frame(from, geom=TRUE), wkt="geometry", crs=from@pntr$get_crs("wkt"))'
# eval(parse(text = txt))
#}
# sf bbox
.ext_from_sf <- function(from) {
sfi <- attr(from, "sf_column")
geom <- from[[sfi]]
e <- attr(geom, "bbox")
ext(e[c(1,3,2,4)])
}
.from_sf <- function(from, geom, sfi) {
crs <- attr(geom, "crs")$wkt
if (is.na(crs)) crs <- ""
#geom <- st_as_text(geom)
#v <- vect(geom, crs=crs)
v <- vect()
v@pntr <- v@pntr$from_hex(sf::rawToHex(sf::st_as_binary(geom)), crs)
v <- messages(v, "SpatVector from sf")
if (ncol(from) > 1) {
from[[sfi]] <- NULL
values(v) <- as.data.frame(from)
}
v
}
.svc_from_sf <- function(from) {
sfi <- attr(from, "sf_column")
geom <- from[[sfi]]
crs <- attr(geom, "crs")$wkt
if (is.na(crs)) crs <- ""
#geom <- st_as_text(geom)
#v <- vect(geom, crs=crs)
v <- svc()
v@pntr <- v@pntr$from_hex_col(sf::rawToHex(sf::st_as_binary(geom)), crs)
#if (ncol(from) > 1) {
# from[[sfi]] <- NULL
# values(v) <- as.data.frame(from)
#}
v
}
setAs("sf", "SpatRaster",
function(from) {
e <- ext(from)
rast(e)
}
)
setAs("sf", "SpatVector",
function(from) {
sfi <- attr(from, "sf_column")
if (is.null("sfi")) {
error("as,sf", "the object has no sf_column")
}
geom <- from[[sfi]]
if (inherits(geom, "list")) {
error("as,sf", "the geometry column is not valid (perhaps first load the sf package)")
}
v <- try(.from_sf(from, geom, sfi), silent=FALSE)
if (inherits(v, "try-error")) {
error("as,sf", "coercion failed. You can try coercing via a Spatial* (sp) class")
}
v
}
)
.from_sfc <- function(from) {
v <- vect()
v@pntr <- v@pntr$from_hex(sf::rawToHex(sf::st_as_binary(from)), "")
crs(v, warn=FALSE) <- attr(from, "crs")$wkt
v
}
setAs("sfc", "SpatVector",
function(from) {
v <- try(.from_sfc(from), silent=TRUE)
if (inherits(v, "try-error")) {
error("as,sfc", "coercion failed. You can try coercing via a Spatial* (sp) class")
}
v
}
)
setAs("sfg", "SpatVector",
function(from) {
v <- try(.from_sfc(from), silent=TRUE)
if (inherits(v, "try-error")) {
error("as,sfg", "coercion failed. You can try coercing via a Spatial* (sp) class")
}
v
}
)
setAs("XY", "SpatVector",
function(from) {
v <- try(.from_sfc(from), silent=TRUE)
if (inherits(v, "try-error")) {
error("as,sfc", "coercion failed. You can try coercing via a Spatial* (sp) class")
}
v
}
)
setAs("im", "SpatRaster",
function(from) {
r <- rast(nrows=from$dim[1], ncols=from$dim[2], xmin=from$xrange[1], xmax=from$xrange[2], ymin=from$yrange[1], ymax=from$yrange[2], crs="")
values(r) <- from$v
units(r) <- from$units$singular
if (from$units$multiplier != 1) {
r <- r * from$units$multiplier
}
flip(r, direction="vertical")
}
)
setAs("SpatVector", "Spatial",
function(from) {
hasmethod <- suppressWarnings("geom,data.frame-method" %in% utils::methods("geom"))
if (!hasmethod) {
error("coerce", "first run 'library(raster)' to coerce a SpatVector to a Spatial object" )
}
g <- geom(from, df=TRUE)
geom(g, values(from), geomtype(from), as.character(crs(from, proj=TRUE)))
}
)
geom_SpatialPolygons <- function(x) {
nobs <- length(x@polygons)
objlist <- vector(mode = "list", length = nobs)
for (i in 1:nobs) {
nsubobs <- length(x@polygons[[i]]@Polygons)
ps <- list()
last <- 0
for (j in 1:nsubobs) {
if (!x@polygons[[i]]@Polygons[[j]]@hole) {
last <- last + 1
hole <- 0
} else {
hole <- max(1, last)
}
ps[[j]] <- cbind(j, x@polygons[[i]]@Polygons[[j]]@coords, hole)
}
objlist[[i]] <- cbind(i, do.call(rbind, ps))
}
do.call(rbind, objlist)
}
geom_SpatialLines <- function(x) {
nobs <- length(x@lines)
objlist <- vector(mode = "list", length = nobs)
for (i in 1:nobs) {
nsubobj <- length(x@lines[[i]]@Lines)
ps <- lapply(1:nsubobj, function(j) cbind(j, x@lines[[i]]@Lines[[j]]@coords))
objlist[[i]] <- cbind(i, do.call(rbind, ps))
}
do.call(rbind, objlist)
}
setAs("Spatial", "SpatVector",
function(from) {
if (inherits(from, "SpatialPolygons")) {
g <- geom_SpatialPolygons(from)
vtype <- "polygons"
} else if (inherits(from, "SpatialLines")) {
g <- geom_SpatialLines(from)
vtype <- "lines"
} else if (inherits(from, "SpatialPoints")) {
g <- from@coords[,1:2,drop=FALSE]
vtype <- "points"
} else {
error("coerce", "cannot coerce this object to a SpatVector")
}
#the below can change the proj-string when going back to sp
#crs <- attr(from@proj4string, "comment")
#if (is.null(crs))
crs <- from@proj4string@projargs
if (methods::.hasSlot(from, "data")) {
vect(g, vtype, from@data, crs=crs)
} else {
vect(g, vtype, crs=crs)
}
}
)
setAs("SpatialGrid", "SpatRaster",
function(from){
prj <- attr(from@proj4string, "comment")
if (is.null(prj)) prj <- from@proj4string@projargs
b <- rast(ext=as.vector(t(from@bbox)), nrow=from@grid@cells.dim[2], ncol=from@grid@cells.dim[1], crs=prj)
if (inherits(from, "SpatialGridDataFrame")) {
cls <- sapply(from@data, function(i) class(i)[1])
if (all(cls == "numeric")) {
nlyr(b) <- ncol(from@data)
b <- setValues(b, as.matrix(from@data))
} else {
x <- vector(mode="list", length=ncol(from@data))
for (i in 1:ncol(from@data)) {
x[[i]] <- setValues(b, from@data[,i])
}
b <- rast(x)
}
names(b) <- colnames(from@data)
} else {
dim(b) <- c(from@grid@cells.dim[2], from@grid@cells.dim[1])
}
b
}
)
setAs("SpatialPixels", "SpatRaster",
function(from){
if (methods::.hasSlot(from, "data")) {
as(as(from, "SpatialGridDataFrame"), "SpatRaster")
} else {
as(as(from, "SpatialGrid"), "SpatRaster")
}
}
)
terra/R/expand.R 0000644 0001762 0000144 00000002576 14726700274 013215 0 ustar ligges users
setMethod("extend", signature(x="SpatExtent"),
function(x, y) {
if (length(y) == 1) {
y <- rep(y, 4)
} else if (length(y) == 2) {
y <- rep(y, each=2)
} else if (! length(y) == 4 ) {
error("extend", 'argument "y" should be a vector of 1, 2, or 4 elements')
}
y <- abs(y)
e <- as.vector(x)
e[1] <- e[1] - y[1]
e[2] <- e[2] + y[2]
e[3] <- e[3] - y[3]
e[4] <- e[4] + y[4]
ext(e)
}
)
setMethod("extend", signature(x="SpatRaster"),
function(x, y, snap="near", fill=NA, filename="", overwrite=FALSE, ...) {
if (!inherits(y, "SpatExtent")) {
if (is.vector(y)) {
stopifnot(all(y >= 0))
rs <- res(x)
e <- as.vector(ext(x))
if (length(y) <= 2) {
y <- rep_len(round(y), 2)
adj <- rev(y) * rs
e[1] <- e[1] - adj[1]
e[2] <- e[2] + adj[1]
e[3] <- e[3] - adj[2]
e[4] <- e[4] + adj[2]
} else if (length(y) == 4) {
e[1] <- e[1] - y[1] * rs[1]
e[2] <- e[2] + y[2] * rs[1]
e[3] <- e[3] - y[3] * rs[2]
e[4] <- e[4] + y[4] * rs[2]
} else {
error("extend", "if 'y' is a vector it should have 1, 2, or 4 numbers")
}
y <- ext(e)
} else {
test <- try ( y <- ext(y), silent=TRUE )
if (inherits(test, "try-error")) {
error("extend", "cannot get a SpatExtent object from argument y")
}
}
}
opt <- spatOptions(filename, overwrite, ...)
x@pntr <- x@pntr$expand(y@pntr, snap[1], fill[1], opt)
messages(x, "extend")
}
)
terra/R/spatvec.R 0000644 0001762 0000144 00000012376 14731656575 013414 0 ustar ligges users
setMethod("geomtype", signature(x="SpatVector"),
function(x){
x@pntr$type()
}
)
setMethod("geomtype", signature(x="SpatVectorProxy"),
function(x){
x@pntr$v$type()
}
)
setMethod("datatype", signature(x="SpatVector"),
function(x){
x@pntr$df$get_datatypes()
}
)
setMethod("is.lines", signature(x="SpatVector"),
function(x) {
geomtype(x) == "lines"
}
)
setMethod("is.polygons", signature(x="SpatVector"),
function(x) {
geomtype(x) == "polygons"
}
)
setMethod("is.points", signature(x="SpatVector"),
function(x) {
grepl("points", geomtype(x))
}
)
setMethod("geomtype", signature(x="Spatial"),
function(x){
type <- sub("spatial", "", as.vector(tolower(class(x)[1])))
type <- sub("dataframe", "", type)
if (type %in% c("grid", "pixels")) type <- "raster"
type
}
)
setMethod("geom", signature(x="SpatVector"),
function(x, wkt=FALSE, hex=FALSE, wkb=FALSE, df=FALSE, list=FALSE, xnm="x", ynm="y"){
if (hex) {
x@pntr$hex()
} else if (wkt) {
x@pntr$getGeometryWKT()
# or via geos with
# x@pntr$wkt()
} else if (list) {
x@pntr$get_geometryList(xnm, ynm)
} else if (wkb) {
x@pntr$wkb_raw()
} else {
g <- x@pntr$get_geometry()
g <- do.call(cbind, g)
colnames(g) <- c("geom", "part", "x", "y", "hole")[1:ncol(g)]
if (df) {
data.frame(g)
} else {
g
}
}
}
)
setMethod("crds", signature(x="SpatVector"),
function(x, df=FALSE, list=FALSE){
if (list) {
gt <- geomtype(x)
if (gt == "lines") {
x@pntr$linesNA()
} else if (gt == "polygons") {
x@pntr$polygonsList()
} else {
x@pntr$coordinates()
}
} else {
g <- x@pntr$coordinates()
g <- do.call(cbind, g)
colnames(g) <- c("x", "y")
if (df) {
data.frame(g)
} else {
g
}
}
}
)
setMethod("crds", signature(x="SpatRaster"),
function(x, df=FALSE, na.rm=TRUE, na.all=FALSE){
# crds( as.points(x, values=(hasValues(x) || (na.rm)), na.rm=na.rm, na.all=na.all), df=df)
opt <- spatOptions()
out <- x@pntr$crds(na.rm, na.all, opt)
messages(x)
if (df) {
out <- data.frame(out)
} else {
out <- do.call(cbind, out)
}
colnames(out) <- c("x", "y")
out
}
)
setMethod("dim", signature(x="SpatVector"),
function(x){
c(nrow(x), ncol(x))
}
)
setMethod("dim", signature(x="SpatVectorProxy"),
function(x){
c(x@pntr$v$geom_count, x@pntr$v$ncol())
}
)
as.data.frame.SpatVector <- function(x, row.names=NULL, optional=FALSE, geom=NULL, ...) {
d <- .getSpatDF(x@pntr$df, ...)
# fix empty names
colnames(d)[1:ncol(x)] <- x@pntr$names
if (!is.null(geom)) {
geom <- match.arg(toupper(geom), c("WKT", "HEX", "XY"))
if (geom == "XY") {
if (!grepl("points", geomtype(x))) {
error("as.data.frame", 'geom="XY" is only valid for point geometries')
}
if (nrow(d) > 0) {
d <- cbind(d, crds(x))
} else {
d <- data.frame(crds(x), ...)
}
} else {
g <- geom(x, wkt=geom=="WKT", hex=geom=="HEX")
if (nrow(d) > 0) {
d$geometry <- g
} else {
d <- data.frame(geometry=g, stringsAsFactors=FALSE, ...)
}
}
}
d
}
setMethod("as.data.frame", signature(x="SpatVector"), as.data.frame.SpatVector)
get.data.frame <- function(x) {
v <- vect()
v@pntr <- x@pntr$v
d <- as.data.frame(v)
d[0,,drop=FALSE]
}
as.list.SpatVector <- function(x, geom=NULL, ...) {
as.list(as.data.frame(x, geom=geom))
}
setMethod("as.list", signature(x="SpatVector"), as.list.SpatVector)
setMethod ("expanse", "SpatVector",
function(x, unit="m", transform=TRUE) {
a <- x@pntr$area(unit, transform, double());
x <- messages(x, "expanse");
return(abs(a))
}
)
setMethod("perim", signature(x="SpatVector"),
function(x) {
p <- x@pntr$length();
x <- messages(x, "perim");
p
}
)
setMethod("nseg", signature(x="SpatVector"),
function(x) {
p <- x@pntr$nsegments();
x <- messages(x, "nseg");
p
}
)
setMethod("length", signature(x="SpatVector"),
function(x) {
x@pntr$size()
}
)
setMethod("fillHoles", signature(x="SpatVector"),
function(x, inverse=FALSE) {
if (inverse) {
x@pntr <- x@pntr$get_holes()
} else {
x@pntr <- x@pntr$remove_holes()
}
messages(x, "fillHoles")
}
)
#setMethod("eliminate", signature(x="SpatVector"),
# function(x, y) {
# x@pntr <- x@pntr$eliminate(y@pntr)
# messages(x)
# }
#)
setMethod("centroids", signature(x="SpatVector"),
function(x, inside=FALSE) {
if (inside) {
x@pntr <- x@pntr$point_on_surface(TRUE)
} else {
x@pntr <- x@pntr$centroid(TRUE)
}
messages(x, "centroids")
}
)
setMethod("densify", signature(x="SpatVector"),
function(x, interval, equalize=TRUE, flat=FALSE) {
x@pntr <- x@pntr$densify(interval, equalize, flat)
messages(x, "densify")
}
)
setMethod("normalize.longitude", signature(x="SpatVector"),
function(x) {
if (nrow(x) == 0) return(deepcopy(x))
nc <- ncol(x)
fname <- "uuu-_123_uqq_-agg_-id123"
x[[fname]] <- 1:nrow(x)
d <- values(x)
out <- x[,fname]
out@pntr <- out@pntr$normalize_longitude()
out <- messages(out)
a <- aggregate(out, fname, count=FALSE)
if (nc > 0) {
a <- merge(a, d, by=fname)
}
a[[fname]] <- NULL
a
}
)
terra/R/values.R 0000644 0001762 0000144 00000034120 14746055732 013227 0 ustar ligges users # Author: Robert J. Hijmans
# Date : June 2018
# Version 0.9
# License GPL v3
setMethod("hasValues", signature(x="SpatRaster"),
function(x) {
x@pntr$hasValues
}
)
.makeDataFrame <- function(x, v, ...) {
v <- data.frame(v, check.names=FALSE, ...)
# factors=TRUE,
# if (factors) {
ff <- is.factor(x)
if (any(ff)) {
fs <- which(ff)
cgs <- levels(x)
for (f in fs) {
cg <- cgs[[f]]
i <- match(v[,f], cg[,1])
if (!inherits(cg[[2]], "numeric")) {
v[[f]] <- factor(cg[i, 2], levels=unique(cg[[2]]))
} else {
v[[f]] <- cg[i, 2]
}
}
}
bb <- is.bool(x)
if (any(bb)) {
for (b in which(bb)) {
v[[b]] = as.logical(v[[b]])
}
}
ii <- (is.int(x) & (!ff) & (substr(datatype(x, TRUE), 1, 4) != "INT8"))
if (any(ii)) {
for (i in which(ii)) {
v[[i]] = as.integer(v[[i]])
}
}
dd <- !(bb | ii | ff)
if (any(dd)) {
d <- which(dd)
v[,d] <- replace(v[,d], is.na(v[,d]), NA)
}
v
}
setMethod("readValues", signature(x="SpatRaster"),
function(x, row=1, nrows=nrow(x), col=1, ncols=ncol(x), mat=FALSE, dataframe=FALSE, ...) {
stopifnot(row > 0 && nrows > 0)
stopifnot(col > 0 && ncols > 0)
v <- x@pntr$readValues(row-1, nrows, col-1, ncols)
messages(x, "readValues")
if (dataframe) {
v <- matrix(v, ncol = nlyr(x))
colnames(v) <- names(x)
return(.makeDataFrame(x, v, ...) )
} else if (mat) {
if (all(is.int(x))) {
v <- matrix(as.integer(v), ncol = nlyr(x))
} else if (all(is.bool(x))) {
v <- matrix(as.logical(v), ncol = nlyr(x))
} else {
v <- matrix(v, ncol = nlyr(x))
}
colnames(v) <- names(x)
} else if (all(is.int(x))) {
v <- as.integer(v)
} else if (all(is.bool(x))) {
v <- as.logical(v)
}
v
}
)
setMethod("readValues", signature(x="SpatRasterDataset"),
function(x, row=1, nrows=nrow(x), col=1, ncols=ncol(x), mat=FALSE, dataframe=FALSE, ...) {
lapply(1:length(x), function(i) readValues(x[i], row, nrows, 1, ncols, mat=mat, dataframe=dataframe, ...))
}
)
setMethod("values", signature(x="SpatRaster"),
function(x, mat=TRUE, dataframe=FALSE, row=1, nrows=nrow(x), col=1, ncols=ncol(x), na.rm=FALSE, ...) {
readStart(x)
on.exit(readStop(x))
v <- readValues(x, row, nrows, col, ncols, mat=mat, dataframe=dataframe, ...)
messages(x, "values")
if (na.rm) {
if (!is.null(dim(v))) {
v[stats::complete.cases(v), , drop=FALSE]
} else {
v[!is.na(v)]
}
} else {
v
}
}
)
setMethod("values<-", signature("SpatRaster", "ANY"),
function(x, value) {
setValues(x, value, keepnames=TRUE)
}
)
setMethod("focalValues", signature("SpatRaster"),
function(x, w=3, row=1, nrows=nrow(x), fill=NA) {
if (is.matrix(w)) {
#m <- as.vector(t(w))
w <- dim(w)
} else {
w <- rep_len(w, 2)
}
readStart(x)
on.exit(readStop(x))
opt <- spatOptions()
m <- matrix(x@pntr$focalValues(w, fill, max(0, row-1), nrows, opt), ncol=prod(w), byrow=TRUE)
messages(x, "focalValues")
m
}
)
mtrans <- function(mm, nc) {
v <- NULL
n <- ncol(mm) / nc
for (i in 1:n) {
j <- 1:nc + (i-1)*nc
v <- c(v, as.vector(t(mm[, j])))
}
v
}
setMethod("setValues", signature("SpatRaster"),
function(x, values, keeptime=TRUE, keepunits=TRUE, keepnames=FALSE, props=FALSE) {
y <- rast(x, keeptime=keeptime, keepunits=keepunits, props=props)
if (is.data.frame(values)) {
# needs improvement to deal with mixed data types
values <- as.matrix(values)
}
if (is.matrix(values)) {
nl <- nlyr(x)
d <- dim(values)
if (!all(d == c(ncell(x), nl))) {
ncx <- ncol(x)
if ((d[1] == nrow(x)) && ((d[2] %% nl*ncx) == 0)) {
# raster-shaped matrix
if (ncx < d[2]) {
values <- mtrans(values, ncx)
} else {
values <- as.vector(t(values))
}
} else if ((d[2] == nl) && (d[1] < ncell(x))) {
if (d[1] > 1) warn("setValues", "values were recycled")
values <- as.vector(apply(values, 2, function(i) rep_len(i, ncell(x))))
} else {
error("setValues","dimensions of the matrix do not match the SpatRaster")
}
}
if (!keepnames) {
nms <- colnames(values)
if (!is.null(nms)) names(y) <- nms
}
} else if (is.array(values)) {
stopifnot(length(dim(values)) == 3)
values <- as.vector(aperm(values, c(2,1,3)))
}
make_factor <- FALSE
set_coltab <- FALSE
if (is.character(values)) {
if (all(substr(stats::na.omit(values), 1, 1) == "#")) {
fv <- as.factor(values)
if (length(levels(fv)) <= 256) {
values <- as.integer(fv) #-1
fv <- levels(fv)
set_coltab <- TRUE
} else {
fv <- NULL
values <- t(grDevices::col2rgb(values))
y <- rast(y, nlyr=3, names=c("red", "green", "blue"))
RGB(y) <- 1:3
}
} else {
values <- as.factor(values)
levs <- levels(values)
values <- as.integer(values) # -1 not needed anymore?
make_factor <- TRUE
}
} else if (is.factor(values)) {
levs <- levels(values)
values <- as.integer(values)# - 1
make_factor <- TRUE
}
if (!(is.numeric(values) || is.integer(values) || is.logical(values))) {
error("setValues", "values must be numeric, integer, logical, factor or character")
}
lv <- length(values)
nc <- ncell(y)
nl <- nlyr(y)
opt <- spatOptions()
if (lv == 1) {
y@pntr$setValues(values, opt)
} else {
if (lv > (nc * nl)) {
warn("setValues", "values is larger than the size of cells")
values <- values[1:(nc*nl)]
} else if (lv < (nc * nl)) {
warn("setValues", "values were recycled")
values <- rep(values, length.out=nc*nl)
}
y@pntr$setValues(values, opt)
}
y <- messages(y, "setValues")
if (make_factor) {
for (i in 1:nlyr(y)) {
levs <- data.frame(value=1:length(levs), label=levs)
set.cats(y, i, levs)
}
names(y) <- names(x)
}
if (set_coltab) {
coltab(y) <- fv
} else if (is.logical(values)) {
if (!all(is.na(values))) y@pntr$setValueType(3)
} else if (is.integer(values)) {
y@pntr$setValueType(1)
}
y
}
)
setMethod("inMemory", signature(x="SpatRaster"),
function(x, bylayer=FALSE) {
r <- x@pntr$inMemory
if (bylayer) {
nl <- .nlyrBySource(x)
r <- rep(r, nl)
}
r
}
)
#..hasValues <- function(x) { x@pntr$hasValues}
#..inMemory <- function(x) { x@pntr$inMemory }
#..filenames <- function(x) { x@pntr$filenames }
subsetSource <- function(x, i) {
x@pntr <- x@pntr$subsetSource(i-1)
messages(x)
}
setMethod("sources", signature(x="SpatRaster"),
function(x, nlyr=FALSE, bands=FALSE) {
src <- x@pntr$filenames()
Encoding(src) <- "UTF-8"
if (bands) {
nls <- x@pntr$nlyrBySource()
d <- data.frame(sid=rep(1:length(src), nls),
source=rep(src, nls),
bands=x@pntr$getBands()+1, stringsAsFactors=FALSE)
if (nlyr) {
d$nlyr <- rep(nls, nls)
}
d
} else if (nlyr) {
data.frame(source=src, nlyr=x@pntr$nlyrBySource(), stringsAsFactors=FALSE)
} else {
src
}
}
)
setMethod("sources", signature(x="SpatRasterCollection"),
function(x, nlyr=FALSE, bands=FALSE) {
if (nlyr | bands) {
x <- lapply(x, function(i) sources(i, nlyr, bands))
x <- lapply(1:length(x), function(i) cbind(cid=i, x[[i]]))
do.call(rbind, x)
} else {
sapply(x, sources)
}
}
)
setMethod("sources", signature(x="SpatRasterDataset"),
function(x, nlyr=FALSE, bands=FALSE) {
if (nlyr | bands) {
x <- lapply(x, function(i) sources(i, nlyr, bands))
x <- lapply(1:length(x), function(i) cbind(cid=i, x[[i]]))
do.call(rbind, x)
} else {
x@pntr$filenames()
}
}
)
setMethod("sources", signature(x="SpatVector"),
function(x) {
if (x@pntr$source != "") {
if (x@pntr$layer != tools::file_path_sans_ext(basename(x@pntr$source))) {
paste0(x@pntr$source, "::", x@pntr$layer)
} else {
x@pntr$source
}
} else {
""
}
}
)
setMethod("sources", signature(x="SpatVectorProxy"),
function(x) {
if (x@pntr$v$layer != tools::file_path_sans_ext(basename(x@pntr$v$source))) {
paste0(x@pntr$v$source, "::", x@pntr$v$layer)
} else {
x@pntr$v$source
}
}
)
setMethod("hasMinMax", signature(x="SpatRaster"),
function(x) {
x@pntr$hasRange
}
)
setMethod("minmax", signature(x="SpatRaster"),
function(x, compute=FALSE) {
have <- x@pntr$hasRange
if (!all(have)) {
if (compute) {
opt <- spatOptions()
x@pntr$setRange(opt, FALSE)
} else {
warn("minmax", "min and max values not available for all layers. See 'setMinMax' or 'global'")
}
}
r <- rbind(x@pntr$range_min, x@pntr$range_max)
if (!compute) {
r[,!have] <- c(Inf, -Inf)
}
colnames(r) <- names(x)
rownames(r) <- c("min", "max")
r
}
)
setMethod("setMinMax", signature(x="SpatRaster"),
function(x, force=FALSE) {
opt <- spatOptions()
if (force) {
x@pntr$setRange(opt, TRUE)
} else if (!all(hasMinMax(x))) {
x@pntr$setRange(opt, FALSE)
}
x <- messages(x, "setMinMax")
}
)
setMethod("compareGeom", signature(x="SpatRaster", y="SpatRaster"),
function(x, y, ..., lyrs=FALSE, crs=TRUE, warncrs=FALSE, ext=TRUE, rowcol=TRUE, res=FALSE, stopOnError=TRUE, messages=FALSE) {
opt <- spatOptions("")
out <- x@pntr$compare_geom(y@pntr, lyrs, crs, opt$tolerance, warncrs, ext, rowcol, res)
if (stopOnError) {
messages(x, "compareGeom")
} else {
m <- NULL
if (x@pntr$has_warning()) {
m <- x@pntr$getWarnings()
}
if (x@pntr$has_error()) {
m <- c(m, x@pntr$getError())
}
if (!is.null(m) && messages) {
message(paste(m, collapse="\n"))
}
}
dots <- list(...)
if (length(dots) > 0) {
for (i in 1:length(dots)) {
if (!inherits(dots[[i]], "SpatRaster")) {
error("compareGeom", "all additional arguments must be a SpatRaster")
}
out <- out &
compareGeom(x, dots[[i]], lyrs=lyrs, crs=crs, warncrs=warncrs, ext=ext, rowcol=rowcol, res=res, stopOnError=stopOnError, messages=messages)
}
}
out
}
)
setMethod("compareGeom", signature(x="SpatRaster", y="list"),
function(x, y, ..., lyrs=FALSE, crs=TRUE, warncrs=FALSE, ext=TRUE, rowcol=TRUE, res=FALSE, stopOnError=TRUE, messages=FALSE) {
dots <- list(...)
if (length(dots) > 0) {
y <- c(y, dots)
}
isr <- sapply(y, inherits, "SpatRaster")
if (!all(isr)) {
y <- y[isr]
if (length(y) == 0) error("compareGeom", "none of the elements of y is a SpatRaster")
n <- sum(!isr)
if (n > 1) {
warn("compareGeom", paste(n, "elements of y are not a SpatRaster"))
} else {
warn("compareGeom", paste("1 element of y is not a SpatRaster"))
}
}
out <- sapply(y, compareGeom, y=x, lyrs=lyrs, crs=crs, warncrs=warncrs, ext=ext, rowcol=rowcol, res=res, stopOnError=stopOnError, messages=messages)
if (!all(isr)) {
res <- rep(NA, length(isr))
res[isr] <- out
return(res)
}
all(out)
}
)
setMethod("compareGeom", signature(x="SpatRasterCollection", y="missing"),
function(x, y, ..., lyrs=FALSE, crs=TRUE, warncrs=FALSE, ext=TRUE, rowcol=TRUE, res=FALSE, stopOnError=FALSE, messages=FALSE) {
x <- as.list(x)
dots <- list(...)
if (length(dots) > 0) {
error("compareGeom", "when x is a SpatRasterCollection, additional arguments are ignored")
}
if (length(x) == 1) return(TRUE)
out <- sapply(x[-1], compareGeom, y=x[1], lyrs=lyrs, crs=crs, warncrs=warncrs, ext=ext, rowcol=rowcol, res=res, stopOnError=stopOnError, messages=messages)
out
}
)
setMethod("compareGeom", signature(x="SpatRaster", y="SpatRasterCollection"),
function(x, y, ..., lyrs=FALSE, crs=TRUE, warncrs=FALSE, ext=TRUE, rowcol=TRUE, res=FALSE, stopOnError=FALSE, messages=FALSE) {
dots <- list(...)
if (length(dots) > 0) {
error("compareGeom", "when y is a SpatRasterCollection, additional arguments are ignored")
}
out <- sapply(as.list(y), compareGeom, y=x, lyrs=lyrs, crs=crs, warncrs=warncrs, ext=ext, rowcol=rowcol, res=res, stopOnError=stopOnError, messages=messages)
all(out)
}
)
setMethod("compareGeom", signature(x="SpatVector", y="SpatVector"),
function(x, y, tolerance=0) {
out <- x@pntr$equals_between(y@pntr, tolerance)
x <- messages(x, "compareGeom")
out[out == 2] <- NA
matrix(as.logical(out), nrow=nrow(x), byrow=TRUE)
}
)
setMethod("compareGeom", signature(x="SpatVector", y="missing"),
function(x, y, tolerance=0) {
symmetrical=FALSE # this is inefficient
out <- x@pntr$equals_within(symmetrical, tolerance)
x <- messages(x, "compareGeom")
out[out == 2] <- NA
out <- matrix(as.logical(out), nrow=nrow(x), byrow=TRUE)
out
}
)
setMethod("all.equal", signature(target="SpatRaster", current="SpatRaster"),
function(target, current, maxcell=100000, ...) {
a <- base::all.equal(rast(target), rast(current))
maxcell <- round(maxcell)
if (isTRUE(a) && maxcell > 0) {
hvT <- hasValues(target)
hvC <- hasValues(current)
if (hvT && hvC) {
if (maxcell < ncell(target)) {
warn(paste("all.equal", "taking a sample of ", maxcell, "cells"))
s1 <- spatSample(current, maxcell, "regular")
s2 <- spatSample(target, maxcell, "regular")
} else {
s1 <- values(current)
s2 <- values(target)
}
a <- all.equal(s1, s2, ...)
} else if (hvT || hvC) {
if (hvT) {
a <- "target has cell values, current does not"
} else {
a <- "current has cell values, target does not"
}
}
}
a
}
)
setMethod("identical", signature(x="SpatRaster", y="SpatRaster"),
function(x, y) {
a <- isTRUE(all.equal(x, y, maxcell=0))
if (a && hasValues(x)) {
v <- unique(unlist(unique(x - y) ))
a <- identical(v, 0)
}
a
}
)
setMethod("values", signature("SpatVector"),
function(x, ...) {
as.data.frame(x, ...)
}
)
setMethod("values<-", signature("SpatVector", "data.frame"),
function(x, value) {
x@pntr <- x@pntr$deepcopy()
if (ncol(value) == 0) {
x@pntr$remove_df()
return(x)
}
value <- .makeSpatDF(value)
x@pntr$set_df(value)
messages(x)
}
)
setMethod("values<-", signature("SpatVector", "matrix"),
function(x, value) {
`values<-`(x, data.frame(value))
}
)
setMethod("values<-", signature("SpatVector", "ANY"),
function(x, value) {
if (!is.vector(value)) {
error("values<-", "the values must be a data.frame, matrix or vector")
}
value <- rep(value, length.out=nrow(x))
value <- data.frame(value=value)
`values<-`(x, data.frame(value))
}
)
setMethod("values<-", signature("SpatVector", "NULL"),
function(x, value) {
x@pntr <- x@pntr$deepcopy()
x@pntr$remove_df()
x
}
)
setMethod("setValues", signature("SpatVector"),
function(x, values) {
x@pntr <- x@pntr$deepcopy()
`values<-`(x, values)
}
)
terra/R/options.R 0000644 0001762 0000144 00000012304 14753274500 013415 0 ustar ligges users
.terra_environment <- new.env(parent=emptyenv())
.create_options <- function() {
opt <- methods::new("SpatOptions")
opt@pntr <- SpatOptions$new()
# check=T does not exist in ancient R
tmpdir <- try(tempdir(check = TRUE), silent=TRUE)
opt@pntr$tempdir <- normalizePath(tempdir(), winslash="/")
.terra_environment$options <- opt
.terra_environment$devs <- NULL
.terra_environment$RStudio_warned <- FALSE
x <- options("terra_default")[[1]]
if (!is.null(x)) {
do.call(terraOptions, x)
}
}
.option_names <- function() {
c("progress", "progressbar", "tempdir", "memfrac", "memmax", "memmin", "datatype", "filetype", "filenames", "overwrite", "todisk", "names", "verbose", "NAflag", "statistics", "steps", "ncopies", "tolerance", "tmpfile", "threads", "scale", "offset") #, "append")
}
.setOptions <- function(x, wopt) {
nms <- names(wopt)
g <- which(nms == "gdal")
if (length(g) > 0) {
gopt <- unlist(wopt[g])
wopt <- wopt[-g]
nms <- nms[-g]
i <- grep("=", gopt)
gopt <- gopt[i]
gopt <- gsub(" ", "", gopt)
x$gdal_options <- gopt
}
s <- nms %in% .option_names()
if (any(!s)) {
bad <- paste(nms[!s], collapse=",")
error("write", "unknown option(s): ", bad)
}
if (any(s)) {
nms <- nms[s]
wopt <- wopt[s]
i <- which(nms == "names")
if (length(i) > 0) {
namevs <- trimws(unlist(strsplit(as.character(wopt[[i]]), ",")))
x[["names"]] <- namevs
wopt <- wopt[-i]
nms <- nms[-i]
}
if ("tempdir" %in% nms) {
i <- which(nms == "tempdir")
if (!dir.exists(wopt[[i]])) {
warn("options", "you cannot set the tempdir to a path that does not exist")
wopt <- wopt[-i]
nms <- nms[-i]
}
}
for (i in seq_along(nms)) {
x[[nms[i]]] <- wopt[[i]]
}
}
if (x$has_warning()) {
warn("options", paste(x$getWarnings(), collapse="\n"))
}
if (x$has_error()) {
error("options", x$getError())
}
x
}
defaultOptions <- function() {
## work around onLoad problem
if (is.null(.terra_environment$options)) .create_options()
.terra_environment$options@pntr$deepcopy()
}
spatOptions <- function(filename="", overwrite=FALSE, ..., wopt=NULL) {
wopt <- c(list(...), wopt)
## work around onLoad problem
if (is.null(.terra_environment$options)) .create_options()
opt <- .terra_environment$options@pntr$deepcopy()
opt$tmpfile <- paste0(gsub("^file", "", basename(tempfile())), "_", Sys.getpid())
filename <- .fullFilename(filename, mustExist=TRUE)
if (!is.null(unlist(wopt))) {
wopt$filenames <- filename
wopt$overwrite <- overwrite[1]
opt <- .setOptions(opt, wopt)
} else {
opt$filenames <- filename
opt$overwrite <- overwrite[1]
}
#messages(opt)
#opt$todisk <- TRUE
opt
}
#..getOptions <- function() {
# spatOptions("", TRUE, list())
#}
#..showOptions <- function(opt) {
# cat("Options for package 'terra'\n")
# cat("memfrac :" , opt$memfrac, "\n")
# cat("tempdir :" , opt$tempdir, "\n")
# cat("datatype :" , opt$def_datatype, "\n")
# cat("filetype :" , opt$def_filetype, "\n")
# cat("progress :" , opt$progress, "\n")
# cat("verbose :" , opt$verbose, "\n")
# if (opt$todisk) {
# cat("todisk :" , opt$todisk, "\n")
# }
#}
.getOptions <- function() {
opt <- spatOptions()
nms <- names(opt)
nms <- nms[!grepl("^\\.", nms)]
nms <- nms[!(nms %in% c("initialize", "messages", "getClass", "finalize", "datatype_set", "tmpfile", "statistics", "gdal_options", "scale", "offset", "threads", "filenames", "NAflag"))]
defnms <- grepl("^def_", nms)
nms <- nms[!defnms]
out <- sapply(nms, function(n) eval(parse(text=paste0("opt$", n))))
out$memmin <- 8 * out$memmin / (1024^3)
if (out$memmax > 0) {
out$memmax <- 8 * out$memmax / (1024^3)
}
out
}
.showOptions <- function(opt, print=TRUE) {
out <- .getOptions()
if (!print) return(out)
nms <- c("memfrac", "tempdir", "datatype", "progress", "todisk", "verbose", "tolerance", "memmin", "memmax")
p <- out[names(out) %in% nms]
if (p$memmax <= 0) p$memmax <- NULL
nms <- names(p)
for (i in seq_along(nms)) {
cat(paste0(substr(paste(nms[i], " "), 1, 10), ": ", p[i], "\n"))
}
invisible(out)
}
.default_option_names <- function() {
c("datatype", "filetype") #, "verbose")
}
terraOptions <- function(..., print=TRUE) {
dots <- list(...)
if (is.null(.terra_environment$options)) .create_options()
opt <- .terra_environment$options@pntr
nms <- names(dots)
if (length(dots) == 0) {
return(.showOptions(opt, print=print))
}
ok <- nms %in% .option_names()
if (any(!ok)) {
bad <- paste(nms[!ok], collapse=", ")
warn("terraOptions<-", paste("unknown option(s):", bad))
dots <- dots[ok]
nms <- nms[ok]
if (length(dots) == 0) return(invisible())
}
if ("tempdir" %in% nms) {
i <- which(nms == "tempdir")
dots[i] <- path.expand(trimws(dots[i]))
if (!dir.exists(dots[[i]])) {
warn("options", "you cannot set the tempdir to a path that does not exist")
dots <- dots[-i]
nms <- nms[-i]
if (length(dots) == 0) return(invisible())
}
}
d <- nms %in% .default_option_names()
dnms <- paste0("def_", nms)
for (i in 1:length(nms)) {
if (d[i]) {
opt[[ dnms[i] ]] <- dots[[ i ]]
} else {
opt[[ nms[i] ]] <- dots[[ i ]]
}
}
if ("memfrac" %in% nms) {
if (dots$memfrac > 0.9) {
warn("terraOptions", "memfrac > 0.9")
}
}
.terra_environment$options@pntr <- opt
}
terra/R/Arith_generics.R 0000644 0001762 0000144 00000042465 14726700273 014664 0 ustar ligges users # Author: Robert J. Hijmans
# Date : September 2018
# Version 1.0
# License GPL v3
setMethod("Arith", signature(e1="SpatExtent", e2="numeric"),
function(e1, e2){
oper <- as.vector(.Generic)[1]
if (oper == "%%") {
e1@pntr <- e1@pntr$align(e2[1], "")
} else if (oper == "+") {
e2 <- rep_len(e2, 4)
e2[c(1,3)] <- -e2[c(1,3)]
e1 <- ext(as.vector(e1) + e2)
} else if (oper == "-") {
e2 <- rep_len(e2, 4)
e2[c(1,3)] <- -e2[c(1,3)]
e1 <- ext(as.vector(e1) - e2)
} else if (oper == "*") {
e2 <- abs(rep_len(e2, 4))
e1 <- as.vector(e1)
dx <- (e1[2] - e1[1])
dy <- (e1[4] - e1[3])
mx <- e1[1] + dx/2
my <- e1[3] + dy/2
e1[1] <- mx - (dx/2)*e2[1]
e1[2] <- mx + (dx/2)*e2[2]
e1[3] <- my - (dy/2)*e2[3]
e1[4] <- my + (dy/2)*e2[4]
e1 <- ext(e1)
} else if (oper == "/") {
e2 <- abs(rep_len(e2, 4))
e1 <- as.vector(e1)
dx <- (e1[2] - e1[1])
dy <- (e1[4] - e1[3])
mx <- e1[1] + dx/2
my <- e1[3] + dy/2
e1[1] <- mx - dx/(2*e2[1])
e1[2] <- mx + dx/(2*e2[2])
e1[3] <- my - dy/(2*e2[3])
e1[4] <- my + dy/(2*e2[4])
e1 <- ext(e1)
} else {
error(oper, "only +, -, *, / and %% are supported")
}
if (!is.valid(e1)) {
error(oper, "this would create an invalid extent")
}
e1
}
)
setMethod("Arith", signature(e1="numeric", e2="SpatExtent"),
function(e1, e2) {
oper <- as.vector(.Generic)[1]
if (oper == "%%") {
error("%%", "only 'Spatextent %% numeric' (in that order) is supported")
} else if (oper == "+") {
return(e2 + e1)
} else if (oper == "-") {
error("-", "only 'Spatextent - numeric' (in that order) is supported")
} else if (oper == "*") {
return(e2 * e1)
} else if (oper == "/") {
error("/", "only 'Spatextent / numeric' (in that order) is supported")
} else {
error(oper, "only +, -, *, / and %% are supported")
}
if (!is.valid(e1)) {
error(oper, "this would create an invalid extent")
}
e1
}
)
setMethod("Arith", signature(e1="SpatExtent", e2="SpatExtent"),
function(e1, e2){
oper <- as.vector(.Generic)[1]
if (oper == "+") {
e1@pntr <- e1@pntr$deepcopy()
e1@pntr$union(e2@pntr)
} else if (oper == "*") {
e1@pntr <- e1@pntr$intersect(e2@pntr)
} else if (oper == "/") {
d <- c(diff(e1[1:2]) / diff(e2[1:2]), diff(e1[3:4]) / diff(e2[3:4]))
names(d) <- c("x", "y")
return(d)
} else {
error(oper, "only +, *, and / are supported for SpatExtent")
}
if (!is.valid(e1)) {
error(oper, "this would create an invalid extent")
}
e1
}
)
setMethod("Arith", signature(e1="SpatVector", e2="SpatVector"),
function(e1, e2){
oper <- as.vector(.Generic)[1]
if (geomtype(e1) != geomtype(e2)) {
error(oper, "geometry types do not match")
}
if (oper == "+") {
e1 <- union(e1, e2)
} else if (oper == "*") {
e1 <- intersect(e1, e2)
} else if (oper == "-") {
e1 <- erase(e1, e2)
} else {
error(oper, "only operators +, *, and - are supported for SpatVector")
}
messages(e1, oper)
}
)
setMethod("Arith", signature(e1="SpatRaster", e2="SpatRaster"),
function(e1, e2){
opt <- spatOptions()
oper <- as.vector(.Generic)[1]
e1@pntr <- e1@pntr$arith_rast(e2@pntr, oper, FALSE, opt)
messages(e1, oper)
}
)
setMethod("Arith", signature(e1="SpatRaster", e2="numeric"),
function(e1, e2){
oper <- as.vector(.Generic)[1]
opt <- spatOptions()
e1@pntr <- e1@pntr$arith_numb(e2, oper, FALSE, FALSE, opt)
messages(e1, oper)
}
)
setMethod("Arith", signature(e1="SpatRaster", e2="logical"),
function(e1, e2){
methods::callGeneric(e1, as.integer(e2))
}
)
setMethod("Arith", signature(e1="SpatRaster", e2="missing"),
function(e1, e2){
methods::callGeneric(0, e1)
}
)
setMethod("Arith", signature(e1="numeric", e2="SpatRaster"),
function(e1, e2){
oper <- as.vector(.Generic)[1]
opt <- spatOptions()
e2@pntr <- e2@pntr$arith_numb(e1, oper, TRUE, FALSE, opt)
messages(e2, oper)
}
)
setMethod("Arith", signature(e1="logical", e2="SpatRaster"),
function(e1, e2){
methods::callGeneric(as.integer(e1), e2)
}
)
setMethod("Arith", signature(e1="SpatRaster", e2="matrix"),
function(e1, e2){
oper <- as.vector(.Generic)[1]
opt <- spatOptions()
e1@pntr <- e1@pntr$arith_m(as.vector(e2), oper, dim(e2)[1:2], FALSE, opt)
messages(e1, oper)
}
)
setMethod("Arith", signature(e1="matrix", e2="SpatRaster"),
function(e1, e2){
oper <- as.vector(.Generic)[1]
opt <- spatOptions()
e1@pntr <- e1@pntr$arith_m(as.vector(e2), oper, dim(e2)[1:2], TRUE, opt)
messages(e1, oper)
}
)
setMethod("Compare", signature(e1="SpatRaster", e2="SpatRaster"),
function(e1, e2){
opt <- spatOptions()
oper <- as.vector(.Generic)[1]
e1@pntr <- e1@pntr$arith_rast(e2@pntr, oper, FALSE, opt)
messages(e1, oper)
}
)
setMethod("Compare", signature(e1="SpatRaster", e2="numeric"),
function(e1, e2){
oper <- as.vector(.Generic)[1]
opt <- spatOptions()
e1@pntr <- e1@pntr$arith_numb(e2, oper, FALSE, FALSE, opt)
messages(e1, oper)
}
)
setMethod("Compare", signature(e1="numeric", e2="SpatRaster"),
function(e1, e2){
oper <- as.vector(.Generic)[1]
opt <- spatOptions()
e2@pntr <- e2@pntr$arith_numb(e1, oper, TRUE, FALSE, opt)
messages(e2, oper)
}
)
setMethod("Compare", signature(e1="SpatRaster", e2="matrix"),
function(e1, e2){
oper <- as.vector(.Generic)[1]
opt <- spatOptions()
e1@pntr <- e1@pntr$arith_m(as.vector(e2), oper, dim(e2)[1:2], FALSE, opt)
messages(e1, oper)
}
)
setMethod("Compare", signature(e1="matrix", e2="SpatRaster"),
function(e1, e2){
oper <- as.vector(.Generic)[1]
opt <- spatOptions()
e1@pntr <- e1@pntr$arith_m(as.vector(e2), oper, dim(e2)[1:2], TRUE, opt)
messages(e1, oper)
}
)
getFactTable <- function(x, table, sender="%in%") {
if (!is.factor(x)) {
error(sender, "Can only match character values if x is categorical")
}
if (nlyr(x) != 1) {
error(sender, "matching with character values is only supported for single layer SpatRaster")
}
d <- levels(x)[[1]]
m <- stats::na.omit(match(table, d[,2]))
if (length(m) == 0) {
return(as.logical(x*0))
}
d[m,1]
}
setMethod("Compare", signature(e1="SpatRaster", e2="character"),
function(e1, e2){
oper <- as.vector(.Generic)[1]
e2 <- getCatIDs(e1, e2, "==")
if (oper != "==") {
error(oper, "only '==' is supported with categorical comparisons")
}
if (length(e2) == 0) {
return(as.logical(e1*0))
}
if (length(e2) != 1) {
error(oper, "comparisons only supported for single values (see %in% and match)")
}
opt <- spatOptions()
e1@pntr <- e1@pntr$arith_numb(e2, oper, TRUE, FALSE, opt)
messages(e1, oper)
}
)
setMethod("Logic", signature(e1="SpatRaster", e2="SpatRaster"),
function(e1, e2){
oper <- as.vector(.Generic)[1]
opt <- spatOptions()
e1@pntr <- e1@pntr$logic_rast(e2@pntr, oper, opt)
messages(e1, oper)
}
)
setMethod("Logic", signature(e1="SpatRaster", e2="numeric"),
function(e1, e2){
opt <- spatOptions()
oper <- as.vector(.Generic)[1]
e2 <- as.logical(e2)
e1@pntr <- e1@pntr$logic_numb(e2, oper, opt)
messages(e1, oper)
}
)
setMethod("Logic", signature(e1="numeric", e2="SpatRaster"),
function(e1, e2){
opt <- spatOptions()
oper <- as.vector(.Generic)[1]
e1 <- as.logical(e1)
e2@pntr <- e2@pntr$logic_numb(e1, oper, opt)
messages(e2, oper)
}
)
setMethod("Logic", signature(e1="SpatRaster", e2="logical"),
function(e1, e2){
opt <- spatOptions()
oper <- as.vector(.Generic)[1]
e1@pntr <- e1@pntr$logic_numb(e2, oper, opt)
messages(e1, oper)
}
)
setMethod("Logic", signature(e1="logical", e2="SpatRaster"),
function(e1, e2){
opt <- spatOptions()
oper <- as.vector(.Generic)[1]
e2@pntr <- e2@pntr$logic_numb(e1, oper, opt)
messages(e2, oper)
}
)
setMethod("!", signature(x="SpatRaster"),
function(x) {
x == 0
}
)
setMethod("not.na", signature(x="SpatRaster"),
function(x, falseNA=FALSE, filename="", ...) {
opt <- spatOptions(filename=filename, ...)
x@pntr <- x@pntr$not_na(falseNA, opt)
messages(x, "not.na")
}
)
setMethod("isTRUE", signature(x="SpatRaster"),
function(x) {
opt <- spatOptions()
x@pntr <- x@pntr$is_true(FALSE, opt)
messages(x, "isTRUE")
}
)
setMethod("isFALSE", signature(x="SpatRaster"),
function(x) {
opt <- spatOptions()
x@pntr <- x@pntr$is_false(FALSE, opt)
messages(x, "isFALSE")
}
)
setMethod("as.logical", signature(x="SpatRaster"),
function(x) {
isTRUE(x)
}
)
setMethod("is.bool", signature(x="SpatRaster"),
function(x) {
x@pntr$valueType(FALSE) == 3
}
)
setMethod("is.int", signature(x="SpatRaster"),
function(x) {
x@pntr$valueType(FALSE) == 1
}
)
setMethod("as.bool", signature(x="SpatRaster"),
function(x, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$is_true(FALSE, opt)
messages(x, "as.boolean")
}
)
setMethod("as.int", signature(x="SpatRaster"),
function(x, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$math("trunc", opt)
messages(x, "as.int")
}
)
setMethod("as.integer", signature(x="SpatRaster"),
function(x, filename="", ...) {
as.int(x, filename, x)
}
)
setMethod("is.na", signature(x="SpatRaster"),
function(x) {
opt <- spatOptions()
x@pntr <- x@pntr$isnan(FALSE, opt)
messages(x, "is.na")
}
)
setMethod("countNA", signature(x="SpatRaster"),
function(x, n=0) {
opt <- spatOptions()
n <- round(n)
if (n == 1) {
x@pntr <- x@pntr$anynan(FALSE, opt)
} else {
x@pntr <- x@pntr$countnan(n, opt)
}
messages(x, "countNA")
}
)
setMethod("anyNA", signature(x="SpatRaster"),
function(x) {
opt <- spatOptions()
x@pntr <- x@pntr$anynan(FALSE, opt)
messages(x, "anyNA")
}
)
setMethod("noNA", signature(x="SpatRaster"),
function(x, falseNA=FALSE) {
opt <- spatOptions()
x@pntr <- x@pntr$nonan(falseNA, opt)
messages(x, "noNA")
}
)
setMethod("allNA", signature(x="SpatRaster"),
function(x, falseNA=FALSE) {
opt <- spatOptions()
x@pntr <- x@pntr$allnan(falseNA, opt)
messages(x, "allNA")
}
)
setMethod("is.nan", signature(x="SpatRaster"),
function(x) {
opt <- spatOptions()
x@pntr <- x@pntr$isnan(FALSE, opt)
messages(x, "is.nan")
}
)
setMethod("is.finite", signature(x="SpatRaster"),
function(x) {
opt <- spatOptions()
x@pntr <- x@pntr$isfinite(FALSE, opt)
messages(x, "is.finite")
}
)
setMethod("is.infinite", signature(x="SpatRaster"),
function(x) {
opt <- spatOptions()
x@pntr <- x@pntr$isinfinite(FALSE, opt)
messages(x, "is.infinite")
}
)
.summarize <- function(x, ..., fun, na.rm=FALSE, filename="", overwrite=FALSE, wopt=list(), par=FALSE) {
dots <- list(...)
add <- NULL
cls <- FALSE
if (length(dots) > 0) {
cls <- sapply(dots, function(i) inherits(i, "SpatRaster"))
if (!all(cls)) {
add <- dots[!cls]
if (!is.null(names(add))) {
error(fun, "additional arguments cannot be names (except for `filename`, `overwrite` and `wopt`)")
}
i <- sapply(add, function(x) class(x) %in% c("logical", "integer", "numeric"))
add <- unlist(add[i], use.names = FALSE)
if (any(!i)) {
error(fun, "invalid argument(s)")
}
}
}
if (any(cls) | par) {
x <- sds(c(list(x), dots[cls]))
}
opt <- spatOptions(filename, overwrite, wopt=wopt)
r <- rast()
if (is.null(add)) {
r@pntr <- x@pntr$summary(fun, na.rm, opt)
} else {
r@pntr <- x@pntr$summary_numb(fun, add, na.rm, opt)
}
messages(r, fun)
r
}
setMethod("which.max", "SpatRaster",
function(x) {
opt <- spatOptions()
x@pntr <- x@pntr$summary("which.max", TRUE, opt)
messages(x, "which.max")
}
)
setMethod("which.min", "SpatRaster",
function(x) {
opt <- spatOptions()
x@pntr <- x@pntr$summary("which.min", TRUE, opt)
messages(x, "which.min")
}
)
setMethod("which.lyr", "SpatRaster",
function(x) {
opt <- spatOptions()
x@pntr <- x@pntr$summary("which", TRUE, opt)
messages(x, "which.lyr")
}
)
wherefun <- function(out, list, values) {
if (list) {
if (values) {
lapply(out, function(i) {
m <- matrix(i, ncol=2)
m[,1] <- m[,1] + 1
colnames(m) <- c("cell", "value")
m
})
} else {
lapply(out, function(i) {i + 1})
}
} else {
if (values) {
out <- lapply(1:length(out), function(i) {
m <- matrix(out[[i]], ncol=2)
m[,1] <- m[,1] + 1
cbind(i, m)
})
out <- do.call(rbind, out)
colnames(out) <- c("layer", "cell", "value")
} else {
out <- lapply(1:length(out), function(i) {cbind(i, out[[i]] + 1)})
out <- do.call(rbind, out)
colnames(out) <- c("layer", "cell")
}
out
}
}
setMethod("where.max", "SpatRaster",
function(x, values=TRUE, list=FALSE) {
opt <- spatOptions()
out <- x@pntr$where("max", values, opt)
x <- messages(x, "where.max")
wherefun(out, list, values)
}
)
setMethod("where.min", "SpatRaster",
function(x, values=TRUE, list=FALSE) {
opt <- spatOptions()
out <- x@pntr$where("min", values, opt)
x <- messages(x, "where.min")
wherefun(out, list, values)
}
)
setMethod("Summary", signature(x="SpatRaster"),
function(x, ..., na.rm=FALSE){
fun <- as.character(sys.call()[[1L]])
.summarize(x, ..., fun=fun, na.rm=na.rm)
}
)
setMethod("Summary", signature(x="SpatVector"),
function(x, ..., na.rm=FALSE){
apply(values(x), 2, sys.call()[[1L]], ...)
}
)
setMethod("Summary", signature(x="SpatExtent"),
function(x, ..., na.rm=FALSE){
e <- as.vector(x)
x <- e[1:2]
y <- e[3:4]
fun <- as.character(sys.call()[[1L]])
if (fun == "range") {
r <- c(diff(x), diff(y))
names(r) <- c("x", "y")
r
} else {
c(callGeneric(x), callGeneric(y))
}
}
)
setMethod("mean", signature(x="SpatExtent"),
function(x, ..., trim=NA, na.rm=FALSE){
if (!is.na(trim)) { warn("mean", "argument 'trim' is ignored") }
e <- as.vector(x)
c(mean(e[1:2]), mean(e[3:4]))
}
)
setMethod("mean", signature(x="SpatRaster"),
function(x, ..., trim=NA, na.rm=FALSE){
if (!is.na(trim)) { warn("mean", "argument 'trim' is ignored") }
.summarize(x, ..., fun="mean", na.rm=na.rm)
}
)
setMethod("mean", signature(x="SpatVector"),
function(x, ..., trim=NA, na.rm=FALSE){
if (!is.na(trim)) { warn("mean", "argument 'trim' is ignored") }
if (!is.null(list(...))) { warn("mean", "additional arguments are ignored") }
colMeans(values(x))
}
)
setMethod("median", signature(x="SpatRaster"),
function(x, na.rm=FALSE, ...){
if (!is.logical(na.rm)) {
error("median", "na.rm (the second argument) must be a logical value")
}
.summarize(x, ..., fun="median", na.rm=na.rm)
}
)
setMethod("median", signature(x="SpatVector"),
function(x, na.rm=FALSE){
apply(values(x), 2, median, na.rm=na.rm)
}
)
setMethod("Compare", signature(e1="SpatExtent", e2="SpatExtent"),
function(e1, e2){
oper <- as.vector(.Generic)[1]
if (!(oper %in% c("==", "!=", ">", "<", ">=", "<="))) {
error(oper, "is not implemented for SpatExtent")
}
return( e1@pntr$compare(e2@pntr, oper, 0.000001) )
}
)
setMethod("stdev", signature(x="SpatRaster"),
function(x, ..., pop=TRUE, na.rm=FALSE){
if (pop) {
.summarize(x, ..., fun="std", na.rm=na.rm)
} else {
.summarize(x, ..., fun="sd", na.rm=na.rm)
}
}
)
setMethod("modal", signature("SpatRaster"),
function(x, ..., ties="first", na.rm=FALSE, filename="", overwrite=FALSE, wopt=list()) {
opt <- spatOptions(filename, overwrite, wopt=wopt)
dots <- list(...)
add <- NULL
if (length(dots) > 0) {
cls <- sapply(dots, function(i) inherits(i, "SpatRaster"))
if (any(cls)) {
y <- c(dots[cls], x)
x <- do.call(c, y)
}
if (!all(cls)) {
dots <- dots[!cls]
i <- sapply(dots, function(x) class(x) %in% c("logical", "integer", "numeric"))
add <- unlist(dots[i], use.names = FALSE)
}
}
if (is.null(add)) {
add <- c(.5)[0]
}
x@pntr <- x@pntr$modal(add, ties[1], na.rm[1], opt)
messages(x, "modal")
}
)
setMethod("compare", signature(x="SpatRaster"),
function(x, y, oper, falseNA=FALSE, filename="", overwrite=FALSE, ...){
if (!is.character(oper)) {
error("compare", "oper must be a character value")
}
oper = oper[1]
ops <- c("==", "!=", ">", "<", ">=", "<=")
if (!(oper %in% ops)) {
error("compare", "oper must be a one of", ops)
}
opt <- spatOptions(filename, overwrite, ...)
if (inherits(y, "SpatRaster")) {
x@pntr <- x@pntr$arith_rast(y@pntr, oper, falseNA[1], opt)
} else {
x@pntr <- x@pntr$arith_numb(y, oper, FALSE, falseNA[1], opt)
}
messages(x, oper)
}
)
setMethod("logic", signature(x="SpatRaster"),
function(x, oper, falseNA=FALSE, filename="", overwrite=FALSE, ...){
if (!is.character(oper)) {
error("logic", "oper must be a character value")
}
oper = oper[1]
ops <- c("!", "is.na", "allNA", "noNA", "is.infinite", "is.finite", "iSTRUE", "isFALSE")
if (!(oper %in% ops)) {
error("compare", "oper must be a one of", ops)
}
opt <- spatOptions(filename, overwrite, ...)
falseNA <- as.logical(falseNA[1])
if (oper == "is.infinite") {
x@pntr <- x@pntr$isinfinite(falseNA, opt)
} else if (oper == "is.finite") {
x@pntr <- x@pntr$isfinite(falseNA, opt)
} else if (oper == "is.na") {
x@pntr <- x@pntr$isnan(falseNA, opt)
} else if (oper == "isTRUE") {
x@pntr <- x@pntr$is_true(falseNA, opt)
} else if (oper == "isFALSE") {
x@pntr <- x@pntr$is_false(falseNA, opt)
} else if (oper == "allNA") {
x@pntr <- x@pntr$allnan(falseNA, opt)
} else if (oper == "noNA") {
x@pntr <- x@pntr$nonan(falseNA, opt)
} else if (oper == "anyNA") {
x@pntr <- x@pntr$anynan(falseNA, opt)
} else if (oper == "anyNA") {
x@pntr <- x@pntr$anynan(falseNA, opt)
} else if (oper == "!") {
x@pntr <- x@pntr$arith_numb(0, "==", FALSE, falseNA[1], opt)
} else {
error("logic", "??")
}
messages(x, "logic")
}
)
terra/R/plot_cartogram.R 0000644 0001762 0000144 00000001166 14536376240 014746 0 ustar ligges users
setMethod("cartogram", signature(x="SpatVector"),
function(x, var, type) {
if (geomtype(x) != "polygons") {
error("cartogram", "x must be polygons")
}
type <- match.arg(tolower(type), "nc")
stopifnot(var %in% names(x))
v <- as.numeric(as.vector(x[[var, drop=TRUE]]))
if (!any(!is.na(v))) stop(paste("no numeric values in", var))
if (any(v <= 0)) stop(paste("non-positive values in", var))
x <- x[!is.na(v)]
v <- v[!is.na(v)]
f <- v / max(v)
cxy <- crds(centroids(x, inside=TRUE))
r <- lapply(1:length(v), function(i) {
rescale(x[i,], f[i], x0=cxy[i,1], y0=cxy[i,2])
})
do.call(rbind, r)
}
)
terra/R/plot_vector.R 0000644 0001762 0000144 00000046221 14752530025 014263 0 ustar ligges users # Author: Robert J. Hijmans
# Date : June 2019
# Version 1.0
# License GPL v3
setMethod("dots", signature(x="SpatVector"),
function(x, field, size, ...) {
reset.clip()
n <- length(x)
if (n < 1) return(NULL)
#method <- match.arg(tolower(method), c("regular", "random"))
if (is.character(field)) {
stopifnot(field %in% names(x))
} else {
stopifnot(field > 0 && field <= ncol(x))
}
stopifnot(is.numeric(x[[field,drop=TRUE]]))
field <- x[[field,drop=TRUE]]
size <- size[1]
stopifnot(size > 0)
d <- round(field / size)
d[d < 1 | is.na(d)] <- 0
i <- d > 0;
if (sum(i) == 0) {
error("dots", "'size' is too small")
}
s <- spatSample(x[i], d[i], method="random")
if (.Device != "null device") {
try(points(s, ...), silent=TRUE)
}
invisible(s)
}
)
.plotLines <- function(x, out, lty=1, lwd=1, ...) {
n <- nrow(x)
if (n == 0) return(out)
# cols <- out$cols
# if (is.null(cols)) cols = rep("black", n)
# g <- lapply(x@pntr$linesList(), function(i) { names(i)=c("x", "y"); i } )
# g <- geom(x, df=TRUE)
# g <- split(g, g[,1])
# g <- lapply(g, function(x) split(x[,3:4], x[,2]))
# n <- length(g)
g <- x@pntr$linesList()
lty <- rep_len(lty, n)
lwd <- rep_len(lwd, n)
for (i in 1:n) {
if (!is.null(g[[i]])) {
names(g[[i]]) = c("x", "y")
graphics::plot.xy(g[[i]], type="l", lty=lty[i], col=out$main_cols[i], lwd=lwd[i], ...)
}
}
# for (i in 1:n) {
# for (j in 1:length(g[[i]])) {
# lines(g[[i]][[j]], col=out$main_cols[i], lwd=lwd[i], lty=lty[i], ...)
# }
# }
out$leg$lwd <- lwd
out$leg$lty <- lty
out
}
.plotPolygons <- function(x, out, lty=1, lwd=1, density=NULL, angle=45, ...) {
n <- nrow(x)
if (n == 0) return(out)
if ((length(out$main_cols) == 0) && (length(out$leg$border) <= 1) && (length(lty) <= 1) && (length(lwd) <= 1) && (is.null(density))) {
if (is.null(out$leg$border)) out$leg$border <- "black"
lines(x, col=out$leg$border, lty=lty, lwd=lwd, ...)
return(out)
}
# cols <- .getCols(length(x), col, alpha)
# out <- list(main_cols=cols)
if (!is.null(out$leg$border)) {
out$leg$border <- rep_len(out$leg$border, n)
} else {
out$leg$border <- NA
}
if (!is.null(density)) {
out$leg$density <- rep_len(density, n)
out$leg$angle <- rep_len(angle, n)
}
if (!is.null(lty)) out$leg$lty <- rep_len(lty, n)
if (!is.null(lwd)) out$leg$lwd <- rep_len(lwd, n)
if (!is.null(out$main_cols)) {
out$main_cols <- rep_len(out$main_cols, n)
}
# g <- geom(x, df=TRUE)
# g <- split(g, g[,1])
# g <- lapply(g, function(y) split(y[,3:5], y[,2]))
# w <- getOption("warn")
# on.exit(options("warn" = w))
# for (i in 1:length(g)) {
# gg <- g[[i]]
# for (j in 1:length(gg)) {
# a <- gg[[j]]
# if (any(is.na(a))) next
# if (any(a[,3] > 0)) {
# a <- split(a[,1:2,drop=FALSE], a[,3])
# a <- lapply(a, function(i) rbind(i, NA))
# a <- do.call(rbind, a )
# a <- a[-nrow(a), ]
# # g[[i]][[1]] <- a
# }
g <- x@pntr$polygonsList()
if (is.null(out$leg$density)) {
for (i in seq_along(g)) {
for (j in seq_along(g[[i]])) {
if (any(is.na(g[[i]][[j]]))) next
graphics::polypath(g[[i]][[j]][[1]], g[[i]][[j]][[2]], col=out$main_cols[i], rule = "evenodd", border=out$leg$border[i], lwd=out$leg$lwd[i], lty=out$leg$lty[i], ...)
}
}
} else {
for (i in 1:length(g)) {
for (j in seq_along(g[[i]])) {
if (any(is.na(g[[i]][[j]]))) next
graphics::polygon(g[[i]][[j]][[1]], g[[i]][[j]][[2]], col=out$main_cols[i], density=out$leg$density[i], angle=out$leg$angle[i], border=NA, lwd=out$leg$lwd[i], lty=out$leg$lty[i], ...)
graphics::polypath(g[[i]][[j]][[1]], g[[i]][[j]][[2]], col=NA, rule="evenodd", border=out$leg$border[i], lwd=out$leg$lwd[i], lty=out$leg$lty[i], ...)
}
}
}
invisible(out)
}
.vplot <- function(x, out, xlab="", ylab="", pch=16, lty=1, lwd=1, ...) {
if (out$leg$geomtype == "points") {
points(x, col=out$main_cols, cex=out$cex, pch=pch, ...)
if (is.null(out$leg$pch)) out$leg$pch <- pch
if (is.null(out$leg$pt.cex)) out$leg$pt.cex = out$cex
} else if (out$leg$geomtype == "polygons") {
out <- .plotPolygons(x, out, density=out$leg$density, angle=out$leg$angle, lty=lty, lwd=lwd, ...)
} else {
# out <- .plotLines(x, out, ...)
lines(x, col=out$main_cols, lty=lty, lwd=lwd, ...)
if (is.null(out$leg$lwd)) out$leg$lwd = lwd
if (is.null(out$leg$lty)) out$leg$lty = lty
}
out
}
.getCols <- function(n, cols, alpha=NULL) {
if (is.null(cols)) {
return(cols)
}
if (inherits(cols, "function")) {
cols <- cols(n)
} else {
ncols <- length(cols)
if (ncols > n) {
steps <- ncols/n
i <- round(seq(1, ncols, steps))
cols <- cols[i]
} else if (ncols < n) {
cols <- rep_len(cols, n)
}
}
if (!is.null(alpha)) {
if (alpha[1] < 1 && alpha[1] >= 0) {
cols <- grDevices::rgb(t(grDevices::col2rgb(cols)), alpha=alpha[1]*255, maxColorValue=255)
}
}
cols
}
.vect.legend.none <- function(out) {
#if (out$leg$geomtype == "points") {
# out$main_cols <- .getCols(out$ngeom, out$cols, 1)
#} else {
# out$cols <- .getCols(out$ngeom, out$cols)
#}
out$main_cols <- out$cols
out
}
.vect.legend.classes <- function(out) {
if (isTRUE(out$legend_sort)) {
out$uv <- sort(out$uv, decreasing=out$legend_sort_decreasing)
} else {
out$uv <- out$uv[!is.na(out$uv)]
}
ucols <- .getCols(length(out$uv), out$cols, out$alpha)
i <- match(out$v, out$uv)
out$cols <- ucols
out$main_cols <- ucols[i]
if (!is.null(out$colNA)) {
out$main_cols[is.na(out$main_cols)] <- out$colNA
}
out$levels <- out$uv
out$leg$legend <- out$uv
nlevs <- length(out$uv)
cols <- out$cols
ncols <- length(cols)
if (nlevs < ncols) {
i <- trunc((ncols / nlevs) * 1:nlevs)
cols <- cols[i]
} else {
cols <- rep_len(cols, nlevs)
}
out$leg$fill <- cols
out$legend_type <- "classes"
if (is.null(out$leg$x)) { # && is.null(out$leg$ext)) {
out$leg$x <- "default"
}
out
}
.vect.legend.continuous <- function(out) {
z <- stats::na.omit(out$v)
n <- length(z)
if (n == 0) error("plot", "no values")
if (!is.numeric(out$v)) {
out$v <- as.integer(as.factor(out$v))
z <- stats::na.omit(out$v)
n <- length(z)
}
#out$range <- range(z)
interval <- (out$range[2]-out$range[1])/(length(out$cols)-1)
breaks <- out$range[1] + interval * (0:(length(out$cols)-1))
out$legend_type <- "continuous"
if (is.null(out$levels)) {
out$levels <- 5
}
if (is.null(out$leg$digits)) {
dif <- diff(out$range)
if (dif == 0) {
out$leg$digits <- 0;
} else {
out$leg$digits <- max(0, -floor(log10(dif/10)))
}
}
if (is.null(out$leg$loc)) out$leg$loc <- "right"
brks <- seq(out$range[1], out$range[2], length.out = length(out$cols))
grps <- cut(out$v, breaks = brks, include.lowest = TRUE)
out$main_cols <- out$cols[grps]
out
}
.vect.legend.interval <- function(out, dig.lab=3, ...) {
nmx <- length(out$uv)
if (!is.numeric(out$v)) {
out$v <- as.integer(as.factor(out$v))
}
if (is.null(out$breaks)) {
out$breaks <- min(5, nmx)
}
if (length(out$breaks) == 1) {
out$breaks <- .get_breaks(out$v, out$breaks, out$breakby, out$range)
}
fz <- cut(out$v, out$breaks, include.lowest=TRUE, right=FALSE, dig.lab=dig.lab)
out$vcut <- as.integer(fz)
levs <- levels(fz)
nlevs <- length(levs)
# cols <- out$cols
# ncols <- length(cols)
# if (nlevs < ncols) {
# i <- trunc((ncols / nlevs) * 1:nlevs)
# cols <- cols[i]
# } else {
# cols <- rep_len(cols, nlevs)
# }
if (out$legend_type == "classes" && nlevs > length(out$cols)) {
# more classes than colors: cycle from beginning
cols_idx <- rep_len(out$cols, nlevs)
} else {
# else sample the colors
cols_idx <- trunc(seq(1, length(out$cols), length.out = nlevs))
}
out$leg$fill <- out$cols <- out$cols[cols_idx]
out$legend_type <- "classes"
if (!is.null(out$leg$legend)) {
if (length(out$leg$legend) != nlevs) {
warn("plot", "legend does not match number of levels")
out$leg$legend <- rep_len(out$leg$legend, nlevs)
}
} else {
levs <- gsub("]", "", gsub(")", "", gsub("\\[", "", levs)))
levs <- paste(levs, collapse=",")
m <- matrix(as.numeric(unlist(strsplit(levs, ","))), ncol=2, byrow=TRUE)
m <- apply(m, 1, function(i) paste(i, collapse=" - "))
out$leg$legend <- m
}
if (is.null(out$leg$x)) { # && is.null(out$leg$ext)) {
out$leg$x <- "default"
}
out$main_cols <- out$cols[out$vcut]
if (!is.null(out$colNA)) {
out$main_cols[is.na(out$main_cols)] <- out$colNA
}
out
}
.plot.vect.map <- function(x, out, ...) {
if ((!out$add) & (!out$legend_only)) {
if (!any(is.na(out$mar))) { graphics::par(mar=out$mar) }
plot(out$lim[1:2], out$lim[3:4], type="n", xlab="", ylab="", asp=out$asp, xaxs="i", yaxs="i", axes=FALSE, main="")
if (!is.null(out$background)) {
graphics::rect(out$lim[1], out$lim[3], out$lim[2], out$lim[4], col=out$background, border=TRUE)
}
}
if (isTRUE(out$blank)) return(out)
nuq <- length(out$uv)
if (out$legend_type == "none") {
out <- .vect.legend.none(out)
} else if (out$legend_type == "classes") {
out <- .vect.legend.classes(out)
} else if (out$legend_type == "interval") {
if (nuq < 2) {
out <- .vect.legend.classes(out, ...)
} else {
out <- .vect.legend.interval(out, dig.lab=out$dig.lab)
}
} else if (out$legend_type == "depends") {
if (!is.null(out$breaks)) {
out <- .vect.legend.interval(out, dig.lab=out$dig.lab)
} else if (nuq < 11) {
out <- .vect.legend.classes(out)
} else if (!is.numeric(out$uv)) {
#if (nuq < 21)
out <- .vect.legend.classes(out)
} else {
out <- .vect.legend.interval(out, dig.lab=out$dig.lab)
}
} else {
if (nuq == 1) {
out <- .vect.legend.classes(out)
} else {
out <- .vect.legend.continuous(out)
out$leg$density <- NULL
}
}
if (!out$legend_only) {
if (!out$add) {
try(set.clip(out$lim, out$lonlat))
}
out <- .vplot(x, out, ...)
}
if (out$axes) {
out <- .plot.axes(out)
}
if (out$legend_draw) {
if (out$legend_type == "continuous") {
out$legpars <- do.call(.plot.cont.legend, list(x=out))
} else {
if (out$add) {
if (out$clip) {
out$leg$plotlim <- unlist(get.clip()[1:4])
} else {
out$leg$plotlim <- graphics::par("usr")
}
if (is.null(out$leg$plotlim)) {
out$leg$plotlim <- out$lim
}
} else {
if (out$clip) {
out$leg$plotlim <- out$lim
} else {
out$leg$plotlim <- graphics::par("usr")
}
}
out$legpars <- do.call(.plot.class.legend, out$leg)
}
}
if (isTRUE(out$box)) {
if (out$clip) {
lines(ext(out$lim))
} else {
lines(ext(graphics::par("usr")))
}
}
if (out$main != "") {
posx <- out$lim[1] + diff(out$lim[1:2])/2
text(posx, out$lim[4], out$main, pos=3, offset=out$line.main, cex=out$cex.main,
font=out$font.main, col=out$col.main, xpd=TRUE)
}
if (!out$add) {
try(set.clip(out$lim, out$lonlat))
}
out
}
.prep.vect.data <- function(x, y, type=NULL, cols=NULL, mar=NULL, legend=TRUE,
legend.only=FALSE, levels=NULL, add=FALSE, range=NULL, fill_range=FALSE, breaks=NULL, breakby="eqint",
xlim=NULL, ylim=NULL, colNA=NA, alpha=NULL, axes=TRUE, buffer=TRUE, background=NULL,
pax=list(), plg=list(), ext=NULL, grid=FALSE, las=0, sort=TRUE, decreasing=FALSE, values=NULL,
box=TRUE, xlab="", ylab="", cex.lab=0.8, line.lab=1.5, yaxs="i", xaxs="i", main="", cex.main=1.2, line.main=0.5, font.main=graphics::par()$font.main, col.main = graphics::par()$col.main,
density=NULL, angle=45, border="black", dig.lab=3, cex=1, clip=TRUE, leg_i=1, asp=NULL, xpd=NULL, ...) {
out <- list()
out$blank <- FALSE
if ((y == "") && (is.null(values))) {
if (is.null(type)) type <- "none"
if (type == "n") {
out$blank <- TRUE
}
type <- "none"
plg <- list()
}
e <- as.vector(ext(x))
if (any(is.na(e))) {
error("plot", "SpatVector has no valid geometries")
}
if (e[1] == e[2]) {
e[1] = e[1] - 0.5
e[2] = e[2] + 0.5
}
if (e[3] == e[4]) {
e[3] = e[3] - 0.5
e[4] = e[4] + 0.5
}
out$lim <- out$ext <- e
if ((!is.null(ext)) || (!is.null(xlim)) || (!is.null(ylim))) {
if (!is.null(ext)) {
ext <- ext(ext)
if (!is.null(xlim) | !is.null(ylim)) {
x <- crop(x, ext)
} else {
x <- x[ext, ]
}
out$ext <- as.vector(ext(x))
out$lim <- as.vector(ext)
}
if (!is.null(xlim)) {
stopifnot(length(xlim) == 2)
out$lim[1:2] <- sort(xlim)
}
if (!is.null(ylim)) {
stopifnot(length(ylim) == 2)
out$lim[3:4] <- sort(ylim)
}
} else if ((!add) && is.null(xpd)) {
xpd <- TRUE
}
out$ngeom <- nrow(x)
out$clip <- isTRUE(clip)
if (buffer) {
dx <- diff(out$lim[1:2]) / 50
dy <- diff(out$lim[3:4]) / 50
out$lim[1:2] <- out$lim[1:2] + c(-dx, dx)
out$lim[3:4] <- out$lim[3:4] + c(-dy, dy)
}
out$main <- main
if ((!is.expression(main)) && (is.null(out$main) || any(is.na(out$main)))) out$main <- ""
out$cex.main <- cex.main
out$font.main <- font.main
out$col.main <- col.main
out$line.main <- line.main
out$dig.lab <- dig.lab
out$box <- isTRUE(box)
out$add <- isTRUE(add)
out$axes <- isTRUE(axes)
out$xlab <- xlab
out$ylab <- ylab
out$axs <- as.list(pax)
out$cex <- cex
if (is.null(out$axs$las)) out$axs$las <- las
if (is.null(out$axs$cex.lab)) out$axs$cex.lab <- cex.lab
if (is.null(out$axs$line.lab)) out$axs$line.lab <- line.lab
out$draw_grid <- isTRUE(grid)
out$leg <- as.list(plg)
out$leg$geomtype <- geomtype(x)
out$leg$density <- density
out$leg$angle <- angle
out$leg$border <- border
if (is.null(asp)) {
out$lonlat <- is.lonlat(x, perhaps=TRUE, warn=FALSE)
if (out$lonlat) {
out$asp <- 1/cos((mean(out$ext[3:4]) * pi)/180)
} else {
out$asp <- 1
}
} else {
out$asp <- asp
out$lonlat <- FALSE
}
out$breaks <- breaks
out$breakby <- breakby
out$background <- background
if (is.null(values)) {
v <- unlist(x[, y, drop=TRUE], use.names=FALSE)
} else {
if (inherits(values, "data.frame")) {
if (ncol(values) == 2) {
xname = names(values)[1]
if (xname %in% names(x)) {
i <- match(x[[xname,drop=TRUE]], values[[1]])
v <- values[[2]][i]
} else {
error("plot", paste(xname, "is not a name in x"))
}
} else {
values <- values[[1]]
}
} else {
v <- as.vector(values)
}
v <- rep_len(v, nrow(x))
}
if (is.factor(v)) v <- as.character(v)
if (is.numeric(v)) {
v[!is.finite(v)] <- NA
}
if (!is.null(range)) {
range <- sort(range)
v[v < range[1]] <- NA
v[v > range[2]] <- NA
if (all(is.na(v))) {
v <- NULL
y <- ""
type = "none"
} else {
out$range <- range
}
out$range_set <- TRUE
} else {
if (!is.null(v)) {
out$range <- range(v, na.rm=TRUE)
}
out$range_set <- FALSE
}
out$fill_range <- fill_range
out$v <- v
if (!is.logical(sort)) {
out$uv <- unique(sort)
out$legend_sort <- FALSE
} else {
out$uv <- unique(out$v)
if (is.factor(out$v)) {
out$uv <- levels(out$v)[levels(out$v) %in% out$uv]
}
out$legend_sort <- isTRUE(sort)
out$legend_sort_decreasing <- isTRUE(decreasing)
}
if (is.null(type)) {
type <- "depends"
} else {
type <- match.arg(type, c("continuous", "classes", "interval", "depends", "none"))
}
out$levels <- levels
if (type=="none") {
legend <- FALSE
legend_only <- FALSE
}
out$legend_type <- type
if (is.null(cols)) {
if (type == "none") {
if (out$leg$geomtype %in% c("lines", "points")) {
cols <- "black"
}
} else {
cols <- .default.pal()
# cols <- rev(grDevices::rainbow(100, start=.1, end=0.9))
}
}
if (!is.null(alpha)) {
alpha <- clamp(alpha[1], 0, 1)
cols <- grDevices::rgb(t(grDevices::col2rgb(cols)), alpha=alpha*255, maxColorValue=255)
} else {
alpha <- 1
}
out$alpha <- alpha
out$cols <- cols
out$legend_draw <- isTRUE(legend)
out$legend_only <- isTRUE(legend.only)
out$leg$leg_i <- leg_i
if (is.null(mar)) {
if (out$legend_draw) {
mar=c(3.1, 3.1, 2.1, 7.1)
} else {
mar=c(3.1, 3.1, 2.1, 2.1)
}
}
out$mar <- rep_len(mar, 4)
out$skipNA <- TRUE
if (!is.null(colNA)) {
if (!is.na(colNA)) {
out$colNA <- grDevices::rgb(t(grDevices::col2rgb(colNA)), alpha=alpha*255, maxColorValue=255)
out$r[is.na(out$r)] <- out$colNA
out$skipNA <- FALSE
} else {
out$colNA <- NULL
}
}
.plot.vect.map(x, out, xpd=xpd, ...)
}
setMethod("plot", signature(x="SpatVector", y="character"),
function(x, y, col=NULL, type=NULL, mar=NULL, add=FALSE, legend=TRUE, axes=!add,
main, buffer=TRUE, background=NULL, grid=FALSE, ext=NULL,
sort=TRUE, decreasing=FALSE, plg=list(), pax=list(), nr, nc, colNA=NA,
alpha=NULL, box=axes, clip=TRUE, ...) {
old.mar <- graphics::par()$mar
on.exit(graphics::par(mar=old.mar))
if (nrow(x) == 0) {
error("plot", "SpatVector has zero geometries")
}
if (add) reset.clip()
y <- trimws(y)
if (any(is.na(match(y, c("", names(x)))))) {
i <- is.na(match(y, names(x)))
error("plot", paste(paste(y[i], collapse=",")), " is not a name in x")
}
nrnc <- c(1,1)
if (length(y) > 1) {
nrnc <- .get_nrnc(nr, nc, length(y))
old.par <- graphics::par(no.readonly =TRUE)
on.exit(graphics::par(old.par))
graphics::par(mfrow=nrnc)
}
if (is.character(legend)) {
plg$x <- legend
legend <- TRUE
}
for (i in 1:length(y)) {
if (length(y) > 1) {
if (missing("main")) {
main <- y
} else {
main <- rep_len(main, length(y))
}
newrow <- (nrnc[2] == 1) | ((i %% nrnc[2]) == 1)
lastrow <- i > (prod(nrnc) - nrnc[2])
if (lastrow) {
if (newrow) {
pax$side <- 1:2
} else {
pax$side <- 1
}
} else if (newrow) {
pax$side <- 2
} else {
pax$side <- 0
}
} else if (missing("main")) {
main <- ""
}
if (missing(col)) col <- NULL
out <- .prep.vect.data(x, y[i], type=type, cols=col, mar=mar, plg=plg, pax=pax, legend=isTRUE(legend), add=add, axes=axes, main=main[i], buffer=buffer, background=background, grid=grid, ext=ext, sort=sort, decreasing=decreasing, colNA=colNA, alpha=alpha, box=box, clip=clip, leg_i=i, ...)
}
invisible(out)
}
)
setMethod("plot", signature(x="SpatVector", y="numeric"),
function(x, y, ...) {
y <- round(y)
if (any(y > ncol(x))) {
error("plot", paste("x only has", ncol(x), " columns"))
}
y[y<0] <- 0
y <- c("", names(x))[y+1]
out <- plot(x, y, ...)
invisible(out)
}
)
#setMethod("plot", signature(x="SpatVector", y="data.frame"),
# function(x, y, values=NULL, ...) {
# out <- plot(x, "", values=y, ...)
# invisible(out)
# }
#)
setMethod("plot", signature(x="SpatVector", y="missing"),
function(x, y, values=NULL, ...) {
invisible( plot(x, "", values=values, ...) )
}
)
setMethod("plot", signature(x="SpatVectorProxy", y="missing"),
function(x, y, ...) {
plot(ext(x), ...)
}
)
setMethod("plot", signature(x="SpatVectorCollection", y="missing"),
function(x, y, main, mar=NULL, nc, nr, maxnl=16, ...) {
nl <- max(1, min(length(x), maxnl))
if (nl==1) {
if (missing(main)) main = ""
out <- plot(x[1], main=main[1], mar=mar, ...)
return(invisible(out))
}
nrnc <- .get_nrnc(nr, nc, nl)
old.par <- graphics::par(no.readonly = TRUE)
on.exit(graphics::par(old.par))
if (is.null(mar)) {
mar=c(1.5, 1, 2.5, 3)
}
graphics::par(mfrow=nrnc)
if (missing("main")) {
main <- names(x)
} else {
main <- rep_len(main, nl)
}
for (i in 1:nl) {
plot(x[i], main=main[i], mar=mar, ...)
}
}
)
setMethod("plot", signature(x="SpatVectorCollection", y="numeric"),
function(x, y, main, mar=NULL, ext=NULL, ...) {
y <- round(y)
if ((y > 0) && (y <= length(x))) {
if (is.null(ext)) ext <- ext(x)
plot(x[y], main=main, mar=mar, ext=ext, ...)
} else {
error("plot", "y should be between 1 and length(x)")
}
}
)
terra/R/update.R 0000644 0001762 0000144 00000000372 14735567526 013223 0 ustar ligges users
setMethod("update", signature(object="SpatRaster"),
function(object, crs=FALSE, extent=FALSE) {
opt <- spatOptions()
names <- FALSE
ok <- object@pntr$update_meta(names, crs, extent, opt)
messages(object, "update")
invisible(object)
}
)
terra/R/rasterizeWin.R 0000644 0001762 0000144 00000025102 14726700274 014412 0 ustar ligges users # Author: Robert J. Hijmans
# Date : October 2022
# Version 1.0
# License GPL v3
check_ngb_pars <- function(algo, pars, fill, caller="rasterizeWin") {
#p <- c("Power", "Smoothing", "Radius", "Radius1", "Radius2", "Angle", "nMaxPoints", "nMinPoints")
n <- tolower(names(pars))
if (length(n) == 0) error(caller, "parameters are not named")
if (algo %in% c("min", "max", "range", "mean", "count", "distto", "distbetween")) {
pex <- c("Radius1", "Radius2", "Angle", "MinPoints")
} else if (algo == "invdistpow") {
pex <- c("Power", "Smoothing", "Radius1", "Radius2", "Angle", "MaxPoints", "MinPoints")
} else if (algo == "invdistpownear") {
pex <- c("Power", "Smoothing", "Radius", "MaxPoints", "MinPoints")
} else if (algo == "nearest") {
pex <- c("Radius1", "Radius2", "Angle")
} else if (algo == "linear") {
pex <- c("Radius")
} else {
error(caller, "invalid algorithm name")
}
if (length(n) != length(pex)) error(caller, paste("expected 4 parameters for", algo, "got", length(n)))
if (!all(n %in% tolower(pex)))error(caller, paste("parameters needed for", algo, ":\n ", paste(pex, collapse=",")))
c(pars[match(n, tolower(pex))], fill)
}
get_z <- function(y, field, caller="rasterizeWin") {
if (inherits(field, "character")) {
if (length(field) == 0) {
error(caller, "field name missing")
}
if (!all(field %in% names(y))) {
f <- paste(field[!(field %in% names(y))], collapse=", ")
error(caller, paste(f, " is not a name in y"))
}
z <- y[, field, drop=TRUE]
#if (any(!sapply(z, is.numeric))) {
# error(caller, paste("fields must be numeric"))
#}
} else {
#if (!is.numeric(field)) {
# error(caller, paste(field, "is not numeric"))
#}
z <- data.frame(field=rep_len(field, nrow(y)))
}
z
}
get_rad <- function(r, caller="rasterizeWin") {
if (length(r) == 1) {
c(r, r, 0)
} else if (length(r) == 2) {
c(r, 0)
} else if (length(r) == 3) {
r[3] = r[3] %% 360
if (r[3] < 0) r[3] = r[3] + 360;
r
} else {
error(caller, "radius argument should have length 1, 2, or 3")
}
}
rastWinR <- function(x, y, win, pars, fun, nl, cvars, filename, wopt, ...) {
out <- rast(x, nlyr=nl)
rb <- rast(out)
e <- ext(out)
hy <- yres(out)/2
opt <- spatOptions()
b <- writeStart(out, filename, n=12, sources="", wopt=wopt)
if ((ncol(y) == 3) && (is.numeric(y[,3]))) {
for (i in 1:b$n) {
e$ymax <- yFromRow(out, b$row[i]) + hy
e$ymin <- yFromRow(out, b$row[i] + b$nrows[i] - 1) - hy
rbe <- crop(rb, e)
if (win == "rectangle") {
p <- rbe@pntr$winrect(y[,1], y[,2], y[,3], pars, opt)
} else {
p <- rbe@pntr$wincircle(y[,1], y[,2], y[,3], pars, opt)
}
if ((pars[4] > 1) && (length(p[[1]]) > 0)) {
a <- aggregate(p[[1]], p[1], length)
a <- a[a[,2] >= pars[4], 1]
a <- p[[1]] %in% a
p[[1]] <- p[[1]][a]
p[[2]] <- p[[2]][a]
}
if (length(p[[1]]) > 0) {
p <- aggregate(p[2], p[1], fun, ...)
v <- matrix(pars[5], ncell(rbe), nl)
v[p[,1]+1, ] <- p[,-1]
writeValues(out, v, b$row[i], b$nrows[i])
} else {
writeValues(out, rep(pars[5], ncell(rbe) * nl), b$row[i], b$nrows[i])
}
}
} else {
id <- 1:nrow(y)
for (i in 1:b$n) {
e$ymax <- yFromRow(out, b$row[i]) + hy
e$ymin <- yFromRow(out, b$row[i] + b$nrows[i] - 1) - hy
rbe <- crop(rb, e)
if (win == "rectangle") {
p <- rbe@pntr$winrect(y[,1], y[,2], id, pars, opt)
} else {
p <- rbe@pntr$wincircle(y[,1], y[,2], id, pars, opt)
}
if ((pars[4] > 1) && (length(p[[1]]) > 0)) {
a <- aggregate(p[[1]], p[1], length)
a <- a[a[,2] >= pars[4], 1]
a <- p[[1]] %in% a
p[[1]] <- p[[1]][a]
p[[2]] <- p[[2]][a]
}
if (length(p[[1]]) > 0) {
py <- y[p[[2]],3:ncol(y)]
v <- matrix(pars[5], ncell(rbe), nl)
if (cvars) {
#u <- unique(p[[1]])
#if (usedots) {
# p <- sapply(u, function(i) fun(py[p[[1]]==i, ,drop=FALSE], ...))
#} else {
# p <- sapply(u, function(i) fun(py[p[[1]]==i, ,drop=FALSE]))
#}
p <- split(py, p[[1]])
p <- sapply(p, fun, ...)
if (!is.null(dim(p))) {
p <- t(as.matrix(p))
u <- rownames(p)
} else {
u <- names(p)
}
u <- as.numeric(u)
v[u+1, ] <- p
} else {
p <- aggregate(py, p[1], fun, ...)
v[p[,1]+1, ] <- as.matrix(p[,-1])
}
writeValues(out, v, b$row[i], b$nrows[i])
} else {
writeValues(out, rep(pars[5], ncell(rbe) * nl), b$row[i], b$nrows[i])
}
}
}
writeStop(out)
}
rastBufR <- function(x, y, win, pars, fun, nl, cvars, filename, wopt, ...) {
w <- pars[1]
z <- y[,-c(1:2), drop=FALSE]
y <- vect(y[,1:2,drop=FALSE], geom=c("x", "y"))
out <- rast(x, nlyr=1)
rb <- rast(out)
if (!is.lonlat(x)) {
ngb <- max(round(w/yres(x)), round(w/xres(x)))
if (ngb <= 5) {
m <- matrix(1, 2*round(w/yres(x))+1, 2*round(w/xres(x))+1)
rb <- rasterize(y, rb)
rb <- focal(rb, m, "sum", na.rm=TRUE)
}
}
out <- rast(x, nlyr=nl)
ncs <- ncol(out)
e <- ext(out)
hy <- yres(out)/2
off <- 0
b <- writeStart(out, filename, n=12, sources="", wopt=wopt)
for (i in 1:b$n) {
e$ymax <- yFromRow(out, b$row[i]) + hy
e$ymin <- yFromRow(out, b$row[i] + b$nrows[i] - 1) - hy
rbe <- crop(rb, e)
buf <- as.polygons(rbe, dissolve=FALSE)
buf <- buffer(buf, w)
r <- relate(buf, y, "intersects", pairs=TRUE)
if ((pars[4] > 1) && (nrow(r) > 0)) {
a <- aggregate(r[,1], list(r[,1]), length)
a <- a[a[,2] >= pars[4], 1]
r <- r[r[,1] %in% a, ]
}
if (nrow(r) > 0) {
v <- matrix(pars[5], ncell(rbe), nl)
if ((ncol(z) == 1) || (!cvars)) {
f <- aggregate(z[r[,2],,drop=FALSE], list(r[,1]), fun, ...)
v[f[,1], ] <- f[,-1]
writeValues(out, v, b$row[i], b$nrows[i])
} else {
#u <- unique(r[,1])
#p <- z[r[,2], ,drop=FALSE]
#if (usedots) {
# p <- sapply(u, function(i) fun(p[r[,1]==i, ,drop=FALSE], ...))
#} else {
# p <- sapply(u, function(i) fun(p[r[,1]==i, ,drop=FALSE]))
#}
#if (!is.null(dim(p))) p <- t(p)
#v[u, ] <- as.matrix(p)
py <- z[r[,2], ,drop=FALSE]
s <- split(py, r[,1])
p <- sapply(s, fun, ...)
if (!is.null(dim(p))) {
p <- t(as.matrix(p))
u <- as.numeric(rownames(p))
} else {
u <- as.numeric(names(p))
}
v[u, ] <- p
writeValues(out, v, b$row[i], b$nrows[i])
}
} else {
writeValues(out, rep(pars[5], ncell(rbe) * nl), b$row[i], b$nrows[i])
}
}
writeStop(out)
}
setMethod("rasterizeWin", signature(x="data.frame", y="SpatRaster"),
function(x, y, win="circle", pars, fun, ..., cvars=FALSE, minPoints=1, fill=NA, filename="", wopt=list()) {
pars <- c(get_rad(pars), minPoints[1], fill[1])
if (ncol(x) < 3) {
error("rasterizeNGB", "expecting a matrix with at least three columns")
}
win <- match.arg(tolower(win), c("circle", "ellipse", "rectangle", "buffer"))
# usedots <- length(list(...)) > 0
if (ncol(x) == 3) cvars = FALSE
if (inherits(fun, "character")) {
if (fun[1] == "count") {
fun <- length
pars[5] = 0
}
nl <- ncol(x)-2
} else {
if (cvars) {
i <- min(10, nrow(x))
v <- x[1:i, -c(1:2)]
test <- sapply(list(v), fun, ...)
nl <- length(test)
} else {
test <- sapply(list(1:5), fun, ...)
nl <- length(test) * (ncol(x)-2)
}
}
if (win == "buffer") {
rastBufR(y, x, win, pars=pars, fun=fun, nl=nl, cvars=cvars, filename=filename, wopt=wopt, ...)
} else {
if (win == "circle") {
pars[2] = pars[1]
pars[3] = 0;
}
algo <- .makeTextFun(fun)
#algos <- c("min", "max", "range", "mean", "count", "distto", "distbetween")
algos <- c("distto", "distbetween")
builtin <- FALSE
if (inherits(algo, "character") && (algo %in% algos)) {
if (win == "rectangle") {
error("rasterizeWin", paste(fun, "not yet available for 'win=rectangle'"))
} else {
opt <- spatOptions(filename, wopt=wopt)
x@pntr <- x@pntr$rasterizeWindow(x[,1], x[,2], x[,3], algo, pars, opt)
return(messages(x, "rasterizeWin"))
}
}
rastWinR(x=y, y=x, win=win, pars=pars, fun=fun, nl=nl, cvars=cvars, filename=filename, wopt=wopt, ...)
}
}
)
setMethod("rasterizeWin", signature(x="SpatVector", y="SpatRaster"),
function(x, y, field, win="circle", pars, fun, ..., cvars=FALSE, minPoints=1, fill=NA, filename="", wopt=list()) {
if (geomtype(x) != "points") {
error("rasterizeWin", "SpatVector y must have a point geometry")
}
x <- cbind(crds(x), get_z(x, field, "rasterizeWin"))
rasterizeWin(x, y, win=win, pars=pars, fun=fun, minPoints=minPoints, fill=fill, cvars=cvars, filename=filename, wopt=wopt, ...)
}
)
setMethod("interpNear", signature(x="SpatRaster", y="matrix"),
function(x, y, radius, interpolate=FALSE, fill=NA, filename="", ...) {
if (ncol(y) != 3) {
error("interpNear", "expecting a matrix with three columns")
}
if (!is.numeric(y)) {
error("interpNear", "values must be numeric")
}
if (interpolate) {
algo <- "linear"
pars <- c(radius[1], fill)
} else {
algo <- "nearest"
pars <- c(get_rad(radius, "interpNear"), fill)
}
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$rasterizeWindow(y[,1], y[,2], y[,3], algo, pars, opt)
messages(x, "interpNear")
}
)
setMethod("interpNear", signature(x="SpatRaster", y="SpatVector"),
function(x, y, field, radius, interpolate=FALSE, fill=NA, filename="", ...) {
if (geomtype(y) != "points") {
error("interpNear", "SpatVector y must have a point geometry")
}
y <- cbind(crds(y), get_z(y, field, "interpNear"))
y <- as.matrix(y)
interpNear(x, y, radius=radius, interpolate=interpolate, fill=fill, filename=filename, ...)
}
)
setMethod("interpIDW", signature(x="SpatRaster", y="matrix"),
function(x, y, radius, power=2, smooth=0, maxPoints=Inf, minPoints=1, near=TRUE, fill=NA, filename="", ...) {
if (ncol(y) != 3) {
error("interpIDW", "expecting a matrix with three columns")
}
if (!is.numeric(y)) {
error("interpIDW", "values must be numeric")
}
if (near) {
algo <- "invdistpownear"
pars <- c(power, smooth, radius[1], maxPoints, minPoints, fill)
} else {
algo <- "invdistpow"
pars <- c(power, smooth, get_rad(radius, "interpIDW"), maxPoints, minPoints, fill)
}
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$rasterizeWindow(y[,1], y[,2], y[,3], algo, pars, opt)
messages(x, "interpIDW")
}
)
setMethod("interpIDW", signature(x="SpatRaster", y="SpatVector"),
function(x, y, field, radius, power=2, smooth=0, maxPoints=Inf, minPoints=1, near=TRUE, fill=NA, filename="", ...) {
if (geomtype(y) != "points") {
error("interpIDW", "SpatVector y must have a point geometry")
}
y <- cbind(crds(y), get_z(y, field, "interpIDW"))
y <- as.matrix(y)
interpIDW(x, y, radius, power=power, smooth=smooth, maxPoints=maxPoints, minPoints=minPoints, near=near, fill=fill, filename=filename, ...)
}
)
terra/R/mergeTime.R 0000644 0001762 0000144 00000004743 14536376240 013653 0 ustar ligges users
if (!isGeneric("fillTime")) {setGeneric("fillTime", function(x, ...) standardGeneric("fillTime"))}
setMethod("fillTime", signature(x="SpatRaster"),
function(x, filename="", ...) {
tm <- time(x)
if (any(is.na(tm))) {
error("fillTime", "NA in time values")
}
if (any(table(tm)>1)) {
error("fillTime", "duplicate time values")
}
if (is.unsorted(tm)) {
warn("mergeTimelines", "sorting layers")
ord <- order(tm)
x <- x[[ ord ]]
tm <- tm[ord]
}
d <- data.frame(time=seq(min(tm), max(tm), min(diff(tm))))
d <- merge(d, data.frame(time=tm, tm=tm), by=1, all.x=TRUE)
b <- (!is.na(d[,2])) + 0
b <- cumsum(b) * b
if (any(b==0)) {
mx <- max(b)
b[b==0] <- mx+1
r <- init(rast(x, nlyr=1), NA)
x <- c(x, r)
x <- x[[b]]
}
time(x) <- d[,1]
if (filename != "") {
writeRaster(x, ...)
} else {
x
}
}
)
if (!isGeneric("mergeTime")) {setGeneric("mergeTime", function(x, ...) standardGeneric("mergeTime"))}
setMethod("mergeTime", signature(x="SpatRasterDataset"),
function(x, fun="mean", filename="", ...) {
tim <- lapply(1:length(x), function(i) time(x[i]))
if (any(sapply(tim, function(i) any(is.na(i))))) {
error("mergeTime", "NA in time values")
}
if (any(sapply(tim, function(i) any(table(i)>1)))) {
error("mergeTime", "duplicate time values")
}
us <- sapply(tim, is.unsorted)
if (any(us)) {
warn("mergeTime", paste("sorting layers of SpatRaster:", paste(us, collapse=", ")))
us <- which(us)
for (i in us) {
ord <- order(tim[[i]])
x[i] <- x[i][[ ord ]]
tim[[i]] <- tim[[i]][ord]
}
}
z <- data.frame(time=sort(unique(do.call(c, tim))))
for (i in 1:length(tim)) {
d <- data.frame(tim[[i]],tim[[i]])
names(d) <- c("time", paste0("x", i))
z <- merge(z, d, by=1, all.x=TRUE)
}
b <- (!is.na(z)) + 0
y <- apply(b, 1, function(i) paste(i, collapse=""))
r <- rep(1, length(y))
for (i in 2:length(y)) {
if (y[i] == y[i-1]) {
r[i] <- r[i-1]
} else {
r[i] <- r[i-1] + 1
}
}
u <- unique(r)
out <- list()
d <- apply(b, 2, cumsum) * b
for (i in u) {
zz <- z[r==i, ,drop=FALSE]
dd <- d[r==i, -1, drop=FALSE]
tim <- zz[,1]
s <- which(colSums(is.na(zz[,-1])) == 0)
if (length(s) == 1) {
out[[i]] <- x[s][[ dd[,s] ]]
} else {
ss <- x[s]
for (j in 1:length(s)) {
ss[j] = ss[j][[ dd[, s[j]] ]]
}
out[[i]] <- app(ss, fun)
time(out[[i]]) <- tim
}
}
out <- rast(out)
if (filename != "") {
out <- writeRaster(out, ...)
}
out
}
)
terra/R/roll.R 0000644 0001762 0000144 00000003352 14726700274 012677 0 ustar ligges users # Author: Robert Hijmans
# November 2009
# License GPL3
movingFun <- function(x, n, fun=mean, type="around", circular=FALSE, na.rm=FALSE, ...) {
n <- round(abs(n))
if (n == 0) { stop("n == 0") }
x = as.vector(x)
lng <- length(x)
if (type == "around") {
hn <- floor(n/2)
if (circular) {
x <- c(x[(lng-hn+1):lng], x, x[1:hn])
} else {
x <- c(rep(NA, hn), x, rep(NA, hn))
}
} else if (type == "to") {
if (circular) {
x <- c(x[(lng-n+2):lng], x)
} else {
x <- c(rep(NA, n-1), x)
}
} else if (type == "from") {
if (circular) {
x <- c(x, x[1:n])
} else {
x <- c(x, rep(NA, n))
}
} else {
stop('unknown type; should be "around", "to", or "from"')
}
m <- matrix(ncol=n, nrow=lng)
for (i in 1:n) { m[,i] <- x[i:(lng+i-1)] }
if (na.rm) {
apply(m, MARGIN=1, FUN=fun, na.rm=na.rm, ...)
} else {
apply(m, MARGIN=1, FUN=fun, ...)
}
}
.roll <- function(x, n) {
# by Josh O'Brien
x[(seq_along(x) - (n+1)) %% length(x) + 1]
}
setMethod("roll", signature(x="numeric"),
function(x, n, fun=mean, type="around", circular=FALSE, na.rm=FALSE, ...) {
movingFun(x, n, fun, type=type, circular=circular, na.rm=na.rm, ...)
}
)
setMethod("roll", signature(x="SpatRaster"),
function(x, n, fun="mean", type="around", circular=FALSE, na.rm=FALSE, filename="", ..., wopt=list()) {
txtfun <- .makeTextFun(match.fun(fun))
if (inherits(txtfun, "character")) {
if (txtfun %in% .cpp_funs) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$roll(n, txtfun, type, circular, na.rm, opt)
return (messages(x, "roll") )
}
} else {
f <- function(i) {
movingFun(i, n, fun, type=type, circular=circular, na.rm=na.rm, ...)
}
app(x, f, filename=filename, ..., wopt=wopt)
}
}
)
terra/R/wrap.R 0000644 0001762 0000144 00000030321 14743554311 012672 0 ustar ligges users
setClass("Packed", contains="VIRTUAL")
setMethod("show", signature(object="Packed"),
function(object) {
print(paste("This is a", class(object), "object. Use 'terra::unwrap()' to unpack it"))
}
)
setClass("PackedSpatExtent", contains="Packed",
representation (
extent = "numeric"
),
prototype (
extent = numeric()
)
)
setClass("PackedSpatVector", contains="Packed",
representation (
type = "character",
crs = "character",
coordinates = "matrix",
index = "matrix",
attributes = "data.frame"
),
prototype (
type= "",
crs = ""
)
)
setClass("PackedSpatRaster", contains="Packed",
representation (
definition = "character",
values = "matrix",
attributes = "list"
),
prototype (
attributes = list()
)
)
setClass("PackedSpatRasterDC", contains="Packed",
representation (
type = "character",
rasters = "list"
),
prototype (
rasters = list()
)
)
setMethod("wrap", signature(x="SpatVector"),
function(x) {
vd <- methods::new("PackedSpatVector")
vd@type <- geomtype(x)
vd@crs <- as.character(crs(x))
#stopifnot(vd@type %in% c("points", "lines", "polygons"))
g <- geom(x)
vd@coordinates <- g[, c("x", "y"), drop=FALSE]
j <- c(1, 2, grep("hole", colnames(g)))
g <- g[ , j, drop=FALSE]
i <- which(!duplicated(g))
vd@index <- cbind(g[i, ,drop=FALSE], start=i)
vd@attributes <- as.data.frame(x)
vd
}
)
setMethod("unwrap", signature(x="PackedSpatVector"),
function(x) {
p <- methods::new("SpatVector")
p@pntr <- SpatVector$new()
if (!is.na(x@crs)) {
crs(p, warn=FALSE) <- x@crs
}
if (nrow(x@coordinates) == 0) {
return(p)
}
n <- ncol(x@index)
reps <- diff(c(x@index[,n], nrow(x@coordinates)+1))
i <- rep(1:nrow(x@index), reps)
if (n == 2) {
p@pntr$setGeometry(x@type, x@index[i,1], x@index[i,2], x@coordinates[,1], x@coordinates[,2], rep(0, nrow(x@coordinates)))
} else {
p@pntr$setGeometry(x@type, x@index[i,1], x@index[i,2], x@coordinates[,1], x@coordinates[,2], x@index[i,3])
}
if (nrow(x@attributes) > 0) {
values(p) <- x@attributes
}
messages(p, "pack")
}
)
setMethod("vect", signature(x="PackedSpatVector"),
function(x) {
unwrap(x)
}
)
setMethod("as.character", signature(x="SpatRaster"),
function(x) {
e <- as.vector(ext(x))
d <- crs(x, describe=TRUE)
if (!(is.na(d$authority) || is.na(d$code))) {
crs <- paste0(", crs='", d$authority, ":", d$code, "'")
} else {
d <- crs(x)
crs <- ifelse(d=="", ", crs=''", paste0(", crs='", d, "'"))
crs <- gsub("\n[ ]+", "", crs)
}
nms <- paste0(", names=c('", paste(names(x), collapse="', '"), "')")
paste0("rast(",
"ncols=", ncol(x),
", nrows=", nrow(x),
", nlyrs=", nlyr(x),
", xmin=",e[1],
", xmax=",e[2],
", ymin=",e[3],
", ymax=",e[4],
nms,
crs, ")"
)
}
)
#eval(parse(text=as.character(s)))
writeSources <- function(x, fsource, ftarget, overwrite, ...) {
fex <- file.exists(ftarget)
if (isFALSE(overwrite) && (any(fex))) {
error("wrap", "file(s) exist(s) and 'overwrite=FALSE'")
}
mem <- fsource == ""
for (i in 1:length(mem)) {
r <- subsetSource(x, i)
if (mem[i]) {
writeRaster(r, ftarget[i], overwrite=TRUE, ...)
} else {
ff <- r@pntr$getAllFiles();
if (length(ff) > 1) {
target_noex <- tools::file_path_sans_ext(basename(ftarget[i]))
source_noex <- tools::file_path_sans_ext(basename(fsource[i]))
fftarget <- file.path(dirname(ftarget[i]), gsub(source_noex, target_noex, basename(ff)))
file.copy(ff, fftarget)
} else {
file.copy(fsource[i], ftarget[i])
}
}
}
}
finalizeWrap <- function(x, r, mem) {
if (any(is.factor(x))) {
r@attributes$levels <- cats(x)
r@attributes$levindex <- activeCat(x, 0)
}
if (any(has.colors(x))) {
r@attributes$colors <- coltab(x)
}
v <- time(x)
if (any(!is.na(v))) {
r@attributes$time <- v
r@attributes$tinfo <- timeInfo(x)
}
v <- units(x)
if (all(v != "")) {
r@attributes$units <- v
}
v <- depth(x)
if (!all(v == 0)) {
r@attributes$depth <- v
}
v <- varnames(x)
if (!all(v == "")) {
if (mem) {
v <- unique(v)
if (length(v) == 1) {
r@attributes$varnames <- v
}
} else {
r@attributes$varnames <- v
}
}
v <- longnames(x)
if (!all(v == "")) {
if (mem) {
v <- unique(v)
if (length(v) == 1) {
r@attributes$longnames <- v
}
} else {
r@attributes$longnames <- v
}
}
r
}
setMethod("wrapCache", signature(x="SpatRaster"),
function(x, filename=NULL, path=NULL, overwrite=FALSE, ...) {
r <- methods::new("PackedSpatRaster")
r@definition <- as.character(x)
xs <- sources(x, TRUE, TRUE)
s <- xs$source
if (!is.null(filename)) {
if ((length(filename) != 1) && (nrow(xs) != length(filename))) {
error("wrap", "length(files) does not match the number of sources")
}
if (any(filename == "")) {
error("wrap", "filenames cannot be empty")
}
filename <- file.path(normalizePath(dirname(filename), mustWork=TRUE), basename(filename))
if (length(filename) == 1) {
if (is.logical(overwrite)) {
writeRaster(x, filename, overwrite=overwrite, ...)
} else if (!file.exists(filename)) {
writeRaster(x, filename, overwrite=FALSE, ...)
}
} else {
writeSources(x, s, filename, overwrite, ...)
}
xs$source <- filename
} else if (!is.null(path)) {
path <- normalizePath(path, mustWork=TRUE)
fnames <- file.path(path, basename(s))
i <- s == ""
if (any(i)) {
fnames[i] <- file.path(path, paste0(basename(tempfile()), "_", 1:sum(i), ".tif"))
}
writeSources(x, s, fnames, overwrite)
xs$source <- fnames
} else {
error("wrapCache", "both path and files are NULL")
}
r@attributes$sources <- xs
finalizeWrap(x, r, FALSE)
}
)
setMethod("wrap", signature(x="SpatExtent"),
function(x) {
r <- methods::new("PackedSpatExtent")
r@extent <- as.vector(x)
r
}
)
setMethod("unwrap", signature(x="PackedSpatExtent"),
function(x) {
ext(x@extent)
}
)
setMethod("wrap", signature(x="SpatRaster"),
function(x, proxy=FALSE) {
r <- methods::new("PackedSpatRaster")
r@definition <- as.character(x)
opt <- spatOptions(ncopies=2)
can <- (!proxy) && x@pntr$canProcessInMemory(opt)
s <- sources(x)
mem <- (can || all(s == ""))
if (mem) {
r@values <- values(x)
} else if (all(s != "")) {
xs <- sources(x, TRUE, TRUE)
r@attributes$sources <- xs
} else {
fname <- paste0(tempfile(), ".tif")
if (!is.null(path)) {
path <- normalizePath(path, mustWork=TRUE)
fname <- file.path(path, basename(fname))
}
x <- writeRaster(x, fname)
r@attributes$filename <- fname
}
finalizeWrap(x, r, mem)
}
)
setMethod("unwrap", signature(x="PackedSpatRaster"),
function(x) {
r <- eval(parse(text=x@definition))
if (!is.null(x@attributes$filename)) { # single file, all layers
rr <- rast(x@attributes$filename)
ext(rr) <- ext(r)
crs(rr, warn=FALSE) <- crs(r)
names(rr) <- names(r)
r <- rr
} else if (!is.null(x@attributes$sources)) {
s <- x@attributes$sources
u <- unique(s$sid)
rr <- lapply(1:length(u), function(i) {
ss <- s[s$sid == i, ]
r <- rast(ss[1,2])
r[[ss[,3]]]
})
rr <- rast(rr)
ext(rr) <- ext(r)
crs(rr, warn=FALSE) <- crs(r)
names(rr) <- names(r)
r <- rr
} else {
values(r) <- x@values
}
if (length(x@attributes) > 0) {
nms <- names(x@attributes)
if ("time" %in% nms) {
tinfo <- x@attributes$tinfo
if (!is.null(tinfo)) {
time(r, tinfo$step) <- x@attributes$time
} else {
time(r) <- x@attributes$time
}
}
if (any(nms %in% c("levels", "units", "depth"))) {
time(r) <- x@attributes$time
units(r) <- x@attributes$units
depth(r) <- x@attributes$depth
if (!is.null(x@attributes$levels)) {
lyrnms <- names(r)
if (is.null(x@attributes$levindex)) x@attributes$levindex <- 1
set.cats(r, layer=0, x@attributes$levels, active=x@attributes$levindex)
names(r) <- lyrnms
}
}
if (any(nms=="colors")) {
for (i in seq_along(x@attributes$colors)) {
if (!is.null(x@attributes$colors[[i]])) {
d <- terra:::.makeSpatDF(x@attributes$colors[[i]])
if (!r@pntr$setColors(i-1, d)) messages("cols<-", r)
}
}
}
if (!is.null(x@attributes$varnames)) {
varnames(r) <- x@attributes$varnames
}
if (!is.null(x@attributes$longnames)) {
longnames(r) <- x@attributes$longnames
}
}
r
}
)
setMethod("wrap", signature(x="SpatRasterDataset"),
function(x, proxy=FALSE) {
r <- methods::new("PackedSpatRasterDC")
r@type <- "SpatRasterDataset"
r@rasters <- lapply(x, wrap)
r
}
)
setMethod("wrap", signature(x="SpatRasterCollection"),
function(x, proxy=FALSE) {
r <- methods::new("PackedSpatRasterDC")
r@type <- "SpatRasterCollection"
r@rasters <- lapply(x, wrap)
r
}
)
setMethod("unwrap", signature(x="PackedSpatRasterDC"),
function(x) {
type <- x@type
x <- lapply(x@rasters, unwrap)
if (type == "SpatRasterCollection") {
sprc(x)
} else {
sds(x)
}
}
)
setMethod("rast", signature(x="PackedSpatRaster"),
function(x) {
unwrap(x)
}
)
setMethod("unwrap", signature(x="ANY"),
function(x) {
x
}
)
setMethod("serialize", signature(object="SpatExtent"),
function(object, connection, ascii = FALSE, xdr = TRUE, version = NULL, refhook = NULL) {
serialize(wrap(object), connection=connection, ascii = ascii, xdr = xdr, version = version, refhook = refhook)
}
)
setMethod("saveRDS", signature(object="SpatExtent"),
function(object, file="", ascii = FALSE, version = NULL, compress=TRUE, refhook = NULL) {
saveRDS(wrap(object), file=file, ascii = ascii, version = version, compress=compress, refhook = refhook)
}
)
setMethod("serialize", signature(object="SpatVector"),
function(object, connection, ascii = FALSE, xdr = TRUE, version = NULL, refhook = NULL) {
object = wrap(object)
serialize(object, connection=connection, ascii = ascii, xdr = xdr, version = version, refhook = refhook)
}
)
setMethod("saveRDS", signature(object="SpatVector"),
function(object, file="", ascii = FALSE, version = NULL, compress=TRUE, refhook = NULL) {
object = wrap(object)
saveRDS(object, file=file, ascii = ascii, version = version, compress=compress, refhook = refhook)
}
)
setMethod("serialize", signature(object="SpatRaster"),
function(object, connection, ascii = FALSE, xdr = TRUE, version = NULL, refhook = NULL) {
object <- wrap(object, proxy=TRUE)
serialize(object, connection=connection, ascii = ascii, xdr = xdr, version = version, refhook = refhook)
}
)
setMethod("serialize", signature(object="SpatRasterDataset"),
function(object, connection, ascii = FALSE, xdr = TRUE, version = NULL, refhook = NULL) {
object <- wrap(object, proxy=TRUE)
serialize(object, connection=connection, ascii = ascii, xdr = xdr, version = version, refhook = refhook)
}
)
setMethod("serialize", signature(object="SpatRasterCollection"),
function(object, connection, ascii = FALSE, xdr = TRUE, version = NULL, refhook = NULL) {
object <- wrap(object, proxy=TRUE)
serialize(object, connection=connection, ascii = ascii, xdr = xdr, version = version, refhook = refhook)
}
)
setMethod("unserialize", signature(connection="ANY"),
function(connection, refhook = NULL) {
x <- base::unserialize(connection, refhook)
unwrap(x)
}
)
setMethod("saveRDS", signature(object="SpatRaster"),
function(object, file="", ascii = FALSE, version = NULL, compress=TRUE, refhook = NULL) {
object <- wrap(object)
saveRDS(object, file=file, ascii = ascii, version = version, compress=compress, refhook = refhook)
}
)
setMethod("saveRDS", signature(object="SpatRasterDataset"),
function(object, file="", ascii = FALSE, version = NULL, compress=TRUE, refhook = NULL) {
object <- wrap(object)
saveRDS(object, file=file, ascii = ascii, version = version, compress=compress, refhook = refhook)
}
)
setMethod("saveRDS", signature(object="SpatRasterCollection"),
function(object, file="", ascii = FALSE, version = NULL, compress=TRUE, refhook = NULL) {
object <- wrap(object)
saveRDS(object, file=file, ascii = ascii, version = version, compress=compress, refhook = refhook)
}
)
setMethod("readRDS", signature(file="character"),
function (file = "", refhook = NULL) {
x <- base::readRDS(file=file, refhook=refhook)
unwrap(x)
}
)
#setMethod("wrap", signature(x="Spatial"),
# function(x) {
# pv <- .packVector(x)
# if (methods::.hasSlot(x, "data")) {
# pv@attributes <- x@data
# }
# pv
# }
#)
terra/R/aggregate.R 0000644 0001762 0000144 00000021603 14746554435 013664 0 ustar ligges users # Author: Robert J. Hijmans
# Date : December 2017
# Version 1.0
# License GPL v3
.makeTextFun <- function(fun) {
if (!inherits(fun, "character")) {
fun <- match.fun(fun)
if (is.primitive(fun)) {
test <- try(deparse(fun)[[1]], silent=TRUE)
test <- gsub('.Primitive\\(\"', "", test)
test <- gsub('\")', "", test)
if (test %in% c("sum", "min", "max", "prod", "any", "all")) return(test);
} else {
depf <- deparse(fun)
test1 <- isTRUE(try( depf[2] == 'UseMethod(\"mean\")', silent=TRUE))
test2 <- isTRUE(try( fun@generic == "mean", silent=TRUE))
if (test1 | test2) return("mean")
test1 <- isTRUE(try( depf[2] == 'UseMethod(\"median\")', silent=TRUE))
test2 <- isTRUE(try( fun@generic == "median", silent=TRUE))
if (test1 | test2) return("median")
test1 <- isTRUE(try( depf[1] == "function (x, na.rm = FALSE) ", silent=TRUE))
test2 <- isTRUE(try( depf[2] == "sqrt(var(if (is.vector(x) || is.factor(x)) x else as.double(x), ", silent=TRUE))
test3 <- isTRUE(try( depf[3] == " na.rm = na.rm))", silent=TRUE))
if (test1 && test2 && test3) return("sd")
if (isTRUE(try( fun@generic == "which.min", silent=TRUE))) return("which.min")
if (isTRUE(try( fun@generic == "which.max", silent=TRUE))) return("which.max")
if (isTRUE(all(depf[1] == deparse(base::which)[1]))) return("which")
if (isTRUE(all(depf[1] == deparse(base::table)[1]))) return("table")
}
}
return(fun)
}
setMethod("aggregate", signature(x="SpatRaster"),
function(x, fact=2, fun="mean", ..., cores=1, filename="", overwrite=FALSE, wopt=list()) {
if (hasValues(x)) {
fun <- .makeTextFun(fun)
toc <- FALSE
if (inherits(fun, "character")) {
if (fun %in% c("sum", "mean", "min", "max", "median", "modal","prod", "which.min", "which.max",
"any", "all", "sd", "std", "sdpop", "table")) {
fun[fun == "sdpop"] <- "std"
toc <- TRUE
} else {
fun <- match.fun(fun)
}
} else {
fun <- match.fun(fun)
}
} else {
toc = TRUE
fun = "mean"
}
if (toc) {
# fun="mean", expand=TRUE, na.rm=TRUE, filename=""
narm <- isTRUE(list(...)$na.rm)
opt <- spatOptions(filename, overwrite, wopt=wopt)
x@pntr <- x@pntr$aggregate(fact, fun, narm, opt)
return (messages(x, "aggregate"))
} else {
out <- rast(x)
nl <- nlyr(out)
opt <- spatOptions()
out@pntr <- out@pntr$aggregate(fact, "sum", TRUE, opt)
out <- messages(out, "aggregate")
dims <- x@pntr$get_aggregate_dims(fact)
vtest <- values(x, dataframe=TRUE, row=1, nrows=dims[1], col=1, ncols=dims[2])
vtest <- as.list(vtest)
test <- sapply(vtest, fun, ...)
dm <- dim(test)
do_transpose = FALSE
if (!is.null(dm)) {
do_transpose = TRUE
}
if (inherits(test, "list")) {
error("aggregate", "fun returns a list")
}
fun_ret <- 1
if (length(test) > nl) {
if ((length(test) %% nl) == 0) {
fun_ret <- length(test) / nl
nlyr(out) <- nlyr(x) * fun_ret
} else {
error("aggregate", "cannot use this function")
}
}
b <- blocks(x, 4)
nr <- max(1, floor(b$nrows[1] / fact[1])) * fact[1]
nrs <- rep(nr, floor(nrow(x)/nr))
d <- nrow(x) - sum(nrs)
if (d > 0) nrs <- c(nrs, d)
b$row <- c(0, cumsum(nrs))[1:length(nrs)] + 1
b$nrows <- nrs
b$n <- length(nrs)
outnr <- ceiling(b$nrows / fact[1]);
outrows <- c(0, cumsum(outnr))[1:length(outnr)] + 1
nc <- ncol(x)
if (inherits(cores, "cluster")) {
doPar <- TRUE
} else if (cores > 1) {
doPar <- TRUE
cores <- parallel::makeCluster(cores)
on.exit(parallel::stopCluster(cores))
export_args(cores, ..., caller="aggregate")
} else {
doPar <- FALSE
}
mpl <- prod(dims[5:6]) * fun_ret
readStart(x)
on.exit(readStop(x))
ignore <- writeStart(out, filename, overwrite, sources=sources(x), wopt=wopt)
if (doPar) {
for (i in 1:b$n) {
v <- readValues(x, b$row[i], b$nrows[i], 1, nc)
v <- x@pntr$get_aggregates(v, b$nrows[i], dims)
v <- parallel::parSapply(cores, v, fun, ...)
if (length(v) != outnr[i] * mpl) {
error("aggregate", "this function does not return the correct number of values")
}
if (do_transpose) {
v <- t(v)
}
writeValues(out, v, outrows[i], outnr[i])
}
} else {
for (i in 1:b$n) {
v <- readValues(x, b$row[i], b$nrows[i], 1, nc)
v <- x@pntr$get_aggregates(v, b$nrows[i], dims)
v <- sapply(v, fun, ...)
if (length(v) != outnr[i] * mpl) {
error("aggregate", "this function does not return the correct number of values")
}
if (do_transpose) {
v <- t(v)
}
writeValues(out, v, outrows[i], outnr[i])
}
}
out <- writeStop(out)
messages(out, "aggregate")
}
}
)
.agg_uf <- function(i) {
u <- unique(i)
if (length(u) == 1) { u } else { NA }
}
aggregate_attributes <- function(d, by, fun=NULL, count=TRUE, ...) {
i <- sapply(d, is.numeric)
i[colnames(d) %in% by] <- FALSE
j <- 1:length(by)
da <- db <- NULL
if (!is.null(fun)) {
if (any(i)) {
if (is.character(fun)) {
f <- match.fun(fun)
da <- aggregate(d[, i,drop=FALSE], d[, by, drop=FALSE], f, ...)
names(da)[-j] <- paste0(fun, "_", names(da)[-j])
} else {
da <- aggregate(d[, i,drop=FALSE], d[, by, drop=FALSE], fun, ...)
names(da)[-j] <- paste0("agg_", names(da)[-j])
}
} else {
da <- unique(d[, by, drop=FALSE])
}
} else {
i[] <- FALSE
}
i[colnames(d) %in% by] <- TRUE
if (any(!i)) {
db <- aggregate(d[, !i,drop=FALSE], d[, by, drop=FALSE], .agg_uf)
#db <- db[, colSums(is.na(db)) < nrow(db), drop=FALSE]
if (NCOL(da)>1) {
da <- merge(da, db, by=by)
} else {
da <- db
}
}
if (count) {
dn <- aggregate(d[, by[1],drop=FALSE], d[, by, drop=FALSE], length)
colnames(dn)[ncol(dn)] = "agg_n"
if (NCOL(da) > 1) {
if (nrow(dn) > 0) {
dn <- merge(da, dn, by=by)
} else {
dn <- da
dn$agg_n <- 1
}
}
dn
} else {
da
}
}
setMethod("aggregate", signature(x="SpatVector"),
function(x, by=NULL, dissolve=TRUE, fun="mean", count=TRUE, ...) {
if (inherits(by, "SpatVector")) {
error("use 'zonal' to aggregate a SpatVector with a SpatVector")
}
if (is.null(by)) {
x$aggregate_by_variable = 1;
x@pntr <- x@pntr$aggregate("aggregate_by_variable", dissolve)
x$aggregate_by_variable = NULL;
} else {
if (is.character(by)) {
by <- unique(by)
iby <- match(by, names(x))
if (any(is.na(iby))) {
bad <- paste(by[is.na(iby)], collapse=", ")
error("aggregate", "invalid name(s) in by: ", bad)
}
} else if (is.numeric(by)) {
by <- unique(by)
iby <- round(by)
if (any((iby < 1) | (iby > ncol(x)))) {
bad <- iby[(iby < 1) | (iby > ncol(x))]
error("aggregate", "invalid column number in by: ", bad)
}
} else {
error("aggregate", "by should be character or numeric")
}
d <- values(x)
mvars <- FALSE
if (length(iby) > 1) {
cvar <- apply(d[, iby], 1, function(i) paste(i, collapse="_"))
by <- basename(tempfile())
values(x) <- NULL
x[[by]] <- cvar
mvars <- TRUE
} else {
by <- names(x)[iby]
}
x@pntr <- x@pntr$aggregate(by, dissolve)
messages(x)
if (mvars) {
d[[by]] <- cvar
a <- aggregate_attributes(d, c(by, names(d)[iby]), fun=fun, count=count, ...)
} else {
a <- aggregate_attributes(d, names(d)[iby], fun=fun, count=count, ...)
}
if (any(is.na(d[[by]]))) {
# because NaN and NA are dropped
i <- nrow(a)+(1:2)
a[i,] <- c(NA, NaN)
}
i <- match(x[[by,drop=TRUE]], a[[by]])
i <- i[!is.na(i)]
if (mvars) {
a[[by]] <- NULL
}
values(x) <- a[i,,drop=FALSE]
}
x
}
)
# setMethod("aggregate", signature(x="SpatVector"),
# function(x, by=NULL, dissolve=TRUE, fun="mean", ...) {
# gt <- geomtype(x)
# if (length(by) > 1) {
# error("aggregate", "this method can only aggregate by one variable")
# }
# x <- methods::as(x, "Spatial")
# if (is.numeric(by[1])) {
# i <- round(by)
# if ((i > 0) & (i <= ncol(x))) {
# by <- names(x)[i]
# } else {
# error("aggregate", "invalid column number supplied: ", by)
# }
# }
# r <- aggregate(x, by=by, dissolve=dissolve, ...)
# if (!missing(fun) && !missing(by)) {
# if (.hasSlot(x, "data")) {
# d <- x@data
# i <- sapply(d, is.numeric)
# i[colnames(d) %in% by] <- FALSE
# j <- 1:length(by)
# if (any(i)) {
# if (is.character(fun)) {
# f <- match.fun(fun)
# da <- aggregate(d[, i,drop=FALSE], d[, by, drop=FALSE], f)
# names(da)[-j] <- paste0(fun, "_", names(da)[-j])
# } else {
# da <- aggregate(d[, i,drop=FALSE], d[, by, drop=FALSE], fun)
# names(da)[-j] <- paste0("agg_", names(da)[-j])
# }
# r <- merge(r, da, by)
# }
# i[colnames(d) %in% by] <- TRUE
# if (any(!i)) {
# db <- aggregate(d[, !i,drop=FALSE], d[, by, drop=FALSE], .agg_uf)
# db <- db[, colSums(is.na(db)) < nrow(db), drop=FALSE]
# if (ncol(db) > 1) {
# r <- merge(r, db, by)
# }
# }
# dn <- aggregate(d[, by,drop=FALSE], d[, by, drop=FALSE], length)
# colnames(dn)[2] = "agg_n"
# r <- merge(r, dn, by)
# }
# }
# vect(r)
# }
# )
terra/R/extract_single.R 0000644 0001762 0000144 00000014700 14735320520 014731 0 ustar ligges users
make_extract_index <- function(v, vmx, name="i") {
caller <- paste0("`[`(", name, ")")
if (inherits(v, "SpatRaster")) {
error(caller, paste("index", name, "cannot be a SpatRaster"))
}
if (inherits(v, "SpatVector")) {
error(caller, paste("index", name, "cannot be a SpatVector"))
}
if (inherits(v, "SpatExtent")) {
error(caller, paste("index", name, "cannot be a SpatExtent"))
}
if (!is.numeric(v)) {
if (inherits(v, "data.frame")) {
if (ncol(v) == 1) {
v <- v[,1,drop=TRUE]
} else if ((name == "i") && (ncol(v) == 2)) {
v <- cellFromRowCol(x, v[,1], v[,2])
} else {
error(caller, paste("index", name, "has", ncol(v), "columns"))
}
} else if (inherits(v, "matrix")) {
if (ncol(v) == 1) {
v <- v[,1]
} else {
error(caller, paste("index", name, "is not numeric and has", ncol(v), "columns"))
}
}
if (!is.vector(v)) {
error(caller, paste("the type of index", name, "is unexpected:", class(v)[1]))
}
if (is.factor(v) || is.character(v)) {
error(caller, paste("the type of index", name, "cannot be a factor or character"))
}
if (is.logical(v)) {
v <- which(v)
}
if (!is.numeric(v)) {
error(caller, paste("the type of index", name, "is unexpected:", class(v)[1]))
}
}
if (inherits(v, "matrix")) {
if (ncol(v) == 1) {
v <- v[,1]
} else {
error(caller, paste("index", name, "has unexpected dimensions:", paste(dim(v), collapse=", ")))
}
}
positive_indices(v, vmx, FALSE, caller=caller)
}
.extract_spatraster <- function(x, i, drop) {
if (!hasValues(i)) {
error("`[`", "the index SpatRaster must have values")
}
if (nlyr(i) > 1) {
error("`[`", "the index SpatRaster can only have one layer")
}
if (!compareGeom(x, i, crs=FALSE, stopOnError=FALSE)) {
if (!drop) {
return(crop(x, i))
}
i <- cells(x, ext(i))
return (x[i, drop=drop])
}
if (drop) {
i <- which(values(i)==1)
values(x)[i, ,drop=FALSE]
} else {
if (is.bool(i)) {
mask(x, i, maskvalues=FALSE)
} else {
mask(x, i)
}
}
}
.extract_spatextent <- function(x, i, drop) {
x <- crop(x, i)
if (drop) {
values(x)
} else {
x
}
}
.extract_spatvector <- function(x, i, drop) {
if (drop) {
extract(x, i, data.frame=TRUE)[ , -1, drop=FALSE]
} else {
crop(x, i, mask=TRUE)
}
}
.extract_row <- function(x, i, drop=TRUE) {
if (!drop) {
e <- ext_from_rc(x, min(i), max(i), 1, ncol(x))
return(crop(x, e))
}
i <- cellFromRowColCombine(x, i, 1:ncol(x))
.extract_cell(x, i, drop=TRUE)
}
.extract_col <- function(x, j, drop=TRUE) {
if (!drop) {
e <- ext_from_rc(x, 1, nrow(x), min(j), max(j))
return(crop(x, e))
}
i <- cellFromRowColCombine(x, 1:nrow(x), j)
.extract_cell(x, i, drop=TRUE)
}
.extract_rowcol <- function(x, i, j, drop=TRUE) {
if (!drop) {
e <- ext_from_rc(x, min(i), max(i), min(j), max(j))
return(crop(x, e))
}
i <- cellFromRowColCombine(x, i, j)
.extract_cell(x, i, drop=TRUE)
}
.extract_cell <- function(x, i, drop=TRUE, raw=FALSE) {
if (!drop) {
rc <- rowColFromCell(x, i)
e <- ext_from_rc(x, min(rc[,1]), max(rc[,1]), min(rc[,2]), max(rc[,2]))
y <- crop(x, e)
y[-cellFromXY(y, xyFromCell(x, i))] <- NA
y
} else {
e <- x@pntr$extractCell(i-1)
x <- messages(x, "extract")
e <- do.call(cbind, e)
colnames(e) <- names(x)
if (raw) {
return(e)
}
.makeDataFrame(x, e)
}
}
.extract_cell_layer <- function(x, i, lyrs, drop) {
if (drop) {
e <- x@pntr$extractCell(i-1)
messages(x, "extract")
e <- do.call(cbind, e)
colnames(e) <- names(x)
e <- .makeDataFrame(x, e)
e[cbind(1:length(i), lyrs)]
} else {
rc <- rowColFromCell(x, i)
e <- ext_from_rc(x, min(rc[,1]), max(rc[,1]), min(rc[,2]), max(rc[,2]))
x <- x[unique(lyrs)]
crop(x, e)
}
}
setMethod("[", c("SpatRaster", "ANY", "ANY", "ANY"),
function(x, i, j, k, drop=TRUE) {
m <- c(missing(i), missing(j), missing(k))
if (!m[3]) {
if (is.logical(k) && length(k) == 1) {
drop <- k
m[3] <- TRUE
}
}
s <- rep(FALSE, 3)
if (!m[1]) s[1] <- is.list(i)
if (!m[2]) s[2] <- is.list(j)
if (!m[3]) s[3] <- is.list(k)
if (any(s)) {
if (m[1]) i <- NULL
if (m[2]) j <- NULL
if (m[3]) k <- NULL
m <- c(FALSE, TRUE, TRUE)
i <- rcl(x, row=i, col=j, lyr=k)
}
if ((!m[1]) && (inherits(i, "matrix"))) {
if (ncol(i) == 1) {
i <- i[,1]
} else if (ncol(i) == 2) {
i <- cellFromRowCol(x, i[,1], i[,2])
m[2:3] <- TRUE
} else if (ncol(i) == 3) {
k <- i[,3]
i <- cellFromRowCol(x, i[,1], i[,2])
uk <- unique(k)
if (length(uk) == 1) {
x <- x[[uk]]
m[2:3] <- TRUE
} else {
return(.extract_cell_layer(x, i, k, drop))
}
} else {
error("`[<-`", paste("index i has", ncol(i), "columns"))
}
}
if (!m[3]) {
if (is.logical(k) && length(k) == 1) {
drop <- k
m[3] <- TRUE
} else {
if (inherits(k, "character")) {
k <- match(k, names(x))
if (any(is.na(k))) {
error("`[`(k)", "invalid layer name(s)")
}
} else {
k <- make_extract_index(k, nlyr(x), "k")
}
x <- x[[k]]
}
}
if ((!m[1]) && (inherits(i, "character"))) {
# partial matching of layer names
i <- grep(i, names(x))
x <- subset(x, i, NSE=FALSE)
if (m[2]) return(x)
m[1] <- TRUE
}
if (m[1] && m[2]) {
if (drop) {
return(values(x, mat=TRUE))
} else {
return(deepcopy(x))
}
}
if (!m[1]) { # i not missing
if (inherits(i, "SpatRaster")) {
return(.extract_spatraster(x, i, drop))
}
if (inherits(i, "SpatVector")) {
return(.extract_spatextent(x, i, drop))
}
if (inherits(i, "SpatVector")) {
return(.extract_spatextent(x, i, drop))
}
theCall <- sys.call(-1)
narg <- length(theCall)-length(match.call(call=theCall))
if ((narg==0) && m[2]) {
# cell
i <- make_extract_index(i, ncell(x), "i")
return(.extract_cell(x, i, drop=drop))
} else if (m[2]) {
# row
i <- make_extract_index(i, nrow(x), "i")
return(.extract_row(x, i, drop=drop))
} else {
#row,col
i <- make_extract_index(i, nrow(x), "i")
j <- make_extract_index(j, ncol(x), "j")
return(.extract_rowcol(x, i, j, drop=drop))
}
} else { #if (!m[2]) {
#col
j <- make_extract_index(j, ncol(x), "j")
return(.extract_col(x, j, drop=drop))
}
}
)
setMethod("[", c("SpatVector", "SpatVector", "missing"),
function(x, i, j) {
#r <- !relate(x, i, "disjoint")
#r <- which(apply(r, 1, any))
r <- is.related(x, i, "intersects")
x[r, ]
})
setMethod("[", c("SpatVector", "SpatExtent", "missing"),
function(x, i, j) {
x[as.polygons(i)]
})
terra/R/image.R 0000644 0001762 0000144 00000001517 14536376240 013013 0 ustar ligges users # Author: Robert J. Hijmans
# Date : April 2019
# Version 1.0
# License GPL v3
.plot_image <- function(x, y=1, xlab="", ylab="", asp=NULL, ...) {
X <- xFromCol(x, 1:ncol(x))
Y <- yFromRow(x, nrow(x):1)
value <- matrix(as.vector(x), nrow=nrow(x), byrow=TRUE)
value <- t(value[nrow(value):1, ,drop=FALSE])
if (is.null(asp)) {
asp <- ifelse(is.lonlat(x, perhaps=TRUE, warn=FALSE), 1/cos((mean(as.vector(ext(x))[3:4]) * pi)/180), 1)
graphics::image(x=X, y=Y, z=value, asp=asp, xlab=xlab, ylab=ylab, ...)
} else {
graphics::image(x=X, y=Y, z=value, xlab=xlab, ylab=ylab, ...)
}
}
setMethod("image", signature(x="SpatRaster"),
function(x, y=1, maxcell=500000, ...) {
y <- as.integer(y[1])
stopifnot(y > 0 && y <= nlyr(x))
x <- spatSample(x[[y]], maxcell, method="regular", as.raster=TRUE, warn=FALSE)
.plot_image(x, ...)
}
)
terra/R/Aclasses.R 0000644 0001762 0000144 00000004625 14726700402 013462 0 ustar ligges users # Author: Robert J. Hijmans, r.hijmans@gmail.com
# Date : November 2017
# Version 0
# License GPL v3
setClass("SpatRaster",
representation (
pntr = "C++Object"
),
prototype (
pntr = NULL
),
validity = function(object) {
if (is.null(object@pntr) || is(object@pntr, "Rcpp_SpatRaster")){
return(TRUE)
} else {
return(FALSE)
}
}
)
setClass("SpatRasterDataset",
representation (
pntr = "C++Object"
),
prototype (
pntr = NULL
),
validity = function(object) {
if (is.null(object@pntr) || is(object@pntr, "Rcpp_SpatRasterStack")){
return(TRUE)
} else {
return(FALSE)
}
}
)
setClass("SpatRasterCollection",
representation (
pntr = "C++Object"
),
prototype (
pntr = NULL
),
validity = function(object) {
if (is.null(object@pntr) || is(object@pntr, "Rcpp_SpatRasterCollection")){
return(TRUE)
} else {
return(FALSE)
}
}
)
setClass("SpatVector",
representation (
pntr = "C++Object"
),
prototype (
pntr = NULL
),
validity = function(object) {
if (is.null(object@pntr) || is(object@pntr, "Rcpp_SpatVector")){
return(TRUE)
} else {
return(FALSE)
}
}
)
setClass("SpatVectorProxy",
representation (
pntr = "C++Object"
),
prototype (
pntr = NULL
),
validity = function(object) {
if (is.null(object@pntr) || is(object@pntr, "Rcpp_SpatVectorProxy")){
return(TRUE)
} else {
return(FALSE)
}
}
)
setClass("SpatVectorCollection",
representation (
pntr = "C++Object"
),
prototype (
pntr = NULL
),
validity = function(object) {
if (is.null(object@pntr) || is(object@pntr, "Rcpp_SpatVectorCollection")){
return(TRUE)
} else {
return(FALSE)
}
}
)
setClass("SpatExtent",
representation (
pntr = "C++Object"
),
prototype (
pntr = NULL
),
validity = function(object) {
if (is.null(object@pntr) || is(object@pntr, "Rcpp_SpatExtent")){
return(TRUE)
} else {
return(FALSE)
}
}
)
setClass("SpatOptions",
representation (
pntr = "C++Object"
),
prototype (
pntr = NULL
),
validity = function(object) {
if (is.null(object@pntr) || is(object@pntr, "Rcpp_SpatOptions")){
return(TRUE)
} else {
return(FALSE)
}
}
)
setClass("SpatGraticule",
representation (
pntr = "C++Object",
box = "C++Object"
),
prototype (
pntr = NULL,
pntr = NULL
),
validity = function(object) {
if (is.null(object@pntr) || is(object@pntr, "Rcpp_SpatVector")){
return(TRUE)
} else {
return(FALSE)
}
}
)
terra/R/graticule.R 0000644 0001762 0000144 00000011674 14726700274 013714 0 ustar ligges users # Author: Robert J. Hijmans, r.hijmans@gmail.com
# Date : November 2022
# Version 1
# License GPL v3
graticule <- function(lon=30, lat=30, crs="") {
if (crs == "") {
crs <- "+proj=longlat"
}
if (length(lon) == 1) {
lon <- seq(-180, 180, lon)
} else {
lon <- sort(lon)
}
if (length(lat) == 1) {
lat <- seq(-90, 90, lat)
} else {
lat <- sort(lat)
}
interval <- 100 #should depend on extent
y <- cbind(rep(1:length(lon), each=2), rep(lon, each=2), range(lat))
vy <- vect(y, "lines", crs="+proj=longlat")
vy <- densify(vy, interval*1000, TRUE)
values(vy) <- data.frame(h=FALSE, lon=lon)
rlon <- range(lon)
rlon <- c(rlon[1], rlon[1] + (rlon[2]-rlon[1])/2, rlon[2])
x <- cbind(rep(1:length(lat), each=3), rlon, rep(lat, each=3))
vx <- vect(x, "lines", crs="local")
vx <- densify(vx, interval/110, TRUE)
values(vx) <- data.frame(h=TRUE, lat=lat)
crs(vx, warn=FALSE) <- "+proj=longlat"
v <- rbind(vy, vx)
e <- as.polygons(ext(v), crs=crs(v))
e <- densify(e, interval*1000, TRUE)
if (!is.lonlat(crs, FALSE, FALSE)) {
v <- project(v, crs)
e <- project(e, crs)
}
g <- new("SpatGraticule")
g@pntr <- v@pntr
g@box <- e@pntr
g
}
#setMethod("project", signature(x="SpatGraticule"),
# function(x, y) {
# v <- vect(x)
# v <- project(v, y)
# x@pntr <- v@pntr
# v@pntr <- x@box
# v <- project(v, y)
# x@box <- v@pntr
# x
# }
#)
setMethod("crop", signature(x="SpatGraticule"),
function(x, y) {
v <- vect(x)
v <- crop(v, y)
x@pntr <- v@pntr
v@pntr <- x@box
v <- crop(v, y)
x@box <- v@pntr
x
}
)
setMethod("erase", signature(x="SpatGraticule", y="SpatVector"),
function(x, y) {
v <- vect(x)
y <- project(y, v)
v <- erase(v, y)
x@pntr <- v@pntr
v@pntr <- x@box
v <- erase(v, y)
x@box <- v@pntr
x
}
)
grat_labels <- function(x, retro, atlon, atlat, labloc, cex, col, offlon, offlat, vfont=NULL, font=NULL, ...) {
v <- vect(x)
left <- right <- top <- bottom <- FALSE
labloc <- rep_len(labloc, 2)
if (!is.na(labloc[1])) {
if (labloc[1] == 1) {
bottom <- TRUE
} else if (labloc[1] == 2) {
top <- TRUE
} else {
bottom <- TRUE
top <- TRUE
}
}
if (!is.na(labloc[2])) {
if (labloc[2] == 1) {
left <- TRUE
} else if (labloc[2] == 2) {
right <- TRUE
} else {
left <- TRUE
right <- TRUE
}
}
if (left || right) {
s <- sign(offlat)+2
x <- v[v$h, ]
g <- geom(x)
if (retro) {
labs <- retro_labels(x$lat, lat=TRUE)
} else {
labs <- paste0(x$lat,"\u00B0")
}
if (!is.null(atlat)) {
atlat <- round(stats::na.omit(atlat))
atlat <- atlat[(atlat > 0) & (atlat <= length(labs))]
labs <- labs[atlat]
}
if (left) {
a <- vect(g[match(unique(g[,1]), g[,1]), 3:4])
if (!is.null(atlat)) {
a <- a[atlat, ]
}
pos <- c(4,0,2)[s]
if (pos == 0) pos <- NULL
text(a, labels=labs, pos=pos, offset=abs(offlat), cex=cex, halo=TRUE, xpd=TRUE, col=col)
}
if (right) {
g <- g[nrow(g):1, ]
a <- vect(g[match(unique(g[,1]), g[,1]), 3:4])
if (!is.null(atlat)) {
a <- a[atlat, ]
labs <- rev(labs)
}
pos <- c(2,0,4)[s]
if (pos == 0) pos <- NULL
text(a, labels=labs, pos=pos, offset=abs(offlat), cex=cex, halo=TRUE, xpd=TRUE, col=col)
}
}
if (top || bottom) {
s <- sign(offlon)+2
x <- v[!v$h, ]
g <- geom(x)
if (retro) {
labs <- retro_labels(x$lon, lat=FALSE)
} else {
labs <- paste0(x$lon,"\u00B0")
}
if (!is.null(atlon)) {
atlon <- round(stats::na.omit(atlon))
atlon <- atlon[(atlon > 0) & (atlon <= length(labs))]
labs <- labs[atlon]
}
if (bottom) {
a <- vect(g[match(unique(g[,1]), g[,1]), 3:4])
if (!is.null(atlon)) {
a <- a[atlon, ]
}
pos <- c(3,0,1)[s]
if (pos == 0) pos <- NULL
text(a, labels=labs, pos=pos, offset=abs(offlon), cex=cex, halo=TRUE, xpd=TRUE, col=col)
}
if (top) {
g <- g[nrow(g):1, ]
a <- vect(g[match(unique(g[,1]), g[,1]), 3:4])
if (!is.null(atlon)) {
a <- a[atlon, ]
labs <- rev(labs)
}
pos <- c(1,0,3)[s]
if (pos == 0) pos <- NULL
text(a, labels=labs, pos=pos, offset=abs(offlon), cex=cex, halo=TRUE, xpd=TRUE, col=col)
}
}
}
setMethod("plot", signature(x="SpatGraticule", y="missing"),
function(x, y, background=NULL, col="black", mar=NULL, labels=TRUE, retro=FALSE, lab.loc=c(1,1), lab.lon=NULL, lab.lat=NULL, lab.cex=.65, lab.col="black", off.lat=0.25, off.lon=0.25, box=FALSE, box.col="black", add=FALSE, ...) {
b <- vect()
b@pntr <- x@box
if (!is.null(mar)) mar <- rep_len(mar, 4)
if (!is.null(background)) {
plot(b, col=background, border=NA, axes=FALSE, mar=mar, add=add)
} else {
if (!add) {
plot(ext(b), border=NA, axes=FALSE, mar=mar)
}
}
lines(x, col=col, ...)
if (box) {
lwd <- list(...)$lwd
if (is.null(lwd)) lwd=1;
lines(b, lty=1, col=box.col, lwd=lwd)
}
if (labels) grat_labels(x, isTRUE(retro[1]), lab.lon, lab.lat, lab.loc, lab.cex[1], lab.col[1], off.lon, off.lat, ...)
}
)
setMethod("lines", signature(x="SpatGraticule"),
function(x, ...) {
lines(vect(x), ...)
}
)
terra/R/princomp.R 0000644 0001762 0000144 00000002275 14645307434 013562 0 ustar ligges users
setMethod("princomp", signature(x="SpatRaster"),
function(x, cor=FALSE, fix_sign=TRUE, use="pairwise.complete.obs", maxcell=Inf) {
if (!hasValues(x)) {
error("princomp", "x has no values")
}
if (nlyr(x) < 2) {
error("princomp", "The number of layers of x must be > 1")
}
xcov <- layerCor(x, fun="cov", use=use, asSample=FALSE, maxcell=maxcell)
if (any(is.na(xcov[["covariance"]]))) {
error("princomp", "the covariance matrix has missing values")
}
model <- princomp(covmat=xcov$covariance, cor=cor, fix_sign=fix_sign)
model$center <- diag(xcov$mean)
n <- diag(xcov$n)
if (cor) {
## scale as population sd
S <- diag(xcov$covariance)
model$scale <- sqrt(S)
}
model$n.obs <- stats::as.dist(xcov$n)
model
}
)
setMethod("prcomp", signature(x="SpatRaster"),
function(x, retx = TRUE, center = TRUE, scale. = FALSE, tol = NULL, rank. = NULL, maxcell=Inf) {
d <- na.omit(spatSample(x, maxcell, "regular"))
p <- prcomp(d, retx=retx, center=center, scale.=scale., tol=tol, rank.=rank.)
nms <- names(p$center)
nms <- nms[!(nms %in% names(x))]
if (length(nms) > 0) {
warn("prcomp", "names were changed to make them valid. See 'valid.names'")
}
p
}
)
terra/R/clip.R 0000644 0001762 0000144 00000001500 14624317253 012645 0 ustar ligges users
set.clip <- function(clp, geo) {
# remove non-existing ones
x <- grDevices::dev.list()
x <- paste(names(x), x, sep="_")
e <- .terra_environment$devs
e <- e[e[,1] %in% x, ]
graphics::clip(clp[1], clp[2], clp[3], clp[4])
d <- grDevices::dev.cur()
d <- data.frame(dev=paste(names(d), d[[1]], sep="_"), rbind(clp), geo=geo, row.names="")
# remove one with the same name/number
e <- e[!(e[,1] %in% d[1]), ]
e <- rbind(e, d)
.terra_environment$devs <- e
}
get.clip <- function() {
d <- grDevices::dev.cur()
dev <- paste(names(d), d[[1]], sep="_")
e <- .terra_environment$devs
i <- match(dev, e[,1])[1]
if (is.na(i)) {
NULL
} else {
e[i[1],-1]
}
}
reset.clip <- function() {
g <- get.clip()
if (!is.null(g)) {
graphics::clip(g[[1]], g[[2]], g[[3]], g[[4]])
}
}
map_extent <- function() {
get.clip()
}
terra/R/zzz.R 0000644 0001762 0000144 00000003121 14736322043 012551 0 ustar ligges users
## from htmltools for future use with knitr
## method = c(package, genname, class).
#registerMethods <- function(methods) {
# lapply(methods, function(method) {
# pkg <- method[[1]]
# generic <- method[[2]]
# class <- method[[3]]
# func <- get(paste(generic, class, sep="."))
# if (pkg %in% loadedNamespaces()) {
# registerS3method(generic, class, func, envir = asNamespace(pkg))
# }
# setHook(
# packageEvent(pkg, "onLoad"),
# function(...) {
# registerS3method(generic, class, func, envir = asNamespace(pkg))
# }
# )
# }
# )
#}
.gdinit <- function() {
path = ""
sf <- system.file("", package="terra")
if (file.exists(file.path(sf, "proj/nad.lst"))) {
path <- system.file("proj", package="terra")
}
.gdalinit(path, file.path(sf, "gdal"))
if (libVersion("gdal") == "3.6.0") {
message("Using GDAL version 3.6.0 which was retracted because it cannot write large GPKG files")
}
}
loadModule("spat", TRUE)
.onLoad <- function(libname, pkgname) {
.gdinit()
#registerMethods(list(c(package, genname, class)))
}
.onAttach <- function(libname, pkgname) {
packageStartupMessage("terra ", utils::packageVersion("terra"))
.create_options()
if (length(grep(.geos_version(FALSE, TRUE), .geos_version(TRUE))) != 1) {
packageStartupMessage("WARNING: different compile-time and run-time versions of GEOS")
packageStartupMessage("Compiled with:", .geos_version(FALSE, TRUE))
packageStartupMessage(" Running with:", .geos_version(TRUE, TRUE))
packageStartupMessage("\nYou should reinstall package 'terra'\n")
}
# terraOptions(todisk=TRUE, steps=2)
# terraOptions(memfrac=0)
}
terra/R/extract.R 0000644 0001762 0000144 00000034213 14750564600 013377 0 ustar ligges users # Author: Robert J. Hijmans
# Date : November 2018
# Version 1.0
# License GPL v3
.big_number_warning <- function() {
# this warning should be given by C
warn("big number", "cell numbers larger than ", 2^.Machine$double.digits, " are approximate")
}
ext_from_rc <- function(x, r1, r2, c1, c2){
e <- as.vector(ext(x))
r <- res(x)
c1 <- min(max(c1, 1), ncol(x))
c2 <- min(max(c2, 1), ncol(x))
if (c1 > c2) {
tmp <- c1
c1 <- c2
c2 <- tmp
}
r1 <- min(max(r1, 1), nrow(x))
r2 <- min(max(r2, 1), nrow(x))
if (r1 > r2) {
tmp <- r1
r1 <- r2
r2 <- tmp
}
xn <- xFromCol(x, c1) - 0.5 * r[1]
xx <- xFromCol(x, c2) + 0.5 * r[1]
yx <- yFromRow(x, r1) + 0.5 * r[2]
yn <- yFromRow(x, r2) - 0.5 * r[2]
ext(c(sort(c(xn, xx))), sort(c(yn, yx)))
}
getLyrNrs <- function(layer, nms, n) {
nl <- length(nms)
if (is.numeric(layer)) {
layer <- round(layer)
if (min(layer, na.rm=TRUE) < 1 || max(layer, na.rm=TRUE) > nl) {
error("extract", "layer should be between 1 and nlyr(x)")
}
} else {
layer <- match(layer, nms)
}
if (any(is.na(layer))) {
# error("extract", "names in argument 'layer' do not match names(x)")
}
rep_len(layer, n)
}
extractCells <- function(x, y, raw=FALSE) {
e <- x@pntr$extractCell(y-1)
e <- do.call(cbind, e)
colnames(e) <- names(x)
if (!raw) {
e <- .makeDataFrame(x, e)
}
e
}
use_layer <- function(e, y, layer, nl) {
if (is.null(layer)) {
return(e)
}
layer <- getLyrNrs(layer, colnames(e)[-1], nrow(y))
idx <- cbind(1:nrow(e), layer[e[,1]] + 1)
ee <- data.frame(e[,1,drop=FALSE], colnames(e)[idx[,2]], value=e[idx])
colnames(ee)[2] <- "layer"
if (ncol(e) > (nl+1)) {
cbind(ee, e[,(nl+1):ncol(e), drop=FALSE])
} else {
ee
}
}
extract_table <- function(x, y, ID=FALSE, weights=FALSE, exact=FALSE, touches=FALSE, small=TRUE, na.rm=FALSE) {
if (weights && exact) {
exact = FALSE
}
opt <- spatOptions()
if (weights | exact) {
wtable <- function(p, na.rm=FALSE) {
n <- length(p)
w <- p[[n]]
p[[n]] <- NULL
do.call( rbind,
lapply(1:length(p), function(i) {
x <- p[[i]]
j <- is.na(x)
if (na.rm) {
x <- x[!j]
w <- w[!j]
} else if (any(j)) {
w[] <- NA
}
data.frame(layer=i, aggregate(w, list(x), sum, na.rm=FALSE))
})
)
}
e <- x@pntr$extractVector(y@pntr, touches[1], small[1], "simple", FALSE, FALSE,
isTRUE(weights[1]), isTRUE(exact[1]), opt)
x <- messages(x, "extract")
e <- lapply(e, wtable, na.rm=na.rm)
e <- lapply(1:length(e), function(i) cbind(ID=i, e[[i]]))
e <- do.call(rbind, e)
colnames(e)[3:4] <- c("group", "value")
out <- vector("list", nlyr(x))
for (i in 1:nlyr(x)) {
ee <- e[e[,2] == i, ]
ee <- replace_with_label(x[[i]], ee, 3)
ee <- stats::reshape(ee, idvar=c("ID", "layer"), timevar="group", direction="wide")
colnames(ee) <- gsub("value.", "", colnames(ee))
ee$layer <- NULL
if (!ID) {
ee$ID <- NULL
}
if (na.rm) {
ee[is.na(ee)] <- 0
}
out[[i]] <- ee
}
if (nlyr(x) == 1) return(out[[1]]) else return(out)
} else {
e <- x@pntr$extractVectorFlat(y@pntr, "", FALSE, touches[1], small[1], "", FALSE, FALSE, FALSE, FALSE, opt)
x <- messages(x, "extract")
e <- data.frame(matrix(e, ncol=nlyr(x)+1, byrow=TRUE))
colnames(e) <- c("ID", names(x))
id <- e[,1,drop=FALSE]
e <- cbind(id, .makeDataFrame(x, e[,-1,drop=FALSE]))
cn <- colnames(e)
out <- vector("list", ncol(e)-1)
for (i in 2:ncol(e)) {
fixname <- TRUE
if (!is.factor(e[,i])) {
fixname <- FALSE
e[,i] <- as.factor(e[,i])
}
tb <- table(e[,1], e[,i])
tb <- cbind(ID = rownames(tb), as.data.frame.matrix(tb))
if (fixname) colnames(tb) <- gsub(cn[i], "", colnames(tb))
if (!ID) {
tb$ID <- NULL
}
tb$layer <- NULL
out[[i-1]] <- tb
}
if (ncol(e) == 2) return(out[[1]]) else return(out)
}
}
extract_fun <- function(x, y, fun, ID=TRUE, weights=FALSE, exact=FALSE, touches=FALSE, small=TRUE, layer=NULL, bind=FALSE, na.rm=FALSE) {
nl <- nlyr(x)
nf <- length(fun)
if ((nf > 1) & (!is.null(layer))) {
error("extract", "you cannot use argument 'layer' when using multiple functions")
}
opt <- spatOptions()
e <- x@pntr$extractVectorFlat(y@pntr, fun, na.rm, touches[1], small[1], "", FALSE, FALSE, weights, exact, opt)
x <- messages(x, "extract")
e <- data.frame(matrix(e, ncol=nl*nf, byrow=TRUE))
if (nf == 1) {
colnames(e) <- names(x)
} else {
colnames(e) <- apply(cbind(rep(fun, each=nl), names(x)), 1, function(i) paste(i, collapse="_"))
}
if (!is.null(layer)) {
e <- cbind(ID=1:nrow(e), e)
e <- use_layer(e, y, layer, nlyr(x))
if (!ID || bind) {
e$ID <- NULL
}
ID <- FALSE
}
if (bind) {
if (nrow(e) == nrow(y)) {
e <- data.frame(e)
e <- cbind(y, e)
} else {
#? can this occur?
warn("extract", "cannot return a SpatVector because the number of records extracted does not match he number of rows in y (perhaps you need to use a summarizing function")
}
} else if (ID) {
e <- cbind(ID=1:nrow(e), e)
}
e
}
do_fun <- function(e, fun, ...) {
fun <- match.fun(fun)
e <- aggregate(e[,-1,drop=FALSE], e[,1,drop=FALSE], fun, ...)
m <- sapply(e, NCOL)
if (any(m > 1)) {
cn <- names(e)
e <- do.call(cbind, as.list(e))
i <- rep(1, length(cn))
i[m>1] <- m[m>1]
cn <- rep(cn, i)
cn <- make.names(cn, TRUE)
if (length(cn) == ncol(e)) {
colnames(e) <- cn
}
}
e
}
setMethod("extract", signature(x="SpatRaster", y="SpatVector"),
function(x, y, fun=NULL, method="simple", cells=FALSE, xy=FALSE, ID=TRUE, weights=FALSE, exact=FALSE, touches=is.lines(y), small=TRUE, layer=NULL, bind=FALSE, raw=FALSE, search_radius=0, ...) {
geo <- geomtype(y)
if (!is.null(layer)) {
if (length(layer) != nrow(y)) {
error("extract", "length(layer) != nrow(y)")
}
}
if (geo == "points") {
if (search_radius > 0) {
pts <- crds(y)
e <- x@pntr$extractBuffer(pts[,1], pts[,2], search_radius)
messages(x, "extract")
e <- do.call(cbind, e)
colnames(e) <- c(names(x)[1], "distance", "cell")
e[,3] <- e[,3] + 1
if (xy) {
e <- cbind(xyFromCell(x, e[,3]), e)
}
if (!raw) {
e <- cbind(.makeDataFrame(x, e[,1,drop=FALSE]), e[,2:3])
}
if (bind) {
e <- data.frame(e)
e <- cbind(y, e)
} else if (ID) {
e <- cbind(ID=1:nrow(e), e)
}
return(e)
} else if (weights || exact) {
method <- "bilinear"
weights <- FALSE
exact <- FALSE
}
# method <- match.arg(tolower(method), c("simple", "bilinear"))
} else if (!is.null(fun)) { # nothing to summarize for points
txtfun <- .makeTextFun(fun)
if (inherits(txtfun, "character")) {
if (any(txtfun == "table")) {
if (length(fun) > 1) {
warn("extract", "'table' cannot be combined with other functions")
}
if (!is.null(layer)) {
warn("extract", "argument 'layer' is ignored when 'fun=table'")
}
e <- extract_table(x, y, ID=ID, weights=weights, exact=exact, touches=touches, small=small, ...)
} else {
e <- extract_fun(x, y, txtfun, ID=ID, weights=weights, exact=exact, touches=touches, small=small, bind=bind, layer=layer, ...)
}
return(e)
} else if (weights || exact) {
error("extract", "if 'weights' or 'exact' is TRUE, you can only use functions mean, sum, min, max and table")
}
xy <- cells <- FALSE
raw <- TRUE
}
opt <- spatOptions()
e <- x@pntr$extractVectorFlat(y@pntr, "", FALSE, touches[1], small[1], method, isTRUE(cells[1]), isTRUE(xy[1]), isTRUE(weights[1]), isTRUE(exact[1]), opt)
x <- messages(x, "extract")
cn <- c("ID", names(x))
nc <- nl <- nlyr(x)
if (cells) {
cn <- c(cn, "cell")
nc <- nc + 1
}
if (xy) {
cn <- c(cn, "x", "y")
nc <- nc + 2
}
if (weights) {
cn <- c(cn, "weight")
nc <- nc + 1
} else if (exact) {
cn <- c(cn, "fraction")
nc <- nc + 1
}
if (geo == "points") {
## this was? should be fixed upstream
if (nc == nl) {
e <- matrix(e, ncol=nc)
} else {
e <- matrix(e, ncol=nc, byrow=TRUE)
}
e <- cbind(1:nrow(e), e)
if (nrow(e) > nrow(y)) { #multipoint
g <- geom(y)
e[,1] <- g[,1]
}
} else {
e <- matrix(e, ncol=nc+1, byrow=TRUE)
}
colnames(e) <- cn
if (!is.null(fun)) {
e <- as.data.frame(e)
e <- do_fun(e, fun, ...)
}
if (cells) {
cncell <- cn =="cell"
e[, cncell] <- e[, cncell] + 1
}
if (!raw) {
if (method != "simple") {
e <- as.data.frame(e)
} else {
id <- data.frame(e[,1,drop=FALSE])
e <- cbind(id, .makeDataFrame(x, e[,-1,drop=FALSE]))
}
}
e <- use_layer(e, y, layer, nl)
if (bind) {
if (nrow(e) == nrow(y)) {
e <- data.frame(e)
e <- cbind(y, e[,-1,drop=FALSE])
} else {
warn("extract", "cannot return a SpatVector because the number of records extracted does not match the number of rows in y (perhaps you need to use a summarizing function")
}
} else if (!ID) {
e <- e[,-1,drop=FALSE]
}
e
})
setMethod("extract", signature(x="SpatRaster", y="sf"),
function(x, y, fun=NULL, method="simple", cells=FALSE, xy=FALSE, ID=TRUE, weights=FALSE, exact=FALSE, touches=is.lines(y), layer=NULL, bind=FALSE, ...) {
y <- vect(y)
extract(x, y, fun=fun, method=method, cells=cells, xy=xy, ID=ID, weights=weights, exact=exact, touches=touches, layer=layer, bind=bind, ...)
}
)
setMethod("extract", signature(x="SpatRaster", y="data.frame"),
function(x, y, ...) {
if (ncol(y) != 2) {
error("extract", "extract expects a 2 column data.frame of x and y coordinates")
}
v <- vect(y, colnames(y))
extract(x, v, ...)
})
setMethod("extract", signature(x="SpatRaster", y="numeric"),
function(x, y, xy=FALSE, raw=FALSE) {
y <- round(y)
# y[(y < 1) | (y > ncell(x))] <- NA
v <- .extract_cell(x, y, drop=TRUE, raw=raw)
if (xy) {
v <- cbind(xyFromCell(x, y), v)
}
v
})
setMethod("extract", signature(x="SpatRaster", y="matrix"),
function(x, y, cells=FALSE, method="simple") {
.checkXYnames(colnames(y))
method <- match.arg(tolower(method), c("simple", "bilinear"))
if (method != "simple") {
y <- vect(y)
return(extract(x, y, method=method, ID=FALSE))
}
y <- cellFromXY(x, y)
if (cells) {
cbind(cell=y, extract(x, y))
} else {
extract(x, y)
}
})
setMethod("extract", signature(x="SpatRaster", y="SpatExtent"),
function(x, y, cells=FALSE, xy=FALSE) {
y <- cells(x, y)
v <- extract(x, y, xy=xy)
if (cells) {
v <- cbind(cell=y, v)
}
v
}
)
setMethod("extract", c("SpatVector", "SpatVector"),
function(x, y) {
e <- relate(y, x, "coveredby", pairs=TRUE, na.rm=FALSE)
if (ncol(x) > 0) {
d <- as.data.frame(x)
e <- data.frame(id.y=e[,1], d[e[,2], ,drop=FALSE])
rownames(e) <- NULL
} else {
colnames(e) <- c("id.y", "id.x")
}
e
})
setMethod("extract", signature(x="SpatVector", y="matrix"),
function(x, y) {
stopifnot(ncol(y) == 2)
.checkXYnames(colnames(y))
y <- vect(y)
extract(x, y)
})
setMethod("extract", signature(x="SpatVector", y="data.frame"),
function(x, y) {
extract(x, as.matrix(y))
})
setMethod("extract", signature(x="SpatRasterCollection", y="ANY"),
function(x, y, ...) {
lapply(x, function(r) extract(r, y, ...))
}
)
setMethod("extract", signature(x="SpatRasterDataset", y="ANY"),
function(x, y, ...) {
lapply(x, function(r) extract(r, y, ...))
}
)
extractAlong <- function(x, y, ID=TRUE, cells=FALSE, xy=FALSE, online=FALSE, bilinear=TRUE) {
stopifnot(inherits(x, "SpatRaster"))
if (inherits(y, "sf")) {
y <- vect(y)
} else {
stopifnot(inherits(y, "SpatVector"))
}
stopifnot(geomtype(y) == "lines")
spbb <- as.matrix(ext(y))
rsbb <- as.matrix(ext(x))
addres <- 2 * max(res(x))
nlns <- nrow(y)
res <- vector(mode = "list", length = nlns)
if (spbb[1,1] > rsbb[1,2] | spbb[1,2] < rsbb[1,1] | spbb[2,1] > rsbb[2,2] | spbb[2,2] < rsbb[2,1]) {
res <- data.frame(matrix(ncol=nlyr(x)+4, nrow=0))
colnames(res) <- c("ID", "cell", "x", "y", names(x))
if (!cells) res$cell <- NULL
if (!xy) {
res$x <- NULL
res$y <- NULL
}
if (!ID) res$ID <- NULL
return(res)
}
rr <- rast(x)
g <- data.frame(geom(y))
for (i in 1:nlns) {
yp <- g[g$geom == i, ]
nparts <- max(yp$part)
vv <- NULL
for (j in 1:nparts) {
pp <- as.matrix(yp[yp$part==j, c("x", "y"), ])
for (k in 1:(nrow(pp)-1)) {
ppp <- pp[k:(k+1), ]
spbb <- t(ppp)
if (! (spbb[1,1] > rsbb[1,2] | spbb[1,2] < rsbb[1,1] | spbb[2,1] > rsbb[2,2] | spbb[2,2] < rsbb[2,1]) ) {
lns <- vect(ppp, "lines")
rc <- crop(rr, ext(lns) + addres)
rc <- rasterize(lns, rc, touches=TRUE)
cxy <- crds(rc)
v <- cbind(row=rowFromY(rr, cxy[,2]), col=colFromX(rr, cxy[,1]))
#up or down?
updown <- c(1,-1)[(ppp[1,2] < ppp[2,2]) + 1]
rightleft <- c(-1,1)[(ppp[1,1] < ppp[2,1]) + 1]
v <- v[order(updown*v[,1], rightleft*v[,2]), ]
vv <- rbind(vv, v)
}
}
}
if (!is.null(vv)) {
cell <- cellFromRowCol(rr, vv[,1], vv[,2])
res[[i]] <- data.frame(i, cell)
}
}
res <- do.call(rbind, res)
if (is.null(res)) {
if (xy) {
res <- data.frame(matrix(ncol=nlyr(x)+4, nrow=0))
colnames(res) <- c("ID", "cell", "x", "y", names(x))
} else {
res <- data.frame(matrix(ncol=nlyr(x)+2, nrow=0))
colnames(res) <- c("ID", "cell", names(x))
}
} else {
colnames(res) <- c("ID", "cell")
if (xy) {
xycrd <- xyFromCell(x, res$cell)
method <- "simple"
if (online) {
pts <- vect(xycrd, crs="local")
crs(y) <- "local"
n <- nearest(pts, y)
xycrd <- crds(n)
if (bilinear) method <- "bilinear"
res <- data.frame(res, xycrd, extract(x, xycrd, method=method))
} else {
res <- data.frame(res, xycrd, extract(x, res$cell))
}
} else {
res <- data.frame(res, extract(x, res$cell))
}
}
if (!cells) res$cell <- NULL
if (!ID) res$ID <- NULL
res
}
setMethod("extractRange", signature(x="SpatRaster", y="ANY"),
function(x, y, first, last, lyr_fun=NULL, geom_fun=NULL, ID=FALSE, na.rm=TRUE, ...) {
first <- getLyrNrs(first, names(x), NROW(y)) + 1
last <- getLyrNrs(last, names(x), NROW(y)) + 1
if (inherits(y, "SpatVector")) {
e <- extract(x, y, geom_fun, ID=TRUE, na.rm=na.rm, ...)
if (nrow(e) != nrow(y)) {
error("extractRange", "geom_fun must return a single value for each geometry/layer")
}
} else {
e <- data.frame(ID=1:NROW(y), extract(x, y, ...))
}
a <- lapply(1:nrow(e), function(i) e[i, c(first[i]:last[i])])
if (!is.null(lyr_fun)) {
a <- sapply(a, lyr_fun, na.rm=na.rm)
}
if (ID) {
if (is.list(a)) {
names(a) <- 1:NROW(y)
} else {
a <- data.frame(ID=1:nrow(a), value=a)
}
}
a
}
)
terra/R/distance.R 0000644 0001762 0000144 00000021250 14752176377 013530 0 ustar ligges users # Author: Robert J. Hijmans
# Date : July 2019
# Version 1.0
# License GPL v3
setMethod("buffer", signature(x="SpatRaster"),
function(x, width, background=0, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$buffer(width, background, opt)
messages(x, "buffer")
}
)
#setMethod("nearest", signature(x="SpatRaster"),
# function(x, target=NA, exclude=NULL, unit="m", method="haversine", filename="", ...) {
#
# if (!(method %in% c("geo", "haversine", "cosine"))) {
# error("nearest", "not a valid method. Should be one of: 'geo', 'haversine', 'cosine'")
# }
# opt <- spatOptions(filename, ...)
# target <- as.numeric(target[1])
# keepNA <- FALSE
# if (!is.null(exclude)) {
# exclude <- as.numeric(exclude[1])
# if ((is.na(exclude) && is.na(target)) || isTRUE(exclude == target)) {
# error("nearest", "'target' and 'exclude' must be different")
# }
# if (is.na(exclude)) {
# keepNA <- TRUE
# }
# } else {
# exclude <- NA
# }
# x@pntr <- x@pntr$nearest(target, exclude, keepNA, tolower(unit), TRUE, method, opt)
# messages(x, "nearest")
# }
#
#)
setMethod("distance", signature(x="SpatRaster", y="missing"),
function(x, y, target=NA, exclude=NULL, unit="m", method="haversine", maxdist=NA, values=FALSE, filename="", ...) {
method <- match.arg(tolower(method), c("cosine", "haversine", "geo"))
opt <- spatOptions(filename, ...)
target <- as.numeric(target[1])
keepNA <- FALSE
if (!is.null(exclude)) {
exclude <- as.numeric(exclude[1])
if ((is.na(exclude) && is.na(target)) || isTRUE(exclude == target)) {
error("distance", "'target' and 'exclude' must be different")
}
if (is.na(exclude)) {
keepNA <- TRUE
}
} else {
exclude <- NA
}
x@pntr <- x@pntr$rastDistance(target, exclude, keepNA, tolower(unit), TRUE, method, isTRUE(values), maxdist, opt)
messages(x, "distance")
}
)
setMethod("costDist", signature(x="SpatRaster"),
function(x, target=0, scale=1, maxiter=50, filename="", ...) {
opt <- spatOptions(filename, ...)
maxiter <- max(maxiter[1], 2)
x@pntr <- x@pntr$costDistance(target[1], scale[1], maxiter, FALSE, opt)
messages(x, "costDist")
}
)
setMethod("gridDist", signature(x="SpatRaster"),
function(x, target=0, scale=1, maxiter=50, filename="", ...) {
opt <- spatOptions(filename, ...)
if (is.na(target)) {
x@pntr <- x@pntr$gridDistance(scale[1] , opt)
} else {
maxiter <- max(maxiter[1], 2)
x@pntr <- x@pntr$costDistance(target[1], scale[1], maxiter, TRUE, opt)
}
messages(x, "gridDist")
}
)
setMethod("distance", signature(x="SpatRaster", y="SpatVector"),
function(x, y, unit="m", rasterize=FALSE, method="cosine", filename="", ...) {
opt <- spatOptions(filename, ...)
unit <- as.character(unit[1])
method <- match.arg(tolower(method), c("cosine", "haversine", "geo"))
x@pntr <- x@pntr$vectDistance(y@pntr, rasterize, unit, method, opt)
# if (rasterize) {
# x@pntr <- x@pntr$vectDistanceRasterize(y@pntr, NA, NA, unit, method, opt)
# } else {
# x@pntr <- x@pntr$vectDistanceDirect(y@pntr, unit, method, opt)
# }
messages(x, "distance")
}
)
setMethod("distance", signature(x="SpatRaster", y="sf"),
function(x, y, unit="m", rasterize=FALSE, method="cosine", filename="", ...) {
distance(x, vect(y), unit=unit, rasterize=rasterize, method=method, filename=filename, ...)
}
)
mat2wide <- function(m, sym=TRUE, keep=NULL) {
if (inherits(m, "dist")) {
# sym must be true in this case
nr <- attr(m, "Size")
x <- rep(1:(nr-1), (nr-1):1)
y <- unlist(sapply(2:nr, function(i) i:nr))
cbind(x,y, as.vector(m))
} else {
bool <- is.logical(m)
if (sym) {
m[lower.tri(m)] <- NA
}
m <- cbind(from=rep(1:nrow(m), each=ncol(m)), to=rep(1:ncol(m), nrow(m)), value=as.vector(t(m)))
m <- m[!is.na(m[,3]), , drop=FALSE]
if (!is.null(keep)) {
m <- m[m[,3] == keep, 1:2, drop=FALSE]
}
m
}
}
setMethod("distance", signature(x="SpatVector", y="ANY"),
function(x, y, sequential=FALSE, pairs=FALSE, symmetrical=TRUE, unit="m", method="geo") {
if (!missing(y)) {
error("distance", "If 'x' is a SpatVector, 'y' should be a SpatVector or missing")
}
method <- match.arg(tolower(method), c("cosine", "haversine", "geo"))
if (sequential) {
return( x@pntr$distance_self(sequential, unit, method))
}
unit <- as.character(unit[1])
d <- x@pntr$distance_self(sequential, unit, method)
messages(x, "distance")
class(d) <- "dist"
attr(d, "Size") <- nrow(x)
attr(d, "Diag") <- FALSE
attr(d, "Upper") <- FALSE
attr(d, "method") <- "spatial"
if (pairs) {
d <- as.matrix(d)
diag(d) <- NA
d <- mat2wide(d, symmetrical)
}
d
}
)
setMethod("distance", signature(x="SpatVector", y="SpatVector"),
function(x, y, pairwise=FALSE, unit="m", method = "cosine") {
unit <- as.character(unit[1])
d <- x@pntr$distance_other(y@pntr, pairwise, unit, method)
messages(x, "distance")
if (!pairwise) {
d <- matrix(d, nrow=nrow(x), ncol=nrow(y), byrow=TRUE)
}
d
}
)
test.for.lonlat <- function(xy) {
x <- range(xy[,1], na.rm=TRUE)
y <- range(xy[,2], na.rm=TRUE)
x[1] >= -180 && x[2] <= 180 && y[1] > -90 && y[2] < 90
}
setMethod("distance", signature(x="matrix", y="matrix"),
function(x, y, lonlat, pairwise=FALSE, unit="m", method="geo") {
if (missing(lonlat)) {
lonlat <- test.for.lonlat(x) & test.for.lonlat(y)
warn("distance", paste0("lonlat not set. Assuming lonlat=", lonlat))
}
stopifnot(ncol(x) == 2)
stopifnot(ncol(y) == 2)
v <- vect()
stopifnot(unit %in% c("m", "km"))
m <- ifelse(unit == "m", 1, 0.001)
d <- v@pntr$point_distance(x[,1], x[,2], y[,1], y[,2], pairwise[1], m, lonlat, method=method)
messages(v)
if (pairwise) {
d
} else {
matrix(d, nrow=nrow(x), ncol=nrow(y), byrow=TRUE)
}
}
)
setMethod("distance", signature(x="data.frame", y="data.frame"),
function(x, y, lonlat, pairwise=FALSE, unit="m", method="geo") {
distance(as.matrix(x), as.matrix(y), lonlat, pairwise=pairwise, unit=unit, method=method)
}
)
setMethod("distance", signature(x="matrix", y="missing"),
function(x, y, lonlat=NULL, sequential=FALSE, pairs=FALSE, symmetrical=TRUE, unit="m", method="geo") {
if (missing(lonlat)) {
lonlat <- test.for.lonlat(x) & test.for.lonlat(y)
warn("distance", paste0("lonlat not set. Assuming lonlat=", lonlat))
}
crs <- ifelse(isTRUE(lonlat), "+proj=longlat +datum=WGS84", "+proj=utm +zone=1 +datum=WGS84")
x <- vect(x, crs=crs)
distance(x, sequential=sequential, pairs=pairs, symmetrical=symmetrical, unit=unit, method=method)
}
)
setMethod("distance", signature(x="data.frame", y="missing"),
function(x, y, lonlat=NULL, sequential=FALSE, pairs=FALSE, symmetrical=TRUE, unit="m", method="geo") {
distance(as.matrix(x), lonlat=lonlat, sequential=sequential, pairs=pairs, symmetrical=symmetrical, unit=unit, method=method)
}
)
setMethod("direction", signature(x="SpatRaster"),
function(x, from=FALSE, degrees=FALSE, method="cosine", filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$rastDirection(from[1], degrees[1], NA, NA, method, opt)
messages(x, "direction")
}
)
match_abs <- function(x, y, ...) {
d <- colMeans(abs(y - x), ...)
which.min(d)[1]
}
match_sqr <- function(x, y, ...) {
d <- colMeans((y - x)^2, ...)
which.min(d)[1]
}
setMethod("bestMatch", signature(x="SpatRaster", y="matrix"),
function(x, y, labels=NULL, fun="squared", ..., filename="", overwrite=FALSE, wopt=list()) {
if (!(all(colnames(y) %in% names(x)) && (all(names(x) %in% colnames(y))))) {
error("bestMatch", "names of x and y must match")
}
if (inherits(fun, "character")) {
fun <- match.arg(tolower(fun), c("abs", "squared"))
if (fun == "abs") {
f <- match_abs
} else {
f <- match_sqr
}
out <- app(x, f, y=t(y), ...)
} else {
out <- app(x, fun, y=t(y), ...)
}
if (!is.null(labels)) {
levels(out) <- data.frame(ID=1:nrow(y), label=labels)
}
if (filename!="") {
out <- writeRaster(out, filename, wopt=wopt)
}
out
}
)
setMethod("bestMatch", signature(x="SpatRaster", y="SpatVector"),
function(x, y, labels=NULL, fun="squared", ..., filename="", overwrite=FALSE, wopt=list()) {
y <- as.matrix(extract(x, y, fun="mean", ..., na.rm=TRUE, ID=FALSE))
bestMatch(x, y, labels=labels, fun=fun, filename=filename, ...)
}
)
setMethod("bestMatch", signature(x="SpatRaster", y="data.frame"),
function(x, y, labels=NULL, fun="squared", ..., filename="", overwrite=FALSE, wopt=list()) {
if (!(all(names(y) %in% names(x)) && (all(names(x) %in% names(y))))) {
error("bestMatch", "names of x and y must match")
}
# y <- y[, names(x), drop=FALSE]
i <- unique(sapply(y, class))
if (any(i != "numeric")) {
error("bestMatch", "all values in y must be numeric")
}
y <- as.matrix(y)
bestMatch(x, y, labels=labels, fun=fun, filename=filename, ...)
}
)
terra/R/twoClasses.R 0000644 0001762 0000144 00000004267 14746604252 014065 0 ustar ligges users # Author: Robert J. Hijmans
# Date : January 2025
# Version 1.0
# License GPL v3
otsu <- function(values, counts) {
#based on https://stackoverflow.com/questions/51116495/auto-thresholding-on-r-raster-object by Eric
n <- length(values)
w1 <- cumsum(counts)
w2 <- w1[n] + counts - w1
cv <- counts * values
m1 <- cumsum(cv)
m2 <- m1[n] + cv - m1
varian <- w1 * w2 * (m2/w2 - m1/w1)^2
mxi <- which(varian == max(varian, na.rm = TRUE))
(values[mxi[1]] + values[mxi[length(mxi)]])/2
}
setMethod("thresh", signature(x="SpatRaster"),
function(x, method="otsu", maxcell=1000000, combine=FALSE, as.raster=TRUE, filename="", ...) {
method <- match.arg(tolower(method), c("mean", "median", "otsu"))
nl <- nlyr(x)
if (combine) {
if (method == "otsu") {
rng <- minmax(x, compute=TRUE)
breaks <- seq(rng[1], rng[2], length.out=257)
h <- classify(x, breaks, include.lowest=TRUE, right=FALSE)
f <- freq(h)
f <- aggregate(f[,3,drop=FALSE], f[,2,drop=FALSE], sum)
breaks <- breaks + ((breaks[2] - breaks[1]) / 2)
f$value <- breaks[f$value+1]
th <- otsu(f$value, f$count)
} else if (method == "mean") {
r <- spatSample(x, maxcell, "regular", as.df=FALSE)
th <- mean(r, na.rm=TRUE)
} else if (method == "median") {
r <- spatSample(x, maxcell, "regular", as.df=FALSE)
th <- median(r, na.rm=TRUE)
}
} else {
if (method == "otsu") {
th <- rep(NA, nl)
rng <- minmax(x, compute=TRUE)
for (i in 1:nl) {
breaks <- seq(rng[1,i], rng[2, i], length.out=257)
h <- classify(x, breaks, include.lowest=TRUE, right=FALSE)
f <- freq(h)
breaks <- breaks + ((breaks[2] - breaks[1]) / 2)
f[,2] <- breaks[f[,2]+1]
j <- f[,1] == i
th[i] <- otsu(f[j,2], f[j,3])
}
} else if (method == "mean") {
th <- global(x, "mean", na.rm=TRUE)[,1]
} else if (method == "median") {
r <- spatSample(x, maxcell, "regular", as.df=FALSE)
th <- apply(r, 2, median, na.rm=TRUE)
}
}
if (!as.raster) {
if (combine) {
th <- as.vector(th)
} else {
names(th) <- names(x)
}
return(th)
}
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$arith_numb(th, ">", FALSE, FALSE, opt)
messages(x, "thresh")
}
)
terra/R/read.R 0000644 0001762 0000144 00000002671 14726700274 012645 0 ustar ligges users # Author: Robert J. Hijmans
# Date : December 2017
# Version 1.0
# License GPL v3
setMethod("readStart", signature(x="SpatRaster"),
function(x) {
success <- x@pntr$readStart()
messages(x, "readStart")
if (!success) error("readStart,SpatRaster", "cannot open file for reading")
invisible(success)
}
)
setMethod("readStart", signature(x="SpatRasterDataset"),
function(x) {
success <- x@pntr$readStart()
messages(x, "readStart")
if (!success) error("readStart,SpatRasterDataset", "cannot open file for reading")
invisible(success)
}
)
#setMethod("readStart", signature(x="SpatRasterDataset"),
# function(x, ...) {
# nsd <- length(x)
# for (i in 1:nsd) {
# y <- x[i]
# success <- readStart(y)
# x[i] <- y
# }
# messages(x, "readStart")
# invisible(success)
# }
#)
setMethod("readStop", signature(x="SpatRaster"),
function(x) {
success <- x@pntr$readStop()
messages(x, "readStop")
invisible(success)
}
)
setMethod("readStop", signature(x="SpatRasterDataset"),
function(x) {
success <- x@pntr$readStop()
messages(x, "readStop")
invisible(success)
}
)
setMethod("toMemory", signature(x="SpatRaster"),
function(x) {
x@pntr <- x@pntr$deepcopy()
x@pntr$readAll()
messages(x, "toMemory")
}
)
setMethod("toMemory", signature(x="SpatRasterDataset"),
function(x) {
x@pntr <- x@pntr$deepcopy()
x@pntr$readAll()
messages(x, "toMemory")
}
)
terra/R/layerCor.R 0000644 0001762 0000144 00000012572 14726700274 013513 0 ustar ligges users # Robert Hijmans
# Date : Nov 2021
# Version 1.0
# Licence GPL v3
# Computation of the weighted covariance and (optionally) weighted means of bands in an Raster.
# based on code for "raster" by Jonathan Greenberg and Robert Hijmans
# partly based on code by Mort Canty
setMethod("layerCor", signature(x="SpatRaster"),
function(x, fun, w, asSample=TRUE, use="everything", maxcell=Inf, ...) {
ops <- c("everything", "complete.obs", "pairwise.complete.obs", "masked.complete")
# backwards compatibility
na.rm <- list(...)$na.rm
if (isTRUE(na.rm) && (use == "everything")) {
use <- "pairwise.complete.obs"
}
use <- match.arg(use, ops)
if (use != "everything") {
na.rm <- TRUE
} else {
na.rm <- FALSE
}
stopifnot(is.logical(asSample) & !is.na(asSample))
nl <- nlyr(x)
if (nl < 2) {
error("layerCor", "x must have at least 2 layers")
}
if (inherits(fun, "character")) {
fun <- tolower(fun)
if (!(fun %in% c("cov", "weighted.cov", "pearson", "cor"))) {
error("layerCor", "character function names must be one of: 'cor', 'cov', or 'weighted.cov'")
}
# backwards compatibility
if (fun == "pearson") fun = "cor"
if (fun == "weighted.cov") {
if (missing(w)) {
error("layerCor", "to compute weighted covariance a weights layer should be provided")
}
stopifnot( nlyr(w) == 1 )
x <- c(w, x)
}
} else {
FUN <- fun
fun <- ""
}
if (maxcell < ncell(x)) {
x <- spatSample(x, size=maxcell, "regular", as.raster=TRUE)
}
n <- ncell(x)
# for "cor" masking is done in cpp code
if ((use == "complete.obs") && (fun != "cor")) {
x <- mask(x, anyNA(x), maskvalue=TRUE)
}
if (fun == "weighted.cov") {
w <- x[[1]]
x <- x[[-1]]
means <- mat <- matrix(NA, nrow=nl, ncol=nl)
colnames(means) <- rownames(means) <- colnames(mat) <- rownames(mat) <- names(x)
sqrtw <- sqrt(w)
for(i in 1:nl) {
for(j in i:nl) {
s <- c(x[[c(i,j)]])
if (use == "pairwise.complete.obs") {
s <- mask(c(s, w), anyNA(s), maskvalue=TRUE)
ww <- s[[3]]
s <- s[[1:2]]
sumw <- unlist(global(ww, fun="sum", na.rm=TRUE) )
avg <- unlist(global(s * ww, fun="sum", na.rm=TRUE)) / sumw
} else {
sumw <- unlist(global(w, fun="sum", na.rm=na.rm) )
avg <- unlist(global(s * w, fun="sum", na.rm=na.rm)) / sumw
}
sumw <- sumw - asSample
s <- prod( (s - avg) * sqrtw )
v <- unlist(global(s, fun="sum", na.rm=na.rm)) / sumw
mat[j,i] <- mat[i,j] <- v
means[i,j] <- avg[1]
means[j,i] <- avg[2]
}
}
return( list(weighted_covariance=mat, weighted_mean=means) )
} else if (fun == "cov") {
means <- mat <- nn <- matrix(NA, nrow=nl, ncol=nl)
colnames(means) <- rownames(means) <- colnames(mat) <- rownames(mat) <- names(x)
n_ij <- n
for(i in 1:nl) {
for(j in i:nl) {
s <- x[[c(i,j)]]
if (use == "pairwise.complete.obs") {
m <- anyNA(s)
s <- mask(s, m, maskvalue=TRUE)
n_ij <- n - global(m, fun="sum")$sum
}
avg <- unlist(global(s, fun="mean", na.rm=na.rm) )
r <- prod(s - avg)
v <- unlist(global(r, fun="sum", na.rm=na.rm)) / (n_ij - asSample)
mat[j,i] <- mat[i,j] <- v
means[i,j] <- avg[1]
means[j,i] <- avg[2]
nn[i,j] <- nn[j,i] <- n_ij
}
}
return( list(covariance=mat, mean=means, n=nn) )
} else if (fun == "cor") {
if (isTRUE(list(...)$old)) {
old_pearson(x, asSample=asSample, na.rm=na.rm, nl=nl, n=n, mat=mat)
} else {
opt <- spatOptions()
m <- x@pntr$layerCor("cor", use, asSample, opt)
x <- messages(x)
m <- lapply(m, function(i) {
matrix(i, nrow=nl, byrow=TRUE, dimnames=list(names(x), names(x)))
})
names(m) <- c("correlation", "mean", "n")
return(m)
}
} else {
v <- spatSample(x, size=maxcell, "regular", na.rm=na.rm, warn=FALSE)
if (use %in% c("complete.obs", "complete.masked")) {
v <- na.omit(v)
}
mat <- matrix(NA, nrow=nl, ncol=nl)
for(i in 1:nl) {
for(j in i:nl) {
if (use == "pairwise.complete.obs") {
vij <- na.omit(v[,c(i,j)])
mat[j,i] <- mat[i,j] <- FUN(vij[,1], vij[,2], ...)
} else {
mat[j,i] <- mat[i,j] <- FUN(v[,i], v[,j], ...)
}
}
}
mat
}
}
)
old_pearson <- function(x, asSample, na.rm, nl, n, mat) {
if (na.rm) {
means <- matrix(NA, nrow=2, ncol=nlyr(x))
for(i in 1:(nl-1)) {
for(j in (i+1):nl) {
m <- anyNA(x[[c(i,j)]])
a <- mask(x[[i]], m, maskvalue=TRUE)
b <- mask(x[[j]], m, maskvalue=TRUE)
xx <- c(a, b)
mns <- unlist(global(xx, fun="mean", na.rm=na.rm) )
means[2,i] <- mns[1]
means[1,j] <- mns[2]
sds <- unlist(global(xx, fun="sd", na.rm=na.rm) )
r <- prod(xx - mns)
nas <- unlist(global(is.na(r), fun="sum"))
v <- unlist(global(r, fun="sum", na.rm=na.rm))
v <- v / ((n - nas - asSample) * sds[1] * sds[2])
mat[j,i] <- mat[i,j] <- v
}
}
colnames(means) <- names(x)
} else {
means <- unlist(global(x, fun="mean", na.rm=na.rm) )
sds <- unlist(global(x, fun="sd", na.rm=na.rm) )
x <- (x - means)
for(i in 1:(nl-1)) {
for(j in i:nl) {
r <- x[[i]] * x[[j]]
v <- unlist(global(r, fun="sum", na.rm=na.rm))
v <- v / ((n - asSample) * sds[i] * sds[j])
mat[j,i] <- mat[i,j] <- v
}
}
means <- matrix(means, nrow=1)
colnames(means) <- names(x)
}
diag(mat) <- 1
covar <- list(mat, means)
names(covar) <- c("pearson", "mean")
return(covar)
}
terra/R/RGB.R 0000644 0001762 0000144 00000012274 14726700274 012344 0 ustar ligges users # Author: Robert J. Hijmans
# Date : April 2010
# Version 0.9
# License GPL v3
setMethod ("has.RGB" , "SpatRaster",
function(x, strict=TRUE) {
if (strict) {
x@pntr$rgbtype == "rgb"
} else {
x@pntr$rgbtype != ""
}
}
)
setMethod("set.RGB", signature(x="SpatRaster"),
function(x, value=1:3, type="rgb") {
if (is.null(value[1]) || is.na(value[1]) || any(value < 1)) {
x@pntr$removeRGB()
} else {
if (inherits(value, "character")) {
i <- match(value, names(x))
j <- !is.na(i)
value[j] <- i[j]
value <- as.integer(value)
}
if (!all(value %in% 1:nlyr(x))) {
error("set.RGB", "value(s) are not value layer numbers")
}
if (length(value) == 3) {
x@pntr$setRGB(value[1]-1, value[2]-1, value[3]-1, -99, type)
} else if (length(value) == 4) {
x@pntr$setRGB(value[1]-1, value[2]-1, value[3]-1, value[4]-1, type)
} else {
error("set.RGB", "value must have length 3 or 4")
}
}
x <- messages(x, "set.RGB")
invisible(TRUE)
}
)
setMethod("RGB<-", signature(x="SpatRaster"),
function(x, ..., type="rgb", value) {
x@pntr <- x@pntr$deepcopy()
set.RGB(x, value, type)
x
}
)
setMethod("RGB", signature(x="SpatRaster"),
function(x, value=NULL, type="rgb") {
if (!is.null(value)) {
RGB(x, type=type) <- value
return(x)
} else {
if (x@pntr$rgb) {
x@pntr$getRGB() + 1
} else {
return(NULL)
}
}
}
)
#### RGB2col
make_cut <- function(x) {
j <- length(x)
out <- vector("list", 2*j)
for (i in 1:j) {
rgb <- x[[i]]
if (NROW(rgb) <= 1) {
out[[i]] <- rgb
j <- j - 1
next
}
rng <- apply(rgb[,-1], 2, function(i) diff(range(i)))
if (max(rng) == 0) {
out[[i]] <- rgb
j <- j - 1
next
}
p <- which.max(rng) + 1
m <- median(rgb[,p])
out[[i]] <- rgb[rgb[,p] >= m, ,drop=FALSE]
out[[i+j]] <- rgb[rgb[,p] < m, ,drop=FALSE]
}
i <- sapply(out, is.null)
out <- out[!i]
i <- sapply(out, nrow) > 0
out[i]
}
median_cut <- function(v) {
v <- list(v)
n <- 0
while ((length(v) < 129) & (length(v) > n)) {
n <- length(v)
v <- make_cut(v)
}
s <- sapply(v, function(i) max(apply(i[,-1,drop=FALSE], 2, function(j) diff(range(j)))))
n <- 256 - length(v)
ss <- rev(sort(s))
ss <- max(2, min(ss[1:n]))
i <- which(s > ss)
if (length(i) > 0) {
vv <- make_cut(v[i])
v <- c(v[-i], vv)
}
v <- lapply(1:length(v), function(i) cbind(group=i, v[[i]]))
do.call(rbind, v)
}
rgb2col <- function(x, value, stretch=NULL, grays=FALSE, NAzero=FALSE, filename="", overwrite=FALSE, ...) {
idx <- RGB(x)
if (is.null(idx)) {
if (missing(value)) {
error("colorize", "x does not have an RGB attribute and the value argument is missing")
} else {
idx <- value
}
}
n <- length(idx)
stopifnot((n == 3) | (n == 4))
if ((min(idx) < 1) | (max(idx) > nlyr(x))) {
error("colorize", "invalid value (RGB indices)")
}
x <- x[[idx]]
if (!is.null(stretch)) {
if (stretch == "lin") {
x <- stretch(x, minq=0.02, maxq=0.98)
} else {
x <- stretch(x, histeq=TRUE, scale=255)
}
}
if (n == 4) x[[4]] <- x[[4]] * 255
if (NAzero) {
x <- classify(x, cbind(NA, 0))
}
if (grays) {
opt <- spatOptions(filename, overwrite, ...)
x@pntr <- x@pntr$rgb2col(0, 1, 2, opt)
return(messages(x, "colorize"))
}
v <- cbind(id=1:ncell(x), values(x))
v <- median_cut(stats::na.omit(v))
a <- aggregate(v[,-c(1:2)], list(v[,1]), median)
# if (n==3) {
# a$cols <- grDevices::rgb(a[,2], a[,3], a[,4], maxColorValue=255)
# } else {
# a$cols <- grDevices::rgb(a[,2], a[,3], a[,4], a[,5], maxColorValue=255)
# }
m <- merge(v[,1:2], a, by=1)
m[,1] <- m[,1] - 1
r <- rast(x, 1)
r[m$id] <- m$group
coltab(r) <- unique(m[,-2])
if (filename != "") {
r <- writeRaster(r, filename, overwrite, ...)
}
r
}
terra_col2rgb <- function(x, alpha=FALSE, filename="", overwrite=FALSE, ...) {
if (nlyr(x) > 1) {
x <- x[[1]]
warn("colorize", "only the first layer of 'x' is considered")
}
ct <- coltab(x)[[1]]
if (is.null(ct)) {
error("colorize", "x has no color table")
}
ct <- unique(as.matrix(ct))
nms <- c("red", "green", "blue", "alpha")
rgbidx <- 1:4
if (!alpha) {
ct <- ct[,1:4]
nms <- nms[1:3]
rgbidx <- rgbidx[1:3]
}
wopt=list(...)
if (is.null(wopt$names)) {
wopt$names <- nms
}
out <- subst(x, from=ct[,1], to=ct[,-1], raw=TRUE, filename=filename, overwrite=overwrite, wopt=wopt)
set.RGB(out, rgbidx)
out
}
setMethod("colorize", signature(x="SpatRaster"),
function(x, to="hsv", alpha=FALSE, stretch=NULL, grays=FALSE, NAzero=FALSE, filename="", overwrite=FALSE, ...) {
to <- tolower(to)
if (to %in% c("hsi", "hsl", "hsv")) {
opt <- spatOptions(filename, overwrite, ...)
x@pntr <- x@pntr$rgb2hsx(to, opt)
} else if (to == "rgb") {
if (nlyr(x) == 1) {
return(terra_col2rgb(x, alpha=alpha, filename=filename, overwrite=overwrite, ...))
} else {
opt <- spatOptions(filename, overwrite, ...)
x@pntr <- x@pntr$hsx2rgb(opt)
}
} else if (to == "hsl") {
opt <- spatOptions(filename, overwrite, ...)
x@pntr <- x@pntr$hsx2rgb(to, opt)
} else if (to == "col") {
return(rgb2col(x, stretch=stretch, grays=grays, NAzero=NAzero, filename=filename, overwrite=overwrite, ...))
} else {
error("colorize", "'to' is not valid. Should be 'rgb', 'col', 'hsi', 'hsl', or 'hsv'")
}
messages(x)
}
)
terra/R/math.R 0000644 0001762 0000144 00000005625 14726700274 012665 0 ustar ligges users # Author: Robert J. Hijmans
# Date : September 2018
# Version 1.0
# License GPL v3
#to do
#"gamma", "lgamma", "digamma", "trigamma")
setMethod("log", signature(x="SpatRaster"),
function(x, base=exp(1)){
opt <- spatOptions()
if (base == exp(1)) {
x@pntr <- x@pntr$math("log", opt)
} else if (base == 2) {
x@pntr <- x@pntr$math("log2", opt)
} else if (base == 10) {
x@pntr <- x@pntr$math("log10", opt)
} else {
x <- app(x, function(i) log(i, base))
}
x
}
)
#? "gamma", "lgamma", "digamma", "trigamma"
setMethod("Math", signature(x="SpatRaster"),
function(x){
oper <- as.vector(.Generic)[1]
opt <- spatOptions()
if (substr(oper, 1, 3) == "cum") {
x@pntr <- x@pntr$cum(substr(oper, 4, 10), FALSE, opt)
} else if (oper %in% c("acos", "acosh", "asin", "asinh", "atan", "atanh", "cos", "cosh", "cospi", "sin", "sinh", "sinpi", "tan", "tanh", "tanpi")) {
x@pntr <- x@pntr$trig(oper, opt)
} else {
x@pntr <- x@pntr$math(oper, opt)
}
messages(x, oper)
}
)
setMethod("math", signature(x="SpatRaster"),
function(x, fun, digits=0, filename="", overwrite=FALSE, ...){
if (!is.character(fun)) {
error("math", "fun must be a character value")
}
fun = fun[1]
opt <- spatOptions(filename, overwrite, ...)
if (substr(fun, 1, 3) == "cum") {
x@pntr <- x@pntr$cum(substr(fun, 4, 10), FALSE, "", FALSE)
} else if (fun %in% c("acos", "acosh", "asin", "asinh", "atan", "atanh", "cos", "cosh", "cospi", "sin", "sinh", "sinpi", "tan", "tanh", "tanpi")) {
x@pntr <- x@pntr$trig(fun, opt)
} else if (fun %in% c("abs", "sign", "sqrt", "ceiling", "floor", "trunc", "log", "log10", "log2")) { x@pntr <- x@pntr$math(fun, opt)
} else if (fun %in% c("round", "signif")) {
x@pntr <- x@pntr$math2(fun, digits, opt)
} else {
error("math", "unknown function")
}
messages(x, fun)
}
)
setMethod("Math2", signature(x="SpatRaster"),
function(x, digits=0){
opt <- spatOptions()
oper <- as.vector(.Generic)[1]
x@pntr <- x@pntr$math2(oper, digits, opt)
messages(x, oper)
}
)
setMethod("Math", signature(x="SpatExtent"),
function(x){
oper <- as.vector(.Generic)[1]
if (oper == "floor") {
x@pntr <- x@pntr$floor()
} else if (oper == "ceiling") {
x@pntr <- x@pntr$ceil()
} else {
error(oper, "not implemented for SpatExtent")
}
if (!is.valid(x)) {
error(oper, "invalid extent")
}
return(x)
}
)
setMethod("Math2", signature(x="SpatExtent"),
function(x, digits=0){
oper <- as.vector(.Generic)[1]
if (oper == "round") {
x@pntr <- x@pntr$round(digits)
if (!is.valid(x)) {
error(oper, "invalid extent")
}
return(x)
} else {
error(oper, "not implemented for SpatExtent")
}
}
)
setMethod("Math2", signature(x="SpatVector"),
function(x, digits=4){
oper <- as.vector(.Generic)[1]
if (oper == "round") {
x@pntr <- x@pntr$round(digits)
return(x)
} else {
error(oper, "not implemented for SpatVector")
}
}
)
terra/R/cells.R 0000644 0001762 0000144 00000004204 14734622000 013013 0 ustar ligges users # Author: Robert J. Hijmans
# Date : June 2020
# Version 1.0
# License GPL v3
setMethod("cells", signature(x="SpatRaster", y="missing"),
function(x, y) {
if (hasValues(x)) {
opt <- spatOptions()
x@pntr$cells_notna_novalues(opt) + 1
} else {
# is this useful?
1:ncell(x)
}
}
)
setMethod("cells", signature(x="SpatRaster", y="numeric"),
function(x, y, pairs=FALSE) {
opt <- spatOptions()
v <- x@pntr$is_in_cells(y, pairs, opt)
x <- messages(x, "cells")
if (pairs) {
v <- lapply(v, function(i) {
m <- matrix(i, ncol=2)
m[,1] <- m[,1] + 1
colnames(m) <- c("cell", "value")
m
})
} else {
v <- lapply(v, function(i) i+1)
}
names(v) <- names(x)
v
}
)
setMethod("cells", signature("SpatRaster", "SpatVector"),
function(x, y, method="simple", weights=FALSE, exact=FALSE, touches=is.lines(y), small=TRUE) {
method = match.arg(tolower(method), c("simple", "bilinear"))
opt <- spatOptions()
d <- x@pntr$vectCells(y@pntr, touches[1], small[1], method[1], weights[1], exact[1], opt)
if (geomtype(y) == "points") {
d <- matrix(d, nrow=nrow(y), byrow=TRUE)
d <- cbind(1:nrow(y), d)
if (method == "bilinear") {
colnames(d) <- c("ID", "c1", "c2", "c3", "c4", "w1", "w2", "w3", "w4")
d[,2:5] <- d[,2:5] + 1
} else {
colnames(d) <- c("ID", "cell")
d[,2] <- d[,2] + 1
}
return (d)
}
cn <- c("ID", "cell")
if (weights[1] || exact[1]) {
d <- matrix(d, ncol=3)
cn <- c(cn, "weights")
} else {
d <- matrix(d, ncol=2)
}
d[,1:2] <- d[,1:2] + 1
colnames(d) <- cn
d
}
)
#setMethod("cells", signature("SpatRaster", "SpatExtent"),
# function(x, y, ...) {
# p <- as.polygons(y, crs=crs(x))
# cells(x, p)[,2]
# }
#)
#setMethod("cells", signature("SpatRaster", "SpatExtent"),
# function(x, y, ...) {
# e <- align(y, x)
# s <- res(x)/2
# e <- as.vector(y) + c(s[1], -s[1], s[2], -s[2])
# r <- rowFromY(x, e[4:3])-1
# c <- colFromX(x, e[1:2])
# cc <- c[1]:c[2]
# rr <- (r[1]:r[2]) * ncol(x)
# rep(rr, each=length(cc)) + cc
# }
#)
setMethod("cells", signature("SpatRaster", "SpatExtent"),
function(x, y) {
opt <- spatOptions()
x@pntr$extCells(y@pntr) + 1
}
)
terra/R/rowSums.R 0000644 0001762 0000144 00000004136 14732065717 013412 0 ustar ligges users #Author: Robert J. Hijmans
#Date : April 2015
#Version 1.0
#Licence GPL v3
setMethod("rowSums", signature(x="SpatRaster"),
function(x, na.rm = FALSE, dims = 1L, ...) {
nl <- nlyr(x)
nc <- ncol(x)
readStart(x)
on.exit(readStop(x))
b <- blocks(x, n=4)
s <- vector("list", b$n)
for (i in 1:b$n) {
v <- readValues(x, row=b$row[i], nrows=b$nrows[i])
s[[i]] <- .colSums(v, nc, b$nrows[i]*nl, na.rm=na.rm)
}
s <- t(matrix(unlist(s), nrow=nl, byrow=TRUE))
colnames(s) <- names(x)
s
}
)
setMethod("colSums", signature(x="SpatRaster"),
function(x, na.rm = FALSE, dims = 1L, ...) {
nl <- nlyr(x)
nc <- ncol(x)
readStart(x)
on.exit(readStop(x))
b <- blocks(x, n=4)
s <- matrix(nrow=b$n, ncol=nc*nl)
for (i in 1:b$n) {
v <- readValues(x, row=b$row[i], nrows=b$nrows[i], mat=TRUE)
for (j in 1:nl) {
k <- (j-1) * nc + 1
k <- k:(k+nc-1)
s[i, k] <- .colSums(matrix(v[,j], nrow=b$nrows[i], byrow=TRUE), b$nrows[i], nc, na.rm=na.rm)
}
}
s <- matrix(.colSums(s, nrow(s), ncol(s), na.rm=na.rm), ncol=nl)
colnames(s) <- names(x)
return(s)
}
)
setMethod("rowMeans", signature(x="SpatRaster"),
function(x, na.rm = FALSE, dims = 1L, ...) {
nl <- nlyr(x)
nc <- ncol(x)
readStart(x)
on.exit(readStop(x))
b <- blocks(x, n=4)
s <- vector("list", b$n)
for (i in 1:b$n) {
v <- readValues(x, row=b$row[i], nrows=b$nrows[i])
s[[i]] <- .colMeans(v, nc, b$nrows[i]*nl, na.rm=na.rm)
}
s <- t(matrix(unlist(s), nrow=nl, byrow=TRUE))
colnames(s) <- names(x)
s
}
)
setMethod("colMeans", signature(x="SpatRaster"),
function(x, na.rm = FALSE, dims = 1L, ...) {
nl <- nlyr(x)
nc <- ncol(x)
readStart(x)
on.exit(readStop(x))
b <- blocks(x, n=4)
s <- matrix(nrow=b$n, ncol=nc*nl)
for (i in 1:b$n) {
v <- readValues(x, row=b$row[i], nrows=b$nrows[i], mat=TRUE)
for (j in 1:nl) {
k <- (j-1) * nc + 1
k <- k:(k+nc-1)
s[i, k] <- .colMeans(matrix(v[,j], nrow=b$nrows[i], byrow=TRUE), b$nrows[i], nc, na.rm=na.rm)
}
}
s <- matrix(.colSums(s, nrow(s), ncol(s), na.rm=na.rm), ncol=nl)
colnames(s) <- names(x)
return(s)
}
)
terra/R/levels.R 0000644 0001762 0000144 00000025460 14740020227 013212 0 ustar ligges users
setMethod("droplevels", signature(x="SpatRaster"),
function(x, level=NULL, layer=1) {
if (is.null(level)) {
x@pntr <- x@pntr$droplevels()
messages(x)
} else {
if (is.character(layer)) {
layer <- match(layer, names(x))
if (any(is.na(layer))) {
error("droplevels", "invalid layer")
}
}
x[[layer]][x[[layer]] %in% level] <- NA
x@pntr <- x@pntr$droplevels()
messages(x)
}
}
)
setMethod("is.factor", signature(x="SpatRaster"),
function(x) {
x@pntr$hasCategories()
}
)
setMethod("as.factor", signature(x="SpatRaster"),
function(x) {
x@pntr = x@pntr$makeCategorical(-1, spatOptions())
messages(x)
#if (!hasValues(x)) {
# error("as.factor", "x has no values")
#}
#x <- round(x)
#u <- unique(x, TRUE)
#for (i in 1:nlyr(x)) {
# set.cats(x, i, data.frame(ID=u[[i]], label=u[[i]], stringsAsFactors=FALSE))
#}
#x
}
)
setMethod("levels", signature(x="SpatRaster"),
function(x) {
x <- x@pntr$getCategories()
lapply(x, function(i) {
d <- .getSpatDF(i$df)
if (ncol(d) == 0) return("")
d[, c(1, max(1, i$index+1))]
})
}
)
setMethod("levels<-", signature(x="SpatRaster"),
function(x, value) {
x@pntr <- x@pntr$deepcopy()
if (is.null(value)) {
x@pntr$removeCategories(-1)
return(messages(x, "levels<-"))
} else if (inherits(value, "list")) {
for (i in 1:length(value)) {
set.cats(x, i, value[[i]])
}
} else {
set.cats(x, 1, value)
}
x
}
)
combineLevels <- function(x, assign=TRUE) {
if (nlyr(x) == 1) return(x)
nms <- names(x)
lv <- levels(x)
lv <- lv[sapply(lv, is.data.frame)]
un <- unique(sapply(lv, names))
if (length(un) > 2) {
lv <- lapply(lv, function(i) { colnames(i) <- colnames(lv[[1]]); i})
}
lv <- try(do.call(rbind, lv), silent=TRUE)
if (inherits(lv, "try-error")) { # should not happen anymore
error("panel", "cannot use combine categories")
}
lv <- unique(lv)
if (length(unique(lv[,1])) < nrow(lv)) {
error("panel", "cannot combine conflicting categories")
}
lv <- lv[order(lv[,1]), ]
if (assign) {
x <- categories(x, 0, lv)
names(x) <- nms
x
} else {
lv
}
}
setMethod ("set.cats" , "SpatRaster",
function(x, layer=1, value, active=1) {
if (missing(value)) {
error("set.cats", "value cannot be missing")
#return(invisible(x@pntr$setCatIndex(layer-1, index)))
}
if (is.character(layer)) {
layer <- match(layer, names(x))
if (any(is.na(layer))) {
error("set.cats", "invalid layer")
}
}
layer <- round(layer)
if (length(layer) > 1) {
if (!is.list(value)) {
error("set.cats", "value should be a list")
}
if (length(layer) != length(value)) {
error("set.cats", "length(value) != length(value)")
}
index <- rep_len(active, nlyr(x))
for (i in 1:length(layer)) {
ok <- set.cats(x, layer[i], value[[i]], index[i])
x <- messages(x, "set.cats")
}
return(invisible(ok))
}
if (layer < 1) {
if (layer != 0) {
error("set.cats", "layer must be >= 0")
}
if (nlyr(x) == 1) {
layer <- 1
} else {
if (is.data.frame(value)) {
value <- replicate(nlyr(x), value, simplify=FALSE)
} else {
if (!is.list(value)) {
error("set.cats", "value should be a list")
}
if (length(value) != nlyr(x)) {
error("set.cats", "length(value) != nlyr(x)")
}
}
index <- rep_len(active, nlyr(x))
for (i in 1:length(value)) {
if (!is.null(value[[i]])) {
ok <- set.cats(x, i, value[[i]], index[i])
x <- messages(x, "set.cats")
}
}
return(invisible(ok))
}
}
layer <- layer[1]
if (is.character(layer)) {
i <- match(layer, names(x))[1]
if (length(i) == 0) {
error("set.cats", layer, " is not in names(x)")
}
layer <- i
} else {
stopifnot(layer > 0 && layer <= nlyr(x))
}
if (inherits(value, "list")) {
value <- value[[1]]
}
if (is.null(value)) {
x@pntr$removeCategories(layer-1)
messages(x, "set.cats")
return(invisible(TRUE))
}
setname <- FALSE
if (!is.data.frame(value)) {
if (is.vector(value) || is.factor(value)) {
if ((length(value) == 1) && value[1] == "") {
return(invisible(""))
}
warn("set.cats", "setting categories like this is deprecated; use a two-column data.frame instead")
value <- data.frame(value=0:(length(value)-1), category=value, stringsAsFactors=FALSE)
} else {
error("set.cats", "value should be a data.frame")
}
} else {
setname <- TRUE
if (ncol(value) == 1) {
error("set.cats", "value should have at least two columns")
} else {
if (!is.numeric(value[[1]])) {
error("set.cats", "the first column of 'value' must be numeric")
}
value[,1] <- round(value[[1]])
if (length(unique(value[[1]])) != nrow(value)) {
error("set.cats", "duplicate values (IDs) supplied")
}
}
}
value[[1]] <- as.integer(value[[1]])
for (i in seq_along(value)) {
if (is.factor(value[[i]])) {
value[[i]] <- as.character(value[[i]])
}
}
index <- max(1, min(ncol(value), active))
if (setname) {
nms <- names(x)
cn <- colnames(value)[index+1]
if (!(tolower(cn) %in% c("histogram", "count", "red", "green", "blue", "alpha", "opacity", "r", "g", "b", "a"))) {
nms[layer] <- cn
if (! x@pntr$setNames(nms, FALSE)) {
error("names<-", "cannot set name")
}
}
}
if (any(is.na(value[[1]]))) {
error("set.cats", "you cannot associate a category with NA")
}
if (any(table(value[[1]]) > 1)) {
error("set.cats", "you cannot have duplicate IDs")
}
value <- .makeSpatDF(value)
ok <- x@pntr$setCategories(layer-1, value, index)
x <- messages(x, "set.cats")
invisible(ok)
}
)
setMethod ("categories" , "SpatRaster",
function(x, layer=1, value, active=1, ...) {
#... to accept but ignore old argument "index"
x@pntr <- x@pntr$deepcopy()
set.cats(x, layer, value, active)
x
}
)
setMethod ("activeCat" , "SpatRaster",
function(x, layer=1) {
layer <- layer[1]
if (is.character(layer)) {
layer = which(layer == names(x))[1]
if (is.na(layer)) {
error("activeCat", "invalid layer name")
}
}
if (layer < 1) {
sapply(1:nlyr(x), function(i) x@pntr$getCatIndex(i-1))
} else {
if (!is.factor(x)[layer]) {
return(NA)
}
x@pntr$getCatIndex(layer-1)
}
}
)
setMethod("activeCat<-" , "SpatRaster",
function(x, layer=1, value) {
if (missing(value)) {
value <- layer[1]
layer <- 1
} else {
layer <- layer[1]
}
if ((layer < 1) | (layer > nlyr(x))) {
error("activeCat", "invalid layer")
}
if (!is.factor(x)[layer]) {
error("activeCat", "layer is not categorical")
}
if (is.character(value)) {
g <- cats(x)[[layer]]
value <- which(value == names(g))[1] - 1
if (is.na(value)) {
error("activeCat", "invalid category name")
}
}
x <- deepcopy(x)
if (!x@pntr$setCatIndex(layer-1, value)) {
error("activeCat", "invalid category index")
}
x
}
)
setMethod("cats" , "SpatRaster",
function(x, layer) {
if (!missing(layer)) {
x <- subset(x, layer, NSE=FALSE)
}
cats <- x@pntr$getCategories()
lapply(1:nlyr(x), function(i) {
if (cats[[i]]$df$nrow == 0) {
return(NULL)
}
.getSpatDF(cats[[i]]$df)
})
}
)
# superseded by levels(x)[[layer]]
..active_cats <- function(x, layer) {
ff <- is.factor(x)
if (!any(ff)) {
return (lapply(ff, function(i) NULL))
}
cats <- x@pntr$getCategories()
x <- lapply(1:length(cats), function(i) {
if (cats[[i]]$df$nrow == 0) return(NULL)
r <- .getSpatDF(cats[[i]]$df)
a <- activeCat(x, i)
if (a < 0) return(NULL)
r[, c(1, a+1)]
})
if (!missing(layer)) {
x[[layer]]
} else {
x
}
}
setMethod ("as.numeric", "SpatRaster",
function(x, index=NULL, filename="", ...) {
if (!any(is.factor(x))) {
x <- deepcopy(x)
x@pntr$setValueType(0)
return(x)
}
if (nlyr(x) > 1) {
x <- lapply(1:nlyr(x), function(i) as.numeric(x[[i]], index=index))
x <- rast(x)
if (filename != "") {
x <- writeRaster(x, filename, ...)
}
return(x)
}
g <- cats(x)[[1]]
if (!is.null(index)) {
if (is.character(index)) {
index <- match(index, colnames(g))
if (is.na(index)) {
error("as.numeric", "index is not category name")
}
if (index == 1) {
levels(x) <- NULL
x@pntr$setValueType(0)
if (filename != "") {
x <- writeRaster(x, filename, ...)
}
return(x)
}
} else {
index <- round(index[1])
if (!((index >= 1) & (index < ncol(g)))) {
error("as.numeric", "index out of range")
}
index <- index + 1
}
} else {
index <- activeCat(x, 1)
if (index <= 1) {
levels(x) <- NULL
x@pntr$setValueType(0)
if (filename != "") {
x <- writeRaster(x, filename, ...)
}
return(x)
}
}
from <- g[,1]
to <- g[,index]
if (!is.numeric(to)) {
suppressWarnings(toto <- as.numeric(to))
if (sum(is.na(toto) > sum(is.na(to)))) {
to <- as.integer(as.factor(to))
} else {
to <- toto
}
}
m <- cbind(from, to)
m <- m[!is.na(m[,1]), ,drop=FALSE]
classify(x, m, names=names(g)[index], filename, ...)
}
)
catLayer <- function(x, index, ...) {
stopifnot(nlyr(x) == 1)
if (!is.factor(x)) return(x)
g <- cats(x)[[1]]
if (!is.null(index)) {
if (!((index > 1) & (index <= ncol(g)))) {
error("as.numeric", "invalid index")
}
} else {
index <- set.cats(x, 1)
}
from <- g[,1]
toc <- g[,index]
addFact <- FALSE
if (!is.numeric(toc)) {
addFact <- TRUE
ton <- as.integer(as.factor(toc))
} else {
ton <- toc
}
m <- cbind(from, ton)
m <- m[!is.na(m[,1]), ,drop=FALSE]
x <- classify(x, m, names=names(g)[index], ...)
if (addFact) {
fact <- unique(data.frame(ton, toc))
names(fact) <- c("ID", names(g)[index])
fact <- fact[order(fact[,1]), ]
set.cats(x, 1, fact)
}
x
}
setMethod("catalyze", "SpatRaster",
function(x, filename="", ...) {
g <- cats(x)
out <- list()
for (i in 1:nlyr(x)) {
y <- x[[i]]
gg <- g[[i]]
if (nrow(gg) > 0) {
for (j in 2:ncol(gg)) {
z <- as.numeric(y, index=j-1)
out <- c(out, z)
}
} else {
out <- c(out, y)
}
}
out <- rast(out)
if (filename!="") {
out <- writeRaster(out, filename, ...)
}
out
}
)
setMethod("concats", "SpatRaster",
function(x, y, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr = x@pntr$combineCats(y@pntr, opt)
messages(x, "concats")
}
)
setMethod("addCats", "SpatRaster",
function(x, value, merge=FALSE, layer=1) {
if (!(is.factor(x)[layer])) {
error("addCat", "the layer has no categories to add to")
}
cts <- cats(x)[[layer]]
nact <- ncol(cts)
if (merge) {
if (ncol(value) < 2) {
error("addCat", "'value' must have at least two columns when using 'merge=TRUE'")
}
cts <- merge(cts, value, by=1, all.x=TRUE)
cts <- cts[order(cts[,1]), ]
} else {
if (nrow(cts) != nrow(value)) {
error("addCat", "the number of categories does not match")
}
cts <- cbind(cts, value)
}
categories(x, layer=layer, cts, active=nact)
}
)
terra/R/spatDF.R 0000644 0001762 0000144 00000004730 14536376240 013112 0 ustar ligges users
.makeSpatDF <- function(d) {
x <- methods::new("Rcpp_SpatDataFrame")
nms <- colnames(d)
for (i in 1:ncol(d)) {
if (inherits(d[[i]], "character")) {
s <- d[[i]]
s[is.na(s)] <- "____NA_+"
x$add_column_string(enc2utf8(s), nms[i])
} else if (inherits(d[[i]], "integer")) {
v <- d[[i]]
# min long (should query what it is on the system?)
v[is.na(v)] <- -2147483648
x$add_column_long(v, nms[i])
} else if (inherits(d[[i]], "logical")) {
v <- as.integer(d[[i]])
v[is.na(v)] <- 2
x$add_column_bool(v, nms[i])
} else if (inherits(d[[i]], "numeric")) {
x$add_column_double(d[[i]], nms[i])
} else if (inherits(d[[i]], "Date")) {
x$add_column_time(as.numeric(as.POSIXlt(d[[i]])), nms[i], "days", "")
} else if (inherits(d[[i]], "factor")) {
f <- .makeSpatFactor(d[[i]])
x$add_column_factor(f, nms[i])
} else if (inherits(d[[i]], "POSIXt")) {
tz <- if (nrow(d) > 0) { attr(d[[i]][1], "tzone") } else { "" }
if (is.null(tz)) tz <- ""
x$add_column_time(as.numeric(d[[i]]), nms[i], "seconds", tz)
} else {
v <- try(as.character(d[[i]]))
if (!inherits(v, "try-error")) {
x$add_column_string(enc2utf8(v), nms[i])
}
}
}
x
}
.getSpatDF <- function(x, check.names = FALSE, stringsAsFactors=FALSE, ...) {
d <- x$values()
f <- sapply(d, class) == "Rcpp_SpatFactor"
if (any(f)) {
f <- which(f)
for (i in f) {
d[[i]] <- .getSpatFactor(d[[i]])
}
}
d <- data.frame(d, check.names=check.names, stringsAsFactors=stringsAsFactors, ...)
if (ncol(d) == 0) return(d)
s <- which(sapply(d, function(i) inherits(i, "character")))
for (i in s) {
d[[i]][d[[i]]=="NA"] <- NA
Encoding(d[[i]]) <- "UTF-8"
}
#ints <- which(x$itype == 1)
#for (i in ints) d[[i]] <- suppressWarnings(as.integer(d[[i]]))
#bools <- which(x$itype == 3)
#for (i in bools) d[[i]] <- suppressWarnings(as.logical(d[[i]]))
times <- x$itype == 4
if (any(times)) {
steps <- x$get_timesteps()
zones <- x$get_timezones()
for (i in which(times)) {
d[[i]] <- strptime("1970-01-01", "%Y-%m-%d", tz = "UTC") + d[[i]]
if (!(zones[i] %in% c("", "UTC"))) {
attr(d[[i]], "tzone") = zones[i]
}
if (steps[i] == "days") {
d[[i]] <- as.Date(d[[i]])
}
}
}
d
}
.makeSpatFactor <- function(x) {
i <- as.integer(x)
i[is.na(i)] <- 0
SpatFactor$new(i, levels(x), is.ordered(x))
}
.getSpatFactor <- function(x) {
i <- x$values
i[i==0] <- NA
if (isTRUE(x$ordered)) {
ordered(x$labels[i], x$labels)
} else {
factor(x$labels[i], x$labels)
}
}
terra/R/readsvg.R 0000644 0001762 0000144 00000003513 14536376240 013362 0 ustar ligges users
transform <- function(xy, m) {
newX = m[1] * xy[,1] + m[3] * xy[,2] + m[5]
newY = m[2] * xy[,1] + m[4] * xy[,2] + m[6]
cbind(newX, newY)
}
oneline <- function(x, id) {
x <- trimws(gsub('^m', "", x))
ss <- trimws(unlist(strsplit(x, "m ")))
out <- list()
for (j in 1:length(ss)) {
v <- unlist(utils::read.table(text=ss[j], sep=" "))
vv <- as.numeric(unlist(strsplit(v, ",")))
vv <- matrix(vv, ncol=2, byrow=TRUE)
if (j > 1) {
vv[1,] <- vv[1,] + a[1,]
}
a <- apply(vv, 2, cumsum)
out[[j]] <- a
}
out <- lapply(1:length(out), function(p) cbind(id=id, part=p, out[[p]], hole=0))
out <- do.call(rbind, out)
out[,4] <- -out[,4]
#out[,3:4] <- transform(out[,3:4], m)
out
}
oneline2 <- function(x, id) {
x <- trimws(gsub('^M', "", x))
ss <- trimws(unlist(strsplit(x, "ZM")))
out <- list()
for (j in 1:length(ss)) {
v <- unlist(strsplit(ss[j], "L"))
v <- unlist(strsplit(v, "C"))
v <- unlist(strsplit(v, " "))
v <- gsub("Z", "", v)
vv <- as.numeric(unlist(strsplit(v, ",")))
vv <- matrix(vv, ncol=2, byrow=TRUE)
out[[j]] <- vv
}
out <- lapply(1:length(out), function(p) cbind(id=id, part=p, out[[p]], hole=0))
do.call(rbind, out)
#out[,3:4] <- transform(out[,3:4], m)
}
readSVG <- function(f) {
doc <- XML::htmlParse(f)
p <- XML::xpathSApply(doc, "//path", XML::xmlGetAttr, "d")
s <- list()
for (i in 1:length(p)) {
s[[i]] <- oneline2(p[i], i)
}
ss <- do.call(rbind, s)
v <- vect(ss, type="polygons")
a <- XML::xpathSApply(doc, "//path", XML::xmlAttrs)
a <- unique(unlist(sapply(a, names)))
a <- a[-grep(":", a)]
a <- a[a != "d"]
if (length(a) > 0) {
att <- list()
for (i in 1:length(a)) {
z <- XML::xpathSApply(doc, "//path", XML::xmlGetAttr, a[i])
att[[i]] <- sapply(z, function(i) if (is.null(i)) NA else i, USE.NAMES = FALSE)
}
names(att) <- a
values(v) <- data.frame(att)
}
v
}
terra/R/divide.R 0000644 0001762 0000144 00000014442 14752017430 013167 0 ustar ligges users # Author: Robert Hijmans
# December 2024
# License GPL3
getv <- function(x, a) {
cumsum(values(aggregate(x, a, sum, na.rm=TRUE)) / 1000)
}
splitNS3 <- function(x) {
v <- getv(x, c(1, ncol(x)))
m1 <- which.min(abs(v - max(v)/3))
m2 <- which.min(abs(v - max(v) * 2/3))
list(n=x[1:m1, ,drop=FALSE], m=x[(m1+1):m2, ,drop=FALSE], s=x[(m2+1):nrow(x), ,drop=FALSE])
}
splitNS <- function(x) {
v <- getv(x, c(1, ncol(x)))
m <- which.min(abs(v - max(v)/2))
list(n=x[1:m, ,drop=FALSE], s=x[(m+1):nrow(x), ,drop=FALSE])
}
splitWE3 <- function(x) {
v <- getv(x, c(nrow(x), 1))
m1 <- which.min(abs(v - max(v)/3))
m2 <- which.min(abs(v - max(v) * 2/3))
list(w=x[, 1:m1, drop=FALSE], m=x[, (m1+1):m2, drop=FALSE], e=x[, (m2+1):ncol(x), drop=FALSE])
}
splitWE <- function(x) {
v <- getv(x, c(nrow(x), 1))
m <- which.min(abs(v - max(v)/2))
list(w=x[, 1:m, drop=FALSE], e=x[, (m+1):ncol(x), drop=FALSE])
}
setMethod("divide", signature(x="SpatRaster"),
function(x, n=2, start="ns", as.raster=FALSE, na.rm=TRUE) {
# if (!is.null(border)) stopifnot(inherits(border, "SpatVector"))
if (nlyr(x) > 1) {
warn("divide", "only the first layer is used")
x <- x[[1]]
}
n <- round(n)
if (length(n) > 1) {
if (!all(n %in% c(-2,-1,1,2))) {
error("divide", "if (length(n) > 1), values can only be -3, -2 for WE and 2, 3 for NS")
}
} else {
if (!isTRUE(n > 0)) {
error("divide", "n must be > 0")
}
start <- match.arg(tolower(start), c("ns", "ew"))
north <- start == "ns"
}
if (!hasValues(x)) {
out <- x
if (length(n) > 1) {
nrow(out) <- sum(abs(n[n<0]) + 1)
ncol(out) <- sum(abs(n[n<0]) + 1)
} else {
if (north) {
rows <- ceiling(n / 2)
cols <- n - rows
} else {
cols <- ceiling(n / 2)
rows <- n - cols
}
nrow(out) <- rows * 2
ncol(out) <- cols * 2
}
out <- as.polygons(out)
} else {
out <- list(classify(trim(x), cbind(NA, 0)))
if (length(n) > 1) {
for (i in 1:length(n)) {
if (n[i] == 1) {
out <- unlist(lapply(out, function(i) splitNS(i)))
} else if (n[i] == -1) {
out <- unlist(lapply(out, function(i) splitWE(i)))
} else if (n[i] == 2) {
out <- unlist(lapply(out, function(i) splitNS3(i)))
} else { # if (n[i] == -2) {
out <- unlist(lapply(out, function(i) splitWE3(i)))
}
}
} else {
for (i in 1:n) {
if (north) {
out <- unlist(lapply(out, function(s) splitNS(s)))
} else {
out <- unlist(lapply(out, function(s) splitWE(s)))
}
north <- !north
}
}
out <- vect(lapply(out, function(i) as.polygons(ext(i))))
crs(out) <- crs(out)
}
out$zones <- 1:nrow(out)
if (isTRUE(as.raster) || is.na(as.raster)) {
r <- rasterize(out, x, "zones")
if (na.rm) {
r <- mask(r, x)
}
if (is.na(as.raster)) {
return(list(r=r, v=out))
} else {
return(r)
}
} else if (na.rm) {
border <- as.polygons(not.na(x, TRUE))
out <- crop(out, border)
}
out
}
)
check_frac <- function(f) {
if (is.null(f)) return(f)
if ((any(f <= 0)) || (any(f >= 1))) {
stop("f values must be > 0 and < 1")
}
if (length(f) == 1) {
f <- seq(f, 1, f)
f[length(f)] <- 1
} else {
if (length(unique(f)) < length(f)) {
stop("f values must be unique")
}
ord <- order(f)
if (!all(ord == 1:length(ord))) {
stop("f values must be in ascending order")
}
if (!isTRUE(all.equal(sum(f), 1, tolerance=0.0001))) {
stop("f values must sum to 1")
}
}
f
}
strip_polygon <- function(x, vertical, horizontal) {
## based on a function by Barry Rowlinson
totalArea <- expanse(x, transform=FALSE, unit="km")
e <- ext(x)
ex <- data.frame(t(as.vector(e + 1)))
e <- data.frame(t(as.vector(e)))
if (!is.null(vertical)) {
edges <- sapply(vertical, function(fraction){
target <- totalArea * fraction
target_fun <- function(xm){
expanse(crop(x, ext(ex$xmin, xm, ex$ymin, ex$ymax)), transform=FALSE, unit="km") - target
}
stats::uniroot(target_fun, lower=e$xmin+0.0000001, upper=e$xmax)$root
})
xbnds <- matrix(c(ex$xmin, rep(edges,rep(2,length(edges))), ex$xmax), ncol=2, byrow=TRUE)
xbnds <- cbind(xbnds, ex$ymin, ex$ymax)
xbnds <- do.call(rbind, apply(xbnds, 1, function(i) as.polygons(ext(i))))
xbnds$vid <- 1:nrow(xbnds)
}
if (!is.null(horizontal)) {
edges <- sapply(horizontal, function(fraction){
target <- totalArea * fraction
target_fun <- function(ym){
expanse(crop(x, ext(ex$xmin, ex$xmax, ex$ymin, ym)), transform=FALSE, unit="km") - target
}
stats::uniroot(target_fun, lower=e$ymin+0.0000001, upper=e$ymax)$root
})
ybnds <- matrix(c(ex$ymin, rep(edges,rep(2,length(edges))), ex$ymax), ncol=2, byrow=TRUE)
ybnds <- cbind(ex$xmin, ex$xmax, ybnds)
ybnds <- do.call(rbind, apply(ybnds, 1, function(i) as.polygons(ext(i))))
ybnds$hid <- 1:nrow(ybnds)
if (!is.null(vertical)) {
bnds <- union(xbnds, ybnds)
} else {
bnds <- ybnds
}
}
intersect(x, bnds)
}
divide_polygon <- function(x, n, w, alpha, ...) {
xcrs <- crs(x)
crs(x) <- "+proj=utm +zone=1"
s <- terra::spatSample(x, max(n*4, 1000, log(n) * 100), "regular")
xy <- terra::crds(s)
if (!is.null(w)) {
e <- extract(w, s, ID=FALSE)
alpha <- rep_len(alpha, 2)
xy[,1] <- xy[,1] * alpha[1]
xy[,2] <- xy[,2] * alpha[2]
xy <- na.omit(cbind(xy, e))
}
k <- stats::kmeans(xy, centers = n, ...)
ctrs <- k$centers[, 1:2]
if (!is.null(w)) {
ctrs[,1] <- ctrs[,1] / alpha[1]
ctrs[,2] <- ctrs[,2] / alpha[2]
}
v <- terra::voronoi(vect(ctrs, crs=xcrs), bnd=x)
terra::crop(v, x)
}
setMethod("divide", signature(x="SpatVector"),
function(x, n=5, w=NULL, alpha=1, ...) {
if (geomtype(x) != "polygons") {
error("divide", "the geometry type must be polgyons")
}
if (is.list(n)) {
vertical <- check_frac(n$v)
horizontal <- check_frac(n$h)
if (is.null(vertical) && is.null(horizontal)) return(x)
out <- lapply(1:nrow(x), function(i) strip_polygon(x[i], vertical, horizontal))
} else {
n <- round(n)
stopifnot(n > 0)
if (n == 1) return(deepcopy(x))
out <- lapply(1:nrow(x), function(i) divide_polygon(x[i], n, w, alpha, ...))
}
do.call(rbind, out)
}
)
terra/R/colors.R 0000644 0001762 0000144 00000004731 14726700274 013232 0 ustar ligges users
setMethod ("has.colors" , "SpatRaster",
function(x) {
x@pntr$hasColors()
}
)
setMethod ("coltab" , "SpatRaster",
function(x) {
hascols <- x@pntr$hasColors()
if (any(hascols)) {
d <- x@pntr$getColors()
d <- lapply(d, .getSpatDF)
d[!hascols] <- list(NULL)
} else {
d <- vector("list", length(hascols))
}
d
}
)
setMethod ("coltab<-" , "SpatRaster",
function(x, ..., layer=1, value) {
x@pntr <- x@pntr$deepcopy()
if (inherits(value, "list")) {
for (i in seq_along(value)) {
layer <- i-1
if (is.null(value[[i]])) {
x@pntr$removeColors(layer)
}
if (inherits(value[[i]], "character")) {
value[[i]] <- data.frame(t(grDevices::col2rgb(value[[i]], alpha=TRUE)), stringsAsFactors=FALSE)
} else if (inherits(value[[i]], "matrix")) {
value[[i]] <- data.frame(value[[i]])
}
if (!inherits(value[[i]], "data.frame")) {
error("coltab<-", "cannot process these color values")
}
if (ncol(value[[i]]) == 2) {
value[[i]] <- data.frame(values=value[[i]][,1], t(grDevices::col2rgb(value[[i]][,2], alpha=TRUE)), stringsAsFactors=FALSE)
}
value[[i]][, 1] <- as.integer(value[[i]][, 1])
for (j in 2:ncol(value[[i]])) {
value[[i]][, j] <- as.integer(clamp(value[[i]][, j], 0, 255))
}
value[[i]][is.na(value[[i]])] <- 255
d <- .makeSpatDF(value[[i]])
if (!x@pntr$setColors(layer, d)) {
messages(x, "cols<-")
}
}
} else {
layer <- layer[1]-1
if (is.null(value)) {
x@pntr$removeColors(layer)
return(x)
}
if (inherits(value, "character")) {
value <- data.frame(t(grDevices::col2rgb(value, alpha=TRUE)), stringsAsFactors=FALSE)
} else if (inherits(value, "matrix")) {
value <- data.frame(value)
}
if (!inherits(value, "data.frame")) {
error("coltab<-", "cannot process these color values")
}
if (ncol(value) == 2) {
value <- data.frame(values=value[,1], t(grDevices::col2rgb(value[,2], alpha=TRUE)), stringsAsFactors=FALSE)
} #else {
# nms <- tolower(names(value))
# if (!(grepl("value", nms))) {
# value <- cbind(values=(1:nrow(value))-1, value)
# }
# #value <- value[1:256,]
# if (ncol(value) == 4) {
# value <- cbind(value, alpha=255)
# }
#}
value[, 1] <- as.integer(value[, 1])
for (i in 2:ncol(value)) {
value[, i] <- as.integer(clamp(value[, i], 0, 255))
}
value[is.na(value)] <- 255
d <- .makeSpatDF(value)
if (!x@pntr$setColors(layer, d)) {
messages(x, "cols<-")
}
}
x
}
)
terra/R/window.R 0000644 0001762 0000144 00000001207 14751211317 013224 0 ustar ligges users
setMethod("set.window", signature(x="SpatRaster"),
function(x, value) {
if (inherits(value, "SpatExtent")) {
window(x) <- NULL
value <- intersect(ext(x), value)
if (!(x@pntr$setWindow(value@pntr))) {
error("window<-,SpatRaster", "cannot set this window")
}
} else if (is.null(value) || is.na(value)) {
x@pntr$removeWindow()
} else {
error("window<-", "'value' should be a SpatExtent, NULL or NA")
}
x
}
)
setMethod("window<-", signature(x="SpatRaster"),
function(x, value) {
set.window(deepcopy(x), value)
}
)
setMethod("window", signature(x="SpatRaster"),
function(x) {
x@pntr$hasWindow()
}
)
terra/R/panel.R 0000644 0001762 0000144 00000006016 14740004450 013013 0 ustar ligges users
setMethod("panel", signature(x="SpatRaster"),
function(x, main, loc.main="topleft", nc, nr, maxnl=16, maxcell=500000,
box=FALSE, pax=list(), plg=list(), range=NULL, halo=TRUE, type=NULL, ...) {
if (!is.null(type)) {
type <- match.arg(tolower(type), c("classes", "continuous", "interval"))
}
# dots <- list(...)
# if (!is.null(dots$type)) {
# error("panel", "you cannot set the plot type")
# }
# if (!is.null(dots$breaks)) {
# error("panel", "you cannot use argument 'breaks'")
# }
categorical <- FALSE
if (is.null(type) && any(is.factor(x))) {
x <- combineLevels(x)
categorical <- TRUE
}
nl <- max(1, min(nlyr(x), maxnl))
if (nl==1) {
out <- plot(x, 1, maxcell=maxcell, main=main[1], ...)
return(invisible(out))
}
nrnc <- .get_nrnc(nr, nc, nl)
old.par <- graphics::par(no.readonly = TRUE)
on.exit(graphics::par(old.par))
mar <- rep(0.33, 4)
m <- matrix((1:prod(nrnc))+1, nrow=nrnc[1], ncol=nrnc[2], byrow=TRUE)
m <- rbind(1, cbind(1, m, max(m)+1), 1)
w <- c(0.05, rep(0.8/nrnc[2], nrnc[2]), 0.15)
h <- c(0.05, rep(0.94/nrnc[1], nrnc[1]), 0.05)
graphics::layout(m, w, h)
plot(0, type="n", axes=FALSE, xlab="", ylab="")
maxcell <- maxcell/nl
if (missing("main")) {
tm <- time(x)
if (!any(is.na(tm))) {
main <- as.character(time(x))
} else {
main <- names(x)
}
} else {
main <- rep_len(main, nl)
}
legend <- rep(FALSE , nl)
legi <- max(1, ceiling(nrnc[1] / 2)) * nrnc[2]
legend[legi] <- TRUE
left <- c(0,2)[(((1:nl)-1) %% nrnc[2] == 0)+1]
b <- ((1:nl) > ((nrnc[1]-1) * nrnc[2]))+1
i <- (prod(nrnc) - nl)
if (i > 0) {
b[((nrnc[1]-2) * nrnc[2]) + ((nrnc[2]-(i-1)):nrnc[2])] <- 2
}
bottom <- c(0,1)[b]
if (!categorical) {
x <- spatSample(x, maxcell, method="regular", as.raster=TRUE, warn=FALSE)
r <- as.matrix(x)
if (is.null(range)) {
if (all(hasMinMax(x))) {
range <- range(minmax(x, FALSE))
if (any(is.nan(range) | is.infinite(range))) {
r <- as.matrix(x)
r[is.infinite(r)] <- NA
range <- range(r, na.rm=TRUE)
}
} else {
r[is.infinite(r)] <- NA
range <- range(r, na.rm=TRUE)
}
}
r <- unique(as.vector(r))
if (is.null(type)) {
if (length(r) > 10) {
type <- "continuous"
} else {
type <- "classes"
}
}
if (type == "classes") {
levs <- data.frame(ID=1:length(r), sort(r))
colnames(levs)[2] <- names(x)[1]
x <- categories(x, 0, levs)
categorical <- TRUE
}
}
if (is.null(plg$size)) plg$size <- max(1, nrnc[1] * 0.66)
if (is.null(plg$cex)) plg$cex <- 1.25
plg$yshift <- (nrnc[1] %% 2 == 0)
for (i in 1:nl) {
pax$side <- c(bottom[i], left[i])
if (categorical) {
plot(x[[i]], 1, main=main[i], mar=mar, legend=legend[i], pax=pax, box=box,
loc.main=loc.main, halo=halo, plg=plg, type="classes", all_levels=TRUE, maxcell=Inf, ...)
} else {
plot(x, i, main=main[i], mar=mar, legend=legend[i], range=range, pax=pax, box=box,
loc.main=loc.main, halo=halo, plg=plg, type=type, maxcell=Inf, ...)
}
}
}
)
terra/R/plot_legend.R 0000644 0001762 0000144 00000035317 14725637141 014232 0 ustar ligges users
.get_breaks <- function(x, n, method, r=NULL) {
#x <- x[!is.na(x)]
if (is.function(method)) {
if (!is.null(r)) {
if (!is.na(r[1])) {
x[ x < r[1] ] <- NA
}
if (!is.na(r[2])) {
x[ x > r[2] ] <- NA
}
}
breaks <- method(x)
} else if (method[1]=="cases") {
if (!is.null(r)) {
if (!is.na(r[1])) {
x[ x < r[1] ] <- NA
}
if (!is.na(r[2])) {
x[ x > r[2] ] <- NA
}
}
n <- n+1
i <- seq(0, 1, length.out=n)
breaks <- quantile(x, i, na.rm=TRUE)
breaks <- unique(breaks)
if ((breaks[1] %% 1) != 0) {
breaks[1] <- breaks[1] - 0.000001
}
if ((breaks[n] %% 1) != 0) {
breaks[n] <- breaks[n] + 0.000001
}
} else { # if (method=="eqint") {
if (is.null(r)) {
r <- c(min(x, na.rm=TRUE), max(x, na.rm=TRUE))
} else if (any(is.na(r))) {
if (is.na(r[1])) r[1] <- min(x, na.rm=TRUE)
if (is.na(r[2])) r[2] <- max(x, na.rm=TRUE)
}
small <- 1e-16
if ((r[1] %% 1) != 0) { r[1] <- r[1] - small }
if ((r[2] %% 1) != 0) { r[2] <- r[2] + small }
breaks <- seq(r[1] , r[2], length.out=n+1)
}
unique(breaks)
}
.get_nrnc <- function(nr, nc, nl) {
if (missing(nc)) {
nc <- ceiling(sqrt(nl))
} else {
nc <- max(1, min(nl, round(nc)))
}
if (missing(nr)) {
nr <- ceiling(nl / nc)
} else {
nr <- max(1, min(nl, round(nr)))
nc <- ceiling(nl / nr)
}
c(nr, nc)
}
retro_labels <- function(x, lat=TRUE) {
if ((is.null(x)) || (!is.numeric(x))) {
return(x)
}
if ((length(x) > 1) && (min(diff(x)) <= 1/120)) {
d <- floor(x)
m <- floor(60*(x - d))
s <- round(3600*(x - d - m/60))
} else {
d <- floor(x)
m <- round(60*(x - d))
s <- 0
}
if (lat) {
h <- c("S", "", "N")[sign(d)+2]
} else {
h <- c("W", "", "E")[sign(d)+2]
}
d <- abs(d)
i <- (s == 0) & (m == 0)
j <- (s == 0) & (m != 0)
m <- formatC(m, width=2, flag="0")
s <- formatC(s, width=2, flag="0")
r <- paste0(d, "\u00B0" , m, "'", s, '"', h)
r[i] <- paste0(d[i], "\u00B0" , h[i])
r[j] <- paste0(d[j], "\u00B0" , m[j], "'", h[j])
r
}
.get.leg.coords <- function(x) {
if (is.null(x$leg$ext)) {
if (x$clip) {
p <- x$leg$ext <- x$lim
} else {
p <- x$leg$ext <- graphics::par("usr")
}
} else {
p <- as.vector(x$leg$ext)
}
xmin <- p[1]
xmax <- p[2]
ymin <- p[3]
ymax <- p[4]
flip <- FALSE
if (!is.null(x$leg$shrink)) {
s <- x$leg$shrink
if ((s[1] <= 1) & (s[1] >= 0.5)) {
s[1] <- 2*(s[1] - 0.5)
} else if (s[1] < 0.5) {
s[1] <- (2*(0.5 - s[1]))
flip <- TRUE
}
x$leg$size <- s
}
if (is.null(x$leg$size)) {
x$leg$size <- c(1,1)
} else if (length(x$leg$size) == 1) {
x$leg$size <- c(x$leg$size, 1)
}
if (x$leg$size[1] < 0) flip <- TRUE
x$leg$size <- abs(x$leg$size)
if (!is.null(x$leg$main)) {
n <- length(x$leg$main)
x$leg$size[1] <- min(x$leg$size[1], (1 - .05*n))
}
horiz <- isTRUE(x$leg$x %in% c("top", "bottom"))
if (horiz) {
# xd <- (xmax - xmin) * x$leg$size[2]
# xmin <- xmin + xd
# xmax <- xmax - xd
rhalf <- (xmax - xmin) / 2
xmid <- xmin + rhalf
xd <- rhalf * x$leg$size[1]
xmin <- xmid - xd
xmax <- xmid + xd
# yd <- (ymax - ymin) * x$leg$size[1]/1.5
# ymin <- ymin + yd
# ymax <- ymax - yd
yd <- ymax - ymin
if (x$leg$x == "top") {
ymax <- ymin + yd * x$leg$size[2]
} else {
ymin <- ymax - yd * x$leg$size[2]
}
if (flip) {
tmp <- xmin
xmin <- xmax
xmax <- tmp
}
} else {
rhalf <- (ymax - ymin) / 2
ymid <- ymin + rhalf
yd <- rhalf * x$leg$size[1]
ymin <- ymid - yd
ymax <- ymid + yd
xd <- xmax - xmin
#xmin <- xmin + xd * x$leg$size[2]/5
#xmax <- xmax - xd * x$leg$size[2]/5
xmax <- xmin + xd * x$leg$size[2]
if (flip) {
tmp <- ymin
ymin <- ymax
ymax <- tmp
}
}
dx <- xmax - xmin
dy <- ymax - ymin
x$leg$ext <- data.frame(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, dx=dx, dy=dy)
x
}
.line.usr <- function(line, side) {
## https://stackoverflow.com/questions/30765866/get-margin-line-locations-in-log-space/30835971#30835971
lh <- graphics::par("cin")[2] * graphics::par("cex") * graphics::par("lheight")
x_off <- diff(graphics::grconvertX(c(0, lh), "inches", "npc"))
y_off <- diff(graphics::grconvertY(c(0, lh), "inches", "npc"))
if (side == 1) {
graphics::grconvertY(-line * y_off, "npc", "user")
} else if (side ==2) {
graphics::grconvertX(-line * x_off, "npc", "user")
} else if (side ==3) {
graphics::grconvertY(1 + line * y_off, "npc", "user")
} else {
graphics::grconvertX(1 + line * x_off, "npc", "user")
}
}
.get.leg.extent <- function(x) {
#usr <- graphics::par("usr")
dxy <- graphics::par("cxy") * graphics::par("cex")
loc <- x$leg$x
if (x$clip) {
usr <- x$lim
} else {
usr <- graphics::par("usr")
}
xmin <- usr[1]
xmax <- usr[2]
ymin <- usr[3]
ymax <- usr[4]
p <- NULL
if (is.character(loc)) {
if (loc == "left") {
#s <- .line.usr(trunc(graphics::par("mar")[2]), 2)
#p <- c(s+4*dxy[1], s+5*dxy[1], ymin, ymax)
if (any(2 %in% x$axs$lab)) {
p <- c(xmin-4*dxy[1], xmin-3*dxy[1], ymin, ymax)
} else {
p <- c(xmin-2*dxy[1], xmin-dxy[1], ymin, ymax)
}
} else if (loc == "bottom") {
s <- .line.usr(trunc(graphics::par("mar")[1]), 1)
p <- c(xmin, xmax, s+1.75*dxy[2], s+2.5*dxy[2])
} else if (loc == "top") {
p <- c(xmin, xmax, ymax+dxy[2], ymax+1.75*dxy[2])
} else { #if (loc == "right" or "default"
p <- c(xmax+dxy[1], xmax+2*dxy[1], ymin, ymax)
if (isTRUE(x$leg$yshift)) {
hy <- (ymax - ymin) / 2
p[3:4] <- p[3:4] - hy
}
}
}
x$leg$ext <- p
x$leg$user <- FALSE
.get.leg.coords(x)
}
.txt.loc <- function(x) {
if (isTRUE(x$clip)) {
dxy <- graphics::par("cxy") * x$cex.main
if (grepl("right", x$loc.main)) {
px <- x$lim[2]
pos <- 2
} else {
px <- x$lim[1]
pos <- 4
}
if (grepl("bottom", x$loc.main)) {
py <- x$lim[3] + dxy[2]/2
} else {
py <- x$lim[4] - dxy[2]/2
}
} else {
dxy <- graphics::par("cxy") * x$cex.main
usr <- graphics::par("usr")
if (grepl("right", x$loc.main)) {
px <- usr[2]
pos <- 2
} else {
px <- usr[1]
pos <- 4
}
if (grepl("bottom", x$loc.main)) {
py <- usr[3] + dxy[2]/2
} else {
py <- usr[4] - dxy[2]/2
}
}
out <- c(px, py, pos)
names(out) <- NULL
out
}
.plot.cont.legend <- function(x, ...) {
if (!is.null(x$leg$tic)) {
accepted <- c("in", "out", "none", "through", "throughout")
tics <- accepted[pmatch(x$leg$tic[1], accepted[-5], 5)]
} else {
tics <- "throughout"
}
if (!is.null(x$leg$tic.box.col)) {
ticboxcol <- x$leg$tic.box.col
} else {
ticboxcol <- "black"
}
if (is.null(x$leg$x)) {
x$leg$x <- "right"
} else if (!(x$leg$x %in% c("left", "right", "top", "bottom"))) {
x$leg$x <- "right"
}
if (is.null(x$leg$ext)) {
x <- .get.leg.extent(x)
} else {
x <- .get.leg.coords(x)
}
cex <- x$leg$cex
if (is.null(cex)) cex <- 1
cex <- cex * 0.8
rotate <- isTRUE(x$leg$rotate)
srt <- ifelse(rotate, 90, 0)
cols <- rev(x$cols)
nc <- length(cols)
zlim <- x$range
zz <- x$leg$at
if (is.null(zz)) {
if (is.null(x$levels)){
x$levels <- 5
}
zz <- pretty(zlim, n =(x$levels+1))
zz <- zz[zz >= zlim[1] & zz <= zlim[2]]
}
zztxt <- x$leg$labels
if (is.null(zztxt)) {
zztxt <- formatC(zz, digits=x$leg$digits, format = "f")
if (x$fill_range) {
if (isTRUE(x$range_filled[1])) zztxt[1] <- paste0("< ", zztxt[1])
if (isTRUE(x$range_filled[2])) zztxt[length(zztxt)] <- paste0("> ", zztxt[length(zztxt)])
}
}
e <- x$leg$ext
if (x$leg$x %in% c("left", "right")) {
Y <- seq(e$ymin, e$ymax, length.out=nc+1)
graphics::rect(e$xmin, Y[-(nc + 1)], e$xmax, Y[-1], col=rev(cols), border=NA, xpd=NA)
ypos <- e$ymin + (zz - zlim[1])/(zlim[2] - zlim[1]) * e$dy
if (x$leg$x == "right") {
if (tics == "throughout") {
graphics::segments(e$xmin, ypos, e$xmax+e$dx*0.25, ypos, xpd=NA)
} else if (tics == "through") {
graphics::segments(e$xmin, ypos, e$xmax, ypos, xpd=NA)
} else if (tics == "in") {
graphics::segments(e$xmax-e$dx*0.25, ypos, e$xmax, ypos, xpd=NA)
} else if (tics == "out") {
graphics::segments(e$xmax, ypos, e$xmax+e$dx*0.25, ypos, xpd=NA)
}
text(e$xmax, ypos, zztxt, pos=4, xpd=NA, cex=cex, ...)
} else {
if (tics == "throughout") {
graphics::segments(e$xmin-e$dx*0.25, ypos, e$xmax, ypos, xpd=NA)
} else if (tics == "through") {
graphics::segments(e$xmin, ypos, e$xmax, ypos, xpd=NA)
} else if (tics == "in") {
graphics::segments(e$xmin, ypos, e$xmin+e$dx*0.25, ypos, xpd=NA)
} else if (tics == "out") {
graphics::segments(e$xmin-e$dx*0.25, ypos, e$xmin, ypos, xpd=NA)
}
text(e$xmin, ypos, zztxt, pos=2, xpd=NA, cex=cex, ...)
}
} else {
X <- seq(e$xmin, e$xmax, length.out=nc+1)
graphics::rect(X[-(nc + 1)], e$ymin, X[-1], e$ymax, col=rev(cols), border=NA, xpd=NA)
xpos <- e$xmin + (zz - zlim[1])/(zlim[2] - zlim[1]) * e$dx
if (x$leg$x == "bottom") {
if (tics == "throughout") {
graphics::segments(xpos, e$ymin-e$dy*0.25, xpos, e$ymax, xpd=NA)
} else if (tics == "through") {
graphics::segments(xpos, e$ymin, xpos, e$ymax, xpd=NA)
} else if (tics == "in") {
graphics::segments(xpos, e$ymin+e$dy*0.25, xpos, e$ymin, xpd=NA)
} else if (tics == "out") {
graphics::segments(xpos, e$ymin-e$dy*0.25, xpos, e$ymin, xpd=NA)
}
text(xpos, e$ymin, zztxt, pos=1, xpd=NA, cex=cex)
} else {
if (tics == "throughout") {
graphics::segments(xpos, e$ymin, xpos, e$ymax+e$dy*0.25, xpd=NA)
} else if (tics == "through") {
graphics::segments(xpos, e$ymin, xpos, e$ymax, xpd=NA)
} else if (tics == "in") {
graphics::segments(xpos, e$ymax, xpos, e$ymax-e$dy*0.25, xpd=NA)
} else if (tics == "out") {
graphics::segments(xpos, e$ymax, xpos, e$ymax+e$dy*0.25, xpd=NA)
}
text(xpos, e$ymax+e$dy*0.25, zztxt, pos=3, xpd=NA, cex=cex)
}
}
graphics::rect(e$xmin, e$ymin, e$xmax, e$ymax, border=ticboxcol, xpd=NA)
if (isTRUE("title" %in% names(x$leg))) {
leg_i <- x$leg$leg_i
if (is.null(leg_i)) leg_i = 1
if (leg_i <= length(x$leg$title)) {
legtitle <- x$leg$title[leg_i]
} else {
legtitle <- x$leg$title[1]
}
e <- x$leg$ext
if (length(legtitle) > 1) { # or perhaps !inherits(legtitle, "expression")
if (x$leg$x %in% c("top", "bottom")) {
legtitle <- paste(legtitle, collapse=" ")
} else {
legtitle <- paste(legtitle, collapse="\n")
}
}
# offset=.5*graphics::strheight("a",cex=x$leg$title.cex)
text(x=e$xmax, y=e$ymax, labels=legtitle, pos=3, cex=x$leg$title.cex, xpd=NA)
}
x
}
get_legxy <- function(r, e, pos, yshift) {
xy <- c(r$left, r$top)
if (grepl("top", pos)) {
xy[2] <- e[4]
} else if (grepl("bottom", pos)) {
xy[2] <- e[3] + r$h
}
if (grepl("left", pos)) {
xy[1] <- e[1]
} else if (grepl("right", pos)) {
xy[1] <- e[2] - r$w
}
if (!is.null(yshift)) {
hy <- (e[4] - e[3]) / 2
xy[2] <- xy[2] - hy
}
xy
}
.plot.class.legend <- function(x, y, legend, fill, xpd=NA, cex=1, geomtype="",
lty=1, lwd=1, pch=1, angle=45, density=NULL, pt.cex = 1, pt.bg="black", pt.lwd=1,
bty="n", border="black", seg.len=1, plotlim, yshift=NULL, title=NULL, leg_i=1, ...,
# catch and kill
merge, trace, size) {
cex <- cex * 0.8
if (x %in% c("top", "default")) {
#usr <- graphics::par("usr")
x <- plotlim[2]
y <- plotlim[4]
}
if (is.null(leg_i)) leg_i = 1
if (leg_i <= length(title)) {
title <- title[leg_i]
} else {
title <- title[1]
}
#points(leg$rect$left+leg$rect$w, leg$rect$top-leg$rect$h, xpd=T)
if (grepl("points", geomtype)) {
if (inherits(x, "character")) {
r <- legend(x, y, legend, col=fill, xpd=xpd, bty=bty, cex=cex, pch=pch, pt.cex=pt.cex, pt.bg=pt.bg, pt.lwd=pt.lwd, plot=FALSE, title=title, ...)$rect
xy <- get_legxy(r, plotlim, x, yshift)
leg <- legend(xy[1], xy[2], legend, col=fill, xpd=xpd, bty=bty, cex=cex, pch=pch, pt.cex=pt.cex, pt.bg=pt.bg, pt.lwd=pt.lwd, title=title, ...)
} else {
leg <- legend(x, y, legend, col=fill, xpd=xpd, bty=bty, cex=cex, pch=pch, pt.cex=pt.cex, pt.bg=pt.bg, pt.lwd=pt.lwd, title=title,...)
}
} else if (geomtype == "lines") {
if (inherits(x, "character")) {
r <- legend(x, y, legend, col=fill, xpd=xpd, bty=bty, cex=cex, lty=lty, lwd=lwd, seg.len=seg.len, plot=FALSE, title=title,, ...)$rect
xy <- get_legxy(r, plotlim, x, yshift)
leg <- legend(xy[1], xy[2], legend, col=fill, xpd=xpd, bty=bty, cex=cex, lty=lty, lwd=lwd, seg.len=seg.len, title=title,, ...)
} else {
leg <- legend(x, y, legend, col=fill, xpd=xpd, bty=bty, cex=cex, lty=lty, lwd=lwd, seg.len=seg.len, title=title, ...)
}
} else {
if (inherits(x, "character")) {
r <- legend(x, y, legend, fill=fill, xpd=xpd, bty=bty, cex=cex, density=density*2, angle=angle, border=border, plot=FALSE, title=title, ...)$rect
xy <- get_legxy(r, plotlim, x, yshift)
leg <- legend(xy[1], xy[2], legend, fill=fill, xpd=xpd, bty=bty, cex=cex, density=density*2, angle=angle, border=border, title=title, ...)
} else {
leg <- legend(x, y, legend, fill=fill, xpd=xpd, bty=bty, cex=cex, density=density*2, angle=angle, border=border, title=title, ...)
}
}
leg
}
add_legend <- function(x, y, ...) {
if (inherits(x, "character")) {
e <- unlist(get.clip())
if (!is.null(e)) {
rct <- graphics::legend(x=x, y=y, plot=FALSE, ...)$rect
xy <- get_legxy(rct, e[1:4], x, NULL)
graphics::legend(x=xy[1], y=xy[2], ...)
} else {
graphics::legend(x=x, y=y, ...)
}
} else {
graphics::legend(x=x, y=y, ...)
}
}
add_box <- function(...) {
e <- unlist(get.clip())
if (!is.null(e)) {
bx <- rbind(
cbind(e[1], e[3:4]),
cbind(e[2], e[4:3]),
cbind(e[1], e[3])
)
if (is.null(list(...)$xpd)) {
lines(bx, xpd=TRUE, ...)
} else {
lines(bx, ...)
}
}
}
add_grid <- function(nx=NULL, ny=nx, col="lightgray", lty="dotted", lwd=1) {
p <- get.clip()
## adapted from graphics::grid
g.grid.at <- function (side, n, axp, usr2) {
if (is.null(n)) {
stopifnot(is.numeric(ax <- axp), length(ax) == 3L)
graphics::axTicks(side, axp=ax, usr=usr2, log=FALSE)
}
else if (!is.na(n) && (n <- as.integer(n)) >= 1L) {
at <- seq.int(usr2[1L], usr2[2L], length.out = n + 1L)
at[-c(1L, n + 1L)]
}
}
atx <- if (is.null(nx) || (!is.na(nx) && nx >= 1))
g.grid.at(1L, nx, axp = graphics::par("xaxp"), usr2 = p[1:2])
aty <- if (is.null(ny) || (!is.na(ny) && ny >= 1))
g.grid.at(2L, ny, axp = graphics::par("yaxp"), usr2 = p[3:4])
graphics::abline(v = atx, h = aty, col = col, lty = lty, lwd = lwd)
invisible(list(atx = atx, aty = aty))
}
add_mtext <- function(text, side=3, line=0, ...) {
stopifnot(side %in% 1:4)
p <- unlist(get.clip())
h <- graphics::strheight(text, units = "user", ...)
srt <- 0
if (side==1) {
x <- mean(p[1:2])
y <- p[3] - h - line * h
} else if (side==2) {
x <- p[1] -1.25 * h - line * h
y <- mean(p[3:4])
srt <- 90
} else if (side==3) {
x <- mean(p[1:2])
y <- p[4] + h + line * h
} else {
x <- p[2] + 1.25 * h + line * h
y <- mean(p[3:4])
srt <- 270
}
text(x=x, y=y, labels=text, xpd=TRUE, srt=srt, ...)
}
terra/R/tempfiles.R 0000644 0001762 0000144 00000002743 14715404523 013716 0 ustar ligges users
.orphanTmpFiles <- function() {
objects <- ls(envir=globalenv())
ftmp <- list()
for (i in seq_along(objects)) {
x <- get(objects[i], envir=globalenv())
if (inherits(x, "SpatRaster")) {
ftmp[[i]] <- sources(x)
}
}
ftmp <- unique(unlist(ftmp))
ftmp <- ftmp[ftmp != ""]
pattrn <- "^spat_.*tif$"
i <- grep(pattrn, basename(ftmp))
ftmp <- ftmp[i]
ff1 <- list.files(tempdir(), pattern=pattrn, full.names=TRUE)
ff2 <- list.files(terraOptions(print=FALSE)$tempdir, pattern = pattrn, full.names = TRUE)
ff <- unique(c(ff1, ff2))
i <- !(basename(ff) %in% basename(ftmp))
ff[i]
}
tmpFiles <- function(current=TRUE, orphan=FALSE, old=FALSE, remove=FALSE) {
if (!(old | current | orphan)) {
error("tmpFiles", "at least one of 'orphan', 'current' and 'old' must be set to TRUE")
}
opt <- spatOptions()
d <- opt$tempdir
f <- NULL
if (old) {
if (normalizePath(tempdir()) != normalizePath(d)) {
warn("tmpFiles", "old files can only be found if terra uses the R tempdir")
} else {
f <- list.files(dirname(d), recursive=TRUE, pattern="^spat_", full.names=TRUE)
f <- grep("Rtmp", f, value=TRUE)
if ((length(f) > 0) && (!current)) {
i <- grep(d, f)
if (length(i) > 0) {
f <- f[-i]
}
}
}
}
if (current) {
ff <- list.files(d, pattern="^spat", full.names=TRUE)
f <- c(f, ff)
} else if (orphan) {
fo <- .orphanTmpFiles()
f <- c(f, fo) # for if old=TRUE
}
if (remove) {
file.remove(f)
return(invisible(f))
} else {
return(f)
}
}
terra/R/zonal.R 0000644 0001762 0000144 00000037126 14726701466 013064 0 ustar ligges users
replace_with_label <- function(x, v, colnr) {
ff <- is.factor(x)
if (any(ff)) {
cgs <- cats(x)
for (f in which(ff)) {
cg <- cgs[[f]]
if (length(ff) == 1) {
r <- 1:nrow(v)
} else {
r <- which(v[,1] == f)
}
i <- match(v[r,colnr], cg[,1])
act <- activeCat(x, f) + 1
if (!inherits(cg[[act]], "numeric")) {
v[r, colnr] <- as.character(factor(cg[i, act], levels=unique(cg[[act]])))
} else {
v[r, colnr] <- cg[i, act]
}
}
}
v
}
setMethod("zonal", signature(x="SpatRaster", z="SpatRaster"),
function(x, z, fun="mean", ..., w=NULL, wide=TRUE, as.raster=FALSE, filename="", overwrite=FALSE, wopt=list()) {
group <- FALSE
made_unique <- FALSE
grast <- rast()
nlz <- nlyr(z)
znms <- names(z)
if (nlz == 1) {
group <- FALSE
} else if ((!as.raster) && (nlz == 2)) {
grast <- z[[2]]
z <- z[[1]]
group <- TRUE
} else {
ff <- is.factor(z)
if (any(ff)) {
levs <- levels(z)
levels(z) <- NULL
}
z <- unique(z, as.raster=TRUE)
made_unique <- TRUE
}
txtfun <- .makeTextFun(fun)
if (inherits(txtfun, "character") &&
(txtfun %in% c("max", "min", "mean", "sum", "notNA", "isNA"))) {
if ((nlyr(z) > 1) && (nlyr(x) > 1)) {
error("zonal", "x and z cannot both have more than one layer")
}
na.rm <- isTRUE(list(...)$na.rm)
opt <- spatOptions()
if (!is.null(w)) {
if (txtfun != "mean") {
error("zonal", "fun must be 'mean' when using weights")
}
sdf <- x@pntr$zonal_weighted(z@pntr, w@pntr, na.rm, opt)
} else {
sdf <- x@pntr$zonal(z@pntr, grast@pntr, txtfun, na.rm, opt)
}
sdf <- messages(sdf, "zonal")
out <- .getSpatDF(sdf)
nz <- 1
if (group) {
out$layer <- out$layer + 1
out <- replace_with_label(z, out, 2)
out <- replace_with_label(grast, out, 3)
if (nlyr(x) > 1) {
out <- split(out[-1], out$layer)
out <- Reduce(function(x, y) merge(x=x, y=y, by=1:2, all=TRUE), out)
out <- out[order(out[,1], out[,2]), ]
} else {
out <- out[,-1]
}
colnames(out) <- c(znms, names(x))
nz <- 2
} else if (!as.raster) {
if (made_unique) { # && (!as.raster)) {
ulevs <- cats(z)[[1]][, -c(1:2)]
if (any(ff)) {
for (f in which(ff)) {
i <- match(ulevs[,f], levs[[f]][,1])
ulevs[,f] <- levs[[f]][i,2]
}
}
out <- cbind(ulevs, out[,-1,drop=FALSE])
nz <- ncol(ulevs)
} else {
out <- replace_with_label(z, out, 1)
colnames(out)[1] <- znms
}
}
colnames(out) <- make.unique(colnames(out))
} else {
if (!is.null(w)) {
error("zonal", "can only use weights when fun=mean")
}
compareGeom(x, z, lyrs=FALSE, crs=FALSE, ext=TRUE, rowcol=TRUE)
#if (nlyr(z) > 1) {
# warn("zonal", "z can only have one layer with this function")
# z <- z[[1]]
#}
fun <- match.fun(fun)
nl <- nlyr(x)
nms <- names(x)
if (group) {
gzx <- c(grast, z, x)
v <- as.data.frame(gzx, na.rm=FALSE)
out <- stats::aggregate(v[,-c(1:2)], v[,1:2], fun, ...)
colnames(out)[-c(1:2)] <- nms
} else {
for (i in 1:nl) {
xz <- c(x[[i]], z)
v <- as.data.frame(xz, na.rm=FALSE)
d <- stats::aggregate(v[,1], v[,2,drop=FALSE], fun, ...)
colnames(d)[2] <- nms[i]
if (i == 1) {
out <- d
} else {
out <- merge(out, d, by=1)
}
}
}
}
if (as.raster) {
if (is.null(wopt$names) && (nlyr(x) == 1)) {
wopt$names <- names(x)
}
levels(z) <- NULL
out <- subst(z, out[,1], out[,-1], filename=filename, wopt=wopt)
}
if (wide) {
if (group) {
nms <- names(out)
isch <- inherits(out[,2], "character")
#out <- stats::reshape(out, direction="wide", idvar=nms[c(1,3)], timevar=nms[2])
out <- stats::reshape(out, direction="wide", idvar=nms[1], timevar=nms[2])
if (isch) {
colnames(out) <- gsub(paste0("^", nms[3], "."), "", colnames(out))
}
if (inherits(txtfun, "character") && (txtfun == "sum")) {
out[is.na(out)] <- 0
}
}
} else if (nz == 1){
nls <- as.character(1:nlyr(x))
colnames(out)[-1] <- nls
if (colnames(out)[1] == "layer") colnames(out)[1] <- "zone"
out <- stats::reshape(out, direction="long", varying=nls, timevar="layer",v.names="value")
out <- out[, c(2,1,3)]
rownames(out) <- NULL
}
out
}
)
setMethod("zonal", signature(x="SpatRaster", z="SpatVector"),
function(x, z, fun="mean", na.rm=FALSE, w=NULL, weights=FALSE, exact=FALSE, touches=FALSE, small=TRUE, as.raster=FALSE, as.polygons=FALSE, wide=TRUE, filename="", wopt=list()) {
opt <- spatOptions()
txtfun <- .makeTextFun(fun)
if (!inherits(txtfun, "character")) {
error("zonal", "this 'fun' is not supported. You can use extract instead")
} else {
if (txtfun == "table") {
if (!is.null(w)) {
error("cannot use 'w' when 'fun=table'")
}
v <- x@pntr$zonal_poly_table(z@pntr, weights[1], exact[1], touches[1], small[1], na.rm, opt)
messages(x, "zonal")
v <- lapply(v, function(i) if (length(i) == 0) NA else i)
v <- lapply(1:length(v), function(i) cbind(i, matrix(v[[i]], ncol=2)))
v <- do.call(rbind, v)
v <- as.data.frame(v)
colnames(v) <- c("zone", "value", "count")
ff <- is.factor(x)[1]
if (ff) {
cg <- cats(x)[[1]]
i <- match(v$value, cg[,1])
act <- activeCat(x, 1) + 1
v$value <- cg[i, act]
}
if (as.polygons | wide) {
nms <- names(v)
v <- stats::reshape(v, direction="wide", idvar=nms[1], timevar=nms[2])
names(v) <- gsub("count.", "", names(v))
v[is.na(v)] <- 0
rownames(v) <- NULL
}
if (as.polygons) {
values(z) <- v
return(z)
}
return(v)
} else {
if (is.null(w)) {
out <- x@pntr$zonal_poly(z@pntr, txtfun, weights[1], exact[1], touches[1], small[1], na.rm, opt)
} else {
if (txtfun != "mean") {
error("zonal", "fun must be 'mean' when using weights")
}
out <- x@pntr$zonal_poly_weighted(z@pntr, w@pntr, weights[1], exact[1], touches[1], small[1], na.rm, opt)
}
messages(out, "zonal")
out <- .getSpatDF(out)
}
}
if (as.raster) {
if (is.null(wopt$names)) {
wopt$names <- names(x)
}
x <- rasterize(z, x, 1:nrow(z))
subst(x, 1:nrow(out), out, filename=filename, wopt=wopt)
} else if (as.polygons) {
cbind(z, out)
} else {
out
}
}
)
setMethod("zonal", signature(x="SpatVector", z="SpatVector"),
function(x, z, fun=mean, ..., weighted=FALSE, as.polygons=FALSE) {
if (geomtype(z) != "polygons") {
error("zonal", "x must be points, and z must be polygons")
}
if (nrow(x) == 0) {
error("zonal", "x is empty")
}
isn <- which(sapply(values(x[1,]), is.numeric))
if (!any(isn)) {
error("zonal", "x has no numeric variables (attributes) to aggregate")
}
x <- x[,isn]
if (geomtype(x) == "points") {
r <- !relate(x, z, "disjoint", pairs=FALSE)
i <- apply(r, 1, function(i) if(any(i)) which(i) else (NA))
if (length(i) == 0) {
error("zonal", "there are no points in x that overlap with the polygons in z")
}
a <- aggregate(values(x), data.frame(zone=i), fun, ...)
} else {
if (as.polygons) {
zz <- z
values(zz) <- data.frame(zone = 1:nrow(zz))
i <- intersect(zz, x)
} else {
values(z) <- data.frame(zone = 1:nrow(z))
i <- intersect(z, x)
}
if (nrow(i) == 0) {
error("zonal", "the intersection of x and z is empty")
}
v <- values(i)
if (weighted) {
if (geomtype(i) == "lines") {
v$w <- perim(i)
} else {
v$w <- expanse(i)
}
s <- split(v, v$zone)
n <- ncol(v)-2
s <- lapply(s, function(d) {
out <- rep(NA, n)
for (i in 2:n) {
out[i-1] <- weighted.mean(d[[i]], w = d$w)
}
out
})
a <- data.frame(as.integer(names(s)), do.call(rbind, s))
colnames(a) <- names(v)[-ncol(v)]
} else {
a <- aggregate(v[,-1,drop=FALSE], v[,1,drop=FALSE], fun, ...)
}
}
if (as.polygons) {
f <- basename(tempfile())
z[[f]] <- 1:nrow(z)
names(a)[1] = f
a <- merge(z, a, by=f, all.x=TRUE)
a[[f]] <- NULL
}
a
}
)
setMethod("global", signature(x="SpatRaster"),
function(x, fun="mean", weights=NULL, maxcell=Inf, ...) {
nms <- names(x)
nms <- make.unique(nms)
txtfun <- .makeTextFun(fun)
opt <- spatOptions()
if (!is.null(weights)) {
stopifnot(inherits(weights, "SpatRaster"))
stopifnot(txtfun %in% c("mean", "sum"))
na.rm <- isTRUE(list(...)$na.rm)
tptr <- x@pntr$global_weighted_mean(weights@pntr, txtfun, na.rm, opt)
messages(tptr, "global")
res <- .getSpatDF(tptr)
rownames(res) <- nms
return(res)
}
if (inherits(txtfun, "character")) {
if (any(is.na(txtfun))) error("global", "fun cannot be NA")
if (any(txtfun %in% c("anynotNA", "anyNA"))) {
if (length(txtfun) > 1) error("global", "'anynotNA' and 'anyNA' can not be combined with other functions'")
tptr <- x@pntr$globalTF(txtfun, opt)
messages(tptr, "global")
res <- .getSpatDF(tptr)
rownames(res) <- nms
return(res)
}
if (all(txtfun %in% c("prod", "max", "min", "mean", "sum", "range", "rms", "sd", "std", "sdpop", "notNA", "isNA"))) {
txtfun[txtfun == "sdpop"] <- "std"
i <- grep("range", txtfun)
if (length(i) > 0) {
txtfun <- txtfun[-i]
txtfun <- c(txtfun, "min", "max")
}
txtfun <- unique(txtfun)
na.rm <- isTRUE(list(...)$na.rm)
#if (isTRUE(list(...)$old)) {
# ptr <- x@pntr$global(txtfun, na.rm, opt)
#} else {
tptr <- x@pntr$mglobal(txtfun, na.rm, opt)
#}
messages(tptr, "global")
res <- .getSpatDF(tptr)
rownames(res) <- nms
return(res)
}
}
nl <- nlyr(x)
res <- list()
if (is.finite(maxcell)) {
maxcell <- round(maxcell)
if (maxcell < 1) error("global", "maxcell should be positive")
x <- spatSample(x, maxcell, "regular", as.raster=TRUE)
}
for (i in 1:nl) {
res[[i]] <- fun(values(x[[i]]), ...)
}
res <- do.call(rbind, res)
res <- data.frame(res)
# more efficient but more risky:
#apply(data.frame(x), 2, fun, ...)
if ((ncol(res) == 1) && (colnames(res) == "res")) {
colnames(res) <- "global"
}
rownames(res) <- nms
res
}
)
setMethod("freq", signature(x="SpatRaster"),
function(x, digits=0, value=NULL, bylayer=TRUE, usenames=FALSE, zones=NULL, wide=FALSE) {
if (!is.null(zones)) {
vna <- (!is.null(value) && is.na(value[1]))
# if (vna) levels(x) <- NULL
if (inherits(zones, "SpatVector")) {
out <- vector("list", nrow(zones))
for (i in 1:nrow(zones)) {
z <- zones[i,]
e <- align(ext(z), x, snap="near")
if (!is.null(intersect(e, ext(x)))) {
r <- crop(x, zones[i,], mask=TRUE, touches=FALSE)
if (vna) {
ra <- rasterize(zones[i,], r, NA, background=0, touches=FALSE)
r <- cover(ra, r)
}
out[[i]] <- freq(r, digits=digits, value=value, bylayer=bylayer, usenames=usenames, zones=NULL)
out[[i]]$zone <- i
}
}
} else if (inherits(zones, "SpatRaster")) {
compareGeom(x, zones, crs=FALSE)
if (nlyr(zones) > 1) zones <- zones[[1]]
u <- unlist(unique(zones))
out <- vector("list", length(u))
for (i in 1:length(u)) {
r <- mask(x, zones, maskvalues=u[i], inverse=TRUE)
out[[i]] <- freq(r, digits=digits, value=value, bylayer=bylayer, usenames=usenames, zones=NULL, wide=FALSE)
out[[i]]$zone <- i
}
} else {
error("freq", "zones must be a SpatVector or a SpatRaster")
}
out <- do.call(rbind, out)
if (is.null(out)) return(out)
out <- out[!is.na(out$count), ]
if (nrow(out) == 0) return(out)
out <- out[order(out$layer), ]
if (wide) {
out$count[is.na(out$count)] <- 0
if (vna) {
out$value <- "NA"
}
out <- stats::reshape(out, idvar=c("layer", "zone"), timevar="value", direction="wide")
colnames(out) <- gsub("count.", "", colnames(out))
out[is.na(out)] <- 0
}
return(out)
}
opt <- spatOptions()
if (!bylayer) usenames <- FALSE
if (!is.null(value)) {
value <- unique(value)
if (length(value) > 1) {
error("freq", "value must have a length of one")
}
if (is.character(value)) {
value <- value[value != ""]
if (length(value) == 0) {
error("freq", "no valid value")
}
ff <- is.factor(x)
if (!any(ff)) {
error("freq", "a character value is only meaningful for categorical rasters")
}
f <- freq(x[[ff]])
if (usenames) {
f$layer <- names(x)[f$layer]
}
f <- f[f$label == value,]
return(f)
}
if (is.na(digits)) {
v <- x@pntr$count(value, bylayer[1], FALSE, 0, opt)
} else {
v <- x@pntr$count(value, bylayer[1], TRUE, digits, opt)
value <- round(value, digits)
}
if (bylayer) {
v <- data.frame(layer=1:nlyr(x), value=value, count=v)
} else {
v <- data.frame(value=value, count=v)
}
} else {
if (is.na(digits)) {
v <- x@pntr$freq(bylayer[1], FALSE, 0, opt)
} else {
v <- x@pntr$freq(bylayer[1], TRUE, digits, opt)
}
v <- lapply(v, function(i) if (length(i) == 0) NA else i)
v <- lapply(1:length(v), function(i) cbind(i, matrix(v[[i]], ncol=2)))
v <- do.call(rbind, v)
v <- as.data.frame(v)
colnames(v) <- c("layer", "value", "count")
ff <- is.factor(x)
if (any(ff)) {
cgs <- cats(x)
v <- data.frame(v)
for (f in which(ff)) {
cg <- cgs[[f]]
j <- which(v[,1] == f)
i <- match(v[j,2], cg[,1])
act <- activeCat(x, f) + 1
if (!inherits(cg[[act]], "numeric")) {
v[j, 2] <- as.character(factor(cg[i, act], levels=unique(cg[[act]])))
} else {
v[j, 2] <- cg[i, act]
}
}
}
if (!bylayer) {
# if (nlyr(x) > 1)
# v <- aggregate(v[,"count",drop=FALSE], v[,"value", drop=FALSE], sum)
# }
v <- v[,-1]
}
}
if (usenames) {
v$layer <- names(x)[v$layer]
}
if (wide) {
v$count[is.na(v$count)] <- 0
if ((!is.null(value)) && is.na(value)) {
v$value <- "NA"
}
v <- stats::reshape(v, idvar="layer", timevar="value", direction="wide")
colnames(v) <- gsub("count.", "", colnames(v))
v[is.na(v)] <- 0
}
v
}
)
setMethod ("expanse", "SpatRaster",
function(x, unit="m", transform=TRUE, byValue=FALSE, zones=NULL, wide=FALSE, usenames=FALSE) {
opt <- spatOptions()
if (!is.null(zones)) {
if (!inherits(zones, "SpatRaster")) {
error("expanse", "zones must be a SpatRaster")
}
compareGeom(x, zones, lyrs=FALSE, crs=FALSE, ext=TRUE, rowcol=TRUE)
v <- x@pntr$sum_area_group(zones@pntr, unit[1], transform[1], byValue[1], opt)
messages(x)
v <- lapply(v, function(i) matrix(i, ncol=4, byrow=TRUE))
v <- data.frame(do.call(rbind, v))
colnames(v) <- c("layer", "value", "zone", "area")
v[,1] <- v[,1] + 1
if (byValue) {
v <- replace_with_label(x, v, 2)
v <- replace_with_label(zones, v, 3)
} else {
v <- replace_with_label(zones, v, 3)
v$value <- NULL
}
if (wide) {
if (byValue) {
v <- stats::reshape(v, idvar=c("layer", "zone"), timevar="value", direction="wide")
colnames(v) <- gsub("area.", "", colnames(v))
} else {
v <- stats::reshape(v, idvar=c("layer"), timevar="zone", direction="wide")
colnames(v) <- gsub("area.", "", colnames(v))
}
v[is.na(v)] <- 0
}
} else {
v <- x@pntr$sum_area(unit, isTRUE(transform[1]), isTRUE(byValue[1]), opt)
x <- messages(x, "expanse")
if (byValue) {
v <- lapply(1:length(v), function(i) cbind(i, matrix(v[[i]], ncol=2, byrow=TRUE)))
v <- data.frame(do.call(rbind, v))
colnames(v) <- c("layer", "value", "area")
v <- replace_with_label(x, v, 2)
} else {
v <- v[[1]]
v <- data.frame(layer=1:length(v), area=v)
}
if (wide) {
if (byValue) {
v <- stats::reshape(v, idvar="layer", timevar="value", direction="wide")
colnames(v) <- gsub("area.", "", colnames(v))
}
v[is.na(v)] <- 0
}
}
if (usenames) {
v$layer <- names(x)[v$layer]
}
v
}
)
terra/R/gcp.R 0000644 0001762 0000144 00000001470 14536376240 012500 0 ustar ligges users
setClass("GCP",
representation (
gcp = "matrix"
),
prototype (
gcp = cbind(fx=0, fy=0, tx=0, ty=0)[0,]
)
)
setMethod("show", signature(object="GCP"),
function(object) {
m <- object@gcp
show(m)
if (!is.null(grDevices::dev.list())) {
for (i in 1:nrow(m)) {
graphics::arrows(m[i,1], m[i,2], x1 = m[i,3], y1 = m[i,4], col="red", length = 0.1)
}
}
}
)
#setMethod("add<-", signature(x="GCP"),
# function(x, value) {
# if (missing(value)) {
# value <- terra:::RS_locator(2, "l")
# value <- rbind(as.vector(t(value)))
# }
# if (ncol(value) == 4) {
# x@gcp <- rbind(x@gcp, value)
# }
# if (!is.null(grDevices::dev.list())) {
# graphics::arrows(value[1,1], value[1,2], x1 = value[1,3], y1 = value[1,4], col="red", length = 0.1)
# }
# x
# }
#)
#gcp <- new("GCP")
#gcp <- addGCP(gcp)
terra/R/ncdf.R 0000644 0001762 0000144 00000041002 14733173375 012637 0 ustar ligges users
.ncdf_extent <- function(x, f) {
if (!("ncdf4" %in% rownames(utils::installed.packages()))) {
warn("rast", "GDAL did not find an extent. installing the ncdf4 package may help")
return(x)
}
fname <- f
zvar <- varnames(x)[1]
dims <- 1:3
nc <- ncdf4::nc_open(fname, readunlim=FALSE, suppress_dimvals = TRUE)
on.exit( ncdf4::nc_close(nc) )
ncols <- nc$var[[zvar]]$dim[[dims[1]]]$len
nrows <- nc$var[[zvar]]$dim[[dims[2]]]$len
if (!(ncol(x) == ncols) & (nrow(x) == nrows)) {
warn("rast", "GDAL did not find an extent. Cells not equally spaced?")
return(x)
}
xx <- try(ncdf4::ncvar_get(nc, nc$var[[zvar]]$dim[[dims[1]]]$name), silent = TRUE)
if (inherits(xx, "try-error")) {
xx <- seq_len(nc$var[[zvar]]$dim[[dims[1]]]$len)
}
rs <- xx[-length(xx)] - xx[-1]
if (! isTRUE ( all.equal( min(rs), max(rs), tolerance=0.025, scale= abs(min(rs))) ) ) {
warn("rast", "cells are not equally spaced; extent is not defined")
return(x)
}
xrange <- c(min(xx), max(xx))
resx <- (xrange[2] - xrange[1]) / (ncols-1)
yy <- try(ncdf4::ncvar_get(nc, nc$var[[zvar]]$dim[[dims[2]]]$name), silent = TRUE)
if (inherits(yy, "try-error")) {
yy <- seq_len(nc$var[[zvar]]$dim[[dims[2]]]$len)
}
rs <- yy[-length(yy)] - yy[-1]
if (! isTRUE ( all.equal( min(rs), max(rs), tolerance=0.025, scale= abs(min(rs))) ) ) {
warn("rast", "cells are not equally spaced; extent is not defined")
return(x)
}
yrange <- c(min(yy), max(yy))
resy <- (yrange[2] - yrange[1]) / (nrows-1)
xrange[1] <- xrange[1] - 0.5 * resx
xrange[2] <- xrange[2] + 0.5 * resx
yrange[1] <- yrange[1] - 0.5 * resy
yrange[2] <- yrange[2] + 0.5 * resy
ext(x) <- ext(xrange[1], xrange[2], yrange[1], yrange[2])
return(x)
}
write_tags <- function(tags, nc, varid, prefix="TAG_") {
if (length(tags) > 0) {
nms <- paste0(prefix, names(tags))
for(i in 1:length(nms)) {
ncdf4::ncatt_put(nc, varid, nms[i], tags[i], prec="text")
}
}
}
.write_cdf <- function(x, filename, overwrite=FALSE, zname="time", atts="", gridmap="", prec="float", compression=NA, missval, force_v4=TRUE, verbose=FALSE, ...) {
n <- length(x)
y <- x[1]
if (is.lonlat(y, perhaps=TRUE, warn=FALSE)) {
xname = "longitude"
yname = "latitude"
xunit = "degrees_east"
yunit = "degrees_north"
} else {
xname = "easting"
yname = "northing"
xunit = "meter" # probably
yunit = "meter" # probably
}
xdim <- ncdf4::ncdim_def( xname, xunit, xFromCol(y, 1:ncol(y)) )
ydim <- ncdf4::ncdim_def( yname, yunit, yFromRow(y, 1:nrow(y)) )
vars <- varnames(x)
vars[vars == ""] <- paste0("var_", (1:n)[vars == ""])
vars <- make.unique(vars)
lvar <- longnames(x)
units <- units(x)
zname <- rep_len(zname, n)
valid_prec <- c("short", "integer", "float", "double", "byte")
if (!all(prec %in% valid_prec)) {
error("writeCDF", paste("prec must be one of:", paste(valid_prec, collapse=", ")))
}
prec <- rep_len(prec, n)
if (missing(missval)) {
miss_vals <- c(-32768, -2147483647, -1.175494e38, -1.7976931348623157e308, 255)
missval <- miss_vals[match(prec, valid_prec)]
} else {
missval <- rep_len(missval, n)
}
compression <- compression[1]
nc <- ncol(x)
nr <- nrow(x)
nl <- nlyr(x)
ncvars <- list()
cal <- NA
for (i in 1:n) {
if ((nl[i] > 1) || (x[i]@pntr$hasTime)) {
y <- x[i]
if (y@pntr$hasTime) {
zv <- y@pntr$time
tstep <- y@pntr$timestep
cal <- "standard"
if (tstep == "seconds") {
zunit <- "seconds since 1970-1-1 00:00:00"
} else if (tstep == "days") {
zunit <- "days since 1970-1-1"
zv <- zv / (24 * 3600)
} else if (tstep == "months") {
zunit <- "months"
zv <- time(y)
} else if (tstep == "yearmonths") {
zunit <- "months since 1970"
tm <- time(y) - 1970
yr <- tm %/% 1
zv <- (yr*12) + round(12 * (tm %% 1))
} else if (tstep == "years") {
zunit <- "years since 1970"
zv <- time(y) - 1970
} else {
zunit <- "unknown"
}
} else {
zv <- 1:nlyr(y)
zunit <- "unknown"
}
zdim <- ncdf4::ncdim_def(zname[i], zunit, zv, unlim=FALSE, create_dimvar=TRUE, calendar=cal)
ncvars[[i]] <- ncdf4::ncvar_def(vars[i], units[i], list(xdim, ydim, zdim), missval[i], lvar[i], prec = prec[i], compression=compression,...)
} else {
ncvars[[i]] <- ncdf4::ncvar_def(name=vars[i], units=units[i], dim=list(xdim, ydim), missval=missval[i], longname=lvar[i], prec = prec[i], compression=compression, ...)
}
}
ncvars[[n+1]] <- ncdf4::ncvar_def("crs", "", list(), NULL, prec="integer")
ncobj <- ncdf4::nc_create(filename, ncvars, force_v4=force_v4, verbose=verbose)
on.exit(ncdf4::nc_close(ncobj))
haveprj <- FALSE
prj <- crs(x[1])
prj <- gsub("\n", "", prj)
if (prj != "") {
haveprj <- TRUE
ncdf4::ncatt_put(ncobj, ncvars[[n+1]], "crs_wkt", prj, prec="text")
# need for older gdal?
ncdf4::ncatt_put(ncobj, ncvars[[n+1]], "spatial_ref", prj, prec="text")
prj <- .proj4(x[1])
if (prj != "") {
ncdf4::ncatt_put(ncobj, ncvars[[n+1]], "proj4", prj, prec="text")
}
prj <- crs(x[1], describe=TRUE)[1,2:3]
if (!any(is.na(prj))) {
prj <- paste0(prj, collapse=":")
ncdf4::ncatt_put(ncobj, ncvars[[n+1]], "code", prj, prec="text")
}
}
gridmap <- grep("=", gridmap, value=TRUE)
if (length(gridmap)>0) {
gridmap <- strsplit(gridmap, "=")
for (i in 1:length(gridmap)) {
ncdf4::ncatt_put(ncobj, ncvars[[n+1]], gridmap[[i]][1], gridmap[[i]][2], prec="text")
}
haveprj <- TRUE
}
e <- ext(x)
rs <- res(x)
gt <- paste(trimws(formatC(as.vector(c(e$xmin, rs[1], 0, e$ymax, 0, -1 * rs[2])), 22)), collapse=" ")
ncdf4::ncatt_put(ncobj, ncvars[[n+1]], "geotransform", gt, prec="text")
opt <- spatOptions()
bsteps <- blocks(rast(x[[1]], nlyr=sum(nlyr(x))), 4)
if (bsteps$n > opt$progress) {
progress <- TRUE
pb <- utils::txtProgressBar(0, bsteps$n)
pcnt <- 0
} else {
progress <- FALSE
}
for (i in 1:n) {
y <- x[i]
b <- blocks(y, 8)
readStart(y)
if (length(ncvars[[i]]$dim) == 3) {
for (j in 1:b$n) {
if (progress) { utils::setTxtProgressBar(pb, pcnt); pcnt <- pcnt + 1 }
d <- readValues(y, b$row[j], b$nrows[j], 1, nc, FALSE, FALSE)
d[is.nan(d)] <- NA
d <- array(d, c(nc, b$nrows[j], nl[i]))
ncdf4::ncvar_put(ncobj, ncvars[[i]], d, start=c(1, b$row[j], 1), count=c(nc, b$nrows[j], nl[i]))
}
} else {
for (j in 1:b$n) {
if (progress) { utils::setTxtProgressBar(pb, pcnt); pcnt <- pcnt + 1 }
d <- readValues(y, b$row[j], b$nrows[j], 1, nc, FALSE, FALSE)
d[is.nan(d)] <- NA
d <- matrix(d, ncol=b$nrows[j])
ncdf4::ncvar_put(ncobj, ncvars[[i]], d, start=c(1, b$row[j]), count=c(nc, b$nrows[j]))
}
}
readStop(y)
if (haveprj) {
ncdf4::ncatt_put(ncobj, ncvars[[i]], "grid_mapping", "crs", prec="text")
}
write_tags(metags(y), ncobj, ncvars[[i]], "")
}
if (progress) close(pb)
ncdf4::ncatt_put(ncobj, 0, "Conventions", "CF-1.4", prec="text")
pkgversion <- drop(read.dcf(file=system.file("DESCRIPTION", package="terra"), fields=c("Version")))
ncdf4::ncatt_put(ncobj, 0, "created_by", paste("R packages ncdf4 and terra (version ", pkgversion, ")", sep=""), prec="text")
ncdf4::ncatt_put(ncobj, 0, "created_date", format(Sys.time(), "%Y-%m-%d %H:%M:%S"), prec="text")
write_tags(metags(x), ncobj, 0, "")
atts <- grep("=", atts, value=TRUE)
if (length(atts) > 0) {
atts <- strsplit(atts, "=")
for (i in 1:length(atts)) {
ncdf4::ncatt_put(ncobj, 0, atts[[i]][1], atts[[i]][2], prec="text")
}
}
TRUE
}
setMethod("writeCDF", signature(x="SpatRaster"),
function(x, filename, varname, longname="", unit="", split=FALSE, ...) {
filename <- trimws(filename)
if (length(filename) > 1) {
if (length(filename) != nlyr(x)) {
stop("either provide a single filename, or the same number as nlyr(x)")
}
}
stopifnot(filename != "")
if (split) {
y <- sds(as.list(x))
names(y) <- names(x)
if (!missing(varname)) {
varnames(y) <- varname
}
if (!missing(longname)) {
longnames(y) <- longname
}
if (!missing(unit)) {
units(y) <- unit
} else {
units(y) <- units(x)
}
invisible( writeCDF(y, filename=filename, ...) )
} else {
if (missing(varname)) {
varname <- tools::file_path_sans_ext(basename(filename))
}
varnames(x) <- varname
longnames(x) <- longname
units(x) <- unit
x <- sds(x)
invisible( writeCDF(x, filename=filename, ...) )
}
}
)
setMethod("writeCDF", signature(x="SpatRasterDataset"),
function(x, filename, overwrite=FALSE, zname="time", atts="", gridmap="", prec="float", compression=NA, missval, ...) {
filename <- trimws(filename)
stopifnot(filename != "")
xt <- tools::file_ext(filename)
if (any(!(xt %in% c("nc", "cdf")))) {
warn("writeCDF", "for better results use file extension '.nc' or '.cdf'\nsee: https://stackoverflow.com/a/65398262/635245")
}
if (file.exists(filename) & !overwrite) {
error("writeCDF", "file exists, use 'overwrite=TRUE' to overwrite it")
}
ok <- .write_cdf(x, filename, zname=zname, atts=atts, gridmap=gridmap, prec=prec, compression=compression, missval=missval, ...)
if (ok) {
if (length(x) > 1) {
out <- sds(filename)
} else {
out <- rast(filename)
}
invisible(out)
} else {
error("writeCDF", "?")
}
}
)
.varName <- function(nc, varname="", warn=TRUE) {
n <- nc$nvars
dims <- vars <- vector(length=n)
if (n > 0) {
for (i in 1:n) {
vars[i] <- nc$var[[i]]$name
dims[i] <- nc$var[[i]]$ndims
}
vars <- vars[dims > 1]
dims <- dims[dims > 1]
}
if (varname=='') {
nv <- length(vars)
if (nv == 0) {
return('z')
}
if (nv == 1) {
varname <- vars
} else {
varname <- vars[which.max(dims)]
if (warn) {
if (sum(dims == max(dims)) > 1) {
vars <- vars[dims==max(dims)]
warning('varname used is: ', varname, '\nIf that is not correct, you can set it to one of: ', paste(vars, collapse=", ") )
}
}
}
}
zvar <- which(varname == vars)
if (length(zvar) == 0) {
stop('varname: ', varname, ' does not exist in the file. Select one from:\n', paste(vars, collapse=", ") )
}
return(varname)
}
.getCRSfromGridMap4 <- function(g) {
if (!is.null(g$epsg_code)) {
crs <- g$epsg_code
if (!grep("EPSG:", crs, ignore.case=TRUE)) {
crs <- paste0("epsg:", crs)
}
return(crs)
}
sp <- g$standard_parallel
if (length(sp) > 1) {
g$standard_parallel1 <- sp[1]
g$standard_parallel2 <- sp[2]
g$standard_parallel <- NULL
}
vals <- sapply(g, function(i) i[1])
vars <- names(vals)
if (any(vars %in% c("proj4", "crs_wkt", "spatial_ref"))) {
crs=vals[vars %in% c("proj4", "crs_wkt", "spatial_ref")][1]
return(crs)
}
# based on info at
# http://trac.osgeo.org/gdal/wiki/NetCDF_ProjectionTestingStatus
# accessed 7 October 2012
prj <- matrix(c("albers_conical_equal_area", "aea", "azimuthal_equidistant", "aeqd", "lambert_cylindrical_equal_area", "cea", "lambert_azimuthal_equal_area", "laea", "lambert_conformal_conic", "lcc", "latitude_longitude", "longlat", "mercator", "merc", "orthographic", "ortho", "polar_stereographic", "stere", "stereographic", "stere", "transverse_mercator", "tmerc"), ncol=2, byrow=TRUE)
m <- matrix(c("grid_mapping_name", "+proj", "false_easting", "+x_0","false_northing", "+y_0", "scale_factor_at_projection_origin", "+k_0", "scale_factor_at_central_meridian", "+k_0", "standard_parallel", "+lat_1", "standard_parallel1", "+lat_1", "standard_parallel2", "+lat_2", "longitude_of_central_meridian", "+lon_0", "longitude_of_projection_origin", "+lon_0", "latitude_of_projection_origin", "+lat_0", "straight_vertical_longitude_from_pole", "+lon_0",
"longitude_of_prime_meridian", "+pm", "semi_major_axis", "+a", "semi_minor_axis", "+b", "inverse_flattening", "+rf",
"earth_radius", "+a"), ncol=2, byrow=TRUE)
# add logic that if prime merid is defined but not centr merid. centr merid is same as prime.
i <- match(vars, m[,1])
if (all(is.na(i))) {
gg <- cbind(vars, vals)
mtxt <- paste(apply(gg, 1, function(x) paste(x, collapse='=')), collapse='; ')
warning("cannot process the crs\n", mtxt)
return(NA)
} else if (any(is.na(i))) {
vr <- vars[is.na(i)]
vl <- vals[is.na(i)]
gg <- cbind(vr, vl)
gg <- gg[!(gg[,1] %in% c("crs_wkt", "esri_pe_string")), ,drop=FALSE]
if (NROW(gg) > 0) {
mtxt <- paste(apply(gg, 1, function(x) paste(x, collapse='=')), collapse='\n')
warning("cannot process these parts of the crs:\n", mtxt)
}
vars <- vars[!is.na(i)]
vals <- vals[!is.na(i)]
i <- stats::na.omit(i)
}
tab <- cbind(m[i,], vals)
rr <- which(tab[,1] == "earth_radius")
if (length(rr) > 0) {
bb <- tab[rr,]
bb[2] <- "+b"
tab <- rbind(tab, bb)
}
p <- which(tab[,2] == '+proj')
if (length(p) == 0) {
warning("cannot create a valid crs\n", mtxt)
return(NA)
} else {
tab <- rbind(tab[p, ], tab[-p, ])
}
j <- match(tab[1,3], prj[,1])
tab[1,3] <- prj[j,2]
cr <- paste(apply(tab[,2:3], 1, function(x) paste(x, collapse='=')), collapse=' ')
crtst <- try(rast(crs=cr), silent=TRUE)
if ( inherits(crtst, "try-error")) {
mtxt <- paste(m, collapse='; ')
warning("cannot create a valid crs\n", mtxt)
return(NA)
} else {
return(cr)
}
}
.ncdfTime <- function(nc, zvar, dim3, zval) {
dodays <- TRUE
dohours <- FALSE
doseconds <- FALSE
un <- nc$var[[zvar]]$dim[[dim3]]$units
if (substr(un, 1, 10) == "days since") {
startDate = as.Date(substr(un, 12, 22))
} else if (substr(un, 1, 11) == "hours since") {
dohours <- TRUE
dodays <- FALSE
startTime <- substr(un, 13, 30)
mult <- 3600
} else if (substr(un, 1, 13) == "seconds since") {
doseconds <- TRUE
dodays <- FALSE
startTime = as.Date(substr(un, 15, 31))
mult <- 1
} else if (substr(un, 1, 12) == "seconds from") {
doseconds <- TRUE
dodays <- FALSE
startTime = as.Date(substr(un, 14, 31))
mult <- 1
} else {
return(NULL)
}
if (!dodays) {
start <- strptime(startTime, "%Y-%m-%d %H:%M:%OS", tz = "UTC")
if (is.na(start)) start <- strptime(startTime, "%Y-%m-%d", tz = "UTC")
if (is.na(start)) return(x)
startTime <- start
time <- startTime + as.numeric(zval) * mult
time <- as.character(time)
if (!is.na(time[1])) {
return(time)
}
} else if (dodays) {
# cal = nc$var[[zvar]]$dim[[dim3]]$calendar ?
cal <- ncdf4::ncatt_get(nc, "time", "calendar")
if (! cal$hasatt ) {
greg <- TRUE
} else {
cal <- cal$value
if (cal =='gregorian' | cal =='proleptic_gregorian' | cal=='standard') {
greg <- TRUE
} else if (cal == 'noleap' | cal == '365 day' | cal == '365_day') {
greg <- FALSE
nday <- 365
} else if (cal == '360_day') {
greg <- FALSE
nday <- 360
} else {
greg <- TRUE
warning('assuming a standard calender:', cal)
}
}
if (greg) {
time <- as.Date(time, origin=startDate)
} else {
startyear <- as.numeric( format(startDate, "%Y") )
startmonth <- as.numeric( format(startDate, "%m") )
startday <- as.numeric( format(startDate, "%d") )
year <- trunc( as.numeric(time)/nday )
doy <- (time - (year * nday))
origin <- paste(year+startyear, "-", startmonth, "-", startday, sep='')
time <- as.Date(doy, origin=origin)
}
return(time)
}
return(NULL)
}
pointsCDF <- function(filename, varname, polygons=FALSE) {
if (!("ncdf4" %in% rownames(utils::installed.packages()))) {
warn("rast", "GDAL did not find an extent. installing the ncdf4 package may help")
return(x)
}
zvar <- .varName(nc, varname, warn=TRUE)
nc <- ncdf4::nc_open(filename, readunlim=FALSE, suppress_dimvals = TRUE)
on.exit( ncdf4::nc_close(nc) )
dims <- 1:3
ncols <- nc$var[[zvar]]$dim[[dims[1]]]$len
nrows <- nc$var[[zvar]]$dim[[dims[2]]]$len
xx <- try(ncdf4::ncvar_get(nc, nc$var[[zvar]]$dim[[dims[1]]]$name), silent = TRUE)
if (inherits(xx, "try-error")) {
error("pointsCDF", "no x coordinates found")
}
yy <- try(ncdf4::ncvar_get(nc, nc$var[[zvar]]$dim[[dims[2]]]$name), silent = TRUE)
if (inherits(yy, "try-error")) {
error("pointsCDF", "no x coordinates found")
}
a <- ncdf4::ncatt_get(nc, zvar, "grid_mapping")
prj <- NA
if ( a$hasatt ) {
try(atts <- ncdf4::ncatt_get(nc, a$value), silent=TRUE)
try(prj <- .getCRSfromGridMap4(atts), silent=TRUE)
}
dim3 <- dims[3]
dim3_vals <- try(ncdf4::ncvar_get(nc, nc$var[[zvar]]$dim[[dim3]]$name), silent = TRUE)
if (inherits(dim3_vals, "try-error")) {
dim3_vals <- seq_len(nc$var[[zvar]]$dim[[dim3]]$len)
}
nms <- NULL
if ( nc$var[[zvar]]$dim[[dim3]]$name == "time" ) {
try( nms <- .ncdfTime(nc, zvar, dim3, dim3_vals) )
}
d <- ncdf4::ncvar_get( nc, varid=zvar)
nl <- dim(d)[3]
v <- sapply(1:nl, function(i) d[,,i])
natest1 <- ncdf4::ncatt_get(nc, zvar, "_FillValue")
natest2 <- ncdf4::ncatt_get(nc, zvar, "missing_value")
if (natest1$hasatt) {
v[v==natest1$value] <- NA
} else if (natest2$hasatt) {
v[v==natest2$value] <- NA
}
if (!is.null(nms)) {
colnames(v) <- nms
}
vect(cbind(rep(xx, length(yy)), rep(yy, each=length(xx))), atts=v, crs=prj)
}
terra/R/approximate.R 0000644 0001762 0000144 00000003617 14536376240 014265 0 ustar ligges users # Author: Robert J. Hijmans
# Date : February 2012
# Version 1.0
# Licence GPL v3
setMethod("approximate", signature(x="SpatRaster"),
function(x, method="linear", yleft, yright, rule=1, f=0, ties=mean, z=NULL, NArule=1, filename="", ...) {
out <- rast(x, keeptime=TRUE)
nl <- nlyr(out)
if (nl < 2) {
warning('cannot interpolate with a single layer')
return(x)
}
if (is.null(z)) {
xout <- time(x)
if (any(is.na(xout))) {
xout <- 1:nl
}
} else {
if (length(z)!= nl) {
error("approximate", "length of z does not match nlyr(x)")
}
xout <- z
}
ifelse((missing(yleft) & missing(yright)), ylr <- 0L, ifelse(missing(yleft), ylr <- 1L, ifelse(missing(yright), ylr <- 2L, ylr <- 3L)))
nc <- ncol(out)
readStart(x)
on.exit(readStop(x))
b <- writeStart(out, filename, sources=sources(x), ...)
for (i in 1:b$n) {
v <- readValues(x, b$row[i], b$nrows[i], 1, nc, TRUE)
s <- .rowSums(is.na(v), nrow(v), nl)
if (isTRUE(NArule==1)) {
j <- s == (nl-1) # one non-NA only
if (length(j) > 0 ) {
v[j, ] <- apply(v[j,,drop=FALSE ], 1, max, na.rm=TRUE)
}
}
j <- (s < nl-1) # need at least two
if (length(j) > 0 ) {
if (ylr==0) {
v[j,] <- t( apply(v[j,,drop=FALSE], 1, function(x) stats::approx(x=xout, y=x, xout=xout, method=method, rule=rule, f=f, ties=ties)$y ) )
} else if (ylr==1) {
v[j,] <- t( apply(v[j,,drop=FALSE], 1, function(x) stats::approx(x=xout, y=x, xout=xout, method=method, yright=yright, rule=rule, f=f, ties=ties)$y ) )
} else if (ylr==2) {
v[j,] <- t( apply(v[j,,drop=FALSE], 1, function(x) stats::approx(x=xout, y=x, xout=xout, method=method, yleft=yleft, rule=rule, f=f, ties=ties)$y ) )
} else {
v[j,] <- t( apply(v[j,,drop=FALSE], 1, function(x) stats::approx(x=xout, y=x, xout=xout, method=method, yright=yright, yleft=yleft, rule=rule, f=f, ties=ties)$y ) )
}
}
writeValues(out, v, b$row[i], b$nrows[i])
}
writeStop(out)
}
)
terra/R/init.R 0000644 0001762 0000144 00000002076 14731063166 012672 0 ustar ligges users # Author: Robert J. Hijmans
# Date : May 2019
# Version 1.0
# License GPL v3
setMethod("init", signature(x="SpatRaster"),
function(x, fun, ..., filename="", wopt=list()) {
x <- rast(x)
if (is.character(fun)) {
opt <- spatOptions(filename, wopt=wopt)
x <- rast(x, 1)
fun <- fun[1]
if (fun %in% c("x", "y", "row", "col", "cell", "chess")) {
x@pntr <- x@pntr$initf(fun, TRUE, opt)
messages(x, "init")
} else if (is.na(fun)) {
x@pntr <- x@pntr$initv(as.numeric(NA), opt)
messages(x, "init")
} else {
error("init", "unknown function")
}
} else if (is.numeric(fun) || is.logical(fun)) {
opt <- spatOptions(filename, wopt=wopt)
x@pntr <- x@pntr$initv(fun, opt)
messages(x, "init")
} else {
nc <- ncol(x) * nlyr(x)
b <- writeStart(x, filename, sources=sources(x), wopt=wopt)
for (i in 1:b$n) {
n <- b$nrows[i] * nc;
r <- fun(n, ...)
if (length(r) != n) {
error("init","the number of values returned by 'fun' is not correct")
}
writeValues(x, r, b$row[i], b$nrows[i])
}
writeStop(x)
}
}
)
terra/R/SpatVectorCollection.R 0000644 0001762 0000144 00000006467 14726701421 016042 0 ustar ligges users
setMethod("length", signature(x="SpatVectorCollection"),
function(x) {
x@pntr$size()
}
)
setMethod("svc", signature(x="missing"),
function(x) {
v <- methods::new("SpatVectorCollection")
v@pntr <- SpatVectorCollection$new()
v
}
)
setMethod("svc", signature(x="character"),
function(x, layer="", query="", extent=NULL, filter=NULL) {
if (is.null(filter)) {
filter <- SpatVector$new()
} else {
filter <- filter@pntr
}
if (is.null(extent)) {
extent <- double()
} else {
extent <- as.vector(ext(extent))
}
v <- methods::new("SpatVectorCollection")
v@pntr <- SpatVectorCollection$new(x, layer, query, extent, filter)
v
}
)
setMethod("svc", signature(x="SpatVector"),
function(x, ...) {
r <- methods::new("SpatVectorCollection")
r@pntr <- SpatVectorCollection$new()
r@pntr$push_back(x@pntr)
dots <- list(...)
if (length(dots) > 0) {
for (i in 1:length(dots)) {
if (inherits(dots[[i]], "SpatVector")) {
r@pntr$push_back(dots[[i]]@pntr)
} else {
warn("svc", "cannot add objects of class: ", class(dots[[i]]))
}
}
}
messages(r, "svc")
}
)
setMethod("svc", signature(x="sf"),
function(x) {
.svc_from_sf(x)
}
)
setMethod("svc", signature(x="list"),
function(x) {
r <- methods::new("SpatVectorCollection")
r@pntr <- SpatVectorCollection$new()
for (i in seq_along(x)) {
if (inherits(x[[i]], "SpatVector")) {
r@pntr$push_back(x[[i]]@pntr)
}
}
r <- messages(r, "svc")
names(r) <- names(x)
r
}
)
setReplaceMethod("[", c("SpatVectorCollection", "numeric", "missing"),
function(x, i, j, value) {
stopifnot(inherits(value, "SpatVector"))
if (any(!is.finite(i)) || any(i<1)) {
error("`[<-`", "invalid index")
}
i <- sort(i)
for (j in i) {
if (j == (length(x)+1)) {
x@pntr$push_back(value@pntr)
} else {
x@pntr$replace(value@pntr, j-1)
}
}
messages(x, "`[<-`")
}
)
setMethod("[", c("SpatVectorCollection", "numeric", "missing"),
function(x, i, j, drop=TRUE) {
if (i < 0) {i <- (1:length(x))[i]}
if (drop && (length(i) == 1)) {
tptr <- x@pntr$get(i-1)
x <- methods::new("SpatVector")
x@pntr <- tptr
} else {
x@pntr <- x@pntr$subset(i-1)
}
messages(x, "`[`")
})
setMethod("[[", c("SpatVectorCollection", "ANY", "missing"),
function(x, i, j, drop=TRUE) {
if (inherits(i, "character")) {
i <- na.omit(match(i, names(x)))
if (length(i) == 0) {
error("[[", "no matching names")
}
}
x[i, drop=drop]
})
setMethod("$", c("SpatVectorCollection"),
function(x, name) {
i <- na.omit(grep(name, names(x)))
if (length(i) == 0) {
error("$", "no matching names")
}
x[i,drop=TRUE]
})
setMethod("[[", c("SpatVectorCollection", "numeric", "missing"),
function(x, i, j, drop=TRUE) {
x[i,drop=drop]
})
setMethod("c", signature(x="SpatVector"),
function(x, ...) {
svc(x, ...)
}
)
setMethod("c", signature(x="SpatVectorCollection"),
function(x, ...) {
x@pntr <- x@pntr$subset(0:(x@pntr$size()-1) ) ## deep copy
dots <- list(...)
for (i in seq_along(dots)) {
if (inherits(dots[[i]], "SpatVectorCollection")) {
for (j in 1:length(dots[[i]])) {
x@pntr$push_back(dots[[i]][[j]]@pntr)
}
} else if (inherits(dots[[i]], "SpatVector")) {
x@pntr$push_back(dots[[i]]@pntr)
} else {
error("c", "arguments must be SpatVector or SpatVectorCollection")
}
}
messages(x, "c")
}
)
terra/R/replace_values.R 0000644 0001762 0000144 00000021137 14726700274 014722 0 ustar ligges users # Author: Robert J. Hijmans
# Date: October 2018
# Version 1.0
# License GPL v3
setMethod("set.values", signature(x="SpatRasterDataset"),
function(x) {
x@pntr$readAll()
messages(x, "set.values")
}
)
setMethod("set.values", signature(x="SpatRaster"),
function(x, cells, values, layer=0) {
#if (any(is.na(cells))) {
# warn("set.values", "cells should not be NA")
#}
if (is.character(layer)) {
layer <- match(layer, names(x))
if (any(is.na(layer))) {
error("set.values", "invalid layer")
}
}
layer <- round(layer)
if (all(layer > 0)) {
if (missing(cells) && missing(values)) {
return(invisible(TRUE));
}
if (any(is.na(layer))) { error("set.values", "layers cannot be NA")}
if (inherits(layer, "character")) {
layer <- match(layer, names(x))
if (any(is.na(layer))) { error("set.values", "invalid layer names")}
}
if (any((layer < 1) | (layer > nlyr(x)))) { error("set.values", "invalid layer numbers") }
n <- length(layer)
if (n > length(unique(layer))) { error("set.values", "duplicated layers") }
bylyr <- FALSE
if (!is.null(dim(values))) {
if (ncol(values) != n) {
error("set.values", "ncol(values) does not match `length(layer)`")
}
bylyr <- TRUE
#if (inherits(values, "data.frame")) {
# values <- as.matrix(values)
#}
values <- as.vector(values)
}
ok <- x@pntr$replaceCellValuesLayer(layer-1, cells-1, values, bylyr, spatOptions())
messages(x)
invisible(TRUE)
} else {
if (any(layer > 0)) {
error("set.values", "some (but not all) layer numbers are < 1")
}
if (missing(cells) && missing(values)) {
x@pntr$readAll()
return(messages(x, "set.values"))
}
bylyr <- FALSE
if (!is.null(dim(values))) {
if (ncol(values) != nlyr(x)) {
error("set.values", "ncol(values) does not match the nlyr(x)")
}
bylyr <- TRUE
#if (inherits(values, "data.frame")) {
# values <- as.matrix(values)
#}
values <- as.vector(values)
}
ok <- x@pntr$replaceCellValues(cells-1, values, bylyr, spatOptions())
messages(x)
}
invisible(TRUE)
}
)
make_replace_index <- function(v, vmx, nreps, name="i") {
caller <- paste0("`[<-`(", name, ")")
if (inherits(v, "SpatRaster")) {
error(caller, paste("index", name, "cannot be a SpatRaster"))
}
if (inherits(v, "SpatVector")) {
error(caller, paste("index", name, "cannot be a SpatVector"))
}
if (inherits(v, "SpatExtent")) {
error(caller, paste("index", name, "cannot be a SpatExtent"))
}
if (!is.numeric(v)) {
if (NCOL(v) > 1) {
error(caller, paste("index", name, "has multiple columns"))
}
if (inherits(v, "data.frame")) {
v <- v[,1,drop=TRUE]
} else if (inherits(v, "matrix")) {
v <- as.vector(v)
}
if (!is.vector(v)) {
error(caller, paste("the type of index", name, "is unexpected:", class(v)[1]))
}
if (is.factor(v) || is.character(v)) {
error(caller, paste("the type of index", name, "cannot be a factor or character"))
}
if (is.logical(v)) {
if (length(v) > vmx) {
error(caller, paste("index", name, "is too long"))
}
if (length(v) <= vmx) {
v <- which(rep_len(v, vmx))
}
} else {
v <- as.numeric(v)
}
}
if (inherits(v, "matrix")) {
if (ncol(v) == 1) {
v <- v[,1]
} else if (nrow(v) == 1) {
v <- v[1,]
} else {
error(caller, paste("index", name, "has unexpected dimensions:", paste(dim(v), collapse=", ")))
}
}
if (any(is.na(v))) {
if (nreps > 1) {
error(caller, "NAs are not allowed in subscripted assignments")
} else {
v <- v[!is.na(v)]
}
}
#vv <- stats::na.omit(v)
if (all(v < 0)) {
if (any(v < -vmx)) {
error(caller, paste(name, "is out of its valid range"))
}
v <- (1:vmx)[v]
}
if (any(v < 1 | v > vmx)) {
error(caller, paste(name, "is out of its valid range"))
}
v
}
.replace_all <- function(x, value) {
nl <- nlyr(x)
if (is.matrix(value)) {
d <- dim(value)
if (!all(d == c(ncell(x), nl))) {
if ((d[2] == nl) && (d[1] < ncell(x))) {
value <- apply(value, 2, function(i) rep_len(i, ncell(x)))
} else {
error("`[`","dimensions of the matrix do not match the SpatRaster")
}
}
x <- try( setValues(x, value, TRUE, TRUE) )
} else {
v <- try( matrix(nrow=ncell(x), ncol=nl) )
if (! inherits(x, "try-error")) {
v[] <- value
x <- try( setValues(x, v, TRUE, TRUE) )
}
}
if (inherits(x, "try-error")) {
error("`[`", "cannot set values")
}
return(x)
}
.replace_cell <- function(x, i, k, value) {
bylyr = FALSE
if (!is.null(dim(value))) {
stopifnot(ncol(value) == nlyr(x))
bylyr <- TRUE
if (inherits(value, "data.frame")) {
value <- as.matrix(value)
}
value <- as.vector(value)
}
opt <- spatOptions()
x@pntr <- x@pntr$deepcopy()
if (is.na(k[1])) {
if (!x@pntr$replaceCellValues(i-1, value, bylyr, opt)) {
messages(x, "`[<-`")
}
} else {
if (!x@pntr$replaceCellValuesLayer(k-1, i-1, value, bylyr, opt)) {
messages(x, "`[<-`")
}
}
x
}
.replace_cell_lyr <- function(x, cell, lyrs, value) {
ulyrs <- sort(unique(lyrs))
opt <- spatOptions()
for (lyr in ulyrs) {
y <- x[[lyr]]
i <- which(lyrs == lyr)
if (!y@pntr$replaceCellValues(cell[i]-1, value[i], FALSE, opt)) {
messages(y, "`[<-`")
}
x[[lyr]] <- y
}
x
}
.replace_spatvector <- function(x, i, value) {
if (length(value) > 1) {
if (length(value) > nrow(i)) {
# could be by layer if NCOL>1?
error("`[`", "value is too long")
}
value <- rep_len(value, length.out=length(i))
}
rasterize(i, x, field=value, update=TRUE)
}
.replace_spatextent <- function(x, i, value) {
if (length(value) > 1) {
if (length(value) > nrow(i)) {
# could be by layer if NCOL>1?
error("`[`", "value is too long")
}
value <- rep_len(value, length.out=length(i))
}
rasterize(as.polygons(i), x, field=value, update=TRUE)
}
.replace_spatraster <- function(x, i, value) {
if (inherits(value, "SpatRaster")) {
x <- mask(x, i, maskvalues=TRUE)
cover(x, value)
} else {
if (NCOL(value) > 1) {
error("`[<-`", "cannot use a data.frame with multiple columns")
}
value <- unlist(value)
if (length(value) == 1) {
mask(x, i, maskvalues=TRUE, updatevalue=value[1])
} else {
i <- as.logical(values(i))
i[is.na(i)] <- FALSE #TRUE, for #1115
i <- which(i)
x[i] <- value
x
}
}
}
setReplaceMethod("[", c("SpatRaster", "ANY", "ANY", "ANY"),
function(x, i, j, k, value) {
m <- c(missing(i), missing(j), missing(k))
if (all(m) && is.matrix(value) && ((nrow(value) == nrow(x)) && (ncol(value) == ncol(x) * nlyr(x)))) {
values(x) <- value
return(x)
}
s <- rep(FALSE, 3)
if (!m[1]) s[1] <- inherits(i, "list")
if (!m[2]) s[2] <- inherits(j, "list")
if (!m[3]) s[3] <- inherits(k, "list")
if (any(s)) {
if (m[1]) i <- NULL
if (m[2]) j <- NULL
if (m[3]) k <- NULL
i <- rcl(x, i, j, k)
m <- c(FALSE, TRUE, TRUE)
}
if (missing(value)) {
value <- k
k <- NA
m[3] <- TRUE
}
if ((!m[1]) && (inherits(i, "matrix"))) {
if (ncol(i) == 1) {
i <- i[,1]
} else if (ncol(i) == 2) {
i <- cellFromRowCol(x, i[,1], i[,2])
m[2] <- TRUE
m[3] <- TRUE
} else if (ncol(i) == 3) {
k <- i[,3]
value <- rep_len(value, length(k))
i <- cellFromRowCol(x, i[,1], i[,2])
return(.replace_cell_lyr(x, i, k, value))
} else {
error("`[<-`", paste("index i has", ncol(i), "columns"))
}
}
if (!m[3]) {
if (inherits(k, "character")) {
k <- match(k, names(x))
if (any(is.na(k))) {
stop()
}
} else {
k <- make_replace_index(k, nlyr(x), length(value), "k")
}
} else {
k <- NA
}
if (all(m)) {
return(.replace_all(x, value))
}
if (!m[1]) { # i not missing
if (inherits(i, "SpatRaster")) {
return(.replace_spatraster(x, i, value))
}
if (inherits(i, "SpatVector")) {
return(.replace_spatvector(x, i, value))
}
if (inherits(i, "SpatExtent")) {
return(.replace_spatextent(x, i, value))
}
theCall <- sys.call(-1)
narg <- length(theCall)-length(match.call(call=theCall))
if ((narg==0) && m[2]) {
# cell
i <- make_replace_index(i, ncell(x), length(value), "i")
} else if (m[2]) {
# row
i <- make_replace_index(i, nrow(x), length(value), "i")
i <- cellFromRowColCombine(x, i, 1:ncol(x))
} else {
#row,col
i <- make_replace_index(i, nrow(x), length(value), "i")
j <- make_replace_index(j, ncol(x), length(value), "j")
i <- cellFromRowColCombine(x, i, j)
}
} else if (!m[2]) {
#col
j <- make_replace_index(j, ncol(x), length(value), "j")
i <- cellFromRowColCombine(x, 1:nrow(x), j)
} else {
if (inherits(value, "SpatRaster")) {
x[[k]] <- value
return(x)
}
i <- 1:ncell(x)
}
return(.replace_cell(x, i, k, value))
}
)
terra/R/geom.R 0000644 0001762 0000144 00000041357 14752746600 012667 0 ustar ligges users
# buffer2 <- function(x, width, quadsegs=10) {
# if (is.character(width)) {
# if (!(width %in% names(x))) {
# error("buffer2", paste(width, "is not a field in x"))
# }
# width <- x[[width, drop=TRUE]]
# }
# if (!is.numeric(width)) {
# error("buffer2", "width is not numeric")
# }
# x@pntr <- x@pntr$buffer2(width, quadsegs)
# messages(x, "buffer2")
# }
# buffer3 <- function(x, width, quadsegs=10) {
# if (is.character(width)) {
# if (!(width %in% names(x))) {
# error("buffer3", paste(width, "is not a field in x"))
# }
# width <- x[[width, drop=TRUE]]
# }
# if (!is.numeric(width)) {
# error("buffer3", "width is not numeric")
# }
# x@pntr <- x@pntr$buffer3(width, quadsegs)
# messages(x, "buffer3")
# }
# buffer4 <- function(x, width, quadsegs=10) {
# if (is.character(width)) {
# if (!(width %in% names(x))) {
# error("buffer4", paste(width, "is not a field in x"))
# }
# width <- x[[width, drop=TRUE]]
# }
# if (!is.numeric(width)) {
# error("buffer4", "width is not numeric")
# }
# x@pntr <- x@pntr$buffer4(width, quadsegs)
# messages(x, "buffer4")
# }
roundtrip <- function(x, coll=FALSE) {
if (coll) {
p <- methods::new("SpatVectorCollection")
p@pntr <- x@pntr$bienvenue()
return(p)
} else {
x@pntr <- x@pntr$allerretour()
return(x)
}
}
get_invalid_coords <- function(x) {
x <- x[!x[,1], ]
if (nrow(x) > 0) {
id <- as.integer(rownames(x))
txt <- x[,2]
txt <- gsub("Ring Self-intersection\\[", "", txt)
txt <- gsub("Self-intersection\\[", "", txt)
txt <- gsub("Too few points in geometry component\\[", "", txt)
txt <- unlist(strsplit(gsub("]", "", txt), " "))
txt <- matrix(as.numeric(txt), ncol=2, byrow=TRUE)
v <- vect(txt)
values(v) <- data.frame(id=id, msg=x[,2])
v
} else {
vect()
}
}
setMethod("is.valid", signature(x="SpatVector"),
function(x, messages=FALSE, as.points=FALSE) {
if (as.points) messages = TRUE
if (messages) {
r <- x@pntr$geos_isvalid_msg()
d <- data.frame(matrix(r, ncol=2, byrow=TRUE))
d[,1] = d[,1] == "\001"
colnames(d) <- c("valid", "reason")
if (as.points) {
p <- try(get_invalid_coords(d), silent=TRUE)
if (inherits(p, "try-error")) {
warn("is.valid", "as.points failed, returning matrix")
return(d)
} else {
return(p)
}
}
d
} else {
x@pntr$geos_isvalid()
}
}
)
setMethod("makeValid", signature(x="SpatVector"),
function(x) {
x@pntr <- x@pntr$make_valid2()
messages(x)
}
)
setMethod("is.na", signature(x="SpatVector"),
function(x) {
x@pntr$naGeoms()
}
)
setMethod("na.omit", signature("SpatVector"),
function(object, field=NA, geom=FALSE) {
if (geom) {
g <- geom(object)
g <- g[is.na(g[,"x"]) | is.na(g[,"y"]), 1]
if (length(g) > 0) {
object <- object[-g, ]
}
}
stopifnot(is.vector(field))
if (!is.na(field[1])) {
field <- field[!is.na(field)]
v <- values(object)
if (!any(field == "")) {
v <- v[, field, drop=FALSE]
}
i <- apply(v, 1, function(i) any(is.na(i)))
if (any(i)) {
object <- object[!i, ]
}
}
object
}
)
setMethod("deepcopy", signature("SpatVector"),
function(x) {
x@pntr <- x@pntr$deepcopy()
x
}
)
as.list.svc <- function(x) {
v <- vect()
out <- lapply(1:x$size(),
function(i) {
v@pntr <- x$get(i-1)
v
})
names(out) <- x$names
out
}
setMethod("cover", signature(x="SpatVector", y="SpatVector"),
function(x, y, identity=FALSE, expand=TRUE) {
x@pntr <- x@pntr$cover(y@pntr, identity[1], expand[1])
messages(x, "cover")
}
)
setMethod("symdif", signature(x="SpatVector", y="SpatVector"),
function(x, y) {
x@pntr <- x@pntr$symdif(y@pntr)
messages(x, "symdif")
}
)
setMethod("erase", signature(x="SpatVector", y="SpatVector"),
function(x, y) {
x@pntr <- x@pntr$erase_agg(y@pntr)
messages(x, "erase")
}
)
setMethod("erase", signature(x="SpatVector", y="missing"),
function(x, sequential=TRUE) {
x@pntr <- x@pntr$erase_self(sequential)
messages(x, "erase")
}
)
setMethod("erase", signature(x="SpatVector", y="SpatExtent"),
function(x, y) {
y <- as.polygons(y)
x@pntr <- x@pntr$erase(y@pntr)
messages(x, "erase")
}
)
setMethod("gaps", signature(x="SpatVector"),
function(x) {
x@pntr <- x@pntr$gaps()
messages(x, "gaps")
}
)
setMethod("union", signature(x="SpatVector", y="missing"),
function(x, y) {
x@pntr <- x@pntr$union_self()
messages(x, "union")
}
)
setMethod("union", signature(x="SpatVector", y="SpatVector"),
function(x, y) {
if (geomtype(x) != "polygons") {
unique(rbind(x, y))
} else {
x@pntr <- x@pntr$union(y@pntr)
messages(x, "union")
}
}
)
setMethod("union", signature(x="SpatVector", y="SpatExtent"),
function(x, y) {
y <- as.vector(y)
x@pntr <- x@pntr$union(y@pntr)
messages(x, "union")
}
)
setMethod("union", signature(x="SpatExtent", y="SpatExtent"),
function(x, y) {
x + y
}
)
setMethod("intersect", signature(x="SpatVector", y="SpatVector"),
function(x, y) {
x@pntr <- x@pntr$intersect(y@pntr, TRUE)
messages(x, "intersect")
}
)
setMethod("intersect", signature(x="SpatExtent", y="SpatExtent"),
function(x, y) {
x@pntr <- x@pntr$intersect(y@pntr)
if (!x@pntr$valid_notempty) {
return(NULL)
}
x
}
)
setMethod("intersect", signature(x="SpatVector", y="SpatExtent"),
function(x, y) {
#x@pntr <- x@pntr$crop_ext(y@pntr)
#x
crop(x, y)
}
)
setMethod("intersect", signature(x="SpatExtent", y="SpatVector"),
function(x, y) {
y <- ext(y)
x * y
}
)
setMethod("mask", signature(x="SpatVector", mask="SpatVector"),
function(x, mask, inverse=FALSE) {
x@pntr <- x@pntr$mask(mask@pntr, inverse)
messages(x, "mask")
}
)
setMethod("mask", signature(x="SpatVector", mask="SpatExtent"),
function(x, mask, inverse=FALSE) {
mask <- vect(mask, crs=crs(x))
x@pntr <- x@pntr$mask(mask@pntr, inverse)
messages(x, "mask")
}
)
setMethod("intersect", signature(x="SpatExtent", y="SpatRaster"),
function(x, y) {
x <- align(x, y, snap="near")
intersect(x, ext(y))
}
)
setMethod("intersect", signature(x="SpatRaster", y="SpatExtent"),
function(x, y) {
intersect(y, x)
}
)
setMethod("buffer", signature(x="SpatVector"),
function(x, width, quadsegs=10, capstyle="round", joinstyle="round", mitrelimit=NA, singlesided=FALSE) {
if (is.character(width)) {
if (!(width %in% names(x))) {
error("buffer", paste(width, "is not a field in x"))
}
width <- x[[width, drop=TRUE]]
}
if (!is.numeric(width)) {
error("buffer", "width is not numeric")
}
x@pntr <- x@pntr$buffer(width, quadsegs, tolower(capstyle), tolower(joinstyle), mitrelimit, singlesided)
messages(x, "buffer")
}
)
setMethod("crop", signature(x="SpatVector", y="ANY"),
function(x, y, ext=FALSE) {
if (ext) {
y <- ext(y)
x@pntr <- x@pntr$crop_ext(y@pntr, TRUE)
return(x)
}
if (inherits(y, "SpatVector")) {
x@pntr <- x@pntr$crop_vct(y@pntr)
} else {
if (!inherits(y, "SpatExtent")) {
y <- try(ext(y), silent=TRUE)
if (inherits(y, "try-error")) {
stop("y does not have a SpatExtent")
}
}
## crop_ext does not include points on the borders
## https://github.com/rspatial/raster/issues/283
#x@pntr <- x@pntr$crop_ext(y@pntr)
if (geomtype(x) == "points") {
y <- as.polygons(y)
x@pntr <- x@pntr$crop_vct(y@pntr)
} else {
x@pntr <- x@pntr$crop_ext(y@pntr, TRUE)
}
}
messages(x, "crop")
}
)
setMethod("hull", signature(x="SpatVector"),
function(x, type="convex", by="", param=1, allowHoles=TRUE, tight=TRUE) {
type <- match.arg(tolower(type), c("convex", "rectangle", "circle", "concave_ratio", "concave_length", "concave_polygons"))
x@pntr <- x@pntr$hull(type, by[1], param, allowHoles, tight)
messages(x, "hull")
}
)
setMethod("disagg", signature(x="SpatVector"),
function(x, segments=FALSE) {
x@pntr <- x@pntr$disaggregate(segments[1])
messages(x, "disagg")
}
)
setMethod("flip", signature(x="SpatVector"),
function(x, direction="vertical") {
d <- match.arg(direction, c("vertical", "horizontal"))
x@pntr <- x@pntr$flip(d == "vertical")
messages(x, "flip")
}
)
setMethod("spin", signature(x="SpatVector"),
function(x, angle, x0, y0) {
e <- as.vector(ext(x))
if (missing(x0)) {
x0 <- mean(e[1:2])
}
if (missing(y0)) {
y0 <- mean(e[3:4])
}
angle <- angle[1]
stopifnot(is.numeric(angle) && !is.nan(angle))
x@pntr <- x@pntr$rotate(angle, x0, y0)
messages(x, "spin")
}
)
setMethod("delaunay", signature(x="SpatVector"),
function(x, tolerance=0, as.lines=FALSE, constrained=FALSE) {
x@pntr <- x@pntr$delaunay(tolerance, as.lines, constrained)
messages(x, "delaunay")
}
)
voronoi_deldir <- function(x, bnd=NULL, eps=1e-09, ...){
xy <- crds(x)
dat <- values(x)
if (nrow(dat > 0)) {
dups <- duplicated(xy)
if (any(dups)) {
xy <- xy[!dups, ,drop=FALSE]
dat <- dat[!dups, ,drop=FALSE]
}
} else {
xy <- stats::na.omit(xy[, 1:2])
xy <- unique(xy)
}
e <- bnd
if (!is.null(e)) {
e <- as.vector(ext(bnd))
}
dd <- deldir::deldir(xy[,1], xy[,2], rw=e, eps=eps, suppressMsge=TRUE)
g <- lapply(deldir::tile.list(dd), function(i) cbind(i$ptNum, 1, i$x, i$y))
g <- do.call(rbind, g)
g <- vect(g, "polygons", crs=crs(x))
if (nrow(g) == nrow(dat)) {
values(g) <- dat
} else {
values(g) <- data.frame(id=dd$ind.orig)
}
g
}
setMethod("voronoi", signature(x="SpatVector"),
function(x, bnd=NULL, tolerance=0, as.lines=FALSE, deldir=FALSE) {
if (nrow(x) ==0) {
error("voronoi", "input has no geometries")
}
if (geomtype(x) != "points") {
x <- as.points(x)
}
if (deldir) {
voronoi_deldir(x, bnd, tolerance=tolerance)
} else {
if (is.null(bnd)) {
bnd <- vect()
} else {
bnd <- as.polygons(ext(bnd))
}
x@pntr <- x@pntr$voronoi(bnd@pntr, tolerance, as.lines)
messages(x, "voronoi")
}
}
)
setMethod("elongate", signature(x="SpatVector"),
function(x, length=1, flat=FALSE) {
x@pntr <- x@pntr$elongate(length, flat)
messages(x, "elongate")
}
)
setMethod("width", signature(x="SpatVector"),
function(x, as.lines=FALSE) {
x@pntr <- x@pntr$width()
x <- messages(x, "width")
if (!as.lines) {
x <- perim(x)
}
x
}
)
setMethod("clearance", signature(x="SpatVector"),
function(x, as.lines=FALSE) {
x@pntr <- x@pntr$clearance()
x <- messages(x, "clearance")
if (!as.lines) {
x <- perim(x)
}
x
}
)
setMethod("mergeLines", signature(x="SpatVector"),
function(x) {
x@pntr <- x@pntr$line_merge()
messages(x, "line_merge")
}
)
setMethod("makeNodes", signature(x="SpatVector"),
function(x) {
x@pntr <- x@pntr$make_nodes()
messages(x, "makeNodes")
}
)
setMethod("removeDupNodes", signature(x="SpatVector"),
function(x, digits=-1) {
x@pntr <- x@pntr$remove_duplicate_nodes(digits)
messages(x, "removeDupNodes")
}
)
setMethod("simplifyGeom", signature(x="SpatVector"),
function(x, tolerance=0.1, preserveTopology=TRUE, makeValid=TRUE) {
x@pntr <- x@pntr$simplify(tolerance, preserveTopology)
x <- messages(x, "simplifyGeom")
if (makeValid) {
x <- makeValid(x)
}
x
}
)
setMethod("thinGeom", signature(x="SpatVector"),
function(x, threshold=1e-6, makeValid=TRUE) {
x@pntr <- x@pntr$thin(threshold)
x <- messages(x, "thinGeom")
if (makeValid) {
x <- makeValid(x)
}
x
}
)
setMethod("sharedPaths", signature(x="SpatVector"),
function(x, y=NULL) {
if (is.null(y)) {
x@pntr <- x@pntr$shared_paths(TRUE)
} else {
x@pntr <- x@pntr$shared_paths2(y@pntr, TRUE)
}
x <- messages(x, "sharedPaths")
# sort data to ensure consistent order with spatial indices
if (nrow(x) > 0) x <- x[order(x$id1, x$id2), ]
x
}
)
setMethod("snap", signature(x="SpatVector"),
function(x, y=NULL, tolerance) {
if (is.null(y)) {
x@pntr <- x@pntr$snap(tolerance)
} else {
x@pntr <- x@pntr$snapto(y@pntr, tolerance)
}
messages(x, "snap")
}
)
setMethod("combineGeoms", signature(x="SpatVector", y="SpatVector"),
function(x, y, overlap=TRUE, boundary=TRUE, distance=TRUE, append=TRUE, minover=0.1, maxdist=Inf, dissolve=TRUE, erase=TRUE) {
if ((geomtype(x) != "polygons") || (geomtype(y) != "polygons")) {
error("combineGeoms", "x and y must be polygons")
}
if (nrow(x) == 0) {
if (append) {
return(rbind(x, y))
} else {
return(x)
}
}
if (nrow(y) == 0) {
return(x)
}
xcrs <- crs(x)
ycrs <- crs(y)
if ((xcrs == "") || (ycrs == "")) {
error("combineGeoms", "x and y must have a crs")
} else if (xcrs != ycrs) {
error("combineGeoms", "x and y do not have the same crs")
}
dx <- values(x)
dy <- values(y)
values(x) = data.frame(idx=1:nrow(x))
values(y) = data.frame(idy=1:nrow(y))
y <- erase(y) # no self-overlaps
if (overlap) {
#avoid Warning message: [intersect] no intersection
xy <- suppressWarnings(intersect(y, x))
if (nrow(xy) > 0) {
xy$aint <- expanse(xy)
a <- values(xy)
a <- a[order(a$idy, -a$aint),]
a <- a[!duplicated(a$idy),]
yi <- y[a$idy,]
atot <- expanse(yi)
a <- a[(a$aint / atot) >= minover, ]
if (nrow(a) > 0) {
if (erase) {
ye <- erase(y, x)
i <- stats::na.omit(match(a$idy, ye$idy))
if (length(i) > 0) {
yi <- ye[i,]
values(yi) <- data.frame(idx=a$idx[i])
} else {
yi <- vect()
}
} else {
yi <- y[a$idy,]
values(yi) <- data.frame(idx=a$idx)
}
if (nrow(yi) > 0) {
x <- aggregate(rbind(x, yi), "idx", dissolve=dissolve, counts=FALSE)
}
y <- y[-a$idy,]
}
}
}
if (boundary && (nrow(y) > 0)) {
ye <- erase(y, x)
p <- sharedPaths(ye, x)
if (nrow(p) > 0) {
p$s <- perim(p)
p <- values(p)
p <- p[order(p$id1, -p$s),]
p <- p[!duplicated(p$id1),]
if (erase) {
i <- p$id1
yi <- ye[p$id1,]
yi$idx <- p$id2
yi$idy <- NULL
} else {
i <- ye$idy[p$id1]
i <- match(i, y$idy)
yi <- y[i,]
yi$idx <- 0
yi$idx[i] <- p$id2[i]
}
yi$idy <- NULL
x <- aggregate(rbind(x, yi), "idx", dissolve=dissolve, counts=FALSE)
y <- y[-i,]
}
}
if (distance && (nrow(y) > 0) && (maxdist > 0)) {
n <- nearest(y, x)
n <- n[n$distance <= maxdist, ]
if (nrow(n) > 0) {
yi <- y[n$from_id, ]
yi$idx <- n$to_id
yi$idy <- NULL
x <- aggregate(rbind(x, yi), "idx", dissolve=FALSE, counts=FALSE)
y <- y[-n$from_id, ]
}
}
values(x) <- dx[x$idx, ,drop=FALSE]
if (append && (nrow(y) > 0)) {
values(y) <- dy[y$idy, ,drop=FALSE]
if (erase) {
y <- erase(y, x)
}
x <- rbind(x, y)
}
x
}
)
setMethod("split", signature(x="SpatVector", f="ANY"),
function(x, f) {
if (length(f) > 1) {
x <- deepcopy(x)
x$f <- f
f <- "f"
}
x <- messages(x@pntr$split(f), "split")
as.list.svc(x)
}
)
#setMethod("split", signature(x="SpatVector", f="SpatVector"),
badsplit <- function(x, f) {
if (geomtype(x) != "polygons") error("split", "first argument must be polygons")
if (!(geomtype(f) %in% c("lines", "polygons"))) {
error("split", "argument 'f' must have a lines or polygons geometry")
}
values(f) <- NULL
ex <- ext(x)
r <- relate(x, f, "intersects")
if (sum(r) == 0) {
warn("split", "x and f do not intersect")
return(x)
}
#r <- r[rowSums(r) > 0, ,drop=FALSE]
ri <- which(rowSums(r) > 0)
y <- x[ri,]
r <- r[ri, , drop=FALSE]
values(y) <- NULL
ss <- vector("list", nrow(y))
if (geomtype(f) == "lines") {
for (i in 1:nrow(y)) {
yi <- y[i]
yi <- disagg(yi)
add <- NULL
if (nrow(yi) > 1) {
ri <- relate(yi, f, "intersects")
if (any(!ri)) {
add <- yi[!ri]
yi <- yi[ri]
}
}
lin <- intersect(f[r[i,],], yi)
v <- rbind(as.lines(yi), lin)
v <- makeNodes( aggregate(v) )
v <- as.polygons(v)
if (!is.null(add)) {
v <- combineGeoms(v, add, overlap=FALSE, boundary=FALSE, distance=TRUE, dissolve=FALSE, erase=FALSE)
}
v$id <- i
ss[[i]] <- v
}
ss <- vect(ss)
v <- values(x)
values(ss) <- v[ss$id, ]
rbind(x[-i,], ss)
} else { #if (geomtype(f) == "polygons") {
for (i in 1:nrow(r)) {
yi <- y[i]
v <- rbind(intersect(yi, f[r[i,],]),
erase(yi, f[r[i,],]))
v$id <- i
ss[[i]] <- v
}
ss <- vect(ss)
v <- values(x)
values(ss) <- v[ss$id, ]
rbind(x[-i,], ss)
}
}
#)
setMethod("split", signature(x="SpatVector", f="SpatVector"),
function(x, f) {
if (geomtype(x) != "polygons") error("split", "first argument must be polygons")
if (!(geomtype(f) %in% c("lines", "polygons"))) {
error("split", "argument 'f' must have a lines or polygons geometry")
}
values(f) <- NULL
f <- as.lines(f)
r <- relate(x, f, "intersects")
if (sum(r) == 0) {
warn("split", "x and f do not intersect")
return(x)
}
e <- elongate(intersect(as.lines(f), x), 0.00001)
k <- aggregate(rbind(as.lines(x), e))
nds <- makeNodes(k)
p <- as.polygons(nds)
intersect(x, p)
}
)
setMethod("forceCCW", signature(x="SpatVector"),
function(x) {
x <- deepcopy(x)
x@pntr$make_CCW()
messages(x)
}
)
setMethod("is.empty", signature(x="SpatVector"),
function(x) {
nrow(x) == 0
}
)
terra/R/plot_scale.R 0000644 0001762 0000144 00000021060 14624315507 014046 0 ustar ligges users
..assume_lonlat <- function(pr) {
(pr$usr[1] > -300) && (pr$usr[2] < 300) && (pr$yaxp[1] > -200) && (pr$yaxp[2] < 200)
}
.get_dd <- function(pr, lonlat, d=NULL) {
if (lonlat) {
lat <- mean(pr$usr[3:4])
if (is.null(d)) {
dx <- (pr$usr[2] - pr$usr[1]) / 6
d <- as.vector(distance(cbind(0, lat), cbind(dx, lat), TRUE))
d <- max(1, 5 * round(d/5000))
}
p <- cbind(0, lat)
dd <- .destPoint(p, d * 1000)
dd <- c(dd[1,1], d)
} else {
if (is.null(d)) {
d <- (pr$usr[2] - pr$usr[1]) / 6
digits <- floor(log10(d)) + 1
d <- round(d, -(digits-1))
}
dd <- c(d, d)
}
dd
}
.get_xy <- function(xy, dx=0, dy=0, pr, defpos="bottomleft", caller="") {
if (is.null(xy)) {
xy <- defpos
}
if (!is.character(xy)) {
return( cbind(xy[1], xy[2]) )
}
xy <- tolower(xy)
parrange <- c(pr$usr[2] - pr$usr[1], pr$usr[4] - pr$usr[3])
pad=c(5,5) / 100
if (xy == "bottom") {
xy <- c(pr$usr[1]+0.5*parrange[1]-0.5*dx, pr$usr[3]+(pad[2]*parrange[2])) + c(0,dy)
} else if (xy == "bottomleft") {
xy <- c(pr$usr[1]+(pad[1]*parrange[1]), pr$usr[3]+(pad[2]*parrange[2])) + c(0,dy)
} else if (xy == "bottomright") {
xy <- c(pr$usr[2]-(pad[1]*parrange[1]), pr$usr[3]+(pad[2]*parrange[2])) - c(dx,-dy)
} else if (xy == "topright") {
xy <- c(pr$usr[2]-(pad[1]*parrange[1]), pr$usr[4]-(pad[2]*parrange[2])) - c(dx,dy)
} else if (xy == "top") {
xy <- c(pr$usr[1]+0.5*parrange[1]-0.5*dx, pr$usr[4]-(pad[2]*parrange[2])) - c(0,dy)
} else if (xy == "topleft") {
xy <- c(pr$usr[1]+(pad[1]*parrange[1]), pr$usr[4]-(pad[2]*parrange[2])) - c(0,dy)
} else if (xy == "left") {
xy <- c(pr$usr[1]+(pad[1]*parrange[1]), pr$usr[3]+0.5*parrange[2]-0.5*dy)
} else if (xy == "right") {
xy <- c(pr$usr[2]-(pad[1]*parrange[1])-dx, pr$usr[3]+0.5*parrange[2]-0.5*dy)
} else {
error(caller, 'xy must be a coordinate pair (two numbers) or one of "bottomleft", "bottom", "bottomright", topleft", "top", "topright"')
}
xy
}
.destPoint <- function (p, d, b=90, r=6378137) {
toRad <- pi/180
lon1 <- p[, 1] * toRad
lat1 <- p[, 2] * toRad
b <- b * toRad
lat2 <- asin(sin(lat1) * cos(d/r) + cos(lat1) * sin(d/r) * cos(b))
lon2 <- lon1 + atan2(sin(b) * sin(d/r) * cos(lat1), cos(d/r) - sin(lat1) * sin(lat2))
lon2 <- (lon2 + pi)%%(2 * pi) - pi
cbind(lon2, lat2)/toRad
}
add_N <- function(x, y, asp, label, type=0, user="", angle=0, cex=1, srt=0, xpd=TRUE, ...) {
type <- type[1]
if (type == 0) { symbol = user[1]
} else if (type == 2) { symbol = "\u27A2"
} else if (type == 3) { symbol = "\u2799"
} else if (type == 4) { symbol = "\u27B2"
} else if (type == 5) { symbol = "\u27BE"
} else if (type == 6) { symbol = "\u27B8"
} else if (type == 7) { symbol = "\u27BB"
} else if (type == 8) { symbol = "\u27B5"
} else if (type == 9) { symbol = "\u279F"
} else if (type == 10) { symbol = "\u261B"
} else if (type == 11) { symbol = "\u2708"
} else { symbol = "\u2629"}
if (type == 11) {
rangle <- 45 - angle
mcex <- 1.5
} else {
rangle <- 90 - angle
mcex <- 3
}
text(x, y, symbol, cex=cex*mcex, srt=rangle, xpd=xpd, ...)
xs <- graphics::strwidth(symbol,cex=cex*3)
ys <- graphics::strheight(symbol,cex=cex*3)
b <- pi * angle / 180
rxs <- (abs(xs * cos(b)) + abs(ys * sin(b)))# / asp
rys <- (abs(xs * sin(b)) + abs(ys * cos(b)))# * asp
# xoff <- (rxs - xs) / 2
# yoff <- rys + 0.05 * graphics::strheight(label,cex=cex)
xoff = 0.1 * rxs
yoff = 0.8 * rys * max(0.5, abs(cos(angle)))
if (type == 4) {
.halo(x+xoff, y-0.2*yoff, label, cex = cex, srt = srt, xpd = xpd, ...)
} else if (type == 10) {
.halo(x+xoff, y-yoff, label, cex = cex, srt = srt, xpd = xpd, ...)
} else {
text(x+xoff, y+yoff, label, cex = cex, srt = srt, xpd = xpd, ...)
}
}
north <- function(xy=NULL, type=1, label="N", angle=0, d, head=0.1, xpd=TRUE, ...) {
pr <- graphics::par()
pr$usr <- unlist(get.clip()[1:4])
pa <- c(pr$usr[2] - pr$usr[1], pr$usr[4] - pr$usr[3])
asp <- pa[2]/pa[1]
if (missing(d)) {
d <- 0.07 * pa[2]
}
xy <- .get_xy(xy, 0, d, pr, "topright", caller="north")
if (inherits(type, "character")) {
usertype <- type
type = 0
} else {
type <- round(type)
usertype <- ""
}
if (type == 1) {
if (angle != 0) {
b <- angle * pi / 180;
p2 <- xy + c(d * sin(b), d * cos(b))
b <- b + pi
p1 <- xy + c(d * sin(b), d * cos(b))
if ((p2[1] - p1[1]) > (d/asp)) {
m <- xy[1] #p1[1] + (p2[1] - p1[1]) / 2
slope = (p2[2] - p1[2])/(p2[1] - p1[1])
newx <- m - 0.5 * d / asp
p1[2] <- p1[2] + (newx-p1[1]) * slope
p1[1] <- newx
newx <- m + 0.5 * d / asp
p2[2] <- p2[2] - (p2[1]-newx) * slope
p2[1] <- newx
}
} else {
p1 <- xy - c(0,d)
p2 <- xy + c(0,d)
}
lwd <- list(...)$lwd + 2
if (is.null(lwd)) lwd <- 3
graphics::arrows(p1[1], p1[2], p2[1], p2[2], length=head, lwd=lwd, col="white", xpd=xpd)
graphics::arrows(p1[1], p1[2], p2[1], p2[2], length=head, xpd=xpd, ...)
if (label != "") {
if (is.null(list(...)$hw)) {
.halo(xy[1], xy[2], label, hw=.2, xpd=xpd, ... )
} else {
.halo(xy[1], xy[2], label, xpd=xpd, ... )
}
}
} else {
add_N(xy[1], xy[2], asp=asp, label=label, angle=angle, type=type, user=usertype, xpd=xpd, ...)
}
}
sbar <- function(d, xy=NULL, type="line", divs=2, below="", lonlat=NULL, labels, adj=c(0.5, -1), lwd=2, xpd=TRUE, ticks=FALSE, scaleby=1, halo=TRUE, ...){
stopifnot(type %in% c("line", "bar"))
pr <- graphics::par()
clp <- get.clip()
pr$usr <- unlist(clp[,1:4])
if (is.null(lonlat)) {
lonlat <- isTRUE(clp[[5]])
}
if (missing(d)) {
labels <- NULL
d <- NULL
}
dd <- .get_dd(pr, lonlat, d)
d <- dd[2]
dd <- dd[1]
xy <- .get_xy(xy, dd, 0, pr, "bottomleft", caller="sbar")
if (type == "line") {
if (halo) {
lines(matrix(c(xy[1], xy[2], xy[1]+dd, xy[2]), byrow=T, nrow=2), lwd=lwd+1, xpd=xpd, col="white")
}
lines(matrix(c(xy[1], xy[2], xy[1]+dd, xy[2]), byrow=T, nrow=2), lwd=lwd, xpd=xpd, ...)
if (missing(labels) || is.null(labels)) {
ds <- d / scaleby
if (divs > 2) {
labels <- c(0, round(ds/2, 1), ds)
} else {
labels <- paste(ds)
}
}
if (missing(adj)) {
adj <- c(0.5, -0.2-lwd/20 )
}
tadd <- 0
if (!isFALSE(ticks)) {
if (isTRUE(ticks)) {
tadd <- dd / (15 * diff(pr$usr[1:2]) / diff(pr$usr[3:4]))
} else {
tadd <- ticks
}
if (length(labels) == 1) {
xtick <- c(xy[1], xy[1]+dd)
} else {
xtick <- c(xy[1], xy[1]+dd/2, xy[1]+dd)
}
for (i in 1:length(xtick)) {
lines(rbind(c(xtick[i], xy[2]), c(xtick[i], xy[2]+tadd)), lwd=ceiling(lwd/2), ...)
}
}
tadd <- max(0, tadd)
if (length(labels) == 1) labels =c("", labels, "")
if (halo) {
.halo(xy[1], xy[2]+tadd,labels=labels[1], xpd=xpd, adj=adj, ...)
.halo(xy[1]+0.5*dd, xy[2]+tadd,labels=labels[2], xpd=xpd, adj=adj,...)
.halo(xy[1]+dd, xy[2]+tadd,labels=labels[3], xpd=xpd, adj=adj,...)
} else {
text(xy[1], xy[2]+tadd,labels=labels[1], xpd=xpd, adj=adj, ...)
text(xy[1]+0.5*dd, xy[2]+tadd,labels=labels[2], xpd=xpd, adj=adj,...)
text(xy[1]+dd, xy[2]+tadd,labels=labels[3], xpd=xpd, adj=adj,...)
}
xy[2] <- xy[2] - dd/10
} else if (type == "bar") {
stopifnot(divs > 0)
if (missing(adj)) {
adj <- c(0.5, -1 )
}
lwd <- dd / 25
if (divs==2) {
half <- xy[1] + dd / 2
graphics::polygon(c(xy[1], xy[1], half, half), c(xy[2], xy[2]+lwd, xy[2]+lwd, xy[2]), col="white", xpd=xpd)
graphics::polygon(c(half, half, xy[1]+dd, xy[1]+dd ), c(xy[2], xy[2]+lwd, xy[2]+lwd, xy[2]), col="black", xpd=xpd)
if (missing(labels) || is.null(labels)) {
labels <- c("0", "", d/scaleby)
}
text(xy[1], xy[2],labels=labels[1], xpd=xpd, adj=adj,...)
text(xy[1]+0.5*dd, xy[2],labels=labels[2], xpd=xpd, adj=adj,...)
text(xy[1]+dd, xy[2],labels=labels[3], xpd=xpd, adj=adj,...)
} else {
q1 <- xy[1] + dd / 4
half <- xy[1] + dd / 2
q3 <- xy[1] + 3 * dd / 4
end <- xy[1] + dd
graphics::polygon(c(xy[1], xy[1], q1, q1), c(xy[2], xy[2]+lwd, xy[2]+lwd, xy[2]), col="white", xpd=xpd)
graphics::polygon(c(q1, q1, half, half), c(xy[2], xy[2]+lwd, xy[2]+lwd, xy[2]), col="black", xpd=xpd)
graphics::polygon(c(half, half, q3, q3 ), c(xy[2], xy[2]+lwd, xy[2]+lwd, xy[2]), col="white", xpd=xpd)
graphics::polygon(c(q3, q3, end, end), c(xy[2], xy[2]+lwd, xy[2]+lwd, xy[2]), col="black", xpd=xpd)
if (missing(labels) || is.null(labels)) {
ds <- d / scaleby
labels <- c("0", round(0.5*ds), ds)
}
text(xy[1], xy[2], labels=labels[1], xpd=xpd, adj=adj, ...)
text(half, xy[2], labels=labels[2], xpd=xpd, adj=adj,...)
text(end, xy[2],labels=labels[3], xpd=xpd, adj=adj,...)
}
}
if (below != "") {
adj[2] <- -adj[2]
text(xy[1]+(0.5*dd), xy[2], xpd=xpd, labels=below, adj=adj,...)
}
}
terra/R/arith.R 0000644 0001762 0000144 00000001727 14536376240 013043 0 ustar ligges users
# setMethod("arith", signature(x="SpatRaster"),
## not exported
arith <- function(x, fun, ..., filename="", overwrite=FALSE, wopt=list()) {
out <- rast(x)
nc <- ncol(x)
readStart(x)
on.exit(readStop(x))
# # test the shape of the output by testing with one row
v <- readValues(x, round(0.5*nrow(x)), 1, 1, nc, mat=TRUE)
r <- try(fun(as.vector(v), ...))
if (inherits(r, "try-error")) {
error("arith", "'fun' is not valid")
}
if (!is.vector(r)) {
error("arith", "'fun' does not return a vector")
}
if (!(is.numeric(r) | is.logical(r))) {
error("arith", "'fun' does not return a numeric vector")
}
if (length(r) != length(v)) {
error("arith", "'fun' does not return the same number of values as the input")
}
b <- writeStart(out, filename, overwrite, sources=sources(x), wopt=wopt)
for (i in 1:b$n) {
v <- readValues(x, b$row[i], b$nrows[i], 1, nc, TRUE)
v <- fun(as.vector(v), ...)
writeValues(out, v, b$row[i], b$nrows[i])
}
writeStop(out)
}
# )
terra/R/interpolate.R 0000644 0001762 0000144 00000004403 14536376240 014254 0 ustar ligges users # Author: Robert J. Hijmans
# Date : August 2009
# Version 0.9
# License GPL v3
setMethod("interpolate", signature(object="SpatRaster"),
function(object, model, fun=predict, ..., xyNames=c("x", "y"), factors=NULL, const=NULL, index=NULL, cores=1, cpkgs=NULL, na.rm=FALSE, filename="", overwrite=FALSE, wopt=list()) {
out <- rast(object)
hv <- hasValues(object)
nms <- c(xyNames, names(object))
if (length(unique(nms)) != length(nms)) {
tab <- table(nms)
error("interpolate", "duplicate names: ", tab[tab>1])
}
nc <- ncol(out)
testrow <- round(0.51*nrow(object))
ntest <- min(nc, 500)
xy <- xyFromCell(out, cellFromRowCol(out, testrow, 1):cellFromRowCol(out, testrow, ntest))
colnames(xy) <- xyNames
if (hv) {
readStart(object)
on.exit(readStop(object))
d <- readValues(object, testrow, 1, 1, ntest, TRUE, TRUE)
xy <- cbind(xy, d)
}
r <- .runModel(model, fun, xy, 1, const, (na.rm & hv), index, cores=NULL, ...)
rdim <- dim(r)
if (!is.null(rdim)) {
if (rdim[1] == 1) {
nl <- rdim[1]
} else {
nl <- rdim[2]
}
} else {
nl <- 1
}
out <- rast(object, nlyrs=nl)
cn <- colnames(r)
if (length(cn) == nl) names(out) <- make.names(cn, TRUE)
doclust <- FALSE
if (inherits(cores, "cluster")) {
doclust <- TRUE
} else if (cores > 1) {
doclust <- TRUE
cores <- parallel::makeCluster(cores)
on.exit(parallel::stopCluster(cores), add=TRUE)
}
if (doclust) {
parallel::clusterExport(cores, c("model", "fun"), environment())
if (!is.null(cpkgs)) {
parallel::clusterExport(cores, "cpkgs", environment())
parallel::clusterCall(cores, function() for (i in 1:length(cpkgs)) {library(cpkgs[i], character.only=TRUE) })
}
export_args(cores, ..., caller="interpolate")
} else {
cores <- NULL
}
b <- writeStart(out, filename, overwrite, sources=sources(object), wopt=wopt)
for (i in 1:b$n) {
xy <- xyFromCell(out, cellFromRowCol(out, b$row[i], 1):cellFromRowCol(out, b$row[i]+b$nrows[i]-1, nc))
colnames(xy) <- xyNames
if (hv) {
d <- readValues(object, b$row[i], b$nrows[i], 1, nc, TRUE, TRUE)
xy <- cbind(xy, d)
}
v <- .runModel(model, fun, xy, nl, const, (na.rm & hv), index, cores=cores, ...)
writeValues(out, v, b$row[i], b$nrows[i])
}
writeStop(out)
}
)
terra/R/replace.R 0000644 0001762 0000144 00000017266 14726700274 013353 0 ustar ligges users # # Author: Robert J. Hijmans
# # Date: October 2018
# # Version 1.0
# # License GPL v3
# .rast_replace <- function(x, name, value, caller="$<-") {
# if (inherits(value, "SpatRaster")) {
# value <- value[[1]]
# names(value) <- name
# } else if (!is.null(value)) {
# y <- rast(x, nlyrs=1)
# test <- try(values(y) <- value, silent=TRUE)
# if (inherits(test, "try-error")) {
# error(caller, "the replacement value is not valid")
# }
# value <- y
# names(value) <- name
# }
# i <- which(name == names(x))[1]
# if (is.null(value)) {
# if (is.na(i)) {
# return(x)
# } else {
# return(subset(x, -i, NSE=FALSE))
# }
# }
# if (is.na(i)) {
# c(x, value)
# } else if (nlyr(x) == 1) {
# value$deepcopy()
# } else if (i == 1) {
# c(value, x[[2:nlyr(x)]])
# } else if (i == nlyr(x)) {
# c(x[[1:(nlyr(x)-1)]], value)
# } else {
# c(x[[1:(i-1)]], value, x[[(i+1):nlyr(x)]])
# }
# }
# setMethod("$<-", "SpatRaster",
# function(x, name, value) {
# .rast_replace(x, name, value, "$<-")
# }
# )
# setReplaceMethod("[[", c("SpatRaster", "character", "missing"),
# function(x, i, j, value) {
# if (inherits(value, "SpatRaster")) {
# if (nlyr(value) != length(i)) {
# error("`[[`", "length of names must be equal to the number of layers")
# }
# names(value) <- i
# } else if (length(i) > 1) {
# if (NCOL(value) > 1) {
# value <- as.list(data.frame(value))
# } else {
# stopifnot(length(i) == length(value))
# }
# } else if (!is.list(value)) {
# value <- list(value)
# }
# for (k in 1:length(i)) {
# x <- .rast_replace(x, i[k], value[[k]], " [[<- ")
# # eval(parse(text = paste0("x$", i[k], " <- value[[k]]")))
# }
# x
# }
# )
# setReplaceMethod("[[", c("SpatRaster", "numeric", "missing"),
# function(x, i, j, value) {
# if (!inherits(value, "SpatRaster")) {
# error("`[[<-`", "Expected a SpatRaster as replacement value")
# }
# if (nlyr(value) != length(i)) {
# error("`[[`", "length of indices must be equal to the number of layers")
# }
# if (any(i<1) | any(i > nlyr(x))) {
# error("`[[`", "indices must be between 1 and the number of layers")
# }
# if (nlyr(x) == 1) {
# compareGeom(x, value, crs=FALSE, warncrs=TRUE)
# return(value)
# }
# for (k in 1:length(i)) {
# if (i[k] == 1) {
# x <- c(value[[k]], x[[2:nlyr(x)]])
# } else if (i[k] == nlyr(x)) {
# x <- c(x[[1:(nlyr(x)-1)]], value[[k]])
# } else {
# x <- c(x[[1:(i[k]-1)]], value[[k]], x[[(i[k]+1):nlyr(x)]])
# }
# }
# g <- gc()
# x
# }
# )
# setReplaceMethod("[", c("SpatRaster", "missing", "missing"),
# function(x, i, j, value) {
# nl <- nlyr(x)
# if (is.matrix(value)) {
# d <- dim(value)
# if (!all(d == c(ncell(x), nl))) {
# if ((d[2] == nl) && (d[1] < ncell(x))) {
# value <- apply(value, 2, function(i) rep_len(i, ncell(x)))
# } else {
# error("`[`","dimensions of the matrix do not match the SpatRaster")
# }
# }
# x <- try( setValues(x, value, TRUE, TRUE) )
# } else {
# v <- try( matrix(nrow=ncell(x), ncol=nl) )
# if (! inherits(x, "try-error")) {
# v[] <- value
# x <- try( setValues(x, v, TRUE, TRUE) )
# }
# }
# if (inherits(x, "try-error")) {
# error("`[`", "cannot set values")
# }
# return(x)
# }
# )
# setReplaceMethod("[", c("SpatRaster","numeric", "missing"),
# function(x, i, j, value) {
# theCall <- sys.call(-1)
# narg <- length(theCall)-length(match.call(call=sys.call(-1)))
# if (narg > 0) { # row
# i <- cellFromRowColCombine(x, i, 1:ncol(x))
# }
# #if (any(is.na(i))) {
# # warn("`[`", "indices should not be NA")
# #}
# bylyr = FALSE
# if (!is.null(dim(value))) {
# #x@pntr <- x@pntr$replaceValues(i, value, ncol(value))
# stopifnot(ncol(value) == nlyr(x))
# bylyr <- TRUE
# if (inherits(value, "data.frame")) {
# value <- as.matrix(value)
# }
# value <- as.vector(value)
# }
# x@pntr <- x@pntr$deepcopy()
# opt <- spatOptions()
# if (!x@pntr$replaceCellValues(i-1, value, bylyr, opt)) {
# messages(x, "`[<-`")
# } else {
# x
# }
# }
# )
# setMethod("set.values", signature(x="SpatRaster"),
# function(x, cells, values, layer=0) {
# #if (any(is.na(cells))) {
# # warn("set.values", "cells should not be NA")
# #}
# if (is.character(layer)) {
# layer <- match(layer, names(x))
# if (any(is.na(layer))) {
# error("set.values", "invalid layer")
# }
# }
# layer <- round(layer)
# if (all(layer > 0)) {
# if (missing(cells) && missing(values)) {
# return(invisible(TRUE));
# }
# if (any(is.na(layer))) { error("set.values", "layers cannot be NA")}
# if (inherits(layer, "character")) {
# layer <- match(layer, names(x))
# if (any(is.na(layer))) { error("set.values", "invalid layer names")}
# }
# if (any((layer < 1) | (layer > nlyr(x)))) { error("set.values", "invalid layer numbers") }
# n <- length(layer)
# if (n > length(unique(layer))) { error("set.values", "duplicated layers") }
# bylyr <- FALSE
# if (!is.null(dim(values))) {
# if (ncol(values) != n) {
# error("set.values", "ncol(values) does not match the `length(layer)`")
# }
# bylyr <- TRUE
# #if (inherits(values, "data.frame")) {
# # values <- as.matrix(values)
# #}
# values <- as.vector(values)
# }
# ok <- x@pntr$replaceCellValuesLayer(layer-1, cells-1, values, bylyr, spatOptions())
# messages(x)
# invisible(TRUE)
# } else {
# if (any(layer > 0)) {
# error("set.values", "some (but not all) layer numbers are < 1")
# }
# if (missing(cells) && missing(values)) {
# x@pntr$readAll()
# return(invisible(TRUE));
# }
# bylyr <- FALSE
# if (!is.null(dim(values))) {
# if (ncol(values) != nlyr(x)) {
# error("set.values", "ncol(values) does not match the nlyr(x)")
# }
# bylyr <- TRUE
# #if (inherits(values, "data.frame")) {
# # values <- as.matrix(values)
# #}
# values <- as.vector(values)
# }
# ok <- x@pntr$replaceCellValues(cells-1, values, bylyr, spatOptions())
# messages(x)
# }
# invisible(TRUE)
# }
# )
# setReplaceMethod("[", c("SpatRaster", "numeric", "numeric"),
# function(x, i, j, value) {
# i <- cellFromRowColCombine(x, i, j)
# x[i] <- value
# x
# }
# )
# setReplaceMethod("[", c("SpatRaster","missing", "numeric"),
# function(x, i, j, value) {
# i <- cellFromRowColCombine(x, 1:nrow(x), j)
# x[i] <- value
# x
# }
# )
# setReplaceMethod("[", c("SpatRaster", "logical", "missing"),
# function(x, i, j, value) {
# i <- which(rep_len(i, ncell(x)))
# x[i] <- value
# x
# }
# )
# setReplaceMethod("[", c("SpatRaster", "SpatRaster", "ANY"),
# function(x, i, j, value) {
# theCall <- sys.call(-1)
# narg <- length(theCall)-length(match.call(call=sys.call(-1)))
# if (narg > 0) { # row
# error("`[`", "you cannot use a SpatRaster as a row index")
# }
# if (inherits(value, "SpatRaster")) {
# x <- mask(x, i, maskvalues=TRUE)
# cover(x, value)
# } else {
# if (NCOL(value) > 1) {
# error(" [", "cannot use a data.frame with multiple columns")
# }
# value <- unlist(value)
# if (length(value) == 1) {
# mask(x, i, maskvalues=TRUE, updatevalue=value[1])
# } else {
# i <- as.logical(values(i))
# i[is.na(i)] <- TRUE
# i <- which(i)
# x[i] <- value
# x
# }
# }
# }
# )
# setReplaceMethod("[", c("SpatRaster", "SpatVector", "missing"),
# function(x, i, j, value) {
# theCall <- sys.call(-1)
# narg <- length(theCall)-length(match.call(call=sys.call(-1)))
# if (narg > 0) { # row
# error("`[`", "you cannot use a SpatVector as a row index")
# }
# if (length(value) > 1) {
# value <- rep_len(value, length.out=length(x))
# }
# rasterize(i, x, field=value, update=TRUE)
# }
# ) terra/R/draw.R 0000644 0001762 0000144 00000004503 14732341311 012651 0 ustar ligges users
RS_locator <- function(n, type, id=FALSE, pch=20, ...) {
# locator that also works in RStudio
# Berry Boessenkool
# https://stackoverflow.com/a/65147220/635245
on.exit(return(cbind(x, y)))
x <- y <- NULL
for (i in seq_len(n)) {
p <- graphics::locator(1)
if (is.null(p)) break # ESC
x <- c(x, p$x)
y <- c(y, p$y)
points(x, y, type=type, pch=pch, ...)
if (id) {
text(p$x, p$y, labels=i, pos=4, ...)
}
}
}
.drawPol <- function(n=1000, id=FALSE, ...) {
#xy <- graphics::locator(n=1000, type="l", col=col, lwd=lwd, ...)
#xy <- cbind(xy$x, xy$y)
xy <- RS_locator(n, "l", id=id, ...)
xy <- rbind(xy, xy[1,])
graphics::lines(xy[(length(xy[,1])-1):length(xy[,1]),], ...)
g <- cbind(1,1,xy,0)
vect(g, "polygons")
}
.drawLin <- function(n=1000, ...) {
#xy <- graphics::locator(n=1000, type="l", col=col, lwd=lwd, ...)
#xy <- cbind(xy$x, xy$y)
xy <- RS_locator(n, "l", ...)
g <- cbind(1,1,xy)
vect(g, "lines")
}
.drawPts <- function(n=1000, ...) {
#xy <- graphics::locator(n=1000, type="p", col=col, lwd=lwd, ...)
#xy <- cbind(xy$x, xy$y)
xy <- RS_locator(n, "p", ...)
g <- cbind(1:nrow(xy), 1, xy)
vect(g, "points")
}
.drawExt <- function(...) {
loc1 <- graphics::locator(n=1, type="p", pch="+", ...)
loc2 <- graphics::locator(n=1, type="p", pch="+", ...)
loc <- rbind(unlist(loc1), unlist(loc2))
e <- c(min(loc[,'x']), max(loc[,'x']), min(loc[,'y']), max(loc[,'y']))
if (e[1] == e[2]) {
e[1] <- e[1] - 0.0000001
e[2] <- e[2] + 0.0000001
}
if (e[3] == e[4]) {
e[3] <- e[3] - 0.0000001
e[4] <- e[4] + 0.0000001
}
p <- rbind(c(e[1], e[3]), c(e[1], e[4]), c(e[2], e[4]), c(e[2], e[3]), c(e[1], e[3]) )
graphics::lines(p, ...)
return(ext(e))
}
setMethod("draw", signature(x="character"),
function(x="extent", col="red", lwd=2, id=FALSE, n=1000, xpd=TRUE, ...){
RStudio_warning()
x <- match.arg(tolower(x), c("extent", "polygon", "lines", "points"))
if (x == "extent") {
.drawExt(col=col, lwd=lwd, xpd=xpd, ...)
} else if (x == "polygon") {
.drawPol(n, col=col, lwd=lwd, id=id, xpd=xpd, ...)
} else if (x == "lines") {
.drawLin(n, col=col, lwd=lwd, id=id, xpd=xpd, ...)
} else if (x == "points" || x == "multipoints" ) {
.drawPts(n, col=col, id=id, xpd=xpd, ...)
}
}
)
setMethod("draw", signature(x="missing"),
function(x="extent", ...){
RStudio_warning()
draw("extent", ...)
}
)
terra/R/plotExtent.R 0000644 0001762 0000144 00000001652 14536376240 014077 0 ustar ligges users # Author: Robert J. Hijmans
# Date : July 2019
# Version 1.0
# License GPL v3
setMethod("lines", signature(x="SpatExtent"),
function(x, col="black", alpha=1, ...) {
e <- as.vector(x)
p <- rbind(c(e[1],e[3]), c(e[1],e[4]), c(e[2],e[4]), c(e[2],e[3]), c(e[1],e[3]))
col <- .getCols(1, col, alpha)
graphics::lines(p, col=col, ...)
}
)
setMethod("polys", signature(x="SpatExtent"),
function(x, col="black", alpha=1, ...) {
polys(as.polygons(x), col=col, alpha=alpha, ...)
}
)
setMethod("plot", signature(x="SpatExtent", y="missing"),
function(x, ...) {
if (!is.valid(x)) {
error("plot", "invalid SpatExtent")
}
plot(as.polygons(x), ...)
}
)
setMethod("points", signature(x="SpatExtent"),
function(x, col="black", alpha=1, ...) {
e <- as.vector(x)
p <- rbind(c(e[1],e[3]), c(e[1],e[4]), c(e[2],e[4]), c(e[2],e[3]), c(e[1],e[3]))
col <- .getCols(4, col, alpha)
graphics::points(p, col=col, ...)
}
)
terra/R/subset.R 0000644 0001762 0000144 00000015031 14727110511 013217 0 ustar ligges users # Authors: Robert J. Hijmans
# Date : October 2018
# Version 1.0
# License GPL v3
positive_indices <- function(i, n, na.rm=TRUE, caller="`[`") {
i <- stats::na.omit(i)
if (!is.logical(i)) {
stopifnot(is.numeric(i))
if (!(all(i <= 0) || all(i >= 0))) {
error(caller, "you cannot mix positive and negative indices")
}
}
i <- (1:n)[i]
if (na.rm) {
i[!is.na(i)]
} else {
i
}
}
setMethod("subset", signature(x="SpatRaster"),
function(x, subset, negate=FALSE, NSE=FALSE, filename="", overwrite=FALSE, ...) {
if (NSE) {
subset <- if (missing(subset)) {
1:nlyr(x)
} else {
nl <- as.list(seq_along(names(x)))
names(nl) <- nms <- names(x)
v <- eval(substitute(subset), nl, parent.frame())
if (!inherits(substitute(subset), "character")) {
if (sum(nms %in% nms[v]) > length(v)) {
error("subset", "you cannot select a layer with a name that is not unique")
}
}
v
}
}
if (is.character(subset)) {
nms <- names(x)
if (!all(subset %in% nms)) {
error("subset", "invalid name(s)")
}
if (sum(nms %in% subset) > length(subset)) {
error("subset", "you cannot select a layer with a name that is not unique")
}
subset <- match(subset, nms)
}
if (any(is.na(subset))) {
error("subset", "undefined layer(s) selected")
}
if (negate) subset = -subset
subset <- positive_indices(subset, nlyr(x), TRUE, "subset")
opt <- spatOptions(filename, overwrite, ...)
x@pntr <- x@pntr$subset(subset-1, opt)
messages(x, "subset")
}
)
## exact matching
setMethod("$", "SpatRaster",
function(x, name) {
if ((nlyr(x) == 1) && is.factor(x)) {
factnms <- names(cats(x)[[1]])
i <- match(name, factnms[-1])
if (!is.na(i)) {
activeCat(x) <- i
return(x)
}
}
subset(x, name, NSE=FALSE)
}
)
setMethod("[[", c("SpatRaster", "character","missing"),
function(x, i, j) {
subset(x, i, NSE=FALSE)
})
setMethod("[[", c("SpatRaster", "logical", "missing"),
function(x, i, j) {
subset(x, which(i), NSE=FALSE)
})
setMethod("[[", c("SpatRaster", "numeric", "missing"),
function(x, i, j) {
subset(x, i, NSE=FALSE)
})
setMethod("[[", c("SpatRaster", "ANY", "missing"),
function(x, i, j) {
i <- as.vector(unlist(i))
x[[i]]
})
setMethod("subset", signature(x="SpatVector"),
function(x, subset, select, drop=FALSE, NSE=FALSE) {
if (NSE) {
d <- as.list(x)
# from the subset method
r <- if (missing(subset)) {
TRUE
} else {
e <- substitute(subset)
# r <- eval(e, d, parent.frame())
# for #1600
r <- eval(e, d, globalenv())
if (!is.logical(r)) error("subset", "argument 'subset' must be logical")
r & !is.na(r)
}
v <- if (missing(select)) {
TRUE
} else {
nl <- as.list(seq_along(d))
names(nl) <- names(d)
# eval(substitute(select), nl, parent.frame())
eval(substitute(select), nl, globalenv())
}
x <- x[r, v, drop=drop]
} else {
if (missing(select)) {
x <- x[which(as.vector(subset)), drop=drop]
} else {
x <- x[which(as.vector(subset)), select, drop=drop]
}
}
#g <- gc()
x
}
)
.subset_cols <- function(x, subset, drop=FALSE) {
if (is.character(subset)) {
i <- stats::na.omit(match(subset, names(x)))
if (length(i)==0) {
error("subset", "no valid variable name found")
} else if (length(i) < length(subset)) {
warn("subset", "invalid variable name(s) excluded")
}
} else {
i <- positive_indices(subset, ncol(x), TRUE, "subset")
if (length(i)==0) {
i <- 0
}
}
x@pntr <- x@pntr$subset_cols(i-1)
x <- messages(x, "subset")
if (drop) { # drop geometry
.getSpatDF(x@pntr$df)
} else {
x
}
}
setMethod("[", c("SpatVector", "numeric", "missing"),
function(x, i, j, ... , drop=FALSE) {
i <- positive_indices(i, nrow(x), TRUE, "`[`")
x@pntr <- x@pntr$subset_rows(i-1)
x <- messages(x, "[")
if (drop) {
as.data.frame(x)
} else {
x
}
})
setMethod("[", c("SpatVector", "numeric", "logical"),
function(x, i, j, drop=FALSE) {
j <- which(rep_len(j, ncol(x)))
x[i, j, drop=drop]
})
setMethod("[", c("SpatVector", "logical", "missing"),
function(x, i, j, drop=FALSE) {
i <- which(rep_len(i, nrow(x)))
x@pntr <- x@pntr$subset_rows(i-1)
x <- messages(x, "[")
if (drop) {
as.data.frame(x)
} else {
x
}
})
setMethod("[", c("SpatVector", "numeric", "numeric"),
function(x, i, j, drop=FALSE) {
i <- positive_indices(i, nrow(x), TRUE, "`[`")
j <- positive_indices(j, ncol(x), TRUE, "`[`")
p <- x@pntr$subset_rows(i-1)
x@pntr <- p$subset_cols(j-1)
x <- messages(x, "'['")
if (drop) {
as.data.frame(x)
} else {
x
}
})
setMethod("[", c("SpatVector", "missing", "numeric"),
function(x, i, j, drop=FALSE) {
j <- positive_indices(j, ncol(x), TRUE, "`[`")
x@pntr <- x@pntr$subset_cols(j-1)
x <- messages(x, "[")
if (drop) {
as.data.frame(x)
} else {
x
}
})
setMethod("[", c("SpatVector", "missing", "character"),
function(x, i, j, drop=FALSE) {
if (j[1] == "") {
jj <- 0
} else {
jj <- match(j, names(x))
if (any(is.na(jj))) {
mis <- paste(j[is.na(jj)], collapse=", ")
error(" x[,j] ", paste("name(s) not in x:", mis))
}
if (length(jj) == 0) {
jj <- 0
}
}
x[,jj,drop=drop]
})
setMethod("[", c("SpatVector", "missing", "logical"),
function(x, i, j, drop=FALSE) {
j <- which(rep_len(j, ncol(x)))
x[,j,drop=drop]
})
setMethod("[", c("SpatVector", "numeric", "character"),
function(x, i, j, drop=FALSE) {
j <- stats::na.omit(match(j, names(x)))
if (length(j) == 0) j <- 0
x <- x[i,j,drop=drop]
})
setMethod("[", c("SpatVector", "logical", "character"),
function(x, i, j, drop=FALSE) {
i <- which(rep_len(i, nrow(x)))
x[i,j,drop=drop]
})
setMethod("[", c("SpatVector", "logical", "numeric"),
function(x, i, j, drop=FALSE) {
i <- which(rep_len(i, nrow(x)))
x[i,j,drop=drop]
})
setMethod("[", c("SpatVector", "logical", "logical"),
function(x, i, j, drop=FALSE) {
i <- which(rep_len(i, nrow(x)))
j <- which(rep_len(j, ncol(x)))
x[i,j,drop=drop]
})
setMethod("[", c("SpatVector", "missing", "missing"),
function(x, i, j, drop=FALSE) {
if (drop) {
values(x)
} else {
x
}
})
setMethod("[", c("SpatVector", "matrix", "missing"),
function(x, i, j, drop=FALSE) {
if (ncol(i) > 1) warn("`[`", "using the first column of i to subset x")
x[i[,1]]
})
setMethod("[", c("SpatVector", "data.frame", "missing"),
function(x, i, j, drop=FALSE) {
if (ncol(i) > 1) warn("`[`", "using the first column of i to subset x")
x[i[,1]]
})
setMethod("[", c("SpatVector", "data.frame", "ANY"),
function(x, i, j, drop=FALSE) {
x <- x[i[,1], j]
})
setMethod("[", c("SpatVector", "character", "missing"),
function(x, i, j, ... , drop=FALSE) {
x[, i]
})
terra/R/replace_layer.R 0000644 0001762 0000144 00000006045 14536376240 014541 0 ustar ligges users # Author: Robert J. Hijmans
# Date: October 2018
# Version 1.0
# License GPL v3
.rast_replace <- function(x, name, value, caller="$<-") {
if (inherits(value, "SpatRaster")) {
value <- value[[1]]
names(value) <- name
} else if (!is.null(value)) {
y <- rast(x, nlyrs=1)
test <- try(values(y) <- value, silent=TRUE)
if (inherits(test, "try-error")) {
error(caller, "the replacement value is not valid")
}
value <- y
names(value) <- name
}
i <- which(name == names(x))[1]
if (is.null(value)) {
if (is.na(i)) {
return(x)
} else {
return(subset(x, -i, NSE=FALSE))
}
}
if (is.na(i)) {
if (hasValues(x)) {
c(x, value)
} else if (hasValues(value)) {
value
} else {
c(x, value)
}
} else if (nlyr(x) == 1) {
value$deepcopy()
} else if (i == 1) {
c(value, x[[2:nlyr(x)]])
} else if (i == nlyr(x)) {
c(x[[1:(nlyr(x)-1)]], value)
} else {
c(x[[1:(i-1)]], value, x[[(i+1):nlyr(x)]])
}
}
setMethod("$<-", "SpatRaster",
function(x, name, value) {
.rast_replace(x, name, value, "`$<-`")
}
)
setReplaceMethod("[[", c("SpatRaster", "character"),
function(x, i, value) {
if (inherits(value, "numeric")) {
r <- rast(x, nlyr=length(i))
value <- init(r, value)
names(value) <- i
} else if (inherits(value, "SpatRaster")) {
if (nlyr(value) != length(i)) {
error("`[[`", "length of names must be equal to the number of layers")
}
names(value) <- i
} else if (length(i) > 1) {
if (NCOL(value) > 1) {
value <- as.list(data.frame(value))
} else {
stopifnot(length(i) == length(value))
}
} else if (!is.list(value)) {
value <- list(value)
}
for (k in 1:length(i)) {
x <- .rast_replace(x, i[k], value[[k]], "`[[<-`")
# eval(parse(text = paste0("x$", i[k], " <- value[[k]]")))
}
x
}
)
setReplaceMethod("[[", c("SpatRaster", "numeric"),
function(x, i, value) {
if (inherits(value, "numeric")) {
r <- rast(x, nlyr=length(i))
value <- init(r, value)
} else if (!inherits(value, "SpatRaster")) {
error("`[[<-`", "Expected a SpatRaster or numeric as replacement value")
}
if (nlyr(value) < length(i)) {
if (nlyr(value) > 1) {
j <- rep_len(1:nlyr(value), length(i))
value <- value[[j]]
}
} else if (nlyr(value) > length(i)) {
error("`[[`", "length of indices must be <= the number of layers")
}
if (any(i<1) | any(i > nlyr(x))) {
error("`[[`", "indices must be between 1 and the number of layers")
}
if (nlyr(x) == 1) {
compareGeom(x, value, crs=FALSE, warncrs=TRUE)
return(value)
}
if (nlyr(value) == 1) {
for (k in 1:length(i)) {
if (i[k] == 1) {
x <- c(value, x[[2:nlyr(x)]])
} else if (i[k] == nlyr(x)) {
x <- c(x[[1:(nlyr(x)-1)]], value)
} else {
x <- c(x[[1:(i[k]-1)]], value, x[[(i[k]+1):nlyr(x)]])
}
}
} else {
for (k in 1:length(i)) {
if (i[k] == 1) {
x <- c(value[[k]], x[[2:nlyr(x)]])
} else if (i[k] == nlyr(x)) {
x <- c(x[[1:(nlyr(x)-1)]], value[[k]])
} else {
x <- c(x[[1:(i[k]-1)]], value[[k]], x[[(i[k]+1):nlyr(x)]])
}
}
}
#g <- gc()
x
}
)
terra/R/select.R 0000644 0001762 0000144 00000001475 14536376240 013213 0 ustar ligges users # Author: Robert J. Hijmans
# Date : December 2011
# Version 1.0
# License GPL v3
setMethod("sel", signature(x="SpatRaster"),
function(x, ...) {
e <- draw(...)
int <- intersect(e, ext(x))
if (is.null(int)) {
x <- NULL
} else {
x <- crop(x, e)
}
x
}
)
setMethod("sel", signature(x="SpatVector"),
function(x, use="rec", show=TRUE, col="cyan", draw=TRUE, ...) {
use <- substr(tolower(use), 1, 3)
use <- match.arg(use, c("rec", "pol"))
scol <- ifelse(draw, "red", NA)
if (use == "rec") {
e <- draw(col=scol)
# e <- as.polygons(e)
} else {
e <- draw("pol", col=scol)
}
i <- is.related(x, e, "intersects")
x <- x[i, ]
if (show) {
if (geomtype(x) == "points" || geomtype(x) == "multipoints") {
points(x, col=col, ...)
} else {
lines(x, col=col, ...)
}
}
x
}
)
terra/R/focalMat.R 0000644 0001762 0000144 00000003273 14734631337 013461 0 ustar ligges users # Author: Robert J. Hijmans
# Date : June 2013
# Version 1.0
# License GPL v3
.circular.weight <- function(rs, d, fillNA=FALSE) {
nx <- 1 + 2 * floor(d/rs[1])
ny <- 1 + 2 * floor(d/rs[2])
m <- matrix(ncol=nx, nrow=ny)
m[ceiling(ny/2), ceiling(nx/2)] <- 1
if ((nx != 1) || (ny != 1)) {
x <- rast(m, crs="+proj=utm +zone=1 +datum=WGS84")
ext(x) <- c(xmin=0, xmax=nx*rs[1], ymin=0, ymax=ny*rs[2])
d <- as.matrix(distance(x), wide=TRUE) <= d
m <- d / sum(d)
}
if (fillNA) {
m[m <= 0] <- NA
}
m
}
.Gauss.weight <- function(rs, sigma) {
if (length(sigma) == 1) {
d <- 3 * sigma
} else {
d <- sigma[2]
sigma <- sigma[1]
}
nx <- 1 + 2 * floor(d/rs[1])
ny <- 1 + 2 * floor(d/rs[2])
m <- matrix(ncol=nx, nrow=ny)
xr <- (nx * rs[1]) / 2
yr <- (ny * rs[2]) / 2
r <- rast(m, crs="+proj=utm +zone=1 +datum=WGS84")
ext(r) <- c(xmin=-xr[1], xmax=xr[1], ymin=-yr[1], ymax=yr[1])
p <- xyFromCell(r, 1:ncell(r))^2
# according to http://en.wikipedia.org/wiki/Gaussian_filter
m <- 1/(2*pi*sigma^2) * exp(-(p[,1]+p[,2])/(2*sigma^2))
m <- matrix(m, ncol=nx, nrow=ny, byrow=TRUE)
# sum of weights should add up to 1
m / sum(m)
}
.rectangle.weight <- function(rs, d) {
d <- rep(d, length.out=2)
nx <- 1 + 2 * floor(d[1]/rs[1])
ny <- 1 + 2 * floor(d[2]/rs[2])
m <- matrix(1, ncol=nx, nrow=ny)
m / sum(m)
}
focalMat <- function(x, d, type=c("circle", "Gauss", "rectangle"), fillNA=FALSE) {
type <- match.arg(type)
x <- res(x)
if (type == 'circle') {
.circular.weight(x, d[1], fillNA)
} else if (type == 'Gauss') {
if (!length(d) %in% 1:2) {
error("focalMath", "if type=Gauss, d should be a vector of length 1 or 2")
}
.Gauss.weight(x, d)
} else {
.rectangle.weight(x, d)
}
}
terra/R/sample.R 0000644 0001762 0000144 00000060140 14753300072 013176 0 ustar ligges users
regular_exact <- function(r, size) {
size <- round(size)
stopifnot(size > 0)
if (size >= ncell(r)) {
return(xyFromCell(r, 1:ncell(r)))
}
x <- (ymax(r) - ymin(r)) / (xmax(r) - xmin(r))
if (x < 1) {
nc <- min(max(1, size * 1/(1 + 1/x)), ncol(r))
nr <- (size / nc)
} else {
nr <- min(max(1, size * 1/(1 + x)), nrow(r))
nc <- (size / nr)
}
addrow <- addcol <- 0
floor <- TRUE
if ((nc%%1) >= (nr%%1)) {
nc <- round(nc)
if ((nc * ceiling(nr)) <= size) {
nr <- ceiling(nr)
floor <- FALSE
} else {
nr <- floor(nr)
if ((nr * nc) > size) {
nc <- nc-1
}
}
d <- size - nr * nc
if (d > 0) {
if (floor) {
addcol <- d
} else {
addrow <- d
}
}
} else {
nr <- round(nr)
if ((nr * ceiling(nc)) <= size) {
nc <- ceiling(nc)
floor <- FALSE
} else {
nc <- floor(nc)
if ((nr * nc) > size) {
nr <- nr-1
}
}
d <- size - nr * nc
if (d > 0) {
if (floor) {
addcol <- d
} else {
addrow <- d
}
}
}
if (addcol > 0) {
ncs <- rep(nr, nc+1)
b <- (nr+addcol)/2
ncs[1] <- ceiling(b)
ncs[nc+1] <- floor(b)
nc=ncs
} else if (addrow > 0) {
nrs <- rep(nc, nr+1)
b <- (nc+addrow)/2
nrs[1] <- ceiling(b)
nrs[nr+1] <- floor(b)
nr=nrs
}
nnr <- length(nr)
nnc <- length(nc)
if ((nnr == 1) && (nnc == 1)) {
dx <- (xmax(r) - xmin(r)) / nc
x <- xmin(r) + dx/2 + (0:(nc-1)) * dx
dy <- (ymax(r) - ymin(r)) / nr
y <- ymin(r) + dy/2 + (0:(nr-1)) * dy
expand.grid(x=x, y=y)
} else if (nnc == 1) {
dy <- (ymax(r) - ymin(r)) / nnr
y <- ymin(r) + dy/2 + (0:(nnr-1)) * dy
out <- vector("list", nnr)
for (i in 1:nnr) {
dx <- (xmax(r) - xmin(r)) / nr[i]
x <- xmin(r) + dx/2 + (0:(nr[i]-1)) * dx
out[[i]] <- expand.grid(x=x, y=y[i])
}
do.call(rbind, out)
} else {
dx <- (xmax(r) - xmin(r)) / nnc
x <- xmin(r) + dx/2 + (0:(nnc-1)) * dx
out <- vector("list", nnc)
for (i in 1:nnc) {
dy <- (ymax(r) - ymin(r)) / nc[i]
y <- ymin(r) + dy/2 + (0:(nc[i]-1)) * dy
out[[i]] <- expand.grid(x=x[i], y=y)
}
do.call(rbind, out)
}
}
sampleWeights <- function(x, size, replace=FALSE, as.df=TRUE, as.points=FALSE, values=TRUE, cells=FALSE, xy=FALSE, ext=NULL) {
if (!is.null(ext)) {
x <- crop(x, ext)
}
x <- classify(x, cbind(-Inf, 0, NA))
res <- as.data.frame(x, cells=cells, xy=(xy | as.points))
if (!replace) {
if (size >= nrow(res)) {
i <- 1:nrow(res)
} else {
i <- sample.int(nrow(res), size, prob=res[,ncol(res)], replace=replace)
}
} else {
i <- sample.int(nrow(res), size, prob=res[,ncol(res)], replace=replace)
}
res <- res[i, , drop=FALSE]
if (!values) res <- res[ , 1:(cells + 2*(xy | as.points)), drop=FALSE]
if (as.points) {
res <- vect(res, c("x", "y"), crs=crs(x))
if (!xy) {
res$x <- NULL
res$y <- NULL
}
} #else if (as.df) {
#res <- data.frame(res)
#}
res
}
sampleStratMemory <- function(x, size, replace, lonlat, ext=NULL, weights=NULL, warn=TRUE, each) {
if (!is.null(ext)) {
xold <- rast(x)
x <- crop(x, ext)
cells <- cells(xold, ext)
if (!is.null(weights)) {
weights <- crop(weights, ext)
}
} else {
cells <- 1:ncell(x)
}
doprob <- TRUE
prob <- NULL
if (!is.null(weights)) {
if (!inherits(weights, "SpatRaster")) {
error("spatSample", "weights must be a SpatRaster")
}
if (!compareGeom(x, weights)) {
error("spatSample", "geometry of weights does not match the geometry of x")
}
v <- na.omit(cbind(cell=cells, values(x), values(weights)))
} else if (lonlat) {
v <- cbind(cell=cells, values(x), abs(cos(pi * values(init(x, "y")) / 360)))
} else {
v <- cbind(cell=cells, values(x))
doprob <- FALSE
}
v <- v[!is.na(v[,2]), ]
uv <- sort(unique(v[,2]))
nuv <- length(uv)
if (each) {
sz <- rep(size, nuv)
} else {
sz <- rep(floor(size / nuv), nuv)
d <- size - sum(sz)
i <- sample(nuv, d)
sz[i] <- sz[i] + 1
}
ys <- vector(mode="list", length=nuv)
for (i in seq_len(length(uv))) {
if (sz[i] == 0) next
vv <- v[v[,2] == uv[i], ]
if (doprob) prob <- vv[,3]
if (replace) {
s <- sample.int(nrow(vv), sz[i], prob=prob, replace=TRUE)
} else {
s <- sample.int(nrow(vv), min(sz[i], nrow(vv)), prob=prob, replace=FALSE)
}
ys[[i]] <- vv[s,-3]
}
ys <- do.call(rbind, ys)
if (warn) {
ta <- tapply(ys[,1], ys[,2], length)
sz <- sz[sz > 0]
ta <- names(ta)[ta < sz]
if (length(ta) > 0) {
warn("spatSample", 'fewer samples than requested are available for group(s): ', paste(ta, collapse=', '))
}
}
ys
}
sampleStratified <- function(x, size, replace=FALSE, as.df=TRUE, as.points=FALSE, values=TRUE, cells=TRUE, xy=FALSE, ext=NULL, warn=TRUE, exp=5, weights=NULL, exhaustive=FALSE, lonlat, each) {
if (nlyr(x) > 1) {
x <- x[[1]]
warn("spatSample", "only the first layer of x is used")
}
if (!hasValues(x)) {
error("spatSample", "x has no values")
}
if ((blocks(x, n=4)$n == 1) || exhaustive) {
res <- sampleStratMemory(x, size, replace, lonlat, ext, weights, warn, each=each)
} else {
f <- unique(x)[,1]
exp <- max(1, exp)
ss <- exp * size * length(f)
if (is.null(weights)) {
if ((!lonlat) && (ss > (0.8 * ncell(x)))) {
if (!is.null(ext)) {
x <- crop(x, ext)
}
sr <- cbind(1:ncell(x), values(x))
colnames(sr) <- c("cell", names(x))
} else {
sr <- spatSample(x, ss, "random", replace=replace, na.rm=TRUE, ext=ext, cells=TRUE, values=TRUE, warn=FALSE)
}
} else {
if (!inherits(weights, "SpatRaster")) {
error("spatSample", "weights must be a SpatRaster")
}
if (!compareGeom(x, weights)) {
error("spatSample", "geometry of weights does not match the geometry of x")
}
sr <- vector("list", length=length(f))
for (i in 1:length(f)) {
r <- x == f[i]
r <- mask(weights, r, maskvalue=TRUE, inverse=TRUE)
sr[[i]] <- sampleWeights(r, size, replace=replace, values=FALSE, cells=TRUE, ext=ext)
}
sr <- unlist(sr)
sr <- cbind(cell=sr, extract(x, sr))
}
uv <- unique(sr[,2])
nuv <- length(uv)
if (each) {
sz <- rep(size, nuv)
} else {
sz <- rep(floor(size / nuv), nuv)
d <- size - sum(sz)
i <- sample(nuv, d)
sz[i] <- sz[i] + 1
}
ys <- vector(mode="list", length=length(uv))
for (i in seq_len(length(uv))) {
y <- sr[sr[, 2] == uv[i], ,drop=FALSE]
if (nrow(y) > sz[i]) {
y <- y[sample.int(nrow(y), sz[i]), ,drop=FALSE]
}
ys[[i]] <- y
}
res <- do.call(rbind, ys)
colnames(res) <- c('cell', names(x))
if (warn) {
ta <- table(res[,2])
sz <- sz[sz > 0]
ta <- names(ta[ta < sz])
tb <- f[!(f %in% unique(res[,2]))]
tba <- c(tb, ta)
if ((length(tba) > 0)) {
warn("spatSample", "fewer samples than requested for group(s): ", paste(tba, collapse=", "))
}
}
}
if ((!xy) && (!as.points)) cells <- TRUE
if (xy) {
pts <- xyFromCell(x, res[,1])
res <- cbind(res[,1,drop=FALSE], pts, res[,2,drop=FALSE])
}
if (!values) {
res <- res[,1:(1 + 2*(xy|as.points)), drop=FALSE]
}
if (as.points) {
if (!xy) {
pts <- xyFromCell(x, res[,1])
}
res <- vect(pts, crs=crs(x), atts=data.frame(res))
} else if (as.df) {
res <- data.frame(res)
}
if (!cells) {
res <- res[,-1,drop=FALSE]
}
res
}
.seed <- function() {
sample.int(.Machine$integer.max, 1)
}
.sampleCellsMemory <- function(x, size, replace, lonlat, ext=NULL) {
if (!is.null(ext)) {
x <- crop(x, ext)
}
if (nlyr(x) > 1) {
x <- subst(anyNA(x), 1, NA)
}
if (lonlat) {
v <- cbind(cell=1:ncell(x), abs(cos(pi * values(init(x, "y")) / 360)), values(x))
v <- v[!is.na(v[,3]),]
ssize <- ifelse(replace, size, min(size, nrow(v)))
i <- sample.int(nrow(v), ssize, prob=v[,2], replace=replace)
} else {
v <- cbind(cell=1:ncell(x), values(x))
v <- v[!is.na(v[,2]),]
ssize <- ifelse(replace, size, min(size, nrow(v)))
i <- sample.int(nrow(v), ssize, replace=replace)
}
v[i,1]
}
.sampleCells <- function(x, size, method, replace, na.rm=FALSE, ext=NULL, exp=5, exact=FALSE) {
r <- rast(x)
lonlat <- is.lonlat(r, perhaps=TRUE, warn=TRUE)
if (!is.null(ext)) {
r <- crop(rast(r), ext)
}
if ((!replace) && (size >= ncell(r))) {
cells <- 1:ncell(r)
} else if (method == "random") {
if (na.rm) {
esize <- size * exp
} else {
esize <- size
}
if (na.rm && (blocks(x, n=4)$n == 1)) {
cells <- .sampleCellsMemory(x, esize, replace, lonlat, ext)
} else if (lonlat) {
m <- ifelse(replace, 1.5, 2)
n <- m * esize
y <- yFromRow(r, 1:nrow(r))
rows <- sample.int(nrow(r), n, replace=TRUE, prob=abs(cos(pi*y/180)))
cols <- sample.int(ncol(r), n, replace=TRUE)
cells <- cellFromRowCol(r, rows, cols)
if (!replace) {
cells <- unique(cells)
}
} else {
if (!replace) esize <- min(ncell(r), esize)
cells <- sample.int(ncell(r), esize, replace=replace)
}
} else { # regular
if (TRUE) {
if (exact) {
xy <- regular_exact(r, size)
} else {
xy <- spatSample(ext(r), size, method, lonlat, FALSE)
}
cells <- cellFromXY(r, xy)
} else {
if (lonlat) {
#ratio <- ncol(r)/nrow(r)
e <- ext(r)
r1 = e$xmax - e$xmin;
r2 = e$ymax - e$ymin;
halfy = e$ymin + r2/2;
# beware that -180 is the same as 180; and that latitude can only go from -90:90 therefore:
dx = distance(cbind(e$xmin, halfy), cbind(e$xmin + 1, halfy), TRUE, TRUE) * min(180.0, r1);
dy = distance(cbind(0, e$ymin), cbind(0, e$ymax), TRUE, TRUE);
ratio = dy/dx;
n <- sqrt(size)
#nx <- max(1, (round(n*ratio)))
#ny <- max(1, (round(n/ratio)))
nx <- min(max(1, round(n/ratio)), ncol(r))
ny <- min(max(1, round(n*ratio)), nrow(r))
xi <- ncol(r) / nx
yi <- nrow(r) / ny
rows <- unique(round(seq(.5*yi, nrow(r), yi)))
w <- cos(pi*yFromRow(r, rows)/180)
w <- w * length(w)/sum(w)
xi <- xi / w
xi <- pmax(1,pmin(xi, ncol(r)))
z <- list()
# needs refinement:
global <- diff(e[1:2]) > 355
if (global) {
xi <- round(ncol(r) / round(ncol(r) / xi))
for (i in 1:length(rows)) {
if (xi[i] == 1) {
cols <- 1:ncol(r)
} else {
cols <- seq(xi[i]/2, ncol(r)-1, xi[i])
}
z[[i]] <- cbind(rows[i], cols)
}
} else {
# xi <- round(ncol(r) / (round((ncol(r) / xi))+1))
for (i in 1:length(rows)) {
cols <- seq(xi[i]/2, ncol(r), xi[i])
z[[i]] <- cbind(rows[i], cols)
}
}
z <- do.call(rbind, z)
cells <- cellFromRowCol(r, z[,1], z[,2])
} else {
f <- sqrt(size / ncell(r))
nr <- ceiling(nrow(r) * f)
nc <- ceiling(ncol(r) * f);
xstep <- ncol(r) / nc
ystep <- nrow(r) / nr
xsamp <- seq(0.5*xstep, ncol(r), xstep)
ysamp <- seq(0.5*ystep, nrow(r), ystep)
xy <- expand.grid(ysamp, xsamp)
cells <- cellFromRowCol(r, xy[,1], xy[,2])
}
}
}
if (!is.null(ext)) {
cells <- cellFromXY(x, xyFromCell(r, cells))
}
if (na.rm) {
v <- rowSums(is.na(x[cells])) == 0
cells <- cells[v]
}
if (method == "random") {
if (length(cells) > size) {
cells <- cells[1:size]
}
}
cells
}
set_factors <- function(x, ff, cts, asdf) {
if (!asdf) return(x)
if (any(ff)) {
x <- data.frame(x)
for (i in which(ff)) {
ct <- cts[[i]]
m <- match(x[[i]], ct[,1])
if (!inherits(ct[[2]], "numeric")) {
x[[i]] <- factor(ct[m,2], levels=unique(ct[[2]]))
} else {
x[[i]] <- ct[m,2]
}
}
}
data.frame(x)
}
.sampleCellsExhaustive <- function(x, size, replace, ext=NULL, weights=NULL, warn=TRUE) {
if (!is.null(ext)) {
x <- crop(x, ext)
}
rx <- rast(x)
x <- cells(x)
if (length(x) < size) {
if (!replace) {
warn("spatSample", "fewer samples than requested are available")
return(x)
}
size <- length(x)
}
if (!is.null(weights)) {
if (!inherits(weights, "SpatRaster")) {
error("spatSample", "weights must be a SpatRaster")
}
weights <- weights[[1]]
if (!is.null(ext)) {
weights <- crop(weights, ext)
}
if (!compareGeom(x, weights)) {
error("spatSample", "geometry of weights does not match the geometry of x")
}
weights <- weights[x]
s <- sample.int(x, size, prob=weights, replace=replace)
} else if (is.lonlat(rx)) {
y <- xyFromCell(rx, x)[,2]
weights <- abs(cos(pi * y / 360))
s <- sample(x, size, prob=weights, replace=replace)
} else {
s <- sample(x, size, replace=replace)
}
s
}
sampleRaster <- function(x, size, method, replace, ext=NULL, warn, overview=FALSE) {
# hadWin <- hasWin <- FALSE
if (!is.null(ext)) {
# hasWin <- TRUE
# hadWin <- window(x)
# oldWin <- ext(x)
w <- intersect(ext(x), ext(ext))
if (is.null(w)) {
error("sampleRaster", "x and ext do not intersect")
}
x <- deepcopy(x)
window(x) <- w
}
if (method == "regular") {
if (length(size) > 1) {
x@pntr <- x@pntr$sampleRowColRaster(size[1], size[2], warn[1])
} else {
x@pntr <- x@pntr$sampleRegularRaster(size, overview)
}
} else if (method == "random") {
x@pntr <- x@pntr$sampleRandomRaster(size, replace, .seed())
} else {
error("spatSample", "method must be 'regular' or 'random' if as.raster=TRUE")
}
# if (hasWin) {
# window(x) <- NULL
# if (any(hadWin)) {
# window(x) <- oldWin
# }
# }
messages(x, "spatSample")
}
setMethod("spatSample", signature(x="SpatRaster"),
function(x, size, method="random", replace=FALSE, na.rm=FALSE, as.raster=FALSE, as.df=TRUE, as.points=FALSE, values=TRUE, cells=FALSE, xy=FALSE, ext=NULL, warn=TRUE, weights=NULL, exp=5, exhaustive=FALSE, exact=FALSE, each=TRUE) {
if (method == "display") return(sampleRaster(x, size, "regular", FALSE, ext=ext, warn=FALSE, overview=TRUE))
if (!as.points) {
if (!(values || cells || xy)) {
error("spatSample", "at least one of 'values', 'cells', or 'xy' must be TRUE; or 'as.points' must be TRUE")
}
}
exp <- max(c(1, exp), na.rm=TRUE)
size <- round(size)
if (isTRUE(any(size < 1)) || isTRUE(any(is.na(size)))) {
error("spatSample", "sample size must be a positive integer")
}
method <- match.arg(tolower(method), c("random", "regular", "stratified", "weights"))
if ((!replace) && (method != "regular")) {
if (length(size) > 1) {
error("spatSample", "sample size must be a single number")
}
if (warn && (size > ncell(x))) {
warn("spatSample", "requested sample size is larger than the number of cells")
size <- ncell(x)
}
}
if (as.raster) return(sampleRaster(x, size, method, replace, ext, warn))
lonlat <- is.lonlat(x, perhaps=TRUE, warn=FALSE)
if (lonlat) exact <- FALSE
if (method == "stratified") {
return( sampleStratified(x, size, replace=replace, as.df=as.df, as.points=as.points, cells=cells, values=values, xy=xy, ext=ext, warn=warn, exp=exp, weights=weights, exhaustive=exhaustive, lonlat=lonlat, each=each) )
} else if (!is.null(weights)) {
error("spatSample", "argument weights is only used when method='stratified'")
}
if (method == "weights") {
if (nlyr(x) > 1) {
x <- x[[1]]
warn("spatSample", "only the first layer of x is used")
}
if (!hasValues(x)) {
error("spatSample", "x has no values")
}
out <- try(sampleWeights(x, size, replace=replace, as.df=as.df, values=values, as.points=as.points, cells=cells, xy=xy, ext=ext) )
if (inherits(out, "try-error")) {
error("spatSample", "weighted sample failed. Perhaps the data set is too big")
}
return (out)
}
ff <- is.factor(x)
lv <- levels(x)
if (cells || xy || as.points) {
size <- size[1]
if (exhaustive && (method=="random") && na.rm) {
cnrs <- .sampleCellsExhaustive(x, size, replace, ext, weights=NULL, warn=FALSE)
} else {
cnrs <- .sampleCells(x, size, method, replace, na.rm, ext, exp=exp, exact=exact)
}
if (method == "random") {
if ((length(cnrs) < size) && warn) {
warn("spatSample", "fewer cells returned than requested")
} else if (length(cnrs) > size) {
cnrs <- cnrs[1:size]
}
}
out <- NULL
if (cells) {
out <- matrix(cnrs, ncol=1)
colnames(out) <- "cell"
}
if (xy) {
out <- cbind(out, xyFromCell(x, cnrs))
}
if (values && hasValues(x)) {
e <- extract(x, cnrs)
if (is.null(out)) {
out <- e
} else {
out <- cbind(out, e)
}
}
if (as.points) {
if (xy) {
out <- data.frame(out)
out <- vect(out, geom=c("x", "y"), crs=crs(x))
} else {
xy <- xyFromCell(x, cnrs)
# xy is a matrix, no geom argument
v <- vect(xy, crs=crs(x))
values(v) <- out
return(v)
}
}
return(out)
}
if (!hasValues(x)) {
error("spatSample", "SpatRaster has no values")
}
#method <- tolower(method)
#stopifnot(method %in% c("random", "regular"))
if (!is.null(ext)) x <- crop(x, ext)
if (method == "regular") {
if (exact && (length(size) == 1)) {
xy <- regular_exact(x, size)
v <- extract(x, xy, ID=FALSE)
} else {
opt <- spatOptions()
if (length(size) > 1) {
v <- x@pntr$sampleRowColValues(size[1], size[2], opt)
} else {
v <- x@pntr$sampleRegularValues(size, opt)
}
x <- messages(x, "spatSample")
if (length(v) > 0) {
v <- do.call(cbind, v)
colnames(v) <- names(x)
}
v <- set_factors(v, ff, lv, as.df)
}
return(v)
} else { # random
size <- size[1]
if (exhaustive && na.rm) {
cnrs <- .sampleCellsExhaustive(x, size, replace, ext, weights=NULL, warn=FALSE)
out <- x[cnrs]
} else {
#v <- x@pntr$sampleRandomValues(size, replace, seed)
if (size > 0.75 * ncell(x)) {
if (na.rm) {
out <- stats::na.omit(values(x))
attr(out, "na.action") <- NULL
if (nrow(out) < size) {
if (replace) {
out <- out[sample.int(nrow(out), size, replace=TRUE), ,drop=FALSE]
} else {
warn("spatSample", "more non-NA cells requested than available")
}
} else {
out <- out[sample.int(nrow(out), size), ,drop=FALSE]
}
} else {
out <- values(x)
out <- out[sample.int(nrow(out), size, replace=replace), ,drop=FALSE]
}
out <- set_factors(out, ff, lv, as.df)
return(out)
}
if (na.rm) {
scells <- NULL
ssize <- size*2
for (i in 1:10) {
scells <- c(scells, .sampleCells(x, ssize, method, replace, na.rm, exact=exact))
if ((i>1) && (!replace)) {
scells <- unique(scells)
}
out <- extractCells(x, scells, raw=!as.df)
out <- stats::na.omit(out)
if (nrow(out) >= size) {
out <- out[1:size, ,drop=FALSE]
attr(out, "na.action") <- NULL
rownames(out) <- NULL
break
}
}
} else {
scells <- .sampleCells(x, size, method, replace, exact=exact)
out <- extractCells(x, scells, raw=!as.df)
}
if (NROW(out) < size) {
if (warn) warn("spatSample", "fewer values returned than requested")
} else if (is.null(dim(out))) {
out = out[1:size]
} else {
out = out[1:size, ,drop=FALSE]
}
#out <- set_factors(out, ff, lv, as.df)
return(out)
}
}
}
)
setMethod("spatSample", signature(x="SpatExtent"),
function(x, size, method="random", lonlat, as.points=FALSE, exact=FALSE) {
if (missing(lonlat)) {
error("spatSample", "provide a lonlat argument")
}
if (lonlat) {
stopifnot(x$ymax <= 90 || x$ymin >= -90)
}
method <- match.arg(method, c("regular", "random"))
size <- round(size)
stopifnot(size > 0)
if (method=="random") {
s <- x@pntr$sampleRandom(size, lonlat, .seed())
} else if (exact) {
s <- regular_exact(x, size)
colnames(s) <- c("x", "y")
if (as.points) {
s <- vect(s)
}
return(s)
} else {
s <- x@pntr$sampleRegular(size, lonlat)
}
s <- do.call(cbind, s)
colnames(s) <- c("x", "y")
if (as.points) {
s <- vect(s)
}
s
}
)
.grid_sample <- function(xy, n=1, r, chess="") {
cell <- cellFromXY(r, xy)
uc <- unique(stats::na.omit(cell))
chess <- trimws(chess)
if (chess != "") {
chess <- match.arg(tolower(chess), c("white", "black"))
nc <- ncol(r)
if (nc %% 2 == 1) {
if (chess=="white") {
tf <- 1:ceiling(ncell(r)/2) * 2 - 1
} else {
tf <- 1:ceiling((ncell(r)-1)/2) * 2
}
} else {
nr <- nrow(r)
row1 <- 1:(ceiling(nr / 2)) * 2 - 1
row2 <- row1 + 1
row2 <- row2[row2 <= nr]
if (chess=="white") {
col1 <- 1:(ceiling(nc / 2)) * 2 - 1
col2 <- col1 + 1
col2 <- col2[col2 <= nc]
} else {
col1 <- 1:(ceiling(nc / 2)) * 2
col2 <- col1 - 1
col1 <- col1[col1 <= nc]
}
cells1 <- cellFromRowColCombine(r, row1, col1)
cells2 <- cellFromRowColCombine(r, row2, col2)
tf <- c(cells1, cells2)
}
uc <- uc[uc %in% tf]
}
cell <- cellFromXY(r, xy)
cell <- cbind(1:nrow(xy), cell, stats::runif(nrow(xy)))
cell <- stats::na.omit(cell)
cell <- cell[order(cell[,3]), ]
sel <- list()
for (i in 1:length(uc)) {
ss <- subset(cell, cell[,2] == uc[i])
sel[[i]] <- ss[1:min(n, nrow(ss)), 1]
}
unlist(sel)
}
#coordinates <- function(x) {
# do.call(cbind, x@pntr$coordinates())
#}
get_field_name <- function(x, nms, sender="") {
x <- x[1]
if (is.numeric(x)) {
x <- round(x)
if (x > 0 && x <= length(nms)) {
x = nms[x]
} else {
error(sender, "invalid index. there are ", length(nms), " columns")
}
} else if (is.character(x)) {
if (!(x %in% nms)) {
error(sender, "invalid name")
}
}
x
}
setMethod("spatSample", signature(x="SpatVector"),
function(x, size, method="random", strata=NULL, chess="") {
method = match.arg(tolower(method), c("regular", "random"))
size <- round(size)
stopifnot(size > 0)
gtype <- geomtype(x)
if (gtype == "polygons") {
if (!is.null(strata)) {
if (length(strata) == 1) {
if (is.character(strata)) {
stopifnot(strata %in% names(x))
} else {
stopifnot((strata > 0) && (strata < ncol(x)))
}
strata <- x[[strata, drop=TRUE]]
} else if (length(strata) != length(x)) {
stop("length of strata must be 1 or length(x)")
}
s <- stats::na.omit(unique(strata))
n <- length(size)
if (n==1) {
n <- rep_len(n, length(s))
} else if (length(s) != n) {
stop("length of strata must be 1 or length(na.omit(unique(strata)))")
}
r <- lapply(s, function(s) {
spatSample(x[strata == s, ], size, method, NULL, "")
})
r <- do.call(rbind, r)
return(r)
}
out <- vect()
if (length(size) == 1) {
out@pntr <- x@pntr$sample(size, method[1], .seed())
} else {
out@pntr <- x@pntr$sampleGeom(size, method[1], .seed())
}
messages(x, "spatSample")
return(messages(out, "spatSample"))
} else if (grepl(gtype, "points")) {
if (!is.null(strata)) {
if (inherits(strata, "SpatRaster")) {
xy <- crds(x)
i <- .grid_sample(xy, size[1], rast(strata), chess)
return(x[i,])
} else {
error("spatSample", "not yet implemented for these strata")
}
} else {
error("spatSample", "use `sample` to sample (point) geometries")
}
} else {
error("spatSample", "not yet implemented for lines")
}
}
)
#spatSample(disagg(as.points(v)), 1, "stratified", strata=r, chess="")
# setMethod("spatSample", signature(x="SpatExtent"),
# function(x, size, method="regular", lonlat, ...) {
# if (missing(lonlat)) {
# stop("provide a lonlat argument")
# }
# method = match.arg(method, c("regular", "random"))
# size <- round(size)
# stopifnot(size > 0)
# e <- as.vector(x)
# if (method=="random") {
# if (lonlat) {
# d <- round((e[4] - e[3]) * 1000);
# dx <- (e[4] - e[3]) / (2 * d)
# r <- unique(seq(e[3], e[4], length.out=d))
# w <- abs(cos(pi*r/180))
# x <- sample.int(length(r), size, prob=w, replace=TRUE)
# lat <- r[x] + stats::runif(size, -dx, dx)
# lon <- stats::runif(size, min = e[1], max = e[2])
# vect(cbind(lon,lat), crs="+proj=lonlat +datum=WGS84")
# } else {
# x <- stats::runif(size, min = e[1], max = e[2])
# y <- stats::runif(size, min = e[3], max = e[4])
# vect(cbind(x, y))
# }
# } else {
# r <- range(x)
# ratio <- 0.5 * r[1]/r[2]
# n <- sqrt(size)
# nx <- max(1, (round(n*ratio)))
# ny <- max(1, (round(n/ratio)))
# xi <- r[1] / nx
# yi <- r[2] / ny
# if (lonlat) {
# lat <- seq(e[3]+0.5*yi, e[4], yi)
# w <- cos(pi*lat/180)
# w <- w * length(w)/sum(w)
# xi <- xi / w
# xi <- pmin(xi, 180)
# z <- list()
# #off <- stats::runif(1)
# for (i in 1:length(lat)) {
# z[[i]] <- cbind(seq(e[1]+0.5*xi[i], e[2], xi[i]), lat[i])
# }
# z <- do.call(rbind, z)
# vect(z, crs="+proj=lonlat +datum=WGS84")
# } else {
# x <- seq(e[1]+0.5*xi, e[2], xi)
# y <- seq(e[3]+0.5*yi, e[4], yi)
# vect(cbind(rep(x, length(y)), rep(y, each=length(x))))
# }
# }
# }
# )
terra/R/hist.R 0000644 0001762 0000144 00000004327 14544575727 012714 0 ustar ligges users # Author: Robert J. Hijmans
# Date : June 2008
# Version 1.0
# License GPL v3
setMethod("hist", signature(x="SpatRaster"),
function(x, layer, maxcell=1000000, plot=TRUE, maxnl=16, main, ...) {
if (missing(layer)) {
y <- 1:nlyr(x)
} else if (is.character(layer)) {
y <- match(layer, names(x))
maxnl <- Inf
} else {
y <- layer
maxnl <- Inf
}
y <- as.integer(round(y))
y <- stats::na.omit(y)
y <- y[ y >= 1 & y <= nlyr(x) ]
nl <- length(y)
if (nl == 0) {
error("hist", "no valid layers selected")
}
if (missing(main)) {
main=names(x)
}
if (nl > 1) {
res <- list()
if (nl > maxnl) {
warn(paste("hist", "only the first", maxnl, "layers are used (see argument maxnl)"))
nl <- maxnl
y <- y[1:maxnl]
}
nc <- ceiling(sqrt(nl))
nr <- ceiling(nl / nc)
mfrow <- graphics::par("mfrow")
spots <- mfrow[1] * mfrow[2]
if (spots < nl) {
old.par <- graphics::par(no.readonly =TRUE)
on.exit(graphics::par(old.par))
graphics::par(mfrow=c(nr, nc))
}
for (i in 1:length(y)) {
res[[i]] = .hist1(x[[ y[i] ]], maxcell=maxcell, main=main[y[i]], plot=plot, ...)
}
} else if (nl==1) {
if (nlyr(x) > 1) {
x <- x[[y]]
main <- main[y]
}
res <- .hist1(x, maxcell=maxcell, main=main, plot=plot, ...)
}
if (plot) {
return(invisible(res))
} else {
return(res)
}
}
)
.hist1 <- function(x, maxcell, main, plot, ...){
stopifnot(hasValues(x))
if ( ncell(x) <= maxcell ) {
v <- stats::na.omit(values(x))
} else {
# TO DO: make a function that does this by block and combines all data into a single histogram
v <- spatSample(x, maxcell, method="regular", as.df=FALSE, as.raster=FALSE, warn=FALSE)
msg <- paste("a sample of ", round(100 * length(v) / ncell(x)), "% of the cells was used", sep="")
if (any(is.na(v))) {
v <- stats::na.omit(v)
msg <- paste(msg, " (of which ", 100 - round(100 * length(v) / maxcell ), "% was NA)", sep="")
}
warn("hist", msg)
}
if (nrow(v) == 0) {
error("hist", "all (sampled) values are NA")
}
# if (.shortDataType(x) == 'LOG') {
# v <- v * 1
# }
if (plot) {
out <- hist(v, main=main, plot=plot, ...)
} else {
out <- hist(v, plot=plot, ...)
}
out$xname <- names(x)
out
}
terra/R/lapp.R 0000644 0001762 0000144 00000023717 14746056417 012677 0 ustar ligges users # Author: Robert J. Hijmans
# Date : May 2020
# Version 1.0
# License GPL v3
.lapp_test <- function(v, fun, usenames, ...) {
# figure out the shape of the output
nms = ""
nr <- nrow(v)
if (!usenames) colnames(v) <- NULL
vtst <- try(do.call(fun, c(v, list(...))), silent=FALSE)
if (inherits(vtst, "try-error")) {
nl <- -1
msg <- "cannot use 'fun'"
}
if (length(vtst) >= nr) {
if ((length(vtst) %% nr) == 0) {
nl <- length(vtst) / nr
} else {
if (is.null(dim(vtst))) {
msg <- paste0("cannot use 'fun'. The number of values returned is not divisible by the number of input cells (returning: ", length(vtst), ", expecting :", nr, ")")
} else {
msg <- paste0("cannot use 'fun'. The number of rows returned is not divisible by the number of input cells (returning: ", nrow(vtst), ", expecting: ", nr, ")")
}
nl <- -1
}
} else {
if (is.null(dim(vtst))) {
msg <- paste0("cannot use 'fun'. The number of values returned is less than the number of input cells.\n(returning: ", length(vtst), ", expecting: ", nr, ")\nPerhaps the function is not properly vectorized")
} else {
msg <- paste("cannot use 'fun'. The number of rows returned is less than the number of input cells.\n(returning:", nrow(vtst), ", expecting:", nr, ")\nPerhaps the function is not properly vectorized")
}
nl <- -1
}
if (nl < 0) {
error("lapp", msg)
}
if (is.matrix(vtst)) {
nms <- colnames(vtst)
}
list(nl=nl, names=nms)
}
setMethod("lapp", signature(x="SpatRaster"),
function(x, fun, ..., usenames=FALSE, cores=1, filename="", overwrite=FALSE, wopt=list()) {
fun <- match.fun(fun)
dots <- list(...)
if (any(sapply(dots, function(i) inherits(i, "SpatRaster")))) {
error("lapp", "only 'x' can be a SpatRaster")
# otherwise .lapp_test may crash!
}
# if (usenames) {
# fnames <- names(formals(fun))
# i <- names(x) %in% fnames
# if (!all(i)) {
# warn("lapp", paste(paste(names(x)[!i], collapse=","), "are not used", collapse=", "))
# x <- x[[names(x) %in% fnames]]
# }
# }
doclust <- FALSE
if (inherits(cores, "cluster")) {
doclust <- TRUE
} else if (cores > 1) {
doclust <- TRUE
cores <- parallel::makeCluster(cores)
on.exit(parallel::stopCluster(cores), add=TRUE)
}
readStart(x)
on.exit(readStop(x), add=TRUE)
ncx <- ncol(x)
v <- readValues(x, round(0.51*nrow(x)), 1, 1, ncx, dataframe=TRUE)
test <- .lapp_test(v, fun, usenames, ...)
if (test$nl < 1) error("lapp", "cannot use 'fun'. The number of values returned is not divisible by the number of input cells")
out <- rast(x, nlyrs=test$nl)
if (length(test$names == test$nl)) {
if (is.null(wopt$names)) wopt$names <- test$names
}
b <- writeStart(out, filename, overwrite, sources=sources(x), wopt=wopt)
expected <- test$nl * ncx
if (doclust) {
ncores <- length(cores)
export_args(cores, ..., caller="lapp")
cfun <- function(i, ...) do.call(fun, i, ...)
parallel::clusterExport(cores, "cfun", environment())
for (i in 1:b$n) {
v <- readValues(x, b$row[i], b$nrows[i], 1, ncx, dataframe=TRUE)
if (!usenames) colnames(v) <- NULL
v <- split(v, rep(1:ncores, each=ceiling(nrow(v) / ncores))[1:nrow(v)])
v <- unlist(parallel::parLapply(cores, v, cfun, ...))
if (length(v) != (expected * b$nrows[i])) {
out <- writeStop(out)
error("lapp", "output length of fun is not correct")
}
writeValues(out, v, b$row[i], b$nrows[i])
}
} else {
for (i in 1:b$n) {
v <- readValues(x, b$row[i], b$nrows[i], 1, ncx, dataframe=TRUE)
if (!usenames) colnames(v) <- NULL
v <- do.call(fun, c(v, list(...)))
if (length(v) != (expected * b$nrows[i])) {
out <- writeStop(out)
error("lapp", "output length of fun is not correct")
}
writeValues(out, v, b$row[i], b$nrows[i])
}
}
out <- writeStop(out)
return(out)
}
)
.lapp_test_stack_call <- function(v, fun, recycle, ...) {
# figure out the shape of the output
nms <- msg <- ""
nr <- nrow(v[[1]])
if (recycle) {
v <- lapply(v, as.vector)
}
vtst <- try(do.call(fun, c(v, list(...))), silent=FALSE)
# vtst2 <- try(apply(v, fun, ...), silent=TRUE)
if (inherits(vtst, "try-error")) {
nl <- -1
msg <- "cannot use 'fun'"
}
if (length(vtst) >= nr) {
if ((length(vtst) %% nr) == 0) {
nl <- length(vtst) / nr
} else {
if (is.null(dim(vtst))) {
msg <- paste0("cannot use 'fun'. The number of values returned is not divisible by the number of input cells (returning: ", length(vtst), ", expecting :", nr, ")")
} else {
msg <- paste0("cannot use 'fun'. The number of rows returned is not divisible by the number of input cells (returning: ", nrow(vtst), ", expecting: ", nr, ")")
}
nl <- -1
}
} else {
if (is.null(dim(vtst))) {
msg <- paste0("cannot use 'fun'. The number of values returned is less than the number of input cells.\n(returning: ", length(vtst), ", expecting: ", nr, ")\nPerhaps the function is not properly vectorized.")
} else {
msg <- paste("cannot use 'fun'. The number of rows returned is less than the number of input cells.\n(returning:", nrow(vtst), ", expecting:", nr, ")\nPerhaps the function is not properly vectorized.")
}
nl <- -1
}
if (nl > 0) {
if (is.matrix(vtst)) {
nms <- colnames(vtst)
}
}
list(nl=nl, names=nms, msg=msg)
}
.lapp_test_stack_mapp <- function(v, fun, recycle, ...) {
# figure out the shape of the output
nms <- msg <- ""
nr <- nrow(v[[1]])
if (recycle) {
v <- lapply(v, as.vector)
}
v <- lapply(v, function(i) data.frame(t(i)))
vtst <- try(do.call(mapply, c(v, list(...), FUN=fun)), silent=FALSE)
if (inherits(vtst, "try-error")) {
return(list(nl=-10, names="", msg="cannot use 'fun'", trans=FALSE))
}
trans <- FALSE
if (!is.null(dim(vtst))) {
trans <- TRUE
vtst <- as.vector(t(vtst))
}
if (length(vtst) >= nr) {
if ((length(vtst) %% nr) == 0) {
nl <- length(vtst) / nr
} else {
if (is.null(dim(vtst))) {
msg <- paste0("cannot use 'fun'. The number of values returned is not divisible by the number of input cells (returning: ", length(vtst), ", expecting :", nr, ")")
} else {
msg <- paste0("cannot use 'fun'. The number of rows returned is not divisible by the number of input cells (returning: ", nrow(vtst), ", expecting: ", nr, ")")
}
nl <- -1
}
} else {
if (is.null(dim(vtst))) {
msg <- paste0("cannot use 'fun'. The number of values returned is less than the number of input cells.\n(returning: ", length(vtst), ", expecting: ", nr, ")\nPerhaps the function is not properly vectorized.")
} else {
msg <- paste("cannot use 'fun'. The number of rows returned is less than the number of input cells.\n(returning:", nrow(vtst), ", expecting:", nr, ")\nPerhaps the function is not properly vectorized.")
}
nl <- -10
}
if (nl > 0) {
if (is.matrix(vtst)) {
nms <- colnames(vtst)
}
}
list(nl=nl, names=nms, msg=msg, trans=trans)
}
setMethod("lapp", signature(x="SpatRasterDataset"),
function(x, fun, ..., usenames=FALSE, recycle=FALSE, cores=1, filename="", overwrite=FALSE, wopt=list()) {
fun <- match.fun(fun)
dots <- list(...)
if (any(sapply(dots, function(i) inherits(i, "SpatRasterDataset")))) {
error("lapp", "only 'x' can be a SpatRasterDataset")
# otherwise .lapp_test_stack fails
}
ncx <- ncol(x[1])
nrx <- nrow(x[1])
readStart(x)
on.exit(readStop(x))
nms <- names(x)
v <- lapply(1:length(x), function(i) readValues(x[i], round(0.51*nrx), 1, 1, ncx, mat=TRUE))
if (usenames) names(v) <- nms
mapp <- FALSE
trans <- FALSE
test <- .lapp_test_stack_call(v, fun, recycle, ...)
if (test$nl < 1) {
oldtst <- test
test <- .lapp_test_stack_mapp(v, fun, recycle, ...)
if (test$nl == 0) {
error("lapp", paste0(oldtst$msg, "\n", test$msg))
}
mapp <- TRUE
trans <- test$trans
}
out <- rast(x[1])
nlyr(out) <- test$nl
if (length(test$names == test$nl)) {
if (is.null(wopt$names)) wopt$names <- test$names
}
nltot <- sum(nlyr(x)) + nlyr(out)
fact <- max(4, 4 * nltot / nlyr(out))
b <- writeStart(out, filename, overwrite, sources=unlist(sources(x)), wopt=wopt, n=fact)
doclust <- FALSE
if (inherits(cores, "cluster")) {
doclust <- TRUE
} else if (cores > 1) {
doclust <- TRUE
cores <- parallel::makeCluster(cores)
on.exit(parallel::stopCluster(cores), add=TRUE)
}
if (mapp) {
if (doclust) {
warn("lapp", "no parallel method for this case")
}
for (i in 1:b$n) {
v <- readValues(x, b$row[i], b$nrows[i], 1, ncx, mat=TRUE)
if (recycle) {
v <- lapply(v, as.vector)
}
if (usenames) {
names(v) <- nms
}
v <- lapply(v, function(j) data.frame(t(j)))
v <- do.call(mapply, c(v, list(...), FUN=fun))
if (test$trans) {
v <- as.vector(t(v))
}
writeValues(out, v, b$row[i], b$nrows[i])
}
} else {
if (doclust) {
ncores <- length(cores)
export_args(cores, ..., caller="lapp")
cfun <- function(i, ...) do.call(fun, i, ...)
parallel::clusterExport(cores, "cfun", environment())
for (i in 1:b$n) {
v <- readValues(x, b$row[i], b$nrows[i], 1, ncx, mat=TRUE)
if (usenames) { names(v) <- nms } else { names(v) <- NULL }
if (recycle) {
repl <- max(sapply(v, function(j) prod(dim(j))))
v <- lapply(v, function(j) rep_len(as.vector(j), repl))
j <- split(1:length(v[[1]]), rep(1:ncores, each=ceiling(length(v[[1]]) / ncores))[1:length(v[[1]])])
v <- parallel::parLapply(cores, 1:ncores, function(x, ...) cfun(lapply(v, function(d) d[j[[x]]]), ...))
} else {
j <- split(1:nrow(v[[1]]), rep(1:ncores, each=ceiling(nrow(v[[1]]) / ncores))[1:nrow(v[[1]])])
v <- parallel::parLapply(cores, 1:ncores, function(x, ...) cfun(lapply(v, function(d) d[j[[x]], , drop=FALSE]), ...))
}
v <- unlist(v)
if (length(v) != (b$nrows[i] * test$nl * ncx)) {
out <- writeStop(out)
error("lapp", "output length of fun is not correct")
}
writeValues(out, v, b$row[i], b$nrows[i])
}
} else {
for (i in 1:b$n) {
v <- readValues(x, b$row[i], b$nrows[i], 1, ncx, mat=TRUE)
if (recycle) {
v <- lapply(v, as.vector)
}
if (usenames) {
names(v) <- nms
}
v <- do.call(fun, c(v, list(...)))
writeValues(out, v, b$row[i], b$nrows[i])
}
}
}
writeStop(out)
}
)
terra/R/predict.R 0000644 0001762 0000144 00000015033 14715131207 013350 0 ustar ligges users # Author: Robert J. Hijmans
# Date : August 2009
# Version 0.9
# License GPL v3
parfun <- function(cls, d, fun, model, ...) {
nr <- nrow(d)
nc <- length(cls)
s <- split(d, rep(1:nc, each=ceiling(nr/nc), length.out=nr))
p <- parallel::clusterApply(cls, s, function(i, ...) fun(model, i, ...), ...)
if (!is.null(dim(p[[1]]))) {
do.call(rbind, p)
} else {
unlist(p)
}
}
.runModel <- function(model, fun, d, nl, const, na.rm, index, cores, ...) {
doPar <- !is.null(cores)
if (!is.data.frame(d)) {
d <- data.frame(d)
}
if (!is.null(const)) {
nms <- names(const)
for (i in 1:ncol(const)) {
# avoid rowname recycling warnings
d[[ nms[i] ]] <- const[[ nms[i] ]]
}
}
if (na.rm) {
n <- nrow(d)
i <- rowSums(is.na(d)) == 0
d <- d[i,,drop=FALSE]
if (nrow(d) > 0) {
if (doPar) {
r <- parfun(cores, d, fun, model, ...)
} else {
r <- fun(model, d, ...)
}
if (is.list(r)) {
r <- as.data.frame(r)
# data.frame(lapply) instead of sapply to catch a one-row case
r <- data.frame(lapply(r, as.numeric))
} else if (is.factor(r)) {
r <- as.integer(r)
}
r <- as.matrix(r)
if (!all(i)) {
m <- matrix(NA, nrow=n, ncol=ncol(r))
m[i,] <- r
colnames(m) <- colnames(r)
r <- m
}
} else {
if (!is.null(index)) {
r <- matrix(NA, nrow=nl*n, ncol=length(index))
index <- NULL
} else {
r <- matrix(NA, nrow=nl*n, ncol=1)
}
}
} else {
if (doPar) {
r <- parfun(cores, d, fun, model, ...)
} else {
r <- fun(model, d, ...)
}
if (is.list(r)) {
r <- as.data.frame(lapply(r, as.numeric))
} else if (is.factor(r)) {
r <- as.integer(r)
} else if (is.data.frame(r)) {
r <- sapply(r, as.numeric)
}
r <- as.matrix(r)
}
if (inherits(model, "gstat")) {
if (ncol(r) > 2) {
nr <- max(nrow(d), 5)
xy <- as.matrix(d[1:nr,1:2])
if (all(xy == r[1:nr, 1:2])) {
r <- r[,-c(1:2)] # x, y
}
}
}
if (!is.null(index)) {
r <- r[, index, drop=FALSE]
}
r
}
.getFactors <- function(model, fun, d, nl, const, na.rm, index, ...) {
if (!is.data.frame(d)) {
d <- data.frame(d)
}
if (! is.null(const)) {
for (i in 1:ncol(const)) {
d <- cbind(d, const[,i,drop=FALSE])
}
}
if (na.rm) {
n <- nrow(d)
i <- rowSums(is.na(d)) == 0
d <- d[i,,drop=FALSE]
}
if (nrow(d) > 0) {
r <- fun(model, d, ...)
} else {
return(NULL)
}
if (inherits(model, "gstat")) {
nr <- max(nrow(d), 5)
xy <- d[1:nr,1:2]
if (all(xy == r[1:nr, 1:2])) {
r <- r[,-c(1:2)] # x, y
}
}
if (is.factor(r)) {
levs <- levels(r)
data.frame(value=1:length(levs), class=levs)
} else if (is.list(r) || is.data.frame(r)) {
r <- as.data.frame(r)
out <- sapply(r, levels)
for (i in 1:length(out)) {
if (!is.null(out[[i]])) {
out[[i]] <- data.frame(value=1:length(out[[i]]), label=out[[i]])
}
}
out
} else {
NULL
}
}
find_dims <- function(object, model, nc, fun, const, na.rm, index, ...) {
nr <- nrow(object)
nl <- 1
testrow <- round(0.51*nr)
rnr <- 1
if (nc==1) rnr <- min(nr, 20) - testrow + 1
d <- readValues(object, testrow, rnr, 1, nc, TRUE, TRUE)
cn <- NULL
levs <- NULL
if (!is.null(index)) {
nl <- length(index)
r <- .runModel(model, fun, d, nl, const, na.rm, index, cores=NULL, ...)
rdim <- dim(r)
if (is.null(rdim)) {
cn <- ""
} else {
cn <- colnames(r)
}
} else {
allna <- FALSE
if (na.rm) {
allna <- all(nrow(stats::na.omit(d)) == 0)
if (allna) {
testrow <- ceiling(testrow - 0.25*nr)
d <- readValues(object, testrow, rnr, 1, nc, TRUE, TRUE)
allna <- all(nrow(stats::na.omit(d)) == 0)
}
if (allna) {
testrow <- floor(testrow + 0.5*nr)
if ((testrow + rnr) > nr) rnr = nr - testrow + 1
d <- readValues(object, testrow, rnr, 1, nc, TRUE, TRUE)
allna <- all(nrow(stats::na.omit(d)) == 0)
}
if (allna && (ncell(object) < 1000)) {
d <- readValues(object, 1, nr, 1, nc, TRUE, TRUE)
allna <- all(nrow(stats::na.omit(d)) == 0)
#if (allna) {
# error("predict", "all predictor values are NA")
#}
}
if (allna) {
d <- spatSample(object, min(1000, ncell(object)), "regular", warn=FALSE)
allna <- all(nrow(stats::na.omit(d)) == 0)
}
if (allna) {
d[] <- stats::runif(prod(dim(d)))
}
}
r <- .runModel(model, fun, d, nl, const, na.rm, index, cores=NULL, ...)
if (ncell(object) > 1) {
rdim <- dim(r)
if (is.null(rdim)) {
nl <- 1
cn <- ""
} else {
if (isTRUE(any(rdim == 1))) {
nl <- 1
cn <- colnames(r)[1]
} else {
nl <- ncol(r)
cn <- colnames(r)
}
}
} else {
nl <- length(r)
}
levs <- .getFactors(model, fun, d, nl, const, na.rm, index, ...)
}
out <- rast(object, nlyrs=nl)
if (!all(sapply(levs, is.null))) levels(out) <- levs
if (length(cn) == nl) names(out) <- make.names(cn, TRUE)
out
}
setMethod("predict", signature(object="SpatRaster"),
function(object, model, fun=predict, ..., const=NULL, na.rm=FALSE, index=NULL, cores=1, cpkgs=NULL, filename="", overwrite=FALSE, wopt=list()) {
nms <- names(object)
if (length(unique(nms)) != length(nms)) {
tab <- table(nms)
error("predict", "duplicate names in SpatRaster: ", tab[tab>1])
}
nc <- ncol(object)
#tomat <- FALSE
readStart(object)
on.exit(readStop(object))
if (!is.null(const)) {
const <- data.frame(const)[1,,drop=FALSE]
rownames(const) <- NULL
}
out <- terra:::find_dims(object, model, nc, fun, const, na.rm, index, ...)
nl <- nlyr(out)
doclust <- FALSE
if (inherits(cores, "cluster")) {
doclust <- TRUE
} else if (cores > 1) {
doclust <- TRUE
cores <- parallel::makeCluster(cores)
on.exit(parallel::stopCluster(cores), add=TRUE)
}
if (doclust) {
parallel::clusterExport(cores, c("model", "fun"), environment())
if (!is.null(cpkgs)) {
parallel::clusterExport(cores, "cpkgs", environment())
parallel::clusterCall(cores, function() for (i in 1:length(cpkgs)) {library(cpkgs[i], character.only=TRUE) })
}
export_args(cores, ..., caller="predict")
} else {
cores <- NULL
}
b <- writeStart(out, filename, overwrite, wopt=wopt, n=max(nlyr(out), nlyr(object))*4, sources=sources(object))
for (i in 1:b$n) {
d <- readValues(object, b$row[i], b$nrows[i], 1, nc, TRUE, TRUE)
r <- .runModel(model, fun, d, nl, const, na.rm, index, cores=cores, ...)
if (prod(NROW(r), NCOL(r)) != prod(b$nrows[i], nc, nl)) {
msg <- "the number of values returned by 'fun' (model predict function) does not match the input."
if (!na.rm) msg <- paste(msg, "Try na.rm=TRUE?")
error("predict", msg)
}
writeValues(out, r, b$row[i], b$nrows[i])
}
writeStop(out)
# return(out)
}
)
terra/R/Agenerics.R 0000644 0001762 0000144 00000103525 14750557734 013642 0 ustar ligges users #if (!isGeneric("#")) { setGeneric("#", function(x, ...) standardGeneric("#")) }
#if (!isGeneric("prcomp")) {setGeneric("prcomp", function(x, ...) standardGeneric("princomp"))}
## ADDED BY ecor
if (!isGeneric("watershed")) {setGeneric("watershed", function(x, ...) standardGeneric("watershed"))}
if (!isGeneric("pitfinder")) {setGeneric("pitfinder", function(x, ...) standardGeneric("pitfinder"))}
if (!isGeneric("NIDP")) {setGeneric("NIDP", function(x, ...) standardGeneric("NIDP"))}
if (!isGeneric("flowAccumulation")) {setGeneric("flowAccumulation", function(x, ...) standardGeneric("flowAccumulation"))}
if (!isGeneric("thresh")) {setGeneric("thresh", function(x, ...) standardGeneric("thresh"))}
if (!isGeneric("divide")) {setGeneric("divide", function(x, ...) standardGeneric("divide"))}
if (!isGeneric("bestMatch")) {setGeneric("bestMatch", function(x, y, ...) standardGeneric("bestMatch"))}
if (!isGeneric("k_means")) {setGeneric("k_means", function(x, ...) standardGeneric("k_means"))}
if (!isGeneric("princomp")) {setGeneric("princomp", function(x, ...) standardGeneric("princomp"))}
if (!isGeneric("extractRange")) { setGeneric("extractRange", function(x, y, ...) standardGeneric("extractRange"))}
if (!isGeneric("getTileExtents")) {setGeneric("getTileExtents", function(x, ...) standardGeneric("getTileExtents"))}
if (!isGeneric("layerCor")) {setGeneric("layerCor", function(x, ...) standardGeneric("layerCor"))}
if (!isGeneric("metags")) {setGeneric("metags", function(x, ...) standardGeneric("metags"))}
if (!isGeneric("metags<-")) {setGeneric("metags<-", function(x, ..., value) standardGeneric("metags<-"))}
if (!isGeneric("forceCCW")) {setGeneric("forceCCW", function(x, ...) standardGeneric("forceCCW"))}
if (!isGeneric("addCats")) {setGeneric("addCats", function(x, ...) standardGeneric("addCats"))}
if (!isGeneric("regress")) {setGeneric("regress", function(y, x, ...) standardGeneric("regress"))}
if (!isGeneric("panel")) {setGeneric("panel", function(x, ...) standardGeneric("panel"))}
#if (!isGeneric("colSums")) {setGeneric("colSums", function(x, ...) standardGeneric("colSums"))}
#if (!isGeneric("rowSums")) {setGeneric("rowSums", function(x, ...) standardGeneric("rowSums"))}
#if (!isGeneric("colMeans")) {setGeneric("colMeans", function(x, ...) standardGeneric("colMeans"))}
#if (!isGeneric("rowMeans")) {setGeneric("rowMeans", function(x, ...) standardGeneric("rowMeans"))}
if (!isGeneric("logic")) {setGeneric("logic", function(x, ...) standardGeneric("logic"))}
if (!isGeneric("compare")) {setGeneric("compare", function(x, y, ...) standardGeneric("compare"))}
if (!isGeneric("meta")) {setGeneric("meta", function(x, ...) standardGeneric("meta"))}
if (!isGeneric("rangeFill")) {setGeneric("rangeFill", function(x, ...) standardGeneric("rangeFill"))}
if (!isGeneric("roll")) {setGeneric("roll", function(x, ...) standardGeneric("roll"))}
if (!isGeneric("elongate")) {setGeneric("elongate", function(x, ...) standardGeneric("elongate"))}
if (!isGeneric("update")) {setGeneric("update", function(object, ...) standardGeneric("update"))}
if (!isGeneric("viewshed")) {setGeneric("viewshed", function(x, ...) standardGeneric("viewshed"))}
if (!isGeneric("sieve")) {setGeneric("sieve", function(x, ...) standardGeneric("sieve"))}
if (!isGeneric("rasterizeWin")) {setGeneric("rasterizeWin", function(x, y, ...) standardGeneric("rasterizeWin"))}
if (!isGeneric("interpNear")) {setGeneric("interpNear", function(x, y, ...) standardGeneric("interpNear"))}
if (!isGeneric("interpIDW")) {setGeneric("interpIDW", function(x, y, ...) standardGeneric("interpIDW"))}
if (!isGeneric("normalize.longitude")) {setGeneric("normalize.longitude", function(x, ...) standardGeneric("normalize.longitude"))}
if (!isGeneric("allNA")) {setGeneric("allNA", function(x, ...) standardGeneric("allNA"))}
if (!isGeneric("noNA")) {setGeneric("noNA", function(x, ...) standardGeneric("noNA"))}
if (!isGeneric("countNA")) {setGeneric("countNA", function(x, ...) standardGeneric("countNA"))}
if (!isGeneric("scoff")) {setGeneric("scoff", function(x, ...) standardGeneric("scoff"))}
if (!isGeneric("scoff<-")) {setGeneric("scoff<-", function(x, ..., value) standardGeneric("scoff<-"))}
if (!isGeneric("blocks")) {setGeneric("blocks", function(x, ...) standardGeneric("blocks"))}
if (!isGeneric("droplevels")) {setGeneric("droplevels", function(x, ...) standardGeneric("droplevels"))}
if (!isGeneric("str")) { setGeneric("str", function(object, ...) standardGeneric("str"))}
if (!isGeneric("plet")) { setGeneric("plet", function(x, ...) standardGeneric("plet"))}
if (!isGeneric("combineGeoms")) {setGeneric("combineGeoms", function(x, y, ...) standardGeneric("combineGeoms"))}
if (!isGeneric("concats")) {setGeneric("concats", function(x, ...) standardGeneric("concats"))}
if (!isGeneric("has.colors")) {setGeneric("has.colors", function(x, ...) standardGeneric("has.colors"))}
if (!isGeneric("has.RGB")) {setGeneric("has.RGB", function(x, ...) standardGeneric("has.RGB"))}
if (!isGeneric("emptyGeoms")) {setGeneric("emptyGeoms", function(x, ...) standardGeneric("emptyGeoms"))}
if (!isGeneric("serialize")) {setGeneric("serialize", function(object, connection, ascii = FALSE, xdr = TRUE, version = NULL, refhook = NULL) standardGeneric("serialize"))}
if (!isGeneric("saveRDS")) {setGeneric("saveRDS", function (object, file="", ascii=FALSE, version=NULL, compress=TRUE, refhook=NULL) standardGeneric("saveRDS"))}
if (!isGeneric("query")) {setGeneric("query", function(x, ...) standardGeneric("query"))}
if (!isGeneric("set.values")) {setGeneric("set.values", function(x, ...) standardGeneric("set.values"))}
if (!isGeneric("set.ext")) {setGeneric("set.ext", function(x, ...) standardGeneric("set.ext"))}
if (!isGeneric("set.names")) {setGeneric("set.names", function(x, ...) standardGeneric("set.names"))}
if (!isGeneric("set.crs")) {setGeneric("set.crs", function(x, ...) standardGeneric("set.crs"))}
if (!isGeneric("set.RGB")) {setGeneric("set.RGB", function(x, ...) standardGeneric("set.RGB"))}
if (!isGeneric("set.window")) {setGeneric("set.window", function(x, ...) standardGeneric("set.window"))}
if (!isGeneric("math")) { setGeneric("math", function(x, ...) standardGeneric("math")) }
if (!isGeneric("all.equal")) { setGeneric("all.equal", function(target, current, ...) standardGeneric("all.equal")) }
if (!isGeneric("impose")) { setGeneric("impose", function(x, ...) standardGeneric("impose")) }
if (!isGeneric("density")) { setGeneric("density", function(x, ...) standardGeneric("density"))}
if (!isGeneric("densify")) { setGeneric("densify", function(x, ...) standardGeneric("densify"))}
if (!isGeneric("selectHighest")) {setGeneric("selectHighest", function(x, ...) standardGeneric("selectHighest"))}
if (!isGeneric("focal3D")) { setGeneric("focal3D", function(x, ...) standardGeneric("focal3D")) }
if (!isGeneric("focalReg")) { setGeneric("focalReg", function(x, ...) standardGeneric("focalReg")) }
if (!isGeneric("focalCpp")) { setGeneric("focalCpp", function(x, ...) standardGeneric("focalCpp")) }
if (!isGeneric("focalPairs")) { setGeneric("focalPairs", function(x, ...) standardGeneric("focalPairs")) }
if (!isGeneric("clearance")) {setGeneric("clearance", function(x, ...) standardGeneric("clearance"))}
if (!isGeneric("width")) {setGeneric("width", function(x, ...) standardGeneric("width"))}
if (!isGeneric("simplifyGeom")) {setGeneric("simplifyGeom", function(x, ...) standardGeneric("simplifyGeom"))}
if (!isGeneric("thinGeom")) {setGeneric("thinGeom", function(x, ...) standardGeneric("thinGeom"))}
if (!isGeneric("mergeLines")) {setGeneric("mergeLines", function(x, ...) standardGeneric("mergeLines"))}
if (!isGeneric("mergeTime")) {setGeneric("mergeTime", function(x, ...) standardGeneric("mergeTime"))}
if (!isGeneric("fillTime")) {setGeneric("fillTime", function(x, ...) standardGeneric("fillTime"))}
if (!isGeneric("makeNodes")) {setGeneric("makeNodes", function(x, ...) standardGeneric("makeNodes"))}
if (!isGeneric("removeDupNodes")) {setGeneric("removeDupNodes", function(x, ...) standardGeneric("removeDupNodes"))}
if (!isGeneric("snap")) {setGeneric("snap", function(x, ...) standardGeneric("snap"))}
if (!isGeneric("weighted.mean")) {setGeneric("weighted.mean", function(x, w, ...) standardGeneric("weighted.mean"))}
if (!isGeneric("split")) {setGeneric("split", function(x, f, drop = FALSE, ...) standardGeneric("split"))}
if (!isGeneric("cellSize")) {setGeneric("cellSize", function(x, ...) standardGeneric("cellSize"))}
if (!isGeneric("surfArea")) {setGeneric("surfArea", function(x, ...) standardGeneric("surfArea"))}
if (!isGeneric("na.omit")) {setGeneric("na.omit", function(object, ...) standardGeneric("na.omit"))}
if (!isGeneric("catalyze")) {setGeneric("catalyze", function(x, ...) standardGeneric("catalyze"))}
if (!isGeneric("activeCat")) {setGeneric("activeCat", function(x, ...) standardGeneric("activeCat"))}
if (!isGeneric("activeCat<-")) {setGeneric("activeCat<-", function(x, ..., value) standardGeneric("activeCat<-"))}
if (!isGeneric("sharedPaths")) {setGeneric("sharedPaths", function(x, ...) standardGeneric("sharedPaths"))}
if (!isGeneric("isTRUE")) {setGeneric("isTRUE", function(x) standardGeneric("isTRUE"))}
if (!isGeneric("subst")) {setGeneric("subst", function(x, ...) standardGeneric("subst"))}
if (!isGeneric("colorize")) {setGeneric("colorize", function(x, ...) standardGeneric("colorize"))}
if (!isGeneric("RGB")) {setGeneric("RGB", function(x, ...) standardGeneric("RGB"))}
if (!isGeneric("RGB<-")) {setGeneric("RGB<-", function(x, ..., value) standardGeneric("RGB<-"))}
if (!isGeneric("autocor")) {setGeneric("autocor", function(x, ...) standardGeneric("autocor"))}
if (!isGeneric("delaunay")) {setGeneric("delaunay", function(x, ...) standardGeneric("delaunay"))}
if (!isGeneric("voronoi")) {setGeneric("voronoi", function(x, ...) standardGeneric("voronoi"))}
if (!isGeneric("hull")) {setGeneric("hull", function(x, ...) standardGeneric("hull"))}
if (!isGeneric("convHull")) {setGeneric("convHull", function(x, ...) standardGeneric("convHull"))}
if (!isGeneric("minRect")) {setGeneric("minRect", function(x, ...) standardGeneric("minRect"))}
if (!isGeneric("minCircle")) {setGeneric("minCircle", function(x, ...) standardGeneric("minCircle"))}
#if (!isGeneric("which.related")) {setGeneric("which.related", function(x, y, ...) standardGeneric("which.related"))}
if (!isGeneric("is.related")) {setGeneric("is.related", function(x, y, ...) standardGeneric("is.related"))}
if (!isGeneric("relate")) {setGeneric("relate", function(x, y, ...) standardGeneric("relate"))}
if (!isGeneric("intersect")) {setGeneric("intersect", function(x, y) standardGeneric("intersect"))}
if (!isGeneric("not.na")) {setGeneric("not.na", function(x, ...) standardGeneric("not.na"))}
if (!isGeneric("erase")) {setGeneric("erase", function(x, y, ...) standardGeneric("erase"))}
if (!isGeneric("gaps")) {setGeneric("gaps", function(x, ...) standardGeneric("gaps"))}
if (!isGeneric("is.rotated")) {setGeneric("is.rotated", function(x, ...) standardGeneric("is.rotated"))}
if (!isGeneric("is.flipped")) {setGeneric("is.flipped", function(x, ...) standardGeneric("is.flipped"))}
if (!isGeneric("is.int")) {setGeneric("is.int", function(x) standardGeneric("is.int"))}
if (!isGeneric("as.int")) {setGeneric("as.int", function(x, ...) standardGeneric("as.int"))}
if (!isGeneric("is.bool")) {setGeneric("is.bool", function(x) standardGeneric("is.bool"))}
if (!isGeneric("as.bool")) {setGeneric("as.bool", function(x, ...) standardGeneric("as.bool"))}
if (!isGeneric("nearby")) {setGeneric("nearby", function(x, ...) standardGeneric("nearby"))}
if (!isGeneric("nearest")) {setGeneric("nearest", function(x, ...) standardGeneric("nearest"))}
if (!isGeneric("cartogram")) {setGeneric("cartogram", function(x, ...) standardGeneric("cartogram"))}
if (!isGeneric("dots")) {setGeneric("dots", function(x, ...) standardGeneric("dots"))}
if (!isGeneric("crds")) {setGeneric("crds", function(x, ...) standardGeneric("crds"))}
if (!isGeneric("symdif")) {setGeneric("symdif", function(x, y, ...) standardGeneric("symdif"))}
if (!isGeneric("median")) {setGeneric("median", function(x, na.rm) standardGeneric("median"))}
if (!isGeneric("polys")) {setGeneric("polys", function(x,...) standardGeneric("polys"))}
if (!isGeneric("centroids")) {setGeneric("centroids", function(x, ...) standardGeneric("centroids"))}
if (!isGeneric("coltab")) {setGeneric("coltab", function(x, ...) standardGeneric("coltab"))}
if (!isGeneric("coltab<-")) { setGeneric("coltab<-", function(x, ..., value) standardGeneric("coltab<-")) }
if (!isGeneric("deepcopy")) { setGeneric("deepcopy", function(x, ...) standardGeneric("deepcopy")) }
if (!isGeneric("window")) {setGeneric("window", function(x, ...) standardGeneric("window"))}
if (!isGeneric("window<-")) {setGeneric("window<-", function(x, ..., value) standardGeneric("window<-"))}
if (!isGeneric("NAflag")) {setGeneric("NAflag", function(x, ...) standardGeneric("NAflag"))}
if (!isGeneric("NAflag<-")) {setGeneric("NAflag<-", function(x, ..., value) standardGeneric("NAflag<-"))}
if (!isGeneric("app")) { setGeneric("app", function(x, ...) standardGeneric("app"))}
if (!isGeneric("lapp")) { setGeneric("lapp", function(x, ...) standardGeneric("lapp"))}
if (!isGeneric("rapp")) { setGeneric("rapp", function(x, ...) standardGeneric("rapp"))}
if (!isGeneric("tapp")) { setGeneric("tapp", function(x, ...) standardGeneric("tapp"))}
if (!isGeneric("sapp")) { setGeneric("sapp", function(x, ...) standardGeneric("sapp"))}
if (!isGeneric("xpp")) { setGeneric("xapp", function(x, y, ...) standardGeneric("xapp"))}
if (!isGeneric("add<-")) {setGeneric("add<-", function(x, value) standardGeneric("add<-"))}
if (!isGeneric("align")) { setGeneric("align", function(x, y, ...) standardGeneric("align"))}
if (!isGeneric("as.contour")) {setGeneric("as.contour", function(x,...) standardGeneric("as.contour"))}
if (!isGeneric("as.lines")) {setGeneric("as.lines", function(x,...) standardGeneric("as.lines"))}
if (!isGeneric("as.points")) {setGeneric("as.points", function(x,...) standardGeneric("as.points"))}
if (!isGeneric("as.polygons")) {setGeneric("as.polygons", function(x,...) standardGeneric("as.polygons"))}
if (!isGeneric("classify")) { setGeneric("classify", function(x, ...) standardGeneric("classify")) }
if (!isGeneric("cells")) { setGeneric("cells", function(x, y, ...) standardGeneric("cells")) }
if (!isGeneric("tighten")) {setGeneric("tighten", function(x, ...) standardGeneric("tighten"))}
if (!isGeneric("compareGeom")) {setGeneric("compareGeom", function(x,y,...) standardGeneric("compareGeom"))}
if (!isGeneric("crosstab")) { setGeneric("crosstab", function(x, y, ...) standardGeneric("crosstab")) }
if (!isGeneric("describe")) { setGeneric("describe", function(x, ...) standardGeneric("describe"))}
if (!isGeneric("depth")) {setGeneric("depth", function(x,...) standardGeneric("depth"))}
if (!isGeneric("depth<-")) {setGeneric("depth<-", function(x, value) standardGeneric("depth<-"))}
if (!isGeneric("draw")) {setGeneric("draw", function(x,...) standardGeneric("draw"))}
if (!isGeneric("ext")) { setGeneric("ext", function(x, ...) standardGeneric("ext"))}
if (!isGeneric("ext<-")) { setGeneric("ext<-", function(x, value) standardGeneric("ext<-")) }
if (!isGeneric("fillHoles") ) { setGeneric("fillHoles", function(x, ...) standardGeneric("fillHoles")) }
if (!isGeneric("geomtype")) {setGeneric("geomtype", function(x, ...) standardGeneric("geomtype"))}
if (!isGeneric("datatype")) {setGeneric("datatype", function(x, ...) standardGeneric("datatype"))}
if (!isGeneric("global")) {setGeneric("global", function(x, ...) standardGeneric("global"))}
if (!isGeneric("makeValid")) {setGeneric("makeValid", function(x,...) standardGeneric("makeValid"))}
if (!isGeneric("is.valid")) {setGeneric("is.valid", function(x,...) standardGeneric("is.valid"))}
if (!isGeneric("is.empty")) {setGeneric("is.empty", function(x,...) standardGeneric("is.empty"))}
if (!isGeneric("is.points")) {setGeneric("is.points", function(x,...) standardGeneric("is.points"))}
if (!isGeneric("is.lines")) {setGeneric("is.lines", function(x,...) standardGeneric("is.lines"))}
if (!isGeneric("is.polygons")) {setGeneric("is.polygons", function(x,...) standardGeneric("is.polygons"))}
if (!isGeneric("makeTiles")) {setGeneric("makeTiles", function(x,...) standardGeneric("makeTiles"))}
if (!isGeneric("vrt")) {setGeneric("vrt", function(x,...) standardGeneric("vrt"))}
if (!isGeneric("isTRUE")) { setGeneric("isTRUE", function(x) standardGeneric("isTRUE"))}
if (!isGeneric("isFALSE")) { setGeneric("isFALSE", function(x) standardGeneric("isFALSE"))}
if (!isGeneric("varnames")) {setGeneric("varnames", function(x,...) standardGeneric("varnames"))}
if (!isGeneric("varnames<-")) {setGeneric("varnames<-", function(x, value) standardGeneric("varnames<-"))}
if (!isGeneric("log")) {setGeneric("log", function(x,...) standardGeneric("log"))}
if (!isGeneric("longnames")) {setGeneric("longnames", function(x,...) standardGeneric("longnames"))}
if (!isGeneric("longnames<-")) {setGeneric("longnames<-", function(x, value) standardGeneric("longnames<-"))}
if (!isGeneric("hasMinMax")) {setGeneric("hasMinMax", function(x) standardGeneric("hasMinMax"))}
if (!isGeneric("minmax")) {setGeneric("minmax", function(x, ...) standardGeneric("minmax"))}
if (!isGeneric("nsrc")) { setGeneric("nsrc", function(x) standardGeneric("nsrc")) }
if (!isGeneric("perim")) {setGeneric("perim", function(x, ...) standardGeneric("perim"))}
if (!isGeneric("nseg")) {setGeneric("nseg", function(x, ...) standardGeneric("nseg"))}
if (!isGeneric("project")) {setGeneric("project", function(x,...) standardGeneric("project"))}
if (!isGeneric("wrapCache")) {setGeneric("wrapCache", function(x, ...) standardGeneric("wrapCache"))}
if (!isGeneric("wrap")) {setGeneric("wrap", function(x, ...) standardGeneric("wrap"))}
if (!isGeneric("unwrap")) {setGeneric("unwrap", function(x, ...) standardGeneric("unwrap"))}
if (!isGeneric("cats")) { setGeneric("cats", function(x, ...) standardGeneric("cats")) }
if (!isGeneric("categories")) { setGeneric("categories", function(x, ...) standardGeneric("categories")) }
if (!isGeneric("set.cats")) { setGeneric("set.cats", function(x, ...) standardGeneric("set.cats")) }
if (!isGeneric("as.raster")) { setGeneric("as.raster", function(x, ...) standardGeneric("as.raster"))}
if (!isGeneric("rast") ) { setGeneric("rast", function(x, ...) standardGeneric("rast")) }
if (!isGeneric("rev") ) { setGeneric("rev", function(x) standardGeneric("rev")) }
if (!isGeneric("sds") ) { setGeneric("sds", function(x, ...) standardGeneric("sds")) }
if (!isGeneric("sprc") ) { setGeneric("sprc", function(x, ...) standardGeneric("sprc")) }
if (!isGeneric("svc") ) { setGeneric("svc", function(x, ...) standardGeneric("svc")) }
if (!isGeneric("sel")) {setGeneric("sel", function(x, ...) standardGeneric("sel"))}
if (!isGeneric("segregate")) {setGeneric("segregate", function(x, ...) standardGeneric("segregate"))}
if (!isGeneric("selectRange")) {setGeneric("selectRange", function(x, ...) standardGeneric("selectRange"))}
if (!isGeneric("setValues")) {setGeneric("setValues", function(x, values, ...) standardGeneric("setValues"))}
if (!isGeneric("expanse")) {setGeneric("expanse", function(x, ...) standardGeneric("expanse"))}
if (!isGeneric("size")) {setGeneric("size", function(x, ...) standardGeneric("size"))}
if (!isGeneric("inMemory")) {setGeneric("inMemory", function(x, ...) standardGeneric("inMemory"))}
if (!isGeneric("sources")) {setGeneric("sources", function(x, ...) standardGeneric("sources"))}
if (!isGeneric("spatSample")) { setGeneric("spatSample", function(x, ...) standardGeneric("spatSample"))}
if (!isGeneric("terrain")) {setGeneric("terrain", function(x, ...) standardGeneric("terrain"))}
if (!isGeneric("has.time")) {setGeneric("has.time", function(x,...) standardGeneric("has.time"))}
if (!isGeneric("time")) {setGeneric("time", function(x,...) standardGeneric("time"))}
if (!isGeneric("time<-")) {setGeneric("time<-", function(x, ..., value) standardGeneric("time<-"))}
if (!isGeneric("timeInfo")) {setGeneric("timeInfo", function(x,...) standardGeneric("timeInfo"))}
if (!isGeneric("nlyr")) { setGeneric("nlyr", function(x) standardGeneric("nlyr")) }
if (!isGeneric("nlyr<-")) { setGeneric("nlyr<-", function(x, ..., value) standardGeneric("nlyr<-")) }
if (!isGeneric("linearUnits")) {setGeneric("linearUnits", function(x, ...) standardGeneric("linearUnits"))}
if (!isGeneric("units")) {setGeneric("units", function(x) standardGeneric("units"))}
if (!isGeneric("units<-")) {setGeneric("units<-", function(x,value) standardGeneric("units<-"))}
if (!isGeneric("vect") ) { setGeneric("vect", function(x, ...) standardGeneric("vect")) }
if (!isGeneric("writeCDF")) {setGeneric("writeCDF", function(x, filename, ...) standardGeneric("writeCDF"))}
if (!isGeneric("writeVector")) {setGeneric("writeVector", function(x, filename, ...) standardGeneric("writeVector"))}
## shared with "raster"
if (!isGeneric("%in%")) { setGeneric("%in%", function(x, table) standardGeneric("%in%")) }
if (!isGeneric("adjacent")) {setGeneric("adjacent", function(x, ...) standardGeneric("adjacent"))}
if (!isGeneric("animate")) { setGeneric("animate", function(x, ...) standardGeneric("animate")) }
if (!isGeneric("approximate")) {setGeneric("approximate", function(x, ...) standardGeneric("approximate"))}
if (!isGeneric("as.data.frame")) { setGeneric("as.data.frame", function(x, row.names = NULL, optional = FALSE, ...) standardGeneric("as.data.frame")) }
if (!isGeneric("as.list")) { setGeneric("as.list", function(x, ...) standardGeneric("as.list"))}
if (!isGeneric("as.factor")) {setGeneric("as.factor", function(x) standardGeneric("as.factor"))}
if (!isGeneric("atan2")) { setGeneric("atan2", function(y, x) standardGeneric("atan2"))}
if (!isGeneric("atan_2")) { setGeneric("atan_2", function(y, x, ...) standardGeneric("atan_2"))}
if (!isGeneric("barplot")) {setGeneric("barplot", function(height,...) standardGeneric("barplot"))}
#if (!isGeneric("bndbox")) {setGeneric("bndbox", function(obj) standardGeneric("bndbox"))}
if (!isGeneric("boundaries")) { setGeneric("boundaries", function(x, ...) standardGeneric("boundaries"))}
if (!isGeneric("boxplot")) { setGeneric("boxplot", function(x, ...) standardGeneric("boxplot"))}
if (!isGeneric("buffer")) {setGeneric("buffer", function(x, ...) standardGeneric("buffer"))}
if (!isGeneric("clamp")) { setGeneric("clamp", function(x, ...) standardGeneric("clamp")) }
if (!isGeneric("clamp_ts")) { setGeneric("clamp_ts", function(x, ...) standardGeneric("clamp_ts")) }
if (!isGeneric("click")) {setGeneric("click", function(x, ...)standardGeneric("click"))}
if (!isGeneric("contour")) { setGeneric("contour", function(x,...) standardGeneric("contour"))}
if (!isGeneric("cover")) {setGeneric("cover", function(x, y, ...) standardGeneric("cover"))}
if (!isGeneric("crop")) { setGeneric("crop", function(x, y, ...) standardGeneric("crop")) }
if (!isGeneric("crs")) { setGeneric("crs", function(x, ...) standardGeneric("crs")) }
if (!isGeneric("crs<-")) { setGeneric("crs<-", function(x, ..., value) standardGeneric("crs<-")) }
if (!isGeneric("density")) { setGeneric("density", function(x, ...) standardGeneric("density"))}
if (!isGeneric("aggregate")) {setGeneric("aggregate", function(x, ...) standardGeneric("aggregate"))}
if (!isGeneric("disagg")) {setGeneric("disagg", function(x, ...) standardGeneric("disagg"))}
if (!isGeneric("costDist")) {setGeneric("costDist", function(x, ...)standardGeneric("costDist"))}
if (!isGeneric("gridDist")) {setGeneric("gridDist", function(x, ...)standardGeneric("gridDist"))}
if (!isGeneric("distance")) {setGeneric("distance", function(x, y, ...)standardGeneric("distance"))}
if (!isGeneric("direction")) {setGeneric("direction", function(x, ...)standardGeneric("direction"))}
if (!isGeneric("extract")) { setGeneric("extract", function(x, y, ...) standardGeneric("extract"))}
if (!isGeneric("extend")) {setGeneric("extend", function(x, y, ...) standardGeneric("extend"))}
if (!isGeneric("flip")) {setGeneric("flip", function(x, ...) standardGeneric("flip")) }
if (!isGeneric("focal")) { setGeneric("focal", function(x, ...) standardGeneric("focal")) }
if (!isGeneric("focalValues")) { setGeneric("focalValues", function(x, ...) standardGeneric("focalValues")) }
if (!isGeneric("freq")) { setGeneric("freq", function(x, ...) standardGeneric("freq")) }
if (!isGeneric("geom")) { setGeneric("geom", function(x,...) standardGeneric("geom"))}
if (!isGeneric("hasValues")) {setGeneric("hasValues", function(x, ...) standardGeneric("hasValues")) }
if (!isGeneric("head")) { setGeneric("head", function(x, ...) standardGeneric("head"))}
if (!isGeneric("ifel")) {setGeneric("ifel", function(test, ...) standardGeneric("ifel"))}
if (!isGeneric("image")) {setGeneric("image", function(x, ...)standardGeneric("image"))}
if (!isGeneric("init")) {setGeneric("init", function(x, ...) standardGeneric("init"))}
if (!isGeneric("inset")) {setGeneric("inset", function(x, ...) standardGeneric("inset"))}
if (!isGeneric("inext")) {setGeneric("inext", function(x, ...) standardGeneric("inext"))}
if (!isGeneric("interpolate")) { setGeneric("interpolate", function(object, ...) standardGeneric("interpolate"))}
if (!isGeneric("is.factor")) {setGeneric("is.factor", function(x) standardGeneric("is.factor"))}
if (!isGeneric("is.lonlat")) { setGeneric("is.lonlat", function(x, ...) standardGeneric("is.lonlat"))}
if (!isGeneric("mask")) { setGeneric("mask", function(x, mask, ...) standardGeneric("mask")) }
if (!isGeneric("match")) { setGeneric("match", function(x, table, nomatch=NA_integer_, incomparables=NULL) standardGeneric("match"))}
if (!isGeneric("modal")) {setGeneric("modal", function(x, ...) standardGeneric("modal"))}
if (!isGeneric("mosaic")) {setGeneric("mosaic", function(x, y, ...) standardGeneric("mosaic"))}
if (!isGeneric("ncell")) { setGeneric("ncell", function(x) standardGeneric("ncell")) }
if (!isGeneric("nrow")) { setGeneric("nrow", function(x) standardGeneric("nrow")) }
if (!isGeneric("ncol")) { setGeneric("nrow", function(x) standardGeneric("nrow")) }
if (!isGeneric("ncol<-")) { setGeneric("ncol<-", function(x, ..., value) standardGeneric("ncol<-")) }
if (!isGeneric("nrow<-")) { setGeneric("nrow<-", function(x, ..., value) standardGeneric("nrow<-")) }
if (!isGeneric("origin")) { setGeneric("origin", function(x, ...) standardGeneric("origin")) }
if (!isGeneric("origin<-")) {setGeneric("origin<-", function(x, value) standardGeneric("origin<-"))}
if (!isGeneric("pairs")) { setGeneric("pairs", function(x, ...) standardGeneric("pairs"))}
if (!isGeneric("patches")) {setGeneric("patches", function(x, ...) standardGeneric("patches"))}
if (!isGeneric("persp")) { setGeneric("persp", function(x,...) standardGeneric("persp")) }
if (!isGeneric("plot")) { setGeneric("plot", function(x, y,...) standardGeneric("plot"))}
if (!isGeneric("plotRGB")) { setGeneric("plotRGB", function(x, ...)standardGeneric("plotRGB"))}
if (!isGeneric("predict")) {setGeneric("predict", function(object, ...) standardGeneric("predict"))}
if (!isGeneric("quantile")) {setGeneric("quantile", function(x, ...)standardGeneric("quantile"))}
if (!isGeneric("rasterize")) {setGeneric("rasterize", function(x, y, ...) standardGeneric("rasterize"))}
if (!isGeneric("rasterizeGeom")) {setGeneric("rasterizeGeom", function(x, y, ...) standardGeneric("rasterizeGeom"))}
if (!isGeneric("readStart")) {setGeneric("readStart", function(x, ...) standardGeneric("readStart"))}
if (!isGeneric("readStop")) {setGeneric("readStop", function(x) standardGeneric("readStop"))}
if (!isGeneric("toMemory")) {setGeneric("toMemory", function(x, ...) standardGeneric("toMemory"))}
if (!isGeneric("res")) { setGeneric("res", function(x) standardGeneric("res")) }
if (!isGeneric("res<-")) { setGeneric("res<-", function(x, value) standardGeneric("res<-")) }
if (!isGeneric("rectify")) {setGeneric("rectify", function(x, ...) standardGeneric("rectify"))}
if (!isGeneric("resample")) { setGeneric("resample", function(x, y, ...) standardGeneric("resample"))}
if (!isGeneric("spin")) {setGeneric("spin", function(x, ...) standardGeneric("spin"))}
if (!isGeneric("rotate")) {setGeneric("rotate", function(x, ...) standardGeneric("rotate"))}
if (!isGeneric("rescale")) {setGeneric("rescale", function(x, ...) standardGeneric("rescale"))}
#if (!isGeneric("select")) {setGeneric("select", function(x, ...) standardGeneric("select"))}
if (!isGeneric("setMinMax")) {setGeneric("setMinMax", function(x, ...) standardGeneric("setMinMax"))}
if (!isGeneric("scale")) {setGeneric("scale", function(x, center=TRUE, scale=TRUE) standardGeneric("scale"))}
if (!isGeneric("scale_linear")) { setGeneric("scale_linear", function(x, ...) standardGeneric("scale_linear"))}
if (!isGeneric("shift")) {setGeneric("shift", function(x, ...) standardGeneric("shift"))}
if (!isGeneric("stdev")) { setGeneric("stdev", function(x, ...) standardGeneric("stdev")) }
if (!isGeneric("subset")) {setGeneric("subset", function(x, ...) standardGeneric("subset")) }
if (!isGeneric("summary")) {setGeneric("summary", function(object, ...) standardGeneric("summary")) }
if (!isGeneric("t")) { setGeneric("t", function(x) standardGeneric("t"))}
if (!isGeneric("tail")) { setGeneric("tail", function(x, ...) standardGeneric("tail"))}
if (!isGeneric("text")) { setGeneric("text", function(x, ...) standardGeneric("text")) }
if (!isGeneric("trans")) { setGeneric("trans", function(x, ...) standardGeneric("trans"))}
if (!isGeneric("trim")) { setGeneric("trim", function(x, ...) standardGeneric("trim")) }
if (!isGeneric("xres")) { setGeneric("xres", function(x) standardGeneric("xres")) }
if (!isGeneric("yres")) { setGeneric("yres", function(x) standardGeneric("yres")) }
if (!isGeneric("zonal")) {setGeneric("zonal", function(x, z, ...) standardGeneric("zonal"))}
if (!isGeneric("rcl")) { setGeneric("rcl", function(x, ...) standardGeneric("rcl")) }
if (!isGeneric("yFromRow")) { setGeneric("yFromRow", function(object, row) standardGeneric("yFromRow")) }
if (!isGeneric("xFromCol")) { setGeneric("xFromCol", function(object, col) standardGeneric("xFromCol")) }
if (!isGeneric("colFromX")) { setGeneric("colFromX", function(object, x) standardGeneric("colFromX")) }
if (!isGeneric("rowFromY")) { setGeneric("rowFromY", function(object, y) standardGeneric("rowFromY")) }
if (!isGeneric("cellFromXY")) { setGeneric("cellFromXY", function(object, xy) standardGeneric("cellFromXY")) }
if (!isGeneric("cellFromRowCol")) { setGeneric("cellFromRowCol", function(object, row, col, ...) standardGeneric("cellFromRowCol")) }
if (!isGeneric("rowColCombine")) { setGeneric("rowColCombine", function(object, row, col, ...) standardGeneric("rowColCombine")) }
if (!isGeneric("cellFromRowColCombine")) { setGeneric("cellFromRowColCombine", function(object, row, col, ...) standardGeneric("cellFromRowColCombine")) }
if (!isGeneric("xyFromCell")) { setGeneric("xyFromCell", function(object, cell, ...) standardGeneric("xyFromCell")) }
if (!isGeneric("yFromCell")) { setGeneric("yFromCell", function(object, cell) standardGeneric("yFromCell")) }
if (!isGeneric("xFromCell")) { setGeneric("xFromCell", function(object, cell) standardGeneric("xFromCell")) }
if (!isGeneric("rowColFromCell")) { setGeneric("rowColFromCell", function(object, cell) standardGeneric("rowColFromCell")) }
if (!isGeneric("rowFromCell")) { setGeneric("rowFromCell", function(object, cell) standardGeneric("rowFromCell")) }
if (!isGeneric("colFromCell")) { setGeneric("colFromCell", function(object, cell) standardGeneric("colFromCell")) }
if (!isGeneric("readStart")) { setGeneric("readStart", function(x, ...) standardGeneric("readStart")) }
if (!isGeneric("readValues")) { setGeneric("readValues", function(x, ...) standardGeneric("readValues")) }
if (!isGeneric("readStop")) { setGeneric("readStop", function(x, ...) standardGeneric("readStop")) }
if (!isGeneric("setMinMax")) {setGeneric("setMinMax", function(x, ...) standardGeneric("setMinMax")) }
if (!isGeneric("stretch")) {setGeneric("stretch", function(x, ...) standardGeneric("stretch")) }
if (!isGeneric("union")) {setGeneric("union", function(x, y)standardGeneric("union"))}
if (!isGeneric("unique")) { setGeneric("unique", function(x, incomparables=FALSE, ...) standardGeneric("unique")) }
if (!isGeneric("values")) { setGeneric("values", function(x, ...) standardGeneric("values")) }
if (!isGeneric("values<-")) { setGeneric("values<-", function(x, value) standardGeneric("values<-"))}
if (!isGeneric("where.max")) {setGeneric("where.max", function(x, ...) standardGeneric("where.max"))}
if (!isGeneric("where.min")) {setGeneric("where.min", function(x, ...) standardGeneric("where.min"))}
if (!isGeneric("which.max")) {setGeneric("which.max", function(x) standardGeneric("which.max"))}
if (!isGeneric("which.min")) {setGeneric("which.min", function(x) standardGeneric("which.min"))}
if (!isGeneric("which.lyr")) {setGeneric("which.lyr", function(x) standardGeneric("which.lyr"))}
if (!isGeneric("writeStart")) { setGeneric("writeStart", function(x, filename, ...) standardGeneric("writeStart")) }
if (!isGeneric("writeStop")) { setGeneric("writeStop", function(x, ...) standardGeneric("writeStop")) }
if (!isGeneric("writeValues")) { setGeneric("writeValues", function(x, v, ...) standardGeneric("writeValues")) }
if (!isGeneric("writeRaster")) {setGeneric("writeRaster", function(x, filename, ...) standardGeneric("writeRaster"))}
if (!isGeneric("xmin")) {setGeneric("xmin", function(x) standardGeneric("xmin"))}
if (!isGeneric("xmax")) {setGeneric("xmax", function(x) standardGeneric("xmax"))}
if (!isGeneric("ymin")) {setGeneric("ymin", function(x) standardGeneric("ymin"))}
if (!isGeneric("ymax")) {setGeneric("ymax", function(x) standardGeneric("ymax"))}
if (!isGeneric("xmin<-")) { setGeneric("xmin<-", function(x, ..., value) standardGeneric("xmin<-"))}
if (!isGeneric("xmax<-")) { setGeneric("xmax<-", function(x, ..., value) standardGeneric("xmax<-"))}
if (!isGeneric("ymin<-")) { setGeneric("ymin<-", function(x, ..., value) standardGeneric("ymin<-"))}
if (!isGeneric("ymax<-")) { setGeneric("ymax<-", function(x, ..., value) standardGeneric("ymax<-"))}
if (!isGeneric("zoom")) {setGeneric("zoom", function(x, ...)standardGeneric("zoom"))}
terra/R/autocor.R 0000644 0001762 0000144 00000013212 14731053441 013370 0 ustar ligges users # Author: Robert J. Hijmans
# Date : April 2011 / Jan 2021
# Version 1.0
# License GPL v3
.checkngb <- function(ngb, mustBeOdd=FALSE) {
ngb <- as.integer(round(ngb))
if (length(ngb) == 1) {
ngb <- c(ngb, ngb)
} else if (length(ngb) > 2) {
error("autocor", "ngb should be a single value or two values")
}
if (min(ngb) < 1) { stop("ngb should be larger than 1") }
if (mustBeOdd) {
if (any(ngb %% 2 == 0)) {
error("autocor", "neighborhood size must be an odd number")
}
}
return(ngb)
}
.getFilter <- function(w, warn=TRUE) {
if (!is.matrix(w)) {
w <- .checkngb(w)
w <- matrix(1, nrow=w[1], ncol=(w[2]))
w[ceiling(dim(w)[1]/2), ceiling(dim(w)[2]/2)] <- 0
} else {
if (w[ceiling(dim(w)[1]/2), ceiling(dim(w)[2]/2)] != 0) {
if (warn) {
warning('central cell of weights matrix (filter) was set to zero')
}
w[ceiling(dim(w)[1]/2), ceiling(dim(w)[2]/2)] <- 0
}
stopifnot(all(w >= 0))
}
if (min(dim(w) %% 2)==0) {
stop('dimensions of weights matrix (filter) must be uneven')
}
w
}
setMethod("autocor", signature(x="numeric"),
function(x, w, method="moran") {
method <- match.arg(tolower(method), c("moran", "geary", "gi", "gi*", "mean", "locmor"))
if (all(is.na(x))) {
error("autocor", "all values are NA")
}
if (any(is.na(w))) {
error("autocor", "NA value(s) in the weight matrix")
}
d <- dim(w)
n <- length(x)
if ((d[1] != d[2]) || (d[1] != n)) {
error("autocor", "w must be a square matrix with sides the size of x")
}
if (method %in% c("moran", "geary", "locmor", "gi")) {
if (any(as.numeric(diag(w)) != 0)) {
warn("autocor", paste("it is unexpected that a weight matrix for", method, "has diagonal values that are not zero"))
}
} else if (method %in% c("gi*")) {
if (any(as.numeric(diag(w)) == 0)) {
warn("autocor", paste("it is unexpected that a weight matrix for", method, "has diagonal values that are zero"))
}
}
if (method == "moran") {
dx <- x - mean(x, na.rm=TRUE)
pm <- matrix(rep(dx, each=n) * dx, ncol=n)
(n / sum(dx^2)) * sum(pm * w) / sum(w)
} else if (method == "geary") { # geary
dx <- x - mean(x, na.rm=TRUE)
pm <- matrix(rep(dx, each=n) - dx, ncol=n)^2
((n-1)/sum((dx)^2)) * sum(w * pm) / (2 * sum(w))
} else if (method == "gi") {
if (any(as.numeric(diag(w)) != 0)) {
warn("autocor", "it is unexpected that a weight matrix for Gi has diagonal values that are not zero")
}
diag(w) <- 0
sumxminx <- sum(x, na.rm=TRUE) - x
Gi <- colSums(x * w) / sumxminx
Ei <- rowSums(w) / (n-1)
# variance following spdep::localG
xibar <- sumxminx/(n - 1)
si2 <- (sum(x^2) - x^2)/(n - 1) - xibar^2
VG <- si2 * (((n - 1) * rowSums(w^2) - rowSums(w)^2)/(n - 2))
VG <- VG/((sumxminx)^2)
(Gi-Ei)/sqrt(VG)
} else if (method == "gi*") {
if (any(as.numeric(diag(w)) == 0)) {
warn("autocor", "it is unexpected that a weight matrix for Gi* has diagonal values that are zero")
}
Gi <- colSums(x * w) / sum(x)
Ei <- rowSums(w) / n
# variance following spdep::localG
si2 <- sum(scale(x, scale = FALSE)^2)/n
VG <- (si2 * ((n * rowSums(w^2) - rowSums(w)^2)/(n - 1))) / (sum(x)^2)
(Gi-Ei)/sqrt(VG)
} else if (method == "locmor") {
if (any(as.numeric(diag(w)) != 0)) {
warn("autocor", "it is unexpected that a weight matrix for local Moran has diagonal values that are not zero")
}
z <- x - mean(x, na.rm=TRUE)
mp <- z / ( (sum(z^2, na.rm=TRUE) / length(x)) )
mp * apply(w, 1, function(i) {
sum(z * i, na.rm=TRUE)
} )
} else if (method == "mean") {
j <- is.na(x)
x[j] <- 0
w[j,j] <- 0
m <- apply(w, 1, function(i) {
sum(x * i) / sum(i)}
)
m[j] <- NA
m
}
}
)
setMethod("autocor", signature(x="SpatRaster"),
function(x, w=matrix(c(1,1,1,1,0,1,1,1,1),3), method="moran", global=TRUE) {
method <- match.arg(tolower(method), c("moran", "geary"))
if (nlyr(x) > 1) {
warn("autocor", "only the first layer of x is used")
x <- x[[1]]
}
if (global) {
if (method == "moran") {
z <- x - unlist(global(x, "mean", na.rm=TRUE))
wZiZj <- focal(z, w=w, fun="sum", na.rm=TRUE)
wZiZj <- wZiZj * z
wZiZj <- unlist(global(wZiZj, "sum", na.rm=TRUE))
z2 <- unlist(global(z*z, "sum", na.rm=TRUE))
n <- ncell(z) - unlist(global(z, "isNA"))
zz <- ifel(is.na(x), NA, 1)
W <- focal( zz, w=w, fun="sum", na.rm = TRUE, na.policy="omit")
NS0 <- n / unlist(global(W, "sum", na.rm=TRUE))
m <- NS0 * wZiZj / z2
names(m) <- names(x)
m
} else { # geary
w <- .getFilter(w, warn=FALSE)
i <- trunc(length(w)/2)+1
n <- ncell(x) - unlist(global(x, "isNA"))
fun <- function(x,...) sum((x-x[i])^2, ...)
f <- focal(x, w=dim(w), fun=fun, na.rm=TRUE)
Eij <- unlist(global(f, "sum", na.rm=TRUE))
xx <- ifel(is.na(x), NA ,1)
W <- focal(xx, w=w, na.rm=TRUE )
z <- 2 * unlist(global(W, "sum", na.rm=TRUE)) *
unlist(global((x - unlist(global(x, "mean", na.rm=TRUE)))^2, "sum", na.rm=TRUE))
g <- (n-1)*Eij/z
names(g) <- names(x)
g
}
} else { # local
if (method == "moran") {
z <- x - unlist(global(x, "mean", na.rm=TRUE))
zz <- ifel(is.na(x), NA, 1)
W <- focal(zz, w=w, na.rm=TRUE)
lz <- focal(z, w=w, na.rm=TRUE) / W
##n <- ncell(x) - unlist(global(is.na(x), "sum"))
s2 <- unlist(global(x, "sd", na.rm=TRUE)^2)
m <- (z / s2) * lz
names(m) <- names(x)
m
} else {
w <- .getFilter(w)
i <- trunc(length(w)/2)+1
fun <- function(x,...) sum((x-x[i])^2, ...)
Eij <- focal(x, w=dim(w), fun=fun, na.rm=TRUE)
s2 <- unlist(global(x, "sd", na.rm=TRUE))^2
##n <- ncell(x) - unlist(global(is.na(x), "sum"))
g <- Eij / s2
names(g) <- names(x)
g
}
}
}
)
terra/R/Zdeprecated.R 0000644 0001762 0000144 00000004121 14744562717 014164 0 ustar ligges users
if (!isGeneric("area")) {setGeneric("area", function(x, ...) standardGeneric("area"))}
setMethod ("area", "SpatRaster",
function (x, ...) {
error("area", "this method was removed. Use 'expanse' or 'cellSize'")
}
)
if (!isGeneric("area")) {setGeneric("area", function(x, ...) standardGeneric("area"))}
setMethod ("area", "SpatVector",
function (x, ...) {
error("area", "this method was removed. Use 'expanse'")
}
)
if (!isGeneric("gridDistance")) {setGeneric("gridDistance", function(x, ...) standardGeneric("gridDistance"))}
setMethod("gridDistance", signature(x="SpatRaster"),
function(x, ...) {
error("gridDistance", "'terra::gridDistance' was renamed to 'gridDist'")
}
)
setMethod("convHull", signature(x="SpatVector"),
function(x, by="") {
# warn("convHull", "method is deprecated, please use 'hull(type='convex')'")
hull(x, type="convex", by=by)
}
)
setMethod("minCircle", signature(x="SpatVector"),
function(x, by="") {
# warn("minCircle", "method is deprecated, please use 'hull(type='circle')'")
hull(x, "circle", by)
}
)
setMethod("minRect", signature(x="SpatVector"),
function(x, by="") {
# warn("minRect", "method is deprecated, please use 'hull(type='circle')'")
hull(x, "rectangle", by)
}
)
#if (!isGeneric("setCats")) { setGeneric("setCats", function(x, ...) standardGeneric("setCats")) }
#setMethod ("setCats" , "SpatRaster",
# function (x, ...) {
# warn("setCats", "this function will be removed. Please can use 'levels<-' or 'set.cats' instead")
# set.cats(x, ...)
# }
#)
#setMethod("costDistance", signature(x="SpatRaster"),
# function(x, target=0, scale=1, maxiter=50, filename="", ...) {
# warn("costDistance", "'costDistance' was renamed to 'costDist'. 'costDistance' will be removed in a #future version")
# costDist(x, target=target, scale=scale, maxiter=maxiter, filename=filename, ...)
# }
#)
#if (!isGeneric("focalCor")) { setGeneric("focalCor", function(x, ...) standardGeneric("focalCor")) }
#setMethod("focalCor", signature(x="SpatRaster"),
# function(x, ...) {
# error("focalCor", "'focalCor' was renamed to 'focalPairs'")
# # focalPairs(x, ...)
# }
#)
terra/R/ifelse.R 0000644 0001762 0000144 00000002355 14536376240 013201 0 ustar ligges users # Author: Robert J. Hijmans
# Date : May 2019
# Version 1.0
# License GPL v3
setMethod("ifel", signature(test="SpatRaster"),
function(test, yes, no, filename="", ...) {
no_num <- FALSE
yes_num <- FALSE
if (!inherits(no, "SpatRaster")) {
# logical includes default NA
if (!(is.numeric(no) || is.logical(no))) {
error("ifel", "argument 'no' must be a SpatRaster, numeric or logical")
}
if (length(no) > 1) warn("ifel", 'only the first element of "no" is used')
no <- no[1]
no_num <- TRUE
}
if (!inherits(yes, "SpatRaster")) {
if (!(is.numeric(yes) || is.logical(yes))) {
error("ifel", "argument 'yes' must be a SpatRaster, numeric or logical")
}
if (length(yes) > 1) warn("ifel", 'only the first element of "yes" is used')
yes <- yes[1]
yes_num <- TRUE
}
test <- as.logical(test)
if (no_num & yes_num) {
return (classify(test, rbind(c(1, yes), c(0, no)), filename=filename, ...))
}
if (no_num) {
no <- classify(test, rbind(c(0, no), c(1, NA)))
} else {
no <- mask(no, test, maskvalues=TRUE)
}
if (yes_num) {
yes <- classify(test, rbind(c(1, yes), c(0, NA)))
} else {
yes <- mask(yes, test, maskvalues=FALSE)
}
cover(no, yes, values=NA, filename=filename, ...)
}
)
terra/R/plot_2rasters.R 0000644 0001762 0000144 00000011314 14536376240 014530 0 ustar ligges users # Author: Robert J. Hijmans
# Date : June 2019
# Version 1.0
# License GPL v3
.scatterPlotRaster <- function(x, y, maxcell=100000, warn=TRUE, cex, xlab, ylab, nc, nr,
maxnl=16, main, add=FALSE, smooth=FALSE, gridded=FALSE, ncol=25, nrow=25, asp=NA,
colramp=grDevices::colorRampPalette(c("white", grDevices::blues9)), ...) {
compareGeom(x, y, lyrs=FALSE, crs=FALSE, warncrs=FALSE, ext=TRUE, rowcol=TRUE, res=FALSE)
nlx <- nlyr(x)
nly <- nlyr(y)
maxnl <- max(1, round(maxnl))
nl <- min(max(nlx, nly), maxnl)
if (nl > maxnl) {
nl <- maxnl
if (nlx > maxnl) {
x <- x[[1:maxnl]]
nlx <- maxnl
}
if (nly > maxnl) {
y <- y[[1:maxnl]]
nly <- maxnl
}
}
if (nlx < nly) {
x <- x[[rep_len(1:nlx, nly)]]
nlx <- nly
} else if (nly < nlx) {
y <- y[[rep_len(1:nly, nlx)]]
nly <- nlx
}
if (missing(main)) {
main <- ""
}
if (missing(xlab)) {
ln1 <- names(x)
} else {
ln1 <- xlab
if (length(ln1) == 1) {
ln1 <- rep(ln1, nlx)
}
}
if (missing(ylab)) {
ln2 <- names(y)
} else {
ln2 <- ylab
if (length(ln1) == 1) {
ln2 <- rep(ln2, nly)
}
}
cells <- ncell(x)
if (gridded | smooth) {
# if ((ncell(x) * (nlx + nly)) < .maxmemory()) {
if ((ncell(x) * (nlx + nly)) < 1000000) {
maxcell <- ncell(x)
}
if (smooth) {
dots <- list(...)
if (!is.null(dots$col)) {
colramp <- grDevices::colorRampPalette(dots$col)
}
}
}
x <- as.matrix(spatSample(c(x,y), size=maxcell, method="regular", as.raster=FALSE, warn=FALSE))
# y <- as.matrix(spatSample(y, size=maxcell, method="regular", as.raster=FALSE))
y <- x[,c((nlx+1):ncol(x))]
x <- x[,1:nlx]
if (warn & (NROW(x) < cells)) {
warn("plot", 'plot used a sample of ', round(100*NROW(x)/cells, 1), '% of the cells. You can use "maxcell" to increase the sample)')
}
if (missing(cex)) {
if (NROW(x) < 100) {
cex <- 1
} else if (NROW(x) < 1000) {
cex <- 0.5
} else {
cex <- 0.2
}
}
if (nlx != nly) {
# recycling
d <- cbind(as.vector(x), as.vector(y))
x <- matrix(d[,1], ncol=nl)
y <- matrix(d[,2], ncol=nl)
lab <- vector(length=nl)
lab[] <- ln1
ln1 <- lab
lab[] <- ln2
ln2 <- lab
}
if (nl > 1) {
old.par <- graphics::par(no.readonly = TRUE)
on.exit(graphics::par(old.par))
px <- trunc(sqrt(nl))
py <- ceiling(nl / px)
graphics::par(mfrow=c(px, py), mar=c(3, 3, 1, 1))
if (smooth) {
for (i in 1:nl) {
graphics::smoothScatter(x[,i], y[,i], main=main[i], xlab=ln1[i], ylab=ln2[i], add=add, asp=asp, colramp=colramp, ...)
}
} else if (gridded) {
for (i in 1:nl) {
.plotdens(x[,i], y[,i], nc=ncol, nr=nrow, main=main[i], xlab=ln1[i], ylab=ln2[i], add=add, asp=asp, ...)
}
} else {
if (add) {
for (i in 1:nl) {
graphics::points(x[,i], y[,i], cex=cex, ...)
}
} else {
for (i in 1:nl) {
plot(x[,i], y[,i], cex=cex, xlab=ln1[i], ylab=ln2[i], main=main[i], asp=asp, ...)
}
}
}
} else {
if (smooth) {
graphics::smoothScatter(x, y, main=main[1], xlab=ln1[1], ylab=ln2[1], add=add, asp=asp, colramp=colramp, ...)
} else if (gridded) {
.plotdens(x, y, nc=ncol, nr=nrow, main=main[1], xlab=ln1[1], ylab=ln2[1], add=add, asp=asp, ...)
} else {
if (add) {
graphics::points(x, y, cex=cex, ...)
} else {
plot(x, y, cex=cex, xlab=ln1[1], ylab=ln2[1], main=main[1], asp=asp, ...)
}
}
}
}
setMethod("plot", signature(x="SpatRaster", y="SpatRaster"),
function(x, y, maxcell=100000, warn=TRUE, nc, nr, maxnl=16, smooth=FALSE, gridded=FALSE, ncol=25, nrow=25, ...) {
nl <- max(nlyr(x), nlyr(y))
if (missing(nc)) {
nc <- ceiling(sqrt(nl))
} else {
nc <- max(1, min(nl, round(nc)))
}
if (missing(nr)) {
nr <- ceiling(nl / nc)
} else {
nr <- max(1, min(nl, round(nr)))
nc <- ceiling(nl / nr)
}
.scatterPlotRaster(x, y, maxcell=maxcell, warn=warn, nc=nc, nr=nr, maxnl=maxnl, gridded=gridded, smooth=smooth, ncol=ncol, nrow=nrow, ...)
}
)
.plotdens <- function(x, y, nc, nr, xlim=NULL, ylim=NULL, asp=NULL, ...) {
xy <- stats::na.omit(cbind(x,y))
if (nrow(xy) == 0) {
error("plot (density)", "only NA values (in this sample?)")
}
r <- apply(xy, 2, range)
rx <- r[,1]
if (rx[1] == rx[2]) {
rx[1] <- rx[1] - 0.5
rx[2] <- rx[2] + 0.5
}
ry <- r[,2]
if (ry[1] == ry[2]) {
ry[1] <- ry[1] - 0.5
ry[2] <- ry[2] + 0.5
}
out <- rast(xmin=rx[1], xmax=rx[2], ymin=ry[1], ymax=ry[2], ncol=nc, nrow=nr, crs="+proj=utm +zone=1 +datum=WGS84")
colnames(xy) <- c("x", "y")
out <- rasterize(vect(xy), out, fun=function(x, ...) length(x), background=NA)
if (!is.null(xlim) | !is.null(ylim)) {
if (is.null(xlim)) xlim <- c(xmin(x), xmax(x))
if (is.null(ylim)) ylim <- c(ymin(x), ymax(x))
e <- extent(xlim, ylim)
out <- extend(crop(out, e), e, value=0)
}
plot(out, maxcell=nc*nr, asp=asp, ...)
}
terra/R/time.R 0000644 0001762 0000144 00000021066 14753763672 012702 0 ustar ligges users # Author: Robert J. Hijmans
# Date: October 2018
# Version 1.0
# License GPL v3
format_ym <- function(x) {
y <- floor(x)
m <- round((x-y) * 12 + 1)
m <- month.abb[m]
paste(y, m, sep="-")
}
yearweek <- function(d) {
y <- as.integer(strftime(d, format = "%Y"))
w <- strftime(d, format = "%V")
m <- strftime(d, format = "%m")
i <- w > "51" & m=="01"
y[i] <- y[i] - 1
i <- w=="01" & m=="12"
y[i] <- y[i] + 1
yy <- as.character(y)
i <- nchar(yy) < 4
yy[i] <- formatC(y[i], width=4, flag="0")
paste0(yy, w)
}
setMethod("has.time", signature(x="SpatRaster"),
function(x) {
x@pntr$hasTime
}
)
setMethod("timeInfo", signature(x="SpatRaster"),
function(x) {
time <- x@pntr$hasTime
if (time) {
step <- x@pntr$timestep
if (step == "seconds") {
data.frame(time=time, step=step, zone=x@pntr$timezone)
} else {
data.frame(time=time, step=step, zone="")
}
} else {
data.frame(time=time, step="", zone="")
}
}
)
setMethod("timeInfo", signature(x="SpatRasterDataset"),
function(x) {
t(sapply(x, timeInfo))
}
)
time_as_seconds <- function(x) {
d <- x@pntr$time
d <- strptime("1970-01-01", "%Y-%m-%d", tz="UTC") + d
tz <- x@pntr$timezone
if (!(tz %in% c("", "UTC"))) {
attr(d, "tzone") = tz
}
d
}
#setMethod("time", signature(x="SpatVector"),
# function(x, format="") {
# cls <- sapply(values(x[1,]), function(i) { a = class(i); a[length(a)] })
# i <- which(cls %in% c("Date", "POSIXt"))[1]
# if (is.na(i)) {
# return(rep(NA, nrow(x)))
# } else {
# d <- x[,i,drop=TRUE][,,drop=TRUE]
# if (format != "") {
# steps <- c("seconds", "days", "months", "years", "yearmonths")
# format <- match.arg(tolower(format), steps)
# if (!(format %in% steps)) {
# error("time", "not a valid time format")
# }
# tstep <- ifelse(cls[i]=="Date", "days", "seconds")
# if (format == "seconds") {
# if (tstep != "seconds") {
# error("time", "cannot extract seconds from Dates")
# }
# d
# } else if (format == "days") {
# as.Date(d)
# } else if (format == "yearmonths") {
# y <- as.integer(format(d, "%Y"))
# y + (as.integer(format(d, "%m"))-1)/12
# } else if (format == "months") {
# as.integer(format(d, "%m"))
# } else if (format == "years") {
# as.integer(format(d, "%Y"))
# }
# } else {
# d
# }
# }
# }
#)
setMethod("time", signature(x="SpatRaster"),
function(x, format="") {
if (!x@pntr$hasTime) {
return(rep(NA, nlyr(x)))
}
d <- x@pntr$time
tstep <- x@pntr$timestep
if (format != "") {
steps <- c("seconds", "days", "months", "years", "yearmonths")
format <- match.arg(tolower(format), steps)
if ((format == "months") && (tstep == "years")) {
error("time", "cannot extract months from years-time")
} else if ((format == "years") && (tstep %in% c("months"))) {
error("time", "cannot extract years from months-time")
} else if ((format == "yearmonths") && (tstep %in% c("months", "years"))) {
error("time", "cannot extract yearmonths from this type of time data")
} else if ((format == "seconds") && (tstep != "seconds")) {
error("time", "cannot extract seconds from this type of time data")
} else if ((format == "days") && (!(tstep %in% c("seconds", "days")))) {
error("time", "cannot extract days from this type of time data")
}
tstep <- format
} else if (tstep == "raw") {
return(d)
}
d <- strptime("1970-01-01", "%Y-%m-%d", tz="UTC") + d
if (tstep == "seconds") {
tz <- x@pntr$timezone
if (!(tz %in% c("", "UTC"))) {
attr(d, "tzone") = tz
}
d
} else if (tstep == "days") {
as.Date(d)
} else if (tstep == "yearmonths") {
y <- as.integer(format(d, "%Y"))
y + (as.integer(format(d, "%m"))-1)/12
} else if (tstep == "months") {
as.integer(format(d, "%m"))
} else if (tstep == "years") {
as.integer(format(d, "%Y"))
# } else if (tstep == "yearweeks") {
# yearweek(as.Date(d))
} else { # ???
d
}
}
)
setMethod("time", signature(x="SpatRasterDataset"),
function(x, format="") {
lapply(x,time, format=format)
}
)
posix_from_ym <- function(y, m) {
y <- floor(y)
i <- ((y < 0) | (y > 9999))
if (any(i)) {
d <- paste(paste(rep("1900", length(y)), m, "15", sep="-"), "12:00:00")
d[!i] <- paste(paste(y[!i], m, "15", sep="-"), "12:00:00")
d <- as.POSIXlt(d, format="%Y-%m-%d %H:%M:%S", tz="UTC")
for (j in i) {
d$year[j] = y[j] - 1900
}
d
} else {
d <- paste(paste(y, m, "15", sep="-"), "12:00:00")
as.POSIXlt(d, format="%Y-%m-%d %H:%M:%S", tz="UTC")
}
}
setMethod("time<-", signature(x="SpatRaster"),
function(x, tstep="", value) {
if (missing(value)) {
value <- tstep
tstep <- ""
}
x@pntr <- x@pntr$deepcopy()
if (is.null(value)) {
x@pntr$setTime(0[0], "remove", "")
return(x)
}
if (inherits(value, "character")) {
error("time<-", "value cannot be a character type")
}
if (length(value) != nlyr(x)) {
error("time<-", "length(value) != nlyr(x)")
}
if (tstep != "") {
tstep = match.arg(as.character(tstep), c("seconds", "days", "months", "years", "yearmonths", "raw"))
}
## may not be necessary
if (tstep == "seconds") tstep = ""
tzone <- "UTC"
stept <- ""
if (inherits(value, "Date")) {
value <- as.POSIXlt(value)
if (tstep == "") stept <- "days"
} else if (inherits(value, "POSIXt")) {
if (tstep == "") stept <- "seconds"
tzone <- attr(value, "tzone")[1]
if (is.null(tzone)) tzone = "UTC"
} else if (inherits(value, "yearmon")) {
value <- as.numeric(value)
year <- floor(value)
month <- round(12 * (value - year) + 1)
value <- posix_from_ym(value, month)
if (tstep == "") stept <- "yearmonths"
}
if (stept == "") {
stept = tstep
if (tstep == "years") {
if (is.numeric(value)) {
value <- posix_from_ym(value, "6")
} else {
value <- as.integer(strftime(value, format = "%Y", tz=tzone))
value <- posix_from_ym(value, "6")
}
} else if (tstep == "months") {
if (is.numeric(value)) {
value <- floor(value)
} else {
value <- as.integer(strftime(value, format = "%m", tz=tzone))
}
if (!all(value %in% 1:12)) {
error("date<-", "months should be between 1 and 12")
}
value <- posix_from_ym(1970, value)
} else if (tstep == "yearmonths") {
if (is.numeric(value)) {
y <- as.integer(substr(value, 1, 4))
m <- value - (y * 100)
} else {
y <- as.integer(strftime(value, format = "%Y", tz=tzone))
m <- as.integer(strftime(value, format = "%m", tz=tzone))
}
if (!all(m %in% 1:12)) {
error("date<-", "months should be between 1 and 12")
}
value <- posix_from_ym(y, m)
#} else if (tstep == "days") {
# print(value)
# value <- as.Date(value)
# stept = tstep
} else if (tstep == "") {
stept <- "raw"
}
}
if (!x@pntr$setTime(as.numeric(value), stept, tzone)) {
error("time<-", "cannot set these values")
}
return(x)
}
)
setMethod("time<-", signature(x="SpatRasterDataset"),
function(x, tstep="", value) {
if (missing(value)) {
value <- tstep
tstep <- ""
}
tstep <- rep_len(tstep, length(x))
if (is.list(value)) {
if (length(x) != length(value)) {
error("time<-", "the list should have the same length as 'x'")
}
z <- lapply(1:length(x), function(i) {
time(x[i], tstep=tstep[i]) <- value[[i]]
})
} else {
if (length(unique(nlyr(x))) > 1) {
error("time<-", "not all SpatRasters have the same number of layers")
}
z <- lapply(1:length(x), function(i) {
time(x[i], tstep=tstep[i]) <- value
})
}
x
}
)
setMethod("depth", signature(x="SpatRaster"),
function(x) {
x@pntr$depth
}
)
setMethod("depth<-", signature(x="SpatRaster"),
function(x, value) {
if (is.null(value)) {
x@pntr$setDepth(0[0])
return(x)
}
value <- as.numeric(value)
if (! x@pntr$setDepth(value)) {
error("depth<-", "cannot set these values")
}
return(x)
}
)
setMethod("linearUnits", signature(x="SpatRaster"),
function(x) {
.getLinearUnits(crs(x))
}
)
setMethod("linearUnits", signature(x="SpatVector"),
function(x) {
.getLinearUnits(crs(x))
}
)
setMethod("units", signature(x="SpatRaster"),
function(x) {
x@pntr$units
}
)
setMethod("units<-", signature(x="SpatRaster"),
function(x, value) {
if (is.null(value) || all(is.na(value))) {
value <- ""
} else {
value <- as.character(value)
}
if (! x@pntr$set_units(value)) {
error("units<-", "cannot set these values")
}
return(x)
}
)
setMethod("units", signature(x="SpatRasterDataset"),
function(x) {
x@pntr$units
}
)
setMethod("units<-", signature(x="SpatRasterDataset"),
function(x, value) {
value <- as.character(value)
x@pntr$units <- value
return(x)
}
)
terra/R/names.R 0000644 0001762 0000144 00000013021 14726700274 013024 0 ustar ligges users # Author: Robert J. Hijmans
# Date: October 2018
# Version 1.0
# License GPL v3
setMethod("names", signature(x="SpatRaster"),
function(x) {
nms <- x@pntr$names
Encoding(nms) <- "UTF-8"
nms
}
)
setMethod("names<-", signature(x="SpatRaster"),
function(x, value) {
if (is.null(value)) {
value <- rep("", nlyr(x))
} else {
value <- enc2utf8(as.character(value))
if (length(value) != nlyr(x)) {
error("names<-", "incorrect number of names")
}
}
x@pntr <- x@pntr$deepcopy()
if (! x@pntr$setNames(value, FALSE)) {
error("names<-", "cannot set these names")
}
return(x)
}
)
.names_check <- function(x, value, index, validate, lengthfx) {
value <- enc2utf8(as.character(value))
if (!all(index == 1:lengthfx(x))) {
n <- names(x)
n[index] <- value
value <- n
}
if (length(value) != lengthfx(x)) {
error("names<-", "incorrect number of names")
}
if (validate) {
value <- make.names(value, unique = TRUE)
}
value
}
setMethod("set.names", signature(x="SpatRaster"),
function(x, value, index=1:nlyr(x), validate=FALSE) {
value <- .names_check(x, value, index, validate, nlyr)
if (!x@pntr$setNames(value, FALSE)) {
error("set.names", "cannot set these names")
}
invisible(TRUE)
}
)
setMethod("names", signature(x="SpatRasterCollection"),
function(x) {
nms <- x@pntr$names
Encoding(nms) <- "UTF-8"
nms
}
)
setMethod("names<-", signature(x="SpatRasterCollection"),
function(x, value) {
x@pntr <- x@pntr$deepcopy()
if (is.null(value)) {
value <- rep("", length(x))
}
x@pntr$names <- enc2utf8(as.character(value))
x
}
)
setMethod("set.names", signature(x="SpatRasterCollection"),
function(x, value, index=1:length(x), validate=FALSE) {
value <- .names_check(x, value, index, validate, length)
x@pntr$names <- value
invisible(TRUE)
}
)
setMethod("names", signature(x="SpatRasterDataset"),
function(x) {
nms <- x@pntr$names
Encoding(nms) <- "UTF-8"
nms
}
)
setMethod("names<-", signature(x="SpatRasterDataset"),
function(x, value) {
x@pntr <- x@pntr$deepcopy()
if (is.null(value)) {
value <- rep("", length(x))
}
if (is.list(value)) {
nl <- nlyr(x)
if (length(value) == 1) {
if (length(unique(nl)) > 1) {
error("names<-", "the number of layers varies between datasets")
}
x@pntr$set_layernames(enc2utf8(as.character(value[[1]])), -1)
} else {
if (length(value) != length(x)) {
error("names<-", "the number of list elements does not match the number of datasets")
}
for (i in seq_along(length(x))) x@pntr$set_layernames(enc2utf8(as.character(value[[i]])), i-1)
}
} else {
x@pntr$names <- enc2utf8(as.character(value))
}
messages(x, "names<-")
}
)
setMethod("set.names", signature(x="SpatRasterDataset"),
function(x, value, index=1:length(x), validate=FALSE) {
value <- .names_check(x, value, index, validate, length)
x@pntr$names <- value
invisible(TRUE)
}
)
setMethod("varnames", signature(x="SpatRasterDataset"),
function(x) {
nms <- x@pntr$names
Encoding(nms) <- "UTF-8"
nms
}
)
setMethod("varnames<-", signature(x="SpatRasterDataset"),
function(x, value) {
value <- enc2utf8(as.character(value))
x@pntr <- x@pntr$deepcopy()
x@pntr$names <- value
x
}
)
setMethod("names", signature(x="SpatVector"),
function(x) {
nms <- x@pntr$names
Encoding(nms) <- "UTF-8"
nms
}
)
setMethod("names", signature(x="SpatVectorProxy"),
function(x) {
nms <- x@pntr$v$names
Encoding(nms) <- "UTF-8"
nms
}
)
setMethod("names<-", signature(x="SpatVector"),
function(x, value) {
if (length(value) != ncol(x)) {
error("names<-,SpatVector", "incorrect number of names")
}
value <- enc2utf8(as.character(value))
x@pntr <- x@pntr$deepcopy()
x@pntr$names <- value
if (any(names(x) != value)) {
warn("names<-", "some names were changed to make them valid and/or unique")
}
return(x)
}
)
setMethod("set.names", signature(x="SpatVector"),
function(x, value, index=1:ncol(x), validate=FALSE) {
value <- .names_check(x, value, index, validate, ncol)
x@pntr$names <- value
invisible(TRUE)
}
)
setMethod("varnames", signature(x="SpatRaster"),
function(x) {
nms <- x@pntr$get_sourcenames()
Encoding(nms) <- "UTF-8"
nms
}
)
setMethod("varnames<-", signature(x="SpatRaster"),
function(x, value) {
value <- enc2utf8(as.character(value))
x@pntr <- x@pntr$deepcopy()
if (!x@pntr$set_sourcenames(value)) {
error("varnames<-,SpatRaster", "cannot set these names")
}
return(x)
}
)
setMethod("longnames", signature(x="SpatRasterDataset"),
function(x) {
nms <- x@pntr$long_names
Encoding(nms) <- "UTF-8"
nms
}
)
setMethod("longnames", signature(x="SpatRaster"),
function(x) {
nms <- x@pntr$get_sourcenames_long()
Encoding(nms) <- "UTF-8"
nms
}
)
setMethod("longnames<-", signature(x="SpatRasterDataset"),
function(x, value) {
x@pntr <- x@pntr$deepcopy()
x@pntr$long_names <- enc2utf8(as.character(value))
return(x)
}
)
setMethod("longnames<-", signature(x="SpatRaster"),
function(x, value) {
x@pntr <- x@pntr$deepcopy()
value <- enc2utf8(as.character(value))
if (!x@pntr$set_sourcenames_long(value)) {
error("longnames<-,SpatRaster", "cannot set these names")
}
return(x)
}
)
setMethod("names", signature(x="SpatVectorCollection"),
function(x) {
nms <- x@pntr$names
Encoding(nms) <- "UTF-8"
nms
}
)
setMethod("names<-", signature(x="SpatVectorCollection"),
function(x, value) {
x@pntr <- x@pntr$deepcopy()
if (is.null(value)) {
value <- rep("", length(x))
}
x@pntr$setNames(enc2utf8(as.character(value)), FALSE)
x
}
)
terra/R/focal.R 0000644 0001762 0000144 00000046664 14726700274 013030 0 ustar ligges users # Author: Robert J. Hijmans
# Date : December 2017
# Version 1.0
# License GPL v3
setMethod("focal", signature(x="SpatRaster"),
function(x, w=3, fun="sum", ..., na.policy="all", fillvalue=NA, expand=FALSE, silent=TRUE, filename="", overwrite=FALSE, wopt=list()) {
na.only <- list(...)$na.only
if (!is.null(na.only)) {
warn("focal", "use 'na.policy' instead of 'na.only'")
na.policy <- "only"
}
na.policy <- match.arg(tolower(na.policy), c("all", "only", "omit"))
na.only <- na.policy == "only"
na.omit <- na.policy == "omit"
if (!is.numeric(w)) {
error("focal", "w should be numeric vector or matrix")
}
txtfun <- .makeTextFun(fun)
if (is.matrix(w)) {
m <- as.vector(t(w))
#if (!all(m %in% c(0, 1, NA))) {
#if (isTRUE(list(...)$na.rm)) {
# if (txtfun != "sum") {
# error("focal", 'with "na.rm=TRUE" and weights other than 0, 1, or NA, only fun="sum" is allowed')
# }
#}
#}
w <- dim(w)
} else {
w <- rep_len(w, 2)
stopifnot(all(w > 0))
m <- rep(1, prod(w))
}
cpp <- FALSE
if (is.character(txtfun)) {
if (is.null(wopt$names)) {
wopt$names <- paste0("focal_", txtfun)
}
opt <- spatOptions(filename, overwrite, wopt=wopt)
if (na.only) {
narm <- TRUE
} else {
narm <- isTRUE(list(...)$na.rm)
}
x@pntr <- x@pntr$focal(w, m, fillvalue, narm, na.only, na.omit, txtfun, expand, opt)
messages(x, "focal")
return(x)
} else {
if (expand) {
warn("focal", "expand is ignored for functions that are not 'built-in'")
}
checkNA <- na.only || na.omit
msz <- prod(w)
dow <- !isTRUE(all(m == 1))
if (any(is.na(m))) {
k <- !is.na(m)
mm <- m[k]
msz <- sum(k)
}
v <- focalValues(x, w, trunc(nrow(x)/2), 1)[ncol(x)/2, ,drop=FALSE]
if (dow) {
if (any(is.na(m))) {
v <- v[,k,drop=FALSE] * mm
} else {
v <- v * m
}
}
test <- try(apply(v, 1, fun, ...), silent=silent)
if (inherits(test, "try-error")) {
error("focal", "test failed")
}
readStart(x)
on.exit(readStop(x))
nl <- nlyr(x)
outnl <- nl * length(test)
out <- rast(x, nlyr=outnl)
transp <- FALSE
nms <- NULL
if (isTRUE(nrow(test) > 1)) {
transp <- TRUE
nms <- rownames(test)
if (nl > 1) {
nms <- paste0(rep(names(x), each=nl), "_", rep(nms, nl))
}
} else if (isTRUE(ncol(test) > 1)) {
nms <- colnames(test)
if (nl > 1) {
nms <- paste0(rep(names(x), each=nl), "_", rep(nms, nl))
}
} else {
nms <- names(x)
if (nl > 1) {
nms <- paste0(rep(names(x), each=nl), "_", rep(1:length(test), nl))
}
}
if (length(nms) == nlyr(out)) {
names(out) <- nms
}
b <- writeStart(out, filename, overwrite, n=msz+2, sources=sources(x), wopt=wopt)
opt <- spatOptions()
for (i in 1:b$n) {
vv <- NULL
for (j in 1:nl) {
if (nl > 1) {
v <- x[[j]]@pntr$focalValues(w, fillvalue, b$row[i]-1, b$nrows[i], opt)
} else {
v <- x@pntr$focalValues(w, fillvalue, b$row[i]-1, b$nrows[i], opt)
}
if (dow) {
if (any(is.na(m))) {
v <- v[k] * mm
} else {
v <- v * m
}
}
v <- matrix(v, ncol=msz, byrow=TRUE)
v <- apply(v, 1, fun, ...)
if (transp) {
v <- t(v)
}
if (checkNA) {
if (nl > 1) {
mv <- readValues(x[[j]], b$row[i], b$nrows[i])
} else {
mv <- readValues(x, b$row[i], b$nrows[i])
}
if (na.only) {
k <- !is.na(mv)
} else {
k <- is.na(mv)
}
v[k] <- mv[k]
}
if (nl > 1) {
if (outnl > 1) {
vv <- cbind(vv, v)
} else {
vv <- c(vv, v)
}
}
}
#if (bip) {
# v <- matrix(as.vector(v), ncol=ncol(v), byrow=TRUE)
#}
if (nl > 1) {
writeValues(out, vv, b$row[i], b$nrows[i])
} else {
writeValues(out, v, b$row[i], b$nrows[i])
}
}
out <- writeStop(out)
return(out)
}
}
)
setMethod("focal3D", signature(x="SpatRaster"),
function(x, w=3, fun=mean, ..., na.policy="all", fillvalue=NA, pad=FALSE, padvalue=fillvalue, expand=FALSE, silent=TRUE, filename="", overwrite=FALSE, wopt=list()) {
na.policy <- match.arg(tolower(na.policy), c("all", "only", "omit"))
na.only <- na.policy == "only"
na.omit <- na.policy == "omit"
checkNA <- na.only || na.omit
if (!(inherits(w, "numeric") || inherits(w, "array"))) {
error("focal3D", "w should be numeric vector or array")
}
if (is.array(w)) {
if (length(dim(w)) != 3) {
error("focal3D", "the weights array must have three dimensions")
}
m <- as.vector(w)
w <- dim(w)
} else {
w <- rep_len(w, 3)
stopifnot(all(w > 0))
m <- rep(1, prod(w))
}
if (w[3] > nlyr(x)) {
error("focal3D", "the third weights dimension is larger than nlyr(x)")
}
if (any((w %% 2) == 0)) {
error("focal3D", "w must be odd sized in all dimensions")
}
msz <- prod(w)
dow <- !isTRUE(all(m == 1))
rna <- FALSE
if (any(is.na(m))) {
rna <- TRUE
kna <- !is.na(m)
m <- m[kna]
msz <- sum(kna)
}
opt <- spatOptions()
halfway <- floor(w[3]/2)
v <- lapply(1:w[3], function(i) focalValues(x[[i]], w[1:2], trunc(nrow(x)/2), 1)[ncol(x)/2, ,drop=FALSE])
v <- t(do.call(cbind, v))
if (dow) {
if (rna) {
v <- v[kna,,drop=FALSE] * m
} else {
v <- v * m
}
}
vout <- try(apply(v, 2, fun, ...), silent=silent)
if (inherits(vout, "try-error")) {
error("focal", "test failed")
}
readStart(x)
on.exit(readStop(x))
nl <- nlyr(x)
transp <- FALSE
nms <- NULL
if (isTRUE(nrow(vout) > 1)) {
transp <- TRUE
nms <- rownames(vout)
} else if (isTRUE(ncol(vout) > 1)) {
nms <- colnames(vout)
}
if (pad || expand) {
startlyr = 1;
endlyr = nl;
outnl <- nl * length(vout)
} else {
startlyr = halfway+1;
endlyr = nl-halfway;
outnl <- (1+endlyr-startlyr) * length(vout)
}
out <- rast(x, nlyr=outnl)
if (!is.null(nms)) {
if (length(nms) <= outnl) {
names(out) <- rep_len(nms, outnl)
}
}
b <- writeStart(out, filename, overwrite, n=msz+2, sources=sources(x), wopt=wopt)
nread <- prod(w[1:2])
for (i in 1:b$n) {
nc <- b$nrows[i]*ncol(x)
vv <- NULL
if (expand) {
v <- list(matrix(x[[1]]@pntr$focalValues(w, fillvalue, b$row[i]-1, b$nrows[i], opt), ncol=nc))
v <- do.call(rbind, rep(v, halfway+1))
for (k in 2:(1+halfway)) {
v <- rbind(v, matrix(x[[k]]@pntr$focalValues(w, fillvalue, b$row[i]-1, b$nrows[i], opt), ncol=nc))
}
} else if (pad) {
v <- matrix(padvalue, ncol=b$nrows[i]*ncol(x), nrow=nread*halfway)
for (k in 1:(1+halfway)) {
v <- rbind(v, matrix(x[[k]]@pntr$focalValues(w, fillvalue, b$row[i]-1, b$nrows[i], opt), ncol=nc))
}
} else {
v <- lapply(1:w[3],
function(k) {
y <- x[[k]]
z <- y@pntr$focalValues(w, fillvalue, b$row[i]-1, b$nrows[i], opt)
y <- messages(y, "focal3D")
matrix(z, ncol=nc)
})
v <- do.call(rbind, v)
}
for (j in startlyr:endlyr) {
if (j > startlyr) {
v <- v[-c(1:nread), ]
k <- j + halfway
if (k > nl) {
if (pad) {
v <- rbind(v, matrix(padvalue, nrow=nread, ncol=ncol(v)))
} else {
v <- rbind(v, v[(nrow(v)-nread):nrow(v), ])
}
} else {
v <- rbind(v, matrix(x[[k]]@pntr$focalValues(w, fillvalue, b$row[i]-1, b$nrows[i], opt), ncol=ncol(v)))
}
}
if (dow) {
if (rna) {
vout <- apply(v[kna,] * m, 2, fun, ...)
} else {
vout <- apply(v * m, 2, fun, ...)
}
} else {
vout <- apply(v, 2, fun,...)
}
if (transp) {
vout <- t(vout)
}
if (checkNA) {
mv <- readValues(x[[j]], b$row[i], b$nrows[i])
if (na.only) {
k <- !is.na(mv)
} else {
k <- is.na(mv)
}
vout[k] <- mv[k]
}
vv <- c(vv, as.vector(vout))
}
writeValues(out, vv, b$row[i], b$nrows[i])
}
out <- writeStop(out)
return(out)
}
)
setMethod("focalCpp", signature(x="SpatRaster"),
function(x, w=3, fun, ..., fillvalue=NA, silent=TRUE, filename="", overwrite=FALSE, wopt=list()) {
if (!(all(c("ni", "nw") %in% names(formals(fun))))) {
error("focalRaw", 'fun must have an argument "ni"')
}
if (!is.numeric(w)) {
error("focal", "w should be numeric vector or matrix")
}
if (is.matrix(w)) {
m <- as.vector(t(w))
w <- dim(w)
} else {
w <- rep_len(w, 2)
stopifnot(all(w > 0))
m <- rep(1, prod(w))
}
msz <- prod(w)
readStart(x)
on.exit(readStop(x))
dow <- !isTRUE(all(m == 1))
if (any(is.na(m))) {
k <- !is.na(m)
mm <- m[k]
msz <- sum(k)
}
opt <- spatOptions()
nl <- nlyr(x)
v <- x@pntr$focalValues(w, fillvalue, max(0, trunc(nrow(x)/2)), 1, opt)[1:prod(w)]
if (dow) {
if (any(is.na(m))) {
v <- v[k] * mm
} else {
v <- v * m
}
}
test <- try(fun(v, ..., ni=1, nw=msz), silent=silent)
if (inherits(test, "try-error")) {
error("focalCpp", "test failed")
}
outnl <- nl * length(test)
if (is.null(wopt$names )) {
wopt$names <- colnames(test)
}
out <- rast(x, nlyr=outnl)
b <- writeStart(out, filename, overwrite, n=msz+2, sources=sources(x), wopt=wopt)
nc <- ncol(out)
for (i in 1:b$n) {
vv <- NULL
for (j in 1:nl) {
if (nl > 1) {
v <- x[[j]]@pntr$focalValues(w, fillvalue, b$row[i]-1, b$nrows[i], opt)
} else {
v <- x@pntr$focalValues(w, fillvalue, b$row[i]-1, b$nrows[i], opt)
}
sst <- messages(x)
if (dow) {
if (any(is.na(m))) {
v <- v[k] * mm
} else {
v <- v * m
}
}
v <- fun(v, ..., ni=b$nrows[i]*nc, nw=msz)
if (nl > 1) {
if (outnl > 1) {
vv <- rbind(vv, v)
} else {
vv <- c(vv, v)
}
}
}
if (nl > 1) {
writeValues(out, vv, b$row[i], b$nrows[i])
} else {
writeValues(out, v, b$row[i], b$nrows[i])
}
}
writeStop(out)
}
)
.getRegFun <- function(fun, weighted=FALSE, wopt, nmsx, nl, na.rm=FALSE, intercept=TRUE, ...) {
ols <- function(x, y, ...) {
if (any(is.na(x)) || any(is.na(y)) || (NROW(y) < (NCOL(x) + 1))) {
return(rep(NA, NCOL(x)+1))
}
stats::.lm.fit(cbind(1, x), y)$coefficients
}
ols_noi <- function(x, y, ...) {
if (any(is.na(x)) || any(is.na(y)) || (NROW(y) < (NCOL(x)))) {
return(rep(NA, NCOL(x)))
}
stats::.lm.fit(as.matrix(x), y)$coefficients
}
ols_narm <- function(x, y, ...) {
v <- stats::na.omit(cbind(y, x))
if (nrow(v) < (NCOL(x) + 1)) {
return( cbind(rep(NA, NCOL(x)+1)) )
}
stats::.lm.fit(cbind(1, v[,-1]), v[,1])$coefficients
}
ols_noi_narm <- function(x, y, ...) {
v <- stats::na.omit(cbind(y, x))
if (nrow(v) < (NCOL(x))) {
return( cbind(rep(NA, NCOL(x))) )
}
stats::.lm.fit(v[,-1,drop=FALSE], v[,1])$coefficients
}
weighted_ols <- function(x, y, weights, ...) {
if (any(is.na(x)) || any(is.na(y)) || any(is.na(weights)) || (NROW(y) < (NCOL(x) + 1))) {
return(rep(NA, NCOL(x)+1))
}
stats::lm.wfit(cbind(1, x), y, weights)$coefficients
}
weighted_ols_noi <- function(x, y, weights, ...) {
if (any(is.na(x)) || any(is.na(y)) || any(is.na(weights)) || (NROW(y) < (NCOL(x) + 1))) {
return(rep(NA, NCOL(x)))
}
stats::lm.wfit(as.matrix(x), y, weights)$coefficients
}
weighted_ols_narm <- function(x, y, weights, ...) {
v <- stats::na.omit(cbind(y, weights, x))
if (nrow(v) < (NCOL(x) + 1)) {
return(rep(NA, NCOL(x)+1))
}
stats::lm.wfit(cbind(1, v[,-c(1:2)]), v[,1], v[,2])$coefficients
}
weighted_ols_noi_narm <- function(x, y, weights, ...) {
v <- stats::na.omit(cbind(y, weights, x))
if (nrow(v) < (NCOL(x))) {
return(rep(NA, NCOL(x)))
}
stats::lm.wfit(v[,-c(1:2), drop=FALSE], v[,1], v[,2])$coefficients
}
fun <- tolower(fun[1])
if (fun != "ols") {
return(list(fun=fun, wopt=wopt))
}
intercept <- isTRUE(intercept)
if (intercept) {
if (weighted) {
if (na.rm) {
fun <- weighted_ols_narm
} else {
fun <- weighted_ols
}
} else {
if (na.rm) {
fun = ols_narm
} else {
fun = ols
}
}
if (is.null(wopt$names )) {
wopt$names <- c("intercept", nmsx[-1])
}
} else {
if (weighted) {
if (na.rm) {
fun <- weighted_ols_noi_narm
} else {
fun <- weighted_ols_noi
}
} else {
if (na.rm) {
fun = ols_noi_narm
} else {
fun = ols_noi
}
}
if (is.null(wopt$names )) {
wopt$names <- nmsx[-1]
}
nl = nl-1
}
list(fun=fun, wopt=wopt, nl=nl, intercept=intercept, na.rm=na.rm)
}
setMethod("focalReg", signature(x="SpatRaster"),
function(x, w=3, fun="ols", ..., fillvalue=NA, filename="", overwrite=FALSE, wopt=list()) {
nl <- nlyr(x)
if (nl < 2) error("focalReg", "x must have at least 2 layers")
if (!is.numeric(w)) {
error("focalReg", "w should be numeric vector or matrix")
}
weighted <- FALSE
if (is.matrix(w)) {
m <- as.vector(t(w))
m[m==0] <- NA
test <- stats::na.omit(m)
if (length(test) == 0) {
error("focalReg", "all values in w are NA and/or zero")
}
if (any(test != 1)) {
weighted <- TRUE
message("the focal values are used as weights")
}
w <- dim(w)
} else {
w <- rep_len(w, 2)
stopifnot(all(w > 0))
m <- rep(1, prod(w))
}
msz <- prod(w)
if (msz < 2) {
error("the effective weight matrix must have positive dimensions, and at least one must be > 1")
}
hasnam <- FALSE
if (any(is.na(m))) {
hasnam <- TRUE
k <- !is.na(m)
msz <- sum(k)
weights <- m[k]
} else if (weighted) {
weights <- m
}
if (is.character(fun)) {
funopt <- .getRegFun(fun, weighted, wopt, names(x), nlyr(x), ...)
fun <- funopt$fun
wopt <- funopt$wopt
outnl <- funopt$nl
} else {
# need to test
X <- matrix(sample(msz * (nl-1), replace=TRUE), ncol=nl-1)
out <- fun(1:msz, X)
outnl <- length(out)
if (is.null(wopt$names) && (length(names(out)) == outnl)) {
wopt$names <- names(out)
}
}
out <- rast(x, nlyr=outnl)
b <- writeStart(out, filename, n=msz+2, sources=sources(x), wopt=wopt)
ry <- x[[1]]
rx <- x[[-1]]
if (nl == 2) {
for (i in 1:b$n) {
Y <- focalValues(ry, w, b$row[i], b$nrows[i], fillvalue)
X <- focalValues(rx, w, b$row[i], b$nrows[i], fillvalue)
if (hasnam) {
Y <- Y[,k,drop=FALSE]
X <- X[,k,drop=FALSE]
}
if (weighted) {
v <- t(sapply(1:nrow(Y), function(i) fun(X[i,], Y[i,], weights, ...)))
} else {
v <- t(sapply(1:nrow(Y), function(i) fun(X[i,], Y[i,], ...)))
}
writeValues(out, v, b$row[i], b$nrows[i])
}
} else {
for (i in 1:b$n) {
Y <- focalValues(ry, w, b$row[i], b$nrows[i], fillvalue)
if (hasnam) {
Y <- Y[,k,drop=FALSE]
}
X <- list()
for (j in 1:(nl-1)) {
X[[j]] <- focalValues(rx[[j]], w, b$row[i], b$nrows[i], fillvalue)
if (hasnam) {
X[[j]] <- X[[j]][,k]
}
}
v <- list()
for (p in 1:nrow(Y)) {
xlst <- list()
for (j in 1:(nl-1)) {
xlst[[j]] <- X[[j]][p,]
}
pX <- do.call(cbind, xlst)
if (weighted) {
v[[p]] <- fun(pX, Y[p,], weights)
} else {
v[[p]] <- fun(pX, Y[p,])
}
}
v <- t(do.call(cbind, v))
writeValues(out, v, b$row[i], b$nrows[i])
}
}
out <- writeStop(out)
return(out)
}
)
setMethod("focalPairs", signature(x="SpatRaster"),
function(x, w=3, fun, ..., fillvalue=NA, filename="", overwrite=FALSE, wopt=list()) {
pearson <- function(x, y, ...) {
.pearson(x, y, FALSE)
}
pearson_narm <- function(x, y, ...) {
.pearson(x, y, TRUE)
}
weighted_pearson <- function(x, y, weights, ...) {
.weighted_pearson(x, y, weights, FALSE)
}
weighted_pearson_narm <- function(x, y, weights, ...) {
.weighted_pearson(x, y, weights, TRUE)
}
nl <- nlyr(x)
if (nl < 2) error("focalPairs", "x must have at least 2 layers")
if (!is.numeric(w)) {
error("focalPairs", "w should be numeric vector or matrix")
}
weighted <- FALSE
if (is.matrix(w)) {
m <- as.vector(t(w))
m[m==0] <- NA
test <- stats::na.omit(m)
if (length(test) == 0) {
error("focalPairs", "all values in w are NA and/or zero")
}
if (any(test != 1)) {
weighted <- TRUE
message("the focal values are used as weights")
}
w <- dim(w)
} else {
w <- rep_len(w, 2)
stopifnot(all(w > 0))
m <- rep(1, prod(w))
}
msz <- prod(w)
hasnam <- FALSE
if (any(is.na(m))) {
hasnam <- TRUE
k <- !is.na(m)
msz <- sum(k)
weights <- m[k]
} else if (weighted) {
weights <- m
}
if (msz < 2) {
error("the effective weight matrix must have positive dimensions, and at least one must be > 1")
}
if (is.character(fun)) {
narm <- isTRUE(list(...)$na.rm)
fun <- tolower(fun[1])
if (fun == "pearson") {
if (weighted) {
if (narm) {
fun = weighted_pearson_narm
} else {
fun = weighted_pearson
}
} else {
if (narm) {
fun = pearson_narm
} else {
fun = pearson
}
}
}
}
if (weighted) {
test <- try(do.call(fun, list(1:prod(w), prod(w):1, weights=rep(1, prod(w)), ...)))
if (inherits(test, "try-error")) {
error("focalPairs", "'fun' does not work. Does it have a 'weights' argument?")
}
} else {
test <- try(do.call(fun, list(1:prod(w), prod(w):1, ...)))
if (inherits(test, "try-error")) {
error("focalPairs", "'fun' does not work. Does it have two arguments (one for each layer)")
}
}
if (is.null(wopt$names )) {
wopt$names <- colnames(test)
}
outnl <- (nlyr(x) - 1) * length(test)
out <- rast(x, nlyr=outnl)
b <- writeStart(out, filename, n=msz+2, sources=sources(x), wopt=wopt)
for (i in 1:b$n) {
v <- list()
Y <- focalValues(x[[1]], w, b$row[i], b$nrows[i], fillvalue)
if (hasnam) {
Y <- Y[,k,drop=FALSE]
}
for (j in 2:nlyr(x)) {
X <- Y
Y <- focalValues(x[[j]], w, b$row[i], b$nrows[i], fillvalue)
if (hasnam) {
Y <- Y[,k,drop=FALSE]
}
if (weighted) {
v[[j-1]] <- t(sapply(1:nrow(Y), function(i) fun(X[i,], Y[i,], weights=weights, ...)))
} else {
v[[j-1]] <- t(sapply(1:nrow(Y), function(i) fun(X[i,], Y[i,], ...)))
}
}
v <- do.call(cbind, v)
writeValues(out, v, b$row[i], b$nrows[i])
}
out <- writeStop(out)
return(out)
}
)
# ..ols <- function(x, y, ...) {
# v <- cbind(y, x)
# if (any(is.na(v))) return( cbind(rep(NA, NCOL(x)+1)) )
# X <- cbind(1, v[,-1])
# XtX <- t(X) %*% X
# if (det(XtX) == 0) {
# return(rep(NA, NCOL(y)+1))
# }
# invXtX <- solve(XtX) %*% t(X)
# invXtX %*% v[,1]
# }
# ..ols_noi <- function(x, y, ...) {
# v <- cbind(y, x)
# if (any(is.na(v))) return( cbind (rep(NA, NCOL(x))) )
# X <- v[,-1,drop=FALSE]
# XtX <- t(X) %*% X
# if (det(XtX) == 0) {
# return(rep(NA, ncol(y)+1))
# }
# invXtX <- solve(XtX) %*% t(X)
# invXtX %*% v[,1]
# }
# ..ols_narm <- function(x, y, ...) {
# v <- na.omit(cbind(y, x))
# if (nrow(v) < (NCOL(x) + 1)) {
# return( cbind(rep(NA, NCOL(x)+1)) )
# }
# X <- cbind(1, v[,-1])
# XtX <- t(X) %*% X
# if (det(XtX) == 0) {
# return(NA)
# }
# invXtX <- solve(XtX) %*% t(X)
# invXtX %*% v[,1]
# }
# ..ols_noi_narm <- function(x, y, ...) {
# v <- na.omit(cbind(y, x))
# if (nrow(v) < NCOL(x)) {
# return( cbind(rep(NA, NCOL(y))) )
# }
# X <- v[,-1,drop=FALSE]
# XtX <- t(X) %*% X
# if (det(XtX) == 0) {
# return(NA)
# }
# invXtX <- solve(XtX) %*% t(X)
# invXtX %*% v[,1]
# }
# ..weighted_ols <- function(x, y, weights, ...) {
# if (any(is.na(x)) || any(is.na(y))) {
# return(rep(NA, NCOL(x)+1))
# }
# stats::coefficients(stats::glm(y~x, weights=weights))
# }
# ..weighted_ols_noi <- function(x, y, weights, ...) {
# if (any(is.na(x)) || any(is.na(y))) {
# return(rep(NA, NCOL(x)))
# }
# stats::coefficients(stats::glm(y ~ -1 + ., weights=weights))
# }
# ..weighted_ols_narm <- function(x, y, weights, ...) {
# v <- na.omit(data.frame(y=y, x, weights=weights))
# if (nrow(v) < (NCOL(x) + 1)) {
# return(rep(NA, NCOL(x)+1))
# }
# weights <- v$weights
# v$weights <- NULL
# stats::coefficients(stats::glm(y ~ ., data=v, weights=weights))
# }
# ..weighted_ols_noi_narm <- function(x, y, weights, ...) {
# v <- na.omit(data.frame(y=y, x, weights=weights))
# if (nrow(v) < (NCOL(x))) {
# return(rep(NA, NCOL(x)))
# }
# weights <- v$weights
# v$weights <- NULL
# stats::coefficients(stats::glm(y ~ -1 + ., data=v, weights=weights))
# }
terra/R/tapp.R 0000644 0001762 0000144 00000012505 14726700274 012673 0 ustar ligges users
setMethod("tapp", signature(x="SpatRaster"),
function(x, index, fun, ..., cores=1, filename="", overwrite=FALSE, wopt=list()) {
stopifnot(!any(is.na(index)))
prename <- ""
out_time <- double()
out_tstep <- ""
out_tz <- "UTC"
if (length(index) == 1) {
if (is.character(index)) {
choices <- c("years", "months", "dekads", "weeks", "days", "doy", "yearmonths", "yeardekads", "yearweeks", "7days", "10days", "15days")
i <- pmatch(tolower(index), choices)
if (is.na(i)) {
error("tapp", paste("invalid time step. Use one of:", paste(choices, collapse=", ")))
}
if (!x@pntr$hasTime) {
error("tapp", "x has no time data")
}
choice <- choices[i]
if (choice == "doy") {
# or POSIXlt$yday
index <- format(time(x, "days"), "%j")
prename <- "doy_"
} else if (choice == "dekads") {
index <- floor(as.integer(format(time(x, "days"), "%j")) / 10) + 1
prename <- "dekad_"
} else if (choice == "yeardekads") {
year <- time(res, "years")
year <- formatC(year, width=4, flag = "0")
dekad <- floor(as.integer(format(time(x, "days"), "%j")) / 10) + 1
index <- paste0(year, dekad)
prename <- "yd_"
} else if (choice == "weeks") {
index <- strftime(time(x, "days"), format = "%V")
prename <- "week_"
} else if (choice == "yearweeks") {
index <- yearweek(time(x, "days"))
prename <- "yw_"
} else if (choice == "7days") {
index <- as.integer(format(time(x, "days"), "%j"))
index <- as.character((index-1) %/% 7 + 1)
prename <- "d7_"
} else if (choice == "10days") {
index <- as.integer(format(time(x, "days"), "%j"))
index <- as.character((index-1) %/% 10 + 1)
prename <- "d10_"
} else if (choice == "15days") {
index <- as.integer(format(time(x, "days"), "%j"))
index <- as.character((index-1) %/% 15 + 1)
prename <- "d15_"
} else {
index <- time(x, choice)
out_time <- time_as_seconds(x)[!duplicated(index)]
out_tstep <- choice
out_tz <- attr(index, "tzone")
if (is.null(out_tz)) out_tz = "UTC"
if (choice == "yearmonths") {
year <- trunc(index)
month <- 12 * (index - year) + 1
year <- formatC(year, width=4, flag = "0")
month <- formatC(month, width=2, flag = "0")
index <- paste0(year, month)
prename <- "ym_"
} else {
index <- as.character(index)
if (choice == "months") {
prename <- "m_"
} else if (choice == "days") {
prename <- "d_"
} else if (choice == "years") {
prename <- "y_"
}
}
}
} else if (is.function(index)) {
index <- as.character(index(time(x)))
}
}
nl <- nlyr(x)
if (length(index) > nl) {
error("tapp", "length(index) > nlyr(x)")
} else if (length(unique(index)) == 1) {
warn("tapp", "it is not sensible to a single value as index (use app instead)")
}
index <- rep_len(index, nl)
if (!is.factor(index)) {
index <- factor(index, levels=unique(index))
}
nms <- paste0(prename, as.character(index))
ind <- as.integer(index)
d <- unique(data.frame(nms, ind, stringsAsFactors=FALSE))
uin <- d[,2]
nms <- make.names(d[,1])
nms <- nms[uin]
txtfun <- .makeTextFun(fun)
if (inherits(txtfun, "character")) {
if (txtfun %in% .cpp_funs) {
opt <- spatOptions(filename, overwrite, wopt=wopt)
narm <- isTRUE(list(...)$na.rm)
x@pntr <- x@pntr$apply(index, txtfun, narm, nms, out_time, out_tstep, out_tz, opt)
return(messages(x, "tapp"))
}
}
fun <- match.fun(fun)
readStart(x)
on.exit(readStop(x), add=TRUE)
testnc <- min(ncol(x), 11)
v <- readValues(x, 1, 1, 1, testnc, TRUE)
if (any(is.factor(x))) {
warn("app", "factors are coerced to numeric")
}
test <- apply(v, 1, FUN=fun, ...)
transpose = FALSE
nlout <- 1
if (NCOL(test) > 1) {
if (ncol(test) == testnc) {
transpose = TRUE
nlout <- nrow(test)
addnms <- rownames(test)
} else {
nlout <- ncol(test)
addnms <- colnames(test)
}
nms <- paste(rep(nms, each=length(addnms)), rep(addnms, length(nms)), sep="_")
}
out <- rast(x)
nlyr(out) <- nlout * length(uin)
names(out) <- nms
if (out_tstep != "") {
time(out, out_tstep) <- out_time
}
doclust <- FALSE
if (inherits(cores, "cluster")) {
doclust <- TRUE
} else if (cores > 1) {
doclust <- TRUE
cores <- parallel::makeCluster(cores)
on.exit(parallel::stopCluster(cores))
}
b <- writeStart(out, filename, overwrite, sources=sources(x), wopt=wopt)
if (doclust) {
export_args(cores, ..., caller="tapp")
pfun <- function(x, ...) apply(x, 1, FUN=fun, ...)
parallel::clusterExport(cores, "pfun", environment())
for (i in 1:b$n) {
v <- readValues(x, b$row[i], b$nrows[i], 1, ncol(out), TRUE)
v <- lapply(uin, function(i) v[, ind==i, drop=FALSE])
v <- parallel::parLapply(cores, v, pfun, ...)
if (transpose) {
v <- t(do.call(rbind, v))
} else {
v <- do.call(cbind, v)
}
writeValues(out, v, b$row[i], b$nrows[i])
}
} else {
for (i in 1:b$n) {
v <- readValues(x, b$row[i], b$nrows[i], 1, ncol(out), TRUE)
# like this, na.rm is not passed to FUN
# v <- lapply(uin, function(j, ...) apply(v[, ind==uin[j], drop=FALSE], 1, FUN=fun, ...))
# like this it works
v <- lapply(uin, function(j) apply(v[, ind==uin[j], drop=FALSE], 1, FUN=fun, ...))
if (transpose) {
v <- t(do.call(rbind, v))
} else {
v <- do.call(cbind, v)
}
writeValues(out, v, b$row[i], b$nrows[i])
}
}
out <- writeStop(out)
return(out)
}
)
terra/R/click.R 0000644 0001762 0000144 00000006204 14732342353 013010 0 ustar ligges users # Author: Robert J. Hijmans
# Date : January 2009 - December 2011
# Version 1.0
# License GPL v3
#.getClicks <- function(...) {
# res <- list()
# while(TRUE) {
# loc <- graphics::locator(1, ...)
# if (is.null(loc)) break
# res <- c(res, loc)
# }
# matrix(res, ncol=2, byrow=TRUE)
#}
RStudio_warning <- function() {
if (.terra_environment$RStudio_warned) return()
if (Sys.getenv("RSTUDIO_USER_IDENTITY") != "") {
warn("'click', 'draw', and 'sel' may not work properly\nwith the default RStudio plotting window. See ?click")
}
.terra_environment$RStudio_warned <- TRUE
}
.getCellFromClick <- function(x, n, type, id, ...) {
#loc <- graphics::locator(n, type, ...)
#xyCoords <- cbind(x=loc$x, y=loc$y)
xyCoords <- RS_locator(n, type, ...)
if (id) {
text(xyCoords, labels=1:n)
}
cells <- cellFromXY(x, xyCoords)
cells <- unique(stats::na.omit(cells))
if (length(cells) == 0 ) {
error("click", "no valid cells selected")
}
cells
}
do_click <- function(type="p", id=FALSE, i=1, pch=20, ...) {
p <- graphics::locator(1)
if (is.null(p)) return(p) # ESC
points(p$x, p$y, type=type, pch=pch, ...)
if (id) {
text(p$x, p$y, labels=i, pos=4, ...)
}
cbind(x=p$x, y=p$y)
}
setMethod("click", signature(x="missing"),
function(x, n=10, id=FALSE, type="p", show=TRUE, ...) {
RStudio_warning()
#loc <- graphics::locator(n, type, ...)
#cbind(x=loc$x, y=loc$y)
n <- max(1, round(n))
X <- NULL
if (show) {
on.exit(return(invisible(X)))
} else {
on.exit(return(X))
}
for (i in 1:n) {
x <- do_click(type=type, id=id, i=i, ...)
if (is.null(x)) break
X <- rbind(X, x)
if (show) {
rownames(x) <- i
print(x);
utils::flush.console()
}
}
}
)
setMethod("click", signature(x="SpatRaster"),
function(x, n=10, id=FALSE, xy=FALSE, cell=FALSE, type="p", show=TRUE, ...) {
RStudio_warning()
n <- max(round(n), 1)
values <- NULL
if (show) {
on.exit(return(invisible(values)))
} else {
on.exit(return(values))
}
for (i in 1:n) {
p <- do_click(type=type, id=id, i=i, ...)
if (is.null(p)) break
celln <- cellFromXY(x, p)
if (is.na(celln)) next
value <- x[celln]
if (cell) {
value <- data.frame(cell=celln, value)
}
if (xy) {
p <- xyFromCell(x, celln)
colnames(p) <- c("x", "y")
value <- data.frame(p, value)
}
if (show) {
rownames(value) <- i
print(value)
utils::flush.console()
}
# if (is.null(dim(value))) {
# value <- matrix(value)
# colnames(value) <- names(x)
# }
values <- rbind(values, value)
}
})
setMethod("click", signature(x="SpatVector"),
function(x, n=10, id=FALSE, xy=FALSE, type="p", show=TRUE, ...) {
RStudio_warning()
n <- max(round(n), 1)
values <- xys <- NULL
if (show) {
on.exit(return(invisible(values)))
} else {
on.exit(return(values))
}
for (i in 1:n) {
p <- do_click(type=type, id=id, i=i, ...)
if (is.null(p)) break
e <- extract(x, vect(p))
if (xy) {
e <- cbind(e[,1], x=p$x, y=p$y, e[,-1,drop=FALSE])
}
names(e)[1] <- "ID"
if (show) {
rownames(e) <- i
if (!id) {
print(e[,-1])
} else {
print(e)
}
utils::flush.console()
}
values <- rbind(values, e)
}
}
)
terra/R/plotRGB.R 0000644 0001762 0000144 00000001547 14536376240 013245 0 ustar ligges users # Author: Robert J. Hijmans
# Date : April 2010
# Version 0.9
# License GPL v3
# ..linStretch <- function (x) {
# v <- stats::quantile(x, c(0.02, 0.98), na.rm = TRUE)
# temp <- (255 * (x - v[1]))/(v[2] - v[1])
# temp[temp < 0] <- 0
# temp[temp > 255] <- 255
# return(temp)
# }
# # Histogram equalization stretch
# ..eqStretch <- function(x){
# ecdfun <- stats::ecdf(x)
# ecdfun(x)*255
# }
# ..rgbstretch <- function(RGB, stretch, caller="") {
# stretch = tolower(stretch)
# if (stretch == 'lin') {
# RGB[,1] <- ..linStretch(RGB[,1])
# RGB[,2] <- ..linStretch(RGB[,2])
# RGB[,3] <- ..linStretch(RGB[,3])
# } else if (stretch == 'hist') {
# RGB[,1] <- ..eqStretch(RGB[,1])
# RGB[,2] <- ..eqStretch(RGB[,2])
# RGB[,3] <- ..eqStretch(RGB[,3])
# } else if (stretch != '') {
# warn(caller, "invalid stretch value")
# }
# RGB
# }
terra/R/zoom.R 0000644 0001762 0000144 00000001733 14750560571 012715 0 ustar ligges users # Author: Robert J. Hijmans
# Date : September 2009
# Version 0.9
# License GPL v3
setMethod("zoom", signature(x="SpatRaster"),
function(x, e=draw(), maxcell=100000, layer=1, new=FALSE, ...) {
if (grDevices::dev.cur() == 1) {
if (!is.null(RGB(x))) {
plot(x, maxcell=maxcell, ...)
} else {
plot(x, layer, maxcell=maxcell, ...)
}
}
if (is.function(e)) {
# force to start with drawing before creating a new graphics device
e <- e
} else if (!inherits(e, "SpatExtent")) {
e <- ext(e)
}
if (new) {
grDevices::dev.new()
}
window(x) <- e
plot(x, maxcell=maxcell, ...)
return(invisible(e))
}
)
setMethod("zoom", signature(x="SpatVector"),
function(x, e=draw(), new=FALSE, ...) {
if (grDevices::dev.cur() == 1) {
plot(x, ...)
}
if (is.function(e)) {
e <- e
} else if (!inherits(e, "SpatExtent")) {
e <- ext(e)
}
if (new) {
grDevices::dev.new()
}
x <- crop(x, e)
plot(x, ext=e, ...)
return(invisible(e))
}
)
terra/R/watershed.R 0000644 0001762 0000144 00000002302 14726700274 013707 0 ustar ligges users # Author: Emanuele Cordano
# Date : October 2023
# Version 1.0
# License GPL v3
setMethod("watershed", signature(x="SpatRaster"),
function(x, pourpoint, filename="", ...) {
opt <- spatOptions(filename, ...)
cell <- cellFromXY(x, pourpoint)
if (is.na(cell)) error("watershed", "pourpoint not on raster")
x@pntr <- x@pntr$watershed2(as.integer(cell-1), opt)
messages(x, "watershed") ## EC 20210318
}
)
setMethod("pitfinder", signature(x="SpatRaster"),
function(x, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$pitfinder2(opt)
messages(x, "pitfinder") ## EC 20210318
}
)
setMethod("NIDP", signature(x="SpatRaster"),
function(x, filename="", ...) {
opt <- spatOptions(filename, ...)
x@pntr <- x@pntr$NIDP2(opt)
messages(x, "NIDP") ## EC 20231031
}
)
setMethod("flowAccumulation", signature(x="SpatRaster"),
function(x, weight=NULL, filename="", ...) {
opt <- spatOptions(filename, ...)
if (is.null(weight)) {
x@pntr <- x@pntr$flowAccu2(opt)
} else {
x@pntr <- x@pntr$flowAccu2_weight(weight@pntr, opt)
}
messages(x, "flowAccumulation")
}
)
terra/R/clean.R 0000644 0001762 0000144 00000002163 14536376240 013011 0 ustar ligges users
..gaps <- function(x) {
p <- as.polygons(floor(ext(x)+1), crs=crs(x))
e <- disagg(erase(p, x))
if (nrow(e) > 1) {
xmin = ext(p)[1]
i <- sapply(1:nrow(e), function(i) ext(e[i])[1] > xmin)
e <- e[i]
x <- rbind(x, e)
}
x
}
clean_further <- function(x, tolerance=0.0001) {
out <- as.lines(x)
out <- snap(out, tolerance)
out <- makeNodes(out)
out <- mergeLines(out)
as.polygons(out)
}
clean <- function(x) {
g <- gaps(x)
out <- erase(x)
out <- rbind(out, g)
g <- gaps(out)
rbind(out, g)
}
mergebyborder <- function(x, field) {
i <- is.na(x[[field, drop=TRUE]])
if (!any(i)) return(x)
s <- sharedPaths(x)
s$length <- perim(s)
from <- x[i]
x <- x[!i]
for (i in 1:nrow(from)) {
}
}
centerline <- function(p) {
v <- as.points(voronoi(p, tolerance=0))
v <- intersect(v, p)
v
}
#library(terra); messages = terra:::messages
#p <- vect(system.file("ex/lux.shp", package="terra"))
#h <- convHull(p[-12], "NAME_1")
#x <- clean(h)
#y <- clean_further(x)
#hh <- rbind(h, h)
#e <- erase(hh)
#g <- gaps(e)
#v1 = as.polygons(ext(0,1,0,1))
#v2 = as.polygons(ext(1.01,2,0,1))
#v <- rbind(v1, v2)
#s = snap(v)
terra/R/animate.R 0000644 0001762 0000144 00000001341 14734155361 013341 0 ustar ligges users # comment
setMethod("animate", signature(x="SpatRaster"),
function(x, pause=0.25, main, range, maxcell=50000, n=1, ...) {
if (missing(main)) {
main <- names(x)
}
# x <- spatSample(x, size=maxcell, method="regular", as.raster=TRUE, warn=FALSE)
x <- sampleRaster(x, maxcell, method="regular", replace=FALSE, ext=NULL, warn=FALSE, overview=TRUE)
if (missing(range)) {
mnmx <- minmax(x)
range <- c(min(mnmx[1,]), max(mnmx[2,]))
}
nl <- nlyr(x)
n <- max(1, round(n))
i <- 1
reps <- 0
while (reps < n) {
plot(x[[i]], main = main[i], range=range, maxcell=Inf, ...)
grDevices::dev.flush()
Sys.sleep(pause)
i <- i + 1
if (i > nl) {
i <- 1
reps <- reps+1
}
}
}
)
terra/R/dimensions.R 0000644 0001762 0000144 00000007150 14726700274 014077 0 ustar ligges users # Author: Robert J. Hijmans
# Date : June 2017
# Version 0.9
# License GPL v3
setMethod("dim", signature(x="SpatRaster"),
function(x){ return(c(nrow(x), ncol(x), nlyr(x))) }
)
setMethod("dim", signature(x="SpatRasterDataset"),
function(x) {
c(x@pntr$nrow(), x@pntr$ncol())
}
)
setMethod("dim", signature(x="SpatRasterCollection"),
function(x) {
m <- matrix(x@pntr$dims(), ncol=3)
colnames(m) <- c("nrow", "ncol", "nlyr")
m
}
)
setMethod("nrow", signature(x="SpatRasterCollection"),
function(x) {
dim(x)[,1]
}
)
setMethod("ncol", signature(x="SpatRasterCollection"),
function(x) {
dim(x)[,2]
}
)
setMethod("nlyr", signature(x="SpatRasterCollection"),
function(x) {
dim(x)[,3]
}
)
setMethod("nrow", signature(x="SpatRaster"),
function(x){ return(x@pntr$nrow())}
)
setMethod("nrow", signature(x="SpatRasterDataset"),
function(x){ return(x[1]@pntr$nrow())}
)
setMethod("nrow", signature(x="SpatVector"),
function(x){ return(x@pntr$nrow())}
)
setMethod("ncol", signature(x="SpatRaster"),
function(x){ return(x@pntr$ncol()) }
)
setMethod("ncol", signature(x="SpatRasterDataset"),
function(x){ return(x[1]@pntr$ncol())}
)
setMethod("ncol", signature(x="SpatVector"),
function(x){ return(x@pntr$ncol())}
)
setMethod("dim<-", signature(x="SpatRaster"),
function(x, value) {
if (length(value) == 1) {
value <- c(value, ncol(x), nlyr(x))
} else if (length(value) == 2) {
value <- c(value, nlyr(x))
} else if (length(value) > 3) {
warn("dim<-", "value should have length 1, 2, or 3. Additional values ignored")
value <- value[1:3]
}
value <- as.integer(pmax(round(value), c(1,1,1)))
#here we lose all attributes
rast(nrows=value[1], ncols=value[2], nlyrs=value[3], extent=ext(x), crs=crs(x))
}
)
setMethod("ncell", signature(x="SpatRaster"),
function(x) {
return(as.numeric(ncol(x)) * nrow(x))
}
)
setMethod("ncell", signature(x="SpatRasterDataset"),
function(x) {
ncell(x[1])
}
)
setMethod("ncell", signature(x="ANY"),
function(x) {
NROW(x) * NCOL(x)
}
)
setMethod("size", signature(x="SpatRaster"),
function(x) {
x@pntr$size()
}
)
setMethod("nlyr", signature(x="SpatRaster"),
function(x){
return(x@pntr$nlyr() )
}
)
setMethod("nlyr", signature(x="SpatRasterDataset"),
function(x){
return(x@pntr$nlyr() )
}
)
setMethod("nsrc", signature(x="SpatRaster"),
function(x){
return(x@pntr$nsrc() )
}
)
.nlyrBySource <- function(x) {
x@pntr$nlyrBySource();
}
setMethod("ncol<-", signature("SpatRaster", "numeric"),
function(x, value) {
dim(x) <- c(nrow(x), value)
return(x)
}
)
setMethod("nrow<-", signature("SpatRaster", "numeric"),
function(x, value) {
dim(x) <- c(value, ncol(x))
return(x)
}
)
setMethod("nlyr<-", signature("SpatRaster", "numeric"),
function(x, value) {
dim(x) <- c(nrow(x), ncol(x), value)
return(x)
}
)
setMethod("res", signature(x="SpatRaster"),
function(x) {
x@pntr$res
}
)
setMethod("res", signature(x="SpatRasterDataset"),
function(x) {
x@pntr$res()
}
)
setMethod("res<-", signature(x="SpatRaster"),
function(x, value) {
if (length(value) == 1) {
value <- c(value, value)
} else if (length(value) > 2) {
warn("res<-", "value should have length 1 or 2. Additional values ignored")
}
x@pntr <- x@pntr$set_resolution(value[1], value[2])
messages(x, "resolution")
}
)
setMethod("xres", signature(x="SpatRaster"),
function(x) {
res(x)[1]
}
)
setMethod("yres", signature(x="SpatRaster"),
function(x) {
res(x)[2]
}
)
setMethod("datatype", signature(x="SpatRaster"),
function(x, bylyr=TRUE){
d <- x@pntr$getDataType(FALSE, FALSE);
if (bylyr) {
d <- rep(d, sources(x, TRUE)$nlyr)
}
d
}
)
terra/R/messages.R 0000644 0001762 0000144 00000003364 14744467670 013553 0 ustar ligges users # Author: Robert J. Hijmans
# Date : October 2018
# Version 1.0
# License GPL v3
error <- function(f, emsg="", ...) {
stop("[", f, "] ", emsg, ..., call.=FALSE)
}
warn <- function(f, wmsg="", ...) {
warning("[", f, "] ", wmsg, ..., call.=FALSE)
}
messages <- function(x, f="") {
#g <- gc(verbose=FALSE)
if (methods::.hasSlot(x, "pntr")) {
if (x@pntr$has_warning()) {
warn(f, paste(unique(x@pntr$getWarnings()), collapse="\n"))
}
if (x@pntr$has_error()) {
error(f, x@pntr$getError())
}
} else {
if (x$has_warning()) {
warn(f, paste(unique(x$getWarnings()), collapse="\n"))
}
if (x$has_error()) {
error(f, x$getError())
}
}
x
}
mem_info <- function(x, n=1, print=TRUE) {
#print=TRUE
n <- max(0,n)
opt <- spatOptions()
opt$ncopies = n;
v <- x@pntr$mem_needs(opt)
gb <- 1024^3 / 8 #
v[1:2] <- v[1:2] / gb
memmin <- opt$memmin
memmax <- opt$memmax
if (print) {
cat("\n------------------------")
cat("\nMemory (GB) ")
cat("\n------------------------")
cat(paste("\ncheck threshold :", opt$memmin / gb, "(memmin)"))
if (memmax > 0) {
cat(paste("\navailable :", round(v[2], 2), "(memmax)"))
} else {
cat(paste("\navailable :", round(v[2], 2)))
}
cat(paste0("\nallowed (", round(100* v[3]) , "%) : ", round(v[3] * v[2], 2)))
cat(paste0("\nneeded (n=", n, ") ", ifelse(n<10, " : ", ": "), round(v[1], 2)))
cat("\n------------------------")
cat(paste("\nproc in memory :", round(v[5]) != 0))
cat(paste("\nnr chunks :", ceiling(nrow(x)/v[4])))
cat("\n------------------------\n")
}
names(v) <- c("needed", "available", "memfrac", "chunk_rows", "fits_mem")
invisible(v)
}
free_RAM <- function() {
opt <- spatOptions()
x <- rast()
v <- x@pntr$mem_needs(opt)
v[2] / 128
}
terra/R/rapp.R 0000644 0001762 0000144 00000004317 14726700274 012673 0 ustar ligges users
setMethod("rapp", signature(x="SpatRaster"),
function(x, first, last, fun, ..., allyrs=FALSE, fill=NA, clamp=FALSE, circular=FALSE, filename="", overwrite=FALSE, wopt=list()) {
stopifnot(hasValues(x))
firstval <- lastval <- NA
if (inherits(first, "SpatRaster")) {
first <- first[[1]]
stopifnot(hasValues(first))
} else {
if (!is.numeric(first)) {
error("rapp", "argument `first` should be numeric or SpatRaster")
}
firstval <- first
stopifnot(first %in% 1:nlyr(x))
}
if (inherits(last, "SpatRaster")) {
last <- last[[1]]
stopifnot(hasValues(last))
} else {
if (!is.numeric(last)) {
error("rapp", "argument `last` should be numeric or SpatRaster")
}
lastval <- last
stopifnot(last %in% 1:nlyr(x))
}
if (!(is.na(firstval)) && (!(is.na(lastval)))) {
error("rapp", "argument `first` or `last` must be a SpatRaster. Or use `app`")
}
if (!is.na(firstval)) {
index <- last;
} else if (!is.na(lastval)) {
index <- first
} else {
index <- c(first, last)
}
compareGeom(x, index, lyrs=FALSE, crs=FALSE, warncrs=FALSE, ext=TRUE, rowcol=TRUE, res=FALSE)
if (!allyrs) {
txtfun <- .makeTextFun(match.fun(fun))
if (inherits(txtfun, "character")) {
if (txtfun %in% .cpp_funs) {
opt <- spatOptions(filename, overwrite, wopt=wopt)
na.rm <- isTRUE(list(...)$na.rm)
x@pntr <- x@pntr$rapply(index@pntr, firstval, lastval, txtfun, clamp, na.rm, circular, opt)
return(messages(x, "rapp"))
}
}
}
out <- rast(x)
v <- x@pntr$rappvals(index@pntr, firstval, lastval, clamp, allyrs, fill, 0, 1, circular)
v <- sapply(v, fun, ...)
if (is.list(v)) { error("rapp", "values returned by 'fun' do not have the same length for each cell") }
nc <- ncol(out)
trans = FALSE
if (NCOL(v) == nc) {
trans = TRUE
nlyr(out) <- nrow(v)
} else if (NROW(v) == nc) {
nlyr(out) <- NCOL(v)
} else if (length(v) == nc) {
nlyr(out) <- 1
}
b <- writeStart(out, filename, overwrite, sources=sources(x), wopt=wopt, n=nlyr(x)*3)
for (i in 1:b$n) {
v <- x@pntr$rappvals(index@pntr, firstval, lastval, clamp, allyrs, fill, b$row[i]-1, b$nrows[i], circular)
v <- sapply(v, fun, ...)
if (trans) v = t(v)
writeValues(out, as.vector(v), b$row[i], b$nrows[i])
}
out <- writeStop(out)
return(out)
}
)
terra/R/polygons.R 0000644 0001762 0000144 00000000000 14536376240 013565 0 ustar ligges users terra/R/makeVRT.R 0000644 0001762 0000144 00000007464 14536376240 013251 0 ustar ligges users # Author: Robert J. Hijmans
# Date : October 2010, January 2022
# Version 1.0
# Licence GPL v3
gdalDType <- function(dtype) {
dps <- c("INT2S", "INT4S", "INT1U", "INT2U", "INT4U", "FLT4S", "FLT8S")
if (!(dtype %in% dps)) {
stop(paste(dtype, "is not a valid data type. Should be one of:", paste(dps, collapse=", ")))
}
bytesize <- as.integer(substr(dtype, 4, 4))
size <- bytesize * 8
type <- substr(dtype, 1, 3)
if (type == "INT") {
type <- "Int"
if (size == 64) {
size <- 32
warning("8 byte integer values not supported by GDAL, changed to 4 byte integer values")
}
if (substr(dtype, 5, 5) == "U") {
if (size == 8) {
return(c("Byte", 1))
} else {
type <- paste("U", type, sep="")
}
}
} else {
type <- "Float"
}
return(c(paste0(type, size), bytesize))
}
makeVRT <- function(filename, nrow, ncol, nlyr=1, extent, xmin, ymin, xres, yres=xres, xycenter=TRUE, crs="+proj=longlat", lyrnms="", datatype, NAflag=NA, bandorder="BIL", byteorder="LSB", toptobottom=TRUE, offset=0, scale=1) {
stopifnot(length(filename)==1)
stopifnot(file.exists(filename))
if (tolower(tools::file_ext(filename)) == "vrt") {
stop("cannot (over)write a vrt header for a vrt file")
}
lyrnms <- rep(lyrnms, length.out=nlyr)
fvrt <- paste0(filename, ".vrt")
if (missing(datatype)) {
bytes <- file.info(filename)$size / (3601 * 3601)
if (bytes == 1) {
datatype <- "INT1U"
} else if (bytes == 2) {
datatype <- "INT2U"
} else if (bytes == 4) {
datatype <- "FLT4S"
} else if (bytes == 8) {
datatype <- "FLT8S"
}
}
gd <- gdalDType(datatype[1])
datatype <- gd[1]
pixsize <- as.integer(gd[2])
if (bandorder[1] == "BIL") {
pixoff <- pixsize
lineoff <- pixsize * ncol * nlyr
imgoff <- ((1:nlyr)-1) * ncol * pixsize
} else if (bandorder[1] == "BSQ") {
pixoff <- pixsize
lineoff <- pixsize * ncol
imgoff <- ((1:nlyr)-1) * nrow*ncol * pixsize
} else if (bandorder[1] == "BIP") {
pixoff <- pixsize * nlyr
lineoff <- pixsize * ncol * nlyr
imgoff <- (1:nlyr)-1
} else {
stop("unknown bandorder")
}
stopifnot(byteorder[1] %in% c("LSB", "MSB"))
if (toptobottom[1]) { rotation <- 0 } else { rotation <- 180 }
res <- abs(c(xres, yres))
if (missing(extent)) {
if (xycenter) {
xmin <- xmin - res[1]/2
ymin <- ymin - res[2]/2
}
ymax <- ymin + nrow * res[2]
} else {
xmin <- xmin(extent)
ymax <- ymax(extent)
}
f <- file(fvrt, "w")
cat('\n' , sep = "", file = f)
cat('', xmin, ', ', res[1], ', ', rotation, ', ', ymax, ', ', 0.0, ', ', -1*res[2], '\n', sep = "", file = f)
if (! is.na(crs) ) {
cat('', crs ,'\n', sep = "", file = f)
}
for (i in nlyr) {
cat('\t\n', sep = "" , file = f)
cat('\t\t', lyrnms[i], '\n', sep = "", file = f)
cat('\t\t', basename(filename), '\n', sep = "", file = f)
cat('\t\t', imgoff[i], '\n', sep = "", file = f)
cat('\t\t', pixoff, '\n', sep = "", file = f)
cat('\t\t', lineoff, '\n', sep = "", file = f)
cat('\t\t', byteorder, '\n', sep = "", file = f)
if (!is.na(NAflag)) {
cat('\t\t', NAflag, '\n', sep = "", file = f)
}
if (isTRUE(offset != 0) || isTRUE(scale != 1)) {
cat('\t\t', offset, '\n', sep = "", file = f)
cat('\t\t', scale, '\n', sep = "", file = f)
}
cat('\t\n', sep = "", file = f)
}
cat('\n', sep = "", file = f)
close(f)
return(fvrt)
}
# a = makeVRT(ff[1], 3601, 3601, 1, xmin=37, ymin=37, xres=1/3600, lyrnms="aspect", datatype="INT2U", byteorder="MSB")
terra/R/crs.R 0000644 0001762 0000144 00000017726 14726701261 012525 0 ustar ligges users # Author: Robert J. Hijmans
# Date : January 2009
# Version 0.9
# License GPL v3
character_crs <- function(x, caller="") {
if (!inherits(x, "character")) {
if (is.atomic(x)) {
# for logical NA
x <- as.character(x)
} else {
x <- crs(x)
}
}
if (is.na(x)) {
""
} else {
if (tolower(x) == "local") {
x <- 'LOCAL_CS["Cartesian (Meter)", LOCAL_DATUM["Local Datum",0], UNIT["Meter",1.0], AXIS["X",EAST], AXIS["Y",NORTH]]'
} else if (tolower(x) == "lonlat") {
x <- "+proj=longlat"
}
x
}
}
is.proj <- function(crs) {
substr(crs, 1, 6) == "+proj="
}
.check_proj4_datum <- function(crs) {
crs <- trimws(tolower(crs))
if (!is.proj(crs)) return()
x <- trimws(unlist(strsplit(crs, "\\+")))
d <- grep("datum=", x, value=TRUE)
if (length(d) > 0) {
d <- gsub("datum=", "", d)
if (!(d %in% c("wgs84", "nad83", "nad27"))) {
warn("crs<-", "Only the WGS84, NAD83 and NAD27 datums can be used with a PROJ.4 string. Use WKT2, authority:code, or +towgs84= instead")
}
}
#d <- grep("towgs84=", x, value=TRUE)
#if (length(d) > 0) {
# warn("crs<-", "+towgs84 parameters in a PROJ4 string are ignored")
#}
}
.proj4 <- function(x) {
x@pntr$get_crs("proj4")
}
.name_from_wkt <- function(wkt) {
s = strsplit(wkt, ",")[[1]][1]
strsplit(s, "\"")[[1]][[2]]
}
.name_or_proj4 <- function(x) {
if (inherits(x, "SpatVectorProxy")) {
tptr <- x@pntr$v
} else if (inherits(x, "Rcpp_SpatRaster")) {
tptr <- x
} else {
tptr <- x@pntr
}
wkt <- tptr$get_crs("wkt")
d <- .srs_describe(wkt)
r <- tptr$get_crs("proj4")
if (!(d$name %in% c(NA, "unknown", "unnamed"))) {
if (substr(r, 1, 13) == "+proj=longlat") {
r <- paste("lon/lat", d$name)
} else {
r <- d$name
}
if (!is.na(d$code)) {
r <- paste0(r, " (", d$authority, ":", d$code, ")")
}
}
if (r == "") {
rr <- try(.name_from_wkt(wkt), silent=TRUE)
if (!inherits(rr, "try-error")) {
r <- rr
}
}
r
}
.srs_describe <- function(srs) {
info <- .SRSinfo(srs)
names(info) <- c("name", "authority", "code", "area", "extent")
d <- data.frame(t(info), stringsAsFactors=FALSE)
d$area <- gsub("\\.$", "", d$area)
d[d == ""] <- NA
if (is.na(d$extent)) {
d$extent <- list(c(NA, NA, NA, NA))
} else {
d$extent <- list(as.numeric(unlist(strsplit(d$extent, ","))))
}
d
}
.get_CRS <- function(x, proj=FALSE, describe=FALSE, parse=FALSE) {
if (describe) {
d <- .srs_describe(x@pntr$get_crs("wkt"))
if (proj) {
d$proj <- x@pntr$get_crs("proj4")
}
d
} else if (proj) {
x@pntr$get_crs("proj4")
} else {
r <- x@pntr$get_crs("wkt")
if (parse) {
unlist(strsplit(r, "\n"))
} else {
r
}
}
}
setMethod("crs", signature("character"),
function(x, proj=FALSE, describe=FALSE, parse=FALSE) {
x <- rast(crs=x)
.get_CRS(x, proj=proj, describe=describe, parse=parse)
}
)
setMethod("crs", signature("SpatExtent"),
function(x, proj=FALSE, describe=FALSE, parse=FALSE) {
return("")
}
)
setMethod("crs", signature("SpatRaster"),
function(x, proj=FALSE, describe=FALSE, parse=FALSE) {
.get_CRS(x, proj=proj, describe=describe, parse=parse)
}
)
setMethod("crs", signature("SpatRasterDataset"),
function(x, proj=FALSE, describe=FALSE, parse=FALSE) {
if (length(x) > 0) {
.get_CRS(x[[1]], proj=proj, describe=describe, parse=parse)
} else {
NULL
}
}
)
.txtCRS <- function(x, warn=TRUE) {
if (inherits(x, "SpatVector") | inherits(x, "SpatRaster")) {
x <- crs(x)
}
if (is.null(x) || is.na(x)) {
x <- ""
} else if (inherits(x, "CRS")) {
if (warn) warn("crs", "expected a character string, not a CRS object")
y <- attr(x, "comment")
if (is.null(y)) {
y <- x@projargs
if (is.na(y)) y <- ""
}
x <- y
} else if (is.character(x)) {
x <- x[1]
lowx <- tolower(x)
if (lowx == "local") {
x = 'LOCAL_CS["Cartesian (Meter)", LOCAL_DATUM["Local Datum",0], UNIT["Meter",1.0], AXIS["X",EAST], AXIS["Y",NORTH]]'
} else if (lowx == "lonlat") {
x <- "+proj=longlat"
}
} else {
error("crs", "I do not know what to do with this argument (expected a character string)")
}
.check_proj4_datum(x)
x
}
setMethod("crs<-", signature("SpatRaster", "ANY"),
function(x, warn=FALSE, value) {
if (missing(value)) {
value <- warn
warn <- FALSE
}
value <- .txtCRS(value)
if (warn && (crs(x) != "") && (value != "")) {
message("Assigning a new crs. Use 'project' to transform a SpatRaster to a new crs")
}
x@pntr <- x@pntr$deepcopy()
x@pntr$set_crs(value)
messages(x, "crs<-")
}
)
setMethod("set.crs", signature("SpatRaster"),
function(x, value) {
value <- .txtCRS(value)
x@pntr$set_crs(value)
messages(x, "set_crs")
invisible(TRUE)
}
)
#setMethod("crs<-", signature("SpatRaster", "character"),
# function(x, ..., value) {
# x@pntr$set_crs(value[1])
# messages(x, "crs<-")
# }
#)
setMethod("crs", signature("SpatVector"),
function(x, proj=FALSE, describe=FALSE, parse=FALSE) {
.get_CRS(x, proj=proj, describe=describe, parse=parse)
}
)
setMethod("crs", signature("SpatVectorProxy"),
function(x, proj=FALSE, describe=FALSE, parse=FALSE) {
v <- vect()
v@pntr <- x@pntr$v
.get_CRS(v, proj=proj, describe=describe, parse=parse)
}
)
setMethod("crs", signature("SpatVectorCollection"),
function(x, proj=FALSE, describe=FALSE, parse=FALSE) {
if (length(x) > 0) {
.get_CRS(x[[1]], proj=proj, describe=describe, parse=parse)
} else {
NULL
}
}
)
setMethod("crs", signature("sf"),
function(x, proj=FALSE, describe=FALSE, parse=FALSE) {
xcrs <- attr(x[[ attr(x, "sf_column") ]], "crs")$wkt
x <- vect(cbind(0,0), crs=xcrs)
.get_CRS(x, proj=proj, describe=describe, parse=parse)
}
)
setMethod("crs<-", signature("SpatVector", "ANY"),
function(x, warn=FALSE, value) {
if (missing(value)) {
value <- warn
warn <- FALSE
}
value <- .txtCRS(value)
if (warn && (crs(x) != "") && (value != "")) {
message("Assigning a new crs. Use 'project' to transform a SpatVector to a new crs")
}
x@pntr <- x@pntr$deepcopy()
x@pntr$set_crs(value)
messages(x, "crs<-")
}
)
setMethod("set.crs", signature("SpatVector"),
function(x, value) {
value <- .txtCRS(value)
x@pntr$set_crs(value)
messages(x, "set_crs")
}
)
setMethod("is.lonlat", signature("SpatRaster"),
function(x, perhaps=FALSE, warn=TRUE, global=FALSE) {
if (perhaps) {
ok <- x@pntr$isLonLat()
if (ok) {
messages(x, "is.lonlat")
if (global) {
return(x@pntr$isGlobalLonLat())
} else {
return(ok)
}
}
ok <- x@pntr$couldBeLonLat()
if (ok) {
messages(x, "is.lonlat")
if (global) {
ok <- x@pntr$isGlobalLonLat()
}
}
if (ok && warn) {
warn("is.lonlat", "assuming lon/lat crs")
}
} else {
ok <- x@pntr$isLonLat()
if (ok) {
messages(x, "is.lonlat")
if (global) {
ok <- x@pntr$isGlobalLonLat()
}
} else if (crs(x) == "") {
ok <- NA
warn("is.lonlat", "unknown crs")
}
}
ok
}
)
setMethod("is.lonlat", signature("SpatVector"),
function(x, perhaps=FALSE, warn=TRUE) {
if (perhaps) {
ok <- x@pntr$isLonLat()
if (ok) {
messages(x, "is.lonlat")
return(ok)
}
ok <- x@pntr$couldBeLonLat()
if (ok) {
messages(x, "is.lonlat")
}
if (ok && warn) {
warn("is.lonlat", "assuming lon/lat crs")
}
} else {
ok <- x@pntr$isLonLat()
if (ok) {
messages(x, "is.lonlat")
} else if (crs(x) == "") {
ok <- NA
warn("is.lonlat", "unknown crs")
}
}
ok
}
)
setMethod("is.lonlat", signature("character"),
function(x, perhaps=FALSE, warn=TRUE) {
x <- rast(crs=x)
is.lonlat(x, perhaps=perhaps, warn=warn)
}
)
same.crs <- function(x, y) {
if (!is.character(x)) {
x <- crs(x)
}
if (!is.character(y)) {
y <- crs(y)
}
if (inherits(x, "CRS")) {
if (!is.null(comment(x))) {
x <- comment(x)
} else {
x <- x@projargs
}
}
if (inherits(y, "CRS")) {
if (!is.null(comment(y))) {
y <- comment(y)
} else {
y <- y@projargs
}
}
if (is.na(x)) x <- ""
if (is.na(y)) x <- ""
if (!is.character(x)) {
x <- as.character(x)
}
if (!is.character(y)) {
y <- as.character(y)
}
.sameSRS(x, y)
}
terra/R/tiles.R 0000644 0001762 0000144 00000007533 14735447263 013062 0 ustar ligges users
setMethod("makeTiles", signature(x="SpatRaster"),
function(x, y, filename="tile_.tif", extend=FALSE, na.rm=FALSE, buffer=0, overwrite=FALSE, ...) {
filename <- trimws(filename[1])
filename <- filename[!is.na(filename)]
if (filename == "") error("makeTiles", "filename cannot be empty")
opt <- spatOptions(filename="", overwrite=overwrite, ...)
if (inherits(y, "SpatRaster")) {
ff <- x@pntr$make_tiles(y@pntr, extend[1], buffer, na.rm[1], filename, opt)
} else if (inherits(y, "SpatVector")) {
ff <- x@pntr$make_tiles_vect(y@pntr, extend[1], buffer, na.rm[1], filename, opt)
} else if (is.numeric(y)) {
if (length(y) > 2) {
error("makeTiles", "expected one or two numbers")
}
y <- rep_len(y, 2)
y <- aggregate(rast(x), y)
ff <- x@pntr$make_tiles(y@pntr, extend[1], buffer, na.rm[1], filename, opt)
} else {
error("makeTiles", "y must be numeric or a SpatRaster or SpatVector")
}
messages(x, "makeTiles")
ff
}
)
setMethod("getTileExtents", signature(x="SpatRaster"),
function(x, y, extend=FALSE, buffer=0) {
opt <- spatOptions(filename="")
if (inherits(y, "SpatRaster")) {
e <- x@pntr$get_tiles_ext(y@pntr, extend[1], buffer)
} else if (inherits(y, "SpatVector")) {
e <- x@pntr$get_tiles_ext_vect(y@pntr, extend[1], buffer)
} else if (is.numeric(y)) {
if (length(y) > 2) {
error("getTileExtents", "expected one or two numbers")
}
y <- rep_len(y, 2)
y <- aggregate(rast(x), y)
e <- x@pntr$get_tiles_ext(y@pntr, extend[1], buffer)
} else {
error("getTileExtents", "y must be numeric or a SpatRaster or SpatVector")
}
messages(x, "getTileExtents")
e <- matrix(e, ncol=4, byrow=FALSE)
colnames(e) <- c("xmin", "xmax", "ymin", "ymax")
e
}
)
# if (!hasValues(x)) error("makeTiles", "x has no values")
# y <- rast(y)[[1]]
# if (expand) y <- expand(y, ext(x), snap="out")
# y <- crop(rast(y)[[1]], x, snap="out")
# d <- 1:ncell(y)
# if (length(filename) == 0) error("tiler", "no valid filename supplied")
# e <- paste0(".", tools::file_ext(filename))
# f <- tools::file_path_sans_ext(filename)
# ff <- paste0(f, d, e)
# for (i in d) {
# crop(x, y[i,drop=FALSE], filename=ff[i], ...)
# }
# ff[file.exists(ff)]
# }
#)
setMethod("vrt", signature(x="character"),
function(x, filename="", options=NULL, overwrite=FALSE, set_names=FALSE, return_filename=FALSE) {
opt <- spatOptions(filename, overwrite=overwrite)
r <- rast()
if (is.null(options)) {
options=""[0]
}
f <- r@pntr$make_vrt(x, options, opt)
messages(r, "vrt")
messages(opt, "vrt")
if (set_names) {
v <- readLines(f)
nms <- names(rast(x[1]))
i <- grep("band=", v)
if (length(i) == length(nms)) {
nms <- paste0("", nms, "")
v[i] <- paste(v[i], nms)
writeLines(v, f)
}
}
if (return_filename) {
f
} else {
rast(f)
}
}
)
setMethod("vrt", signature(x="SpatRasterCollection"),
function(x, filename="", options=NULL, overwrite=FALSE, return_filename=FALSE) {
opt <- spatOptions(filename, overwrite=overwrite)
if (is.null(options)) {
options=""[0]
}
f <- x@pntr$make_vrt(options, FALSE, opt)
messages(x, "vrt")
if (return_filename) {
f
} else {
rast(f)
}
}
)
vrt_tiles <- function(x) {
if (inherits(x, "SpatRaster")) {
x <- sources(x)
}
if (!inherits(x, "character")) {
error("vrt_sources", "x must be a filename (character) or SpatRaster)")
}
x <- grep(".vrt$", x, ignore.case =TRUE, value=TRUE)
if (length(x) == 0) {
error("vrt_sources", 'no filenames with extension ".vrt"')
}
tiles <- lapply(x, function(f) {
v <- readLines(f)
v <- v[grep("SourceFilename", v)]
s <- strsplit(v, "\"")
rel <- sapply(s, function(x) x[2])
ff <- strsplit(sapply(s, function(x) x[3]), "<")
ff <- gsub(">", "", sapply(ff, function(x) x[1]))
ff[rel=="1"] <- file.path(dirname(f), ff[rel=="1"])
ff
})
unlist(tiles)
}
terra/R/k_means.R 0000644 0001762 0000144 00000003661 14741601752 013345 0 ustar ligges users
setMethod("k_means", signature(x="ANY"),
function(x, centers=3, ...) {
stats::kmeans(x, centers=centers, ...)
}
)
setMethod("k_means", signature(x="SpatRaster"),
function(x, centers=3, ..., maxcell=1000000, filename="", overwrite=FALSE, wopt=list()) {
stopifnot(maxcell > 0)
if (ncell(x) <= maxcell) {
v <- na.omit(values(x))
omit <- as.vector(attr(v, "na.action"))
km <- stats::kmeans(v, centers=centers, ...)
out <- rast(x, nlyr=1)
if (is.null(omit)) {
values(out) <- km$cluster
} else {
out[-omit] <- km$cluster
}
if (filename != "") {
out <- writeRaster(out, filename=filename, overwrite=overwrite, wopt=wopt)
}
} else {
#pkmeans = function(x, newdata) {
# apply(newdata, 1, function(i) which.min(colSums((t(x$centers) - i)^2)))
#}
pkmeans <- function(x, newdata) {
vec <- integer(nrow(newdata))
newdata <- as.matrix(newdata)
for (i in seq_len(nrow(newdata))) {
vec[i] <- which.min(colSums((t(x) - newdata[i, ])^2))
}
vec
}
v <- unique(na.omit(spatSample(x, maxcell, "regular")))
km <- stats::kmeans(v, centers=centers, ...)$centers
out <- predict(x, km, fun=pkmeans, na.rm=TRUE, filename=filename, overwrite=overwrite, wopt=wopt)
}
out
}
)
h_clust <- function(x, ngroups, dist_metric="euclidean", clust_method="complete", agfun=mean, matchfun="squared", ..., maxcell=10000, filename="", overwrite=FALSE, wopt=list()) {
stopifnot(maxcell > 0)
stopifnot(ngroups > 0)
stopifnot(ngroups < maxcell)
d <- na.omit(spatSample(x, maxcell, "regular"))
dd <- stats::dist(d, dist_metric)
hc <- stats::hclust(dd, clust_method)
th <- sort(hc$height, TRUE)[ngroups]
cls <- stats::cutree(hc, h = th)
hc <- cut(stats::as.dendrogram(hc), h=th)$upper
d <- aggregate(d, list(cls=cls), agfun)
cls <- d$cls
d$cls <- NULL
b <- bestMatch(x, d, fun=matchfun, ..., filename=filename, overwrite=overwrite, wopt=wopt)
return(list(clusters=b, dendrogram=hc))
}
terra/R/merge.R 0000644 0001762 0000144 00000004072 14735571636 013036 0 ustar ligges users # Author: Robert J. Hijmans
# Date : June 2019
# Version 1.0
# License GPL v3
setMethod("merge", signature(x="SpatVector", y="data.frame"),
function(x, y, ...) {
v <- values(x)
v$unique_nique_ique_que_e <- 1:nrow(v)
m <- merge(v, y, ...)
m <- m[order(m$unique_nique_ique_que_e), ]
x <- x[stats::na.omit(m$unique_nique_ique_que_e), ]
m$unique_nique_ique_que_e <- NULL
if (nrow(m) > nrow(x)) {
error("merge", "using 'all.y=TRUE' is not allowed. Should it be?")
}
values(x) <- m
x
}
)
setMethod("merge", signature(x="SpatVector", y="SpatVector"),
function(x, y, ...) {
merge(x, data.frame(y), ...)
}
)
setMethod("merge", signature(x="SpatRasterCollection", "missing"),
function(x, first=TRUE, na.rm=TRUE, algo=1, method=NULL, filename="", ...) {
opt <- spatOptions(filename, ...)
out <- rast()
if (is.null(method)) method = ""
out@pntr <- x@pntr$merge(first[1], na.rm, algo, method, opt)
if (algo == 3) {
messages(opt, "merge")
}
messages(x, "merge")
messages(out, "merge")
}
)
setMethod("merge", signature(x="SpatRaster", y="SpatRaster"),
function(x, y, ..., first=TRUE, na.rm=TRUE, algo=1, method=NULL, filename="", overwrite=FALSE, wopt=list()) {
rc <- sprc(x, y, ...)
merge(rc, first=first, na.rm=na.rm, algo=algo, method=method, filename=filename, overwrite=overwrite, wopt=wopt)
}
)
setMethod("mosaic", signature(x="SpatRaster", y="SpatRaster"),
function(x, y, ..., fun="mean", filename="", overwrite=FALSE, wopt=list()) {
fun <- .makeTextFun(fun)
if (!inherits(fun, "character")) {
error("mosaic", "function 'fun' is not valid")
}
opt <- spatOptions(filename, overwrite, wopt=wopt)
rc <- sprc(x, y, ...)
x@pntr <- rc@pntr$mosaic(fun, opt)
messages(x, "mosaic")
}
)
setMethod("mosaic", signature(x="SpatRasterCollection", "missing"),
function(x, fun="mean", filename="", ...) {
opt <- spatOptions(filename, ...)
out <- rast()
fun <- .makeTextFun(fun)
if (!inherits(fun, "character")) {
error("mosaic", "function 'fun' is not valid")
}
out@pntr <- x@pntr$mosaic(fun, opt)
messages(out, "mosaic")
}
)
terra/R/extent.R 0000644 0001762 0000144 00000013736 14753770106 013246 0 ustar ligges users # Author: Robert J. Hijmans
# Date : October 2017
# Version 0.9
# License GPL v3
setMethod("ext", signature(x="SpatExtent"),
function(x){
x@pntr <- x@pntr$deepcopy()
x
}
)
setMethod("ext", signature(x="SpatRasterCollection"),
function(x){
e <- methods::new("SpatExtent")
e@pntr <- x@pntr$extent()
e
}
)
setMethod("ext", signature(x="sf"),
function(x){
sfi <- attr(x, "sf_column")
geom <- x[[sfi]]
e <- attr(geom, "bbox")
ext(e[c(1,3,2,4)])
}
)
setMethod("ext", signature(x="missing"),
function(x){
e <- methods::new("SpatExtent")
e@pntr <- SpatExtent$new()
e
}
)
setMethod("ext", signature(x="numeric"),
function(x, ..., xy=FALSE){
dots <- as.vector(unlist(list(...)))
x <- c(x, dots)
n <- length(x)
if (n != 4) {
error("ext", "expected four numbers")
}
names(x) <- NULL
e <- methods::new("SpatExtent")
if (xy) {
e@pntr <- SpatExtent$new(x[1], x[3], x[2], x[4])
} else {
e@pntr <- SpatExtent$new(x[1], x[2], x[3], x[4])
}
if (!e@pntr$valid) {
error("ext", "invalid extent")
}
e
}
)
setMethod("ext", signature(x="matrix"),
function(x){
if ((ncol(x) == 2) && (nrow(x) > 2)) {
x <- apply(x, 2, range, na.rm=TRUE)
}
ext(as.vector(x))
}
)
setMethod("ext", signature(x="bbox"),
function(x){
ext(x[c(1,3,2,4)])
}
)
setMethod("ext", signature(x="SpatRaster"),
function(x, cells=NULL){
if (!is.null(cells)) {
cells <- stats::na.omit(unique(round(cells)))
cells <- cells[cells > 0 & cells <= ncell(x)]
if (length(cells) < 1) {
stop("no valid cells")
}
r <- res(x)
dx <- r[1] * c(-0.5, 0.5)
dy <- r[2] * c(-0.5, 0.5)
ext(range(xFromCell(x, cells)) + dx, range(yFromCell(x, cells)) + dy)
} else {
e <- methods::new("SpatExtent")
e@pntr <- x@pntr$extent
return(e)
}
}
)
setMethod("ext", signature(x="SpatRasterDataset"),
function(x){
e <- methods::new("SpatExtent")
e@pntr <- x@pntr$ext()
return(e)
}
)
setMethod("ext<-", signature("SpatRaster", "SpatExtent"),
function(x, value) {
x@pntr <- x@pntr$deepcopy()
x@pntr$extent <- value@pntr
messages(x, "ext<-")
}
)
setMethod("ext<-", signature("SpatRaster", "numeric"),
function(x, value) {
e <- ext(value)
x@pntr <- x@pntr$deepcopy()
x@pntr$extent <- e@pntr
messages(x, "ext<-")
}
)
setMethod("set.ext", signature("SpatRaster"),
function(x, value) {
e <- ext(value)
x@pntr$extent <- e@pntr
messages(x, "set_ext")
invisible(TRUE)
}
)
setMethod("ext", signature(x="SpatVector"),
function(x) {
e <- methods::new("SpatExtent")
e@pntr <- x@pntr$extent()
e
}
)
setMethod("ext", signature(x="SpatVectorCollection"),
function(x) {
e <- sapply(x, function(e) as.vector(ext(e)))
ext(min(e[1,]), max(e[2,]), min(e[3,]), max(e[4,]))
}
)
setMethod("ext", signature(x="SpatVectorProxy"),
function(x) {
e <- methods::new("SpatExtent")
e@pntr <- x@pntr$v$extent()
e
}
)
setMethod("ext", signature(x="Extent"),
function(x) {
ext(as.vector(x))
}
)
setMethod("ext", signature(x="Raster"),
function(x) {
ext(x@extent)
}
)
setMethod("ext", signature(x="Spatial"),
function(x) {
ext(as.vector(t(x@bbox)))
}
)
setMethod("xmin", signature(x="SpatExtent"),
function(x){
x@pntr$vector[1]
}
)
setMethod("xmax", signature(x="SpatExtent"),
function(x){
x@pntr$vector[2]
}
)
setMethod("ymin", signature(x="SpatExtent"),
function(x){
x@pntr$vector[3]
}
)
setMethod("ymax", signature(x="SpatExtent"),
function(x){
x@pntr$vector[4]
}
)
setMethod("xmin<-", signature("SpatExtent", "numeric"),
function(x, value){
v <- as.vector(x)
v[1] <- value
ext(v)
}
)
setMethod("xmax<-", signature("SpatExtent", "numeric"),
function(x, value){
v <- as.vector(x)
v[2] <- value
ext(v)
}
)
setMethod("ymin<-", signature("SpatExtent", "numeric"),
function(x, value){
v <- as.vector(x)
v[3] <- value
ext(v)
}
)
setMethod("ymax<-", signature("SpatExtent", "numeric"),
function(x, value){
v <- as.vector(x)
v[4] <- value
ext(v)
}
)
setMethod("xmin", signature(x="SpatRaster"),
function(x){
xmin(ext(x))
}
)
setMethod("xmax", signature(x="SpatRaster"),
function(x){
xmax(ext(x))
}
)
setMethod("ymin", signature(x="SpatRaster"),
function(x){
ymin(ext(x))
}
)
setMethod("ymax", signature(x="SpatRaster"),
function(x){
ymax(ext(x))
}
)
setMethod("xmin<-", signature("SpatRaster", "numeric"),
function(x, value){
v <- as.vector(ext(x))
v[1] <- value
x@pntr <- x@pntr$deepcopy()
ext(x) <- ext(v)
x
}
)
setMethod("xmax<-", signature("SpatRaster", "numeric"),
function(x, value){
v <- as.vector(ext(x))
v[2] <- value
x@pntr <- x@pntr$deepcopy()
ext(x) <- ext(v)
x
}
)
setMethod("ymin<-", signature("SpatRaster", "numeric"),
function(x, value){
v <- as.vector(ext(x))
v[3] <- value
x@pntr <- x@pntr$deepcopy()
ext(x) <- ext(v)
x
}
)
setMethod("ymax<-", signature("SpatRaster", "numeric"),
function(x, value){
v <- as.vector(ext(x))
v[4] <- value
x@pntr <- x@pntr$deepcopy()
ext(x) <- ext(v)
x
}
)
setMethod("xmin", signature(x="SpatVector"),
function(x){
xmin(ext(x))
}
)
setMethod("xmax", signature(x="SpatVector"),
function(x){
xmax(ext(x))
}
)
setMethod("ymin", signature(x="SpatVector"),
function(x){
ymin(ext(x))
}
)
setMethod("ymax", signature(x="SpatVector"),
function(x){
ymax(ext(x))
}
)
setMethod("$", "SpatExtent",
function(x, name) {
as.vector(x)[name]
}
)
setMethod("$<-", "SpatExtent",
function(x, name, value) {
e <- as.vector(x)
e[name] <- value
ext(e)
}
)
setMethod("[", c("SpatExtent", "missing", "missing"),
function(x, i, j) {
as.vector(x)
}
)
setMethod("[", c("SpatExtent", "numeric", "missing"),
function(x, i, j) {
x <- as.vector(x)
x[i]
}
)
setReplaceMethod("[", c("SpatExtent", "numeric", "missing"),
function(x, i, j, value) {
e <- as.vector(x)
stopifnot(all(i %in% 1:4))
e[i] <- value
ext(e)
}
)
setMethod("is.valid", signature(x="SpatExtent"),
function(x) {
x@pntr$valid
#x@pntr$valid_notempty
}
)
setMethod("is.empty", signature(x="SpatExtent"),
function(x) {
x@pntr$empty
}
)
terra/R/gdal.R 0000644 0001762 0000144 00000007637 14756505507 012655 0 ustar ligges users
fileBlocksize <- function(x) {
v <- x@pntr$getFileBlocksize()
m <- matrix(v, ncol=2)
colnames(m) <- c("rows", "cols")
m
}
clearVSIcache <- function() {
.clearVSIcache(TRUE)
}
gdalCache <- function(size=NA) {
vsi <- FALSE # vsi not working
if (is.null(size) || is.na(size)) {
.getGDALCacheSizeMB(vsi)
} else if (size > 0) {
.setGDALCacheSizeMB(size, vsi)
}
}
getGDALconfig <- function(option) {
sapply(option, .gdal_getconfig)
}
setGDALconfig <- function(option, value="") {
value <- rep_len(value, length(option))
for (i in 1:length(option)) {
if (grepl("=", option[i])) {
opt <- trimws(unlist(strsplit(option[i], "="))[1:2])
.gdal_setconfig(opt[1], opt[2])
} else {
.gdal_setconfig(trimws(option[i]), trimws(value[i]))
}
}
}
libVersion <- function(lib="all", parse=FALSE) {
lib <- tolower(lib)
if (lib=="gdal") {
out <- .gdal_version()
} else if (lib=="proj") {
out <- proj_version()
} else if (lib=="geos") {
out <- .geos_version()
} else {
out <- c(gdal=.gdal_version(), proj=proj_version(), geos=.geos_version())
}
if (parse) {
nms <- names(out)
out <- data.frame(matrix(as.numeric(unlist(strsplit(out, "\\."))), ncol=3, byrow=TRUE), row.names=nms)
names(out) <- c("major", "minor", "sub")
}
out
}
gdal <- function(warn=NA, drivers=FALSE, ...) {
if (!is.na(warn)) {
warn <- as.integer(warn)
stopifnot(warn %in% (1:4))
.set_gdal_warnings(warn)
} else if (drivers) {
x <- .gdaldrivers()
x <- do.call(cbind, x)
x <- data.frame(x)
x[,2] = c(FALSE, TRUE)[as.integer(x[,2])+1]
x[,3] = c(FALSE, TRUE)[as.integer(x[,3])+1]
x[,4] = c("read", "read/write", "read/write")[as.integer(x[,4])+1]
colnames(x) <- c("name", "raster", "vector", "can", "vsi", "long.name")
x[,5] <- x[,5] == 1
x <- x[order(x$name), ]
rownames(x) <- NULL
x
} else {
dots <- list(...)
if (length(dots) > 0) {
libVersion(dots[1])
} else {
libVersion("gdal")
}
}
}
.describe_sds <- function(x, print=FALSE) {
x <- .sdinfo(x)
if (length(x[[1]]) == 1 & length(x[[2]]) == 0) {
error("gdal (sds)", x[[1]])
}
names(x) <- c("name", "var", "desc", "nrow", "ncol", "nlyr")
m <- do.call(cbind, x)
m <- data.frame(id=1:nrow(m), m, stringsAsFactors=FALSE)
ii <- which(colnames(m) %in% c("nrow", "ncol", "nlyr"))
for (i in ii) m[,i] <- as.integer(m[,i])
if (print) {
print(m)
invisible(m)
} else {
m
}
}
.meta_sds <- function(x, parse=FALSE, ...) {
if (parse) {
m <- .parsedsdsmetadata(x)
m <- do.call(cbind, m)
if (nrow(m) > 0) {
m <- data.frame(1:nrow(m), m, stringsAsFactors=FALSE)
} else {
m <- data.frame(0[0], m, stringsAsFactors=FALSE)
}
for (i in 5:7) m[,i] <- as.integer(m[,i])
colnames(m) <- c("id", "name", "var", "desc", "nrow", "ncol", "nlyr")
} else {
m <- .sdsmetadata(x)
}
m
}
setMethod("describe", signature(x="character"),
function(x, sds=FALSE, meta=FALSE, parse=FALSE, options="", print=FALSE, open_opt="") {
#x <- .fullFilename(x[1], FALSE)
x <- x[1]
if (meta) {
if (sds) {
return(.meta_sds(x, parse))
} else {
return(.metadata(x))
}
}
if (sds) {
return(.describe_sds(x, print=print))
}
options <- unique(trimws(options))
options <- options[options != ""]
if (length(options) > 0) {
options <- paste0("-", options)
options <- gsub("^--", "-", options)
}
open_opt <- unique(trimws(open_opt))
open_opt <- open_opt[open_opt != ""]
g <- .gdalinfo(x, options, open_opt)
if (g == "") {
add <- ifelse(!file.exists(x), "\n", "\nThe file does not exist\n")
x <- paste0("GDAL cannot open: ", x, add)
}
y <- unlist(strsplit(g, "\n"))
if (print) {
cat(g, "\n")
invisible(y)
} else {
return(y)
}
}
)
setMethod("describe", signature(x="SpatRaster"),
function(x, source=1, ...) {
if (!hasValues(x)) return(NULL)
source <- round(source)
if ((source < 1) || (source > nsrc(x))) {
error("describe", "source should be >= 1 and <= nsrc()")
}
describe(sources(x)[source])
}
)
terra/R/app.R 0000644 0001762 0000144 00000020254 14726700273 012506 0 ustar ligges users
.cpp_funs <- c("sum", "mean", "median", "modal", "which", "which.min", "which.max", "min", "max", "prod", "any", "all", "sd", "std", "first")
setMethod("sapp", signature(x="SpatRaster"),
function(x, fun, ..., filename="", overwrite=FALSE, wopt=list()) {
x <- lapply(x, function(r) fun(r, ...))
x <- rast(x)
if (filename[1] != "") {
writeRaster(x, filename, overwrite, wopt=wopt)
} else {
tighten(x)
}
}
)
setMethod("sapp", signature(x="SpatRasterDataset"),
function(x, fun, ..., filename="", overwrite=FALSE, wopt=list()) {
x <- lapply(as.list(x), function(r) app(r, fun, ...))
x <- rast(x)
if (filename != "") {
writeRaster(x, filename, overwrite, wopt=wopt)
} else {
tighten(x)
}
}
)
export_args <- function(cores, ..., caller="app") {
vals <- list(...)
if (length(vals) < 1) return(NULL)
nms <- names(vals)
if (any(nms == "")) {
error(caller, "additional arguments must be named when using multiple cores")
}
for (i in seq_along(vals)) {
assign(nms[i], force(vals[i]))
}
parallel::clusterExport(cores, nms, envir=environment())
}
## similar from predict
# dots <- list(...)
# if (length(dots) > 0) {
# nms <- names(dots)
# dotsenv <- new.env()
# lapply(1:length(dots), function(i) assign(nms[i], dots[[i]], envir=dotsenv))
# parallel::clusterExport(cls, nms, dotsenv)
# }
setMethod("app", signature(x="SpatRaster"),
function(x, fun, ..., cores=1, filename="", overwrite=FALSE, wopt=list()) {
txtfun <- .makeTextFun(fun)
if (inherits(txtfun, "character")) {
if (txtfun %in% .cpp_funs) {
opt <- spatOptions(filename, overwrite, wopt=wopt)
na.rm <- isTRUE(list(...)$na.rm)
x@pntr <- x@pntr$summary(txtfun, na.rm, opt)
return(messages(x, "app"))
}
}
fun <- match.fun(fun)
out <- rast(x)
nlyr(out) <- 1
nc <- ncol(x)
readStart(x)
on.exit(readStop(x))
nl <- nlyr(x)
dots <- list(...)
if (length(dots) > 0) {
test <- any(sapply(dots, function(i) inherits(i, "SpatRaster")))
if (test) {
error("app", "additional arguments cannot be a SpatRaster")
}
}
if (any(is.factor(x))) {
warn("app", "factors are coerced to numeric")
}
# figure out the shape of the output by testing with up to 13 cells
teststart <- max(1, 0.5 * nc - 6)
testend <- min(teststart + 12, nc)
ntest <- 1 + testend - teststart
v <- readValues(x, round(0.51*nrow(x)), 1, teststart, ntest, mat=TRUE)
usefun <- FALSE
if (nl==1) {
r <- fun(v, ...)
usefun <- TRUE
} else {
r <- try(apply(v, 1, fun, ...), silent=TRUE)
if (inherits(r, "try-error")) {
rr <- try(fun(v, ...), silent=TRUE)
if (inherits(rr, "try-error")) {
error("app", paste0("cannot use this function\n", attr(r, "condition")))
} else {
usefun <- TRUE
r <- rr
}
}
}
if (is.list(r)) {
if (length(unique(sapply(r, length))) > 1) {
error("app", "'fun' returns a list (should be numeric or matrix).\nPerhaps because returned values have different lengths due to NAs in input?")
} else {
error("app", "'fun' returns a list (should be numeric or matrix)")
}
}
trans <- FALSE
if (NCOL(r) > 1) {
#? if ((ncol(r) %% ntest) == 0) {
if (ncol(r) == ntest) {
nlyr(out) <- nrow(r)
trans <- TRUE
nms <- rownames(r)
} else if (nrow(r) == ntest) {
nlyr(out) <- ncol(r)
nms <- colnames(r)
} else {
error("app", "the number of values returned by 'fun' is not appropriate\n(it should be the product of the number of cells and and a positive integer)")
}
if (is.null(wopt$names)) {
wopt$names <- nms
}
} else {
if ((length(r) %% ntest) != 0) {
error("app", "the number of values returned by 'fun' is not appropriate")
} else {
nlyr(out) <- length(r) / ntest
}
}
doclust <- FALSE
if (inherits(cores, "cluster")) {
doclust <- TRUE
} else if (cores > 1) {
doclust <- TRUE
cores <- parallel::makeCluster(cores)
on.exit(parallel::stopCluster(cores), add=TRUE)
}
ncops <- nlyr(x) / nlyr(out)
ncops <- ifelse(ncops > 1, ceiling(ncops), 1) * 4
b <- writeStart(out, filename, overwrite, wopt=wopt, n=ncops, sources=sources(x))
if (doclust) {
ncores <- length(cores)
export_args(cores, ...)
for (i in 1:b$n) {
v <- readValues(x, b$row[i], b$nrows[i], 1, nc, TRUE)
icsz <- max(min(100, ceiling(b$nrows[i] / ncores)), b$nrows[i])
r <- parallel::parRapply(cores, v, fun, ..., chunk.size=icsz)
if (nlyr(out) > 1) {
r <- matrix(r, ncol=nlyr(out), byrow=TRUE)
}
writeValues(out, r, b$row[i], b$nrows[i])
}
} else {
if (usefun) {
for (i in 1:b$n) {
v <- readValues(x, b$row[i], b$nrows[i], 1, nc, TRUE)
r <- fun(v, ...)
if (trans) {
r <- t(r)
}
writeValues(out, r, b$row[i], b$nrows[i])
}
} else {
for (i in 1:b$n) {
v <- readValues(x, b$row[i], b$nrows[i], 1, nc, TRUE)
r <- apply(v, 1, fun, ...)
if (trans) {
r <- t(r)
#r <- as.vector(r)
}
writeValues(out, r, b$row[i], b$nrows[i])
}
}
}
writeStop(out)
}
)
.app_test_stack <- function(v, fun, ncols, ...) {
# figure out the shape of the output
nms = ""
nr <- nrow(v[[1]])
v <- lapply(v, as.vector)
v <- do.call(cbind, v)
r <- apply(v, 1, fun, ...)
if (inherits(r, "try-error")) {
nl <- -1
}
trans <- FALSE
if (NCOL(r) > 1) {
#? if ((ncol(r) %% nc) == 0) {
if (ncol(r) == ncols) {
nl <- nrow(r)
trans <- TRUE
} else if (nrow(r) == ncols) {
nl <- ncol(r)
} else {
error("app", "cannot handle 'fun'")
}
} else if (length(r) >= nr) {
if ((length(r) %% nr) == 0) {
nl <- length(r) / nr
} else {
nl <- -1
}
} else {
nl <- -1
}
if (is.matrix(r)) {
nms <- colnames(r)
}
list(nl=nl, trans=trans, names=nms)
}
.app_test_stack <- function(v, fun, ncols, ...) {
# figure out the shape of the output
nms = ""
nr <- nrow(v[[1]])
v <- lapply(v, as.vector)
v <- do.call(cbind, v)
r <- apply(v, 1, fun, ...)
if (inherits(r, "try-error")) {
nl <- -1
}
trans <- FALSE
if (NCOL(r) > 1) {
#? if ((ncol(r) %% nc) == 0) {
if (ncol(r) == ncols) {
nl <- nrow(r)
trans <- TRUE
} else if (nrow(r) == ncols) {
nl <- ncol(r)
} else {
error("app", "'fun' is not appropriate")
}
} else if (length(r) >= nr) {
if ((length(r) %% nr) == 0) {
nl <- length(r) / nr
} else {
nl <- -1
}
} else {
nl <- -1
}
if (is.matrix(r)) {
nms <- colnames(r)
}
list(nl=nl, trans=trans, names=nms)
}
setMethod("app", signature(x="SpatRasterDataset"),
function(x, fun, ..., cores=1, filename="", overwrite=FALSE, wopt=list()) {
txtfun <- .makeTextFun(match.fun(fun))
if (inherits(txtfun, "character")) {
if (txtfun %in% .cpp_funs) {
opt <- spatOptions(filename, overwrite, wopt=wopt)
narm <- isTRUE(list(...)$na.rm)
r <- rast()
r@pntr <- x@pntr$summary(txtfun, narm, opt)
return (messages(r, "app") )
}
}
if (missing(fun)) error("app", "'fun' is missing")
ncx <- ncol(x[1])
nrx <- nrow(x[1])
readStart(x)
on.exit(readStop(x))
v <- lapply(1:length(x), function(i) readValues(x[i], round(0.51*nrx), 1, 1, ncx, mat=TRUE))
test <- .app_test_stack(v, fun, ncx, ...)
if (test$nl < 1) error("app", "cannot find 'fun'")
out <- rast(x[1], nlyrs=test$nl)
if (length(test$names == test$nl)) {
if (is.null(wopt$names)) wopt$names <- test$names
}
nc <- (nlyr(x[1]) * length(x)) / nlyr(out)
nc <- ifelse(nc > 1, ceiling(nc), 1) * 3
b <- writeStart(out, filename, overwrite, wopt=wopt, n=nc, sources=unlist(sources(x)))
if (inherits(cores, "cluster")) {
doclust <- TRUE
} else if (cores > 1) {
doclust <- TRUE
cores <- parallel::makeCluster(cores)
on.exit(parallel::stopCluster(cores), add=TRUE)
} else {
doclust <- FALSE
}
if (doclust) {
ncores <- length(cores)
export_args(cores, ...)
for (i in 1:b$n) {
v <- lapply(1:length(x), function(s) as.vector(readValues(x[s], b$row[i], b$nrows[i], 1, ncx, mat=TRUE)))
v <- do.call(cbind, v)
icsz <- max(min(100, ceiling(b$nrows[i] / ncores)), b$nrows[i])
r <- parallel::parRapply(cores, v, fun, ..., chunk.size=icsz)
if (test$trans) {
r <- t(r)
}
writeValues(out, r, b$row[i], b$nrows[i])
}
} else {
for (i in 1:b$n) {
v <- lapply(1:length(x), function(s) as.vector(readValues(x[s], b$row[i], b$nrows[i], 1, ncx, mat=TRUE)))
r <- apply(do.call(cbind, v), 1, fun, ...)
if (test$trans) {
r <- t(r)
}
writeValues(out, r, b$row[i], b$nrows[i])
}
}
#readStop(x)
writeStop(out)
}
)
terra/R/lines.R 0000644 0001762 0000144 00000010302 14726700274 013032 0 ustar ligges users
setMethod("lines", signature(x="SpatRaster"),
function(x, mx=10000, ...) {
reset.clip()
if(prod(dim(x)) > mx) {
error("lines", "too many lines (you can increase the value of mx or use as.polygons)")
}
v <- as.polygons(x[[1]], dissolve=FALSE, values=FALSE)
lines(v, ...)
}
)
setMethod("points", signature(x="SpatRaster"),
function(x, ...) {
reset.clip()
p <- as.points(x[[1]])
points(p, ...)
}
)
setMethod("polys", signature(x="SpatRaster"),
function(x, mx=10000, dissolve=TRUE, ...) {
reset.clip()
if(prod(dim(x)) > mx) {
error("lines", "too many lines (you can increase the value of mx or use as.polygons)")
}
p <- as.polygons(x[[1]], dissolve=dissolve)
polys(p, ...)
}
)
setMethod("lines", signature(x="SpatVector"),
function(x, y=NULL, col, lwd=1, lty=1, arrows=FALSE, alpha=1, ...) {
reset.clip()
n <- nrow(x)
if (n == 0) return(invisible(NULL))
gtype <- geomtype(x)
if (missing(col)) col <- "black"
if (!is.null(y)) {
stopifnot(inherits(y, "SpatVector"))
ytype <- geomtype(y)
if ((ytype != "points") || (gtype != "points")) {
error("lines", "when supplying two SpatVectors, both must have point geometry")
}
stopifnot(nrow(x) == nrow(y))
p1 <- geom(x)[, c("x", "y"), drop=FALSE]
p2 <- geom(y)[, c("x", "y"), drop=FALSE]
if (arrows) {
arrows(p1[,1], p1[,2], p2[,1], p2[,2], col=col, lwd=lwd, lty=lty, ...)
} else {
a <- as.vector(t(cbind(p1[,1], p2[,1], NA)))
b <- as.vector(t(cbind(p1[,2], p2[,2], NA)))
lines(cbind(a, b), col=col, lwd=lwd, lty=lty, ...)
}
} else {
if (gtype != "polygons") {
x <- as.lines(x)
}
if ((length(col) == 1) && (length(lty)==1) && (length(lwd)==1)) {
col <- .getCols(1, col, alpha)
g <- x@pntr$linesNA()
names(g) <- c("x", "y")
graphics::plot.xy(g, type="l", lty=lty, col=col, lwd=lwd, ...)
} else {
col <- .getCols(n, col, alpha)
lwd <- rep_len(lwd, n)
lty <- rep_len(lty, n)
# g <- lapply(x@pntr$linesList(), function(i) { names(i)=c("x", "y"); i } )
g <- x@pntr$linesList()
for (i in 1:n) {
if (length(g[[i]]) > 0) {
names(g[[i]]) = c("x", "y")
graphics::plot.xy(g[[i]], type="l", lty=lty[i], col=col[i], lwd=lwd[i])
}
}
}
#g <- geom(x, df=TRUE)
#g <- split(g, g[,1])
#if (gtype == "polygons") {
# g <- lapply(g, function(x) split(x, x[,c(2,5)]))
#} else {
# g <- lapply(g, function(x) split(x, x[,2]))
#}
#for (i in 1:length(g)) {
# for (j in 1:length(g[[i]])) {
# lines(g[[i]][[j]][,3:4], col=col[i], lwd=lwd[i], lty=lty[i], ...)
# }
#}
}
}
)
setMethod("points", signature(x="SpatVector"),
function(x, col, cex=0.7, pch=16, alpha=1, ...) {
reset.clip()
n <- length(x)
if (n == 0) return(invisible(NULL))
if (missing(col)) col <- "black"
if ((length(col) == 1) && (length(cex)==1) && (length(pch)==1)) {
col <- .getCols(1, col, alpha)
#graphics::points(g[,3:4], col=col, pch=pch, cex=cex,...)
g <- crds(x)
graphics::plot.xy(list(x=g[,1], y=g[,2]), type="p", pch=pch, col=col, cex=cex, ...)
} else {
col <- .getCols(n, col, alpha)
cex <- rep_len(cex, n)
pch <- rep_len(pch, n)
g <- geom(x, df=TRUE)
if (nrow(g) > g[nrow(g), 1]) {
g <- split(g[,3:4], g[,1])
for (i in 1:n) {
#graphics::points(g[[i]], col=col[i], pch=pch[i], cex=cex[i], ...)
graphics::plot.xy(list(x=g[[i]][,1], y=g[[i]][,2]), type="p", pch=pch[i], col=col[i], cex=cex[i], ...)
}
} else {
graphics::plot.xy(list(x=g[,3], y=g[,4]), type="p", pch=pch, col=col, cex=cex, ...)
}
}
}
)
setMethod("polys", signature(x="SpatVector"),
function(x, col, border="black", lwd=1, lty=1, alpha=1, ...) {
reset.clip()
gtype <- geomtype(x)
if (gtype != "polygons") {
error("polys", "expecting polygons")
}
if (missing(col)) {
col <- NULL
} else {
col <- .getCols(length(x), col, alpha)
}
out <- list(main_cols=col)
out$leg$border <- border
p <- .plotPolygons(x, out, lwd=lwd, lty=lty, ...)
}
)
setMethod("points", signature(x="sf"),
function(x, ...) {
points(vect(x), ...)
}
)
setMethod("lines", signature(x="sf"),
function(x, ...) {
lines(vect(x), ...)
}
)
setMethod("polys", signature(x="sf"),
function(x, ...) {
polys(vect(x), ...)
}
)
terra/cleanup 0000755 0001762 0000144 00000000116 14757467215 012764 0 ustar ligges users #!/bin/sh
rm -fr src/Makevars config.log config.status
rm -fr proj_conf_test*
terra/src/ 0000755 0001762 0000144 00000000000 14757467212 012175 5 ustar ligges users terra/src/geosphere.cpp 0000644 0001762 0000144 00000026076 14752175705 014673 0 ustar ligges users // Copyright (c) 2018-2025 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 .
#include "spatVector.h"
#include "geodesic.h"
#include "recycle.h"
#include "geosphere.h"
#ifndef M_PI
#define M_PI (3.1415926535897932384626433)
#endif
#ifndef M_2PI
#define M_2PI (M_PI * 2.0)
#endif
#ifndef M_hPI
#define M_hPI (M_PI / 2.0)
#endif
#ifndef WGS84_a
#define WGS84_a 6378137.0
#endif
#ifndef WGS84_f
#define WGS84_f 1/298.257223563
#endif
//#include "Rcpp.h"
inline void normLon(double &lon) {
lon = fmod(lon + 180, 360.) - 180;
}
inline void normLonRad(double &lon) {
lon = fmod(lon + M_PI, M_2PI) - M_PI;
}
inline double get_sign(const double &x) {
return (x > 0.0) ? 1.0 : (x < 0.0) ? -1.0 : 0;
}
double distance_geo(double lon1, double lat1, double lon2, double lat2) {
double s12, azi1, azi2;
struct geod_geodesic g;
geod_init(&g, WGS84_a, WGS84_f);
geod_inverse(&g, lat1, lon1, lat2, lon2, &s12, &azi1, &azi2);
return s12;
}
inline double distance_cos_r(double lon1, double lat1, double lon2, double lat2, double r = 6378137.) {
return r * acos((sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon1-lon2)));
}
inline double distance_hav_r(double lon1, double lat1, double lon2, double lat2, const double r = 6378137.) {
double dLat = lat2-lat1;
double dLon = lon2-lon1;
double a = sin(dLat/2.) * sin(dLat/2.) + cos(lat1) * cos(lat2) * sin(dLon/2.) * sin(dLon/2.);
return 2. * atan2(sqrt(a), sqrt(1. - a)) * 6378137.0;
}
/*
double distance_cosdeg(double lon1, double lat1, double lon2, double lat2, double r = 6378137.) {
deg2rad(lon1);
deg2rad(lon2);
deg2rad(lat1);
deg2rad(lat2);
return r * acos((sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon1-lon2)));
}
*/
void dest_geo(double slon, double slat, double sazi, double dist, double &dlon, double &dlat, double &dazi) {
struct geod_geodesic g;
geod_init(&g, WGS84_a, WGS84_f);
geod_direct(&g, slat, slon, sazi, dist, &dlat, &dlon, &dazi);
}
double direction_geo(double lon1, double lat1, double lon2, double lat2) {
double s12, azi1, azi2;
struct geod_geodesic g;
geod_init(&g, WGS84_a, WGS84_f);
geod_inverse(&g, lat1, lon1, lat2, lon2, &s12, &azi1, &azi2);
return( azi1) ;
}
double direction_cos(double& lon1, double& lat1, double& lon2, double& lat2) {
if ((lon1 == lon2) && (lat1 == lat2)) return 0; // NAN?
double dLon = lon2 - lon1;
double y = sin(dLon) * cos(lat2);
double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
double azm = atan2(y, x);
azm = fmod(azm+M_PI, M_PI);
return azm > M_PI ? -(M_PI - azm) : azm;
}
double dist2track_geo(double lon1, double lat1, double lon2, double lat2, double plon, double plat, bool sign, double r=6378137) {
double a = 1;
double f = 0;
struct geod_geodesic geod;
geod_init(&geod, a, f);
double d, b2, b3, azi;
geod_inverse(&geod, lat1, lon1, lat2, lon2, &d, &b2, &azi);
geod_inverse(&geod, lat1, lon1, plat, plon, &d, &b3, &azi);
double toRad = M_PI / 180.;
b2 *= toRad;
b3 *= toRad;
double xtr = asin(sin(b3-b2) * sin(d)) * r;
return sign ? xtr : fabs(xtr);
}
inline double dist2track_cos(double lon1, double lat1, double lon2, double lat2, double plon, double plat, bool sign, double r=6378137) {
double b2 = direction_cos(lon1, lat1, lon2, lat2);
double b3 = direction_cos(lon1, lat1, plon, plat);
double d = distance_cos_r(lon1, lat1, plon, plat, 1);
double xtr = asin(sin(b3-b2) * sin(d)) * r;
return sign ? xtr : fabs(xtr);
}
inline double dist2track_hav(double lon1, double lat1, double lon2, double lat2, double plon, double plat, bool sign, double r=6378137) {
double b2 = direction_cos(lon1, lat1, lon2, lat2);
double b3 = direction_cos(lon1, lat1, plon, plat);
double d = distance_hav_r(lon1, lat1, plon, plat, 1);
double xtr = asin(sin(b3-b2) * sin(d)) * r;
return sign ? xtr : fabs(xtr);
}
double alongTrackDistance_geo(double lon1, double lat1, double lon2, double lat2, double plon, double plat, double r=6378137) {
double a = 1;
double f = 0;
struct geod_geodesic geod;
geod_init(&geod, a, f);
double d, b2, b3, azi;
geod_inverse(&geod, lat1, lon1, lat2, lon2, &d, &b2, &azi);
geod_inverse(&geod, lat1, lon1, plat, plon, &d, &b3, &azi);
deg2rad(b2);
deg2rad(b3);
double xtr = asin(sin(b3-b2) * sin(d));
double bsign = get_sign(cos(b2-b3));
return fabs(bsign * acos(cos(d) / cos(xtr)) * r);
}
double alongTrackDistance_cos(double lon1, double lat1, double lon2, double lat2, double plon, double plat, double r=6378137) {
double tc = direction_cos(lon1, lat1, lon2, lat2); // * toRad
double tcp = direction_cos(lon1, lat1, plon, plat); // * toRad
double dp = distance_cos_r(lon1, lat1, plon, plat, 1);
double xtr = asin(sin(tcp-tc) * sin(dp));
// +1/-1 for ahead/behind [lat1,lon1]
double bearing = get_sign(cos(tc - tcp));
double angle = cos(dp) / cos(xtr);
// Fixing limits for the angle between [-1, 1] to avoid NaNs from acos
angle = angle > 1 ? 1 : angle < -1 ? -1 : angle;
double dist = bearing * acos(angle) * r;
return fabs(dist);
}
double alongTrackDistance_hav(double lon1, double lat1, double lon2, double lat2, double plon, double plat, double r=6378137) {
double tc = direction_cos(lon1, lat1, lon2, lat2); // * toRad
double tcp = direction_cos(lon1, lat1, plon, plat); // * toRad
double dp = distance_hav_r(lon1, lat1, plon, plat, 1);
double xtr = asin(sin(tcp-tc) * sin(dp));
// +1/-1 for ahead/behind [lat1,lon1]
double bearing = get_sign(cos(tc - tcp));
double angle = cos(dp) / cos(xtr);
// Fixing limits for the angle between [-1, 1] to avoid NaNs from acos
angle = angle > 1 ? 1 : angle < -1 ? -1 : angle;
double dist = bearing * acos(angle) * r;
return fabs(dist);
}
// the alongTrackDistance is the length of the path along the great circle to the point of intersection
// there are two, depending on which node you start
// we want to use the min, but the max needs to be < segment length
double dist2segment_geo(double plon, double plat, double lon1, double lat1, double lon2, double lat2, double notused) {
double seglength = distance_geo(lon1, lat1, lon2, lat2);
double trackdist1 = alongTrackDistance_geo(lon1, lat1, lon2, lat2, plon, plat);
double trackdist2 = alongTrackDistance_geo(lon2, lat2, lon1, lat1, plon, plat);
if ((trackdist1 >= seglength) || (trackdist2 >= seglength)) {
double d1 = distance_geo(lon1, lat1, plon, plat);
double d2 = distance_geo(lon2, lat2, plon, plat);
return d1 < d2 ? d1 : d2;
}
return dist2track_geo(lon1, lat1, lon2, lat2, plon, plat, false);
}
double dist2segment_cos(double plon, double plat, double lon1, double lat1, double lon2, double lat2, double r) {
double seglength = distance_cos_r(lon1, lat1, lon2, lat2, r);
double trackdist1 = alongTrackDistance_cos(lon1, lat1, lon2, lat2, plon, plat, r);
double trackdist2 = alongTrackDistance_cos(lon2, lat2, lon1, lat1, plon, plat, r);
if ((trackdist1 >= seglength) || (trackdist2 >= seglength)) {
double d1 = distance_cos_r(lon1, lat1, plon, plat, r);
double d2 = distance_cos_r(lon2, lat2, plon, plat, r);
return d1 < d2 ? d1 : d2;
}
return dist2track_cos(lon1, lat1, lon2, lat2, plon, plat, false, r);
}
double dist2segment_hav(double plon, double plat, double lon1, double lat1, double lon2, double lat2, double r) {
double seglength = distance_hav_r(lon1, lat1, lon2, lat2, r);
double trackdist1 = alongTrackDistance_hav(lon1, lat1, lon2, lat2, plon, plat, r);
double trackdist2 = alongTrackDistance_hav(lon2, lat2, lon1, lat1, plon, plat, r);
if ((trackdist1 >= seglength) || (trackdist2 >= seglength)) {
double d1 = distance_hav_r(lon1, lat1, plon, plat, r);
double d2 = distance_hav_r(lon2, lat2, plon, plat, r);
return d1 < d2 ? d1 : d2;
}
return dist2track_hav(lon1, lat1, lon2, lat2, plon, plat, false, r);
}
// [[Rcpp::export]]
double dist2segmentPoint_geo(double plon, double plat, double lon1, double lat1, double lon2, double lat2, double &ilon, double &ilat) {
double seglength = distance_geo(lon1, lat1, lon2, lat2);
double trackdist1 = alongTrackDistance_geo(lon1, lat1, lon2, lat2, plon, plat);
double trackdist2 = alongTrackDistance_geo(lon2, lat2, lon1, lat1, plon, plat);
if ((trackdist1 >= seglength) || (trackdist2 >= seglength)) {
double d1 = distance_geo(lon1, lat1, plon, plat);
double d2 = distance_geo(lat2, lat2, plon, plat);
if (d1 < d2) {
ilon = lon1;
ilat = lat1;
return d1;
} else {
ilon = lon2;
ilat = lat2;
return d2;
}
}
double azi;
double crossd = dist2track_geo(lon1, lat1, lon2, lat2, plon, plat, false);
if (trackdist1 < trackdist2) {
double bear = direction_geo(lon1, lat1, lon2, lat2);
dest_geo(lon1, lat1, bear, trackdist1, ilon, ilat, azi);
} else {
double bear = direction_geo(lon2, lat2, lon1, lat1);
dest_geo(lon2, lat2, bear, trackdist2, ilon, ilat, azi);
}
return crossd;
}
// [[Rcpp::export(name = "intermediate")]]
std::vector> intermediate(double lon1, double lat1, double lon2, double lat2, int n, double distance) {
double a = 6378137.0;
double f = 1/298.257223563;
struct geod_geodesic geod;
geod_init(&geod, a, f);
double d, azi1, azi2;
std::vector> out(2);
if (n <= 0) {
if (distance <= 0) {
out[0] = {lon1, lon2};
out[1] = {lon1, lon2};
return out;
} else {
geod_inverse(&geod, lat1, lon1, lat2, lon2, &d, &azi1, &azi2);
n = std::round(d / distance);
if (n < 2) {
out[0] = {lon1, lon2};
out[1] = {lon1, lon2};
return out;
}
distance = d / n;
}
} else if (n == 1) {
out[0] = {lon1, lon2};
out[1] = {lon1, lon2};
return out;
} else {
geod_inverse(&geod, lat1, lon1, lat2, lon2, &d, &azi1, &azi2);
//distance = d / n;
}
out[0].resize(n+1);
out[1].resize(n+1);
out[0][0] = lon1;
out[1][0] = lat1;
for (int i=1; i antipodal(std::vector lon1, std::vector lat1, std::vector lon2, std::vector lat2, double tol=1e-9) {
recycle(lon1, lon2);
recycle(lat1, lat2);
std::vector out;
out.reserve(lon1.size());
double Pi180 = M_PI / 180.;
for (size_t i=0; i &lon, std::vector &lat) {
size_t n=lon.size();
for (size_t i=0; i