Skip to content

Commit

Permalink
linscale
Browse files Browse the repository at this point in the history
  • Loading branch information
rhijmans committed Dec 16, 2024
1 parent ac4725b commit 825554d
Show file tree
Hide file tree
Showing 9 changed files with 104 additions and 4 deletions.
2 changes: 1 addition & 1 deletion NAMESPACE
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
useDynLib(terra, .registration=TRUE)
import(methods, Rcpp)
exportClasses(SpatExtent, SpatRaster, SpatRasterDataset, SpatRasterCollection, SpatVector, SpatVectorProxy, SpatVectorCollection)
exportMethods("[", "[[", "!", "%in%", activeCat, "activeCat<-", "add<-", addCats, adjacent, all.equal, aggregate, allNA, align, animate, anyNA, app, Arith, approximate, as.bool, as.int, as.contour, as.lines, as.points, as.polygons, as.raster, as.array, as.data.frame, as.factor, as.list, as.logical, as.matrix, as.numeric, atan2, atan_2, autocor, barplot, blocks, boundaries, boxplot, buffer, cartogram, categories, cats, catalyze, clamp, clamp_ts, classify, clearance, cellSize, cells, cellFromXY, cellFromRowCol, cellFromRowColCombine, centroids, click, bestMatch, colFromX, colFromCell, colorize, coltab, "coltab<-", combineGeoms, compare, concats, Compare, compareGeom, contour, convHull, countNA, costDist, crds, cover, crop, crosstab, crs, "crs<-", datatype, deepcopy, delaunay, densify, density, depth, "depth<-", describe, diff, disagg, direction, distance, dots, draw, droplevels, edges, elongate, emptyGeoms, erase, extend, ext, "ext<-", extract, extractRange, expanse, fillHoles, fillTime, flip, focal, focal3D, focalPairs, focalReg, focalCpp, focalValues, forceCCW, freq, gaps, geom, geomtype, getTileExtents, global, gridDist, has.colors, has.RGB, has.time, hasMinMax, hasValues, hist, head, identical, ifel, impose, init, image, inext, interpIDW, interpNear, inMemory, inset, interpolate, intersect, is.bool, is.int, is.lonlat, is.rotated, isTRUE, isFALSE, is.empty, is.factor, is.lines, is.points, is.polygons, is.related, is.valid, k_means, lapp, layerCor, levels, "levels<-", linearUnits, lines, Logic, varnames, "varnames<-", logic, longnames, "longnames<-", makeValid, mask, match, math, Math, Math2, mean, median, meta, merge, mergeLines, mergeTime, minCircle, minmax, minRect, modal, mosaic, na.omit, not.na, NAflag, "NAflag<-", nearby, nearest, ncell, ncol, "ncol<-", nlyr, "nlyr<-", noNA, normalize.longitude, nrow, "nrow<-", nsrc, origin, "origin<-", pairs, panel, patches, perim, persp, plot, plotRGB, plet, prcomp, princomp, RGB, "RGB<-", polys, points, predict, project, quantile, query, rangeFill, rapp, rast, rasterize, rasterizeGeom, rasterizeWin, readStart, readStop, readValues, rectify, regress, relate, removeDupNodes, res, "res<-", resample, rescale, rev, rcl, roll, rotate, rowFromY, rowColCombine, rowColFromCell, rowFromCell, sapp, scale, scoff, "scoff<-", sds, sort, sprc, sel, selectRange, setMinMax, setValues, segregate, selectHighest, set.cats, set.crs, set.ext, set.names, set.RGB, set.values, size, sharedPaths, shift, sieve, simplifyGeom, snap, sources, spatSample, split, spin, stdev, stretch, subset, subst, summary, Summary, surfArea, svc, symdif, t, metags, "metags<-", tail, tapp, terrain, tighten, makeNodes, makeTiles, time, timeInfo, "time<-", text, toMemory, trans, trim, units, union, "units<-", unique, unwrap, update, vect, values, "values<-", viewshed, voronoi, vrt, weighted.mean, where.min, where.max, which.lyr, which.min, which.max, which.lyr, width, window, "window<-", writeCDF, writeRaster, wrap, wrapCache, writeStart, writeStop, writeVector, writeValues, xmin, xmax, "xmin<-", "xmax<-", xres, xFromCol, xyFromCell, xFromCell, ymin, ymax, "ymin<-", "ymax<-", yres, yFromCell, yFromRow, zonal, zoom, cbind2, readRDS, saveRDS, unserialize, serialize, xapp, area, gridDistance, colSums, rowSums, colMeans, rowMeans)
exportMethods("[", "[[", "!", "%in%", activeCat, "activeCat<-", "add<-", addCats, adjacent, all.equal, aggregate, allNA, align, animate, anyNA, app, Arith, approximate, as.bool, as.int, as.contour, as.lines, as.points, as.polygons, as.raster, as.array, as.data.frame, as.factor, as.list, as.logical, as.matrix, as.numeric, atan2, atan_2, autocor, barplot, blocks, boundaries, boxplot, buffer, cartogram, categories, cats, catalyze, clamp, clamp_ts, classify, clearance, cellSize, cells, cellFromXY, cellFromRowCol, cellFromRowColCombine, centroids, click, bestMatch, colFromX, colFromCell, colorize, coltab, "coltab<-", combineGeoms, compare, concats, Compare, compareGeom, contour, convHull, countNA, costDist, crds, cover, crop, crosstab, crs, "crs<-", datatype, deepcopy, delaunay, densify, density, depth, "depth<-", describe, diff, disagg, direction, distance, dots, draw, droplevels, edges, elongate, emptyGeoms, erase, extend, ext, "ext<-", extract, extractRange, expanse, fillHoles, fillTime, flip, focal, focal3D, focalPairs, focalReg, focalCpp, focalValues, forceCCW, freq, gaps, geom, geomtype, getTileExtents, global, gridDist, has.colors, has.RGB, has.time, hasMinMax, hasValues, hist, head, identical, ifel, impose, init, image, inext, interpIDW, interpNear, inMemory, inset, interpolate, intersect, is.bool, is.int, is.lonlat, is.rotated, isTRUE, isFALSE, is.empty, is.factor, is.lines, is.points, is.polygons, is.related, is.valid, k_means, lapp, layerCor, levels, "levels<-", linearUnits, lines, Logic, varnames, "varnames<-", logic, longnames, "longnames<-", makeValid, mask, match, math, Math, Math2, mean, median, meta, merge, mergeLines, mergeTime, minCircle, minmax, minRect, modal, mosaic, na.omit, not.na, NAflag, "NAflag<-", nearby, nearest, ncell, ncol, "ncol<-", nlyr, "nlyr<-", noNA, normalize.longitude, nrow, "nrow<-", nsrc, origin, "origin<-", pairs, panel, patches, perim, persp, plot, plotRGB, plet, prcomp, princomp, RGB, "RGB<-", polys, points, predict, project, quantile, query, rangeFill, rapp, rast, rasterize, rasterizeGeom, rasterizeWin, readStart, readStop, readValues, rectify, regress, relate, removeDupNodes, res, "res<-", resample, rescale, rev, rcl, roll, rotate, rowFromY, rowColCombine, rowColFromCell, rowFromCell, sapp, scale, scale_linear, scoff, "scoff<-", sds, sort, sprc, sel, selectRange, setMinMax, setValues, segregate, selectHighest, set.cats, set.crs, set.ext, set.names, set.RGB, set.values, size, sharedPaths, shift, sieve, simplifyGeom, snap, sources, spatSample, split, spin, stdev, stretch, subset, subst, summary, Summary, surfArea, svc, symdif, t, metags, "metags<-", tail, tapp, terrain, tighten, makeNodes, makeTiles, time, timeInfo, "time<-", text, toMemory, trans, trim, units, union, "units<-", unique, unwrap, update, vect, values, "values<-", viewshed, voronoi, vrt, weighted.mean, where.min, where.max, which.lyr, which.min, which.max, which.lyr, width, window, "window<-", writeCDF, writeRaster, wrap, wrapCache, writeStart, writeStop, writeVector, writeValues, xmin, xmax, "xmin<-", "xmax<-", xres, xFromCol, xyFromCell, xFromCell, ymin, ymax, "ymin<-", "ymax<-", yres, yFromCell, yFromRow, zonal, zoom, cbind2, readRDS, saveRDS, unserialize, serialize, xapp, area, gridDistance, colSums, rowSums, colMeans, rowMeans)

