Title: | Non-Interactive Spatial Tools for Raster Processing and Visualization |
---|---|
Description: | S3 classes and methods for manipulation with georeferenced raster data: reading/writing, processing, multi-panel visualization. |
Authors: | Nikita Platonov [aut, cre] |
Maintainer: | Nikita Platonov <[email protected]> |
License: | GPL (>= 2) |
Version: | 3.11.0-1093 |
Built: | 2024-11-18 05:57:27 UTC |
Source: | https://github.com/nplatonov/ursa |
Have a great work with ursa!
See table of content.
Nikita Platonov [email protected]
allocate
takes x
and y
coordinates and values from data frame, which is describing point spatial data, and puts them into cells of raster. The certain function (either mean value, sum of values, number of points) is applied for >0 points inside of the exact cell borders.
allocate(vec, coords = c("x", "y"), nodata = NA, attr = ".+", fun = c("mean", "sum", "n"), cellsize = NA, resetGrid = FALSE, verbose = FALSE)
allocate(vec, coords = c("x", "y"), nodata = NA, attr = ".+", fun = c("mean", "sum", "n"), cellsize = NA, resetGrid = FALSE, verbose = FALSE)
vec |
|
coords |
Character of length 2. Colums names, which contain coordinates of data points. Raster bands are not produced for specified columns. For misreference of coordinate columns, the attempt to find more appropriate coordinate columns is taken. |
fun |
Character keyword of function, which is applied to value of points, which are dropped into the same cell. Valid values are |
nodata |
Numeric of length 1. This value used to mark |
attr |
Pattern in the format of regular expressions, which is used to select required columns in data frame. By default ( |
cellsize |
Numeric. Desired size of cell in the raster grid. Used only when source data are not in regular grid. Default is |
resetGrid |
Logical. If |
verbose |
Logical. Some output in console. Primarily for debug purposes. |
Here fun
differs from R-styled fun
in such functions as *apply
, aggregate
.
It was refused “rasterize” for function name to distinguish with rasterize
in the package raster
Object of class ursaRaster
Nikita Platonov [email protected]
session_grid(NULL) g1 <- session_grid(regrid(session_grid(),mul=1/10)) n <- 1000 x <- with(g1,runif(n,min=minx,max=maxx)) y <- with(g1,runif(n,min=miny,max=maxy)) z <- with(g1,runif(n,min=0,max=10)) da <- data.frame(x=x,y=y,value=z) res <- c(mean=allocate(da,fun="mean") ,mean_=NA ,sum=allocate(da,fun="sum") ,count=allocate(da,fun="n")) res["mean_"]=res["sum"]/res["count"] print(res)
session_grid(NULL) g1 <- session_grid(regrid(session_grid(),mul=1/10)) n <- 1000 x <- with(g1,runif(n,min=minx,max=maxx)) y <- with(g1,runif(n,min=miny,max=maxy)) z <- with(g1,runif(n,min=0,max=10)) da <- data.frame(x=x,y=y,value=z) res <- c(mean=allocate(da,fun="mean") ,mean_=NA ,sum=allocate(da,fun="sum") ,count=allocate(da,fun="n")) res["mean_"]=res["sum"]/res["count"] print(res)
`stars`
Coercion from raster ursaRaster
object to raster stars
object defined in package stars.
as_stars(obj)
as_stars(obj)
obj |
Object of class |
Simple coercion to stars
object of package stars. Currently, color tables and attribution tables are not supported.
Object of class stars
for argument of class ursaRaster
. Otherwise, NULL
.
Nikita Platonov [email protected]
session_grid(NULL) a <- ursa_dummy(3) x <- as_stars(a) class(x) if (requireNamespace("stars")) { print(x) b <- as_ursa(x) print(a) print(b) }
session_grid(NULL) a <- ursa_dummy(3) x <- as_stars(a) class(x) if (requireNamespace("stars")) { print(x) b <- as_ursa(x) print(a) print(b) }
In the ursaRaster
object the 3-dimensional image data are presented in 2-dimensional matrix. as.array
transforms internal 2-dimensional data to the usual 3-dimansional data. as.matrix
just extracts image data in internal 2-dimensional format.
## S3 method for class 'ursaRaster' as.array(x, ...) ## non-public .as.array(x, drop = FALSE, flip = FALSE, permute = FALSE, dim = FALSE)
## S3 method for class 'ursaRaster' as.array(x, ...) ## non-public .as.array(x, drop = FALSE, flip = FALSE, permute = FALSE, dim = FALSE)
... |
Arguments, which are passed to |
x |
|
drop |
Logical. If |
permute |
Logical. If |
flip |
Logical. If |
dim |
Logical. If |
Use permute=TRUE
to create an object of class raster
: as.raster(as.array(...))
The spatial reference system is lost.
If dim=FALSE
then as.array
returns object of class array
.
If dim=TRUE
then as.array
returns dimension of array.
as.matrix
returns object of class matrix
.
Nikita Platonov [email protected]
as.raster
is a function to direct export to the object of class raster
.
as.matrix
with argument/value coords=TRUE
and as.data.frame
for object of class ursaRaster
keep spatial reference system.
session_grid(NULL) a <- pixelsize() a <- (a-global_min(a))/(global_max(a)-global_min(a)) b <- c(entire=a,half=a/2,double=a*2) str(m <- as.matrix(b)) str(d1 <- as.array(b)) str(d2 <- as.array(b[1],drop=FALSE)) str(d3 <- as.array(b[1],drop=TRUE)) contour(d3) filled.contour(d3) d4 <- as.array(b,perm=TRUE)/global_max(b) d4[is.na(d4)] <- 0 str(d4 <- as.raster(d4)) plot(d4)
session_grid(NULL) a <- pixelsize() a <- (a-global_min(a))/(global_max(a)-global_min(a)) b <- c(entire=a,half=a/2,double=a*2) str(m <- as.matrix(b)) str(d1 <- as.array(b)) str(d2 <- as.array(b[1],drop=FALSE)) str(d3 <- as.array(b[1],drop=TRUE)) contour(d3) filled.contour(d3) d4 <- as.array(b,perm=TRUE)/global_max(b) d4[is.na(d4)] <- 0 str(d4 <- as.raster(d4)) plot(d4)
as.data.frame
reorganizes ursaRaster
object into data frame, where first two columns (x
and y
) are coordinates of cells, and the rest columns are cell values.
## S3 method for class 'ursaRaster' as.data.frame(x, ...) # non-public .as.data.frame(obj, band = FALSE, id = FALSE, na.rm = TRUE, all.na = FALSE, col.names = NULL)
## S3 method for class 'ursaRaster' as.data.frame(x, ...) # non-public .as.data.frame(obj, band = FALSE, id = FALSE, na.rm = TRUE, all.na = FALSE, col.names = NULL)
x , obj
|
Object of class |
||||||||||||||||||
... |
Set of arguments, which are recognized via their names (using regular expressions) and classes. Passed to non-public
|
||||||||||||||||||
band |
Logical. If |
||||||||||||||||||
id |
Logical. If |
||||||||||||||||||
na.rm |
Logical. If |
||||||||||||||||||
all.na |
Logical. If |
||||||||||||||||||
col.names |
Character vector or |
The structure of voxel is kept. The number of rows for band=TRUE
is equal to the number of rows for band=FALSE
multiplied to number of bands. To extract all numeric data with destroying of voxel, you may use followed code:subset(as.data.frame(obj,band=TRUE),!is.na(z))
.
Data frame.
If band=TRUE
then
x |
Horizontal coordinate of cell's midpoint |
y |
Vertical coordinate of cell's midpoint |
z |
Value |
band |
Band as a |
id |
Optional. Unique number for |
If band=FALSE
then
x |
Horizontal coordinate of cell's midpoint |
y |
Vertical coordinate of cell's midpoint |
... |
Additional columns. Names of columns are names of bands. Values of columns are values of corresponded bands. |
If ursaRaster
is projected, then data frame has additional attribute attr(...,"proj")
with value of PROJ.4 string.
Nikita Platonov [email protected]
session_grid(NULL) session_grid(regrid(res=50000,lim=c(-1200100,-1400800,1600900,1800200))) a0 <- ursa_dummy(nband=3,min=0,max=100) a0[a0<30 | a0>70] <- NA names(a0) <- c("x","y","z") print(a0) b0 <- as.data.frame(a0) session_grid(NULL) a1 <- as.ursa(b0) print(a1-a0) session_grid(NULL) session_grid(regrid(res=5800000)) set.seed(352) a2 <- as.integer(ursa_dummy(nband=2,min=0,max=100)) a2[a2>50] <- NA print(a2) print(b1 <- as.data.frame(a2,na.rm=FALSE)) print(b2 <- as.data.frame(a2,na.rm=TRUE)) print(b3 <- as.data.frame(a2,all.na=TRUE)) print(b4 <- as.data.frame(a2,band=TRUE,na.rm=FALSE)) print(b5 <- as.data.frame(a2,band=TRUE,all.na=FALSE)) print(b6 <- as.data.frame(a2,band=TRUE,all.na=TRUE)) print(b7 <- as.data.frame(a2,band=TRUE,all.na=TRUE,id=TRUE))
session_grid(NULL) session_grid(regrid(res=50000,lim=c(-1200100,-1400800,1600900,1800200))) a0 <- ursa_dummy(nband=3,min=0,max=100) a0[a0<30 | a0>70] <- NA names(a0) <- c("x","y","z") print(a0) b0 <- as.data.frame(a0) session_grid(NULL) a1 <- as.ursa(b0) print(a1-a0) session_grid(NULL) session_grid(regrid(res=5800000)) set.seed(352) a2 <- as.integer(ursa_dummy(nband=2,min=0,max=100)) a2[a2>50] <- NA print(a2) print(b1 <- as.data.frame(a2,na.rm=FALSE)) print(b2 <- as.data.frame(a2,na.rm=TRUE)) print(b3 <- as.data.frame(a2,all.na=TRUE)) print(b4 <- as.data.frame(a2,band=TRUE,na.rm=FALSE)) print(b5 <- as.data.frame(a2,band=TRUE,all.na=FALSE)) print(b6 <- as.data.frame(a2,band=TRUE,all.na=TRUE)) print(b7 <- as.data.frame(a2,band=TRUE,all.na=TRUE,id=TRUE))
as.integer
for object of class ursaRaster
truncates decimal part of image values and then converts to type integer
.
## S3 method for class 'ursaRaster' as.integer(x, ...)
## S3 method for class 'ursaRaster' as.integer(x, ...)
x |
|
... |
Other arguments which passed to function |
Object of class ursaRaster
where storage.mode
of values is integer
.
Nikita Platonov [email protected]
session_grid(NULL) a <- pixelsize() a <- a-min(a)+0.5 str(ursa_value(a)) print(storage.mode(a$value)) b <- as.integer(a) str(ursa_value(b)) print(storage.mode(b$value))
session_grid(NULL) a <- pixelsize() a <- a-min(a)+0.5 str(ursa_value(a)) print(storage.mode(a$value)) b <- as.integer(a) str(ursa_value(b)) print(storage.mode(b$value))
as.matrix(coords=TRUE)
prepares a list from the first band of ursaRaster
, which is suitable as input parameter for functions image
, contour
and filled.contour
.
## S3 method for class 'ursaRaster' as.matrix(x, ...) ## S3 method for class 'ursaRaster' x[[i]]
## S3 method for class 'ursaRaster' as.matrix(x, ...) ## S3 method for class 'ursaRaster' x[[i]]
x |
Object of class |
... |
Set of arguments, which are recognized via their names (using regular expressions) and classes.
|
i |
Positive integer or character of lentg. If integer, then band index. If character, then band name. If missing, then first band (value |
Item colortable
is mainly for internal usage, e. g., for mapping. Item proj
is useful for convertion back to ursaRaster
object by calling as.ursa
function.
Extract operator x[[i]]
is a wrapper for as.matrix(x[i],coords=TRUE)
Depending of argument coords
.
If coords=FALSE
, then it is a two-dimensional matrix c(samples*lines, bands)
, unclassed from ursaValue
class.
If coords=TRUE
, then it is a list:
x |
Numeric. Midpoints of cells on horizontal axis |
y |
Numeric. Midpoints of cells on vertical axis |
z |
Numeric. Matrix of values |
attr(* , "proj")
|
PROJ.4 string for grid, defined by |
attr(* , "colortable")
|
Optional. Object of class |
Nikita Platonov [email protected]
session_grid(NULL) a <- ursa_dummy(nband=3,min=0,max=100) a <- a[a>=20 & a<=80] ignorevalue(a) <- 121 str(ursa_value(a[2])) str(as.matrix(a[2])) b1 <- a[[2]] str(b1) image(b1,asp=1) b2 <- as.matrix(a[2:3],coords=TRUE) print(c('theSame?'=identical(b1,b2))) a2 <- as.ursa(b2) res <- c(src=a[2],exported_then_imported=a2,diff=a[2]-a2) print(res)
session_grid(NULL) a <- ursa_dummy(nband=3,min=0,max=100) a <- a[a>=20 & a<=80] ignorevalue(a) <- 121 str(ursa_value(a[2])) str(as.matrix(a[2])) b1 <- a[[2]] str(b1) image(b1,asp=1) b2 <- as.matrix(a[2:3],coords=TRUE) print(c('theSame?'=identical(b1,b2))) a2 <- as.ursa(b2) res <- c(src=a[2],exported_then_imported=a2,diff=a[2]-a2) print(res)
as.raster
transforms object of class ursaRaster
to the object of class raster
(package grDevices)
## S3 method for class 'ursaRaster' as.raster(x, ...)
## S3 method for class 'ursaRaster' as.raster(x, ...)
x |
|
... |
Set of arguments, which are recognized via their names (using regular expressions) and classes:
|
A raster
object. It is a matrix. The values of matrix are colors.
Nikita Platonov [email protected]
session_grid(NULL) session_grid(regrid(mul=1/2)) a <- ursa_dummy(4,min=0,max=255) a[a<70] <- NA compose_open(layout=c(1,4),legend=NULL) for (i in seq(4)) { panel_new() panel_plot(as.raster(a[seq(i)]),interpolate=FALSE) panel_annotation(paste("Number of channels:",i)) } compose_close() op <- par(mfrow=c(2,2),mar=rep(0.5,4)) plot(as.raster(a[1:1]),interpolate=FALSE) plot(as.raster(a[1:2]),interpolate=FALSE) plot(as.raster(a[1:3]),interpolate=FALSE) plot(as.raster(a[1:4]),interpolate=FALSE) par(op)
session_grid(NULL) session_grid(regrid(mul=1/2)) a <- ursa_dummy(4,min=0,max=255) a[a<70] <- NA compose_open(layout=c(1,4),legend=NULL) for (i in seq(4)) { panel_new() panel_plot(as.raster(a[seq(i)]),interpolate=FALSE) panel_annotation(paste("Number of channels:",i)) } compose_close() op <- par(mfrow=c(2,2),mar=rep(0.5,4)) plot(as.raster(a[1:1]),interpolate=FALSE) plot(as.raster(a[1:2]),interpolate=FALSE) plot(as.raster(a[1:3]),interpolate=FALSE) plot(as.raster(a[1:4]),interpolate=FALSE) par(op)
as.Raster
converts singe-band ursaRaster
object to raster, multi-band ursaRaster
object to brick and list of ursaRaster
objects to stack. S4 classes “raster”, “brick”, and “stack” are defined in package raster.
as.Raster(obj) ## S3 method for class 'ursaRaster' as.Raster(obj) ## S3 method for class 'list' as.Raster(obj) ## S3 method for class 'ursaStack' as.Raster(obj) ## S3 method for class 'NULL' as.Raster(obj)
as.Raster(obj) ## S3 method for class 'ursaRaster' as.Raster(obj) ## S3 method for class 'list' as.Raster(obj) ## S3 method for class 'ursaStack' as.Raster(obj) ## S3 method for class 'NULL' as.Raster(obj)
obj |
Object of class |
Package raster is required for conversions.
The uppercase as.
R
aster
is important, because as.raster
is used in internal functions for coercion to object of class raster
.
Single-banded ursaRaster
object (with or without colortable) is coerced to RasterLayer
. Colortables are kept.
Multi-banded ursaRaster
object is coerced to RasterBrick
. Colortables are destroyed.
Multi-layered object (list of ursaRaster
objects) is coerced to RasterStack
. Colortables are destroyed.
Either RasterLayer
, RasterBrick
, or RasterStack
object.
If package raster is not installed then return value is NULL
Package raster is marked as "Suggested".
Nikita Platonov [email protected]
## test is skipped: raster's loading time is close to CRAN allowable test time session_grid(NULL) if (requireNamespace("raster")) { session_grid(regrid(mul=1/4)) msk <- ursa_dummy(1,min=0,max=100)>40 a1 <- ursa_dummy(1,min=200,max=500)[msk] a2 <- colorize(a1,ramp=FALSE) a3 <- as.integer(ursa_dummy(3,min=0,max=255.99)) a4 <- ursa_stack(a3[msk]) if (isLayer <- TRUE) { print(a1) r1 <- as.Raster(a1) message(as.character(class(r1))) print(r1) print(raster::spplot(r1)) b1 <- as.ursa(r1) print(c(exported=a1,imported=b1,failed=b1-a1)) print(c(theSameValue=identical(ursa_value(a1),ursa_value(b1)) ,rheSameGrid=identical(ursa_grid(a1),ursa_grid(b1)))) } if (isLayerColortable <- TRUE) { r2 <- as.Raster(a2) message(as.character(class(r2))) print(r2) print(raster::spplot(r2)) b2 <- as.ursa(r2) print(c(theSameValue=identical(ursa_value(a2),ursa_value(b2)) ,rheSameGrid=identical(ursa_grid(a2),ursa_grid(b2)))) } if (isBrickOrRGB <- TRUE) { r3 <- as.Raster(a3) message(as.character(class(r3))) print(r3) print(raster::spplot(r3)) raster::plotRGB(r3) b3 <- as.ursa(r3) print(c(theSameValue=identical(ursa_value(a3),ursa_value(b3)) ,rheSameGrid=identical(ursa_grid(a3),ursa_grid(b3)))) } if (isStack <- TRUE) { r4 <- as.Raster(a4) message(as.character(class(r4))) print(r4) print(raster::spplot(r4)) b4 <- as.ursa(r4) print(c(theSameValue=identical(ursa_value(a4),ursa_value(b4)) ,theSameGrid=identical(ursa_grid(a4),ursa_grid(b4)))) } }
## test is skipped: raster's loading time is close to CRAN allowable test time session_grid(NULL) if (requireNamespace("raster")) { session_grid(regrid(mul=1/4)) msk <- ursa_dummy(1,min=0,max=100)>40 a1 <- ursa_dummy(1,min=200,max=500)[msk] a2 <- colorize(a1,ramp=FALSE) a3 <- as.integer(ursa_dummy(3,min=0,max=255.99)) a4 <- ursa_stack(a3[msk]) if (isLayer <- TRUE) { print(a1) r1 <- as.Raster(a1) message(as.character(class(r1))) print(r1) print(raster::spplot(r1)) b1 <- as.ursa(r1) print(c(exported=a1,imported=b1,failed=b1-a1)) print(c(theSameValue=identical(ursa_value(a1),ursa_value(b1)) ,rheSameGrid=identical(ursa_grid(a1),ursa_grid(b1)))) } if (isLayerColortable <- TRUE) { r2 <- as.Raster(a2) message(as.character(class(r2))) print(r2) print(raster::spplot(r2)) b2 <- as.ursa(r2) print(c(theSameValue=identical(ursa_value(a2),ursa_value(b2)) ,rheSameGrid=identical(ursa_grid(a2),ursa_grid(b2)))) } if (isBrickOrRGB <- TRUE) { r3 <- as.Raster(a3) message(as.character(class(r3))) print(r3) print(raster::spplot(r3)) raster::plotRGB(r3) b3 <- as.ursa(r3) print(c(theSameValue=identical(ursa_value(a3),ursa_value(b3)) ,rheSameGrid=identical(ursa_grid(a3),ursa_grid(b3)))) } if (isStack <- TRUE) { r4 <- as.Raster(a4) message(as.character(class(r4))) print(r4) print(raster::spplot(r4)) b4 <- as.ursa(r4) print(c(theSameValue=identical(ursa_value(a4),ursa_value(b4)) ,theSameGrid=identical(ursa_grid(a4),ursa_grid(b4)))) } }
as.table
is an implementation of function base::table
for values of raster image.
## S3 method for class 'ursaRaster' as.table(x, ...) ursa_table(x, ...)
## S3 method for class 'ursaRaster' as.table(x, ...) ursa_table(x, ...)
x |
|
... |
Other arguments which passed to function |
If ursaRaster
has a colortable
, then values are replaced by names of categories.
ursa_table
is synonym to method as.table
for class `ursaRaster`
.
Object of class table
.
Nikita Platonov [email protected]
session_grid(NULL) a <- colorize(pixelsize(),nbreak=4) t1 <- as.table(a) print(t1) str(t1) ursa_colortable(a) <- NULL t2 <- as.table(a) print(t2)
session_grid(NULL) a <- colorize(pixelsize(),nbreak=4) t1 <- as.table(a) print(t1) str(t1) ursa_colortable(a) <- NULL t2 <- as.table(a) print(t2)
as.ursa
converts R base objects matrix
, array
, numeric
, data.frame
list
, sp objects SpatialGridDataFrame
, SpatialPixelsDataFrame
and SpatialPointsDataFrame
, raster objects raster
, stack
and brick
, and GDAL raster files (using functions from rgdal package) to ursaRaster
object.
as.ursa(obj, ...) as_ursa(obj, ...)
as.ursa(obj, ...) as_ursa(obj, ...)
obj |
R object for coercion |
... |
Depending on class of |
as_ursa
is a synonym to as.ursa
.
This is a high-level function to create ursaRaster
objects. The follwed classes of R objects are implemented:
‘Data Class’ | ‘Appropriate method’ |
array |
ursa_new
|
matrix |
ursa_new
|
numeric |
ursa_new
|
data.frame |
allocate
|
SpatialPointsDataFrame (sp) |
allocate
|
SpatialPixelsDataFrame (sp) |
allocate
|
SpatialGridDataFrame (sp) |
ursa_new
|
list of ursaRaster objects |
unlist
|
list returned by sf::gdal_read |
ursa_new
|
list (general) |
Items $x and $y are required, If lengths of $x and $y are equal to dim of data, then allocate , else: 1) raster grid is defined from $x and $y , 2) ursa_new is called. |
ggmap (ggmap) |
ursa_new . |
raster (raster) |
ursa_new . |
brick (raster) |
ursa_new . |
stack (raster) |
ursa_new . |
bitmap (magick) |
ursa_new . |
character (GDAL supported file name) |
read_gdal .
|
Generally, allocate
is used for objects with non-regular grid, and ursa_new
is used for regular grids. The raster grid is defined from object properties or from sessional grid.
Color tables are supported for GDAL file names and raster objects (raster, brick, stack).
For ENVI *.hdr Labelled Raster Files there are alternatives:
Object of class ursaRaster
Nikita Platonov [email protected]
session_grid(NULL) a1 <- as.ursa(volcano) print(a1) display(a1) session_grid(NULL) b <- ursa_dummy(mul=1/16,bandname=format(Sys.Date()+seq(3)-1,"%A")) print(b) c1 <- b[[1]] ## equal to 'c1 <- as.matrix(b[1],coords=TRUE)' str(c1) b1a <- as.ursa(c1) print(c(original=b[1],imported=b1a)) print(c(projection.b1a=ursa_proj(b1a))) session_grid(NULL) b1b <- as.ursa(c1$z) print(b1b) print(c(projection.b1b=ursa_proj(b1b))) c2 <- as.data.frame(b) str(c2) session_grid(NULL) b2a <- as.ursa(c2) print(b2a) session_grid(NULL) attr(c2,"crs") <- NULL b2b <- as.ursa(c2) print(b2b) print(ursa_grid(b2b)) c3 <- unclass(as.matrix(b,coords=TRUE)) str(c3) session_grid(b) b3a <- as.ursa(c3) print(b3a) print(ursa_grid(b3a)) session_grid(NULL) b3b <- as.ursa(c3) print(b3b) print(ursa_grid(b3b)) c4 <- as.array(b) str(c4) session_grid(b) b4a <- as.ursa(c4) print(b4a) print(ursa_grid(b4a)) session_grid(NULL) b4b <- as.ursa(c4) print(b4b) print(ursa_grid(b4b)) n <- 20 c5 <- data.frame(y=runif(n,min=1000000,max=5000000) ,x=runif(n,min=-3000000,max=1000000) ,value=runif(n,min=0,max=10)) print(head(c5)) session_grid(b) b5a <- as.ursa(c5) print(b5a) ## to avoid over-timing during tests -- begin display(b5a) ## to avoid over-timing during tests -- end session_grid(NULL) b5b <- as.ursa(c5) print(b5b) ## to avoid over-timing during tests -- begin display(b5b) ## to avoid over-timing during tests -- end # b6 <- as.ursa(system.file("pictures/erdas_spnad83.tif",package="rgdal")) b6 <- as.ursa(system.file("tif/geomatrix.tif",package="sf")) print(b6) display(b6,pal=c("black","white"),coast=FALSE,col="orange") ## package 'raster' is required -- begin if (requireNamespace("raster")) { r <- raster::brick(system.file("external/rlogo.gri",package="raster")) print(r) b7 <- as.ursa(r) ursa_proj(b7) <- "" print(b7) display_rgb(b7) } ## package 'raster' is required -- end
session_grid(NULL) a1 <- as.ursa(volcano) print(a1) display(a1) session_grid(NULL) b <- ursa_dummy(mul=1/16,bandname=format(Sys.Date()+seq(3)-1,"%A")) print(b) c1 <- b[[1]] ## equal to 'c1 <- as.matrix(b[1],coords=TRUE)' str(c1) b1a <- as.ursa(c1) print(c(original=b[1],imported=b1a)) print(c(projection.b1a=ursa_proj(b1a))) session_grid(NULL) b1b <- as.ursa(c1$z) print(b1b) print(c(projection.b1b=ursa_proj(b1b))) c2 <- as.data.frame(b) str(c2) session_grid(NULL) b2a <- as.ursa(c2) print(b2a) session_grid(NULL) attr(c2,"crs") <- NULL b2b <- as.ursa(c2) print(b2b) print(ursa_grid(b2b)) c3 <- unclass(as.matrix(b,coords=TRUE)) str(c3) session_grid(b) b3a <- as.ursa(c3) print(b3a) print(ursa_grid(b3a)) session_grid(NULL) b3b <- as.ursa(c3) print(b3b) print(ursa_grid(b3b)) c4 <- as.array(b) str(c4) session_grid(b) b4a <- as.ursa(c4) print(b4a) print(ursa_grid(b4a)) session_grid(NULL) b4b <- as.ursa(c4) print(b4b) print(ursa_grid(b4b)) n <- 20 c5 <- data.frame(y=runif(n,min=1000000,max=5000000) ,x=runif(n,min=-3000000,max=1000000) ,value=runif(n,min=0,max=10)) print(head(c5)) session_grid(b) b5a <- as.ursa(c5) print(b5a) ## to avoid over-timing during tests -- begin display(b5a) ## to avoid over-timing during tests -- end session_grid(NULL) b5b <- as.ursa(c5) print(b5b) ## to avoid over-timing during tests -- begin display(b5b) ## to avoid over-timing during tests -- end # b6 <- as.ursa(system.file("pictures/erdas_spnad83.tif",package="rgdal")) b6 <- as.ursa(system.file("tif/geomatrix.tif",package="sf")) print(b6) display(b6,pal=c("black","white"),coast=FALSE,col="orange") ## package 'raster' is required -- begin if (requireNamespace("raster")) { r <- raster::brick(system.file("external/rlogo.gri",package="raster")) print(r) b7 <- as.ursa(r) ursa_proj(b7) <- "" print(b7) display_rgb(b7) } ## package 'raster' is required -- end
Function from this band.*
list returns required statistics for each band.
band_mean(obj) band_sd(obj) band_sum(obj) band_min(obj) band_max(obj) band_n(obj) band_nNA(obj) band_quantile(obj, ...)
band_mean(obj) band_sd(obj) band_sum(obj) band_min(obj) band_max(obj) band_n(obj) band_nNA(obj) band_quantile(obj, ...)
obj |
Object of class |
... |
Arguments, which are passed to generic |
band_mean
returns mean value.
band_sd
returns value of standard deviation with n-1
denominator.
band_sum
returns sum of values.
band_min
returns minimal value.
band_max
returns maximal value.
band_n
returns number of non-NA
pixels.
band_nNA
returns number of NA
pixels.
band_quantile
returns matrix of quantiles.
Named vector of numerical or integer values. Band names are used for naming.
Currently, implementation is not optimal, because firstly bundle of statistics is computed using band_stat function, and then required statistics is extracted.
Nikita Platonov [email protected]
session_grid(NULL) a <- ursa_dummy() print(a) print(a<80) print(class(a)) a[a<80] a[a<80] <- NA b1 <- band_stat(a) print(b1) b2.n <- band_n(a) str(b2.n) b2.mean <- band_mean(a) print(b1$mean) print(b2.mean) print(b1$mean-b2.mean) print(band_quantile(a))
session_grid(NULL) a <- ursa_dummy() print(a) print(a<80) print(class(a)) a[a<80] a[a<80] <- NA b1 <- band_stat(a) print(b1) b2.n <- band_n(a) str(b2.n) b2.mean <- band_mean(a) print(b1$mean) print(b2.mean) print(b1$mean-b2.mean) print(band_quantile(a))
For each band of ursaRaster
object, band_stat
returns certain statistics (mean, sd, sum, min, max, number of non-NA
pixels, number of NA
pixels). Regarding to each band, it is global operations of map algebra.
band_stat(x, grid = FALSE, raw = FALSE)
band_stat(x, grid = FALSE, raw = FALSE)
x |
Object of class |
grid |
Logical. If |
raw |
Logical. For the case of raster values are categories, if |
If raster values are not in memory or grid=TRUE
then ursa_info
is returned.
Generic function print
for object of class ursaRaster
uses returned value of band_stat
function with formatted columns.
Statistics is computed for omitted NA
values.
data.frame
. Row names are indices of bands. Column names are:
name |
Band name. |
mean |
Mean value. |
sd |
Value of standard deviation with |
sum |
Sum of values. |
min |
Minimal value. |
min |
Maximal value. |
n |
Number of non- |
nNA |
Number of |
Nikita Platonov [email protected]
Columns extraction from returned data frame is in the group of band.*
functions.
session_grid(NULL) s <- substr(as.character(sessionInfo()),1,48) a <- reclass(ursa_dummy(mul=1/2,bandname=s),ramp=FALSE) band_stat(a,grid=TRUE) b2 <- band_stat(a) b3 <- band_stat(a,raw=TRUE) str(b2) str(b3) print(b2) print(a) ## 'print.ursaRaster' uses 'band_stat' print(a,raw=TRUE)
session_grid(NULL) s <- substr(as.character(sessionInfo()),1,48) a <- reclass(ursa_dummy(mul=1/2,bandname=s),ramp=FALSE) band_stat(a,grid=TRUE) b2 <- band_stat(a) b3 <- band_stat(a,raw=TRUE) str(b2) str(b3) print(b2) print(a) ## 'print.ursaRaster' uses 'band_stat' print(a,raw=TRUE)
bandname
(names
) returns names of bands for object of class ursaRaster
or existing ENVI labelled *.hdr file.
bandname<-
(names<-
) sets names of bands for object of class ursaRaster
.
bandname(x) bandname(x) <- value ## S3 method for class 'ursaRaster' names(x) ## S3 replacement method for class 'ursaRaster' names(x) <- value
bandname(x) bandname(x) <- value ## S3 method for class 'ursaRaster' names(x) ## S3 replacement method for class 'ursaRaster' names(x) <- value
x |
Object of class |
value |
Character of length the same length of number of bands of |
names
is a synonym for bandname
. names<-
is a synonym for bandname<-
For bandname
and names
, character vector.
For bandname<-
and names<-
, updated object of class ursaRaster
.
Nikita Platonov [email protected]
session_grid(NULL) a1 <- pixelsize() a2 <- c("Band 1"=a1,Band2=a1/2,sqrt=sqrt(a1),NA) print(a2) print(bandname(a2)) bandname(a2)[1:2] <- c("Original","Half") print(a2) print(bandname(a2))
session_grid(NULL) a1 <- pixelsize() a2 <- c("Band 1"=a1,Band2=a1/2,sqrt=sqrt(a1),NA) print(a2) print(bandname(a2)) bandname(a2)[1:2] <- c("Original","Half") print(a2) print(bandname(a2))
Set of functions for checking is any or all bands have no data, and for retrieving indices for non-data bands.
band_blank(obj, ref = c("any", "0", "NA"), verbose = FALSE) ursa_blank(obj, ref)
band_blank(obj, ref = c("any", "0", "NA"), verbose = FALSE) ursa_blank(obj, ref)
obj |
Object of class |
ref |
Character. Definition criteria, what is blank mean. If value |
verbose |
Logical. Value |
It is defined locally that if all values of band are NA
or 0 (see description to argument ref
), then such band is blank. The fact is ursa_new
create new object in memory with default values NA
, but create_envi
writes zeros to disk quick. It is decided to consider both these cases as blank. Function band_blank
checks blanks for each band of image. If all bands are blank then function ursa_blank
returns TRUE
.
Function ursa_blank
returns logical value of length 1.
Function band_blank
returns logical value of length nband(obj)
.
Nikita Platonov [email protected]
is.na
returns object of class ursaRaster
; it is mask of cells, which have NA
value.
session_grid(NULL) a <- ursa_new(bandname=c("first","second","third","fourth")) ursa_value(a,"first") <- 0 ## 'a[1] <- 1' works, but it is slow print(ursa_blank(a)) a[3] <- pixelsize() a[4] <- a[3]>625 print(a) print(band_blank(a)) print(which(band_blank(a))) print(ursa_blank(a))
session_grid(NULL) a <- ursa_new(bandname=c("first","second","third","fourth")) ursa_value(a,"first") <- 0 ## 'a[1] <- 1' works, but it is slow print(ursa_blank(a)) a[3] <- pixelsize() a[4] <- a[3]>625 print(a) print(band_blank(a)) print(which(band_blank(a))) print(ursa_blank(a))
This function is an instrument for appending bands or for reorganizing bands.
## S3 method for class 'ursaRaster' c(...)
## S3 method for class 'ursaRaster' c(...)
... |
Objects of class |
You may use this function to assign new bandname for single-band raster: objDst <- c('Relative density'=objSrc)
Use also 'Extract' operator [ ]
to reorganize band sequence.
The returned object can be interpreted as a brick in the notation of package raster. To produce stack just call list
or ursa_stack
.
ursaRaster
object.
Nikita Platonov [email protected]
ursa_brick
converts list of ursaRaster
objects (stack) to a singe multiband ursaRaster
object (brick).
session_grid(NULL) session_grid(regrid(mul=1/16)) a1 <- ursa_dummy(nband=2) names(a1) <- weekdays(Sys.Date()+seq(length(a1))-1) a2 <- ursa_dummy(nband=2) names(a2) <- names(a1) print(a1) print(a2) a3 <- a1[1] print(names(a3)) a4 <- c(today=a3) print(names(a4)) print(b1 <- c(a1,a2)) print(b2 <- c(a1=a1)) print(b3 <- c(a1=a1,a2=a2)) print(b5 <- c(a1=a1,a2=a2[1])) print(b4 <- c(a1,'(tomorrow)'=a1[2])) ## raster append print(b6 <- c(a1,50))
session_grid(NULL) session_grid(regrid(mul=1/16)) a1 <- ursa_dummy(nband=2) names(a1) <- weekdays(Sys.Date()+seq(length(a1))-1) a2 <- ursa_dummy(nband=2) names(a2) <- names(a1) print(a1) print(a2) a3 <- a1[1] print(names(a3)) a4 <- c(today=a3) print(names(a4)) print(b1 <- c(a1,a2)) print(b2 <- c(a1=a1)) print(b3 <- c(a1=a1,a2=a2)) print(b5 <- c(a1=a1,a2=a2[1])) print(b4 <- c(a1,'(tomorrow)'=a1[2])) ## raster append print(b6 <- c(a1,50))
In the case of 'Cannot allocate vector of size ...' error message chunk_band
returns list of bands indices, which are suitable for allocation in memory at once, chunk_line
returns list of lines (rows) indices, which are suitable for allocation in memory at once. chunk_expand
is used to expand lines indices and can by applied in focal functions.
chunk_band(obj, mem = 100, mul = 1) chunk_line(obj, mem = 100, mul = 1) chunk_expand(ind, size = 3)
chunk_band(obj, mem = 100, mul = 1) chunk_line(obj, mem = 100, mul = 1) chunk_expand(ind, size = 3)
obj |
Object of class |
mem |
Numeric. Memory size in GB, which is suitable for allocation. |
mul |
Numeric. Expansion or reduction factor (multiplier) of default value of memory allocation. |
ind |
Integer. Line indices. |
size |
Integer. Size of focal window. |
chunk_band
returns list with sequences of bands
chunk_line
returns list with sequences of lines
chunk_expand
returns list:
src |
expanded set if line indices |
dst |
matching of source indices in the expanded set |
Nikita Platonov [email protected]
## 1. Prepare data session_grid(NULL) fname <- ursa:::.maketmp(2) a <- create_envi(fname[1],nband=3,ignorevalue=-99) for (i in seq(nband(a))) a[i] <- pixelsize()^(1/i) close(a) rm(a) ## 2. Read a <- open_envi(fname[1]) chB <- chunk_band(a,2) str(chB) for (i in chB) print(a[i]) chL <- chunk_line(a,2.5) str(chL) for (j in chL) print(a[,j]) ## 3. Filtering with partial reading b <- create_envi(a,fname[2]) fsize <- 15 for (j in chL) { k <- chunk_expand(j,fsize) b[,j] <- focal_mean(a[,k$src],size=fsize)[,k$dst] } d1 <- b[] ## 4. Filtering in memory d2 <- focal_mean(a[],size=fsize) close(a,b) envi_remove(fname) print(d1-d2) print(round(d1-d2,4))
## 1. Prepare data session_grid(NULL) fname <- ursa:::.maketmp(2) a <- create_envi(fname[1],nband=3,ignorevalue=-99) for (i in seq(nband(a))) a[i] <- pixelsize()^(1/i) close(a) rm(a) ## 2. Read a <- open_envi(fname[1]) chB <- chunk_band(a,2) str(chB) for (i in chB) print(a[i]) chL <- chunk_line(a,2.5) str(chL) for (j in chL) print(a[,j]) ## 3. Filtering with partial reading b <- create_envi(a,fname[2]) fsize <- 15 for (j in chL) { k <- chunk_expand(j,fsize) b[,j] <- focal_mean(a[,k$src],size=fsize)[,k$dst] } d1 <- b[] ## 4. Filtering in memory d2 <- focal_mean(a[],size=fsize) close(a,b) envi_remove(fname) print(d1-d2) print(round(d1-d2,4))
close()
for ursaRaster
object closes connection for opened file using inheritted function base::close
. Function close_envi()
closes opened connection for ENVI binary file.
## S3 method for class 'ursaRaster' close(...) close_envi(...)
## S3 method for class 'ursaRaster' close(...) close_envi(...)
... |
Object or sequence of objects of class |
NULL
Nikita Platonov [email protected]
close
of base package
session_grid(NULL) a <- create_envi() fname <- a$con$fname message(paste("Created file",dQuote(basename(fname)),"will be deleted.")) print(dir(pattern=basename(envi_list(fname)))) close(a) invisible(envi_remove(fname))
session_grid(NULL) a <- create_envi() fname <- a$con$fname message(paste("Created file",dQuote(basename(fname)),"will be deleted.")) print(dir(pattern=basename(envi_list(fname)))) close(a) invisible(envi_remove(fname))
compress
reduces dimension of source image matrix and assigns indices. decompress
uses indices for expansion of reduced image matrix.
decompress(obj) compress(obj)
decompress(obj) compress(obj)
obj |
Object of class |
After masking, vectorization of lines, points and small polygons image matrix is often sparse.
Compressing (compress
) is an option to reduce object size in memory. Decompressing (decompress
) restore original data matrix.
Object of class ursaRaster
Currently, usage of compressed image matrix is limited. Spatial filtering (e.g. focal_mean
) does not operate with compressed data.
Nikita Platonov [email protected]
session_grid(NULL) b <- as.data.frame(pixelsize()) b <- subset(b,x>1000000 & x<2000000 & y>3000000 & y<4000000) a1 <- as.ursa(b) print(a1) print(object.size(a1)) a2 <- compress(a1) print(a2) print(object.size(a2)) a3 <- decompress(a2) print(a3) print(object.size(a3)) print(identical(a1,a3))
session_grid(NULL) b <- as.data.frame(pixelsize()) b <- subset(b,x>1000000 & x<2000000 & y>3000000 & y<4000000) a1 <- as.ursa(b) print(a1) print(object.size(a1)) a2 <- compress(a1) print(a2) print(object.size(a2)) a3 <- decompress(a2) print(a3) print(object.size(a3)) print(identical(a1,a3))
colorize
assigns color table to raster image.
colorize(obj, value = NULL, breakvalue = NULL, name = NULL, pal = NULL, inv = NA, stretch = c("default", "linear", "equal", "mean", "positive", "negative", "diff", "category", "julian", "date", "time", "slope", "conc", "sd", "significance", "bathy", "grayscale", "greyscale", ".onetoone"), minvalue = NA, maxvalue = NA, byvalue = NA, ltail = NA, rtail = NA, tail = NA, ncolor = NA, nbreak = NA, interval = 0L, ramp = TRUE, byte = FALSE, lazyload = TRUE, reset = FALSE, origin = "1970-01-01" ,format = "", alpha = "", colortable = NULL, verbose = FALSE, ...) palettize(...) ## wrapper for non-spatial vectors
colorize(obj, value = NULL, breakvalue = NULL, name = NULL, pal = NULL, inv = NA, stretch = c("default", "linear", "equal", "mean", "positive", "negative", "diff", "category", "julian", "date", "time", "slope", "conc", "sd", "significance", "bathy", "grayscale", "greyscale", ".onetoone"), minvalue = NA, maxvalue = NA, byvalue = NA, ltail = NA, rtail = NA, tail = NA, ncolor = NA, nbreak = NA, interval = 0L, ramp = TRUE, byte = FALSE, lazyload = TRUE, reset = FALSE, origin = "1970-01-01" ,format = "", alpha = "", colortable = NULL, verbose = FALSE, ...) palettize(...) ## wrapper for non-spatial vectors
obj |
|
value |
Numeric. Values to be assigned to categories. |
breakvalue |
Numeric. Values to be assigned to intervals. |
name |
Character. Names of categories. |
pal |
Function or character. If function then value should corresponded to function, which creates a vector of colors. If character then values should correponded to R color names or hexadecimal string of the form "#RRGGBB" or "#RRGGBBAA". |
inv |
Logical. Invert sequence of colors. |
stretch |
Character. Either kind of value transformation ( |
minvalue |
Numeric. Lower range limit. |
maxvalue |
Numeric. Upper range limit. |
byvalue |
Numeric. Increment of the sequence from |
ltail |
Numeric. Partition of omitted values at left tail. |
rtail |
Numeric. Partition of omitted values at right tail. |
tail |
Numeric. Partition of omitted values at both tail. If length of |
ncolor |
Numeric or interer. Number of desired colors (or categories) |
nbreak |
Numeric or interer. Number of desired separators between colors. |
interval |
Integer. How to underwrite categories? Use direct |
ramp |
Logical. Is color ramp required? |
byte |
Logical. Forcing to produce color table for storage in byte format (not more than 255 colors). Default is |
lazyload |
Logical. If |
reset |
Logical. If |
origin |
Character. Origin for |
format |
Character. Format date/time objects for arguments |
alpha |
Character or numeric. The characteristics of transparency. If character, then hexadecimal values between "00" and "FF" are allowed, and then coerced to numeric value between 0 and 255. If numeric, and |
colortable |
Object of class |
verbose |
Logical. Some output in console. Primarily for debug purposes. |
... |
For For |
palettize
is a wrapper ursa_colortable(colorize(...))
to return color table for one-dimensional numeric or character vector.
colortable
is designed to prepare pretty thematic maps.
Color rampimg (ramp=TRUE
) is not quick in computatons and has no effective labelling. It is intoduced to visualize non-thematic maps, and it is assumed that labeling can be omitted for such maps.
The labelling implementation is based on some improvements of pretty
function. The notation of intervals is mixed by brackets and comparative symbols, for example: "<=1.5","(1.5,2.5]","(2.5,3.5]",">3.5"
Reserved values for interval
:
0L
or FALSE
- no interlavs. Values are interpreted as category, even if they are in non-nominal scale
1L
or TRUE
- each category corresponds to interval. The low limit of lowest category is -Inf
. The high limit of highest category is +Inf
2L
- different implementation of interval=1
. In some cases may relult more pretty labeling.
If breaks
is numerical vector and colors
has zero length, then it is assumed interal scaling, and interval=1L
is assigned to unspecified interval
Finite values of extreme intervals are neccessary sometimes, however this option is not implemented currently
Keywords for stretch
to create pre-defined color tables:
"positive"
- lower limit is 0. Palette is "Oranges"
"negative"
- higher limit is 0. Palette is "Purples"
"grayscale", "greyscale"
- palette is "Greys". Usually used for raw satellite images.
"mean"
- designed for common thematic maps and for averaged map across set of maps. Palette is "Spectral"
"sd"
- designed for spatial mapping of standard deviation across set of maps. Palette is "YlGnBu"
"diff"
- diverge palette "RdBu". Absolute values of lower and upper limits are equal, zero is in the middle of palette. Designed for anomaly maps.
"slope"
- is similar to diff
but without extreme colors, which are reserved for contouring of statistically significant areas.
"significance"
- desiged to illustrate statistically significant areas of slope.
The realisation is colortable(obj, value=c(-0.999, -0.99, -0.95, -0.9, -0.5, +0.5, +0.9, +0.95, +0.99, +0.999), interval=1L, palname="RdBu")
"category"
- Values are interpreted in nominal scale. Palette is based on random colors from "Pairs" palette.
"conc"
- designed for visualization of sea ice concentration data, which have lower limit 0 and higher limit 100. Palette is "Blues"
"bathy"
- designed for ocean depth (bathymetry) maps. Internally colorize(obj, stretch="equal",interval=1L, palname="Blues", inv=TRUE)
is used to detect the crossing from shelf waters to deep water basin. Better practice is to do second step with manual specification of value
argument.
"internal"
- continuous colors, designed for conversion to greyscale with keeping of intensities.
"default"
- allowing to detect stretch by intuition, without any strong mathematical criteria
It is allowed manual correction of labels using followed code example:
names(ursa_colortable(x)) <- c("a<=0","0<a<=1","a>1")
Object of class ursaRaster
with named character vector of item $colortable
Nikita Platonov [email protected]
ursa_colortable
,
ursa_colortable<-
session_grid(NULL) a <- pixelsize()-350 print(a) b1 <- colorize(a,ramp=FALSE) print(ursa_colortable(b1)) b2 <- colorize(a,interval=1,stretch="positive",ramp=FALSE) print(ursa_colortable(b2)) b3 <- colorize(a,interval=2,stretch="positive",ramp=FALSE) print(ursa_colortable(b3)) b4 <- colorize(a,value=c(150,250),interval=1) print(ursa_colortable(b4)) names(ursa_colortable(b4)) <- c("x<=150","150<x<=250","x>250") print(ursa_colortable(b4)) display(b4)
session_grid(NULL) a <- pixelsize()-350 print(a) b1 <- colorize(a,ramp=FALSE) print(ursa_colortable(b1)) b2 <- colorize(a,interval=1,stretch="positive",ramp=FALSE) print(ursa_colortable(b2)) b3 <- colorize(a,interval=2,stretch="positive",ramp=FALSE) print(ursa_colortable(b3)) b4 <- colorize(a,value=c(150,250),interval=1) print(ursa_colortable(b4)) names(ursa_colortable(b4)) <- c("x<=150","150<x<=250","x>250") print(ursa_colortable(b4)) display(b4)
Manipulation with color tables of raster images.
## S3 method for class 'ursaColorTable' print(x, ...) ## S3 method for class 'ursaColorTable' x[i] ursa_colortable(x) ursa_colortable(x) <- value ursa_colorindex(ct) ursa_color(ct, ...) ## S3 method for class 'ursaColorTable' names(x) ## S3 replacement method for class 'ursaColorTable' names(x) <- value
## S3 method for class 'ursaColorTable' print(x, ...) ## S3 method for class 'ursaColorTable' x[i] ursa_colortable(x) ursa_colortable(x) <- value ursa_colorindex(ct) ursa_color(ct, ...) ## S3 method for class 'ursaColorTable' names(x) ## S3 replacement method for class 'ursaColorTable' names(x) <- value
x |
|
ct |
|
value |
Named character vector. In Replacement functions: For For |
i |
Integer vector. Indices specifying elements to extract part (subset) of color table. |
... |
In |
The example of the class structure
Class 'ursaColorTable' Named chr [1:4] "#313695" "#BCE1EE" "#FDBE70" "#A50026" ..- attr(*, "names")= chr [1:4] "<= 450" "(450;550]" "(550;650]" "> 650"
It is recommended to use ursa_colortable
and ursa_colortable<-
instead of colortable
and colortable<-
. ursa_colortable
and colortable
are synonyms. ursa_colortable<-
and colortable<-
are synonyms too. Package raster contains colortable
and colortable<-
functions. colortable
and colortable<-
will be remove from this package if the case of frequent joint use of both packages.
If color tables describe continuous and non-intersecting intervals, then print
gives additional line of extracted breaks.
ursa_colortable
returns value of $colortable
element if ursaRaster
object.
ursa_colortable<-
returns ursaRaster
object with modified $colortable
element.
Class of $colortable
element is “ursaColorTable”. This is named character vector, where names are categories, and values are “#RRGGBB” or R color names.
Extract function []
for ursaColorTable
object returns object of class ursaColorTable
.
Extract function names
for ursaColorTable
object returns character vector (names of categories).
Replace function names<-
for ursaColorTable
object returns ursaColorTable
with changed names of categories.
ursa_colorindex
returns index (if presents) for ursaColorTable
object.
ursa_color
returns character vector of colors in hex format.
Color tables are written to ENVI header file.
If colors are specified as R color names, then slow down may appear.
Nikita Platonov [email protected]
session_grid(NULL) print(methods(class="ursaColorTable")) a <- pixelsize() print(a) b1 <- colorize(a,value=c(400,500,600,700),interval=FALSE) b2 <- colorize(a,value=c(450,550,650) ,interval=TRUE) display(list(b1,b2)) print(is.ursa(a,"colortable")) print(is.ursa(b1,"colortable")) print(is.ursa(b2,"colortable")) print(ursa_colortable(a)) print(ursa_colortable(b1)) print(ursa_colortable(b2)) ursa_colortable(b2) <- c("Low"="darkolivegreen1" ,"Moderate"="darkolivegreen2" ,"High"="darkolivegreen3" ,"undefined"="darkolivegreen4") print(ursa_colortable(b2)) names(ursa_colortable(b2))[4] <- "Polar" print(ursa_colortable(b2)) display(b2) lab <- sample(c("A","B","C"),9,replace=TRUE) lab ct <- ursa_color(lab) names(ct) <- lab ct
session_grid(NULL) print(methods(class="ursaColorTable")) a <- pixelsize() print(a) b1 <- colorize(a,value=c(400,500,600,700),interval=FALSE) b2 <- colorize(a,value=c(450,550,650) ,interval=TRUE) display(list(b1,b2)) print(is.ursa(a,"colortable")) print(is.ursa(b1,"colortable")) print(is.ursa(b2,"colortable")) print(ursa_colortable(a)) print(ursa_colortable(b1)) print(ursa_colortable(b2)) ursa_colortable(b2) <- c("Low"="darkolivegreen1" ,"Moderate"="darkolivegreen2" ,"High"="darkolivegreen3" ,"undefined"="darkolivegreen4") print(ursa_colortable(b2)) names(ursa_colortable(b2))[4] <- "Polar" print(ursa_colortable(b2)) display(b2) lab <- sample(c("A","B","C"),9,replace=TRUE) lab ct <- ursa_color(lab) names(ct) <- lab ct
ursaRaster
class.
Set of generic functions, implemented for objects of ursaRaster
class.
## S3 method for class 'ursaRaster' duplicated(x, incomparables = FALSE, MARGIN = 2, fromLast = FALSE, ...) ## S3 method for class 'ursaRaster' diff(x, lag = 1, differences = 1, ...)
## S3 method for class 'ursaRaster' duplicated(x, incomparables = FALSE, MARGIN = 2, fromLast = FALSE, ...) ## S3 method for class 'ursaRaster' diff(x, lag = 1, differences = 1, ...)
x |
Object of |
incomparables |
Passed to S3 method |
MARGIN |
Overwitten to value |
fromLast |
Passed to S3 method |
lag |
Passed to default S3 method |
differences |
Passed to default S3 method |
... |
Other arguments, which are passed to the respective S3 method. |
duplicated()
: logical of length equal to number of bands.
diff()
: ursaRaster
object.
Nikita Platonov [email protected]
a <- ursa_dummy(5) a[3] <- a[2] a duplicated(a) diff(a)
a <- ursa_dummy(5) a[3] <- a[2] a duplicated(a) diff(a)
Function compose_close
does followed tasks: 1) completes all unfinsished actions before shutting down graphical device, 2) cuts extra margins, and 3) opens resulted PNG file in the associated viewer.
compose_close(...) ## non-public .compose_close(kind = c("crop2", "crop", "nocrop"), border = 5, bpp = 0, execute = TRUE, verbose = FALSE)
compose_close(...) ## non-public .compose_close(kind = c("crop2", "crop", "nocrop"), border = 5, bpp = 0, execute = TRUE, verbose = FALSE)
... |
Set of arguments, which are recognized via their names and classes, and then passed to
|
||||||||||||
kind |
Character keyword for cutting of excess white spaces. If |
||||||||||||
border |
Non-negative integer. Number of pixels for margins, which are not cropped. Default is |
||||||||||||
bpp |
Integer. Bits per pixel for output PNG file. Valid values are |
||||||||||||
execute |
Logical. Should created PNG file be opened in the associated external program for viewing graphical files? Default is |
||||||||||||
verbose |
Logical. Value |
The cut manipulations (crop="crop"
or crop="crop2"
) are implemented using readPNG
and writePNG
functions of package png. These fuctions have limitations in the memory allocation.
Function compose_close
clears all internal graphical options, specified during compose_open
executing.
Some parameters are specified in compose_open
: weather output PNG file will be removed after opening (logical delafter
), or what is the time of waiting for file opening and next removing (numerical wait
in seconds).
Function returns NULL
value.
Currenty, execute=TRUE
is implemented for Windows platform only using construction R CMD open \emph{fileout}
.
Nikita Platonov [email protected]
session_grid(NULL) a <- ursa_dummy(nband=6,min=0,max=255,mul=1/4) ## exam 1 compose_open() compose_close() ## exam 2 compose_open(a) compose_close() ## exam 3 compose_open("rgb",fileout="tmp1") compose_plot(a[1:3]) compose_close(execute=FALSE) Sys.sleep(1) a <- dir(pattern="tmp1.png") print(a) file.remove(a)
session_grid(NULL) a <- ursa_dummy(nband=6,min=0,max=255,mul=1/4) ## exam 1 compose_open() compose_close() ## exam 2 compose_open(a) compose_close() ## exam 3 compose_open("rgb",fileout="tmp1") compose_plot(a[1:3]) compose_close(execute=FALSE) Sys.sleep(1) a <- dir(pattern="tmp1.png") print(a) file.remove(a)
compose_design
prepares scheme for layout of images and color bars.
compose_design(...)
compose_design(...)
... |
Set of arguments, which are recognized via their names and classes:
|
Function compose_design
extracts and validates required arguments from a list of parameters (three-dots construct) and passes them to internal function .compose_design
.
Argument legend
is a list
or coerced to a list
. The length of this list is equal to number of color bars; each item describes certain color bar. This desctiption is a list again with two elements, which desribes the position of color bar in relation to main panels of images.
If argument legend
is in interval 1L:4L
then it is interpreted as argument side
in functions axis
, mtext
. Argument side
in function compose_design
plays the same role. It is introduced for consistency with R graphic system.
In the one of example below (See Examples section) the layout with dimension of two rows by three columns is considered (layout=c(2,3)
). The dimension of resulting layout matrix is c(7,9)
, where 7=2*2+3, and 9=3*2+3.
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [1,] 0 0 0 0 0 0 0 0 0 [2,] 0 0 0 0 0 0 0 0 0 [3,] 0 0 1 0 2 0 3 0 0 [4,] 0 0 0 0 0 0 0 0 0 [5,] 0 0 4 0 5 0 6 0 0 [6,] 0 0 0 0 0 0 0 0 0 [7,] 0 0 0 0 0 0 0 0 0
The complicated color bar structure is specified via R's list
function:
> leg <- list("7"=list(row=1,col=0),"8"=list(2,"left") + ,"9"=list("full","right"),"10"=list("top","full") + ,"11"=list(99,1:2),"12"=list("bottom",3)) > str(leg) $ 7 :List of 2 ..$ row: num 1 ..$ col: num 0 $ 8 :List of 2 ..$ : num 2 ..$ : chr "left" $ 9 :List of 2 ..$ : chr "full" ..$ : chr "right" $ 10:List of 2 ..$ : chr "top" ..$ : chr "full" $ 11:List of 2 ..$ : num 99 ..$ : int [1:2] 1 2 $ 12:List of 2 ..$ : chr "bottom" ..$ : num 3
Here, six color bars are specified. It is a list of six lists (sub-lists). First item of sub-list is row number, and the second one is column number. Integers can be replaces by character keywords.
For row-position, "top"
means 0L
(less than first row), "bottom"
means large integer value (greater than last row, currently, 99L
), "first"
means 1L
, "last"
means number of last row (2L
in this example), "full"
means whole range from first to last rows (1L:2L
in this example). Values "top"
and "bottom"
are used for horizontal color bars (last three sub-lists), and the rest for vertical color bars (first three sub-lists).
For column-position, "left"
means 0L
(less then first column), "bottom"
means large integer value (greater than last column, currently, 99L
), "first"
means first column (1L
), "last"
means last column (3L
in this example), "full"
means whole range from first to last columns ((1L:3L
in this example)). Values "left"
and "right"
are used for vertical color bars, and the rest are for horizontal ones.
The resulting layout is a sparse matrix with zero values for each even row and each column. These zeros plays role of white space between panels in the plotted layout. In our example, values 1L:6L
are corresponded to six map panels, and values 7L:12L
are corresponded to six narrow panels of color bars (legends).
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [1,] 0 0 10 0 10 0 10 0 0 [2,] 0 0 0 0 0 0 0 0 0 [3,] 7 0 1 0 2 0 3 0 9 [4,] 0 0 0 0 0 0 0 0 0 [5,] 8 0 4 0 5 0 6 0 9 [6,] 0 0 0 0 0 0 0 0 0 [7,] 0 0 11 0 11 0 12 0 0
It is a list of class ursaLayout
.
layout |
Integer matrix with dimension |
image |
Nonnegative integer. Number of panels with images. |
dim |
Nonnegative integer of length two. Number of rows and number of columns for panel layout. |
legend |
Nonnegative integer. Number of panels with color bars (legends). |
The returned value is passed to function compose_open
and further is kept in the options
until calling of compose_close
.
Nikita Platonov [email protected]
session_grid(NULL) a <- ursa_dummy(nband=5,min=1,max=200,mul=1/8) b <- list(colorize(a[1:3],pal.rich=240,pal.rotate=0) ,colorize(sqrt(a[4:5]),pal.rich=-15,pal.rotate=0,stretch="equal")) cl1 <- compose_design(layout=c(2,3),byrow=TRUE,legend=NULL) print(cl1) compose_open(cl1) compose_close() cl2 <- compose_design(layout=c(2,3),byrow=FALSE,legend="left") print(cl2$layout) compose_open(cl2) compose_close() cl3 <- compose_design(a,side=2) print(cl3) compose_open(cl3) compose_close() cl4 <- compose_design(b) print(cl4) ## to avoid over-time during example check -- begin compose_open(cl4) compose_plot(b,decor=FALSE,las=2) compose_close("nocrop") ## to avoid over-time during example check -- end cl5 <- compose_design(b,byrow=FALSE,skip=3 ,legend=list(list("full","left"),list(1:2,"right"))) compose_open(cl5) compose_plot(b,decor=FALSE) compose_close("nocrop") leg <- list(list(1,0),list(2,"left") ,list("full","right"),list("top","full") ,list(99,1:2),list("bottom",3)) str(leg) cl6 <- compose_design(layout=c(2,3),skip=NA,legend=leg) print(cl6) compose_open(cl6,scale=3,pointsize=16) compose_close("nocrop") cl7 <- compose_design(layout=matrix(c(1,1,3,2,2,0),nrow=2,byrow=TRUE)) print(cl7) compose_open(cl7) compose_close()
session_grid(NULL) a <- ursa_dummy(nband=5,min=1,max=200,mul=1/8) b <- list(colorize(a[1:3],pal.rich=240,pal.rotate=0) ,colorize(sqrt(a[4:5]),pal.rich=-15,pal.rotate=0,stretch="equal")) cl1 <- compose_design(layout=c(2,3),byrow=TRUE,legend=NULL) print(cl1) compose_open(cl1) compose_close() cl2 <- compose_design(layout=c(2,3),byrow=FALSE,legend="left") print(cl2$layout) compose_open(cl2) compose_close() cl3 <- compose_design(a,side=2) print(cl3) compose_open(cl3) compose_close() cl4 <- compose_design(b) print(cl4) ## to avoid over-time during example check -- begin compose_open(cl4) compose_plot(b,decor=FALSE,las=2) compose_close("nocrop") ## to avoid over-time during example check -- end cl5 <- compose_design(b,byrow=FALSE,skip=3 ,legend=list(list("full","left"),list(1:2,"right"))) compose_open(cl5) compose_plot(b,decor=FALSE) compose_close("nocrop") leg <- list(list(1,0),list(2,"left") ,list("full","right"),list("top","full") ,list(99,1:2),list("bottom",3)) str(leg) cl6 <- compose_design(layout=c(2,3),skip=NA,legend=leg) print(cl6) compose_open(cl6,scale=3,pointsize=16) compose_close("nocrop") cl7 <- compose_design(layout=matrix(c(1,1,3,2,2,0),nrow=2,byrow=TRUE)) print(cl7) compose_open(cl7) compose_close()
compose_legend
recognizes color tables and characters among arguments and passes them to suitable functions for plotting on margins outside of panel area.
compose_legend(...)
compose_legend(...)
... |
If first argument is a list, then either If first argument is
|
Named list in the first argument is allowed or named vectors are allowed if first argument is not a list. For legend_colorbar
name of object can be used as an argument units
.
This function is designed to make plot on moderate level of usage with the followed construction:
compose_open(...) compose_panel(...) compose_legend(...) compose_close(...)
Function compose_panel
returns list of color tables of plotted rasters, and followed sequence is available:
ct <- compose_panel(a) compose_legend(ct) # or, if 'a' has color tables, then 'compose_legend(a)'
NULL
Nikita Platonov [email protected]
session_grid(NULL) b <- lapply(as.list(ursa_dummy(2)),colorize) cd <- compose_design(layout=c(1,2),legend=list(list(1,"left"),list(1,"right") ,list("top","full"),list("bottom",1))) for (i in 1:4) { compose_open(cd,dev=i==1) ct <- compose_panel(b,decor=FALSE) if (i==2) compose_legend(ct) else if (i==3) compose_legend(ct[[1]],'Tomorrow'=b[[2]] ,top="This is example of legend composition" ,format(Sys.Date(),"(c) %Y")) else if (i==4) compose_legend(c(ct,"top","bottom"),units=c("left","right")) compose_close() }
session_grid(NULL) b <- lapply(as.list(ursa_dummy(2)),colorize) cd <- compose_design(layout=c(1,2),legend=list(list(1,"left"),list(1,"right") ,list("top","full"),list("bottom",1))) for (i in 1:4) { compose_open(cd,dev=i==1) ct <- compose_panel(b,decor=FALSE) if (i==2) compose_legend(ct) else if (i==3) compose_legend(ct[[1]],'Tomorrow'=b[[2]] ,top="This is example of legend composition" ,format(Sys.Date(),"(c) %Y")) else if (i==4) compose_legend(c(ct,"top","bottom"),units=c("left","right")) compose_close() }
compose_open
create plot layout and open PNG graphic device.
compose_open(...)
compose_open(...)
... |
Set of arguments, which are recognized via their names and classes:
|
Other usage of compose_open(...,dev=TRUE)
is
compose_open(...,dev=FALSE) compose_close()
The reason to use compose_design
function before compose_open
is to reduce number of arguments in the case of complicated layout matrix and non-standard settings.
compose_open
passes arguments to png
function.
If character values are specified for arguments width
, height
or scale
, then layout development is oriented to produce PNG file, which will be used as a paper copy. Character values for width
and height
are in centimeters. Character value V
or 1:
V
of scale
defines scale 1/
V
.
The Cairo device (device="cairo"
) is more quick on MS Windows computers. However Windows GDI may produce less depth of colors (even 8 BPP) in the case of no font antialiasing. Usage of Windows GDI (device="windows"
) is a way to produce illustations for scientific journals with strict requirements of mininal line width, font size, etc.
The PNG layout reserves extra margins for captions of color bars. These margins are filled by white spaces. The cropping of layout applies to created PNG file using read-write functions of package png. Only white ("white"
, "#FFFFFF"
) or transparent ("transparent"
) colors are regognized as white spaces. Therefore, specification of bg!="white"
or bg!="transparent"
breaks PNG image cropping.
It is noted that Cyrillics is supported on Windows GDI (device="windows"
) and is not supported on Cairo (device="cairo"
) types of PNG device on MS Windows platform.
Argument retina
is ignored for leaflet-compatible tiling.
Name of created PNG file.
If dev=TRUE
then output on console is layout matrix.
The set of required parameters for plotting are kept until function compose_close
call via options
.
ursaPngAuto |
For developers. Indicator of high-level functions for internal use (manual set; value is |
ursaPngBox |
Argument |
ursaPngDelafter |
Argument |
ursaPngDevice |
Argument |
ursaPngDpi |
Argument |
ursaPngFamily |
Applied for text plotting in annotations and legends. |
ursaPngFigure |
Set |
ursaPngFileout |
Name of created PNG file. |
ursaPngLayout |
Layout matrix, the object of class |
ursaPngPaperScale |
Numeric. Used for scalebar representation on the paper-based maps. If value |
ursaPngPlot |
The opposite to argument |
ursaPngScale |
The actual value of argument |
ursaPngShadow |
Set |
ursaPngSkipLegend |
Integer vector of non-negative length. Defines list of images panels, for which the color bars are not displayed. |
ursaPngWaitBeforeRemove |
Argument |
Nikita Platonov [email protected]
session_grid(NULL) b <- ursa_dummy(nband=4,min=0,max=50,mul=1/4,elements=16) p <- list(colorize(b[1:2],pal.rich=240,pal.rotate=0) ,colorize(sqrt(b[3:4]),pal.rich=-15,pal.rotate=0,stretch="equal")) p ## exam #01 compose_open(width=950,dpi=150,pointsize=16,legend=NULL,dev=TRUE) ## exam #02 compose_open(pointsize=8,dpi=150,scale="1:130000000") compose_plot(colorize(b[1]),scalebar=TRUE,coast=FALSE) compose_close() ## exam #03 cl <- compose_design(layout=c(2,4) ,legend=list(list("top","full"),list("bottom",1:3))) compose_open(cl,dev=TRUE) ## exam #04 cl <- compose_design(p,layout=c(2,3),skip=c(2,4,6)) compose_open(cl,dev=TRUE) ## exam #05 cl <- compose_design(p,side=3) compose_open(cl,dev=FALSE,bg="transparent") compose_close()
session_grid(NULL) b <- ursa_dummy(nband=4,min=0,max=50,mul=1/4,elements=16) p <- list(colorize(b[1:2],pal.rich=240,pal.rotate=0) ,colorize(sqrt(b[3:4]),pal.rich=-15,pal.rotate=0,stretch="equal")) p ## exam #01 compose_open(width=950,dpi=150,pointsize=16,legend=NULL,dev=TRUE) ## exam #02 compose_open(pointsize=8,dpi=150,scale="1:130000000") compose_plot(colorize(b[1]),scalebar=TRUE,coast=FALSE) compose_close() ## exam #03 cl <- compose_design(layout=c(2,4) ,legend=list(list("top","full"),list("bottom",1:3))) compose_open(cl,dev=TRUE) ## exam #04 cl <- compose_design(p,layout=c(2,3),skip=c(2,4,6)) compose_open(cl,dev=TRUE) ## exam #05 cl <- compose_design(p,side=3) compose_open(cl,dev=FALSE,bg="transparent") compose_close()
compose_panel
divides the multi-band raster image (brick) or layers of raster images (stack) on the sequence of single-band images and plots each image on the separate panel of layout. Panel plotting is finalized by adding of decoration (gridlines, coastline, annotation, scalebar).
compose_panel(..., silent = FALSE)
compose_panel(..., silent = FALSE)
... |
Set of arguments, which are passed to |
silent |
Logical. Value |
For each panel of layout the sequence of called functions is permanent:panel_new
- - > panel_raster
- - > panel_coastline
- - > panel_graticule
- - > panel_annotation
- -> panel_scalebar
.
If this order is undesirable, then call these functions in the required sequence.
NULL
Nikita Platonov [email protected]
panel_new
, panel_raster
, panel_coastline
, panel_graticule
, panel_annotation
, panel_scalebar
session_grid(NULL) a <- ursa_dummy(6) b1 <- list(maxi=a[1:4]*1e2,mini=a[5:6]/1e2) print(b1) b2 <- lapply(b1,function(x) colorize(x,nbreak=ifelse(global_mean(x)<100,5,NA))) compose_open(b2,byrow=FALSE ,legend=list(list("bottom",1:2),list("bottom",3),list("left"))) ct <- compose_panel(b2,scalebar=2,coastline=3:4,gridline=5:6,gridline.margin=5 ,annotation.text=as.character(seq(6))) compose_legend(ct) legend_mtext(as.expression(substitute(italic("Colorbars are on the bottom")))) compose_close()
session_grid(NULL) a <- ursa_dummy(6) b1 <- list(maxi=a[1:4]*1e2,mini=a[5:6]/1e2) print(b1) b2 <- lapply(b1,function(x) colorize(x,nbreak=ifelse(global_mean(x)<100,5,NA))) compose_open(b2,byrow=FALSE ,legend=list(list("bottom",1:2),list("bottom",3),list("left"))) ct <- compose_panel(b2,scalebar=2,coastline=3:4,gridline=5:6,gridline.margin=5 ,annotation.text=as.character(seq(6))) compose_legend(ct) legend_mtext(as.expression(substitute(italic("Colorbars are on the bottom")))) compose_close()
compose_plot
plots images (raster brick or raster stack) and corresponding color bars according to given rectangular layout.
compose_plot(...)
compose_plot(...)
... |
Set of arguments, which are passed to |
Function merges to functions. The first one plots image layout and returns list of color tables. The second one plots legend (colorbars) based on returned color tables. Simplified description is:
ct <- compose_panel(...) compose_legend(ct,...)
These two functions are separated to allow use additional plotting on image panel after primary plot of raster and decorations before panel change or legend plot.
This function returns NULL
value.
Nikita Platonov [email protected]
session_grid(NULL) a <- ursa_dummy(nband=6,min=0,max=255,mul=1/4) if (example1 <- TRUE) { b1 <- ursa_brick(a) # b1 <- colorize(b1,stretch="positive",ramp=FALSE) compose_open(b1) compose_plot(b1,grid=FALSE,coast=FALSE,scale=FALSE,trim=1 ,stretch="positive",ramp=!FALSE) compose_close() } if (example2 <- TRUE) { b2 <- ursa_stack(a) compose_open(b2) compose_plot(b2,grid=FALSE,coast=FALSE,labels=5,trim=2,las=0) compose_close() }
session_grid(NULL) a <- ursa_dummy(nband=6,min=0,max=255,mul=1/4) if (example1 <- TRUE) { b1 <- ursa_brick(a) # b1 <- colorize(b1,stretch="positive",ramp=FALSE) compose_open(b1) compose_plot(b1,grid=FALSE,coast=FALSE,scale=FALSE,trim=1 ,stretch="positive",ramp=!FALSE) compose_close() } if (example2 <- TRUE) { b2 <- ursa_stack(a) compose_open(b2) compose_plot(b2,grid=FALSE,coast=FALSE,labels=5,trim=2,las=0) compose_close() }
create_envi
creates ENVI binary and header files on disk. ENVI binary file is filled by blank (zero) values.
create_gdal
is just an entry for GDAL wrapper; currently via internal ENVI implementation.
create_gdal(x, ...) create_envi(x, ...)
create_gdal(x, ...) create_envi(x, ...)
x |
Filename, or any refenerce object to help assign properties of new ENVI file. Can be missed. |
... |
Use |
Prior ursa version < 3.10, create_gdal()
used classes and methods from package rgdal. Currenty, alternatives are not found for complete replacement of rgdal. At the present, ENVI binary and header are created, firstly, and close()
transforms to desired GDAL format, finally.
create_envi
and create_gdal
use parameters of grid (boundary box, cell size, projection) from reference object of class ursaRaster
in argument x
or calls session_grid
. You may specify values of GDAL or ENVI binary file later using [<-
. If x
is object of class ursaRaster
then metadata parameters (interleave, data type, ignore value, etc) are inherited.
Keywords:
fname
- character. File name for created GDAL or ENVI file.
For create_envi
only: If compress
of connections
is not specified then example for “fileout” file name:
"fileout" - If external 'gzip' is found then "fileout.envigz" is created else "fileout.envi"
"fileout.envi" - "fileout.envi" is created without any compression.
"fileout." - "fileout" is created without any compression.
"fileout.bin" - "fileout.bin" is created without any compression.
"fileout.img" - "fileout.img" is created without any compression.
"fileout.dat" - "fileout.dat" is created without any compression.
driver
- character. For create_gdal
only. Which GDAL driver is used.
layername
- character of length>=1. Layernames (‘Band name’ in ENVI header file)
bandname
- character of length>=1. Layernames (‘Band name’ in ENVI header file)
name
- character of length>=1. Layernames (‘Band name’ in ENVI header file)
nodata
- integer or numeric. Value in GDAL or ENVI binary file, which is interpretted as NA
in R
ignore
- integer or numeric. Value in GDAL or ENVI binary file, which is interpretted as NA
in R
ignorevalue
- integer or numeric. Value in GDAL or ENVI binary file, which is interpretted as NA
in R
bg
- integer or numeric. Value in GDAL or ENVI binary file, which is interpretted as NA
in R
connection
- character. For create_envi
only. connections
for ENVI binary file.
Valid values are:
"gz" - connection is "gzfile"
"bz" - connection is "bzfile"
"xz" - connection is "xzfile"
"file" - connection is "file"
interleave
- character. Interleave. Valid values are "bsq", "bil", "bip". For create_gdal
and driver="GTiff"
valid values are "bsq" and "bil".
datatype
- character or integer (numeric). Data type.
Valid values are:
1, "byte", "Byte", "UInt8" = Byte: 8-bit unsigned integer
2, "integer", "Int16" = Integer: 16-bit signed integer
3, "Int32" = Long: 32-bit signed integer
4, "real", "float", "Float32" = Floating-point: 32-bit single-precision
5, "Float64" = Double-precision: 64-bit double-precision floating-point
11, "UInt8" = Byte: 8-bit signed integer. Not in specification. Only for use with this package.
12, "UInt16" = Integer: 16-bit unsigned integer
13, "UInt32" = Long: 32-bit unsigned integer
Specification https://www.nv5geospatialsoftware.com/docs/ENVIHeaderFiles.html is used.
byteorder
- numeric (integer). Byte order.
bands
- numeric( integer). Number of bands/layers
nband
- numeric( integer). Number of bands/layers
nlayer
- numeric( integer). Number of bands/layers
layers
- numeric( integer). Number of bands/layers
compress
- integer (numeric) or logical. For create_envi
only. Should ENVI binary file be compressed after closing connection.
wkt
- integer (numeric) or logical. Forced adding ‘coordinate system string’ to ENVI header file
ext
- character. For create_envi
only. Extension of ENVI binary file. For extensions not in c("envi","bin","dat","img")
list
If file name is unknown, then random file name is used with informing via message()
.
Object of class ursaRaster
with opened connection of GDAL or ENVI binary file.
Nikita Platonov [email protected]
ursa_new
creates object of class ursaRaster
in memory and allows to assign values at once.
Use session_grid
to check or specify parameters of grid before calling create_envi
.
Use [<-
to assign values to ENVI binary file after calling create_envi
.
Use close
(or close_envi
) to close connections
.
session_grid(NULL) a <- create_envi() fname <- a$con$fname dir(pattern=basename(envi_list(fname))) close(a) invisible(envi_remove(fname)) a <- create_envi("exam1",layername=paste("Band",1:5) ,ignorevalue=99,datatype="Int16",interleave="bil") ursa_info(a) print(a[]) close(a) invisible(envi_remove("exam1"))
session_grid(NULL) a <- create_envi() fname <- a$con$fname dir(pattern=basename(envi_list(fname))) close(a) invisible(envi_remove(fname)) a <- create_envi("exam1",layername=paste("Band",1:5) ,ignorevalue=99,datatype="Int16",interleave="bil") ursa_info(a) print(a[]) close(a) invisible(envi_remove("exam1"))
cubehelix
returns set of RGB colours, which are screen display of intensity images
cubehelix(n, value = numeric(), weak = NA, rich = NA, rotate = NA, hue = NA, gamma = 1, dark = NA, light = NA, bright = NA, inv = NA, verbose = NA)
cubehelix(n, value = numeric(), weak = NA, rich = NA, rotate = NA, hue = NA, gamma = 1, dark = NA, light = NA, bright = NA, inv = NA, verbose = NA)
n |
Positive integer. Length of returned color vector. If |
value |
Numeric vector of values, which are associated with a palette. If both positive and negative values are in this vector, then divergence color palette is returned. Default in numeric of length zero (unspecified). |
weak |
Numeric. The angle (in degrees) of the helix for color with |
rich |
Numeric. The angle (in degrees) of the helix for color with |
rotate |
Numeric. The angle of rotation (in degrees) of the helix over the scale; can be negative. If |
hue |
Non-negative numeric. Saturation of color. |
gamma |
Numeric. Power of intensity. Intensity is between |
dark |
Positive numeric in interval between 0 and 255. The intensity of the darkest color in the palette. For light backgrounds default is 63. For dark backgrounds default is 14 (inverse order with |
light |
Positive numeric in interval between 0 and 255. The intensity of the lightest color in the palette. For light backgrounds default is 241, for dark backgrounds default is 192 (inverse order with |
bright |
Positive numeric in interval between 0 and 255. Value for equal intensity for |
inv |
Logical. Inversion of color intensity. If |
verbose |
Logical. Value |
This is modified source code of function cubeHelix()
from package rje under GPL>=2 license.
The palette design is oriented that figures can be printed on white paper. Under this assumption, light color is for small values, and dark color is for big values. In some computer vision and GIS software black background is used, and in this case light color for big values, and dark color of small values looks more naturally. For some thematic maps big values are light, and small values are small (for example, sea ice concentration: open water is blue, close ice is white). RGB and Grayscale remote sensing and photo imagery use light colors for strong signal, and dark colors for weak signal.
Light background is default for figure (specified by argument background
in function compose_open
).
The palette divergency can be defined only if value
is specified. If all values are positive, or all values are negative, then returned palette is not drivergent. For divergent palettes the helix sequence is continuous.
If dark
and lihgt
are unspecified, the color contrast bewteen dark
and light
drops on reducing number of colors in returned vector.
Vector of RGB color specification.
Dave Green, Robin Evans
Dave Green
Robin Evans
Nikita Platonov [email protected]
Dave Green's ‘cubehelix’ colour scheme.
Green, D. A., 2011, ‘A colour scheme for the display of astronomical intensity images’, Bulletin of the Astronomical Society of India, 39, 289. http://astron-soc.in/bulletin/11June/289392011.pdf (pre-print at 'arxiv.org')
rje::cubeHelix()
; rje at CRAN: https://CRAN.R-project.org/package=rje
session_grid(NULL) set.seed(352) session_grid(regrid(mul=1/16)) a <- ursa_dummy(3,min=0,max=255) b4 <- b3 <- b2 <- b1 <- vector("list",length(a)) for (i in seq_along(b1)) { b1[[i]] <- colorize(a[i],pal=cubehelix(11,weak=45*i,rotate=+270),ncolor=11) b2[[i]] <- colorize(a[i],pal=cubehelix(11,weak=45*i,rotate=-270),ncolor=11) b3[[i]] <- colorize(a[i]-127,pal=cubehelix) hue <- sample(seq(2)-1,1) s <- ifelse(hue==0,NA,runif(1,min=91,max=223)) b4[[i]] <- colorize(a[i]-127,pal=cubehelix,pal.hue=hue,pal.dark=s,pal.light=s) } display(c(b1,b2),layout=c(2,NA),decor=FALSE) display(c(b3,b4),layout=c(2,NA),decor=FALSE)
session_grid(NULL) set.seed(352) session_grid(regrid(mul=1/16)) a <- ursa_dummy(3,min=0,max=255) b4 <- b3 <- b2 <- b1 <- vector("list",length(a)) for (i in seq_along(b1)) { b1[[i]] <- colorize(a[i],pal=cubehelix(11,weak=45*i,rotate=+270),ncolor=11) b2[[i]] <- colorize(a[i],pal=cubehelix(11,weak=45*i,rotate=-270),ncolor=11) b3[[i]] <- colorize(a[i]-127,pal=cubehelix) hue <- sample(seq(2)-1,1) s <- ifelse(hue==0,NA,runif(1,min=91,max=223)) b4[[i]] <- colorize(a[i]-127,pal=cubehelix,pal.hue=hue,pal.dark=s,pal.light=s) } display(c(b1,b2),layout=c(2,NA),decor=FALSE) display(c(b3,b4),layout=c(2,NA),decor=FALSE)
Retrieve the dimension of an object of class ursaRaster
. The replacement function is dummy; it doesn't change raster dimension.
## S3 method for class 'ursaRaster' dim(x) ## S3 replacement method for class 'ursaRaster' dim(x) <- value
## S3 method for class 'ursaRaster' dim(x) ## S3 replacement method for class 'ursaRaster' dim(x) <- value
x |
Object of class |
value |
Any. Ignored |
Use extract operator []
and combine function c
to change third (e.g., temporal) dimension of raster.
Use regrid
function to change grid parameters and to resize/resample raster into new grid.
The 'Extract' function dim
returns named integer vector of length three: 1) number of lines/rows, 2) number of samples/columns, 3) number of bands/channels/layers.
The 'Replacement' function dim<-
returns ursaRaster
object without changes.
Nikita Platonov [email protected]
session_grid(NULL) session_grid(regrid(mul=1/16)) a <- ursa_dummy(nband=3) ursa_info(a) print(dim(a)) dim(a) <- c(25,00,34) print(dim(a)) b <- create_envi("tmp1",bandname=letters[1:5],compress=FALSE) print(dim(b)) close(b) envi_remove("tmp1")
session_grid(NULL) session_grid(regrid(mul=1/16)) a <- ursa_dummy(nband=3) ursa_info(a) print(dim(a)) dim(a) <- c(25,00,34) print(dim(a)) b <- create_envi("tmp1",bandname=letters[1:5],compress=FALSE) print(dim(b)) close(b) envi_remove("tmp1")
If raster's categories are integer or numeric, then raster values are restored from names of categories. Otherwise only category names are dropped.
discolor(obj, nodata = NA)
discolor(obj, nodata = NA)
obj |
Object of class |
nodata |
Numeric. Flag value for "no-data". If |
Object of class ursaRaster
without color table.
Nikita Platonov [email protected]
session_grid(NULL) a <- colorize(pixelsize(),ncolor=7) print(ursa_colortable(a)) print(a) b <- discolor(a) print(ursa_colortable(b)) print(b)
session_grid(NULL) a <- colorize(pixelsize(),ncolor=7) print(ursa_colortable(a)) print(a) b <- discolor(a) print(ursa_colortable(b)) print(b)
High-level function to create multi-panel layout of images and to display with decoration (gridlines, coastlines, scalebar, colorbars) in the PNG format. It is an aggregator of low-level functions for typical plotting.
display(obj, ...)
display(obj, ...)
obj |
Object of class |
... |
Passed to either |
If argument obj
is missing (e.g, calling display()
without parameters) then plotting the sessional CRS with blank image.
If argument obj
is list
of ursaRaster
objects (or object of class ursaStack
) then display_stack
is called.
If argument obj
is object of class ursaRaster
and has 3 or 4 bands and values in each band are integer
and in interval between 0 and 255, then display_rgb
is called.
If argument obj
is object of class ursaRaster
then firstly internal test is applied to detect either image's bands contains homogeneous information (raster brick) or heterogeneous information (raster stack). Then either display_brick
or display_stack
is called. This test is rough due to unknown data origin. It is supposed to adjust kind of plotting by means of direct specification of display_brick
or display_stack
.
Returned value from either display_brick
or display_stack
or display_rgb
functions.
Nikita Platonov [email protected]
display_brick
, display_stack
, display_rgb
R-styled plotting: plot
, image
session_grid(NULL) set.seed(500) a.brick <- a.stack <- ursa_dummy(nband=3,min=0,max=255,mul=1/16) a.stack[2] <- a.stack[2]/10 a.stack[3] <- sqrt(a.stack[3]) a.rgb <- as.integer(round(a.brick)) print(a.brick) print(a.stack) print(a.rgb) display(a.brick,decor=FALSE) display(a.stack,decor=FALSE) display(a.rgb)
session_grid(NULL) set.seed(500) a.brick <- a.stack <- ursa_dummy(nband=3,min=0,max=255,mul=1/16) a.stack[2] <- a.stack[2]/10 a.stack[3] <- sqrt(a.stack[3]) a.rgb <- as.integer(round(a.brick)) print(a.brick) print(a.stack) print(a.rgb) display(a.brick,decor=FALSE) display(a.stack,decor=FALSE) display(a.rgb)
Raster image is forced to be interpreted as homogenuous (having the same units). It implies creating multi-panel layout with multiple colorbars.
display_brick(obj, ...) display_homo(obj, ...)
display_brick(obj, ...) display_homo(obj, ...)
obj |
Object of class |
... |
Passed to hierarchy of plotting functions: |
If argument obj
is list
of ursaRaster
objects (or object of class ursaStack
) then obj
is coerced to class ursaRaster
('stack' is coerced to 'brick').
display_homo
is a synonym to display_brick
. It is introduced to emphasize the plotting of homogenous object.
Function returns NULL
value.
Nikita Platonov [email protected]
display
, display_stack
, display_rgb
session_grid(NULL) a <- ursa_dummy(nband=3,min=0,max=250) a[2] <- -a[1] a[3] <- sqrt(a[1]) a2 <- ursa_stack(a) print(a2) display(a2) # likely 'display_stack' will be called display_brick(a2,stretch="eq",labels=c(-150,-100,0,10,12,20,100,150))
session_grid(NULL) a <- ursa_dummy(nband=3,min=0,max=250) a[2] <- -a[1] a[3] <- sqrt(a[1]) a2 <- ursa_stack(a) print(a2) display(a2) # likely 'display_stack' will be called display_brick(a2,stretch="eq",labels=c(-150,-100,0,10,12,20,100,150))
Raster images are forced to be interpreted as color composition with 3 (RGB) or 4 (RGBA) channels. Values should be in the range between 0 and 255.
display_rgb(obj, ...)
display_rgb(obj, ...)
obj |
Object of class |
... |
Passed to hierarchy of plotting functions: |
If argument obj
is list
of ursaRaster
objects (or object of class ursaStack
) then obj
is coerced to class ursaRaster
('stack' is coerced to 'brick').
Colorbar is not plotted.
By default, the created PNG has 24 bits per pixel. This is equal to parameter bpp=24
(compose_close
). It is allow to specify other value, e.g., display_rgb(a,bpp=8)
.
By default, labels of gridlines are located in bottom and left sides of the panel with raster. This is equal to parameter margin=c(TRUE,TRUE,FALSE,FALSE)
(panel_graticule
). It is allow to specify other value, e.g., display_rgb(a,margin=T)
.
Currently, for color compositions the argument useRaster
(panel_raster
) is introduced to fix possible coordinate mismatch for Cairo-devices, but have never used.
Function returns NULL
value.
Nikita Platonov [email protected]
display
, display_brick
, display_stack
session_grid(NULL) a <- ursa_dummy(nband=3) display_rgb(a)
session_grid(NULL) a <- ursa_dummy(nband=3) display_rgb(a)
Raster images are forced to be interpreted as heterogenuous (having the different units). It implies creating multi-panel layout with multiple colorbars.
display_stack(obj, ...) display_hetero(obj, ...)
display_stack(obj, ...) display_hetero(obj, ...)
obj |
Object of class |
... |
Passed to hierarchy of plotting functions: |
If argument obj
is object of class ursaRaster
then obj
is coerced to list
of ursaRaster
objects ('brick' is coerced to 'stack').
The plot layout is either two-columns or two-rows. Extent of coordinate grid has a form of rectangle. The layout selection depends on ratio of rectangle's sides. For single-column design use parameter layout=c(NA,1L)
. e.g., display_brick(a,layout=c(NA,1))
, for single-row design use parameter layout=c(1,NA)
. The same is for forcing of two-columns (layout=c(NA,2L)
) and two-rows layouts (layout=c(2L,NA)
). Other layouts are not applicable for multiple colorbars.
display_hetero
is a synonym to display_stack
. It is introduced to emphasize the plotting of complex object with heterogeneous elements, for example, having different units.
Function returns NULL
value.
Nikita Platonov [email protected]
display
, display_brick
, display_rgb
session_grid(NULL) a <- ursa_dummy(nband=3) display_stack(a)
session_grid(NULL) a <- ursa_dummy(nband=3) display_stack(a)
Management of ENVI files similar to functions of OS file manager.
envi_exists(pattern = ".+", path = ".", all.files = FALSE, full.names = TRUE, recursive = FALSE, ignore.case = TRUE, exact = FALSE) envi_list(pattern = ".+", path = ".", all.files = FALSE, full.names = recursive, recursive = FALSE, ignore.case = TRUE, exact = FALSE) envi_remove(pattern = ".+", path = ".", all.files = FALSE, full.names = recursive, recursive = FALSE, ignore.case = TRUE, verbose = FALSE) envi_copy(src, dst, overwrite = TRUE) envi_rename(src, dst, overwrite = TRUE) ursa_exists(fname)
envi_exists(pattern = ".+", path = ".", all.files = FALSE, full.names = TRUE, recursive = FALSE, ignore.case = TRUE, exact = FALSE) envi_list(pattern = ".+", path = ".", all.files = FALSE, full.names = recursive, recursive = FALSE, ignore.case = TRUE, exact = FALSE) envi_remove(pattern = ".+", path = ".", all.files = FALSE, full.names = recursive, recursive = FALSE, ignore.case = TRUE, verbose = FALSE) envi_copy(src, dst, overwrite = TRUE) envi_rename(src, dst, overwrite = TRUE) ursa_exists(fname)
pattern |
Either filename (like |
path |
Either path name (like |
all.files |
A logical value. If FALSE, only the names of visible files are returned. If TRUE, all file names will be returned. Similar to |
full.names |
A logical value. If TRUE, the directory path is prepended to the file names to give a relative file path. If FALSE, the file names (rather than paths) are returned. Similar to |
recursive |
Logical. Should the listing recurse into directories? Similar to |
ignore.case |
Logical. Should pattern-matching be case-insensitive? Similar to |
exact |
Logical. Attempt to cancel regular expressions. |
verbose |
Logical. |
src |
Strings of length 1 or more. Name or directory name or path of source ENVI files. |
dst |
Strings of length 1 or more. Name or directory name path of destination ENVI files. Length is assuming to be equal to length of |
overwrite |
Logical. |
fname |
Character. Full file name or file pattern with file path. |
Functions do not view content of any files. The major identifier of ENVI files in file system is ENVI header (*.hdr) file. Binary file is searching along 1) original *.envi, *.bin, *.img, *.dat extensions, 2) externally packing *.gz. *.bz2, *.xz extensions, or 3) packed by this package *.envigz, *.bingz extensions. Functions envi_copy()
and envi_rename()
keeps original extension of ENVI binary file; use file.rename
to rename ENVI binary file.
envi_exists()
returns integer number of found ENVI files.
envi_list()
returns character vector of found ENVI files.
envi_remove()
returns character vector of deleted ENVI files.
envi_copy()
returns 0L.
envi_rename()
returns value of file.rename
, which is applied to objects in file system.
ursa_exists()
returs TRUE
if any *.tif, *.tiff, *.bin, *.hfa file is found.
Nikita Platonov [email protected]
session_grid(NULL) wd <- setwd(tempdir()) a1 <- create_envi("tmp1.envi") a2 <- create_envi("tmp2.") close(a1,a2) envi_list() envi_copy("tmp1","tmp3") envi_copy("tmp2","tmp4") envi_list() envi_rename("tmp3","tmp5") envi_list() envi_exists("nofilewithsuchname") envi_exists("tmp[34]") envi_remove(".+") envi_list() setwd(wd)
session_grid(NULL) wd <- setwd(tempdir()) a1 <- create_envi("tmp1.envi") a2 <- create_envi("tmp2.") close(a1,a2) envi_list() envi_copy("tmp1","tmp3") envi_copy("tmp2","tmp4") envi_list() envi_rename("tmp3","tmp5") envi_list() envi_exists("nofilewithsuchname") envi_exists("tmp[34]") envi_remove(".+") envi_list() setwd(wd)
This operator is used to get single band or subset of bands from multi-band ursaRaster
object. Another purpose is get portions of data including data reading from files.
## S3 method for class 'ursaRaster' x[i, j, ..., drop = FALSE]
## S3 method for class 'ursaRaster' x[i, j, ..., drop = FALSE]
x |
|
i |
Integer or character. If integer, then band index, specifying bands to extract. If character, either list of band names or character sting for |
j |
Integer. Line index, specifying lines to extract. |
... |
Mentioned for consistence with internal generic function |
drop |
Not used. For consistence with generic function. |
Operator \sQuote{[}
is high-level implementation for data reading. If x$value
item is not applicable, then value of ursaRaster
is not in memory. In this case the controlled by i
and j
portion is read to memory. If both i
and j
are missing, then x[]
reads all values from file.
x[,j]
is appropriate for time series analysis and processing in the case bands have relation to temporal observation. Use regrid
for geographical subset and cropping.
ursaRaster
object with extracter bands. Values ($value
item) are in memory.
It is not allowed to read simultaneously portion of bands and portion of lines from file, e.g.,
x <- open_envi(fname) y <- x[2:3,10:20] close(x)
Such brunch is not implemented in code. You use one of the followed tricks:
x <- open_envi(fname) y <- x[2:3][,20:30] close(x)
or
x <- open_envi(fname) y <- x[,20:30][2:3] close(x)
Nikita Platonov [email protected]
session_grid(NULL) ## Prepare session_grid(regrid(mul=1/8)) a <- pixelsize() w <- c("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday" ,"MondayAgain") b <- rep(a/mean(a),length(w))+seq(length(w))-1 bandname(b) <- w nr <- ursa_rows(b) bottom <- (as.integer(nr/2)):nr write_envi(b,"tmp1",compress=FALSE,interleave="bil") ## Extract print(b["Monday",regexp=TRUE]) print(b["Monday",regexp=FALSE]) print(b["s"]) print(b["^s"]) d1 <- b[6,bottom] rm(b) ## Read from file b <- open_envi("tmp1") print(b[]) print(b[-c(6:8)]) d2 <- b[,bottom][6] ## don't use b[6,bottom] close(b) envi_remove("tmp1") ## Compare print(d1) print(d2)
session_grid(NULL) ## Prepare session_grid(regrid(mul=1/8)) a <- pixelsize() w <- c("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday" ,"MondayAgain") b <- rep(a/mean(a),length(w))+seq(length(w))-1 bandname(b) <- w nr <- ursa_rows(b) bottom <- (as.integer(nr/2)):nr write_envi(b,"tmp1",compress=FALSE,interleave="bil") ## Extract print(b["Monday",regexp=TRUE]) print(b["Monday",regexp=FALSE]) print(b["s"]) print(b["^s"]) d1 <- b[6,bottom] rm(b) ## Read from file b <- open_envi("tmp1") print(b[]) print(b[-c(6:8)]) d2 <- b[,bottom][6] ## don't use b[6,bottom] close(b) envi_remove("tmp1") ## Compare print(d1) print(d2)
For each band and for each cell, depending of specification, function finds either minimal or maximal value inside of square window. Focal operation of map algebra.
focal_extrem(x, kind = c("min", "max"), size = 3, cover = 1e-06, fillNA = FALSE, saveMargin = TRUE, verbose = 0L) focal_min(x, size = 3, cover = 1e-06, fillNA = FALSE, saveMargin = TRUE, verbose = 0L) focal_max(x, size = 3, cover = 1e-06, fillNA = FALSE, saveMargin = TRUE, verbose = 0L)
focal_extrem(x, kind = c("min", "max"), size = 3, cover = 1e-06, fillNA = FALSE, saveMargin = TRUE, verbose = 0L) focal_min(x, size = 3, cover = 1e-06, fillNA = FALSE, saveMargin = TRUE, verbose = 0L) focal_max(x, size = 3, cover = 1e-06, fillNA = FALSE, saveMargin = TRUE, verbose = 0L)
x |
Object of class |
kind |
Character. What kind of extremum is required. Allowed values |
size |
Positive numeric. Odd values (3, 5, 7, ...) are allowed, but if other value is specified, then it expanded to the next odd value not less than original value. Default is |
cover |
Numeric. |
fillNA |
Logical. If |
saveMargin |
Logical. If |
verbose |
Integer of |
focal_min(x,...)
is a wrapper to focal_extrem(x,"min",...)
focal_max(x,...)
is a wrapper to focal_extrem(x,"max",...)
Object of class ursaRaster
with the same number of bands as in input raster.
Nikita Platonov [email protected]
Other focal operations: focal_mean
, focal_median
.
session_grid(NULL) a <- ursa_dummy(nband=2,mul=1/8,elements=32) a[a<80] <- NA b.min <- focal_extrem(a,"min",size=4,cover=0.5,verbose=1L) b.max <- focal_extrem(a,"max",size=4,cover=0.5,verbose=1L) print(list(src=a,min=b.min,max=b.max,dif=b.max-b.min))
session_grid(NULL) a <- ursa_dummy(nband=2,mul=1/8,elements=32) a[a<80] <- NA b.min <- focal_extrem(a,"min",size=4,cover=0.5,verbose=1L) b.max <- focal_extrem(a,"max",size=4,cover=0.5,verbose=1L) print(list(src=a,min=b.min,max=b.max,dif=b.max-b.min))
Low-pass filtering by a square window in the image processing. Focal operation of map algebra. Weight of pixels is proportional to cell area inside of focal window.
focal_mean(x, size = 3.0, cover = 1e-06, fillNA = FALSE, saveMargin = TRUE ,noNA = TRUE, verbose = 0L)
focal_mean(x, size = 3.0, cover = 1e-06, fillNA = FALSE, saveMargin = TRUE ,noNA = TRUE, verbose = 0L)
x |
Object of class |
size |
Positive numeric. Size of square focal window. Fractional values are allowed. If |
cover |
Numeric. |
fillNA |
Logical. If |
saveMargin |
Logical. If |
noNA |
Logical. If |
verbose |
Integer of |
The reference is always central pixel, even if window size is even.
If size=3
then multiplicator is 3^(-2)
and elements have equal weights:
[,1] [,2] [,3] [1,] 1 1 1 [2,] 1 1 1 [3,] 1 1 1
If size=2
then multiplicator is 2^(-2)
and weights of elements are:
[,1] [,2] [,3] [1,] 0.25 0.50 0.25 [2,] 0.50 1.00 0.50 [3,] 0.25 0.50 0.25
If size=3.4
then multiplicator is 3.4^(-2)
and weights of elements are:
[,1] [,2] [,3] [,4] [,5] [1,] 0.04 0.20 0.20 0.20 0.04 [2,] 0.20 1.00 1.00 1.00 0.20 [3,] 0.20 1.00 1.00 1.00 0.20 [4,] 0.20 1.00 1.00 1.00 0.20 [5,] 0.04 0.20 0.20 0.20 0.04
Object of class ursaRaster
with the same number of bands as in input raster.
Nikita Platonov [email protected]
session_grid(NULL) a <- ursa_dummy(nband=1,mul=1/8,elements=0) a[a<80] <- NA print(a) b1 <- focal_mean(a,size=6,cover=0.5,saveMargin=FALSE) b2 <- focal_mean(a,size=6,cover=0.5,saveMargin=TRUE) b3 <- focal_mean(a,size=6,cover=0.5,saveMargin=TRUE,fillNA=TRUE) print(b3-a) display(c(a,b1,b2,b3),blank.angle=c(-45,45),blank.density=20)
session_grid(NULL) a <- ursa_dummy(nband=1,mul=1/8,elements=0) a[a<80] <- NA print(a) b1 <- focal_mean(a,size=6,cover=0.5,saveMargin=FALSE) b2 <- focal_mean(a,size=6,cover=0.5,saveMargin=TRUE) b3 <- focal_mean(a,size=6,cover=0.5,saveMargin=TRUE,fillNA=TRUE) print(b3-a) display(c(a,b1,b2,b3),blank.angle=c(-45,45),blank.density=20)
For each band and for each cell, function finds median value inside of square window. Focal operation of map algebra.
focal_median(x, size = 3, cover = 1e-06, fillNA = FALSE, saveMargin = TRUE, verbose = 0L)
focal_median(x, size = 3, cover = 1e-06, fillNA = FALSE, saveMargin = TRUE, verbose = 0L)
x |
Object of class |
size |
Positive numeric. Odd values (3, 5, 7, ...) are allowed, but if other value is specified, then it expanded to the next odd value not less than original value. Default is |
cover |
Numeric. |
fillNA |
Logical. If |
saveMargin |
Logical. If |
verbose |
Integer of |
Object of class ursaRaster
with the same number of bands as in input raster.
Nikita Platonov [email protected]
Other focal operations: focal_mean
, focal_extrem
.
session_grid(NULL) a <- ursa_dummy(1,mul=1/8,elements=0,bandname="src") a[a<80] <- NA bF <- c(fillNA.F=focal_median(a[1],size=5,cover=0.5,fillNA=FALSE)) bT <- c(fillNA.T=focal_median(a[1],size=5,cover=0.5,fillNA=TRUE)) print(c(diff=bT-bF)) d <- c(a,bF,bT) print(d) display(d)
session_grid(NULL) a <- ursa_dummy(1,mul=1/8,elements=0,bandname="src") a[a<80] <- NA bF <- c(fillNA.F=focal_median(a[1],size=5,cover=0.5,fillNA=FALSE)) bT <- c(fillNA.T=focal_median(a[1],size=5,cover=0.5,fillNA=TRUE)) print(c(diff=bT-bF)) d <- c(a,bF,bT) print(d) display(d)
For each band and for each cell, function calculates value using specific matrix of square window. Focal operation of map algebra.
focal_special(x, type = c("custom", "gaussian", "laplacian", "osisaf", "hires", "correl", "LoG", "sobel", "sobelG"), fmask = NULL, size = 3, alpha = 0.5, sigma = (size-1)/4, cover = 1 - 1e-06, fillNA = FALSE, saveMargin = FALSE, verbose = 0L)
focal_special(x, type = c("custom", "gaussian", "laplacian", "osisaf", "hires", "correl", "LoG", "sobel", "sobelG"), fmask = NULL, size = 3, alpha = 0.5, sigma = (size-1)/4, cover = 1 - 1e-06, fillNA = FALSE, saveMargin = FALSE, verbose = 0L)
x |
Object of class |
type |
Character, which is checked by |
fmask |
Numeric square matrix. Filter mask. If |
size |
Numeric. Diameter of circuled filter mask. Coerced to the nearest odd value not less than original value. |
alpha |
Nimeric. Parameter |
sigma |
Numeric. Parameter |
cover |
Numeric. |
fillNA |
Logical. If |
saveMargin |
Logical. If |
verbose |
Integer of |
Developed under impression from Matlab's "fspecial".
type="custom"
Filter mask (argument fmask
) should be specified manually.
type="gaussian"
Gaussian filter. For cascade filtering (sequence of increasing or decreasing window size
) sigma=(size-1)/4
produces the same distribution density relative to window size. If sigma
is high but not Inf
then it is low-pass filter with diameter=size
of circular focal window.
type="laplacian"
Laplacian filter. Only size=3
makes sence. Any size
is coerced to size=3
.
type="osisaf"
Filter for edge detection. Only size=5
makes sence. Any size
is coerced to size=5
. TODO (pl): reference
-0.0625 -0.0625 -0.0625 -0.0625 -0.0625 -0.0625 0.1250 0.1250 0.1250 -0.0625 -0.0625 0.1250 0.0000 0.1250 -0.0625 -0.0625 0.1250 0.1250 0.1250 -0.0625 -0.0625 -0.0625 -0.0625 -0.0625 -0.0625
type="hires"
Filter for unsharping. Only size=3
makes sence. Any size
is coerced to size=3
.
-alpha alpha-1 -alpha alpha-1 alpha+5 alpha-1 -alpha alpha-1 -alpha
type="correl"
Filter for contrast increasing. Only size=3
makes sence. Any size
is coerced to size=3
.
alpha^2 -alpha*(1+alpha^2) alpha^2 -alpha*(1+alpha^2) (1+alpha^2)^2 -alpha*(1+alpha^2) alpha^2 -alpha*(1+alpha^2) alpha^2
type="LoG"
Laplacian of Gaussian. Filter for edge detection. sigma
is used, alpha
is ignored.
type="sobel"
Two-directional Sobel filtering. Only size=3
makes sence. Any size
is coerced to size=3
.
type="sobelG"
Sobel gradient. Only size=3
makes sence. Any size
is coerced to size=3
.
Object of class ursaRaster
with the same number of bands as in input raster.
Laplacian of Gaussian filter (type="LoG"
) is not implemented clearly due to applying continuous-valued formula to discrete matrix.
Nikita Platonov [email protected]
TODO(pl): at least reference to 'osisaf'.
Other focal operations: focal_mean
, focal_median
, focal_extrem
.
session_grid(NULL) v <- round(runif(8,min=-1,max=1),3) customFilter <- matrix(c(v[1:4],-sum(v),v[5:8]),ncol=3) a <- ursa_dummy(1,mul=4/8,elements=32) tpList <- eval(formals("focal_special")$type) res <- c(src=a,as.ursa(bandname=tpList)) for (tp in tpList) { message(tp) res[tp] <- focal_special(a,tp,fmask=customFilter,size=11,sigma=1,alpha=0.8 ,saveMargin=0,verbose=2L) } print(res) display(res,decor=FALSE)
session_grid(NULL) v <- round(runif(8,min=-1,max=1),3) customFilter <- matrix(c(v[1:4],-sum(v),v[5:8]),ncol=3) a <- ursa_dummy(1,mul=4/8,elements=32) tpList <- eval(formals("focal_special")$type) res <- c(src=a,as.ursa(bandname=tpList)) for (tp in tpList) { message(tp) res[tp] <- focal_special(a,tp,fmask=customFilter,size=11,sigma=1,alpha=0.8 ,saveMargin=0,verbose=2L) } print(res) display(res,decor=FALSE)
get_earthdata
allows retrieving georeferences optical satellite images of low and moderate spatial resolution (up to 250m per cell) using GIBS API for Developers.
get_earthdata(bbox = NA, res = c("2km", "1km", "500m", "250m"), date = NA, product = "", geocode = "", expand = 1.05, border = 0, display = FALSE, cache = NA, verbose = FALSE)
get_earthdata(bbox = NA, res = c("2km", "1km", "500m", "250m"), date = NA, product = "", geocode = "", expand = 1.05, border = 0, display = FALSE, cache = NA, verbose = FALSE)
bbox |
Numeric of length 4 or character. Spatial extent in the notation |
res |
Character or numeric. Parameter, which is responsible for dimension of output raster image. If character, then zoom is selected using keyword list |
date |
Character or |
product |
Character of integer. Data product form GIBS. Currently only MODIS-oriented (corrected reflectance) products are available:
Please check actual list by calling If numeric, then index of item among available products. Regular expressions can be used to simplify value of product, e.g., case-insensitive "aqua 721", "terra truecolor", "suomi", "SNNP". |
geocode |
Character. Keyword for geocode service. Valid values are |
expand |
Numeric. Multiplier for plotting panel zoom in relation to extent of plotting geometry. Ignored if geocoding is not applied. Default is |
border |
Integer. Value in pixels of fixed margins around plotting geometry. Ignored if geocoding is not applied. Default is |
display |
Logical. Value |
cache |
Logical. Is cache used? Default is |
verbose |
Logical. Value |
Argument method="libcurl"
is used in function download.file
for tile downloading. Please check capabilities("libcurl")
.
Valid zoom values (e. g., specified via res
argument) are 3:6 for EPSG:3413 and 0:8 for EPSG:3587.
Longitude 180 degrees has a seam in EPSG:3857 (e.g., see bbox=c(170,68,-170,73)
and bbox=c(-1600000,1308000,-1370000,1570000)
for Wrangel Island. If region crosses longitude 180 degrees in EPSG:3857, then the prior day is taken for Western Hemisphere.
If bbox=NULL
, then character vector of available products.
If display=FALSE
then object of class ursaRaster
with RGBA image.
If display=TRUE
then returned value of display_brick
.
Nikita Platonov [email protected]
session_grid(NULL) pr <- get_earthdata() print(pr,quote=FALSE) ## internet connection is required -- begin a1 <- get_earthdata(bbox=c(2000000,400000,2300000,700000)) display(a1) ## internet connection is required -- end a2 <- get_earthdata(product=2 # ,date=Sys.Date()-7L ## empty tiles for winter polar regions ,date=as.Date(format(Sys.Date()-365L,"%Y-06-15")) ,res=7,bbox=c(57.8,69.4,62.3,70.8)) display(a2)
session_grid(NULL) pr <- get_earthdata() print(pr,quote=FALSE) ## internet connection is required -- begin a1 <- get_earthdata(bbox=c(2000000,400000,2300000,700000)) display(a1) ## internet connection is required -- end a2 <- get_earthdata(product=2 # ,date=Sys.Date()-7L ## empty tiles for winter polar regions ,date=as.Date(format(Sys.Date()-365L,"%Y-06-15")) ,res=7,bbox=c(57.8,69.4,62.3,70.8)) display(a2)
glance
is a parser of command line arguments for non-public function .glance
, which creates multi-panel plots for each attribute of vector file or for each band of raster file.
glance(...) # non-public .glance(dsn, layer = ".*", grid = NULL, field = ".+", size = NA, expand = 1, border = 27, lat0 = NA, lon0 = NA, resetProj = FALSE, resetGrid = FALSE, style = "auto", feature = c("auto", "field", "geometry"), alpha = NA, basemap.order = c("after", "before"), basemap.alpha = NA, engine = c("native", "sp", "sf"), geocode = "", place="", area = c("bounding", "point", "shape"), zoom = NA, gdal_rasterize = FALSE, silent = FALSE, verbose = FALSE, ...)
glance(...) # non-public .glance(dsn, layer = ".*", grid = NULL, field = ".+", size = NA, expand = 1, border = 27, lat0 = NA, lon0 = NA, resetProj = FALSE, resetGrid = FALSE, style = "auto", feature = c("auto", "field", "geometry"), alpha = NA, basemap.order = c("after", "before"), basemap.alpha = NA, engine = c("native", "sp", "sf"), geocode = "", place="", area = c("bounding", "point", "shape"), zoom = NA, gdal_rasterize = FALSE, silent = FALSE, verbose = FALSE, ...)
dsn |
Character or object of either |
layer |
Character or integer. If integer, then layer index. If character, then pattern (regular expressions) to recognize layer by name. Only one layer selection is allowed. If selected more then one layer, the error message contains indices and names of layers. Usually, datasets (e. g., "ESRI Shapefile") have only one layer. Default is |
grid |
Object of class |
field |
Character. Pattern for field (attribute, column,...) selection by name using regular expressions. Multiple selection is allowed. Default is |
size |
Integer of length 1 or 2 or character of length 1. Size of plotting panel in pixels. If character, then parsed to integer of length 1 or 2. Length 2 is used only for web cartography. If length 1, then |
expand |
Numeric. Multiplier for plotting panel zoom in relation to extent of plotting geometry. Default is |
border |
Integer. Value in pixels of fixed margins around plotting geometry. Default is |
lat0 |
Numeric. Parallel os zero distortion. If |
lon0 |
Numeric. Central meridian, which have vertical direction on the plot. If |
resetProj |
Logical. Value |
resetGrid |
Logical. If |
style |
Character. Either projection class or source of web-catrogrpaphy for basemap. Specified by a sentence of words separated by spaces.
Keywords |
feature |
Character. Appearance of visualization. If |
basemap.order |
Character. The order of basemap layer rendering in the case of web-cartography basemap.If |
basemap.alpha |
Character. The saturation of basemap in the case of web-cartography basemap. Default is |
alpha |
Character. The opacity of plotted object. Default is |
engine |
Character keyword. Forcing to vector files processing by functions from package sp ( |
geocode |
Character. Keyword for geocode service. Valid values are |
place |
Character. Type of geographical object (river, island) in the geocoding request. If |
area |
Character. Keyword of spatial class of geocoded object. |
zoom |
Positive integer or character. Zooming if web-cartography is applied for basemap. If integer, then value of zoom for tile services and staticmap. If character, then |
gdal_rasterize |
Logical. If |
silent |
Logical. Value |
verbose |
Logical. Logical. Value |
... |
|
Command line usage implies set of arguments using pair: argument name
and argument value
. and values in the format "[name1=]value1 [name2]=value2
". No spaces around =
(equal symbol). Argument name
can be omitted, symbol =
is omitted too. If argument value
has spaces, then argument value should be surrounded by double quotes (fname="my test.shp"
). If argument value
is matched to R function, then such value should be surrounded by single quotes (layer='density'
).
Command line usage example: Rscript -e ursa::glance() 'final_more_than_032.sqlite' attr="select" resetProj=TRUE expand=1.5
For OS Windows, bat-file can be created for raster and vector file association:
Rscript -e ursa::glance() %*
Command line usage implies external software for PNG view session_pngviewer(TRUE)
.
glance
returns integer: 0L
- successful, 10L
- call without arguments.
Package sp is 'Suggested' for package ursa.
Nikita Platonov [email protected]
session_grid(NULL) f <- system.file("shape/nc.shp",package="sf") glance(f,style="merc",field="(NAME|AREA|COUNT)") cmd <- paste("Rscript --vanilla -e ursa::glance()",paste0("\"",f,"\"") ,"style=\"merc\"","field=\"(lon|lat)\"") cat(" --------- Try in command line: -----------\n") message(cmd) cat(" ----------- end of quoting ---------------\n") ## windows: figure will be opened using *.png file association try(system(cmd,wait=FALSE)) a <- data.frame(lat=c(70.734,71.657),lon=c(178.577,-177.38),place="Wrangel Island") if (requireNamespace("sp")) { sp::coordinates(a) <- ~lon+lat sp::proj4string(a) <- "EPSG:4326" } else { a <- sf::st_as_sf(a,coords=c("lon","lat"),crs=4326) } ## internet connection is required glance(a,style="google color maptype=terrain") ## internet connection is required glance(a,style="Positron",border=0) ## internet connection is required glance(a,style="opentopomap grey",border=0) ## internet connection is required glance("Svalbard",resetGrid=TRUE)
session_grid(NULL) f <- system.file("shape/nc.shp",package="sf") glance(f,style="merc",field="(NAME|AREA|COUNT)") cmd <- paste("Rscript --vanilla -e ursa::glance()",paste0("\"",f,"\"") ,"style=\"merc\"","field=\"(lon|lat)\"") cat(" --------- Try in command line: -----------\n") message(cmd) cat(" ----------- end of quoting ---------------\n") ## windows: figure will be opened using *.png file association try(system(cmd,wait=FALSE)) a <- data.frame(lat=c(70.734,71.657),lon=c(178.577,-177.38),place="Wrangel Island") if (requireNamespace("sp")) { sp::coordinates(a) <- ~lon+lat sp::proj4string(a) <- "EPSG:4326" } else { a <- sf::st_as_sf(a,coords=c("lon","lat"),crs=4326) } ## internet connection is required glance(a,style="google color maptype=terrain") ## internet connection is required glance(a,style="Positron",border=0) ## internet connection is required glance(a,style="opentopomap grey",border=0) ## internet connection is required glance("Svalbard",resetGrid=TRUE)
Function from this global.
FUN
list returns required statistics FUN for the whole image.
global_mean(x, ursa = FALSE, ...) global_median(x, ursa = FALSE, ...) global_sd(x, ursa = FALSE, ...) global_sum(x, ursa = FALSE, ...) global_min(x, ursa = FALSE, ...) global_max(x, ursa = FALSE, ...) global_n(x, ursa = FALSE, ...) global_nNA(x, ursa = FALSE, ...) global_range(x, ursa = FALSE, ...) global_quantile(x, ursa = FALSE, ...)
global_mean(x, ursa = FALSE, ...) global_median(x, ursa = FALSE, ...) global_sd(x, ursa = FALSE, ...) global_sum(x, ursa = FALSE, ...) global_min(x, ursa = FALSE, ...) global_max(x, ursa = FALSE, ...) global_n(x, ursa = FALSE, ...) global_nNA(x, ursa = FALSE, ...) global_range(x, ursa = FALSE, ...) global_quantile(x, ursa = FALSE, ...)
x |
Object of class |
ursa |
Logical. The class of returned value. If |
... |
Arguments in function |
For any function global
.FUN
, if argument na.rm
is not in ...
, then FUN
is called with forced na.rm=TRUE
.
global_range\emph{list of arguments}
is implemented as c(global_min(
list of arguments
), global_max(
list of arguments
))
with the same list of arguments.
Alternative method to get global statistics is function applying directly to the raster value. For example, sd(ursa_value(x,na.rm=TRUE))
. This way is also appropriate for missing global functions: for example, var(ursa_value(x,na.rm=TRUE))
.
If ursa=FALSE
then numeric
.
If ursa=TRUE
then object of class ursaRaster
.
Nikita Platonov [email protected]
session_grid(NULL) a <- ursa_dummy(2,min=-40,max=80) a[a<0] <- NA print(a) a.mean <- global_mean(a) a.sd <- global_sd(a) a.sum <- global_sum(a) a.min <- global_min(a) a.max <- global_max(a) a.median <- global_median(a) print(c(mean=a.mean,sd=a.sd,sum=a.sum,min=a.min,max=a.max,median=a.median)) v.max <- max(ursa_value(a),na.rm=TRUE) print(c('global_max()'=a.max,'max(ursa_value())'=v.max,dif=a.max-v.max)) r.max <- global_max(a,ursa=TRUE) print(r.max) b <- c(a,'appended scalar value'=a.max) print(b) print(global_quantile(a))
session_grid(NULL) a <- ursa_dummy(2,min=-40,max=80) a[a<0] <- NA print(a) a.mean <- global_mean(a) a.sd <- global_sd(a) a.sum <- global_sum(a) a.min <- global_min(a) a.max <- global_max(a) a.median <- global_median(a) print(c(mean=a.mean,sd=a.sd,sum=a.sum,min=a.min,max=a.max,median=a.median)) v.max <- max(ursa_value(a),na.rm=TRUE) print(c('global_max()'=a.max,'max(ursa_value())'=v.max,dif=a.max-v.max)) r.max <- global_max(a,ursa=TRUE) print(r.max) b <- c(a,'appended scalar value'=a.max) print(b) print(global_quantile(a))
These functions implement arithmetical and logical operations, mathematical functions for objects of class ursaRaster
as well as group generic functions from package base do similar for S3 class. These are local operations in the raster algebra (map algebra).
## S3 method for class 'ursaRaster' Ops(e1, e2 = NULL) ## S3 method for class 'ursaRaster' Math(x, ...) ## S3 method for class 'ursaRaster' Complex(z) ## S3 method for class 'ursaRaster' Summary(..., na.rm = FALSE)
## S3 method for class 'ursaRaster' Ops(e1, e2 = NULL) ## S3 method for class 'ursaRaster' Math(x, ...) ## S3 method for class 'ursaRaster' Complex(z) ## S3 method for class 'ursaRaster' Summary(..., na.rm = FALSE)
x |
|
e1 |
|
e2 |
Numeric of length 1, matrix, array, or |
na.rm |
Logical. If |
z |
Any. |
... |
For group Math - further arguments passed to methods. See description for generic. For group Summary - set of arguments, which are recognized via their names (using regular expressions), position and classes.
|
The groups are 'Summary'
, 'Ops'
, 'Math'
, and 'Complex
'. See “Details” section in the S3 Generic Functions help page.
The group 'Complex'
is unsupported.
The groups 'Math'
and 'Summary'
are implemented completely.
The group 'Ops'
has some features.
Logical operators "<"
, ">"
, "<="
, ">="
, "=="
, \"!="
return 'NA'
for value FALSE
and '1'
for value TRUE
to organize cells' masking.
Unary operator "!"
is equal to binary operator operators "!="
, where the second argument is scalar value 0
(zero).
The operators of groups 'Math'
and 'Ops'
destroy color tables.
For group 'Summary'
the realization of local operators of map algebra is possible via apply
function:apply(ursa_value(obj),1,function(x) {y <- sd(x)+1;y})
oras.ursa(apply(obj,1:2,function(x) {y <- sd(x)+1;y}))
Operators of groups 'Complex'
return stop
Operators of groups 'Math'
, 'Ops'
, 'Summary'
return object of class ursaRaster
Nikita Platonov [email protected]
Other S3 generic function for local operations of map algebra are mean
, median
.
Standard deviation (local) and certain local operations can be extracted using local_stat
.
session_grid(NULL) session_grid(regrid(mul=1/4)) a1 <- ursa_dummy(nband=3,min=-5*pi,max=5*pi) print(a1) try(print(complex1 <- Re(a1))) print(math1 <- a2 <- round(a1)) print(math1 <- sin(a1)) print(math2 <- floor(a1)) print(math3 <- ceiling(a1)) print(math4 <- cumsum(a1)) ## does this have a sense for rasters? print(ops1 <- a1-2*rev(a1)+mean(a1)) print(mean(ops1)) ## vanishing a2 <- ursa_new(value=c(1,2,4),bandname=c("single","double","quadruple")) print(a2) print(ops2 <- a2[1]==a2[2]) print(ops3 <- a2[1]==a2[2]/2) print(ops4 <- a1>0) print(a1[a1>0]) print(sum1 <- sum(a1)) print(sum2 <- range(a1))
session_grid(NULL) session_grid(regrid(mul=1/4)) a1 <- ursa_dummy(nband=3,min=-5*pi,max=5*pi) print(a1) try(print(complex1 <- Re(a1))) print(math1 <- a2 <- round(a1)) print(math1 <- sin(a1)) print(math2 <- floor(a1)) print(math3 <- ceiling(a1)) print(math4 <- cumsum(a1)) ## does this have a sense for rasters? print(ops1 <- a1-2*rev(a1)+mean(a1)) print(mean(ops1)) ## vanishing a2 <- ursa_new(value=c(1,2,4),bandname=c("single","double","quadruple")) print(a2) print(ops2 <- a2[1]==a2[2]) print(ops3 <- a2[1]==a2[2]/2) print(ops4 <- a1>0) print(a1[a1>0]) print(sum1 <- sum(a1)) print(sum2 <- range(a1))
Functions to extract first bands (head
), last bands (tail
) and first+last bands (series
) of raster image.
## S3 method for class 'ursaRaster' head(x, n = 3L, ...) ## S3 method for class 'ursaRaster' tail(x, n = 3L, ...) series(x, n = 3L, s=170, ...)
## S3 method for class 'ursaRaster' head(x, n = 3L, ...) ## S3 method for class 'ursaRaster' tail(x, n = 3L, ...) series(x, n = 3L, s=170, ...)
x |
Object of class |
n |
Positive integer. Number of extracted bands. |
s |
Positive numeric. Maximal size of memory in MB for extracted raster image in the assumption that class of values is |
... |
Not used. |
Function series
combines consequtive calling head(x); tail(x)
with checking the size of extracted part of raster image. If size exceeds specified value of the argument s
, then number of extracted bands n
is decreased.
Object of class ursaRaster
Nikita Platonov [email protected]
session_grid(NULL) session_grid(regrid(mul=1/8)) a <- ursa_dummy(nband=101) print(head(a)) print(tail(a)) print(series(a,2)) print(series(a[1:5]))
session_grid(NULL) session_grid(regrid(mul=1/8)) a <- ursa_dummy(nband=101) print(head(a)) print(tail(a)) print(series(a,2)) print(series(a[1:5]))
Two functions for manipulation with histograms. In function hist
values of ursaRaster
objects are passed to generic function hist
, which allows compute and optionally plot histograms. Other function, histogram
, plots histogram in the graphical device png
directly.
## S3 method for class 'ursaRaster' hist(x, ...) ursa_hist(obj, width = 800, height = 600, ...) histogram(...)
## S3 method for class 'ursaRaster' hist(x, ...) ursa_hist(obj, width = 800, height = 600, ...) histogram(...)
obj , x
|
Object of class |
width |
Positive integer. Width of histogram's panel. |
height |
Positive integer. Height of histogram's panel. |
... |
Other arguments, which are passed to |
histogram
is synonym of ursa_hist
.
Function hist
for ursaRaster
object is defined as hist(ursa_value(obj),...)
.
In the function histogram
each bin corresponds to category. The image splitting to categories is realized via colorize
function. The panel of plotting is constucted using artificial coordinate system without geographical projection. The purpose of compose_open
function is prepare layout for plotting raster images; in the case of histogram, the purpose of this function is prepare layout for plotting histogram
Function histogram
returns 0L
.
Nikita Platonov [email protected]
colorize
is used to define histogram bins.
compose_open
prepares panel for histogram plotting.
hist
computes and plots histograms.
session_grid(NULL) a <- pixelsize() hist(a) histogram(a,breaks=21)
session_grid(NULL) a <- pixelsize() hist(a) histogram(a,breaks=21)
Functions to extract values of raster image from given location, specified by coordinates in raster projection, by cell position or by geogpaphical coordinates. Additional utils to convert cell position and planar coordinates mutually.
value_xy(obj, ...) value_ll(obj, ...) value_cr(obj, ...) coord_xy(obj, ...) coord_cr(obj, ...)
value_xy(obj, ...) value_ll(obj, ...) value_cr(obj, ...) coord_xy(obj, ...) coord_cr(obj, ...)
obj |
Object of class |
||||||||||||||||||||||||||||||||
... |
the set of arguments, which are recognized via their names (using regular expressions) and classes:
|
value_xy
returns values for location, which is specified by planar coordinates (x, y).value_cr
returns values for location, which is specified by cell posisition (column, row) relative to upper-left corner of image .value_ll
returns values for location, which is specified by longitude and latitude (long, lat).
coord_xy
transforms planar coordinates (x, y) to cell position (column, row).coord_cr
transforms cell position (column, row) to planar coordinates (x, y).
It is required to use a couple of coordinate vectors: (x, y)
, (c, r)
or (lon, lat)
of the same length. The unary argument is interpreted as index in internal value storage.
Position in column/row coordinates starts from upper-lever corner. The cell of upper-level corner has (1, 1) coordinates (in R indices starts from 1L
), whereas in some GIS the same corner cell has (0, 0) coordinates.
The column names of returned matrix are character format of index in internal value storage. This index can be specify in any function as argument ind
instead of coordinates (planar, geographical, cell position).
For value.*
numeric matrix of raster values. Band values for specific coordinates are by column. Set of specific coordinates are by row. rownames
are band names, and colnames
are index in internal value storage.
For coord.*
numeric matrix of coordinates with a vector of couple coordinates, one coordinate per one row. rownames
are returned coordinates, and colnames
are index in internal value storage.
Nikita Platonov [email protected]
session_grid(NULL) set.seed(352) a <- as.integer(ursa_dummy(3,min=0,max=999)) ind <- which(ursa_value(a[1])==890) print(ind) msk <- a[1]==890 am <- a[msk] b <- as.data.frame(am) b$jx <- b$x+runif(nrow(b),min=-1000,max=1000) b$jy <- b$y+runif(nrow(b),min=-1000,max=1000) print(b) cr1 <- coord_xy(a,x=b$jx,y=b$jy) cr2 <- coord_xy(a,y=b$y,x=b$x) cr3 <- coord_xy(a,ind=ind) print(cr1) print(list('cr1 and cr2'=all.equal(cr1,cr2) ,'cr2 and cr3'=all.equal(cr2,cr3) ,'cr3 and cr1'=all.equal(cr3,cr1))) xy1 <- coord_cr(a,c=cr1["c",],r=cr1["r",]) print(xy1) print(list('in x'=identical(unname(xy1["x",]),b[,"x",drop=TRUE]) ,'in y'=identical(unname(xy1["y",]),b[,"y",drop=TRUE]))) val1 <- value_xy(a,x=b$jx,y=b$jy) val2 <- value_xy(a,x=b$x,y=b$y) val3 <- value_cr(a,ind=ind) val4 <- value_cr(a,c=cr1["c",],r=cr1["r",]) print(val1) print(list('val1 and val2'=all.equal(val1,val2) ,'val2 and val3'=all.equal(val2,val3) ,'val3 and val4'=all.equal(val3,val4) ,'val4 and val1'=all.equal(val4,val1))) ps <- pixelsize() v <- value_ll(ps,lon=180,lat=70) print(c('True scale'=v/with(ursa_grid(ps),1e-6*resx*resy)))
session_grid(NULL) set.seed(352) a <- as.integer(ursa_dummy(3,min=0,max=999)) ind <- which(ursa_value(a[1])==890) print(ind) msk <- a[1]==890 am <- a[msk] b <- as.data.frame(am) b$jx <- b$x+runif(nrow(b),min=-1000,max=1000) b$jy <- b$y+runif(nrow(b),min=-1000,max=1000) print(b) cr1 <- coord_xy(a,x=b$jx,y=b$jy) cr2 <- coord_xy(a,y=b$y,x=b$x) cr3 <- coord_xy(a,ind=ind) print(cr1) print(list('cr1 and cr2'=all.equal(cr1,cr2) ,'cr2 and cr3'=all.equal(cr2,cr3) ,'cr3 and cr1'=all.equal(cr3,cr1))) xy1 <- coord_cr(a,c=cr1["c",],r=cr1["r",]) print(xy1) print(list('in x'=identical(unname(xy1["x",]),b[,"x",drop=TRUE]) ,'in y'=identical(unname(xy1["y",]),b[,"y",drop=TRUE]))) val1 <- value_xy(a,x=b$jx,y=b$jy) val2 <- value_xy(a,x=b$x,y=b$y) val3 <- value_cr(a,ind=ind) val4 <- value_cr(a,c=cr1["c",],r=cr1["r",]) print(val1) print(list('val1 and val2'=all.equal(val1,val2) ,'val2 and val3'=all.equal(val2,val3) ,'val3 and val4'=all.equal(val3,val4) ,'val4 and val1'=all.equal(val4,val1))) ps <- pixelsize() v <- value_ll(ps,lon=180,lat=70) print(c('True scale'=v/with(ursa_grid(ps),1e-6*resx*resy)))
Ignored values (aka 'nodata') are implemented via NA
values, and are optional for raster images in memory. However, to avoid ambiguity for data storage, it is desirable to specify ignored value. “ENVI .hdr Labelled Raster” supports ‘nodata’ by means of “data ignore value” field in the header file.
ignorevalue(obj) ursa_nodata(obj) ignorevalue(obj) <- value ursa_nodata(obj) <- value
ignorevalue(obj) ursa_nodata(obj) ignorevalue(obj) <- value ursa_nodata(obj) <- value
obj |
|
value |
Integer of numeric of length one. Ignored (‘nodata’) value. |
ursa_nodata
is synonym to ignorevalue
for both Extract and Replace methods.
The ‘nodata’ value of raster image obj
is specified in the item obj$con$nodata
.
If values of raster image are in memory then replace function ignorevalue<-
also changes ‘nodata’ values to NA
values.
Extract function ignorevalue
returns value of $con$nodata
item of ursaRaster
object.
Replace function ignorevalue<-
returns ursaRaster
with modified $con$nodata
item.
Nikita Platonov [email protected]
session_grid(NULL) a <- round(ursa_dummy(nband=1,min=0.500001,max=4.499999)) print(a) print(as.table(a)) print(ignorevalue(a)) ignorevalue(a) <- NA print(as.table(a)) print(ignorevalue(a)) ignorevalue(a) <- 4 print(as.table(a)) print(ignorevalue(a)) print(a)
session_grid(NULL) a <- round(ursa_dummy(nband=1,min=0.500001,max=4.499999)) print(a) print(as.table(a)) print(ignorevalue(a)) ignorevalue(a) <- NA print(as.table(a)) print(ignorevalue(a)) ignorevalue(a) <- 4 print(as.table(a)) print(ignorevalue(a)) print(a)
The "Extract" function is.na
creates mask for each band. In this mask value 1L
corresponds to NA
value in the source image, and value NA
corresponds non-missing values in the source image. The "Replacement" function is.na<-
assigns numerical value for cells with ‘no data’ value.
## S3 method for class 'ursaRaster' is.na(x) ## S3 method for class 'ursaRaster' is.infinite(x) ## S3 method for class 'ursaRaster' is.nan(x) ## S3 replacement method for class 'ursaRaster' is.na(x) <- value
## S3 method for class 'ursaRaster' is.na(x) ## S3 method for class 'ursaRaster' is.infinite(x) ## S3 method for class 'ursaRaster' is.nan(x) ## S3 replacement method for class 'ursaRaster' is.na(x) <- value
x |
Object of class |
value |
Numeric. |
These functions are corresponded to local operators of map algebra.
"Extract" functions is.na
, is.infinite
, is.nan
return object of class ursaRaster
.
"Replacement" function is.na<-
modifies object of class ursaRaster
.
Nikita Platonov [email protected]
session_grid(NULL) session_grid(regrid(mul=1/4)) a <- ursa_dummy(nband=2,min=0,max=100) print(a) print(is.na(a)) a2 <- ursa_new(nband=2) print(a2) print(is.na(a2)) a3 <- a a3[a3<30 | a3>70] <- NA print(a3) print(is.na(a3)) is.na(a3) <- 200 print(a3)
session_grid(NULL) session_grid(regrid(mul=1/4)) a <- ursa_dummy(nband=2,min=0,max=100) print(a) print(is.na(a)) a2 <- ursa_new(nband=2) print(a2) print(is.na(a2)) a3 <- a a3[a3<30 | a3>70] <- NA print(a3) print(is.na(a3)) is.na(a3) <- 200 print(a3)
When multiple panels on the same axis, the different order of values or different units of values may provoke different shifting of values and caption from panels. legend_align
repairs it by the taking names of classes of the required rasters. The function output is for argument aling
of legend_colorbar
.
legend_align(obj)
legend_align(obj)
obj |
Object of class |
The function is defined as:
c(unlist(sapply(obj,function(x) names(ursa_colortable(x)))))
Character vector.
Nikita Platonov [email protected]
session_grid(NULL) a <- ursa_dummy(5,mul=1/4,min=-150,max=200) a[1] <- a[1]*100 a[2] <- -a[2]*10 a[3] <- a[3]/10 a[4] <- a[4]/1000 b <- lapply(a,colorize) la.top <- legend_align(b[c(1,2)]) la.left <- legend_align(c(b[[1]],b[[3]])) la.bottom <- legend_align(b[c(3,4)]) la.right <- legend_align(b[c(2,4)]) leg <- vector("list",12) leg[[1]] <- list("top",2) leg[[2]] <- list("top",3) leg[[3]] <- list("bottom",1) leg[[4]] <- list("bottom",2) leg[[5]] <- list(2,"left") leg[[6]] <- list(1,"right") leg[[7]] <- list(3,"left") leg[[8]] <- list(2,"right") leg[[9]] <- list("top",1) leg[[10]] <- list("bottom",3) leg[[11]] <- list(1,"left") leg[[12]] <- list(3,"right") cl <- compose_design(layout=c(3,3),legend=leg,byrow=TRUE,skip=5) print(cl) compose_open(cl) ct <- compose_panel(b[c(5,1,2,1,4,3,4,5)],decor=FALSE) L <- 2 Tr <- 2 legend_colorbar(b[1],trim=Tr,las=L,align=la.top,units="top aligned --->") legend_colorbar(b[2],trim=Tr,las=L,align=la.top,units="<--- top aligned") legend_colorbar(b[3],trim=Tr,las=L,align=la.bottom,units="bottom aligned --->") legend_colorbar(b[4],trim=Tr,las=L,align=la.bottom,units="<--- bottom aligned") legend_colorbar(b[1],trim=Tr,las=L,align=la.left,units="<--- left aligned") legend_colorbar(b[2],trim=Tr,las=L,align=la.right,units="<--- right aligned") legend_colorbar(b[3],trim=Tr,las=L,align=la.left,units="left aligned --->") legend_colorbar(b[4],trim=Tr,las=L,align=la.right,units="right aligned --->") legend_colorbar(b[5],trim=Tr,las=L,units=" *** not aligned ***") legend_colorbar(b[5],trim=Tr,las=L,units=" *** not aligned ***") legend_colorbar(b[5],trim=Tr,las=L,units=" *** not aligned ***") legend_colorbar(b[5],trim=Tr,las=L,units=" *** not aligned ***") compose_close()
session_grid(NULL) a <- ursa_dummy(5,mul=1/4,min=-150,max=200) a[1] <- a[1]*100 a[2] <- -a[2]*10 a[3] <- a[3]/10 a[4] <- a[4]/1000 b <- lapply(a,colorize) la.top <- legend_align(b[c(1,2)]) la.left <- legend_align(c(b[[1]],b[[3]])) la.bottom <- legend_align(b[c(3,4)]) la.right <- legend_align(b[c(2,4)]) leg <- vector("list",12) leg[[1]] <- list("top",2) leg[[2]] <- list("top",3) leg[[3]] <- list("bottom",1) leg[[4]] <- list("bottom",2) leg[[5]] <- list(2,"left") leg[[6]] <- list(1,"right") leg[[7]] <- list(3,"left") leg[[8]] <- list(2,"right") leg[[9]] <- list("top",1) leg[[10]] <- list("bottom",3) leg[[11]] <- list(1,"left") leg[[12]] <- list(3,"right") cl <- compose_design(layout=c(3,3),legend=leg,byrow=TRUE,skip=5) print(cl) compose_open(cl) ct <- compose_panel(b[c(5,1,2,1,4,3,4,5)],decor=FALSE) L <- 2 Tr <- 2 legend_colorbar(b[1],trim=Tr,las=L,align=la.top,units="top aligned --->") legend_colorbar(b[2],trim=Tr,las=L,align=la.top,units="<--- top aligned") legend_colorbar(b[3],trim=Tr,las=L,align=la.bottom,units="bottom aligned --->") legend_colorbar(b[4],trim=Tr,las=L,align=la.bottom,units="<--- bottom aligned") legend_colorbar(b[1],trim=Tr,las=L,align=la.left,units="<--- left aligned") legend_colorbar(b[2],trim=Tr,las=L,align=la.right,units="<--- right aligned") legend_colorbar(b[3],trim=Tr,las=L,align=la.left,units="left aligned --->") legend_colorbar(b[4],trim=Tr,las=L,align=la.right,units="right aligned --->") legend_colorbar(b[5],trim=Tr,las=L,units=" *** not aligned ***") legend_colorbar(b[5],trim=Tr,las=L,units=" *** not aligned ***") legend_colorbar(b[5],trim=Tr,las=L,units=" *** not aligned ***") legend_colorbar(b[5],trim=Tr,las=L,units=" *** not aligned ***") compose_close()
Functions draw single color bar outside of maps panels. legend_colorbar
(without prefix dot) is a wrapper for non-public .legend_colorbar
(with prefix dot)
legend_colorbar(...) ## non-public .legend_colorbar(ct, units = "", labels = NA, align = NULL, shift = 1, cex = 1, adj = NA, las = 1, forceLabel = FALSE, lomar = 0, himar = 0, turn = FALSE, useRaster = NA, trim = 0L, abbrev = 24L, opacity = NA, verbose = FALSE)
legend_colorbar(...) ## non-public .legend_colorbar(ct, units = "", labels = NA, align = NULL, shift = 1, cex = 1, adj = NA, las = 1, forceLabel = FALSE, lomar = 0, himar = 0, turn = FALSE, useRaster = NA, trim = 0L, abbrev = 24L, opacity = NA, verbose = FALSE)
... |
Set of arguments, which are recognized via their names (using regular expressions) and classes. Passed to non-public
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ct |
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
units |
Argument of class |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
labels |
Argument of class |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
align |
Argument of class |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
shift |
Argument of class |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
cex |
Argument of class |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
adj |
Argument of class |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
las |
Argument of values |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
forceLabel |
Argument of class |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
lomar |
Argument of class |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
himar |
Argument of class |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
turn |
Argument of class |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
useRaster |
Argument of class |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
trim |
Argument of values |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
abbrev |
Argument of class |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
opacity |
Argument of class |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||
verbose |
Argument of class |
If units
are expression
, then possible way for formatting is:
units=as.expression(substitute(bold(degree*C)))
NULL
Nikita Platonov [email protected]
session_grid(NULL) display(ursa_dummy(1),units="Required 99 labels; displayed less" ,colorbar.labels=99,las=3,gridline.trim=FALSE,colorbar.trim=1L) cname <- c("Apple","Orange","Cherry","Blueberry","Strawberry","Currant") a <- ursa_dummy(4) b <- list(colorize(a[1],value=seq(50,200,length=length(cname)) ,name=cname)#,stretch="category") ,colorize(a[2]*10,ramp=FALSE),colorize(a[3]*100),colorize(a[4]/10)) la <- legend_align(b[3:4]) leg <- vector("list",10) leg[[1]] <- list(1,"left") leg[[2]] <- list(1,"right") for (i in seq(4)) { leg[[i+2]] <- list("top",i) leg[[i+6]] <- list("bottom",i) } compose_open(layout=c(1,4),legend=leg,scale=NA,dev=FALSE) # use 'dev=TRUE' to check layout compose_panel(b) legend_colorbar(b[[1]],lomar=20,himar=0) ## "left" legend_colorbar(b[[4]],labels=c(6,7.5,12,15,20) ,units="Manual set of labels") ## "right" legend_colorbar(b[[1]],las=2,adj=0.5,turn=TRUE,lomar=6,himar=6 ,units="Central adjustment; inverse order") ## ("top",1) legend_colorbar(b[[2]],cex=0.9 ,units="Horizontal labels can be overlapped") ## ("top",2) legend_colorbar(b[[3]],las=3,align=la ,units="Increased width, but aligned -->") ## ("top",3) legend_colorbar(b[[4]],las=3,align=la,labels=3 ,units="<-- Reduced width, but aligned") ## ("top",4) legend_colorbar(b[[1]],las=2,adj=0,shift=0.9,turn=FALSE,lomar=2,himar=10 ,units="Left adjustement. Non-optimal; shifted") ## ("bottom",1) legend_colorbar(b[[2]],las=3,adj=0 ,units="But right adj. is default for numeric") ## ("bottom",2) legend_colorbar(b[[3]],labels=99,las=3,trim=2L ,units="Required 99 labels, but displayed less") ## ("bottom",3) legend_colorbar('Caption from named item'=b[[4]],labels=99) ## ("bottom",4) compose_close()
session_grid(NULL) display(ursa_dummy(1),units="Required 99 labels; displayed less" ,colorbar.labels=99,las=3,gridline.trim=FALSE,colorbar.trim=1L) cname <- c("Apple","Orange","Cherry","Blueberry","Strawberry","Currant") a <- ursa_dummy(4) b <- list(colorize(a[1],value=seq(50,200,length=length(cname)) ,name=cname)#,stretch="category") ,colorize(a[2]*10,ramp=FALSE),colorize(a[3]*100),colorize(a[4]/10)) la <- legend_align(b[3:4]) leg <- vector("list",10) leg[[1]] <- list(1,"left") leg[[2]] <- list(1,"right") for (i in seq(4)) { leg[[i+2]] <- list("top",i) leg[[i+6]] <- list("bottom",i) } compose_open(layout=c(1,4),legend=leg,scale=NA,dev=FALSE) # use 'dev=TRUE' to check layout compose_panel(b) legend_colorbar(b[[1]],lomar=20,himar=0) ## "left" legend_colorbar(b[[4]],labels=c(6,7.5,12,15,20) ,units="Manual set of labels") ## "right" legend_colorbar(b[[1]],las=2,adj=0.5,turn=TRUE,lomar=6,himar=6 ,units="Central adjustment; inverse order") ## ("top",1) legend_colorbar(b[[2]],cex=0.9 ,units="Horizontal labels can be overlapped") ## ("top",2) legend_colorbar(b[[3]],las=3,align=la ,units="Increased width, but aligned -->") ## ("top",3) legend_colorbar(b[[4]],las=3,align=la,labels=3 ,units="<-- Reduced width, but aligned") ## ("top",4) legend_colorbar(b[[1]],las=2,adj=0,shift=0.9,turn=FALSE,lomar=2,himar=10 ,units="Left adjustement. Non-optimal; shifted") ## ("bottom",1) legend_colorbar(b[[2]],las=3,adj=0 ,units="But right adj. is default for numeric") ## ("bottom",2) legend_colorbar(b[[3]],labels=99,las=3,trim=2L ,units="Required 99 labels, but displayed less") ## ("bottom",3) legend_colorbar('Caption from named item'=b[[4]],labels=99) ## ("bottom",4) compose_close()
Functions write text outside of maps panels. legend_mtext
(without prefix dot) is a wrapper for non-public .legend_mtext
(with prefix dot).
legend_mtext(...) ## non-public .legend_mtext(text = "Annotation", cex = 1)
legend_mtext(...) ## non-public .legend_mtext(text = "Annotation", cex = 1)
... |
Set of arguments, which are recognized via their names (using regular expressions) and classes. Passed to non-public
|
||||||||||||
text |
Argument of class |
||||||||||||
cex |
Argument of class |
If text
is expression
, then possible way for formatting is:
text=as.expression(substitute(bold(italic("Omega powered by alpha is ",Omega^alpha))))
Returned value of function mtext
from package graphics.
Nikita Platonov [email protected]
session_grid(NULL) a <- ursa_dummy(1,min=-10,max=+30) compose_open(legend=list("right","top","bottom","left")) panel_new() ct <- panel_raster(a) legend_colorbar(ct)#,units=as.expression(substitute(bold(degree*C)))) legend_mtext("Characters are in bold") legend_mtext(as.expression(substitute(italic( paste("Units can be interpreted as",~degree*C)))),cex=0.7) legend_mtext(text=as.expression(substitute(italic(paste("Omega powered by alpha is" ,~~Omega^alpha))))) compose_close(execute=!FALSE)
session_grid(NULL) a <- ursa_dummy(1,min=-10,max=+30) compose_open(legend=list("right","top","bottom","left")) panel_new() ct <- panel_raster(a) legend_colorbar(ct)#,units=as.expression(substitute(bold(degree*C)))) legend_mtext("Characters are in bold") legend_mtext(as.expression(substitute(italic( paste("Units can be interpreted as",~degree*C)))),cex=0.7) legend_mtext(text=as.expression(substitute(italic(paste("Omega powered by alpha is" ,~~Omega^alpha))))) compose_close(execute=!FALSE)
Local operations (mean value, sum of values, median, minimum, maximum) of map algebra for multi-bands ursaRaster
object.
local_mean(x, cover = 0.5 - 1e-3, weight = NULL, verbose = FALSE, bandname = "mean") local_sum(x, cover = 0.5 - 1e-3, weight = NULL, verbose = FALSE, bandname = "sum") local_median(x, cover = 0.5 - 1e-3, verbose = FALSE) local_min(x, cover = 0.5 - 1e-3, verbose = FALSE) local_max(x, cover = 0.5 - 1e-3, verbose = FALSE) local_sd(x, cover = 0.5 - 1e-3, verbose = FALSE) local_var(x, cover = 0.5 - 1e-3, verbose = FALSE) local_quantile(x, probs = seq(0, 1, 0.25), type = 7, cover = 0.5 - 1e-3, verbose = FALSE) ## S3 method for class 'ursaRaster' mean(x, ...) ## S3 method for class 'ursaRaster' median(x, ...) ## S3 method for class 'ursaRaster' quantile(x, ...) # non public .average(x, cover = 0.5 - 1e-3, weight = NULL, sum = FALSE, verbose = FALSE)
local_mean(x, cover = 0.5 - 1e-3, weight = NULL, verbose = FALSE, bandname = "mean") local_sum(x, cover = 0.5 - 1e-3, weight = NULL, verbose = FALSE, bandname = "sum") local_median(x, cover = 0.5 - 1e-3, verbose = FALSE) local_min(x, cover = 0.5 - 1e-3, verbose = FALSE) local_max(x, cover = 0.5 - 1e-3, verbose = FALSE) local_sd(x, cover = 0.5 - 1e-3, verbose = FALSE) local_var(x, cover = 0.5 - 1e-3, verbose = FALSE) local_quantile(x, probs = seq(0, 1, 0.25), type = 7, cover = 0.5 - 1e-3, verbose = FALSE) ## S3 method for class 'ursaRaster' mean(x, ...) ## S3 method for class 'ursaRaster' median(x, ...) ## S3 method for class 'ursaRaster' quantile(x, ...) # non public .average(x, cover = 0.5 - 1e-3, weight = NULL, sum = FALSE, verbose = FALSE)
x |
|
cover |
Numeric. |
weight |
Positive numeric of length equal to number of bands. For |
sum |
Logical. For |
probs |
Numeric. For |
type |
Numeric. For |
verbose |
Logical. If |
bandname |
Character. Band name for created single-band image. |
... |
Function |
If for valid output cell value it is required to have at least m
values not marked as NA
, specify quota as cover=m/nband(x)
.
local_mean
and local_sum
are wrapper to non-public function .average
.
Generic functions mean
, median
, sd
for ursaRaster
class are implemented via local_mean
, local_median
, local_sd
, respectively.
Double-band ursaRaster
object for local_range()
.
Multi-band ursaRaster
object for local_quantile()
.
Otherwise, single-band ursaRaster
object.
Nikita Platonov [email protected]
If bands are interpreted as time series, apply local_stat
Mean value for image brick global_mean
Mean value for each band band_mean
session_grid(NULL) b <- ursa_dummy(nband=7,min=0,max=100,mul=1/16) b[b<40] <- NA print(b) res <- c('mean'=mean(b),'local_mean'=local_mean(b) ,'sum0'=local_sum(b,cover=0),'sum1'=local_sum(b,cover=1)) print(res) display(b) display(res)
session_grid(NULL) b <- ursa_dummy(nband=7,min=0,max=100,mul=1/16) b[b<40] <- NA print(b) res <- c('mean'=mean(b),'local_mean'=local_mean(b) ,'sum0'=local_sum(b,cover=0),'sum1'=local_sum(b,cover=1)) print(res) display(b) display(res)
If bands of ursaRaster
object are interpreted as observations in time, then local_stat
returns some parameters for time-series analysis. This is a local operation of map algebra.
local_stat(obj, time = NULL, cover = 1e-06, smooth = FALSE, verbose = FALSE)
local_stat(obj, time = NULL, cover = 1e-06, smooth = FALSE, verbose = FALSE)
obj |
Object of class |
time |
Numeric or |
cover |
Numeric. |
smooth |
Logical. If |
verbose |
Logical. Value |
Object of class ursaRaster
with bands:
mean |
Mean value in each cell across all bands of source raster. |
sd |
Standard deviation in each cell across all bands of source raster. Denominator is |
sum |
Sum value in each cell across all bands of source raster. |
min |
Minimal value in each cell across all bands of source raster. |
max |
Maximal value in each cell across all bands of source raster. |
n |
Number of non- |
slope |
Slope value in each cell across all bands of source raster. |
slopeS |
Significance of slope value taken with a sign of slope. |
RSS |
Resisual sum of squares. |
ESS |
Explained sum of squares. |
Nikita Platonov [email protected]
Local statistics of map algebra,
Group generics for objects of class ursaRaster
.
session_grid(NULL) set.seed(353) session_grid(regrid(mul=1/8)) a <- ursa_dummy(nband=15) a[a<60] <- NA cvr <- 12 b <- local_stat(a,cover=cvr) print(b) c.mean <- c('<bundle> mean'=b["mean"] ,'local_mean'=local_mean(a,cover=cvr) ,'<generic> mean'=mean(a,cover=cvr)) c.max <- c('<bundle> max'=b["max"] ,'local_max'=local_max(a,cover=cvr) ,'<generic> max'=max(a,cover=cvr)) print(c.mean) print(c.max) cmp <- c(mean=b["mean"]-local_mean(a,cover=cvr) ,sd=b["sd"]-local_sd(a,cover=cvr)) print(round(cmp,12)) d <- as.list(b) d[["slopeS"]] <- colorize(d[["slopeS"]],stretch="signif") display(d,blank.density=20,blank.angle=c(-45,45))
session_grid(NULL) set.seed(353) session_grid(regrid(mul=1/8)) a <- ursa_dummy(nband=15) a[a<60] <- NA cvr <- 12 b <- local_stat(a,cover=cvr) print(b) c.mean <- c('<bundle> mean'=b["mean"] ,'local_mean'=local_mean(a,cover=cvr) ,'<generic> mean'=mean(a,cover=cvr)) c.max <- c('<bundle> max'=b["max"] ,'local_max'=local_max(a,cover=cvr) ,'<generic> max'=max(a,cover=cvr)) print(c.mean) print(c.max) cmp <- c(mean=b["mean"]-local_mean(a,cover=cvr) ,sd=b["sd"]-local_sd(a,cover=cvr)) print(round(cmp,12)) d <- as.list(b) d[["slopeS"]] <- colorize(d[["slopeS"]],stretch="signif") display(d,blank.density=20,blank.angle=c(-45,45))
The bands with band_blank images, are omitted.
## S3 method for class 'ursaRaster' na.omit(object, ...)
## S3 method for class 'ursaRaster' na.omit(object, ...)
object |
Object of class |
... |
Ignored. For consistence with definition of generic function. |
Object of class ursaRaster
, which has no bands without any data.
Nikita Platonov [email protected]
session_grid(NULL) session_grid(regrid(mul=1/4)) a <- ursa_new(value=1:3) print(a) a[2] <- NA print(a) a2 <- na.omit(a) print(a2)
session_grid(NULL) session_grid(regrid(mul=1/4)) a <- ursa_new(value=1:3) print(a) a[2] <- NA print(a) a2 <- na.omit(a) print(a2)
nband
(length
) returns number of bands (layers, if appropriate in terminology) of ursaRaster
object.
nband(x) ## S3 method for class 'ursaRaster' length(x)
nband(x) ## S3 method for class 'ursaRaster' length(x)
x |
Object of class |
length
for ursaRaster
object is a synonym for nband
.
Positive integer of length 1.
Nikita Platonov [email protected]
bandname
(names
for ursaRaster
object).
session_grid(NULL) a1 <- pixelsize() print(a1) print(nband(a1)) a2 <- c("Band 1"=a1,Band2=a1/2,sqrt=sqrt(a1),NA) print(a2) print(nband(a2))
session_grid(NULL) a1 <- pixelsize() print(a1) print(nband(a1)) a2 <- c("Band 1"=a1,Band2=a1/2,sqrt=sqrt(a1),NA) print(a2) print(nband(a2))
open_envi
creates object of ursaRaster
class, reads ENVI header file and prepares connections
for ENVI binary file
open_envi(fname, resetGrid = FALSE, headerOnly = FALSE, decompress = !headerOnly, cache = 0L, ...)
open_envi(fname, resetGrid = FALSE, headerOnly = FALSE, decompress = !headerOnly, cache = 0L, ...)
fname |
Filename; full-name or short-name |
resetGrid |
Logical. If |
headerOnly |
Logical. If |
decompress |
If ENVI binary file is compressed and you have not to use ENVI values then put |
cache |
Integer. Using cache for compressed files. If |
... |
If input file does not exists then these additional arguments will be passed to |
open_envi
try to find ENVI files (binary and header) and open them. If unsuccessful then function passes ...
-arguments to create_envi
function
Returns object of class ursaRaster
. Values from ENVI binary are not in memory yet.
Nikita Platonov [email protected]
session_grid(NULL) a <- pixelsize() write_envi(a,"example") a <- open_envi("example") dir(pattern="^example.*") ursa_info(a) close(a) rm(a) envi_remove("example") ## additional arguments are enough to create new ENVI file dir(pattern="^example.*") a <- open_envi("example",layername=paste0("test",1:3)) ursa_info(a) dir(pattern="^example.*") close(a) envi_remove("example")
session_grid(NULL) a <- pixelsize() write_envi(a,"example") a <- open_envi("example") dir(pattern="^example.*") ursa_info(a) close(a) rm(a) envi_remove("example") ## additional arguments are enough to create new ENVI file dir(pattern="^example.*") a <- open_envi("example",layername=paste0("test",1:3)) ursa_info(a) dir(pattern="^example.*") close(a) envi_remove("example")
open_gdal
creates object of ursaRaster
class, and prepares connections
for data reading.
open_gdal(fname, engine=c("native", "sf", "gdalraster", "vapour"), verbose = FALSE) ursa_open(fname, verbose = FALSE)
open_gdal(fname, engine=c("native", "sf", "gdalraster", "vapour"), verbose = FALSE) ursa_open(fname, verbose = FALSE)
fname |
Character. Filename; full-name or short-name. |
engine |
Character. Functionality of which package is used for reading data. This is experimental list, which future depends on evolution of reviewed packages and their availability for partial reading of multiband rasters. |
verbose |
Logical. |
ursa_open
is a synonym to open_gdal
. Generally, both function names are abridged version of ursa_open_dgal
.
open_gdal
doesn't read data. Data can be read later using Extract operator [
.
If argument fname
is ENVI .hdr Labelled Raster then either open_gdal
or open_envi
can be used. The former provides external implementation for data reading via GDAL in rgdal package.
Returns object of class ursaRaster
. Values are not in memory.
Nikita Platonov [email protected]
session_grid(NULL) # fname1 <- system.file("pictures/cea.tif",package="rgdal") fname1 <- system.file("tif/geomatrix.tif",package="sf") message(fname1) a1 <- open_gdal(fname1) print(a1) print(a1[]) close(a1) # fname2 <- system.file("pictures/test_envi_class.envi",package="rgdal") fname2 <- tempfile(fileext=".") a <- ursa_dummy(1,resetGrid=TRUE) b <- colorize(a[a>91],stretch="equal",name=format(Sys.Date()+seq(0,6),"%A %d")) write_envi(b,fname2) message(fname2) b1 <- open_gdal(fname2) b2 <- open_envi(fname2) print(b1) print(b2) print(c('The same grid?'=identical(ursa_grid(b1),ursa_grid(b2)) ,'The same data?'=identical(ursa_value(b1[]),ursa_value(b2[])))) close(b1,b2) envi_remove(fname2)
session_grid(NULL) # fname1 <- system.file("pictures/cea.tif",package="rgdal") fname1 <- system.file("tif/geomatrix.tif",package="sf") message(fname1) a1 <- open_gdal(fname1) print(a1) print(a1[]) close(a1) # fname2 <- system.file("pictures/test_envi_class.envi",package="rgdal") fname2 <- tempfile(fileext=".") a <- ursa_dummy(1,resetGrid=TRUE) b <- colorize(a[a>91],stretch="equal",name=format(Sys.Date()+seq(0,6),"%A %d")) write_envi(b,fname2) message(fname2) b1 <- open_gdal(fname2) b2 <- open_envi(fname2) print(b1) print(b2) print(c('The same grid?'=identical(ursa_grid(b1),ursa_grid(b2)) ,'The same data?'=identical(ursa_value(b1[]),ursa_value(b2[])))) close(b1,b2) envi_remove(fname2)
panel_annotation
puts an annotation (text label) on the panel with raster image without anchors to any layer. Can be used as captions to image panels.
panel_annotation(...) # non-public .panel_annotation(label = expression(), position = "bottomright", lon = NA, lat = NA, x = NA, y = NA, cex = 1.0, adjust = 0.5, fg = "#000000", bg = "#FFFFFF1F", buffer = 1, fill = "#FFFFFF7F", font = par("family"), vertical = FALSE, alpha = 1, interpolate = FALSE, resample = FALSE, verbose = FALSE, ...)
panel_annotation(...) # non-public .panel_annotation(label = expression(), position = "bottomright", lon = NA, lat = NA, x = NA, y = NA, cex = 1.0, adjust = 0.5, fg = "#000000", bg = "#FFFFFF1F", buffer = 1, fill = "#FFFFFF7F", font = par("family"), vertical = FALSE, alpha = 1, interpolate = FALSE, resample = FALSE, verbose = FALSE, ...)
... |
Set of arguments, which are recognized via their names (using regular expressions) and classes:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
label |
Character, expression, or objects of classes |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
position |
Character keyword or numeric of length 2 in the interval [0,1]. Defines the location of scale bar. If character, then one of the "bottomleft", "bottomright", "topleft", "topright", "left", "right", "bottom", "top", or "center". If numeric then relative position on panel is defined using shift on horizontal and vertical axes from origin in the bottom-left corner. Default is |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
lon |
Numeric. Longitude for center of annotation's position. Default is |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
lat |
Numeric. Latitude for center of annotation's position. Default is |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
x |
Numeric. The horizontal coordinate of the annotation's position in the units of image grid. Default is |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
y |
Numeric. The vertical coordinate of the annotation's position in the units of image grid. Default is |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
cex |
Positive numeric. The relative font size for annotation's label. Default is |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
adjust |
One or two values in [0, 1]. Specifies the horizontal (and optionally vertical) adjustment of the labels. See description of argument |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
fg |
Character. Color name or code for label (texts and symbols). Default is |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
bg |
Character. Color name or code for thin buffer around label's elements. Default is |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
buffer |
Numeric. The relative width of buffer around label's elements. Default is |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
fill |
Character. Color name or code for circumscribed rectangle around labels. Default is |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
font |
Character. Font family. Default is |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
vertical |
Logical or numeric. Vertical or inclined orientation of label. If |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
interpolate |
Logical. Passed as argument |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
resample |
Logical or numeric. Passed as argument |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
alpha |
Numeric or character. Level of transparency for logos. If numeric, the either |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
verbose |
Logical. Value |
This function is based on function text with adding some decoration elements. For low-level plotting use layout.text function, which is equal to function text with additional control of image panels.
Since the most of character keywords of position
have relation to the boundary of image panel, such annotation is assigned as a caption for image panel. Default decoration is shadowed background rectangle, which is implemented by function rect.
If location is defined by two-dimensional vector (either relative position inside of image boundaries (pos
is numeric of length two), or pair lon
, lat
, or pair x
, y
), then such labeling is assigned as an annotation. Default decoration is thin buffer around symbols. The implementaion is via application of function function text for small diplacements around original position.
The priority of arguments (from higher to lower): 1) pair lon
, lat
, 2) pair x
, y
, 3) two-dimensional numeric of pos
, 4) character keyword of pos
. However, the default annotation is interpreted as a caption.
This function returns NULL
value.
Nikita Platonov [email protected]
session_grid(NULL) ## exam no.1 -- direct use compose_open(layout=c(2,3),legend=NULL,device="cairo") for (i in seq(6)) { panel_new() panel_annotation(label=LETTERS,cex=1.5) panel_annotation(pos=c(0.7,0.2) ,label=paste("panel",paste("no.",i),sep="\n")) if (i==1) panel_annotation(pos="center") } compose_close() ## exam no.2 -- indirect use display(pixelsize(),scale=2 ,ann.label="FJL",ann.lon=52,ann.lat=80,ann.buffer=1 ,ann.bg="#8F6FFF2F",ann.fill="#FFFF7F9F",ann.font="courier")
session_grid(NULL) ## exam no.1 -- direct use compose_open(layout=c(2,3),legend=NULL,device="cairo") for (i in seq(6)) { panel_new() panel_annotation(label=LETTERS,cex=1.5) panel_annotation(pos=c(0.7,0.2) ,label=paste("panel",paste("no.",i),sep="\n")) if (i==1) panel_annotation(pos="center") } compose_close() ## exam no.2 -- indirect use display(pixelsize(),scale=2 ,ann.label="FJL",ann.lon=52,ann.lat=80,ann.buffer=1 ,ann.bg="#8F6FFF2F",ann.fill="#FFFF7F9F",ann.font="courier")
panel_coastline
puts a coastline to the active panel of layout with optional land shadowing. The package provides data for coastline.
compose_coastline(...) panel_coastline(...) update_coastline(merge = TRUE) # not public .compose_coastline(obj = NULL, panel = 0, col = NA, fill = "transparent", detail = NA, density = NA, angle = NA, land = FALSE, lwd = 0.5, lty = 1, fail180 = NA, verbose = FALSE) # not public .panel_coastline(obj, verbose = FALSE)
compose_coastline(...) panel_coastline(...) update_coastline(merge = TRUE) # not public .compose_coastline(obj = NULL, panel = 0, col = NA, fill = "transparent", detail = NA, density = NA, angle = NA, land = FALSE, lwd = 0.5, lty = 1, fail180 = NA, verbose = FALSE) # not public .panel_coastline(obj, verbose = FALSE)
... |
Set of arguments, which are recognized via their names (using regular expressions) and classes:
|
|||||||||||||||||||||||||||||||||||||||
obj |
Objects of the one of the classes |
|||||||||||||||||||||||||||||||||||||||
panel |
Integer vector. Panel for which coastline will be displayed. |
|||||||||||||||||||||||||||||||||||||||
col |
Character. Color code/name for coastline. Default is |
|||||||||||||||||||||||||||||||||||||||
fill |
Character. Color code/name for land masking/shadowing. Default is |
|||||||||||||||||||||||||||||||||||||||
detail |
Character keyword. The categorical spatial resolution for coastline. Valid values are |
|||||||||||||||||||||||||||||||||||||||
density |
Numeric. The density of shading lines for land masking/shadowing. If |
|||||||||||||||||||||||||||||||||||||||
angle |
Numeric. The slope of shading lines, given as an angle in degrees (counter-clockwise). If |
|||||||||||||||||||||||||||||||||||||||
land |
Logical. If |
|||||||||||||||||||||||||||||||||||||||
lwd |
Positive numeric. Width of coastline. Default is |
|||||||||||||||||||||||||||||||||||||||
lty |
Positive integer. Type (pattern) of coastline. Default is |
|||||||||||||||||||||||||||||||||||||||
fail180 |
Logical. Patch for correct plotof polygons crossing 180 degree longitude. |
|||||||||||||||||||||||||||||||||||||||
verbose |
Logical. Value |
|||||||||||||||||||||||||||||||||||||||
merge |
Logical. Ingored. |
compose_coastline
forms an obect of class ursaCoastLine
. panel_coastline
displays object of class ursaCoastLine
. It is expected higher performance for multi-panel plotting.
If obj
is NULL
, then internal data is used. This data is based on simplified polygons of OpenStreetMap-derived data. Source data is licensed under the Open Data Commons Open Database License (ODbL). The crossing longitude 180 degrees polygons are merged. Removing of small polygons and simplifying of polygons geometry is applied for three levels of details ("l"
- low, "i"
- interim, "h"
- high). For the full ("f"
) level of details data simplification is not applied.
Coastline data are taken from directory, which is specified by getOption("ursaRequisite")
with default value system.file("requisite",package="ursa")
. Package contains data of "l"
(low) details level in the file system.file("requisite/coast-l.rds",package="ursa")
. Data of higher levels can be added using update_coastline()
function. It is required to specify user's requisite path using options(ursaRequisite=path/to/user/files)
before loading ursa, e.g. in the user's ~/.Rprofile
file. Otherwise, there is a chance that data can not be updated due to 'permission deny' of the system directories. Package sf and some it's suggestions are required for data update.
If detail=NA
then the spatial resolution is selected using CRS boundary and resolution using intuitive approach. If package's database cannot supply required details, then lower resolution is used.
Source coastline data in EPSG:4326 are transformed to CRS projection, extracted using session_grid
function. Coastlines with optional filling of either land or ocean area is interpreted as polygons. If filling is solid (there is no transparency or shading lines (numerical values of arguments density
and angle
), then coastline plotting is imlemented via polypath
function, otherwise polygon
function.
panel_coastline
returns NULL
compose_coastline
returns of object of class ursaCoastLine
. It is a list:
coast_xy |
Two-column matix of coordinates in the sessional projection. The polygons are separated by |
panel |
Integer. Panel for coastline displaying. If |
col |
See description of argument |
fill |
See description of argument |
shadow |
If filling is semi-transparent, then it is "alpha" of filling color (argument |
land |
See description of argument |
density |
See description of argument |
angle |
See description of argument |
lwd |
See description of argument |
lty |
See description of argument |
Coastal data (land polygons) is distributed under ODbL.
In the versions <=3.7-19 package ursa contained land polygons based on union of "GSHHS_l_L1.shp" and "GSHHS_l_L5.shp" data from Self-consistent Hierarchical High-resolution Geography Database (GSHHG), Version 2.3.3 (01 November 2014), distributed under the Lesser GNU Public License, Version 3 (29 June 2007).
Nikita Platonov [email protected]
session_grid(NULL) a <- pixelsize() p1 <- colorize(a[a>500],ramp=FALSE,interval=TRUE) p2 <- colorize(a,ramp=FALSE,pal=colorRampPalette(c("grey40","grey100")) ,verbose=!TRUE,interval=TRUE) compose_open(layout=c(2,2),legend=list(list(1,"right"),list(2,"left"))) for (i in 1:4) { panel_new(col=ifelse(i==2,"white",NA)) if (i %in% c(3,4)) panel_raster(p1) else if (i %in% 2) panel_raster(p2) if (i==1) panel_coastline() panel_coastline(coast=4,col="#007F00",fill="lightgreen",land=TRUE) panel_coastline(coast=3,col="#0000003F",fill="#0000003F") panel_coastline(coast=2,col="black",fill="black",density=20 ,angle=c(-45,45),lwd=0.25,detail="l") # panel_graticule(decor=4) panel_annotation(text=as.character(i)) if (i==1) panel_annotation(pos=c(1,1),text="default") else if (i==2) panel_annotation(pos=c(0,1),text="greyscale") else if (i==3) panel_annotation(pos=c(1,1),text="land is shadowed") else if (i==4) panel_annotation(pos=c(0,1),text="ocean is masked") } compose_legend(p2,p1) compose_close()
session_grid(NULL) a <- pixelsize() p1 <- colorize(a[a>500],ramp=FALSE,interval=TRUE) p2 <- colorize(a,ramp=FALSE,pal=colorRampPalette(c("grey40","grey100")) ,verbose=!TRUE,interval=TRUE) compose_open(layout=c(2,2),legend=list(list(1,"right"),list(2,"left"))) for (i in 1:4) { panel_new(col=ifelse(i==2,"white",NA)) if (i %in% c(3,4)) panel_raster(p1) else if (i %in% 2) panel_raster(p2) if (i==1) panel_coastline() panel_coastline(coast=4,col="#007F00",fill="lightgreen",land=TRUE) panel_coastline(coast=3,col="#0000003F",fill="#0000003F") panel_coastline(coast=2,col="black",fill="black",density=20 ,angle=c(-45,45),lwd=0.25,detail="l") # panel_graticule(decor=4) panel_annotation(text=as.character(i)) if (i==1) panel_annotation(pos=c(1,1),text="default") else if (i==2) panel_annotation(pos=c(0,1),text="greyscale") else if (i==3) panel_annotation(pos=c(1,1),text="land is shadowed") else if (i==4) panel_annotation(pos=c(0,1),text="ocean is masked") } compose_legend(p2,p1) compose_close()
An instrument to overlay multiple rasters on the same image panel. Contour is derived from one band of raster image. The colors (and respective colorbar in legend) is an alternative to contour labeling.
panel_contour(obj, type = "", ...)
panel_contour(obj, type = "", ...)
obj |
Object of class |
type |
Character. Keyword list to descibe characteristics of contour, which is interpreted using regular expressions. |
... |
Set of arguments, which are recognized via their names (using regular expressions) and classes:
Other arguments are used in the functuion |
Function contourLines
is used for contouring.
The color table of input raster image is kept. The output panel have one element left, because contours are borders between areas of the same color. It is recommended to use only gradient palettes.
The color table is forced not to be ramp (argument ramp=FALSE
in the function colorize
) to prevent extra density of contour lines.
The color table is forced to be interval (argument interval=1L
in the function colorize
) to prevent lost of elements in the palette.
Object of class ursaColorTable
, which then should be used as an input argument for the colorbar legend (function legend_colorbar
). If there is no argument of class ursaRaster
then function returns NULL
value.
Nikita Platonov [email protected]
session_grid(NULL) a <- pixelsize() refval <- seq(450,650,by=25) val <- refval[seq(refval) %% 2 == 1] ref <- colorize(a,breakvalue=refval,pal.rich=45,pal.rotate=0) p1 <- colorize(a,breakvalue=val,pal.rich=135,pal.rotate=0) p2 <- colorize(a,value=val,pal.rich=-15,pal.rotate=0) p3 <- colorize(a,value=refval) if (exam1 <- TRUE) { compose_open(legend=list(list(1,"left"),list(1,"right")),scale=2) panel_new() # ct1 <- panel_raster(ref) # ct2 <- panel_contour(p2,"colored line",palname="Greens",lwd=15,lwd.bg=0) ct2 <- panel_contour(p2,"colored line",pal.rich=240,pal.rotate=0,lwd.fg=15,lwd.bg=0) # panel_contour(ref,lwd=0) # mysource("contour.R") # mycontour(.panel_contour(a),lwd=0) if (exists("ct1")) compose_legend(ct1,units="raster") if (exists("ct2")) compose_legend(ct2,units="contour") compose_close(bpp=8) } if (exam2 <- TRUE) { compose_open(layout=c(2,2),byrow=FALSE ,legend=list(list(1,"left"),list("bottom",1) ,list(1,"right"),list("top",2) ,list(2,"right"),list("bottom",2))) panel_new() panel_raster(ref) panel_contour(a) panel_new() ct0 <- panel_contour(a,"color",value=val,pal.rich=240,pal.rotate=0,lwd=11,lwd.bg=12) panel_contour(a) panel_annotation(text="no colortable") panel_new() panel_raster(p1) ct1 <- panel_contour(p1,"color",lwd=11,lwd.bg=2) panel_contour(a) panel_annotation(text="colortable:category") panel_new() panel_raster(p2) ct2 <- panel_contour(p2,"color",lwd=11,lwd.bg=2) panel_contour(a)#,cex=0.5) panel_annotation(text="colortable:interval") compose_legend(ref,units="reference") compose_legend(ct0,units="contour") compose_legend(p1,units="raster") compose_legend(ct1,units="contour") compose_legend(p2,units="raster") compose_legend(ct2,units="contour") compose_close() } if (exam3 <- TRUE) { s <- 29 session_grid(NULL) a <- as.ursa(volcano) if (FALSE) { display(a) a2 <- regrid(a,mul=s,cascade=TRUE,verbose=TRUE) display(a2) session_grid(a) } compose_open() ## device="windows") panel_new() ct1 <- panel_raster(a,ramp=FALSE,interval=TRUE) ct2 <- panel_contour(a,"label") rm(ct2) panel_decor() if (exists("ct2")) legend_colorbar(ct2) else if (exists("ct1")) legend_colorbar(ct1) compose_close() }
session_grid(NULL) a <- pixelsize() refval <- seq(450,650,by=25) val <- refval[seq(refval) %% 2 == 1] ref <- colorize(a,breakvalue=refval,pal.rich=45,pal.rotate=0) p1 <- colorize(a,breakvalue=val,pal.rich=135,pal.rotate=0) p2 <- colorize(a,value=val,pal.rich=-15,pal.rotate=0) p3 <- colorize(a,value=refval) if (exam1 <- TRUE) { compose_open(legend=list(list(1,"left"),list(1,"right")),scale=2) panel_new() # ct1 <- panel_raster(ref) # ct2 <- panel_contour(p2,"colored line",palname="Greens",lwd=15,lwd.bg=0) ct2 <- panel_contour(p2,"colored line",pal.rich=240,pal.rotate=0,lwd.fg=15,lwd.bg=0) # panel_contour(ref,lwd=0) # mysource("contour.R") # mycontour(.panel_contour(a),lwd=0) if (exists("ct1")) compose_legend(ct1,units="raster") if (exists("ct2")) compose_legend(ct2,units="contour") compose_close(bpp=8) } if (exam2 <- TRUE) { compose_open(layout=c(2,2),byrow=FALSE ,legend=list(list(1,"left"),list("bottom",1) ,list(1,"right"),list("top",2) ,list(2,"right"),list("bottom",2))) panel_new() panel_raster(ref) panel_contour(a) panel_new() ct0 <- panel_contour(a,"color",value=val,pal.rich=240,pal.rotate=0,lwd=11,lwd.bg=12) panel_contour(a) panel_annotation(text="no colortable") panel_new() panel_raster(p1) ct1 <- panel_contour(p1,"color",lwd=11,lwd.bg=2) panel_contour(a) panel_annotation(text="colortable:category") panel_new() panel_raster(p2) ct2 <- panel_contour(p2,"color",lwd=11,lwd.bg=2) panel_contour(a)#,cex=0.5) panel_annotation(text="colortable:interval") compose_legend(ref,units="reference") compose_legend(ct0,units="contour") compose_legend(p1,units="raster") compose_legend(ct1,units="contour") compose_legend(p2,units="raster") compose_legend(ct2,units="contour") compose_close() } if (exam3 <- TRUE) { s <- 29 session_grid(NULL) a <- as.ursa(volcano) if (FALSE) { display(a) a2 <- regrid(a,mul=s,cascade=TRUE,verbose=TRUE) display(a2) session_grid(a) } compose_open() ## device="windows") panel_new() ct1 <- panel_raster(a,ramp=FALSE,interval=TRUE) ct2 <- panel_contour(a,"label") rm(ct2) panel_decor() if (exists("ct2")) legend_colorbar(ct2) else if (exists("ct1")) legend_colorbar(ct1) compose_close() }
panel_decor
adds over plot sequentially the followed elements: coastline, gridline, scalebar. Unlike panel_decor
, function layout.grid
does not add scalebar.
panel_decor(...)
panel_decor(...)
... |
Passed to sequence of plotting functions:
|
The sequence of elements is constant. To change order, use direct calling of panel_graticule
, panel_coastline
, panel_scalebar
in any sequence.
Sometimes, for rasters with NA
values the followed sequence may be used:
panel_coastline(col="transparent",fill="grey80") panel_raster(a) panel_coastline(col="grey40")
panel_decor
returns NULL
value.layout.grid
returns NULL
value.
Nikita Platonov [email protected]
session_grid(NULL) a <- ursa_dummy(nband=1,min=0,max=100) a[a<30] <- NA compose_open() panel_new() ct <- panel_raster(a) panel_decor(graticule.col="green4",graticule.lwd=2,scalebar.col="brown") compose_legend(ct) compose_close()
session_grid(NULL) a <- ursa_dummy(nband=1,min=0,max=100) a[a<30] <- NA compose_open() panel_new() ct <- panel_raster(a) panel_decor(graticule.col="green4",graticule.lwd=2,scalebar.col="brown") compose_legend(ct) compose_close()
panel_graticule
puts a grid on the panel with raster image. If CRS is georeferenced then grid is generated from longitudes and latitudes.
panel_graticule(...) compose_graticule(...) # non-public .compose_graticule(panel = 0L, col = "grey70", border = "grey70", lon = NA, lat = NA, lwd = 0.5, lty = 2, marginalia = rep(FALSE, 4), trim = FALSE, language = NA_character_, cex = 0.75, verbose = FALSE) # non-public .panel_graticule(obj, marginalia = rep(TRUE, 4), verbose = FALSE)
panel_graticule(...) compose_graticule(...) # non-public .compose_graticule(panel = 0L, col = "grey70", border = "grey70", lon = NA, lat = NA, lwd = 0.5, lty = 2, marginalia = rep(FALSE, 4), trim = FALSE, language = NA_character_, cex = 0.75, verbose = FALSE) # non-public .panel_graticule(obj, marginalia = rep(TRUE, 4), verbose = FALSE)
... |
Set of arguments, which are recognized via their names (using regular expressions) and classes:
|
|||||||||||||||||||||||||||||||||||||||
obj |
Objects of the class |
|||||||||||||||||||||||||||||||||||||||
panel |
Integer vector. Panel for which coastline will be displayed. |
|||||||||||||||||||||||||||||||||||||||
col |
Character. Color code/name for grid lines. Default is |
|||||||||||||||||||||||||||||||||||||||
border |
Character. Color code/name for marginal labels and ticks. Default is |
|||||||||||||||||||||||||||||||||||||||
lon |
Numeric vector. Set of longitudes for grid. If |
|||||||||||||||||||||||||||||||||||||||
lat |
Numeric vector. Set of latitudes for grid. If |
|||||||||||||||||||||||||||||||||||||||
lwd |
Positive numeric. Width of grid line. Default is |
|||||||||||||||||||||||||||||||||||||||
lty |
Positive integer. Type (pattern) of grid line. Default is |
|||||||||||||||||||||||||||||||||||||||
marginalia |
Logical or integer vectors. Responsible for whether longitudes and latitudes (or metric coordinates) be labelled on the frame of panel with raster image. If logical and |
|||||||||||||||||||||||||||||||||||||||
language |
Character. Language for longitude and latitude captions. If |
|||||||||||||||||||||||||||||||||||||||
trim |
Logical. If grid lines are labelled then |
|||||||||||||||||||||||||||||||||||||||
cex |
Positive numeric. The relative font size for grid lines' labels. Make sence in the case of labels plotting. Default is |
|||||||||||||||||||||||||||||||||||||||
verbose |
Logical. Value |
If not language="ru"
but environmental variable LANGUAGE=ru
then labels are in Russian (cyrillics).
Argument gridline
(or, grid
) is introduced for unconditional calling of panel_graticule
inside of high-level functions.
Grid lines can be controlled in high-level plot functions (e.g., display
, compose_plot
, display_stack
, display_brick
, display_rgb
, etc.). To prevent displaying grid lines, use argument gridline=FALSE
(or grid=FALSE
). To display grid lines, use argument gridline=TRUE
(or grid=TRUE
) and prefix grid(line)*
(gridline.*
or grid.*
) for grid lines' parameters, e.g., gridline.verb=TRUE
, grid.col="black"
. If prefix is omitted then arguments with the same names affect in other functions in the part of high-level function.
If grid lines are formed internally, then desirable number of lines for each direction is 3. The design of line density is based on intuition, providing pretty labelling.
If CRS is georeferenced then grid lines are corresponded to longitudes and latitudes. Integer minutes are used to illustate fractional values of degrees. If precision of minutes is insufficient, then integer values of seconds are introduced. The fractional values of seconds are not used.
Labels are located at the points, where grid lines cross plot margin. Labels are not overlapped along the same side. To prevent overlapping along the same side, labels are shifted or omitted. Argument trim=TRUE
prevents overlapping labels from neighbor sides via hidding.
Function returns NULL
value.
Nikita Platonov [email protected]
session_grid(NULL) ## Changing of environmental variables is out of CRAN Policy ## Not run: Sys.setenv(LANGUAGE="ru") # example no.1 cl <- compose_design(layout=c(2,2),legend=NULL) session_grid(regrid(lim=3.2*1e6*c(-1,-1,1,1))) compose_open(cl) for (i in 1:4) { panel_new() panel_coastline() panel_graticule(decor=TRUE,trim=i %in% c(2:4)) panel_annotation(text=as.character(i)) panel_scalebar(scalebar=i==3) } compose_close() # example no.2 session_grid(regrid(lim=1e6*c(-0.5,0.5,1.5,2.5))) compose_open(layout=c(2,2),legend=NULL,skip=4) for (i in seq(getOption("ursaPngLayout")$image)) { panel_new() panel_coastline() if (i==1) panel_graticule() else if (i==2) panel_graticule(decor=TRUE,lon=seq(0,360,by=40)[-1],lat=seq(-90,90,by=10)) else if (i==3) panel_graticule(decor=TRUE,lon=seq(0,360,by=20)[-1],lat=seq(-90,90,by=5) ,trim=TRUE) else if (i==4) panel_graticule(gridline=FALSE) panel_scalebar(scalebar=1) panel_annotation(text=as.character(i)) } compose_close() # example no.3 -- indirect usage session_grid(NULL) display(pixelsize(),decor=TRUE,grid.col="green3",coast.col="darkgreen",side=2) ## Changing of environmental variables is out of CRAN Policy ## Not run: Sys.setenv(LANGUAGE="") # reset environmental variable
session_grid(NULL) ## Changing of environmental variables is out of CRAN Policy ## Not run: Sys.setenv(LANGUAGE="ru") # example no.1 cl <- compose_design(layout=c(2,2),legend=NULL) session_grid(regrid(lim=3.2*1e6*c(-1,-1,1,1))) compose_open(cl) for (i in 1:4) { panel_new() panel_coastline() panel_graticule(decor=TRUE,trim=i %in% c(2:4)) panel_annotation(text=as.character(i)) panel_scalebar(scalebar=i==3) } compose_close() # example no.2 session_grid(regrid(lim=1e6*c(-0.5,0.5,1.5,2.5))) compose_open(layout=c(2,2),legend=NULL,skip=4) for (i in seq(getOption("ursaPngLayout")$image)) { panel_new() panel_coastline() if (i==1) panel_graticule() else if (i==2) panel_graticule(decor=TRUE,lon=seq(0,360,by=40)[-1],lat=seq(-90,90,by=10)) else if (i==3) panel_graticule(decor=TRUE,lon=seq(0,360,by=20)[-1],lat=seq(-90,90,by=5) ,trim=TRUE) else if (i==4) panel_graticule(gridline=FALSE) panel_scalebar(scalebar=1) panel_annotation(text=as.character(i)) } compose_close() # example no.3 -- indirect usage session_grid(NULL) display(pixelsize(),decor=TRUE,grid.col="green3",coast.col="darkgreen",side=2) ## Changing of environmental variables is out of CRAN Policy ## Not run: Sys.setenv(LANGUAGE="") # reset environmental variable
panel_new
finishes plotting on previuos image panel and starts plotting on next image panel.
panel_new(...) # non-public .panel_new(col = "chessboard", alpha = NA, density = NA, angle = NA, lwd = 1, lty = 1, asp = NA, mar = rep(0, 4), grid = NULL, verbose = FALSE)
panel_new(...) # non-public .panel_new(col = "chessboard", alpha = NA, density = NA, angle = NA, lwd = 1, lty = 1, asp = NA, mar = rep(0, 4), grid = NULL, verbose = FALSE)
... |
Set of arguments, which are recognized via their names (using regular expressions) and classes. Passed to non-public
|
|||||||||||||||||||||||||||||||||
col |
Character. Color code/name for panel filling/shadowing. Default is |
|||||||||||||||||||||||||||||||||
alpha |
Numeric, |
|||||||||||||||||||||||||||||||||
density |
Numeric. The density of shading lines for fill/shadowing. If |
|||||||||||||||||||||||||||||||||
angle |
Numeric. The slope of shading lines, given as an angle in degrees (counter-clockwise). If |
|||||||||||||||||||||||||||||||||
lwd |
Positive numeric. Width of coastline. Default is |
|||||||||||||||||||||||||||||||||
lty |
Character or positive integer. Type (pattern) of coastline. Default is |
|||||||||||||||||||||||||||||||||
asp |
Positive numeric. The y/x aspect ration. Default is |
|||||||||||||||||||||||||||||||||
mar |
Positive numeric of length 4. Plot margins. Default is |
|||||||||||||||||||||||||||||||||
grid |
Object of class |
|||||||||||||||||||||||||||||||||
verbose |
Logical. Value |
Prefix blank
is introduced for manipulations with panel_new
inside of high-level functions (e.g., display
). Prefix skipping is the subject for confict with functions, which use the same name of arguments.
It is required to call panel_new
for every image panel. First calling starts plotting on the first panel. Second and next callings change image panels.
The panel sequence is set in function compose_design
, which is called directly or indirectly from compose_open
, and keeps in the options (access via getOption("ursaPngLayout")$layout
).
Image background is formed via consecutive call of functions plot(...,type="n")
, and rect(...)
.
Function returns NULL
value.
Nikita Platonov [email protected]
session_grid(NULL) # example no.1 -- direct use compose_open(layout=c(1,3),legend=NULL) panel_new() panel_annotation(label="Default + Empty") panel_new(col="#0000FF3F",density=15,angle=45,lwd=3) panel_decor() panel_annotation(label="Settings + Grid") panel_new("#FFFF0040",grid=regrid(expand=0.5)) panel_decor() panel_annotation(label="Another spatial extent") compose_close() # example no.2 -- indirect use a <- pixelsize() a <- a[a>560] display(a,blank.col="#0000FF3F",blank.density=15,blank.angle=45,blank.lwd=3 ,coast.fill="#007F005F",coast.density=20,coast.angle=c(-30,60))
session_grid(NULL) # example no.1 -- direct use compose_open(layout=c(1,3),legend=NULL) panel_new() panel_annotation(label="Default + Empty") panel_new(col="#0000FF3F",density=15,angle=45,lwd=3) panel_decor() panel_annotation(label="Settings + Grid") panel_new("#FFFF0040",grid=regrid(expand=0.5)) panel_decor() panel_annotation(label="Another spatial extent") compose_close() # example no.2 -- indirect use a <- pixelsize() a <- a[a>560] display(a,blank.col="#0000FF3F",blank.density=15,blank.angle=45,blank.lwd=3 ,coast.fill="#007F005F",coast.density=20,coast.angle=c(-30,60))
Standard fuctions for plotting from package graphics are used for manual adding elements to current plot. Theses series of functions used that standard instruments with additional controling the acceptability of plotting.
panel_plot(obj,...) panel_box(...) panel_lines(...) panel_points(...) panel_text(...) panel_abline(...) panel_polygon(...) panel_segments(...)
panel_plot(obj,...) panel_box(...) panel_lines(...) panel_points(...) panel_text(...) panel_abline(...) panel_polygon(...) panel_segments(...)
obj |
R object. |
... |
In |
If unable to get value TRUE
from getOption("ursaPngPlot")
then plotting is disable, and any function from this series returns NULL
.
Generally, for spatial objects argument add=TRUE
is used in panel_plot
.
For spatial objects (simple features from sf or spatial abstract classes from sp) function panel_plot
returns object of class ursaLegend
. It is a list with items, which can be used to as arguments of legend()
. This is intermediate step for experimental feature (not ready) to display colorbars on plot panel. For other objects function panel_plot
returns value of function plot
.
Function panel_box
returns value of function box
.
Function panel_lines
returns value of function lines
.
Function panel_points
returns value of function points
.
Function panel_text
returns value of function text
.
Function panel_abline
returns value of function abline
.
Function panel_polygon
returns value of function polygon
.
Function panel_segments
returns value of function segments
.
For plotted elements it is possible to create legend for colors using color bars. No shapes kind and size, no line widths.
To convert object x
of class ursaLegend
to object of class ursaColorTable
please use ursa_colortable(x)
.
Nikita Platonov [email protected]
Package graphics (help(package="graphics")
) and functions plot
, box
, lines
, points
, text
, abline
, polygon
, segments
.
session_grid(NULL) # require(rgdal) ## 'rgdal' is retired a <- pixelsize() g1 <- session_grid() n <- 12L k <- 5L x <- with(g1,runif(n,min=minx,max=maxx)) y <- with(g1,runif(n,min=miny,max=maxy)) panel_plot(x,y) ## plots nothing, because 'compose_open(...,dev=F)' is not called yet shpname <- tempfile(fileext=".shp") layername <- gsub("\\.shp$","",basename(shpname)) if (requireNamespace("sp")) { sl <- lapply(seq(k),function(id){ x <- sort(with(g1,runif(n,min=minx,max=maxx))) y <- sort(with(g1,runif(n,min=miny,max=maxy))) sp::Lines(sp::Line(cbind(x,y)),ID=id) }) sl <- sp::SpatialLines(sl,proj4string=sp::CRS(ursa_proj(g1)))#,id=length(sl)) lab <- t(sapply(sp::coordinates(sl),function(xy) xy[[1]][round(n/2),])) lab <- as.data.frame(cbind(lab,z=seq(k))) sl <- sp::SpatialLinesDataFrame(sl ,data=data.frame(ID=runif(k,min=5,max=9),desc=LETTERS[seq(k)])) print(sl@data) ct <- colorize(sl@data$ID)#,name=sldf@data$desc) try(writeOGR(sl,dirname(shpname),layername,driver="ESRI Shapefile")) ## 'rgdal' is retired spatial_write(sl,shpname) } else if (requireNamespace("sf")) { sl <- lapply(seq(k),function(id) { x <- sort(with(g1,runif(n,min=minx,max=maxx))) y <- sort(with(g1,runif(n,min=miny,max=maxy))) sf::st_linestring(cbind(x,y)) }) sl <- sf::st_sfc(sl,crs=as.character(ursa_crs(g1))) sl <- sf::st_sf(ID=runif(k,min=5,max=9),desc=LETTERS[seq(k)],geometry=sl) print(spatial_data(sl)) lab <- do.call("rbind",lapply(sf::st_geometry(sl),colMeans)) lab <- as.data.frame(cbind(lab,z=seq(k))) ct <- colorize(sl$ID) sf::st_write(sl,shpname) } compose_open(layout=c(1,2),legend=list(list("bottom",2))) panel_new() panel_decor() panel_lines(x,y,col="orange") panel_points(x,y,cex=5,pch=21,col="transparent",bg="#00FF005F") panel_points(0,0,pch=3) panel_text(0,0,"North\nPole",pos=4,cex=1.5,family="Courier New",font=3) panel_new() panel_decor() if (exists("sl")) panel_plot(sl,lwd=4,col="grey20") if ((exists("ct"))&&(file.exists(shpname))) panel_plot(shpname,lwd=3,col=ct$colortable[ct$index]) if (exists("lab")) panel_points(lab$x,lab$y,pch=as.character(lab$z),cex=2) if (exists("ct")) compose_legend(ct$colortable) compose_close() file.remove(dir(path=dirname(shpname) ,pattern=paste0(layername,"\\.(cpg|dbf|prj|shp|shx)") ,full.names=TRUE))
session_grid(NULL) # require(rgdal) ## 'rgdal' is retired a <- pixelsize() g1 <- session_grid() n <- 12L k <- 5L x <- with(g1,runif(n,min=minx,max=maxx)) y <- with(g1,runif(n,min=miny,max=maxy)) panel_plot(x,y) ## plots nothing, because 'compose_open(...,dev=F)' is not called yet shpname <- tempfile(fileext=".shp") layername <- gsub("\\.shp$","",basename(shpname)) if (requireNamespace("sp")) { sl <- lapply(seq(k),function(id){ x <- sort(with(g1,runif(n,min=minx,max=maxx))) y <- sort(with(g1,runif(n,min=miny,max=maxy))) sp::Lines(sp::Line(cbind(x,y)),ID=id) }) sl <- sp::SpatialLines(sl,proj4string=sp::CRS(ursa_proj(g1)))#,id=length(sl)) lab <- t(sapply(sp::coordinates(sl),function(xy) xy[[1]][round(n/2),])) lab <- as.data.frame(cbind(lab,z=seq(k))) sl <- sp::SpatialLinesDataFrame(sl ,data=data.frame(ID=runif(k,min=5,max=9),desc=LETTERS[seq(k)])) print(sl@data) ct <- colorize(sl@data$ID)#,name=sldf@data$desc) try(writeOGR(sl,dirname(shpname),layername,driver="ESRI Shapefile")) ## 'rgdal' is retired spatial_write(sl,shpname) } else if (requireNamespace("sf")) { sl <- lapply(seq(k),function(id) { x <- sort(with(g1,runif(n,min=minx,max=maxx))) y <- sort(with(g1,runif(n,min=miny,max=maxy))) sf::st_linestring(cbind(x,y)) }) sl <- sf::st_sfc(sl,crs=as.character(ursa_crs(g1))) sl <- sf::st_sf(ID=runif(k,min=5,max=9),desc=LETTERS[seq(k)],geometry=sl) print(spatial_data(sl)) lab <- do.call("rbind",lapply(sf::st_geometry(sl),colMeans)) lab <- as.data.frame(cbind(lab,z=seq(k))) ct <- colorize(sl$ID) sf::st_write(sl,shpname) } compose_open(layout=c(1,2),legend=list(list("bottom",2))) panel_new() panel_decor() panel_lines(x,y,col="orange") panel_points(x,y,cex=5,pch=21,col="transparent",bg="#00FF005F") panel_points(0,0,pch=3) panel_text(0,0,"North\nPole",pos=4,cex=1.5,family="Courier New",font=3) panel_new() panel_decor() if (exists("sl")) panel_plot(sl,lwd=4,col="grey20") if ((exists("ct"))&&(file.exists(shpname))) panel_plot(shpname,lwd=3,col=ct$colortable[ct$index]) if (exists("lab")) panel_points(lab$x,lab$y,pch=as.character(lab$z),cex=2) if (exists("ct")) compose_legend(ct$colortable) compose_close() file.remove(dir(path=dirname(shpname) ,pattern=paste0(layername,"\\.(cpg|dbf|prj|shp|shx)") ,full.names=TRUE))
If specified image has 3 or 4 bands, then color composite is plotted on image panel, else the image is plotted regarding to its color table.
panel_raster(...)
panel_raster(...)
... |
Set of arguments, which are recognized via their names (using regular expressions) and classes.
|
If obj
is list of raster images, then panel_raster
is applied to each item of list, and colortable of last item is returned.
If obj
has 3 or 4 bands then obj
is interpreted as RGB(A) image.
Function attempts to speed up plotting by reduce image matrix for big rasters.
If argument obj
has strictly one band, then function returns color table - object of class ursaColorTable
, which can be used as an input argument for the colorbar legend (function legend_colorbar
). Otherwise function returns NULL
value.
Nikita Platonov [email protected]
session_grid(NULL) # example no.1 -- direct use session_grid(regrid(mul=1/32)) dima <- with(session_grid(),c(columns,rows,3)) a <- ursa_new(value=array(runif(prod(dima),min=127,max=255),dim=dima)) p <- colorize(a,pal=c("black","white"),ramp=TRUE,value=0:256) compose_open(layout=c(2,3),skip=4,legend=list(list("top","full"),list("bottom",2:3))) for (i in seq(6)) { panel_new() if (i<4) panel_raster(p[i]) else panel_raster(a,interpolate=i==5) panel_decor(col="black",coast=FALSE) panel_annotation(c("red","green","blue" ,"interpolate=FALSE","interpolate=TRUE")) } legend_colorbar(p,label=seq(0,256,by=16),units="channels") legend_mtext("color composite") compose_close() # example no.2 -- indirect use ps <- pixelsize(NULL) display(ps,raster.verb=TRUE) # example no.3 -- color table for legend session_grid(NULL) compose_open() panel_new() ct <- panel_raster(ps,pal=terrain.colors) panel_decor() compose_legend(ct) compose_close()
session_grid(NULL) # example no.1 -- direct use session_grid(regrid(mul=1/32)) dima <- with(session_grid(),c(columns,rows,3)) a <- ursa_new(value=array(runif(prod(dima),min=127,max=255),dim=dima)) p <- colorize(a,pal=c("black","white"),ramp=TRUE,value=0:256) compose_open(layout=c(2,3),skip=4,legend=list(list("top","full"),list("bottom",2:3))) for (i in seq(6)) { panel_new() if (i<4) panel_raster(p[i]) else panel_raster(a,interpolate=i==5) panel_decor(col="black",coast=FALSE) panel_annotation(c("red","green","blue" ,"interpolate=FALSE","interpolate=TRUE")) } legend_colorbar(p,label=seq(0,256,by=16),units="channels") legend_mtext("color composite") compose_close() # example no.2 -- indirect use ps <- pixelsize(NULL) display(ps,raster.verb=TRUE) # example no.3 -- color table for legend session_grid(NULL) compose_open() panel_new() ct <- panel_raster(ps,pal=terrain.colors) panel_decor() compose_legend(ct) compose_close()
panel_scalebar
puts a scale bar ('box' style) on the panel with raster image.
panel_scalebar(...) # non-public .panel_scalebar(position = "bottomleft", w = NA, cex = 0.85, col = "#0000002F", bg = "transparent", fill = "#FFFFFF2F", language=NA, verbose = FALSE)
panel_scalebar(...) # non-public .panel_scalebar(position = "bottomleft", w = NA, cex = 0.85, col = "#0000002F", bg = "transparent", fill = "#FFFFFF2F", language=NA, verbose = FALSE)
... |
Set of arguments, which are recognized via their names (using regular expressions) and classes. Passed to non-public
|
||||||||||||||||||||||||||||||
position |
Character keyword or numeric of length 2 in the interval [0,1]. Defines the location of scale bar. If character, then one of the "bottomleft", "bottomright", "topleft", "topright", "left", "right", "bottom", "top", or "center". If numeric then relative position on panel is defined using shift on horizontal and vertical axes from origin in the bottom-left corner. Default is |
||||||||||||||||||||||||||||||
w |
Positive numeric. The length in km of scalebar's right segment. If |
||||||||||||||||||||||||||||||
cex |
Positive numeric. The relative font size for scalebar's labels. Default is |
||||||||||||||||||||||||||||||
col |
Character. Primary fill color for scalebar box and scalebar labels. Default is |
||||||||||||||||||||||||||||||
fill |
Character. Secondary fill color for scalebar box. Default is |
||||||||||||||||||||||||||||||
bg |
Character. Background color for the area of scalebar box and labels. Default is |
||||||||||||||||||||||||||||||
language |
Character. Language for longitude and latitude captions. If |
||||||||||||||||||||||||||||||
verbose |
Logical. Value |
The scalebar has 2 left segments and 2 right segments. Left and right segments are separated by 0. The length of left segments is a half of length of right segments.
Argument scalebar
(or, synonym, ruler
) is introduced for unconditional calling of panel_scalebar
inside of high-level functions.
Default x=0
and y=0
define the "bottomleft"
position of scale bar.
If argument scale
in the function compose_open
is character, then the length of one segment is exactly 1 cm, and the total length of scalebar is 3 cm.
If not language="ru"
but environmental variable LANGUAGE=ru
then labels are in Russian (cyrillics).
The length distortions is taken into account for transverse Mercator ("+proj=tmerc"
) projection regarding to location of scalebar.
Scalebar (single occurence) can be controlled in high-level plot functions (e.g., display
, compose_plot
, display_stack
, display_brick
, display_rgb
, etc.).
To plot scalebar, use argument scalebar=TRUE
and prefix (ruler|scalebar)
(scalebar.*
or ruler.*
) for scalebar's parameters, e.g., scalebar.pos="bottomright"
, scalebar.cex=0.9
.
Scalebar is not displayed for longlat projection ("+proj=longlat"
), where units are degrees.
This function returns NULL
value.
Nikita Platonov [email protected]
session_grid(NULL) # example no.1 -- direct usage a <- colorize(pixelsize()) compose_open(a) panel_new() panel_raster(a) panel_graticule() panel_coastline() panel_scalebar() compose_close() # example no.2 -- indirect usage display_rgb(ursa_dummy(nband=3,min=0,max=255),coastline=FALSE ,scalebar=TRUE,scalebar.col="white",scalebar.fill="black") # example no.3 -- for paper copy a <- colorize(pixelsize(),breakvalue=seq(400,650,by=50),pal=c("gray90","gray30")) compose_open(scale="1:95000000",dpi=150,device="cairo",family="Times") compose_plot(a,graticule=TRUE,coastline=FALSE,scalebar=TRUE,scalebar.x=1,units=expression(km^2)) compose_close(bpp=8) # example no.4 -- length distortion in the Transverse Mercator projection a1 <- regrid(setbound=c(10,65,71,83),dim=c(100,100),crs=4326) a2 <- polygonize(ursa_bbox(a1)) a3 <- spatial_transform(a2,3857) a4 <- regrid(setbound=spatial_bbox(a3),res=20000,crs=spatial_crs(a3)) compose_open(legend=NULL) panel_new("white") panel_coastline(fill="#00000010",detail="l") # panel_graticule() for (p in c("bottom","center","top")) panel_scalebar(pos=p,w=200) compose_close()
session_grid(NULL) # example no.1 -- direct usage a <- colorize(pixelsize()) compose_open(a) panel_new() panel_raster(a) panel_graticule() panel_coastline() panel_scalebar() compose_close() # example no.2 -- indirect usage display_rgb(ursa_dummy(nband=3,min=0,max=255),coastline=FALSE ,scalebar=TRUE,scalebar.col="white",scalebar.fill="black") # example no.3 -- for paper copy a <- colorize(pixelsize(),breakvalue=seq(400,650,by=50),pal=c("gray90","gray30")) compose_open(scale="1:95000000",dpi=150,device="cairo",family="Times") compose_plot(a,graticule=TRUE,coastline=FALSE,scalebar=TRUE,scalebar.x=1,units=expression(km^2)) compose_close(bpp=8) # example no.4 -- length distortion in the Transverse Mercator projection a1 <- regrid(setbound=c(10,65,71,83),dim=c(100,100),crs=4326) a2 <- polygonize(ursa_bbox(a1)) a3 <- spatial_transform(a2,3857) a4 <- regrid(setbound=spatial_bbox(a3),res=20000,crs=spatial_crs(a3)) compose_open(legend=NULL) panel_new("white") panel_coastline(fill="#00000010",detail="l") # panel_graticule() for (p in c("bottom","center","top")) panel_scalebar(pos=p,w=200) compose_close()
This specific function is designed to illustrate linear slope and areas of statistically significant slope on the same panel, however can be used commonly for shading by raster mask.
panel_shading(obj, level = NA, col = NULL, density = 25, angle = c( -45, 45), lwd = 1, lty = 1, verbose = TRUE)
panel_shading(obj, level = NA, col = NULL, density = 25, angle = c( -45, 45), lwd = 1, lty = 1, verbose = TRUE)
obj |
Object of class |
level |
Positive numeric. Threshold for |
col |
|
density |
Numeric. The density of shading lines, in lines per inch. Default is |
angle |
Numeric. The slope of shading lines, given as an angle in degrees (counter-clockwise). Default is vector of length two |
lwd |
Numeric. Line width for shading. Default is |
lty |
Numeric or character. Line type for shading. Default is |
verbose |
Logical. If |
Values of input obj
is reclassified to raster mask: { values<=(-level)
OR values>=(+level)
}. For common use, select appropriate level
and, if necessary, reclassify obj
prior.
Color limits are extracted using range
function.
Raster images can be used for colored shading using alpha
argument of panel_raster
function, e.g. panel_raster(a,alpha=3/4)
NULL
Nikita Platonov [email protected]
session_grid(NULL) if (first.example <- TRUE) { session_grid(NULL) session_grid(regrid(mul=1/8)) ps <- pixelsize() compose_open() ct <- compose_panel() panel_shading(ps>1.1*global_mean(ps),angle=90) compose_legend(ct) compose_close() } if (second.example <- TRUE) { session_grid(NULL) a <- ursa_dummy(nband=15,mul=1/8) b <- local_stat(a) compose_open() lev <- 0.90 d <- as.matrix(b["slopeS"],coords=TRUE) e <- contourLines(d,levels=c(-lev,lev)) p <- list(significance.raw=colorize(b["slopeS"]) ,significance.formatted=colorize(b["slopeS"],stretch="significance") ,slope=colorize(b["slope"])) p <- c(p,rep(p[3],3)) names(p)[c(3,4,5)] <- c("Slope and shaded significance" ,"Slope and contoured significance" ,"Slope and 'contourLines'") compose_open(p,layout=c(2,NA),byrow=FALSE) compose_panel(p[1]) compose_panel(p[2]) compose_panel(p[3]) panel_shading(b["slopeS"],level=lev) compose_panel(p[4]) panel_contour(b["slopeS"],value=c(-lev,lev)) compose_panel(p[5]) lapply(e,panel_polygon) compose_panel(p[6]) ct <- panel_contour(b["slopeS"],"color" ,value=c(-0.99,-0.95,-0.9,-0.5,0.5,0.9,0.95,0.99)) compose_legend(c(head(p,-1),'(Colorbar for contours)'=list(ct)),las=3) compose_close() }
session_grid(NULL) if (first.example <- TRUE) { session_grid(NULL) session_grid(regrid(mul=1/8)) ps <- pixelsize() compose_open() ct <- compose_panel() panel_shading(ps>1.1*global_mean(ps),angle=90) compose_legend(ct) compose_close() } if (second.example <- TRUE) { session_grid(NULL) a <- ursa_dummy(nband=15,mul=1/8) b <- local_stat(a) compose_open() lev <- 0.90 d <- as.matrix(b["slopeS"],coords=TRUE) e <- contourLines(d,levels=c(-lev,lev)) p <- list(significance.raw=colorize(b["slopeS"]) ,significance.formatted=colorize(b["slopeS"],stretch="significance") ,slope=colorize(b["slope"])) p <- c(p,rep(p[3],3)) names(p)[c(3,4,5)] <- c("Slope and shaded significance" ,"Slope and contoured significance" ,"Slope and 'contourLines'") compose_open(p,layout=c(2,NA),byrow=FALSE) compose_panel(p[1]) compose_panel(p[2]) compose_panel(p[3]) panel_shading(b["slopeS"],level=lev) compose_panel(p[4]) panel_contour(b["slopeS"],value=c(-lev,lev)) compose_panel(p[5]) lapply(e,panel_polygon) compose_panel(p[6]) ct <- panel_contour(b["slopeS"],"color" ,value=c(-0.99,-0.95,-0.9,-0.5,0.5,0.9,0.95,0.99)) compose_legend(c(head(p,-1),'(Colorbar for contours)'=list(ct)),las=3) compose_close() }
This function helps to calculate size of pixels in the unit of area (squared km) for zonal statistics with taking into account distortion in area for classes of projections.
pixelsize(obj, verbose = FALSE)
pixelsize(obj, verbose = FALSE)
obj |
Either |
verbose |
Logical. Value |
pixelsize()
is applied to coordinate reference system (grid) of ursaRaster
object or to raster grid directly. If argument obj
is missed, then session grid is used.
Currently, only Stereographic ("+stere"
in PROJ.4 notation), Mercator ("+merc"
), and Lambert Azimuthal Equal Area ("+laea"
) classes of map projections are implemented, though the last one (LAEA) has no distortion in area.
Object of class ursaRaster
, single-band. If size of cell is more than 10e5
square meters, then the unit is squared kilometers (band name is "Pixel Size (sq.km)") else squared meters (band name is "Pixel Size (sq.m)").
Nikita Platonov [email protected]
session_grid(NULL) pixelsize() ## internet connection is required; access was tested on 2018-06-04 invisible({ dpath <- file.path("ftp://sidads.colorado.edu/pub/DATASETS" ,"nsidc0081_nrt_nasateam_seaice/north") dst <- tempfile(fileext=".bin") isOK <- FALSE d3 <- Sys.Date() for (i in seq(5)) { src <- file.path(dpath,format(d3,"nt_%Y%m%d_f18_nrt_n.bin")) a <- try(download.file(src,dst,mode="wb")) if ((is.integer(a))&&(a==0)) { isOK <- TRUE break } d3 <- d3-1 } if (isOK) { g1 <- regrid(bbox=c(-385,-535,375,585)*1e4,res=25*1e3 ,crs=paste("+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45" ,"+k=1 +x_0=0 +y_0=0 +a=6378273 +b=6356889.449" ,"+units=m +no_defs")) session_grid(g1) b <- readBin(dst,integer(),size=1L,n=136492L,signed=FALSE) ice <- ursa_new(value=tail(b,-300)) ice[ice>251] <- NA ## keep Pole ice[ice==251] <- 250 ## consider 100% ice at Pole ice <- ice/2.5 ## uncategorize ice[ice<15] <- 0 ## not ice, if less 15% ice[ice>0] <- 100 extent1 <- band_sum(ice*1e-2*ursa(ice,"cell")^2*1e-6)*1e-6 extent2 <- band_sum(ice*1e-2*pixelsize(ice))*1e-6 message(paste("Near real-time Arctic sea ice extent (NASA Team algorithm, NSIDC)")) message(sprintf(" Direct area calculation: %5.2f*1e6 km^2.",extent1)) message(sprintf(" Distortion in area is corrected: %5.2f*1e6 km^2.",extent2)) } else message("It is failed to get sea ice concentration data.") })
session_grid(NULL) pixelsize() ## internet connection is required; access was tested on 2018-06-04 invisible({ dpath <- file.path("ftp://sidads.colorado.edu/pub/DATASETS" ,"nsidc0081_nrt_nasateam_seaice/north") dst <- tempfile(fileext=".bin") isOK <- FALSE d3 <- Sys.Date() for (i in seq(5)) { src <- file.path(dpath,format(d3,"nt_%Y%m%d_f18_nrt_n.bin")) a <- try(download.file(src,dst,mode="wb")) if ((is.integer(a))&&(a==0)) { isOK <- TRUE break } d3 <- d3-1 } if (isOK) { g1 <- regrid(bbox=c(-385,-535,375,585)*1e4,res=25*1e3 ,crs=paste("+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45" ,"+k=1 +x_0=0 +y_0=0 +a=6378273 +b=6356889.449" ,"+units=m +no_defs")) session_grid(g1) b <- readBin(dst,integer(),size=1L,n=136492L,signed=FALSE) ice <- ursa_new(value=tail(b,-300)) ice[ice>251] <- NA ## keep Pole ice[ice==251] <- 250 ## consider 100% ice at Pole ice <- ice/2.5 ## uncategorize ice[ice<15] <- 0 ## not ice, if less 15% ice[ice>0] <- 100 extent1 <- band_sum(ice*1e-2*ursa(ice,"cell")^2*1e-6)*1e-6 extent2 <- band_sum(ice*1e-2*pixelsize(ice))*1e-6 message(paste("Near real-time Arctic sea ice extent (NASA Team algorithm, NSIDC)")) message(sprintf(" Direct area calculation: %5.2f*1e6 km^2.",extent1)) message(sprintf(" Distortion in area is corrected: %5.2f*1e6 km^2.",extent2)) } else message("It is failed to get sea ice concentration data.") })
Function image
for ursaRaster
object calls generic function image
.
Function plot
for ursaRaster
object calls function filled.contour
.
Color tables are supported.
## S3 method for class 'ursaRaster' plot(x, ...) ## S3 method for class 'ursaRaster' image(x, ...)
## S3 method for class 'ursaRaster' plot(x, ...) ## S3 method for class 'ursaRaster' image(x, ...)
x |
Object of class |
... |
Other parameters. Are passed to or |
Usage of both these functions is justified for low-level control of plotting. It is recommended to use high-level function display
. It is flexible and power instrument for raster images visualization.
Function as.list
for ursaRaster
object transforms single band of raster image to a suitable object for plotting via function image
from package graphics
Returned value from image
or filled.contour
(both functions are in the package graphics)
Nikita Platonov [email protected]
session_grid(NULL) a <- pixelsize() plot(a,asp=1) image(a,asp=1) b <- colorize(a,ncolor=15) plot(b,asp=1) image(b,asp=1)
session_grid(NULL) a <- pixelsize() plot(a,asp=1) image(a,asp=1) b <- colorize(a,ncolor=15) plot(b,asp=1) image(b,asp=1)
Representing each raster cell as a polygon. In comparison to common GIS raster to vector conversion, where neighbor cells with the same value are combined to the single polygon, the number of output polygons is equal to number of non-NA
values.
polygonize(obj, fname, engine = c("native", "sf"), verbose = NA, ...)
polygonize(obj, fname, engine = c("native", "sf"), verbose = NA, ...)
obj |
Object of class |
fname |
Missing or character. If specified, then ESRI Shapefile is created. Default is missing. |
engine |
Character keyword from list |
verbose |
Logical. If |
... |
Additional arguments, which are passed to internal function for writing ESRI Shapefile.
|
Some GIS software (e.g., QGIS) has broad tools for display vector data. Excepting choroplets, it is assumed that visualization of each cell separately is more attractive than displaying of polygons with different forms, which are produced, for example, by GDAL convertion utillity gdal_polygonize.py.
If missing fname
and tools from sp then object of class "SpatialPolygonsDataFrame" (package sp).
If missing fname
and tools from sf then object of class "sf" with geometry of class "sfc_POLYGON" (package sf).
If fname
is specified, then NULL
.
Implementation is very slow even for moderate image size. Use progress bar (verbose=TRUE
) to control this process.
Nikita Platonov [email protected]
session_grid(NULL) a <- ursa_dummy(mul=1/16) a <- a[a>100] print(a) print(band_mean(a)) b2 <- polygonize(a,engine=ifelse(requireNamespace("sp"),"sp","sf")) print(class(b2)) print(colMeans(spatial_data(b2),na.rm=TRUE)) str(e1 <- spatial_bbox(a)) str(e2 <- spatial_bbox(b2)) print(as.numeric(e1)) print(as.numeric(e2))
session_grid(NULL) a <- ursa_dummy(mul=1/16) a <- a[a>100] print(a) print(band_mean(a)) b2 <- polygonize(a,engine=ifelse(requireNamespace("sp"),"sp","sf")) print(class(b2)) print(colMeans(spatial_data(b2),na.rm=TRUE)) str(e1 <- spatial_bbox(a)) str(e2 <- spatial_bbox(b2)) print(as.numeric(e1)) print(as.numeric(e2))
Reads all or several bands of ENVI .hdr Labelled Raster file from disk to memory.
read_envi(fname, ...)
read_envi(fname, ...)
fname |
Character. Filename for ENVI .hdr Labelled Raster file. |
... |
For
|
Function read_envi
is designed to one-time reading (from disk to memory) ENVI .hdr Labelled Raster file. For multiple access to disk (by chunks), use followed construction:
a <- open_envi(fname) d1 <- a[condition_1] d2 <- a[condition_2] ... close(a)
In this case, the connection keeps open. The gain is more effective for compressed binary files.
Object of class ursaRaster
.
Nikita Platonov [email protected]
open_envi
, Extract method [
for ursaRaster
object, close_envi
.
read_gdal
uses GDAL (rgdal) to read ENVI .hdr Labelled Raster file.
session_grid(NULL) fname <- tempfile() a <- ursa_dummy() bandname(a) <- c("first","second","third") write_envi(a,fname,compress=FALSE) print(read_envi(fname)) print(read_envi(fname,c(1,3))) print(read_envi(fname,-c(1,3))) print(read_envi(fname,c("first","third"))) print(read_envi(fname,"iR")) print(session_grid()) g <- regrid(session_grid(),mul=1/2.3) b <- read_envi(fname,ref=g) print(session_grid()) print(b) envi_remove(fname)
session_grid(NULL) fname <- tempfile() a <- ursa_dummy() bandname(a) <- c("first","second","third") write_envi(a,fname,compress=FALSE) print(read_envi(fname)) print(read_envi(fname,c(1,3))) print(read_envi(fname,-c(1,3))) print(read_envi(fname,c("first","third"))) print(read_envi(fname,"iR")) print(session_grid()) g <- regrid(session_grid(),mul=1/2.3) b <- read_envi(fname,ref=g) print(session_grid()) print(b) envi_remove(fname)
read_gdal
creates ursaRaster
object from GDAL supported raster files using functions from packages with low-level raster reading.
read_gdal(fname, resetGrid = TRUE, band = NULL, engine = c("native", "sf"), verbose = FALSE, ...) ursa_read(fname, verbose = FALSE)
read_gdal(fname, resetGrid = TRUE, band = NULL, engine = c("native", "sf"), verbose = FALSE, ...) ursa_read(fname, verbose = FALSE)
fname |
Character. GDAL supported raster file name. |
resetGrid |
Logical. If |
band |
Character (regular expression) or integer. |
engine |
Character. Functionality of which package is used for reading data. This is experimental list, which future depends on evolution of reviewed packages and their availability for partial reading of multiband rasters. |
verbose |
Logical. Value |
... |
Ignored. |
ursa_read
is simplified implementation of gdal_read
.
The composite GDAL formats (e.g., NetCDF: Network Common Data Format, HDF5: Hierarchical Data Format Release 5) are likely unsupported.
read_gdal
uses functions from other other packages. It's a wrapper.
Category names and color tables are supported.
Object of class ursaRaster
.
Nikita Platonov [email protected]
as.ursa
is an alternative call for GDAL raster files import.
session_grid(NULL) # rgdal::gdalDrivers() if (requireNamespace("sf")) print(sf::st_drivers()) if (file.exists(Fin1 <- system.file("gdal/gdalicon.png",package="sf"))) { a1 <- read_gdal(Fin1) print(a1) display(a1) } Fin2 <- tempfile(fileext=".") a <- ursa_dummy(1,resetGrid=TRUE) b <- colorize(a[a>91],stretch="equal",name=format(Sys.Date()+seq(0,6),"%A %d")) write_envi(b,Fin2) b1 <- read_gdal(Fin2) b2 <- read_envi(Fin2,resetGrid=TRUE) envi_remove(Fin2) print(c('same colortable?'=identical(ursa_colortable(b1),ursa_colortable(b2)))) print(ursa_colortable(b1)) print(as.table(b1)) print(c('same values?'=identical(ursa_value(b1),ursa_value(b2)))) print(c('same grid?'=identical(ursa_grid(b1),ursa_grid(b2)))) if (requireNamespace("sf")) { p1 <- sf::st_crs(ursa_crs(b1)) p2 <- sf::st_crs(ursa_crs(b2)) print(c('same proj4string for CRS?'=identical(p1$proj4string,p2$proj4string))) print(c('same WKT for CRS?'=identical(p1$Wkt,p2$Wkt))) ursa_crs(b1) <- ursa_crs(b2) print(c('after same CRS, same grid?'=identical(ursa_grid(b1),ursa_grid(b2)))) } display(b1,detail="l")
session_grid(NULL) # rgdal::gdalDrivers() if (requireNamespace("sf")) print(sf::st_drivers()) if (file.exists(Fin1 <- system.file("gdal/gdalicon.png",package="sf"))) { a1 <- read_gdal(Fin1) print(a1) display(a1) } Fin2 <- tempfile(fileext=".") a <- ursa_dummy(1,resetGrid=TRUE) b <- colorize(a[a>91],stretch="equal",name=format(Sys.Date()+seq(0,6),"%A %d")) write_envi(b,Fin2) b1 <- read_gdal(Fin2) b2 <- read_envi(Fin2,resetGrid=TRUE) envi_remove(Fin2) print(c('same colortable?'=identical(ursa_colortable(b1),ursa_colortable(b2)))) print(ursa_colortable(b1)) print(as.table(b1)) print(c('same values?'=identical(ursa_value(b1),ursa_value(b2)))) print(c('same grid?'=identical(ursa_grid(b1),ursa_grid(b2)))) if (requireNamespace("sf")) { p1 <- sf::st_crs(ursa_crs(b1)) p2 <- sf::st_crs(ursa_crs(b2)) print(c('same proj4string for CRS?'=identical(p1$proj4string,p2$proj4string))) print(c('same WKT for CRS?'=identical(p1$Wkt,p2$Wkt))) ursa_crs(b1) <- ursa_crs(b2) print(c('after same CRS, same grid?'=identical(ursa_grid(b1),ursa_grid(b2)))) } display(b1,detail="l")
This is look-up table reclassification: the destination value is found for each source value.
reclass(obj, dst = NULL, src = NULL, sparse = FALSE, ...)
reclass(obj, dst = NULL, src = NULL, sparse = FALSE, ...)
obj |
Object of class |
dst |
Object of class |
src |
Numerical vector, but allowed using with numerical vector of |
sparse |
Logical. If image has a lot of |
... |
Other arguments are used for classification in the function |
If dst
is numeric vector, then the source value have to be specific, without any ranges. It is required the equality lengths of src
and dst
. If image has color table then function tries reconstruct dst
from names of categories.
This function can be used for data compression for storage, e.g. for distribution or interchange.
If obj
is object of class ursaColorTable
then numeric vector of categories' centers.
If dst
is numeric, then object of class ursaRaster
without color table.
If dst
is ursaColorTable
then object of class ursaRaster
(NA
values) in color table.
If dst
is NULL
then object of class ursaRaster
with empty color names (NA
values) in color table.
There were no a lot of tests how GIS software reads "ENVI .hdr Labelled Raster" files with color tables without color values (only categories). At least, GDAL recognizes categories (gdalinfo
utility).
Nikita Platonov [email protected]
The reclassification from interval source values to specific destination values is used in colorize
.
session_grid(NULL) # example no.1 manual classification a <- as.ursa(round(matrix(runif(100,min=0.5,max=3.5),ncol=10))) print(as.table(a)) b <- reclass(a,src=c(3,1,2),dst=round(runif(3),2)) print(as.table(b)) print(c(src=a,dst=b)) # example no.2 -- similarity to other object session_grid(NULL) a <- ursa_dummy(nband=2,min=-1,max=1) print(a) b1 <- colorize(a[1],value=seq(-1,1,length=21),pal.rich=240,pal.rotate=0) b2 <- reclass(a[2],b1) b3 <- reclass(a[2],ursa_colortable(b2)) b <- c(b1,b2,b3) print(reclass(b)) # example no.3 -- compression with data lost a <- pixelsize(NULL) b <- reclass(a,byte=TRUE,tail=0) ## try 'byte=FALSE' a2 <- reclass(b) res <- c(source=a,as_category=a2,difference=a-a2) print(res) message(paste("RMS error: ",format(sqrt(band_sum(res[3]^2)/band_n(res[3]))))) prefix <- names(res)[1:2] fname <- file.path(tempdir(),paste0(prefix,".envi")) s <- data.frame(object.size=sapply(list(a,b),object.size)) rownames(s) <- prefix print(s) write_envi(a,fname[1]) write_envi(b,fname[2]) f <- file.info(dir(path=tempdir() ,pattern=paste0("(",prefix,")\\.(envi|hdr)",sep="|") ,full.names=TRUE))[,"size",drop=FALSE] colnames(f) <- "file.size" print(f) envi_remove(fname)
session_grid(NULL) # example no.1 manual classification a <- as.ursa(round(matrix(runif(100,min=0.5,max=3.5),ncol=10))) print(as.table(a)) b <- reclass(a,src=c(3,1,2),dst=round(runif(3),2)) print(as.table(b)) print(c(src=a,dst=b)) # example no.2 -- similarity to other object session_grid(NULL) a <- ursa_dummy(nband=2,min=-1,max=1) print(a) b1 <- colorize(a[1],value=seq(-1,1,length=21),pal.rich=240,pal.rotate=0) b2 <- reclass(a[2],b1) b3 <- reclass(a[2],ursa_colortable(b2)) b <- c(b1,b2,b3) print(reclass(b)) # example no.3 -- compression with data lost a <- pixelsize(NULL) b <- reclass(a,byte=TRUE,tail=0) ## try 'byte=FALSE' a2 <- reclass(b) res <- c(source=a,as_category=a2,difference=a-a2) print(res) message(paste("RMS error: ",format(sqrt(band_sum(res[3]^2)/band_n(res[3]))))) prefix <- names(res)[1:2] fname <- file.path(tempdir(),paste0(prefix,".envi")) s <- data.frame(object.size=sapply(list(a,b),object.size)) rownames(s) <- prefix print(s) write_envi(a,fname[1]) write_envi(b,fname[2]) f <- file.info(dir(path=tempdir() ,pattern=paste0("(",prefix,")\\.(envi|hdr)",sep="|") ,full.names=TRUE))[,"size",drop=FALSE] colnames(f) <- "file.size" print(f) envi_remove(fname)
General function to change parameters of cells under the same geographical projection. It is implemented via raster resampling to the new grid.
regrid(x, ...) ## non-public .regrid(grid = NULL, mul = NA, res = NA, resx = NA, resy = NA, setbound = NA, columns = NA, rows = NA, dim = NA, bbox = NA, expand = NA, minx = NA, miny = NA, maxx = NA, maxy = NA, cut = NA, proj4 = NA, crs = NA, border = 0, zero = c("keep", "node", "center"), raster = FALSE, tolerance = NA, zoom = NA, verbose = FALSE, ...)
regrid(x, ...) ## non-public .regrid(grid = NULL, mul = NA, res = NA, resx = NA, resy = NA, setbound = NA, columns = NA, rows = NA, dim = NA, bbox = NA, expand = NA, minx = NA, miny = NA, maxx = NA, maxy = NA, cut = NA, proj4 = NA, crs = NA, border = 0, zero = c("keep", "node", "center"), raster = FALSE, tolerance = NA, zoom = NA, verbose = FALSE, ...)
x |
Object of class |
... |
|
grid |
Reference |
mul |
|
res |
|
resx |
Positive |
resy |
Positive |
setbound |
|
columns |
Positive |
rows |
Positive |
dim |
Positive |
bbox |
|
minx |
|
miny |
|
maxx |
|
maxy |
|
cut |
|
border |
|
proj4 |
|
crs |
|
expand |
|
raster |
|
zero |
|
tolerance |
|
zoom |
|
verbose |
Reporting via |
Generally, argument resample
sets a rectangular region. The area of this region is in proportion to area of output cell. Argument resample
is the value of this proportion. Each cell is interpreted as a set of adjoining rectangular figures. The value of output cells is a weighted mean of that input cells, which fall into rectangular region. The weights are defined as an partial area inside of rectangular region.
Function implements "nearest neighbor" resampling method if argument resample=0
(or, resample=FALSE
). If resample=1
(or, resample=TRUE
) and both input and output rasters have the same cell size, then resampling method is "bilinear interpolation".
Expand raster x
to 3 times with cell repeating: regrid(x,mul=3,resample=FALSE) ## nearest neighbor
;
Expand raster x
to 3 times with cell aggregation: regrid(x,mul=3,resample=TRUE) ## bilinear interpolation
;
Contract raster x
to 3 times without cell aggregation: regrid(x,mul=1/3,resample=FALSE) ## nearest neighbor
;
Contract raster x
to 3 times with cell aggregation: regrid(x,mul=1/3,resample=TRUE) ## weighted mean
;
Low-pass filtering by 3 x 3
window size: regrid(x,resample=3*3) ##
see focal_mean
However, simple contraction regrid(x,mul=1/2,resample=FALSE)
is implemented as contration with aggregation (regrid(x,mul=1/2,resample=FALSE)
), because centers or output cells are located in the nodes (crossing of boundaries of input cells).
It seems that for categorical rasters parameter resample=0
is more suitable, because nearest neigboring does not introduce new values to output raster, excepting coincidence of input cells' nodes and output cell centers.
Usage of proj4
argument specifies only desirable PROJ.4 string and does not do reprojection.
The violation of grid regualarity is due to columns and rows of image should be integer. The restoration of grid regularity is realized by spatial extension (boundary box) expansion.
regrid
returns object of class ursaRaster
.
Return value of non-public function .regrid
depends on logical value of raster
argument. If raster=FALSE
then .regrid
returns new grid without any change of sessional grid. If raster=TRUE
then .regrid
returns blank image and changes sessional grid.
Nikita Platonov [email protected]
session_grid(NULL) print(g1 <- session_grid()) print(g2 <- regrid(g1,mul=2)) print(g3 <- regrid(g1,res=50000,lim=c(-1200000,-1400000,1600000,1800000))) print(g4 <- regrid(g1,res=50000,lim=c(-1200100,-1400900,1600900,1800100),verbose=TRUE)) print(g5 <- regrid(g1,mul=1/4)) print(g6 <- regrid(g1,mul=1/4,cut=c(-1,-2,3,4)*25000)) print(g7 <- regrid(g1,mul=1/4,expand=1.05)) print(session_grid()) ## equal to 'g1' print(a <- regrid(g1,mul=1/4,border=3,raster=TRUE)) print(session_grid()) ## not equal to 'g1' session_grid(NULL) '.makeRaster' <- function(nc=6,nr=8) { as.ursa(t(matrix(runif(nc*nr,min=0,max=255),ncol=nc,nrow=nr))) } session_grid(NULL) a <- .makeRaster(12,18) expand <- 1/3 a1 <- regrid(regrid(a,mul=expand,resample=FALSE),a,resample=FALSE) a2 <- regrid(regrid(a,mul=expand,resample=TRUE),a,resample=FALSE) b <- c('source'=a,'contract'=a1,'aggregation'=a2) print(b) display_brick(b,grid=TRUE ,grid.lon=(seq(ncol(a)*expand+1)-1)/expand ,grid.lat=(seq(nrow(a)*expand+1)-1)/expand) session_grid(NULL) a <- .makeRaster(6,8) expand <- 3 b <- c("source"=regrid(a,mul=expand,resample=FALSE,resetGrid=FALSE) ,"simple"=regrid(a,mul=expand,cascade=TRUE,resetGrid=FALSE) ,"cascaded"=regrid(a,mul=expand,cascade=FALSE,resetGrid=FALSE)) print(b) display_brick(b) session_grid(a) eps <- 1e-4 r <- c(0,expand^(-2)-eps,expand^(-2)+eps,1,expand^0.5 ,(expand+2/3)^2-eps,(expand+2/3)^2+eps,99) g2 <- regrid(mul=expand) session_grid(g2) b <- ursa_new(bandname=sprintf("Resample=%.4f",r)) for (i in seq(b)) b[i] <- regrid(a,g2,resample=r[i]) print(b) display_brick(b,layout=c(2,NA) ,grid=TRUE,grid.lon=seq(ncol(a)+1)-1,grid.lat=seq(nrow(a)+1)-1)
session_grid(NULL) print(g1 <- session_grid()) print(g2 <- regrid(g1,mul=2)) print(g3 <- regrid(g1,res=50000,lim=c(-1200000,-1400000,1600000,1800000))) print(g4 <- regrid(g1,res=50000,lim=c(-1200100,-1400900,1600900,1800100),verbose=TRUE)) print(g5 <- regrid(g1,mul=1/4)) print(g6 <- regrid(g1,mul=1/4,cut=c(-1,-2,3,4)*25000)) print(g7 <- regrid(g1,mul=1/4,expand=1.05)) print(session_grid()) ## equal to 'g1' print(a <- regrid(g1,mul=1/4,border=3,raster=TRUE)) print(session_grid()) ## not equal to 'g1' session_grid(NULL) '.makeRaster' <- function(nc=6,nr=8) { as.ursa(t(matrix(runif(nc*nr,min=0,max=255),ncol=nc,nrow=nr))) } session_grid(NULL) a <- .makeRaster(12,18) expand <- 1/3 a1 <- regrid(regrid(a,mul=expand,resample=FALSE),a,resample=FALSE) a2 <- regrid(regrid(a,mul=expand,resample=TRUE),a,resample=FALSE) b <- c('source'=a,'contract'=a1,'aggregation'=a2) print(b) display_brick(b,grid=TRUE ,grid.lon=(seq(ncol(a)*expand+1)-1)/expand ,grid.lat=(seq(nrow(a)*expand+1)-1)/expand) session_grid(NULL) a <- .makeRaster(6,8) expand <- 3 b <- c("source"=regrid(a,mul=expand,resample=FALSE,resetGrid=FALSE) ,"simple"=regrid(a,mul=expand,cascade=TRUE,resetGrid=FALSE) ,"cascaded"=regrid(a,mul=expand,cascade=FALSE,resetGrid=FALSE)) print(b) display_brick(b) session_grid(a) eps <- 1e-4 r <- c(0,expand^(-2)-eps,expand^(-2)+eps,1,expand^0.5 ,(expand+2/3)^2-eps,(expand+2/3)^2+eps,99) g2 <- regrid(mul=expand) session_grid(g2) b <- ursa_new(bandname=sprintf("Resample=%.4f",r)) for (i in seq(b)) b[i] <- regrid(a,g2,resample=r[i]) print(b) display_brick(b,layout=c(2,NA) ,grid=TRUE,grid.lon=seq(ncol(a)+1)-1,grid.lat=seq(nrow(a)+1)-1)
rep
for object of class ursaRaster
creates new ursaRaster
objects with repitition of original band sequence.
## S3 method for class 'ursaRaster' rep(x, ...)
## S3 method for class 'ursaRaster' rep(x, ...)
x |
Object of class |
... |
Further arguments to be passed to or from other methods. Keywords:
If argument has no name, then |
Object of class ursaRaster
.
Nikita Platonov [email protected]
c
for ursaRaster
.
session_grid(NULL) session_grid(regrid(mul=1/4)) a <- ursa_dummy(nband=3) print(a) b1 <- rep(a,by=2) print(b1) b2 <- rep(a,length=5) print(b2) b3 <- rep(a[3],3) print(b3)
session_grid(NULL) session_grid(regrid(mul=1/4)) a <- ursa_dummy(nband=3) print(a) b1 <- rep(a,by=2) print(b1) b2 <- rep(a,length=5) print(b2) b3 <- rep(a[3],3) print(b3)
This operator is used to set or replace values in portion of bands or lines in ursaRaster
object in memory or data writing to file.
## S3 replacement method for class 'ursaRaster' x[i, j, ...] <- value
## S3 replacement method for class 'ursaRaster' x[i, j, ...] <- value
x |
|
i |
Integer or character. If integer, then band index, specifying bands to replace. If character, either list of band names or character sting for |
j |
Mentioned for consistence with internal generic function |
... |
Mentioned for consistence with internal generic function |
value |
|
Operator \sQuote{[<-}
is high-level implementation for data writing. If x$value
item is not applicable, then value of ursaRaster
is not in memory. In this case the controlled by i
and j
portion is written to file. If both i
and j
are missing, then x[] <- value
writes values to file wholly.
It is not implemented the simultaneously writing to file portion of bands and portion of lines.
Files (currently, ENVI Binary) are opened for reading and writing.
If values of ursaRaster
object are in memory, then modified ursaRaster
object with replaced bands or lines.
If values of ursaRaster
object are not applicable, then ursaRaster
object as is.
Nikita Platonov [email protected]
session_grid(NULL) ## Prepare session_grid(regrid(mul=1/4)) a <- pixelsize() w <- c("first","second","third","fourth","fifth","sixth") b1 <- rep(a/mean(a),length(w))+seq(length(w))-1 bandname(b1) <- w nr <- ursa_rows(b1) bottom <- (as.integer(nr/2)):nr write_envi(b1,"tmp1",compress=FALSE,interleave="bil") b2 <- b1 print(b1) ## Replace b2[1] <- 10+b1["second"] b2[2] <- 20 try({ data(volcano) b2[3] <- 30+volcano }) ## error: unable to coerce b2["fourth"] <- 40+as.matrix(b1[3]) b2[5] <- 50+as.array(b1[4]) set.seed(352) try(b2["six"] <- 60+6+runif(5,min=-1,max=1)) ## Data structures mismatching print(b2) print(object.size(b2)) ## Write b3 <- create_envi(b2,"tmp2") print(object.size(b3)) for (i in chunk_line(b3,0.04)) { b3[,i] <- b2[,i]+100 if (5 %in% i) print(object.size(b3)) } close(b3) print(object.size(b3)) b4 <- read_envi("tmp2") print(b4) envi_remove("tmp[12]")
session_grid(NULL) ## Prepare session_grid(regrid(mul=1/4)) a <- pixelsize() w <- c("first","second","third","fourth","fifth","sixth") b1 <- rep(a/mean(a),length(w))+seq(length(w))-1 bandname(b1) <- w nr <- ursa_rows(b1) bottom <- (as.integer(nr/2)):nr write_envi(b1,"tmp1",compress=FALSE,interleave="bil") b2 <- b1 print(b1) ## Replace b2[1] <- 10+b1["second"] b2[2] <- 20 try({ data(volcano) b2[3] <- 30+volcano }) ## error: unable to coerce b2["fourth"] <- 40+as.matrix(b1[3]) b2[5] <- 50+as.array(b1[4]) set.seed(352) try(b2["six"] <- 60+6+runif(5,min=-1,max=1)) ## Data structures mismatching print(b2) print(object.size(b2)) ## Write b3 <- create_envi(b2,"tmp2") print(object.size(b3)) for (i in chunk_line(b3,0.04)) { b3[,i] <- b2[,i]+100 if (5 %in% i) print(object.size(b3)) } close(b3) print(object.size(b3)) b4 <- read_envi("tmp2") print(b4) envi_remove("tmp[12]")
Set of functions to generate regular sequences of bands, x-/y-cordinates and columns/rows.
## S3 method for class 'ursaRaster' seq(...) ## S3 method for class 'ursaGrid' seq(...) ursa_seqx(obj) ursa_seqy(obj) ursa_seqc(obj) ursa_seqr(obj)
## S3 method for class 'ursaRaster' seq(...) ## S3 method for class 'ursaGrid' seq(...) ursa_seqx(obj) ursa_seqy(obj) ursa_seqc(obj) ursa_seqr(obj)
... |
Set of arguments, which are recognized via their names (using regular expressions), position and classes.
|
obj |
Object of classes |
All ordinal sequences (axis
is \dQuote{c}
, \dQuote{r}
, \dQuote{z}
) start from 1L
.
axis=\dQuote{z}
is ignored in the function seq
for ursaGrid
object. The returned value is 1L
.
seq(obj)
for ursaRaster
objects is suitable for using in cycles across bands.
Functions ursa_seqx
and seq(obj, "x")
return x-coordinates of cell midpoints.
Functions ursa_seqy
and seq(obj, "y")
return y-coordinates of cell midpoints.
Functions ursa_seqc
, seq(obj, "samples")
and seq(obj, "c")
return sequence of cells in horizontal direction.
Functions ursa_seqr
, seq(obj, "lines")
and seq(obj, "r")
return sequence of cells in vertical direction.
Functions seq(obj)
and seq(obj, "z")
for ursaRaster
object returns sequence of bands.
Function seq(obj)
and seq(obj, "z")
for ursaGrid
object returns 1L
.
Nikita Platonov [email protected]
session_grid(NULL) session_grid(regrid(mul=1/16)) print(session_grid()) a <- ursa_dummy(nband=5) print(a) print(seq(a)) print(seq(a,"c")) print(seq(a,"x")) print(ursa_seqx())
session_grid(NULL) session_grid(regrid(mul=1/16)) print(session_grid()) a <- ursa_dummy(nband=5) print(a) print(seq(a)) print(seq(a,"c")) print(seq(a,"x")) print(ursa_seqx())
session_grid
without arguments returns current grid properties. session_grid
with arguments specifies grid, which is used by functions of this package, e.g., for plotting, for opened and created raster images during current session.
session_pngviwer
is used to permit external software to open PNG files.
session_tempdir
specifies directory for temporal files in some cases.
session_use_experimental_functions
allows to use undocumented (experimental) functions.
Group of functions session_proj4
, session_crs
, session_cellsize
, session_bbox
extracts certain properties of sessional grid.
session_grid(obj, ...) session_proj4() session_crs() session_cellsize() session_bbox() session_dim() session_pngviewer(allow = NA) session_tempdir(dst = character()) session_use_experimental_functions()
session_grid(obj, ...) session_proj4() session_crs() session_cellsize() session_bbox() session_dim() session_pngviewer(allow = NA) session_tempdir(dst = character()) session_use_experimental_functions()
obj |
Either missing, or |
allow |
Logical. If |
dst |
Character. Directory name for temporal files. Empty character or non-character is interpreted as |
... |
Optional arguments passing to |
session_grid
deals with option “ursaSessionGrid”: options(ursaSessionGrid=...)
or getOption("ursaSessionGrid")
.
Usage session_grid()
without arguments return value of “ursaSessionGrid” option via calling getOption("ursaSessionGrid")
. If is.null(getOption("ursaSessionGrid"))
then session_grid()
returns default CRS.
Usage session_grid(NULL)
resets “ursaSessionGrid” option via calling options(ursaSessionGrid=NULL)
.
The sequential calling
session_grid(NULL) session_grid()
returns default CRS. For checking that the option has been reset successfully, use getOption("ursaSessionGrid")
after session_grid(NULL)
session_proj4
and session_crs
are synonyms.
Object of class ursaGrid
. It is a list.
Default values are grid parameters of NSIDC polar stereo gridded data of Northern hemispere with nominal gridded resolution 25 km.
List of 9 $ columns: int 304 $ rows : int 448 $ resx : num 25000 $ resy : num 25000 $ minx : num -3850000 $ maxx : num 3750000 $ miny : num -5350000 $ maxy : num 5850000 $ proj4 : chr "+proj=stere +lat_0=90 +lat_ts=70.0 +lon_0=-45.0 +k=1 +x_0=0.0 +y_0=0.0 +a=6378273.000 +b=6356889.449 +units=m +no_defs" - attr(*, "class")= chr "ursaGrid" NULL
session_proj4
and session_crs
return item proj4
.
session_cellsize
returns squared root from multiplication of cell dimension: sqrt(resx*resy)
.
session_pngviewer
returns value of getOption("ursaAllowPngViewer")
.
session_bbox
returns named numeric of length 4: minimal x-coodrinate (xmin
), minimal y-coordinate (ymin
), maximal x-coordinate (xmax
), maximal y-coordinate (ymax
).
session_dim
returns named integer of length 2: number of rows (lines
) and number of columns (samples
).
session_use_experimental_functions
added some non-public functions to current namespaces and returns invisile list of function names.
Nikita Platonov [email protected]
Class ursaGrid
. Use regrid
to partial grid changing.
session_grid(NULL) getOption("ursaSessionGrid") ## NULL (g1 <- session_grid()) ## default g1$resx <- g1$resy <- 12500 g1$columns <- as.integer(with(g1,(maxx-minx)/resx)) g1$rows <- as.integer(with(g1,(maxy-miny)/resy)) session_grid(g1) session_grid(NULL) a <- ursa_new(value=3) session_grid(a) print(session_pngviewer())
session_grid(NULL) getOption("ursaSessionGrid") ## NULL (g1 <- session_grid()) ## default g1$resx <- g1$resy <- 12500 g1$columns <- as.integer(with(g1,(maxx-minx)/resx)) g1$rows <- as.integer(with(g1,(maxy-miny)/resy)) session_grid(g1) session_grid(NULL) a <- ursa_new(value=3) session_grid(a) print(session_pngviewer())
Changing order of bands based on sorting of band names.
## S3 method for class 'ursaRaster' sort(x, decreasing = FALSE, ...)
## S3 method for class 'ursaRaster' sort(x, decreasing = FALSE, ...)
x |
Object of class |
decreasing |
Logical. Should the sort be increasing or decreasing? Not available for partial sorting. Default is |
... |
Other arguments, which are passed to S3 method for sorting characters. |
Function sort()
for ursaRaster
assumes bands reordering based on character band names.
Object of class ursaRaster
Nikita Platonov [email protected]
a <- ursa_dummy(nband=7L) a sort(a) sort(a,decreasing=TRUE)
a <- ursa_dummy(nband=7L) a sort(a) sort(a,decreasing=TRUE)
These wrappers return iniform properties or do consimilar manipulations for spatial objects of different types: simple features (package sf) and abstract class Spatial (package sp). Appropriate functionality (“engine”) of respective packages is used.
spatial_engine(obj, verbose = FALSE) spatial_crs(obj, verbose = FALSE) spatial_proj(obj, verbose = FALSE) spatial_proj4(obj, verbose = FALSE) spatial_crs(obj, verbose = FALSE) <- value spatial_proj(obj, verbose = FALSE) <- value spatial_proj4(obj, verbose = FALSE) <- value spatial_bbox(obj, verbose = FALSE) spatial_bbox(obj, verbose = FALSE) <- value spatial_data(obj, subset= ".+", drop = NA, verbose = FALSE) spatial_data(obj, verbose = FALSE) <- value spatial_geometry(obj, verbose = FALSE) spatial_geometry(obj, verbose = FALSE) <- value spatial_geotype(obj, each = FALSE, verbose = FALSE) spatial_shape(obj, each = FALSE, verbose = FALSE) spatial_transform(obj, crs, verbose = FALSE, ...) spatial_coordinates(obj, verbose = FALSE) spatial_centroid(obj, verbose = FALSE) spatial_fields(obj, verbose = FALSE) spatial_colnames(obj, verbose = FALSE) spatial_fields(obj, verbose = FALSE) <- value spatial_colnames(obj, verbose = FALSE) <- value spatial_area(obj, verbose = FALSE) spatial_dim(obj, verbose = FALSE) spatial_count(obj, verbose = FALSE) spatial_nrow(obj, verbose = FALSE) spatial_ncol(obj, verbose = FALSE) spatial_filelist(path = ".", pattern = NA, full.names = TRUE, recursive = FALSE, ignore.case = TRUE) spatial_dir(path = ".", pattern = NA, full.names = TRUE, recursive = FALSE, ignore.case = TRUE) spatial_basename(fname) spatial_pattern(fname) is_spatial(obj, verbose = FALSE) is_spatial_points(obj, verbose = FALSE) is_spatial_lines(obj, verbose = FALSE) is_spatial_polygons(obj, verbose = FALSE) spatial_intersection(x, y, geometry=c("default", "polygons", "lines", "points", "all"), verbose = FALSE) spatial_symdifference(x, y, verbose = FALSE) spatial_difference(x, y, verbose = FALSE) spatial_union(x, y, byid=NA, verbose = FALSE) spatial_crop(x, y) spatial_buffer(obj, dist = 0, quadsegs = 30L, verbose = FALSE) spatial_trim(obj) spatial_valid(obj, each = FALSE, reason = FALSE, verbose = FALSE) spatial_grid(obj) spatial_bind(...)
spatial_engine(obj, verbose = FALSE) spatial_crs(obj, verbose = FALSE) spatial_proj(obj, verbose = FALSE) spatial_proj4(obj, verbose = FALSE) spatial_crs(obj, verbose = FALSE) <- value spatial_proj(obj, verbose = FALSE) <- value spatial_proj4(obj, verbose = FALSE) <- value spatial_bbox(obj, verbose = FALSE) spatial_bbox(obj, verbose = FALSE) <- value spatial_data(obj, subset= ".+", drop = NA, verbose = FALSE) spatial_data(obj, verbose = FALSE) <- value spatial_geometry(obj, verbose = FALSE) spatial_geometry(obj, verbose = FALSE) <- value spatial_geotype(obj, each = FALSE, verbose = FALSE) spatial_shape(obj, each = FALSE, verbose = FALSE) spatial_transform(obj, crs, verbose = FALSE, ...) spatial_coordinates(obj, verbose = FALSE) spatial_centroid(obj, verbose = FALSE) spatial_fields(obj, verbose = FALSE) spatial_colnames(obj, verbose = FALSE) spatial_fields(obj, verbose = FALSE) <- value spatial_colnames(obj, verbose = FALSE) <- value spatial_area(obj, verbose = FALSE) spatial_dim(obj, verbose = FALSE) spatial_count(obj, verbose = FALSE) spatial_nrow(obj, verbose = FALSE) spatial_ncol(obj, verbose = FALSE) spatial_filelist(path = ".", pattern = NA, full.names = TRUE, recursive = FALSE, ignore.case = TRUE) spatial_dir(path = ".", pattern = NA, full.names = TRUE, recursive = FALSE, ignore.case = TRUE) spatial_basename(fname) spatial_pattern(fname) is_spatial(obj, verbose = FALSE) is_spatial_points(obj, verbose = FALSE) is_spatial_lines(obj, verbose = FALSE) is_spatial_polygons(obj, verbose = FALSE) spatial_intersection(x, y, geometry=c("default", "polygons", "lines", "points", "all"), verbose = FALSE) spatial_symdifference(x, y, verbose = FALSE) spatial_difference(x, y, verbose = FALSE) spatial_union(x, y, byid=NA, verbose = FALSE) spatial_crop(x, y) spatial_buffer(obj, dist = 0, quadsegs = 30L, verbose = FALSE) spatial_trim(obj) spatial_valid(obj, each = FALSE, reason = FALSE, verbose = FALSE) spatial_grid(obj) spatial_bind(...)
obj |
Simple feature (package sf) or Spatial abstract class (package sp) for all functions, excepting |
x , y
|
Objects of simple feature (package sf) class or Spatial abstract class (package sp). Spatial abstracts are not applicable for |
crs |
Projection EPSG code or projection PROJ.4 string. |
subset |
Pattern to field names (colnames) of attribute table (data frame) for subbsetting using |
drop |
Logical. Dropping column of data frame. If |
value |
Value for property assignment in replacement functions. Either numeric EPSG code or character PROJ.4 string for |
path |
See description of argument |
pattern |
See description of argument |
full.names |
See description of argument |
recursive |
See description of argument |
ignore.case |
See description of argument |
quadsegs |
Integer. Number of segments per quadrant (fourth of a circle), for all or per-feature. See description
for |
dist |
Numeric. Buffer distance for all, or for each of the elements. See description
for |
byid |
Logical. For |
fname |
Character. Filename (source or packed) of spatial data. |
each |
Logical. Whether result will be returned for each record ( |
geometry |
Character. Desired output geometry for |
reason |
Logical. If |
verbose |
Logical. Value |
... |
1) Spatial objects for function |
spatial_engine
returns package name (character string "sf"
or "sp"
), which functionality is used for manipulation with spatial object obj
.
spatial_crs
and spatial_proj4
are synonyms, The Extract functions return projection string in the PROJ.4 notation; the Replace functions change projection property of the object.
spatial_bbox
(Extract function) returns numeric vector of length 4 with names "xmin", "ymin", "xmax" and "ymax".
spatial_bbox<-
(Replace function) assigns boundary bbox to the object; it is valid only for objects of Spatial abstract class (package sp).
spatial_data
(Extract function) returns attribute table only, without geometry. Subsetting fields can be specified by argument subset
using regular expressions. If drop=TRUE
and selected single column then vector is returned instead of data frame.
spatial_data<-
(Replace function) adds spatial data to the object geomerty. Source data (if presents) are droped.
spatial_geometry
(Extract function) returns only geometry, which format is depended on class of obj
.
spatial_geometry<-
(Replace function) addes geometry to the object.
spatial_transform
does a transformation of spatial coordinates to the new CRS and returns object of the same class as class of obj
.
spatial_geotype
and spatial_shape
are synonyms; each returns type of spatial data: "POINT", "LINESTRING", "POLYGON", "MULTIPOLYGON", ....
spatial_coordinates
returns simplified matrix or list of coordinates of original object.
Extract functions spatial_fields
and spatial_columns
return column names of spatial attributive table. spatial_columns
is synonym to spatial_fields
.
Replace functions spatial_fields<-
and spatial_columns<-
change column names of spatial attributive table. spatial_columns<-
is synonym to spatial_fields<-
.
spatial_area
is valid for polygonal geometry. It returns area of polygons.
spatial_length
is valid for linear geometry. It returns length of lines.
spatial_dim
gets dimension of spatial coordinates; it returns either 2L
(XY) or 3L
(XYZ).
spatial_count
returns number of items of object geometry.
spatial_nrow
and spatial_ncol
return number of rows and number of columns of attributive table.
spatial_filelist
and its synonym spatial_dir
return list of files with file extensions, which are associated with certain GIS vector formats. The function's basis is dir
.
spatial_basename
returns basename (without extension) of file fname
of spatial object.
spatial_pattern
returns pattern of spatial_basename
for using in regular expressions.
is_spatial
returns logical value does the object belong to the class of spatial data.
is_spatial_points
returns logical value does the object have point geometry.
is_spatial_lines
returns logical value does the object have (multi)linestring geometry.
is_spatial_polygons
returns logical value does the object have (multi)polygonal geometry.
spatial_intersection
returns intersection of two spatial objects.
spatial_difference
returns difference of two spatial objects.
spatial_symdifference
returns symmetric difference of two spatial objects.
spatial_buffer
returns buffered spatial object.
spatial_union
returns combined geometry without internal boundaries.
spatial_crop
returns cropped geometry of first spatial object by second spatial object of boundary box derived from spatial object.
spatial_trim
returns spatial object without extra attributes added by ursa package.
spatial_grid
generates suitable spatial grid from input vector and returns object of class ursaGrid
.
spatial_centroid
returns spatial centroid.
spatial_bind
returns spatial object concatenated from input spatial objects.
The great improvement for development of functions for manipulation with spatial objects has been reached during work in series of projects (2015-2018) for design of marine protected areas in the Arctic.
Nikita Platonov [email protected]
Classes and methods in packages sf and sp help.
session_grid(NULL) n <- 1e2 x <- runif(n,min=25,max=65) y <- runif(n,min=55,max=65) z <- runif(n,min=1,max=10) da <- data.frame(x=x,y=y,z=z) if (requireNamespace("sp")) { da.sp <- da sp::coordinates(da.sp) <- ~x+y sp::proj4string(da.sp) <- "+init=epsg:4326" print(spatial_bbox(da.sp)) print(spatial_crs(da.sp)) } if (requireNamespace("sf")) { da.sf <- sf::st_as_sf(da,coords=c("x","y"),crs=4326) print(spatial_bbox(da.sf)) print(spatial_crs(da.sf)) }
session_grid(NULL) n <- 1e2 x <- runif(n,min=25,max=65) y <- runif(n,min=55,max=65) z <- runif(n,min=1,max=10) da <- data.frame(x=x,y=y,z=z) if (requireNamespace("sp")) { da.sp <- da sp::coordinates(da.sp) <- ~x+y sp::proj4string(da.sp) <- "+init=epsg:4326" print(spatial_bbox(da.sp)) print(spatial_crs(da.sp)) } if (requireNamespace("sf")) { da.sf <- sf::st_as_sf(da,coords=c("x","y"),crs=4326) print(spatial_bbox(da.sf)) print(spatial_crs(da.sf)) }
Contour (levels after kernel utilization distribution, isochrones and other isolines) polygonizations produces set of polygon layers, which geometry is overlapped. Plot of such polygons may cause the invisibility the less polygon behind the larger polygon. This function makes consequent geometries. Simplifuied, concentrated circles are dropped to non-overlapped rings.
spatial_levelsplit(obj, sep = " - ")
spatial_levelsplit(obj, sep = " - ")
obj |
Spatial object, either simple features (package sf) or abstract class Spatial (package sp) |
sep |
Separator between concatenation of two values |
Spatial object, which class is the same as class of obj
.
Nikita Platonov [email protected]
palette("Set3") radius <- seq(1,length.out=5,by=1)*200 ct <- ursa_colortable(colorize(radius,alpha=0.5,pal=sample(palette(),length(radius)))) origin <- sf::st_sfc(sf::st_point(c(lon=139.2,lat=36.6)),crs=4326) origin <- spatial_transform(origin,"EPSG:6671") isopoly <- do.call(spatial_bind,lapply(radius*1e3,function(r) spatial_buffer(origin,r))) spatial_data(isopoly) <- data.frame(radius=radius) isointerval <- spatial_levelsplit(isopoly) isointerval$radius ct2 <- ursa_colortable(colorize(isointerval$radius,pal=unname(ct))) session_grid(isopoly,border=20) compose_open(2,legend=list("left","right")) compose_panel(isopoly,col=ct ,annotation.text="Semi-transparent colors are overlapped") compose_panel(isointerval,col=ct2 ,annotation.text="Not overlapped rings") compose_legend(list(ct,ct2)) compose_close()
palette("Set3") radius <- seq(1,length.out=5,by=1)*200 ct <- ursa_colortable(colorize(radius,alpha=0.5,pal=sample(palette(),length(radius)))) origin <- sf::st_sfc(sf::st_point(c(lon=139.2,lat=36.6)),crs=4326) origin <- spatial_transform(origin,"EPSG:6671") isopoly <- do.call(spatial_bind,lapply(radius*1e3,function(r) spatial_buffer(origin,r))) spatial_data(isopoly) <- data.frame(radius=radius) isointerval <- spatial_levelsplit(isopoly) isointerval$radius ct2 <- ursa_colortable(colorize(isointerval$radius,pal=unname(ct))) session_grid(isopoly,border=20) compose_open(2,legend=list("left","right")) compose_panel(isopoly,col=ct ,annotation.text="Semi-transparent colors are overlapped") compose_panel(isointerval,col=ct2 ,annotation.text="Not overlapped rings") compose_legend(list(ct,ct2)) compose_close()
Read either simple features (package sf) from disk using appropriate functionality (“engine”) of respective packages is used.
spatial_read(dsn, engine = c("native", "sf"))
spatial_read(dsn, engine = c("native", "sf"))
dsn |
Character. File name of spatial object (vector GIS). |
engine |
Character. Functionality of which package is used for reading data. If value is |
Currently, list of arguments of this funtion is simplified and can be expanded.
Depending of used engine, either simple features (package sf) or Spatial abstracts (sp).
For GeoJSON files in the case engine="geojsonsf"
reading is faster and the order of fields can be rearranged.
Nikita Platonov [email protected]
session_grid(NULL) n <- 1e2 x <- runif(n,min=25,max=65) y <- runif(n,min=55,max=65) z <- runif(n,min=1,max=10) da <- data.frame(x=x,y=y,z=z) if (requireNamespace("sf",quietly=TRUE)) { obj1 <- sf::st_as_sf(da,coords=c("x","y"),crs=4326) print(series(obj1)) fname1 <- file.path(tempdir(),"res1.shp") print(fname1) spatial_write(obj1,fname1) res1 <- spatial_read(fname1,engine="sf") print(series(res1)) } print(spatial_dir(tempdir()))
session_grid(NULL) n <- 1e2 x <- runif(n,min=25,max=65) y <- runif(n,min=55,max=65) z <- runif(n,min=1,max=10) da <- data.frame(x=x,y=y,z=z) if (requireNamespace("sf",quietly=TRUE)) { obj1 <- sf::st_as_sf(da,coords=c("x","y"),crs=4326) print(series(obj1)) fname1 <- file.path(tempdir(),"res1.shp") print(fname1) spatial_write(obj1,fname1) res1 <- spatial_read(fname1,engine="sf") print(series(res1)) } print(spatial_dir(tempdir()))
Write spatial object to disk. If spatial object is Simple Features, then appropriate functions from package sf are used. If spatial objest are abstract of class Spatial (package sp) then preliminarly transformation to Simple Features is performed.
spatial_write(obj, fname, layer, driver = NA, compress = "", verbose = FALSE)
spatial_write(obj, fname, layer, driver = NA, compress = "", verbose = FALSE)
obj |
Spatial object: Either Simple Features (sf) or Spatial Abstract (sp). List of spatial objects can be used. |
fname |
Character. File name with or without extension. If extension is missed, then argument |
layer |
Character. Layer name. If missed, then basename of |
driver |
Character. Driver for specification of output file format. Default is |
compress |
Character or logical. Will output file or list of files be packed after writing and what archive format will be used. Available character values are |
verbose |
Logical. Value |
Based on sf::st_write
function with additonal options: compressing of output file(s), coordinates trasforming (to longitudes and latitudes for driver="GeoJSON"
), creating multi-layer destination (for driver="SQLite"
).
invisible NULL
.
Nikita Platonov [email protected]
session_grid(NULL) n <- 1e2 x <- runif(n,min=25,max=65) y <- runif(n,min=55,max=65) z <- runif(n,min=1,max=10) da <- data.frame(x=x,y=y,z=z) if (requireNamespace("sf",quietly=TRUE)) { obj1 <- sf::st_as_sf(da,coords=c("x","y"),crs=4326) print(series(obj1)) fname1 <- file.path(tempdir(),"res1.shp") print(fname1) spatial_write(obj1,fname1) res1 <- spatial_read(fname1,engine="sf") print(series(res1)) } print(spatial_dir(tempdir()))
session_grid(NULL) n <- 1e2 x <- runif(n,min=25,max=65) y <- runif(n,min=55,max=65) z <- runif(n,min=1,max=10) da <- data.frame(x=x,y=y,z=z) if (requireNamespace("sf",quietly=TRUE)) { obj1 <- sf::st_as_sf(da,coords=c("x","y"),crs=4326) print(series(obj1)) fname1 <- file.path(tempdir(),"res1.shp") print(fname1) spatial_write(obj1,fname1) res1 <- spatial_read(fname1,engine="sf") print(series(res1)) } print(spatial_dir(tempdir()))
Function summary
for ursaRaster
object produces summaries for each band.
Function summary
for ursaValue
object produces summaries for all values of raster image regardless of bands.
## S3 method for class 'ursaRaster' summary(object, ...) ## S3 method for class 'ursaNumeric' summary(object, ...) ## S3 method for class 'ursaCategory' summary(object, ...)
## S3 method for class 'ursaRaster' summary(object, ...) ## S3 method for class 'ursaNumeric' summary(object, ...) ## S3 method for class 'ursaCategory' summary(object, ...)
object |
Object of classes |
... |
Additional arguments affecting the summary produced. |
summary
for ursaRaster
object applies summary
to each column of two-dimensions value matrix and collating the results.
summary
for ursaValue
object drops dimensions and applies summary
to a vector.
summary
for ursaRaster
object returns value of function summary.matrix
.
summary
for ursaValue
object returns object of class \dQuote{summaryDefault}
.
Nikita Platonov [email protected]
summary
in package base.
session_grid(NULL) session_grid(regrid(mul=1/4)) a <- ursa_dummy(nband=3) print(summary(a)) print(summary(ursa_value(a))) print(a)
session_grid(NULL) session_grid(regrid(mul=1/4)) a <- ursa_dummy(nband=3) print(summary(a)) print(summary(ursa_value(a))) print(a)
temporal_interpolate
is applicable for multiband raster image, where bands are regular timestamps or period. For each cell (local operation of map algebra), NA
value is replaced by averaging of two closest values (one value before, one value later) inside of moving window.
temporal_interpolate(obj, win = 7, cover = 0, verbose = FALSE)
temporal_interpolate(obj, win = 7, cover = 0, verbose = FALSE)
obj |
Object of class |
win |
Positive integer. Size of moving window. Required odd value; otherwise is coerced to the closest odd integer. |
cover |
Not applicable. For consistence call with |
verbose |
Logical. |
Function uses weighted averaging depending of proximity of found non-NA
values. For example, if ind
is temporal index of NA
value in the center of movind window, indL=ind-2
is temporal index of the closest early value valL
, and indR=ind+1
is temporal index of the closest late value valR
, then result is val <- (1/3) * valL + (2/3) * valR
.
ursaRaster
object, if obj
is object of class ursaRaster
.
matrix
object, if obj
is a matrix.
Nikita Platonov [email protected]
session_grid(NULL) n <- 45 # bands m <- 3 # sample size k <- median(seq(n))+seq(m)-(m %/% 2)-1 ## sample subset s <- 5 # window size a <- round(ursa_dummy(n,min=-60,max=60,elements=15,mul=1/8)) a[a<(-40)] <- NA b <- temporal_interpolate(a,7) p1 <- colorize(a,lazy=TRUE) p2 <- colorize(b,lazy=TRUE,colortable=p1) display(list('Source'=p1[k],'Gaps are filled'=p2[k]),layout=c(2,NA) ,legend=list(list(1,"right"),list(2,"right")),decor=FALSE)
session_grid(NULL) n <- 45 # bands m <- 3 # sample size k <- median(seq(n))+seq(m)-(m %/% 2)-1 ## sample subset s <- 5 # window size a <- round(ursa_dummy(n,min=-60,max=60,elements=15,mul=1/8)) a[a<(-40)] <- NA b <- temporal_interpolate(a,7) p1 <- colorize(a,lazy=TRUE) p2 <- colorize(b,lazy=TRUE,colortable=p1) display(list('Source'=p1[k],'Gaps are filled'=p2[k]),layout=c(2,NA) ,legend=list(list(1,"right"),list(2,"right")),decor=FALSE)
temporal_mean
is applicable for multiband raster image, where bands are regular timestamps or period. For each cell (local operation of map algebra), the values are averaged using moving window.
temporal_mean(obj, win = 7, cover = 0, verbose = FALSE)
temporal_mean(obj, win = 7, cover = 0, verbose = FALSE)
obj |
Object of class |
win |
Positive integer. Size of moving window. Required odd value; otherwise is coerced to the closest odd integer. |
cover |
Numeric in the interval |
verbose |
Logical. |
temporal_mean
is similar to function runmean(x=obj, k=win, endrule="mean")
from package caTools.
ursaRaster
object, if obj
is object of class ursaRaster
.
matrix
object, if obj
is a matrix.
temporal_mean
is only smoothing of time-series. For time-series analysis and processing it is suggested to apply lower-level approach.
as.matrix
(for ursaRaster
object with argument coords=FALSE
) or ursa_value
return matrix with spatial component by rows and temporal component by columns. It is possible to use apply
with argument MARGIN=1
to this matrix. If apply
returns matrix Y
, then this matrix can be coerced to ursaRaster
object by calling as.ursa
with argument t(Y)
.
X <- as.matrix(obj) Y <- apply(X, 1, function(x) {y <- do_something_return_matrix(x); y}) res <- as.ursa(t(Y))
For example, package caTools provides some functions for manipulation with moving window.
Nikita Platonov [email protected]
Package caTools https://CRAN.R-project.org/package=caTools
caTools::runmean
(click if package caTools is installed)
session_grid(NULL) set.seed(352) n <- 45 # bands m <- 3 # sample size k <- median(seq(n))+seq(m)-(m %/% 2)-1 ## sample subset s <- 5 # window size a <- round(ursa_dummy(n,min=-60,max=60,elements=15,mul=1/8)) ## namespace of package 'caTools' is required if (requireNamespace("caTools")) { b1 <- as.ursa(t(apply(as.matrix(a),1,caTools::runmean,k=s,endrule="mean"))) b2 <- temporal_mean(a,s) print(b1[k]) print(b2[k]) print(c('identical?'=all.equal(ursa_value(b1),ursa_value(b2)))) } a[a<(-40)] <- NA va <- as.matrix(a) # or 'ursa_value(a)' b3 <- temporal_mean(a,s,cover=3/4,verbose=TRUE) b4 <- as.ursa(temporal_mean(as.matrix(va),s,cover=3/4,verbose=TRUE)) p <- list('Before moving window'=a[k] ,'After moving window'=b3[k] ,'\'temporal_mean\' to matrix'=b4[k]) print(p) print(c('identical?'=all.equal(ursa_value(b3),ursa_value(b4)))) display(p[1:2],legend=list(list(1,"right"),list(2,"right")),decor=FALSE)
session_grid(NULL) set.seed(352) n <- 45 # bands m <- 3 # sample size k <- median(seq(n))+seq(m)-(m %/% 2)-1 ## sample subset s <- 5 # window size a <- round(ursa_dummy(n,min=-60,max=60,elements=15,mul=1/8)) ## namespace of package 'caTools' is required if (requireNamespace("caTools")) { b1 <- as.ursa(t(apply(as.matrix(a),1,caTools::runmean,k=s,endrule="mean"))) b2 <- temporal_mean(a,s) print(b1[k]) print(b2[k]) print(c('identical?'=all.equal(ursa_value(b1),ursa_value(b2)))) } a[a<(-40)] <- NA va <- as.matrix(a) # or 'ursa_value(a)' b3 <- temporal_mean(a,s,cover=3/4,verbose=TRUE) b4 <- as.ursa(temporal_mean(as.matrix(va),s,cover=3/4,verbose=TRUE)) p <- list('Before moving window'=a[k] ,'After moving window'=b3[k] ,'\'temporal_mean\' to matrix'=b4[k]) print(p) print(c('identical?'=all.equal(ursa_value(b3),ursa_value(b4)))) display(p[1:2],legend=list(list(1,"right"),list(2,"right")),decor=FALSE)
Connect sequence of points (locations) by direct lines (tracks)
trackline(obj, by=NULL, connect=c("united", "consequent"))
trackline(obj, by=NULL, connect=c("united", "consequent"))
obj |
Simple feature (package sf) or Spatial abstract class (package sp) with POINTS spatial geometry. |
by |
Either field name or |
connect |
Structure of output segments; either sequence of single segments ( |
Function generates n-1
segments from n
input points. Data (attribute table) is trasfered to output object with excluding of first row.
Simple feature (package sf) or Spatial abstract class (package sp) with LINESTRING spatial geometry.
Nikita Platonov [email protected]
session_grid(NULL) n <- 15 lon <- rev(sort(runif(n,min=40,max=60))) lat <- sort(runif(n,min=30,max=50)) pt <- data.frame(lon=lon,lat=lat,value=seq(n)) if (requireNamespace("sp")) { sp::coordinates(pt) <- c("lon","lat") sp::proj4string(pt) <- "EPSG:4326" } else { pt <- sf::st_as_sf(pt,coords=c("lon","lat"),crs="WGS84") } ct <- ursa_colortable(colorize(pt$value)) tr <- trackline(pt,connect="consequent") #opW <- options(warn=0) session_grid(pt,expand=1.1) compose_open(2) panel_new() panel_plot(pt,col=ct) panel_decor() panel_new() panel_plot(tr,col=ct,lwd=3) panel_decor() compose_legend(ct,unit="step number") compose_close()
session_grid(NULL) n <- 15 lon <- rev(sort(runif(n,min=40,max=60))) lat <- sort(runif(n,min=30,max=50)) pt <- data.frame(lon=lon,lat=lat,value=seq(n)) if (requireNamespace("sp")) { sp::coordinates(pt) <- c("lon","lat") sp::proj4string(pt) <- "EPSG:4326" } else { pt <- sf::st_as_sf(pt,coords=c("lon","lat"),crs="WGS84") } ct <- ursa_colortable(colorize(pt$value)) tr <- trackline(pt,connect="consequent") #opW <- options(warn=0) session_grid(pt,expand=1.1) compose_open(2) panel_new() panel_plot(pt,col=ct) panel_decor() panel_new() panel_plot(tr,col=ct,lwd=3) panel_decor() compose_legend(ct,unit="step number") compose_close()
For package description see.
ursa
is a wrapper to initialize object of class ursaRaster
, to get and to set properties for this object.
ursa(obj, attr, ...) ursa(obj, attr, ...) <- value
ursa(obj, attr, ...) ursa(obj, attr, ...) <- value
obj |
Any numeric structure (scalar, matrix, array) for initializing. Object of class |
attr |
Character. Name of property. |
... |
Arguments, which are passed for properties specification. |
value |
Value for property assignment. |
Initializing function ursa
with missing argument attr
is a wrapper for function as.ursa
.
Matched pattern | Replace method? | Description of property | Implementation |
"grid" |
Yes | Raster grid (extent, projection, cellsize) | ursa_grid
|
"(proj|crs)" |
Yes | Coordinate reference system | ursa_proj
|
"val" |
Yes | Raster value in the internal storage format | ursa_value
|
"(colort|ct)" |
Yes | Color table | ursa_colortable
|
"(categ|class)" |
Yes | Names of categories | names(ursa_colortable(obj))
|
"name" |
Yes | Band names | names
|
"(nodata|ignorevalue|bg)" |
Yes | Value, which is interpreted as NA . |
ignorevalue
|
"^table$" |
No | Frequency of unique values | as.table
|
"cell" |
No | Squared cell size | with(ursa_grid(obj),sqrt(resx*resy))
|
"^dim$" |
No | Dimension of raster image | dim
|
"(extent|bbox)" |
No | Spatial extent of raster image | with(ursa_grid(obj),c(xmin=minx,ymin=miny,xmax=maxx,ymax=maxy))
|
"(nrow|rows|lines)" |
No | Number of rows of raster image | ursa_grid(obj)$rows
|
"(ncol|columns|samples)" |
No | Number of columns of raster image | ursa_grid(obj)$columns
|
"con" |
No | structure of connection | obj$con
|
"(info|meta(data)*)" |
No | Metadata, brief info | ursa_info
|
"^file(name)*" |
No | Connection name (filename) | obj$con$fname
|
Argument ... is used to specify band index or band pattern in ursa(obj,"value",...)
Inititalizing function ursa
(missing attr
) returns object of class ursaRaster
.
Extract function ursa
returns object of respective property.
Replace function ursa<-
returns object
Nikita Platonov [email protected]
a1 <- ursa(volcano) print(a1) ## to avoid over-timing during tests -- begin display(a1) ## to avoid over-timing during tests -- end a2 <- ursa(volcano,flip=TRUE) print(a2) ## to avoid over-timing during tests -- begin display(a2) ## to avoid over-timing during tests -- end a3 <- ursa(volcano,permute=TRUE) print(a3) ## to avoid over-timing during tests -- begin display(a3) ## to avoid over-timing during tests -- end a4 <- ursa(volcano,flip=TRUE,permute=TRUE) print(a4) ## to avoid over-timing during tests -- begin display(a4) ## to avoid over-timing during tests -- end dima <- c(200,300,4) b1 <- ursa(array(runif(prod(dima)),dim=dima)) print(b1) display_brick(b1,scale=1,pal.rotate=0,pal.hue=0,decor=FALSE) session_grid(NULL) c1 <- ursa(seq(3)) print(c1) c2 <- ursa(seq(3),bands=3) print(c2) c3 <- ursa(value=FALSE) str(ursa(c3,"value")) c4 <- ursa(bands=2,nodata=-99L) print(c4) print(ursa(c4,"nodata")) c5 <- ursa(bandname=format(Sys.Date()+seq(7)-1,"%A")) ursa(c5,"value") <- rev(seq(nband(c5))) c5 <- colorize(c5) ct <- ursa(c5,"colortable") print(c5) v <- ursa(c5[3:5],"value") str(v) v <- c(v) str(v) c6 <- ursa(v,colortable=ct) print(c6) print(ursa(c6,"colortable"))
a1 <- ursa(volcano) print(a1) ## to avoid over-timing during tests -- begin display(a1) ## to avoid over-timing during tests -- end a2 <- ursa(volcano,flip=TRUE) print(a2) ## to avoid over-timing during tests -- begin display(a2) ## to avoid over-timing during tests -- end a3 <- ursa(volcano,permute=TRUE) print(a3) ## to avoid over-timing during tests -- begin display(a3) ## to avoid over-timing during tests -- end a4 <- ursa(volcano,flip=TRUE,permute=TRUE) print(a4) ## to avoid over-timing during tests -- begin display(a4) ## to avoid over-timing during tests -- end dima <- c(200,300,4) b1 <- ursa(array(runif(prod(dima)),dim=dima)) print(b1) display_brick(b1,scale=1,pal.rotate=0,pal.hue=0,decor=FALSE) session_grid(NULL) c1 <- ursa(seq(3)) print(c1) c2 <- ursa(seq(3),bands=3) print(c2) c3 <- ursa(value=FALSE) str(ursa(c3,"value")) c4 <- ursa(bands=2,nodata=-99L) print(c4) print(ursa(c4,"nodata")) c5 <- ursa(bandname=format(Sys.Date()+seq(7)-1,"%A")) ursa(c5,"value") <- rev(seq(nband(c5))) c5 <- colorize(c5) ct <- ursa(c5,"colortable") print(c5) v <- ursa(c5[3:5],"value") str(v) v <- c(v) str(v) c6 <- ursa(v,colortable=ct) print(c6) print(ursa(c6,"colortable"))
This help topic is about how cache is managed in the package.
ursa_cache()
ursa_cache()
Users, who want to keep cache files between R sessions, should define option with name ursaCacheDir
and value of the path for storage of cache files. This setting can be specified if ~/.Rprofile
file, or be in your code. If you specify permanent cache directory as sub-directory of tempdir()
(see example), it will be removed after finishing of R session.
NULL
There is no neccessary to call this function. It just defines this help topic.
Nikita Platonov [email protected]
## internet connection is required options(ursaCacheDir=file.path(tempdir(),".ursaCacheDir")) print(c(tempdir=tempdir(),ursaCacheDir=getOption("ursaCacheDir"))) glance("Mount Eden",place="park") dir(getOption("ursaCacheDir"))
## internet connection is required options(ursaCacheDir=file.path(tempdir(),".ursaCacheDir")) print(c(tempdir=tempdir(),ursaCacheDir=getOption("ursaCacheDir"))) glance("Mount Eden",place="park") dir(getOption("ursaCacheDir"))
Function ursa_crop
makes such spatial subset of source raster image, where margins of 'no data' values are absent or have specified width.
ursa_crop(obj, condition, border = 0, expand = 1, resetGrid = TRUE, verbose = FALSE)
ursa_crop(obj, condition, border = 0, expand = 1, resetGrid = TRUE, verbose = FALSE)
obj |
Object of class |
condition |
Object of class |
border |
Integer of length 1, 2 or 4. Desired margins for geographical subset. Units are cells (pixels). |
expand |
Numeric of length 1, 2 or 4. Desired boundary expansion for geographical subset. Units is ratio (relative to 1). Default is 1. |
resetGrid |
Logical. If |
verbose |
Logical. |
This function calls regrid
with passing values of arguments resetGrid
and verbose
without changes.
Bordering (argument border
) is applied before expansion (argument expand
).
This function is an instrument for data compression for spatial matrices with wide margins of 'no data' value. It keeps spatial structure (pixel's neighborhood) in the internal data storage. Otherwise, compress
reduces object size using spatial indexing with dropping of spatial structure.
Object of class ursaRaster
Nikita Platonov [email protected]
session_grid(NULL) 'printCR' <- function(obj) print(with(ursa_grid(obj),c(c=columns,r=rows))) g0 <- session_grid() a <- pixelsize() th <- with(ursa_grid(a),resx*resy*1e-6) a0 <- a[a>th*0.9] print(session_grid()) printCR(a0) print(a0) a1 <- ursa_crop(a0,resetGrid=TRUE) print(session_grid()) printCR(a1) print(a1) a2 <- ursa_crop(a0,resetGrid=FALSE) print(session_grid()) printCR(a2) print(a2) a3 <- a[a>=th*0.85 & a<=th*1.01] b1 <- ursa_dummy(nband=3,min=0,max=255) print(b1) b2 <- ursa_crop(b1[a3>0],border=10) print(b2) printCR(b2) b2[is.na(b2)] <- 255 display_rgb(b2) b3 <- ursa_crop(b1,a3,border=0) print(b3) printCR(b3)
session_grid(NULL) 'printCR' <- function(obj) print(with(ursa_grid(obj),c(c=columns,r=rows))) g0 <- session_grid() a <- pixelsize() th <- with(ursa_grid(a),resx*resy*1e-6) a0 <- a[a>th*0.9] print(session_grid()) printCR(a0) print(a0) a1 <- ursa_crop(a0,resetGrid=TRUE) print(session_grid()) printCR(a1) print(a1) a2 <- ursa_crop(a0,resetGrid=FALSE) print(session_grid()) printCR(a2) print(a2) a3 <- a[a>=th*0.85 & a<=th*1.01] b1 <- ursa_dummy(nband=3,min=0,max=255) print(b1) b2 <- ursa_crop(b1[a3>0],border=10) print(b2) printCR(b2) b2[is.na(b2)] <- 255 display_rgb(b2) b3 <- ursa_crop(b1,a3,border=0) print(b3) printCR(b3)
Functions manipulate with $crs
item of the ursaGrid
object, which is embedded in the ursaRaster
object (obj$grid$crs
). Projection is specified in PROJ.4 notation.
ursa_crs(obj) ursa_crs(obj, keepGrid = FALSE) <- value
ursa_crs(obj) ursa_crs(obj, keepGrid = FALSE) <- value
obj |
|
keepGrid |
Logical. Should sessional grid be changed after assignment. Default is |
value |
Character sting in PROJ.4 format. |
Boath Extract and Replace functions ursa_proj()
and ursa_proj4()
are synonyms for ursa_crs
.
Extract function ursa_crs
returns character value of $grid$crs
item of ursaRaster
object.
Replace function ursa_crs<-
returns ursaRaster
with modified $grid$crs
item.
Nikita Platonov [email protected]
session_grid(NULL) a <- ursa_dummy(nband=1) print(ursa_crs(a)) p4s <- "+init=epsg:3576" ursa_crs(a) <- p4s print(ursa_crs(a)) fname <- tempfile() write_envi(a,fname) a2 <- read_envi(fname,resetGrid=TRUE) print(ursa_crs(a2)) # try(print(rgdal::CRSargs(sp::CRS(p4s)))) ## 'rgdal' is retired envi_remove(fname)
session_grid(NULL) a <- ursa_dummy(nband=1) print(ursa_crs(a)) p4s <- "+init=epsg:3576" ursa_crs(a) <- p4s print(ursa_crs(a)) fname <- tempfile() write_envi(a,fname) a2 <- read_envi(fname,resetGrid=TRUE) print(ursa_crs(a2)) # try(print(rgdal::CRSargs(sp::CRS(p4s)))) ## 'rgdal' is retired envi_remove(fname)
ursa_dummy
returns georeferenced raster image with required number of bands. The value of such image has no sence in reality, but are suitable for R's examples.
ursa_dummy(nband = 3L, minvalue = 0, maxvalue = 255, mul = 1, elements = 8L, bandname = NULL, nodata = TRUE, resetGrid=FALSE)
ursa_dummy(nband = 3L, minvalue = 0, maxvalue = 255, mul = 1, elements = 8L, bandname = NULL, nodata = TRUE, resetGrid=FALSE)
nband |
Positive integer. Number of bands. Default is 3L. |
minvalue |
Numeric of length 1. Minimal value for raster image. Default is |
maxvalue |
Numeric of length 1. Maximal value for raster image. Default is |
mul |
Positive numeric. The scaling of the existing session grid. Value |
elements |
Positive integer. Maximal dimension of matrix, which is proportional to session grid. If |
bandname |
Character vector or |
nodata |
Numerical or logical. Set value, which is interpreted as 'no-data' flag. If logical and |
resetGrid |
Logical. Whether the grid will be reset to default before raster generation? If |
Currently, the values are generated using runif
.
The value mul<1
speeds up raster generation.
Object of class ursaRaster
Nikita Platonov [email protected]
session_grid(NULL) a1 <- as.integer(ursa_dummy(nband=1,mul=1/16,elements=1e3)) ## white noise ## to avoid over-time during example check -- begin display(a1,legend=NULL) ## to avoid over-time during example check -- end a2 <- ursa_dummy() print(a2) display_brick(a2,decor=FALSE) display_stack(a2,decor=FALSE) display_rgb(a2,decor=FALSE)
session_grid(NULL) a1 <- as.integer(ursa_dummy(nband=1,mul=1/16,elements=1e3)) ## white noise ## to avoid over-time during example check -- begin display(a1,legend=NULL) ## to avoid over-time during example check -- end a2 <- ursa_dummy() print(a2) display_brick(a2,decor=FALSE) display_stack(a2,decor=FALSE) display_rgb(a2,decor=FALSE)
Raster image (ursaRaster
) contains embedded spatial parameters (ursaGrid
) in item $grid
. These functions manipulate with item $grid
.
ursa_grid(obj) ursa_grid(obj) <- value ursa_ncol(obj) ursa_nrow(obj) ursa_columns(obj) ursa_rows(obj) ursa_samples(obj) ursa_lines(obj) ursa_extent(obj) ursa_bbox(obj) consistent_grid(obj, ref, expand = 1, border = rep(0, 4), verbose = FALSE)
ursa_grid(obj) ursa_grid(obj) <- value ursa_ncol(obj) ursa_nrow(obj) ursa_columns(obj) ursa_rows(obj) ursa_samples(obj) ursa_lines(obj) ursa_extent(obj) ursa_bbox(obj) consistent_grid(obj, ref, expand = 1, border = rep(0, 4), verbose = FALSE)
obj |
|
value |
|
ref |
|
expand |
Podsitive numeric. Multiplier of boundary box. |
border |
|
verbose |
Logical. Some output in console. Primarily for debug purposes. |
ursa_grid<-
may used to minor corrections of spatial parameters. Howevert, it seems that this function is not claimed in practice.
ursa_ncol
, ursa_columns
, ursa_samples
are synonyms for extracting number of columns/samples.
ursa_nrow
, ursa_rows
, ursa_lines
are synonyms for extracting number of rows/lines.
ursa_extent
, ursa_bbox
, are synonyms for extracting boundary box (spatial extent).
consistent_grid
trasforms dimension (ursa_nrow()
by ursa_ncol()
) obj
-grid to dimension of ref
-grid. This helpful for multipanel plotting if objects have different boundary boxes.
ursa_grid
return value of $grid
item of ursaRaster
object.
ursa_grid<-
return ursaRaster
with modified $grid
item.
ursa_ncol
, ursa_columns
, ursa_samples
return integer of length 1.
ursa_nrow
, ursa_rows
, ursa_lines
return integer of length 1.
ursa_extent
, ursa_bbox
return numeric of length 4 (xmin, ymin, xmax, ymax).
ursa_consistent
returns ursaGrid
object.
Nikita Platonov [email protected]
session_grid(NULL) a <- pixelsize() print(ursa_grid(a)) ursa_grid(a)$crs <- gsub("\\.0+","",ursa_grid(a)$crs) print(ursa_grid(a))
session_grid(NULL) a <- pixelsize() print(ursa_grid(a)) ursa_grid(a)$crs <- gsub("\\.0+","",ursa_grid(a)$crs) print(ursa_grid(a))
Function shows information about raster CRS, data type, storage mode, nodata value, structure of band names.
ursa_info(obj, detail = NA, ...)
ursa_info(obj, detail = NA, ...)
obj |
|
detail |
Not used. Reserved for potential detail levels |
... |
Arguments, which are passed to |
ursa_info
generates a list and then shows structure of this list via function str
.
Object of temporal class ursaMetadata
is a list with items:
columns |
Number of columns (samples) |
rows |
Number of rows (lines) |
resx |
Grid cell size by horizontal axis |
resy |
Grid cell size by vertical axis |
minx |
Left margin of boundary box |
maxx |
Right margin of boundary box |
miny |
Bottom margin of boundary box |
maxy |
Top margin of boundary box |
proj4 |
PROJ.4 string |
nodata |
Optional. Value, which is interpreted as |
datatype |
Optional. If data are on disk, then integer code of data type. |
interleave |
Optional. If data are on disk, then abbreviation of bands interleave. |
mode |
Character of length 2: |
bandname |
Band names. |
colortable |
Optional. Structure of color table. |
Function returns NULL
.
Nikita Platonov [email protected]
session_grid(NULL) a <- as.integer(round(ursa_dummy(nband=3))) print(a) ## print data ursa_info(a,digits=1) ## print metadata fname <- tempfile() write_envi(a,fname,compress=FALSE) b1 <- open_envi(fname) ursa_info(b1) close(b1) b2 <- read_envi(fname) ursa_info(b2) # print ENVI header sapply(c(" -------------- begin --------------",readLines(paste0(fname,".hdr")) ," --------------- end ---------------"),message) envi_remove(fname)
session_grid(NULL) a <- as.integer(round(ursa_dummy(nband=3))) print(a) ## print data ursa_info(a,digits=1) ## print metadata fname <- tempfile() write_envi(a,fname,compress=FALSE) b1 <- open_envi(fname) ursa_info(b1) close(b1) b2 <- read_envi(fname) ursa_info(b2) # print ENVI header sapply(c(" -------------- begin --------------",readLines(paste0(fname,".hdr")) ," --------------- end ---------------"),message) envi_remove(fname)
ursa_new
creates object of class ursaRaster
in memory using session grid parameters or properties of input object (matrix
or array
). By option, band names and ignore values are specified.
ursa_new(...)
ursa_new(...)
... |
Set of arguments, which are recognized via their names (using regular expressions) and classes:
|
ursa_new
creates ursaRaster
object in memory. To manipulate with raster chunks use the followed construction:
a <- create_envi(fname,...) a[condition_1] <- value print(a[condition_2] ... close(a)
ursa_new
is designed to create blank raster images. Use as.ursa
for conversion R objects to ursaRaster
.
Object of class ursaRaster
.
Nikita Platonov [email protected]
session_grid(NULL) a1 <- ursa_new(volcano) print(a1) ## to avoid over-timing during tests -- begin display(a1) ## to avoid over-timing during tests -- end a2 <- ursa_new(volcano,flip=TRUE) print(a2) ## to avoid over-timing during tests -- begin display(a2) ## to avoid over-timing during tests -- end a3 <- ursa_new(volcano,permute=TRUE) print(a3) ## to avoid over-timing during tests -- begin display(a3) ## to avoid over-timing during tests -- end dima <- c(200,300,4) b1 <- as.ursa(array(runif(prod(dima)),dim=dima)) print(b1) display_brick(b1,scale=1,pal=c("white","black"),decor=FALSE) session_grid(NULL) c1 <- ursa_new(seq(3)) print(c1) c2 <- ursa_new(seq(3),bands=3) print(c2) c3 <- ursa_new(value=FALSE) str(ursa_value(c3)) c4 <- ursa_new(bands=2,nodata=-99L) print(c4) print(ignorevalue(c4)) c5 <- ursa_new(bandname=format(Sys.Date()+seq(7)-1,"%A")) ursa_value(c5) <- rev(seq(nband(c5))) c5 <- colorize(c5) ct <- ursa_colortable(c5) print(c5) v <- ursa_value(c5[3:5]) str(v) v <- c(v) str(v) c6 <- ursa_new(v,colortable=ct) print(c6) print(ursa_colortable(c6))
session_grid(NULL) a1 <- ursa_new(volcano) print(a1) ## to avoid over-timing during tests -- begin display(a1) ## to avoid over-timing during tests -- end a2 <- ursa_new(volcano,flip=TRUE) print(a2) ## to avoid over-timing during tests -- begin display(a2) ## to avoid over-timing during tests -- end a3 <- ursa_new(volcano,permute=TRUE) print(a3) ## to avoid over-timing during tests -- begin display(a3) ## to avoid over-timing during tests -- end dima <- c(200,300,4) b1 <- as.ursa(array(runif(prod(dima)),dim=dima)) print(b1) display_brick(b1,scale=1,pal=c("white","black"),decor=FALSE) session_grid(NULL) c1 <- ursa_new(seq(3)) print(c1) c2 <- ursa_new(seq(3),bands=3) print(c2) c3 <- ursa_new(value=FALSE) str(ursa_value(c3)) c4 <- ursa_new(bands=2,nodata=-99L) print(c4) print(ignorevalue(c4)) c5 <- ursa_new(bandname=format(Sys.Date()+seq(7)-1,"%A")) ursa_value(c5) <- rev(seq(nband(c5))) c5 <- colorize(c5) ct <- ursa_colortable(c5) print(c5) v <- ursa_value(c5[3:5]) str(v) v <- c(v) str(v) c6 <- ursa_new(v,colortable=ct) print(c6) print(ursa_colortable(c6))
Class ursaConnection
is a part of class ursaRaster
. It defines storage of raster images and manipulations with reading and writing.
## S3 method for class 'ursaConnection' print(x, ...) ## S3 method for class 'ursaConnection' seek(con, where = NA, origin = "start", rw = "", ...)
## S3 method for class 'ursaConnection' print(x, ...) ## S3 method for class 'ursaConnection' seek(con, where = NA, origin = "start", rw = "", ...)
x |
|
con |
|
where |
Passed to |
origin |
Passed to |
rw |
Passed to |
... |
|
ursaConnection
get item $con
from ursaRaster
object.
Functions print
and is.con
are for developers rather than users.
Non-public function .con.skeleton()
is used to generate the blank ursaConnection
object. This approach provides unified sequence of list's items:
ursaConnection
is a list. The most of names have a relation to specification of ENVI Header Files. Items:
driver |
Character. Keyword of supported image formats. Allowed "ENVI" or "GDAL". |
samples |
Integer. Number of image columns (samples) |
lines |
Integer. Number of image rows (lines) |
bands |
Integer. Number of image bands (channels, layers) |
datatype |
Integer. Keyword for data type (4 - 32-bit floating point, 2 - 16-bit signed integer, etc) |
interleave |
Character |
byteorder |
Integer, 0 or 1. The order of bytes. |
endian |
Character. See |
swap |
Integer 0 or 1. Passed to C-funcions |
signed |
Logical. Derived from |
offset |
Integer. Header offset in binary file. Default is 0. |
wkt |
Logical. In ENVI Header files |
nodata |
Numeric. Replacement |
mode |
Character. |
sizeof |
Integer, positive. Size in bytes for stored values. Extracted from |
indexC |
Integer vector. Sample indices in spatial cropping. |
indexR |
Integer vector. Line indices in spatial cropping. |
indexZ |
Integer vector. Band indices |
posC |
Integer vector. Sample indices in partial reading. |
posR |
Integer vector. Line indices in partial reading. |
posZ |
Integer vector. Band indices in spatial crottping or partial reading. |
fname |
Character. File name. If |
connection |
Character. See |
compress |
Signed integer. |
seek |
Logical. Does connection support |
handle |
|
Nikita Platonov [email protected]
ursa(obj,"con")
session_grid(NULL) print(methods(class="ursaConnection")) a <- pixelsize() write_envi(rep(a,5),"tmp1",compress=FALSE) ## change spatial domain for cropping example g <- session_grid(regrid(lim=c(-1200000,-1400000,1600000,1800000))) print(g) b <- open_envi("tmp1") d <- b[,30:70] print(ursa(d[2:3],"con")) close(b) envi_remove("tmp1")
session_grid(NULL) print(methods(class="ursaConnection")) a <- pixelsize() write_envi(rep(a,5),"tmp1",compress=FALSE) ## change spatial domain for cropping example g <- session_grid(regrid(lim=c(-1200000,-1400000,1600000,1800000))) print(g) b <- open_envi("tmp1") d <- b[,30:70] print(ursa(d[2:3],"con")) close(b) envi_remove("tmp1")
Class ursaCRS
is a part of class ursaGrid
. It defines map projection.
## S3 method for class 'ursaCRS' print(x, ...) ## S3 method for class 'ursaCRS' str(object, ...)
## S3 method for class 'ursaCRS' print(x, ...) ## S3 method for class 'ursaCRS' str(object, ...)
x |
|
object |
|
... |
Further arguments passed to generic functions |
Functions print information about CRS and return invisible NULL
value.
Nikita Platonov [email protected]
session_grid(NULL) a <- ursa_dummy() crs <- ursa_crs(a) print(c('Is proj4string used?'=p4 <- isTRUE(getOption("ursaProj4Legacy")))) print(crs) str(crs) op <- options(ursaProj4Legacy=!p4) print(c('Is proj4string used?'=p4 <- isTRUE(getOption("ursaProj4Legacy")))) session_grid(NULL) a <- ursa_dummy() crs <- ursa_crs(a) print(crs) str(crs) options(op)
session_grid(NULL) a <- ursa_dummy() crs <- ursa_crs(a) print(c('Is proj4string used?'=p4 <- isTRUE(getOption("ursaProj4Legacy")))) print(crs) str(crs) op <- options(ursaProj4Legacy=!p4) print(c('Is proj4string used?'=p4 <- isTRUE(getOption("ursaProj4Legacy")))) session_grid(NULL) a <- ursa_dummy() crs <- ursa_crs(a) print(crs) str(crs) options(op)
Class ursaGrid
is a part of class ursaRaster
. It defines spatial locations of image.
## S3 method for class 'ursaGrid' print(x, ...) ## S3 method for class 'ursaGrid' str(object, ...) ## S3 method for class 'ursaGrid' dim(x) ## S3 method for class 'ursaGrid' as.data.frame(x, row.names = NULL, optional = FALSE, ...)
## S3 method for class 'ursaGrid' print(x, ...) ## S3 method for class 'ursaGrid' str(object, ...) ## S3 method for class 'ursaGrid' dim(x) ## S3 method for class 'ursaGrid' as.data.frame(x, row.names = NULL, optional = FALSE, ...)
x |
|
object |
|
row.names |
Ignored. Argument, which is passed to generic function |
optional |
Ignored. Argument, which is passed to generic function |
... |
Further arguments passed to generic functions |
The blank ursaGrid
object is generated by calling of ursa_grid()
without arguments. These approaches provide unified sequence of list's items:
List of 9 $ columns: int NA $ rows : int NA $ resx : num NA $ resy : num NA $ minx : num NA $ maxx : num NA $ miny : num NA $ maxy : num NA $ proj4 : chr "" - attr(*, "class")= chr "ursaGrid" NULL
Object of class ursaGrid
is a list with items:
columns |
Number of columns (samples) |
rows |
Number of rows (lines) |
resx |
Grid cell size by horizontal axis |
resy |
Grid cell size by vertical axis |
minx |
Left margin of boundary box |
maxx |
Right margin of boundary box |
miny |
Bottom margin of boundary box |
maxy |
Top margin of boundary box |
proj4 |
PROJ.4 string |
Function dim
for object of class ursaGrid
returns named vector of length 2: number of rows ("lines"
) and number of elements in a row ("samples"
)
Nikita Platonov [email protected]
session_grid(NULL) print(methods(class="ursaGrid")) a <- pixelsize() g <- ursa_grid(a) print(is.ursa(a,"grid")) print(is.ursa(g,"grid")) print(g)
session_grid(NULL) print(methods(class="ursaGrid")) a <- pixelsize() g <- ursa_grid(a) print(is.ursa(a,"grid")) print(is.ursa(g,"grid")) print(g)
Informative progress bars with dispaying elapsed and remained time.
ursaProgressBar(kind = c("tk", "txt"),title = .argv0(), label = "", min = 0, max = 1, initial = min, width = NA, style = 1, tail = FALSE, silent = FALSE) setUrsaProgressBar(pb, value, title = NULL, label = NULL) ## S3 method for class 'ursaProgressBar' close(con, ...)
ursaProgressBar(kind = c("tk", "txt"),title = .argv0(), label = "", min = 0, max = 1, initial = min, width = NA, style = 1, tail = FALSE, silent = FALSE) setUrsaProgressBar(pb, value, title = NULL, label = NULL) ## S3 method for class 'ursaProgressBar' close(con, ...)
kind |
Character. Type or progress bar. Valid values are |
style |
See description for the same argument in |
width |
See description for the same argument in |
title , label , min , max , initial , value , pb
|
See description for the same arguments in |
con , ...
|
See description for the same arguments in |
tail |
Logical. Behaviour of progress bar appearing. If |
silent |
Logical. If |
Wrapper to one of
txtProgressBar
,
tkProgressBar
.
Visualization of progress bar is updates each 0.5 seconds, it is effective for multiple short-term iterations.
Progress bars should be closed by calling of appropriate method of generic function close
depending of class of reference progress bar.
ursaProgressBar
returns object of reference progress bar.
Function name in style camelCase for consistence with other progress bar functions in R.
Nikita Platonov [email protected]
session_grid(NULL) n1 <- 3 n2 <- 83 p <- 0.0011 #require(tcltk) pb <- ursaProgressBar(min=0,max=n1,title="first",tail=TRUE) for (i in seq(n1)) { pb2 <- ursaProgressBar(min=0,max=n2,title="second") for (i in seq(n2)) { setUrsaProgressBar(pb2) Sys.sleep(p) } close(pb2) setUrsaProgressBar(pb) } close(pb)
session_grid(NULL) n1 <- 3 n2 <- 83 p <- 0.0011 #require(tcltk) pb <- ursaProgressBar(min=0,max=n1,title="first",tail=TRUE) for (i in seq(n1)) { pb2 <- ursaProgressBar(min=0,max=n2,title="second") for (i in seq(n2)) { setUrsaProgressBar(pb2) Sys.sleep(p) } close(pb2) setUrsaProgressBar(pb) } close(pb)
ursaRaster
class.
ursaRaster
is S3 class for manipulation with georeferred raster images. See ‘Value’ section.
is.ursa
checks inhering to class ursaRaster
## S3 method for class 'ursaRaster' print(x, digits = NA, grid = FALSE, raw = FALSE, caption = FALSE, ...) ## S3 method for class 'ursaRaster' str(object,...) is.ursa(obj, ref = NULL) is_ursa(obj, ref = NULL)
## S3 method for class 'ursaRaster' print(x, digits = NA, grid = FALSE, raw = FALSE, caption = FALSE, ...) ## S3 method for class 'ursaRaster' str(object,...) is.ursa(obj, ref = NULL) is_ursa(obj, ref = NULL)
x , object
|
|
||||||||||||||||||
obj |
Any. |
||||||||||||||||||
digits |
Passed to |
||||||||||||||||||
grid |
Logical. If |
||||||||||||||||||
raw |
Logical. If |
||||||||||||||||||
caption |
Logical of character. Print title or other identificational info. If logical and |
||||||||||||||||||
... |
Passed to |
||||||||||||||||||
ref |
Character or
|
is.ursa()
is designed mainly for developers to check arguments' class in function's call. is_ursa
is a synonym to is.ursa
.
Stucture of ursaRaster
class is generated by non-public .raster.skeleton()
function.
ursaRaster
is R's S3 class. It is a list with items:
grid |
Geospatial properties. |
con |
Connection properties. |
value |
2-dimensional numerical or integer matrix of classes |
dim |
Dimension of |
name |
Band names |
colortable |
Color table. |
is.ursa(x)
returns TRUE
, if class of x
is ursaRaster
Nikita Platonov [email protected]
session_grid(NULL) print(methods(class="ursaRaster")) a <- pixelsize() print(a) print(a,grid=TRUE) s <- substr(as.character(sessionInfo()),1,48) b <- rep(a,length(s)) bandname(b) <- s print(b) require(datasets) data(volcano) print(is.ursa(a)) print(is.ursa(volcano)) print(is.ursa(as.ursa(volcano)))
session_grid(NULL) print(methods(class="ursaRaster")) a <- pixelsize() print(a) print(a,grid=TRUE) s <- substr(as.character(sessionInfo()),1,48) b <- rep(a,length(s)) bandname(b) <- s print(b) require(datasets) data(volcano) print(is.ursa(a)) print(is.ursa(volcano)) print(is.ursa(as.ursa(volcano)))
Functions to create list (layers) of multiband raster images (stack in the notation of raster package) and to coerce list of images to single multiband image (brick in the notation of raster package).
ursa_stack(...) ursa_brick(obj) ursa_apply(obj, FUN, ...) ## S3 method for class 'ursaRaster' as.list(x, ...) ## S3 method for class 'ursaStack' unlist(x, recursive, use.names)
ursa_stack(...) ursa_brick(obj) ursa_apply(obj, FUN, ...) ## S3 method for class 'ursaRaster' as.list(x, ...) ## S3 method for class 'ursaStack' unlist(x, recursive, use.names)
obj , x
|
Object of class |
||||||||
FUN |
Argument " |
||||||||
recursive |
Not used. For consistency with generic function |
||||||||
use.names |
Not used. For consistency with generic function |
||||||||
... |
Denending of functions:
|
as.list
(of ursaRaster
object(s)), ursa_stack
create list of ursaRaster
objects, where items of list are sinle-band images. If x
is ursaRaster
object, then list(x)
create a list of length one, which item is multiband image.
unlist
(for list of ursaRaster
objects), ursa_brick
create single multiband ursaRaster
object. There is an alternative way for unlisting the list of ursaRaster
: as.ursa
.
Raster stack is a way to group bands, for example, by units (degree Celsium, meters).
Raster brick is a way to combine versalite images to the single multiband image, for example, for saving in file.
ursa_stack
, as.list
return object of class ursaStack
. It is a list, with class "ursaStack" attribute.
unlist
(for list of ursaRaster
objects), ursa_brick
return object of class ursaRaster
.
ursa_apply
returns object of class ursaStack
, if result is list of ursaRaster
objects, otherwise returns general list
.
There is no any verifications, that grids of ursaRaster
objects are the same.
Generic unlist(x)
deals only with class of x
, but doesn't take into account class of objects in list (e. g., x[[1]]
). So, there is no effective way to use only list
/unlist
for ursaRaster
objects to do a conversion between raster brick and stack.
Generic unlist(x)
deals only with class of x
, but doesn't take into account class of objects in list (e. g., x[[1]]
). So, there is no effective way to use only list
/unlist
for ursaRaster
objects to do a conversion between raster brick and stack.
Nikita Platonov
https://CRAN.R-project.org/package=raster
c
for ursaRaster
objects.
session_grid(NULL) a <- ursa_dummy(3) print(a) b1 <- ursa_stack(a[1:2],colorize(a[3],ramp=FALSE)) print(b1) b2 <- as.list(a) print(b2) b3 <- list(a[1],a[2:3]) print(b3) b31 <- lapply(b3,colorize,ramp=FALSE) print(b31) b32 <- ursa_apply(b3,colorize,ramp=FALSE,rev=TRUE) print(b32) s311 <- ursa_apply(b31,ursa_colortable) print(s311) s21 <- lapply(b2,global_mean) print(s21) s22 <- sapply(b2,global_mean) print(s22) s31 <- lapply(b3,global_mean) print(s31) s32 <- sapply(b3,global_mean) print(s32) c1 <- unlist(b1) print(c1) c2 <- unlist(b2) print(c2) c3 <- unlist(b3) print(if (is.ursa(c3)) c3 else "broken object") d3 <- as.ursa(b3) print(if (is.ursa(d3)) d3 else "broken object")
session_grid(NULL) a <- ursa_dummy(3) print(a) b1 <- ursa_stack(a[1:2],colorize(a[3],ramp=FALSE)) print(b1) b2 <- as.list(a) print(b2) b3 <- list(a[1],a[2:3]) print(b3) b31 <- lapply(b3,colorize,ramp=FALSE) print(b31) b32 <- ursa_apply(b3,colorize,ramp=FALSE,rev=TRUE) print(b32) s311 <- ursa_apply(b31,ursa_colortable) print(s311) s21 <- lapply(b2,global_mean) print(s21) s22 <- sapply(b2,global_mean) print(s22) s31 <- lapply(b3,global_mean) print(s31) s32 <- sapply(b3,global_mean) print(s32) c1 <- unlist(b1) print(c1) c2 <- unlist(b2) print(c2) c3 <- unlist(b3) print(if (is.ursa(c3)) c3 else "broken object") d3 <- as.ursa(b3) print(if (is.ursa(d3)) d3 else "broken object")
Class ursaValue
is a part of class ursaRaster
. It contains values of image. In the case of numeric values, the exterior class is ursaNumeric
. In the case of categorical values, the exterior class is ursaCategory
.
## S3 method for class 'ursaCategory' print(x, ...) ## S3 method for class 'ursaNumeric' print(x, ...) ursa_value(obj, band) ursa_value(obj, band) <- value
## S3 method for class 'ursaCategory' print(x, ...) ## S3 method for class 'ursaNumeric' print(x, ...) ursa_value(obj, band) ursa_value(obj, band) <- value
x |
Object of the one of classes |
... |
Further arguments passed to generic functions |
obj |
Object of class |
band |
Optional. Vector of band numbers (positive integer) or band names (character). |
value |
Numeric or integer scalar, vector, or matrix. Coerced to dimenstion of |
Try to use high-level assignment using replacement [<-
operator for class ursaRaster
. However, if you don't get desired result, you can downgrade the level of your code.
Object of class ursaNumeric
is a numerical matrix. Object of class ursaCategory
is an integer matrix. Dimensions of this matrix:
dim(...)[1] |
Spatial domain; the length is muliplications of lines (rows) and samples (columns) |
dim(...)[2] |
Band or temporal domain; the length is number of bands |
It is allowed to use scalar value NA
in the case when values are not in memory. In this case the class is ursaValue
.
Nikita Platonov [email protected]
Extract [
and replacement [<-
methods for class ursaRaster
session_grid(NULL) session_grid(regrid(mul=1/4)) a1 <- create_envi("exam1.envi",bandname=c("today","tomorrow")) str(ursa_value(a1)) close(a1) envi_remove("exam1") a2 <- ursa_dummy(nband=4,min=1,max=99) str(ursa_value(a2),digits=3) a3 <- as.integer(a2) str(ursa_value(a3)) str(ursa_value(a3,2)) print(ursa_value(a3)) print(a3) ursa_value(a3,"Band 2") <- 199 ursa_value(a3)[,3] <- 299 a3[4] <- 399 print(a3) ursa_value(a3[1:3]) <- ursa_value(a3[4]) print(a3) ursa_value(a3[1:3]) <- -c(1:3) print(a3)
session_grid(NULL) session_grid(regrid(mul=1/4)) a1 <- create_envi("exam1.envi",bandname=c("today","tomorrow")) str(ursa_value(a1)) close(a1) envi_remove("exam1") a2 <- ursa_dummy(nband=4,min=1,max=99) str(ursa_value(a2),digits=3) a3 <- as.integer(a2) str(ursa_value(a3)) str(ursa_value(a3,2)) print(ursa_value(a3)) print(a3) ursa_value(a3,"Band 2") <- 199 ursa_value(a3)[,3] <- 299 a3[4] <- 399 print(a3) ursa_value(a3[1:3]) <- ursa_value(a3[4]) print(a3) ursa_value(a3[1:3]) <- -c(1:3) print(a3)
Wrapper to tools from "whitebox" package to manipulate with ursaRaster
objects
whiteboxing(tool_name, ...)
whiteboxing(tool_name, ...)
tool_name |
Either tool name of Whitebox or function name from whitebox. |
... |
List of parameters. |
Wrapper to function wbt_run_tool
.
ursaRaster
object foo
can be passed via parameter input=foo
instead of GeoTIFF file name.
If argument output
is missed or output=FALSE
, then object of class ursaRaster
. Otherwise, output GeoTIFF file name.
Internally, for piping support, first character argument without *.tif
suffix is interpreted as tool_name
. First unnamed character argument with *.tif
suffix or ursaRaster
object is interpreted as input.
Nikita Platonov [email protected]
if ((requireNamespace("whitebox"))&&(isTRUE(whitebox::wbt_init()))) { dem <- whitebox::sample_dem_data() a1 <- c(DEM=read_gdal(dem)) a2 <- whiteboxing("BreachDepressions",input=a1) b <- list(value=c(a1,a2),difference=c(diff=a1-a2)) print(b) display(b,layout=c(2,NA),legend=list(list("first","left"),list("last","left"))) if (getRversion()>="4.1.0") { a5 <- dem |> whiteboxing("feature_preserving_smoothing",filter=9) |> whiteboxing("breach_depressions") |> print() } }
if ((requireNamespace("whitebox"))&&(isTRUE(whitebox::wbt_init()))) { dem <- whitebox::sample_dem_data() a1 <- c(DEM=read_gdal(dem)) a2 <- whiteboxing("BreachDepressions",input=a1) b <- list(value=c(a1,a2),difference=c(diff=a1-a2)) print(b) display(b,layout=c(2,NA),legend=list(list("first","left"),list("last","left"))) if (getRversion()>="4.1.0") { a5 <- dem |> whiteboxing("feature_preserving_smoothing",filter=9) |> whiteboxing("breach_depressions") |> print() } }
write_envi
writes in-memory object of class ursaRaster
to disk in the ENVI .hdr Labelled Raster file format.
write_envi(obj, ...)
write_envi(obj, ...)
obj |
Object of class |
... |
Arguments, which are passed to |
write_envi
implements writing the whole ursaRaster
object to disk. For multiple access to disk (by chunks), use followed construction:
a <- create_envi(fname) a[condition_1] <- value1 a[condition_2] <- value2 ... close(a)
Integer code of ENVI data type. See values of the “data type” field in description of the ENVI Header Format.
Nikita Platonov [email protected]
create_envi
, Replace method [<-
for ursaRaster
object, close_envi
(close
for ursaRaster
object).
write_gdal(...,driver="ENVI")
uses GDAL (rgdal) for writing ursaRaster
object to the ENVI .hdr Labelled Raster file.
session_grid(NULL) dir.create(tmpWD <- file.path(tempdir(),"certain")) wd <- setwd(tmpWD) print(c('temp dir'=session_tempdir(),'working dir'=getwd())) list1a <- envi_list(session_tempdir()) list1b <- envi_list() fname <- tempfile(tmpdir=".") a <- ursa_dummy() bandname(a) <- c("first","second","third") write_envi(a) write_envi(a,fname) list2a <- envi_list(session_tempdir()) list2b <- envi_list() fname1 <- list2a[!(list2a %in% list1a)] fname2 <- list2b[!(list2b %in% list1b)] print(c('in temp dir'=fname1,'in working dir'=fname2)) a2 <- open_envi(fname1) print(a2) close(a2) envi_remove(c(fname1,fname2)) setwd(wd)
session_grid(NULL) dir.create(tmpWD <- file.path(tempdir(),"certain")) wd <- setwd(tmpWD) print(c('temp dir'=session_tempdir(),'working dir'=getwd())) list1a <- envi_list(session_tempdir()) list1b <- envi_list() fname <- tempfile(tmpdir=".") a <- ursa_dummy() bandname(a) <- c("first","second","third") write_envi(a) write_envi(a,fname) list2a <- envi_list(session_tempdir()) list2b <- envi_list() fname1 <- list2a[!(list2a %in% list1a)] fname2 <- list2b[!(list2b %in% list1b)] print(c('in temp dir'=fname1,'in working dir'=fname2)) a2 <- open_envi(fname1) print(a2) close(a2) envi_remove(c(fname1,fname2)) setwd(wd)
write_gdal
writes in-memory object of class ursaRaster
to disk using GDAL from rgdal package.
write_gdal(obj, ...) ursa_write(obj, fname, ...)
write_gdal(obj, ...) ursa_write(obj, fname, ...)
obj |
Object of class |
... |
Arguments, which are passed to For GDAL formats it is creation options For GDAL formats For GDAL formats |
fname |
Character. File name with extension. |
ursa_write
is simplified call of write_gdal
.
write_gdal
implements writing the whole ursaRaster
object to disk. For multiple access to disk (by chunks), use followed Replace construction:
a <- create_gdal(fname) a[condition_1] <- value1 a[condition_2] <- value2 ... close(a)
Integer code of ENVI data type. See values of the “data type” field in description of the ENVI Header Format.
Nikita Platonov [email protected]
create_gdal
, Replace method [<-
for ursaRaster
object, close
method for ursaRaster
object.
session_grid(NULL) ftemp <- tempfile(pattern="",fileext="") fpath <- dirname(ftemp) fname <- basename(ftemp) a <- round(ursa_dummy(1,min=0,max=255,nodata=NA)) write_envi(a,file.path(fpath,paste0(fname,"_1",".envi"))) write_gdal(a,file.path(fpath,paste0(fname,"_2"))) write_gdal(a,file.path(fpath,paste0(fname,"_3",".tif"))) write_gdal(a,file.path(fpath,paste0(fname,"_4")),driver="EHdr") flist <- dir(path=fpath,pattern=fname,full.names=TRUE) file.remove(flist) blist <- basename(flist) res <- NULL for (i in seq(4)) res <- c(res,paste(grep(paste0("_",i),blist,value=TRUE),collapse=" ")) print(res)
session_grid(NULL) ftemp <- tempfile(pattern="",fileext="") fpath <- dirname(ftemp) fname <- basename(ftemp) a <- round(ursa_dummy(1,min=0,max=255,nodata=NA)) write_envi(a,file.path(fpath,paste0(fname,"_1",".envi"))) write_gdal(a,file.path(fpath,paste0(fname,"_2"))) write_gdal(a,file.path(fpath,paste0(fname,"_3",".tif"))) write_gdal(a,file.path(fpath,paste0(fname,"_4")),driver="EHdr") flist <- dir(path=fpath,pattern=fname,full.names=TRUE) file.remove(flist) blist <- basename(flist) res <- NULL for (i in seq(4)) res <- c(res,paste(grep(paste0("_",i),blist,value=TRUE),collapse=" ")) print(res)
'Zonal' operator of map algebra. Applied to raster images.
zonal_stat(x, by, FUN, table = FALSE) ## S3 method for class 'ursaRaster' aggregate(x, by, FUN, table = FALSE, ...)
zonal_stat(x, by, FUN, table = FALSE) ## S3 method for class 'ursaRaster' aggregate(x, by, FUN, table = FALSE, ...)
x |
|
by |
|
FUN |
a function to compute the summary statistics which can be applied to all data subsets. |
table |
Logical. If |
... |
Other arguments which passed to function |
zonal_stat
is a wrapper of aggregate(x,by,FUN,table=FALSE,na.rm=TRUE)
You can use multichannel image (argument x
) for analysis.
You can use multichannel raster image for group elements (argument by
)
If table=FALSE
then ursaRaster
object of summarized statistics.
If table=TRUE
then data.frame
.
Nikita Platonov [email protected]
session_grid(NULL) session_grid(regrid(mul=1/2)) a <- pixelsize() val <- c(normal=a,half=a/2) gr <- c(group=colorize(a,nbreak=1))#+0 print(as.table(gr)) ##~ display(gr) ra <- round(aggregate(val,gr,mean),4) print(ra) print(as.table(ra[1])) print(as.table(ra[2])) da <- aggregate(val,gr,table=TRUE,mean) n <- aggregate(a,gr,table=TRUE,length)[,2,drop=FALSE] da <- cbind(da,n=unname(n)) gr2 <- c(group2=colorize(a,nbreak=6))#+0 mgr <- list(gr,gr2) da2 <- aggregate(val[1],mgr,table=TRUE,mean) print(da2) da3 <- aggregate(val,mgr,table=TRUE,mean) print(da3) ra3 <- aggregate(val,mgr,table=FALSE,mean) ## not implemented for rasters print(ra3)
session_grid(NULL) session_grid(regrid(mul=1/2)) a <- pixelsize() val <- c(normal=a,half=a/2) gr <- c(group=colorize(a,nbreak=1))#+0 print(as.table(gr)) ##~ display(gr) ra <- round(aggregate(val,gr,mean),4) print(ra) print(as.table(ra[1])) print(as.table(ra[2])) da <- aggregate(val,gr,table=TRUE,mean) n <- aggregate(a,gr,table=TRUE,length)[,2,drop=FALSE] da <- cbind(da,n=unname(n)) gr2 <- c(group2=colorize(a,nbreak=6))#+0 mgr <- list(gr,gr2) da2 <- aggregate(val[1],mgr,table=TRUE,mean) print(da2) da3 <- aggregate(val,mgr,table=TRUE,mean) print(da3) ra3 <- aggregate(val,mgr,table=FALSE,mean) ## not implemented for rasters print(ra3)