exportMethods(watershed, pitfinder, NIDP, flowAccumulation)

Expand Down
3 changes: 2 additions & 1 deletion NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@

## new

- `$<SpatRaster>` can now be used to set the active category for categorical rasters
- `$<SpatRaster>` can now be used to get a categorical SpatRaster with a different active category
- `scale_linear<SpatRaster>` method for linear scaling between e.g., 0 and 1


# version 1.8-5
Expand Down
1 change: 1 addition & 0 deletions R/Agenerics.R
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,7 @@ if (!isGeneric("rescale")) {setGeneric("rescale", function(x, ...) standardGener
#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")) }
Expand Down
7 changes: 7 additions & 0 deletions R/generics.R
Original file line number Diff line number Diff line change
Expand Up @@ -968,6 +968,13 @@ setMethod("rescale", signature(x="SpatVector"),
}
)

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) {
Expand Down
4 changes: 2 additions & 2 deletions man/scale.Rd
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
\title{Scale values}

\description{
Center and/or scale raster data. For details see \code{\link{scale}}
Center and/or scale raster data. For details see \code{\link[base]{scale}}
}

\usage{
Expand All @@ -26,7 +26,7 @@ SpatRaster
}


\seealso{ \code{\link[base]{scale}} }
\seealso{ \code{\link{scale_linear}} }

\examples{
r <- rast(system.file("ex/logo.tif", package="terra"))
Expand Down
37 changes: 37 additions & 0 deletions man/scale_linear.Rd
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
\name{scale_linear}

\alias{scale_linear}
\alias{scale_linear,SpatRaster-method}


\title{Scale values linearly}

\description{
Linear scaling of raster cell values.
}

\usage{
\S4method{scale_linear}{SpatRaster}(x, min=0, max=1)
}


\arguments{
\item{x}{SpatRaster}
\item{min}{minimum value to scale to}
\item{max}{maximum value to scale to}
}

\value{
SpatRaster
}


\seealso{ \code{\link{scale}} }

\examples{
r <- rast(system.file("ex/logo.tif", package="terra"))
s1 <- scale_linear(r)
s2 <- scale_linear(r, 1, 10)
}

\keyword{ spatial }
1 change: 1 addition & 0 deletions src/RcppModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -955,6 +955,7 @@ RCPP_MODULE(spat){
.method("sampleRandomRaster", &SpatRaster::sampleRandomRaster)
.method("sampleRandomValues", &SpatRaster::sampleRandomValues)
.method("scale", &SpatRaster::scale)
.method("scale_linear", &SpatRaster::scale_linear)
.method("shift", &SpatRaster::shift)
.method("similarity", &SpatRaster::similarity)
.method("terrain", &SpatRaster::terrain)
Expand Down
51 changes: 51 additions & 0 deletions src/raster_methods.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4732,6 +4732,57 @@ SpatRaster SpatRaster::scale(std::vector<double> center, bool docenter, std::vec
}


SpatRaster SpatRaster::scale_linear(double smin, double smax, SpatOptions &opt) {
SpatRaster out = geometry();
if (!hasValues()) return out;
if (smin >= smax) {
out.setError("min scaling value must be smaller than the max scaling value");
return out;
}

SpatOptions opts(opt);
setRange(opts, false);
std::vector<double> rmin = SpatRaster::range_min();
std::vector<double> rmax = SpatRaster::range_max();
std::vector<double> rdif;
rdif.reserve(rmin.size());
double dmnmx = smax - smin;

for (size_t i=0; i<rmin.size(); i++) {
rdif.push_back((rmax[i] - rmin[i]) / dmnmx);
}

if (!readStart()) {
out.setError(getError());
return(out);
}
if (!out.writeStart(opt, filenames())) {
readStop();
return out;
}

size_t nl = nlyr();

for (size_t i = 0; i < out.bs.n; i++) {
std::vector<double> v;
readBlock(v, out.bs, i);
size_t lyroff = 0;
size_t cellperlyr = out.bs.nrows[i] * ncol();
for (size_t lyr = 0; lyr < nl; lyr++) {
for (size_t j=lyroff; j<(lyroff+cellperlyr); j++) {
v[j] = ((v[j] - rmin[lyr]) / rdif[i]) + smin;
}
lyroff = lyroff + cellperlyr;
}
if (!out.writeBlock(v, i)) return out;
}
readStop();
out.writeStop();
return out;
}



/*
bool can_use_replace(const std::vector<double> &from, const std::vector<double> &to) {
// test if any "to" later occurs in "from"
Expand Down
2 changes: 2 additions & 0 deletions src/spatRaster.h
Original file line number Diff line number Diff line change
Expand Up @@ -801,6 +801,8 @@ class SpatRaster {
SpatRaster sort(bool decreasing, bool order, SpatOptions &opt);

SpatRaster scale(std::vector<double> center, bool docenter, std::vector<double> scale, bool doscale, SpatOptions &opt);
SpatRaster scale_linear(double smin, double smax, SpatOptions &opt);

SpatRaster similarity(std::vector<double> x, SpatOptions &opt);

SpatRaster terrain(std::vector<std::string> v, unsigned neighbors, bool degrees, unsigned seed, SpatOptions &opt);
Expand Down

0 comments on commit 825554d

Please sign in to comment.