content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
'summary.ursaRaster' <- function(object,...) {
isCategory <- .is.category(object)
if (isCategory) {
class(object$value) <- paste0(".",class(object$value))
# return(as.table(x))
res <- NULL
for (i in seq(object))
res <- rbind(res,as.table(object[i]))
z <- object$con$posZ
rownames(res) <- if (is.na(z[1])) object$name else object$name[z]
return(res)
}
class(object$value) <- paste0(".",class(object$value))
z <- object$con$posZ
colnames(object$value) <- if (is.na(z[1])) object$name else object$name[z]
# print(colnames(object$value))
summary(object$value)
}
'summary.ursaNumeric' <- function(object,...) {
dim(object) <- NULL
class(object) <- paste0(".",class(object))
summary(object)
}
'summary.ursaCategory' <- function(object,...) {
# dim(object) <- NULL
class(object) <- NULL # paste0(".",class(object))
# str(object)
as.table(object)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_summary.R
|
'as.list.ursaRaster' <- function(x,...) ursa_stack(x,...)
'unlist.ursaStack' <- function(x,recursive,use.names) ursa_brick(x)
'ursa_apply' <- function(obj,FUN,...) {
# if (!.is.ursa_stack(res))
# res <- lapply(seq(obj),function(i),FUN=FUN,obj...)
res <- lapply(X=obj,FUN=FUN,...)
if (.is.ursa_stack(res))
class(res) <- "ursaStack"
res
}
'ursa_stack' <- function(...) { ## 'ursa_hetero' (make syn?)
obj <- list(...)
if ((length(obj)==1)&&(is.ursa(obj[[1]]))) {
obj <- obj[[1]]
res <- vector("list",nband(obj))
# names(res) <- bandname(obj)
for (i in seq_along(res)) {
res[[i]] <- obj[i]
}
names(res) <- names(obj)
class(res) <- "ursaStack"
return(res)
}
class(obj) <- "ursaStack"
obj
}
'ursa_brick' <- function(obj) { ## 'ursa_homo' (make syn?)
if (is.ursa(obj))
return(obj)
isList <- .is.ursa_stack(obj)
if (!isList)
return(NULL)
n <- sapply(obj,nband)
nodata <- unique(sapply(obj,ignorevalue))
rname <- unname(unlist(lapply(obj,bandname)))
res <- ursa_new(nband=sum(n))#,bandname=rname)
oname <- names(obj)
k <- 0L
for (i in seq_along(obj)) {
if (!n[i])
next
img <- .extract(obj[[i]])
##~ if (.is.colortable(img)) {
##~ print(img)
##~ print(ursa_colortable(img))
##~ img <- reclass(img)
##~ print(img)
##~ }
nl <- nband(img)
k2 <- k+seq(nl)
res[k2] <- img
if ((!is.null(oname))&&(nl==1)) {
# bandname(res)[k2] <- oname[i]
rname[k2] <- oname[i]
}
k <- k+nl
}
if (all(tail(duplicated(lapply(obj,ursa_colortable)),-1)))
if (length(nodata)==1)
ignorevalue(res) <- nodata
bandname(res) <- rname
if (all(tail(duplicated(lapply(obj,ursa_colortable)),-1))) {
ct <- ursa_colortable(obj[[1]])
if (length(ct)) {
ursa_colortable(res) <- ct
class(ursa_value(res)) <- "ursaCategory"
}
}
# class(res) <- c(class(res),"ursaBrick") ## not necessary
res
}
'.is.ursa_stack' <- function(obj) {
if (is.ursa(obj))
return(FALSE)
if (!is.list(obj))
return(FALSE)
all(sapply(obj,function(x) is.ursa(x) | is.null(x)))
}
'.is.ursa_brick' <- function(obj) is.ursa(obj)
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/classStack.R
|
'print.ursaNumeric' <- function(x,...) {
class(x) <- paste0(".",class(x))
print(summary(x,...))
}
'print.ursaCategory' <- function(x,...) {
# class(x) <- paste0(".",class(x))
print(summary(x,...))
}
'ursa_value' <- function(obj,band) {
if (inherits(obj,c("ursaNumeric","ursaCategory"))) {
if (missing(band))
return(obj)
if (is.character(band))
stop("unable get band index from band name")
val <- obj[,band,drop=FALSE]
class(val) <- class(obj)
return(val)
}
if (!is.ursa(obj))
return(NULL)
if (missing(band))
return(obj$value)
if (is.character(band))
band <- .getBand(obj,band)
val <- obj$value[,band,drop=FALSE]
class(val) <- class(obj$value)
val
}
'ursa_value<-' <- function(obj,band,value) {
if (!is.ursa(obj))
return(NULL)
if (missing(band)) {
dima <- dim(obj$value[])
if (is.null(dima)) {
cl <- class(obj$value)
dima <- obj$dim
obj$value <- array(NA,dim=dima)
class(obj$value) <- cl
}
if (is.ursa(value)) {
dimb <- dim(value$value)
ind <- rep(seq(dimb[2]),length.out=dima[2])
obj$value <- value$value
}
else if (is.array(value)) {
dimb <- dim(value)
if (dima[1]==dimb[1]) {
obj$value[] <- value
}
else if (dima[1]==prod(dimb))
obj$value[] <- value
else {
if ((.is.sparse(value))&&(dima[2]==dimb[2])) {
obj$value <- value
}
else
obj$value[] <- rep(value,length=prod(dima))
}
}
else if ((is.numeric(value))||((length(value)==1)&&(is.na(value)))) {
if (.is.integer(length(value)/obj$dim[1]))
obj$value[] <- value
else if (length(value)==nband(obj)) {
for (i in seq(nband(obj)))
obj$value[,i] <- value[i]
}
else {
obj$value[] <- rep(value,length=prod(dima))
}
}
else {
opW <- options(warn=0)
warning("Optimization is required (condition 3)")
options(opW)
obj[] <- value
}
}
else
{
if (is.character(band))
band <- .getBand(obj,band)
dima <- dim(obj$value[,band,drop=FALSE])
if (is.array(value)) {
if (dima[1]==dim(value)[1])
obj$value[,band] <- value
else if (dima[1]==prod(dim(value)))
obj$value[,band] <- value
else {
opW <- options(warn=0)
warning("Optimization is required (condition 4)")
options(opW)
obj[band] <- value
}
}
else if (is.numeric(value)) {
if (.is.integer(length(value)/dima[1]))
obj$value[,band] <- value
else if (length(value)==dima[2]) {
for (i in seq(dima[2]))
obj$value[,band[i]] <- value[i]
}
else
obj$value[,band] <- rep(value,length=prod(dima))
}
}
class(obj$value) <- if (inherits(value,"ursaCategory")) "ursaCategory"
else "ursaNumeric"
obj
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/classValue.R
|
'compress' <- function(obj) {
if (inherits(obj,c("ursaCategory","ursaNumeric"))) {
if (length(attr(obj,"sparse")))
return(obj)
dimx <- dim(obj)
ind <- .Cursa(C_makeField,as.numeric(obj),dim=dimx
,res=integer(dimx[1]),NAOK=TRUE)$res
ind <- ind[ind!=0L]
if (!length(ind)) {
attr(obj,"sparse") <- NULL ## neccessary?
return(obj)
}
cl <- class(obj)
obj <- obj[ind,,drop=FALSE]
class(obj) <- cl
attr(obj,"sparse") <- ind
.gc()
return(obj)
}
if (!is.ursa(obj))
return(obj)
dimx <- dim(obj$value)
if (is.null(dimx))
return(obj)
dimx2 <- obj$dim
if (!is.na(obj$con$posZ[1]))
dimx2[2] <- length(obj$con$posZ)
if (!identical(dimx2,dimx))
return(obj)
if (length(attr(obj$value,"sparse")))
return(obj)
if (TRUE) {
ind <- .Cursa(C_makeField,as.numeric(obj$value),dim=dimx
,res=integer(dimx[1]),NAOK=TRUE)$res
}
else
{
ind <- apply(obj$value,2,function(x) !all(is.na(x)))
ind <- which(ind)
}
ind <- ind[ind!=0L]
if (!length(ind))
{
attr(obj$value,"sparse") <- NULL ## neccessary?
return(obj)
}
cl <- class(obj$value)
obj$value <- obj$value[ind,,drop=FALSE]
class(obj$value) <- cl
attr(obj$value,"sparse") <- ind #if ((1)&&(n*2>obj$dim[1])) -which(ind2==0L) else ind
obj$dim <- dim(obj$value)
.gc()
obj
}
'decompress' <- function(obj)
{
if (inherits(obj,c("ursaCategory","ursaNumeric"))) {
sparse <- attr(obj,"sparse")
if (is.null(sparse)) ## no compression
return(obj)
g0 <- session_grid()
columns <- g0$columns
rows <- g0$rows
if (all(na.omit(sparse)<0))
sparse <- seq(columns*rows)[sparse]
val <- array(NA,dim=c(columns*rows,dim(obj)[2]))
cl <- class(obj)
val[sparse,] <- obj[]
obj <- val
class(obj) <- cl
attr(obj,"sparse") <- NULL ## neccessary?
.gc()
return(obj)
}
if (!is.ursa(obj))
return(obj)
sparse <- attr(obj$value,"sparse")
if (is.null(sparse)) ## no compression
return(obj)
columns <- obj$grid$columns
rows <- obj$grid$rows
if (all(na.omit(sparse)<0))
sparse <- seq(columns*rows)[sparse]
val <- array(NA,dim=c(columns*rows,obj$dim[2]))
cl <- class(obj$value)
val[sparse,] <- obj$value[]
obj$value <- val
class(obj$value) <- cl
attr(obj$value,"sparse") <- NULL ## neccessary?
obj$dim <- dim(val)
.gc()
obj
}
'.is.sparse' <- function(obj) length(attr(ursa_value(obj),"sparse"))>0
'.is.sparse.deprecated' <- function(obj) {
if (is.ursa(obj))
return(length(attr(ursa_value(obj),"sparse"))>0)
if (inherits(obj,c("ursaNumeric","ursaCategory")))
return(length(attr(obj,"sparse"))>0)
NULL
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/codec.R
|
# TODO Stretch: https://en.wikipedia.org/wiki/Jenks_natural_breaks_optimization
##~ 'categorize' <- 'colored' <- function(...) .syn('colorize',0,...)
'colorize' <- function(obj,value=NULL,breakvalue=NULL,name=NULL
#,col=NULL ## deprecated
,pal=NULL,inv=NA
# ,palname=NULL ## deprecated
,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=FALSE,reset=FALSE
,origin="1970-01-01",format="",alpha=""
,colortable=NULL
,verbose=FALSE,...)
{
fun <- "colorize" #"colorize" ## as.character(as.list(match.call())[1])
if (F)
rel <- mget(names(match.call())[-1])
else {
rel <- as.list(match.call()) # try mget(names(match.call())[-1])
if (!FALSE) { ## ++ 20170629
# .elapsedTime("---")
# print(c('as.character(rel[[1]])'=as.character(rel[[1]])))
# print(c(isPackageInUse=.isPackageInUse()))
# print(c('rel[[1]]'=rel[[1]]))
# try(print(c(a=head(names(as.list(args(rel[[1]]))))),quote=FALSE))
# try(print(c(b=head(names(as.list(args(as.character(rel[[1]])))))),quote=FALSE))
# try(print(c(c=head(names(as.list(args(colorize))))),quote=FALSE))
# try(print(c(d=head(names(as.list(args(ursa::colorize))))),quote=FALSE))
argname <- names(as.list(args(colorize)))
rname <- names(rel)
j <- NULL
# str(rel)
# print(argname)
for (i in seq_along(rel)[-1]) {
if (rname[i]=="obj")
next
if ((is.language(rel[[i]]))&&(rname[i] %in% argname)) {
if (isTRUE(getOption("ursaNoticeMatchCall")))
message('colorize: try `mget(names(match.call())[-1])` instead of `as.list(match.call())`')
res <- eval.parent(rel[[i]])
if (is.null(res))
j <- c(j,i)
else if (is.language(res)) {
res <- eval.parent(res)
if (!is.language(res)) {
assign(rname[i],res)
rel[[i]] <- res
}
else
stop("unable to evaluate agrument ",.sQuote(rname[i]))
}
else
rel[[i]] <- res
}
}
if (length(j))
rel <- rel[-j]
# .elapsedTime("===")
}
else if (TRUE)
rel <- .evaluate(rel,"colorize")
}
if (is.numeric(alpha)) {
## ?adjustcolor
if (all(alpha<=1))
alpha <- round(alpha*255)
alpha[alpha<0] <- 0
alpha[alpha>255] <- 255
alpha <- sprintf("%02X",alpha)
}
col <- NULL ## plug
palname <- NULL ## plug
keepColors <- ncolor
dropIndex <- FALSE
if (missing(obj)) {
if (length(value)) {
# v <- length(value)
obj <- value
dropIndex <- TRUE
}
else if (length(name)) {
v <- length(name)
obj <- seq_len(v)
dropIndex <- TRUE
}
else if (length(breakvalue)) {
v <- length(breakvalue)+1L
obj <- seq_len(v)
dropIndex <- TRUE
}
else if ((is.character(pal))&&(length(pal))) {
v <- length(pal)
obj <- seq_len(v)
dropIndex <- TRUE
}
}
isList <- .is.ursa_stack(obj)
if (isList) { ## recursive!!!
res <- vector("list",length(obj))
oname <- names(obj)
for (i in seq_along(obj)) {
rel[["obj"]] <- quote(obj[[i]])
img <- do.call(fun,rel[-1])
if ((!is.null(oname))&&(nband(img)==1))
bandname(img) <- oname[i]
res[[i]] <- img
rm(img)
}
names(res) <- oname
##~ for (i in seq_along(obj))
##~ res[[i]] <- colorize(obj[[i]])
return(res)
}
if (!is.ursa(obj)) {
daily <- integer()
isTime <- inherits(obj,c("Date","POSIXct","POSIXlt")[2:3])
isDate <- inherits(obj,c("Date","POSIXct","POSIXlt")[1])
# print(c(isCharacter=is.character(obj),isTime=isTime,isDate=isDate))
if (inherits(obj,c("Date","POSIXct","POSIXlt"))) {
# obj <- sort(obj) ## -- 20230611
# od <- sort(unique(diff(sort(unique(obj)))))
if (is.data.frame(obj))
ob <- sort(unique(c(obj)))
else
od <- sort(unique(obj))
if (length(od)>1) {
od <- sort(unique(diff(od)))
if (all(od %% min(od) == 0)) {
os <- seq(min(obj),max(obj),by=min(od))
daily <- match(obj,os)
}
}
# daily <- integer()
obj <- if (nchar(format)) format(obj,format) else as.character(obj)
}
if ((is.numeric(obj))||(is.character(obj))||(is.factor(obj))) {
isOrdered <- is.ordered(obj)
isChar <- is.character(obj) | is.factor(obj)
g1 <- getOption("ursaSessionGrid")
ctname <- .grep("colortable",names(rel),value=TRUE)
if (.is.grid(g1))
session_grid(NULL)
# if ((isDate)||(isTime))
# obj <- sort(obj)
if (isOrdered) {
levname <- levels(obj)
obj <- as.integer(obj)-1L
}
else if (isChar) {
if (length(daily)) {
oname <- as.character(os)
obj <- seq_along(os)
}
else {
oname <- as.character(obj)
obj <- seq_along(obj)
}
}
res <- ursa_new(matrix(rev(obj),nrow=1),flip=FALSE,permute=FALSE) ## rev()?
if ((isChar)&&(!isOrdered)) {
res <- reclass(res,src=seq_along(oname),dst=oname)
if (length(ctname))
ursa(res,"value") <- match(oname,names(rel[[ctname]]))-1L
}
rel[["obj"]] <- quote(res)
if (length(ind <- .grep("lazy",names(rel))))
rel[[ind]] <- FALSE
else
rel[["lazy"]] <- FALSE
if (isTime)
s <- "time"
else if (isDate)
s <- "date"
# else if (isOrdered)
# s <- "category"
else
s <- "default"
if (!length(ind <- .grep("stretch",names(rel))))
rel[["stretch"]] <- s
if (isOrdered) {
if (FALSE) { ## TODO
levvalue <- .deintervale(levname)
if ((is.numeric(levvalue))&&(length(levvalue)+1==length(levname)))
rel[["breakvalue"]] <- seq_along(levname)-1L
else
rel[["value"]] <- seq_along(levname)-1L
}
rel[["name"]] <- levname
}
if ((TRUE)&&(length(ctname))) {
# rel$value <- seq_along(rel[[ctname]])-1L
# rel$name <- names(rel[[ctname]])
# rel$pal <- unclass(unname(rel[[ctname]]))
rel$stretch <- "category"
# rel[[ctname]] <- NULL
# print(c(ursa(res,"value")))
# str(rel)
}
img <- do.call(fun,rel[-1]) ## RECURSIVE!
if (length(ctname)) {
img$colortable <- rel[[ctname]]
}
# if (length(ctname)) {
# str(img)
# q()
# }
if (isOrdered) { ## TODO avoid this double coloring
levvalue <- .deintervale(levname)
if ((is.numeric(levvalue))&&(length(levvalue)+1==length(levname))) {
rel$name <- NULL
rel[["breakvalue"]] <- levvalue
rel[["obj"]] <- quote(discolor(.extract(img)))
# img <- colorize(discolor(.extract(img)),breakvalue=levvalue)
img <- do.call(fun,rel[-1]) ## RECURSIVE!
}
}
if (.is.grid(g1))
session_grid(g1)
else
session_grid(NULL)
if (dropIndex)
return(img$colortable)
if (!length(daily))
return(list(index=c(img$value)+1L,colortable=img$colortable))
return(list(index=daily,colortable=img$colortable))
}
return(list(index=NA,colortable=NA))
}
if (reset) {
obj <- .extract(obj)
ursa_colortable(obj) <- character(0)
class(obj$value) <- "ursaNumeric"
}
if (.is.colortable(obj$colortable)) {
ct <- obj$colortable
if (all(!is.na(ct))) {
if (.is.category(obj)) ## attr(obj$value,"category")
return(obj)
else {
rel$pal <- unclass(unname(ct))
}
}
cname <- .deintervale(ct)
isCategory <- is.character(cname)
if (isCategory) {
ursa_colortable(obj) <- character(0)
rel$name <- cname
rel$value <- seq_along(cname)-1L
# rel$obj <- if (TRUE) quote(obj) else obj
}
else {
if (length(cname)==length(ct)) { ## categoral
# m1: OK for 'obj <- colorize(x,lazy=TRUE);reclass(obj)'
# m2: WANTED TEST!
rel$value <- as.numeric(cname) ## m1, 20170401 removed
# rel$value <- seq_along(as.numeric(cname))-1L ## m2, 20170401 added
rel$breakvalue <- NULL
}
else { ## interval
# rel$breakvalue <- as.numeric(cname) ## 20170401 removed
rel$value <- seq_along(as.numeric(cname))-1L ## 20170401 added
rel$value <- NULL
}
# rel$obj <- if (TRUE) quote(reclass(obj)) else reclass(obj)
}
ursa_colortable(obj) <- character(0)
# rel$obj <- if (!TRUE) quote(.extract(obj)) else .extract(obj)
rel$obj <- quote(obj)
if (TRUE) {## simple but not quick
if (.is.category(obj)) { ## attr(obj$value,"category")
rel$value <- seq(length(ct))-1L
rel$stretch <- ".onetoone"
}
# print("REC CAT -- begin")
# str(rel)
res <- do.call(fun,rel[-1]) ## RECURSIVE
names(res$colortable) <- names(ct)
# print("REC CAT -- end")
}
else { ## dev
if (nchar(palname)) {
maxcol <- 9L
}
if ((is.null(pal))&&(is.null(palname))&&(is.null(col)))
pal <- c("#FFFFAF","#FFBF3F","#FF6F3F","#9F3F9F","#00007F")
else if ((length(col))&&(length(col)!=length(rel$value))) {
pal <- col
}
print(pal)
print(palname)
print(col)
q()
}
return(res)
}
if (.is.colortable(colortable)) {
ct <- ursa_colortable(colortable)
val <- .deintervale(ct,verbose=TRUE)
interval <- as.integer(length(val)!=length(ct))
isChar <- is.character(val)
name <- if (isChar) val else NULL
value <- names(ct)
pal <- as.character(ct)
if (isChar)
val <- seq_along(val)-1L
arglist <- list(obj=quote(obj),interval=interval,value=val,name=name
,pal=pal,lazyload=lazyload)
res <- do.call("colorize",arglist) ## recursive!!!
names(ursa_colortable(res)) <- value
if (FALSE) {
ct2 <- ursa_colortable(res)
print(ct)
print(ct2)
print(names(ct))
print(names(ct2))
print(all.equal(ct2,ct))
q()
}
return(res)
}
stretch <- match.arg(stretch)
if (length(name)) {
ncolor <- length(name)
ramp <- FALSE
# if (stretch=="default")
# stretch <- "category"
}
if (stretch!=".onetoone") {
uniqval <- unique(c(obj$value))
nuniqval <- length(uniqval)
}
if ((is.null(value))&&(!is.null(breakvalue))) {
value <- breakvalue
if (!interval)
interval <- 1L
}
if (stretch=="default")
{
# if ((nuniqval<=21)&&((is.null(value))||(is.null(breakvalue))))
# if (((nuniqval<=21)&&(is.null(value)))||(length(name)))
# if ((nuniqval<=21)&&(is.null(value)))
if (((nuniqval<=21)&&(is.null(value)))||((length(name))&&(length(name)>nuniqval)))
{
ncolor <- nuniqval
stretch <- "category"
if ((is.null(palname))&&(is.null(pal))) {
# palname <- "Paired" ## "random"
if (dev <- T) {
arglist <- list(...)
myname <- names(arglist)
ind <- .grep("^pal\\.",myname)
if (length(ind)) {
arglist <- arglist[ind]
names(arglist) <- .gsub("(^pal\\.)","",myname[ind])
arglist <- c(list(value=uniqval),arglist)
pal <- do.call("cubehelix",arglist)
}
else
pal <- cubehelix(value=uniqval)#,rotate=2.5)
}
else
pal <- cubehelix(value=uniqval)#,rotate=2.5)
inv <- FALSE
}
}
else if (storage.mode(obj$value)=="integer") {
val <- c(obj$value)
if ((is.null(palname))&&(is.null(pal))) {
if ((min(val,na.rm=TRUE)<50)&&
((max(val,na.rm=TRUE)>200) && (max(val,na.rm=TRUE)<=255))) {
palname <- "Greys"
if (is.na(inv))
inv <- TRUE
}
}
}
}
if ((is.na(ncolor))&&(!is.na(nbreak))) { ## added 2015-11-18
ncolor <- nbreak+1L
if (!interval)
interval <- 1L
}
if ((is.null(value))&&(!is.na(ncolor))&&(interval %in% c(1L)))
ncolor <- ncolor-1L ## added 2015-11-17
# print(c(nbreak=nbreak,ncolor=ncolor,keepColors=keepColors))
if (!is.na(ncolor)) ## added 20170103
ramp <- FALSE
if (is.na(ncolor))
{
if ((FALSE)&&(length(col))&&(!is.na(col)[1]))
ncolor <- length(col)
else if (ramp)
ncolor <- 255L
else {
if (!(stretch %in% c("bathy")))
ncolor <- 11L
if ((interval %in% c(1L))) { # && stretch %in% c("diff","slope"))
ncolor <- 10L
}
}
}
if ((length(value)>0)&&(length(name)>0)) {
if ((interval==0)&&(length(value)!=length(name)))
name <- NULL
else if (interval>0) {
if ((interval==1)&&(length(name) %in% (length(value)+c(0)))) {
n0 <- name
if (length(n0)>1)
name <- paste0("(",n0[-length(n0)],";",n0[-1],"]")
name <- c(paste0("<= ",n0[1]),name,paste0("> ",n0[length(n0)]))
}
if ((interval>0)&&((length(value)+1)!=length(name))) {
name <- NULL
}
}
}
if (is.null(palname)) {
if (FALSE) ## 20170105 test for disabling RColorBrewer
palname <- switch(stretch,slope="RdBu",diff="RdBu",sd="YlGnBu"
,linear="cubehelix",equal="cubehelix"
,mean="Spectral",conc="Blues"
,positive="Oranges",negative="Purples"
,rainbow=".rainbow",category="Paired" ##"random"
,julian="YlGn"
,significance=c("RdBu","PuOr")[2],aspect=".rainbow"
,grayscale="Greys",greyscale="Greys"
,c("cubehelix","RdYlBu")[1]) ## default "RdYlBu"
else { ## rownames(RColorBrewer::brewer.pal.info)
if ((is.character(pal))&&(length(pal)==1)&&(pal %in% c("dummycolornamewhichisabsent"
,"BrBG","PiYG","PRGn","PuOr","RdBu","RdGy"
,"RdYlBu","RdYlGn","Spectral","Accent","Dark2","Paired"
,"Pastel1","Pastel2","Set1","Set2","Set3","Blues"
,"BuGn","BuPu","GnBu","Greens","Greys","Oranges"
,"OrRd","PuBu","PuBuGn","PuRd","Purples","RdPu"
,"Reds","YlGn","YlGnBu","YlOrBr","YlOrRd"
# ,"terrain.colors"
)))
palname <- pal
else
palname <- "cubehelix"
}
}
if (stretch=="conc")
{
if ((!is.na(ignorevalue(obj)))&&(ignorevalue(obj)==0))
{
minvalue <- 1
maxvalue <- 101
}
else
{
minvalue <- 0
maxvalue <- 100
}
if (is.na(inv))
inv <- TRUE
palname <- "Blues"
}
else if (stretch=="sd")
{
if (is.na(inv))
inv <- FALSE
stretch <- "positive"
}
else if (stretch=="positive") {
if (is.na(inv))
inv <- FALSE
}
else if (stretch=="negative") {
if (is.na(inv))
inv <- TRUE
}
else if (stretch=="significance")
{
value <- c(-0.999,-0.99,-0.95,-0.9,-0.5,0.5,0.9,0.95,0.99,0.999)
interval <- TRUE
}
else if (stretch=="bathy")
{
palname <- "Blues"
inv <- FALSE
interval <- 1L
if (is.na(ncolor))
ncolor <- 21L
stretch <- "equal"
}
if (FALSE) {
if (((stretch=="default")&&(is.null(pal))&&(is.null(col)))||
(palname %in% c("zzz.internal"))) {
if (palname=="make.your.own.here")
pal <- c("#FFFFAF","#FFBF3F","#FF6F3F","#9F3F9F","#00007F")
else if (palname=="viridis")
pal <- c("#FFFFAF","#FFBF3F","#FF6F3F","#9F3F9F","#00007F")
else if (palname=="cubehelix") {
pal <- cubehelix
}
}
}
isCharOneToOne <- is.character(.deintervale(name))
if ((is.null(pal))&&(stretch %in% c("default"))) {
if (palname %in% c("cubehelix")) {
if (TRUE) {
pal <- cubehelix
}
else {
if (isCharOneToOne) {
if (length(unique(name))<12) {
pal <- cubehelix(11)
}
else {
pal <- cubehelix(11,rotate=sample(c(-1,1),1)*2.5*360)
pal <- sample(pal)
}
}
else if (FALSE)
palname <- "Paired"
else {
pal <- cubehelix
}
}
}
else if (palname=="viridis")
pal <- c("#FFFFAF","#FFBF3F","#FF6F3F","#9F3F9F","#00007F")
}
if ((FALSE)&&(stretch==".onetoone")) { ## disable 20170112
if (isCharOneToOne) {
palname <- "Paired"
# pal <- cubehelix
}
}
maxcol <- 9L
if (!is.null(pal)) {
if (is.na(inv))
inv <- FALSE
}
else if (palname %in% c("Spectral","RdYlGn","RdYlBu","RdGy","RdBu"
,"PuOr","PRGn","PiYG","BrBG"))
{
if (is.na(inv))
inv <- TRUE
maxcol <- ifelse(stretch=="slope" & palname!="Spectral",9L,11L)
}
else {
if ((is.na(inv))&&(palname=="Greys"))
inv <- TRUE
else if (is.na(inv))
inv <- FALSE
if (palname %in% c("Set2","Pastel2","Dark2","Accent"))
maxcol <- 8L
else if (palname %in% c("Set3","Paired"))
maxcol <- 12L
else if (palname %in% c(".rainbow"))
stop("HERE")
}
##~ pal <- colorRampPalette(brewer.pal(maxcol,palname))
##~ pal <- rgb(runif(maxcol),runif(maxcol),runif(maxcol)))
##~ pal <- sample(colorspace::rainbow_hcl(maxcol,l=75,c=80))
if ((FALSE)&&(!is.null(value))) ## added 20160127
value <- as.numeric(format(value,trim=TRUE))
if (stretch=="category")
{
arglist <- list(...)
if (("forceLabel" %in% names(arglist))&&((arglist[["forceLabel"]])))
ncolor <- 999L
interval <- 0L
if (storage.mode(obj$value)=="double") {
obj$value <- round(obj$value,11)
class(obj$value) <- "ursaNumeric"
}
val <- c(obj$value)
if (!is.null(value)) {
v2 <- value
toSort <- FALSE
n0 <- length(v2)
}
else {
v1 <- c(na.omit(sort(unique(val))))
toSort <- length(v1)>ncolor
if (toSort)
v1 <- rev(v1)
n0 <- ifelse(!toSort,length(v1),ncolor-1)
v2 <- if (toSort) rev(v1[seq(n0)]) else v1[seq(n0)]
}
val[!is.na(val)] <- 0
for (i in seq_along(v2))
val[obj$value==v2[i]] <- i-!toSort#-other
obj$value[] <- val
storage.mode(obj$value) <- "integer"
ignorevalue(obj) <- n0+toSort
ok <- FALSE
if (length(v2)>1) {
# print(v2,digits=12)
for (i2 in -6:+6) ## -4:+4
{
v3 <- unique(round(v2*10^i2))
if (length(v3)==length(v2))
{
if ((i2==0)&&(!all((v2-floor(v2)) %in% c(0,1))))
next
if (all(v3 %in% c(0,1))) ## added 20150815 (fail for 0.0500001 rounding)
next
# if ((i2<(9))&&(any(abs(v3-v2*(10^i2))>0.499)))
# next
if (TRUE) { ## 20190306 ++
v4 <- na.omit(v3*10^(-i2)/v2)
if ((length(v4))&&(any(abs(v4-1)>0.101)))
next
}
ok <- TRUE
break
}
}
}
else if (length(v2)<(+2)) {
iv2 <- try(as.integer(v2))
if ((is.integer(v2))&&(!is.na(v2))&&(abs(v2-iv2)>.Machine$double.eps)) {
.v2 <- pretty(v2*(1+c(-1,0,1)*1e-3),n=2)
v2 <- .v2[which.min(abs(.v2-v2))[1]]
}
}
label2 <- as.character(v2)
if (!ok)
label <- label2
else
{
if (i2<(0)) {
# cat("--- RR2 begin\n")
# print(i2)
# print(v2)
# options(warn=-10)
# label <- sprintf("%%f",as.double(round(v2,i2+1)))
# label <- sprintf(sprintf("%%.0f",i2),as.double(round(v2,i2+1)))
# label <- sprintf(sprintf("%%.0f",i2),as.double(v2)) ## --20210520
label <- sprintf("%.0f",as.double(v2)) ## ++20210520 or
# label <- sprintf("%.0f",as.double(round(v2,i2+1))) ## ++20210520 or
# label <- sapply(as.double(v2),function(v9) sprintf(sprintf("%%.0f",i2),v9)) ##++
# label <- format(v2,trim=TRUE,scientific=FALSE)
# label <- label2
# i2 <- 0
# cat("--- RR2 end\n")
}
else {
# print(i2)
label1 <- sprintf(sprintf("%%.%df",i2),as.double(v2))
label <- if (max(nchar(label2))+0==max(nchar(label1))) label2 else label1
}
hasZero <- any(v2==0)
while((length(label)!=length(unique(label)))||
((!hasZero)&&(any(as.numeric(label)==0))))
{
i2 <- i2+1
# message(paste("i2 chanded from",i2-1,"to",i2))
if (i2<0)
next
else
label <- sprintf(sprintf("%%.%df",i2),as.double(v2))
}
sl <- unique(substr(label,nchar(label)-1,nchar(label)))
if ((length(sl)==1)&&(sl==".0")) {
# label <- sprintf(sprintf("%%.0f",i2),as.double(label)) ## -- 20210916
label <- sprintf(sprintf("%%.%df",i2),as.double(label)) ## ++ 20210916
}
dv <- diff(sort(v2))
if (length(dv))
dv <- dv/min(dv)
v3 <- abs(v2)
v3 <- v3[v3!=0]
if ((length(dv)==1)&&(.is.integer(v2[2]/v2[1]))) {
label <- label3 <- as.character(as.numeric(format(v2,trim=TRUE,scientific=FALSE)))
}
else if ((length(dv)>1)&&((.is.integer(dv))||(.is.integer(v3/min(v3)))))
label <- label3 <- format(v2,trim=TRUE,scientific=FALSE)
else {
for (i2 in 1:12) {
label3 <- format(v2,trim=TRUE,scientific=FALSE,digits=1,nsmall=i2)
if (length(label3)==length(v2))
break
}
}
}
if (FALSE) {
message("---------")
print(i2)
print(.is.integer(dv))
print(label2,quote=FALSE)
message("|")
print(label3,quote=FALSE)
message("|")
print(label,quote=FALSE)
message("=========")
}
if (is.null(name))
name <- if (toSort) c(paste0("/",length(v1)-ncolor,"/"),label)
else as.character(label)
n <- length(name)
if (is.null(col))
{
if ((palname=="random")||(is.null(pal)))
{
##~ if ((palname=="Paired")&&(n<maxcol))
##~ col <- colorRampPalette(sample(brewer.pal(maxcol,palname)))(n)
##~ else if (palname!="Paired")
##~ col <- colorRampPalette(brewer.pal(maxcol,palname))(n)
if (palname %in% c("cubehelix","random")) {
pal <- "cubehelix"
arglist <- list(...)
myname <- names(arglist)
ind <- .grep("^pal\\.",myname)
if (length(ind)) {
arglist <- arglist[ind]
names(arglist) <- .gsub("(^pal\\.)","",myname[ind])
arglist <- c(n=n,arglist)
col <- do.call(pal,arglist)
}
else
col <- do.call(pal,list(n=n))#,dark=191,light=191))
if (palname=="random")
col <- sample(col)
}
else {
message("BREWER A -- not-reproduced ")
stop("Unexpected branch A which is required deprecated 'RColorBrewer'")
##~ requireNamespace("RColorBrewer",quietly=.isPackageInUse())
##~ if (n<maxcol) {
##~ col <- colorRampPalette(sample(
##~ RColorBrewer::brewer.pal(maxcol,palname)))(n)
##~ }
##~ else
##~ {
##~ c1 <- RColorBrewer::brewer.pal(maxcol,palname)
##~ c2 <- NULL
##~ k <- rep(ceiling(2*n/maxcol),maxcol/2)
##~ if (sum(k)>n)
##~ {
##~ ind <- sample(seq(length(k)),sum(k)-n)
##~ k[ind] <- k[ind]-1L
##~ }
##~ j <- seq(1,maxcol-1,by=2)
##~ for (i in seq_along(j))
##~ {
##~ i2 <- j[i]
##~ c2 <- c(c2,colorRampPalette(c1[c(i2+1,i2)])(k[i]))
##~ }
##~ col <- sample(c2)
##~ }
}
}
else {
if (is.function(pal)) {
arglist <- list(...)
myname <- names(arglist)
ind <- .grep("^pal\\.",myname)
if (length(ind)) {
arglist <- arglist[ind]
names(arglist) <- .gsub("(^pal\\.)","",myname[ind])
arglist <- c(n=n,arglist)
col <- do.call(pal,arglist)
}
else
col <- pal(n)
}
else if (is.character(pal)) {
if ((length(pal)==1)&&(!.lgrep("^#[0-9A-F]+$",pal))&&
(requireNamespace("RColorBrewer",quietly=.isPackageInUse()))) {
available <- RColorBrewer::brewer.pal.info
if (!is.na(ind <- match(pal,rownames(available)))) {
pal <- RColorBrewer::brewer.pal(available$maxcolors[ind],pal)
if (available$category[ind]=="qual")
pal <- sample(pal)
}
else if (pal %in% available$category) {
selected <- available[sample(which(available$category==pal),1),]
pal <- RColorBrewer::brewer.pal(selected$maxcolors,rownames(selected))
if (rownames(selected)=="qual")
pal <- sample(pal)
}
}
## 20180316 added alpha=TRUE
col <- colorRampPalette(unlist(strsplit(pal,split="\\s+")),alpha=TRUE)(n)
}
else
stop("Unable interpret 'pal' argument")
}
if (inv)
col <- rev(col)
}
obj <- .as.colortable(obj,col=col,name=name,alpha=alpha)
class(obj$value) <- "ursaCategory"
return(obj)
}
# labels <- ncolor ## (TODO: keep desired labels if ramp=TRUE)
if ((FALSE)&&(ramp))# &&(!is.na(keepColors))?
{
# interval <- 0L
if (ncolor<21)
ncolor <- 255
}
if (stretch=="equal")
{
val <- sort(c(na.omit(c(obj$value))))
for (mycol in seq(ncolor,11*(ncolor-1)+1,by=2))
{
if (interval %in% c(0L))
th <- seq(0,1,length=mycol*2+1)[seq(mycol)*2]
else if (interval %in% c(1L,2L))
{
th <- seq(0,1,length=mycol+2)
th <- th[-c(1,length(th))]
}
value <- unique(val[round(length(val)*th)])
if (length(value) >= ncolor) {
break
}
}
ok <- FALSE
for (i2 in -6:+6) ## -4:+4
{
v <- unique(round(value*10^i2))
if ((length(value)==1)&&(v==0))
next
if (length(v)==length(value))
{
if ((i2==0)&&(!all((value-floor(value)) %in% c(0,1))))
next
ok <- TRUE
break
}
}
# ok <- FALSE
if (!ok)
{
event <- FALSE
for (i2 in 1:3)
{
label <- format(value,trim=TRUE,digits=i2)
if (length(unique(label))==length(value)) {
event <- TRUE ## added 20190619
break
}
}
if (!event) {
label <- unique(label)
value <- as.numeric(label)
}
}
else
{
# i2 <- i2+1 ##
if (i2<0) {
# label <- sprintf(sprintf("%%f",i2),as.double(round(value,i2+1))) # --
label <- sprintf("%.0f",as.double(round(value,i2+1))) # ++ 20210524
i2 <- 0
# label <- sprintf(sprintf("%%f",i2),as.double(value))
}
else
label <- sprintf(sprintf("%%.%df",i2),as.double(value))
while(length(label)!=length(unique(label)))
{
i2 <- i2+1
label <- sprintf(sprintf("%%.%df",i2),as.double(value))
}
sl <- unique(substr(label,nchar(label)-1,nchar(label)))
if ((length(sl)==1)&&(sl==".0")) {
label <- sprintf(sprintf("%%.0f",i2),as.double(value))
}
value <- as.numeric(label)
}
names(value) <- label
rm(val,th,label)
}
if (!length(value))
{
# ncol <- 11L ## desirable number of colors
val <- sort(na.omit(c(obj$value)))
if (!is.na(byvalue)) {
minb <- floor(min(val)/byvalue)*byvalue
maxb <- ceiling(max(val)/byvalue)*byvalue
ncolor <- (maxb-minb)/byvalue
rm(minb,maxb)
}
if (any(is.na(tail))) {
tail <- 0.11/ncolor
# print(c(colors=ncolor,tail=tail))
}
tail <- rep(tail,2)
if (!is.na(ltail))
tail[1] <- ltail
if (!is.na(rtail))
tail[2] <- rtail
if ((stretch %in% c("positive","negative"))&&(interval %in% c(-1L)))
ncolor <- ncolor+1L
n <- length(val)
lo <- floor(n*tail[1])
hi <- n-floor(n*tail[2])+1
if (T) { ## ++ 20210111
lo <- lo+1
hi <- hi-1
}
if ((lo<=1)||(hi>n)) {
rngv <- (c(lo,hi)-1)*(max(val)-min(val))/(n-1)+min(val)
}
minv <- if (lo>0) val[lo] else if (n) rngv[1] else 0
maxv <- if (hi<=n) val[hi] else if (n) rngv[2] else 1
if (verbose)
print(data.frame(n=n,lo=lo,hi=hi,minv=minv,maxv=maxv,min=min(val),max=max(val)))
if (stretch %in% c("diff","slope"))
{
extv <- max(abs(minv),abs(maxv))
minv <- -extv
maxv <- extv
rm(extv)
}
if (is.na(minvalue))
minvalue <- minv
if (is.na(maxvalue))
maxvalue <- maxv
if (!is.na(byvalue)) {
minb <- floor(minvalue/byvalue)*byvalue
maxb <- ceiling(maxvalue/byvalue)*byvalue
ncolor <- (maxb-minb)/byvalue
}
rm(n,lo,hi,minv,maxv,val)
if (verbose)
print(data.frame(stretch=stretch,min=minvalue,max=maxvalue))
byv <- ifelse(interval %in% c(1L),0.75,0.25)*(maxvalue-minvalue)/ncolor
minvalue <- minvalue+byv
maxvalue <- maxvalue-byv
if (stretch=="positive")
minvalue <- 0
else if (stretch=="negative")
maxvalue <- 0
if (maxvalue<minvalue) {
.m <- c(maxvalue,minvalue)
minvalue <- .m[1]
maxvalue <- .m[2]
rm(.m)
}
if (verbose)
print(data.frame(colors=ncolor,min=minvalue,max=maxvalue))
# str(ncolor)
if (interval %in% c(2L,3L)) {
ncolor <- (ncolor-1)*2+1
}
# str(ncolor)
# q()
if (!is.na(byvalue)) {
value <- seq(minb,maxb,by=byvalue)
rm(minb,maxb)
names(value) <- value
}
else {
if ((ramp)||(ncolor>51)) {
if (stretch %in% c("julian")) {
minvalue <- floor(minvalue)
maxvalue <- ceiling(maxvalue)
ncolor <- as.integer(maxvalue-minvalue+1)
mc <- seq(minvalue,maxvalue,by=1)
}
else {
if ((byte)&&(is.na(keepColors)))
keepColors <- 255L
# if (ncolor>nuniqval)
# ncolor <- nuniqval
for (i in 1:101) {
mc <- pretty(c(minvalue,maxvalue),n=ncolor,min.n=ncolor%/%1.5)
# print(c(i=i,colors=ncolor,pretty=length(mc)))
if (is.na(keepColors))
break
if (length(mc)<=keepColors)
break
ncolor <- ncolor-1
if (ncolor<2)
break
}
}
lab <- format(mc,trim=TRUE)
if (length(unique(lab))==-1) {
for (dig in seq(16)) {
lab <- format(mc,trim=TRUE,digits=dig)
if (length(unique(lab))>1)
break
}
mc <- as.numeric(lab)
}
else if (length(unique(lab))<length(mc)) {
for (dig in seq(16)) {
lab <- unique(format(mc,trim=TRUE,digits=dig))
if (length(lab)>1)
break
}
mc <- as.numeric(lab)
ncolor <- length(mc)
}
mc <- data.frame(at=mc,lab=lab,stringsAsFactors=FALSE)
if (FALSE)
cat(sprintf("colors(ramp)=%d\n",nrow(mc)))
}
else {
if (ncolor==1) {
mc <- .prettyLabel(c(minvalue,maxvalue),ncol=3,onPanel=TRUE)
if (nrow(mc)==3) {
mc <- mc[2,]
}
else
mc <- .prettyLabel(c(minvalue,maxvalue),ncol=ncolor,onPanel=TRUE)
}
else
mc <- .prettyLabel(c(minvalue,maxvalue),ncol=ncolor,onPanel=TRUE)
if (nrow(mc)==0) {
mc <- pretty(c(minvalue,maxvalue),n=ncolor,min.n=ncolor%/%1.5)
mc <- data.frame(at=mc,lab=format(mc,trim=TRUE),stringsAsFactors=FALSE)
}
}
if (interval %in% c(2L))
{
ind <- which(abs(mc$at)<1e-15)
if ((!length(ind))||(ind%%2==0))
mc <- mc[seq(1,ncolor,by=2),]
else
mc <- mc[seq(2,ncolor,by=2),]
# mc <- subset(mc,!is.na(at))
mc <- mc[which(!is.na(mc$at)),]
ncolor <- (ncolor-1)/2+1
}
if ((stretch %in% c("positive","negative"))&&(interval))
{
if (length(ind <- which(mc$at==0.0)))
mc <- mc[-ind,]
}
if (verbose)
print(mc)
value <- mc$at
if (stretch=="date")
mc$lab <- as.Date(mc$at,origin=origin)
else if (stretch=="time")
mc$lab <- as.POSIXct(mc$at,origin=origin)
if ((nchar(format))&&(stretch %in% c("date","time","julian"))) {
if (stretch %in% "julian")
mc$lab <- as.Date(paste0("2018",mc$lab),format="%Y%j")
mc$lab <- format(mc$lab,format)
}
names(value) <- mc$lab
}
}
if (!interval)
ivalue <- c(-Inf,value[-1]-diff(value)/2,+Inf)
else
ivalue <- c(-Inf,value,+Inf)
ivalue <- unname(ivalue)
if (verbose)
print(ivalue)
if ((!lazyload)&&(stretch!=".onetoone")) {
val <- c(obj$value)
if (verbose)
.elapsedTime("reclass:start")
if (FALSE)
{
for (i in seq_along(ivalue)[-1])
{
if (verbose)
print(c(i-2,ivalue[i-1],ivalue[i]))
val[obj$value>ivalue[i-1] & obj$value<=ivalue[i]] <- i-2
}
}
else if (FALSE)
{
ind <- is.na(val)
if (!all(ind))
{
nodata <- ceiling(max(val,na.rm=TRUE))+1
val[ind] <- nodata
ivalue[ivalue==-Inf] <- -1e38
ivalue[ivalue==Inf] <- +1e38
val <- .Cursa(C_reclassify,src=as.numeric(val),n=as.integer(length(val))
,nodata=as.numeric(nodata)
,class=as.numeric(ivalue),nclass=length(ivalue)
,dst=integer(length(val)),NAOK=TRUE)$dst
val[ind] <- NA
}
}
else ## less memory usage
{
ind <- which(!is.na(val))
if (length(ind))
{
nodata <- ceiling(max(val,na.rm=TRUE))+1
ivalue[ivalue==-Inf] <- -1e38
ivalue[ivalue==Inf] <- +1e38
val[ind] <- .Cursa(C_reclassify,src=as.numeric(val[ind])
,n=as.integer(length(ind))
,nodata=as.numeric(nodata)
,class=as.numeric(ivalue),nclass=length(ivalue)
,dst=integer(length(ind)),NAOK=!FALSE)$dst
}
}
if (verbose)
.elapsedTime("reclass:finish")
obj$value[] <- val
storage.mode(obj$value) <- "integer"
}
if (!length(name))
{
if (stretch=="zzzsignificance")
n0 <- as.character(abs(value))
else if (stretch %in% c("julian")) {
repeat({
if (!length(ind <- which(value>365)))
break
value[ind] <- value[ind]-365
})
n0 <- format(as.Date(sprintf("2019%03d",as.integer(value)),"%Y%j")
,ifelse(nchar(format),format,"%d%b"))
}
else if (stretch=="zzzdate") {
n0 <- format(as.Date(value,origin=origin)
,ifelse(!nchar(format),"%Y-%m-%d",format))
}
else if (!is.null(names(value)))
n0 <- names(value)
else if (inherits(value,"Date")) {
n0 <- format(value,ifelse(!nchar(format),"%Y-%m-%d",format))
}
else {
if (stretch %in% c("category","equal"))
n0 <- as.character(value)
else {
n0 <- format(value,trim=TRUE)
}
}
##~ print(n0)
##~ print(col)
##~ print(length(n0))
##~ print(length(col))
if (interval)
{
# if (minval<min(value))
# value <- c(minval,value)
# if (maxval>max(value))
# value <- c(value,maxval)
if (length(n0)>1)
name <- paste0("(",n0[-length(n0)],";",n0[-1],"]")
name <- c(paste0("<= ",n0[1]),name,paste0("> ",n0[length(n0)]))
}
else
name <- n0
}
if ((verbose)&&(!lazyload))
{
vt <- table(c(obj$value))
names(vt) <- name[as.integer(names(vt))+1]
print(vt)
}
n <- length(name)
if (!is.null(col))
inv <- FALSE
else
{
if (palname=="random") {
arglist <- list(...)
myname <- names(arglist)
ind <- .grep("^pal\\.",myname)
if (length(ind)) {
arglist <- arglist[ind]
names(arglist) <- .gsub("(^pal\\.)","",myname[ind])
arglist <- c(list(n=n,value=unname(value)),arglist)
col <- do.call("cubehelix",arglist)
}
else
col <- cubehelix(n,value=unname(value))
col <- sample(col)
}
else if (is.null(pal)) {
if ((stretch==".onetoone")&&(isCharOneToOne)) {
if (FALSE) {
message("BREWER C -- fixed")
##~ col <- RColorBrewer::brewer.pal(maxcol,palname)
##~ if (n<maxcol)
##~ col <- sample(col,n)
##~ else
##~ col <- colorRampPalette(sample(col))(n)
}
else {
arglist <- list(...)
myname <- names(arglist)
ind <- .grep("^pal\\.",myname)
if (length(ind)) {
arglist <- arglist[ind]
names(arglist) <- .gsub("(^pal\\.)","",myname[ind])
arglist <- c(list(n=n,value=unname(value)),arglist)
col <- do.call("cubehelix",arglist)
}
else
col <- cubehelix(n,rotate=sample(c(-360,360),1)*
runif(1,min=0.8,max=1.2)*(n/11)^0.75)
}
}
else {
arglist <- list(...)
myname <- names(arglist)
ind <- .grep("^pal\\.",myname)
if (length(ind)) {
arglist <- arglist[ind]
names(arglist) <- .gsub("(^pal\\.)","",myname[ind])
}
else
arglist <- list()
arglist <- c(list(n=n,value=unname(value)),arglist)
if (palname=="cubehelix") {
if (TRUE) {
col <- do.call("cubehelix",arglist)
}
else {
arglist <- list(...)
myname <- names(arglist)
ind <- .grep("^pal\\.",myname)
if (length(ind)) {
arglist <- arglist[ind]
names(arglist) <- .gsub("(^pal\\.)","",myname[ind])
arglist <- c(list(n=n,value=unname(value)),arglist)
col <- do.call("cubehelix",arglist)
}
else
col <- cubehelix(n,value=unname(value))
}
}
else {
if (FALSE) {
message("BREWER B -- fixed")
##~ requireNamespace("RColorBrewer",quietly=.isPackageInUse())
##~ col <- colorRampPalette(RColorBrewer::brewer.pal(maxcol,palname))(n)
}
else {
if (palname=="Greys") {
arglist$hue <- 0
}
if (palname=="Blues") {
arglist$rotate <- 45
arglist$hue <- 1.5
}
col <- do.call("cubehelix",arglist)
}
}
}
}
else {
if (is.function(pal)) {
arglist <- list(...)
myname <- names(arglist)
ind <- .grep("^pal\\.",myname)
if (length(ind)) {
arglist <- arglist[ind]
names(arglist) <- .gsub("(^pal\\.)","",myname[ind])
fname <- names(formals(pal))
if ("value" %in% names(formals(pal)))
arglist <- c(list(n=n,value=unname(value)),arglist)
else
arglist <- c(list(n=n),arglist)
col <- do.call(pal,arglist)
}
else {
argname <- names(as.list(args(pal)))
if ("value" %in% argname) {
col <- pal(n,value=unname(value))
}
else {
col <- pal(n)
}
}
}
else if (is.character(pal)) {
if ((length(pal)==1)&&
(requireNamespace("RColorBrewer",quietly=.isPackageInUse()))) {
available <- RColorBrewer::brewer.pal.info
if (!is.na(ind <- match(pal,rownames(available)))) {
pal <- RColorBrewer::brewer.pal(available$maxcolors[ind],pal)
if (available$category[ind]=="qual")
pal <- sample(pal)
}
else if (pal %in% available$category) {
selected <- available[sample(which(available$category==pal),1),]
pal <- RColorBrewer::brewer.pal(selected$maxcolors,rownames(selected))
if (rownames(selected)=="qual")
pal <- sample(pal)
}
##~ else if (pal %in% c("terrain.colors")) {
##~ str(pal)
##~ stop("0204")
##~ }
}
col <- colorRampPalette(unlist(strsplit(pal,split="\\s+"))
,alpha=TRUE)(n)
}
else
stop("Unable interpret 'pal' argument")
}
if (inv)
col <- rev(col)
}
obj <- .as.colortable(obj,col=col,name=name,alpha=alpha)
class(obj$value) <- ifelse(lazyload,"ursaNumeric","ursaCategory")
if (!lazyload)
ignorevalue(obj) <- n
else if (is.na(ignorevalue(obj)))
ignorevalue(obj) <- .optimal.nodata(ursa_value(obj))
obj
}
'.as.colortable' <- function(x,value=NULL,name=NULL,blank="",col=NULL
,alpha="",colored=FALSE)
{
# str(list(value=value,name=name,col=col,colored=colored))
if (!is.ursa(x))
return(NULL)
if ((length(value)>0)&&(length(value)==length(name)))
val <- value
else if (colored)
val <- seq(0,max(x$value,na.rm=TRUE),by=1)
else if (!length(col))
val <- sort(unique(c(x$value)))
else
val <- seq(col)-1L
n <- length(val)
if (length(name)==length(val))
cname <- name
else
cname <- paste0(blank,val)
if (length(col)==n)
val <- col
else if (colored)
val <- grDevices::rgb(runif(n),runif(n),runif(n))
val <- t(grDevices::col2rgb(val,alpha=TRUE))
if (any(!is.na(val)))
val <- grDevices::rgb(val[,1],val[,2],val[,3],val[,4],max=255)
if (nchar(alpha)==2) ## if (toupper(alpha)!="")
val <- paste0(substr(val,1,7),toupper(alpha))
# val <- paste0(val,alpha)
names(val) <- cname
class(val) <- "ursaColorTable"
x$colortable <- val
x
}
'palettize' <- function(...) {
arglist <- list(...)[[1]]
# cat("---------\n")
# str(arglist)
if (length(ind <- which(sapply(arglist,.is.colortable)))) {
ret <- arglist[[ind]]
return(ret)
}
# cat("---------\n")
ursa_colortable(colorize(...))
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/colorize.R
|
'compose_close' <- function(...) {
if (.skipPlot(FALSE))
return(invisible(NULL))
arglist <- list(...)
kind <- .getPrm(arglist,name="(^$|crop|kind)",valid=c("crop","crop2","nocrop"))
border <- .getPrm(arglist,name="(border|frame)",default=5L)
bpp <- .getPrm(arglist,name="bpp",valid=c(8L,24L)
,default=switch(getOption("ursaPngDevice"),windows=8L,cairo=24L,24L))
execute <- .getPrm(arglist,name="(execute|view|open|render)",default=!.isShiny())
# if (isTRUE(Sys.getenv("_R_CHECK_PACKAGE_NAME_")=="ursa"))
# execute <- FALSE
verbose <- .getPrm(arglist,name="verb(ose)*",kwd="close",default=FALSE)
# wait <- .getPrm(arglist,name="wait",default=NA_real_)
.compose_close(kind=kind,border=border,bpp=bpp,execute=execute#,wait=wait
,verbose=verbose)
}
'.compose_close' <- function(kind=c("crop2","crop","nocrop")
,border=5,bpp=0,execute=TRUE#,wait=NA
,verbose=FALSE) {
sysRemove <- TRUE
if (verbose)
str(list(kind=kind,border=border,bpp=bpp,execute=execute,verbose=verbose))
isPackageTest <- isTRUE(Sys.getenv("_R_CHECK_PACKAGE_NAME_")=="ursa")
toOpen <- !isPackageTest & session_pngviewer()
if (FALSE) {
message(paste(commandArgs(FALSE),collapse=" "))
print(Sys.getenv()[grep("^(_)*R_",names(Sys.getenv()))])
}
delafter <- getOption("ursaPngDelafter")
fileout <- getOption("ursaPngFileout")
isJPEG <- .lgrep("(jpg|jpeg)",gsub(".*\\.(.+$)","\\1",fileout))>0
isWEBP <- .lgrep("(webp)",gsub(".*\\.(.+$)","\\1",fileout))>0
if (!(bpp %in% c(8,24)))
bpp <- switch(getOption("ursaPngDevice")
,windows=ifelse(isJPEG | isWEBP,24L,8L),cairo=24L,24L)
on.exit({
op <- options()
if (length(ind <- .grep("^ursaPng.+",names(op))))
options(lapply(op[ind],function(x) NULL))
NULL
})
if (sysRemove & execute) { ## patch for "shell"
sysWait <- FALSE
con <- showConnections(all=TRUE)
ind <- which(!is.na(match(con[,"class"],"file")))
if (length(ind)) { ## FAILURES with connections: 1) unpacked, 2) being to pack
if (tryToRepair <- FALSE) {
con <- con[ind,,drop=FALSE]
print(con)
unable <- grep("\\.unpacked(.*)\\~$",con[,"description"])
if (length(unable)) {
opW <- options(warn=1)
w <- paste0("Detected opened connection(s): "
,paste(.dQuote(basename(con[unable,"description"]))
,collapse=", ")
,".")
warning(w)
w <- "Script is suspended until close of image viewer."
message(w)
options(opW)
sysWait <- TRUE
}
}
else if (FALSE) {
if (delafter & execute & !.isPackageInUse())
cat("Info: required pausing due to opened connection(s)\n")
sysRemove <- FALSE
}
}
}
if (!toOpen) {
if (delafter)
delafter <- .normalizePath(dirname(fileout))!=.normalizePath(tempdir())
message(paste("Use",.sQuote("session_pngviewer(TRUE)")
,"\nto open",.sQuote(.normalizePath(fileout))
,"in external software."))
}
if (getOption("ursaPngFigure")==0L) ## plot layout only
{
if (TRUE) {## introduced 20150916 to deprecate 'dev' arg in compose_open()
mosaic <- getOption("ursaPngLayout")
# print(mosaic)
# print(fileout)
layout.show(max(mosaic$layout))
# str(par())
# plot(ann,add=TRUE)
grDevices::dev.off()
if (proposed <- TRUE) {
# print(c(knitr=.isKnitr(),shiny=.isShiny(),jupyter=.isJupyter()))
if (.isShiny()) { ## in 'imageOutput'/'renderImage'
return(if (execute) list(src=fileout) else fileout)
}
if ((execute)&&(.isKnitr())) {
execute <- FALSE
retK <- knitr::include_graphics(fileout
,auto_pdf=FALSE
,dpi=getOption("ursaPngDpi"))
return(retK)
}
if (.isJupyter()) {
execute <- FALSE
return(invisible(IRdisplay::display_png(file=fileout)))
}
}
if (execute) {
if (!toOpen) {
op <- par(mar=c(0,0,0,0))
plot(grDevices::as.raster(png::readPNG(fileout)))
if (TRUE) {
fann <- .dir(path=system.file("optional/sponsorship",package="ursa")
,pattern="\\.png$",full.names=TRUE)
ann <- png::readPNG(sample(fann,1))
plot(grDevices::as.raster(ann),add=TRUE)
}
par(op)
}
else {
if (isPackageTest)
NULL
else if (TRUE)
browseURL(normalizePath(fileout))
else if (.Platform$OS.type=="unix")
system2("xdg-open",c(.dQuote(fileout)),wait=!.isRscript())
else
system2(file.path(R.home("bin"),"R")
,c("CMD","open",.dQuote(fileout)),wait=!.isRscript())
# system2("open",list(fileout),wait=!.isRscript()) ## wait=sysWait
# stop("How to implement file association in Unix-like systems?")
}
}
if (delafter) {
if (execute) {
wait <- getOption("ursaPngWaitBeforeRemove")
if (!sysRemove)
Sys.sleep(wait)
else {
if (wait<5)
wait <- 5
cmd <- paste0("Sys.sleep(",wait,");"
,"if (file.exists(",sQuote(fileout),"))"
," file.remove(",sQuote(fileout),")")
ret <- system2(file.path(R.home("bin"),"Rscript")
,c("-e",dQuote(cmd)),wait=FALSE,stdout=NULL)
}
}
else if (!sysRemove)
file.remove(fileout)
}
}
else { ## original
graphics.off()
if ((delafter)&&(file.exists(fileout)))
file.remove(fileout)
}
return(invisible(NULL))
}
if (getOption("ursaPngFigure")==getOption("ursaPngLayout")$image) {
.panel_attribution()
if (getOption("ursaPngBox"))
panel_box()
}
grDevices::dev.off()
# kind <- match.arg(kind)
do.call(paste0(".",kind),list(fileout,border,verbose))
n <- 999L
if (!(bpp %in% c(8,24))) {
requireNamespace("png",quietly=.isPackageInUse())
x <- png::readPNG(fileout,native=TRUE,info=FALSE)
if (verbose)
.elapsedTime("uniqueColor:start")
n <- length(unique(c(x)))
if (verbose)
.elapsedTime(paste0("uniqueColor:finish (",n,")"))
bpp <- ifelse(n<256,8,24)
}
if ((bpp==8)&&(!(tolower(gsub(".*\\.(\\S+$)","\\1",fileout)) %in% c("svg","pdf")))) {
if (requireNamespace("magick",quietly=.isPackageInUse())) {
magick::image_write(
magick::image_quantize(
magick::image_read(fileout)
,max=256,dither=FALSE,colorspace='sRGB')
,fileout)
cmd <- ""
}
else if (nchar(Sys.which("zzzi_view32"))) {
FoutTmp <- ifelse(dirname(fileout)==".",basename(fileout),normalizePath(fileout))
cmd <- paste("i_view32",FoutTmp,"/bpp=8",paste0("/convert=",FoutTmp))
}
else if ((nchar(im <- Sys.getenv("R_IMAGEMAGICK"))>0)&&(file.exists(im))) {
# print("R_IMAGEMAGICK is found")
cmd <- paste(im,fileout,ifelse(n>=255,"-colors 255","")
,paste0("png8:",fileout))
}
else if ((nchar(imdisplay <- Sys.which("imdisplay"))>0)) {
# imagemagick ver>=7.0.7 "magick" instead of "convert"
# print("imagemagick is in PATH")
cmd <- paste(file.path(dirname(imdisplay),"convert")
,fileout,ifelse(n>=255,"-colors 255","")
,paste0("png8:",fileout))
}
else if ((nchar(im <- Sys.which("convert"))>0)&& ##
(toupper(normalizePath(dirname(dirname(im))))!=
toupper(normalizePath(Sys.getenv("WINDIR"),mustWork=FALSE)))) {
# print("convert is not in Windows directory")
cmd <- paste(im,fileout,ifelse(n>=255,"-colors 255","")
,paste0("png8:",fileout))
}
else {## else if... (other ways to force to bpp=8
# print("imagemagick is not found")
cmd <- ""
}
if (nchar(cmd)) {
if (T & verbose)
message(cmd)
system(cmd)
}
}
if (proposed <- TRUE) {
if (.isShiny()) { ## in 'imageOutput'/'renderImage'
# print("URSA as list with '$src'")
return(if (execute) list(src=fileout) else fileout)
}
if ((execute)&&(.isKnitr())) {
execute <- FALSE
if (.isKnitr())
delafter <- FALSE & delafter & ## don't delete: longtime rendering cannot find removed file
length(grep("self-contained",knitr::opts_knit$get()$rmarkdown.pandoc.args))>0
dpi1 <- getOption("ursaPngDpi")
dpi2 <- knitr::opts_current$get("dpi")
dpi3 <- dpi1/96*dpi2/96
opK <- options(warn=-1) ## https://github.com/yihui/knitr/pull/2063
retK <- knitr::include_graphics(fileout
,auto_pdf=FALSE
,dpi=getOption("ursaPngDpi"))
options(opK)
if ((delafter)&&(sysRemove))
on.exit({
wait <- 5
cmd <- paste0("Sys.sleep(",wait,");"
,"if (file.exists(",sQuote(fileout),"))"
," file.remove(",sQuote(fileout),")")
system2(file.path(R.home("bin"),"Rscript")
,c("-e",dQuote(cmd)),wait=FALSE,stdout=NULL)
},add=TRUE)
# print(fileout)
return(retK)
}
if (.isJupyter()) {
execute <- FALSE
return(invisible(IRdisplay::display_png(file=fileout)))
# return(invisible(do.call("IRdisplay::display_png",list(file=fileout))))
# retK <- IRdisplay::display_png(file=fileout)
# return(invisible(retK))
}
}
if (execute | delafter)
wait <- getOption("ursaPngWaitBeforeRemove")
if (execute)
{
if (!toOpen) {
op <- par(mar=c(0,0,0,0))
if (TRUE)
plot(grDevices::as.raster(png::readPNG(fileout)))
else { ## failed asp=1
img <- png::readPNG(fileout,native=TRUE)
dima <- dim(img)
plot(0,0,type="n",axes=FALSE,xlim=c(0,dima[1]),ylim=c(0,dima[2]),asp=1,xlab="",ylab="")
rasterImage(img,0,0,dima[1],dima[2])
}
par(op)
}
else {
if (isPackageTest)
NULL
else if (TRUE)
browseURL(normalizePath(fileout))
else if (.Platform$OS.type=="unix")
system2("xdg-open",c(.dQuote(fileout)),wait=!.isRscript())
else
system2(file.path(R.home("bin"),"R")
,c("CMD","open",.dQuote(fileout)),wait=TRUE)
# system2("R cmd open",list(,fileout),wait=TRUE) #!.isRscript()) ## wait=sysWait
# stop("How to implement file association in Unix-like systems?")
}
if (normalizePath(tempdir())==normalizePath(dirname(fileout)))
sysRemove <- FALSE
# print(wait)
if ((!sysRemove)&&(delafter))
Sys.sleep(wait)
}
if (delafter) {
if (FALSE) {
fpath <- dirname(fileout)
isTempDir <- tempdir()==normalizePath(fpath)
file.remove(fileout)
if (isTempDir) {
a <- .dir(path=fpath)
print(fpath)
if (!length(a)) {
res <- unlink(fpath,force=TRUE)
print(res)
}
}
}
else if (!sysRemove) {
file.remove(fileout)
}
else {
if (wait<5)
wait <- 5
cmd <- paste0("Sys.sleep(",wait,");"
,"if (file.exists(",sQuote(fileout),")) file.remove(",sQuote(fileout),")")
if (FALSE) {
# requireNamespace("sys"))
# message(cmd)
# ret <- sys::r_background(c('--vanilla','-e',dQuote(cmd)))
# print(ret)
}
else {
# message('Package `sys` is suggested for cleaning spead-up')
ret <- system2(file.path(R.home("bin"),"Rscript")
,c("-e",dQuote(cmd)),wait=FALSE,stdout=NULL)
}
# print(cmd)
# print(ret)
}
}
if (file.exists(fileout)) {
return(invisible(fileout))
}
invisible(NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/compose_close.R
|
'compose_design' <- function(...) {
arglist <- list(...)
# str(lapply(arglist,function(x) list(class=class(x),names=names(x))))
obj <- .getPrm(arglist,name="^$",default=NULL
,class=list(c("list","ursaRaster"),"ursaRaster","integer"))
layout <- .getPrm(arglist,name="layout",default=NA_integer_)
# if (identical(obj,layout))
# obj <- NULL
byrow <- .getPrm(arglist,name="byrow",default=TRUE)
skip <- .getPrm(arglist,name="skip",class="integer",default=NULL)
legend <- .getPrm(arglist,name="legend",class="",default=NA)
side <- .getPrm(arglist,name="side",default=NA_integer_,valid=1L:4L)
ratio <- .getPrm(arglist,name="ratio",default=(16+0.05)/(9+0.05))
fixed <- .getPrm(arglist,name="fixed",default=FALSE)
verbose <- .getPrm(arglist,name="verb(ose)*",default=FALSE)
.compose_design(obj=obj,layout=layout,byrow=byrow,skip=skip,legend=legend
,side=side,ratio=ratio,fixed=fixed,verbose=verbose)
}
'.compose_design' <- function(obj=NULL,layout=NA,byrow=TRUE,skip=NULL,legend=NA
,side=NA,ratio=(16+1)/(9+1),fixed=fixed,verbose=FALSE) {
if (is.na(ratio))
ratio <- (16+1)/(9+1)
if (verbose)
str(list(obj=if (is.list(obj)) sapply(obj,class) else class(obj)
,layout=layout,byrow=byrow,skip=skip,legend=legend
,side=side,ratio=ratio,fixed=fixed))
if (is.null(legend)) {
forcedLegend <- FALSE
legend <- NA
}
else
forcedLegend <- TRUE
if (!length(layout))
layout <- NA
if ((is.numeric(side))&&(length(side)==1)&&(side %in% c(1:4)))
legend <- side
layout[!is.finite(layout)] <- NA
oldM <- layout
# print(class(obj))
##~ if ((length(layout)==1)&&(is.numeric(layout))) {
##~ print("0114 D")
##~ nb <- layout
##~ layout <- NA
##~ }
if (is.null(obj)) ## || (missing(obj))
{
# print(class(obj))
# stop("NULL")
if (any(is.na(layout)))
layout <- c(1L,1L)
panelr <- layout[1]
panelc <- layout[2]
isList <- FALSE
}
else
{
# session_grid(obj) ## added 2015-12-02 # removed 20161226
if (is.null(g0 <- getOption("ursaSessionGrid"))) ## added 20161226
session_grid(obj)
isList <- .is.ursa_stack(obj)
if (isList)
{
# if ((all(is.na(layout)))&&(is.na(legend))) {
# # message("calling internal function '.compose_design.stack()'")
# # return(.compose_design.stack(obj))
# }
fld <- NULL
for (i in seq_along(obj)) {
isF <- is.ursa(obj[[i]])
if (!isF)
fld <- c(fld,0L)
else
fld <- c(fld,rep(i,nband(obj[[i]])))
}
}
else {
if (is.integer(obj)) {
if (length(obj)==1) {
if (fixed) {
ol <- .optimal_layout(obj,ratio=ratio,verbose=verbose)
# ratio <- unname(ol[2]/ol[1])
layout <- ol
g0 <- session_grid()
}
fld <- rep(1L,obj)
}
else {
fld <- rep(1L,length(obj))
}
}
else
fld <- rep(1L,nband(obj))
}
g1 <- session_grid()
if (is.null(skip))
skip <- which(!fld)
else {
res <- rep(1,length(fld)+length(skip))
res[skip] <- 0
res[-skip] <- fld
fld <- res
rm(res)
}
if (length(layout)==2) {
if ((is.na(layout[1]))&&(is.numeric(layout[2]))) {
layout[1] <- ceiling(length(fld)/layout[2])
}
else if ((is.na(layout[2]))&&(is.numeric(layout[1]))) {
layout[2] <- ceiling(length(fld)/layout[1])
}
}
if (any(is.na(layout))) {
nl <- length(fld)
##~ if (!isList) {
##~ nc <- obj$grid$columns
##~ nr <- obj$grid$rows
##~ }
##~ else {
##~ nc <- obj[[1]]$grid$columns
##~ nr <- obj[[1]]$grid$rows
##~ }
nc <- g1$columns
nr <- g1$rows
s0 <- rep(0,nl)
for (pr in seq(nl))
{
pc <- ceiling(nl/pr)
if (((pc-1)*pr>=nl)||(pc*(pr-1)>=nl)) {
s0[pr] <- 9999
next
}
if ((isList)&&((pc>2)&&(pr>2))) {
s0[pr] <- 9999
next
}
lc <- pc*nc
lr <- pr*nr
s1 <- (lc/lr)/ratio #-1 ## ratio 1.5=15:10 16:9 4:3
if (s1<1)
s1 <- 1/s1
s0[pr] <- s1-1
if (verbose)
print(data.frame(panelc=pc,panelr=pr,nc=nc,nr=nr
,lc=lc,lr=lr,ratio=(lc/lr)/ratio,s=s0[pr]))
}
ind <- which.min(abs(s0))[1]
if ((FALSE)&&(length(legend)==1)&&(is.na(legend)))
legend <- ifelse(s0[ind]<=0,4L,1L)
panelr <- ind
panelc <- ceiling(nl/panelr)
if (isList & (panelc>2 & panelr>2)) {
if (panelc>panelr) { ## *ratio?
panelr <- 2
panelc <- ceiling(nl/panelr)
}
else {
panelc <- 2
panelr <- ceiling(nl/panelc)
}
}
##~ if (nl<=panelr*(panelc-1)) repeat({
##~ panelc <- panelc-1
##~ if (nl<=panelr*(panelc-1))
##~ break
##~ })
##~ else if (nl<=(panelr-1)*panelc) repeat ({
##~ panelr <- panelr-1
##~ if (nl<=(panelr-1)*panelc)
##~ break
##~ })
if (!length(skip))
skip <- which(is.na(match(seq(panelc*panelr),seq(nl))))
if (verbose)
print(c(bands=nl,columns=panelc,rows=panelr,panels=panelc*panelr
,samples=nc,lines=nr))
rm(nc,nr,lc,lr,s0,ind)
}
else
{
panelr <- layout[1]
panelc <- layout[2]
if (!length(skip)) {
oldF <- fld
fld <- rep(0L,prod(layout))
fld[seq(length(oldF))] <- oldF
skip <- which(!fld)
}
}
}
mosaic <- matrix(0,ncol=panelc*2+3,nrow=panelr*2+3)
k <- 0L
m <- k
if (byrow)
{
for (ir in 1:panelr)
{
for (ic in 1:panelc)
{
k <- k+1L
if (k %in% skip)
next
m <- m+1L
mosaic[2*ir+1,2*ic+1] <- m
}
}
}
else
{
for (ic in 1:panelc)
{
for (ir in 1:panelr)
{
k <- k+1L
if (k %in% skip)
next
m <- m+1L
mosaic[2*ir+1,2*ic+1] <- m
}
}
}
k <- m+1
if (length(legend)==1) {
if ((isList)&&(forcedLegend)&&((panelc>1)||(panelr>1))) { ## 20160112 added &&(forcedLegend)
nl <- length(unique(fld[fld>0]))
# print(c(panelc=panelc,panelr=panelr))
oldL <- legend
step3 <- (length(oldM)==2) && (!is.na(oldM[1])) && (oldM[1]==2)
step4 <- (length(oldM)==2) && (!is.na(oldM[2])) && (oldM[2]==2)
if (!step3 & !step4) {
if ((panelr==2)&&(panelc>2))
step3 <- TRUE
else if ((panelc==2)&&(panelr>2))
step4 <- TRUE
else if ((panelc==2)&&(panelr==2))
step4 <- TRUE
}
legend <- vector("list",nl)
if ((panelc==1)&&(panelr==1)) { ## single panel
;
}
if (panelc==1) { ## 1-column
if (is.na(oldL))
oldL <- "right"
for (i in seq(nl))
legend[[i]] <- list(i,oldL)
}
else if (panelr==1) { ## 1-row
if (is.na(oldL))
oldL <- "bottom"
for (i in seq(nl))
legend[[i]] <- list(oldL,i)
}
else if (step3) { ## 2-rows
j <- 1L
if (!byrow) {
for (i in seq(panelc)) {
for (i2 in c(1,2)) {
i3 <- (i-1)*panelr+(i2-1)+1
if (!(i3 %in% fld))
next
legend[[j]] <- list(ifelse(i2==1,"top","bottom"),i)
j <- j+1L
}
}
}
else {
for (i2 in c(1,2)) {
for (i in seq(panelc)) {
i3 <- (i2-1)*panelc+(i-1)+1
if (!(i3 %in% fld))
next
legend[[j]] <- list(ifelse(i2==1,"top","bottom"),i)
j <- j+1L
}
}
}
}
else if (step4) { ## 2-columns
j <- 1L
if (!byrow) {
for (i2 in c(1,2)) {
for (i in seq(panelr)) {
i3 <- (i2-1)*panelr+(i-1)+1
if (!(i3 %in% fld))
next
legend[[j]] <- list(i,ifelse(i2==1,"left","right"))
j <- j+1L
}
}
}
else {
for (i in seq(panelr)) {
for (i2 in c(1,2)) {
i3 <- (i-1)*panelc+(i2-1)+1
if (!(i3 %in% fld))
next
legend[[j]] <- list(i,ifelse(i2==1,"left","right"))
j <- j+1L
}
}
}
}
else {
opW <- options(warn=1)
warning("Unable to composite multiple scalebars")
options(opW)
legend <- list()#(NULL)
forcedLegend <- FALSE
}
}
else if ((forcedLegend)&&(is.na(legend)))
legend <- "right"
}
if (is.character(legend))
legend <- list(list(switch(legend[1],top=0,bottom=99,1:99)
,switch(legend[1],left=0,right=99,1:99)))
else if ((length(legend)==1)&&(is.numeric(legend))&&
(as.integer(legend) %in% 1L:4L))
{
if (legend==1)
legend <- list(list(99,1:99))
else if (legend==2)
legend <- list(list(1:99,0))
else if (legend==3)
legend <- list(list(0,1:99))
else if (legend==4)
legend <- list(list(1:99,99))
}
for (i in seq_along(legend))
{
# if ((length(skip))&&(panelc*panelr==length(legend))&&(i %in% skip))
# next
leg <- legend[[i]]
if (length(leg)!=2)
{
if (is.list(leg))
kwd <- leg[[1]]
else
kwd <- leg[1]
leg <- switch(kwd
,left=list("full","left")
,right=list("full","right")
,top=list("top","full")
,bottom=list("bottom","full")
,list())
if (!length(leg))
next
# stop("wrong format")
# k <- k+1
# next
}
leg1 <- leg[[1]]
leg2 <- leg[[2]]
if (is.character(leg1))
leg1 <- switch(leg1,top=0,first=1,last=panelr,bottom=99,full=1:99
,stop("unknown keyword"))
if (is.character(leg2))
leg2 <- switch(leg2,left=0,first=1,last=panelc,right=99,full=1:99
,stop("unknown keyword"))
posr <- range(leg1)
posc <- range(leg2)
posr <- (posr[1]:posr[2])*2+1
posc <- (posc[1]:posc[2])*2+1
posr[posr<1] <- 1
posc[posc<1] <- 1
posr[posr>nrow(mosaic)] <- nrow(mosaic)
posc[posc>ncol(mosaic)] <- ncol(mosaic)
posc <- unique(posc)
posr <- unique(posr)
if ((length(leg1)>1)&&((length(leg2)==1)))
posr <- posr[posr>1 & posr<nrow(mosaic)]
else if ((length(leg2)>1)&&((length(leg1)==1)))
posc <- posc[posc>1 & posc<ncol(mosaic)]
mosaic[posr,posc] <- k
k <- k+1
}
if (FALSE)
{
a1 <- diff(apply(mosaic,1,function(x){all(x==0)}))
a2 <- diff(apply(mosaic,2,function(x){all(x==0)}))
if (a1[1]==0)
mosaic <- mosaic[-c(1,2),,drop=FALSE]
if (a1[length(a1)]==0)
mosaic <- mosaic[-nrow(mosaic)+c(0,1),,drop=FALSE]
if (a2[1]==0)
mosaic <- mosaic[,-c(1,2),drop=FALSE]
if (a2[length(a2)]==0)
mosaic <- mosaic[,-ncol(mosaic)+c(0,1),drop=FALSE]
}
if (!forcedLegend)
sLegend <- 1
else
sLegend <- sapply(legend,function(x) length(x)>0)
options(ursaPngSkipLegend=which(!sLegend)) ## ,ursaPngSkip=skip
# print(c(panelc=panelc,panelr=panelr))
res <- list(layout=mosaic,image=m,dim=c(panelr,panelc)
,legend=ifelse(!forcedLegend,0L,sum(sLegend)))
# if (!is.null(names(legend)))
# res$legendName=names(legend)
# res <- list(layout=mosaic,image=vector("list",prod(image))
# ,legend=vector("list",length(legend)))
class(res) <- "ursaLayout"
res
}
'.optimal_layout' <- function(panels=1,ratio=10,grid=NULL,verbose=FALSE,...) {
if (.is.grid(grid))
grid <- with(grid,c(rows,columns))
if (!((is.numeric(grid))&&(length(grid)==2))) {
grid <- with(session_grid(),c(rows,columns))
}
if (verbose)
print(grid)
# grid <- c(1200,1600)
r1 <- ratio # max(grid)/min(grid)
# panels <- sample(2:15,1)
v2 <- data.frame(s=seq(panels),nrow=NA,r2=NA)
if (verbose)
print(c(r1=r1))
for (i in seq(panels)) {
j <- ceiling(panels/i)
d2 <- round(c(r1*grid[2]/i,grid[1]/j))
if (verbose)
print(d2)
v2$nrow[i] <- j
v2$r2[i] <- round(max(d2)/min(d2),2)
}
if (verbose)
print(v2)
v <- v2[which.min(v2$r2),"nrow"]
u <- ceiling(panels/v)
x <- round(grid[2]/u)
y <- round(grid[1]/v)
if (verbose)
print(data.frame(nr=v,nc=u,x=x,y=y))
session_grid(unname(c(y,x)))
c(nr=v,nc=u)
# cd <- compose_design(,scale=1,legend=NULL,r)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/compose_design.R
|
'compose_legend' <- function(...)
{
if (.skipPlot(FALSE))
return(NULL)
nlegend <- getOption("ursaPngLayout")$legend
arglist <- list(...)
colorbar <- .getPrm(arglist,name="^colorbar$",default=TRUE)
if (!as.logical(colorbar))
return(invisible(NULL))
units <- NULL
aname2 <- sapply(arglist,function(x) {
y <- names(x)
if (is.null(y))
return("")
if (.is.colortable(x)) {
return("")
}
if (length(y)>1) {
y <- paste0(head(y,1),"...",tail(y,1))
}
y
})
arglist <- lapply(arglist,function(x1) {
if (identical(c("index","colortable"),names(x1)))
return(x1$colortable)
if (is.ursa(x1))
return(x1$colortable)
if ((is.list(x1))&&(length(x1)==1)) {
return(x1[[1]])
}
x1
})
ind <- sapply(arglist,is.ursa,"colortable")
if (length(which(ind))) {
obj <- vector("list",length(ind))
myname <- names(ind)
if (length(ind2 <- which(!nchar(myname)))) {
myname[ind2] <- aname2[ind2]
}
names(obj) <- myname
ind2 <- rep(TRUE,length(ind))
for (i in seq_along(obj)) {
if (ind[i])
obj[[i]] <- ursa_colortable(arglist[[i]])
else {
if (!nchar(myname[i]))
obj[[i]] <- as.character(arglist[[i]])
else
ind2[i] <- FALSE
# obj[[i]] <- NULL
}
}
obj <- obj[ind2]
arglist <- arglist[!ind2]
isList <- TRUE
# arglist <- list(NA)
units <- names(obj)
}
else {
if (inherits(arglist[[1]],"ursaLegend"))
arglist[[1]] <- ursa_colortable(arglist[[1]])
if (!inherits(arglist[[1]],"ursaColorTable")) {
arglist[[1]] <- lapply(arglist[[1]],function(x1) {
if (identical(c("index","colortable"),names(x1)))
return(x1$colortable)
if ((is.list(x1))&&(length(x1)==1)) {
if (is.ursa(x1))
return(x1$colortable)
else
return(x1[[1]])
}
x1
})
}
ind <- sapply(arglist[[1]],is.ursa,"colortable")
if ((is.list(ind))&&(!length(ind)))
return(invisible(NULL))
if (length(which(ind))) {
obj <- vector("list",length(ind))
names(obj) <- names(ind)
for (i in seq_along(obj)) {
if (ind[i])
obj[[i]] <- ursa_colortable(arglist[[1]][[i]])
else
obj[[i]] <- as.character(arglist[[1]][[i]])
}
isList <- TRUE
}
else {
obj <- .getPrm(arglist,name="",default=NULL
,class=list(c("list","ursaRaster"),"ursaRaster"))
if (is.null(obj)) {
obj <- .getPrm(arglist,name="",default=NULL
,class=list(c("list","ursaColorTable"),"ursaColorTable")
,verbose=FALSE)
obj <- .getPrm(arglist,index=1L,class="ursaColorTable",verbose=TRUE)
isList <- all(sapply(obj,function(x) class(x) %in% "ursaColorTable"))
if (is.null(obj))
return(invisible(NULL))
}
else {
isList <- .is.ursa_stack(obj)
if (isList) {
myname <- names(obj)
obj <- lapply(obj,ursa_colortable)
names(obj) <- myname
}
else
obj <- ursa_colortable(obj)
}
}
}
# str(obj,grid=FALSE)
mUnits <- .getPrm(arglist,name="unit(s)*",class=c("expression","character")
,default=NA_character_)
if (((is.expression(mUnits))||((is.character(mUnits))&&(is.na(mUnits[1]))))&&
(length(mUnits)==length(units)))
units <- mUnits
else if ((is.null(units))||(all(!nchar(units)))) {
units <- .getPrm(arglist,name="unit(s)*",class=c("expression","character")
,default=NA_character_)
}
skip <- getOption("ursaPngSkipLegend")
if (isList) {
if ((!is.expression(units))&&(is.na(units[1]))) {
units <- names(obj)
if (is.null(units)) {
# units <- sapply(obj,names)
units <- sapply(obj,function(x) {
if (is.ursa(x))
return(names(x))
NULL
})
}
}
if ((is.null(units))||(length(units)!=length(obj))) {
if (is.null(units))
units <- rep("",len=length(obj))
else
units <- rep(units,len=length(obj))
}
for (i in seq_along(obj)) {
if (i %in% skip)
next
if (i>nlegend)
break
# legend_colorbar(obj=obj[[i]],units=units[i],...)
arglist2 <- c(quote(obj[[i]]),arglist) ## 20180308 change 'arglist[-1]'?
# arglist[[1]] <- quote(obj[[i]])
if (.is.colortable(obj[[i]])) {
arglist2[["unit"]] <- units[i]
# str(arglist2)
do.call("legend_colorbar",arglist2)
# arglist[["units"]] <- NULL
}
else {
do.call("legend_mtext",arglist2)
# legend_mtext(obj[[i]])
}
}
}
else {
myname <- names(arglist)
if (is.null(myname))
myname <- ""
arglist <- arglist[match(unique(myname),myname)]
# legend_colorbar(obj,units=units,...)
do.call("legend_colorbar",arglist)
}
invisible(NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/compose_legend.R
|
'compose_open' <- function(...) {
if (T & .isKnitr()) {
retina0 <- 2
}
else {
retina0 <- getOption("ursaRetina")
if (!is.numeric(retina0))
retina0 <- 1
}
arglist <- list(...)
mosaic <- .getPrm(arglist,name="",default=NA,class="")
fileout <- .getPrm(arglist,name="fileout",default="")
retina <- .getPrm(arglist,name="retina",default=ifelse(nchar(fileout),1,retina0))
if ((!is.numeric(retina))||(is.na(retina)))
retina <- retina0
dpi <- .getPrm(arglist,name="dpi"
,default=as.integer(round(ifelse(.isKnitr(),150*retina,96*retina))))
pointsize <- .getPrm(arglist,name="pointsize",default=NA_real_)
scale <- .getPrm(arglist,name="^scale$",class="",default=NA_real_)
width <- .getPrm(arglist,name="width",class=list("integer","character"),default=NA_real_)
height <- .getPrm(arglist,name="height",class=list("integer","character"),default=NA_real_)
indent <- .getPrm(arglist,name="(space|offset|indent)",default=NA_real_)
# frame <- .getPrm(arglist,name="(frame|colorbar|strip)(height)*",default=NA_real_)
frame <- .getPrm(arglist,name="((frame|strip)(height)*|colorbar$)",default=NA_real_)
box <- .getPrm(arglist,name="box",default=TRUE)
delafter <- .getPrm(arglist,name="(del|remove)after",default=NA)
wait <- .getPrm(arglist,name="wait",default=switch(.Platform$OS.type,windows=1,3))
dtype <- if (.Platform$OS.type=="windows") c("cairo","windows","agg","cairo-png")
else c("cairo","cairo-png","Xlib","quartz")
device <- .getPrm(arglist,name="^(device|type)",valid=dtype)
antialias <- .getPrm(arglist,name="antialias",valid=c("default","none","cleartype"))
# font <- .getPrm(arglist,name="(font|family)",valid=ifelse(device=="windows","sans","Tahoma"))
font <- .getPrm(arglist,name="(^font$|family)"
,default=ifelse(device=="windows","sans","sans"))
background <- .getPrm(arglist,name="(background|nodata)",default="white")
dev <- .getPrm(arglist,name="^dev(el)*$",default=FALSE)
fixed <- .getPrm(arglist,name="^(fixed)",default=FALSE)
verbose <- .getPrm(arglist,name="verb(ose)*",kwd="open",default=FALSE)
options(ursaPngWebCartography=FALSE)
if (is_spatial(mosaic))
session_grid(regrid(spatial_grid(mosaic),border=27))
if (is.ursa(mosaic)) {
cr <- attr(mosaic,"copyright")
if ((is.character(cr))&&(nchar(cr)>1)) {
mosaic <- compose_design(layout=c(1,1),legend=NULL)
# print("WEB #1")
options(ursaPngWebCartography=TRUE)
scale <- 1
}
}
else if ((.lgrep("\\+proj=merc",session_crs()))&&
(!is.na(.is.near(session_cellsize(),2*6378137*pi/(2^(1:21+8)))))) {
# print("WEB #2")
arglist <- as.list(match.call()) ## try mget(names(match.call())[-1])
if (!("scale" %in% names(arglist))) {
# options(ursaPngWebCartography=TRUE) ## -- 20201125
scale <- 1
}
if (.is.integer(scale)) ## ++ 20201125
options(ursaPngWebCartography=TRUE)
}
if (isTRUE(getOption("ursaPngWebCartography"))) {
retina1 <- session_grid()$retina
if ((retina>1)&&(!is.na(retina1))&&(retina1>1)) {
dpi <- round(dpi*retina1/retina)
retina <- 2
}
}
if ((is.character(mosaic))&&(mosaic=="rgb"))
mosaic <- compose_design(layout=c(1,1),legend=NULL)
else if (!inherits(mosaic,"ursaLayout"))
mosaic <- compose_design(...)
if ((isTRUE(fixed))&&(is.na(scale)))
scale <- 1
.compose_open(mosaic=mosaic,fileout=fileout,dpi=dpi,pointsize=pointsize
,scale=scale,width=width,height=height
,indent=indent,frame=frame,box=box,delafter=delafter,wait=wait
,device=device,antialias=antialias,font=font
,background=background,retina=retina,dev=dev,verbose=verbose)
if (dev) {
options(ursaPngPlot=TRUE)
compose_close(...)
}
invisible(fileout)
}
'.compose_open' <- function(mosaic=NULL,fileout="",dpi=NA,pointsize=NA,scale=NA
,width=NA,height=NA
,indent=NA,frame=NA,box=TRUE,delafter=NA,wait=5
,device=NA,antialias=NA,font=NA,background="white"
,retina=NA,dev=FALSE,verbose=FALSE) {
if (is.na(retina)) {
retina <- getOption("ursaRetina")
if (!is.numeric(retina))
retina <- 1
}
# session_pngviewer()
if (FALSE) {
str(list(mosaic=if (is.list(mosaic)) sapply(mosaic,class) else class(mosaic)
,fileout=fileout,dpi=dpi,pointsize=pointsize,scale=scale
,width=width,height=height,indent=indent,frame=frame
,box=box,delafter=delafter,wait=wait,device=device
,antialias=antialias,font=font,background=background,dev=dev
,verbose=verbose))
}
patt <- "^\\.(png|svg|png|webp|jpeg|jpg)$"
if (grepl(patt,fileout)) {
fileext <- tolower(gsub(patt,"\\1",fileout))
fileext[fileext=="jpg"] <- "jpeg"
fileout <- ""
}
else
fileext <- NULL
if (isTemp <- !nchar(fileout))
{
# print(c(batch=.isRscript()))
# print(commandArgs(FALSE))
# print(c(tempdir=session_tempdir()))
if ((FALSE)&&((!.isRscript())||(!session_pngviewer())||(.isKnitr())))
fileout <- file.path(tempdir(),.maketmp()) ## CRAN Repository Policy
else if (!TRUE)
fileout <- file.path(tempdir(),basename(.maketmp()))
else if (.isKnitr()) {
bname <- paste0(gsub("^_+","",basename(.maketmp())),"")
klabel <- knitr::opts_current$get("label")
if (!is.null(klabel))
bname <- gsub("_[0-9a-f]+"
,paste0("_",klabel),bname,ignore.case=TRUE)
if (is.null(bpath <- knitr::opts_current$get("fig.path")))
if (is.null(bpath <- knitr::opts_chunk$get("fig.path")))
bpath <- "."
if ((FALSE)&&(dirname(bpath)==knitr::opts_current$get("root.dir")))
bpath <- basename(bpath)
fileout <- file.path(bpath,bname)
}
else
fileout <- .maketmp()
if (is.na(delafter))
delafter <- TRUE
}
else if (is.na(delafter))
delafter <- FALSE
if (is.null(fileext))
fileext <- if ((isTemp)&&(!.isKnitr())&&(mosaic$image<5)) c("png","svg")[1]
else if (.lgrep("\\.(jpeg|jpg)$",fileout)) "jpeg"
else if (.lgrep("\\.(webp)$",fileout)) "webp"
else if (.lgrep("\\.(svg)$",fileout)) "svg"
else "png"
else
fileout <- paste0(fileout,".",fileext)
isJPEG <- fileext %in% "jpeg"
isWEBP <- fileext %in% "webp"
isSVG <- fileext %in% "svg"
if ((!isJPEG)&&(!isWEBP)&&(!isSVG)&&(!.lgrep("\\.png$",fileout)))
fileout <- paste0(fileout,".png")
else if ((isSVG)&&(!.lgrep("\\.svg$",fileout)))
fileout <- paste0(fileout,".svg")
g1 <- session_grid()
# scale1 <- (18.5*96)/(g1$rows*2.54)
# scale2 <- (23.7*96)/(g1$columns*2.54)
paperScale <- 0
if (is.character(scale)) {
patt <- "\\D*((\\d+(\\.\\d+)*)(\\:))*(\\d+(\\.\\d+)*)\\D*"
.s0 <- .gsub(patt,"\\2",scale)
.s <- as.numeric(.gsub(patt,"\\5",scale))
.un <- .gsub(patt,"\\1 \\2 \\3 \\4 \\5 \\6",scale)
if (nchar(.s0))
.s <- .s/100000
.s0 <- ifelse(nchar(.s0),as.numeric(.s0),1)
if (.lgrep("\\+proj=merc",g1$crs)) {
lat <- with(session_grid(),.project(cbind(0.5*(maxx+minx),0.5*(maxy+miny))
,crs,inv=TRUE))[1,2]
sc <- 1/cos(lat*pi/180)
}
else
sc <- 1
scale <- NA
dx <- with(g1,maxx-minx)/1000
width <- round((1/sc)*dx/.s*dpi/2.54)-1 ## defines correctness of scalebar
height <- 1e6
paperScale <- c(.s,.s0)
}
else if ((!is.na(width))&&(is.na(height))) {
if (is.character(width)) {
.w <- as.numeric(.gsub("\\D*(\\d+(\\.\\d+)*)\\D*","\\1",width))
width <- dpi*.w/2.54
paperScale <- c(-1,1)
}
height <- 1e6
}
else if ((!is.na(height))&&(is.na(width))) {
if (is.character(height)) {
.h <- as.numeric(.gsub("\\D*(\\d+(\\.\\d+)*)\\D*","\\1",height))
height <- dpi*.h/2.54
paperScale <- c(-1,1) # TRUE
}
width <- 1e6
}
# print(c(width=width,s=ifelse(is.na(width),900,width),r=ifelse(is.na(width),900,width)/g1$columns))
# print(c(height=height,s=ifelse(is.na(height),600,height),r=ifelse(is.na(height),600,height)/g1$rows))
scale1 <- ifelse(is.na(height),600*retina,height)/g1$rows
scale2 <- ifelse(is.na(width),900*retina,width)/g1$columns
rescale <- mosaic$image^(0.1)
autoscale <- min(scale1,scale2)
if ((is.na(height))&&(is.na(width)))
autoscale <- autoscale/mosaic$image^0.25
if (is.na(scale))
scale <- autoscale
# dpiscale <- scale*(2.54/96.0) # 2.54cm per inch / 96 dpi screen
dpiscale <- scale*(2.54/dpi)
mainc <- g1$columns*dpiscale
mainr <- g1$rows*dpiscale
if (verbose)
print(c(v=scale1,h=scale2,autoscale=autoscale,scale=scale,c=g1$columns,r=g1$rows
,retina=retina,digits=3))
pointsize0 <- ifelse(.isKnitr(),round(12*retina,1),round(12*retina,1))
if (is.na(pointsize)) {
# print(c(pointsize0=pointsize0,dpi=dpi,scale=scale,scale0=autoscale))
# pointsize <- pointsize0*96/dpi*scale/autoscale ## removed 20161217
pointsize <- pointsize0*96/dpi ## added 20161217
}
if (FALSE) { ## removed 20161201
if (is.na(frame))
frame <- 0.028*mainr*rescale
else
frame <- 0.028*mainr*rescale*frame
if (is.na(indent))
indent <- 0.008*mainr*rescale
else
indent <- 0.008*mainr*rescale*indent
}
else { ## added 20161201
if (is.na(frame))
frame <- 0.021*pointsize*rescale
else
frame <- 0.021*pointsize*rescale*frame
if (is.na(indent))
indent <- 0.007*pointsize*rescale
else
indent <- 0.007*pointsize*rescale*indent
}
simage <- seq(mosaic$image)
slegend <- max(simage)+seq(mosaic$legend)
panel <- mosaic$layout
sizec <- rep(indent,ncol(panel))
sizer <- rep(indent,nrow(panel))
'indmatch' <- function(x,fun=c("all","any"),ind)
{
fun <- match.arg(fun)
x <- x[x>0]
if (!length(x))
return(FALSE)
do.call(fun,list(x %in% ind))
}
sizer[apply(panel,1,indmatch,"all",slegend)] <- frame
sizec[apply(panel,2,indmatch,"all",slegend)] <- frame
sizer[apply(panel,1,indmatch,"any",simage)] <- mainr
sizec[apply(panel,2,indmatch,"any",simage)] <- mainc
if ((TRUE)||(box))
{
sizec <- sizec+1*2.54/dpi
sizer <- sizer+1*2.54/dpi
}
png_height <- round(sum(sizer)*dpi/2.54+5*dpi/96+5*dpi*pointsize/pointsize0)
png_width <- round(sum(sizec)*dpi/2.54+5*dpi/96+5*dpi*pointsize/pointsize0)
dname <- dirname(fileout)
if ((dname!=".")&&(!dir.exists(dname)))
dir.create(dname,recursive=TRUE)
if (verbose)
print(c(png_width=png_width,png_height=png_height
,scale=scale,autoscale=autoscale,pointsize=pointsize,dpi=dpi))
if (.isJupyter())
options(jupyter.plot_mimetypes=ifelse(isJPEG,'image/jpeg','image/png'))
if (isSVG) {
# print(c(w=png_width/dpi,h=png_height/dpi,dpi=dpi)) ## svglite::svglite
a <- try(svg(filename=fileout
,width=png_width/dpi,height=png_height/dpi#,res=dpi
,bg=background,pointsize=pointsize
# ,antialias=antialias
# ,family=font
))
}
else if ((device=="agg")&&(requireNamespace("ragg",quietly=.isPackageInUse()))) {
a <- try(ragg::agg_png(filename=fileout
,width=png_width,height=png_height,res=dpi
,bg=background,pointsize=pointsize
# ,antialias=antialias
# ,family=font
))
}
# else if ((device=="CairoPNG")&&(requireNamespace("Cairo",quietly=.isPackageInUse()))) {
# a <- try(Cairo::CairoPNG(filename=fileout
# ,width=png_width,height=png_height,res=dpi
# ,bg=background,pointsize=pointsize
# #,type="png"
# ,antialias=antialias,family=font))
# }
else {
# if (device=="default")
# device <- "cairo"
if ((device %in% c("cairo","cairo-png"))&&(!capabilities("cairo"))) {
if (.Platform$OS.type=="windows")
device <- "windows"
else
device <- if (capabilities("aqua")) "quartz" else "Xlib"
}
a <- try(png(filename=fileout,width=png_width,height=png_height,res=dpi
,bg=background,pointsize=pointsize
,type=device,antialias=antialias,family=font))
}
if ((inherits(a,"try-error"))&&(.Platform$OS.type=="windows")) { ## 20180117 patch for conda without cairo
device <- "windows"
if (isJPEG)
png(filename=fileout,width=png_width,height=png_height,res=dpi
,bg=background,pointsize=pointsize
,type=device,antialias=antialias,family=font)
else
png(filename=fileout,width=png_width,height=png_height,res=dpi
,bg=background,pointsize=pointsize
,type=device,antialias=antialias,family=font)
}
# ,family=c("Tahoma","Verdana","Georgia","Calibri","sans")[1]
nf <- layout(panel,widths=lcm(sizec)
,heights=lcm(sizer),respect=TRUE)
options(ursaPngScale=scale,ursaPngDpi=dpi,ursaPngLayout=mosaic
,ursaPngFileout=fileout,ursaPngBox=box ## ,ursaPngLegend=mosaic$legend
,ursaPngFigure=0L,ursaPngDelafter=delafter ## ,ursaPngBar=frame
,ursaPngPlot=!dev,ursaPngPaperScale=paperScale
,ursaPngFamily=font,ursaPngWaitBeforeRemove=wait
,ursaPngDevice=device,ursaPngShadow=""
,ursaPngBackground=background,ursaPngPanel="",ursaPngSkip=FALSE
,ursaPngRetina=retina
,ursaPngPointsize=pointsize,ursaPngComposeGrid=session_grid())
# if (.isKnitr()) {
# # if (knitr::opts_knit$get(""))
# fileout <- paste0("file:///",fileout)
# }
invisible(fileout)
}
'.compose_open.example' <- function() {
a <- pixelsize()
compose_open(side=4,scale="1:50000000",pointsize=12,dpi=300)
panel_new()
panel_raster(a)
panel_coastline()
panel_graticule()
for (y in seq(0,1,len=5))
panel_scalebar(x=0.5,y=y,col="black")
compose_close()
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/compose_open.R
|
'compose_panel' <- function(...,silent=FALSE)
{
if (.skipPlot(TRUE))
return(NULL)
arglist <- list(...)
img <- .getPrm(arglist,name="",default=NULL
,class=list(c("list","ursaRaster"),"ursaRaster"))
isList <- .is.ursa_stack(img)
if ((is.null(img))||((!isList)&&(all(is.na(ursa_value(img)))))) { ## was 'missing'
# if (is.null(img)) {
ret <- NULL
if ((is.ursa(img))||(!length(arglist))) {
panel_new(...)
panel_decor(...)
panel_annotation(...)
}
else {
aname <- names(arglist)
indB <- .grep("^blank",aname)
do.call("panel_new",arglist[indB])
# indSP <- which(sapply(arglist,inherits,"Spatial"))
# indSF <- which(sapply(arglist,inherits,c("sfc","sf")))
indSP <- which(sapply(arglist,.isSP))
indSF <- which(sapply(arglist,.isSF))
other <- seq_along(arglist)
indS <- c(sp=indSP,sf=indSF)
# print(indS)
if (length(indS))
other <- other[-indS]
if (length(indSP)) {
# panel_plot(...)
ret <- do.call("panel_plot",c(arglist[indSP],arglist[other]))#$col
}
if (length(indSF)) {
# str(arglist[other])
ret <- do.call("panel_plot",c(arglist[indSF],arglist[other]))#[[1]]#$col
# if (inherits(ret,"ursaLegend"))
# NULL # ret <- ret[[1]]$col
# if ((!is_ursa(ret,"colortable"))||(!inherits(ret,"ursaLegend")))
# ret <- ret$col
# str(ret)
# q()
}
if ((!length(indS))&&(length(other))) {
ret <- do.call("panel_plot",c(arglist[other]))$col
}
indD <- .grep("^(decor|coast|grid|graticul|scale|ruler)",aname)
do.call("panel_decor",arglist[indD])
indA <- .grep("^(caption|ann|label)",aname)
do.call("panel_annotation",arglist[indA])
}
return(invisible(ret))
}
annotation <- .getPrm(arglist,name="annotation",default=NA_character_)
# decor <- .getPrm(arglist,name="decor",default=TRUE)
# scalebar <- .getPrm(arglist,name="scalebar",default=FALSE)
verbose <- .getPrm(arglist,name="verb",kwd="plot",default=NA) ## FALSE?
forceRGB <- .getPrm(arglist,name="rgb",kwd="plot",default=FALSE)
# if ((!is.na(verbose))&&(verbose))
# str(list(annotation=annotation,verbose=verbose))
# isBox <- getOption("ursaPngBox")
# skip <- getOption("ursaPngSkip")
np <- getOption("ursaPngLayout")$image
if (isList)
{
ng <- length(img)
nb <- sum(unlist(sapply(img,nband)))
ln <- unlist(lapply(unname(img),bandname))
units <- names(img)
if (is.null(units))
units <- if (FALSE) rep("",ng) else unname(ln)
canRGB <- FALSE
}
else
{
ng <- 1L
nb <- nband(img)
ln <- bandname(img)
units <- if (nb==1) ln[1] else ""
canRGB <- .is.rgb(img) ## can improve RGB detection?
}
isRGB <- nb/3==np || nb/4==np || nb/2==np
if ((!.is.integer(nb/np))&&(!isRGB)&&(canRGB))
isRGB <- TRUE
if (forceRGB)
isRGB <- TRUE
if (isRGB)
nl <- nb/np ## ??? not used after
# print(img)
# print(c(nb=nb,np=np,ng=ng,isRGB=as.integer(isRGB)))
if ((length(annotation)==1)&&(is.na(annotation))) {
annotation <- nb>1 & !isRGB #& !isList
}
if (is.na(verbose))
verbose <- nb>2
txt <- NULL
if (is.character(annotation))
txt <- if (length(annotation)==nb) annotation else rep(annotation,nb)
else if ((is.logical(annotation))&&(isTRUE(annotation)))
txt <- ln
else
txt <- ""
annotation <- is.character(txt)
k <- 0L
myname <- names(arglist)
if (is.null(myname))
myname <- ""
arglist <- arglist[nchar(myname)>0]
blankAnnotation <- .lgrep("(caption|ann(otation)*)\\.label",myname)==0
ct <- vector("list",ng)
# names(ct) <- if (isList) ln else ""
if (length(ct)==length(units))
names(ct) <- units
else
names(ct) <- rep("",length(ct))
ll <- do.call("compose_graticule",arglist)
coast <- do.call("compose_coastline",arglist)
for (j in seq(ng))
{
if (isList) {
obj <- img[[j]]
p <- do.call("colorize",c(list(obj),arglist))
ct[[j]] <- p$colortable
nl <- nband(obj)
}
else if (!isRGB) {
# obj <- img
if ((is.ursa(img,"colortable"))&&(!anyNA(ursa(img,"colortable"))))
p <- img
else
p <- do.call("colorize",c(list(img),arglist))
ct[[j]] <- p$colortable
nl <- nband(p)
}
if (isRGB)
nl <- 1
for (i in seq(nl))
{
if ((verbose)&&(k==0)) {
pb <- ursaProgressBar(min=0,max=ifelse(isRGB,nl,nb),silent=silent,tail=TRUE)
# setUrsaProgressBar(pb,k)
}
k <- k+1L
# if (i %in% skip)
# next
panel_new(...)
if (isRGB) {
if (isList)
panel_raster(img[[j]],...)
else
panel_raster(img,...)
# panel_raster(colorize(obj,...),...)
}
else {
# panel_raster(colorize(obj[i],...),...)
if (isList) {
# p <- do.call("colorize",c(list(obj[i]),arglist))
# ct[[j]] <- p$colortable
# do.call("panel_raster",c(list(p),arglist))
do.call("panel_raster",c(list(p[i]),arglist))
}
else {
do.call("panel_raster",c(list(p[i]),arglist))
}
}
if (FALSE) {
do.call("panel_coastline",arglist)
do.call("panel_graticule",arglist)
}
else {
panel_coastline(coast)
panel_graticule(ll)
}
if (blankAnnotation) {
arglist[["caption.label"]] <- if (length(txt)==nl) txt[i] else txt
}
do.call("panel_annotation",arglist) ## only through 'do.call'
do.call("panel_scalebar",arglist) ## panel_scalebar(...)
if (verbose)
setUrsaProgressBar(pb,k)
}
}
if (verbose)
close(pb)
if (isRGB)
return(invisible(NULL))
if (FALSE) {
# compose_legend(...)
# compose_legend(img,...)
do.call("compose_legend",c(list(ct),arglist))
# do.call("compose_legend",c(img,arglist)) ## FAIL
return(NULL)
}
invisible(ct)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/compose_panel.R
|
'.compose_plot' <- function(img,annotation=NA,decor=!FALSE,scalebar=FALSE
,verbose=NA,...) {
NULL
}
'compose_plot' <- function(...) {
fig <- getOption("ursaPngFigure")
if (is.null(fig))
return(invisible(NULL))
if (fig>=getOption("ursaPngLayout")$image)
return(invisible(NULL))
ct <- compose_panel(...)
if (is.null(ct))
return(invisible(NULL))
arglist <- list(...)
myname <- names(arglist)
if (is.null(myname))
myname <- ""
arglist <- arglist[nchar(myname)>0]
do.call("compose_legend",c(list(ct),arglist))
invisible(NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/compose_plot.R
|
'create_envi' <- function(x,...) {
.prepare.con(x,implement="ENVI",...)
}
'create_gdal' <- function(x,...) {
if (!.isPackageInUse()) {
.rgdal_requireNamespace()
return(.prepare.con(x,implement="RGDAL",...))
}
.prepare.con(x,implement="EGDAL",...)
}
#'create_ncdf' <- function(x,...) {
# requireNamespace("ncdf4",quietly=.isPackageInUse())
# .prepare.con(x,implement="NCDF",...)
#}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/conn.create_any.R
|
'open_envi' <- function(fname,resetGrid=FALSE,headerOnly=FALSE
,decompress=!headerOnly,cache=0L,...)
{
##~ str(nodata);q()
if (resetGrid)
session_grid(NULL)
obj <- .raster.skeleton()
con <- .con.skeleton()
grid <- .grid.skeleton()
if (missing(fname))
stop("filename is missing")
fname <- gsub("\\.$","",fname)
wname <- fname
fname <- envi_list(wname,exact=TRUE)
dname <- unique(dirname(fname))
if (identical(wname,dname)) ## 20220130
fname <- envi_list(file.path(dirname(wname),paste0("^",basename(wname),"$"))
,exact=TRUE)
# str(list(wname=wname,dname=dname,fname=fname))
if ((length(fname)!=1)&&(dirname(wname)=="."))
fname <- envi_list(path=getOption("ursaRequisite")
,pattern=basename(wname),exact=TRUE,full.names=TRUE)
if (length(fname)!=1)
{
arglist <- list(...)
if (length(list(...))==0) {
warning(paste("ENVI header",.sQuote(wname),"not found. Terminated."))
return(NULL)
}
op <- options(warn=1)
warning(paste("ENVI header",.sQuote(wname),"not found."
,"Trying to interpret additional arguments for creating new."))
on.exit(options(op))
return(create_envi(wname,...)) ## 'return(grid)' before 2012-09-07
}
myname <- paste0(fname,".hdr")
if (!file.exists(myname))
myname <- .gsub("^(.+)(\\..+)$","\\1.hdr",fname)
f1 <- readLines(myname,warn=FALSE)
fields = c("samples","lines","bands","data type","header offset"
,"interleave","byte order","band names"
,"map info","projection info","data ignore value"
,"classes","class lookup","class names","coordinate system string")
f3 <- paste(f1,collapse=" ")
f3 <- .gsub("\\s+"," ",f3)
f3 <- .gsub(",\\s",",",f3)
f3 <- .gsub("\\s,",",",f3)
f3 <- .gsub("{\\s","{",f3)
f3 <- .gsub("\\s}","}",f3)
f3 <- .gsub("\\s=","=",f3)
f3 <- .gsub("=\\s","=",f3)
mylen <- nchar(f3)
map <- NULL
cl <- list(n=0,val=NULL,name=NULL)
wkt <- ""
p <- character()
for (name in tolower(sample(fields)))
{
ind1 <- regexpr(name,f3,ignore.case=TRUE,perl=TRUE,fixed=FALSE)
if (ind1<0)
next
len <- attr(ind1,"match")
f4 <- substr(f3,ind1+len,mylen)
ind2 <- substr(f4,2,2)
if (ind2=="{")
{
ind3 <- regexpr("(}|$)",f4,ignore.case=TRUE,perl=TRUE,fixed=FALSE)
f5 <- substr(f4,3,ind3-1)
}
else
{
ind3 <- regexpr("(\\s|$)",f4,ignore.case=TRUE,perl=TRUE,fixed=FALSE)
f5 <- substr(f4,2,ind3-1)
}
if (name=="samples")
con$samples <- as.integer(f5)
else if (name=="lines")
con$lines <- as.integer(f5)
else if (name=="bands")
con$bands <- as.integer(f5)
else if (name=="data type")
con$datatype <- as.integer(f5)
else if (name=="header offset")
con$offset <- as.integer(f5)
else if (name=="interleave")
con$interleave <- f5
else if (name=="byte order")
con$byteorder <- as.integer(f5)
else if (name=="band names")
{
obj$name <- unlist(strsplit(f5,","))
}
else if (name=="classes")
cl$n <- as.integer(f5)
else if (name=="class lookup")
cl$val <- as.numeric(unlist(strsplit(f5,",")))
else if (name=="class names")
{
f6 <- .grep(name,f1,value=TRUE)
f6 <- .gsub("^.+\\{(.+)\\}","\\1",f5) ## gsub(,,f5) or gsub(,,f6) ?
cl$name <- unlist(strsplit(f6,",",perl=TRUE))
}
else if (name=="coordinate system string")
wkt <- f5
else if (name=="map info")
{
map <- unlist(strsplit(f5,","))
if (map[1]=="Geographic Lat/Lon")
grid$crs <- c("4326","+proj=longlat +datum=WGS84 +no_defs")[-1]
else if (map[1]=="UTM")
grid$crs <- paste("+proj=utm",paste0("+zone=",map[8])
,paste0("+datum="
,switch(map[10]
,'North America 1927'="NAD27"
,'WGS-84'="WGS84"
,"WGS84"))
,"+units=m +no_defs")
op <- options(warn=-1)
map <- na.omit(as.numeric(map))
options(op)
}
else if (name=="projection info")
p <- strsplit(f5,",")[[1]]
else if (name=="data ignore value")
con$nodata <- as.numeric(f5)
}
if (is.na(con$byteorder))
con$byteorder <- 0L
if (with(cl,((n>0)&&(length(val) %in% c(0,n,3*n))&&(length(name)%in% c(0L,n)))))
{
if (length(cl$val)==3*cl$n)
val <- rgb(matrix(cl$val,ncol=3,byrow=TRUE)/255)
else if (!length(cl$val))
val <- rep(NA_character_,cl$n)
else
val <- cl$val
if ((FALSE)&&(all(nchar(val)==7)))
val <- paste0(val,"FF")
names(val) <- cl$name
class(val) <- "ursaColorTable"
obj$colortable <- val
rm(val)
class(obj$value) <- "ursaCategory"
}
else {
class(obj$value) <- "ursaNumeric" ## by default
}
rm(cl)
con$indexZ <- seq(con$bands)
con$sizeof <- with(con,ifelse(datatype %in% c(1,11),1L
,ifelse(datatype %in% c(2,12),2L
,ifelse(datatype %in% c(3,13,4),4L
,ifelse(datatype %in% c(5),8L
,stop(datatype))))))
con$signed <- with(con,if (datatype %in% c(1,12,13)) FALSE else TRUE)
con$mode <- with(con,if (datatype %in% c(1,2,3,11,12,13)) "integer" else "double")
con$endian <- if (ifelse(.Platform$endian=="big",1,0)==con$byteorder |
con$byteorder<0) .Platform$endian
else "swap"
con$swap <- as.integer((.Platform$endian=="big")&(!con$byteorder)|
(.Platform$endian=="little")&(con$byteorder))
con$fname <- file.path(chartr("\\","/",normalizePath(dirname(fname)))
,basename(fname))
if (con$mode=="integer")
con$nodata <- as.integer(con$nodata)
if (length(p))
{
proj4 <- NULL
pr <- NULL
if (p[8]=="WGS-84")
ellps <- "+ellps=WGS84"
else if (p[8]=="Hughes")
ellps <- ""
if (p[1] %in% c("36","11"))
{
pr <- paste("+proj=laea",paste0("+lat_0=",p[4]),paste0("+lon_0=",p[5])
,paste0("+x_0=",p[6]),paste0("+y_0=",p[7])
,paste0("+a=",p[2]),paste0("+b=",p[3]),"+units=m","+no_defs")
if ((as.numeric(p[2])==6371228)&&(as.numeric(p[3])==6371228)&&
(as.numeric(p[4])==90)&&(as.numeric(p[5])==0))
proj4 <- "3408"
else if ((as.numeric(p[2])==6378137)&&(as.numeric(p[3])==6356752.314245179)&&
(as.numeric(p[4])==90)&&(as.numeric(p[5])==180))
proj4 <- "3571"
else if ((as.numeric(p[2])==6378137)&&(as.numeric(p[3])==6356752.314245179)&&
(as.numeric(p[4])==90)&&(as.numeric(p[5])==-150))
proj4 <- "3572"
else if ((as.numeric(p[2])==6378137)&&(as.numeric(p[3])==6356752.314245179)&&
(as.numeric(p[4])==90)&&(as.numeric(p[5])==90))
proj4 <- "3576"
}
else if (p[1]=="31")
{
pr <- paste("+proj=stere",paste0("+lat_0=",90*sign(as.numeric(p[4])))
,paste0("+lat_ts=",p[4]),paste0("+lon_0=",p[5]),"+k=1"
,paste0("+x_0=",p[6]),paste0("+y_0=",p[7]))
if (p[8]=="WGS-84")
{
if ((as.numeric(p[4])==70)&&(as.numeric(p[5])==-45))
proj4 <- "3413"
pr <- paste(pr,"+ellps=WGS84")
}
else
{
if ((as.numeric(p[2])==6378273)&&(as.numeric(p[3])==6356889.449)&&
(as.numeric(p[4])==70)&&(as.numeric(p[5])==-45))
proj4 <- "3411"
pr <- paste(pr,paste0("+a=",p[2]),paste0("+b=",p[3]))
}
pr <- paste(pr,"+units=m","+no_defs")
}
else if (p[1]=="20")
{
pr <- "+proj=merc"
proj4 <- "3388"
}
else if (p[1]=="4")
{
# proj4 <- "LCC Caspy"
pr <- paste("+proj=lcc",paste0("+lat_1=",p[8]),paste0("+lat_2=",p[9])
,paste0("+lat_0=",p[4]),paste0("+lon_0=",p[5])
,paste0("+x_0=",p[6]),paste0("+y_0=",p[7])
,paste0("+a=",p[2]),paste0("+b=",p[3]),"+units=m","+no_defs")
}
else if (p[1]=="7")
{
pr <- paste("+proj=stere",paste0("+lat_0=",90*sign(as.numeric(p[4])))
,paste0("+lon_0=",p[5]),paste0("+k=",p[8])
,paste0("+x_0=",p[6]),paste0("+y_0=",p[7]))
if (p[10]=="WGS-84")
pr <- paste(pr,"+ellps=WGS84")
else
pr <- paste(pr,paste0("+a=",p[2]),paste0("+b=",p[3]))
pr <- paste(pr,"+units=m","+no_defs")
}
else if (p[1]=="3")
{
# proj4 <- "Transverse mercator"
pr <- paste("+proj=tmerc",paste0("+lat_0=",p[4]),paste0("+lon_0=",p[5])
,paste0("+x_0=",p[6]),paste0("+y_0=",p[7])
,paste0("+a=",p[2]),paste0("+b=",p[3]),"+units=m","+no_defs")
}
else if (p[1]=="9")
{
pr <- paste("+proj=aea",paste0("+lat_1=",p[8]),paste0("+lat_2=",p[9])
,paste0("+lat_0=",p[4]),paste0("+lon_0=",p[5])
,paste0("+x_0=",p[6]),paste0("+y_0=",p[7])
,paste0("+a=",p[2]),paste0("+b=",p[3]),"+units=m","+no_defs")
}
else if (p[1]=="99")
{
pr <- paste("+proj=cea",paste0("+lon_0=",p[4]),paste0("+lat_ts=",p[5])
,paste0("+x_0=",p[6]),paste0("+y_0=",p[7])
,paste0("+a=",p[2]),paste0("+b=",p[3]),"+units=m","+no_defs")
}
else
proj4 <- "*unknown*"
proj4 <- pr
grid$crs <- proj4
}
grid$rows <- con$lines
grid$columns <- con$samples
if (!is.null(map))
{
# print(map)
grid$minx <- map[3]-(map[1]-1)*map[5]
grid$maxx <- grid$minx+grid$columns*map[5]
grid$maxy <- map[4]+(map[2]-1)*map[6]
grid$miny <- grid$maxy-grid$rows*map[6]
grid$resx <- map[5]
grid$resy <- map[6]
# print(grid)
}
else
{
grid$minx <- 0
grid$maxx <- grid$columns
grid$miny <- 0
grid$maxy <- grid$rows
grid$resx <- 1
grid$resy <- 1
}
grid2 <- getOption("ursaSessionGrid")
if (!.is.grid(grid2))
{
session_grid(grid)
con$indexC <- seq(grid$columns)
con$indexR <- seq(grid$rows)
}
else if (TRUE)
{
x2 <- with(grid2,(seq(minx,maxx,by=resx)-0.5*resx))[-1]
y2 <- with(grid2,(seq(miny,maxy,by=resy)-0.5*resy))[-1]
x1 <- with(grid,(seq(minx,maxx,by=resx)-0.5*resx))[-1]
y1 <- with(grid,(seq(miny,maxy,by=resy)-0.5*resy))[-1]
tolx <- .Machine$double.eps*max(abs(c(grid$minx,grid$maxx)))*1e1
toly <- .Machine$double.eps*max(abs(c(grid$miny,grid$maxy)))*1e1
tolerance <- c(tolx,toly)
dig <- -as.integer(.gsub(".+e\\-(\\d+)$","\\1"
,format(signif(tolerance,1),sci=TRUE)))
tolerance <- 10^dig
if ((length(x1)==length(x2))&&(all(abs(x1-x2)<1e-12)))
con$indexC <- seq(grid$columns)
else {
# con$indexC <- match(x2,x1) ## release before 2011-02-19
for (i in (seq(6)-1)) {
tol <- tolerance[1]*10^i
if (TRUE) ## reliable but 5x slower
a <- .is.near(x2,x1)
else
a <- match(round(x2/tol),round(x1/tol))
# if (anyNA(a))
# next
ind <- diff(which(!is.na(a)))
if (!length(ind))
next
if (all(ind==1))
break
}
if (i==5)
con$indexC <- match(y2,y1)
else
con$indexC <- a
}
if ((length(y1)==length(y2))&&(all(abs(y1-y2)<1e-12)))
con$indexR <- seq(grid$rows)
else {
# con$indexR <- rev(grid$rows+1-match(y2r,y1r)) ## release before 2011-02-19
for (i in (seq(6)-1)) {
tol <- tolerance[2]*10^i
if (TRUE) ## reliable but 5x slower
a <- .is.near(y2,y1)
else
a <- match(round(y2/tol),round(y1/tol))
ind <- diff(which(!is.na(a)))
if (!length(ind))
next
if (all(ind==1))
break
}
if (i==5)
con$indexR <- rev(grid$rows+1-match(y2,y1))
else
con$indexR <- rev(grid$rows+1-a)
}
grid <- grid2
}
else if (FALSE) ## introduced 2012-08-16
{
x1 <- with(grid,(seq(minx,maxx,by=resx)-0.5*resx))[-1]
y1 <- with(grid,(seq(miny,maxy,by=resy)-0.5*resy))[-1]
con$indexC <- with(grid2,which(x1>=minx & x1<=maxx))
con$indexR <- with(grid2,rev(grid$rows+1-which(y1>=miny & y1<=maxy)))
grid <- grid2
}
fname.envi <- paste(fname,".envi",sep="")
fname.bin <- paste(fname,".bin",sep="")
fname.img <- paste(fname,".img",sep="")
fname.dat <- paste(fname,".dat",sep="")
fname.gz <- paste(fname,".gz",sep="")
fname.bingz <- paste(fname,".bingz",sep="")
fname.envigz <- paste(fname,".envigz",sep="")
fname.xz <- paste(fname,".xz",sep="")
fname.bz <- paste(fname,".bz2",sep="")
fname.aux <- NA
if (is.character(cache))
cache <- 1L
if (FALSE)
NULL
else if ((file.exists(fname))&&(!file.info(fname)$isdir))
{
con$connection <- "file"
con$fname <- fname
fname.aux <- paste0(fname,".aux.xml")
}
else if ((file.exists(fname.envi))&&(!file.info(fname.envi)$isdir))
{
con$connection <- "file"
con$fname <- fname.envi
fname.aux <- paste0(fname.envi,".aux.xml")
}
else if ((file.exists(fname.bin))&&(!file.info(fname.bin)$isdir))
{
con$connection <- "file"
con$fname <- fname.bin
fname.aux <- paste0(fname.bin,".aux.xml")
}
else if ((file.exists(fname.img))&&(!file.info(fname.img)$isdir))
{
con$connection <- "file"
con$fname <- fname.img
fname.aux <- paste0(fname.img,".aux.xml")
}
else if ((file.exists(fname.dat))&&(!file.info(fname.dat)$isdir))
{
con$connection <- "file"
con$fname <- fname.dat
fname.aux <- paste0(fname.dat,".aux.xml")
}
else if ((file.exists(fname.gz))&&(!file.info(fname.gz)$isdir))
{
verbose <- Sys.Date()<=as.Date("2020-04-20") & !.isPackageInUse()
solved <- FALSE
if (nchar(Sys.which("gzip"))) {
if (cache) {
if (verbose)
message("trying cache")
con$fname <- .ursaCacheRaster(fname.gz
,ifelse(decompress,"gzip","gzip"),reset=cache!=1)
solved <- !is.null(con$fname)
}
else if (decompress) {
if (verbose)
message("local unpack")
# con$fname <- paste0(fname,".unpacked",.maketmp(),"~")
fbase <- .maketmp()
con$fname <- file.path(dirname(fbase)
,paste0(basename(fname)
,".unpacked",basename(fbase),"~"))
# print(con$fname)
# q()
system2("gzip",c("-f -d -c",.dQuote(fname.bz)),stdout=con$fname,stderr=FALSE)
solved <- !is.null(con$fname)
}
if (solved) {
con$connection <- "file"
con$compress <- ifelse(cache,0L,-1L)
}
}
if ((!solved)&&(!decompress)) {
if (verbose)
message("internal ungzip")
con$connection <- "gzfile"
con$fname <- fname.gz
solved <- TRUE
}
if (!solved)
stop("Unable to open gzipped file")
fname.aux <- paste0(fname,".aux.xml")
}
else if ((file.exists(fname.envigz))&&(!file.info(fname.envigz)$isdir))
{
verbose <- Sys.Date()<=as.Date("2023-05-29") & !.isPackageInUse()
solved <- FALSE
if (nchar(Sys.which("gzip"))) {
if (cache) {
if (verbose)
message("trying cache")
srcname <- con$fname
con$fname <- .ursaCacheRaster(fname.envigz
,ifelse(decompress,"gzip","gzip"),reset=cache!=1)
solved <- !is.null(con$fname)
if (F & solved)
attr(con$fname,"aux") <- c(fname.envigz,"gzfile","read")
}
else if (decompress) {
if (verbose)
message("local unpack")
# con$fname <- paste0(fname,".unpacked",.maketmp(),"~")
fbase <- .maketmp()
con$fname <- file.path(dirname(fbase)
,paste0(basename(fname)
,".unpacked",basename(fbase),"~"))
# print(con$fname)
# q()
system2("gzip",c("-f -d -c",.dQuote(fname.envigz)),stdout=con$fname,stderr=FALSE)
solved <- !is.null(con$fname)
}
if (solved) {
con$connection <- "file"
con$compress <- ifelse(cache,0L,-1L)
}
}
if ((!solved)&&(!decompress)) {
if (verbose)
message("internal ungzip")
con$connection <- "gzfile"
con$fname <- fname.envigz
solved <- TRUE
}
if (!solved)
stop("Unable to open gzipped file")
fname.aux <- paste0(fname.envi,".aux.xml")
}
else if ((file.exists(fname.bz))&&(!file.info(fname.bz)$isdir)) {
verbose <- Sys.Date()<=as.Date("2020-04-20") & !.isPackageInUse()
solved <- FALSE
if (nchar(Sys.which("bzip2"))) {
if (cache) {
if (verbose)
message("trying cache")
con$fname <- .ursaCacheRaster(fname.bz
,ifelse(decompress,"bzip2","bzip2"),reset=cache!=1)
solved <- !is.null(con$fname)
}
else if (decompress) {
if (verbose)
message("local unpack")
# con$fname <- paste0(fname,".unpacked",.maketmp(),"~")
fbase <- .maketmp()
con$fname <- file.path(dirname(fbase)
,paste0(basename(fname)
,".unpacked",basename(fbase),"~"))
# print(con$fname)
# q()
system2("bzip2",c("-f -d -c",.dQuote(fname.bz)),stdout=con$fname,stderr=FALSE)
solved <- !is.null(con$fname)
}
if (solved) {
con$connection <- "file"
con$compress <- ifelse(cache,0L,-1L)
}
}
if ((!solved)&&(!decompress)) {
if (verbose)
message("internal un-bzip2")
con$connection <- "bzfile"
con$fname <- fname.bz
solved <- TRUE
}
if (!solved)
stop("Unable to open bzip2-ped file")
fname.aux <- paste0(fname,".aux.xml")
}
else if ((file.exists(fname.bingz))&&(!file.info(fname.bingz)$isdir))
{
if (!decompress)
{
con$connection <- "gzfile"
con$fname <- fname.bingz
}
else
{
con$connection <- "file"
# con$fname <- paste0(fname,".unpacked~")
# con$fname <- paste0(fname,".unpacked",basename(.maketmp()),"~")
fbase <- .maketmp()
con$fname <- file.path(dirname(fbase)
,paste0(basename(fname)
,".unpacked",basename(fbase),"~"))
if (FALSE) {
system(paste("gzip -f -d -k -Sgz",fname.bingz))
file.rename(fname.bin,con$fname)
}
else ## without "-k" key
system2("gzip",c("-f -d -c",.dQuote(fname.bingz)),stdout=con$fname,stderr=FALSE)
con$compress <- -1L
}
fname.aux <- paste0(fname.bin,".aux.xml")
}
else if ((file.exists(fname.xz))&&(!file.info(fname.xz)$isdir))
{
if (!decompress)
{
con$connection <- "xzfile"
con$fname <- fname.xz
}
else
{
con$connection <- "file"
# con$fname <- paste0(fname,".unpacked~")
# con$fname <- paste0(fname,".unpacked",basename(.maketmp()),"~")
fbase <- .maketmp()
con$fname <- file.path(dirname(fbase)
,paste0(basename(fname)
,".unpacked",basename(fbase),"~"))
if (FALSE) ## should be obsolete
shell(paste("xz -d -c",fname.xz,"1>",con$fname))
else {
system(paste("xz -f -d -k",fname.bz))
file.rename(fname,con$fname)
}
con$compress <- -1L
}
fname.aux <- paste0(fname,".aux.xml")
}
else {
dpath <- dirname(fname)
a <- .dir(path=dpath
,pattern=paste0("^",basename(fname),"(\\..+)$")
,recursive=FALSE,full.names=FALSE)
a <- .grep("\\.(hdr|png|tif)$",a,invert=TRUE,value=TRUE)
if (length(a)==1) {
con$connection <- "file"
con$fname <- file.path(dpath,a)
}
else if (!headerOnly) {
opW <- options(warn=0)
warning("Unable to recognize ENVI binary file name. Data values are skipped")
options(opW)
}
}
metadata <- if ((!is.na(fname.aux)&&(file.exists(fname.aux))))
readLines(fname.aux,warn=FALSE) else NULL
# md <- xml2::as_list(xml2::read_xml(fname.aux))
if (!is.na(con$connection)) {
con$handle <- try(do.call(con$connection,list(con$fname,"r+b")),silent=TRUE)
if (inherits(con$handle,"try-error")) ## read-only
con$handle <- do.call(con$connection,list(con$fname,"rb"))
}
if (("bzfile" %in% class(con$handle))||("xzfile" %in% class(con$handle)))
con$seek <- FALSE
else
con$seek <- TRUE
obj$dim <- c(grid$rows*grid$columns,con$bands)
if (!is.null(metadata)) {
patt <- "<MDI key=\"Band_(\\d+)\">(.+)</MDI>"
bname1 <- .grep(patt,metadata,value=TRUE)
if (length(bname1)) {
bname2 <- .gsub2(patt,"\\2",bname1)
if (!all(bname2==bname1)) {
bseq2 <- as.integer(.gsub2(patt,"\\1",bname1))
obj$name[bseq2] <- bname2
}
}
}
if (is.na(obj$name[1])) {
obj$name <- sprintf(sprintf("%s %%0%dd","Band"
,nchar(length(1:obj$dim[2]))),1:obj$dim[2])
# obj$name <- character()
}
if (!is.null(metadata))
{
a <- .grep("NoDataValue",metadata,value=TRUE)
if (length(a)) {
con$nodata <- as.numeric(.gsub2("<NoDataValue.*>(.+)</NoDataValue>"
,"\\1",a[1]))
if (is.infinite(con$nodata)) ## "-1.79769313486232Ee308"
con$nodata <- sign(con$nodata)*1.7976931348623e+308
}
}
res <- NULL
if (!is.null(metadata)) {
ind1 <- grep("<PAMRasterBand",metadata)
ind2 <- grep("</PAMRasterBand",metadata)
if ((length(ind1))&&(length(ind1)==length(ind2))) {
res <- vector("list",length(ind1))
# names(res) <- rep("___",length(ind1))
names(res) <- as.character(seq(length(ind1)))
patt1 <- "^.*<MDI key=\"(.+)\">(.+)</MDI>.*$"
patt2 <- "^.*<Description>(.+)</Description>.*$"
for (i in seq_along(ind1)) {
md <- metadata[ind1[i]:ind2[i]]
if (length(ind4 <- grep(patt2,md)))
desc <- gsub(patt2,"\\1",md[ind4])
else
desc <- character()
ord <- as.integer(gsub("^.*band=\"(\\d+)\".*$","\\1",md[1]))
ind3 <- grep(patt1,md)
if (length(ind3)) {
name <- gsub(patt1,"\\1",md[ind3])
value <- as.list(gsub(patt1,"\\2",md[ind3]))
names(value) <- name
if (length(desc))
names(res)[ord] <- desc
res[[ord]] <- value
}
}
# str(head(res,3))
# q()
}
}
res2 <- NULL
ind1 <- grep("<PAMDataset",metadata)
ind2 <- grep("</PAMDataset",metadata)
if ((length(ind1)==1)&&(length(ind2)==1)) {
patt1 <- "^.*<MDI key=\"(.+)\">(.+)</MDI>.*$"
md <- metadata[seq(ind1+1L,ind2-1L)]
ind3 <- grep(patt1,md)
if (length(ind3)) {
name <- gsub(patt1,"\\1",md[ind3])
value <- as.list(gsub(patt1,"\\2",md[ind3]))
names(value) <- name
res2 <- list(value)
names(res2) <- "Dataset metadata (unstructured)"
# if (length(desc))
# names(res)[ord] <- desc
# res[[ord]] <- value
}
}
res <- c(res2,res)
if (!is.null(res)) {
attr(obj,"metadata") <- res
}
if (is.null(grid$crs))
grid$crs <- ""
if ((!nchar(grid$crs))&&(nchar(wkt)))
{
lverbose <- FALSE
if (lverbose)
.elapsedTime("wkt -> proj4 start")
# (!("package:rgdal" %in% search()))) {
isSF <- ("sf" %in% loadedNamespaces())&&(utils::packageVersion("sf")<"99990.9")
isSP <- "sp" %in% loadedNamespaces()
if ((nchar(Sys.which("gdalsrsinfo")))&&(!isSF)&&(!isSP)) {
if (lverbose)
message("'gdalsrsinfo' engine (read)")
if (FALSE) ## slow
grid$crs <- .gsub("\'","",system2("gdalsrsinfo"
,c("-o proj4",wkt),stdout=TRUE,stderr=FALSE))
else {
tmp <- .maketmp()
wktin <- paste0(tmp,".prj~")
writeLines(wkt,wktin)
wktout <- paste0(tmp,".wkt~")
system2("gdalsrsinfo",c("-o proj4",wktin),stdout=wktout,stderr=FALSE)
grid$crs <- .gsub("\'","",readLines(wktout,warn=FALSE))
file.remove(wktout)
file.remove(wktin)
grid$crs <- grid$crs[nchar(grid$crs)>0]
}
}
else if (!isSF) {
if (lverbose)
message("showP4() in 'rgdal'")
.try(grid$crs <- .rgdal_showP4(wkt))
# .try(grid$crs <- attr(GDALinfo(con$fname,returnStats=FALSE)
# ,"projection")) ## GDALinfo() from 'rgdal'
}
else {
if (lverbose)
message("sf::st_crs")
opW <- options(warn=ifelse(.isPackageInUse(),-1,1))
if (utils::packageVersion("sf")<"0.9")
.try(grid$crs <- sf::st_crs(wkt=wkt)$proj4string)
else
.try(grid$crs <- sf::st_crs(wkt)$proj4string)
options(opW)
# res <- sf::st_crs(wkt)$proj4string
# message(res)
if ((is.na(grid$crs))||(!nchar(grid$crs))) {
if (nchar(Sys.which("gdalsrsinfo"))) {
## FAILED for prj with 'wkt_esri' spec
if (lverbose)
message(" sf::st_crs --> gdalsrsinfo")
tmp <- .maketmp()
wktin <- paste0(tmp,".prj~")
writeLines(wkt,wktin)
wktout <- paste0(tmp,".wkt~")
system2("gdalsrsinfo",c("-o proj4",wktin),stdout=wktout,stderr=FALSE)
grid$crs <- .gsub("\'","",readLines(wktout,warn=FALSE))
file.remove(wktout)
file.remove(wktin)
grid$crs <- grid$crs[nchar(grid$crs)>0]
}
else {
message(" sf::st_crs -> showP4() in 'rgdal'")
.try(grid$crs <- .rgdal_showP4(wkt))
}
}
# stop("This is ureacheable branch! TODO for `sf`>0.8")
}
if (lverbose)
.elapsedTime("wkt -> proj4 finish")
session_grid(grid)
}
con$driver <- "ENVI"
# class(grid$crs) <- c("character","ursaProjection")
obj$grid <- grid
obj$con <- con
arglist <- list(...)
nodata <- .getPrm(arglist,name="^(nodata|ignore(value)*|bg)$"
,class=c("integer","numeric"),default=NA,verbose=FALSE)
if (!is.na(nodata))
obj$con$nodata <- nodata
if (!.lgrep("(layer|band)*name",names(arglist)))
return(obj)
ln1 <- obj$name
ln2 <- arglist[[.grep("(layer|band)*name",names(arglist))]]
if (identical(ln1,ln2))
return(obj)
close(obj) ## rebuild bands; e.g. after update to monthly sst
if (length(unique(ln1))!=length(ln1)) {
stop("Band names are not unique")
}
m12 <- c(na.omit(match(ln1,ln2)))
m21 <- c(na.omit(match(ln2,ln1)))
if (length(m12)!=length(m21)) { # (any(is.na(m12))) {
# close(obj)
stop("Inconsistence of band names")
}
ftemp <- .maketmp()
envi_rename(fname,ftemp)
src <- open_envi(ftemp,cache=TRUE) ## RECURSUVE
dst <- create_envi(wname,...)
srcname <- names(src)
dstname <- names(dst)
cb <- chunk_band(src)
from <- head(m21,1)
to <- tail(m21,1)
for (i in chunk_band(src)) {
j <- i[i>=from & i<=to]
if (!length(j))
next
k <- match(j,m21)
if (anyNA(k)) {
j <- j[which(!is.na(k))]
k <- c(na.omit(k))
}
if (!length(j))
next
dst[k] <- src[j]
}
close(src)
envi_remove(ftemp)
rm(src)
dst
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/conn.open_envi.R
|
'ursa_open' <- function(fname,verbose=FALSE) open_gdal(fname=fname,verbose=verbose)
'open_gdal' <- function(fname,engine=c("native","sf","gdalraster","vapour")
,verbose=FALSE) {
engList <- as.character(as.list(match.fun("open_gdal"))[["engine"]])[-1]
if (length(engine)<length(engList)) {
if (!.isPackageInUse()) {
engList <- c(engList,"rgdal")
}
}
engine <- match.arg(engine,engList)
# if (engine=="native")
# engine <- "sf" ## replace to 'sf'
# if (verbose)
# print(c(engine=engine))
fname <- gsub("\\.$","",fname)
if ((engine=="vapour")&&(requireNamespace("vapour",quite=!.isPackageInUse()))) {
return(.open_vapour(fname,engine=engine,verbose=verbose))
}
if ((engine=="gdalraster")&&(requireNamespace("gdalraster",quite=!.isPackageInUse()))) {
return(.open_gdalraster(fname,engine=engine,verbose=verbose))
}
if (engine!="rgdal") {
return(.open_sfgdal(fname,engine=engine,verbose=verbose))
}
if (engine=="rgdal") {
return(.open_rgdal(fname,engine=engine,verbose=verbose))
}
## 20170116 removed '...' argument
if (!is.character(fname))
return(NULL)
stop("unknown 'engine'")
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/conn.open_gdal.R
|
## 'caTools::read.ENVI'
##~ '.read_envi' <- function(fname,subset=NULL,nodata=NaN
##~ ,ref=NULL,resetGrid=FALSE,...)
'read_envi' <- function(fname,...)
{
arglist <- list(...)
subset <- .getPrm(arglist,name="(^$|band|subset)",class=c("integer","character")
,default=NULL)
nodata <- .getPrm(arglist,name="(nodata|ignorevalue)",default=NaN)
cache <- .getPrm(arglist,name="cache",class=c("integer","logical","character"),default=0L)
ref <- .getPrm(arglist,class=c("ursaRaster","ursaGrid"),default=NULL)
resetGrid <- .getPrm(arglist,name="reset(Grid)*",default=FALSE)
verbose <- .getPrm(arglist,name="verb(ose)*",default=FALSE)
if (!is.null(ref)) {
if (is.ursa(ref))
ref <- ref$grid
}
g0 <- getOption("ursaSessionGrid")
g1 <- if (is.null(ref)) g0 else ref
if (is.null(g1))
theSame <- TRUE
else {
g2 <- ursa_grid(fname)
# .c1 <- match(ursa_seqx(g2),ursa_seqx(g1));print(.c1);q()
x1 <- ursa_seqx(g1)
x2 <- ursa_seqx(g2)
y1 <- ursa_seqy(g1)
y2 <- ursa_seqy(g2)
condX <- na.omit(.is.near(x2,x1))
ind <- attr(condX,"na.action")
condY <- na.omit(.is.near(y2,y1))
condX <- ((length(condX))&&(all(diff(condX)==1)))
condY <- ((length(condY))&&(all(diff(condY)==1)))
# condG <- .grid.equal(g1,g2)
# print(c(condX=condX,condY=condY,condG=condG))
theSame <- condX & condY # & condG
}
if (!theSame) {
ref <- g1
##~ resetGrid <- TRUE
}
if (verbose) {
str(list(subset=subset,nodata=nodata,ref=ref,grid=ursa_grid(fname)
,theSame=theSame,resetGrid=resetGrid))
}
if ((!is.null(ref))&&(theSame)) {
session_grid(ref)
}
# if (!theSame) { ## removed 20161002
if ((resetGrid)||(!theSame)) { ## added 20161002
session_grid(NULL)
}
obj <- open_envi(fname,cache=cache,decompress=!is.null(subset)) ## ,nodata=nodata
bname <- bandname(obj)
if (.is.grid(obj))
return(NULL)
if (!is.nan(nodata)) {
storage.mode(nodata) <- obj$con$mode
obj$con$nodata <- nodata
}
if ((!is.null(subset))&&(obj$con$connection=="file")) { ## if (obj$con$seek)
ret <- obj[subset]
}
else
{
# if ((is.character(obj$con$fname))&&(nchar(obj$con$fname)>0)&&
# (!file.exists(obj$con$fname)))
if (is.na(obj$con$handle)) {
# ursa_value(obj) <- NA
ret <- ursa_new(bandname=bandname(obj))
}
else {
ret <- obj[]
}
if (!is.null(subset))
ret <- obj[subset]
}
if (FALSE) { ## --20180312
# print(summary(as.numeric(obj$value)));q()
if (!is.na(obj$con$handle))
close(obj$con$handle)
obj$con$handle <- NA
}
else
close(obj)
# .gc() ## 20180312 does it required?
# if (!theSame & !resetGrid) {
if (!theSame & !resetGrid) {
ret <- regrid(ret,grid=ref,...)
}
if ((!resetGrid)&&(!is.null(g0)))
session_grid(g0)
ret
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/conn.read_envi.R
|
'ursa_read' <- function(fname,verbose=FALSE) { ## ,resetGrid=TRUE
if (envi_exists(fname)) {
return(read_envi(fname)) # ,resetGrid=resetGrid
}
if (!.lgrep("\\.zip$",fname)) {
return(read_gdal(fname=fname,verbose=verbose)) ## ,resetGrid=resetGrid
# return(.read_gdal(fname=fname,verbose=verbose))
}
list1 <- unzip(fname,exdir=tempdir());on.exit(file.remove(list1))
ind <- .grep("\\.tif(f)*$",list1)
if (length(ind)) {
aname <- .gsub("\\.tif(f)*","",basename(list1[ind]))
if (TRUE) {
res <- vector("list",length(aname))
names(res) <- aname
res <- lapply(list1[ind],read_gdal,verbose=verbose) ## '.read_gdal'
names(res) <- aname
g <- lapply(res,ursa_grid)
if (all(sapply(head(g,-1),function(g2) all.equal(g[[1]],g2))))
res <- as.ursa(res)
return(res)
}
for (i in sample(seq_along(aname))) {
a <- .read_gdal(fname=list1[ind][i],verbose=verbose)
if (!exists("res"))
res <- ursa(bandname=aname)
res[i] <- a
}
return(res)
}
NULL
}
'read_gdal' <- function(fname,resetGrid=TRUE,band=NULL
,engine=c("native","sf","gdalraster","vapour")
,verbose=FALSE,...) { ## ,...
# if (resetGrid)
# session_grid(NULL)
engList <- as.character(as.list(match.fun("read_gdal"))[["engine"]])[-1]
if (length(engine)<length(engList)) {
if (!.isPackageInUse()) {
engList <- c(engList,"rgdal")
}
}
engine <- match.arg(engine,engList)
fname <- gsub("\\.$","",fname)
if (!file.exists(fname)) {
list1 <- dir(path=dirname(fname),pattern=paste0("^",basename(fname)),full.names=TRUE)
list1 <- list1[.grep("\\.(tif|tiff|img|hfa)$",basename(list1))]
if (length(list1)==1)
fname <- list1
}
if ((engine=="vapour")&&(requireNamespace("vapour",quite=!.isPackageInUse()))) {
return(.read_vapour(fname,resetGrid=resetGrid,band=band
,engine=engine,verbose=verbose))
}
if ((engine=="gdalraster")&&(requireNamespace("gdalraster",quite=!.isPackageInUse()))) {
return(.read_gdalraster(fname,resetGrid=resetGrid,band=band
,engine=engine,verbose=verbose))
}
if (engine %in% c("vapour","gdalraster"))
engine <- "native"
loaded <- loadedNamespaces() #.loaded()
forceSF <- isTRUE(getOption("ursaForceSF"))
if (accepted_changes <- TRUE) {
if ((is.null(band))&&(engine %in% "native")) {
if ((!forceSF)&&(("sp" %in% loaded)||("rgdal" %in% loaded)))
isSF <- FALSE
if ((forceSF)||("sf" %in% loaded))
isSF <- TRUE
else
isSF <- FALSE
}
else if (engine %in% c("native","sf")[2]) {
isSF <- TRUE
}
# else if ((!is.null(band))||(engine %in% c("native","rgdal")[1:2])) {
# isSF <- FALSE
# }
else
isSF <- FALSE
##~ else {
##~ loaded <- loadedNamespaces() #.loaded()
##~ if ("sf" %in% loaded)
##~ isSF <- TRUE
##~ else if (("sp" %in% loaded)||("rgdal" %in% loaded))
##~ isSF <- FALSE
##~ else
##~ isSF <- requireNamespace("sf",quietly=.isPackageInUse())
##~ }
}
else
isSF <- FALSE
if ((isSF)&&(!("sf" %in% loaded)))
isSF <- requireNamespace("sf",quietly=.isPackageInUse())
if (verbose)
print(data.frame(isSF=isSF,engine=engine))
if (isSF) {
# str(md <- sf::gdal_metadata(fname,parse=!FALSE))
# str(ds <- sf::gdal_subdatasets(fname,name=TRUE))
opW <- options(warn=ifelse(.isPackageInUse(),-1,1))
res <- as_ursa(sf::gdal_read(fname))
options(opW)
if (forcedNoData <- TRUE) {
gi <- sf::gdal_utils("info",fname,quiet=!FALSE)
gi <- strsplit(gi,split="\\n")[[1]]
gi <- grep("NoData Value",gi,value=TRUE)
if (length(gi)>0) {
nodata <- gsub("^.*=(\\s*(\\S+))$","\\1",gi)
if (typeof(ursa_value(res))=="integer")
ignorevalue(res) <- as.integer(unique(nodata))
else
ignorevalue(res) <- as.numeric(unique(nodata))
}
}
if (!is.null(band))
res <- res[band]
}
else {
obj <- open_gdal(fname,engine=engine,verbose=verbose)
if (is.null(obj))
return(NULL)
res <- if (!is.null(band)) obj[band] else obj[]
close(obj)
}
if (T & length(grep("^(\\d{8}\\.s1ab\\.1km\\.n\\.mos[13]d|.+sentinel1-n-[13]daymos)\\.jpg$"
,basename(fname)))) {
## patch to seaice.dk Sentinel-1 mosaic
g0 <- ursa_grid(res)
if ((g0$columns==4500L)&&(g0$rows==5500L)) {
xy <- .project(c(-176.682000,61.327000),spatial_crs(3413))
g1 <- .grid.skeleton()
g1$resx <- g1$resy <- 1004.1
g1$crs <- spatial_crs(3413)
g1$columns <- g0$columns
g1$rows <- g0$rows
g1$minx <- round(xy[,1])-g1$resx/2
g1$maxy <- round(xy[,2])#+g1$resy/2
g1$maxx <- g1$minx+g1$resx*g1$columns
g1$miny <- g1$maxy-g1$resy*g1$rows
ursa_grid(res) <- g1
}
}
if (resetGrid)
session_grid(res)
res
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/conn.read_gdal.R
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/conn.read_stars.R
|
|
## 'caTools::write.ENVI'
'write_envi' <- function(obj,...)
{
if (.is.ursa_stack(obj))
obj <- if (length(obj)>1) ursa_brick(obj) else obj[[1]]
arglist <- list(...)
isRaster <- is.ursa(obj)
isGrid <- .is.grid(obj)
isCT <- .getPrm(arglist,name="colortable",default=TRUE)
if (!.is.colortable(obj))
isCT <- FALSE
# if (((isCT)&&(!obj$category))||((!isCT)&&(obj$category)))
if (isCT+.is.category(obj)==1)
{
obj <- reclass(obj)
}
if ((isRaster)&&(!isCT)) {
ursa_colortable(obj) <- character(0)
}
if (!FALSE) {# removed (20161225 restored)
if (isGrid) {
g1 <- session_grid()
session_grid(obj)
res <- create_envi(obj,nodata=NA,datatype=1L,compress=FALSE,...)
close(res)
file.remove(res$con$fname)
session_grid(g1)
return(invisible(100L+res$con$datatype))
}
res <- create_envi(obj,...)
}
else {
nodata <- .getPrm(arglist,name="(^bg$|nodata|ignore)",default=NA)
if ((is.na(nodata))&&(anyNA(obj$value)))
arglist$nodata <- .optimal.nodata(obj$value)
res <- do.call("create_envi",c(list(obj),arglist))
}
if (isRaster)
res[] <- obj
close(res)
return(invisible(res$con$datatype))
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/conn.write_envi.R
|
# 'ursa_write' <- function(...) .syn('.write_gdal',2,...)
'ursa_write' <- function(obj,fname) { ## proposed: compress=TRUE for DEFLATE, ZSTD, etc
if (!.lgrep("\\..+$",basename(fname))) {
return(write_envi(obj,fname))
}
# stop("B")
if (.lgrep("\\.zip$",basename(fname))) {
aname <- paste0(names(obj),".tif")
td <- file.path(tempdir(),basename(.maketmp()))
dir.create(td)
wd <- setwd(td)
for (i in seq(obj)) {
ursa_write(obj[i],aname[i]) ## RECURSIVE!!!
# write_gdal(obj[i],aname[i])
}
if (!.is.colortable(obj))
file.remove(dir(pattern="\\.aux\\.xml$"))
zname <- file.path(wd,fname)
if (file.exists(zname))
file.remove(zname)
utils::zip(zname,dir(),"-qmj9")
setwd(wd)
return(invisible(integer()))
}
if ((FALSE)&&(.lgrep("\\.(tif|img)$",basename(fname)))&&(nchar(Sys.which("gdal_translate")))) {
# print("interim ENVI, then system GDAL")
ftmp <- .maketmp()
ret <- write_envi(obj,paste0(ftmp,"."))
pr <- ifelse(ret %in% c(1L,2L,3L,11L,12L,13L),2L,3L)
fpath <- dirname(fname)
if (!dir.exists(fpath))
dir.create(fpath,recursive=TRUE)
proj_lib <- Sys.getenv("PROJ_LIB")
Sys.setenv(PROJ_LIB=file.path(dirname(dirname(Sys.which("gdal_translate")))
,"share/proj"))
if (.lgrep("\\.(tif)$",basename(fname)))
system2("gdal_translate",c("-q","-of","GTiff"
,"-co",.dQuote(paste0("COMPRESS=",c("DEFLATE","ZSTD")[1]))
,"-co",.dQuote(paste0("PREDICTOR=",pr))
,"-co",.dQuote("ZSTD_LEVEL=9")
,"-co",.dQuote("ZLEVEL=9")
,"-co",.dQuote("TILED=NO")
,"-co",.dQuote(paste0("INTERLEAVE="
,ifelse(length(obj)<2,"PIXEL","BAND")))
,.dQuote(ftmp),.dQuote(fname)))
else if (.lgrep("\\.(img)$",basename(fname)))
system2("gdal_translate",c("-q","-of","HFA"
,"-co",.dQuote("COMPRESSED=YES")
,.dQuote(ftmp),.dQuote(fname)))
Sys.setenv(PROJ_LIB=proj_lib)
envi_remove(ftmp)
return(invisible(ret))
}
##~ if (("sf" %in% loadedNamespaces())&&
##~ (requireNamespace("stars",quietly=.isPackageInUse()))) {
##~ ret <- .write_sfgdal(obj,fname)
##~ }
if ((!"sf" %in% loadedNamespaces())&&(isTRUE(getOption("ursaForceSF"))))
requireNamespace("sf",quietly=.isPackageInUse())
ftmp <- .maketmp()
ret <- write_envi(obj,paste0(ftmp,"."))
ret2 <- .envi2gdal(src=ftmp,dst=fname,datatype=ret,bands=length(obj))
envi_remove(ftmp)
if (ret==ret2)
return(invisible(ret))
# stop("Failed to write raster file ",dQuote(fname))
return(write_gdal(obj=obj,fname=fname))
}
'.envi2gdal' <- function(src,dst,datatype,bands) {
fpath <- dirname(dst)
if (!dir.exists(fpath))
dir.create(fpath,recursive=TRUE)
if (file.exists(dst))
file.remove(dst)
op <- character()
if (.lgrep("\\.(tif(f)*)$",basename(dst))) {
pr <- ifelse(datatype %in% c(4L,5L),3L,2L)
op <- c("-of","GTiff"
,"-co",paste0("COMPRESS=",c("DEFLATE","ZSTD")[1])
,"-co",paste0("PREDICTOR=",pr)
,"-co",paste0("ZSTD_LEVEL=9")
,"-co",paste0("ZLEVEL=9")
,"-co",paste0("TILED=NO")
,"-co",paste0("INTERLEAVE="
,ifelse(bands<2,"PIXEL","BAND"))
)
}
else if (.lgrep("\\.(img|hfa)$",basename(dst))) {
op <- c("-of","HFA"
,"-co",paste("COMPRESSED=YES")
)
}
else {
return(invisible(-98L))
}
# print(paste(op,collapse=" "))
gd <- sf::gdal_utils(util="translate"
,source=src
,destination=dst
,quiet=TRUE
,options=op
)
if (file.exists(dst))
return(invisible(datatype))
invisible(-97L)
}
'write_gdal' <- function(obj,...) {
arglist <- list(...)
engine <- .getPrm(arglist,name="engine",default="native")
# if ((.isPackageInUse())||(!.rgdal_requireNamespace())) { ## .rgdal_loadedNamespaces
if ((.isPackageInUse())||(engine!="rgdal")) {
res <- try(.write_sfgdal(obj,...))
# ret <- .try(res <- .write_sfgdal(obj,...))
if (!inherits(res,"try-error"))
return(invisible(res))
message(as.character(res))
warning("File creation is failed; writting is failed")
return(invisible(NULL))
}
res <- create_gdal(obj,...)
if (is.null(res))
return(invisible(-99L))
res[] <- obj
opt <- list(...)
opt <- opt[nchar(names(opt))>0]
res$con$compress <- opt
close(res)
return(invisible(res$con$datatype))
}
'.write_sfgdal' <- function(obj,fname,driver,options,...) {
if ((!"sf" %in% loadedNamespaces())&&(T | isTRUE(getOption("ursaForceSF"))))
requireNamespace("sf",quietly=.isPackageInUse())
if (!requireNamespace("stars",quietly=.isPackageInUse()))
warning("Package `stars` is required for raster writting")
datatype <- .optimal.datatype(obj)
nodata <- ignorevalue(obj)
dtName <- switch(as.character(datatype)
,'1'="Byte",'2'="Int16",'4'="Float32"
,'11'="Int8",'12'="UInt16",'13'="UInt32",'3'="Int32"
,'5'="Float64",stop("cannot recognize datatype"))
if (missing(driver)) {
driver <- NULL
bname <- basename(fname)
if (.lgrep("\\.tif(f)*$",bname))
driver <- "GTiff"
else if (.lgrep("\\.img$",bname))
driver <- "HFA" # https://gdal.org/frmt_hfa.html
else if (.lgrep("\\.png$",bname))
driver <- "PNG"
else if (.lgrep("\\.jp(e)*g$",bname))
driver <- "JPEG"
else if (.lgrep("\\.bmp$",bname))
driver <- "BMP"
# else if (.lgrep("\\.sdat$",fname))
# driver <- "SAGA"
if (is.null(driver))
driver <- "ENVI"
}
if (missing(options)) {
if (driver=="GTiff") {
opt <- c("COMPRESS=DEFLATE"
,paste0("PREDICTOR=",ifelse(datatype %in% c(4,5),"3","2"))
,paste0("INTERLEAVE=",ifelse(length(obj)==1,"PIXEL","BAND"))
,"TILED=NO"
)
}
else
opt <- character()
}
else {
if (is.character(options)) {
oname <- names(options)
if (is.null(oname))
opt <- do.call(c,strsplit(options,split="\\s+"))
else
opt <- paste0(oname,"=",options)
}
else if (is.list(options))
opt <- paste0(names(options),"=",sapply(options,\(x) x))
else
opt <- character()
# opt <- paste(opt,collapse=" ")
}
ret <- sf::gdal_write(as_stars(obj),driver=driver
,file=fname,type=dtName,NA_value=nodata,options=opt
,geotransform=with(ursa_grid(obj),c(minx,resx,0,maxy,0,-resy))
)
return(invisible(datatype))
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/conn.write_gdal.R
|
## modified from rje::cubeHelix
# b <- colorize(n,weak=-270*pi/180,rotate=270/360) ~ colorBrewer "Spectral"
# b <- colorize(n,rich=0,rotate=60,hue=1.5 ~ for bathymetry
'cubehelix' <- function(n,value=numeric(),weak=NA,rich=NA,rotate=NA,hue=NA,gamma=1
,dark=NA,light=NA,bright=NA,inv=NA,verbose=NA)
{
# str(match.call())
# set.seed(as.integer(as.numeric(Sys.time())/10))
# value <- NULL
# verbose <- FALSE
bg <- getOption("ursaPngBackground")
bg <- ifelse(is.null(bg),255,sum(c(col2rgb(bg))*c(0.30,0.59,0.11)))
.dark <- 91 # '63' for monitors, '91' for printers
.light <- 241
# print(getOption("ursaPngBackground"))
default.dark <- ifelse(bg>127,.dark,255-.light)
default.light <- ifelse(bg>127,.light,255-.dark)
autobright <- FALSE
if ((is.na(dark))&&(is.na(light))) {
if (is.na(bright)) {
dark <- default.dark/255
light <- default.light/255
autobright <- TRUE
}
else {
dark <- light <- bright
}
}
else if ((is.na(dark))&&(!is.na(light))) {
if (light>1)
light <- light/255
dark <- default.dark/255
# autobright <- FALSE
}
else if ((!is.na(dark))&&(is.na(light))) {
if (dark>1)
dark <- dark/255
light <- default.light/255
# autobright <- FALSE
}
if ((dark>1)||(light>1)) {
dark <- dark/255
light <- light/255
}
value <- unname(sort(value))
if (missing(n))
n <- if (length(value)) length(value) else 256L
if (is.na(verbose))
verbose <- FALSE #is.na(rich) || is.na(rotate) || is.na(hue)
if (autobright) {
# k <- round(1/(exp(n^0.5)),6) ## --20180324
# k <- round(0.5/(exp(n^0.44)),6) ## ++20180324
k <- round(0.7/(exp(n^0.475)),6) ## ++20180324
}
else
k <- 0
divergent <- length(value)>0 ## 20170705 -- length(value)>0
if (divergent) {
isCategory <- length(value)==n
isInterval <- length(value)==n-1
if ((!isCategory)&&(!isInterval))
divergent <- FALSE
else {
# verbose <- TRUE
# eps <- min(abs(value))
eps <- 1e-14 #ifelse(eps<1e-11,1e-11,0)
npos <- length(which(value>(-eps)))
nneg <- length(which(value<(+eps)))
nzer1 <- length(which(abs(value)<eps))
if ((!npos)||(!nneg)||((npos==1)&&(nneg==1))) {
divergent <- FALSE
}
else {
if (isInterval) {
dval <- diff(value)
value <- c(head(value,1)-head(dval,1)/2
,tail(value,-1)-dval/2
,tail(value,1)+tail(dval,1)/2)
}
nzer2 <- length(which(abs(value)<eps))
# npos <- length(which(value>(-eps)))
# nneg <- length(which(value<(+eps)))
indZ <- which(abs(abs(value)-min(abs(value)))<1e-11)
if (nzer2) { ## 20170123 added '(TRUE)', 20170201 changed (nzer)
# print(c(pos=npos,neg=nneg))
npos <- length(which(seq(n)>=head(indZ,1)))
nneg <- length(which(seq(n)<=tail(indZ,1)))
}
rest <- n-max(npos,nneg)#-as.integer(isInterval)
n <- n-rest
if (verbose)
print(c(pos=npos,neg=nneg,z1=nzer1,z2=nzer2,n=n,rest=rest,indZ=indZ
,int=isInterval,cat=isCategory))
}
}
}
if (dark+k>light-k) {
k <- 0
if (n==1)
dark=0.7*light
}
# k is not optimal for n=2
dark <- dark+3*k/2
light <- light-1*k/2
lambda <- rev(seq(dark,light,length.out=n))
if ((divergent)&&(rest>0)) {
if (length(indZ)==1) {
lambda <- c(lambda[rev(1+seq(rest))],lambda)
n <- n+rest
if (anyNA(lambda)) {
lambda <- rev(seq(dark,light,length.out=n))
divergent <- FALSE
}
}
else {
if (TRUE) { #(length(lambda)>2) {
nr <- 4
# print(rest)
# print(lambda[rev(0+seq(rest))])
# print(rep(lambda[1],nr))
lambda <- c(lambda[rev(0+seq(rest))],rep(lambda[1],nr),lambda)
n <- n+rest+nr
toOmit <- if (nneg>npos) n-rev(rest+seq(nr))+1 else rest+seq(nr)
}
else
toOmit <- integer()
}
if (nneg>npos)
lambda <- rev(lambda)
# print(round(lambda*255,1))
}
if ((is.character(rotate))&&(.lgrep("circle|round",rotate))) {
if (n>1)
rotate <- .sample(c(-1,1),1)*360*(1-1/n)
else
rotate <- NA
}
if ((!is.na(rich))&&(!is.na(weak))) {
rotate <- rich-weak
}
if (any(is.na(rotate))) {
if (length(unique(lambda))==1) {
rotate <- round(runif(1,min=0.5,max=0.9),2)
# rotate <- 1
}
else {
if (divergent)
rotate <- round(runif(1,min=0.6,max=0.8),2)
else if ((light-dark)/n<0.005)
rotate <- round(runif(1,min=0.5,max=0.9),2)
else
rotate <- round(runif(1,min=0.4,max=1.2),2)
}
rotate <- sample(c(-1,1),1)*rotate*360
}
if ((is.na(weak))&&(!is.na(rich))) {
weak <- rich-rotate
}
else if ((!is.na(weak))&&(is.na(rich))) {
rich <- weak+rotate
}
else if ((is.na(weak))&&(is.na(rich))) {
rich <- round(runif(1,min=0,max=2*pi),2)*180/pi
weak <- rich-rotate
}
if (length(rotate)>1)
rotate <- sample(rotate,1)
if (is.na(hue))
hue <- round(runif(1,min=0.9,max=1.5),2)
if ((!FALSE)&&(verbose))
message(sprintf("cubehelix: br=%d:%d weak=%4.0f rich=%4.0f rotate=%4.0f hue=%4.2f k=%.2f n=%d"
,round(dark*255),round(light*255),weak,rich,rotate,hue,k,n))
rich <- rich*pi/180
weak <- weak*pi/180
rotate <- rotate/360
l <- rep(lambda^gamma,each=3)
phi = weak+2*pi*rotate*seq(0,1,length.out=n) # head(seq(0,1,length.out=n+1),-1))
# print(round(phi*180/pi))
tau <- rbind(cos(phi),sin(phi))
M <- matrix(c(-0.14861,-0.29227,1.97294,1.78277,-0.90649,0),ncol=2)
# print(M %*% tau)
out <- l + hue * l * (1 - l)/2 * (M %*% tau)
if ((divergent)&&(rest>0)&&(length(indZ)==2)) {
# print(toOmit)
if (length(toOmit))
out <- out[,-toOmit]
}
out <- pmin(pmax(out, 0), 1)
out <- apply(out,2,function(x) rgb(x[1],x[2],x[3]))
if ((FALSE)&&((light-dark)/n<0.005))
out <- sample(out)
# if ((length(value))&&(nneg>npos))
# return(rev(out))
if (is.na(inv)) {
cond1 <- !length(value[value>0]) & length(value[value<0])>2
inv <- bg<128 | cond1
}
if (inv)
return(rev(out))
out
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/cubehelix.R
|
'discolor' <- function(obj,nodata=NA) {
if (!is.ursa(obj))
return(invisible(obj))
# if (!is.colortable(obj))
# return(invisible(obj))
obj <- .extract(obj)
ursa_colortable(obj) <- character()
if (!is.na(nodata))
ursa_nodata(obj) <- nodata
invisible(obj)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/discolor.R
|
'.plot.ursaRaster' <- function(obj,...) display(obj,...)
#'glance' <- function(obj,...) UseMethod("glance") ## 'broom::glance'
#'glance.ursaRaster' <- function(obj,...) display(obj,...)
'display' <- function(obj,...)
{
arglist <- list(...)
isBlank <- missing(obj)
if (isBlank)
obj <- ursa_new()
verbose <- .getPrm(arglist,name="verb(ose)*",default=FALSE)
toStack <- .getPrm(arglist,name="stack",default=FALSE)
toBrick <- .getPrm(arglist,name="brick",default=FALSE)
isStack <- .is.ursa_stack(obj)
if (verbose)
print(c(toStack=toStack,toBrick=toBrick,isStack=isStack))
if (TRUE) { ## keep to read *.bz2 etc
if ((is.character(obj))&&(!is.matrix(obj))) {
if (isURL <- .lgrep("^(http://|https://|ftp://|file:///)",obj)>0) {
fname <- tempfile()
# download.file(obj,fname,method="curl")
ind <- .grep("(method|mode|cache|extra)",names(arglist))
args2 <- c(url=obj,destfile=fname,arglist[ind])
# do.call("download.file",args2)
fname <- do.call(".ursaCacheDownload",c(url=obj,arglist[ind]))
obj <- read_gdal(fname,...)
# try(file.remove(fname))
}
else {
obj <- if (envi_exists(obj)) read_envi(obj,...) else read_gdal(obj,...)
}
}
}
if ((!isStack)&&(!.try(obj <- as.ursa(obj)))) {
if (is.ursa(obj,"grid")) {
g0 <- session_grid()
session_grid(obj)
ret <- display()
session_grid(g0)
return(ret)
}
return(NULL)
}
if (.is.rgb(obj)) {
if (verbose)
print("display_rgb")
return(display_rgb(obj,...))
}
if ((toStack)||(.is.ursa_stack(obj))) {
if (verbose)
print("display stack")
return(display_stack(obj,...))
}
ind <- pmatch("verb",names(arglist))
if ((!is.na(ind))&&(is.logical(arglist[[ind]]))&&(arglist[[ind]]))
verb <- TRUE
else
verb <- !.isPackageInUse()
if ((toBrick)||(.is.brick(obj,verbose=verb))) {
if (!TRUE) {
arglist <- list(...)
if ((!.lgrep("decor",names(arglist)))&&(nband(obj)==1))
arglist$decor <- TRUE
return(invisible(do.call("display_brick",c(list(obj),arglist))))
}
else if (isBlank) {
if (verbose)
print("display blank")
compose_open(legend=NULL,...)
panel_new(...)
panel_decor(...)
if (TRUE) { #(.isPackageInUse())
fann <- .dir(path=system.file("optional/sponsorship",package="ursa")
,pattern="\\.png$",full.names=TRUE)
ann <- png::readPNG(sample(fann,1))
panel_annotation(ann,alpha=0.5,pos="bottomright",cex=0.5)
}
if (.isKnitr())
return(compose_close(...))
compose_close(...)
return(invisible(NULL))
}
else {
if (verbose)
print("display_brick")
if (.isKnitr())
return(display_brick(obj,...))
return(invisible(display_brick(obj,...)))
}
}
else {
if (verbose)
print("display stack")
if (.isKnitr())
return(display_stack(obj,...))
return(invisible(display_stack(obj,...)))
}
stop("unreachable code")
}
'.is.brick' <- function(obj,tol=0.8,verbose=!.isPackageInUse()) {
# verbose <- TRUE
if (nband(obj)==1)
return(TRUE)
e <- band_stat(obj)
if (!TRUE) {
e.var <- e$sd^2/e$n
n <- nrow(e)
p <- rep(NA,n)
for (i in seq(n)) {
j <- if (i==1) n else i-1L
p[i] <- (e$mean[i]-e$mean[j])/sqrt(e.var[i]+e.var[j])
}
if (verbose)
print(p)
p <- na.omit(abs(p))
print(all(p<500)) ## return
}
e.avg <- na.omit(e$mean)
e.sd <- na.omit(e$sd)
e.min <- na.omit(e$min)
e.max <- na.omit(e$max)
if (!length(e.avg))
return(TRUE)
##~ sd.avg <- sd(e.avg)
##~ sd.sd <- sd(e.sd)
##~ sd.min <- sd(e.min)
##~ sd.max <- sd(e.max)
mean.avg <- mean(e.avg)
mean.sd <- mean(e.sd)
mean.min <- mean(e.min)
mean.max <- mean(e.max)
range.avg <- diff(range(e.avg))
range.sd <- diff(range(e.sd))
range.min <- diff(range(e.min))
range.max <- diff(range(e.max))
p.avg <- abs(range.avg/mean.avg)
p.sd <- abs(range.sd/mean.sd)
p.min <- abs(range.min/mean.min)
p.max <- abs(range.max/mean.max)
##~ p.avg <- sd.avg/mean.avg
##~ p.sd <- sd.sd/mean.sd
##~ p.min <- sd.min/mean.min
##~ p.max <- sd.max/mean.max
##~ res.mean <- c(avg=mean.avg,sd=mean.sd,min=mean.min,max=mean.max)
##~ res.sd <- c(avg=sd.avg,sd=sd.sd,min=sd.min,max=sd.max)
res <- c(avg=p.avg,sd=p.sd,min=p.min,max=p.max,tol=tol)
res[is.na(res)] <- 0
if (verbose) {
# print(res.mean)
# print(res.sd)
print(res)
}
ret <- unname((res["min"]<tol & res["max"]<tol) | res["sd"]==0)
ret
}
'.cmd.display' <- function() {
do.call("display",.args2list())
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/display.R
|
'display_brick' <- 'display_homo' <- function(obj,...) {
if (is.character(obj))
obj <- if (envi_exists(obj)) read_envi(obj,...) else read_gdal(obj,...)
if (.is.ursa_stack(obj))
obj <- ursa_brick(obj)
options(ursaPngAuto=TRUE)
arglist <- list(...)
ind <- .grep("decor",names(arglist))
if (!length(ind))
arglist$decor <- TRUE
if (.is.sparse(obj))
obj <- decompress(obj)
compose_open(obj,...)
# do.call("compose_plot",c(quote(obj),arglist))
compose_plot(obj,...)
compose_close(...)
# invisible(.Last.value)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/display_brick.R
|
'display_rgb' <- function(obj,...)
{
if (is.character(obj))
obj <- if (envi_exists(obj)) read_envi(obj) else read_gdal(obj)
options(ursaPngAuto=TRUE)
arglist <- list(...)
if (.getPrm(arglist,name="bpp",default=0L)==0L)
arglist$bpp <- 24L
if (.getPrm(arglist,name="crop",default="")=="")
arglist$crop <- "crop"
margin <- .getPrm(arglist,name="margin",class=list("logical","integer")
,default=-1L)
if (is.na(useRaster <- .getPrm(arglist,name="useRaster",default=NA)))
arglist$useRaster <- FALSE
if ((length(margin)==1)&&(margin==-1L))
arglist$margin <- c(T,T,F,F)
if (.is.ursa_stack(obj))
obj <- ursa_brick(obj)
if (!is.integer(obj$value))
obj <- as.integer(round(obj))
copyright <- attr(obj,"copyright")
copyright <- ((is.character(copyright))&&(nchar(copyright)))
if (copyright) {
if (.getPrm(arglist,name="scale",default=-1)==-1)
arglist$scale <- 1
if (is.na(.getPrm(arglist,name="coast",default=NA))) {
if (!.lgrep("coast",names(arglist)))
arglist$coast <- FALSE
}
}
do.call("compose_open",c("rgb",arglist))
do.call("compose_plot",c(quote(obj),arglist))
do.call("compose_close",c(quote(obj),arglist))
# invisible(NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/display_rgb.R
|
'.display_stack' <- function(obj,oneside=FALSE
,horizontal=NA,vertical=NA
,ratio=1.5,decor=TRUE
,crop="crop",...) {
NULL
}
'display_stack' <- 'display_hetero' <- function(obj,...)
{
if (is.character(obj))
obj <- if (envi_exists(obj)) read_envi(obj) else read_gdal(obj)
isList <- .is.ursa_stack(obj)
if (isList) {
# p <- colorize(obj,...)
# p <- lapply(obj,colorize,...)
p <- lapply(obj,function(x) colorize(decompress(x),...))
}
else {
# p <- colorize(ursa_stack(obj),...)
# p <- lapply(ursa_stack(obj),colorize,...)
p <- lapply(ursa_stack(decompress(obj)),function(x) do.call("colorize",list(x,...)))
}
# cl <- .compose_design.stack(p,oneside=oneside
# ,horizontal=horizontal,vertical=vertical,ratio=ratio)
cl <- compose_design(p,...)
s1 <- colSums(cl$layout)
arglist <- list(...)
las <- if (all(s1[c(1,length(s1))]==0)) 2L else 1L
options(ursaPngAuto=TRUE)
compose_open(cl,...)
if ("las" %in% names(arglist))
compose_plot(p,trim=2L*(cl$legend>0),...)
else
compose_plot(p,las=las,trim=2L*(cl$legend>0),...) ## ,decor=decor
compose_close(...)
# invisible(0L)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/display_stack.R
|
'envi_exists' <- function(pattern=".+",path=".",all.files=FALSE,full.names=TRUE
,recursive=FALSE,ignore.case=TRUE,exact=FALSE)
{
length(envi_list(pattern=pattern,path=path,all.files=all.files
,full.names=full.names,recursive=recursive
,ignore.case=ignore.case,exact=exact))
}
'envi_copy' <- function(src,dst,overwrite=TRUE)
{
patlist <- "(\\.(hdr|gz|bz2|xz|bin|bingz|envi|envigz|img|dat))*$"
srcdir <- dirname(src)
srcname <- basename(src)
n <- nchar(dst)
if (substr(dst,n,n)=="/")
dst <- substr(dst,1,n-1)
if (missing(dst))
{
dstdir <- "."
dstname <- srcname
}
else if ((file.exists(dst))&&(file.info(dst)$isdir))
{
dstdir <- dst
dstname <- srcname
}
else
{
dstdir <- dirname(dst)
dstname <- basename(dst)
}
srcname <- paste0("^",srcname)
list1 <- .dir(path=srcdir
,pattern=paste0(srcname,patlist)
,full.names=TRUE)
if (overwrite)
{
list2 <- .dir(path=dstdir
,pattern=paste0(dstname,patlist)
,full.names=TRUE)
if (length(list2))
file.remove(list2)
}
list2 <- file.path(dstdir,.gsub(srcname,dstname,basename(list1)))
for (i in seq_along(list1))
file.copy(list1[i],list2[i],overwrite=overwrite,copy.date=TRUE)
invisible(0L)
}
'envi_remove' <- function(pattern=".+",path=".",all.files=FALSE,full.names=recursive
,recursive=FALSE,ignore.case=TRUE,verbose=FALSE)
{
list2 <- NULL
for (a in pattern)
{
list2 <- c(list2,.delete.envi.each(pattern=a,path=path
,all.files=all.files
,full.names=full.names
,recursive=recursive
,ignore.case=ignore.case
,verbose=verbose))
}
invisible(list2)
}
'.delete.envi.each' <- function(pattern=".+",path=".",all.files=FALSE
,full.names=FALSE,recursive=FALSE
,ignore.case=!FALSE,verbose=FALSE)
{
list1 <- envi_list(pattern=pattern,path=path,all.files=all.files
,full.names=full.names,recursive=recursive
,ignore.case=ignore.case)
if (verbose)
print(list1)
for (a in list1)
{
toRemove <- FALSE
for (ext in c("envi","envigz","bin","","bingz","img","dat","gz","bz2","xz"))
{
b <- gsub("\\.$","",sprintf("%s.%s",a,ext))
if (verbose)
print(data.frame(file=b,exists=file.exists(b)))
if (!file.exists(b))
next
if ((ext=="bin")&&(file.exists(sprintf("%s.idr",a))))
next
file.remove(b)
toRemove <- TRUE
}
if (!toRemove)
next
file.remove(sprintf("%s.hdr",a))
aux.xml <- .dir(path=dirname(a)
,pattern=paste0("^",basename(a),".*\\.aux\\.xml$")
,full.names=TRUE)
if (verbose)
print(aux.xml)
if (length(aux.xml))
file.remove(aux.xml)
}
list1
}
'envi_rename' <- function(src,dst,overwrite=TRUE)
{
srcdir <- dirname(src)
srcname <- basename(src)
if (missing(dst))
{
dstdir <- "."
dstname <- srcname
}
else if ((file.exists(dst))&&(file.info(dst)$isdir))
{
dstdir <- dst
dstname <- srcname
}
else
{
dstdir <- dirname(dst)
dstname <- basename(dst)
}
srcname <- paste0("^",srcname)
list1 <- .dir(path=srcdir
,pattern=paste0(srcname,"(\\.(hdr|gz|bzip2|xz|envi|envigz|bin|bingz|img|dat))*$")
,full.names=TRUE)
list2 <- file.path(dstdir,.gsub(srcname,dstname,basename(list1)))
file.rename(list1,list2)
}
'envi_list' <- function(pattern=".+",path=".",all.files=FALSE,full.names=recursive
,recursive=FALSE,ignore.case=TRUE,exact=FALSE)
{
if (length(pattern)>1)
return(do.call(c,lapply(pattern,envi_list))) ## RECURSIVE
'.noESRI' <- function(elist) {
fpath <- ifelse(full.names | length(grep("/",elist)),elist,file.path(path,elist))
a <- elist[sapply(fpath,function(f) readLines(paste0(f,".hdr"),1)=="ENVI")]
elist[sapply(fpath,function(f) readLines(paste0(f,".hdr"),1)=="ENVI")]
}
if (!nchar(pattern))
return(character())
if (T) { ## ++ 20210521
# str(list(path=path,pattern=pattern))
path <- gsub("\\\\","/",path)
if (grepl("\\\\",pattern))
if (!(grepl("(^\\^|\\$$|\\\\[dDwWsS](\\{|\\+|\\*))",pattern)))
pattern <- gsub("\\\\","/",pattern) ## failed for sia\\d{4}
}
if (.lgrep("(/|\\\\)",pattern))
{
isDir <- file.info(pattern)$isdir
if ((!is.na(isDir))&&(isDir)) {
path <- pattern
pattern <- ".+"
full.names <- TRUE
}
else {
if (dirname(pattern) %in% "/") { ## ++ 20210125
NULL # path <- "."
}
else if (file.exists(dirname(pattern))) {
path <- dirname(pattern)
pattern <- gsub(paste0(path,"(/+|\\\\)"),"",pattern)
# pattern <- basename(pattern)
recursive <- FALSE
full.names <- TRUE
}
}
# print(c(path=path,pattern=pattern))
}
if ((substr(pattern,1,1))=="+")
pattern <- paste0("\\\\",pattern)
patt1a <- patt1 <- .gsub("\\.hdr$","",pattern)
patt1 <- .gsub("(\\.)$","",patt1)
patt1a <- patt1
patt2 <- .gsub("\\.(bin|envi|img|dat|gz|bz2|xz|bingz|envigz)$","",patt1)
if (exact) {
patt1 <- paste0("^",patt1,"$")
patt2 <- paste0("^",patt2,"$")
}
# patt1 <- gsub("\\\\","/",patt1)
# patt2 <- gsub("\\\\","/",patt2)
list1 <- dir(path=path,pattern="\\.hdr$",all.files=all.files
,full.names=full.names,recursive=recursive
,ignore.case=ignore.case)
list2 <- .gsub("\\.hdr$","",list1)
if (!length(list2))
return(character())
ind <- try(.grep(patt1,basename(list2)),silent=TRUE)
if (inherits(ind,"try-error"))
ind <- integer()
if (length(ind)) {
return(.noESRI(list2[ind]))
}
ind <- try(.grep(patt2,basename(list2)))
if (inherits(ind,"try-error"))
ind <- integer()
if (length(ind))
return(.noESRI(list2[ind]))
if (.lgrep("\\.(tif|tiff|png|bmp|shp|sqlite|geojson|json|gpkg|kml|mif|fgb)$",patt2)) {
return(character()) ## if exist TIF and HDR, then HDR is not associated with TIF
}
patt2a <- .gsub("(\\..+)$","",patt2)
ind <- try(.grep(patt2a,basename(list2))) ## truncate binary file extension
if (inherits(ind,"try-error"))
ind <- integer()
if (length(ind)==1L) ## only exact matching!
return(.noESRI(list2[ind]))
ind <- .grep(patt2,basename(list2))
if ((0)&&(file.exists(patt1a))&&((file.exists(paste0(patt1a,".hdr")))||
(file.exists(.gsub("^.+(\\..+)$",".hdr",patt1a)))))
return(patt1a)
if (!exact)
return(character())
list1 <- dir(path=getOption("ursaRequisite")
,pattern="\\.hdr$",all.files=all.files
,full.names=TRUE,recursive=FALSE
,ignore.case=ignore.case)
list2 <- .gsub("\\.hdr$","",list1)
ind <- .grep(patt1,basename(list2))
if (length(ind))
return(.noESRI(list2[ind]))
# ind <- .grep(patt2,basename(list2))
# if (length(ind))
# return(list2[ind])
character()
}
'ursa_exists' <- function(fname) {
list1 <- envi_list(fname)
if (length(list1)>1) {
print(list1)
warning("Multiple datasests")
return(FALSE)
}
if (length(list1)==1)
return(TRUE)
list1 <- dir(path=dirname(fname),pattern=basename(fname),full.names=TRUE)
if (length(list1)) {
ind <- grep("\\.(tif|tiff|hfa|bin)$",basename(list1))
if (length(ind)==1)
return(TRUE)
return(FALSE)
}
return(FALSE)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/envi_files.R
|
# https://earthdata.nasa.gov/about/science-system-description/eosdis-components/global-imagery-browse-services-gibs#ed-gibs-citation
'get_earthdata' <- function(bbox=NA #,c(2000000,400000,2300000,700000)
,res=c("2km","1km","500m","250m")
,date=NA,product="",geocode=""
,expand=1.05,border=0,display=FALSE
,cache=NA,verbose=FALSE) {
productList <- c('1'="MODIS_Aqua_CorrectedReflectance_Bands721"
,'2'="MODIS_Terra_CorrectedReflectance_Bands721"
,'3'="MODIS_Aqua_CorrectedReflectance_TrueColor"
,'4'="MODIS_Terra_CorrectedReflectance_TrueColor"
,'5'="VIIRS_SNPP_CorrectedReflectance_TrueColor"
,'6'="Coastlines")
epsg3413 <- paste("+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1"
,"+x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs")
epsg3857 <- paste("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0"
,"+x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null"
,"+wktext +no_defs")
if ((length(bbox)==1)&&(is.na(bbox))) {
g0 <- session_grid()
if (.lgrep("\\+proj=merc",g0$crs)) {
ll <- with(g0,.project(cbind(c(minx,maxx),c(miny,maxy)),crs,inv=TRUE))
# bbox <- c(min(ll[,1]),min(ll[,2]),max(ll[,1]),max(ll[,2]))
bbox <- c(ll[1,1],ll[1,2],ll[2,1],ll[2,2])
# stop("A")
}
else if (.gsub("(^\\s|\\s$)","\\1",g0$crs)==.gsub("(^\\s|\\s$)","\\1",epsg3413)) {
# stop("B")
bbox <- with(g0,c(minx,miny,maxx,maxy))
}
else {
# stop("C")
bbox <- NULL
}
}
if (is.null(bbox))
return(productList)
g4 <- session_grid()
if (product %in% seq_along(productList))
product <- productList[product]
else {
pr2 <- try(match.arg(product,productList),silent=TRUE)
if (inherits(pr2,"try-error")) {
isAqua <- length(grep("aqua",product,ignore.case=TRUE))>0
isTerra <- length(grep("terra",product,ignore.case=TRUE))>0
isSuomi <- length(grep("(snpp|suomi)",product,ignore.case=TRUE))>0
is721 <- length(grep("721",product,ignore.case=TRUE))>0
isTrueColor <- length(grep("(true|color)",product,ignore.case=TRUE))>0
# print(c(aqua=isAqua,terra=isTerra,suomi=isSuomi,b721=is721,TT=isTrueColor))
if ((isAqua)&&(is721))
product <- productList[1]
else if ((isTerra)&&(is721))
product <- productList[2]
else if (isAqua) #((isAqua)&&(isTrueColor))
product <- productList[3]
else if (isTerra) #((isTerra)&&(isTrueColor))
product <- productList[4]
else if (isSuomi)
product <- productList[5]
else
product <- productList[6]
}
else
product <- pr2
}
if (is.na(date)) {
t0 <- as.integer(format(as.POSIXlt(Sys.time(),tz="UTC"),"%H"))
date <- Sys.Date()-ifelse(t0>17.5,0L,1L)
}
if (is.character(date)) {
if (.lgrep("today",date))
date <- Sys.Date()
else if (.lgrep("yesterday",date))
date <- Sys.Date()-1L
date <- as.Date(date)
}
if (is.character(bbox)) {
g0 <- attr(spatialize(bbox,geocode=geocode,expand=expand,border=border
,verbose=verbose),"grid")
xy <- with(g0,cbind(c(minx,maxx),c(miny,maxy)))
ll <- with(g0,.project(xy,crs,inv=TRUE))
# bbox <- c(min(ll[,1]),min(ll[,2]),max(ll[,1]),max(ll[,2]))
bbox <- c(ll)[c(1,3,2,4)]
if (length(bbox)!=4)
return(productList)
}
if ((is.na(cache))||(!is.logical(cache))) {
cache <- TRUE
if (date==Sys.Date()) {
t0 <- as.integer(format(as.POSIXlt(Sys.time(),tz="UTC"),"%H"))
if (t0<17.5)
cache <- FALSE
}
}
epsg <- if ((any(bbox>(+360)))||(any(bbox<(-180)))) epsg3413 else epsg3857
is3857 <- epsg==epsg3857
is3413 <- epsg==epsg3413
# print(c('3413'=is3413,'3857'=is3857))
tsize <- ifelse(is3413,512,256)
zoomList <- if (is3413) c(3:6) else c(1:9)-1
B <- ifelse(is3413,4194304,20037508.34278925)
cross180 <- FALSE
if (is3857) {
bbox <- c(.project(rbind(c(bbox[1],bbox[2]),c(bbox[3],bbox[4]))
,epsg3857))[c(1,3,2,4)]
if (bbox[1]>bbox[3]) {
bbox[3] <- bbox[3]+2*B
cross180 <- TRUE
}
}
g0 <- regrid(ursa_grid(),setbound=c(-B,-B,B,B),dim=c(tsize,tsize),proj=epsg)
if ((is.character(res))&&((length(res)==1))) {
res <- match.arg(res)
zoom <- switch(res,'2km'=3,'1km'=4,'500m'=5,'250m'=6,NA)
g1 <- regrid(g0,mul=2^(zoom+0),bbox=bbox)
}
else if ((length(res)==1)&&(res %in% zoomList)) {
zoom <- res
g1 <- regrid(g0,mul=2^(zoom),bbox=bbox)
}
else {
size <- if ((is.numeric(res))&&(res>128)) res else 480
# print(g0)
for (z in zoomList) {
g1 <- regrid(g0,mul=2^(z+1),bbox=bbox)
if ((g1$columns>size)||(g1$rows>size))
break
}
zoom <- z+1
}
g2 <- regrid(ursa_grid(),setbound=c(-B,-B,B,B),dim=c(2^zoom,2^zoom)
,proj=ifelse(is3413,epsg3413,epsg3857))
session_grid(g2)
a <- ursa_new()
cr <- coord_xy(a,x=c(g1$minx,g1$maxx-ifelse(cross180,2*B,0)),y=c(g1$maxy,g1$miny))
xy <- coord_cr(a,c=cr[1,],r=cr[2,])
if (cross180)
xy[1,2] <- xy[1,2]+2*B
cr <- cr-1
g3 <- regrid(g1,bbox=c(xy[1,1]-1*g2$resx/2,xy[2,2]-1*g2$resy/2
,xy[1,2]+1*g2$resx/2,xy[2,1]+1*g2$resy/2))
if (is3413)
zoom <- zoom-1
if (cr[1,2]<cr[1,1])
seqc <- c(cr[1,1]:(g2$columns-1),0:cr[1,2])
else
seqc <- cr[1,1]:cr[1,2]
seqr <- cr[2,1]:cr[2,2]
tile <- expand.grid(z=zoom,y=seqr,x=seqc,time=date)
tile$time[which(tile$x<tile$x[1])] <- date-1L
crind <- cr-apply(cr,1,min)
tind <- expand.grid(z=zoom,r=seq_along(seqr)-1,c=seq_along(seqc)-1)
img <- array(0,dim=c(tsize*length(seqc),tsize*length(seqr),4))
img[,,4] <- 1
a <- .getEarthdataTile(x=tile[,"x"],y=tile[,"y"],z=tile[,"z"]
,epsg=ifelse(is3413,"3413","3857")
,product=product,time=tile[,"time"]
,cache=cache,verbose=verbose)
for (i in seq(nrow(tile))) {
if (is.null(a[[i]]))
next
img[tind[i,"c"]*tsize+seq(tsize)
,tind[i,"r"]*tsize+seq(tsize),seq(dim(a[[i]])[3])] <- a[[i]]
}
b <- as.ursa(img,flip=TRUE)
# session_grid(b);display_rgb(b*255);q()
ursa(b,"grid") <- g3
b <- as.integer(regrid(b,g1,resample=0)*255)
ursa(b,"nodata") <- NA
if ((nband(b)==4)&&(global_min(b[4])==255)&&(global_max(b[4])==255))
b <- b[-4]
attr(b,"copyright") <- "Global Imagery Browse Services, NASA/GSFC/ESDIS"
cond1 <- .lgrep("\\+proj=merc\\s",g1$crs) & .lgrep("\\+proj=merc\\s",g4$crs)
cond2 <- g1$columns==g4$columns & g1$rows==g4$rows &
.is.near(g1$miny,g4$miny) & .is.near(g1$maxy,g4$maxy) &
.is.near(g1$resx,g4$resx) & .is.near(g1$resy,g4$resy) &
TRUE
# print(c(cond1=cond1,cond2=cond2))
# print(g1)
# print(g4)
if (cond1 & cond2)
ursa(b,"grid") <- g4
session_grid(b)
if (!display)
return(b)
display_brick(b,scale=1,coast=TRUE)
}
'.getEarthdataTile' <- function(x=13,y=23,z=4,epsg=c("3413","3857")
,product="MODIS_Aqua_CorrectedReflectance_Bands721"
,time=Sys.Date()-2L
,cache=TRUE,verbose=FALSE) {
if (inherits(time,c("Date","POSIXct","POSIXlt")))
time <- format(time,"%Y-%m-%d")
# product <- c("Coastlines","arctic_coastlines")[1]
isDecor <- product %in% c("Coastlines","arctic_coastline")
if (isDecor)
time <- ""
ext <- ifelse(product %in% c("Coastlines","arctic_coastline"),".png",".jpg")
epsg <- match.arg(epsg)
matrixSet <- switch(epsg,'3413'="250m",'3857'="GoogleMapsCompatible_Level9")
isPNG <- length(grep("png",ext))>0
isJPEG <- length(grep("jpg",ext))>0
if (isJPEG) {
if (!requireNamespace("jpeg",quietly=.isPackageInUse()))
stop("Suggested package 'jpeg' is missed, but is required here.")
}
src <- file.path("https://gibs.earthdata.nasa.gov/wmts",paste0("epsg",epsg)
,"best",product,"default",time,matrixSet,paste0(z,"/",y,"/",x,ext))
# dst <- paste0("tmp-",z,"-",y,"-",x,ext)
# dst <- sapply(seq_along(src),function(x) tempfile())
method <- getOption("download.file.method")
isBundle <- ((!is.null(method))&&(method=="libcurl")&&(capabilities("libcurl")))
if (isBundle) {
download.file(src,dst,mode="wb",method="libcurl",quiet=!verbose)
}
a <- vector("list",length(src))
if (!cache)
dst <- tempfile()
for (i in seq_along(a)) {
if (!isBundle) {
if (cache) {
dst <- try(.ursaCacheDownload(src[i],mode="wb",quiet=!verbose))
if (inherits(dst,"try-error")) {
if (verbose)
cat(dst)
# a[[i]] <- NULL
next
}
}
else {
res <- try(download.file(src[i],dst,mode="wb",quiet=!verbose))
if (inherits(res,"try-error")) {
# a[[i]] <- NULL
next
}
}
}
if (isPNG) {
a[[i]] <- aperm(png::readPNG(dst),c(2,1,3))
}
else if (isJPEG)
a[[i]] <- aperm(jpeg::readJPEG(dst),c(2,1,3))
}
# file.remove(dst)
a
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/get_earthdata.R
|
## http://leaflet-extras.github.io/leaflet-providers/preview/index.html
'glance' <- function(...) {
arglist <- list(...)
execute <- .getPrm(arglist,name="(execute|view|open|render)",default=!.isShiny())
# if (isTRUE(Sys.getenv("_R_CHECK_PACKAGE_NAME_")=="ursa"))
# execute <- FALSE
plotKnitr <- .isKnitr() & execute
if (!length(arglist)) {
viewer <- session_pngviewer(TRUE)
on.exit(session_pngviewer(viewer))
arglist <- .args2list()
}
if (!length(arglist)) {
return(display())
}
if (inherits(arglist[[1]],c("list","character"))) {
isWMS <- FALSE
if ((is.list(arglist[[1]]))&&(all(sapply(arglist[[1]],.is.wms)))) {
s1 <- unlist(arglist[[1]])
isWMS <- TRUE
sname <- names(s1)
}
else if (.is.wms(arglist[[1]])) {
s1 <- arglist[[1]]
isWMS <- TRUE
sname <- ""
}
if (isWMS) {
# session_grid(NULL)
s2 <- unlist(sapply(s1,.compose_wms,extend=FALSE))
compose_open(length(s2),legend=NULL,...)#,fileout="res1.png")
pb <- ursaProgressBar(min=0,max=length(s2),tail=TRUE)
# print(getOption("ursaPngScale"))
for (i in seq_along(s2)) {
arglist[[1]] <- s2[i]
do.call("panel_new",arglist[-1])
arglist$extend <- FALSE
arglist$verbose <- !.isPackageInUse()
# .panel_wms(s2[i],tile=1e5,legend=TRUE,verbose=!TRUE)
a <- try(do.call(".panel_wms",arglist))
if (inherits(a,"try-error"))
cat(as.character(a))
arglist$verbose <- FALSE
if (length(sname))
panel_annotation(sname[i],pos="bottomright")
do.call("panel_decor",arglist[-1])
setUrsaProgressBar(pb,i)
}
close(pb)
compose_close(...)
return(invisible(0L))
}
}
if (!is.character(arglist[[1]])) {
a <- do.call(".glance",arglist)
if (plotKnitr)
return(a)
return(invisible(a))
}
if (!nchar(arglist[[1]])) {
return(invisible(10L))
}
# if (.lgrep("\\.rds$",basename(arglist[[1]]))) {
# arglist[[1]] <- readRDS(arglist[[1]])
# # return(do.call(".glance",arglist))
# }
# str(arglist)
if (is.character(arglist[[1]])) {
if (.lgrep("\\.(gpkg|tab|kml|json|geojson|mif|sqlite|fgb|shp|osm)(\\.(zip|gz|bz2))*$"
,arglist[[1]])) {
ret <- do.call(".glance",arglist)
if (plotKnitr)
return(ret)
return(invisible(ret))
}
else if (envi_exists(arglist[[1]],exact=TRUE)) {
return(do.call("display",arglist))
}
else if (.lgrep("\\.(tif|tiff|img|png|bmp|dat|grb)$",arglist[[1]])) {
return(do.call("display",arglist))
}
else {
if ((TRUE)&& #(!.isPackageInUse())&&
(.lgrep("\\.(nc|hdf)$",basename(arglist[[1]])))) { ## dev
# obj <- .open_nc(arglist[[1]])
obj <- .read_nc(arglist[[1]],".+")
if (!inherits(obj,"data.frame")) {
obj <- obj[sapply(obj,is.ursa)]
if (length(arglist)==1)
return(display(obj))
return(do.call("display",list(obj,arglist[-1])))
}
else {
indX <- .grep("^(lon|x$|west|east)",colnames(obj))
indY <- .grep("^(lat|y$|south|north)",colnames(obj))
if (!length(indX))
indX <- 1L
if (!length(indY))
indY <- 2L
colnames(obj)[c(indX,indY)] <- c("x","y")
}
stop("Development has been stopped")
##~ p4s <- attr(obj,"crs")
##~ if (isSF) {
##~ if (!is.null(p4s))
##~ obj <- sf::st_as_sf(obj,coords=c("x","y"),crs=attr(obj,"crs"))
##~ else
##~ obj <- sf::st_as_sf(obj,coords=c("x","y"))
##~ }
##~ if (isSP) {
##~ sp::coordinates(obj) <- ~x+y
##~ if (!is.null(p4s))
##~ sp::proj4string(obj) <- sp::CRS(p4s)
##~ }
}
if (.lgrep("\\.rds$",basename(arglist[[1]]))) {
obj <- readRDS(arglist[[1]])
# print(class(obj))
# print(inherits(obj,"Spatial"))
if (.isSP(obj)) {
# print(isS4(obj))
# print(loadedNamespaces())
# requireNamespace("methods")
arglist[[1]] <- quote(obj) ## 'GADM' distributes 'rds'
arglist$engine <- "sp"
return(do.call(".glance",arglist))
}
if (inherits(obj,"may be GDAL???")) { ## not good idea
arglist[[1]] <- quote(obj)
return(do.call("display",arglist))
}
}
b <- if (file.exists(arglist[[1]])) open_gdal(arglist[[1]]) else NULL
if (!is.null(b)) {
close(b)
do.call("display",arglist)
return(invisible(2L))
}
# else if (requireNamespace("sf",quietly=.isPackageInUse())) {
# do.call(".glance",arglist)
# }
else {
# message("Cannot complete without suggested package 'sf'.")
ret <- do.call(".glance",arglist)
if (plotKnitr)
return(ret)
return(invisible(ret))
}
}
}
invisible(0L)
}
'.glance' <- function(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,...) {
arglist <- list(...)
a <- as.list(match.call()) ## try mget(names(match.call())[-1])
# feature <- "geometry"
if (TRUE) {
geocodeList <- eval(as.list(args(.geocode))$service)
if (!nchar(geocode))
geocode <- geocodeList
else
for (i in seq_along(geocode))
geocode[i] <- match.arg(geocode[i],geocodeList)
}
else
geocode <- match.arg(geocode)
projClass <- c("longlat","stere","laea","merc")
projPatt <- paste0("(",paste(projClass,collapse="|"),")")
staticMap <- c("openstreetmap","sputnikmap","google")
tileClass <- c(staticMap,.tileService())
tilePatt <- paste0("(",paste0(unique(c(staticMap,tileClass)),collapse="|"),")")
basemap.order <- match.arg(basemap.order)
after <- basemap.order %in% "after"
before <- basemap.order %in% "before"
feature <- match.arg(feature)
engine <- match.arg(engine)
# area <- match.arg(area)
# print(c(dsn=class(dsn)))
# obj <- spatialize(dsn)
if (missing(dsn)) {
dsn <- if (style!="auto") .geomap(style=style) else .geomap()
return(display(dsn,...)) ## ++20180617
}
toUnloadMethods <- !("methods" %in% .loaded())
S4 <- isS4(dsn)
if (S4) {
.require("methods",quietly=.isPackageInUse())
# requireNamespace("methods",quietly=.isPackageInUse())
}
obj <- spatialize(dsn=dsn,engine=engine,layer=layer,field=field,geocode=geocode
,place=place,area=area,grid=grid,size=size
# ,expand=expand,border=border
,expand=expand,border=0
,lat0=lat0,lon0=lon0
,resetProj=resetProj,resetGrid=resetGrid
,style=style#,zoom=NA
,verbose=verbose)
if (inherits(obj,"NULL"))
return(invisible(NULL))
isSF <- inherits(obj,c("sfc","sf"))
isSP <- !isSF
g0 <- attr(obj,"grid")
if (is.null(g0))
g0 <- session_grid()
# g1 <- getOption("ursaSessionGrid")
# if (identical(g0,g1))
# border <- 0
if ((FALSE)&&(expand!=1)) {
bbox <- with(g0,c(minx,miny,maxx,maxy))
.sc <- (expand-1)*sqrt(diff(bbox[c(1,3)])*diff(bbox[c(2,4)]))
bbox <- bbox+c(-1,-1,1,1)*.sc
g0 <- regrid(g0,bbox=bbox)
print(g0)
}
toUnloadMethods <- if (S4) toUnloadMethods else attr(obj,"toUnloadMethods")
if (is.null(toUnloadMethods))
toUnloadMethods <- FALSE
# dname <- attr(obj,"colnames")
dname <- spatial_fields(obj)
style <- attr(obj,"style")
geocodeStatus <- attr(obj,"geocodeStatus")
if (is.null(geocodeStatus))
geocodeStatus <- FALSE
# obj <- sp::SpatialLinesDataFrame(obj,data=data.frame(uid="test it")) ## for debug
noAttr <- geocodeStatus |
((isSF)&&(inherits(obj,"sfc"))) |
((isSP)&&(!inherits(obj,paste0("Spatial",c("Points","Lines","Polygons")
,"DataFrame"))))
toColor <- ((is.numeric(dsn))||(noAttr))||(TRUE)
art <- style
if ((toColor)&&(!.lgrep("\\s(colo(u)*r|gr[ae]y(scale)*)",style))&&
(length(style)==1))
style <- paste(style,"color")
else if ((!toColor)&&(!.lgrep("\\s(colo(u)*r|gr[ae]y(scale)*)",style)&&
(length(style)==1)))
style <- paste(style,"greyscale")
if (!.lgrep(projPatt,style))
proj <- "auto"
else
proj <- .gsub2(projPatt,"\\1",style)
if (FALSE) { ## dev
s1 <- .tileService()
s2 <- strsplit(style,split="\\s+")
s <- expand.grid(s1,s2)
}
canUrl <- length(unlist(regmatches(style,gregexpr("\\{[xyz]\\}",style))))==3
if (!canUrl) {
sascache <- gsub("\\s(color|grey|gray)$","",style)
if (!length(ind <- which(dir.exists(sascache))))
sascache <- file.path(getOption("SAS_Planet_cache"),sascache)
if (length(ind <- which(dir.exists(sascache)))>0) {
list1 <- dir(path=sascache[ind],pattern="\\.sqlitedb$",recursive=TRUE)
canUrl <- length(list1)>0
if (canUrl)
style <- basename(sascache)
}
}
isUrl <- .lgrep("http(s)*://",style) | canUrl
if (isUrl) {
ind <- .grep("http(s)*://",style)
style[ind] <- unlist(strsplit(style[ind],split="\\s+"))[1]
}
if (!is.null(style))
providers <- .tileService(providers=TRUE)
else
providers <- ""
if (!.lgrep(tilePatt,style)) {
if (isUrl) {
# art <- style
proj <- "merc"
}
else if ((length(art))&&(art %in% providers)) {
# art <- style
proj <- "merc"
}
else
art <- "none"
}
else {
art <- .gsub2(tilePatt,"\\1",style)
proj <- "merc"
}
isWeb <- .lgrep(tilePatt,art)>0 | art %in% providers | isUrl
if (verbose)
str(list(style=style,art=art,proj=proj,isUrl=isUrl,isWeb=isWeb))
# proj <- match.arg(proj)
# attr(obj,"grid") <- NULL
# attr(obj,"toUnloadMethods") <- NULL
# attr(obj,"dname") <- NULL
#attr(obj,"geocodeStatus") <- NULL
basemapRetina <- FALSE
if (isWeb) {
bbox <- with(g0,c(minx,miny,maxx,maxy))
if (grepl("\\+proj=longlat",g0$crs))
lim <- bbox
else
lim <- c(.project(matrix(bbox,ncol=2,byrow=TRUE),g0$crs
,inv=TRUE,verbose=verbose))[c(1,3,2,4)]
ostyle <- unlist(strsplit(style,split="\\s+"))
isStatic <- ostyle[1] %in% staticMap
ustyle <- ""#ostyle[1]
if (isStatic)
nextStyle <- .grep(ostyle[1],staticMap
,invert=TRUE,value=TRUE)
else
nextStyle <- .grep(ostyle[1],c("CartoDB","mapnik","opentopomap")
,invert=TRUE,value=TRUE)[seq(3)]
nsize <- length(nextStyle)+1
cache <- .getPrm(arglist,"cache",class=c("logical","character"),default=TRUE)
for (i in seq(nsize)) {
opE <- options(show.error.messages=TRUE)
basemap <- try(.geomap(lim,style=style,size=size,zoom=zoom
,border=border,cache=cache,verbose=verbose))
options(opE)
if (!inherits(basemap,"try-error"))
break
# message(geterrmessage())
if (i==nsize)
break
.style <- style
style <- paste(nextStyle[1],ostyle[-1],collapse=" ")
nextStyle <- nextStyle[-1]
message(paste("failed to get map; change service:"
,.sQuote(.style),"->",.sQuote(style)))
}
# print(basemap)
# str(basemap)
if (inherits(basemap,"try-error")) {
message(paste("failed to get map; cancel"))
print(lim)
basemap <- NULL
g0 <- session_grid()
}
else {
basemapRetina <- isTRUE(attr(basemap,"retina"))
g0 <- ursa(basemap,"grid") ## 0605 TODO
}
if (is.null(g0)) {
g0 <- session_grid()
}
}
else {
basemap <- NULL
zrel <- zabs <- NA
if (isTRUE(is.numeric(zoom))) { ## absolute
zabs <- zoom
}
else if (isTRUE(is.character(zoom))) { ## relative
if (nchar(gsub("\\d+","",zoom))==0)
zabs <- as.integer(gsub("\\D","",zoom))
else {
zrel <- gregexpr("^(\\+)+$",zoom)[[1]]
if ((length(zrel)==1)&&(zrel==1)) {
# str(zrel)
zrel <- 2^(-attr(zrel,"match.length"))
}
else {
zrel <- gregexpr("^(\\-)+$",zoom)[[1]]
if ((length(zrel)==1)&&(zrel==1)) {
# str(zrel)
zrel <- 2^(+attr(zrel,"match.length"))
}
else if (.lgrep("^(\\+|\\-)\\d$",zoom)) {
zrel <- 2^(-eval(parse(text=paste0("",zoom))))
}
else
zrel <- NA
}
}
}
# print(c(zabs=zabs,zrel=zrel))
if ((!is.na(zabs))||(!is.na(zrel))) {
ps <- ursa(g0,"cellsize")
if (!is.na(zabs)) {
# print(g0)
z1 <- 2*6378137/(2^(seq(21)+8))
z2 <- 2^c(24,25)[1]/(2^(seq(21)+8))
##~ print(format(z1,sci=FALSE),quote=FALSE)
##~ print(format(z2,sci=FALSE),quote=FALSE)
res <- if (!is.na(.is.near(ps,z1))) z1[round(zabs)] else z2[zabs]
}
else if (!is.na(zrel))
res <- ps*zrel # ps*2^zrel
if (FALSE) {
# g0 <- regrid(g0,mul=1/m,expand=m)
g0 <- regrid(g0,res=res,expand=res/ps)
}
else {
m <- res/ps
bbox <- with(g0,c(minx,miny,maxx,maxy))
m2 <- if (m<1) 1 else with(g0,sqrt((maxx-minx)*(maxy-miny)))/2
# print(c(m=m,m2=m2,ps=ps,res=res,expand=m*m2))
# g0 <- regrid(g0,mul=1/m,bbox=bbox+0*c(-1,-1,1,1)*m*m2)
g0 <- regrid(g0,res=res,bbox=bbox+c(-1,-1,1,1)*m*m2)
}
}
}
if ((is.null(basemap))&&(border>0)) {
g0 <- regrid(g0,border=border)
}
attr(obj,"grid") <- g0
session_grid(g0)
# str(g0)
# xy <- with(g0,.project(rbind(c(minx,miny),c(maxx,maxy)),crs,inv=TRUE))
# display(blank="white",col="black");q()
if (verbose)
print(c(sf=isSF,sp=isSP))
if (isSF) {
geoType <- unique(as.character(sf::st_geometry_type(obj)))
obj_geom <- sf::st_geometry(obj)
# bbox <- c(sf::st_bbox(obj))
# crs <- sf::st_crs(obj)$proj4string
}
if (isSP) {
geoType <- switch(class(sp::geometry(obj))
,SpatialPolygons="POLYGON"
,SpatialPoints="POINT"
,SpatialLines="LINE")
obj_geom <- switch(geoType,POLYGON=methods::slot(sp::geometry(obj),"polygons")
,LINE=methods::slot(sp::geometry(obj),"lines")
,POINT=sp::geometry(obj))
# bbox <- c(sp::bbox(obj))
# names(bbox) <- c("xmin","ymin","xmax","ymax")
# crs <- sp::proj4string(obj)
}
toCoast <- !isWeb | isWeb & .getPrm(list(...),name="coast",default=FALSE)
if ((FALSE)&&(.lgrep("POLYGON",geoType))&&(isSF)) {
valid <- .try(ov <- sf::st_covers(obj_geom,sparse=!FALSE))
if (!valid)
isOverlap <- FALSE
else
isOverlap <- length(which(sapply(ov,function(x) length(x)>1)))>0
}
else
isOverlap <- FALSE
if (feature=="auto")
feature <- ifelse(isOverlap,"geometry","field")
if ((!toUnloadMethods)&&(isSP)&&(!"package:methods" %in% search())) {
# I've read "R-exts 1.1.3.1",
# but sp::plot() is failed for 'requireNamespace("methods")
# .require("methods")
opW <- options(warn=-1)
warning("Package 'methods' is required for S4 object coercion.")
options(opW)
toUnloadMethods <- TRUE
}
if ((gdal_rasterize)&&(nchar(Sys.which("gdal_rasterize")))) {
res <- .rasterize(obj,feature=feature,verbose=verbose)
}
##~ print(session_grid())
if (isSF)
geoType <- unique(as.character(sf::st_geometry_type(obj)))
if (isSP) {
# geoType <- geoType ## no change
}
# dname <- names(attr(obj,"relation_to_geometry"))
# ct <- colorize(obj[,dname[4],drop=TRUE][,1],alpha=1)
# print(ct)
# print(unname(ct$colortable[ct$ind]))
# require(methods)
if (geocodeStatus) { ## move to 'visualization' block
if ("auto" %in% style) {
if (geocode=="google")
style <- "google static"
else if (geocode=="nominatim")
style <- "openstreetmap static"
else
style <- "openstreetmap static"
}
if ((is_spatial_lines(obj))&&("bounding" %in% area)) {
basemap.alpha <- 1
alpha <- 0
}
}
if ((isWeb)&&(is.na(basemap.alpha)))
basemap.alpha <- ifelse(before,0.5,0.35)
if (is.na(alpha))
alpha <- ifelse(isWeb,ifelse(before,0.75,1),1)
if (feature=="field") {
noData <- length(dname)==0
ct <- vector("list",length(dname))
cpg <- NULL#"1251"
for (i in seq_along(dname)) {
# print(i)
# print(dname[i])
# str(obj[,dname[i]][,1])
if (isSF) {
# val <- obj[,dname[i],drop=TRUE][,1] ## sf>=0.4
val <- obj[,dname[i],drop=TRUE]#[,1] ## sf>=0.5
}
if (isSP)
val <- methods::slot(obj,"data")[,dname[i],drop=TRUE]
if ((is.character(cpg))&&(is.character(val)))
val <- iconv(val,"UTF-8","1251")
# print(all(is.na(val)))
# print(obj[,dname[i],drop=TRUE][,1])
if (all(is.na(val)))
ct[[i]] <- colorize("(all values are NA)")
else
ct[[i]] <- colorize(val,alpha=alpha,...)
# print(names(ct[[i]]$colortable),quote=FALSE)
# print(ct[[i]])
# print("-----------------------------------------")
}
if (noData)
ct <- list(colorize(seq(spatial_count(obj)),alpha=0.5))
hasField <- any(sapply(ct,function(x) any(!is.na(x$index))))
if ((!hasField)&&(alpha==1))
alpha <- 0.5
if (!gdal_rasterize) {
if (length(dname))
res <- lapply(rep(NA,length(ct)),ursa_new)
else
res <- list(geometry=ursa_new())
}
if (isWeb) {
# retina1 <- getOption("ursaRetina")
retina2 <- .getPrm(arglist,"retina",default=NA_integer_)
retina3 <- 1L+as.integer(basemapRetina)
# print(c(retina1=retina1,retina2=retina2,retina3=retina2))
retina <- ifelse(is.na(retina2),retina3,retina2)
compose_open(res,scale=1,retina=retina,...)
}
else
compose_open(res,...)
gline <- compose_graticule(...)
if (toCoast)
cline <- compose_coastline(...)
pb <- ursaProgressBar(min=0,max=length(res),silent=silent,tail=TRUE)
for (i in seq_along(res)) {
if (isWeb)
panel_new(fill="transparent",...)
else
panel_new(...) #fill=ifelse(isWeb,"transparent","chessboard"))
if (before) {
panel_plot(basemap,alpha=basemap.alpha)
if (toCoast)
panel_coastline(cline)
}
# if ((!length(ct))||(all(is.na(ct[[i]]$index)))) {
if ((!length(ct))||(!hasField)) {
if (isSF) {
panel_plot(obj_geom,col=rgb(0,0,0,alpha))
}
if (isSP) {
panel_plot(obj,col=rgb(0,0,0,alpha))#,add=TRUE)
}
}
else if (gdal_rasterize){
ct[[i]] <- panel_raster(colorize(res[[i]]),alpha=alpha)
# ct[[i]] <- panel_raster(res[[i]],alpha=alpha,verbose=TRUE)
}
else {
# col <- unname(ct[[i]]$colortable[ct[[i]]$ind])
col <- ct[[i]]$colortable[ct[[i]]$ind]
ind <- which(is.na(col))
bg.line <- rep("#0000007F",length(col))
bg.point <- rep("#000000FF",length(col))
bg.polygon <- rep("#000000FF",length(col))
if (length(ind)) {
col[ind] <- "#FFFFFF00"
bg.line[ind] <- "#0000000F"
bg.point[ind] <- "#0000002F"
bg.polygon[ind] <- "#0000002F"
}
if (.lgrep("polygon",geoType)) {
if ((T)&&(spatial_count(obj)>1000)&&(sd(spatial_area(obj))<0.05))
lwd <- 1e-6
else
lwd <- 0.1
if (length(ind <- .grep("plot\\.lwd",names(arglist))))
lwd <- arglist[[ind]]
if (lwd==0)
lwd <- 1e-6
# .elapsedTime("Z")
# panel_plot(obj,col=col,border=bg.polygon,lwd=lwd)
# str(col)
if (FALSE) {
.elapsedTime("P1")
panel_plot(obj,col=col,border=bg.polygon,lwd=lwd,lty="blank")
.elapsedTime("P2")
panel_plot(obj,col="transparent",border=bg.polygon,lwd=lwd)
.elapsedTime("P3")
}
else {
panel_plot(obj,col=col,border=bg.polygon,lwd=lwd)
}
}
if (.lgrep("point",geoType)) {
lwd <- 0.25
if (length(ind <- .grep("plot\\.lwd",names(arglist))))
lwd <- arglist[[ind]]
cex <- 1.2
if (length(ind <- .grep("plot\\.cex",names(arglist))))
cex <- arglist[[ind]]
pch <- 21
if (length(ind <- .grep("plot\\.pch",names(arglist))))
cex <- arglist[[ind]]
panel_plot(obj,col=bg.point,bg=col,pch=pch,lwd=lwd,cex=cex)
}
if (.lgrep("line",geoType)) {
lwd <- c(3,2)
if (length(ind <- .grep("plot\\.lwd",names(arglist)))) {
lwd <- rep(arglist[[ind]],length=2)
}
panel_plot(obj,lwd=lwd[1],col=bg.line)
panel_plot(obj,lwd=lwd[2],col=col)
}
}
if (after) {
panel_plot(basemap,alpha=basemap.alpha)
if (toCoast)
panel_coastline(cline)
}
if ((geocodeStatus)||(!length(ct)))
panel_graticule(gline,margin=c(T,T,F,F))
else
panel_graticule(gline)
if (proj %in% c("merc")) {
if ((g0$miny<0)&&(g0$maxy>0)) {
if ((-g0$miny)>(g0$maxy))
y <- c(g0$miny,0)
else
y <- c(0,g0$maxy)
}
else
y <- c(g0$miny,g0$maxy)
sc <- 1/cos(.project(cbind((g0$minx+g0$maxx)/2,y)
,g0$crs,inv=TRUE)[,2]*pi/180)
# x <- 0#ifelse(((isWeb)&&(isStatic)&&(isGoogle)),0.5,0)
# print(art)
x <- ifelse(any(art %in% "google"),0.5,0)
if (max(sc)/min(sc)>1.2) {
y <- (y-g0$miny)/(g0$maxy-g0$miny)
panel_scalebar(pos=c(x,min(y)),...)
panel_scalebar(pos=c(x,max(y)),...)
}
else { # if (isWeb)
panel_scalebar(pos=c(x[1],0),...)
}
# else
# panel_scalebar(pos="bottomleft",...)
}
else
panel_scalebar(pos="bottomleft",...)
setUrsaProgressBar(pb)
}
close(pb)
if ((length(ct))&&(!noData)) {
if (!gdal_rasterize) {
ct <- lapply(ct,function(x) {
y <- ursa(x,"colortable") ## y <- x$colortable
if ((TRUE)&&(isWeb)&&(after)) {
alpha2 <- 0.65
y[] <- paste0(substr(y,1,7),format(as.hexmode(round(alpha2*255))
,width=2,upper.case=TRUE))
}
y
})
}
names(ct) <- dname
if (TRUE) {
if (!.lgrep("las",names(arglist)))
arglist$las <- 2
if (!.lgrep("trim",names(arglist)))
arglist$trim <- 2L
arglist <- c(ct,arglist)
do.call("compose_legend",arglist)
}
else
compose_legend(ct,las=2,trim=2L)
}
ret <- compose_close(...) #res)
}
else if (feature=="geometry") {
# print(geoType)
if (isSF)
n <- length(obj_geom)
if (isSP)
n <- length(obj_geom)
if (FALSE) {
if (isSF) {
# da <- obj[,dname,drop=TRUE][,1] ## wrong
da <- obj[,dname,drop=TRUE]#[,dname,drop=TRUE]
names(da) <- dname
}
if (isSP)
da <- methods::slot(obj,"data")[,dname,drop=FALSE]
}
else
da <- spatial_data(obj)
if ((is.data.frame(da))&&(!ncol(da)))
da <- NULL
if (!is.null(da)) {
da <- rbind(format(da),paste0(names(da),":"))
# print(da)
# print(format(da))
# e <- format(t(da),justify="right")
e <- .gsub("^\\s+","",t(da))
# e1 <- paste(apply(e[,c(n+1,1)],1,paste,collapse=" "),collapse="\n")
# print(e)
# message(e1)
# q()
}
if (!gdal_rasterize)
res <- ursa_new(nband=n)
ct <- lapply(seq(n),function(i) colorize(0L))
if (isWeb)
compose_open(res,scale=1,legend=NULL,...)
else
compose_open(res,legend=NULL,...)
gline <- compose_graticule(...)
if (toCoast)
cline <- compose_coastline(...)
pb <- ursaProgressBar(min=0,max=length(res))
# geoType <- "skip"
for (i in seq_along(res)) {
if (isWeb)
panel_new(fill="transparent",...)
else
panel_new(...)
if (before) {
panel_plot(basemap,alpha=basemap.alpha)
}
if (!gdal_rasterize) {
# panel_plot(obj_geom[[i]])
if (!isSP) {
if (.lgrep("polygon",geoType)) {
panel_plot(obj_geom[[i]]
,col=unname(ct[[i]]$colortable[ct[[i]]$ind]),lwd=0.1)
}
if (.lgrep("point",geoType)) {
panel_plot(obj_geom[[i]]
,col="black",bg=unname(ct[[i]]$colortable[ct[[i]]$ind])
,pch=21,lwd=0.25,cex=1)
}
if (.lgrep("line",geoType)) {
panel_plot(obj_geom[[i]],lwd=3,col="#0000007F")
panel_plot(obj_geom[[i]],lwd=2
,col=unname(ct[[i]]$colortable[ct[[i]]$ind]))
}
}
else {
if (.lgrep("polygon",geoType)) {
panel_plot(obj[i,],col=unname(ct[[i]]$colortable[ct[[i]]$ind])
,lwd=0.1)#,add=TRUE)
}
if (.lgrep("point",geoType)) {
panel_plot(obj[i,]
,col="black",bg=unname(ct[[i]]$colortable[ct[[i]]$ind])
,pch=21,lwd=0.25,cex=1)#,add=TRUE)
}
if (.lgrep("line",geoType)) {
panel_plot(obj[i,],lwd=3,col="#0000007F",add=TRUE)
panel_plot(obj[i,],lwd=2
,col=unname(ct[[i]]$colortable[ct[[i]]$ind]))#,add=TRUE)
}
}
}
else
panel_raster(res[i])
if (after) {
panel_plot(basemap,alpha=basemap.alpha)
}
if (toCoast)
panel_coastline(cline)
panel_graticule(gline)
panel_scalebar(pos=ifelse(isWeb,"bottomleft","bottomleft"),...)
if (!is.null(da)) {
e1 <- paste(apply(e[,c(n+1,i),drop=FALSE],1,paste,collapse=" ")
,collapse="\n")
panel_annotation(text=e1,adj=0,...) # pos="topleft")
}
setUrsaProgressBar(pb)
}
close(pb)
ret <- compose_close(...)
# str(n)
}
if ((toUnloadMethods)&&("package:methods" %in% search())) {
if (!(any(c("package:sp","zzzzzzzzzz") %in% search())))
detach("package:methods",unload=FALSE)
# but namespace "methods" is not unloaded, because namespace "sp" is loaded
# 'as' is not found now
}
if (.isKnitr()) {
return(invisible(ret))
if (proposed <- FALSE) {
render <- .getPrm(arglist,name="(open|render|execute|view)",default=TRUE)
print(c(render=render))
if (render)
return(ret)
else
return(invisible(ret))
}
}
invisible(ret)
}
'.cmd.glance' <- function() {
a <- .args2list()
do.call(".glance",a)
NULL
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/glance.R
|
'value_xy' <- function(obj,...) .getValue(obj,.getIndex(obj,...))
'value_ll' <- function(obj,...) {
if (!is.ursa(obj))
return(NULL)
arglist <- list(...)
lon <- .getPrm(arglist,name="^lon",default=NA_real_)
lat <- .getPrm(arglist,name="^lat",default=NA_real_)
stopifnot(length(lon)==length(lat))
xy <- .project(cbind(lon,lat),ursa_proj(obj),inv=FALSE)
if (is.null(dim(xy)))
return(NULL)
.getValue(obj,.getIndex(obj,xy[,1],xy[,2]))
}
'value_cr' <- function(obj,...) {
arglist <- list(...)
n <- length(arglist)
if (!n)
return(NULL)
if (n==1)
ind <- arglist[[1]]
else {
if (is.ursa(obj))
nc <- obj$grid$columns
else if (is.ursa(obj,"grid"))
nc <- obj$columns
else
nc <- session_grid()$columns
lc <- .getPrm(arglist,name="^c",default=NA_real_)
lr <- .getPrm(arglist,name="^r",default=NA_real_)
ind <- (lr-1L)*nc+lc
}
.getValue(obj=obj,ind=ind)
}
'coord_xy' <- function(obj,...)
{
arglist <- list(...)
n <- length(arglist)
if (!n)
return(NULL)
if (n==1)
ind <- arglist[[1]]
else {
x <- .getPrm(arglist,name="^x",default=NA_real_)
y <- .getPrm(arglist,name="^y",default=NA_real_)
ind <- .getIndex(obj,x,y)
}
if (is.ursa(obj))
n <- obj$grid$columns
else if (is.ursa(obj,"grid"))
n <- obj$columns
else
n <- session_grid()$columns
res <- matrix(NA,nrow=2,ncol=length(ind)
,dimnames=list(c("c","r"),ind))
if ((!missing(ind))&&(length(ind)>0))
{
res["r",] <- (ind-1L)%/%n+1L
res["c",] <- (ind-1L)%%n+1L
}
res
}
'coord_cr' <- function(obj,...)
{
# if (!is.ursa(obj))
# return(NULL)
arglist <- list(...)
n <- length(arglist)
if (!n)
return(NULL)
# nc <- obj$grid$columns
if (is.ursa(obj))
nc <- obj$grid$columns
else if (is.ursa(obj,"grid"))
nc <- obj$columns
else
nc <- session_grid()$columns
if (n==1) {
ind <- arglist[[1]]
row <- (ind-1L)%/%nc+1L
col <- (ind-1L)%%nc+1L
}
else {
col <- .getPrm(arglist,name="^c",default=NA_integer_)
row <- .getPrm(arglist,name="^r",default=NA_integer_)
ind <- (row-1L)*nc+col
}
if (!is.na(obj$con$posR[1]))
row <- obj$con$posR[row]
if (!is.na(obj$con$posC[1]))
col <- obj$con$posC[col]
res <- matrix(NA,nrow=2,ncol=length(ind)
,dimnames=list(c("x","y"),ind))
res["x",] <- with(ursa_grid(obj),minx+(col-0.5)*resx)
res["y",] <- with(ursa_grid(obj),miny+(rows-row+0.5)*resy)
res
}
'.getValue' <- function(obj,ind,col,row)
{
if (!is.ursa(obj))
return(NULL)
isCT <- .is.colortable(obj)
cl <- ursa(obj,"class")
isCT <- isCT & length(cl)
n <- obj$grid$columns
if ((!missing(ind))&&(length(ind)!=-11L))
{
row <- (ind-1L)%/%n+1L
col <- (ind-1L)%%n+1L
}
else {
if (length(col)!=length(row))
return(NULL)
ind <- n*(row-1L)+col
}
# str(obj[row,])
if ((FALSE)&&(length(obj$value))&&(is.na(obj$value)))
{
print(str(obj))
print(c(ind=ind,c=col,r=row))
}
nc <- length(col)
res <- matrix(NA,ncol=nc,nrow=nband(obj),dimnames=list(bandname(obj),ind))
for (i in seq(nc)) {
val <- obj[,row[i]]$value[col[i],]
if (isCT)
res[,i] <- cl[val+1L]
else
res[,i] <- val
}
# obj$value[ind,] ## incorrect if use "open_envi" construction
# if (.is.colortable(obj)) {
# res[] <- res[][ursa(res,"value")]
# }
res
}
'.getIndex' <- function(obj,x,y)
{
isRaster <- is.ursa(obj)
isGrid <- is.ursa(obj,"grid")
if (!isRaster & !isGrid)
return(NULL)
if (isRaster)
grid <- ursa(obj,"grid")
else
grid <- obj
# print(c(raster=isRaster,grid=isGrid))
if (missing(y))
{
if (length(x)==1)
return(x)
else if (length(x)==2)
{
y <- x[2]
x <- x[1]
}
else if (ncol(x)==2)
{
y <- x[,2]
x <- x[,1]
}
else
stop("specify 'y'")
}
if (TRUE) {
columns <- grid$columns
rows <- grid$rows
}
else if ((isRaster)&&(!is.na(obj$con$samples))&&(!is.na(obj$con$lines)))
{
columns <- obj$con$samples
rows <- obj$con$lines
}
else
{
columns <- grid$columns
rows <- grid$rows
}
nx <- length(x)
ny <- length(y)
if (nx!=-11)
{
x2 <- with(grid,(seq(minx,maxx,resx)-0.5*resx)[-1])
whichx <- numeric(nx)
for (i in seq(nx))
whichx[i] <- which.min(abs(x2-x[i]))
}
else
stop("TODO#1-X")
if (ny!=-11)
{
y2 <- with(grid,(seq(miny,maxy,resy)-0.5*resy)[-1])
whichy <- numeric(ny)
for (i in seq(ny))
whichy[i] <- rows-which.min(abs(y2-y[i]))+1
}
else
stop("TODO#1-Y")
ind <- as.integer((whichy-1)*columns+(whichx-1)+1)
ind
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/identify.R
|
'ursa_nodata' <- function(obj) .syn('ignorevalue',0,obj)
'ursa_nodata<-' <- function(obj,value) .syn('ignorevalue<-',0,obj,value)
'ignorevalue' <- function(obj)
{
if (!is.ursa(obj))
return(NULL)
if (!.is.con(obj$con))
return(NA)
obj$con$nodata
}
'ignorevalue<-' <- function(obj,value)
{
if (!is.ursa(obj))
return(NULL)
obj$con$nodata <- value
if (TRUE)
{
if (!is.null(dim(obj$value)))
obj$value[obj$value==value] <- NA
}
obj
}
'.make.nodata' <- function(datatype)
{
d <- as.integer(datatype)
res <- if (FALSE) 0L
else if (d==1L) 255L
else if (d==2L) -32768L
else if (d==3L) -999999L
else if (d==4L) -9999.9
else if (d==12L) 32767L
else if (d==11L) -128L
else -999999.9
res
}
'.optimal.nodata' <- function(x) {
if (is.data.frame(x))
x <- as.matrix(x)
if (is.ursa(x))
x <- x$value
x <- as.numeric(na.omit(c(x)))
if (!length(x))
return(NA_integer_)
a <- range(x)
b <- max(abs(a))
res <- -b+1
s <- ifelse(all(a>=0),1L,-1)
if (b<90)
res <- 99L*s
else if (b<900)
res <- 999L*s
else if (b<9000)
res <- 9999L*s
else if (b<90000)
res <- 99999L*s
storage.mode(res) <- storage.mode(x)
if ((FALSE)||(.is.integer(x))) { ## forcing to integer
if (all(a>=0 & a<=100))
res <- 121L
else if (all(a>=0 & a<=250))
res <- 255L
else if (all(a>=0 & a<=30000))
res <- 32767L
else if (all(abs(a<=30000)))
res <- -32768L
else if (all(abs(a<=125)))
res <- -128L
}
res
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/ignorevalue.R
|
'legend_align' <- function(obj){
# c(unlist(sapply(obj,function(x){names(x$colortable)})))
c(unlist(sapply(obj,function(x) names(ursa_colortable(x)))))
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/legend_align.R
|
'legend_colorbar' <- function(...) {
if (.skipPlot(FALSE))
return(NULL)
# if (!getOption("ursaPngLegend"))
if (!getOption("ursaPngLayout")$legend)
return(invisible(10L))
arglist <- list(...)
kwd <- "colorbar"
colorbar <- .getPrm(arglist,class="logical",name=paste0("^",kwd,"$")
,default=TRUE)
if (!is.logical(colorbar))
colorbar <- TRUE
if (!colorbar)
return(NULL)
obj <- .getPrm(arglist,name="",default=NULL
,class=list(c("list","ursaRaster"),"ursaRaster"
,c("list","ursaColorTable"),"ursaColorTable"
# ,c("list","ursaLegend"),"ursaLegend"
)
# ,verbose=TRUE
)
if (is.null(obj)) {
obj <- ursa_colortable(arglist[[1]])
}
if (is.null(obj))
return(invisible(NULL))
if (!.is.colortable(obj)) {
ind <- which(sapply(obj,.is.colortable))
if (length(ind)) {
for (i in ind) {
arglist[[1]] <- ursa_colortable(obj[[i]])
do.call("legend_colorbar",arglist)
}
}
return(NULL)
}
units <- .getPrm(arglist,name="unit(s)*",kwd=kwd
,class=list("character","expression"),default="",verbose=FALSE)
if (all(!nchar(units))) {
aname <- names(arglist[1])
if (!is.null(aname))
units <- names(arglist[1])
}
labels <- .getPrm(arglist,name="labels",kwd=kwd,default=NA_real_)
align <- .getPrm(arglist,name="align",class=list("character","numeric")
,kwd=kwd,default=NULL,verbose=FALSE)
shift <- .getPrm(arglist,name="shift",kwd=kwd,default=1)
cex <- .getPrm(arglist,name="cex",kwd=kwd,default=1)
adj <- .getPrm(arglist,name="adj",kwd=kwd,default=NA_real_)
las <- .getPrm(arglist,name="las",kwd=kwd,default=1)
forceLabel <- .getPrm(arglist,name="forceLabel",kwd=kwd,default=FALSE)
lomar <- .getPrm(arglist,name="lomar",kwd=kwd,default=0)
himar <- .getPrm(arglist,name="himar",kwd=kwd,default=0)
turn <- .getPrm(arglist,name="turn",kwd=kwd,default=FALSE)
useRaster <- .getPrm(arglist,name="useRaster",kwd=kwd,default=NA)
trim <- .getPrm(arglist,name="trim",kwd=kwd,default=0L)
abbrev <- .getPrm(arglist,name="abbrev",class=list("integer","logical")
,kwd=kwd,default=18L)
opacity <- .getPrm(arglist,name="opacity",kwd=kwd,default=NA_real_)
if (is.logical(abbrev))
abbrev <- 24L*as.integer(abbrev)
verbose <- .getPrm(arglist,name="verb(ose)*",kwd=kwd,default=FALSE)
if (is.ursa(obj)) {
if (.is.colortable(obj))
ct <- obj$colortable
else
ct <- colorize(obj,...)$colortable
}
else if (inherits(obj,"ursaColorTable"))
ct <- obj
else
stop("Unclear coercion 'object' -> colorbar") ## return(NULL)
ret <- .legend_colorbar(ct,units=units,labels=labels,align=align,shift=shift
,cex=cex,adj=adj,las=las,forceLabel=forceLabel
,lomar=lomar,himar=himar,turn=turn
,useRaster=useRaster,trim=trim,abbrev=abbrev
,opacity=opacity,verbose=verbose)
invisible(ret)
}
'.legend_colorbar' <- function(ct,units="",labels=NA,align=NULL,shift=1 # labels=11L
,cex=1,adj=NA,las=1
,forceLabel=FALSE,lomar=0,himar=0,turn=FALSE
,useRaster=NA,trim=0L,abbrev=24L,opacity=NA
,verbose=FALSE)
{
devPrettyLab <- F | .isPackageInUse()
if (.skipPlot(FALSE))
return(NULL)
if (!getOption("ursaPngLayout")$legend)
return(invisible(10L))
# print(names(ct),quote=FALSE)
# str(as.list(match.call()))
if (is.null(names(ct)))
return(NULL)
if (all(is.na(names(ct)))) {
if (!FALSE) {
# display colorbar without labels or not?
}
else {
# par() ## or 'plot'?
plot(0,0,type="n",axes=FALSE,xlab="",ylab="")
return(0L)
}
}
if (is.na(useRaster)) {
cond1 <- getOption("ursaPngDevice")!="windows"
cond2 <- !(tolower(gsub(".*\\.(\\S+)$","\\1"
,getOption("ursaPngFileout"))) %in% c("svg"))
useRaster <- cond1 #&& cond2
# print(c(cond1=cond1,cond2=cond2,useRaster=useRaster))
}
# isChar <- length(grep("([A-Za-d]|[f-z]|/|\\*)",names(ct)))>0
if ((devSkipExtraTiffValues <- TRUE)&&(length(ct) %in% 2^c(8,16,32))) {
# ct <- tail(ct,-2540) ## dev N_20200407_concentration_v3.0.tif
ind <- unname(which(rev(ct)=="#000000"))
seqi <- rev(seq(length(ct)))
if ((length(ind)>1)&&(1L %in% ind)) {
ind2 <- which(diff(ind)>1)
if (length(ind2)) {
ind3 <- seq(seqi[tail(ind2,1)]+1,seqi[1])
}
else {
ind3 <- seq(seqi[tail(ind,1)-1],seqi[1])
}
ct <- ct[-ind3]
}
}
label <- .deintervale(ct,verbose=FALSE)
fmtLabel <- attr(ct,"label")
if (length(label)==length(fmtLabel)) {
label <- fmtLabel
isChar <- TRUE
}
isChar <- is.character(label)
isInterval <- length(label)!=length(ct)
if ((isChar)&&(!isInterval))
label <- names(ct)
family <- getOption("ursaPngFamily")
side <- .getSide()
if ((length(ct)==1)&&(isChar | !isChar))
las <- 0
# maxlabel <- ifelse(isChar || forceLabel,999,21) ## removed 2015-12-13
maxlabel <- ifelse(forceLabel,999,21) ## added 2015-12-13
offset <- NULL
if (length(offset)!=4)
offset <- rep(offset[1],4)
if (is.na(adj)) {
if (!isChar) {
if (side %in% c(2,4)) {
if (las %in% c(0,3)) ## vert
adj <- 0.5
else
adj <- 1
}
else { ## side %in% c(1,3)
if (las %in% c(2,3)) ## vert
adj <- 1
else
adj <- 0.5
}
}
else {
# adj <- ifelse(side %in% c(4,3),0,1)
if (side %in% c(2,4)) {
if (las %in% c(0,3)) ## vert
adj <- 0.5
else
adj <- ifelse(side==2,1,0)
}
else { ## side %in% c(1,3)
if (las %in% c(2,3)) ## vert
adj <- ifelse(side==1,1,0)
else
adj <- 0.5
}
# if (verbose)
# print(c(adj=adj))
}
}
par(mar=c(ifelse(side %in% c(2,4),lomar,0)
,ifelse(side %in% c(1,3),lomar,0)
,ifelse(side %in% c(2,4),himar,0)
,ifelse(side %in% c(1,3),himar,0)))
scale <- getOption("ursaPngScale")
# colorbar <- getOption("ursaPngBar")
col <- as.character(ct)
if (!length(col)) {
ct <- c(no_data="transparent")
col <- as.character(ct)
}
np <- length(col)
# label <- if (isChar) names(ct) else .deintervale(names(ct))
##~ label <- paste0("sdsddsd",label)
##~ label <- substr(label,1,1)
nl <- length(label)
interval <- as.integer(nl!=np)
at1 <- seq(nl)+ifelse(interval,0.5,0.0)
isRamp <- FALSE
if (is.na(labels[1]))
labels <- ifelse(isChar,31L,11L)
isSpecified <- ((length(labels)>1)||(labels[1]==0)||(!.is.integer(labels[1]))||
((!is.integer(labels[1]))&&(labels[1]==1)))
if (!isSpecified) {
labels[labels>nl] <- nl
}
isTick <- (nl>maxlabel) | isSpecified
keepLabel <- NULL
z <- z0 <- seq(col)-0L ## start from 0 or 1?
# z <- z0 <- seq(keepLabel)-0L ## start from 0 or 1?
if (side %in% c(1,3))
plot(0,0,type="n",xlim=c(min(z0)-0.5,max(z0)+0.5),ylim=c(0,1)
,xlab="",ylab="",axes=FALSE)
else if (side %in% c(2,4))
plot(0,0,type="n",ylim=c(min(z0)-0.5,max(z0)+0.5),xlim=c(0,1)
,xlab="",ylab="",axes=FALSE)
if ((isChar)&&(abbrev>0)) {
if (all(Encoding(label)!="UTF-8")) {
label2 <- label #iconv(label,to="UTF-8")
if (.isRscript()) {
shorten <- side %in% c(1,3) & las %in% c(0,1) |
side %in% c(2,4) & las %in% c(0,3)
if (!shorten)
a <- .try(label <- abbreviate(label2,minlength=abbrev,strict=TRUE))
else {
abbrev <- 64
mwidth <- par()$fin[ifelse(side %in% c(1,3),1,2)]
for (abbr in c(abbrev:2)) {
a <- .try(label <- abbreviate(label2,minlength=abbr,strict=TRUE))
if (!a)
break
width <- max(strwidth(paste0("Ww",label)
,units="inches",cex=cex,family=family))
# print(c(w0=width,w1=mwidth,w2=width*length(label)))
if (width*length(label)<mwidth)
break
}
}
}
else {
# encdng <- Encoding(label)
# Encoding(label) <- "UTF-8"
a <- .try(label <- abbreviate(label2,minlength=abbrev,strict=TRUE))
# Encoding(label) <- encdng
}
rm(label2)
}
else
a <- FALSE
if (!a) {
ind <- which(nchar(iconv(label,to="UTF-8"))>abbrev)
if (F) {
label[ind] <- substr(label[ind],1,abbrev)
substr(label[ind],abbrev,abbrev) <- ">"
a2 <- .try(label[ind] <- substr(label[ind],1,abbrev))
}
else {
label[ind] <- paste0(substr(label[ind],1,abbrev-1),"\u2026")
}
}
}
if (isTick)
{
if (TRUE) { #(!isChar) {
if (isChar) {
keepLabel <- label
# label <- factor(label)
label <- seq_along(label)-0L ## start from 0 or 1?
}
else if (any(diff(as.numeric(label))<0)) { ## unsorted means categories
keepLabel <- label
label <- seq_along(label)-0L ## start from 0 or 1?
}
y <- as.numeric(label)
uniy <- unique(diff(y))
isRamp <- TRUE
x <- seq(nl)+ifelse(interval,0.5,0.0)
isRegular <- ((length(uniy)==1)||(sd(uniy)<1e-11))
if (isSpecified) {
isManual <- TRUE
label <- labels
labels <- length(label)
}
else if (TRUE) {
if (!isRegular)
keepIrreg <- label
isW <- side %in% c(1,3) & las %in% c(0,1) |
side %in% c(2,4) & las %in% c(0,3)
isManual <- FALSE
if (!isW) {
height <- 1.5*strheight("Mg",units="inches",cex=cex,family=family)
mheight <- max(par()$fin)
repeat({
label <- pretty(y,n=labels)
if ((length(label)+1)*height<mheight)
break
labels <- labels-1
if (labels<1)
break
})
}
else {
mwidth <- max(par()$fin)
repeat({
if (!isChar) {
label <- pretty(y,n=labels)
if (F & devPrettyLab & !is.null(keepLabel)) {
label <- label[label>0]
# ct <- colorize(keepLabel,ncolor=length(label),tail=0)
# label4 <- as.numeric(names(ursa_colortable(ct)))
# print(c('L4:'=label4))
label1 <- keepLabel[label]
label2 <- pretty(label1,n=length(label))
print(c('L1:'=label1))
print(c('L2:'=label2))
label3 <- sapply(label1,function(x) {
dl <- abs(x-label2)
ind <- which.min(dl)
dl[ind]
# label2[ind]
# ind
})
print(c('L3:'=label3))
# print(c(label=length(label),label1=length(label1)
# ,label2=length(label2),label3=length(label3)
# ,label4=length(label4),labels=labels))
# print(keepLabel[label3])
# label <- label+label3
# label <- label[label>=1 & label<=max(y)]
}
}
else {
labelProposed <- .prettyLabel(y,ncol=labels)$at
if (is.null(labelProposed))
break
label <- labelProposed
if (!.is.integer(label)) {
labels <- labels-1
next
}
}
labelW <- if (isChar) keepLabel[label] else label
width <- max(strwidth(paste0(ifelse(isChar,"Wii","Wii"),labelW)
,units="inches",cex=cex,family=family))
if (width*length(label)<mwidth)
break
labels <- labels-1
})
}
if (!isRegular)
label <- keepIrreg
# print(c(have=(length(label)+1)*height,lim=mheight))
}
if ((!isRegular)&&(is.numeric(label))&&(!isSpecified)) {
y <- as.numeric(label)
uniy <- unique(diff(y))
if (length(uniy)==1)
isRegular <- TRUE
}
# adj <- if ((side %in% c(4L))&&())
if (isRegular) {
a0 <- (max(x)-min(x))/(max(y)-min(y))
b0 <- min(x)-a0*min(y)
at2 <- a0*label+b0
at1 <- at2[at2>=min(x) & at2<=max(x)]
label <- label[match(at1,at2)]
if (all(is.na(label))) {
label <- unique(y)
}
rm(at2)
}
else {
if (!isManual) {
val <- reclass(ct) ## 20160128 reclass(obj) -> reclass(ct)
if (is.ursa(val))
val <- sort(c(na.omit(c(val$value))))
for (mycol in seq(labels,11*(labels-1)+1,by=2))
{
if (interval %in% c(0L))
th <- seq(0,1,length=mycol*2+1)[seq(mycol)*2]
else if (interval %in% c(1L,2L))
{
th <- seq(0,1,length=mycol+2)
th <- th[-c(1,length(th))]
}
value <- unique(val[round(length(val)*th)])
if (length(value) >= labels)
break
}
dth <- mean(diff(th))/2
# sh <- c(1/2,1/4,1/8,1/16,1/32,1/64)
sh <- c(seq(0.6,0.1,by=-0.1),seq(0.1,0.02,by=-0.02)[-1])
# names(sh) <- as.character(sh)
v <- vector("list",length(value))
n <- length(val)
ind <- c(1,1)
for (i in seq_along(value)) {
if (i!=1L)
ind[1L] <- ind[2L]+1
ind[2L] <- ceiling((th[i]+dth)*n)
if (!FALSE)
v[[i]] <- val[ind[1]:ind[2]]
else
v[[i]] <- val[ceiling(c(th[i]-dth+1e-6,th[i]+dth)*n)]
}
res <- vector("list",length(sh))
# names(res) <- names(sh)
for (j in seq_along(sh)) {
value2 <- rep(NA,length(value))
for (i in seq_along(value)) {
v2 <- v[[i]]
if ((v2[1]<=0)&&(v2[2]>=0))
value2[i] <- 0
else {
# a <- pretty(v2,n=3,shrink=sh[j])
# a <- pretty(range(v2),shrink=sh[j],n=3)
a <- pretty(median(v2),shrink=sh[j])
value2[i] <- a[which.min(abs(a-median(v2)))[1]]
}
}
res[[j]] <- unique(value2)
if (length(res[[j]])>=length(value))
break
}
ind <- which.min(abs(length(value)-sapply(res,length)))
label <- res[[ind]]
# print(length(label))
rm(val,th,dth,value)
}
label <- label[label>=min(y) & label<=max(y)]
at1 <- rep(NA,length(label))
for (i in seq_along(label)) {
lab <- label[i]
ind2 <- which((y-lab)>0)[1]
if (is.na(ind2))
at1[i] <- tail(x,1)
else if (ind2>1) {
ind1 <- ind2-1L
at1[i] <- x[ind1]+(lab-y[ind1])/(y[ind2]-y[ind1])
}
else
at1[i] <- x[ind2]
# print(data.frame(i=i,lab=lab,ind2=ind2,at=at1[i]))
}
if (exists("ind1"))
rm(ind1)
if (exists("ind2"))
rm(ind2)
}
if (!is.null(keepLabel)) {
if (!devPrettyLab | is.character(keepLabel)) {
label <- keepLabel[unique(as.integer(round(label)))]
}
else {
label <- unique(as.integer(round(label)))
# print(label)
label1 <- keepLabel[label]
label2 <- pretty(label1,n=length(label))
# print(c('L1:'=label1))
# print(c('L2:'=label2))
label3 <- sapply(label1,function(x) {
dl <- abs(x-label2)
ind <- which.min(dl)
dl[ind]
# label2[ind]
# ind
})
# print(c('L3:'=label3))
label <- label1+label3
# print(c('L:'=label))
if (F & is.numeric(keepLabel)) {
label0 <- label
dlab <- diff(unique(sort(label)))
if (.is.integer(dlab))
dlab <- as.integer(round(dlab))
if (length(unique(dlab))==1) {
ud1 <- unique(dlab)
desired <- pretty(keepLabel,n=length(label))
print(length(label)==length(desired))
ud2 <- unique(diff(desired))
if (ud1==ud2) {
print(label0)
label <- c(na.omit(match(desired,keepLabel)))
# label <- keepLabel[label]
print(label)
q()
}
}
}
}
}
# if ((!isChar)&&(!((side %in% c(1,3))&&(las %in% c(0,1)))))
# label <- format(label,trim=TRUE,scientific=FALSE)
rm(x,y)
}
else {
maxlabel <- (labels-1L)/2+1L
i1 <- seq(label)
i2 <- 1+.round((nl-1)*seq(0,1,length=(maxlabel)*2+1)[2*seq(1,maxlabel,by=1)])
ind <- i1 %in% i2
label[!ind] <- ""
rm(i1,i2)
}
}
# print(data.frame(at=at1,label=label))
# str(keepLabel)
# print(c(col=length(col),label=length(keepLabel)))
if (turn)
{
z <- rev(z)
label <- rev(label)
}
shadow <- getOption("ursaPngShadow")
bg <- sum(c(col2rgb(getOption("ursaPngBackground")))*c(0.30,0.59,0.11))
tcol <- ifelse(bg<128,"#FFFFFF","#000000")
scol <- paste0(tcol,"7F")
if (length(z)>32767)
useRaster <- FALSE
if (any(substr(col,1,1)!="#")) {
.col <- col2rgb(col)
col <- rgb(.col[1,],.col[2,],.col[3,],maxColorValue=255)
}
ocol <- substr(col,8,9)
# print(all(nchar(ocol)==2))
# print(any(as.integer(paste0("0x",ocol))))
if (is.na(opacity))
opacity <- ((all(nchar(ocol)==2))&&((any(as.integer(paste0("0x",ocol))<255))))
if (opacity<=0)
opacity <- 0
else if (opacity>=1)
opacity <- 1
if (opacity)
shadow <- ""
if (side %in% c(1,3))
{
if (opacity) {
colBW <- colorRampPalette(c("grey40","grey80","white","white"))(16)
if (side==3)
colBW <- rev(colBW)
nu <- length(colBW)
zu <- matrix(rep(seq_along(colBW),times=length(z0)),nrow=nu)
image(x=z0,y=seq(0,1,length=nu),t(zu),axes=FALSE,col=colBW
,xlab="",ylab="",useRaster=!useRaster,add=TRUE)
}
image(x=z0,y=c(0,1),z=matrix(z,ncol=1),axes=FALSE,col=col
,xlab="",ylab="",useRaster=useRaster & isTick,add=TRUE)
if (nchar(shadow)) {
image(x=z0,y=if (side==3) c(0.7,1) else c(0,0.3)
,z=matrix(z,ncol=1),axes=FALSE,col=shadow
,xlab="",ylab="",useRaster=useRaster,add=TRUE)
}
if (length(at1)>191)
NULL
else if (!isTick)
abline(v=z0[-1]-0.5,h=0,col=scol,lty=1,lwd=0.5)
else {
for (d in c(1,3))
axis(d,col=NA,col.ticks=scol,at=at1,tck=0.2
,labels=NA,lty=1,lwd=0.5)
}
}
else if (side %in% c(2,4))
{
if (opacity) {
colBW <- colorRampPalette(c("grey40","grey80","white","white"))(16)
if (side==2)
colBW <- rev(colBW)
nu <- length(colBW)
zu <- matrix(rep(seq_along(colBW),each=length(z0)),ncol=nu)
image(y=z0,x=seq(0,1,length=nu),t(zu),axes=FALSE,col=colBW
,xlab="",ylab="",useRaster=!useRaster,add=TRUE)
}
image(y=z0,x=c(0,1),z=matrix(z,nrow=1),axes=FALSE,col=col
,xlab="",ylab="",useRaster=useRaster & isTick,add=TRUE)
if (nchar(shadow)) {
image(y=z0,x=if (side==4) c(0.7,1) else c(0,0.3)
,z=matrix(z,nrow=1),axes=FALSE,col=shadow
,xlab="",ylab="",useRaster=useRaster,add=TRUE)
}
if (length(at1)>191)
NULL
if (!isTick)
abline(v=0,h=seq(col)[-1]-0.5,col=scol,lty=1,lwd=0.5)
else {
for (d in c(2,4))
axis(d,col=NA,col.ticks=scol,at=at1,tck=0.2
,labels=NA,lty=1,lwd=0.5)
}
}
if (!length(label)) {
label <- ""
skipLabel <- TRUE
}
else
skipLabel <- FALSE
# return(NULL)
# a <- 2*adj*width#*scale[2]
# print(a)
## dependence on compose_open(pointsize=...)
usr <- par()$usr
fin <- par()$fin
if (!skipLabel) {
if (is.numeric(label)) {
if (TRUE) {
label1 <- format(label,trim=TRUE,scientific=NA)
label2 <- as.character(label)
label3 <- format(label,trim=TRUE,scientific=FALSE)
sci <- length(.grep("e(\\+|\\-)\\d+$",label2))
if (sci) {
dig <- max(nchar(gsub("^(.+)\\.(\\d+)$","\\2",label2)))
label2 <- format(label,trim=TRUE,scientific=FALSE,nsmall=dig)
}
cond1 <- max(nchar(label1))+0<=max(nchar(label2))
cond2 <- (!sci)||(sci==length(label))
cond3 <- length(unique(label1))==length(label)
label <- if (((cond1)||(!cond2))&&(cond3)) label1
else label2
if (localVerb <- FALSE) {
print(label1)
print(label2)
print(label3)
print(c(cond1=cond1,cond2=cond2,cond3=cond3))
print(label)
q()
}
}
else {
if (length(label)>2) {
difL <- diff(label)
if (length(which(!is.na(.is.near(difL,mean(difL)))))==length(difL))
label <- format(label,trim=TRUE,scientific=NA)
else
label <- as.character(label)
}
else
label <- format(label,trim=TRUE,scientific=NA)
}
}
}
if (!length(align)) {
width <- try(max(strwidth(label,units="inches",cex=cex,family=family)))
if (inherits(width,"try-error")) {
labE <- Encoding(label)
if (all(c("unknown","UTF-8") %in% unique(labE))) {
Encoding(label) <- "unknown"
width <- max(strwidth(label#[labE %in% "unknown"]
,units="inches",cex=cex,family=family))
}
}
}
else
width <- max(strwidth(align,units="inches",cex=cex))
height <- max(strheight(label,units="inches",cex=cex,family=family)) ## family was missing
if (is.numeric(shift)) {
# print(c(side=side,las=las,shift=shift))
if ((side %in% c(2,4))&&(las %in% c(1,2))||
(side %in% c(1,3))&&(las %in% c(0,1)))
width <- width*shift
else
height <- height*shift
}
if (width < 0) {
width <- strwidth(paste(rep(0,max(nchar(label))),collapse="")
,units="inches",cex=cex,family=family)
width <- strheight("000",units="inches",cex=cex,family=family)
}
if (!skipLabel) {
if (side==4)
{
adj1 <- adj
if ((isRamp)&&(trim)) {
mul <- (usr[4]-usr[3])/fin[2]
n <- length(label)
if (las %in% c(1L,2L))
w <- strheight(label,units="inch",cex=cex)*mul
else {
w <- strwidth(label,units="inch",cex=cex)*mul
adj1 <- 0.5
}
if (at1[1]-w[1]/2<usr[3]) {
at1[1] <- usr[3]+1.3*w[1]/2
if (trim>1)
label[1] <- ""
}
if (at1[n]+w[n]/2>usr[4]) {
at1[n] <- usr[4]-(1.3*ifelse(las %in% c(1L,2L),1.5,1))*w[n]/2
if (trim>1)
label[n] <- ""
}
if ((!numeric(shift))&&(!length(align))&&(trim>1))
width <- max(strwidth(label,units="inches",cex=cex,family=family))
}
if (las %in% c(1,2)) ## horiz
mtext(text=label,at=at1,las=las,line=0.6+cex*adj*width/height*1.0
,side=side,cex=cex,padj=ifelse(isRamp,0.5,0.4),adj=adj1,col=tcol
,family=getOption("ursaPngFamily")
)
else
mtext(text=label,at=at1,las=las,line=0.1
,side=side,cex=cex,padj=0.5,adj=adj1,col=tcol
,family=getOption("ursaPngFamily")
)
##~ mtext(text=label,at=at1,las=las,line=0.6+adj*width/height
##~ ,side=side,padj=ifelse(isRamp,0.5,0.4),adj=adj1,cex=cex,col="black")
}
else if (side==3)
{
if ((isRamp)&&(trim)) {
mul <- (usr[2]-usr[1])/fin[1]
n <- length(label)
if (las %in% c(2L,3L))
w <- strheight(label,units="inch",cex=cex)*mul
else {
w <- strwidth(label,units="inch",cex=cex)*mul
}
if (at1[1]-w[1]/2<usr[1]) {
at1[1] <- usr[1]+(1.3*ifelse(las %in% c(2L,3L),1.5,1))*w[1]/2
if (trim>1)
label[1] <- ""
}
if (at1[n]+w[n]/2>usr[2]) {
at1[n] <- usr[2]-(1.3*ifelse(las %in% c(2L,3L),1,1))*w[n]/2
if (trim>1)
label[n] <- ""
}
if ((!numeric(shift))&&(!length(align))&&(trim>1))
width <- max(strwidth(label,units="inches",cex=cex,family=family))
}
mtext(text=label,at=at1,las=las
,line=ifelse(las %in% c(0,1),0,0.5+adj*width/height)
,side=side
,padj=ifelse(las %in% c(0,1),-0.25,0.4)
,adj=adj #ifelse(las==1,0.5,adj)
,cex=cex,col=tcol
,family=getOption("ursaPngFamily")
)
}
else if (side==2)
{
if ((isRamp)&&(trim)) {
mul <- (usr[4]-usr[3])/fin[2]
n <- length(label)
if (las %in% c(1L,2L))
w <- strheight(label,units="inch",cex=cex)*mul
else {
w <- strwidth(label,units="inch",cex=cex)*mul
}
if (at1[1]-w[1]/2<usr[3]) {
at1[1] <- usr[3]+1.3*w[1]/2
if (trim>1)
label[1] <- ""
}
if (at1[n]+w[n]/2>usr[4]) {
at1[n] <- usr[4]-(1.3*ifelse(las %in% c(1L,2L),1.5,1))*w[n]/2
if (trim>1)
label[n] <- ""
}
if ((!numeric(shift))&&(!length(align))&&(trim>1))
width <- max(strwidth(label,units="inches",cex=cex,family=family))
}
mtext(text=label,at=at1,las=las,line=0.4
,side=side,padj=ifelse(las %in% c(0,3),0.2,0.4)
,adj=ifelse(las %in% c(0,3),0.5,adj),cex=cex,col=tcol
,family=getOption("ursaPngFamily")
)
}
else if (side==1)
{
if ((isRamp)&&(trim)) {
mul <- (usr[2]-usr[1])/fin[1]
n <- length(label)
if (las %in% c(2L,3L))
w <- strheight(label,units="inch",cex=cex)*mul
else {
w <- strwidth(label,units="inch",cex=cex)*mul
}
if (at1[1]-w[1]/2<usr[1]) {
at1[1] <- usr[1]+(1.3*ifelse(las %in% c(2L,3L),1.5,1))*w[1]/2
if (trim>1)
label[1] <- ""
}
if (at1[n]+w[n]/2>usr[2]) {
at1[n] <- usr[2]-(1.3*ifelse(las %in% c(1L,2L),1,1))*w[n]/2
if (trim>1)
label[n] <- ""
}
if ((!numeric(shift))&&(!length(align))&&(trim>1))
width <- max(strwidth(label,units="inches",cex=cex,family=family))
}
mtext(text=label,at=at1,las=las
,line=ifelse(las %in% c(0,1),0,0.3+(1-adj)*width/height)
,side=side,padj=0.5
,adj=adj # ifelse(las %in% c(0,1),0.5,adj)
,cex=cex,col=tcol
,family=getOption("ursaPngFamily")
)
}
}
if (getOption("ursaPngBox")) {
panel_box()
}
# options(ursaWidth=width,ursaHeight=height)
if (((is.character(units))&&(is.na(units[1])))||(!nchar(units[1])))
return(invisible(10L))
# b <- 2*width+0.5+height
# print(b)
## TODO: how to use UTF8 in "as.expressions"
if (F & is.character(units)) {
if (getOption("ursaPngDevice") %in% c("windows","agg"))
toE <- TRUE
else {
opWE <- options(warn=2)
toE <- .try(abbreviate(units,minlength=2,strict=TRUE),silent=TRUE)
options(opWE)
}
if (toE <- !TRUE)
units <- as.expression(substitute(bold(u),list(u=units)))
# else
# message(paste("Note (colorbar): unable to make bold caption for",.dQuote(units)))
str(units)
}
else if (is.list(units))
units <- as.expression(substitute(bold(u)
,list(u=paste(unlist(units),collapse=", "))))
if (side==4) {
if (las %in% c(1,2))
mtext(units,side=side,padj=0,adj=0.5,las=3,col=tcol,cex=cex
,line=width/height+1.2
,font=2,family=getOption("ursaPngFamily")
)
else
mtext(units,side=side,padj=0,adj=0.5,las=3,col=tcol,cex=cex
,line=height+2
,font=2,family=getOption("ursaPngFamily")
)
}
else if (side==3) {
mtext(units,side=side,padj=0,adj=0.5,las=1,col=tcol,cex=cex
,line=ifelse(las %in% c(0,1),1.5,width/height+0.7)
,font=2,family=getOption("ursaPngFamily")
)
}
else if (side==2) {
mtext(units,side=side,padj=0,adj=0.5,las=3,col=tcol,cex=cex
,line=ifelse(las %in% c(1,2),0.8+width/height,height+1.5)
,font=2,family=getOption("ursaPngFamily")
)
}
else if (side==1) {
##~ mtext(units,side=side,padj=1,adj=0.5,las=1,col=tcol,cex=cex
##~ ,line=0.85)
# units <- expression(degree~C)
# Encoding(units) <- "UTF-8"
mtext(units,side=side,padj=1,adj=0.5,las=1,col=tcol,cex=cex
,line=ifelse(las %in% c(0,1),0.85,1*width/height)
,font=2,family=getOption("ursaPngFamily")
)
}
invisible(0L)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/legend_colorbar.R
|
'legend_mtext' <- function(...) {
if (.skipPlot(FALSE))
return(NULL)
kwd <- "mtext"
arglist <- list(...)
text <- .getPrm(arglist,name="(text|.*)",kwd=kwd
,class=list("character","expression"),default="Title/subtitle")
cex <- .getPrm(arglist,name="cex",kwd=kwd,default=1)
verbose <- .getPrm(arglist,name="verb(ose)*",kwd=kwd,default=FALSE)
.legend_mtext(text=text,cex=cex)
}
'.legend_mtext' <- function(text="Annotation",cex=1) {
'.mtext' <- function(text,...) {
if (is.character(text)) {
if (getOption("ursaPngDevice") %in% c("windows","agg"))
toE <- TRUE
else {
opWE <- options(warn=2)
toE <- .try(abbreviate(text,minlength=2,strict=TRUE),silent=TRUE)
options(opWE)
}
if (toE)
txt <- as.expression(substitute(bold(u),list(u=text)))
else {
message(paste("Note (mtext): unable to make bold label for",.dQuote(text)))
txt <- text
}
}
else if (is.expression(text))
txt <- text
.try(mtext(txt,...))
}
if (.skipPlot(FALSE))
return(NULL)
side <- .getSide()
if (!length(text))
text <- ""
width <- max(strwidth(text,units="inches",cex=cex))
height <- max(strheight(text,units="inches",cex=cex))
# print(c(width=width,height=height,ratio=width/height))
par(mar=c(0,0,0,0))
plot(0,0,type="n",xlim=c(-1,1),ylim=c(-1,1),axes=FALSE,xlab="",ylab="")
# text(0.5,0.5,labels=text,las=3,xpd=FALSE,cex=cex,xpd=TRUE,col="red")
if (side==1)
ret <- .mtext(text,side=3,cex=cex,line=-0.25,adj=0.5,padj=1.1,xpd=TRUE)
else if (side==3)
ret <- .mtext(text,side=1,cex=cex,line=-0.85-0.10,adj=0.5,padj=0,xpd=TRUE)
else if (side==2)
ret <- .mtext(text,side=4,cex=cex,line=-1,adj=0.5,padj=0,xpd=TRUE)
else if (side==4) {
# sink(.maketmp(ext="par"))
# str(par())
# sink()
ret <- .mtext(text,side=2,cex=cex,line=c(-1.4,0)[1],adj=0.5
,padj=c(0,1.1)[1],xpd=TRUE)
}
else
ret <- .mtext(text,side=side,cex=cex,padj=0.75,xpd=TRUE)
invisible(ret)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/legend_mtext.R
|
'.open_gdalraster' <- function(fname,engine="gdalraster",verbose=FALSE) {
if (!is.character(fname))
return(NULL)
engine <- match.arg(engine)
requireNamespace("gdalraster",quietly=.isPackageInUse())
opW <- options(warn=0-!verbose,show.error.messages=TRUE)
on.exit(options(opW))
ds <- methods::new(gdalraster::GDALRaster,filename=fname,read_only=TRUE)
# str(ds)
if (verbose) {
md <- list(ncols=ds$getRasterXSize()
,nrows=ds$getRasterYSize()
,bbox=ds$bbox()
,nodata=ds$getNoDataValue(band=1)
,dim=ds$dim()
,res=ds$res()
# ,md=ds$getMetadata(band=1)
,transform=ds$getGeoTransform()
,crs=ds$getProjectionRef()
,datatype=ds$getDataTypeName(band=1)
# ,info=ds$info()
# ,jinfo=ds$infoAsJSON() |> jsonlite::fromJSON()
,md0=ds$getMetadata(band=0,domain="")
# ,md1=ds$getMetadata(band=1,domain="")
# ,mdi0=ds$getMetadataItem(band=0,domain="",mdi_name="")
,ct=ds$getColorTable(band=1) ## ver 1.4.1
)
str(md)
}
dima <- ds$dim()
datatype <- ds$getDataTypeName(band=1)
nodata <- ds$getNoDataValue(band=1)
md0 <- ds$getMetadata(band=0,domain="")
bbox <- ds$bbox()
res <- ds$res()
if (TRUE) {
g1 <- regrid(bbox=bbox,res=res
,crs=sf::st_crs(ds$getProjectionRef())$proj4string
# ,crs=ds$getProjectionRef()
)
}
else {
g1 <- .grid.skeleton()
g1$minx <- bbox[1]
g1$maxx <- bbox[3]
g1$miny <- bbox[2]
g1$maxy <- bbox[4]
g1$columns <- dima[1]
g1$rows <- dima[2]
g1$resx <- res[1]
g1$resy <- res[2]
# g1$crs=sf::st_crs(ds$getProjectionRef())$proj4string
g1$crs=ds$getProjectionRef()
}
# session_grid(g1)
res <- .raster.skeleton()
res$dim <- c(prod(dima[1:2]),dima[3])
con <- .con.skeleton()
con$driver <- "GDALRASTER"
con$samples <- g1$columns
con$lines <- g1$rows
con$bands <- dima[3]
con$indexC <- seq(g1$columns)
con$indexR <- seq(g1$rows)
con$indexZ <- seq_len(dima[3])
con$seek <- FALSE
con$fname <- fname
con$handle <- ds
con$datatype <- switch(datatype,byte=1L,integer=2L,real=4L,float=4L
,Byte=1L,UInt8=1L,Int8=11
,Int16=2L,UInt16=12,UInt32=13,Int32=3
,Float32=4L,Float64=5L
,NA_integer_)
res$con <- con
ursa_grid(res) <- g1
if (!is.null(datatype))
ignorevalue(res) <- ifelse(con$datatype %in% c(1L,11L,2L,12L,3L,13L)
,as.integer(nodata),nodata)
ct <- NULL ## CURRENTLY UNEMPLEMENTED
ursa_grid(res) <- g1
patt <- "^Band_(\\d+)=(.+)$"
j <- grep(patt,md0)
bname <- gsub(patt,"\\2",md0[j])
# bname <- gsub("^Band_\\d+=","",grep("^Band",md$md0,value=TRUE))
if (!length(bname))
names(res) <- paste("Band",seq_along(con$bands))
else {
ind <- as.integer(gsub(patt,"\\1",md0[j]))
names(res)[ind] <- bname
}
# names(res) <- bname
ursa_colortable(res) <- ct
# if (!is.null(a$nodata_value))
# ignorevalue(res) <- a$nodata_value
class(res$value) <- ifelse(length(ct),"ursaCategory","ursaNumeric")
res
}
'.read_gdalraster' <- function(fname,resetGrid=TRUE,band=NULL
,engine=c("gdalraster"),verbose=FALSE,...) { ## ,...
engine <- match.arg(engine)
requireNamespace("gdalraster",quietly=.isPackageInUse())
a <- .open_gdalraster(fname,engine=engine,verbose=verbose)
ds <- methods::new(gdalraster::GDALRaster,filename=fname,read_only=TRUE)
if (verbose) {
md <- list(ncols=ds$getRasterXSize()
,nrows=ds$getRasterYSize()
,bbox=ds$bbox()
,nodata=ds$getNoDataValue(band=1)
,dim=ds$dim()
,res=ds$res()
# ,md=ds$getMetadata(band=1)
,transform=ds$getGeoTransform()
,crs=ds$getProjectionRef()
# ,info=ds$info()
# ,jinfo=ds$infoAsJSON() |> jsonlite::fromJSON()
,md0=ds$getMetadata(band=0,domain="")
# ,md1=ds$getMetadata(band=1,domain="")
# ,mdi0=ds$getMetadataItem(band=0,domain="",mdi_name="")
,ct=ds$getColorTable(band=1) ## ver 1.4.1
)
str(md)
}
dima <- ds$dim()
nodata <- ds$getNoDataValue(band=1)
md0 <- ds$getMetadata(band=0,domain="")
g1 <- regrid(bbox=ds$bbox(),res=ds$res()
,crs=sf::st_crs(ds$getProjectionRef())$proj4string
# ,crs=ds$getProjectionRef()
)
session_grid(g1)
patt <- "^Band_(\\d+)=(.+)$"
j <- grep(patt,md0)
bname <- gsub(patt,"\\2",md0[j])
# bname <- gsub("^Band_\\d+=","",grep("^Band",md$md0,value=TRUE))
if (!length(bname))
bname <- paste("Band",seq_along(dima[3]))
else {
ind <- as.integer(gsub(patt,"\\1",md0[j]))
bname[ind] <- bname
}
out <- ursa_new(bandname=bname,nodata=nodata)
if (verbose)
cat("read")
for (i in seq(out)) {
if (verbose)
cat(".")
# print(i)
# ursa_value(out)[,i] <-
a <- ds$read(band=i
,xoff=0,yoff=0
,xsize=dima[1],ysize=dima[2]
,out_xsize=dima[1],out_ysize=dima[2]
)
out$value[,i] <- a
}
if (verbose)
cat(" done!\n")
out
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/package_gdalraster.R
|
# TODO: replace 'a@value' --> 'methods::slot(a,"value")'
# 'raster' <- function(obj) UseMethod("as.Raster",obj)
## The following object is masked from 'package:...'
## how to register:
# ?knitr::knit_print
# library(knitr)
# knit_print.data.frame = function(x, ...) {
# res = paste(c("", "", kable(x, output = FALSE)), collapse = "\n")
# asis_output(res)
# }
# registerS3method("knit_print", "data.frame", knit_print.data.frame)
'as.Raster' <- function(obj=NULL) UseMethod("as.Raster",obj)
'as.Raster.ursaRaster' <- function(obj) .as.Raster(obj)
'as.Raster.list' <- function(obj) .as.Raster(obj)
'as.Raster.ursaStack' <- function(obj) .as.Raster(obj)
# 'as.Raster.ursaBrick' <- function(obj) .as.Raster(obj)
'as.Raster.NULL' <- function(obj) .as.Raster(session_grid())
#'as.Raster.NULL' <- function(obj) .as.Raster(ursa())
'.as.Raster' <- function(obj) {
# suppressMessages({
requireNamespace("methods",quietly=.isPackageInUse())
# requireNamespace("rgdal",quietly=.isPackageInUse())
# require("raster") ## FAILED if 'requireNamespace'
requireNamespace("raster",quietly=.isPackageInUse())
# })
'.addColorTable<-' <- function(r,value) {
if (!length(value))
return(r)
r <- raster::as.factor(r)
x <- raster::levels(r)[[1]]
x$code <- names(value)
r@data@attributes[[1]] <- x # levels(r) <- x ## 'levels<-' is not public
if (!anyNA(value))
raster::colortable(r) <- as.character(value)
r@legend@values <- seq_along(value)-1
# res@legend@color <- as.character(value)
# res@legend@type <- "a"
r@legend@names <- names(value)
r
}
isGrid <- .is.grid(obj)
isStack <- .is.ursa_stack(obj)
if ((!isGrid)&&(!isStack)&&(!.is.ursa_brick(obj)))
return(NULL)
g1 <- ursa_grid(obj)
ct <- ursa_colortable(obj)
# ct2 <- lapply(obj,ursa_colortable)
isCT <- FALSE # length(ct)>0
isLayer <- !isGrid && !isStack && length(obj)==1
isBrick <- !isGrid && !isStack && !isLayer
# print(c(isGrid=isGrid,isLayer=isLayer,isBrick=isBrick,isStack=isStack))
if (isLayer) {
a <- as.array(obj,permute=TRUE,flip=TRUE,drop=TRUE)
res <- raster::raster(as.array(obj,permute=TRUE,flip=TRUE,drop=TRUE))
.addColorTable(res) <- ursa_colortable(obj)
}
else if (isBrick) {
res <- raster::brick(as.array(discolor(obj),permute=TRUE,flip=TRUE,drop=TRUE))
}
else if (isStack) {
res <- vector("list",length(obj))
for (i in seq_along(res)) {
r <- raster::raster(as.array(obj[[i]],permute=TRUE,flip=TRUE,drop=TRUE))
if (isCT <- FALSE) {
r <- raster::as.factor(res)
x <- raster::levels(r)[[1]]
x$code <- names(ct)
r@data@attributes[[1]] <- x # levels(r) <- x ## 'levels<-' is not public
raster::colortable(r) <- as.character(ct)
r@legend@values <- seq_along(ct)-1
# res@legend@color <- as.character(ct)
# res@legend@type <- "a"
r@legend@names <- names(ct)
}
.addColorTable(r) <- ursa_colortable(obj[[i]])
res[[i]] <- r
}
res <- raster::stack(res)
}
else if (isGrid) {
res <- with(g1,raster::raster(nrows=rows,ncols=columns))
}
raster::extent(res) <- with(g1,c(minx,maxx,miny,maxy))
# print(c(isPackageInUse=.isPackageInUse()))
opC <- options(warn=ifelse(.isPackageInUse(),-1,1))
raster::crs(res) <- sp::CRS(ursa_crs(g1),doCheckCRSArgs=!FALSE) ## 20220118 doCheck...=TRUE
options(opC)
if (isGrid)
return(res)
nodata <- sapply(obj,ursa_nodata)
if (!anyNA(nodata))
raster::NAvalue(res) <- nodata
names(res) <- names(obj)
res
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/package_raster.R
|
'.open_sfgdal' <- function(fname,engine="sf",verbose=FALSE) {
if (!requireNamespace("sf",quietly=.isPackageInUse()))
stop("Package 'sf' is required for this operation")
obj <- sf::gdal_read(fname,read_data=FALSE)
columns <- obj$cols[2]
rows <- obj$rows[2]
bands <- length(obj$bands)
if (length(ind <- grep("(^crs$|^wkt|wkt$)",names(obj))))
crs <- obj[[ind]]
if (is.character(crs))
crs <- sf::st_crs(crs)$proj4string
if (inherits(crs,"crs"))
crs <- crs$proj4string
if (is.na(crs))
crs <- ""
if (all(is.na(obj$geotransform))) {
resx <- 1
resy <- 1
minx <- 0
miny <- 0
maxx <- columns
maxy <- rows
}
else {
resx <- obj$geotransform[2]
resy <- -obj$geotransform[6]
minx <- obj$geotransform[1]
maxy <- obj$geotransform[4]
maxx <- minx+columns*resx
miny <- maxy-rows*resy
}
g1 <- regrid(minx=minx,maxx=maxx,miny=miny,maxy=maxy,columns=columns,rows=rows
,crs=crs # sf::st_crs(obj$crs)$proj4string
)
res <- .raster.skeleton()
res$grid <- g1
con <- .con.skeleton()
con$samples <- columns
con$lines <- rows
con$bands <- bands
con$driver <- "SF"
con$indexC <- seq(columns)
con$indexR <- seq(rows)
con$indexZ <- seq_along(bands)
con$seek <- FALSE
con$fname <- fname
con$datatype <- switch(obj$datatype,byte=1L,integer=2L,real=4L,float=4L
,Byte=1L,UInt8=1L,Int8=11
,Int16=2L,UInt16=12,UInt32=13,Int32=3
,Float32=4L,Float64=5L
,NULL)
con$handle <- obj
res$con <- con
isClass <- length(obj$attribute_tables[[1]])>0
isColor <- length(obj$color_tables[[1]])>0
isCat <- (isClass)||(isColor)
if (isCat) {
if (isClass) {
ctName <- obj$attribute_tables[[1]][["category"]]
if (is.null(ctName))
isCat <- FALSE
}
}
if (isCat) {
if (isColor) {
ctCol <- obj$color_tables[[1]]
ct <- rgb(ctCol[,1],ctCol[,2],ctCol[,3],ctCol[,4],maxColorValue=255)
if (all(substr(ct,8,9)=="FF"))
ct <- substr(ct,1,7)
if (isClass)
if (length(ct)>length(ctName))
ct <- ct[seq_len(length(ctName))]
}
else
ct <- rep(NA,length(ctName))
if (isClass)
names(ct) <- ctName
class(ct) <- "ursaColorTable"
if (length(ind <- which(names(ct)==""))) {
if (length(ind <- ind[ind>1])>0) {
if (length(ctCol <- unique(substr(ct[ind],1,7)))==1) {
ct <- ct[-ind]
}
}
}
}
if ((isCat)||((T & !.lgrep("float",obj$datatype)))) {
# .elapsedTime("F")
# v <- as.integer(v)
# dim(v) <- dimv
# storage.mode(v) <- "integer"
mode(res$value) <- "integer"
# .elapsedTime("G")
}
# .elapsedTime("as.ursa -- before")
# res <- as.ursa(v) ## RECURSIVE
# res <- ursa_new(v)
# .elapsedTime("as.ursa -- after")
if (isCat) {
ursa_colortable(res) <- ct
class(res$value) <- "ursaCategory"
}
bname <- obj$description
if (any(nchar(bname)>0)) {
names(res) <- gsub("\\t","",bname) ## patch for ENVI 'band name'
}
else {
patt <- "^Band_(\\d+)=(.+)$"
j <- grep(patt,obj$meta)
ind <- as.integer(gsub(patt,"\\1",obj$meta[j]))
bname <- gsub(patt,"\\2",obj$meta[j])
bname[ind] <- bname
if (!length(bname))
bname <- paste("Band",seq(bands))
names(res) <- bname
}
res$dim <- as.integer(c(columns*rows,bands))
gi <- sf::gdal_utils("info",fname,quiet=!FALSE)
gi <- strsplit(gi,split="\\n")[[1]]
if (tryToUseOnlyInfoForGridAndMetadata <- FALSE) {
cat("---------------\n")
print(gi)
cat("---------------\n")
q()
}
gi <- grep("NoData Value",gi,value=TRUE)
if (length(gi)>0) {
nodata <- gsub("^.*=(\\s*(\\S+))$","\\1",gi)
if (typeof(ursa_value(res))=="integer")
ignorevalue(res) <- as.integer(unique(nodata))
else
ignorevalue(res) <- as.numeric(unique(nodata))
}
res
}
'.read_stars' <- function(fname) {
if (!requireNamespace("sf",quietly=.isPackageInUse()))
stop("Package 'sf' is required for this operation")
a <- sf::gdal_read(fname,read_data=FALSE)
columns <- a$cols[2]
rows <- a$rows[2]
bands <- a$bands[2]
# patt <- "^Band_(\\d+)=(.+)$"
patt <- "^Band_(\\d+)=\\t*(.+)$"
bname <- grep(patt,a$meta,value=TRUE)
b1 <- .grep(patt,a$meta,value=TRUE)
bname <- .gsub(patt,"\\2",b1)
bname[as.integer(.gsub(patt,"\\1",b1))] <- bname
if (all(is.na(a$geotransform))) {
resx <- 1
resy <- 1
minx <- 0
miny <- 0
maxx <- columns
maxy <- rows
}
else {
resx <- a$geotransform[2]
resy <- -a$geotransform[6]
minx <- a$geotransform[1]
maxy <- a$geotransform[4]
maxx <- minx+columns*resx
miny <- maxy-rows*resy
}
g1 <- regrid(minx=minx,maxx=maxx,miny=miny,maxy=maxy,columns=columns,rows=rows
,crs=sf::st_crs(a$crs)$proj4string)
session_grid(g1)
res <- ursa(attr(sf::gdal_read(fname,read_data=TRUE),"data"),flip=TRUE)
if (length(bname)==length(res))
names(res) <- bname
res
}
'as_stars' <- function(obj) {
if (!inherits(obj,"ursaRaster"))
return(NULL)
g <- ursa_grid(obj)
crs <- ursa_crs(obj)
if ((FALSE)&&(requireNamespace("sf",quietly=.isPackageInUse())))
crs <- sf::st_crs(crs)
md <- list(x=NULL
,y=NULL
,band=NULL
)
md$x <- list(from=1L
,to=g$columns
,offset=g$minx
,delta=g$resx
,refsys=crs
,point=NA
,values=NULL
)
md$y <- list(from=1L
,to=g$rows
,offset=g$maxy
,delta=-g$resy
,refsys=crs
,point=NA
,values=NULL
)
md$band <- list(from=1L
,to=unname(length(obj))
,offset=NA_real_
,delta=NA_real_
,refsys=NA_character_
,point=NA,values=names(obj)
)
class(md$x) <- class(md$y) <- class(md$band) <- "dimension"
band <- list(affine=c(0,0)
,dimensions=c("x","y")
,curvilinear=FALSE
,blocksizes=NULL
)
class(band) <- "stars_raster"
attr(md,"raster") <- band
class(md) <- "dimensions"
ret <- list(imported=as.array(obj,flip=TRUE,permute=FALSE))
if (T & length(ct <- ursa_colortable(obj))>0) {
dima <- dim(ret[[1]])[-3]
ret[[1]] <- factor(ret[[1]],levels=seq_along(ct)-0L,labels=names(ct))
dim(ret[[1]]) <- dima
attr(ret[[1]],"colors") <- unclass(unname(ct))
attr(ret[[1]],"exclude") <- rep(FALSE,length(ct))
md$band <- NULL
}
attr(ret,"dimensions") <- md
# attr(ret,"geotransform") <- c(g$minx,g$resx,0,g$maxy,-g$resy,0)
class(ret) <- "stars"
ret
}
# 'as.stars' <- function(obj) as_stars(obj=obj) ## if 'stars' is class, then 'as' is function
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/package_sf.R
|
'.as_terra' <- function(a) {
if (!requireNamespace("terra",quietly=.isPackageInUse()))
stop("Package 'terra' is required for this operation")
r <- terra::rast(resolution=ursa(a,"cell")
,extent=ursa_bbox(a)[c(1,3,2,4)]
,nlyrs=length(a)
,names=names(a)
,crs=ursa_crs(a)
,vals=ursa_value(a)
)
r
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/package_terra.R
|
'.open_vapour' <- function(fname,engine="vapour",verbose=FALSE) {
if (!is.character(fname))
return(NULL)
engine <- match.arg(engine)
requireNamespace("vapour",quietly=.isPackageInUse())
opW <- options(warn=0-!verbose,show.error.messages=TRUE) ## to prevent 'GeoTransform values not available'
on.exit(options(opW))
a <- vapour::vapour_raster_info(fname)
g1 <- regrid()
g1$rows <- a$dimension[2]
g1$columns <- a$dimension[1]
##~ nl <- as.integer(a1[3])
g1$minx <- a$extent[1]
g1$maxx <- a$extent[2]
g1$miny <- a$extent[3]
g1$maxy <- a$extent[4]
# g1$resx <- a$geotransform[2]
# g1$resy <- -a$geotransform[4]
g1$resx <- with(g1,(maxx-minx)/columns)
g1$resy <- with(g1,(maxy-miny)/rows)
g1$crs <- a$projstring
# comment(g1$crs) <- a$projection
# if (is.na(g1$crs))
# g1$crs <- ""
# str(g1)
# session_grid(g1)
res <- .raster.skeleton()
# res$dim <- as.integer(c(prod(a$dimension),a$bands))
res$dim <- c(prod(a$dimension),a$bands) |> as.integer()
con <- .con.skeleton()
con$driver <- "VAPOUR"
con$samples <- g1$columns
con$lines <- g1$rows
con$bands <- a$bands
con$indexC <- seq(g1$columns)
con$indexR <- seq(g1$rows)
con$indexZ <- seq_len(a$bands)
con$seek <- FALSE
con$fname <- fname
con$handle <- fname ## methods::new("GDALReadOnlyDataset",fname)
con$datatype <- switch(a$datatype,byte=1L,integer=2L,real=4L,float=4L
,Byte=1L,UInt8=1L,Int8=11
,Int16=2L,UInt16=12,UInt32=13,Int32=3
,Float32=4L,Float64=5L
,NA_integer_)
res$con <- con
if (!is.null(a$nodata_value))
ignorevalue(res) <- ifelse(con$datatype %in% c(1L,11L,2L,12L,3L,13L)
,as.integer(a$nodata_value),a$nodata_value)
vrt <- vapour::vapour_vrt(fname)
vrt <- strsplit(vrt,split="\n")[[1]]
if (length(ind <- grep("CategoryName",vrt))) {
patt <- "\\s*<Category>(.+)</Category>$"
ca <- grep(patt,vrt[seq(ind[1],ind[2])],value=TRUE)
ca <- gsub(patt,"\\1",ca)
}
else
ca <- NULL
if (length(ind <- grep("ColorTable",vrt))) {
patt <- "\\s*<Entry c1=\"(\\d+)\" c2=\"(\\d+)\" c3=\"(\\d+)\" c4=\"(\\d+)\"\\s*/>"
ct <- vrt[seq(ind[1]+1L,ind[2]-1L)]
ct <- data.frame(c1=as.integer(gsub(patt,"\\1",ct))
,c2=as.integer(gsub(patt,"\\2",ct))
,c3=as.integer(gsub(patt,"\\3",ct))
,c4=as.integer(gsub(patt,"\\4",ct))
)
ct <- apply(ct,1,function(x) {
rgb(x[1],x[2],x[3],x[4],maxColorValue=255)
})
}
else
ct <- NULL
if (!is.null(ct)) {
if (!is.null(ca)) {
ct <- ct[seq(length(ca))]
}
names(ct) <- ca
}
else if (!is.null(ca)) {
ct <- rep(NA,length(ca))
names(ct) <- ca
}
else
ct <- character()
class(ct) <- "ursaColorTable"
patt <- "^\\s*<MDI key=\"Band_(\\d+)\">(.+)</MDI>$"
b <- vrt[grep(patt,vrt)]
if (!length(b))
bname <- paste("Band",seq_along(con$bands))
else
bname <- gsub(patt,"\\2",b)[as.integer(gsub(patt,"\\1",b))]
ursa_grid(res) <- g1
names(res) <- bname
ursa_colortable(res) <- ct
# if (!is.null(a$nodata_value))
# ignorevalue(res) <- a$nodata_value
class(res$value) <- ifelse(length(ct),"ursaCategory","ursaNumeric")
res
}
'.read_vapour' <- function(fname,resetGrid=TRUE,band=NULL
,engine=c("vapour"),verbose=FALSE,...) { ## ,...
if (engine=="vapour") {
# .elapsedTime("vapour -- step1")
if (F) {
ri <- vapour::vapour_raster_info(fname)
str(ri)
# .elapsedTime("vapour -- step5")
q()
}
a <- .open_vapour(fname,engine=engine,verbose=verbose)
# .elapsedTime("vapour -- step2")
if (inDetail <- TRUE) {
# .elapsedTime("vapour -- step3")
b <- vapour::gdal_raster_data(fname,bands=seq(a))
# print(is.raw(b[[1]]))
# .elapsedTime("vapour -- step4")
# if (ri$datatype %in% c("Byte","Int32","UInt32","Int64"))
if (a$con$datatype %in% c(1L,2L,3L,11L,12L,13L))
ursa_value(a) <- as.integer(do.call(cbind,b))
else
ursa_value(a) <- do.call(cbind,b)
# .elapsedTime("vapour -- step5")
}
else
ursa_value(a) <- vapour::gdal_raster_data(fname,bands=seq(a)) |> do.call(cbind,args=_)
if (resetGrid)
session_grid(a)
return(a)
}
NULL
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/package_vapour.R
|
##~ 'layout.label' <- function(...) .syn('panel_annotation',0,...)
## 'panel_annotation'??
'panel_annotation' <- function(...) {
if (.skipPlot(TRUE))
return(invisible(NULL))
arglist <- list(...)
if ((length(arglist))&&(is_spatial(arglist[[1]]))) {
obj <- spatial_transform(arglist[[1]],session_crs())
xy <- spatial_coordinates(spatial_centroid(obj))
da <- spatial_data(obj)
noLabel <- !ncol(da)
# if (noLabel)
# da <- data.frame(label=rep("*",nrow(xy)))
if (!noLabel)
da <- da[[1]]
return(invisible(lapply(seq_len(spatial_count(obj)),function(i) {
do.call(panel_annotation,c(x=xy[i,1],y=xy[i,2]
,label=if (noLabel) NULL else da[i]
,arglist[-1]))
})))
}
kwd <- "(caption|ann(otation)*)"
annotation <- .getPrm(arglist,name=kwd,default=TRUE)
if (!is.logical(annotation))
annotation <- TRUE
if (!annotation)
return(NULL)
label <- .getPrm(arglist,name="($|label|text)",kwd=kwd
,class=rev(c("expression","character","array","matrix"))
,default=expression()) ## expression(degree*C) ## "May"
if (!length(label))
return(NULL)
if ((!is.expression(label))&&(all(is.na(label))))
return(NULL)
# label <- .getPrm(arglist,name="label",kwd=kwd,default="May")
# font <- .getPrm(arglist,name="font",kwd=kwd,default=par("family"))
position <- .getPrm(arglist,name="pos(ition)*",kwd=kwd
,class=list("character","numeric"),default="topright")
cex <- .getPrm(arglist,name="cex",kwd=kwd,default=1.2-0.2)
adjust <- .getPrm(arglist,name="adj(ust)*",kwd=kwd,default=0.5)
fg <- .getPrm(arglist,name="fg",kwd=kwd,default="#000000AF")
bg <- .getPrm(arglist,name="bg",kwd=kwd,default=NA_character_)
fill <- .getPrm(arglist,name="fill",kwd=kwd,default=NA_character_)
buffer <- .getPrm(arglist,name="buf(fer)*",kwd=kwd,default=1)
lon <- .getPrm(arglist,name="lon(gitude)*",kwd=kwd,default=NA_real_)
lat <- .getPrm(arglist,name="lat(itude)*",kwd=kwd,default=NA_real_)
x <- .getPrm(arglist,name="x$",kwd=kwd,default=NA_real_)
y <- .getPrm(arglist,name="y$",kwd=kwd,default=NA_real_)
# font <- .getPrm(arglist,name="font",kwd=kwd,default=par("family"))
font <- .getPrm(arglist,name="font",kwd=kwd,default=getOption("ursaPngFamily"))
##~ vertical <- .getPrm(arglist,name="vert(ical)*"
##~ ,class=c("logical","numeric"),kwd=kwd,default=FALSE)
# vertical <- .getPrm(arglist,name="vert(ical)*",kwd=kwd,default=FALSE)
vertical <- .getPrm(arglist,name="vert(ical)*",kwd=kwd,default=0)
if (vertical==1)
vertical <- 90
alpha <- .getPrm(arglist,name="(alpha|transp(aren(cy)*)*)",kwd=kwd,default=1)
interpolate <- .getPrm(arglist,name="interp(olate)*",kwd=kwd,default=FALSE)
resample <- .getPrm(arglist,name="resample",kwd=kwd,default=FALSE)
verbose <- .getPrm(arglist,name="verb(ose)*",kwd=kwd,default=FALSE)
.panel_annotation(label=label,position=position,lon=lon,lat=lat,x=x,y=y
,cex=cex,adjust=adjust
,fg=fg,bg=bg,buffer=buffer,fill=fill
,font=font,vertical=vertical
,alpha=alpha,verbose=verbose)
}
'.panel_annotation' <- function(label=expression()#Omega^alpha)
,position="bottomright",lon=NA,lat=NA,x=NA,y=NA
,cex=1,adjust=0.5
,fg="#000000",bg="#FFFFFF1F",buffer=1,fill="#FFFFFF7F"
,font=par("family"),vertical=FALSE
,alpha=1,interpolate=FALSE,resample=FALSE
,verbose=FALSE,...) {
if (verbose)
str(list(label=label,position=position,cex=cex,adjust=adjust,fg=fg,bg=bg
,fill=fill,buffer=buffer,vertical=vertical,verbose=verbose))
opt <- par(family=font)
g1 <- getOption("ursaPngPanelGrid") # session_grid()
minx <- g1$minx
miny <- g1$miny
maxx <- g1$maxx
maxy <- g1$maxy
centerx <- 0.5*(minx+maxx)
centery <- 0.5*(miny+maxy)
device <- getOption("ursaPngDevice")
vadj0 <- if ((!is.null(device))&&(device=="windows")) 0.35 else 0.40
isPicture <- inherits(label,c("array","matrix"))
srt <- if (is.logical(vertical)) ifelse(vertical,90,0) else vertical
if (length(adjust)==2) {
vadj <- adjust[2]
adjust <- adjust[1]
}
else if (!isPicture) {
vadj <- ifelse(any(as.numeric(unlist(gregexpr("\\\n",label)))<0),vadj0,0.5)
}
if ((!anyNA(lon))&&(!anyNA(lat))) {
xy <- .project(cbind(lon,lat),g1$crs)
pos <- c((xy[1,1]-minx)/(maxx-minx),(xy[1,2]-miny)/(maxy-miny))
}
else if ((!is.na(x))&&(!is.na(y))) {
# if ((x<minx)||(x>maxx)||(y<miny)||(y>maxy))
# return(NULL)
pos <- c((x-minx)/(maxx-minx),(y-miny)/(maxy-miny))
}
else
pos <- position
# scale <- getOption("ursaPngScale")
if (F)
print(data.frame(cex=cex,par=par()$cex,retina=getOption("ursaPngRetina")
,pointsize=getOption("ursaPngPointsize"),default=12))
mycex <- cex/par()$cex#*getOption("ursaPngRetina")*getOption("ursaPngPointsize")/12
if (!isPicture)
if ((length(label)>1)&&(length(label)>=getOption("ursaPngLayout")$image))
label <- label[getOption("ursaPngFigure")]
isE <- is.expression(label)
if (!isPicture) {
if (!isE)
label <- paste(label,collapse="\n")
if (!nchar(label))
return(invisible(NULL)) ## 10L
}
if (is.factor(pos))
pos <- as.character(pos)
isCaption <- is.character(pos)
if (isCaption) {
pos <- switch(pos,center=c(0.5,0.5),top=c(0.5,1),bottom=c(0.5,0)
,left=c(0,0.5),right=c(1,0.5),topleft=c(0,1),topright=c(1,1)
,bottomleft=c(0,0),bottomright=c(1,0),{
message(sprintf("'%s' is invalid keyword",pos))
match.arg(pos,c("center","top","bottom","left","right"
,"topleft","topright"
,"bottomleft","bottomright"))
})
}
if (length(pos)==1)
pos <- c(1,1)
# print(pos)
if (!length(pos)) {
cat("Unable to detect position for annotation\n")
return(invisible(NULL))
}
if ((isCaption)&&(is.na(fill)))
fill <- "#FFFFFF7F"
if ((!isCaption)&&(is.na(bg)))
bg <- "#FFFFFF3F"
if (isPicture) {
sc <- getOption("ursaPngScale")
g2 <- if (is.numeric(sc)) regrid(g1,mul=sc,resample=resample) else g1
dima <- dim(label)
# nb <- length(dima) ## -- 20170919
nb <- dima[3] ## ++ 20170919
if (is.character(alpha)) {
alpha <- as.numeric(as.hexmode(alpha))/255
}
if (alpha>1)
alpha <- alpha/255
if (alpha<1) {
if (nb==3) {
label <- c(label,rep(alpha,prod(dima[1:2])))
dim(label) <- c(dima[1:2],nb+1)
}
else if (nb==4) {
label[,,4] <- label[,,4]*alpha
}
}
width <- dima[2]*g2$resx*cex
height <- dima[1]*g2$resy*cex
}
else {
height <- 1.5*strheight(paste0(label,"(Cjyp^~_)"),units="user",cex=mycex)
if (is.expression(label))
width <- strwidth(label,units="user",cex=mycex)+0.2*height
else
width <- strwidth(paste(label,"|",sep=""),units="user",cex=mycex)
}
if (vertical) {
.w <- width
width <- height
height <- .w*1.05
rm(.w)
}
# print(c(width=width,height=height))
coord <- c(NA,NA,NA,NA)
# rect(coord[1],coord[2],coord[3],coord[4],col="red")
coord[1] <- minx+pos[1]*(maxx-minx)-0.5*width
coord[2] <- miny+pos[2]*(maxy-miny)-0.5*height
coord[3] <- minx+pos[1]*(maxx-minx)+0.5*width
coord[4] <- miny+pos[2]*(maxy-miny)+0.5*height
if (coord[1]<minx)
{
coord[1] <- minx-ifelse(isE,width/3.5,0)
coord[3] <- coord[1]+width
}
if (coord[3]>maxx)
{
coord[3] <- maxx+ifelse(isE,0,0) ## ifelse(isE,width/3.5,0)
coord[1] <- coord[3]-width
}
if (coord[2]<miny)
{
coord[2] <- miny
coord[4] <- coord[2]+height
}
if (coord[4]>maxy)
{
coord[4] <- maxy-ifelse(isE,height/6,0) # ifelse(isE,height,0)
coord[2] <- coord[4]-height
}
# rect(coord[1],coord[2],coord[3],coord[4],col="#0000FF50")
if (isPicture) {
graphics::rasterImage(grDevices::as.raster(label,max=1)
,coord[1],coord[2],coord[3],coord[4]
,interpolate=interpolate)
par(opt)
return(invisible(NULL))
}
if (TRUE) { ## 20180625
if (adjust>=0.48)
adjust <- (adjust-0.5)*width/height+0.5
}
# print(c(scale=scale,cex=mycex))
x <- 0.5*(coord[1]+coord[3])
y <- 0.5*(coord[2]+coord[4])
x <- x+(adjust-0.5)*(coord[3]-coord[1])
if ((!is.na(fill))&&(is.character(fill))) ##(isCaption)
rect(coord[1],coord[2],coord[3],coord[4],border="transparent",col=fill)
if ((!is.na(bg))&&(is.character(bg))) ##(!isCaption)
{
if (verbose)
.elapsedTime("label:start")
sc <- getOption("ursaPngScale")
b <- buffer*sc
w <- seq(-b,b,length=ceiling(b)*2+1)*with(g1,sqrt(resx*resy))/sc
for (dx in w)
for (dy in w)
text(x=x+dx,y+dy,adj=c(adjust,vadj),label,cex=mycex,col=bg,srt=srt)
if (verbose)
.elapsedTime("label:finish")
}
if (verbose)
str(list(x=x,y=y,adj=c(adjust,vadj),labels=label,cex=mycex,col=fg,srt=srt))
text(x=x,y=y,adj=c(adjust,vadj),labels=label,cex=mycex,col=fg,srt=srt)
par(opt)
invisible(NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/panel_annotation.R
|
## http://www.soest.hawaii.edu/pwessel/gshhg/ 2.3.7 2017-06-15
## http://gis-lab.info/forum/viewtopic.php?t=22977
## http://thematicmapping.org/downloads/world_borders.php
##~ '.panel_coastline' <- function(
##~ coastline=TRUE,col="grey60",fill="transparent"
##~ ,detail=NA,density=NA,angle=NA,land=FALSE
##~ ,lwd=1,lty=1L,...) {
##~ NULL
##~ }
'compose_coastline' <- function(...) {
arglist <- list(...)
kwd <- "coast(line)*"
coastline <- .getPrm(arglist,name=paste0("(",kwd,"|decor)$")
,class=list("integer","logical"),default=TRUE)
if (any(!coastline)) {
res <- list(coast_xy=NULL)
class(res) <- "ursaCoastLine"
return(res)
}
res <- .getPrm(arglist,name=kwd,class="ursaCoastLine",default=NULL)
if (!is.null(res)) {
return(res)
}
res <- getOption("ursaPngCoastLine")
if (!is.null(res))
return(res)
bg <- sum(c(col2rgb(getOption("ursaPngBackground")))*c(0.30,0.59,0.11))
defcol <- ifelse(bg<128,"#FFFFFF3F","#0000003F") # grey60
col <- .getPrm(arglist,name="(col|line)",kwd=kwd,default=defcol)
fill <- .getPrm(arglist,name="fill",kwd=kwd,default="transparent")
detail <- .getPrm(arglist,name="detail",kwd=kwd,default=NA_character_)
density <- .getPrm(arglist,name="density",kwd=kwd,default=NA_real_)
angle <- .getPrm(arglist,name="angle",kwd=kwd,default=NA_real_)
land <- .getPrm(arglist,name="land",kwd=kwd,default=FALSE)
lwd <- .getPrm(arglist,name="lwd",kwd=kwd,default=0.5)
lty <- .getPrm(arglist,name="lty",kwd=kwd,default=1L)
fail180 <- .getPrm(arglist,name="fail180",kwd=kwd,default=NA)
obj <- .getPrm(arglist,name=paste0("(^$|",kwd,"$)") ## name="^$"
,class=list("character","matrix","SpatialPolygonsDataFrame","sf")#[-3]
,default=NULL)
verbose <- .getPrm(arglist,name="verbose",kwd=kwd,default=FALSE)
if (is.integer(coastline)) {
panel <- coastline
# coastline <- TRUE
}
else
panel <- 0L
invisible(.compose_coastline(obj=obj,panel=panel,col=col,fill=fill,detail=detail
,density=density,angle=angle
,land=land,lwd=lwd,lty=lty,fail180=fail180,verbose=verbose))
}
'.compose_coastline' <- function(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) {
if (verbose)
str(list(obj=obj,panel=panel,col=col,fill=fill,detail=detail
,density=density,angle=angle
,land=land,lwd=lwd,lty=lty,fail180=fail180))
g1 <- session_grid()
if (!is.null(obj)) {
isPoly <- inherits(obj,c("sf","SpatialPolygonsDataFrame"))
if ((is.matrix(obj))&&(ncol(obj)==2))
coast_xy <- obj
else if ((is.character(obj))||(isPoly)) {
if ((isPoly)||(.lgrep("\\.shp",obj))) {
if (isPoly)
a <- obj
else {
# a <- .shp.read(obj)
a <- spatialize(obj)#,engine="sp")
}
if (.isSP(a)) {
a <- lapply(methods::slot(a,grep("(polygons|lines)"
,methods::slotNames(a),value=TRUE)),function(x) {
y <- lapply(methods::slot(x,grep("(Polygons|Lines)"
,methods::slotNames(x),value=TRUE)),function(y) {
do.call("rbind",lapply(list(sp::coordinates(y),cbind(NA,NA))
,matrix,ncol=2))
})
do.call("rbind",lapply(y,matrix,ncol=2))
})
coast_xy <- head(do.call("rbind",lapply(a,matrix,ncol=2)),-1)
rm(a)
}
else if (.isSF(a)) {
if (.lgrep("^multi",spatial_shape(a))) {
a <- do.call("rbind",lapply(spatial_coordinates(a),function(x) {
do.call("rbind",lapply(unlist(x,recursive=FALSE),rbind,cbind(NA,NA)))
}))
}
else {
a <- do.call("rbind",lapply(spatial_coordinates(a),function(x) {
do.call("rbind",lapply(x,rbind,cbind(NA,NA)))
}))
}
coast_xy <- head(a,-1)
rm(a)
}
}
else if (.lgrep("\\.rds$",obj)) {
g1 <- session_grid()
coast_xy <- readRDS(obj)
if (nchar(g1$crs)) {
# b <- attributes(coast_xy)
coast_xy <- .project(coast_xy,g1$crs)
# attributes(coast_xy) <- b
}
}
else
coast_xy <- NULL
}
if (!is.null(coast_xy))
{
shadow <- unname(col2rgb(fill,alpha=TRUE)[4,1])
options(ursaPngShadow=ifelse(shadow %in% c(0,255),"",fill))
res <- list(coast_xy=coast_xy,grid=g1,detail=detail,panel=panel
,col=col,fill=fill,shadow=shadow,land=land
,density=density,angle=angle,lwd=lwd,lty=lty)
class(res) <- "ursaCoastLine"
options(ursaPngCoastLine=res)
return(res)
}
}
isLongLat <- .lgrep("(\\+proj=longlat|epsg:4326)",g1$crs)>0
isMerc <- .lgrep("\\+proj=merc",g1$crs)>0
isCea <- .lgrep("\\+proj=cea",g1$crs)>0
isUTM <- .lgrep("\\+proj=utm",g1$crs)>0
proj <- g1$crs
if ((is.list(proj))&&("input" %in% names(proj)))
proj <- proj[["input"]]
proj <- proj[nchar(proj)==max(nchar(proj))]
if ((any(is.na(proj)))||(nchar(proj)==0))
return(NULL)
isDetail <- !is.na(detail)
if (is.na(detail))
detail <- "l"
if (!(detail %in% c("l","i","h","f",NA)))
message(paste("coastline detail:",detail))
if ((FALSE)&&(.lgrep("proj=(merc|longlat)",proj))&&((g1$maxx<=20037508))) {
if (detail %in% c("f"))
detail <- "h180"
else
detail <- paste0(detail,"180")
}
if (FALSE)
{
g2 <- with(g1,my.expand.grid(x=seq(minx,maxx,length=16)
,y=seq(miny,maxy,length=16)))
ll <- .project(with(g2,cbind(x,y)),g1$crs,inv=TRUE)
if (all(ll[,2]<65))
return(NULL)
}
fpath <- getOption("ursaRequisite")
# if (!nchar(fpath))
# fpath <- system.file("requisite",package="ursa")
if (!is.na(detail)) {
fname <- file.path(fpath,paste0("coast-",detail,".rds"))
if (!file.exists(fname)) {
detail <- "l"
fname <- file.path(fpath,paste0("coast-",detail,".rds"))
if (!file.exists(fname))
fname <- system.file("requisite/coast-l.rds",package="ursa")
}
xy <- readRDS(fname)
}
else {
stop("Detalization level is unknown")
# xy <- readRDS("C:/platt/shapefile/auxiliary/thematicmapping.org/countries.rds")
}
coast_xy <- cbind(lon=xy[,1],lat=xy[,2])
ind <- .grep("^\\d+$",proj)
# isLoaded <- .lgrep("package:rgdal",search())>0
isLoaded <- "rgdal" %in% loadedNamespaces()
if (length(ind))
{
proj4 <- "" ## was NA
try(proj4 <- get(paste0("epsg",proj[ind])))
if (!nchar(proj4))
{
if (!isLoaded)
requireNamespace(ifelse(.isPackageInUse(),"sf","rgdal")
,quietly=.isPackageInUse())
proj4 <- .rgdal_CRSargs(sp::CRS(sprintf("+init=epsg:%s",proj[ind])))
}
else if (!isLoaded) {
if (!requireNamespace("proj4",quietly=.isPackageInUse()))
requireNamespace(ifelse(.isPackageInUse(),"sf","rgdal")
,quietly=.isPackageInUse())
}
}
else
{
if (!isLoaded) {
if (!("sf" %in% loadedNamespaces())) {
if (!requireNamespace("proj4",quietly=.isPackageInUse()))
requireNamespace(ifelse(.isPackageInUse(),"sf","rgdal")
,quietly=.isPackageInUse())
}
}
proj4 <- paste(proj,collapse=" ")
}
if ((!isLongLat)&&(!isMerc)) {
lat0 <- .gsub("^.*\\+lat_[012]=(\\S+)\\s.*$","\\1",proj4)
if (lat0==proj4) {
# lat0 <- .gsub("^.*\\+lat_ts=(\\S+)\\s.*$","\\1",proj4)
if (lat0==proj4) {
epsg <- .gsub("^.+init=epsg:(\\d+).*$","\\1",proj4)
if ((epsg==proj4))
lat0 <- NA
else {
epsg <- as.integer(epsg)
if (epsg %in% c(3411,3413,3408,3571:3576,6931,6973))
lat0 <- 90
else if (epsg %in% c(3409,6932,6974,3412,3976))
lat0 <- -90
else
lat0 <- NA
}
}
else
lat0 <- as.numeric(lat0)
}
else
lat0 <- as.numeric(lat0)
}
else
lat0 <- NA
ant_xy <- NULL
ind <- attr(xy,"antarctic")
if (!is.null(ind))
indS <- which(abs(coast_xy[ind,2])<(85.0-1e-3))
if (!isLongLat) {
# indNA <- which(is.na(coast_xy[,1]) | is.na(coast_xy[,2]))
coast_xy <- .project(coast_xy,proj4)
isInf <- any(is.infinite(coast_xy))
if (isInf) {
shadow <- unname(col2rgb(fill,alpha=TRUE)[4,1]) # if (shadow!=0)
# coast_xy[indNA,] <- NA
indI <- which(is.infinite(coast_xy[,1]) | is.infinite(coast_xy[,2]))
coast_xy[indI,] <- NA
if (dev <- TRUE) {
ind <- NULL ## drop Antarctic
# coast_xy <- coast_xy[500:600,]
ind1 <- as.integer(!is.na(coast_xy[,1]) & !is.na(coast_xy[,2]))
# print(c(ind=ind))
ind2 <- cumsum(ind1)
# print(ind2)
ind3 <- which(duplicated(ind2))
# print(ind3)
ind4 <- diff(ind3)
# print(ind4)
ind5 <- which(ind4==1)
# print(ind5)
ind6 <- ind3[ind5]
coast_xy <- coast_xy[-ind6,]
if (dev2 <- TRUE) {
if (anyNA(coast_xy[nrow(coast_xy),]))
coast_xy <- head(coast_xy[,1:2],-1)
ind7 <- which(is.na(coast_xy[,1]) | is.na(coast_xy[,2]))
ind7a <- c(1,ind7+1L)
ind7b <- c(ind7-1L,nrow(coast_xy))
ind8 <- NULL
for (i in sample(seq_along(ind7a))) {
ind9 <- ind7a[i]:ind7b[i]
xy <- coast_xy[ind9,,drop=FALSE]
if (nrow(xy)==1)
ind8 <- c(ind8,c(ind9,tail(ind9,1)+1L))
# print(all(abs(head(xy,1)-tail(xy,1))<1e-11))
}
if (length(ind8))
coast_xy <- coast_xy[-ind8,]
}
# print(coast_xy)
## for detail=="l": [7720,] [8897,]
# q()
}
else {
res <- list()
class(res) <- "ursaCoastLine"
options(ursaPngCoastLine=res)
return(res)
}
}
}
if (!is.null(ind)) {
if ((is.na(lat0))||(lat0<=0)) {
ant_xy <- coast_xy[ind,]
if (length(indS))
ant_xy <- ant_xy[indS,]
}
ind <- c(head(ind,1)-1,ind)
coast_xy <- coast_xy[-ind,]
}
isMerc <- isMerc | isCea
if (is.na(fail180))
fail180 <- (isMerc || isLongLat)
if ((fail180)||(isLongLat || isMerc)) {
if (!isLongLat) {
lon0 <- as.numeric(.gsub(".*\\+lon_0=(\\S+)\\s*.*","\\1",proj4))
B <- mean(abs(.project(rbind(cbind(lon0-180+1e-9,-45),cbind(lon0+180-1e-9,+45))
,proj4)[,1]))
}
else
B <- 180
if (isMerc) {
# B <- .getMajorSemiAxis(proj4)*pi
# B <- 7720000
'.shift' <- function(seg) {
# if (all(seg[,2]>0)) ## debug Chukotka vs
# return(NULL)
j <- which(abs(diff(seg[,1]))>B)
if (!length(j))
return(NULL)
# plot(seg[,1],seg[,2],type="l")
# abline(v=c(-B,B),lty=2)
center <- sign(mean(seg[,1]))
j1 <- c(1,j+1)
j2 <- c(j,nrow(seg))
if (center<0)
k <- which(seg[j1,1]>0.9*B)
else
k <- which(seg[j1,1]<=(-0.9*B))
# da <- data.frame(j1=j1,j2=j2,center=center,s=0,seg=seg[j1,1])
# da2 <- apply(da,1,function(x) range(seg[x["j1"]:x["j2"],1]))
# da$s <- -sign(da$seg)
# da$min <- da2[1,]
# da$max <- da2[2,]
# print(da)
# print(da[k,])
if (TRUE) { ## added 20180207
nr <- length(j1)
if ((1 %in% k)&&(!(nr %in% k)))
k <- c(k,nr)
else if ((nr %in% k)&&(!(1 %in% k)))
k <- c(1,k)
}
j1k <- j1[k]
j2k <- j2[k]
# print(data.frame(j1=j1,j2=j2,center=center,seg=seg[j1,1]))
if (center<0) {
for (m in seq_along(j1k))
seg[j1k[m]:j2k[m],1] <- seg[j1k[m]:j2k[m],1]-2*B
}
else {
for (m in seq_along(j1k))
seg[j1k[m]:j2k[m],1] <- seg[j1k[m]:j2k[m],1]+2*B
}
# for (m in c(1))
# seg[j1[m]:j2[m],1] <- seg[j1[m]:j2[m],1]-2*B
# da <- data.frame(j1=j1,j2=j2,center=center,seg=seg[j1,1])
# da2 <- apply(da,1,function(x) range(seg[x["j1"]:x["j2"],1]))
# da$min2 <- da2[1,]
# da$max2 <- da2[2,]
# print(da)
# print(summary(seg))
# plot(seg[,1],seg[,2],type="l")
# abline(v=c(-B,B),lty=2)
seg
}
if ((TRUE)||(g1$minx<(-B))||(g1$maxx>(+B))) {
ind <- which(is.na(coast_xy[,1]))
ind1 <- c(1,ind+1)
ind2 <- c(ind-1,nrow(coast_xy))
for (i in seq(length(ind1))) {
if (ind1[i]>ind2[i])
next
# if (nrow(coast_xy[ind1[i]:ind2[i],])<1e3) ## debug
# next
seg <- .shift(coast_xy[ind1[i]:ind2[i],])
if (is.null(seg))
next
# str(seg)
# if (nrow(seg)<1e3)
# next
# message("-----")
# str(seg)
# print(summary(coast_xy[ind1[i]:ind2[i],]))
# print(summary(seg))
# message("=====")
# if (nrow(seg)<1e3)
# next
# print(c(i=i,ind1=ind1[i],ind2=ind2[i]))
coast_xy[ind1[i]:ind2[i],] <- seg
}
if (!is.null(ant_xy)) {
seg <- .shift(ant_xy)
if (!is.null(seg))
ant_xy <- seg
}
}
}
cond1 <- g1$minx<(-B*(169.2/180)) ## east boarder of Eurasia
cond2 <- g1$maxx>(+B)
if (cond1) {
if (verbose)
print("expand to the West")
opp1 <- coast_xy
opp1[,1] <- opp1[,1]-2*B
if (!is.null(ant_xy)) {
if (FALSE) {
opp1a1 <- opp1a2 <- ant_xy[-nrow(ant_xy),]
opp1a1[,1] <- opp1a1[,1]-4*B
opp1a2[,1] <- opp1a2[,1]-2*B
opp1a <- rbind(opp1a1,c(NA,NA),opp1a2)
rm(opp1a1,opp1a2)
}
else {
opp1a <- ant_xy[-1,]
opp1a[,1] <- opp1a[,1]-2*B
}
}
}
if (cond2) {
if (verbose)
print("expand the East")
opp2 <- coast_xy
opp2[,1] <- opp2[,1]+2*B
if (!is.null(ant_xy)) {
opp2a <- ant_xy[-1,]
opp2a[,1] <- opp2a[,1]+2*B
}
}
if (cond1) {
coast_xy <- rbind(coast_xy,c(NA,NA),opp1)
if (!is.null(ant_xy))
ant_xy <- rbind(opp1a,ant_xy)
}
if (cond2) {
coast_xy <- rbind(coast_xy,c(NA,NA),opp2)
if (!is.null(ant_xy))
ant_xy <- rbind(ant_xy,opp2a)
}
}
if (any(is.na(coast_xy[1,])))
coast_xy <- coast_xy[-1,]
n <- nrow(coast_xy)
if (any(is.na(coast_xy[n,])))
coast_xy <- coast_xy[-n,]
if (!is.null(ant_xy)) {
if ((isLongLat)||(isMerc)) {
ant1 <- ant_xy[1,]
ant2 <- ant_xy[nrow(ant_xy),]
ant1[2] <- g1$miny-g1$resy
ant2[2] <- ant1[2]
ant_xy <- rbind(ant1,ant_xy,ant2,ant1)
rownames(ant_xy) <- NULL
if (FALSE) { ## non-reproducible code for non-author
plot(0,0,xlim=range(c(coast_xy[,1],ant_xy[,1]),na.rm=TRUE),
,ylim=range(c(coast_xy[,2],ant_xy[,2]),na.rm=TRUE),type="n")
polypath(coast_xy[,1],coast_xy[,2],col="red")
polypath(ant_xy[,1],ant_xy[,2],col="green")
stop("")
}
}
coast_xy <- rbind(coast_xy[,1:2],c(NA,NA),ant_xy[,1:2])
}
if (!.isPackageInUse())
print(c(detail=detail))
if (!isDetail) {
inside <- with(g1,coast_xy[,1]>=minx & coast_xy[,1]<=maxx &
coast_xy[,2]>=miny & coast_xy[,2]<=maxy)
inside <- any(na.omit(unique(inside)))
if (inside) {
area <- with(g1,max(maxx-minx,maxy-miny))
# if (grepl("\\+units=km",g1$crs))
# area <- area*1e3
if (isLongLat)
area <- area*111
else
area <- area/ifelse(grepl("\\+units=km",g1$crs),1,1000)
if (area<=(-10))
return(NULL)
else if (area<=100)
detail <- "f"
else if (area<=500)
detail <- "h"
else if (area<=3000)
detail <- "i"
else
detail <- "l"
if (detail!="l") {
fname <- file.path(fpath,paste0("coast-",detail,".rds"))
if (file.exists(fname)) {
if (FALSE) {
arglist <- list(...)
ind <- .grep("detail",names(arglist))
if (length(ind))
arglist[[ind]] <- detail
else
arglist$detail <- detail
return(do.call("compose_coastline",arglist))
}
else {
arglist <- as.list(match.call()) ## try mget(names(match.call())[-1])
arglist$detail <- detail
return(do.call(as.character(arglist[[1]]),arglist[-1]))
}
}
}
}
}
# ind <- which(coast_xy[,2]<(-68))
# print(summary(coast_xy[ind,1]))
shadow <- unname(col2rgb(fill,alpha=TRUE)[4,1])
options(ursaPngShadow=ifelse(shadow %in% c(0,255),"",fill))
res <- list(coast_xy=coast_xy,grid=g1,detail=detail,panel=panel,col=col,fill=fill
,shadow=shadow,land=land,density=density,angle=angle,lwd=lwd,lty=lty)
class(res) <- "ursaCoastLine"
options(ursaPngCoastLine=res)
res
}
'panel_coastline' <- function(...) {
if (.skipPlot(TRUE))
return(NULL)
arglist <- list(...)
kwd <- "coast(line)*"
isWeb <- getOption("ursaPngWebCartography")
if (!is.logical(isWeb))
isWeb <- FALSE
coastline <- .getPrm(arglist,name=paste0("^(",kwd,"|decor)$")
,class=list("integer","logical","ursaCoastLine")[1:2]
,default=TRUE,verbose=FALSE)
##~ decor <- .getPrm(arglist,name="^decor$"
##~ ,class=list("integer","logical","ursaCoastLine")[1:2]
##~ ,default=TRUE,verbose=FALSE)
##~ coastline <- .getPrm(arglist,name=paste0("^",kwd,"$")
##~ ,class=list("integer","logical","ursaCoastLine")[1:2]
##~ ,default=,verbose=FALSE)
##~ str(arglist)
##~ print(c(coast=coastline,web=isWeb))
##~ q()
##~ if (inherits(coastline,"ursaCoastLine")) {
##~ obj <- coastline
##~ coastline <- TRUE
##~ isFound <- TRUE
##~ }
##~ else
##~ isFound <- FALSE
if (!coastline)
return(NULL)
g1 <- session_grid()
# if (!isFound)
obj <- .getPrm(arglist,class="ursaCoastLine",default=NULL)
figure <- getOption("ursaPngFigure")
if ((!is.logical(coastline))&&(figure!=coastline))
return(NULL)
if (is.null(obj)) {
obj <- getOption("ursaPngCoastLine")
if (!is.null(obj)&&(any(obj$panel))&&(!(figure %in% obj$panel)))
return(NULL)
if ((is.null(obj))||(!identical(g1,obj$grid))) {
options(ursaPngCoastLine=NULL)
obj <- compose_coastline(...)
}
else {
detail <- .getPrm(arglist,name="detail",kwd=kwd,default=obj$detail)
if (!identical(detail,obj$detail)) {
options(ursaPngCoastLine=NULL)
obj <- compose_coastline(...)
}
}
}
if ((any(obj$panel))&&(!(figure %in% obj$panel)))
return(NULL)
if (is.null(obj$coast_xy))
return(NULL)
if (!FALSE) {
obj$col <- .getPrm(arglist,name="col",kwd=kwd,default=obj$col)
obj$fill <- .getPrm(arglist,name="fill",kwd=kwd,default=obj$fill)
obj$density <- .getPrm(arglist,name="density",kwd=kwd,default=obj$density)
obj$angle <- .getPrm(arglist,name="angle",kwd=kwd,default=obj$angle)
obj$land <- .getPrm(arglist,name="land",kwd=kwd,default=obj$land)
obj$lwd <- .getPrm(arglist,name="lwd",kwd=kwd,default=obj$lwd)
obj$lty <- .getPrm(arglist,name="lty",kwd=kwd,default=obj$lty)
}
verbose <- .getPrm(arglist,name="verbose",kwd=kwd,default=FALSE)
.panel_coastline(obj,verbose=verbose)
}
'.panel_coastline' <- function(obj,verbose=FALSE) {
with(obj,{
shadow <- unname(col2rgb(fill,alpha=TRUE)[4,1])
if (verbose)
str(list(col=col,fill=fill,shadow=shadow,detail=detail
,density=density,angle=angle,land=land,lwd=lwd,lty=lty))
if ((TRUE)&&(shadow==0)|| ## 20171214 changed 'shadow!=255'
((!is.na(angle[1]))&&(!is.na(density[1])))) ## more quick
{
# op <- par(usr=par()$usr-c(0,125000,0,125000))
# print(par()$usr)
if ((is.na(angle[1]))||(is.na(density[1]))) {
if (inherits(coast_xy,"SpatialPolygonsDataFrame"))
plot(coast_xy,border=col,col=fill,lwd=lwd,add=TRUE)
else {
polygon(coast_xy[,1],coast_xy[,2],border=col,col=fill,lwd=lwd)
}
}
else {
for (an in angle) {
# print(str(list(angle=an,border=col,col=fill,density=density,lwd=lwd)))
polygon(coast_xy[,1],coast_xy[,2],border=col,col=fill
,density=density,angle=an,lwd=lwd)
}
}
# par(op)
}
else
{
if (inherits(coast_xy,"SpatialPolygonsDataFrame"))
plot(coast_xy,border=col,col=fill,lwd=lwd
,usePolypath=TRUE,rule=c("winding","evenodd")[2],add=TRUE)
else if (!all(is.na(c(coast_xy)))) {
if (land)
{
g1 <- session_grid()
x <- with(g1,c(minx,minx,maxx,maxx,minx)+c(-1,-1,1,1,-1)*resx)
y <- with(g1,c(miny,maxy,maxy,miny,miny)+c(-1,1,1,-1,-1)*resy)
coast_xy <- rbind(cbind(x,y),c(NA,NA),coast_xy)
}
## ?polypath: Hatched shading (as implemented for polygon()) is not (currently) supported.
## if semi-opacity|trasparency them 'polygon' else fill is transparent
polypath(coast_xy[,1],coast_xy[,2],border=col,col=fill
,rule=c("winding","evenodd")[2],lwd=lwd) ##,density=15??
}
}
})
invisible(NULL)
}
'update_coastline' <- function(merge=TRUE) {
missedSF <- !requireNamespace("sf",quietly=TRUE)
if (missedSF)
stop("Suggested package 'sf' is required for this operation")
# missedLW <- !requireNamespace("lwgeom",quietly=TRUE)
# if (missedLW)
# stop("Suggested package 'lwgeom' is required for this operation")
dpath <- getOption("ursaRequisite")
ftemp <- tempfile(tmpdir=dpath)
opW <- options(warn=-1)
res <- .try(writeLines("1",ftemp))
options(opW)
if (res)
file.remove(ftemp)
else
stop("Unable to update 'requisite' directory for package")
verbose <- !.isPackageInUse()
if (!verbose)
merge <- TRUE
if (FALSE) {
toUnloadMethods <- !("methods" %in% .loaded())
.require("methods",quietly=!verbose)
}
else
toUnloadMethods <- FALSE
# src <- "http://data.openstreetmapdata.com/simplified-land-polygons-complete-3857.zip" ## (depredated)
src <- "https://osmdata.openstreetmap.de/download/simplified-land-polygons-complete-3857.zip"
dst <- .ursaCacheDownload(src,mode="wb",quiet=FALSE)
list1 <- unzip(dst,exdir=tempdir())
a <- sf::st_read(list1[.grep("\\.shp$",basename(list1))],quiet=TRUE)
file.remove(list1)
if (verbose)
n <- nrow(a)
aG <- sf::st_geometry(a)
# sf::st_geometry(a) <- NULL
# a <- sf::st_sf(data.frame(FID=as.integer(a$FID)),geometry=aG)
spatial_data(a) <- data.frame(FID=as.integer(a$FID))
.elapsedTime("reading - done")
FID <- a$FID
prj1 <- spatial_crs(a)
lon0 <- 120
# prj1 <- spatial_proj4(a) ## commented this 'x'-line after 'x-2' line assign
prj2 <- .gsub("(^.+)(\\s\\+lon_0=)(\\d+(\\.\\d+)*)(\\s.+$)"
,paste0("\\1\\2",lon0,"\\5"),prj1)
if (merge) {
aG <- sf::st_transform(aG,crs=4326)
cross180 <- NULL
if (verbose)
pb <- ursaProgressBar(min=0,max=n,tail=TRUE)
for (i in sample(seq_along(FID))) {
fid <- FID[i]
bG <- lapply(aG[[i]],function(x) which(abs(x[,1])>180-1e-11))
if (verbose)
setUrsaProgressBar(pb)
if (!sum(sapply(bG,length)))
next
cross180 <- c(cross180,fid)
}
if (verbose)
close(pb)
a180 <- subset(a,FID %in% cross180)
sf::st_agr(a180) <- "constant"
# spatial_write(a180,"a180.sqlite")
c180 <- sf::st_transform(sf::st_centroid(a180),crs=4326)
g180 <- do.call("rbind",lapply(lapply(sf::st_geometry(c180),unclass)
,matrix,ncol=2))
sf::st_geometry(c180) <- NULL
c180 <- data.frame(c180,lon=g180[,1],lat=g180[,2],area=spatial_area(a180)*1e-6)
if (verbose) {
print(c180)
print(nrow(c180))
}
p1 <- c180$FID[c180$lat>52.0 & c180$lat<67.0] # Chukotka
p2 <- c180$FID[c180$lat>71.0 & c180$lat<71.5] # Wrangel
p3 <- c180$FID[c180$lat>(-17.0) & c180$lat<(-16.7)] # Taveuni (south)
p4 <- c180$FID[c180$lat>(-16.55) & c180$lat<(-16.45)] # Rabi (center)
p5 <- c180$FID[c180$lat>(-16.65) & c180$lat<(-16.55) |
c180$lat>(-16.3) & c180$lat<(-16.0)] # Labasa (top MANUAL)
pair <- list(Chukotka=p1,Wrangel=p2,Taveuni_S=p3,Rabi_M=p4,Labasa_N=p5)
pname <- names(pair)
if (verbose) {
print(pair)
if (FALSE) {
a180 <- subset(a180,FID %in% c180$FID[abs(c180$lat)<=20])
if (FALSE)
spatial_write(sf::st_transform(a180,prj2),"cross180.sqlite")
}
}
if ((!.isPackageInUse())&&(devel <- F)) {
a5 <- subset(a,FID %in% pair[[2]])
message("writing `wrangel_fail.sqlite`")
spatial_write(spatial_transform(a5,3571),"wrangel_fail.sqlite")
q()
##~ a5 <- spatial_union(a5)
##~ str(a5)
##~ glance(a5,resetProj=TRUE)
##~ q()
}
a180 <- vector("list",length(pair))
if (devel3 <- TRUE) {
# pair <- pair[2]
for (i in seq_along(pair)) {
fid5 <- pair[[i]]
a180[[i]] <- subset(a,FID %in% fid5)
a0 <- spatialize(a180[[i]],resetProj=TRUE)
# a0 <- spatialize(subset(a,FID %in% fid5),style="merc",lon0=180)
# print(spatial_crs(a0))
# spatial_write(a0,"wrangel_fail.sqlite")
# str(a0)
# print(spatial_area(a0))
a1 <- spatial_union(a0)
a1 <- sf::st_cast(a1,"MULTIPOLYGON")
# str(a1)
# cat("------------\n")
# str(spatial_geometry(a1)[[1]])
ng <- length(spatial_geometry(a1)[[1]])
# str(ng)
# cat("------------\n")
if (ng>1)
next
spatial_data(a1) <- data.frame(FID=65000L+i)
a180[[i]] <- sf::st_transform(a1,prj1)
# print(spatial_area(a1))
# print(spatial_count(a2))
# glance(a2,resetGrid=TRUE,decor=FALSE)
}
# cat("===============\n")
}
for (i in seq_along(pair)) {
if (spatial_count(a180[[i]])==1)
next
a0 <- a180[[i]]
# fid5 <- pair[[i]]
# a0 <- spatial_transform(subset(a,FID %in% fid5),3571)
a0 <- spatial_transform(a0,3571)
xy0 <- spatial_coordinates(a0)
if (devel6 <- F) {
if (i==4) {
str(xy0)
p <- unlist(xy0,recursive=FALSE)
str(p)
saveRDS(p,"tmp2.rds")
q()
}
}
xy1 <- head(xy0[[1]][[1]],-1)
xy2 <- head(xy0[[2]][[1]],-1)
d1 <- .dist2(xy1,xy2,verbose=FALSE,summarize=FALSE)
order1 <- order(d1$dist,xy1[,1])[1:2]
ind1 <- d1$ind[order1]
d2 <- .dist2(xy2,xy1,verbose=FALSE,summarize=FALSE)
order2 <- order(d2$dist,xy2[,1])[1:2]
ind2 <- d2$ind[order2]
if (ind2[1]>ind2[2]) { ## 10 9
# print("ind2A")
xy1 <- xy1[c(ind2[1]:nrow(xy1),1L:ind2[2]),]
}
else if (ind2[1]>1) { ## 9 10
# print("ind2B")
xy1 <- xy1[c(ind2[1]:1L,nrow(xy1):ind2[2]),]
}
else if (ind2[2]>2) {
# print("ind2C")
}
else {
xy1 <- xy1[c(tail(seq(nrow(xy1)),-1),head(seq(nrow(xy1)),1)),]
# print("ind2D")
}
if (ind1[1]>ind1[2]) { ## 10 9
# print("ind1A")
xy2 <- xy2[c(ind1[1]:nrow(xy2),1L:ind1[2]),]
}
else if (ind1[1]>1) { ## 9 10
# print("ind1B")
xy2 <- xy2[c(ind1[1]:1L,nrow(xy2):ind1[2]),]
}
else if (ind1[2]>2) {
# print("ind1C")
}
else {
xy2 <- xy2[c(tail(seq(nrow(xy2)),-1),head(seq(nrow(xy2)),1)),]
# print("ind1D")
}
ind3 <- .dist2(xy1[range(seq(nrow(xy1))),],xy2[range(seq(nrow(xy2))),]
,verbose=FALSE,summarize=FALSE)$ind
xy7 <- rbind(if (T) xy1 else head(xy1,-1)
,if (ind3[1]>ind3[2]) xy2
else xy2[order(seq(nrow(xy2)),decreasing=TRUE),]
)
xy7 <- xy7[c(which(!duplicated(xy7))),]
xy7 <- xy7[c(seq(nrow(xy7)),1),]
if (mean(xy1[,1])<0) {
xy0[[1]][[1]] <- xy7
xy0[2] <- NULL
}
else {
xy0[[2]][[1]] <- xy7
xy0[1] <- NULL
}
a7 <- sf::st_sfc(GOMER=sf::st_polygon(xy0[[1]]),crs=spatial_crs(a0))
spatial_data(a7) <- data.frame(FID=65000L+i)
a180[[i]] <- sf::st_transform(a7,prj1)
}
if (devel10 <- F) {
a2 <- do.call(spatial_bind,a180)
g1 <- session_grid(c(360,400))
compose_open(length(pair),fix=TRUE)
for (i in seq_along(pair)) {
a2 <- spatialize(a180[[i]],resetProj=TRUE)
g3 <- consistent_grid(spatial_grid(a2),ref=g1)
session_grid(g3)
panel_new("white")
panel_plot(a2,lwd=1)
}
compose_close()
q()
}
.elapsedTime("spliting - done")
if (F) {
a180 <- spatial_bind(a180)
a180 <- spatialize(a180,style="merc",lon0=180)
str(a180)
spatial_write(a180,"wrangel_fail.sqlite")
q()
}
a <- list(subset(a,!(FID %in% unlist(pair))))
a <- do.call("rbind",c(a,a180))
.elapsedTime("merging - done")
# spatial_write(do.call(spatial_bind,a180),"tmp1.sqlite")
}
if (devel2 <- FALSE) {
sf::sf_use_s2(TRUE)
print("D")
a3 <- sf::st_area(a)
print("A")
str(a3)
str(attr(a3,"units"))
# u <- attr(a3,"units")$numerator
a1 <- sf::st_transform(a,crs=4326)
print("B")
a2 <- sf::st_area(a1)
print("C")
str(a2)
q()
}
sf::sf_use_s2(FALSE) ## ++ 20220125
pArea <- sf::st_area(sf::st_transform(a,crs=4326))
# pArea <- as.numeric(units::set_units(pArea,km^2))
u <- attr(pArea,"units")$numerator
m <- rep(1,length(u))
for (i in seq_along(u)) {
if (u[i]=="m")
m[i] <- 1/1000
else
stop(u[i])
}
pArea <- as.numeric(pArea)*prod(m)
.elapsedTime("area calculation - done")
res <- sapply(c("l","i","h","f"),function(x) .update_coastline(a,pArea,merge,x))
if ((toUnloadMethods)&&("package:methods" %in% search())) {
detach("package:methods",unload=FALSE)
}
res
}
'.update_coastline' <- function(a,pArea,merge,detail=c("l","i","h","f")) {
detail <- match.arg(detail)
verbose <- !.isPackageInUse()
thL <- switch(detail,l=12,i=3.5,h=1,f=0,stop("unable set length"))
thA <- (0.5*thL)^2
if (thA>0) {
ind <- which(pArea<thA)
if (length(ind))
a <- a[-ind,]
}
if (thL>0) {
a <- sf::st_simplify(a,dTolerance=thL*1e3,preserveTopology=TRUE)
}
.elapsedTime(paste0(detail,": simplifying - done"))
a <- sf::st_transform(a,crs=4326)
g1 <- sf::st_geometry(a)
k <- 0
for (i in seq_along(g1)) {
g2 <- g1[[i]]
for (j in seq_along(g2)) {
g3 <- g2[[j]]
if (!is.list(g3))
g3 <- list(g3)
for (j in seq_along(g3)) {
k <- k+1L
}
}
}
xy <- vector("list",k)
k <- 0
for (i in seq_along(g1)) {
g2 <- g1[[i]]
for (j in seq_along(g2)) {
g3 <- g2[[j]]
if (!is.list(g3))
g3 <- list(g3)
for (m in seq_along(g3)) {
g4 <- g3[[m]]
isATA <- try(as.integer(any(g4[,2]<(-84.9))))
if (isATA) {
a$FID[i] <- -abs(a$FID[i])
if (verbose)
print(c('Antarctida FID'=a$FID[i])) # Antarctida 43705
}
k <- k+1
if (isATA) {
indX <- which(abs(g4[,1])>180-1e-3)
indY <- which(abs(g4[,2])>85-1e-3)
ind2 <- na.omit(match(indY,indX))
if (length(ind2)) {
ind2 <- ind2[1L]-1L
g4 <- head(g4,-1L)
g4 <- unname(rbind(tail(g4,-ind2),head(g4,ind2)))
g4 <- rbind(g4,head(g4,1L))
}
}
else if (any(g4[,1]>(+175)) && any(g4[,1]<(-175))) {
ind3 <- which(g4[,1]>=(-180) & g4[,1]<=(-120))
g4[ind3,1] <- g4[ind3,1]+360
}
xy[[k]] <- rbind(cbind(g4,isATA),c(NA,NA,NA))
}
}
}
ind <- which(sapply(xy,function(x) is.null(x)))
if (length(ind))
xy <- xy[-ind]
xy <- do.call("rbind",lapply(xy,I))
xy <- xy[-nrow(xy),]
indA <- which(xy[,3]>0)
colnames(xy) <- c("lon","lat","spole")
if (TRUE)
xy <- xy[,1:2]
if (length(indA))
attr(xy,"antarctic") <- indA
indP <- which(xy[,2]<(-84.99))
if (length(indP))
attr(xy,"south_pole") <- indP
.elapsedTime(paste0(detail,": coercing - done"))
if (merge)
saveRDS(xy,file.path(getOption("ursaRequisite"),paste0("coast-",detail,".rds"))
,version=2) ## Such files are only readable in R >= 3.5.0.
if (!.isPackageInUse())
spatial_write(a,paste0(paste0("coast-",detail,ifelse(merge,"","180")),".sqlite"))
0L
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/panel_coastline.R
|
'panel_contour' <- function(obj,type="",...) {
if (.skipPlot(TRUE))
return(NULL)
if (!is.ursa(obj))
return(contour(obj,...))
isLabel <- .lgrep("label",type)>0
isLine <- .lgrep("line",type)>0
isFilled <- .lgrep("fill",type)>0
isColored <- .lgrep("colo(u)*r",type)>0
if ((!isLine)&&(!isFilled)&&(!isColored)&&(!isLabel))
isLine <- TRUE
if ((isFilled)&&(isColored))
isColored <- FALSE
if (isLabel){
# if (isLine)
# isLabel <- FALSE
# if ((isFilled)||(isColored))
# isLine <- TRUE
}
verbose <- .getPrm(list(...),name="verb(ose)*",default=FALSE)
if (T & verbose)
print(c(line=isLine,filled=isFilled,colored=isColored,label=isLabel))
if ((!TRUE)&&(isLabel)&&(!isFilled)&&(!isColored)&&(!isLine))
res <- .panel_contour(obj,expand=0,...)
else {
res <- .panel_contour(obj,category=isColored,...)
}
if (isFilled) {
with(res,.filled.contour(x,y,z,levels=lev,col=col))
}
if (isColored) {
cl <- with(res,contourLines(x,y,z,levels=lev))
arglist <- list(...)
col.fg <- res$col
col.bg <- .getPrm(arglist,name="bg",default="black")
lwd.fg <- .getPrm(arglist,name="lwd(\\.fg)*",default=2)
lwd.bg <- .getPrm(arglist,name="lwd.bg",default=lwd.fg*1.5)
short <- .getPrm(arglist,name="short",default=0L)
verbose <- .getPrm(arglist,name="verb(ose)*",default=FALSE)
if (verbose)
print(list(col.fg=col.fg,col.bg=col.bg,lwd.fg=lwd.fg,lwd.bg=lwd.bg
,short=short))
val <- .deintervale(col.fg)
isbg <- lwd.bg>lwd.fg
if (isbg) {
col.bg <- rep(col.bg,length=length(col.fg))
}
lapply(cl,function(p){
with(p,{
if (length(x)<short)
return(NULL)
ind <- match(level,val)
if (isbg)
lines(x,y,col=col.bg[ind],lwd=lwd.bg)
lines(x,y,col=col.fg[ind],lwd=lwd.fg)
})
})
}
if ((isLine)||(isLabel)) {
arglist <- list(...)
ct <- res$col
val <- .deintervale(ct)
# if ((!FALSE)&&(!isColored)&&(length(ct)==length(val))) {
# res$lev <- head(res$lev,-1)+diff(res$lev)/2
# }
# add <- .getPrm(arglist,name="add",default=TRUE)
if ((isLabel)&&(!isLine))
lwd <- NA
else
lwd <- .getPrm(arglist,name="lwd$",default=0.5)
col <- .getPrm(arglist,name="col",class=c("character","logical")
,default="black") ## res$col col.bg
if ((isLabel)&&(!isLine))
lty <- "blank"
else
lty <- .getPrm(arglist,name="lty",class=list("character","numeric")
,default=1)
labcex <- .getPrm(arglist,name="(lab)*cex",default=1) ## 0.85
method <- .getPrm(arglist,name="method",default="flattest")
labels <- .getPrm(arglist,name="label(s)",class="character",default=NULL)
if ((isLine)&&(!isLabel))
drawL <- FALSE
else if ((isFilled)&&(!isLabel))
drawL <- FALSE
else
drawL <- TRUE
# str(list(res="res",levels=res$lev,col=col,lwd=lwd,lty=lty,labels=labels
# ,labcex=labcex,method=method,drawlabels=drawL,add=TRUE))
if (is.character(res$lev)) {
if (is.null(labels)) {
labels <- res$lev
}
res$lev <- seq_along(res$lev)-1
}
if (!length(res$lev)) {
if (is.character(res$z)) {
res$lev <- seq_along(res$col)-1
dimz <- dim(res$z)
res$z <- as.integer(factor(res$z,levels=names(res$col)))-1
dim(res$z) <- dimz
}
}
if (isTRUE(is.logical(col))) {
bright <- mean(colSums(col2rgb(res$col)*c(0.30,0.59,0.11)))
bgcol <- ifelse(bright<160,"white","black")
col <- c(bgcol,res$col,bgcol)
reps <- round(strwidth(labels,cex=labcex)/strwidth(" ",cex=labcex))
spaces <- sapply(reps, function(x) paste(rep(" ", round(x)), collapse=""))
contour(res,levels=unique(res$lev),col=bgcol,lwd=tail(lwd,1)
,lty=lty,labels=spaces
,labcex=labcex,method=method,drawlabels=T,add=TRUE)
contour(res,levels=unique(res$lev),col=col,lwd=head(lwd,1),lty=lty
,labels=spaces
,labcex=labcex,method=method,drawlabels=drawL,add=TRUE)
len <- 500
usr <- par()$usr
xo <- seq(usr[1],usr[2],len=len)
yo <- seq(usr[3],usr[4],len=len)
dx <- diff(xo[1:2])
dy <- diff(yo[1:2])
labrange <- seq(-2,2)
for (di in labrange) {
for (dj in labrange) {
if (abs(dj)+abs(di)>3)
next
if ((!dj)&(!di))
next
o <- res
o$x <- o$x+dx/2*di
o$y <- o$y+dy/2*dj
contour(o,lty=0,labels=labels,levels=unique(res$lev)
,labcex=labcex,add=TRUE,col=bgcol)
}
}
contour(res,lty=0,labels=labels,levels=unique(res$lev)
,labcex=labcex,add=TRUE,col=col)
}
else
contour(res,levels=unique(res$lev),col=col,lwd=head(lwd,1)
,lty=lty,labels=labels
,labcex=labcex,method=method,drawlabels=drawL,add=TRUE)
}
res$col
}
'.panel_contour' <- function(obj,category=FALSE,...) {
arglist <- list(...)
g0 <- session_grid()
isCT <- .is.colortable(obj)
verbose <- .getPrm(arglist,name="verb(ose)*",default=FALSE)
sc <- .getPrm(arglist,name="expand",default=NA_real_)
before <- if (isCT) FALSE else .getPrm(arglist,name="before",default=TRUE)
if (is.na(sc)) {
sc <- getOption("ursaPngScale")
if (!is.numeric(sc))
sc <- 300/with(obj$grid,sqrt(columns*rows))
}
if (verbose)
print(data.frame(sc=sc,before=before))
'.smooth' <- function(obj,sc) {
proposed <- FALSE ## added 20170608 (TRUE) removed 20180218 (FALSE)
if (sc<=1)
return(obj)
# verbose <- TRUE
g2 <- regrid(g0,mul=sc,border=1)
cov <- .getPrm(arglist,name="cover",default=NA_real_)
if (proposed) {
ct2 <- ursa(obj,"colortable")
if (length(ct2)) {
# print(ursa(obj,"table"))
obj <- discolor(obj)
}
}
obj <- regrid(obj,border=1,cover=cov,resample=1+1e-6,fillNA=TRUE
,verbose=verbose)
obj <- regrid(obj,mul=sc,cover=cov,cascade=TRUE,verbose=verbose)
obj <- regrid(obj,g2,verbose=verbose)
if (proposed) {
if (length(ct2)) {
obj <- colorize(obj,colortable=ct2,lazyload=FALSE)
# obj <- as.integer(round(obj));ursa(obj,"colortable") <- ct2
}
}
obj
}
if (before) {
if (isCT)
obj <- reclass(obj) ## category -> real
obj <- .smooth(obj,sc)
}
if (!isCT) {
arglist$stretch <- .getPrm(arglist,name="stretch",default="linear")
arglist$ramp <- .getPrm(arglist,name="ramp",default=FALSE)
arglist$interval <- .getPrm(arglist,name="interval",default=1L)
arglist$value <- .getPrm(arglist,name="^value",class="numeric",default=NULL)
if ((arglist$interval==0)||(!is.na(pmatch(arglist$stretch,"category"))))
{
if (TRUE) {
opW <- options(warn=-2)
warning("Unable to make 'filled.contour' with categories")
options(opW)
}
return(NULL)
}
isJulian <- arglist$stretch %in% c("julian")
if (isJulian)
arglist$interval <- 0L
obj <- do.call("colorize",c(quote(obj[1]),arglist))
val <- .deintervale(obj)
arglist$interval <- !arglist$interval
arglist$stretch <- "linear"
if (isJulian) {
# arglist$name <- val
val <- seq_along(val)
arglist$ncolor <- length(val)
}
o <- as.ursa(matrix(val,ncol=1))
o <- do.call("colorize",c(quote(o),arglist))
ct2 <- ursa_colortable(o)
}
else
isJulian <- FALSE
ct <- ursa_colortable(obj)
if (!before) {
ct3 <- ursa_colortable(obj)
obj <- .extract(obj)
# obj <- reclass(obj)
ursa_colortable(obj) <- character(0)
obj <- .smooth(obj,sc)
ursa_colortable(obj) <- ct3
}
session_grid(g0)
if ((!FALSE)&&(category)) {
# levels <- reclass(ct)
val <- .deintervale(ct)
if (.is.nominal(ct)) {
val <- val[-1]-diff(val)/2
}
if (isCT)
ct2 <- colorRampPalette(ct)(2*length(val)+1)[2*seq(val)]
names(ct2) <- val
class(ct2) <- "ursaColorTable"
}
obj <- reclass(obj,ct)
# obj <- reclass(discolor(obj),ct) ## 20170608 proposed
res <- as.matrix(obj,coords=TRUE)
val <- .deintervale(ct)
if (isJulian) {
vname <- val
val <- seq_along(vname)
}
oneBreak <- length(val)==1
if (!is.character(val))
dval <- if (oneBreak) 0 else diff(val)/2
if (((category)&&(.is.nominal(ct)))||(is.character(val))) {
val2 <- .deintervale(ct2)
dval2 <- diff(val2)
res$lev <- c(head(val2,1)-head(dval2,1),val2,tail(val2,1)+tail(dval2,1))
}
else {
res$lev <- c(head(val,1)-2*head(dval,1),val,tail(val,1)+2*tail(dval,1))
if (isJulian) {
lev <- rep("***",length(res$lev))
lev[1] <- "low"
lev[length(lev)] <- "high"
lev[match(val,res$lev)] <- vname
res$lev <- lev
}
val <- c(head(val,1)-head(dval,1),head(val,-1)+dval,tail(val,1)+tail(dval,1))
}
if (oneBreak) {
if (val[1]==0)
val <- c(-1e-6,1e-6)
else
val <- c(val[1]-1e-6/val[1],val[2]+1e-6/val[2])
res$lev <- res$lev[1:2]
}
res$col <- if (category) ct2 else ct
res$z[] <- val[res$z+1L]
attr(res,"colortable") <- NULL
invisible(res)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/panel_contour.R
|
'panel_decor' <- function(...) {
arglist <- list(...)
opR <- options(ursaPngAuto=TRUE)
isWeb <- getOption("ursaPngWebCartography")
ann <- getOption("ursaPngCopyright")
ann <- ((is.character(ann)[1])&&(nchar(ann[1])))
ann <- ((ann)&&(!.getPrm(arglist,name="coast",default=FALSE)))
isWeb <- (is.logical(isWeb)&&(isWeb))
isBefore <- isWeb & !ann
isAfter <- !isBefore
if (isBefore)
do.call("panel_coastline",arglist)
ind <- .grep("decor",names(arglist))
if (!length(ind))
arglist$decor <- TRUE
if (isAfter)
do.call("panel_coastline",arglist)
do.call("panel_graticule",arglist)
do.call("panel_scalebar",arglist)
do.call("panel_annotation",arglist)
options(opR)
invisible(NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/panel_decor.R
|
##~ '.panel_graticule' <- function(gridline=TRUE,col="grey70",lon=NULL,lat=NULL
##~ ,lwd=1,lty=2,margin=rep(FALSE,4),trim=FALSE
##~ ,cex=0.75,...) {
##~ NULL
##~ }
'compose_graticule' <- function(...) {
arglist <- list(...)
# kwd <- "grid(line)*"
kwd <- "(graticule|grid(line)*)"
# gridline <- .getPrm(arglist,name=paste0("^(",kwd,"|decor)$"),default=TRUE)
gridline <- .getPrm(arglist,name=paste0("^(",.gsub("(^\\(|\\)$)","",kwd),"|decor)$")
,default=TRUE)
if (!any(gridline)) {
res <- list(gridline=NULL,margin=NULL)
class(res) <- "ursaGridLine"
return(res)
}
lon <- .getPrm(arglist,name="lon",kwd=kwd,default=NA_real_)
lat <- .getPrm(arglist,name="lat",kwd=kwd,default=NA_real_)
marginalia <- .getPrm(arglist,name="(decor|margin(alia)*)",kwd=kwd
,class=c("integer","logical")
,default=c(!FALSE,!FALSE,!FALSE,!FALSE))
panel <- .getPrm(arglist,name=paste0("^",kwd,"$"),default=0L)
trim <- .getPrm(arglist,name="trim",kwd=kwd,default=TRUE)
cex <- .getPrm(arglist,name="cex",kwd=kwd,default=0.75)
# defcol <- ifelse(bg2<128,"#FFFFFF4F","#0000002F") # grey70
bg1 <- sum(c(col2rgb(getOption("ursaPngBackground")))*c(0.30,0.59,0.11))
bg2 <- getOption("ursaPngPanel")
bg2 <- if ((is.null(bg2))||(!nchar(bg2))) bg1 else sum(c(col2rgb(bg2))*c(0.30,0.59,0.11))
col <- .getPrm(arglist,name="col",kwd=kwd,default="defcol")
border <- .getPrm(arglist,name="border",kwd=kwd,default=col)
if (col=="defcol")
col <- ifelse(bg2<128,"#FFFFFF4F","#0000002F") # grey70
if (border=="defcol")
border <- ifelse(bg1<128,"#FFFFFF4F","#0000002F") # grey70
lwd <- .getPrm(arglist,name="lwd",kwd=kwd,default=0.5)
lty <- .getPrm(arglist,name="lty",kwd=kwd,default=2L)
language <- .getPrm(arglist,name="language",kwd=kwd,default=NA_character_)
verbose <- .getPrm(arglist,name="verb(ose)*",kwd=kwd,default=FALSE)
if (is.integer(marginalia)) {
if ((length(panel)==1)&&(panel==0))
panel <- seq(getOption("ursaPngLayout")$image)
panel <- -panel
internal <- which(marginalia<0)
marginalia <- abs(marginalia)
ind <- match(marginalia,-panel)
panel[ind] <- -panel[ind]
if (length(internal))
panel[ind][internal] <- panel[ind][internal]+10000L
# panel <- marginalia
marginalia <- TRUE
}
# else
# panel <- 0L
a <- list(col=col,lon=lon,lat=lat,lwd=lwd,lty=lty,panel=panel
,marginalia=marginalia,trim=trim,cex=cex)
if (verbose)
str(list(col=col,lon=lon,lat=lat,col=col,lwd=lwd,lty=lty,panel=panel
,marginalia=marginalia,trim=trim,cex=cex))
opStrangeWarn <- options(warn=-1) ## strings not representable in native encoding will be translated to UTF-8
ret <- .compose_graticule(panel=panel,col=col,border=border
,lon=lon,lat=lat,lwd=lwd,lty=lty
,marginalia=marginalia,trim=trim
,language=language,cex=cex,verbose=verbose)
options(opStrangeWarn)
ret
}
'.compose_graticule' <- function(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) {
# verbose <- TRUE
if (is.na(language)) {
if (TRUE) {
ctype <- Sys.getlocale("LC_TIME")
if (.lgrep("Russian",ctype))
language <- "ru"
}
else
language <- Sys.getenv("LANGUAGE")
}
g1 <- session_grid()
proj4 <- g1$crs
isProj <- nchar(proj4)>0
projClass <- if (isProj) .gsub(".*\\+proj=(\\S+)\\s.+","\\1",proj4) else ""
isLonLat <- .lgrep("(\\+proj=longlat|epsg:4326)",proj4)>0
isMerc <- .lgrep("\\+proj=merc",proj4)>0
minx <- g1$minx
miny <- g1$miny
maxx <- g1$maxx
maxy <- g1$maxy
if (any(is.na(marginalia)))
marginalia <- TRUE
if ((!anyNA(lon))&&(!anyNA(lat)))
{
# dlon <- unique(diff(lon))
# dlat <- unique(diff(lat))
# if ((length(dlon)==1)&&(length(dlat)==1))
# dlon <- max(abs(diff(lon)))
# dlat <- max(abs(diff(lat)))
# lon <- c(head(lon,1)-dlon,lon,tail(lon,1)+dlon)
# lat <- c(head(lat,1)-dlat,lat,tail(lat,1)+dlat)
lon3 <- lon
lon4 <- lon
ind3 <- which(lon3<0)
ind4 <- which(lon3>180)
lon3[ind3] <- lon3[ind3]+360
lon4[ind4] <- lon4[ind4]-360
sd2 <- sd(lon)
sd3 <- sd(lon3)
sd4 <- sd(lon4)
if (verbose)
print(c(sd2=sd2,sd3=sd3,sd4=sd4))
if ((sd3<sd2)&&(sd3<sd4))
lon <- lon3
else if ((sd4<sd2)&&(sd4<sd3))
lon <- lon4
else if ((sd3<sd2)&&(sd3==sd4))
lon <- lon3
dlon <- max(abs(diff(lon)))
dlat <- max(abs(diff(lat)))
lon <- c(head(lon,1)-dlon,lon,tail(lon,1)+dlon)
lat <- c(head(lat,1)-dlat,lat,tail(lat,1)+dlat)
lonList <- list(lon)
latList <- list(lat)
}
else if (!isProj)
{
x <- with(g1,seq(minx,maxx,by=resx))
y <- with(g1,seq(miny,maxy,by=resy))
dx <- with(g1,maxx-minx)
dy <- with(g1,maxy-miny)
x1 <- max(abs(c(minx,maxx)))
y1 <- max(abs(c(miny,maxy)))
for (n in 5:9) {
x <- pretty(x,n=n)
y <- pretty(y,n=n)
dx <- mean(diff(x))
dy <- mean(diff(y))
d <- max(dx,dy)
if (FALSE) { ## removed 20170222
dx <- d
dy <- d
}
lon <- c(rev(seq(0,-x1-dx,by=-dx)[-1]),seq(0,x1+dx,by=dx))
lat <- c(rev(seq(0,-y1-dy,by=-dy)[-1]),seq(0,y1+dy,by=dy))
lon <- lon[lon>=minx-dx & lon<=maxx+dx]
lat <- lat[lat>=miny-dy & lat<=maxy+dy]
nx <- length(lon[lon>=minx & lon<=maxx])
ny <- length(lat[lat>=miny & lat<=maxy])
if ((nx>=2)&&(ny>=2))
break
}
lonList <- list(lon)
latList <- list(lat)
}
else {
if (!isLonLat) {
xy0 <- c((maxx+minx)/2,(miny+maxy)/2)
aside <- atan(xy0[1]/xy0[2])*180/pi
}
##~ if (FALSE) {
##~ g2 <- expand.grid(x=seq(minx,maxx,length=2),y=seq(miny,maxy,length=2)
##~ ,KEEP.OUT.ATTRS=FALSE,stringsAsFactors=FALSE)
##~ g2 <- cbind(g2$x,g2$y)[c(1,4),]
##~ g2a <- proj4::project(g2,g1$crs,inv=TRUE)
##~ g2b <- project(g2,g1$crs,inv=TRUE) ## project() from 'rgdal'
##~ print(g2)
##~ print(g2a)
##~ print(g2b)
##~ }
g2 <- expand.grid(x=seq(minx,maxx,length=16),y=seq(miny,maxy,length=16)
,KEEP.OUT.ATTRS=FALSE,stringsAsFactors=FALSE)
if (FALSE) {
xy <- with(g2,cbind(x,y))
session_grid(NULL)
xy <- as.data.frame(cbind(xy,z=runif(nrow(xy),min=1,max=2)))
a <- allocate(xy)
display(a)
}
##~ if (FALSE) { ## known reprojection issues
##~ xy0 <- as.data.frame(xy)
##~ sp::coordinates(xy0) <- ~x+y
##~ sp::proj4string(xy0) <- g1$crs
##~ xy2 <- sp::coordinates(sp::spTransform(xy0,"+init=epsg:4326"))
##~ print(apply(xy2,2,range))
##~ }
if (!isLonLat) {
xy <- .project(with(g2,cbind(x,y)),g1$crs,inv=TRUE)
if (is.null(xy)) {
xy <- with(g2,cbind(x,y))
minx <- min(xy[,1])
maxx <- max(xy[,1])
miny <- min(xy[,2])
maxy <- max(xy[,2])
xy <- xy[xy[,1]>minx & xy[,1]<maxx & xy[,2]>miny & xy[,2]<maxy,]
minx <- min(xy[,1])
maxx <- max(xy[,1])
miny <- min(xy[,2])
maxy <- max(xy[,2])
xy <- .project(xy,g1$crs,inv=TRUE)
if (is.null(xy)) {
cat("Likely, reprojection is failed.\n")
res <- list(gridline=NULL,margin=NULL)
class(res) <- "ursaGridLine"
return(invisible(res))
}
}
}
else
xy <- with(g2,cbind(x,y))
xy <- xy[which(xy[,2]>=-90 & xy[,2]<=90),]
n <- nrow(xy)
i1 <- round(0.05*n)
i1 <- c(i1,n-i1)
if (i1[1]<1)
i1[1] <- 1
if (i1[2]>n)
i1[2] <- n
lon <- xy[,1]
# print(summary(lon,digits=7))
if (!isLonLat) {
lon3 <- lon
lon4 <- lon
ind3 <- which(lon3<0)
ind4 <- which(lon3>180)
lon3[ind3] <- lon3[ind3]+360
lon4[ind4] <- lon4[ind4]-360
sd2 <- sd(lon)
sd3 <- sd(lon3)
sd4 <- sd(lon4)
if (verbose)
print(c(sd2=sd2,sd3=sd3,sd4=sd4))
if ((sd3<sd2)&&(sd3<sd4))
lon <- lon3
else if ((sd4<sd2)&&(sd4<sd3))
lon <- lon4
else if ((sd3<sd2)&&(sd3==sd4)) {
lon <- lon3
}
}
# print(summary(lon,digits=7))
# q()
lat <- xy[,2]
cond1 <- length(which(abs(lon)<=10))>0
cond2 <- length(which(abs(abs(lon)-180)<=10))>0
if (cond1 && cond2 && projClass %in% c("laea","stere"))
pole <- TRUE
else {
pole <- FALSE
if ((!isLonLat)&&(FALSE)) {
if ((cond2)&&(length(ind <- which(lon<0))))
lon[ind] <- lon[ind]+360
else if ((cond1)&&(length(ind <- which(lon>180))))
lon[ind] <- lon[ind]-180
}
}
##~ hist(lon,breaks=180)
lon <- sort(lon)[i1]
lat <- sort(lat)[i1]
isSouth <- all(lat<0)
isNorth <- all(lat>=0)
isEquator <- any(lat>0) & any(lat<0)
isLatDistortion <- isEquator & isProj & !isLonLat &
projClass %in% c("laea","merc","cea")
# alat <- sort(abs(lat))
alat <- sort(lat)
# print(c(lat=lat,lon=lon))
# pole <- any(lat>80)
dx <- (maxx-minx)/1000
dy <- (maxy-miny)/1000
nrE <- ifelse(isLatDistortion,5,3) ## if equator then 5?
if (dx<dy) {
sc <- dy/dx
nc0 <- 3
nc <- ifelse(sc>2,nc0-1,nc0)
nr <- floor(nc0*sc)
# print(nr)
if (nr<nrE)
nr <- max(round(nc0*sc),nrE)
}
else {
sc <- dx/dy
nr <- nrE
nr0 <- ifelse(sc>2.5,nr-1,nr)
# print(c(scX=sc,nr=nr,nc=nr0*sc))
nc <- round(nr0*sc) ## only if floor()<3
}
if ((FALSE)&&(!isLonLat)&&(!pole)) {
xy0 <- c((minx+maxx)/2,(miny+maxy)/2)
if (any(xy0!=0)) {
aside <- abs(atan(xy0[1]/xy0[2])*180/pi)
if (aside>=60) {
.nc <- nc
nc <- nr
nr <- .nc
rm(.nc)
}
else if (aside>30) {
nc <- nr <- min(c(nc,nr))
}
}
}
if (verbose)
print(c(nc=nc,nr=nr))
# if (length(ind <- lon<0))
# lon[ind] <- lon[ind]+360
# if (pole)
# lon <- c(0,lon,360)
dl <- rev(c(60,45,40,30,20,15,10,6,5,4,3,2,1 ## insert 2.5?
,c(30,20,15,12,10,6,5,4,3,2,1)/60 ## 3? 0.5?
,c(30,20,15,12,10,6,5,4,3,2,1)/3600))
if (pole) {
if (min(alat)>=75)
.by=15
else if (min(alat)>=60)
.by=20
else
.by=30
lon <- seq(0,360,by=.by)
lat0 <- 90-.prettyLabel(90-alat,ncol=6)$at
for (i in dl) {
if (i %in% c(20,40,60))
next
lat3 <- seq(-90,90,by=i)
lat3 <- lat3[lat3>alat[1] & lat3<alat[2]]
if (length(lat3)<=nr) {
lat <- lat3
break
}
}
if (!length(lat))
lat <- lat0
else {
dlat <- mean(diff(lat))
lat <- unique(c(lat-dlat,lat,lat+dlat))
}
}
else if ((FALSE)&&(isLonLat)) {
for (i in 1:9) {
lon <- pretty(lon,n=nc+i-1)
if (length(which(lon>=g1$minx & lon<=g1$maxx))>=2)
break
}
for (i in 1:9) {
lat <- pretty(lat,n=nc+i-1)
if (length(which(lat>=g1$miny & lat<=g1$maxy))>=2)
break
}
}
else {
lon2a <- pretty(lon,n=nc)
lon2b <- .prettyLabel(lon,ncol=nc+1)$at
# lon1 <- if (length(lon2a)<length(lon2b)) lon2a else lon2a
lon1 <- lon0 <- lon2a
mm <- (lon0-floor(lon0))*60
resa <- with(g1,min(c(maxx-minx,maxy-miny)))/1000
# mm <- 0.5
if ((TRUE)||(any(round(mm,6)!=0)))
{
if (isMerc) {
lon_0 <- as.numeric(.gsub2("\\+lon_0=(\\S+)\\s","\\1",proj4))
lat_ts <- .gsub2("\\+lat_ts=(\\S+)\\s","\\1",proj4)
lat_ts <- ifelse(lat_ts==proj4,0,as.numeric(lat_ts))
# lat_ts <- 0
lon <- c(minx,maxx)/6378137/pi*180/cos(lat_ts*pi/180)+lon_0
}
v1 <- ifelse(lon[1]>=-180,-180,-360) #floor(min(lon))
v2 <- 360 #ceiling(max(lon))
dl2 <- dl[resa/(2*nc*111)<dl]
if (!length(dl2))
dl2 <- dl
for (i in dl2) {
lon3 <- seq(v1,v2,by=i)
lon3 <- lon3[lon3>lon[1] & lon3<lon[2]]
if (length(lon3)>1)
lon0 <- lon3
if (length(lon3)<=nc) {
break
}
}
}
# if (isMerc)
# lon <- seq(v1,v2,by=i)
# else
# if (length(lon3)==1)
# lon3 <- .prettyLabel(lon,ncol=nc)$at
if (TRUE) { ## ++ 20170616
if (length(lon3)>1)
lon <- lon3
else if (length(lon0)<=3)
lon <- lon0
else
lon <- lon2b
}
else
lon <- if (length(lon3)>1) lon3 else lon2b ## -- 20170616
lat1 <- lat0 <- .prettyLabel(lat,ncol=nr+2)$at
mm <- (lat0-floor(lat0))*60
# mm <- 0.5
if ((TRUE)&&(any(round(mm,6)!=0)))
{
v1 <- -90 #floor(min(lat))
v2 <- 90 #ceiling(max(lat))
dl2 <- dl[resa/(2*nr*111)<dl]
if (!length(dl2))
dl2 <- dl
for (i in dl) {
if (i %in% c(20,40,60))
next
lat3 <- seq(v1,v2,by=i)
lat3 <- lat3[lat3>lat[1] & lat3<lat[2]]
if (length(lat3)<=nr) {
lat0 <- lat3
break
}
}
}
lat <- if (length(lat0)>1) lat0 else lat1
dlon <- mean(diff(lon))
dlat <- mean(diff(lat))
if (length(lon)>1) {
lon <- unique(c(lon-dlon,lon,lon+dlon))
}
if (length(lat)>1) {
lat <- unique(c(lat-dlat,lat,lat+dlat))
}
# if (isMerc) {
# print(v)
# print(right)
# print(lon)
# q()
# }
# if ((0 %in% lon) && (360 %in% lon))
# lon <- lon[lon!=360]
rm(lon0,lon1,lat0,lat1,dlon,dlat)
# print(lon)
# print(lat)
}
# lat[lat>=90] <- 89.9
# lat <- lat[lat<90]
dlon <- abs(diff(lon))[1]*c(1)
dlat <- abs(diff(lat))[1]*c(1)
if (!pole) {
if (!(projClass %in% c("cea"))) {
lon <- c(lon[1]-rev(dlon),lon,lon[length(lon)]+dlon)
lat <- c(lat[1]-rev(dlat),lat,lat[length(lat)]+dlat)
}
}
else if (!isSouth){
lat <- sort(lat)
lat <- unique(c(lat[1]-rev(dlat),lat,90))
}
else {
lat <- sort(-lat)
lat <- unique(c(lat[1]-rev(dlat),lat,90))
lat <- -lat
}
lonList <- list(unique(lon))
latList <- list(unique(lat))
# print(lon)
# print(lat)
}
marginalia <- rep(marginalia,length=4)
# north <- 89.5
if (TRUE) {#((isProj)&&(!isLonLat)) {
if (projClass %in% c("zzzmerc","zzzlonglat"))
north <- 90-1e-6
else
north <- 90-0.25*abs(mean(diff(lat)))
south <- -north
}
outframe <- NULL
alim <- 15 ## critical anlge (degree) between border line and grid line
projclass <- .gsub(".+proj=(\\S+)\\s.+","\\1",g1$crs)
for (j in seq_along(lonList))
{
lonSet <- unique(round(lonList[[j]],11))
latSet <- unique(round(latList[[j]],11))
if ((isProj)&&(!isLonLat)) {
latSet[latSet>north] <- north
latSet[latSet<south] <- south
latSet <- unique(latSet)
}
if ((FALSE)&&(projClass %in% c("merc","longlat"))) {
if (180 %in% lonSet)
lonSet <- sort(c(lonSet[lonSet!=180],180-1e-6,180+1e-6))
}
gridline <- vector("list",length(lonSet)+length(latSet))
llkind <- rep(0L,length(gridline))
llval <- rep(NA,length(gridline))
i <- 0L
if (!isProj) {
lat <- seq(min(latSet),max(latSet),len=10)
}
else {
latSet <- na.omit(latSet)
if (projclass %in% c("stere","laea")[1])
lat <- seq(min(latSet),max(latSet),len=2)
else if (projclass %in% c("merc"))
lat <- c(-1,1)*(90-1e-6)
else {
if (length(latSet)==1)
lat <- latSet
else {
lat <- seq(min(latSet),max(latSet),by=mean(diff(latSet))/10)
}
}
}
if (isMerc) {
B <- .getMajorSemiAxis(g1$crs)*pi
lon_0 <- as.numeric(.gsub(".*\\+lon_0=(\\S+)\\s.*","\\1",g1$crs))
lat_ts <- .gsub2("\\+lat_ts=(\\S+)\\s","\\1",g1$crs)
lat_ts <- ifelse(lat_ts==g1$crs,0,as.numeric(lat_ts))
}
for (lon in lonSet)
{
if (!((isLonLat)||(isMerc))) {
if ((lon==360)&&(0 %in% lonSet))
next
if ((lon==-180)&&(+180 %in% lonSet))
next
}
i <- i+1L
ll <- cbind(rep(lon,length(lat)),lat)
# proj4a <- "+proj=merc +lon_0=48 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs "
# gridline[[i]] <- if (isProj & !isLonLat) proj4::project(t(ll),g1$crs) else ll
if (isProj & !isLonLat) {
gridline[[i]] <- .project(ll,g1$crs)
# gridline[[i]] <- .project(ll,proj4a)
if ((FALSE)&&(isMerc)) {
x <- gridline[[i]][1,1]
print(data.frame(lon=lon,x=x,y=(lon-lon_0)/180*B))
##~ if (((lon<0)&&(x>maxx))||(lon<=(-180)))
##~ x <- x-2*20037508
##~ else if ((lon>360)&(x<minx))#(+180))
##~ x <- x+2*20037508
if ((lon<0)&&(x>0))
x <- x-2*B
else if ((lon>360)&(x<B))
x <- x+2*B
# if (x>maxx)
# x <- x-2*20037508
# else if (x<minx)
# x <- x+2*20037508
# print(data.frame(lon=lon,lonL=lon-360,lonR=lon+360
# ,minx=minx,src=xtmp,dst=x,maxx=maxx))
gridline[[i]][,1] <- x
}
if ((!FALSE)&&(isMerc)) ## -- 20180423
gridline[[i]][,1] <- (lon-lon_0)/180*B*cos(lat_ts*pi/180)
# print(gridline[[i]])
# if ((isMerc)&&((lon<0)&&(gridline[[i]][1,1]>0)))
# gridline[[i]][,1] <- -2*20037508+gridline[[i]][,1]
}
else
gridline[[i]] <- ll
llkind[i] <- 1L
llval[i] <- lon
}
if (projclass %in% c("merc"))
lon <- seq(-180,360,len=10)
else if (isProj)
lon <- seq(min(lonSet),max(lonSet),by=mean(abs(diff(lonSet)))/(j*10))
else
lon <- seq(min(lonSet),max(lonSet),len=10)
for (lat in latSet)
{
i <- i+1L
if (abs(lat)==max(abs(latSet)))
gridline[[i]] <- cbind(NA,NA)
else {
ll <- cbind(lon,rep(lat,length(lon)))
# print(series(ll,3))
# gridline[[i]] <- if (isProj & !isLonLat) proj4::project(t(ll),g1$crs) else ll
if (isProj & !isLonLat) {
ll <- .project(ll,g1$crs)
if (projclass %in% "merc") {
ll <- ll[order(ll[,1]),]
ll[1,1] <- ll[1,1]-1e8
ll[nrow(ll),1] <- ll[nrow(ll),1]+1e8
}
ind <- which(diff(ll[,1])<0)
if ((length(ind)==2)&&(ind[1]+1!=ind[2])) {
ll <- ll[(ind[1]+1):ind[2],,drop=FALSE]
}
}
gridline[[i]] <- ll
}
llkind[i] <- 2L
llval[i] <- lat
}
for (i in seq(along=gridline))
{
xy <- gridline[[i]]
if (all(is.na(xy)))
next
if (marginalia[2]) {
e1 <- which(diff((xy[,1]-minx)>0)!=0)
for (j in seq_along(e1)) {
l <- xy[c(e1[j],e1[j]+1),]
p <- l[1,2]+(minx-l[1,1])/(l[2,1]-l[1,1])*(l[2,2]-l[1,2])
an <- 90-abs(atan(diff(l[,2])/diff(l[,1]))*180/pi)
if ((is.finite(p))&&(.is.ge(p,miny))&&(.is.le(p,maxy))&&(abs(an)>=alim))
outframe <- rbind(outframe,data.frame(side=2,at=p
,kind=llkind[i],v=llval[i],an=an
,i=i,j=j,stringsAsFactors=FALSE))
}
}
if (marginalia[4]) {
e1 <- which(diff((xy[,1]-maxx)>0)!=0)
for (j in seq_along(e1)) {
l <- xy[c(e1[j],e1[j]+1),]
p <- l[1,2]+(maxx-l[1,1])/(l[2,1]-l[1,1])*(l[2,2]-l[1,2])
an <- 90-abs(atan(diff(l[,2])/diff(l[,1]))*180/pi)
if ((is.finite(p))&&(.is.ge(p,miny))&&(.is.le(p,maxy))&&(abs(an)>=alim))
outframe <- rbind(outframe,data.frame(side=4,at=p
,kind=llkind[i],v=llval[i],an=an
,i=i,j=j,stringsAsFactors=FALSE))
}
}
if (marginalia[1]) {
e1 <- which(diff((xy[,2]-miny)>0)!=0)
for (j in seq_along(e1)) {
l <- xy[c(e1[j],e1[j]+1),]
p <- l[1,1]+(miny-l[1,2])/(l[2,2]-l[1,2])*(l[2,1]-l[1,1])
an <- abs(atan(diff(l[,2])/diff(l[,1]))*180/pi)
if ((is.finite(p))&&(.is.ge(p,minx))&&(.is.le(p,maxx))&&(abs(an)>=alim))
outframe <- rbind(outframe,data.frame(side=1,at=p
,kind=llkind[i],v=llval[i],an=an
,i=i,j=j,stringsAsFactors=FALSE))
}
}
if (marginalia[3]) {
e1 <- which(diff((xy[,2]-maxy)>0)!=0)
for (j in seq_along(e1)) {
l <- xy[c(e1[j],e1[j]+1),]
p <- l[1,1]+(maxy-l[1,2])/(l[2,2]-l[1,2])*(l[2,1]-l[1,1])
an <- abs(atan(diff(l[,2])/diff(l[,1]))*180/pi)
if ((is.finite(p))&&(.is.ge(p,minx))&&(.is.le(p,maxx))&&(abs(an)>=alim))
outframe <- rbind(outframe,data.frame(side=3,at=p
,kind=llkind[i],v=llval[i],an=an
,i=i,j=j,stringsAsFactors=FALSE))
}
}
}
}
if (is.null(outframe)) {
res <- list(gridline=gridline,grid=list(lon=lonSet,lat=latSet)
,panel=panel,margin=NULL,col=col,border=border,lwd=lwd,lty=lty)
class(res) <- "ursaGridLine"
return(res)
}
outframe <- outframe[with(outframe,order(side,at)),]
if (!isLonLat) {
outframe$at <- round(outframe$at,6)
outframe$an <- round(outframe$an,6)
}
outframe$i <- NULL
outframe$j <- NULL
outframe <- unique(outframe)
if (isProj) {
if (length(ind <- outframe$v>180))
outframe$v[ind] <- outframe$v[ind]-360
if (length(ind <- outframe$v<=(-180)))
outframe$v[ind] <- outframe$v[ind]+360
outframe$lab <- NA
# suffNS <- c("N","S")
# suffEW <- c("E","W")
suffNS <- switch(language,ru=c("\u0441.\u0448.","\u044E.\u0448."),c("N","S"))
suffEW <- switch(language,ru=c("\u0432.\u0434.","\u0437.\u0434."),c("E","W"))
# suffNS <- switch(language,ru=c("\xF1.\xF8.","\xFE.\xF8."),c("N","S"))
# suffEW <- switch(language,ru=c("\xE2.\xE4.","\xE7.\xE4."),c("E","W"))
ind <- (outframe$kind==2)
outframe$lab[ind] <- .degminsec(outframe$v[ind],suffNS)
ind <- (outframe$kind==1)
outframe$lab[ind] <- .degminsec(outframe$v[ind],suffEW)
}
else {
if (g1$resx!=g1$resy) {
for (i in c(1,2)) {
ind <- (outframe$kind==i)
outframe$lab[ind] <- format(outframe$v[ind],trim=TRUE)
}
}
else
outframe$lab <- format(outframe$v,trim=TRUE)
# outframe$lab <- sprintf(ifelse(outframe$v==round(outframe$v),"%.0f","%f")
# ,outframe$v)
}
# outframe$kind <- NULL
outframe$adj <- 0.5
outframe$cex <- cex
da <- unique(outframe)
daZ <- data.frame(side=0,at=NA,kind=NA,v=NA,an=90,lab="|",adj=0.5,cex=cex
,stringsAsFactors=FALSE)
outframe <- NULL
if (trim) {
sc <- getOption("ursaPngScale")
if (is.numeric(sc)) {
sx <- 5/sc*g1$resx ## set 0, if failed
sy <- 5/sc*g1$resy ## set 0, if failed
}
else {
opW <- options(warn=-1)
warning(paste("It seems 'compose_open' have not called yet."
,"The labelling is less optimal."))
options(opW)
sx <- 0
sy <- 0
}
}
for (i in 1:4) {
if (!marginalia[i])
next
ind1 <- which(da$side==i)
da0 <- da[ind1,]
if (!nrow(da0))
next
if (trim) {
da0 <- rbind(daZ,da0,daZ)
if (i %in% c(1,3)) {
da0$at[1] <- g1$minx-sx
da0$at[nrow(da0)] <- g1$maxx+sx
}
else {
da0$at[1] <- g1$miny-sy
da0$at[nrow(da0)] <- g1$maxy+sy
}
}
nr <- nrow(da0)
daX <- NULL
da0$ind <- seq(nr)
k <- 0
width <- with(g1,if (i %in% c(1,3)) (maxx-minx) else (maxy-miny))
res <- with(g1,if (i %in% c(1,3)) resx else resy)
repeat ({
if (k>200)
break
w <- strwidth(paste0(da0$lab,"mmmm"),units="inches",cex=cex)*
res*getOption("ursaPngDpi")/getOption("ursaPngScale")
# ,family=getOption("ursaPngFamily")
if ((FALSE)&&(sum(w)/width>2)) {
# daY <- subset(da0,kind==1)
daY <- da0[which(da0$kind==1),]
n <- nrow(daY)
v1 <- seq(1,n,by=2)
v2 <- seq(n,1,by=-2)
d <- v1-v2
ind <- c(v1[d<=0],n-v2[d>=0]+1)
# da0 <- rbind(subset(da0,kind==2),daY[ind,])
da0 <- rbind(da0[which(da0$kind==2),],daY[ind,])
da0 <- da0[with(da0,order(at)),]
next
}
wL <- da0$at-w*da0$adj
wR <- da0$at+w*(1-da0$adj)
wD <- wL[-1]-wR[-length(wR)]
wD1 <- c(1e-6,wD)
wD2 <- c(wD,1e-6) # length(w)
ind2 <- which.min(wD2)
if (wD2[ind2]>=0)
break
if (length(ind2)==length(w))
break
ind2 <- c(ind2,ind2+1L)
adj <- da0[ind2,"adj"]
adj <- adj+c(0.0999,-0.0999)
if (all(adj>=-0.01 & adj<=1.01)) {
da0[ind2,"adj"] <- adj
next
}
k <- k+1
ind2 <- ind2[which.min(da0$an[ind2])]
daX <- rbind(daX,da0[ind2,])
da0 <- da0[-ind2,]
daX <- daX[order(daX$ind),]
ind3 <- which(!diff(diff(daX$ind)))+1
if ((FALSE)&&(length(ind3))) {
if (length(ind3)==3)
ind3 <- ind3[2]
else if (length(ind3)==5)
ind3 <- ind3[3]
else
ind3 <- sample(ind3,1)
ind4 <- daX$ind[ind3]
ind5 <- sort(c(da0$ind,ind4))
ind6 <- ind5[which(!diff(diff(ind5)))+1]
if (!(ind4 %in% ind6))
{
da0 <- rbind(da0,daX[ind3,])
daX <- daX[-ind3,]
}
}
da0[,"adj"] <- 0.5
})
# outframe <- rbind(outframe,subset(da0,side!=0))
outframe <- rbind(outframe,da0[which(da0$side!=0),])
}
outframe <- outframe[with(outframe,order(side,at)),]
res <- list(gridline=gridline,grid=list(lon=lonSet,lat=latSet)
,panel=panel,margin=outframe
,col=col,border=border,lwd=lwd,lty=lty)
class(res) <- "ursaGridLine"
res
}
'panel_graticule' <- function(...) {
if (.skipPlot())
return(NULL)
arglist <- list(...)
kwd <- "^(graticule|grid(line)*)$"
figure <- getOption("ursaPngFigure")
gridline <- .getPrm(arglist,name=kwd,class=list("integer","logical")
,default=TRUE)
if (is.integer(gridline))
gridline <- figure %in% gridline
if ((length(gridline)==1)&&(!gridline))
return(NULL)
obj <- .getPrm(arglist,class="ursaGridLine",default=NULL)
g1 <- session_grid()
# if ((!is.null(g1$labx))&&(!is.null(g1$laby))) {
if ((length(g1$seqx))&&(length(g1$seqy))) {
.repairForScatterPlot()
return(NULL)
}
if (is.null(obj))
obj <- compose_graticule(...)
if (is.null(obj$gridline))
return(NULL)
if ((!is.null(attr(g1$seqx,"units"))&&(!is.null(attr(g1$seqy,"units"))))) {
if (is.null(g1$labx))
g1$labx <- unique(obj$margin[obj$margin$kind==1,"at"])
if (is.null(g1$laby))
g1$laby <- unique(obj$margin[obj$margin$kind==2,"at"])
session_grid(g1)
.repairForScatterPlot()
return(NULL)
}
if ((!(0 %in% obj$panel))&&(!((figure %in% abs(obj$panel))||
((figure+10000L) %in% abs(obj$panel)))))
return(NULL)
if (FALSE) {
obj$col <- .getPrm(arglist,name="col",kwd=kwd,default=obj$col)
obj$lwd <- .getPrm(arglist,name="lwd",kwd=kwd,default=obj$lwd)
obj$lty <- .getPrm(arglist,name="lty",kwd=kwd,default=obj$lty)
}
verbose <- .getPrm(arglist,name="verb(ose)*",kwd=kwd,default=FALSE)
marginalia <- !is.na(match(seq(4),sort(unique(obj$margin$side))))
marginalia <- .getPrm(arglist,name="(decor|margin(alia)*)",kwd=kwd
,class=list("integer","logical"),default=marginalia)
if (is.integer(marginalia)) {
marginalia <- rep(figure %in% abs(marginalia),4)
}
if ((any(obj$panel))&&(!((figure %in% obj$panel)||((figure+10000L) %in% obj$panel)))) {
marginalia <- FALSE
}
marginalia <- rep(marginalia,length=4)
if ((figure+10000L) %in% obj$panel)
comment(marginalia) <- "internal"
else
comment(marginalia) <- NULL
.panel_graticule(obj,marginalia=marginalia,verbose=verbose)
}
'.panel_graticule' <- function(obj,marginalia=rep(TRUE,4),verbose=FALSE) {
g1 <- getOption("ursaPngComposeGrid")
g2 <- getOption("ursaPngPanelGrid")
# print(g1)
# print(g2)
# internal <- isTRUE(comment(marginalia)=="internal")
internal <- !identical(g1,g2)
if (internal) {
g1a <- g1
g2a <- g2
# g1a$crs <- NULL
# g2a$crs <- NULL
if (!identical(g1a,g2a)) {
res <- sapply(names(g1a),function(x) {
# if (x %in% c("retina"))
# return(TRUE)
if ((is.null(g1a[[x]]))||(is.null(g2a[[x]])))
return(TRUE)
if ((isTRUE(is.na(g1a[[x]])))||(isTRUE(is.na(g2a[[x]]))))
return(TRUE)
ret <- identical(g1a[[x]],g2a[[x]])
if (!ret) {
if (is.numeric(g1a[[x]])) {
ret <- .is.eq(g1a[[x]],g2a[[x]])
}
if (is.character(g1a[[x]])) {
if (length(grep("\\+proj",g1a[[x]]))) {
proj1 <- gsub(".*\\+proj=(\\S+)($|\\s+.*$)","\\1",g1a[[x]])
proj2 <- gsub(".*\\+proj=(\\S+)($|\\s+.*$)","\\1",g2a[[x]])
cond1 <- proj1==proj2
}
else
cond1 <- TRUE
if (length(grep("\\+lon_0",g1a[[x]]))) {
lon1 <- gsub(".*\\+lon_0=(\\S+)($|\\s+.*$)","\\1",g1a[[x]])
lon2 <- gsub(".*\\+lon_0=(\\S+)($|\\s+.*$)","\\1",g2a[[x]])
cond2 <- lon1==lon2
}
else
cond2 <- TRUE
if (length(grep("\\+lat_0",g1a[[x]]))) {
lat1 <- gsub(".*\\+lat_0=(\\S+)($|\\s+.*$)","\\1",g1a[[x]])
lat2 <- gsub(".*\\+lat_0=(\\S+)($|\\s+.*$)","\\1",g2a[[x]])
cond3 <- lat1==lat2
}
else
cond3 <- TRUE
ret <- cond1 & cond2 & cond3
}
}
ret
})
internal <- !all(res)
}
}
with(obj,{
if (verbose)
str(list(col=col,lwd=lwd,lty=lty))
for (i in seq(along=gridline))
{
xy <- gridline[[i]]
# if (all(is.na(xy)))
# next
lines(xy[,1],xy[,2],col=col,lwd=lwd,lty=lty)
}
if (is.null(margin))
return(NULL)
pngOp <- options()[.grep("^ursaPng.+",names(options()))]
layout <- pngOp[["ursaPngLayout"]][["layout"]]
layout0 <- (layout==pngOp[["ursaPngFigure"]])
indr <- which(rowSums(layout0)==1)
indc <- which(colSums(layout0)==1)
# print(c(row=indr,column=indc))
if (FALSE) {
isTop <- all(layout[1L:(indr-1L),indc]==0)
isBottom <- all(layout[(indr+1L):nrow(layout),indc]==0)
isLeft <- all(layout[indr,1L:(indc-1L)]==0)
isRight <- all(layout[indr,(indc+1L):ncol(layout)]==0)
}
else {
isTop <- all(layout[(indr-2L):(indr-1L),indc]==0)
isBottom <- all(layout[(indr+1L):(indr+2L),indc]==0)
isLeft <- all(layout[indr,(indc-2L):(indc-1L)]==0)
isRight <- all(layout[indr,(indc+1L):(indc+2L)]==0)
}
marginalia0 <- marginalia
marginalia <- as.integer(marginalia0 & c(isBottom,isLeft,isTop,isRight))
if (internal) {
if ((sum(marginalia[c(1,3)])>0)&&(sum(marginalia[c(2,4)])))
internal <- FALSE
}
# print(c(bottom=isBottom,left=isLeft,top=isTop,right=isRight))
if (internal) {
panel2 <- pngOp[["ursaPngLayout"]][["image"]]
# fig2 <- pngOp[["ursaPngFigure"]]
layout2 <- layout
layout2[layout2<=panel2] <- 0L
isTop2 <- all(layout2[(indr-2L):(indr-1L),indc]==0)
isBottom2 <- all(layout2[(indr+1L):(indr+2L),indc]==0)
isLeft2 <- all(layout2[indr,(indc-2L):(indc-1L)]==0)
isRight2 <- all(layout2[indr,(indc+1L):(indc+2L)]==0)
marginalia2 <- as.integer(marginalia0 & c(isBottom2,isLeft2,isTop2,isRight2))
marginalia2 <- as.integer(!marginalia)*marginalia2
if ((marginalia[4])&&(marginalia2[2]))
marginalia2[2] <- 0L
if ((marginalia[2])&&(marginalia2[4]))
marginalia2[4] <- 0L
if ((marginalia[3])&&(marginalia2[1]))
marginalia2[1] <- 0L
if ((marginalia[1])&&(marginalia2[3]))
marginalia2[3] <- 0L
# print(marginalia)
# print(marginalia2)
# marginalia2 <- marginalia2-marginalia
marginalia <- marginalia2+marginalia
if ((marginalia2[4]==1)&&((marginalia2[2]==marginalia2[4])))
marginalia2[4] <- marginalia[4] <- 0L
if ((marginalia2[3]==1)&&((marginalia2[1]==marginalia2[3])))
marginalia2[3] <- marginalia[3] <- 0L
rm(layout2,isTop2,isBottom2,isLeft2,isRight2,panel2)
# print(marginalia)
# print(marginalia2)
}
rm(pngOp,layout,layout0,indc,indr,isTop,isBottom,isLeft,isRight)
# da1 <- if (marginalia[1]) subset(margin,side==1) else NULL
# da2 <- if (marginalia[2]) subset(margin,side==2) else NULL
# da3 <- if (marginalia[3]) subset(margin,side==3) else NULL
# da4 <- if (marginalia[4]) subset(margin,side==4) else NULL
da1 <- if (marginalia[1]) margin[which(margin$side==1),] else NULL
da2 <- if (marginalia[2]) margin[which(margin$side==2),] else NULL
da3 <- if (marginalia[3]) margin[which(margin$side==3),] else NULL
da4 <- if (marginalia[4]) margin[which(margin$side==4),] else NULL
# opT <- par(family="Arial Narrow")
if (F & internal) {
print(c((!is.null(da1))&&(nrow(da1)&&(marginalia2[1]))
,(!is.null(da2))&&(nrow(da2)&&(marginalia2[2]))
,(!is.null(da3))&&(nrow(da3)&&(marginalia2[3]))
,(!is.null(da4))&&(nrow(da4)&&(marginalia2[4]))
))
}
if ((!is.null(da1))&&(nrow(da1)))
with(da1,{
if ((internal)&&(marginalia2[1])) {
mtext(side=1,at=at,text=lab,padj=-1.7,adj=adj,cex=cex,col=border
,family=getOption("ursaPngFamily")
)
}
else {
axis(side=1,at=at,labels=NA,tcl=-0.2,col=border,lwd=0,lwd.ticks=lwd)
mtext(side=1,at=at,text=lab,padj=0.5,adj=adj,cex=cex,col=border
,family=getOption("ursaPngFamily")
)
}
})
if ((!is.null(da2))&&(nrow(da2)))
with(da2,{
if ((internal)&&(marginalia2[2])) {
mtext(side=2,at=at,text=lab,padj=0.4,adj=adj,line=-1,cex=cex,col=border
,family=getOption("ursaPngFamily")
)
}
else {
axis(side=2,at=at,labels=NA,tcl=-0.2,col=border,lwd=0,lwd.ticks=lwd)
mtext(side=2,at=at,text=lab,padj=0.4,adj=adj,line=0.6,cex=cex,col=border
,family=getOption("ursaPngFamily")
)
}
})
if ((!is.null(da3))&&(nrow(da3)))
with(da3,{
if ((internal)&&(marginalia2[3])) {
mtext(side=3,at=at,text=lab,padj=-0.25,adj=adj,line=-1.4,cex=cex,col=border
,family=getOption("ursaPngFamily")
)
}
else {
axis(side=3,at=at,labels=NA,tcl=-0.2,col=border,lwd=0,lwd.ticks=lwd)
mtext(side=3,at=at,text=lab,padj=-0.25,adj=adj,line=0,cex=cex,col=border
,family=getOption("ursaPngFamily")
)
}
})
if ((!is.null(da4))&&(nrow(da4)))
with(da4,{
if ((internal)&&(marginalia2[4])) {
mtext(side=4,at=at,text=lab,line=0,adj=adj,padj=-1.6,cex=cex,col=border
,family=getOption("ursaPngFamily")
)
}
else {
axis(side=4,at=at,labels=NA,tcl=-0.2,col=border,lwd=0,lwd.ticks=lwd)
mtext(side=4,at=at,text=lab,line=0,adj=adj,padj=0.4,cex=cex,col=border
,family=getOption("ursaPngFamily")
)
}
})
# options(opT)
})
invisible(NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/panel_graticule.R
|
##~ '.panel_new' <- function(dymmy=NULL,
##~ col.blank=NA,asp=1,density=NA,angle=NA,lwd=1,mar=rep(0,4),...)
##~ {
##~ 0L
##~ }
'panel_new' <- function(...)
{
if (.skipPlot())
return(invisible(NULL))
figN <- getOption("ursaPngFigure")+1L
if (figN>getOption("ursaPngLayout")$image) {
options(ursaPngSkip=TRUE)
return(invisible(NULL))
}
g1 <- session_grid()
if (figN>1) {
.panel_attribution()
if (getOption("ursaPngBox"))
panel_box()
}
options(ursaPngFigure=figN)
arglist <- list(...)
kwd <- "blank"
density <- .getPrm(arglist,name="density",kwd=kwd,default=NA_real_)
angle <- .getPrm(arglist,name="angle",kwd=kwd,default=NA_real_)
def.col <- if ((any(!is.na(density)))&&(any(!is.na(angle)))) "grey80" else "chessboard"
col <- .getPrm(arglist,name="(^$|bg|blank|fill)",kwd=kwd
,default=ifelse(nchar(g1$crs)>0,def.col,"white")) # grey90
lwd <- .getPrm(arglist,name="lwd",kwd=kwd,default=1)
lty <- .getPrm(arglist,name="lty",class=c("character","integer")
,kwd=kwd,default=1)
mar <- .getPrm(arglist,name="mar",kwd=kwd,default=rep(0,4))
asp <- .getPrm(arglist,name="asp",kwd=kwd,default=NA_real_) # default=1?
verbose <- .getPrm(arglist,name="verb(ose)*",kwd=kwd,default=FALSE)
.panel_new(col=col,density=density,angle=angle,lwd=lwd,lty=lty,mar=mar
,asp=asp,verbose=verbose)
}
'.panel_new' <- function(col="chessboard",density=NA,angle=NA,lwd=1,lty=1
,asp=NA,mar=rep(0,4),verbose=FALSE) {
if (.skipPlot())
return(invisible(NULL))
if (verbose)
str(list(col=col,density=density,angle=angle,lwd=lwd,lty=lty,mar=mar,asp=asp))
g1 <- session_grid()
scale <- getOption("ursaPngScale")
par(mar=rep(mar,length=4),xaxs="i",yaxs="i")#,xaxt="n",yaxt="n")
xlim <- with(g1,c(minx,maxx))
ylim <- with(g1,c(miny,maxy))
xlim[1] <- xlim[1]-1*g1$resx/scale
ylim[2] <- ylim[2]+1*g1$resy/scale
plot(0,0,type="n",xlim=xlim,ylim=ylim,axes=FALSE,asp=asp,xlab="",ylab="")
if (col=="chessboard") {
sc <- getOption("ursaPngScale")
if (!is.numeric(sc))
sc <- 1
g2 <- regrid(mul=sc/8,resetGrid=TRUE,tolerance=0.999) ## let rough grid
dima <- dim(g2)
if (isTRUE(getOption("ursaPngBackground") %in% c("black","#000000"))) {
minc <- 21/255
maxc <- 0.000
}
else {
minc <- 247/255
maxc <- 1.000
}
s1 <- rep(c(minc,maxc),length=dima["samples"])
s2 <- rep(c(maxc,minc),length=dima["samples"])
a <- matrix(NA,nrow=dima["lines"],ncol=dima["samples"],byrow=TRUE)
ind1 <- seq(floor(dima["lines"]/2))*2
ind2 <- seq(nrow(a))[-ind1]
m1 <- matrix(rep(s1,length(ind1)),byrow=TRUE,ncol=ncol(a))
m2 <- matrix(rep(s2,length(ind2)),byrow=TRUE,ncol=ncol(a))
a[ind1,] <- m1
a[ind2,] <- m2
panel_plot(as.raster(a),interpolate=FALSE)
session_grid(g1)
col <- "white"
}
else {
opEnd <- par(lend="square")
for (an in angle)
rect(min(xlim),min(ylim),max(xlim),max(ylim)
,col=col,border="transparent",density=density,angle=an,lwd=lwd,lty=lty)
par(opEnd)
}
options(ursaPngPanel=col,ursaPngPanelGrid=session_grid())
invisible(NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/panel_new.R
|
## ?formals
'panel_plot' <- function(obj,...) {
if (.skipPlot(TRUE))
return(NULL)
geoType <- ""
isSP <- FALSE
isSF <- FALSE
arglist <- as.list(match.call()) ## try mget(names(match.call())[-1])
isLang <- is.language(arglist[["obj"]])
if (isLang)
oname <- as.character(arglist["obj"])
else
oname <- "*undetermed*"
# str(lapply(arglist,class))
arglist2 <- list(...) ## remove dupe of 'add=TRUE'
ct <- NULL
if (inherits(obj,c("raster"))) {
ret <- with(session_grid()
,rasterImage(as.raster(obj),minx,miny,maxx,maxy,...))
}
else if (is.character(obj)) {
if (.lgrep("\\.(shp(\\.zip)*|(geojson|sqlite|gpkg)(\\.(gz|bz2))*)$",obj)) {
if (FALSE) { ## 20171216 deprecated
op <- options(warn=0)
# requireNamespace("rgdal",quietly=.isPackageInUse())
a <- .shp.read(obj)
# a <- spTransform(a,session_grid()$crs)
# ret <- .panel_plot(a,add=TRUE,...)
ret <- sp::plot(a,add=TRUE,...)
options(op)
}
else {
ret <- panel_plot(spatialize(obj),...) ## RECURSIVE
}
}
else if ((length(obj)==1)&&(envi_exists(obj))) {
ret <- panel_raster(read_envi(obj),...)
}
else if ((length(obj)==1)&&(file.exists(obj))) {
ret <- panel_raster(read_gdal(obj),...)
}
else if ((getOption("ursaPngScale")==1)&&
(.lgrep("\\+proj=merc",session_crs())>0)&&
((TRUE)||(.lgrep(obj,.tileService())))) {
ret <- panel_raster(obj,...)
}
else
return(invisible(NULL))
}
else if (is.ursa(obj)) {
ct <- panel_raster(obj,...)
}
else if (is_spatial(obj)) {
oprj <- spatial_crs(obj)
sprj <- session_crs()
if (!identical(oprj,sprj)) {
if ((is.list(oprj))&&("input" %in% names(oprj)))
oprj <- oprj[["input"]]
if ((is.list(sprj))&&("input" %in% names(sprj)))
sprj <- sprj[["input"]]
if (nchar(sprj)>2) {
oprj2 <- .gsub("\\+wktext\\s","",oprj)
sprj2 <- .gsub("\\+wktext\\s","",sprj)
oprj2 <- .gsub("(^\\s|\\s$)","",oprj2)
sprj2 <- .gsub("(^\\s|\\s$)","",sprj2)
if (!identical(oprj2,sprj2)) {
obj <- spatial_transform(obj,sprj)
}
}
}
geoType <- spatial_geotype(obj)
onlyGeometry <- is.null(spatial_data(obj))
if ((FALSE)&&(onlyGeometry)) {
# ret <- plot(obj,add=TRUE,...)
ret <- .tryE(do.call(".panel_plot",c(obj,add=TRUE)))
}
else if (TRUE) { ## is advanced condition required here?
# ret <- plot(sf::st_geometry(obj),...)
# opE <- options(show.error.messages=TRUE)
# ret <- .tryE(.panel_plot(sf::st_geometry(obj),add=TRUE,...))
# ret <- .tryE(.panel_plot(obj,add=TRUE,...))
# message("===========")
# str(arglist2)
# str(.lgrep("^(plot\\.)*col(o(u)*r)*$",names(arglist2)))
# message("===========")
if ((TRUE)&&(.lgrep("^col(o(u)*r)*$",names(arglist2)))) {
# stop("I")
if (is.numeric(col)) {
# stop("G")
ct <- colorize(col)
col <- ct$colortable[ct$index]
}
else if ((is.character(arglist2$col))&&(length(spatial_fields(obj)))) {
# stop("H")
if (!anyNA(match(arglist2$col,spatial_fields(obj)))) {
# stop("A")
ct <- colorize(spatial_data(obj,subset=col,drop=TRUE))
col <- ct$colortable[ct$index]
}
else if (length(spatial_fields(obj))==-1) {
stop("B")
if (.is.colortable(arglist2$col)) {
# stop("B1")
val <- spatial_data(obj,drop=TRUE)
ind <- match(names(arglist2$col),val)
if ((!anyNA(ind))&&(all(diff(ind)==1))) {
# stop("B1a")
col <- unname(unclass(arglist2$col))
ct <- arglist2$col
# ct <- colorize(val,pal=arglist2$col)
}
else {
# stop("B1b")
if (length(val)==length(arglist2$col)) {
ct <- arglist2$col
col <- unname(unclass(arglist2$col))
}
else {
ct <- colorize(val,colortable=arglist2$col)
col <- ct$colortable[ct$index]
}
}
}
else {
# stop("B2")
col <- arglist2$col
}
}
else if (is.character(col)) {
# stop("C")
col <- arglist2$col
}
else if ((.is.colortable(arglist2$col))&&
(length(spatial_fields(obj))==1)) {
# stop("D")
ct <- arglist2$col
val <- spatial_data(obj)[,1,drop=TRUE]
if (length(ct)==length(val)) {
# stop("D1")
col <- unname(ct)
}
else {
# stop("D2")
# str(val)
# str(ct)
# print(table(val))
if (!FALSE) { ## -- 20230529
col <- colorize(val,colortable=ct)
col <- unname(col$colortable[col$index])
}
else { ## ++ 20230529
col <- palettize(val,colortable=ct)
}
}
# str(col)
# print(table(col))
}
else {
##~ stop("E")
col <- NULL
}
}
else {
# stop("F")
col <- arglist2$col
if (length(spatial_fields(obj))==1) {
if (.is.colortable(arglist2$col)) {
ct <- ursa_colortable(arglist2$col)
ind <- match(obj[[1]],names(ct))
if (all(!anyNA(ind)))
col <- unname(ct)[ind]
}
}
}
alpha <- .getPrm(arglist2,"alpha",default=1)
if (alpha<1) {
val <- t(grDevices::col2rgb(col,alpha=TRUE))
col <- grDevices::rgb(val[,1],val[,2],val[,3],val[,4]*alpha,max=255)
}
if (!is.null(col))
arglist2$col <- unclass(col)
# str(arglist2)
}
else if (length(spatial_fields(obj))==1) {
# stop("II")
if ((!is.null(arglist2$pal))&&(inherits(arglist2$pal,"ursaColorTable"))) {
# stop("II1")
if (isTRUE(is.numeric(arglist2$alpha))) {
pname <- names(arglist2$pal)
alpha <- sprintf("%02X",.round(as.hexmode(gsub(".*(\\w{2}$)","\\1"
,arglist2$pal))*arglist2$alpha))
arglist2$pal <- paste0(gsub("(\\w{2}$)","",arglist2$pal),alpha)
names(arglist2$pal) <- pname
}
ind <- match(obj[[1]],names(arglist2$pal))
if (!anyNA(ind))
arglist2$col <- arglist2$pal[ind]
else {
ct <- do.call("colorize",c(list(obj[[1]],arglist2)))
arglist2$col <- ct$colortable[ct$index]
}
}
else if (is_ursa(attr(obj[[1]],"colortable"),"colortable")) {
# stop("II2")
arglist2$pal <- attr(obj[[1]],"colortable")
ind <- match(obj[[1]],names(arglist2$pal))
arglist2$col <- unclass(unname(arglist2$pal))[ind]
}
else {
# stop("II3")
# ct <- colorize(obj[[1]])
ct <- do.call("colorize",c(list(obj[[1]]),arglist2))
arglist2$pal <- ct$colortable ## ++ 20210520
arglist2$col <- unclass(unname(ct$colortable))[ct$index] ## -- 20210520
}
}
else {
arglist2$col <- ifelse(is_spatial_lines(obj),"black"
,ifelse(T,ursa_colortable(colorize("",alpha=0.2))
,"transparent"))
}
if (.lgrep("point",geoType)) {
if (F & !.isPackageInUse())
message("'ursa'-dev: test 'scattermode' ('https://github.com/exaexa/scattermore') for points plot")
if (!.lgrep("pch",names(arglist2))) {
arglist2$pch <- 21
}
if (!.lgrep("bg",names(arglist2))) {
arglist2$bg <- arglist2$col
if ((.lgrep("pch",names(arglist2)))&&
(arglist2$pch %in% c(21,22,23,24,25))) { ## ?pch
op <- median(col2rgb(arglist2$bg,alpha=T)["alpha",])
arglist2$col <- rgb(0,0,0,op,maxColorValue=255)
# arglist2$bg <- "transparent"
}
}
if (!.lgrep("cex",names(arglist2))) {
arglist2$cex <- 1.2
}
if (!.lgrep("lwd",names(arglist2))) {
arglist2$lwd <- 0.5
}
if (!.lgrep("col",names(arglist2)))
arglist2$col <- "black"
}
else if (.lgrep("lines",geoType)) {
if (!.lgrep("lwd",names(arglist2))) {
arglist2$lwd <- 1 ## 20180309 was 'lwd <- 3'
}
if (F & length(ind <- .grep("^border",names(arglist2)))) { ## -- 20220515
arglist2$col <- arglist2[[ind]]
}
}
if (.lgrep("polygon",geoType)) {
if (!.lgrep("lwd",names(arglist2))) {
arglist2$lwd <- 0.1
}
else {
lwd <- arglist2$lwd
if ((is.character(lwd))&&(.lgrep("(km|m)$",lwd))) {
if (.lgrep("km$",lwd))
mul <- 1e3
else if (.lgrep("m$",lwd))
mul <- 1
else
mul <- 1
lwd <- mul*as.numeric(gsub("\\D","",lwd))
cell <- session_cellsize()
sc <- getOption("ursaPngScale")
dpi <- getOption("ursaPngDpi")/96
px <- cell/sc
res <- lwd/px/dpi
# print(data.frame(lwd=lwd,cell=cell,sc=sc,px=px,res=res))
arglist2$lwd <- res
}
else if ((is.numeric(lwd))&&(lwd<=0))
arglist2$lwd <- 1e-6
else if ((is.na(lwd))||(is.null(lwd)))
arglist2$lwd <- 1e-6
}
# str(arglist2)
# str(ct)
}
# str(c(obj=list(spatial_geometry(obj)),add=TRUE,arglist2))
if (isFALSE(arglist2$border))
arglist2$border <- NULL
if ((TRUE)&&(is_spatial_lines(obj))&&("border" %in% names(arglist2))) {
if (isTRUE(arglist2$border)) {
gscale <- median(colSums(col2rgb(arglist2$col)*c(0.30,0.59,0.11)))
arglist2$border <- ifelse(gscale>160,"#000000A0","#FFFFFFA0")
}
arglist3 <- list(lwd=1.25,col=arglist2$border)
if ("lwd" %in% names(arglist2)) {
if (length(arglist2$lwd)==1)
arglist3$lwd <- max(arglist2$lwd*1.3,arglist2$lwd+1.5)
else if (length(arglist2$lwd)==2) {
arglist3$lwd <- max(arglist2$lwd)
arglist2$lwd <- min(arglist2$lwd)
}
}
ret3 <- .tryE(do.call(".panel_plot"
,c(obj=list(spatial_geometry(obj)),add=TRUE,arglist3)))
}
ret <- .tryE(do.call(".panel_plot"
,c(obj=list(spatial_geometry(obj)),add=TRUE,arglist2)))
# str(arglist2)
# str(ret)
arglist2$type <- spatial_geotype(obj)
# options(opE)
}
isSF <- .isSF(obj)
isSP <- .isSP(obj)
}
else if (F & is.list(obj)) {
retname <- names(obj)[1]
ret <- try(.panel_plot(obj[[1]],add=TRUE,...))
str(ret)
q()
}
else {
ret <- try(.panel_plot(obj,add=TRUE,...))
if (inherits(ret,"try-error")) {
opW <- options(warn=1)
warning(paste("Unable to call 'plot' method for class"
,.sQuote(class(obj))
,"\nIt seems that package 'methods' is required."))
options(opW)
ret <- NULL
}
}
aname <- names(arglist2)
# str(arglist2)
if (is_spatial_points(obj)) {
ret <- .legend.skeleton()
ret$name <- oname
ret$type <- "POINT"
ret$col <- arglist2$col
ret$pch <- arglist2$pch
ret$pt.cex <- arglist2$cex
ret$pt.lwd <- arglist2$lwd
ret$pt.bg <- arglist2$bg
ret$border <- "transparent"
}
else {
ret <- .legend.skeleton()
ret$name <- oname
rname <- names(ret)
if (.lgrep("polygon",geoType)) { # 20171215 -- 'if (geoType %in% c("POLYGON","MULTIPOLYGON"))'
ret$pch <- NA
# ret$cex <- 3
}
for (i in seq_along(rname)) {
if (is.na(j <- match(rname[i],aname)))
next
ret[[i]] <- arglist2[[j]]
}
if ((TRUE)&&(.lgrep("line",geoType))) {
##~ str(ret)
##~ str(arglist)
##~ str(arglist2)
##~ q()
if (!is.list(ret$col)) {
.col <- ret$col
ret$col <- ret$border
ret$border <- .col
}
}
if ((TRUE)&&(.lgrep("point",geoType))&&(!is.null(ct))) {
ret$col <- ct$colortable
}
if ((all(ret$bg!="transpareny"))&&(all(ret$border=="transparent"))) {
ret$fill <- ret$bg
}
if ((TRUE)&&(.lgrep("polygon",geoType))) {
if (F & is_ursa(ret$col,"colortable")) {
# rname <- unique(names(ret$col))
ret$fill <- unique(ret$col)
ret$name <- unique(names(ret$col))
# q()
}
else
ret$fill <- ret$col
if (is.null(arglist2$col))
ret$col <- NA
if (is.null(arglist2$lwd))
ret$lwd <- NA
if (is.null(arglist2$lty))
ret$lty <- NA
}
}
if ((is_spatial(obj))&&(isLang)&&(length(spatial_colnames(obj))>0)) {
##~ sink("C:/tmp/res1.out")
##~ str(arglist)
##~ str(obj)
##~ str(eval.parent(arglist[["obj"]]))
##~ str(eval(arglist[["obj"]]))
##~ sink()
# ret$name <- spatial_data(eval(arglist[["obj"]]))[[1]]
if (isTRUE(getOption("ursaNoticeMatchCall")))
message('panel_plot: try `mget(names(match.call())[-1])` instead of `as.list(match.call())`')
ret$name <- spatial_data(eval.parent(arglist[["obj"]]))[[1]]
# if (length(unique(ret$name))==length(ret$pt.bg))
# ret$name <- unique(ret$name)
}
if (FALSE) {
if (length(geoType)>1) {
print(geoType)
# spatial_write(obj,"res1.sqlite")
}
}
# str(ret)
if (!is.null(ct)) {
ct <- ursa_colortable(ct)
ret$name <- names(ct)
if (is_spatial_polygons(obj))
ret$fill <- as.character(ct)
else if (is_spatial_points(obj)) {
ret$pt.bg <- as.character(ct)
}
}
# class(ret) <- "ursaLegend"
if (any(nchar(geoType)>0)) {
opR <- getOption("ursaPngLegend")
options(ursaPngLegend=if (is.null(opR)) list(ret) else c(opR,list(ret)))
}
# if (!is.null(ct))
# return(invisible(ct))
invisible(list(ret))
}
'panel_box' <- function(...){
if (.skipPlot(FALSE))
return(NULL)
bg <- sum(c(col2rgb(getOption("ursaPngBackground")))*c(0.30,0.59,0.11))
if (!length(list(...))) {
box(lwd=0.5,col=ifelse(bg<128,"#FFFFFF7F","#0000007F"))
}
else
box(...)
}
'panel_lines' <- function(...){
if (.skipPlot(TRUE))
return(NULL)
lines(...)
}
'panel_points' <- function(...){
if (.skipPlot(TRUE))
return(NULL)
points(...)
}
'panel_text' <- function(...){
if (.skipPlot(TRUE))
return(NULL)
text(...)
}
'panel_polygon' <- function(...){
if (.skipPlot(TRUE))
return(NULL)
polygon(...)
}
'panel_abline' <- function(...){
if (.skipPlot(TRUE))
return(NULL)
abline(...)
}
'panel_segments' <- function(...){
if (.skipPlot(TRUE))
return(NULL)
segments(...)
}
'.zzz.panel_plot.--20171115' <- function(obj,...){
if (.skipPlot(TRUE))
return(NULL)
if (is.null(obj))
return(obj)
plot(obj,...)
}
'.panel_plot' <- function(obj,...) {
if (.skipPlot(TRUE))
return(NULL)
if (is.null(obj))
return(obj)
arglist <- list(...)
# str(arglist)
arglist <- lapply(arglist,function(x1) {
if (identical(c("index","colortable"),names(x1)))
return(unclass(unname(x1$colortable))[x1$index])
x1
})
if ((TRUE)&&(.isSF(obj))&&(.lgrep("(dens|angl)",names(arglist)))) {
# arglist$add <- NULL
if (!.isPackageInUse())
message("'sf' doesn't deal with fill patterns; converted to 'Spatial'")
if (TRUE)
obj <- sf::as_Spatial(obj)
else if (FALSE) {
arglist$add <- NULL
ret <- lapply(obj,function(x1) {
do.call("polygon",c(unclass(x1),arglist))
})
}
}
pkg <- attr(class(obj),"package")
opW <- NULL
if (is.character(pkg)) {
if (pkg=="sp")
plot <- sp::plot ## unerror "cannot coerce type 'S4' to vector of type 'double'"
opW <- options(warn=-1) ## release 'warn=-1': no warnings
}
##~ message("-----------------")
##~ str(obj)
##~ str(arglist)
##~ message("-----------------")
ret <- do.call("plot",c(list(obj),arglist))
if (!is.null(opW))
options(opW)
ret
}
'.legend.skeleton' <- function()
{
leg <- list(name="legend item",type="default"
,col="transparent",border="transparent",lty=NULL,lwd=NULL,pch=0,cex=NA
,fill="transparent",bg="transparent",density=NA,angle=45)
class(leg) <- "ursaLegend"
leg
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/panel_plot.R
|
'panel_raster' <- function(...)
{
if (.skipPlot(TRUE))
return(NULL)
arglist <- list(...)
kwd <- "raster"
obj <- .getPrm(arglist,name="",default=NULL
,class=list(c("list","ursaRaster"),"ursaRaster","ggmap","character"))
verbose <- .getPrm(arglist,name="verb(ose)*",kwd=kwd,default=FALSE)
if (is.character(obj)) {
cache <- .getPrm(arglist,name="cache",class=c("logical","character"),default=TRUE)
obj <- .geomap(style=obj,cache=cache,verbose=verbose)
}
if (inherits(obj,"ggmap"))
obj <- as.ursa(obj)
if (is.null(obj))
return(invisible(NULL))
useRaster <- .getPrm(arglist,name="useRaster",kwd=kwd,default=NA)
interpolate <- .getPrm(arglist,name="interp(olate)*",kwd=kwd,default=FALSE)
alpha <- .getPrm(arglist,name="(alpha|transp(aren(cy)*)*)"
,kwd=kwd,class=list("numeric","character"),default=NA)
attribution <- .getPrm(arglist,name="(ann(otat)*|attr)",kwd=kwd,default="bottomright")
if (verbose)
str(list(obj=class(obj),useRaster=useRaster,interpolate=interpolate
,alpha=alpha))
if (.is.ursa_stack(obj)) { ## recursive!!! (20160404 has bugs)
if (verbose)
print(match.call())
rel <- as.list(match.call()) ## try mget(names(match.call())[-1])
fun <- as.character(rel[1])
rel <- rel[-1]
rel <- rel[nchar(names(rel))>0]
lastCT <- NULL
for (i in seq_along(obj)) {
rel[["obj"]] <- obj[[i]]
lastCT <- do.call(fun,rel)
}
return(invisible(lastCT))
}
isRGB <- nband(obj) %in% c(2,3,4) & all(band_nNA(obj)>=0) # '==0' is NA used for RGB?
if (isRGB) {
if ((nband(obj)==4)&&(all(band_stat(obj)$sd[1:3]==0))) { ## ++ 20170718
if (TRUE)
obj <- c(obj[1:3]*obj[4]/255,obj[4])
else {
obj <- obj[4]
}
if ((is.numeric(alpha))&&(alpha<1))
obj <- round(obj*alpha)
}
if ((is.numeric(alpha))&&(alpha<1)) {
if (nband(obj) %in% c(1,3)) {
g3 <- session_grid()
session_grid(obj)
obj <- c(obj,ursa_new(round(alpha*255),bandname=paste("Band",nband(obj)+1)))
session_grid(g3)
}
else if (nband(obj) %in% c(4)) {
obj[4] <- round(obj[4]*alpha)
}
}
a <- with(ursa_grid(obj),rasterImage(as.raster(obj),minx,miny,maxx,maxy
,interpolate=interpolate))
ann <- attr(obj,"copyright")
if ((is.character(ann))&&(nchar(.gsub("\\s","",ann))>1)) {
##~ panel_annotation(ann,pos=attribution,cex=0.7,font="Arial Narrow"
##~ ,fg=sprintf("#000000%s","4F"))
options(ursaPngCopyright=c(getOption("ursaPngCopyright"),ann))
}
return(invisible(NULL))
}
# .panel_raster(colorize(obj,...),useRaster=useRaster
# ,interpolate=interpolate,alpha=alpha,verbose=verbose)
##~ .panel_raster(obj,useRaster=useRaster
##~ ,interpolate=interpolate,alpha=alpha,verbose=verbose,...)
##~ }
##~ '.panel_raster' <- function(obj,useRaster=NA,interpolate=FALSE,alpha=NA
##~ ,verbose=FALSE,...) {
##~ if (.skipPlot(TRUE))
##~ return(NULL)
# if (!getOption("ursaBackground"))
# panel_new()
# print(obj)
# q()
# print(c(isCT=.is.colortable(obj),isC=obj$category))
isCT <- .is.colortable(obj) & .is.category(obj) # & attr(obj$value,"category")
if (isCT)
ct <- ursa_colortable(obj)
scale <- getOption("ursaPngScale")
e <- band_nNA(obj)
isRGB <- nband(obj) %in% c(2,3,4) & all(band_nNA(obj)>=0) # '==0' is NA used for RGB?
g1 <- getOption("ursaPngPanelGrid")
if (ursa_crs(g1)!=ursa_crs(obj))
obj <- .gdalwarp(obj,grid=g1)
toResample <- floor(1/scale)>1 & !isRGB
if (is.na(useRaster)) {
cond1 <- getOption("ursaPngDevice")!="windows"
cond2 <- !(tolower(gsub(".*\\.(\\S+)$","\\1"
,getOption("ursaPngFileout"))) %in% c("svg"))
useRaster <- cond1 && cond2
}
if (verbose)
str(list(isRGB=isRGB,isCT=isCT,toResample=toResample,isColorTable=isCT
,useRasrer=useRaster))
if (toResample)
{
# obj <- contract(obj,size=sc,verbose=TRUE)
# obj <- resampl4(obj,resize=1/sc,area=0,verbose=TRUE)
g2 <- ursa_grid(obj)
# if (isCT) {
# obj <- reclass(obj)
# }
# if (isCT)
# print(as.table(obj))
obj <- regrid(obj,mul=scale,resample=ifelse(isCT,-1,1)
,verbose=verbose)#,resetGrid=TRUE)
# if ((TRUE)&&(isCT)) { ## FALSE?
# obj <- reclass(discolor(obj),ct) ## round(obj)?
# }
}
##~ if (isRGB) {
##~ with(ursa_grid(obj),rasterImage(as.raster(obj),minx,miny,maxx,maxy
##~ ,interpolate=interpolate))
##~ return(NULL)
##~ }
arglist <- list(...)
if (!isCT) {
if (!.is.colortable(obj)) {
arglist[[1]] <- quote(obj)
obj <- do.call("colorize",arglist)
}
else if (!.is.category(obj)) { # attr(obj$value,"category")
obj <- reclass(obj)
}
}
else if (all(is.na(ct))) {
val <- .deintervale(ct)
if (is.numeric(val)) {
if (length(val)==length(ct)) {
arglist$value <- val
}
else {
stop("TODO: interval")
}
}
else {
arglist$value <- seq(length(ct))-1L ## val
arglist$name <- names(ct)
}
arglist$stretch <- ".onetoone"
arglist <- c(quote(obj),arglist)
arglist[[1]] <- quote(obj)
obj <- do.call("colorize",arglist)
}
if (!is.na(alpha)) { ## ?adjustcolor
if ((is.numeric(alpha))&&(alpha>=0)&&(alpha<=1))
alpha <- paste0(toupper(sprintf("%x",round(alpha*255))))
else if ((is.numeric(alpha))&&(alpha>=0)&&(alpha<=255))
alpha <- paste0(toupper(sprintf("%x",round(alpha))))
else if (is.character(alpha)) {
a <- as.numeric(paste0("0x",alpha))
if ((a<0)||(a>255))
alpha <- NA
}
else
alpha <- NA
if (!is.na(alpha)) {
if (nchar(alpha)<2)
alpha <- paste0("0",alpha)
ctname <- names(obj$colortable)
ursa_colortable(obj) <- paste0(substr(ursa_colortable(obj),1,7),alpha)
names(obj$colortable) <- ctname
}
}
img <- as.matrix(obj,coords=TRUE)
g1 <- ursa_grid(obj) #session_grid()
xo <- with(g1,seq(minx,maxx,len=columns+1L))
yo <- with(g1,seq(miny,maxy,len=rows+1L))
if (!FALSE)
{
xo <- xo[-1]-g1$resx/2
yo <- yo[-1]-g1$resy/2
}
if ((FALSE)&&(useRaster))
{
xo <- xo-0.5*g1$resx/scale
yo <- yo+0.5*g1$resy/scale
}
if (.is.colortable(attr(img,"colortable")))
{
col <- as.character(attr(img,"colortable"))
zlim <- c(1,length(col))-1
}
else ## color ramp
{
col <- 1:255
if (any(!is.na(img$z)))
zlim <- range(img$z,na.rm=TRUE)
else
zlim <- range(col)
}
if ((verbose)&&(!useRaster))
.elapsedTime(paste0("useRaster=",useRaster,"--start"))
# require(grid)
# a <- grDevices::as.raster(t(img$z)/max(img$z,na.rm=TRUE))
# grid.raster(a,x=unit(0.5,"npc"),y=unit(0.5,"npc"),interpolate=FALSE)
image(x=xo,y=yo,z=img$z,col=col,asp=NA,zlim=zlim,useRaster=useRaster,add=TRUE)
##### rasterImage(img$z,min(xo),min(yo),max(xo),max(yo),)
if ((verbose)&&(!useRaster))
.elapsedTime(paste0("useRaster=",useRaster,"--finish"))
if (toResample)
session_grid(g2)
col1 <- col2rgb(obj$colortable,alpha=TRUE)/255
isAlpha <- any(col1[4,]!=1)
ann <- c(getOption("ursaPngCopyright"),attr(obj,"copyright"))
if (sum(nchar(ann)))
options(ursaPngCopyright=ann)
# if ((is.character(ann))&&(nchar(.gsub("\\s","",ann))>1))
# panel_annotation(ann,pos="bottomright",cex=0.7,font="Arial Narrow"
# ,fg=sprintf("#000000%s",ifelse(isAlpha,alpha,"4F")))
if (!isAlpha)
return(invisible(obj$colortable))
if (is.na(alpha))
col1[4,] <- 1-col1[4,]
bg <- col2rgb(getOption("ursaPngPanel"),alpha=TRUE)/255
col2 <- apply(col1,2,function(x) x*c(bg))
if ((TRUE)||(identical(col1,col2))) ## 20170522 added TRUE
return(invisible(obj$colortable))
alphaPatch <- ifelse(!is.na(alpha),1,1-1e-2) ## desured to be 1
col3 <- rgb(col2[1,],col2[2,],col2[3,],col2[4,]*alphaPatch,maxColorValue=1)
ct1 <- ursa_colortable(obj)
ct2 <- ursa_colortable(col3)
names(ct2) <- names(ct1)
# str(obj$colortable)
# print(col1)
# print(col2)
# str(ct2)
invisible(ct2)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/panel_raster.R
|
'panel_scalebar' <- function(...) {
if (.skipPlot(TRUE))
return(invisible(NULL))
arglist <- list(...)
kwd <- "(ruler|scalebar)"
scalebar <- .getPrm(arglist,name=gsub("\\)","|decor)$",kwd)
,class=list("integer","logical")
,default=TRUE)
if (is.integer(scalebar))
scalebar <- getOption("ursaPngFigure") %in% scalebar
if (!scalebar) {
# scalebar <- .getPrm(arglist,name=kwd,coerce=FALSE,verb=TRUE,default=NULL)
# str(scalebar)
return(NULL)
}
position <- .getPrm(arglist,name="pos(ition)*",kwd=kwd
,class=list("character","numeric"),default="---")
g0 <- session_grid()
canScale <- .lgrep("(epsg:3857|\\+proj=(merc|zzzzz)\\s)",g0$crs)>0
if ((all(position=="---"))&&(canScale)) {
lat <- with(g0,.project(rbind(c(minx,miny),c(maxx,maxy)),crs,inv=TRUE))[,2]
sc <- sort(1/cos(lat*pi/180))
if (sc[2]/sc[1]>1.25)
position <- c("bottomleft","topleft")
}
if (position[1]=="---")
position <- "bottomleft"
w <- .getPrm(arglist,name="w",kwd=kwd,class=list("numeric","character")
,default=NA_real_)
cex <- .getPrm(arglist,name="cex",kwd=kwd,default=0.75)
bg <- sum(c(col2rgb(getOption("ursaPngBackground")))*c(0.30,0.59,0.11))
defcol <- ifelse(bg<128,"#FFFFFF2F","#0000002F")
col <- .getPrm(arglist,name="col",kwd=kwd,default=defcol)
bg <- .getPrm(arglist,name="bg",kwd=kwd,default="transparent")
fill <- .getPrm(arglist,name="fill",kwd=kwd,default="transparent") # "#FFFFFF3F"
language <- .getPrm(arglist,name="lan(g(uage)*)*",kwd=kwd,default=NA_character_)
verbose <- .getPrm(arglist,name="verb(ose)*",kwd=kwd,default=FALSE)
if (is.character(position)) {
for (pos in position)
.panel_scalebar(position=pos,w=w,cex=cex,col=col,bg=bg,fill=fill
,language=language,verbose=verbose)
}
else {
.panel_scalebar(position=position,w=w,cex=cex,col=col,bg=bg,fill=fill
,language=language,verbose=verbose)
}
invisible(NULL)
}
'.panel_scalebar' <- function(position="bottomleft",w=NA,cex=0.85
,col="#0000002F",bg="transparent",fill="#FFFFFF2F"
,language=NA,verbose=FALSE) {
if (.skipPlot(TRUE))
return(invisible(NULL))
indirect <- getOption("ursaPngAuto")
if (!is.logical(indirect))
indirect <- FALSE
if (verbose)
str(list(position=position,w=w,cex=cex,col=col,bg=bg,fill=fill,verbose=verbose))
g1 <- session_grid()
paperScale <- getOption("ursaPngPaperScale")
if (is.na(language)) {
if (TRUE) {
ctype <- Sys.getlocale("LC_TIME")
if (.lgrep("Russian",ctype))
language <- "ru"
}
else
language <- Sys.getenv("LANGUAGE")
}
pos <- position
if (is.factor(pos))
pos <- as.character(pos)
if (is.character(pos))
pos <- switch(pos,center=c(0.5,0.5),top=c(0.5,1),bottom=c(0.5,0)
,left=c(0,0.5),right=c(1,0.5),topleft=c(0,1),topright=c(1,1)
,bottomleft=c(0,0),bottomright=c(1,0),{
message(sprintf("'%s' is invalid keyword",pos))
match.arg(pos,c("center","top","bottom","left","right"
,"topleft","topright"
,"bottomleft","bottomright"))
})
if (!((is.numeric(pos))&&(length(pos)==2))) {
opW <- options(warn=1)
warning("Unable to detect 'position'. Skipping scalebar")
options(opW)
return(invisible(NULL))
}
isLonLat <- .lgrep("(\\+proj=longlat|epsg:4326)",g1$crs)>0
if ((isLonLat)||((TRUE)&&(!nchar(g1$crs))))
return(invisible(NULL))
isGeo <- nchar(g1$crs)>0
if ((indirect)&&(!isGeo))
return(invisible(NULL))
dx <- with(g1,maxx-minx)
dy <- with(g1,maxy-miny)
isMerc <- .lgrep("(\\+proj=merc|epsg\\:3857)",g1$crs)>0
if (isMerc) {
x3 <- pos[1]
if (pos[1]<0.1)
x3 <- 0.1
else if (pos[1]>0.9)
x3 <- 0.9
y3 <- pos[2]
if (pos[2]<0.05)
y3 <- 0.05
else if (pos[2]>0.95)
y3 <- 0.95
lat <- with(g1,.project(cbind(minx+x3*(maxx-minx),miny+y3*(maxy-miny))
,g1$crs,inv=TRUE))#[1,2]
lat_ts <- .gsub2("\\+lat_ts=(\\S+)\\s","\\1",g1$crs)
lat_ts <- ifelse(lat_ts==g1$crs,0,as.numeric(lat_ts))
sc <- if (is.null(lat)) 1 else 1/cos((lat[1,2]-lat_ts)*pi/180)
}
else
sc <- 1
mycex <- cex/par()$cex
w0 <- 15*strheight("M",units="user",cex=mycex)/sc
# w0 <- (180/sc)*g1$resx/getOption("ursaPngScale") ## desired width 180 pxls
# print(c(new=w1,old=w0,r=w0/w1))
if (w0>0.6*dx) {
w0 <- 0.6*dx
}
w0 <- w0/3000
if (is.character(w)) {
wVal <- as.numeric(.gsub("^(\\d+(\\.\\d+)*)([A-Za-z\\s])*$","\\1",w))
wUn <- .gsub("^(\\d+(\\.\\d+)*)\\s*([A-Za-z]+)*$","\\3",w)
w <- wVal*switch(wUn,km=1,m=1e-3,mm=1e-6)
}
if (verbose)
print(c(manual=w,auto=w0))
if ((is.na(w))||(w<=0)) {
scW <- 10
# if (isMerc)
# w <- (0.08/sc)*dx/1000
# else
w <- w0
# print(c(sc=sc,scF=scF,resx=g1$resx,w=w,lw=g1$columns*scF
# ,pr=(180/3)*g1$resx/1000/scF))
# q()
# w <- (0.08/sc)*max(dx,dy)/1000
manualW <- FALSE
}
else {
scW <- 1
manualW <- TRUE
}
if (TRUE) {
if (!manualW) {
w0 <- c(10,12,15,16,20,25,30,40,50,60,70,80,90)
for (i in c(-6:6)) {
if (w<=10^i)
break
}
w1 <- w0*10^(i-2)
w <- w1[which.min(abs(w1-w))]
}
if (w<1e-6) {
# print(w)
message(paste0("Nano scale of scalebar length (",w,") is ignored"))
return(invisible(NULL))
}
else if (w<1e-3) {
w0 <- w*1e6
un <- switch(language,ru="\u043C\u043C","mm")
}
else if (w<1) {
w0 <- w*1000
un <- switch(language,ru="\u043C","m")
}
else {
w0 <- w
un <- switch(language,ru="\u043A\u043C","km")
}
}
else
w0 <- w*1000
if ((!manualW)&&(paperScale[1]!=0)) { ## 20171019 ++ (!manualW)
pw <- par()$fin[1]*2.54
w1 <- paperScale[2]/(pw*sc) ## 1cm or 'paperScale[2] cm'
if (w1<1)
{
w1 <- w1*dx
if (w1<1000) {
if (FALSE) {
wP <- pretty(w1,n=20)
w0 <- wP[which.min(abs(wP-w1))[1]]
}
else if (paperScale[1]>0) {
w0 <- paperScale[1]*1e3
}
else {
e <- 1e0
w0 <- round(w1/e,0)*e
}
message(paste("Composer: figure width for"
,sprintf("1:%.0f",w0*100/paperScale[2]),"scale is"
,pw*(w1/paperScale[2])/(w0),"cm"))
un <- switch(language,ru="\u043C","m")
}
else {
if (paperScale[1]>0)
w0 <- paperScale[1]
else
w0 <- round(w1/1000,0) ## ,1 for tuning
# if (as.integer(w0)!=w0)
message(paste("Composer: figure width for"
,sprintf("1:%.0f",w0*100000/paperScale[2]),"scale is"
,pw*(w1/paperScale[2])/(1000*w0),"cm"))
un <- switch(language,ru="\u043A\u043C","km")
}
w <- w1/1000
# print(w)
# print(w0)
# print(un)
}
}
if (!nchar(g1$crs))
un <- ""
w <- w*sc
##~ if (pos[1]<0.5) {
##~ x1 <- g1$minx+pos[1]*dx
##~ x2 <- x1+3*w*1000
##~ }
##~ else {
##~ x2 <- g1$maxx-(1-pos[1])*dx
##~ x1 <- x2-3*w*1000
##~ }
h <- strheight("M",units="user",cex=mycex)
lu <- strwidth(paste0("n",un),units="user",cex=mycex)
lw <- strwidth(paste0(w0,"|"),units="user",cex=mycex)/2
ls <- strwidth("n",units="user",cex=mycex)/2
lw2 <- strwidth(paste0(2*w0,""),units="user",cex=mycex)/2
lw3 <- max(lw2,lu)
h2 <- 0.25*h
hs <- 0.3*h
h3 <- 0.8*h
h4 <- h2+1.7*h
x1 <- g1$minx+pos[1]*dx-1.5*w*1000
x2 <- x1+3.0*w*1000
if ((x1-lw)<g1$minx) {
x1 <- g1$minx+lw
x2 <- x1+3.0*w*1000
}
else if ((x2+lw3)>g1$maxx) {
x2 <- g1$maxx-lw3
x1 <- x2-3.0*w*1000
}
y1 <- g1$miny+pos[2]*dy
if ((y1-h3)<g1$miny)
y1 <- g1$miny+h3
else if ((y1+h4)>g1$maxy)
y1 <- g1$maxy-h4
# print(pos)
# print(c(x1=x1,x2=x2,y0=y1))
# print(g1)
xo <- seq(x1,x2,length=7)[-c(4,6)]#+ifelse(pos[1]>=0.5,-max(lu,lw2),lw)
yo <- seq(y1-hs,y1+hs,length=3)#+ifelse(pos[2]>=0.5,-h-3*h2,h)
rect(min(xo)-1.0*lw,y1-h3,max(xo)+1.0*lw3,max(yo)+h4
,col=bg,border="transparent")
if (TRUE)
rect(xo[1],yo[1],xo[5],yo[3],lwd=1,border=col,col=fill)
else {
rect(xo[1],yo[1],xo[2],yo[2],lwd=1,border=col,col="transparent")
rect(xo[2],yo[2],xo[3],yo[3],lwd=1,border=col,col="transparent")
rect(xo[3],yo[1],xo[4],yo[2],lwd=1,border=col,col="transparent")
rect(xo[4],yo[2],xo[5],yo[3],lwd=1,border=col,col="transparent")
}
rect(xo[1],yo[2],xo[2],yo[3],lwd=1,border="transparent",col=col)
rect(xo[2],yo[1],xo[3],yo[2],lwd=1,border="transparent",col=col)
rect(xo[3],yo[2],xo[4],yo[3],lwd=1,border="transparent",col=col)
rect(xo[4],yo[1],xo[5],yo[2],lwd=1,border="transparent",col=col)
text(xo[1],yo[3]+h2,w0,col=col,cex=mycex,adj=c(0.5,-0.2)
,family=getOption("ursaPngFamily")
)
text(xo[3],yo[3]+h2,0,col=col,cex=mycex,adj=c(0.5,-0.2)
,family=getOption("ursaPngFamily")
)
text(xo[4],yo[3]+h2,w0,col=col,cex=mycex,adj=c(0.5,-0.2)
,family=getOption("ursaPngFamily")
)
text(xo[5],yo[3]+h2,2*w0,col=col,cex=mycex,adj=c(0.5,-0.2)
,family=getOption("ursaPngFamily")
)
text(xo[5]+ls,yo[2],un,col=col,cex=mycex,adj=c(0,0.5)
,family=getOption("ursaPngFamily")
) ## adj=c(0,0.6)
invisible(NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/panel_scalebar.R
|
'panel_shading' <- function(obj,level=NA,col=NULL,density=25,angle=c(-45,45)
,lwd=1,lty=1,verbose=TRUE)
{
if (.skipPlot(TRUE))
return(NULL)
if (!is.ursa(obj))
return(NULL)
g1 <- session_grid()
if (is.null(col)) {
if (.is.colortable(obj))
col <- ursa_colortable(obj)
else if (.is.colortable(col))
col <- ursa_colortable(col)
else
col <- "#0000002F"
}
col <- range(col)
if ((is.numeric(level))&&(level>0)) {
obj <- discolor(obj)
obj[abs(obj)<level] <- NA
}
obj <- as.data.frame(obj)
if (!nrow(obj))
return(NULL)
# scale <- getOption("ursaPngScale")
# res <- with(g1,sqrt(resx*resy))
dens <- density # (1/scale)*density#/par()$cex
if (verbose)
{
# print(c(original=density,applied=dens,cex=par()$cex,scale=scale,res=res/1e3))
pb <- ursaProgressBar(min=0,max=nrow(obj),tail=TRUE)
# cat("dashing start...")
}
for (i in seq(nrow(obj)))
{
x1 <- obj$x[i]-g1$resx/2
x2 <- obj$x[i]+g1$resx/2
y1 <- obj$y[i]-g1$resy/2
y2 <- obj$y[i]+g1$resy/2
s <- sign(obj[i,3])>=0
for (j in angle)
polygon(c(x1,x1,x2,x2,x1),c(y1,y2,y2,y1,y1)
,density=dens,angle=j #sign(obj[i,3])*45*j
,border=NA,col=ifelse(!s,col[1],col[2]),lwd=0.8*lwd,lty=lty)
if (verbose)
setUrsaProgressBar(pb,i)
}
if (verbose) {
close(pb)
# cat("done!\n")
}
NULL
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/panel_shading.R
|
'pixelsize' <- function(obj,verbose=FALSE) {
if (missing(obj))
g1 <- session_grid()
else if (is.ursa(obj))
g1 <- ursa_grid(obj)
else if (.is.grid(obj))
g1 <- obj
else if (is.null(obj)) {
session_grid(NULL)
g1 <- session_grid()
}
if (.lgrep("\\+proj=stere",g1$crs))
return(.pxlsize.stere(g1,verbose=verbose))
if (.lgrep("\\+proj=merc",g1$crs))
return(.pxlsize.merc(g1,verbose=verbose))
mul <- if (with(g1,resx*resy)<1e5) c("sq.m"=1) else c("sq.km"=1e-6)
ursa_new(value=with(g1,resx*resy*mul)
,bandname=paste0("Pixel Size (",names(mul),")"),ignorevalue=-99L)
}
'.pxlsize.merc' <- function(g,verbose=FALSE) {
mul <- if (with(g,resx*resy)<1e5) c("sq.m"=1) else c("sq.km"=1e-6)
a <- ursa_new(value=0,bandname=paste0("Pixel Size (",names(mul),")"))
da <- as.data.frame(a)
lat <- .project(with(da,cbind(x,y)),g$crs,inv=TRUE)[,2]
# ursa_value(a) <- with(g,resx*resy*mul/cos(lat*pi/180))
a$value[] <- with(g,resx*resy*mul/cos(lat*pi/180))
a
}
'.pxlsize.stere' <- function(g,verbose=FALSE) {
# https://en.wikibooks.org/wiki/PROJ.4
'.pow' <- function(x,y) x^y
proj4 <- g$crs
if (FALSE)
semi <- c("6378137","6356752.3") ## low-precision
if (.lgrep("\\+datum=WGS84",proj4))
semi <- c("6378137","6356752.314245179")
else if (.lgrep("\\+ellps=WGS84",proj4))
semi <- c("6378137","6356752.314245179")
else if (.lgrep("\\+ellps=krass",proj4))
semi <- c("6378245","6356863.018773047")
else {
semi <- c(.gsub2("\\s\\+a=(\\S+)\\s","\\1",proj4)
,.gsub2("\\s\\+b=(\\S+)\\s","\\1",proj4)
,.gsub2("\\s\\+rf=(\\S+)\\s","\\1",proj4)
)
semi <- semi[nchar(semi)<nchar(proj4)]
}
semi <- as.numeric(semi)
lat_ts <- as.numeric(.gsub2("\\s\\+lat_ts=(\\S+)\\s","\\1",proj4))
lat0 <- as.numeric(.gsub2("\\s\\+lat_0=(\\S+)\\s","\\1",proj4))
lon0 <- as.numeric(.gsub2("\\s\\+lon_0=(\\S+)\\s","\\1",proj4))
x0 <- as.numeric(.gsub2("\\s\\+x_0=(\\S+)\\s","\\1",proj4))
y0 <- as.numeric(.gsub2("\\s\\+y_0=(\\S+)\\s","\\1",proj4))
if (.lgrep("\\s\\+k=(\\S+)\\s",proj4))
scale <- as.numeric(.gsub2("\\s\\+k=(\\S+)\\s","\\1",proj4))
else
scale <- 1
major <- max(semi)
minor <- min(semi)
if (minor<6300000)
minor <- major*(1-1/minor) ## +rf=298.278...
ecentr2 <- 1-minor*minor/(major*major)
ecentr <- sqrt(ecentr2)
if (verbose)
print(c(lat0=lat0,lat_ts=lat_ts,lon0=lon0,k=scale,x0=x0,y0=y0
,a=major,b=minor),digits=16)
xlon <- 0
ylat <- 90
xlon <- pi*xlon/180.0
ylat <- pi*ylat/180.0
lat_ts <- (90-lat_ts)*pi/180
fi0 <- pi*lat0/180
sinfi0 <- sin(fi0)
cosfi0 <- cos(fi0)
lamba0 <- pi*lon0/180.0
sinlamba0 <- sin(lamba0)
coslamba0 <- cos(lamba0)
if (lat_ts==0.0)
perimper4 <- 2*scale*major*major/minor*
.pow((1-ecentr)/(1+ecentr),ecentr/2)
else {
Rk <- major*sin(lat_ts)/sqrt(1-ecentr2*cos(lat_ts)*cos(lat_ts))
Uk <- ((1+cos(lat_ts))/sin(lat_ts))*
.pow((1-ecentr*cos(lat_ts))/(1+ecentr*cos(lat_ts)),ecentr/2)
perimper4=scale*Rk*Uk;
}
fi1 <- acos(sin(ylat)*sinfi0+cos(ylat)*cosfi0*cos(xlon-lamba0))
d1 <- cos(ylat)*sin(xlon-lamba0)
d2 <- sin(ylat)*cosfi0-sinfi0*cos(ylat)*cos(xlon-lamba0)
if (d2==0.0)
lamba1 <- 0.0
else if (d2>0.0)
lamba1 <- atan(d1/d2)
else if (d2<0.0)
lamba1 <- atan(d1/d2)+pi
dist <- perimper4*(sin(fi1)/(1+cos(fi1)))*
.pow((1+ecentr*cos(fi1))/(1-ecentr*cos(fi1)),ecentr/2)
xshift <- -dist*scale*sin(lamba1)+x0
yshift <- -dist*scale*cos(lamba1)+y0
mul <- if (with(g,resx*resy)<1e5) c("sq.m"=1) else c("sq.km"=1e-6)
ps <- ursa_new(value=0,bandname=paste0("Pixel Size (",names(mul),")")
,ignorevalue=-99L)
da <- as.data.frame(ps)
x1 <- da$x+xshift
y1 <- da$y+yshift
lamba1 <- rep(0,length(y1))
if (length(ind <- which(y1>0)))
lamba1[ind] <- atan(x1[ind]/y1[ind])
if (length(ind <- which(y1<0)))
lamba1[ind] <- atan(x1[ind]/y1[ind])+pi
fi1 <- rep(NA,length(lamba1))
if (length(ind <- which(sin(lamba1)==0)))
fi1[ind] <- 2*atan(y1[ind]/(perimper4*cos(lamba1[ind])));
if (length(ind <- which(sin(lamba1)!=0)))
fi1[ind] <- 2*atan(x1[ind]/(perimper4*sin(lamba1[ind])));
val <- (1.0/scale)*(1+cos(fi1))/(1+cos(lat_ts))*
.pow((1+ecentr*cos(lat_ts))/(1-ecentr*cos(lat_ts)),ecentr/2)*
.pow((1-ecentr*cos(fi1))/(1+ecentr*cos(fi1)),ecentr/2);
# ursa_value(ps) <- val*val*with(g,resx*resy)*mul
ps$value[] <- val*val*with(g,resx*resy)*mul
ps
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/pixelsize.R
|
'polygonize' <- function(obj,fname,engine=c("native","sp","sf")
,verbose=NA,...) {
# class(obj)
missing(obj) ## keep`session_grid` from reset in `a <- polygonize(envi_read())`
engine <- match.arg(engine)
if (engine=="sp") {
isSF <- FALSE
isSP <- TRUE
}
else if (engine=="sf") {
isSF <- requireNamespace("sf",quietly=.isPackageInUse())
isSP <- !isSF
}
else {
loaded <- loadedNamespaces() # .loaded()
if ("sf" %in% loaded)
isSF <- TRUE
else if (("sp" %in% loaded)||("rgdal" %in% loaded))
isSF <- FALSE
else
isSF <- requireNamespace("sf",quietly=.isPackageInUse())
isSP <- !isSF
}
if ((!is.na(verbose))&&(verbose))
print(c(isSP=isSP,isSF=isSF))
if (is.na(verbose))
verbose <- isSP
g0 <- session_grid()
if ((!missing(obj))&&(is.numeric(obj))&&(length(obj)==4)&&
((!anyNA(match(names(obj),c("minx","maxx","miny","maxy"))))||
(!anyNA(match(names(obj),c("xmin","xmax","ymin","ymax")))))) {
obj <- regrid(bbox=unname(obj),dim=c(1,1),crs=session_crs())
}
onlyGeometry <- missing(obj) || .is.grid(obj)
isList <- !onlyGeometry && .is.ursa_stack(obj)
if ((!isList)&&(!((onlyGeometry)||(is.ursa(obj))||(is.data.frame(obj))))) ## propose?
# if ((!isList)&&(!(is.ursa(obj))))
return(NULL)
# requireNamespace("sp",quietly=.isPackageInUse())
# requireNamespace("methods",quietly=.isPackageInUse())
# obj$grid$seqy <- nuimeric()
g1 <- if (onlyGeometry) {
if (missing(obj))
session_grid()
else
ursa(obj,"grid")
}
else if (isList)
ursa_grid(obj[[1]])
else
ursa_grid(obj)
if (is.null(g1))
g1 <- g0
prj <- ursa_proj(g1)
if (onlyGeometry)
b <- as.data.frame(g1)
else if (isList) {
for (i in seq_along(obj)) {
b0 <- as.data.frame(obj[[i]],na.rm=FALSE)
b <- if (i==1) b0 else cbind(b,b0[,3:ncol(b0),drop=FALSE])
}
ind <- which(apply(b[,3:ncol(b),drop=FALSE],1,function(x) all(is.na(x))))
if (length(ind))
b <- b[-ind,]
}
else if (is.ursa(obj)) {
if (length(ind <- attr(obj$value,"sparse"))) {
val <- data.frame(unclass(ursa_value(obj)),check.names=FALSE)
colnames(val) <- names(obj)
b <- cbind(data.frame(t(coord_cr(obj,ind))),val)
attr(b,"crs") <- ursa_crs(obj)
}
else {
b <- as.data.frame(obj)
}
}
else
b <- obj
# b <- b[sample(seq(nrow(b)),1e3),]
n <- nrow(b)
sa <- vector("list",n)
if (!length(g1$seqx))
dx <- g1$resx/2
else {
dx <- diff(g1$seqx)
dx <- (c(head(dx,1),dx)+c(dx,tail(dx,1)))/2
ind <- match(b$x,g1$seqx) ## or .near?
if (anyNA(ind))
stop("TODO: near matching (x-axis)")
dx <- dx[ind]/2
}
if (!length(g1$seqy))
dy <- g1$resy/2
else {
dy <- diff(g1$seqy)
dy <- (c(head(dy,1),dy)+c(dy,tail(dy,1)))/2
ind <- match(b$y,g1$seqy) ## or .near?
if (anyNA(ind))
stop("TODO: near matching (y-axis)")
dy <- dy[ind]/2
}
if (isSF) {
if (verbose)
cat("1 of 3: create polygons from points...")
xy <- cbind(b$x-dx,b$y-dy,b$x-dx,b$y+dy,b$x+dx,b$y+dy,b$x+dx,b$y-dy
,b$x-dx,b$y-dy)
if (!onlyGeometry) {
b <- b[,3:ncol(b),drop=FALSE]
for (i in seq(ncol(b))) {
if ((!is.factor(b[,i]))&&(.is.integer(na.omit(b[,i]))))
b[,i] <- as.integer(b[,i])
}
}
sa <- apply(xy,1,function(x) {
res <- list(matrix(x,ncol=2,byrow=TRUE))
class(res) <- c("XY","POLYGON","sfg")
## check for new versions of 'sf':
# res2 <- sf::st_polygon(res);print(identical(res,res2));q()
res
})
if (verbose)
cat(" done!\n2 of 3: create geometry...")
sa <- sf::st_sfc(sa)
if (verbose)
cat(" done!\n")
if (!onlyGeometry) {
if (verbose)
cat("3 of 3: assign data to geometry...")
p4s <- if (nchar(g1$crs)) g1$crs else sf::NA_crs_
sa <- sf::st_sf(b,coords=sa,crs=p4s)
if (verbose)
cat(" done!\n")
}
else {
if (verbose)
cat("3 of 3: assign data to geometry... skipped!\n")
sf::st_crs(sa) <- .p4s2epsg(g1$crs)
# spatial_crs(sa,verbose=TRUE) <- g1$crs ## alt
}
if ((TRUE)&&(!onlyGeometry)) { ## ++ 20171128
colnames(sa)[head(seq(ncol(sa)),-1)] <- colnames(b)
}
}
else if (isSP) {
if (verbose) {
pb <- ursaProgressBar(min=0,max=n,tail=TRUE)
i <- -1
repeat({
n1 <- n*(10^i)
if (n1<100)
break
i <- i-1
})
n1 <- 10^(-i-1)
}
for (i in seq(n))
{
x <- b$x[i]+c(-dx,-dx,+dx,+dx,-dx)
y <- b$y[i]+c(-dy,+dy,+dy,-dy,-dy)
sa[[i]] <- sp::Polygons(list(sp::Polygon(cbind(x,y))),i)
if ((verbose)&&(i%%n1==0))
setUrsaProgressBar(pb,i)
}
if (verbose)
close(pb)
sa <- sp::SpatialPolygons(sa,proj4string=sp::CRS(prj,doCheckCRSArgs=FALSE))
if (!onlyGeometry) {
b <- b[,3:ncol(b),drop=FALSE]
for (i in seq(ncol(b)))
if ((!is.factor(b[,i]))&&(.is.integer(na.omit(b[,i]))))
b[,i] <- as.integer(b[,i])
sa <- sp::SpatialPolygonsDataFrame(sa,data=b,match.ID=FALSE)
}
}
if (!missing(fname)) {
# return(.shp.write(sa,fname,...))
return(spatial_write(sa,fname,verbose=verbose,...))
}
session_grid(g0)
sa
}
'.vectorize' <- function(obj,fname,opt="",engine=c("sf","sp"),verbose=FALSE) {
stopifnot('\'gdal_polygonize.py\' not found'=!nchar(Sys.which("gdal_polygonize.py"))==0)
engine <- match.arg(engine)
if (engine=="sp") {
isSF <- FALSE
isSP <- TRUE
}
else if (engine=="sf") {
isSF <- requireNamespace("sf",quietly=.isPackageInUse())
isSP <- !isSF
}
else {
loaded <- loadedNamespaces() # .loaded()
if ("sf" %in% loaded)
isSF <- TRUE
else if (("sp" %in% loaded)||("rgdal" %in% loaded))
isSF <- FALSE
else
isSF <- requireNamespace("sf",quietly=.isPackageInUse())
isSP <- !isSF
}
internal <- missing(fname)
if (internal) {
bname <- .maketmp() # tempfile()
fname <- paste0(bname,".shp")
}
Fout <- .maketmp()
write_envi(obj,paste0(Fout,"."))
cmd <- paste("python",Sys.which("gdal_polygonize.py")
,opt," -f \"ESRI Shapefile\"",Fout,fname)
if (verbose)
print(cmd)
system(cmd)
envi_remove(Fout)
if (!internal)
return(0L)
ret <- spatialize(fname,engine=engine)
list1 <- dir(path=dirname(bname),pattern=paste0("^",basename(bname)),full.names=TRUE)
file.remove(list1)
ret
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/polygonize.R
|
'ursaProgressBar' <- function(kind=c("tk","txt")
# ,title=basename(strsplit(commandArgs(FALSE)[4],"=")[[1]][2])
,title=.argv0(),label=""
,min=0,max=1,initial=min,width=NA,style=1
,tail=FALSE,silent=FALSE) {
if (isPackageTest <- isTRUE(Sys.getenv("_R_CHECK_PACKAGE_NAME_")=="ursa"))
silent <- TRUE
if (silent) {
pb <- logical()
class(pb) <- "ursaProgressBar"
return(pb)
}
# if (.isKnitr())
# return(NULL)
if (!.try(kind0 <- match.arg(kind),silent=TRUE)) {
n <- length(kind)
max <- if ((n==1)&&(is.numeric(kind))&&(.is.integer(kind))) kind else n
kind <- head(eval(formals()$kind),1)
}
else
kind <- kind0
if (kind=="tk") {
Rver <- R.Version()
if ((.Platform$OS.type=="unix")&&(!nchar(Sys.getenv("DISPLAY"))))
kind <- "txt"
else if ((!requireNamespace("tcltk",quietly=.isPackageInUse()))||
(!capabilities("tcltk"))||((Rver$'svn rev' %in% c("78619"))&&(Rver$arch %in% c("x86_64"))))
kind <- "txt"
}
if ((!is.na(title))&&(!nchar(title)))
title <- "'ursa' package"
t1 <- proc.time()[3]
names(t1) <- title
st <- c(t1,prev=unname(t1),delta=0,min=min,max=max,current=initial
,tail=as.numeric(tail))
if (kind=="tk") {
if (is.na(width))
width <- 360
retina <- 1 # getOption("ursaRetina")
if (is.null(retina))
retina <- 1
width <- round(width*retina)
title <- sprintf("%s: %.0f of %.0f",title,initial,max)
pb <- try(tcltk::tkProgressBar(title=title,label=label,min=min,max=max
,initial=initial,width=width))
if (inherits(pb,"try-error"))
pb <- utils::txtProgressBar(title=title,label=label,min=min,max=max
,initial=initial,width=width,style=style)
}
##~ else if ((.Platform$OS.type=="windows")&&(kind=="win")) {
##~ if (is.na(width))
##~ width <- 300
##~ pb <- utils::winProgressBar(title=title,label=label,min=min,max=max
##~ ,initial=initial,width=width)
##~ }
else
pb <- utils::txtProgressBar(title=title,label=label,min=min,max=max
,initial=initial,width=width,style=style)
pb$optionName <- paste0("ursaProgressBar",basename(.maketmp()))
op <- list(st)
names(op) <- pb$optionName
options(op)
class(pb) <- c("ursaProgressBar",class(pb))
if (tail)
setUrsaProgressBar(pb)
pb
}
'setUrsaProgressBar' <- function(pb,value,title=NULL,label=NULL) {
if (is.null(pb))
return(pb)
if ((length(class(pb))==1)&&(inherits(pb,"ursaProgressBar")))
return(pb)
# if (.isKnitr())
# return(pb)
t2 <- unname(proc.time()[3])
cl <- class(pb)[2]
st <- getOption(pb$optionName)
if (missing(value))
st["current"] <- st["current"]+1
else
st["current"] <- value
# if (names(st[1])=="first")
# print(st)
if (!is.null(title))
names(st)[1] <- title
st["delta"] <- t2-st["prev"]+st["delta"]
reset <- st["delta"]>0.5 | st["current"]==1 | st["current"]>st["max"]
if (reset)
st["delta"] <- 0
st["prev"] <- t2
op <- list(st)
names(op) <- pb$optionName
options(op)
if ((!reset)&&(T & st["max"]!=st["current"]))
return(NULL)
if (missing(value))
value <- unname(st["current"])-1
else
value <- value-1
# print(c(current=unname(st["current"]),value=value))
##~ if (st["current"]>st["max"])
##~ st["current"] <- st["max"]
# if (value>=st["max"])
# value <- unname(st["max"])-1
# print(c(st,value=value))
if (value<st["max"])
title <- sprintf("%s: %.0f of %.0f",names(st)[1],value+1,st["max"])
else {
title <- sprintf("%s: %s!",names(st)[1]
,ifelse(isTRUE(all.equal(value,unname(st["max"]))),"completed","OVER LIMIT"))
}
d1 <- unname((value-st["min"])/(st["max"]-st["min"]))
t3 <- t2-st[1]
# print(cbind(as.data.frame(t(st)),onset=reset,curr=t3))
if (t2-st[1]<0.49999)
label <- sprintf("%5.0f%% %56s",d1*100," ")
else {
d2 <- 1-d1
if (d1==0)
d3 <- 0
else
d3 <- d2*(t2-st[1])/d1
d6 <- ceiling(as.numeric(as.difftime(d3,units="secs")))
d8 <- round(t3)
d9 <- d6+d8
d4h <- d6 %/% 3600
d4 <- d6-d4h*3600
d4m <- d4 %/% 60
d4s <- d4-d4m*60
if (is.na(d4h)) {
print(c(d1=d1,d2=d2,d3=d3,d6=d6,d8=d8,d9=d9,d4h=d4h,d4=d4,d4m=d4m,d4s=d4s))
Sys.sleep(999)
stop("PROGRESSBAR")
}
if (d4h==0) {
d4f <- sprintf("%02d:%02d:%02d",d4h,d4m,d4s)
d5 <- format(Sys.time()+d6,"(%H:%M:%S)")
}
else {
d4f <- sprintf("%02dh%02dm",d4h,d4m)
d5 <- format(Sys.time()+d6,"(%d%b %H:%M)")
}
d8s <- d8%%60
d8 <- (d8-d8s)/60
d8m <- d8%%60
d8h <- (d8-d8m)/60
# d8 <- sprintf("%02d:%02d:%02d",d8h,d8m,d8s)
d9s <- d9%%60
d9 <- (d9-d9s)/60
d9m <- d9%%60
d9h <- (d9-d9m)/60
if (d9h==0)
d9 <- sprintf("%02d:%02d:%02d",d9h,d9m,d9s)
else
d9 <- sprintf("%02dh%02dm",d9h,d9m)
if (d8h==0)
d8 <- sprintf("%02d:%02d:%02d",d8h,d8m,d8s)
else
d8 <- sprintf("%02dh%02dm",d8h,d8m)
d8 <- paste0("+",d8)
d4f <- paste0("-",d4f)
# d9 <- paste0("=",d9)
if ((TRUE)||((st[4]>1500)||(d1>0.05)))
label <- sprintf("%5.0f%% %9s %9s %9s %12s",d1*100,d8,d4f,d9,d5)
else
# label <- sprintf("%5.0f%% ???:??? (????-??-?? ??:??)",d1*100)
label <- sprintf("%5.0f%% %30s",d1*100," ")
}
# print(c(value=value))
if (cl=="tkProgressBar")
return(tcltk::setTkProgressBar(pb,value,title=title,label=label))
##~ else if ((cl=="winProgressBar")&&(.Platform$OS.type=="windows"))
##~ return(utils::setWinProgressBar(pb,value,label=label))
utils::setTxtProgressBar(pb,value,title=title,label=label)
}
'close.ursaProgressBar' <- function(con,...) {
if (!length(con))
return(invisible(NULL))
p <- getOption(con$optionName)
if (p["current"]==p["max"]) {
setUrsaProgressBar(con,unname(p["max"]))
}
NextMethod("close",con,...)
}
# 'close.ursaProgressBar' <- function(con,...) close(con,...)
# 'close.NULL' <- function(obj,...) invisible(NULL)
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/progressBar.R
|
# ?findInterval
#'levels.ursaRaster' <- function(obj) names(ursa_colortable(obj))
'reclass' <- function(obj,dst=NULL,src=NULL,sparse=FALSE,...) {
verbose <- .getPrm(list(...),name="verb(ose)*",default=FALSE)
# str(as.list(match.call()))
if (is.ursa(obj)) {
ct <- obj$colortable
onlyCT <- FALSE
}
else if (inherits(obj,"ursaColorTable")) {
ct <- obj
onlyCT <- TRUE
}
else {
print("unable recognize object for reclass")
return(NULL)
}
if ((is.null(names(ct)))&&(length(ct))) {
names(ct) <- as.character(seq(length(ct))-1L)
}
if (length(dst)) {
if (.is.colortable(dst)) {
ct <- ursa_colortable(dst)
val <- .deintervale(ct)
if (is.character(val))
{
if (length(val)==length(ct)) {## categoral
cname <- val
val <- seq_along(val)-1L
# str(list(value=val,name=cname,pal=unclass(unname(ct))))
pal <- unclass(unname(ct))
if (anyNA(pal)) {
res <- colorize(obj,value=val,name=cname)
ursa_colortable(res) <- ct
}
else
res <- colorize(obj,value=val,name=cname,pal=unclass(unname(ct)))
}
else { ## interval ## not-tested
res <- obj
ursa_colortable(res) <- ct
class(res$value) <- "ursaCategory"
}
}
else {
# print(c(val=length(val),ct=length(ct)))
if (length(val)==length(ct)) ## categoral
{
res <- colorize(obj,value=val,pal=unclass(unname(ct)))
}
else ## interval
res <- colorize(obj,breakvalue=val,pal=unclass(unname(ct)))
}
return(res)
}
else {
if (!length(src)) {
if (length(ct)==length(dst)) {
src <- seq_along(ct)-1
}
}
if (length(src)==length(dst)) {
# sparse <- !TRUE ## forced to change 'sparse' argument
if (sparse)
obj <- compress(obj)
isChar <- !is.numeric(dst)
if (isChar) {
cname <- dst
# print(cname)
# dst <- seq_along(dst)-1
dst <- factor(dst,levels=unique(dst))
cname <- levels(dst)
ct <- rep(NA,length(cname))
names(ct) <- cname
dst <- as.integer(dst)-1L
ursa_colortable(obj) <- ct
class(obj$value) <- "ursaCategory"
}
else {
class(obj$value) <- "ursaNumeric"
}
if (TRUE) {
n1 <- length(na.omit(c(obj$value)))
isInteger <- is.integer(src)
if ((isInteger)&&(!is.integer(obj$value)))
obj$value[] <- as.integer(obj$value)
val <- dst[match(c(obj$value),src)] ## faster
n2 <- length(na.omit(c(val)))
if ((!isInteger)&&(n1!=n2)) { ## slower
str(src)
str(dst)
val <- c(obj$value)
pb <- ursaProgressBar(min=0,max=length(src)
,title="reclass: need optimization"
,tail=TRUE)
for (i in seq_along(src)) {
ind <- .is.eq(c(obj$value),src[i])
if (length(ind))
val[ind] <- dst[i]
setUrsaProgressBar(pb)
}
close(pb)
if ((TRUE)||(verbose)) {
n3 <- length(na.omit(c(val)))
print(c('berore'=n1,'after'=n2,'corrected'=n3))
}
}
obj$value[] <- val
rm(val)
}
else {
# print(".C optimization is needed")
}
if (sparse)
return(decompress(obj))
else
return(obj)
}
}
}
# if ((length(ct)>0)&&(obj$category)) {
if (length(ct)>0) {
if ((is.ursa(obj))&&(!.is.category(obj))) { # if ((is.ursa(obj))&&(!attr(obj$value,"category")))
return(reclass(obj,ct,verbose=verbose)) ## recursive!!!
}
val <- .deintervale(ct)
if (is.character(val)) {
if (FALSE)
ursa_colortable(obj) <- character(0) ## 'character(0)'? 'ct'?
else {
class(obj$value) <- "ursaNumeric"
}
return(obj)
}
args <- as.list(match.call()) ## try mget(names(match.call())[-1])
args$obj <- quote(obj)
args$src <- seq_along(ct)-1
if (length(val)==length(ct)) { ## categoral
args$dst <- as.numeric(val)
}
else { ## interval
v1 <- as.numeric(val)
if (length(v1)<4) {
if (length(v1)==1)
args$dst <- rep(v1,2)
else {
v2 <- diff(v1)
v3 <- max(v2)
v4 <- v1[-1]-v2/2
args$dst <- c(head(v4,1)-v3,v4,tail(v4,1)+v3)
rm(v2,v3,v4)
}
rm(v1)
}
else {
x1 <- seq(v1)
x2 <- seq(length(v1)-1)+0.5
x12 <- sort(c(x1,x2))
opLoess <- options(warn=-1)
for (s in seq(0.99,0.19,by=-0.1)) {
m1 <- try(loess(v1~x1,span=s),silent=TRUE)
if (inherits(m1,"try-error"))
next
v12 <- predict(m1,x12)
v3 <- c(head(v12,1)-head(diff(v12),1)
,predict(m1,x2)
,tail(v12,1)+tail(diff(v12),1))
if (length(unique(sign(diff(v3))))==1)
break
}
options(opLoess)
args$dst <- v3
rm(v1,x1,x12,m1,v12,v3)
}
}
if (identical(args$src,args$dst)) {
if (TRUE) { ## ++ 20180706
if (inherits(obj$value,"ursaCategory"))
class(obj$value) <- "ursaNumeric"
else if (inherits(obj$value,"ursaNumeric"))
class(obj$value) <- "ursaCategory"
}
return(obj)
}
if (onlyCT)
return(args$dst)
if (any(is.na(args$dst))) {
if (FALSE) {
obj$colortable <- character(0)
class(obj$colortable) <- "ursaColorTable"
}
return(obj)
}
res <- do.call(as.character(args[1]),args[-1]) ## recursive!!!
res$con$nodata <- .optimal.nodata(args$dst)
return(res)
}
if (FALSE)
res <- colorize(obj,...)
else {
arglist <- list(...)
if (!.lgrep("tail",names(arglist)))
arglist$tail <- 0
res <- do.call("colorize",c(list(obj),arglist),quote=TRUE)
}
res$colortable[] <- rep(NA_character_,length(res$colortable))
if ((is.character(dst))&&(length(dst)==length(res$colortable))) {
names(res$colortable) <- dst
# str(res$colortable)
}
return(res)
# NULL
}
'.extract' <- function(obj) {
if (!.is.category(obj)) ##(!.is.colortable(obj))
return(obj)
if (is.character(.deintervale(obj$colortable))) {
class(obj$value) <- "ursaNumeric"
return(obj)
}
obj <- reclass(obj)
if (FALSE)
ursa_colortable(obj) <- character(0)
obj
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/reclass.R
|
##~ 'resize' <- function(x,scale=1,grid=NULL,cover=0.5-1e-3,resample=1
##~ ,resetGrid=TRUE,verbose=0L)
'regrid' <- function(x,...)
{
# print("resize")
arglist <- list(...)
if (missing(x)) {
result <- .regrid(...)
resetGrid <- .getPrm(arglist,name="^reset",default=TRUE)
if (resetGrid)
session_grid(result)
return(result)
}
fun <- "regrid" #as.character(match.call())[1]
if (.is.ursa_stack(x)) {
return(lapply(x,regrid,...))
}
if (!is.ursa(x)) {
return(.regrid(x,...))
# return(NULL)
}
# grid <- do.call("regrid",as.list(match.call())[-1])
# session_grid(x) ## removed 20160619
cond <- .getPrm(arglist,class="ursaRaster",default=NULL)
if ((FALSE)&&((is.ursa(cond))||(length(arglist)==0))) { ## or don't include '!length'?
return(ursa_crop(x,...))
}
else
g2 <- do.call(".regrid",arglist)
session_grid(x) ## added 20160619
resetGrid <- TRUE
cover <- NA
resample <- 1
verbose <- 0L
cascade <- FALSE
myname <- names(arglist)
for (i in seq_along(arglist)) {
a <- arglist[[i]]
n <- myname[i]
if (is.ursa(arglist[[i]]))
g2 <- ursa_grid(a)
else if (.lgrep("^reset",n))
resetGrid <- as.logical(a)
else if (.lgrep("resample",n))
resample <- as.numeric(a)
else if (.lgrep("cover",n))
cover <- as.numeric(a)
else if (.lgrep("cascade",n))
cascade <- as.logical(a)
else if (.lgrep("verb(ose)*",n))
verbose <- as.integer(a)
}
if (is.na(cover))
cover <- 0.5-1e-3
g1 <- x$grid
# isCT <- x$category # .is.category(x)
ct <- x$colortable
isCT <- length(ct)>0
clValue <- class(x$value)
smValue <- storage.mode(x$value)
x <- .extract(x)
if (cascade) {
m0 <- sqrt((g1$resx*g1$resy)/(g2$resx*g2$resy))
mul <- NULL
for (i in seq(1000)) {
m2 <- c(mul,2)
if (prod(m2)>m0)
break
mul <- m2
}
mul <- c(mul,m0/prod(mul))
for (m in head(mul,-1)) {
x <- regrid(x,mul=m,resample=resample,cover=cover,verbose=verbose)
}
res <- regrid(x,g2,resample=resample,cover=cover,verbose=verbose)
if (!resetGrid)
session_grid(g1)
return(res)
}
if (!is.na(x$con$posZ[1]))
nb <- length(x$con$posZ)
else
nb <- x$dim[2]
dimx <- with(g1,c(columns,rows,nb))
dimy <- with(g2,c(columns,rows,nb))
dim(x$value) <- dimx
x$value <- as.numeric(x$value)
if (verbose>1)
print(summary(x$value))
if (verbose>2)
.elapsedTime(paste0("start:nodata-assing:",fun))
nodata <- x$con$nodata
missedNodata <- is.na(nodata)
if (missedNodata)
# nodata <- max(x$value,na.rm=TRUE)+1
nodata <- .optimal.nodata(x$value)
x$value[is.na(x$value)] <- nodata
if (verbose>2)
.elapsedTime(paste0("finish:nodata-assing:",fun))
if (verbose>1)
print(summary(x$value))
if (verbose)
.elapsedTime(paste0("start:",fun))
session_grid(g2)
# isCT <- .is.colortable(x$colortable)
y <- as.ursa(NA,bandname=bandname(x),nodata=nodata) ## ursa_new
##~ if (isCT)
##~ y$colortable <- x$colortable
y$value <- .Cursa(C_resampl4,x=x$value,nodata=as.numeric(nodata)
,dim1=as.integer(dimx),dim2=as.integer(dimy)
,lim1=as.numeric(with(g1,c(minx,miny,maxx,maxy)))
,lim2=as.numeric(with(g2,c(minx,miny,maxx,maxy)))
,cover=as.numeric(cover),area=as.numeric(resample)
,verbose=as.integer(verbose)
,res=numeric(prod(dimy)),NAOK=FALSE)$res
if (verbose)
.elapsedTime(paste0("finish:",fun))
if (verbose>1)
print(summary(y$value))
if (verbose>2)
.elapsedTime(paste0("start:nodata-restore:",fun))
if (TRUE) ## added 20160406
y$value[.is.eq(y$value,nodata)] <- NA
else { ## deprecated
if (abs(nodata)<1)
y$value[abs(y$value-nodata)<1e-27] <- NA
else
y$value[abs(y$value/nodata-1)<1e-6] <- NA
}
if (verbose>2)
.elapsedTime(paste0("finish:nodata-restore:",fun))
if (isCT) {
y <- reclass(discolor(y),ct)
}
if (verbose>1)
print(summary(y$value))
if (FALSE) {
if (FALSE) {
if ((resample==0)&&(smValue=="integer")) {
if (TRUE) ## quick
storage.mode(y$value) <- "integer"
else
y$value <- as.integer(round(y$value))
}
if ((resample==0)&&(isCT)) {
class(y$value) <- "ursaCategory"
}
else
class(y$value) <- "ursaNumeric"
}
else
class(y$value) <- "ursaNumeric"
}
dim(y$value) <- with(g2,c(columns*rows,nb))
if (TRUE) { ## added 20170524
if (resample==0) {
class(y$value) <- clValue
storage.mode(y$value) <- smValue
}
else
class(y$value) <- "ursaNumeric"
}
# if ((.is.colortable(x$colortable))&&(length(unique(y$value))==length(x$colortable)))
# y$colortable <- x$colortable
if (missedNodata)
y$con$nodata <- NA
if (!resetGrid)
session_grid(g1)
y
}
'.regrid' <- function(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 #1e-10
,zoom=NA
,verbose=FALSE,...)
{
if (is.character(border)) ## cuttof 'border' in 'plot' functions
border <- 0
# print("regrid")
# verbose <- TRUE
if (length(arglist <- list(...))) {
res <- .getPrm(arglist,name="cell",default=as.numeric(res)) ## cell, cellsize -> res
}
mtol <- 1e5 # [1e2->1e5 20170720]
etol <- 1e-14
zero <- match.arg(zero)
if (missing(grid)) {
checkZero <- FALSE
if (verbose)
message("grid is missing")
g <- session_grid()
}
else if (is.null(grid)) {
checkZero <- FALSE
if (verbose)
message("grid is NULL")
g <- .grid.skeleton()
}
else if (is.ursa(grid)) {
checkZero <- TRUE
if (verbose)
message("grid from raster")
g <- ursa_grid(grid)
}
else if ((is.character(grid))&&(envi_exists(grid,exact=TRUE))) {
checkZero <- TRUE
if (verbose)
message("grid from ENVI")
g <- ursa_grid(grid)
}
else {
checkZero <- TRUE
if (verbose)
message("grid as is")
g <- grid
}
if (FALSE) {
x <- seq(g,"x")
y <- seq(g,"y")
print(x)
print(y)
}
step1 <- TRUE
dima <- length(dim)
if (length(dim)==2) {
rows <- dim[1]
columns <- dim[2]
}
if (!is.na(setbound)[1]) {
setbound <- rep(setbound,length=4)
g$minx <- unname(setbound[1])
g$miny <- unname(setbound[2])
g$maxx <- unname(setbound[3])
g$maxy <- unname(setbound[4])
toDefine <- 0L
# if ((is.na(g$columns))&&(!is.na(columns))) { ## -- 20170613
if (!is.na(columns)) { ## ++ 20170613
g$columns <- as.integer(round(columns))
toDefine <- toDefine+1L
}
# if ((is.na(g$rows))&&(!is.na(rows))) { ## -- 20170613
if (!is.na(rows)) { ## ++ 20170613
g$rows <- as.integer(round(rows))
toDefine <- toDefine+1L
}
if (toDefine<2)
toDefine <- FALSE
if ((!toDefine)&&(!is.na(g$columns))&&(!is.na(g$columns)))
toDefine <- TRUE
if (toDefine) {
g$resx <- with(g,(maxx-minx)/columns)
g$resy <- with(g,(maxy-miny)/rows)
}
if (zero=="node") {
if (verbose)
print("setbound:zero:node")
g$minx <- round(g$minx/g$resx)*g$resx
g$maxx <- round(g$maxx/g$resx)*g$resx
g$miny <- round(g$miny/g$resy)*g$resy
g$maxy <- round(g$maxy/g$resy)*g$resy
}
}
##~ if (verbose) {
##~ print(g)
##~ }
if ((is.numeric(zoom))&&(!is.numeric(mul))&&(!is.numeric(expand))) {
expand <- zoom
mul <- 1/zoom
zoom <- NA
}
if (!is.na(cut[1])) {
if (length(cut)==1)
cut <- cut*c(-1,-1,1,1)
cut <- rep(cut,length=4)
bbox <- with(g,c(minx,miny,maxx,maxy))+cut
}
if (!anyNA(expand)) {
x0 <- (g$minx+g$maxx)/2
y0 <- (g$miny+g$maxy)/2
sx <- (g$maxx-g$minx)/2
sy <- (g$maxy-g$miny)/2
if (length(expand)==1) {
expand <- rep(expand,length.out=2)
s <- sqrt(sx*sy)
if (T) {
dx <- sx+round(s*(expand[1]-1)/g$resx*2)*g$resx/2
dy <- sy+round(s*(expand[2]-1)/g$resy*2)*g$resy/2
}
else { ## deprecated
dx <- sx+s*(expand[1]-1)
dy <- sy+s*(expand[2]-1)
}
}
else {
dx <- (expand[1])*sx
dy <- (expand[2])*sy
}
# print(with(g,c(minx,miny,maxx,maxy)))
bbox <- c(x0-dx,y0-dy,x0+dx,y0+dy)
# print(bbox)
}
if ((anyNA(res))&&(!is.na(resx))&&(!is.na(resy)))
res <- c(resx,resy)
if (is.numeric(mul))
{
g$resx <- g$resx/mul
g$resy <- g$resy/mul
}
else if ((!is.na(res[1]))&&(is.numeric(res[1])))
{
if (length(res)==2)
{
g$resx <- res[1]
g$resy <- res[2]
}
else
g$resx <- g$resy <- res
if ((!is.na(bbox[1]))&&(length(bbox)==4))
step1 <- FALSE
}
else
step1 <- FALSE
if (step1)
{
if (all(!is.na(c(minx,miny,maxx,maxy)))) {
g$minx <- minx
g$miny <- miny
g$maxx <- maxx
g$maxy <- maxy
minx <- miny <- maxx <- maxy <- NA
}
if (is.na(tolerance)) {
tolx <- .Machine$double.eps*max(abs(c(g$minx,g$maxx)))*mtol
toly <- .Machine$double.eps*max(abs(c(g$miny,g$maxy)))*mtol
if (tolx<etol)
tolx <- etol
if (toly<etol)
toly <- etol
tolerance <- min(tolx,toly)
}
else {
tolx <- toly <- tolerance
}
c0 <- with(g,(maxx-minx)/resx)
r0 <- with(g,(maxy-miny)/resy)
# r0 <- with(g,((maxy-meany)-(miny-meany))/resy)
if ((!.is.integer(r0,toly))||(!.is.integer(c0,tolx))) {
if (verbose) {
message("#1. 'bbox' is changed to integerity of matrix dimension")
}
g$minx <- floor(g$minx/g$resx)*g$resx
g$maxx <- ceiling(g$maxx/g$resx)*g$resx
g$miny <- floor(g$miny/g$resy)*g$resy
g$maxy <- ceiling(g$maxy/g$resy)*g$resy
g$columns <- with(g,(maxx-minx)/resx)
g$rows <- with(g,(maxy-miny)/resy)
}
else {
g$columns <- as.integer(round(c0))
g$rows <- as.integer(round(r0))
}
if ((!.is.integer(g$columns,tolx))||(!.is.integer(g$rows,toly))) {
print(c(dc=g$columns-round(g$columns),dr=g$rows-round(g$rows)))
stop(paste("#1. Unable to calculate integer dim size."
,"Try to change 'tolerance'"
,paste0("(",format(tolerance,digits=1),")")))
}
g$columns <- as.integer(round(g$columns))
g$rows <- as.integer(round(g$rows))
}
step2 <- FALSE
g2 <- g
if ((!is.na(bbox[1]))&&(length(bbox)==4))
{
g$minx <- unname(bbox[1])
g$miny <- unname(bbox[2])
g$maxx <- unname(bbox[3])
g$maxy <- unname(bbox[4])
step2 <- TRUE
}
else if (!is.na(cut[1])) {
if (length(cut)==1)
cut <- cut*c(-1,-1,1,1)
cut <- rep(cut,length=4)
g$minx <- g$minx+cut[1]
g$miny <- g$miny+cut[2]
g$maxx <- g$maxx+cut[3]
g$maxy <- g$maxy+cut[4]
step2 <- TRUE
}
# else ## not neccessary: initial value is FALSE
# step2 <- FALSE
if (!is.na(minx))
g$minx <- minx
if (!is.na(miny))
g$miny <- miny
if (!is.na(maxx))
g$maxx <- maxx
if (!is.na(maxy))
g$maxy <- maxy
if ((!step2)&&(any(!is.na(c(minx,miny,maxx,maxy)))))
step2 <- TRUE
if ((!FALSE)&&(!is.na(columns))&&(!is.na(rows))) { ## ++ 20170719
if ((FALSE)&&(!.isPackageInUse()))
message("Not a good idea to define cell size from image dimension")
if ((is.na(g$columns))||(g$columns!=columns))
g$columns <- as.integer(round(columns))
if ((is.na(g$rows))||(g$rows!=rows))
g$rows <- as.integer(round(rows))
g$resx <- with(g,(maxx-minx)/columns)
g$resy <- with(g,(maxy-miny)/rows)
}
if (step2)
{
if (zero=="node") {
if (verbose)
print("step2:zero=node")
g$minx <- round(g$minx/g$resx)*g$resx
g$maxx <- round(g$maxx/g$resx)*g$resx
g$miny <- round(g$miny/g$resy)*g$resy
g$maxy <- round(g$maxy/g$resy)*g$resy
}
else if ((T & checkZero)&&(zero=="keep")&&
(!is.na(g2$minx))&&(!is.na(g2$maxx))&&
(!is.na(g2$miny))&&(!is.na(g2$maxy))) {
if (verbose)
print("step2:zero=keep")
if (F) {
str(as.list(match.call()))
message("g")
print(g,digits=12)
message("g2")
print(g2,digits=12)
q()
}
x <- seq(g2,"x")
y <- seq(g2,"y")
if (verbose) {
comment(verbose) <- "seq"
print(series(x))
print(series(y))
}
if (!TRUE) {
indX <- which(x>=g$minx-g$resx/2 & x<=g$maxx+g$resx/2)
indY <- which(y>=g$miny-g$resy/2 & y<=g$maxy+g$resy/2)
if ((length(indX))&&(length(indY))) {
if (verbose)
message("matched")
# print(range(x[indX])+c(-1,1)*g$resx/2)
# print(range(y[indY])+c(-1,1)*g$resy/2)
g$minx <- min(x[indX])-g$resx/2
g$maxx <- max(x[indX])+g$resx/2
g$miny <- min(y[indY])-g$resy/2
g$maxy <- max(y[indY])+g$resy/2
if (F) {
x <- seq(g,"x")
y <- seq(g,"y")
print(series(x))
print(series(y))
}
}
else if (verbose)
message("unmatched")
}
else { ## deprecate???
shift <- c(0,1)[1]
indMinX <- which(x<=g$minx-shift*g$resx/2)
indMaxX <- which(x>=g$maxx+shift*g$resx/2)
indMinY <- which(y<=g$miny-shift*g$resy/2)
indMaxY <- which(y>=g$maxy+shift*g$resy/2)
if ((length(indMinX))&&(length(indMaxX))&&(length(indMinY))&&(length(indMaxY))) {
if (verbose) {
message("matched")
}
##~ print(indMinX)
##~ print(indMaxX)
##~ print(indMinY)
##~ print(indMaxY)
g$minx <- max(x[indMinX])-g$resx/2
g$maxx <- min(x[indMaxX])+g$resx/2
g$miny <- max(y[indMinY])-g$resy/2
g$maxy <- min(y[indMaxY])+g$resy/2
if (F) {
x <- seq(g,"x")
y <- seq(g,"y")
print(series(x))
print(series(y))
}
}
else if (verbose)
message("unmatched")
}
}
c0 <- with(g,(maxx-minx)/resx)
r0 <- with(g,(maxy-miny)/resy)
if (is.na(tolerance)) {
tolx <- .Machine$double.eps*max(abs(c(g$minx,g$maxx)))*mtol
toly <- .Machine$double.eps*max(abs(c(g$miny,g$maxy)))*mtol
if (tolx<etol)
tolx <- etol
if (toly<etol)
toly <- etol
tolerance <- min(tolx,toly)
}
else {
tolx <- toly <- tolerance
}
if ((!.is.integer(r0,toly))||(!.is.integer(c0,tolx))) {
if (verbose)
message("#2. 'bbox' is changed to integerity of matrix dimension")
g$minx <- floor(g$minx/g$resx)*g$resx
g$maxx <- ceiling(g$maxx/g$resx)*g$resx
g$miny <- floor(g$miny/g$resy)*g$resy
g$maxy <- ceiling(g$maxy/g$resy)*g$resy
g$columns <- with(g,(maxx-minx)/resx)
g$rows <- with(g,(maxy-miny)/resy)
}
else {
g$columns <- as.integer(round(c0))
g$rows <- as.integer(round(r0))
}
if ((!.is.integer(g$columns,tolx))||(!.is.integer(g$rows,toly))) {
# print(g)
# if (verbose)
print(c(dc=g$columns-round(g$columns),dr=g$rows-round(g$rows)
,tolx=tolx,toly=toly))
stop(paste("#2. Unable to calculate integer dim size."
,"Try to change 'tolerance'"
,paste0("(",format(tolerance,digits=1),")")))
}
g$columns <- as.integer(round(g$columns))
g$rows <- as.integer(round(g$rows))
if ((verbose)&&(is.character(comment(verbose)))&&(comment(verbose)=="seq")) {
print(seq(g,"x"))
print(seq(g,"y"))
}
}
# str(list(crs=crs,crs=proj4,'g$crs'=g$crs))
if ((is.na(proj4))&&(!is.na(crs)))
proj4 <- crs
if (FALSE) {
if (is.character(proj4))
g$crs <- proj4
else if (is.numeric(proj4))
g$crs <- .epsg2proj4(proj4,force=!TRUE,verbose=verbose)
}
else if ((!is.na(proj4))&&(!identical(g$crs,proj4))) {
g$crs <- spatial_crs(proj4)
}
# else {
# message("skip")
# }
if (is.na(g$crs))
g$crs <- ""
if (any(border!=0))
{
border <- round(rep(border,length=4))
g$minx <- with(g,minx-border[2]*resx)
g$miny <- with(g,miny-border[1]*resy)
g$maxx <- with(g,maxx+border[4]*resx)
g$maxy <- with(g,maxy+border[3]*resy)
g$columns <- with(g,(maxx-minx)/resx)
g$rows <- with(g,(maxy-miny)/resy)
# print("STEP3")
if (is.na(tolerance)) {
tolx <- .Machine$double.eps*max(abs(c(g$minx,g$maxx)))*mtol
toly <- .Machine$double.eps*max(abs(c(g$miny,g$maxy)))*mtol
if (tolx<etol)
tolx <- etol
if (toly<etol)
toly <- etol
tolerance <- min(tolx,toly)
}
else {
tolx <- toly <- tolerance
}
if ((!.is.integer(g$columns,tolx))||(!.is.integer(g$rows,toly))) {
verbose <- TRUE
if (verbose) {
print(g,digits=15)
}
print(c(dc=g$columns-round(g$columns),dr=g$rows-round(g$rows)
,tolx=tolx,toly=toly))
stop(paste("#3. Unable to calculate integer dim size."
,"Try to change 'tolerance'"
,paste0("(",format(tolerance,digits=1),")")))
}
g$columns <- as.integer(round(g$columns))
g$rows <- as.integer(round(g$rows))
}
g$seqx <- numeric()
g$seqy <- numeric()
if (!raster)
return(invisible(g))
session_grid(g)
ursa_new()
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/regrid.R
|
'segmentize' <- function(obj,by=NULL,connect=c("united","consequent")) {
connect <- match.arg(connect)
# if (!is.null(by))
# connect <- "united"
if ((!is.null(by))&&(connect=="consequent")) {
ret <- do.call(spatial_bind,by(obj,by,segmentize,connect=connect)) ## RECURSIVE
##~ for (a in spatial_fields(obj)) {
##~ byvalue <- obj[[a]]
##~ str(a)
##~ str(byvalue)
##~ if (is.integer(byvalue))
##~ ret[[a]] <- as.integer(ret[[a]])
##~ else if (is.numeric(byvalue))
##~ ret[[a]] <- as.numeric(ret[[a]])
##~ else if (inherits(byvalue,"Date"))
##~ ret[[a]] <- as.Date(ret[[a]])
##~ }
return(ret)
}
if ((TRUE)&&(T & is.null(by))&&(spatial_geotype(obj) %in% c("MULTIPOINT"))&&
(spatial_count(obj)>1)) {
ret <- lapply(seq_len(spatial_count(obj)),\(j) {
res <- segmentize(obj[j,],by=spatial_data(obj[j,]),connect=connect) ## RECURSIVE
})
ret <- do.call(spatial_bind,ret)
return(ret)
}
if (is_spatial_lines(obj)) {
crd <- sapply(seq(1,2),function (x) basename(tempfile(pattern="")))
if (is.null(by)) {
by <- rep(0L,spatial_count(obj))
}
index <- by(obj,by,rownames)
conseq <- is.list(index)
if (!conseq)
da <- spatial_data(obj)
a <- lapply(index,function(x) {
if (is.null(x))
return(NULL)
ind <- match(x,rownames(spatial_data(obj)))
xy <- do.call(rbind,spatial_coordinates(obj[ind,]))
colnames(xy) <- crd
if (!conseq) {
return(cbind(xy,da[rep(ind,nrow(xy)),,drop=FALSE]))
}
ind2 <- c(1L,which(seq_len(nrow(xy)) %% 2 ==0))
# ind2 <- which(!duplicated(xy))
da <- spatial_data(obj[c(ind[1L],ind),])
cname <- colnames(da)
if (length(ind3 <- grep("\\.1$",cname))>0) {
for (i in ind3) {
da[1,gsub("\\.1$","",cname[i])] <- da[1,i]
}
da[,ind3] <- NULL
}
cbind(xy[ind2,],da)
})
ret <- spatialize(do.call(rbind,a),coords=crd
,crs=spatial_crs(obj),engine=ifelse(.isSF(obj),"sf","sp"))
rownames(ret) <- NULL
return(ret)
}
if (!is_spatial_points(obj))
return(NULL)
xy <- unname(spatial_coordinates(obj))
if (is.list(xy)) {
if (length(xy)==1)
xy <- xy[[1]]
else {
str(xy)
stop("It seems that MULTI<geometry>, which is unsupported")
}
}
if (connect=="united") {
if (!is.null(by)) {
##~ if ((length(by)==1)&&(by %in% spatial_fields(obj))) {
##~ dname <- by
##~ by <- obj[[by]]
##~ }
##~ else
##~ dname <- NULL
# q()
if (!.isSF(obj))
crd <- dimnames(obj@coords)[[2]]
res <- by(obj,by,simplify=FALSE,function(x) {
if (!.isSF(x)) {
# sp::coordinates(x) <- c("coords.x1","coords.x2")
sp::coordinates(x) <- crd
}
ret <- segmentize(x,connect=connect) ## RECURSIVE
ret
})
ind <- which(!sapply(res,is.null))
da <- attr(res,"dimnames")
if (!is.data.frame(da)) {
da <- do.call(expand.grid,list(da,stringsAsFactors=FALSE))[ind,,drop=FALSE]
attr(da,"out.attrs") <- NULL
}
if (ncol(da)==1) {
byname <- as.list(match.call())[["by"]]
byvalue <- eval(byname,envir=parent.frame())
if (is.list(byvalue)) {
dname <- names(byvalue)
byvalue <- byvalue[[1]]
}
else {
list1 <- as.list(match.call())
dname <- gsub(paste0(as.character(list1["obj"]),"\\$"),""
,as.character(list1["by"]))
by <- data.frame(array(by,dim=c(length(by),1),dimnames=list(NULL,dname))
,check.names=FALSE)
}
colnames(da) <- dname
# if (is.null(names(by)))
# names(by) <- byname
}
for (a in names(by)) {
byvalue <- by[[a]]
if (is.integer(byvalue))
da[[a]] <- as.integer(da[[a]])
else if (is.numeric(byvalue))
da[[a]] <- as.numeric(da[[a]])
else if (inherits(byvalue,"Date"))
da[[a]] <- as.Date(da[[a]])
}
res <- do.call(spatial_bind,res[ind])
spatial_data(res) <- da
if (.isSP(obj))
sp::proj4string(res) <- sp::CRS(spatial_crs(obj),doCheckCRSArgs=FALSE)
}
else if (.isSF(obj)) {
if (nrow(xy)==1)
res <- sf::st_sfc(sf::st_linestring(xy[integer(),]),crs=spatial_crs(obj))
else
res <- sf::st_sfc(sf::st_linestring(xy),crs=spatial_crs(obj))
}
else if (.isSP(obj)) {
res <- sp::Lines(sp::Line(xy),1L)
res <- sp::SpatialLines(list(res))
sp::proj4string(res) <- sp::CRS(spatial_crs(obj),doCheckCRSArgs=FALSE)
}
else
res <- NULL
return(res)
}
ind <- tail(seq_len(nrow(xy)),-1)
n <- length(ind)
res <- vector("list",n)
if (.isSF(obj)) {
for (i in seq_along(ind)) {
res[[i]] <- sf::st_linestring(xy[ind[i]+c(-1,0),])
}
res <- sf::st_sfc(res,crs=spatial_crs(obj))
}
else if (.isSP(obj)) {
for (i in seq_along(ind)) {
res[[i]] <- sp::Lines(sp::Line(xy[ind[i]+c(-1,0),]),ind[i])
}
res <- sp::SpatialLines(res)
sp::proj4string(res) <- sp::CRS(spatial_crs(obj),doCheckCRSArgs=FALSE)
}
else
return(NULL)
if (F)
spatial_data(res) <- tail(spatial_data(obj),-1)
else {
da <- spatial_data(obj)
if (nrow(da)==1)
spatial_data(res) <- da
else {
da1 <- head(da,-1)
da2 <- tail(da,-1)
ind <- rep(NA,ncol(da))
for (i in seq_len(ncol(da1))) {
ind[i] <- identical(da1[,i],da2[,i])
}
da1[,which(ind)] <- NULL
spatial_data(res) <- data.frame(cbind(da2,da1))
}
}
res
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/segmentize.R
|
'session_grid' <- function(obj,...) {
arglist <- list(...)
ref <- getOption("ursaSessionGrid")
if (missing(obj)) { ## 'Extract'
if ((is.null(ref))||(!.is.grid(ref))) {
# fname <- system.file("template","default.hdr",package="ursa")
fname <- file.path(getOption("ursaRequisite"),"template.hdr")
if (file.exists(fname)) {
fname <- system.file("requisite/template.hdr",package="ursa")
if (file.exists(fname))
ref <- .read.hdr(fname)$grid
else
ref <- .read.hdr("default")$grid ## read.idr
}
options(ursaSessionGrid=ref)
}
if (!length(arglist)) {
# return(invisible(ref))
return(ref)
}
else {
obj <- do.call(regrid,c(list(ref),arglist))
arglist <- NULL
}
}
# above - 'Extract' (visible), below - 'Replace' (invisible)
options(ursaSessionGrid_prev=ref)
if (is.null(obj))
return(options(ursaSessionGrid=NULL))
if (length(arglist)) {
# if (is_spatial(obj))
obj <- do.call(regrid,c(list(spatial_grid(obj)),arglist))
# else
# obj <- do.call(regrid,c(list(ursa_grid(obj)),arglist))
}
if (.is.grid(obj)) {
options(ursaSessionGrid=obj)
return(invisible(obj))
}
if (.is.ursa_stack(obj))
obj <- obj[[1]]
if (is.ursa(obj)) {
options(ursaSessionGrid=obj$grid)
return(invisible(obj$grid))
}
if (is_spatial(obj)) {
return(session_grid(spatial_grid(obj)))
}
if ((length(obj)==1)&&(!envi_exists(obj))&&
(nchar(Sys.getenv("R_IDRISI")))&&(exists("read.idr"))) {
g1 <- do.call("read.idr",list((obj)))$grid
options(ursaSessionGrid=g1)
return(invisible(g1))
}
if (is.character(obj)) {
# print(obj)
# print(spatial_dir(pattern=obj,recursive=FALSE))
opW <- options(warn=2)
a <- try(open_envi(obj,resetGrid=TRUE,decompress=FALSE))
options(opW)
if (inherits(a,"try-error")) {
if (file.exists(obj)) {
a <- open_gdal(obj)
}
else {
list1 <- dir(path=dirname(obj)
,pattern=paste0(basename(obj),"\\.(tif|tiff|hfa)$")
,full.names=TRUE)
if (length(list1)==1)
a <- open_gdal(list1)
}
}
if (!inherits(a,"try-error")) {
g1 <- a$grid
if (is_ursa(a))
close(a)
}
else if (T & length(spatial_dir(path=dirname(obj),pattern=basename(obj)
,recursive=FALSE))==1) {
a <- spatial_read(obj)
g1 <- spatial_grid(a)
rm(a)
}
else
return(NULL)
if (!.is.grid(g1))
return(NULL)
options(ursaSessionGrid=g1)
return(invisible(g1))
}
if ((is.numeric(obj))&&(length(obj)==2)) {
obj <- unname(obj)
ref <- round(obj)
g1 <- .grid.skeleton()
g1$columns <- as.integer(ref[2])
g1$rows <- as.integer(obj[1])
g1$minx <- 0
g1$miny <- 0
g1$maxx <- obj[2]
g1$maxy <- obj[1]
g1$resx <- with(g1,(maxx-minx)/columns)
g1$resy <- with(g1,(maxy-miny)/rows)
if (!FALSE) {
retina <- getOption("ursaRetina")
if ((is.numeric(retina))&&(retina>1))
g1$retina <- retina
}
options(ursaSessionGrid=g1)
return(invisible(g1))
}
str(obj)
stop('Unable to recognize paramaters for new grid')
}
## .Unable to implement 'session_grid() <- val' for missing object
#'session_grid<-' <- function(value) {
# stop("<-s")
# # options(ursaSessionGrid=value)
# session_grid(value)
# # return(session_grid())
#}
# .syn('session_crs',0)
#'.session_crs<-' <- function(x,value) {
# a <- session_grid()
# a$crs <- .epsg2proj4(value,force=TRUE)
# session_grid(a)
#}
'session_proj' <- 'session_proj4' <- 'session_crs' <- function() session_grid()$crs
'session_cellsize' <- function() with(session_grid(),sqrt(as.numeric(resx)*as.numeric(resy)))
'session_dim' <- function() with(session_grid(),c(lines=rows,samples=columns))
'session_bbox' <- function() {
ret <- with(session_grid(),c(minx=minx,miny=miny,maxx=maxx,maxy=maxy))
attr(ret,"crs") <- session_crs()
ret
}
'session_pngviewer' <- function(allow=NA) {
opV <- getOption("ursaAllowPngViewer")
# str(list(allow=allow,opV=opV,isRscript=.isRscript()))
if ((is.na(allow))||(!is.logical(allow))) {
if (is.logical(opV))
return(opV)
allow <- interactive() | .isRscript() | .isKnitr() | .isJupyter() | .isShiny()
}
opA <- options(ursaAllowPngViewer=allow)[[1]]
if (is.null(opV))
opA <- allow
# invisible(getOption("ursaAllowPngViewer"))
# invisible(allow) ## RC
invisible(opA)
}
'session_tempdir' <- function(dst=character()) {
if ((is.character(dst))&&(length(dst))) {
if (!dir.exists(dst)) {
opW <- options(warn=2)
dir.create(dst)
options(opW)
}
# options(ursaTempDir=normalizePath(dst,winslash="/",mustWork=FALSE))
options(ursaTempDir=dst)
return(invisible(dst))
}
opD <- getOption("ursaTempDir")
if (length(opD))
return(opD)
dst <- ifelse(.isRscript()
,ifelse(T,.ursaCacheDir(),getwd())
# ,normalizePath(tempdir(),winslash="/")
,tempdir()
) ## "." <-> 'getwd()'
options(ursaTempDir=dst)
return(dst)
}
'session_use_experimental_functions' <- function() {
list1 <- readLines(system.file("NAMESPACE",package="ursa"))
list1 <- grep("^export\\(",list1,value=TRUE)
list1 <- gsub("^export\\(\\\"(.+)\\\"\\)","\\1",list1)
ns <- asNamespace("ursa")
list2 <- ls(envir=ns)
list2 <- grep("^[A-Za-z]",list2,value=TRUE)
list2 <- grep("\\.(ursa(Raster|Grid|ColorTable|Connection|Numeric|Category|Stack))"
,list2,value=TRUE,invert=TRUE)
list2 <- grep("^(as\\.Raster|djqwotrhfndh)\\.",list2,value=TRUE,invert=TRUE)
list2 <- list2[which(is.na(match(list2,list1)))]
for (v in list2) {
# global env set hack (function(key, val, pos) assign(key,val, envir=as.environment(pos)))(myKey, myVal, 1L) `
# assign(v,get(v,envir=ns),envir=as.environment(1)) ## 'as.environment(1)' '.GlobalEnv'
do.call("assign",list(v,get(v,envir=ns),envir=as.environment(1)))
}
invisible(list2)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/session.R
|
# wrappers to spatial (not raster) objects
#.syn('spatial_crs',0,...)
'spatial_proj4' <- 'spatial_proj' <- 'spatial_crs' <- function(obj,verbose=FALSE) {
if (!is.null(attr(obj,"crs",exact=TRUE))) {
res <- attr(obj,"crs")
if (inherits(res,"crs")) {
if ((is.list(res))&&(!is.null(res$wkt))&&("sf" %in% loadedNamespaces())) {
return(sf::st_crs(res$wkt)$proj4string)
}
return(res$proj4string)
}
return(res)
}
if ((TRUE)&&(is.character(obj))&&(nchar(obj)>0)&&(length(spatial_dir(obj))==1)) {
obj <- spatial_read(obj)
}
isUrsa <- is.ursa(obj) | is.ursa(obj,"grid")
isPrm <- is.numeric(obj) | is.character(obj)
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(ursa=isUrsa,sf=isSF,sp=isSP,prm=isPrm,row.names="engine"))
if ((isSF)||(inherits(obj,"crs"))) {
return(sf::st_crs(obj)$proj4string)
}
if (isSP) {
if (FALSE) ## `sp`<1.4-2
return(sp::proj4string(obj))
spCRS <- methods::slot(obj,"proj4string")
if (methods::is(spCRS,"CRS")) {
wkt <- comment(spCRS)
ret <- methods::slot(spCRS,"projargs")
if (FALSE) ## possible for future use
comment(ret) <- wkt
return(ret)
}
return(NA_character_)
}
if (isUrsa)
return(ursa_crs(obj))
if (isPrm) {
return(.epsg2proj4(obj,verbose=verbose,force=TRUE))
}
if (isTRUE(all(sapply(obj,.isSF))))
return(lapply(obj,spatial_crs,verbose=verbose))
if (isTRUE(all(sapply(obj,.isSP))))
return(lapply(obj,spatial_crs,verbose=verbose))
return(NULL)
}
#.syn('spatial_crs<-',0,...)
'spatial_proj4<-' <- 'spatial_proj<-' <- 'spatial_crs<-' <- function(obj,verbose=FALSE,value) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
sf::st_crs(obj) <- sf::NA_crs_ ## ??? comment it?
sf::st_crs(obj) <- .p4s2epsg(value)
}
if (isSP) {
if (is.numeric(value))
value <- .epsg2proj4(value,force=!TRUE)
sp::proj4string(obj) <- NA_character_
sp::proj4string(obj) <- value
}
if ((inherits(obj,"stars"))&&("sf" %in% loadedNamespaces())) {
sf::st_crs(obj) <- .p4s2epsg(value)
}
obj
}
'spatial_geometry' <- function(obj,verbose=FALSE) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
return(sf::st_geometry(obj))
}
if (isSP) {
return(sp::geometry(obj))
}
if (isTRUE(all(sapply(obj,.isSF))))
return(lapply(obj,spatial_geometry,verbose=verbose))
if (isTRUE(all(sapply(obj,.isSP))))
return(lapply(obj,spatial_geometry,verbose=verbose))
return(NULL)
}
'spatial_geometry<-' <- function(obj,verbose=FALSE,value) {
isSF <- .isSF(value)
isSP <- .isSP(value)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="value"))
if (isSF) {
if (!.isSF(obj)) {# lost geometry colname
cname <- colnames(obj)
obj <- sf::st_sf(obj,geometry=spatial_geometry(value))
spatial_fields(obj) <- cname
}
else {
if (inherits(obj,"sfc"))
return(value)
obj[,attr(obj,"sf_column")][[1]] <- value
}
}
if (isSP) {
if (inherits(obj,c("SpatialLinesDataFrame","SpatialPointsDataFrame"
,"SpatialPolygonsDataFrame"))) {
obj <- methods::slot(obj,"data")
}
geotype <- spatial_geotype(value)
obj <- switch(geotype
,POLYGON=sp::SpatialPolygonsDataFrame(value,obj,match.ID=FALSE)
,LINESTRING=sp::SpatialLinesDataFrame(value,obj,match.ID=FALSE)
,POINT=sp::SpatialPointsDataFrame(value,obj,match.ID=FALSE)
,stop(paste("unimplemented selection:",geotype)))
}
if (!isSP & !isSF) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="obj"))
if (is.null(value)) {
if (isSF)
sf::st_geometry(obj) <- NULL
if (isSP)
obj <- methods::slot(obj,"data")
return(obj)
}
print(class(value))
stop("no sp, no sf")
}
obj
}
'spatial_bbox' <- function(obj,verbose=FALSE) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if ((!isSF)&&(!isSP)&&(is.list(obj))) {
if (isTRUE(all(sapply(obj,function(o) isTRUE(.isSF(o)) | isTRUE(.isSP(o)))))) {
return(lapply(obj,spatial_bbox,verbose=verbose))
}
}
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
res <- NULL
isLongLat <- .lgrep("\\+proj=longlat",spatial_crs(obj))>0
if (F & isLongLat) {
xy <- spatial_coordinates(obj)
if (F & isSF) {
xy <- spatial_coordinates(sf::st_cast(spatial_geometry(obj),"POINT"))
res <- c(xmin=min(xy[,1]),ymin=min(xy[,2]),xmax=max(xy[,1]),ymax=max(xy[,2]))
# return(res)
}
if (T | isSP) {
xy <- spatial_coordinates(obj)
while(all(sapply(xy,is.list)))
xy <- unlist(xy,recursive=FALSE)
if (is.list(xy)) ## deprecated and resored 20190930
xy <- do.call(rbind,xy)
res <- c(xmin=min(xy[,1]),ymin=min(xy[,2]),xmax=max(xy[,1]),ymax=max(xy[,2]))
# return(res)
}
}
if ((is.null(res))&&(isSF)) {
res <- sf::st_bbox(obj)
rname <- names(res)
res <- as.numeric(res)
names(res) <- rname
attr(res,"crs") <- spatial_crs(obj)
# return(res)
}
if ((is.null(res))&&(isSP)) {
res <- c(sp::bbox(obj))
if (length(res)==6)
res <- res[c(1,2,4,5)]
names(res) <- c("xmin","ymin","xmax","ymax")
attr(res,"crs") <- spatial_crs(obj)
# return(res)
}
##~ cat("----------------\n")
##~ if ((isLongLat)&&(res["xmin"]<(-180+1e-6))&&(res["xmax"]>(180-1e-6))) {
##~ print("HERE")
##~ }
##~ print(res)
##~ cat("----------------\n")
##~ q()
# return(res)
if (!is.null(res)) {
if (!isLongLat)
return(res)
dg180 <- 0.1
is180 <- (res["xmin"]<=(-180+dg180))&&(res["xmax"]>=(180-dg180))
if (!is180)
return(res)
dg90 <- -1e-6
is90 <- (res["ymin"]<=(-90+dg90))||(res["ymax"]>=(90-dg90))
if (is90)
return(res)
if (skip_dev <- !TRUE)
return(res)
# if ((TRUE)&&(res["xmin"]>0)&&(res["xmax"]<0))
# res["xmax"] <- res["xmax"]+360
if (T) {
xy <- unname(spatial_coordinates(obj))
if (T) {
for (i in seq(4)) {
if (isFALSE(any(sapply(xy,is.list))))
break
if (length(ind <- which(sapply(xy,is.list)))) {
xy <- c(xy[-ind],unlist(xy[ind],recursive=FALSE))
}
}
}
else {
repeat({
if (isFALSE(any(sapply(xy,is.list))))
break
xy <- unlist(xy,recursive=FALSE)
})
}
if (is.list(xy))
xy <- do.call("rbind",xy)
x1 <- xy[,1]
x2 <- x1
ind <- which(x2<(0))
if (length(x2))
x2[ind] <- x2[ind]+360
sd1 <- sd(x1)
sd2 <- sd(x2)
if (verbose) {
print(summary(x1))
print(summary(x2))
print(c(sd1=sd1,sd2=sd2))
}
if (sd1<sd2)
return(res)
res[c(1,3)] <- range(x2)
}
else {
d2 <- spatialize(obj,style="merc",verbose=verbose) ## sp: failed for 90.0N
res <- matrix(spatial_bbox(d2),ncol=2,byrow=FALSE)
res <- .project(res,spatial_crs(d2),inv=TRUE)
res <- c(t(res))
names(res) <- c("xmin","ymin","xmax","ymax")
attr(res,"crs") <- spatial_crs(obj)
}
}
res
}
'spatial_bbox<-' <- function(obj,verbose=FALSE,value) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
NULL ## 'sf' has no replacement function for bbox
}
if (isSP) {
val <- matrix(value,ncol=2)
colnames(val) <- c("min","max")
rownames(val) <- paste0("coords.x",seq(nrow(val)))
methods::slot(obj,"bbox") <- val
}
obj
}
'spatial_engine' <- function(obj,verbose=FALSE) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
return("sf")
}
if (isSP) {
return("sp")
}
return(NULL)
}
'spatial_fields' <- 'spatial_colnames' <- function(obj,verbose=FALSE) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if ((!isSF)&&(!isSP)&&(is.list(obj))) {
if (isTRUE(all(sapply(obj,function(o) isTRUE(.isSF(o)) | isTRUE(.isSP(o)))))) {
return(lapply(obj,spatial_fields,verbose=verbose))
}
}
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
if (FALSE) { ## 'st_agr' FAILURE for 'obj$newfield' <- assignment
dname <- try(names(sf::st_agr(obj)),silent=TRUE)
if (inherits(dname,"try-error"))
dname <- character()
}
else {
dname <- colnames(obj)
if (is.null(dname))
dname <- character()
else if (length(ind <- match(attr(obj,"sf_column"),dname)))
dname <- dname[-ind]
}
return(dname)
}
if (isSP) {
dname <- try(colnames(methods::slot(obj,"data")),silent=TRUE)
if (inherits(dname,"try-error"))
dname <- character()
return(dname)
}
return(NULL)
}
'spatial_fields<-' <- 'spatial_colnames<-' <- function(obj,verbose=FALSE,value) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
oldvalue <- names(attr(obj,"agr"))
if (!is.null(oldvalue)) {
colnames(obj)[match(oldvalue,colnames(obj))] <- value
# colnames(obj)[-match(attr(obj,"sf_column"),colnames(obj))] <- value
names(attr(obj,"agr")) <- value
}
else {
ind <- grep(attr(obj,"sf_column"),names(obj),invert=TRUE,value=FALSE)
colnames(obj)[ind] <- value
}
}
if (isSP) {
colnames(spatial_data(obj)) <- value
}
obj
}
'spatial_data' <- function(obj,subset=".+",drop=NA,verbose=FALSE) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if ((!isSF)&&(!isSP)&&(is.list(obj))) {
if (isTRUE(all(sapply(obj,function(o) isTRUE(.isSF(o)) | isTRUE(.isSP(o)))))) {
return(lapply(obj,spatial_data,subset=subset,drop=drop,verbose=verbose))
}
}
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
if (inherits(obj,"sfc"))
return(NULL)
# res <- obj
##~1 sf::st_geometry(res) <- NULL
##~1 attributes(res) <- attributes(res)[c("names","row.names","class")]
##~2 res[[attr(res,"sf_column")]] <- NULL
##~2 attr(res,"sf_column") <- NULL
##~2 class(res) <- grep("^(sf|sfc)$",class(res),value=TRUE,invert=TRUE)
res <- sf::st_set_geometry(obj,NULL)
}
else if (isSP) {
if (!methods::.hasSlot(obj,"data"))
return(NULL)
res <- methods::slot(obj,"data")
}
else if (is.data.frame(obj))
return(obj)
else
return(NULL)
ind <- .grep(subset,colnames(res))
if (!length(ind))
return(res)
if (is.na(drop))
drop <- if (TRUE) FALSE else length(ind)==1
return(res[,ind,drop=drop])
}
'spatial_data<-' <- function(obj,verbose=FALSE,value) {
if (is.null(value))
return(spatial_geometry(obj))
operation <- "unknown"
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (isSF | isSP)
operation <- "geometry"
else {
isSF <- .isSF(value)
isSP <- .isSP(value)
if (isSF | isSP)
operation <- "data"
}
if (verbose)
print(data.frame(sf=isSF,sp=isSP,operation=operation,row.names="engine"))
if (operation=="geometry") {
n <- spatial_count(obj)
if (nrow(value)!=n) {
value <- value[rep(seq(nrow(value)),len=n),,drop=FALSE]
}
spatial_geometry(value) <- obj
return(value)
}
if (operation=="data")
stop(paste("Not imlemented for operation",sQuote(operation)))
NULL
}
'spatial_transform' <- function(obj,crs,verbose=FALSE,...) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if ((!isSF)&&(!isSP)&&(is.list(obj))) {
if (isTRUE(all(sapply(obj,function(o) isTRUE(.isSF(o)) | isTRUE(.isSP(o)))))) {
return(lapply(obj,spatial_transform,crs=crs,verbose=verbose))
}
}
if (missing(crs))
crs <- session_crs()
else if ((is.ursa(crs))||(is.ursa(crs,"grid")))
crs <- ursa(crs,"crs")
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
return(sf::st_transform(obj,sf::st_crs(crs),...))
}
if (isSP) {
if (is.numeric(crs))
crs <- .epsg2proj4(crs,force=FALSE)
else if (.isSP(crs))
crs <- sp::proj4string(crs)
opW <- options(warn=ifelse(verbose,0,-1))
crs <- methods::slot(sp::CRS(crs,doCheckCRSArgs=TRUE),"projargs")
crs0 <- spatial_crs(obj)
if (.lgrep("\\+init=epsg\\:\\d+",crs0)) {
spatial_crs(obj) <- methods::slot(sp::CRS(crs0,doCheckCRSArgs=TRUE),"projargs")
}
ret <- sp::spTransform(obj,crs,...)
options(opW)
return(ret)
# return(sp::spTransform(obj,crs,...)) ## sp::CRS(crs) ?
}
return(NULL)
}
'spatial_geotype' <- 'spatial_shape' <- function(obj,each=FALSE,verbose=FALSE) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
if (each)
return(sf::st_geometry_type(obj))
if (inherits(obj,"sfc"))
geoType <- .grep("^sfc_.+$",class(obj),value=TRUE)
else
geoType <- .grep("^sfc_.+$",class(obj[[attr(obj,"sf_column")]]),value=TRUE)
geoType <- .gsub("^sfc_","",geoType)
if (geoType=="GEOMETRY")
geoType <- unique(as.character(sf::st_geometry_type(obj)))
return(geoType)
}
if (isSP) {
geoType <- switch(class(sp::geometry(obj))
,SpatialPolygons="POLYGON"
,SpatialPoints="POINT"
,SpatialLines="LINESTRING"
,SpatialPixels="GRID"
,stop(class(sp::geometry(obj)))
)
if (!each)
return(geoType)
return(rep(geoType,spatial_count(obj)))
}
# print(class(obj))
return(NULL)
}
'spatial_coordinates' <- function(obj,verbose=FALSE) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
geoType <- spatial_geotype(obj)
if (isSF) {
if ((FALSE)&&(length(geoType)>1)) {
if (("POLYGON" %in% geoType)&&("MULTIPOLYGON" %in% geoType)) {
obj <- sf::st_cast(obj,"MULTIPOLYGON")
geoType <- "MULTIPOLYGON"
}
else
stop(paste("Unimplemented for multiple geometries (sf): "
,paste(geoType,collapse=", ")))
}
if (all(geoType=="POINT")) {
# ret <- do.call("rbind",lapply(sf::st_geometry(obj),unclass))
ret <- t(sapply(sf::st_geometry(obj),unclass))
rownames(ret) <- seq(nrow(ret))
colnames(ret) <- c("x","y")
return(ret)
}
if (all(geoType=="LINESTRING")) {
multi <- any(sapply(sf::st_geometry(obj),is.list))
if (!multi) {
ret <- lapply(sf::st_geometry(obj),unclass)
names(ret) <- seq_along(ret)
return(ret)
}
else
stop(paste("Unimplemented MULTILINESTRING (sf)"))
}
if (all(geoType=="MULTIPOLYGON")) {
ret <- lapply(sf::st_geometry(obj),unclass) ## Holes are not ignored
# ret <- lapply(sf::st_geometry(obj),unlist,recursive=FALSE) ## ignore holes
names(ret) <- seq_along(ret)
return(ret)
}
else if (all(geoType=="POLYGON")) {
ret <- lapply(sf::st_geometry(obj),unclass)
names(ret) <- seq_along(ret)
return(ret)
}
else if (("POLYGON" %in% geoType)&&("MULTIPOLYGON" %in% geoType)) {
if (FALSE) { ## make all multu
k <- 0
ret <- lapply(sf::st_geometry(obj),function(xy) {
str(xy)
k <<- k+1
##~ if (k<=1442)
##~ return(NULL)
##~ ret1 <- lapply(xy,function(xy1) {
##~ str(xy1)
##~ })
NULL
})
rm(k)
q()
}
else
ret <- lapply(sf::st_geometry(obj),unclass)
names(ret) <- seq_along(ret)
return(ret)
}
else if (all(geoType=="MULTILINESTRING")) {
ret <- lapply(sf::st_geometry(obj),unclass)
nseg <- unique(sapply(ret,length))
if ((FALSE)&&(length(nseg)==1)&&(nseg==1)) ## consistence with 'sp'
ret <- lapply(ret,function(x) x[[1]])
names(ret) <- seq_along(ret)
return(ret)
}
else if (all(geoType=="MULTIPOINT")) {
ret <- lapply(sf::st_geometry(obj),unclass)
names(ret) <- seq_along(ret)
return(ret)
}
# ret <- lapply(sf::st_geometry(obj),unclass) ## dummy
stop(paste("Unimplemented for geometry (sf): "
,paste(geoType,collapse=", ")))
## back to sf
# g1 <- lapply(geom,function(x1) {
# y1 <- sf::st_multilinestring(x1)
# # y1 <- sf::st_multipolygon(list(x1))
# })
}
if (isSP) {
if (geoType=="POINT") {
ret <- unname(sp::coordinates(obj))
rownames(ret) <- seq(nrow(ret))
colnames(ret) <- c("x","y")
return(ret)
}
if (geoType=="LINESTRING") {
ulen <- sort(unique(sapply(methods::slot(obj,"lines")
,function(x) length(methods::slot(x,"Lines")))))
if ((length(ulen)==1)&&(ulen==1)) {
ret <- lapply(methods::slot(obj,"lines"),function(x) {
x2 <- lapply(methods::slot(x,"Lines"),sp::coordinates)[[1]]
})
names(ret) <- seq_along(ret)
return(ret)
}
else
stop(paste("Unimplemented MULTILINESTRING (sp)"))
}
if (geoType=="POLYGON") {
ulen <- sort(unique(sapply(methods::slot(obj,"polygons")
,function(x) length(methods::slot(x,"Polygons")))))
# ret <- vector("list",length(ulen))
ret <- lapply(methods::slot(obj,"polygons"),function(x1) {
x2 <- methods::slot(x1,"Polygons")
hole <- sapply(x2,function(x3) methods::slot(x3,"hole"))
if (TRUE) {# if (any(hole)) {
if ((any(hole))&&(hole[1])) {
ind <- order(hole)
x2 <- x2[ind]
hole <- hole[ind]
}
indF <- which(!hole)
ret2 <- vector("list",length(indF))
jF <- 1L
prevHole <- TRUE
for (i in seq_along(hole)) {
if (!hole[i]) {
if (i==length(hole))
h2 <- 0
else {
h1 <- i+1
hole2 <- hole[h1:length(hole)]
if (hole2[1]) {
indE <- which(diff(hole2)!=0)
if (!length(indE))
h2 <- length(hole2)
else
h2 <- indE[1]
# print(h2)
}
else
h2 <- 0
}
if (!h2) {
ret2[[jF]] <- list(unname(sp::coordinates(x2[[i]])))
jF <- jF+1L
next
}
h2 <- h2+1
ret3 <- vector("list",h2)
ret3[[1]] <- unname(sp::coordinates(x2[[i]]))
jH <- 2L
}
else {
if (!exists("ret3")) {
str(x2)
str(hole)
q()
}
ret3[[jH]] <- unname(sp::coordinates(x2[[i]]))
jH <- jH+1L
if (jH>h2) {
ret2[[jF]] <- ret3
jF <- jF+1L
}
}
}
# ret2 <- unlist(ret2,recursive=FALSE) ## TRUE ignores holes
ret2
}
else
stop(paste("Unimplemented POLYGON (sp) without holes"))
})
names(ret) <- seq_along(ret)
return(ret)
}
if (geoType=="GRID") {
ret <- sp::coordinates(obj)
names(ret) <- seq_along(ret)
return(ret)
}
stop(paste("Unimplemented for geometry (sp): "
,paste(geoType,collapse=", ")))
}
return(NULL)
}
'spatial_area' <- function(obj,verbose=FALSE) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
res <- sf::st_area(obj)
if (TRUE) {
u <- attr(res,"units")$numerator
m <- rep(1,length(u))
for (i in seq_along(u))
m[i] <- switch(u[i],"m"=1,"km"=1e3,"mm"=1e-3,stop(u[i]))
res <- as.numeric(res)*prod(m)
}
return(res)
}
if (isSP) {
if (!("POLYGON" %in% spatial_geotype(obj)))
return(NULL)
# res <- sapply(obj@polygons,function(x) sapply(x@Polygons,methods::slot,"area"))
res <- sapply(methods::slot(obj,"polygons"),function(x1)
sum(sapply(methods::slot(x1,"Polygons"),function(x2)
y2 <- ifelse(methods::slot(x2,"hole"),-1,1)*methods::slot(x2,"area"))))
return(res)
}
NULL
}
'spatial_length' <- function(obj,verbose=FALSE) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
if (is_spatial_polygons(obj))
res <- sf::st_length(sf::st_cast(obj,"MULTILINESTRING"))
else
res <- sf::st_length(obj)
if (TRUE) {
u <- attr(res,"units")$numerator
m <- rep(1,length(u))
for (i in seq_along(u))
m[i] <- switch(u[i],"m"=1,"km"=1e3,"mm"=1e-3,stop(u[i]))
res <- as.numeric(res)*prod(m)
}
return(res)
}
if (isSP) {
if (!("LINESTRING" %in% spatial_geotype(obj))) {
if (.rgeos_requireNamespace())
stop("suggested package is required for this operation")
res <- try(.rgeos_gLength(obj,byid=TRUE))
if (inherits(res,"try-error"))
res <- try(.rgeos_gLength(spatial_buffer(obj),byid=TRUE))
return(unname(res))
}
if (FALSE) { ## thesame
res <- sapply(methods::slot(obj,"lines"),function(x1)
sum(sapply(methods::slot(x1,"Lines"),function(x2) {
xy <- diff(methods::slot(x2,"coords"))
sum(sqrt(xy[,1]*xy[,1]+xy[,2]*xy[,2]))
}))
)
}
else {
res <- sp::SpatialLinesLengths(obj
,longlat=.lgrep("\\+proj=longlat",spatial_crs(obj))>0)
}
return(res)
}
NULL
}
'spatial_dim' <- function(obj,verbose=FALSE) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSP)
return(2L)
if (isSF) {
return(max(sapply(obj[[attr(obj,"sf_column")]],function(x) {
if (is.list(x)) max(sapply(x,function(y) {
if (is.list(y)) {
max(sapply(y,function(z) {
if (!is.null(dim(z))) ncol(z) else length(z)
}))
}
else if (!is.null(dim(y))) ncol(y) else length(y)
}))
else if (!is.null(dim(x))) ncol(x)
else length(x)
})))
}
NULL
}
'spatial_dim<-' <- function(obj,verbose=FALSE,value) {
'redim' <- function(x) {
d <- dim(x)[2]
if (d==value)
return(x)
if (d<value) {
res <- cbind(x,0)
class(res) <- c("XYZ",grep("^XY$",class(x),value=TRUE))
return(res)
}
res <- x[,seq_len(value)]
class(res) <- c("XY",grep("^XY[MTZ]$",class(x),value=TRUE))
res
}
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSP)
return(obj)
if (isSF) {
res0 <- spatial_geometry(obj)
res <- lapply(res0,function(g1) {
if (is.list(g1)) {
res1 <- lapply(g1,function(g2) {
if (is.list(g2)) {
res2 <- lapply(g2,redim)
class(res2) <- class(g2)
}
else
res2 <- redim(g2)
res2
})
}
else
res1 <- redim(g1)
class(res1) <- class(g1)
res1
})
attributes(res) <- attributes(res0)
##~ cat("----------------\n")
##~ str(unclass(res))
##~ cat("----------------\n")
##~ str(unclass(res0))
##~ cat("----------------\n")
spatial_geometry(obj) <- res0
return(obj)
}
NULL
}
'is_spatial_points' <- function(obj,verbose=FALSE) {
res <- .lgrep("POINT",spatial_geotype(obj,verbose=verbose))>0
}
'is_spatial_lines' <- function(obj,verbose=FALSE) {
.lgrep("LINES",spatial_geotype(obj,verbose=verbose))>0 ## LINEString
}
'is_spatial_polygons' <- function(obj,verbose=FALSE) {
.lgrep("POLYGON",spatial_geotype(obj,verbose=verbose))>0
}
'spatial_nrow' <- 'spatial_count' <- function(obj,verbose=FALSE) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
length(spatial_geometry(obj))
}
'is_spatial' <- function(obj,verbose=FALSE) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
isSF | isSP
}
'spatial_filelist' <- 'spatial_dir' <- function(path=".",pattern=NA,full.names=TRUE
,recursive=FALSE,ignore.case=TRUE) {
patt0 <- "\\.(gpkg|tab|kml|json|geojson|mif|sqlite|fgb|shp|osm)(\\.(zip|gz|bz2))*$"
if (devel <- TRUE & all(!dir.exists(path))) {
dname <- dirname(path)
if (dname!=".") {
dpath <- list.dirs(dirname(path),full.names=FALSE)
ind <- grep(basename(path),dpath,ignore.case=ignore.case)
if (length(ind)==1)
path <- file.path(dirname(path),dpath[ind])
}
}
res <- dir(path=path,pattern=patt0,full.names=full.names
,recursive=recursive,ignore.case=ignore.case)
if ((!length(res))&&(is.na(pattern))) {
if ((path==basename(path))&&(!dir.exists(path))) {
# print("A")
pattern <- path
path <- "."
res <- dir(path=path,pattern=patt0,full.names=full.names
,recursive=recursive,ignore.case=ignore.case)
}
else {
pattern <- basename(path)
path2 <- dirname(path)
res <- dir(path=path2,pattern=patt0,full.names=full.names
,recursive=recursive,ignore.case=ignore.case)
if (!length(res)) {
pattern <- path
path3 <- "."
res <- dir(path=path3,pattern=patt0,full.names=full.names
,recursive=recursive,ignore.case=ignore.case)
}
}
}
if (is.character(pattern)) {
ind <- grep(pattern,basename(res),ignore.case=ignore.case)
if (!length(ind)) {
ind <- na.omit(match(pattern,basename(res)))
if (!length(ind)) {
ind <- na.omit(match(pattern,spatial_basename(res)))
# return(res[ind])
}
}
res <- res[ind]
}
# res <- gsub("(\\.zip|gz|bz2)*$","",res) ## lack for 'file.info'
res
}
'.spatial_shape' <- function(data,geometry,verbose=FALSE) { ## not useful
isSF <- .isSF(geometry)
isSP <- .isSP(geometry)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
spatial_geometry(data) <- geometry
data
}
'spatial_ncol' <- function(obj,verbose=FALSE) length(spatial_fields(obj,verbose=verbose))
'spatial_centroid' <- function(obj,verbose=FALSE) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
if (inherits(obj,"sf"))
sf::st_agr(obj) <- "constant"
return(sf::st_centroid(obj))
}
if (isSP) {
geoType <- spatial_geotype(obj)
if (geoType=="POLYGON") {
res <- lapply(methods::slot(spatial_geometry(obj),"polygons"),function(x) {
a1 <- methods::slot(x,"labpt")
if (FALSE) {
a2 <- lapply(methods::slot(x,"Polygons"),function(y) {
methods::slot(y,"labpt")
})
str(a2)
q()
}
a1
})
res <- do.call("rbind",res)
res <- data.frame(x=res[,1],y=res[,2])
sp::coordinates(res) <- c("x","y")
# sp::proj4string(res) <- spatial_crs(obj)
spatial_crs(res) <- spatial_crs(obj)
da <- spatial_fields(obj)
if (length(da))
spatial_data(res) <- spatial_data(obj)
}
else
stop(paste("Unimplemented for geometry:",geoType))
return(res)
}
NULL
}
'spatial_clip' <- function(obj,verbose=FALSE) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
ind <- sf::st_intersects(polygonize(session_bbox(),engine="sf"),obj)[[1]]
return(obj[ind,])
}
if (isSP) {
ind <- unname(sp::over(polygonize(session_bbox(),engine="sp")
,spatial_geometry(obj),returnList=TRUE)[[1]])
return(obj[ind,])
}
obj
}
'spatial_intersection' <- function(x,y,geometry=c("default","polygons","lines"
,"points","all"),verbose=FALSE) {
geometry <- match.arg(geometry)
if (is.ursa(x)) {
if (.isSF(y))
x <- polygonize(x,engine="sf",verbose=verbose)
else if (.isSP(y))
x <- polygonize(x,engine="sp",verbose=verbose)
else
x <- polygonize(x,verbose=verbose)
}
if (is.ursa(y)) {
if (.isSF(x))
y <- polygonize(y,engine="sf",verbose=verbose)
else if (.isSP(x))
y <- polygonize(y,engine="sp",verbose=verbose)
else
y <- polygonize(y,verbose=verbose)
}
isSF <- .isSF(x) & .isSF(y)
isSP <- .isSP(x) & .isSP(y)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
if (inherits(x,"sf"))
sf::st_agr(x) <- "constant"
if (inherits(y,"sf"))
sf::st_agr(y) <- "constant"
if (missedAttrTable <- is.null(spatial_data(x))) {
xname <- basename(tempfile(pattern="field",tmpdir=""))
spatial_data(x) <- data.frame(array(0,dim=c(spatial_length(x),1)
,dimnames=list(NULL,xname)))
sf::st_agr(x) <- "constant"
}
res <- try(sf::st_intersection(x,y))
if (inherits(res,"try-error")) {
if (length(grep("st_crs\\(x\\) == st_crs\\(y\\) is not TRUE"
,as.character(res))))
res <- sf::st_intersection(x,spatial_transform(y,x))
}
if (missedAttrTable) {
x <- spatial_geometry(x)
res[[xname]] <- NULL
}
if (is.null(spatial_data(res))) {
if (!is.null(spatial_data(x)))
spatial_data(res) <- spatial_data(x)
else if (!is.null(spatial_data(y)))
spatial_data(res) <- spatial_data(y)
}
if (length(ind <- grep("\\.1$",spatial_fields(res)))) {
rname <- spatial_fields(res)
for (i in ind) {
if (identical(res[[gsub("\\.1$","",rname[i])]],res[[rname[i]]]))
res[[rname[i]]] <- NULL
}
}
if (FALSE) {
# spatial_geometry(res) <- sf:::st_cast_sfc_default(spatial_geometry(res))
}
else {
if (geometry=="all")
return(res)
xGeotype <- as.character(spatial_geotype(x,each=TRUE))
yGeotype <- as.character(spatial_geotype(y,each=TRUE))
geotype <- as.character(spatial_geotype(res,each=TRUE))
uGeotype <- unique(geotype)
xPolygon <- .lgrep("polygon",xGeotype)>0
xLine <- .lgrep("line",xGeotype)>0
xPoint <- .lgrep("point",xGeotype)>0
yPolygon <- .lgrep("polygon",yGeotype)>0
yLine <- .lgrep("line",yGeotype)>0
yPoint <- .lgrep("point",yGeotype)>0
if (geometry=="default") {
if ((xPolygon)&&(yPolygon))
geometry <- "polygons"
else if (((xLine)&&(yLine))||((xLine)&&(yPolygon))||((xPolygon)&&(yLine)))
geometry <- "lines"
else if ((xPoint)||(yPoint))
geometry <- "points"
else
return(res)
}
if (geometry=="polygons") {
ind <- .grep("(polygon|collection)",geotype)
if (!length(ind))
return(res)
res <- res[ind,]
geotype <- geotype[ind]
if (length(na.omit(match(unique(geotype)
,c("POLYGON","MULTIPOLYGON"))))==2) {
if (length(ind2 <- .grep("collection",geotype))) {
opWC <- options(warn=-1)
res2 <- sf::st_collection_extract(res[ind2,],"POLYGON")
options(opWC)
if (spatial_count(res2)) {
res <- spatial_bind(res[-ind2,],res2)
geotype <- as.character(spatial_geotype(res,each=TRUE))
}
}
res <- sf::st_cast(res[grep("POLYGON",geotype),],"MULTIPOLYGON")
}
return(res)
}
else if (geometry=="lines") {
ind <- .grep("(line|collection)",geotype)
if (!length(ind))
return(res)
if (noData <- is.null(spatial_data(res)))
spatial_data(res) <- data.frame(dummy=0L)
res <- res[ind,]
geotype <- geotype[ind]
if (length(na.omit(match(unique(geotype)
,c("MULTILINESTRING","LINESTRING"))))==2) {
if (length(ind2 <- .grep("collection",geotype))) {
res <- spatial_bind(res[-ind2,]
,sf::st_collection_extract(res[ind2,],"LINESTRING"))
geotype <- as.character(spatial_geotype(res,each=TRUE))
}
res <- sf::st_cast(res[grep("LINESTRING",geotype),],"MULTILINESTRING")
}
if (noData)
res <- spatial_geometry(res)
return(res)
}
else if (geometry=="points") {
ind <- .grep("point",geotype)
if (!length(ind))
return(res)
res <- res[ind,]
return(res)
}
if ("GEOMETRYCOLLECTION" %in% uGeotype) {
if (length(grep("POLYGON",uGeotype)))
res <- sf::st_collection_extract(res,"POLYGON")
}
else if (length(na.omit(match(uGeotype,c("POLYGON","MULTIPOLYGON"))))==2) {
res <- sf::st_cast(res[grep("POLYGON",geotype),],"MULTIPOLYGON")
}
else if (length(na.omit(match(uGeotype,c("MULTILINESTRING","LINESTRING"))))==2) {
res <- sf::st_cast(res[grep("LINESTRING",geotype),],"MULTILINESTRING")
}
}
return(res)
}
else if (isSP) {
if (!requireNamespace("raster",quietly=.isPackageInUse()))
stop("suggested package is required for this operation")
# opW <- options(warn=-1)
res <- try(raster::intersect(x,y))
# options(opW)
if (inherits(res,"try-error")) {
res <- raster::intersect(spatial_buffer(x),spatial_buffer(y))
}
if (is.null(res))
return(res)
if (spatial_geotype(res) %in% "POLYGON") {
k <- 0
res@polygons <- lapply(res@polygons,function(x) {
k <<- k+1
x@ID <- as.character(k)
x
})
rm(k)
}
return(res)
}
else if (implement_by_rgeos <- FALSE) {
# stop("unimplemented for 'sp' objects")
.rgeos_requireNamespace()
res <- .rgeos_gIntersection(x,y,byid=TRUE,drop_lower_td=TRUE
,unaryUnion_if_byid_false=FALSE)
res2 <- names(sp::over(spatial_geometry(x),spatial_geometry(y),returnList=TRUE))
res2 <- grep("NA",res2,invert=TRUE,value=TRUE)
str(res2)
# q()
# spatial_data(res) <- data.frame(I=rep(1L,spatial_nrow(res)))
# spatial_write(res,"res1.shp")
# q()
# return(res)
}
NULL
}
'spatial_difference' <- function(x,y,verbose=FALSE) {
isSF <- .isSF(x) & .isSF(y)
isSP <- .isSP(x) & .isSP(y)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
if (inherits(x,"sf"))
sf::st_agr(x) <- "constant"
if (inherits(y,"sf"))
sf::st_agr(y) <- "constant"
res <- try(sf::st_difference(x,y))
if (inherits(res,"try-error")) {
if (length(grep("st_crs\\(x\\) == st_crs\\(y\\) is not TRUE"
,as.character(res))))
res <- sf::st_difference(x,spatial_transform(y,x))
}
return(res)
}
else if (isSP) {
if (!.rgeos_requireNamespace())
stop("suggested package is required for this operation")
# opW <- options(warn=-1)
res <- try(.rgeos_gDifference(x,y,byid=TRUE))
# options(opW)
if (inherits(res,"try-error"))
res <- try(.rgeos_gDifference(spatial_buffer(x),spatial_buffer(y),byid=TRUE))
return(res)
}
else if (dev <- FALSE) {
}
NULL
}
'spatial_symdifference' <- function(x,y,verbose=FALSE) {
isSF <- .isSF(x) & .isSF(y)
isSP <- .isSP(x) & .isSP(y)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
if (inherits(x,"sf"))
sf::st_agr(x) <- "constant"
if (inherits(y,"sf"))
sf::st_agr(y) <- "constant"
res <- try(sf::st_sym_difference(x,y))
if (inherits(res,"try-error")) {
if (length(grep("st_crs\\(x\\) == st_crs\\(y\\) is not TRUE"
,as.character(res))))
res <- sf::st_sym_difference(x,spatial_transform(y,x))
}
return(res)
}
else if (isSP) {
if (!.rgeos_requireNamespace())
stop("suggested package is required for this operation")
# opW <- options(warn=-1)
res <- try(.rgeos_gSymdifference(x,y,byid=TRUE))
# options(opW)
if (inherits(res,"try-error"))
res <- try(.rgeos_gSymdifference(spatial_buffer(x),spatial_buffer(y),byid=TRUE))
return(res)
}
else if (dev <- FALSE) {
}
NULL
}
'spatial_buffer' <- function(obj,dist=0,quadsegs=30L,verbose=FALSE) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (is.character(dist)) {
if (is.null(sc <- getOption("ursaPngScale")))
sc <- 1
if (is.null(retina <- getOption("ursaPngRetina")))
retina <- 1
if (.lgrep("px$",dist)) {
# print(c(dist=dist))
# print(c(scale=sc))
dist <- session_cellsize()*as.numeric(gsub("px","",dist))/sc*retina
# print(c(dist=dist))
}
else if (.lgrep("lwd$",dist)) {
dist <- as.numeric(gsub("lwd","",dist))
cell <- session_cellsize()
sc <- getOption("ursaPngScale")
dpi <- getOption("ursaPngDpi")/96
px <- cell/sc
res <- dist*(px*dpi)
# print(data.frame(dist=dist,cell=cell,dpi=dpi,sc=sc,px=px,res=res))
dist <- res
}
}
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
res <- sf::st_buffer(obj,dist=dist,nQuadSegs=quadsegs)
return(res)
}
else if (isSP) {
if (!.rgeos_requireNamespace())
stop("suggested package is required for this operation")
# opW <- options(warn=-1)
res <- .rgeos_gBuffer(obj,byid=TRUE,width=dist,quadsegs=quadsegs)
# options(opW)
return(res)
}
else if (dev <- FALSE) {
}
NULL
}
'spatial_union' <- function(x,y,byid=NA,verbose=FALSE) {
if (missing(y)) {
isSF <- .isSF(x)
isSP <- .isSP(x)
if (is.na(byid))
byid <- FALSE
}
else {
isSF <- .isSF(x) & .isSF(y)
isSP <- .isSP(x) & .isSP(y)
if (is.na(byid))
byid <- TRUE
}
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
# message("first run: 'spatial_union' for 'sf' object(s)")
# sf::st_agr(x) <- "constant"
# sf::st_agr(y) <- "constant"
res <- sf::st_union(x,y,by_feature=byid)
return(res)
}
else if (isSP) {
if (!.rgeos_requireNamespace())
stop("suggested package is required for this operation")
if (missing(y)) {
res <- try(.rgeos_gUnaryUnion(x,id=NULL))
if (inherits(res,"try-error")) {
res <- .rgeos_gUnaryUnion(.spatial_repair(x),id=NULL)
}
return(res)
}
res <- .rgeos_gUnion(x,y,byid=byid)
return(res)
}
else if (dev <- FALSE) {
}
NULL
}
'spatial_simplify' <- function(obj,tol=0,topologyPreserve=TRUE,verbose=FALSE) {
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
res <- sf::st_simplify(obj,preserveTopology=topologyPreserve,dTolerance=tol)
return(res)
}
else if (isSP) {
if (!.rgeos_requireNamespace())
stop("suggested package is required for this operation")
# opW <- options(warn=-1)
res <- .rgeos_gSimplify(obj,tol=tol,topologyPreserve=topologyPreserve)
# options(opW)
return(res)
}
else if (dev <- FALSE) {
}
NULL
}
'.spatial_repair' <- function(obj,verbose=FALSE) {
# https://www.r-spatial.org/r/2017/03/19/invalid.html
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF) {
valid <- try(sf::st_is_valid(obj,NA_on_exception=TRUE,reason=verbose))
}
else if (isSP) {
if (!.rgeos_requireNamespace())
stop("suggested package is required for this operation")
valid <- try(.rgeos_gIsValid(obj,reason=verbose))
}
else
return(NULL)
if (verbose) {
print(valid)
valid <- FALSE
}
if ((any(inherits(valid,"try-error")))||(any(!valid))) {
if (verbose)
print("repaired by buffering")
obj <- spatial_buffer(obj)
}
obj
}
'spatial_bind' <- function(...) {
arglist <- list(...)
if (length(ind <- which(sapply(arglist,is.null))))
arglist <- arglist[-ind]
if (!length(arglist))
return(NULL)
if ((length(arglist)==1)&&
(any(sapply(arglist[[1]],is_spatial)))&&
(!is_spatial(arglist[[1]])))
arglist <- arglist[[1]]
res <- arglist[[1]]
isSF <- .isSF(res)
isSP <- .isSP(res)
if (!is.null(spatial_data(res))) {
if (isSP) {
# res <- lapply(seq_along(arglist),function(i) sp::spChFIDs(arglist[[i]],as.character(i)))
da <- do.call(rbind,lapply(arglist,spatial_data))
geom <- lapply(arglist,spatial_geometry)
geom$makeUniqueIDs <- TRUE
geom <- do.call(rbind,geom)
# da <- data.frame(foo=seq(spatial_count(geom)))
if (!ncol(da))
return(geom)
spatial_data(geom) <- da
return(geom)
}
if (isSF) {
geom <- unique(sapply(arglist,function(x) attr(x,"sf_column")))
if (length(unique(geom))==1)
return(do.call("rbind",arglist))
if (TRUE) { ## fixed st_column name 'geometry'
for (i in seq_along(arglist))
arglist[[i]] <- sf::st_sf(spatial_data(arglist[[i]])
,geometry=spatial_geometry(arglist[[i]]))
}
else { ## repeat st_column name for first argument
for (i in tail(seq_along(arglist),-1)) {
res <- arglist[[i]]
ind <- match(attr(res,"sf_column"),colnames(res))
colnames(res)[ind] <- geom[1]
attr(res,"sf_column") <- geom[1]
arglist[[i]] <- res
}
}
return(do.call("rbind",arglist))
}
}
if (isSF)
return(do.call("c",arglist))
geoType <- spatial_geotype(res)
coerce <- switch(geoType
,POLYGON="SpatialPolygons" ## "SpatialPolygonsDataFrame"
,LINESTRING="SpatialLines" ## "SpatialLinesDataFrame"
,POINT="SpatialPoints" ## "SpatialPointsDataFrame"
,stop("geoType"))
for (i in seq_along(arglist))
arglist[[i]] <- methods::as(arglist[[i]],coerce)
# res <- spatial_geometry(do.call("rbind",arglist)) ## in the case of *DataFrame
res <- lapply(seq_along(arglist),function(i) sp::spChFIDs(arglist[[i]],as.character(i)))
res <- do.call("rbind",res)
res
}
'spatial_basename' <- function(fname) {
gsub(paste0("\\."
,"(shp|geojson|json|fgb|sqlite|gpkg|mif|kml|osm|csv|tif|envi|bin|envigz|img|bingz)"
,"(\\.(gz|bz2|zip|rar))*$")
,"",basename(fname),ignore.case=TRUE)
}
'spatial_pattern' <- function(fname) {
s <- "|()[]{}^$*+?."
p <- paste0("(",paste(paste0("\\",unlist(strsplit(s,split="+"))),collapse="|"),")")
gsub(p,"\\\\\\1",spatial_basename(fname))
}
'spatial_fileext' <- function(fname) {
a <- gsub("^(.+)(\\.(gz|bz2|zip|rar))$","\\1",basename(fname),ignore.case=TRUE)
gsub(".*\\.(.+)$","\\1",a)
}
'spatial_revise' <- function(obj,engine=c("auto","sf","sp"),verbose=FALSE) {
engine <- match.arg(engine)
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (engine=="auto")
engine <- ifelse(isSF,"sp",ifelse(isSP,"sf",stop('unknown spatial class')))
toSP <- engine=="sp"
toSF <- engine=="sf" & requireNamespace("sf",quietly=.isPackageInUse())
if (isSP & toSP | isSF & toSF)
return(obj)
if (toSP)
return(sf::as_Spatial(obj))
if (toSF) {
## 'methods' have already loaded because Spatial* is S4
# try `sf::st_as_sf`
return(methods::as(obj,"sf"))
}
NULL
}
'spatial_valid' <- function(obj,each=FALSE,reason=FALSE,verbose=FALSE) {
if (is.character(obj))
return(all(obj %in% c("Valid Geometry")))
isSF <- .isSF(obj)
isSP <- .isSP(obj)
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSP) {
if (!.rgeos_requireNamespace())
stop("suggested package is required for this operation")
res <- .rgeos_gIsValid(obj,byid=TRUE,reason=TRUE)
if (reason)
return(unname(res))
if (each)
return(res %in% c("Valid Geometry"))
return(all(res %in% c("Valid Geometry")))
}
if (isSF) {
res <- sf::st_is_valid(obj,reason=TRUE)
if (reason)
return(res)
if (each)
return(res %in% c("Valid Geometry"))
return(all(res %in% c("Valid Geometry")))
}
NULL
}
'spatial_trim' <- function(obj) {
attr(obj,"grid") <- NULL
attr(obj,"toUnloadMethods") <- NULL
attr(obj,"colnames") <- NULL
attr(obj,"style") <- NULL
attr(obj,"geocodeStatus") <- NULL
attr(obj,"dsn") <- NULL
attr(obj,basename(tempfile())) <- NULL ## dummy
obj
}
'spatial_grid' <- function(obj) {
if (!is_spatial(obj))
return(ursa_grid(obj))
if ((is.numeric(obj))&&(length(obj)==4)) {
bbox <- obj
if (!is.null(attr(obj,"crs")))
crs <- attr(obj,"crs")
else
crs <- session_crs()
}
else {
bbox <- spatial_bbox(obj)
if ((bbox["xmin"]==bbox["xmax"])||(bbox["ymin"]==bbox["ymax"]))
bbox <- bbox+100*c(-1,-1,1,1)
crs <- spatial_crs(obj)
}
if ((.lgrep("\\+proj=longlat",crs))&&(bbox["xmax"]<0)&&(bbox["xmin"]>0))
bbox["xmax"] <- bbox["xmax"]+360
nc <- (bbox["xmax"]-bbox["xmin"])
nr <- (bbox["ymax"]-bbox["ymin"])
res <- max(nc,nr)/640
p <- as.numeric(pretty(res))
res <- p[which.min(abs(res-p))]
regrid(setbound=unname(bbox),crs=crs,res=res)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/spatial_engine.R
|
'spatial_levelsplit' <- function(obj,sep=" - ") {
ind <- order(spatial_area(obj),decreasing=TRUE)
n <- length(ind)
obj <- obj[ind,]
res <- vector("list",length(ind-1))
aname <- spatial_colnames(obj)
res[[1]] <- tail(obj,1)
da <- spatial_data(obj)
if (length(dtype <- which(sapply(da,inherits,c("integer","numeric"))))) {
for (i in dtype) {
spatial_data(res[[1]])[,i] <- paste("0",spatial_data(res[[1]])[,i],sep=sep)
}
}
for (i in rev(tail(seq(spatial_count(obj)),-1))) {
res2 <- spatial_difference(spatial_geometry(obj[i-1,]),spatial_geometry(obj[i,]))
da2 <- apply(da[c(i,i-1),,drop=FALSE],2,function(x) {
y <- unique(x)
if (length(y)==1)
return(y)
paste(unique(x),collapse=sep)
})
if (!is.list(da2))
da2 <- lapply(da2,function(x) x)
spatial_data(res2) <- as.data.frame(da2)
res[[n-i+2L]] <- res2
}
ret <- do.call(spatial_bind,res)
ret
}
'.spatial_levelsplit_prev' <- function(obj,sep=" - ") {
ind <- order(spatial_area(obj),decreasing=TRUE)
obj <- obj[rev(ind),]
res <- vector("list",length(ind-1))
n1 <- ncol(spatial_data(obj))
indCol1 <- seq(1L,n1)
indCol2 <- seq(n1+1L,2L*n1)
aname <- spatial_colnames(obj)
res[[1]] <- obj[tail(ind,1),]
da <- spatial_data(obj)
if (length(dtype <- which(sapply(da,inherits,c("integer","numeric")))))
for (i in dtype)
spatial_data(res[[1]])[,i] <- paste("0",spatial_data(res[[1]])[,i],sep=sep)
for (i in tail(ind,-1)) {
res2 <- spatial_difference(spatial_geometry(obj[i+1,]),spatial_geometry(obj[i,]))
da2 <- apply(da[c(i,i+1),,drop=FALSE],2,function(x) {
y <- unique(x)
if (length(y)==1)
return(y)
paste(unique(x),collapse=sep)
})
if (!is.list(da2))
da2 <- lapply(da2,function(x) x)
spatial_data(res2) <- as.data.frame(da2)
res[[i+1]] <- res2
}
do.call(spatial_bind,res)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/spatial_levelsplit.R
|
'spatial_read' <- function(dsn,engine=c("native","sf","geojsonsf")) {
if (.lgrep("\\.(tif|tiff|tif\\.zip|img|png|bmp|dat)$",dsn))
return(ursa_read(dsn))
g0 <- getOption("ursaSessionGrid")
res <- spatialize(dsn=dsn,engine=engine,style="keep")
if (FALSE)
res <- spatial_trim(res)
else if (TRUE) {
sapply(c("toUnloadMethods","colnames","style","geocodeStatus","dsn","grid")
,function(x) attr(res,x) <<- NULL)
}
else {
attr(res,"toUnloadMethods") <- NULL
attr(res,"colnames") <- NULL
attr(res,"style") <- NULL
attr(res,"geocodeStatus") <- NULL
attr(res,"dsn") <- NULL
attr(res,"grid") <- NULL
}
res
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/spatial_read.R
|
'spatial_write' <- function(obj,fname,layer,driver=NA,compress=""
,ogr2ogr=nchar(Sys.which("ogr2ogr"))>0
,verbose=FALSE) {
# obj <- head(obj,100)
bname <- basename(fname)
dname <- dirname(fname)
if ((dname!=".")&&(!dir.exists(dname)))
dir.create(dname,recursive=TRUE)
fext <- .gsub("^.+\\.(.+)$","\\1",bname)
wait <- 60
isGeoJSON <- fext %in% c("geojson")
interimExt <- if (isGeoJSON) fext else c("gpkg","geojson","shp","sqlite")[4]
driverList <- c(shp="ESRI Shapefile"
,sqlite="SQLite",json="GeoJSON",geojson="GeoJSON",gpkg="GPKG"
,tab="Mapinfo File",kml="KML",fgb="FlatGeobuf")
if (!nchar(compress)) {
packPatt <- "^(zip|bz(ip)*2|gz(ip)*|xz)$"
if (.lgrep(packPatt,fext)>0) {
compress <- .gsub(packPatt,"\\1",fext)
bname <- gsub(paste0("\\.",compress),"",bname)
fext <- .gsub("^(.+)\\.(.+)$","\\2",bname)
fname <- file.path(dname,bname)
}
}
lname <- .gsub("^(.+)\\.(.+)$","\\1",bname)
if (inherits(obj,"sf"))
isList <- FALSE
else
isList <- is.list(obj)
if (isList) {
cl <- sapply(obj,inherits,c("sf","sfc","SpatialLinesDataFrame"
,"SpatialPointsDataFrame","SpatialPolygonsDataFrame"
,"SpatialLines","SpatialPoints","SpatialPolygons"))
cl2 <- sapply(obj,function(x) {
if (.isSF(x))
return("sf")
if (.isSP(x))
return("sp")
return("unknown")
})
allSF <- all(cl2 %in% "sf")
allSP <- all(cl2 %in% "sp")
if (any(!cl))
isList <- FALSE
}
if (!is.character(driver)) {
driver <- driverList[fext]
if (is.na(driver)) {
if (isList)
driver <- driverList["sqlite"]
else
driver <- driverList["sqlite"]
fext <- names(driver)
lname <- bname
bname <- paste0(lname,".",fext)
fname <- file.path(dname,bname)
}
}
if ((!missing(layer))&&((is.character(layer))&&(nchar(layer))))
lname <- layer
ext <- switch(driver,'ESRI Shapefile'="(cpg|dbf|prj|qpj|shp|shx)"
,'MapInfo File'="(mif|mid)",fext)
if (isList) {
if ((!allSF)&&(!ogr2ogr))
stop("'ogr2ogr' is requires to merge layers")
# fname1 <- paste0("res",seq_along(obj),".gpkg")
# fname1 <- .maketmp(length(obj),ext=interimExt)
fname1 <- file.path(tempdir(),paste0("interim",seq_along(obj),".",interimExt))
if (!allSF)
pb <- ursaProgressBar(min=0,max=2*length(obj),tail=TRUE)
p4s <- sapply(obj,function(x){
res <- if (inherits(x,c("sf","sfc"))) sf::st_crs(x)$proj4string
else sp::proj4string(x)
res
})
p4s <- unname(p4s)
# keepCRS <- ifelse(length(p4s)==1,TRUE,do.call("all.equal",as.list(p4s)))
keepCRS <- ifelse(length(p4s)==1,TRUE,{
p4ind <- expand.grid(seq_along(p4s),seq_along(p4s))
p4ind <- as.list(data.frame(t(as.matrix(p4ind[p4ind[,1]<p4ind[,2],]))))
all(sapply(p4ind,function(i) identical(p4s[i[1]],p4s[i[2]])))
})
if (verbose)
.elapsedTime("list:0")
iname <- vector("list",length(fname1))
lname <- names(obj)
if (is.null(lname))
lname <- rep("",length(obj))
if (any(ind <- !nchar(lname))) {
## try mget(names(match.call())[-1])
lname[ind] <- as.character(as.list(match.call())$obj)[-1][ind]
# lname[ind] <- aname[ind]
}
options(ursaSpatialMultiLayer=0L)
for (i in seq_along(obj)) {
o <- obj[[i]]
isSF <- inherits(o,c("sf","sfc"))
isSP <- !isSF
if (isSF) {
ind <- match(attr(o,"sf_column"),colnames(o))
jname <- colnames(o)[-ind]
if (interimExt=="shp")
colnames(o)[-ind] <- sprintf("fld%03d",seq_along(jname))
}
else if (isSP) {
jname <- colnames(methods::slot(o,"data"))
if (interimExt=="shp")
colnames(methods::slot(o,"data")) <- sprintf("fld%03d",seq_along(jname))
}
iname[[i]] <- jname
options(ursaSpatialMultiLayer=getOption("ursaSpatialMultiLayer")+1L)
if (allSF) {
if (isGeoJSON) {
spatial_write(o,fname1[i],verbose=verbose) ## RECURSIVE
}
else
spatial_write(o,fname,layer=lname[i],verbose=verbose) ## RECURSIVE
}
else
spatial_write(o,fname1[i],verbose=verbose) ## RECURSIVE
if (!allSF)
setUrsaProgressBar(pb)
if (verbose)
.elapsedTime(paste0("list:",i))
}
options(ursaSpatialMultiLayer=NULL)
if (allSF) {
if (!isGeoJSON)
return(invisible(0L))
a <- lapply(fname1,function(src) {
a <- readLines(src,encoding="UTF-8")
a <- paste(a,collapse="")
ind2 <- regexpr("\"features\":\\s*\\[",a)
a <- substr(a,ind2+attr(ind2,"match.length"),nchar(a)-2)
a <- paste0(a,",")
a
})
a <- c("{","\"type\": \"FeatureCollection\", \"features\": [",do.call(c,a),"]}")
ind <- length(a)-1L
a[ind] <- substr(a[ind],1,nchar(a[ind])-1)
Fout <- file(fname,encoding="UTF-8")
writeLines(a,Fout)
close(Fout)
file.remove(fname1)
return(invisible(0L))
}
dopt <- character()
lopt <- character()
if (driver=="ESRI Shapefile")
lopt <- c(lopt,"ENCODING=UTF-8","ADJUST_GEOM_TYPE=ALL_SHAPES")
if (driver=="MapInfo File")
dopt <- c(dopt,"FORMAT=MIF")
if (driver=="SQLite") {
# dopt <- c(dopt,"SPATIALITE=yes")
lopt <- c(lopt,"LAUNDER=NO")#,"SPATIAL_INDEX=YES")
}
suppressWarnings({
first <- TRUE
op <- options(warn=2)
for (i in seq(wait)) {
if (!file.exists(fname))
break
if (file.remove(fname))
break
if (first) {
cat(paste("Waiting",wait,"seconds for permitted writting"
,.sQuote(bname)))
first <- FALSE
}
cat(".")
Sys.sleep(1)
}
options(op)
if (!first) {
if (i==wait)
cat(" FAILURE!\n")
else
cat(" ok!\n")
}
})
for (i in seq_along(fname1)) {
if (!allSF)
setUrsaProgressBar(pb)
b <- paste(fname,fname1[i],"-nln",lname[i])
if (length(dopt))
b <- paste(paste("-dco",dopt),b)
if (length(lopt))
b <- paste(paste("-lco",lopt),b)
if ((i==1)&&(keepCRS))
b <- paste(b,"-t_srs",.dQuote(p4s[1]))
if ((interimExt=="shp")&&(!is.null(iname[[i]]))) {
aname <- sprintf("fld%03d",seq_along(iname[[i]]))
s <- paste("select",paste(aname,"as",paste0("\\\"",iname[[i]],"\\\"")
,collapse=",")
,"from",paste0("\\\""
,.gsub("\\.shp$","",basename(fname1[i]))
,"\\\""))
s <- paste("-sql",.dQuote(s))
##~ cat(s)
##~ cat("\n")
##~ s <- ""
}
else
s <- ""
if (i==1)
cmd <- paste("ogr2ogr",s,"-f",.dQuote(driver),b)
else
cmd <- paste("ogr2ogr",s,"-update -append",b)
if (verbose)
message(cmd)
if (!system(cmd)) {
if (.lgrep("\\.shp$",basename(fname1[i])))
.shp.remove(fname1[i])
else if (file.exists(fname1[i]))
file.remove(fname1[i])
}
if (verbose)
.elapsedTime(paste0("append:",i))
}
if (!allSF)
close(pb)
return(invisible(0L))
}
appendlayer <- getOption("ursaSpatialMultiLayer")
appendlayer <- ifelse(is.null(appendlayer),FALSE,appendlayer>1)
if ((ogr2ogr)&&(interimExt!="sqlite")&&(driver %in% "SQLite")) { ## sf>=0.6.3 great improvement
interim <- TRUE
driver0 <- driver
fext0 <- fext
fname0 <- fname
fext <- interimExt
driver <- driverList[fext]
# fname <- .gsub(paste0("\\.",fext0,"$"),paste0(".",fext),fname)
fname <- .maketmp(ext=interimExt)
bname <- basename(fname)
p4s <- if (inherits(obj,c("sf","sfc"))) sf::st_crs(obj)$proj4string
else sp::proj4string(obj)
}
else
interim <- FALSE
dopt <- character()
lopt <- character()
if (driver=="ESRI Shapefile")
lopt <- c(lopt,"ENCODING=UTF-8")
if (driver=="MapInfo File")
dopt <- c(dopt,"FORMAT=MIF")
if (driver=="SQLite") {
# dopt <- c(dopt,"SPATIALITE=yes")
lopt <- c(lopt,"LAUNDER=NO")#,"SPATIAL_INDEX=YES")
}
if (driver=="FlatGeobuf") {
lopt <- c(lopt,"SPATIAL_INDEX=NO")
}
if ((is.logical(compress))&&(compress)) {
compress <- if (driver %in% c("GeoJSON","SQLite","FlatGeobuf","GPKG","KML")) "gz"
else "zip"
}
if (verbose)
print(data.frame(fname=fname,pack=compress,bname=bname,layer=lname
,ext=fext,driver=driver))
if (!appendlayer) {
suppressWarnings({
first <- TRUE
op <- options(warn=2)
fname.gz <- paste0(fname,".gz")
for (i in seq(wait)) {
if (file.exists(fname.gz))
file.remove(fname.gz)
if (!file.exists(fname))
break
if (file.remove(fname))
break
if (first) {
cat(paste("Waiting",wait,"seconds for permitted writting"
,.sQuote(bname)))
first <- FALSE
}
cat(".")
Sys.sleep(1)
}
options(op)
if (!first) {
if (i==wait)
cat(" FAILURE!\n")
else
cat(" ok!\n")
}
})
}
if (is.null(spatial_geometry(obj))) {
if ("sf" %in% loadedNamespaces()) {
sf::st_write(obj,dsn=fname,layer=lname,driver=driver
,dataset_options=dopt,layer_options=lopt
,delete_layer=file.exists(fname) & !appendlayer
,delete_dsn=file.exists(fname) & !appendlayer
,append=!file.exists(fname) | appendlayer ## append=T means replace=F
,quiet=!verbose)
return(invisible(NULL))
}
}
isSF <- inherits(obj,c("sf","sfc"))
isSP <- !isSF
if (verbose)
print(data.frame(sf=isSF,sp=isSP,row.names="engine"))
if (isSF)
aname <- try(names(sf::st_agr(obj)),silent=TRUE)
else if (isSP)
aname <- try(colnames(methods::slot(obj,"data")),silent=TRUE)
if (inherits(aname,"try-error"))
aname <- character()
for (a in aname) {
if (is.ordered(obj[[a]])) {
if (.is.numeric(levels(obj[[a]])))
obj[[a]] <- as.numeric(as.character(obj[[a]]))
else
obj[[a]] <- factor(obj[[a]],ordered=FALSE)
}
else if ((is.factor(obj[[a]]))&&(.is.numeric(levels(obj[[a]]))))
obj[[a]] <- as.numeric(as.character(obj[[a]]))
}
if (driver %in% c("ESRI Shapefile")) {
for (a in aname) {
if (!inherits(obj[[a]],"POSIXt"))
next
v <- as.character(as.POSIXct(as.numeric(obj[[a]])
,origin="1970-01-01",tz="UTC"))
obj[[a]] <- paste0(.gsub("(^.+\\d)(\\s)(\\d.+$)","\\1\\T\\3",v),"Z")
}
}
if (isSP) {
if (driver %in% c("GeoJSON","KML","GPX")) {
obj <- sp::spTransform(obj,sp::CRS("+init=epsg:4326"))
}
opW <- options(warn=1)
# dsn <- if (driver %in% c("zzzESRI Shapefile")) dname else fname
if ((interim)&&(interimExt=="shp")) {
colnames(methods::slot(obj,"data")) <- iname <- sprintf("fld%03d"
,seq_along(colnames(methods::slot(obj,"data"))))
}
lch <- getOption("encoding")
lcl <- localeToCharset()
if (length(lcl)>1)
lcl <- grep("UTF.*8",lcl,value=TRUE,invert=TRUE,ignore.case=TRUE)
if (length(lcl)>1)
lcl <- lcl[1]
if (!inherits(obj,c("SpatialPointsDataFrame","SpatialLinesDataFrame"
,"SpatialPolygonsDataFrame")))
spatial_data(obj) <- data.frame(dummy=seq_len(spatial_count(obj)))
.rgdal_writeOGR(obj
,dsn=fname # iconv(fname,to="UTF-8")
,layer=lname,driver=driver
,dataset_options=dopt,layer_options=lopt
,encoding=if (lch=="UTF-8") NULL else lcl
,overwrite_layer=TRUE,morphToESRI=FALSE
,verbose=verbose)
if ((FALSE)&&(driver=="ESRI Shapefile")) { ## replace "OGC ESRI" by "OGC WKT"
prj <- sp::proj4string(obj)
prj1 <- .rgdal_showWKT(prj,morphToESRI=TRUE)
prj2 <- .rgdal_showWKT(prj,morphToESRI=FALSE)
if (!identical(prj1,prj2)) {
writeLines(prj2,gsub("\\.shp$",".prj",fname))
}
}
options(opW)
}
else if (isSF) {
if (FALSE) {
f <- .dir(path=dname
,pattern=paste0("^",lname,"\\.",ext,"$")
,full.names=TRUE)
file.remove(f)
}
if (driver %in% c("GeoJSON","KML","GPX")) {
if (!identical(spatial_crs(obj),spatial_crs(4326))) {
if ((devel <- FALSE)&&(!.isPackageInUse())) {
## see ?make_EPSG for 'rgdal'
print(spatial_crs(obj))
# epsg <- sf::st_crs(spatial_crs(obj))$epsg
# print(c(epsg=epsg))
print(sf::st_crs(3571)$proj4string)
print(sf::st_crs(spatial_crs(obj))$proj4string)
print(sf::st_crs(3571)$epsg)
print(sf::st_crs(spatial_crs(obj))$epsg)
q()
}
obj <- sf::st_transform(obj,4326)
}
}
opW <- options(warn=1)
if ((interim)&&(interimExt=="shp")) {
# ind <- head(seq_along(obj),-1)
ind <- which(is.na(match(colnames(obj),attr(obj,"sf_column"))))
names(obj)[ind] <- iname <- sprintf("fld%03d",ind)
}
if (FALSE) {
print(c(dsn=fname,layer=lname,appendlayer=as.character(appendlayer))
,quote=FALSE)
print(c(delete_layer=file.exists(fname) & !appendlayer
,delete_dsn=file.exists(fname) & !appendlayer
,append=appendlayer))
}
jsonSF <- (isSF)&&(driver=="GeoJSON")&&(T | !inherits(obj,"sfc"))&&
(requireNamespace("geojsonsf",quietly=.isPackageInUse()))
if (jsonSF) {
# fromList <- length(tail(.parentFunc(),-1))>1
# enc2native(a);Encoding(a) <- "UTF-8"
Fout <- file(fname)#,encoding="UTF-8")
if (inherits(obj,"sfc")) {
a <- geojsonsf::sfc_geojson(obj,digits=6)
# cl <- class(a)
# a <- c("{\"type\": \"FeatureCollection\",\"features\": [",a,"]}")
# class(a) <- cl
writeLines(a,Fout)
}
else {
aname <- spatial_colnames(obj)
if (length(ind <- which(Encoding(aname) %in% "unknown"))) {
# print(ind)
# print(aname[ind])
# print(Encoding(aname[ind]))
aname[ind] <- enc2utf8(aname[ind])
spatial_colnames(obj) <- aname
# print(Encoding(bname))
# bname <- iconv(aname[ind],from="unknown",to="UTF=8")
# bname <- iconv(iconv(aname,to="UTF=8"),to="native")
# print(bname)
# q()
}
if (length(ind <- which(sapply(obj,inherits,"character")))) {
for (i in ind) {
obj[,i] <- enc2utf8(obj[,i,drop=TRUE])
# obj[,i] <- iconv(obj[,i,drop=TRUE],to="UTF-8")
# Encoding(obj[[i]]) <- "UTF-8"
}
}
if (length(ind <- which(sapply(obj,inherits,c("POSIXlt","POSIXct"))))) {
for (i in ind) {
obj[,i] <- format(c(obj[,i,drop=TRUE]),tz="UTC","%Y-%m-%dT%H:%M:%SZ")
}
}
a <- geojsonsf::sf_geojson(obj,atomise=F,simplify=F,digits=6)
# a <- iconv(a,to="UTF-8")
# writeLines(a,Fout)
writeLines(a,Fout)
}
close(Fout)
}
else if (utils::packageVersion("sf")>="0.9-0") {
sf::st_write(obj,dsn=fname,layer=lname,driver=driver
,dataset_options=dopt,layer_options=lopt
,delete_layer=file.exists(fname) & !appendlayer
,delete_dsn=file.exists(fname) & !appendlayer
,append=!file.exists(fname) | appendlayer ## append=T means replace=F
,quiet=!verbose)
}
else
sf::st_write(obj,dsn=fname,layer=lname,driver=driver
,dataset_options=dopt,layer_options=lopt
,delete_layer=file.exists(fname) & !appendlayer
,delete_dsn=file.exists(fname) & !appendlayer
,update=appendlayer ## -> 'append' in v0.9-0 (deprecation error)
,quiet=!verbose)
if ((FALSE)&&(driver %in% "ESRI Shapefile")) { ## replace "OGC ESRI" by "OGC WKT"
prjname <- gsub("\\.shp$",".prj",fname)
wkt1 <- readLines(prjname,warn=FALSE)
wkt2 <- sf::st_as_text(sf::st_crs(spatial_crs(obj)))
if (!identical(wkt1,wkt2))
writeLines(wkt2,prjname)
}
options(opW)
}
if (interim) {
dopt <- character()
lopt <- character()
if (driver0=="MapInfo File")
dopt <- c(dopt,"FORMAT=MIF")
if (driver0=="SQLite") {
# dopt <- c(dopt,"SPATIALITE=yes")
lopt <- c(lopt,"LAUNDER=NO")#,"SPATIAL_INDEX=YES")
}
b <- character()
if (length(dopt))
b <- c(b,paste("-dco",.dQuote(dopt)))
if (length(lopt))
b <- c(b,paste("-lco",.dQuote(lopt)))
lnameF <- ifelse(interimExt=="shp",.gsub("\\.shp$","",basename(fname)),lname)
if (length(aname)) {
s <- paste("select"
,paste(iname,"as",paste0("\\\"",aname,"\\\""),collapse=",")
,"from",paste0("\\\"",lnameF,"\\\""))
s <- paste("-sql",.dQuote(s))
}
else
s <- ""
cmd <- paste("ogr2ogr"
,ifelse(verbose,"-progress",""),s
,"-f",.dQuote(driver0)
,ifelse(interimExt=="shp","",paste("-t_srs",.dQuote(p4s)))
,b
,.dQuote(fname0),.dQuote(fname),"-nln",lname)
if (verbose)
message(cmd)
keepHDR <- length(envi_list(lname))
if (keepHDR) {
fhdr2 <- tempfile()
fhdr1 <-paste0(lname,".hdr")
file.rename(fhdr1,fhdr2)
}
system(cmd) ## this ov
if (keepHDR) {
file.rename(fhdr2,fhdr1)
}
if (file.exists(fname0)) {
if (interimExt=="shp")
.shp.remove(fname)
else
file.remove(fname)
}
}
else if (driver=="ESRI Shapefile") {
cpgname <- file.path(dname,paste0(lname,".cpg"))
if (FALSE)
writeLines("1251",cpgname)
else {
if (file.exists(cpgname))
file.remove(cpgname)
}
}
if (!nchar(compress))
return(invisible(NULL))
if (verbose)
cat("pack...")
if ((.lgrep("gz",compress))&&(nchar(Sys.which("gzip"))))
system2("gzip",c("-9","-f",fname))
else if (.lgrep("bz(ip)*2",compress)&&(nchar(Sys.which("bzip2"))))
system2("bzip2",c("-f",fname))
else if (.lgrep("xz",compress)&&(nchar(Sys.which("xz"))))
system2("xz",c("-f",fname))
else if (compress=="zip") {
f <- .dir(path=dname
,pattern=paste0("^",lname,"\\.",ext,"$")
,full.names=TRUE)
if (!length(f)) {
s <- paste0("(",paste(paste0("\\",unlist(strsplit("|()[]{}^$*+?",split="+")))
,collapse="|"),")")
lname <- gsub(s,"\\\\\\1",lname)
f <- .dir(path=dname
,pattern=paste0("^",lname,"\\.",ext,"$")
,full.names=TRUE)
}
z <- paste0(fname,".zip")
opW <- options(warn=-1)
first <- TRUE
for (i in seq(wait)) {
if (!file.exists(z))
break
if (file.remove(z))
break
if (first) {
cat(paste("Waiting for deleting",.sQuote(z)))
first <- FALSE
}
cat(".")
Sys.sleep(1)
}
if (!first) {
if (i==wait)
cat(" FAILURE!\n")
else
cat(" ok!\n")
}
options(opW)
if (hasDir <- dirname(z)!=".")
wd <- setwd(dirname(z))
ret <- utils::zip(basename(z),basename(f),flags="-qmj") ## -9?
## verbose output ## 'myzip(z,f,keys="-m -9 -j")'
if (hasDir)
setwd(wd)
if (ret) {
if (isSevenZip <- nchar(Sys.which("7z"))>0) {
if (!.isPackageInUse()) {
opW <- options(warn=1)
warning("'zip' is failed. Trying '7z'")
options(opW)
}
ret <- system2("7z",c("a -mx9 -sdel -sccWIN",dQuote(z),dQuote(f)),stdout="nul")
}
else {
opW <- options(warn=1)
warning("Unable to compress files (zip)")
options(opW)
}
}
}
if (verbose)
cat(" done!\n")
invisible(NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/spatial_write.R
|
'temporal_interpolate' <- function(obj,win=7,cover=0,verbose=FALSE)
{
fun <- "temporal_interpolate" # as.character(match.call())[1]
win <- floor(win/2)*2+1
if (win<1)
win <- 1
if (cover>1)
cover <- cover/win
if (cover>1)
cover <- 1
if (cover<0)
cover <- 0
isArray <- FALSE
if (!is.ursa(obj))
{
if (!is.array(obj))
return (NULL)
isArray <- TRUE
}
if (isArray)
{
dimx <- dim(obj)
a <- .Cursa(C_interp4
,x=as.numeric(obj),dim=as.integer(dimx),win=as.integer(win)
,cover=as.numeric(cover)
,res=numeric(prod(dimx)),NAOK=TRUE)$res
dim(a) <- dimx
return(a)
}
dimx <- dim(obj$value)
if (verbose)
.elapsedTime(paste(fun,"start",sep=":"))
obj$value[] <- .Cursa(C_interp4
,x=as.numeric(obj$value),dim=as.integer(dimx)
,win=as.integer(win),cover=as.numeric(cover)
,res=numeric(prod(dimx)),NAOK=TRUE)$res
if (verbose)
.elapsedTime(paste(fun,"stop",sep=":"))
obj
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/temporal_interpolate.R
|
'temporal_mean' <- function(obj,win=7,cover=0,verbose=FALSE)
{
fun <- "temporal_mean" # as.character(match.call())[1]
win <- floor(win/2)*2+1
if (win<1)
win <- 1
if (cover>1)
cover <- cover/win
if (cover>1)
cover <- 1
if (cover<0)
cover <- 0
isArray <- FALSE
if (!is.ursa(obj))
{
if (!is.array(obj))
return (NULL)
isArray <- TRUE
}
if (isArray)
{
dimx <- dim(obj)
a <- .Cursa(C_timefilt4
,x=as.numeric(obj),dim=as.integer(dimx),win=as.integer(win)
,cover=as.numeric(cover)
,res=numeric(prod(dimx)),NAOK=TRUE)$res
dim(a) <- dimx
return(a)
}
# obj <- ursa_new(len=x$dim[2])
dimx <- dim(obj$value)
if (verbose)
.elapsedTime(paste(fun,"start",sep=":"))
obj$value[] <- .Cursa(C_timefilt4
,x=as.numeric(obj$value),dim=as.integer(dimx)
,win=as.integer(win),cover=as.numeric(cover)
,res=numeric(prod(dimx)),NAOK=TRUE)$res
if (verbose)
.elapsedTime(paste(fun,"stop",sep=":"))
obj
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/temporal_mean.R
|
'ursa' <- function(obj,attr,...) {
if (missing(obj)) {
return(as.ursa(attr,...))
}
if (missing(attr)) {
if (is.character(obj)) {
if (.lgrep("grid",obj))
return(session_grid())
if (.lgrep("(proj|crs)",obj))
return(session_crs())
if (.lgrep("(cell)",obj))
return(session_cellsize())
if (.lgrep("(^dummy$)",obj,ignore.case=FALSE))
return(ursa_dummy())
}
return(as.ursa(obj,...))
}
if (!is.character(attr)) {
if (.lgrep("dummy",obj))
return(ursa_dummy(attr,...))
return(as.ursa(obj,attr,...))
}
if (is.array(obj))
return(as.ursa(obj))
if (is.matrix(obj))
return(as.ursa(obj))
if (is.numeric(obj))
return(as.ursa(obj))
if (.is.ursa_stack(obj)) {
return(NULL)
}
if (.lgrep("^(color|ct)",attr))
return(ursa_colortable(obj))
if (is.ursa(obj,"grid")) {
if (.lgrep("^(proj|crs)",attr))
return(ursa_proj(obj))
if (.lgrep("^grid",attr))
return(ursa_grid(obj))
if (.lgrep("brick",attr))
return(ursa_brick(obj))
if (.lgrep("^cell",attr))
return(with(ursa_grid(obj),sqrt(resx*resy)))
if (.lgrep("^(extent|bbox)",attr)) {
res <- with(ursa_grid(obj),c(xmin=minx,ymin=miny,xmax=maxx,ymax=maxy))
attr(res,"crs") <- ursa_crs(obj)
return(res)
}
if (.lgrep("(ncol|columns|samples)",attr))
return(ursa_grid(obj)$columns)
if (.lgrep("(nrow|rows|lines)",attr))
return(ursa_grid(obj)$rows)
if (.lgrep("^dim",attr))
return(dim(obj))
return(NULL)
}
if (!is.ursa(obj)) {
options(warn=1)
if (.lgrep("^table",attr)) {
if ((is.list(obj))&&(all(names(obj) %in% c("index","colortable")))) {
na <- names(obj$colortable)
ta <- table(with(obj,names(colortable[index])))
res <- rep(0L,length(na))
names(res) <- na
class(res) <- "table"
ind <- match(names(ta),na)
res[ind] <- as.integer(ta)
return(res)
}
}
return(obj)
}
if (.lgrep("^grid",attr))
return(ursa_grid(obj))
if (.lgrep("^con",attr))
return(.ursa_connection(obj))
if (.lgrep("^(proj|crs)",attr))
return(ursa_proj(obj))
if (.lgrep("^val",attr))
return(ursa_value(obj,...))
##~ if (.lgrep("(color|ct)",attr))
##~ return(ursa_colortable(obj))
if (.lgrep("^(categ|class)",attr))
return(names(ursa_colortable(obj)))
if (.lgrep("(nodata|ignorevalue|bg)",attr))
return(ignorevalue(obj))
if (.lgrep("^table",attr))
return(as.table(obj))
if (.lgrep("^cell",attr))
return(with(ursa_grid(obj),sqrt(resx*resy)))
if (.lgrep("^name",attr))
return(bandname(obj))
if (.lgrep("^dim$",attr))
return(dim(obj))
if (.lgrep("^(extent|bbox)",attr))
return(with(ursa_grid(obj),c(xmin=minx,ymin=miny,xmax=maxx,ymax=maxy)))
if (.lgrep("(ncol|columns|samples)",attr))
return(ursa_grid(obj)$columns)
if (.lgrep("(nrow|rows|lines)",attr))
return(ursa_grid(obj)$rows)
if (.lgrep("(nband|bands|nlayer|layers)",attr))
return(nband(obj))
if (.lgrep("(info|meta(data)*)",attr))
return(ursa_info(obj))
if (.lgrep("^file(name)*",attr))
return(obj$con$fname)
if (.lgrep("(dummy)",attr)) {
return(obj$con$fname)
}
return(NULL)
}
'ursa<-' <- function(obj,attr,...,value) {
if (missing(obj))
return(obj)
if (!is.ursa(obj))
return(obj)
if (missing(attr))
return(obj)
if (.lgrep("grid",attr)) {
ursa_grid(obj) <- value
return(obj)
}
if (.lgrep("(proj|crs)",attr)) {
ursa_crs(obj) <- value
return(obj)
}
if (.lgrep("val",attr)) {
ursa_value(obj,...) <- value
return(obj)
}
if (.lgrep("(color|ct)",attr)) {
ursa_colortable(obj) <- value
return(obj)
}
if (.lgrep("(categ|class)",attr)) {
if (!length(value))
names(ursa_colortable(obj)) <- NULL
else
names(ursa_colortable(obj)) <- value
return(obj)
}
if (.lgrep("(name)",attr)) {
bandname(obj) <- value
return(obj)
}
if (.lgrep("(nodata|ignorevalue|bg)",attr)) {
ignorevalue(obj) <- value
return(obj)
}
if (.lgrep("(bbox|extent)",attr)) {
ursa_grid(obj) <- regrid(ursa_grid(obj),setbound=value)
return(obj)
}
return(obj)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/ursa_000.R
|
'as_ursa' <- function(obj,...) as.ursa(obj=obj,...)
'as.ursa' <- function(obj,...) {
if (missing(obj))
return(ursa_new(...))
if (is.ursa(obj))
return(obj)
if (.is.ursa_stack(obj))
return(ursa_brick(obj)) ## 20170122 removed 'return(obj)'
if (is.data.frame(obj)) {
return(allocate(obj,...))
}
if (inherits(obj,c("SpatialGridDataFrame"))) {
requireNamespace("sp",quietly=.isPackageInUse())
cs <- methods::slot(sp::getGridTopology(obj),"cellsize")
bb <- c(sp::bbox(obj))
opW6 <- options(warn=ifelse(.isPackageInUse(),0,1))
pr <- sp::proj4string(obj)
options(opW6)
# g1 <- regrid(bbox=bb,res=cd,proj=p)
g1 <- regrid(ursa_grid(),bbox=bb,res=cs,proj=pr)
session_grid(g1)
isList <- F
# dt <- all(sapply(obj@data,class) %in% c("numeric"))
dt <- sapply(obj@data,class)
isList <- !(all(dt %in% "integer") | all(dt %in% "numeric"))
if (isList) {
res <- vector("list",ncol(methods::slot(obj,"data")))
names(res) <- names(dt) # colnames(methods::slot(obj,"data"))
}
else {
res <- ursa(bandname=names(dt))
}
for (i in seq_len(ncol(methods::slot(obj,"data")))) {
value <- methods::slot(obj,"data")[,i]
if (!is.numeric(value)) {
val <- factor(value)
value <- as.integer(val)-1L
ct <- ursa_colortable(colorize(value,name=levels(val)))
if (TRUE)
ct[] <- NA
res[[i]] <- ursa_new(value,colortable=ct,flip=FALSE
,permute=FALSE)#,bandname=names(res)[i])
class(res[[i]]$value) <- "ursaCategory"
}
else {
if (isList)
res[[i]] <- ursa_new(value,flip=FALSE
,permute=FALSE)#,bandname=names(res)[i])
else {
res$value[,i] <- value
}
}
}
if (isList) {
if (length(ind <- which(sapply(res,is.null)))) {
res[ind] <- as.list(ursa_new(NA,nband=length(ind)))
}
for (i in seq_along(res))
names(res[[i]]) <- names(res)[i]
}
return(res)
}
if (inherits(obj,c("SpatialPointsDataFrame"#,"SpatialPoints"
,"SpatialPixelsDataFrame"))) {
return(allocate(obj,...))
}
if (inherits(obj,c("RasterBrick","RasterStack","RasterLayer"))) {
g1 <- .grid.skeleton()
e <- raster::extent(obj)
##~ g1$minx <- round(e@xmin,5)
##~ g1$maxx <- round(e@xmax,5)
##~ g1$miny <- round(e@ymin,5)
##~ g1$maxy <- round(e@ymax,5)
g1$minx <- e@xmin
g1$maxx <- e@xmax
g1$miny <- e@ymin
g1$maxy <- e@ymax
g1$columns <- raster::ncol(obj)
g1$rows <- raster::nrow(obj)
g1$crs <- raster::projection(obj)
if (is.na(g1$crs))
g1$crs <- ""
g1$resx <- with(g1,(maxx-minx)/columns)
g1$resy <- with(g1,(maxy-miny)/rows)
session_grid(g1)
if (all(is.factor(obj))) {
cname <- raster::levels(obj)[[1]]$code
if (is.null(cname))
cname <- raster::levels(obj)[[1]]$category
ct <- raster::colortable(obj)
if (!length(ct))
ct <- rep(NA,length(cname))
names(ct) <- cname
class(ct) <- "ursaColorTable"
}
else {
if (!inherits(obj,"RasterStack")) {
# at <- obj@data@attributes[[1]]#[,2,drop=FALSE]
pal <- raster::colortable(obj)
if (length(pal)) {
ct <- colorize(pal=pal,name=obj@data@attributes[[1]]$code)
ct[pal=="NA"] <- NA_character_
}
else {
ct <- character() #colorize(name=obj@data@attributes[[1]]$code)
}
# ct <- ursa_colortable(as.character(raster::colortable(obj)))
}
else {
ct <- lapply(methods::slot(obj,"layers"),function(x) {
ursa_colortable(as.character(raster::colortable(x)))
})
}
}
if (inherits(obj,"RasterStack")) {
res <- vector("list",dim(obj)[3])
for (i in seq_along(res)) {
res[[i]] <- ursa_new(value=raster::values(obj[[i]])
,bandname=names(obj[[i]])
,flip=FALSE,permute=FALSE)
ursa_colortable(res[[i]]) <- ct[[i]]
}
}
else if (inherits(obj,"RasterBrick")) {
res <- ursa_new(value=raster::values(obj),flip=FALSE,permute=FALSE)
ursa_colortable(res) <- ct
}
else if (inherits(obj,"RasterLayer")) {
if (length(ct))
res <- ursa_new(raster::values(obj),colortable=ct
,flip=FALSE,permute=FALSE)
else {
at <- obj@data@attributes#[[1]]#[,2,drop=FALSE]
if ((!length(at))||((length(at)==1)&&(!length(at[[1]]))))
res <- ursa_new(raster::values(obj),flip=FALSE,permute=FALSE)
else {
at <- at[[1]]
v <- raster::values(obj)
u <- ursa_new(v-1L,flip=FALSE,permute=FALSE)
res <- vector("list",ncol(at))
aname <- colnames(at)
for (i in seq_along(res)) {
tname <- names(table(at[,i]))
ind <- match(at[,i],tname)
obj <- ursa_new(ind[v]-1L,flip=FALSE,permute=FALSE
,bandname=aname[i])
res[[i]] <- reclass(obj,src=seq_along(tname)-1L,dst=tname)
}
# stop("R: as.ursa from raster with attributes")
}
}
}
return(res)
}
if ((is.list(obj))&&(!anyNA(match(c("filename","cols","rows","bands","driver"
,"geotransform","datatype","meta")
,names(obj))))) { ## from 'sf::gdal_read'
# .elapsedTime("A")
columns <- obj$cols[2]
rows <- obj$rows[2]
bands <- obj$bands[2]
if (length(ind <- grep("(^crs$|^wkt|wkt$)",names(obj))))
crs <- obj[[ind]]
# if (!is.na(crs))
# crs <- crs$proj4string
if (is.character(crs))
crs <- sf::st_crs(crs)$proj4string
else if (inherits(crs,"crs"))
crs <- crs$proj4string
if (is.na(crs))
crs <- ""
# patt <- "^Band_(\\d+)=\\t*(.+)$"
# bname <- grep(patt,obj$meta,value=TRUE)
# b1 <- .grep(patt,obj$meta,value=TRUE)
# bname <- .gsub(patt,"\\2",b1)
# bname[as.integer(.gsub(patt,"\\1",b1))] <- bname
resx <- obj$geotransform[2]
resy <- -obj$geotransform[6]
minx <- obj$geotransform[1]
maxy <- obj$geotransform[4]
maxx <- minx+columns*resx
miny <- maxy-rows*resy
if (miny>maxy) {
interim <- maxy
maxy <- miny
miny <- interim
}
##~ prm <- list(minx=minx,maxx=maxx,miny=miny,maxy=maxy,columns=columns,rows=rows
##~ ,crs=obj$crs$proj4string)
##~ g1 <- regrid(minx=minx,maxx=maxx,miny=miny,maxy=maxy,columns=columns,rows=rows
##~ ,crs=obj$crs$proj4string)
# .elapsedTime("I")
if (F)
g1 <- regrid(setbound=c(minx,miny,maxx,maxy),dim=c(rows,columns)
,crs=crs)
else {
g1 <- .grid.skeleton()
g1$columns <- as.integer(columns)
g1$rows <- as.integer(rows)
g1$minx <- minx
g1$maxx <- maxx
g1$miny <- miny
g1$maxy <- maxy
g1$resx <- with(g1,(maxx-minx)/columns)
g1$resy <- with(g1,(maxy-miny)/rows)
g1$crs <- crs
}
if (is.na(g1$crs))
g1$crs <- ""
# .elapsedTime("J")
session_grid(g1)
# hasData <- inherits("NULL",class(attr(obj,"data")))
hasData <- !inherits(attr(obj,"data"),"NULL")
# .elapsedTime("sf::gdal_read -- start")
if (!hasData) {
if (!requireNamespace("sf",quietly=.isPackageInUse()))
stop("Package 'sf' is required for this operation")
res <- as.ursa(attr(sf::gdal_read(obj$filename,read_data=TRUE),"data")
,flip=TRUE) ## RECURSIVE
}
else {
v <- attr(obj,"data")
attr(v,"units") <- NULL
dimv <- dim(v)
if (R.Version()$arch %in% c("i386","x86_64","dummy")[1:2]) {
# print("U")
if (devel2 <- TRUE) {
if (length(dimv)==2)
dimv <- c(dimv,band=1L)
dimv <- unname(c(prod(dimv[1:2]),dimv[3]))
dim(v) <- dimv
isClass <- length(obj$attribute_tables[[1]])>0
isColor <- length(obj$color_tables[[1]])>0
isCat <- (isClass)||(isColor)
if (isCat) {
if (isClass) {
ctName <- obj$attribute_tables[[1]][["category"]]
if (is.null(ctName))
isCat <- FALSE
}
}
if (isCat) {
if (isColor) {
ctCol <- obj$color_tables[[1]]
ct <- rgb(ctCol[,1],ctCol[,2],ctCol[,3],ctCol[,4],maxColorValue=255)
if (all(substr(ct,8,9)=="FF"))
ct <- substr(ct,1,7)
if (isClass)
if (length(ct)>length(ctName))
ct <- ct[seq_len(length(ctName))]
}
else
ct <- rep(NA,length(ctName))
if (isClass)
names(ct) <- ctName
# else
# names(ct) <-
class(ct) <- "ursaColorTable"
if (length(ind <- which(names(ct)==""))) {
if (length(ind <- ind[ind>1])>0) {
if (length(ctCol <- unique(substr(ct[ind],1,7)))==1) {
ct <- ct[-ind]
}
}
}
}
if ((isCat)||((T & !.lgrep("float",obj$datatype)))) {
# .elapsedTime("F")
# v <- as.integer(v)
# dim(v) <- dimv
# storage.mode(v) <- "integer"
mode(v) <- "integer"
# .elapsedTime("G")
}
# .elapsedTime("as.ursa -- before")
# res <- as.ursa(v) ## RECURSIVE
res <- ursa_new(v)
# .elapsedTime("as.ursa -- after")
if (isCat) {
ursa_colortable(res) <- ct
class(res$value) <- "ursaCategory"
}
bname <- obj$description
if (any(nchar(bname)>0)) {
names(res) <- gsub("\\t","",bname) ## patch for ENVI 'band name'
}
else {
patt <- "^Band_(\\d+)=(.+)$"
j <- grep(patt,obj$meta)
ind <- as.integer(gsub(patt,"\\1",obj$meta[j]))
bname <- gsub(patt,"\\2",obj$meta[j])
names(res)[ind] <- bname
}
}
else {
if (length(dimv)==2)
res <- ursa_new() ## or RECURSIVE as_ursa()
else
res <- ursa_new(nband=dimv[3])
res$value <- v
dima <- dim(res)
dim(res$value) <- c(prod(dima[1:2]),dima[3])
class(res$value) <- "ursaNumeric"
rm(v)
}
}
else {## quicker for 'x86_64'
# print("V")
res <- as.ursa(v,flip=TRUE) ## RECURSIVE!!!
}
rm(v)
}
# .elapsedTime("C")
# .elapsedTime("sf::gdal_read -- finish")
return(res)
}
if (inherits(obj,"stars")) {
d <- sapply(obj,function(x) length(dim(x)))
if (any(d>3))
stop("import 'stars' object: unhandled 4-dimensional (>3D) arrays")
md <- attr(obj,"dimensions")
cond1 <- identical(md$x$geotransform,md$y$geotransform)
cond2 <- identical(md$x$refsys,md$y$refsys)
if ((!cond1)||(!cond2))
stop("import 'stars' object: unhandled difference in 'x' and 'y' dimensions")
geot <- md$x$geotransform
columns <- md$x$to
rows <- md$y$to
if (!is.null(geot)) {
resx <- geot[2]
resy <- -geot[6]
minx <- geot[1]
maxy <- geot[4]
}
else {
resx <- md$x$delta
resy <- -md$y$delta
minx <- md$x$offset
maxy <- md$y$offset
}
maxx <- minx+columns*resx
miny <- maxy-rows*resy
##~ prm <- list(minx=minx,maxx=maxx,miny=miny,maxy=maxy,columns=columns,rows=rows
##~ ,crs=md$x$refsys)
##~ g1 <- regrid(minx=minx,maxx=maxx,miny=miny,maxy=maxy,columns=columns,rows=rows
##~ ,crs=md$x$refsys)
if (F) ## quick development
g1 <- regrid(setbound=c(minx,miny,maxx,maxy),dim=c(rows,columns)
,crs=md$x$refsys$proj4string)
else { ## quick implementation
g1 <- .grid.skeleton()
g1$columns <- as.integer(columns)
g1$rows <- as.integer(rows)
g1$minx <- minx
g1$maxx <- maxx
g1$miny <- miny
g1$maxy <- maxy
g1$resx <- with(g1,(maxx-minx)/columns)
g1$resy <- with(g1,(maxy-miny)/rows)
g1$crs <- if (is.character(md$x$refsys)) md$x$refsys else md$x$refsys$proj4string
}
session_grid(g1)
isHomo <- length(obj)==0 ##
# print(c(isHomo=isHomo))
if (isHomo) {
res <- as.ursa(obj[[1]],flip=TRUE)
}
else {
res <- vector("list",length(obj))
names(res) <- names(obj)
for (i in seq_along(res)) {
if (R.Version()$arch %in% c("i386","x86_64","zzz")[-3]) {
o <- obj[[i]]
# print("A")
dima <- dim(o)
if (length(dima)==2)
dima <- c(dima,band=1L)
if (devel2 <- TRUE) {
dim(o) <- c(prod(dima[1:2]),dima[3])
if (isCat <- is.factor(o)) {
ct <- attr(o,"colors")
names(ct) <- levels(o)
class(ct) <- "ursaColorTable"
o <- as.integer(o)-1L
}
res[[i]] <- as.ursa(o)
if (isCat) {
class(res[[i]]$value) <- "ursaCategory"
ursa_colortable(res[[i]]) <- ct
}
bname <- attr(obj[i],"dimensions")$band$values
if (!is.null(bname))
names(res[[i]]) <- bname
rm(o)
}
else {
a <- ursa(nband=dima[3])
a$value <- o
dim(a$value) <- c(prod(dima[1:2]),dima[3])
class(a$value) <- "ursaNumeric"
res[[i]] <- a
rm(a)
}
}
else { ## faster for 'x86_64' // 20210203 -- slower for any
# print("B")
res[[i]] <- as.ursa(obj[[i]],flip=TRUE) ## RECURSIVE!!!
}
}
}
if (length(obj)==1)
return(res[[1]])
return(res)
}
if (inherits(obj,"SpatRaster")) { ## package `terra`
if (devel <- FALSE) {
# a1 <- obj@ptr$getCategories()
# a1 <- obj@ptr$getCatIndex()
##~ ctname <- terra::levels(obj)
##~ str(ctname)
##~ ct <- terra::coltab(obj)
##~ str(ct)
##~ a1 <- obj@ptr$getColors()
##~ str(a1)
##~ print(a1)
##~ str(a1[[1]]$finalize())
##~ q()
}
# bbox <- obj@ptr$extent$vector[c(1,3,2,4)]
# res <- obj@ptr$res
# crs <- obj@ptr$get_crs("proj4")
# aname <- obj@ptr$names
bbox <- as.vector(terra::ext(obj))[c(1,3,2,4)]
res <- terra::res(obj)
crs <- terra::crs(obj,proj=TRUE)
# sn <- methods::slotNames(obj)
# aname <- methods::slot(obj,sn)$names
aname <- names(obj) ## wrong, TODO
g1 <- regrid(bbox=bbox,res=res,crs=crs)
if (identical(bbox,c(0,0,1,1)))
g1 <- regrid(bbox=c(0,0,rev(dim(g1))),res=1,crs=crs)
# g0 <- getOption("ursaSessionGrid")
# session_grid(g1)
if (approved <- TRUE) {
opW <- options(warn=-1)
res <- ursa(obj[]) ## as.matrix()
options(opW)
}
else {
.elapsedTime("rast -- 1")
o <- obj[]
# o <- as.matrix(obj)
# o <- as.array(obj)
.elapsedTime("rast -- 2")
res <- ursa(o)
.elapsedTime("rast -- 3")
}
names(res) <- aname
return(res)
}
if (is.list(obj)) {
if ((length(obj$x)==length(obj$z))&&(length(obj$y)==length(obj$z))) {
return(allocate(obj,...))
}
g <- .grid.skeleton()
g$resx <- mean(diff(obj$x))
g$resy <- mean(diff(obj$y))
g$minx <- min(obj$x)-g$resx/2
g$miny <- min(obj$y)-g$resy/2
g$maxx <- max(obj$x)+g$resx/2
g$maxy <- max(obj$y)+g$resy/2
g$columns <- with(g,(maxx-minx)/resx)
g$rows <- with(g,(maxy-miny)/resy)
tolerance <- 1e-11
if ((!.is.integer(g$columns,tolerance))||(!.is.integer(g$rows,tolerance)))
stop(paste("Unable to calculate integer dim size."
,"Try to change 'tolerance'",paste0("(",tolerance,")")))
g$columns <- as.integer(round(g$columns))
g$rows <- as.integer(round(g$rows))
p <- attr(obj,"crs")
if ((is.character(p))&&(nchar(p)))
g$crs <- p
g2 <- getOption("ursaSessionGrid")
session_grid(g)
arglist <- list(...)
ind <- .grep("^reset(Grid)*",names(arglist))
if ((length(ind)==1)&&(is.logical(arglist[[ind]]))&&(arglist[[ind]]))
resetGrid <- TRUE
else
resetGrid <- FALSE
# res <- ursa_new(value=obj$z[,rev(seq(ncol(obj$z)))],bandname="z")
res <- ursa_new(value=obj$z,bandname="z",flip=FALSE,permute=FALSE)
ursa_grid(res) <- g
if ((.is.grid(g2))&&(resetGrid))
session_grid(g2)
else
session_grid(g)
return(res)
}
if (inherits(obj,"ggmap")) {
B <- 6378137*pi
.epsg3857 <- paste("+proj=merc +a=6378137 +b=6378137"
,"+lat_ts=0.0 +lon_0=0.0"
,"+x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null"
,"+wktext +no_defs")
ll <- matrix(as.numeric(attr(obj,"bb")),ncol=2,byrow=TRUE)
bbox <- .project(list(x=ll[,2],y=ll[,1]),.epsg3857)
# bbox <- c(bbox$x[1],bbox$y[1],bbox$x[2],bbox$y[2])
if (is.list(bbox))
bbox <- with(bbox,c(x[1],y[1],x[2],y[2]))
else
bbox <- c(bbox)[c(1,3,2,4)]
g1 <- .grid.skeleton()
g1$columns <- dim(obj)[2]
g1$rows <- dim(obj)[1]
# str(obj)
if (ll[2,2]>180)
bbox[3] <-bbox[3]+2*B
if (ll[1,2]<(-180))
bbox[1] <-bbox[1]-2*B
# print(bbox)
if (bbox[1]>bbox[3]) {
if ((ll[1,2]<0)&&(bbox[1]>0))
bbox[1] <- bbox[1]-2*B
if ((ll[2,2]>0)&&(bbox[3]<0))
bbox[3] <- bbox[3]+2*B
# else
# print(bbox)
}
g1$minx <- bbox[1]
g1$miny <- bbox[2]
g1$maxx <- bbox[3]
g1$maxy <- bbox[4]
# print(ll)
if (FALSE) {
if (g1$maxx<g1$minx) {
if ((g1$minx>0)&&(g1$maxx<0)) {
if ((ll[1,2]<(-180))&&(ll[1,2]<(-180)))
g1$minx <- g1$minx-2*B
g1$maxx <- g1$maxx+2*B
}
else {
print(g1)
stop("AS:1")
g1$maxx <- 2*B+g1$maxx
}
}
}
g1$crs <- .epsg3857
g1$resx <- with(g1,(maxx-minx)/columns)
g1$resy <- with(g1,(maxy-miny)/rows)
stopifnot(with(g1,abs((resx-resy)/(resx+resy)))<1e-3)
session_grid(g1)
a1 <- factor(obj)
v1 <- levels(a1)
# names(v1) <- seq(length(v1))-1L
class(v1) <- "ursaColorTable"
a1 <- as.integer(a1)-1
dim(a1) <- rev(dim(obj))
res <- ursa_new(value=a1[,rev(seq(dim(a1)[2]))],flip=FALSE,permute=FALSE)
res$colortable <- v1
class(res$value) <- "ursaCategory"
return(res)
}
if (inherits(obj,"cimg")) { ## require(imager)
dima <- dim(obj)
if (dima[3]==1) {
res <- ursa_new(value=obj[,rev(seq(dima[2])),1,],flip=FALSE,permute=FALSE)
return(res)
}
if (dima[4]!=1) {
res <- ursa_new(value=obj[,rev(seq(dima[2])),,1],flip=FALSE,permute=FALSE)
return(res)
}
}
ind <- inherits(obj,c("bitmap","rgba"),which=TRUE) ## package 'magick'
ind <- ind[ind>0]
if (length(ind)>=2) {
res <- ursa_new(as.integer(obj),flip=TRUE,permute=TRUE)
return(res)
}
# isMatrix <- is.matrix
# if ((is.matrix(obj))||(is.array(obj)))
isArray <- !is.null(dim(obj)) ## 20170327 replaced 'isArray <- !is.null(dim)'
if ((!isArray)&&(is.numeric(obj))) {
# print("NOT-ARRAY")
if (!length(obj)) {
return(session_grid())
}
res <- ursa_new(obj,...)
return(res)
}
if (is.array(obj)) {
arglist <- list(...)
bname <- NULL
if (!is.null(b1 <- attr(obj,"grid"))) {
g1 <- .grid.skeleton()
aname <- names(b1)
indx <- .grep("^(x$|lon)",aname)
indy <- .grep("^(y$|lat)",aname)
proj4 <- .grep("(crs|proj4)",aname)
aname <- .grep("(crs|proj4)",aname,value=TRUE,invert=TRUE)
indz <- which(is.na(match(seq_along(aname),c(indx,indy))))
if ((length(indx))&&(length(indy))) {
x <- b1[[indx]]
y <- b1[[indy]]
g1$resx <- mean(unique(diff(x)))
g1$resy <- mean(unique(diff(y)))
g1$minx <- min(x)-g1$resx/2
g1$maxx <- max(x)+g1$resx/2
g1$miny <- min(y)-g1$resy/2
g1$maxy <- max(y)+g1$resy/2
g1$columns <- length(x)
g1$rows <- length(y)
if ((length(proj4))&&(nchar(b1[[proj4]]))) {
g1$crs <- p
}
else if (.lgrep("(lon|lat)",aname)==2)
g1$crs <- "+proj=longlat +datum=WGS84 +no_defs"
session_grid(g1)
}
if (length(indz)==1)
bname <- as.character(b1[[indz]])
}
res <- ursa_new(value=obj,bandname=bname,...)
return(res)
}
if (is.character(obj)) {
if ((FALSE)&&(envi_exists(obj))) ## FALSE to keep alternative to read ENVI using GDAL
return(read_envi(obj,...))
if ((!FALSE)&&(envi_exists(obj))) {
return(read_envi(obj,...))
}
if (file.exists(obj))
return(read_gdal(obj,...))
if (ursa_exists(obj))
return(read_gdal(obj,...))
if (isURL <- .lgrep("^(http://|https://|ftp://|file:///)",obj)>0) {
arglist <- list(...)
fname <- tempfile()
# download.file(obj,fname,...)
ind <- .grep("(method|cache|extra|quiet)",names(arglist)) ## -- "|mode|"
args2 <- c(url=obj,mode="wb",arglist[ind])
# do.call("download.file",args2)
fname <- do.call(".ursaCacheDownload",args2)
return(read_gdal(fname,...))
}
}
ursa_new(obj,...)
# str(obj)
# print(class(obj))
# stop("Unsupportes type of source object")
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/ursa_as.R
|
'band_blank' <- function(obj,ref=c("any","0","NA"),verbose=FALSE)
{
if (!is.ursa(obj))
return(NULL)
arglist <- eval(as.list(args("band_blank"))$ref)
ref <- match.arg(as.character(ref),arglist)
# ref <- match.arg(as.character(ref))
z <- obj$con$posZ
nb <- if (!is.na(z[1])) length(z) else obj$dim[2]
res <- rep(FALSE,nb)
if (is.matrix(obj$value))
{
for (i in seq_along(res)) {
r <- unique(obj$value[,i])
res[i] <- switch(ref
,'0'=(length(r)==1)&&(r==0)
,'NA'=(length(r)==1)&&(is.na(r))
,(length(r)==1)&&(r==0 | is.na(r))
)
}
}
else
{
cb <- chunk_band(obj)
if (pr <- verbose & length(cb)>1)
pb <- ursaProgressBar(min=0,max=length(cb),tail=TRUE)
for (i in cb) {
res[i] <- apply(obj[i]$value,2,function(z) {#(all(is.na(z)))||(all(z==0)))
r <- unique(z)
switch(ref
,'0'=(length(r)==1)&&(r==0)
,'NA'=(length(r)==1)&&(is.na(r))
,(length(r)==1)&&(r==0 | is.na(r))
)
})
if (pr)
setUrsaProgressBar(pb)
}
if (pr)
close(pb)
}
res
}
'ursa_blank' <- function(obj,ref) {
if (!is.ursa(obj))
return(NULL)
if (missing(ref))
ref <- "any"
all(band_blank(obj,ref))
}
'.which.blank' <- function(obj,ref) if (is.ursa(obj)) which(band_blank(obj,ref)) else NULL
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/ursa_blank.R
|
'ursa_cache' <- function() NULL
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/ursa_cache.R
|
# 'subset.ursaRaster' <- function(...) .syn('ursa_crop',0,...)
#'subset.ursaRaster' <- function(x,...) ursa_crop(x,...)
'ursa_crop' <- function(obj,condition,border=0,expand=1,resetGrid=TRUE
,verbose=FALSE)
{
# 20171111 ++ 'discolor(cond)'
border <- as.integer(round(rep(border,length=4)))
expand <- rep(expand,length=4)
if (is.null(obj$value))
return(NULL)
if (missing(condition))
a <- as.data.frame(discolor(obj))
else {
if (FALSE) ## longtime
a <- as.data.frame(obj[condition])
else {
a <- as.data.frame(discolor(condition))
}
}
if (!nrow(a)) {
if (verbose) {
opW <- options(warn=0)
warning("Crop cannot be applied due to blank image. Return full spatial domain.")
options(opW)
}
return(obj)
}
g1 <- g2 <- obj$grid
g1$minx <- min(a$x)-g1$resx/2-border[2]*g1$resx
g1$miny <- min(a$y)-g1$resy/2-border[1]*g1$resy
g1$maxx <- max(a$x)+g1$resx/2+border[4]*g1$resx
g1$maxy <- max(a$y)+g1$resy/2+border[3]*g1$resy
dx <- g1$maxx-g1$minx
dy <- g1$maxy-g1$miny
if (T)
dx <- dy <- sqrt(dx*dy)
g1$maxx <- g1$maxx+(expand[4]-1)*dx
g1$minx <- g1$minx-(expand[2]-1)*dx
g1$miny <- g1$miny-(expand[1]-1)*dy
g1$maxy <- g1$maxy+(expand[3]-1)*dy
g1$columns <- as.integer(.round(with(g1,(maxx-minx)/resx)))
g1$rows <- as.integer(.round(with(g1,(maxy-miny)/resy)))
regrid(obj,g1,resetGrid=resetGrid,resample=0,verbose=verbose)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/ursa_crop.R
|
'ursa_dummy' <- function(nband=3L,minvalue=0,maxvalue=255,mul=1,elements=8L
,bandname=NULL,nodata=TRUE,resetGrid=FALSE) {
#
if (resetGrid)
session_grid(NULL)
if (mul!=1)
session_grid(regrid(session_grid(),mul=mul))
g1 <- session_grid()
ratio <- max(with(g1,c(columns,rows)/(elements-0.5)))
ratio[ratio<1] <- 1
g2 <- session_grid(regrid(g1,mul=1/ratio))
if (is.character(bandname))
nband <- length(bandname)
d <- with(g2,c(columns,rows,nband))
b <- array(runif(prod(d),min=minvalue,max=maxvalue),dim=d)
b <- as.ursa(b,flip=FALSE,permute=FALSE)
if (is.character(bandname))
bandname(b) <- bandname
else {
lT <- Sys.getlocale("LC_TIME")
Sys.setlocale("LC_TIME","C") # "English_United States.1252"
bandname(b) <- format(Sys.time()+(seq(nband)-1)*24*60*60,"%A %d")
Sys.setlocale("LC_TIME",lT)
}
if (ratio>1) {
repeat({
b <- regrid(b,mul=2,resample=1)
g3 <- ursa_grid(b)
if ((g3$columns>g1$columns)||(g3$rows>g1$rows))
break
})
b <- regrid(b,g1,resample=1)
}
.gc()
if (is.numeric(nodata))
ursa_nodata(b) <- nodata
else if ((is.na(nodata))||((is.logical(nodata))&&(!nodata)))
ursa_nodata(b) <- NA
b
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/ursa_dummy.R
|
#'ursaGrid' <- function(...) .syn('ursa_grid',0,...)
#'ursaGrid<-' <- function(...) .syn('ursa_grid<-',0,...)
'ursa_grid' <- function(obj=NULL) {
if (is.null(obj))
return(.grid.skeleton())
if (.is.ursa_stack(obj))
obj <- obj[[1]]
if (is.ursa(obj))
return(obj$grid)
if (is.ursa(obj,"grid"))
return(obj)
if ((is.character(obj))&&(envi_exists(obj,exact=TRUE))) {
g1 <- getOption("ursaSessionGrid")
a <- open_envi(obj,resetGrid=TRUE,decompress=FALSE)
res <- a$grid
close(a)
if (is.null(g1))
session_grid(res)
else
session_grid(g1)
return(res)
}
if ((is.character(obj))&&(file.exists(obj))&&
(.lgrep("\\.(tif|tiff|img|dat|png|jpeg|jpg|bmp)$",basename(obj)))) {
g1 <- getOption("ursaSessionGrid")
session_grid(NULL)
a <- try(open_gdal(obj),silent=TRUE)
if (inherits(a,"try-error")) {
session_grid(g1)
return(NULL)
}
res <- a$grid
close(a)
if (is.null(g1))
session_grid(res)
else
session_grid(g1)
return(res)
}
if ((is.numeric(obj))&&(length(obj)==2)) {
ref <- round(obj)
g1 <- .grid.skeleton()
g1$columns <- as.integer(ref[2])
g1$rows <- as.integer(obj[1])
g1$minx <- 0
g1$miny <- 0
g1$maxx <- obj[2]
g1$maxy <- obj[1]
g1$resx <- with(g1,(maxx-minx)/columns)
g1$resy <- with(g1,(maxy-miny)/rows)
if (TRUE) {
retina <- getOption("ursaRetina")
if ((is.numeric(retina))&&(retina>1))
g1$retina <- retina
}
return(g1)
}
NULL
}
'ursa_grid<-' <- function(obj,value) {
if (!is.ursa(obj))
return(obj)
if (!.is.grid(value))
return(obj)
obj$grid <- value
if ((inherits(obj$con$handle,"connection"))&&(is.null(dim(obj$value))))
.write.hdr(obj,clear=FALSE)
obj
}
'ursa_nrow' <- 'ursa_lines' <- 'ursa_rows' <- function(obj) ursa_grid(obj)$rows
'ursa_ncol' <- 'ursa_samples' <- 'ursa_columns' <- function(obj) ursa_grid(obj)$columns
'ursa_extent' <- 'ursa_bbox' <- function(obj) {
res <- with(ursa_grid(obj),c(xmin=minx,ymin=miny,xmax=maxx,ymax=maxy))
attr(res,"crs") <- ursa_crs(obj)
res
}
'consistent_grid' <- function(obj,ref,expand=1,border=rep(0,4),verbose=FALSE) {
# verbose <- !.isPackageInUse()
if (!missing(obj)) {
if (is_ursa(obj))
obj <- ursa_grid(obj)
else if (is_spatial(obj))
obj <- spatial_grid(obj)
}
if (!missing(ref)) {
if (is_ursa(ref))
ref <- ursa_grid(ref)
else if (is_spatial(ref))
ref <- spatial_grid(ref)
else if ((is.numeric(ref))&&(length(ref)==2)&&(all(ref>0))) {
d0 <- round(ref)
ref <- .grid.skeleton()
ref$minx <- 0
ref$maxx <- d0[2]
ref$columns <- as.integer(d0[2])
ref$miny <- 0
ref$maxy <- d0[1]
ref$rows <- as.integer(d0[1])
ref$resx <- ref$resy <- 1
}
}
g0 <- getOption("ursaPngComposeGrid")
isPlot <- isFALSE(is.null(g0))
if (!isPlot)
g0 <- getOption("ursaSessionGrid")
# if (identical(obj,g0))
if (missing(ref)) {
if ((FALSE)&&(!missing(obj))&&(!identical(obj,g0))) {
ref <- obj
obj <- g0
}
else
ref <- g0
}
if (missing(obj))
obj <- g0
if (identical(obj,ref))
return(obj)
isWeb <- ((.lgrep("\\+proj=merc",session_crs()))&&
(!is.na(.is.near(ursa(obj,"cellsize"),2*6378137*pi/(2^(1:21+8))))))
if (is_spatial(ref))
ref <- spatial_grid(ref)
if (is_ursa(ursa_grid(ref),"grid"))
d2 <- unname(ursa(ref,"dim"))
else if ((is.numeric(ref))&&(length(ref)==2)) {
d2 <- unname(ref)
if (!is.na(g0$retina))
d2 <- g0$retina*d2
}
if (missing(d2))
stop("Unable to detect reference grid. Check 'ref' argument)")
d1 <- unname(ursa(obj,"dim"))
d <- min(d2/d1)
d.orig <- d
if (preD <- T & isWeb)
d <- ifelse(d>1,d/expand,d*expand)
d.web <- floor(log(d)/log(2)) ## trunc(use) round(dev) [trunc==floor for positive]
# d.web <- trunc(log(d)/log(2)) ## trunc(use) round(dev)
d.less <- 2^(d.web-1+1*1)
d.more <- 2^(d.web+0+1*1)
if (verbose)
print(c(d=d,d.orig=d.orig,d.more=d.more,d.less=d.less,d.web=2^d.web
,d.raw=2^(log(d)/log(2)),expand=expand),digits=3)
if (d>1) {
if (!preD)
d <- d/expand
# cat("---------\n")
# str(obj)
# g2 <- regrid(obj,expand=d) ## ifelse(isWeb,2^(trunc(log(d)/log(2))+1),d)
g2 <- regrid(obj,mul=ifelse(isWeb,d.less,d)) ## d.more d.less d.web
# str(g2)
# cat("---------\n")
# g2$retina <- NA
}
else {
if (!preD)
d <- d/expand
# g2 <- regrid(obj,mul=ifelse(isWeb,d.more,d)) ## d.more d.less d.web
g2 <- regrid(obj,mul=ifelse(isWeb,d.less,d)) ## d.more d.less d.web
# g2$retina <- NA
}
# cat("--------------\n")
# str(g2)
# cat("--------------\n")
d3 <- c(ursa(g2,"nrow"),ursa(g2,"ncol"))
if (verbose) {
print(c(web=isWeb))
print(c('d1:'=d1))
print(c('d2:'=d2))
print(c('d2/d1:'=d2/d1))
print(c(d=d,d.less=d.less,d.web=2^d.web,d.more=d.more))
print(c('d3:'=d3))
}
d4 <- d2-d3
dx <- rep(floor(d4[1]/2),2)
dy <- rep(floor(d4[2]/2),2)
if (d4[1] %% 2 ==1)
dx <- dx+c(0,1)
if (d4[2] %% 2 ==1)
dy <- dy+c(0,1)
b <- c(dx[1],dy[1],dx[2],dy[2])
g3 <- regrid(g2,border=b)
if (any(border!=0)) {
g3 <- consistent_grid(regrid(g3,border=border),ref=g3) ## RECURSIVE
}
##~ d4 <- c(ursa(g3,"nrow"),ursa(g3,"ncol"))
##~ print(d4)
if (isPlot) {
# options(ursaPngPanelGrid=g3)
session_grid(g3)
}
g3
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/ursa_grid.R
|
'.metadata' <- function(...) .syn('ursa_info',0,...) ## raster::metadata
# 'ursa_info' <- function(obj,detail=NA,digits=3,...) {
'ursa_info' <- function(obj,detail=NA,...) {
toClose <- FALSE
isList <- .is.ursa_stack(obj)
if (isList) { ## recursive!!!
rel <- as.list(match.call()) ## try mget(names(match.call())[-1])
fun <- as.character(rel[1])
res <- vector("list",length(obj))
# oname <- names(obj)
for (i in seq_along(obj)) {
rel[["obj"]] <- quote(obj[[i]])
img <- do.call(fun,rel[-1])
# if ((!is.null(oname))&&(nband(img)==1))
# bandname(img) <- oname[i]
res[[i]] <- img
rm(img)
}
# names(res) <- oname
return(res)
}
if (is.character(obj)) {
list1 <- envi_list(obj)
if (length(list1)==1)
obj <- open_envi(list1)
else
obj <- open_gdal(list1)
toClose <- TRUE
}
if (!is.ursa(obj))
return(NULL)
res <- obj$grid
if (!length(res$seqx))
res$seqx <- NULL
if (!length(res$seqy))
res$seqy <- NULL
if (!is.na(obj$con$nodata))
res$nodata <- obj$con$nodata
if (!is.na(obj$con$datatype))
res$datatype <- obj$con$datatype
if (!is.na(obj$con$interleave))
res$interleave <- obj$con$interleave
res$mode <- c(obj$con$mode,storage.mode(obj$value))
res$bandname <- obj$name
if (!is.na(obj$con$posZ[1]))
res$bandname <- res$bandname[obj$con$posZ]
if (.is.colortable(obj$colortable))
res$colortable <- obj$colortable
if (is.na(res$retina))
res$retina <- NULL
class(res) <- "ursaMetadata"
if (toClose)
close(obj)
str(res,...)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/ursa_info.R
|
'ursa_new' <- function(...)
{
arglist <- list(...)
value <- .getPrm(arglist,name="(^$|^value)"
,class=list("numeric","matrix","array")
,coerce=FALSE,default=NA,verbose=FALSE)
nd <- length(dim(value))
isMatrix <- if (nd==2) TRUE else FALSE
isArray <- if (nd==3) TRUE else FALSE
bands <- .getPrm(arglist,name="(len(gth)*|nband|nlayer|bands|layers)"
,default=1L)
nodata <- .getPrm(arglist,name="(bg|background|nodata|ignore(value)*)"
,default=NA_real_)
bname <- .getPrm(arglist,name="(band|layer)*name(s*)",class="character"
,default=NULL)
if (length(bname))
bands <- length(bname)
datatype <- .getPrm(arglist,name="datatype",default=NA_integer_)
colorTable <- .getPrm(arglist,name="(colortable|category)"
,class="ursaColorTable",default=NULL)
permute <- .getPrm(arglist,name="perm(ute)*",default=FALSE) ## -- 20170720 TRUE
flip <- .getPrm(arglist,name="flip",default=FALSE) ## -- 20170720 TRUE
crs <- .getPrm(arglist,name="ref",class=list("ursaGrid","character")
,default=NULL)
verbose <- .getPrm(arglist,name="verbose",default=FALSE)
if (verbose) {
str(list(value=value,iaArray=isArray,isMarix=isMatrix
,nband=bands,bandname=bname,datatype=datatype
,colorTable=colorTable,permute=permute,flip=flip))
}
grid <- getOption("ursaSessionGrid") ## grid <- session_grid()
if ((is.null(grid))||(!.is.grid(grid)))
{
if (.is.grid(crs))
session_grid(crs)
else if (is.character(crs))
session_grid(ursa_grid(crs))
}
result <- .raster.skeleton()
grid <- session_grid()
sp <- with(grid,columns*rows)
if (is.array(value)) ## # if ((is.null(grid))&&(is.array(value)))
{
dimb <- dima <- dim(value)
if (length(dima)==2) {
if ((TRUE)&&(dima[1]!=with(grid,columns*rows))) {## added 20160201
value <- value[,rev(seq(dima[2])),drop=FALSE]
}
if (permute) {
value <- t(value)
dima <- rev(dima)
}
dima <- c(dima,1L)
# dim(value) <- dima ## added 20170129
}
else if (length(dima)==3) {
if (permute) {
ind <- c(2,1,3)
value <- aperm(value,ind)
dima <- dim(value)
}
}
if (!((sp==dima[1])||(sp==dima[2]))) {
if ((grid$columns!=dima[1])||(grid$rows!=dima[2]))
{
grid <- .grid.skeleton()
grid$columns <- dima[1]
grid$rows <- dima[2]
grid$resx <- 1
grid$resy <- 1
grid$minx <- 0
grid$maxx <- as.numeric(dima[1])
grid$miny <- 0
grid$maxy <- as.numeric(dima[2])
grid$crs <- ""
session_grid(grid)
}
# str(grid)
}
if (flip) {
# dimb <- dim(value)
if (length(dimb)==2) {
value <- value[,rev(seq(dima[2])),drop=FALSE]
}
else if (length(dimb)==3)
value <- value[,rev(seq(dima[2])),,drop=FALSE]
}
}
result$grid <- grid
if ((is.matrix(value))&&((sp==dim(value)[1]))) {
result$value <- value
dimnames(result$value) <- NULL
result$dim <- dim(result$value)
bands <- result$dim[2]
if ((is.null(bname))&&(length(colnames(value))==bands))
bname <- colnames(value)
}
else if ((is.matrix(value))&&((sp==dim(value)[2]))) {
result$value <- t(value)
dimnames(result$value) <- NULL
result$dim <- dim(result$value)
bands <- result$dim[2]
if ((is.null(bname))&&(length(rownames(value))==bands))
bname <- rownames(value)
}
else if (is.array(value))
{
if (length(dim(value))==2) {
dim(value) <- c(prod(dim(value)),1L)
}
else {
value <- value[,rev(seq(dima[2])),,drop=FALSE] ## added 20160330
dim(value) <- c(prod(dim(value)[1:2]),dim(value)[3])
}
result$value <- value
result$dim <- dim(value) #with(result$grid,c(columns*rows,dim(value)[2]))
bands <- result$dim[2]
}
else if ((length(value)==1)&&(is.logical(value))&&(!is.na(value))&&(!value))
{
result$value <- as.numeric(NA)
result$dim <- with(result$grid,c(columns*rows,bands))
}
else
{
if (is.null(dim(value))) {
nb <- length(value)/with(result$grid,columns*rows)
if ((bands==1)&&((length(value)>1)&&(!.is.integer(nb)))) { ## 12 months
opW <- options(warn=1)
warning("How many bands do you mean? Please specify argument 'bands='.")
opW <- options(opW)
if (length(value)<12)
bands <- length(value)
}
if (.is.integer(nb))
bands <- as.integer(round(nb))
}
##~ if (is.null(dim(value))) {
##~ if ((bands==1)&&(length(value)<=12)) ## 12 months
##~ bands <- length(value)
##~ }
dim1 <- with(result$grid,c(rows,columns,bands))
##~ dim1[3] <- bands
# dim3 <- as.integer(c(prod(dim1[1:2]),dim1[3]))
dim3 <- c(dim1[1]*dim1[2],dim1[3])
if ((is.null(dim(value)))&&(length(value)==bands)) {
if ((bands==1)&&(length(value)==1)) {
result$value <- array(value,dim=dim3)
}
else
result$value <- array(rep(value,each=dim3[1]),dim=dim3)
}
else {
result$value <- array(value,dim=dim3)
}
result$dim <- dim3
}
# result$name <- sprintf(sprintf("%s%%0%dd","tmp"
# ,nchar(length(1:x$con$bands))),1:x$con$bands)
result$con <- .con.skeleton()
if (!is.na(nodata))
result$con$nodata <- nodata
if (is.numeric(datatype))
result$con$datatype <- as.integer(datatype)
else if (is.character(datatype)) {
result$con$datatype <- switch(var,byte=1L,integer=2L,real=4L,float=4L
,Byte=1L,UInt8=1L,Int8=11
,Int16=2L,UInt16=12,UInt32=13,Int32=3
,Float32=4L,Float64=5L
,NA_integer_)
}
##~ if ((is.null(bname))||(length(bname)!=result$dim[2]))
if (is.null(bname)) {
result$name <- sprintf(sprintf("%s%%0%dd"
,"Band ",nchar(bands)),seq_len(bands))
}
else {
bname <- rep(bname,length=bands)
result$name <- bname
}
if (!is.null(colorTable))
{
result$colortable <- colorTable
class(result$colortable) <- "ursaColorTable"
result$con$nodata <- length(colorTable)
class(result$value) <- "ursaCategory"
}
else {
ursa_colortable(result) <- character()
class(result$value) <- "ursaNumeric" ## not quick
# attr(result$value,"class") <- c(attr(result$value,"class"),"ursaNumeric")
# attr(result$value,"class") <- "ursaNumeric" ## not quick too
# print(class(result$value))
}
result
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/ursa_new.R
|
'ursa_proj4' <- function(obj) .syn('ursa_crs',0,obj)
'ursa_proj4<-' <- function(obj,keepGrid=FALSE,value) .syn('ursa_crs<-',0,obj,keepGrid,value)
'ursa_proj' <- function(obj) .syn('ursa_crs',0,obj)
'ursa_proj<-' <- function(obj,keepGrid=FALSE,value) .syn('ursa_crs<-',0,obj,keepGrid,value)
'ursa_crs' <- function(obj) {
if (is.ursa(obj,"stack"))
return(obj[[1]]$grid$crs)
if (is.ursa(obj)) {
return(obj$grid$crs)
}
if (.is.grid(obj))
return(obj$crs)
if ((is.character(obj))&&(nchar(obj))&&(envi_exists(obj,exact=TRUE))) {
g1 <- session_grid()
a <- open_envi(obj,resetGrid=TRUE)
res <- a$grid$crs
close(a)
session_grid(g1)
return(res)
}
if (is.character(obj)) {
# class(obj) <- c("character","ursaProjection")
return(obj)
}
NULL
}
'ursa_crs<-' <- function(obj,keepGrid=FALSE,value) {
if ((is.numeric(value))&&(.is.integer(value)))
value <- paste0("+init=epsg:",round(value))
else if (inherits(value,"CRS"))
value <- methods::slot(value,"projargs")
else if (!is.character(value))
{
warning("unable to detect projection")
return(obj)
}
if (!is.ursa(obj)) {
if (!.is.grid(obj))
return(NULL)
obj$crs <- ursa_crs(value)
return(obj)
}
obj$grid$crs <- ursa_crs(value)
if (!keepGrid)
session_grid(obj)
obj
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/ursa_proj.R
|
'whiteboxing' <- function(tool_name,...) {
if (is.character(tool_name))
prm <- c(tool_name,list(...))
else {
prm <- c(list(...),list(tool_name))
}
ind <- which(sapply(prm,function(x) (is.character(x))&&(!grepl(".+\\.tif$",x))))
if (length(ind)==1) {
tool_name <- prm[[ind]]
prm <- prm[-ind]
}
else {
stop("cannot extract 'tool_name'")
}
verbose <- .getPrm(prm,name="verbose",default=F)
wbt <- !.isPackageInUse() & .getPrm(prm,name="^wbt$",default=F)
if (!wbt) {
if (!requireNamespace("whitebox",quietly=.isPackageInUse()))
stop("Suggested package `whitebox` is required for this operation")
}
else {
if (!.require("whitebox",quietly=.isPackageInUse()))
stop("Suggested package `whitebox` is required for this operation")
}
# data("wbttools",package="whitebox")
# if (is.na(indT <- match(tool_name,wbttools$tool_name))) {
# if (is.na(indF <- match(tool_name,wbttools$function_name))) {
# return(NULL)
# }
# tool_name <- wbttools$tool_name[indF]
# }
if (grepl("\\w_\\w",tool_name)) {
if (!grepl("^wbt_\\w",tool_name))
tool_name <- paste0("wbt_",tool_name)
}
tool_name <- gsub("_(\\w)","\\U\\1",gsub("(^wbt)(_.+)$","\\2",tool_name),perl=TRUE)
if (wbt)
prm <- prm[grep("^wbt$",names(prm),invert=TRUE)]
pname <- names(prm)
if (is.null(pname))
pname <- rep("",length(prm))
if (!nchar(pname[1]))
pname[1] <- "input"
for (i in seq_along(prm)) {
if (is_ursa(prm[[i]])) {
fname <- tempfile(fileext=".tif")
write_gdal(prm[[i]],fname,options="COMPRESS=LZW")
prm[[i]] <- fname
}
if (!nchar(pname[i])) {
p <- prm[[i]]
if (!is.null(names(p))) {
pname[i] <- names(p)
prm[[i]] <- unname(p)
}
else {
sp <- strsplit(p,split="=")[[1]]
if (length(sp)==2) {
prm[[i]] <- sp[2]
pname[i] <- sp[1]
}
}
}
}
pname <- gsub("^--","",pname)
names(prm) <- pname
if (isUrsa <- !length(ind <- grep("^output$",names(prm)))) {
prm[["output"]] <- tempfile(fileext=".tif")
}
if (is.logical(prm[["output"]])) {
isUrsa <- !isTRUE(prm[["output"]])
prm[["output"]] <- tempfile(fileext=".tif")
}
ret <- prm[["output"]]
if (!wbt) {
names(prm) <- paste0("--",names(prm))
prm <- paste0(names(prm),"=",sapply(prm,\(x) x))
prm <- gsub("=TRUE","",prm)
prm <- gsub("--.+=FALSE","",prm)
prm <- paste(prm[nchar(prm)>0],collapse=" ")
if (verbose)
cat(paste0(tool_name,": ",prm,"\n"))
whitebox::wbt_run_tool(tool_name=tool_name,args=prm)
}
else {
if (verbose)
str(prm)
a <- do.call("wbt",c(tool_name,prm))
attr(ret,"wbt") <- a
}
if (!isUrsa)
return(ret)
ret <- read_gdal(ret)
names(ret) <- tool_name
ret
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/whiteboxing.R
|
'widgetize' <- function(obj,...) {
# if (!requireNamespace("widgetframe",quietly=.isPackageInUse()))
# return(browse(obj))
# widgetframe::frameWidget(obj)
if (is.null(obj))
return(invisible(obj))
if (!.isKnitr()) {
if (is.character(obj)) {
return(cat(obj,sep="\n"))
}
# cat("not knit","a\n")
return(browse(obj,...))
}
# if (.isRemark())
# return(browse(obj,...))
if (inherits(obj,c("datatables")))
return(browse(obj,...))
if (inherits(obj,c("htmlwidget"))) {
# cat("htmlwidget 1","\n")
# cat("knitr:",c(knitr="knitr" %in% loadedNamespaces()),"\n")
# cat("asis:",knitr::opts_current$get("results")=="asis","\n")
# cat("class:",class(obj),"\n")
if ("knitr" %in% loadedNamespaces()) {
if (!isTRUE(knitr::opts_chunk$get("customized_rendering")))
return(obj)
if (isTRUE(knitr::opts_current$get("results")=="asis")) {
# cat("asis 2","\n")
return(browse(obj,...))
}
}
}
if (!inherits(obj,c("htmlwidget","knitr_kable"))) {
# cat("htmlwidget 3","\n")
return(browse(obj,...))
}
# cat("obj 4","\n")
obj
}
'browse' <- '.open' <- function(...) {
arglist <- list(...)
if (length(ind <- grep("^ref$",ignore.case=FALSE,names(arglist)))) {
ind2 <- tail(ind,1)
reflab <- arglist[[ind2]]
arglist[ind2] <- NULL
}
else
reflab <- NULL
if (length(ind <- grep("^dpi$",ignore.case=FALSE,names(arglist)))) {
ind2 <- tail(ind,1)
dpi <- arglist[[ind2]]
arglist[ind2] <- NULL
}
else
dpi <- NULL
if (length(ind <- grep("^height$",ignore.case=FALSE,names(arglist)))) {
ind2 <- tail(ind,1)
height <- arglist[[ind2]]
arglist[ind2] <- NULL
}
else
height <- NULL
if (length(ind <- grep("^width$",ignore.case=FALSE,names(arglist)))) {
ind2 <- tail(ind,1)
width <- arglist[[ind2]]
arglist[ind2] <- NULL
}
else
width <- NULL
if (length(ind <- grep("^output$",ignore.case=FALSE,names(arglist)))) {
ind2 <- tail(ind,1)
output <- arglist[[ind2]]
arglist[ind2] <- NULL
}
else
output <- NULL
if (length(ind <- grep("^link$",ignore.case=FALSE,names(arglist)))) {
ind2 <- tail(ind,1)
link <- arglist[[ind2]]
arglist[ind2] <- NULL
}
else
link <- FALSE
if (length(ind <- .grep("verb(ose)*",names(arglist)))) {
ind2 <- tail(ind,1)
verbose <- arglist[[ind2]]
arglist[ind2] <- NULL
}
else
verbose <- FALSE # !.isPackageInUse()
if (length(ind <- .grep("(fig\\.cap|caption)",names(arglist)))) {
ind2 <- tail(ind,1)
cap <- arglist[[ind2]]
arglist[ind2] <- NULL
}
else
cap <- NULL
cl <- lapply(arglist,class)
aname <- NULL
if ((length(cl)==1)&&(cl=="list")) {
aname <- names(arglist)
arglist <- arglist[[1]]
cl <- lapply(arglist,class)
# if (verbose)
# str(cl)
}
oname <- names(arglist)
if (sum(nchar(oname))==0) {
if ((!is.null(aname))&&(length(aname)==1)) {
oname <- rep("",length(arglist))
oname[length(oname)] <- aname
}
else
oname <- NULL
}
if ((is.null(oname))&&(!is.null(cap)))
oname <- cap
if (is.null(reflab))
reflab <- if (T) rep("",length(arglist))
else paste(sample(letters,4,replace=TRUE),collapse="")
if ((length(arglist)>1)&&(length(reflab)==1))
reflab <- paste0(reflab,seq_along(arglist))
if ((length(arglist)>1)&&(length(dpi)==1))
dpi <- rep(dpi,length(arglist))
if (all(nchar(reflab)>0))
reflab <- paste0(" ",reflab)
k <- 0L
# return(oname)
ret <- lapply(arglist,function(obj) {
k <<- k+1L
if (verbose)
print(k)
ret2 <- NULL
if (is.character(obj)) {
if (!file.exists(obj)) { ## e.g.,Rplots%02d.png
obj <- head(dir(path=dirname(obj)
,pattern=gsub("\\%(\\d+)*d","\\\\d+",obj)
,full.names=TRUE),1)
}
if (!length(obj))
return(ret2)
if (length(grep("\\.(png|gif)$",basename(obj))))
cmd <- c(paste0("```{r",reflab[k]
,", echo=F"
,if (!is.null(oname)) paste0(", fig.cap=",dQuote(oname[k]))
,"}")
,paste0("knitr::include_graphics(",dQuote(obj)
,if (!is.null(dpi)) paste0(",dpi=",dpi[k])
# ,",height=",dQuote(paste0(round(4.8*96,1),"px"))
,")")
,"```")
else
cmd <- NULL
if (!.isKnitr()) {
if ((verbose)&&(!is.null(cmd)))
cat(cmd,sep="\n")
ret2 <- browseURL(normalizePath(obj))
}
else {
cmd <- knitr::knit_child(text=cmd,quiet=TRUE)
cat(cmd,sep="\n")
ret2 <- invisible(NULL)
}
}
if (inherits(obj,"mapview"))
obj <- methods::slot(obj,"map")
# if (inherits(obj,"tmap")) {
# if (requireNamspace("tmap"))
# obj <- tmap::tmap_leaflet(obj)
# }
if (inherits(obj,c("tmap","htmlwidget"))) {
isUrsaCache <- !identical(normalizePath(.ursaCacheDir()),tempdir())
if (!isUrsaCache & is.null(output))
return(ret2)
cond2 <- requireNamespace("htmlwidgets",quietly=.isPackageInUse())
if (!cond2)
return(ret2)
ftemp <- tempfile(fileext=".rds")
o <- obj[grep("dependencies",names(obj),invert=TRUE)]
saveRDS(o,ftemp)
md5 <- tools::md5sum(ftemp)
file.remove(ftemp)
if (is.null(output)) {
if (!.isKnitr())
output <- file.path(.ursaCacheDir(),"knit")
else
output <- file.path(knitr::opts_chunk$get("fig.path"))
}
else {
# TODO 'if (length(grep("\\.html$",output)))...'
output <- normalizePath(output)
}
if (!dir.exists(output))
dir.create(output,recursive=TRUE)
if (!.isKnitr()) {
libdir <- file.path(output,"site_libs")
fname <- file.path(output,paste0("htmlwidget_",unname(md5),".html"))
}
else {
libdir <- file.path("libs")
fname <- file.path(output,paste0("widget_"
,knitr::opts_current$get("label")
,"_",unname(md5)
,".html"))
caption <- knitr::opts_current$get("fig.cap")
if ((is.null(oname))&&(!is.null(caption)))
oname <- caption
}
if (!file.exists(fname)) {
# obj <- htmlwidgets::prependContent(obj,htmltools::HTML("<style>iframe {border: 3px solid magenta;}</style>"))
if (requireNamespace("widgetframe",quietly=.isPackageInUse())) {
obj <- widgetframe::frameableWidget(obj)
}
if (!.isPackageInUse())
opW <- options(warn=1)
htmlwidgets::saveWidget(obj,file=fname,libdir=libdir
,selfcontained=FALSE
,knitrOptions=list(hello="World")
)
if (!.isPackageInUse())
options(opW)
}
if (T | !.isKnitr()) {
a <- readLines(fname,encoding="UTF-8")
a <- grep("application/json.+data-for=\\\"htmlwidget",a,value=TRUE)
id <- gsub("^.+visdat\\W+([0-9a-f]+)\\W+.+$","\\1",a)
if ((nchar(id)>4)&&(nchar(id)<36)) {
a <- gsub(id,"gggg",a)
a <- gsub("(^.+htmlwidget\\W+)([0-9a-f]+)(\\W+.+$)","\\1hhhhh\\3",a)
saveRDS(a,ftemp)
md5 <- unname(tools::md5sum(ftemp))
file.remove(ftemp)
ename <- fname
if (!.isKnitr())
fname <- file.path(dirname(fname),paste0("htmlwidget-",md5,".html"))
else
fname <- file.path(dirname(fname),paste0("widget_"
,knitr::opts_current$get("label")
,"_",unname(md5)
,".html"))
file.rename(ename,fname)
}
}
# oname <- "PUT YOUR CAPTION HERE"
fname <- gsub("\\\\","/",fname)
if ((T | !.isKnitr())&&(length(grep("^(/\\w|[A-Z\\:\\w])",fname))))
fname <- paste0("file:///",fname)
# cap <- paste0("<a href=",URLencode(fname),">",oname[k],"</a>")
if (link) {
cap <- paste0("^[🔗](",URLencode(fname),")^") ## []{style=\"opacity: 0.3\"}
# cap <- paste0("<span style=\"color: magenta;\">[🔗](",URLencode(fname),")</span>") ## []{style=\"opacity: 0.3\"}
}
else
cap <- ""
if ((!is.null(oname))&&(nchar(oname[k])>0))
cap <- paste(oname[k],cap)
iframe <- paste0("knitr::include_url(",dQuote(fname))
if (!is.null(height)) {
if (is.character(height))
iframe <- paste0(iframe,",height=",dQuote(height))
if (is.numeric(height))
iframe <- paste0(iframe,",height=",dQuote(height)) ## dQuote(height,c("","px")[1])
}
iframe <- paste0(iframe,")")
cmd <- c(paste0("```{r",reflab[k]
,", echo=F"
# ,if (!is.null(oname)) paste0(", fig.cap=",dQuote(oname[k]))
,if (T | !nchar(cap)) paste0(", fig.cap=",dQuote(cap))
,paste0(", out.extra=",dQuote("class=\\\'ursa-widgetize\\\'"))
,"}")
##~ ,paste0("knitr::include_url(",dQuote(fname)
##~ #,",height=",dQuote(paste0(round(4.8*96,1),"px"))
##~ ,")")
,iframe
,"```"
# ,""
# ,paste0("[link to widget](",fname,"){style=\"font-size: 75%;\"}")
# ,paste0("[🔗](",URLencode(fname),"){style=\"font-size: 75%; opacity: 0.6;\" class=\"noprint\"}")
)
# print(iframe)
# print(cmd)
# str(knitr::opts_current$get())
if (!.isKnitr()) {
if (verbose)
cat(cmd,sep="\n")
ret2 <- browseURL(fname)
}
else {
if (T) {
if (.isRemark()) {
if (is.null(height))
height <- knitr::opts_current$get("out.height")
if (is.null(width))
width <- "100%"
suffix <- paste0(" style=\"height:",height,"px; width=",width,"\"")
}
else
suffix <- ""
cmd <- c(paste0("<div class=\"framed\"",suffix,">"),cmd,"</div>")
}
# writeLines(cmd,"c:/tmp/cap.Rmd")
# knitr::asis_output(cmd)
if (!.isRemark()) {
cmd <- knitr::knit_child(text=cmd,quiet=TRUE)
}
else {
cmd <- paste0("<div class=\"figure\">\n"
,"<div class=\"framed\"",suffix,">\n"
,"<iframe src=",dQuote(fname)
,ifelse(is.null(width),"",paste0(" width=",dQuote(width)))
,ifelse(is.null(height),"",paste0(" height=",dQuote(height)))
," class=",dQuote("ursa-widgetize"),">"
,"</iframe>\n"
,"</div>\n"
,if (nchar(cap))
paste0("<p class=",dQuote("caption"),">"
,cap," </p>\n")
,"</div>")
}
# print(cmd)
cat(cmd,sep="\n")
ret2 <- invisible(NULL)
}
##~ inventory <- .ursaCacheInventory()
##~ if (file.exists(inventory)) {
##~ was <- utils::read.table(inventory,sep=",",encoding=enc)
##~ colnames(was) <- c("time","stamp","visits","size","src","dst")
##~ }
##~ else
##~ was <- NULL
##~ data.frame(time=format(Sys.time(),"%Y-%m-%dT%H:%M:%SZ",tz="UTC")
##~ ,stamp=as.integer(file.mtime(fname))
##~ ,visits=0L
##~ ,size=file.size(fname)
##~ ,src=basename(fname)
##~ ,dst=basename(fname)
##~ )
# da <- rbind(was,da)
##~ utils::write.table(da,quote=TRUE,col.names=FALSE,row.name=FALSE,sep=","
##~ ,file=inventory,append=TRUE,fileEncoding="UTF-8")
if ((isUrsaCache)&&(!.ursaCacheFind(fname))) {
da <- .ursaCacheRecord(fname)
.ursaCacheWrite(da,append=TRUE)
}
}
ret2
})
if (length(ret)==1)
ret <- ret[[1]]
invisible(ret)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/xxx.browse.R
|
'.fasterize' <- function(obj,by=NULL,fun="last") {
for (pkg in c("sf","raster","fasterize")[3])
if (!requireNamespace(pkg,quietly=.isPackageInUse(),partial=FALSE))
stop(paste("Package",sQuote(pkg),"is required for this operation"))
# if (is.character(obj))
obj <- spatialize(obj,engine="sf")
# print(spatial_crs(obj))
if (is.null(by)) {
by <- spatial_fields(obj)
if (!length(by)) {
# spatial_data(obj) <- data.frame(mask=seq(spatial_count(obj)))
spatial_data(obj) <- data.frame(mask=0)
by <- NULL
}
}
# if (!("OGRFID" %in% spatial_fields(obj)))
# obj$OGRFID <- seq(spatial_count(obj))
# print(spatial_data(obj))
# q()
# if (inherits(by,"try-error"))
# by <- NULL
byVal <- obj[,by,drop=TRUE]
isCategory <- is.character(by) && is.character(byVal)
if (isCategory) {
a <- ursa(fasterize::fasterize(sf=obj
,raster=as.Raster()
,by=by,fun=fun))
if (identical(gsub("(\\s|\\.)","",names(a))
,gsub("(\\s|\\.)","",unique(byVal))))
names(a) <- unique(byVal)
a2 <- sum(a*seq(a),cover=0)
res <- reclass(a2,src=seq(a),dst=names(a))
if (!is.null(by))
names(res) <- by
}
else {
isList <- length(by)>1
if (isList) {
bname <- by
if (!("OGRFID" %in% spatial_fields(obj)))
obj$OGRFID <- seq(spatial_count(obj))
by <- "OGRFID"
}
if (devel <- FALSE) {
a9 <- fasterize::fasterize(sf=obj,raster=as.Raster()
,field=by,by=NULL,fun=fun) ## in memory
print(object.size(a9))
print(object.size(ursa(a9)))
q()
}
res <- ursa(fasterize::fasterize(sf=obj,raster=as.Raster()
,field=by,by=NULL,fun=fun))
# res <- fasterize::fasterize(sf=obj,raster=as.Raster(),field=by,by=NULL,fun=fun)
if (isList) {
src <- as.integer(names(ursa(res,"table")))
res <- lapply(bname,function(x) {
a <- reclass(res,src=src,dst=obj[src,x,drop=TRUE])
names(a) <- x
a
})
names(res) <- bname
}
else if (!is.null(by))
names(res) <- by
}
res
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/xxx.fasterize.R
|
# https://github.com/ecohealthalliance/fasterize
'.gdal_rasterize' <- '.rasterize' <- function(obj,...) {
if (!nchar(Sys.which("gdal_rasterize")))
return(NULL)
on.exit(NULL)
arglist <- list(...)
verbose <- .getPrm(arglist,name="verb(ose)*",default=FALSE)
# obj <- .getPrm(arglist,name=".*",class=list("character","ursaVectorExternal"))
# inMemory <- inherits(obj,c("sf","Spatial"))
inMemory <- (.isSF(obj))||(.isSP(obj))
if (inMemory) {
if (.isSF(obj)) {
mname <- try(names(sf::st_agr(obj)),silent=TRUE)
if (inherits(mname,"try-error"))
mname <- character()
}
else if (.isSP(obj)) {
mname <- try(colnames(methods::slot(obj,"data")),silent=TRUE)
if (inherits(mname,"try-error"))
mname <- character()
}
Ftemp <- .maketmp(ext=ifelse(spatial_dim(obj)==2,".shp",".gpkg"))
spatial_write(obj,Ftemp,verbose=verbose)
obj <- Ftemp
isShp <- .lgrep("\\.shp$",basename(Ftemp))>0
if (isShp)
on.exit(.shp.remove(Ftemp),add=TRUE)
else
on.exit(file.remove(Ftemp),add=TRUE)
}
external <- is.character(obj)
if (external) {
dsnE <- obj
if (verbose)
.elapsedTime("read vector -- start")
obj <- spatialize(obj,...)
if (verbose)
.elapsedTime("read vector -- finish")
}
if (external)
dsn <- dsnE
else
dsn <- attr(obj,"dsn")
# print(c(dsn=dsn,dsnE=dsnE))
g0 <- attr(obj,"grid")
dname <- attr(obj,"colnames")
dmask <- .getPrm(arglist,name="(attr|field)",default=".+")
feature <- .getPrm(arglist,name="feature",valid=c("field","geometry","FID"))
where <- .getPrm(arglist,name="subset",default="")
ogropt <- .getPrm(arglist,name="ogropt",default="")
optF <- .getPrm(arglist,name="^opt$",class="character",default="")
clipsrc <- .getPrm(arglist,name="clipsrc",default=FALSE)
clipdst <- .getPrm(arglist,name="clipdst",default=FALSE)
wrapdateline <- .getPrm(arglist,name="wrapdateline",default=FALSE)
layer <- .getPrm(arglist,name="layer",default=".*")
isZip <- .lgrep("\\.zip$",dsn)>0
fname1 <- .gsub("\\.zip$","",dsn)
fname2 <- paste0(fname1,".zip")
fname3 <- gsub("(\\..+$)",".zip",fname1)
fname4 <- paste0(fname1,".gz")
fname5 <- paste0(fname1,".bz2")
cond1 <- file.exists(fname1)
cond2 <- file.exists(fname2)
cond3 <- file.exists(fname3)
cond4 <- file.exists(fname4)
cond5 <- file.exists(fname5)
# print(dsn)
# print(c(fname1=fname1,fname2=fname2,fname3=fname3))
# print(c(isZip=isZip,cond1=cond1,cond2=cond2,cond3=cond3,cond4=cond4,cond5=cond5))
if (cond1)
dsn <- fname1
else if (cond2 | cond3) {
if (cond2)
ziplist <- unzip(fname2,exdir=tempdir())
if (cond3)
ziplist <- unzip(fname3,exdir=tempdir())
on.exit(file.remove(ziplist),add=TRUE)
dsn <- .grep("\\.shp$",ziplist,value=TRUE)
}
else if ((cond4)&&(nchar(Sys.which("gzip")))) {
dsn0 <- dsn
dsn <- tempfile();on.exit(file.remove(dsn))
system2("gzip",c("-f -d -c",.dQuote(dsn0)),stdout=dsn,stderr=FALSE)
}
else if ((cond5)&&(nchar(Sys.which("bzip2")))) {
dsn0 <- dsn
dsn <- tempfile();on.exit(file.remove(dsn))
system2("bzip2",c("-f -d -c",.dQuote(dsn0)),stdout=dsn,stderr=FALSE)
}
else
dsn <- NA
isSF <- inherits(obj,"sf")
isSP <- !isSF
# print(dsn)
# str(obj)
if ((nchar(ogropt)>1)||(nchar(where)>0)) {
shpname <- .maketmp()
cmd <- paste("ogr2ogr"
,ogropt
,"-where",dQuote(where)
,"-f",.dQuote(c("ESRI Shapefile","SQLite","GeoJSON")[1])
# ,ifelse(verbose,"-progress","")
,.dQuote(paste0(shpname,".shp")),.dQuote(dsn)
)
if (verbose)
message(cmd)
system(cmd)
list3 <- .dir(path=dirname(shpname)
,pattern=paste0(basename(shpname),"\\.(cpg|dbf|prj|shp|shx)")
,recursive=FALSE,full.names=TRUE)
on.exit(file.remove(list3),add=TRUE)
lname <- basename(shpname)
dsn <- .grep("\\.shp$",list3,value=TRUE)
}
if (isZip <- .lgrep("\\.zip$",dsn)>0) {
ziplist <- unzip(dsn,exdir=tempdir());on.exit(file.remove(ziplist))
dsn <- .grep("\\.(shp|sqlite|fgb|gpkg|geojson)$",ziplist,value=TRUE)
}
else if ((nchar(Sys.which("gzip")))&&(isZip <- .lgrep("\\.gz$",dsn)>0)) {
dsn0 <- dsn
dsn <- tempfile();on.exit(file.remove(dsn))
system2("gzip",c("-f -d -c",.dQuote(dsn0)),stdout=dsn,stderr=FALSE)
}
cmd <- paste("gdalsrsinfo -o proj4",.dQuote(dsn))
if (verbose)
message(cmd)
proj4 <- system(cmd,intern=TRUE)
proj4 <- .gsub("'","",proj4)
proj4 <- .gsub("(^\\s|\\s$)","",proj4)
proj4 <- proj4[nchar(proj4)>0]
if (noProj <- !length(proj4))
proj4 <- "+proj=longlat +datum=WGS84 +no_defs"
ftemp <- .maketmp() # .maketmp() #tempfile(pattern="") # ".\\tmp1"
cmd <- paste("ogrinfo","-q",.dQuote(dsn))
if (verbose)
message(cmd)
lname <- system(cmd,intern=TRUE)
lname <- .gsub("(\\s\\(.+\\))*$","",lname)
lname <- .gsub("^\\d+:\\s(.+)$","\\1",lname)
.lname <- .grep(layer,lname,value=TRUE)
if (length(.lname)>1)
.lname <- lname[match(layer,lname)]
if (length(.lname)!=1) {
print(paste("Select only one layer:",paste(paste0(seq(.lname),")")
,.sQuote(.lname),collapse=", ")),quote=FALSE)
return(NULL)
}
lname <- .lname
rm(.lname)
if (proj4!=g0$crs) {
# if (verbose)
# message("REPROJECT")
shpname <- .maketmp()
bb1 <- with(regrid(g0,expand=1.1),matrix(c(minx,miny,maxx,maxy),ncol=2))
bb1 <- matrix(bb1[c(1,2,1,4,3,4,3,2,1,2)],ncol=2,byrow=TRUE)
if (TRUE) {
x <- bb1[,1]
y <- bb1[,2]
n <- 256
x <- c(seq(x[1],x[2],len=n),seq(x[2],x[3],len=n)
,seq(x[3],x[4],len=n),seq(x[4],x[5],len=n))
y <- c(seq(y[1],y[2],len=n),seq(y[2],y[3],len=n)
,seq(y[3],y[4],len=n),seq(y[4],y[5],len=n))
bb1 <- cbind(x,y)
}
if (isSF) {
bb1 <- sf::st_sfc(sf::st_multilinestring(list(bb1)),crs=g0$crs)
bb2 <- sf::st_transform(bb1,proj4)
bb2 <- sf::st_bbox(bb2)
}
else if (isSP) {
bb1 <- sp::SpatialLines(list(sp::Lines(sp::Line(bb1),1L))
,proj4string=sp::CRS(g0$crs,doCheckCRSArgs=FALSE))
bb2 <- sp::spTransform(bb1,proj4)
bb2 <- c(sp::bbox(bb2))
if (length(bb2)==6)
bb2 <- bb2[c(1,2,4,5)]
}
# print(proj4)
if (.lgrep("\\+proj=longlat",proj4)) {
bb2[1][bb2[1]<(-179)] <- -180
bb2[3][bb2[3]>(179)] <- 180
}
## https://gdal.org/ogr2ogr.html https://gis-lab.info/qa/ogr2ogr-examples.html
g1 <- regrid(g0,border=5)
cmd <- paste("ogr2ogr","-t_srs",.dQuote(g0$crs)
,ifelse(noProj,paste("-s_srs",.dQuote(proj4)),"")
,"-sql",.dQuote(paste("select FID,* from",.dQuote(.dQuote(lname))))
,"-dialect",c("SQLITE","OGRSQL")[2]
,"-select FID"
,"-f",.dQuote(c("ESRI Shapefile","SQLite")[1])
,ifelse(verbose,"-progress","")
# ,"-skipfailures"
,ifelse(wrapdateline,"-wrapdateline","")
# ,"-datelineoffset 180"
,ifelse(clipsrc,paste("-clipsrc",paste(bb2,collapse=" ")),"")
,ifelse(clipdst,paste("-clipdst"
,with(g1,paste(c(minx,miny,maxx,maxy),collapse=" "))),"")
,.dQuote(paste0(shpname,".shp")),.dQuote(dsn)
)
if (verbose)
message(cmd)
# .elapsedTime("a")
system(cmd)
# .elapsedTime("b")
list2 <- .dir(path=dirname(shpname)
,pattern=paste0(basename(shpname),"\\.(cpg|dbf|prj|shp|shx)")
,recursive=FALSE,full.names=TRUE)
on.exit(file.remove(list2),add=TRUE)
lname <- basename(shpname)
shpname <- .grep("\\.shp$",list2,value=TRUE)
proj4 <- g0$crs
}
else
shpname <- dsn
dname <- dname[.grep(dmask,dname)] ## ++ 20191009
if (is.null(dname)) {
md <- system(paste("ogrinfo -al -so",dsn),intern=TRUE)
patt <- "^(.+): \\S+ \\(.+\\)$"
md <- .grep(patt,md,value=TRUE)
dname <- .grep(dmask,.gsub(patt,"\\1",md),value=TRUE)
}
fext <- .gsub(".+\\.(.+)$","\\1",basename(dsn))
fromZero <- .lgrep("^(sqlite|gpkg)$",fext)==0 & .lgrep("^fid$",dname)==0
if (verbose)
print(c(FID_starts_from_zero=fromZero))
if (feature=="field") {
if (inMemory)
dname <- mname ## restore dbf coersion
# opt <- paste()
# dname <- .grep(dmask,dname,value=TRUE)
cmd <- with(g0,paste("gdal_rasterize"
,"-a FID",optF
,"-sql",.dQuote(paste("select FID,* from",.dQuote(.dQuote(lname))))
,"-dialect",c("SQLITE","OGRSQL")[2]
,"-init -1 -a_nodata -1"
,"-a_srs",.dQuote(proj4)
,"-tr",resx,resy
# ,"-where",dQuote(subset)
,"-te",minx,miny,maxx,maxy
,"-of ENVI -ot Int32",ifelse(verbose,"","-q")
,.dQuote(shpname),ftemp))
if (verbose) {
.elapsedTime(paste("rasterize",.sQuote(feature),"-- start"))
message(cmd)
}
system(cmd)
if (verbose)
.elapsedTime(paste("rasterize",.sQuote(feature),"-- finish"))
va <- read_envi(ftemp,resetGrid=TRUE)
envi_remove(ftemp)
ta <- ursa(va,"table")
tavalue <- as.integer(names(ta))
if (TRUE) { ## ++ 20171127
# print(ursa_table(va))
if (fromZero)
va <- va+1L
}
else {
minva <- global_min(va)
if ((!is.na(minva))&&(minva==0))
va <- va+1L
}
va[va==0] <- NA
res <- lapply(dname,function(x) {
isFID <- .lgrep("fid",x)
if ((isFID)||(identical(tavalue,obj[[x]])))
a <- va
else {
a <- reclass(va,src=seq(nrow(obj)),dst=obj[[x]])
}
if (.is.category(a))
ursa(a,"nodata") <- length(ursa(a,"colortable"))
names(a) <- x
a
})
names(res) <- dname ## or, comment it
}
else if (feature=="geometry") {
writeValue <- FALSE
if (length(dname)==1) {
if (is.numeric(obj[[dname]])) {
value <- obj[[dname]]
writeValue <- TRUE
}
}
if (verbose)
.elapsedTime(paste("rasterize",.sQuote(feature),"-- start"))
nr <- nrow(obj)
res <- ursa_new(badname=paste("FID",seq(nr)))
for (i in seq(nr)) {
cmd <- with(g0,paste("gdal_rasterize"
,"-a FID",optF
,"-sql",.dQuote(paste("select FID,* from",.dQuote(.dQuote(lname))
,"where",paste0(.dQuote("FID"),"=",i-fromZero)))
,"-dialect",c("SQLITE","OGRSQL")[2]
# ,"-where",paste0(.dQuote("FID"),"=",i)
,"-tr",resx,resy
,"-te",minx,miny,maxx,maxy
,"-of ENVI -ot Int16",ifelse(verbose,"","-q")
,"-a_nodata -1 -init -1"
,shpname,ftemp))
if (verbose)
message(cmd)
system(cmd)
if (writeValue) {
va <- read_envi(ftemp)
va[!is.na(va)] <- value[i]
res[i] <- va
}
else
res[i] <- read_envi(ftemp)
envi_remove(ftemp)
}
if (verbose)
.elapsedTime(paste("rasterize",.sQuote(feature),"-- finish"))
}
else if (feature=="FID") {
cmd <- with(g0,paste("gdal_rasterize"
,"-a FID",optF
,"-sql",.dQuote(paste("select FID,* from",.dQuote(.dQuote(lname))))
,"-dialect",c("SQLITE","OGRSQL")[2]
,"-init -1 -a_nodata -1"
,"-a_srs",.dQuote(proj4)
,"-tr",resx,resy
# ,"-where",dQuote(subset)
,"-te",minx,miny,maxx,maxy
,"-of ENVI -ot Int32",ifelse(verbose,"","-q")
,.dQuote(shpname),ftemp))
if (verbose) {
.elapsedTime(paste("rasterize",.sQuote(feature),"-- start"))
message(cmd)
}
system(cmd)
if (verbose)
.elapsedTime(paste("rasterize",.sQuote(feature),"-- finish"))
res <- c(FID=read_envi(ftemp,resetGrid=TRUE)+1*fromZero)
envi_remove(ftemp)
}
else
stop(paste("Unimplemented feature:",feature))
res
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/xxx.gdal_rasterize.R
|
# https://gis.stackexchange.com/questions/37790/how-to-reproject-raster-from-0-360-to-180-180-with-cutting-180-meridian
# gdalwarp -t_srs WGS84 ~/0_360.tif 180.tif -wo SOURCE_EXTRA=1000 --config CENTER_LONG 0
'.gdalwarp' <- function(src,dst=NULL,grid=NULL,resample="near",nodata=NA
,resetGrid=FALSE,opt=NULL,sf=TRUE,close=FALSE,verbose=0L) {
if (is.null(grid)) {
if (is.ursa(dst,"grid")) {
grid <- dst
dst <- NULL
}
else if (is.ursa(dst)) {
grid <- ursa(dst,"grid")
dst <- NULL
}
else
grid <- getOption("ursaSessionGrid")
}
else
grid <- ursa_grid(grid)
isSF <- isTRUE(sf) & requireNamespace("sf",quietly=.isPackageInUse())
if (!isSF & !nchar(Sys.which("gdalwarp"))) {
withRaster <- requireNamespace("raster",quietly=.isPackageInUse())
if (withRaster) {
r1 <- as.Raster(src)
session_grid(grid)
r2 <- as.Raster(ursa_new(0L))
r3 <- try(raster::resample(r1,r2,method=switch(resample,near="ngb","bilinear")))
if (inherits(r3,"try-error")) {
if (verbose)
message('reprojection is failed')
return(src)
}
}
else if (verbose)
message(paste("'gdalwarp' is not found; package 'raster' is not found."
,"Reprojection is failed."))
return(src)
}
# a <- open_envi(src)
# ct <- ursa_colortable(a)
# close(a)
ct <- NULL
if (is.ursa(src)) {
ct <- ursa_colortable(src)
removeSrc <- TRUE
.src <- src
nodata <- ignorevalue(src)
credits <- attr(.src,"copyright")
attr(.src,"copyright") <- NULL
src <- .maketmp(ext=".")
if (resample=="near")
write_envi(.src,src)
else
write_envi(.src,src,datatype=NA)
rm(.src)
}
else {
removeSrc <- FALSE
# nodata <- NA
}
inMemory <- is.null(dst)
if (inMemory) {
dst <- .maketmp(ext="")
driver <- "ENVI"
}
else {
# driver <- .gsub("^.+(\\.(.+))$","\\2",tolower(basename(dst)))
driver <- switch(.gsub("^.+(\\.(.+))$","\\2",tolower(basename(dst)))
,tif="GTiff",tiff="GTiff",envi="ENVI",img="HFA",hfa="HFA"
,"ENVI")
}
if (verbose)
print(c(inMemory=inMemory,removeSrc=removeSrc,isNullGrid=is.null(grid),isSF=isSF))
proj4 <- ursa_crs(grid)
if (!nchar(proj4)) {
opt <- c(opt,to="SRC_METHOD=NO_GEOTRANSFORM",to="DST_METHOD=NO_GEOTRANSFORM")
}
if (!("co" %in% names(opt))) {
if (driver=="GTiff") {
pr <- ifelse(((removeSrc)&&(inherits(.src$value,"ursaNumeric"))),3,2)
opt <- c(opt,co=paste0("COMPRESS=",c("DEFLATE","ZSTD")[1])
,co=paste0("PREDICTOR=",pr)
,co="TILED=NO")
}
else if (driver=="HFA") {
opt <- c(opt,co="COMPRESSED=YES")
}
}
if (is.null(opt)) {
optF <- ""
}
else if (!is.null(names(opt))) {
str(opt)
if (T) ## 20230228++
optF <- paste(lapply(names(opt),\(x) {
val <- opt[[x]]
res <- paste0("-",x)
if (is.character(val)) {
if (!nchar(val))
return(res)
if (grepl("-config",x))
res <- paste0(res," ",val)
else
res <- paste0(res," ",.dQuote(val))
}
else
res <- paste0(res," ",val)
res
}),collapse=" ")
else { ## --
optS <- unlist(opt)
optF <- paste(paste0("-",names(optS)," ",.dQuote(unname(optS))),collapse=" ")
optF <- gsub("\\s*\"TRUE\"","",optF)
optF <- .gsub("\\s\\\"\\\"","",optF)
}
}
else
optF <- ""
if (!("r" %in% names(opt))) {
optF <- paste(optF,"-r",resample)
}
if (is.null(grid))
cmd <- paste("-overwrite -of",driver
,ifelse(is.na(nodata),"",paste("-srcnodata",nodata,"-dstnodata",nodata))
,ifelse(verbose==0L,"-q","")
,optF)
else
cmd <- with(grid,c(NULL
,"-overwrite"
,"-of",driver
,if (nchar(proj4)) c("-t_srs",.dQuote(proj4))
# ,if (nchar(proj4)) c("-t_srs",proj4)
,"-nosrcalpha"
,"-tr",resx,resy,"-te",minx,miny,maxx,maxy
,if (!is.na(nodata)) c("-srcnodata",nodata,"-dstnodata",nodata)
,if (verbose==0L) "-q"
,unlist(strsplit(optF,split="\\s+"))
))
cmdcli <- paste("gdalwarp",paste(cmd,collapse=" "),src,dst)
if (verbose)
message(cmdcli)
if (verbose>1)
return(NULL)
if (!isSF) {
# proj_lib <- Sys.getenv("PROJ_LIB")
# Sys.setenv(PROJ_LIB=file.path(dirname(dirname(Sys.which("gdalwarp"))),"share/proj"))
### Sys.setenv(PROJ_LIB="")
# print(Sys.getenv("PROJ_LIB"))
system(cmdcli)
# Sys.setenv(PROJ_LIB=proj_lib)
}
else {
sf::gdal_utils("warp",src,dst,options=gsub("\"","",cmd),quiet=verbose==0L)
}
session_grid(NULL)
if (inMemory) {
ret <- if (driver=="ENVI") read_envi(dst) else read_gdal(dst)
if (!is.null(ct))
ursa_colortable(ret) <- ct
attr(ret,"copyright") <- credits
}
else if (!close)
ret <- if (driver=="ENVI") open_envi(dst) else open_gdal(dst)
else
ret <- NULL
if (!is.na(nodata)) {
ignorevalue(ret) <- nodata
if (inMemory)
ret[ret==nodata] <- NA
}
if (inMemory) {
envi_remove(dst)
}
if (removeSrc) {
envi_remove(src)
}
if (resetGrid)
session_grid(ret)
ret
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/xxx.gdalwarp.R
|
# http://geo2tag.org/?page_id=671&lang=en_US
# https://geocode-maps.yandex.ru/1.x/?geocode=metro Tretyakovskaya&results=100&format=json
# geocodeList <- eval(as.list(args(.geocode))$service)
'.geocode' <- function(loc=NULL,area=c("bounding","point","shape"),place=""
,select=c("top","expand","all")
,service=c("nominatim","pickpoint","google")
,cache=TRUE,verbose=FALSE) {
if (is.null(loc)) {
if (!TRUE) {
dst <- tempfile()
download.file("http://ip-api.com/csv",dst,mode="wt")
a <- readLines(dst,warn=FALSE)
file.remove(dst)
a <- unlist(strsplit(a,split=","))
pt <- c(lon=as.numeric(a[9]),lat=as.numeric(a[10]))
}
else
a <- readLines("http://ip-api.com/line")
pt <- cbind(lon=as.numeric(a[9]),lat=as.numeric(a[8]))
rownames(pt) <- "ip-api.com"
return(pt)
}
area <- match.arg(area)
# print(c(service=service,loc=loc))
service <- match.arg(service)
pSea <- "(Sea|\u043C\u043e\u0440\u0435)" ## 'MOPE' in Russian
isSea <- .lgrep(paste0("(",pSea,"\\s|\\s",pSea,")"),loc)>0
if ((area=="bounding")&&(isSea)&&(service=="nominatim")) {
cat("More faults with 'nominatim' for 'sea' geocoding\n")
# cat("Redirecting to 'google' for 'sea' geocoding\n")
# service <- "google"
}
select <- match.arg(select)
shape <- NULL
if (service %in% c("nominatim","pickpoint")) {
## curl -H Accept-Language:de 'https://nominatim.openstreetmap.org......."
if (service %in% "nominatim")
endpoint <- "https://nominatim.openstreetmap.org/search.php?"
else if (service %in% "pickpoint") {
key <- getOption("pickpointKey")
if (!is.character(key)) {
message(paste("Unable to get 'pickpoint' API key using"
,"`getOption(\"pickpointKey\")`."
,"Switched to 'nominatim' geocoding."))
service <- "nominatim"
endpoint <- "https://nominatim.openstreetmap.org/search.php?"
}
else
endpoint <- paste0("https://api.pickpoint.io/v1/forward?&key=",key,"&")
}
src <- paste0(endpoint,"q=",loc
# ,"&polygon_text=1"
,"&format=xml","&bounded=0","&accept-language=en-US,ru")
# dst <- tempfile() # "nominatim.xml" # tempfile()
if (F & verbose)
message(src)
dst <- .ursaCacheDownload(src,quiet=!verbose)
xmlstring <- scan(dst,character(),quiet=!verbose)
# Encoding(xmlstring) <- "UTF-8"
# str(as.list(xmlstring))
# if (dirname(dst)==tempdir())
# file.remove(dst)
ind <- grep("geotext",xmlstring)
if (length(ind)) {
geotext <- xmlstring[ind]
print(geotext)
}
ptype <- .grep("^type=",xmlstring,value=TRUE)
ptype <- .gsub(".*(\'|\")(.+)(\'|\").*","\\2",ptype)
pclass <- .grep("^class=",xmlstring,value=TRUE)
pclass <- .gsub(".*(\'|\")(.+)(\'|\").*","\\2",pclass)
prank <- .grep("^place_rank=",xmlstring,value=TRUE)
prank <- .gsub(".*(\'|\")(.+)(\'|\").*","\\2",prank)
if (FALSE) {
prank[prank=="8"] <- "state"
prank[prank=="10"] <- "region"
prank[prank=="12"] <- "county"
prank[prank=="16"] <- "city"
# prank[prank=="17"] <- "town|island"
# prank[prank=="18"] <- "village|"
# prank[prank=="19"] <- ""
}
ptype <- paste(pclass,ptype,prank,sep=":")
lon <- .grep("lon=",xmlstring,value=TRUE)
lon <- as.numeric(.gsub(".*(\'|\")(.+)(\'|\").*","\\2",lon))
lat <- .grep("lat=",xmlstring,value=TRUE)
lat <- as.numeric(.gsub(".*(\'|\")(.+)(\'|\").*","\\2",lat))
pt <- cbind(lon=lon,lat=lat)
if (!nrow(pt))
return(NULL)
rownames(pt) <- ptype
ind <- grep("boundingbox",xmlstring)
bounding <- xmlstring[ind]#[1]
bounding <- .gsub(".*\"(.+)\".*","\\1",bounding)
bounding <- lapply(bounding,function(p){
as.numeric(unlist(strsplit(p,split=",")))
})
bounding <- do.call(rbind,bounding)
rownames(bounding) <- ptype
colnames(bounding) <- c("miny","maxy","minx","maxx")
ann <- .grep("display_name=",xmlstring,value=TRUE)
ann <- .gsub(".*\"(.+)\".*","\\1",ann)
importance <- .grep("importance",xmlstring,value=TRUE)
importance <- as.numeric(.gsub(".*(\'|\")(.+)(\'|\").*","\\2",importance))
# type <- NULL ## debug
typeInd <- integer()
if ((is.character(place))&&(nchar(place))) {
typeInd <- which(!is.na(match(ptype,place)))
typeInd <- .grep(place,ptype)
if (length(typeInd)) {
bounding <- bounding[typeInd,,drop=FALSE]
pt <- pt[typeInd,,drop=FALSE]
importance <- importance[typeInd]
}
}
else if (is.numeric(place)) {
print("numeric place -- 'place_rank' -- ignored (TODO)")
}
important <- which(importance==max(importance))[1]
if (select=="top") {
lat <- lat[important]
lon <- lon[important]
pt <- pt[important,,drop=FALSE]
bounding <- bounding[important,,drop=FALSE]
}
if (select %in% c("expand","top")) {
dg <- 1
is180 <- (bounding[,"minx"]<=(-180+dg))&&(bounding[,"maxx"]>=(180-dg))
isShape <- "shape" %in% area
if ((isShape)||(is180)) {
if (verbose)
.elapsedTime("shape|180 -- download")
if (T & !isShape) { ## to deprecate
src <- paste0(endpoint,"q=",loc
,"&polygon_text=1"
,"&format=xml"
,"&bounded=0","&accept-language=en-US,ru")
if (verbose)
message(src)
dst <- .ursaCacheDownload(src,cache=cache,quiet=!verbose)
if (verbose)
.elapsedTime("shape|180 -- parsing")
b <- readLines(dst,encoding="UTF-8",warn=FALSE)
# print(file.size(dst))
b <- unlist(strsplit(b,split="'"))
b <- .grep("(MULTI)*(POLYGON|LINESTRING)",b,value=TRUE,ignore.case=FALSE)
b <- .gsub("(^.+(MULTI)*(POLYGON|LINESTRING)|\\(|\\))"," ",b)
b <- .gsub("(^\\s+|\\s+(\".+)*$)","",b)
b <- lapply(b,function(b2) {
b3 <- unlist(strsplit(b2,split=","))
b3 <- unlist(strsplit(b3,split="\\s+"))
b3 <- b3[nchar(b3)>0]
b3 <- matrix(as.numeric(b3),ncol=2,byrow=TRUE)[,1]
b4 <- b3
ind <- b4<0
if (length(ind))
b4[ind] <- b4[ind]+360
sd3 <- sd(b3)
sd4 <- sd(b4)
if (sd4<sd3)
ret <- c(minx=min(b3[b3>0]),maxx=max(b3[b3<0]))
else
ret <- c(minx=min(b3),maxx=max(b3))
ret
})
b <- do.call("rbind",b)
##~ b <- unlist(strsplit(b,split=","))
##~ b <- unlist(strsplit(b,split="\\s+"))
##~ b <- b[nchar(b)>0]
##~ b <- matrix(as.numeric(b),ncol=2,byrow=TRUE)[,1]
# bounding[,"minx"] <- min(b[b>0])
# bounding[,"maxx"] <- max(b[b<0])
if (select=="top")
ind <- important
else if (length(typeInd))
ind <- typeInd
else
ind <- seq(nrow(bounding))
bounding[,c("minx","maxx")] <- b[ind,c("minx","maxx")]
}
else {
loaded <- loadedNamespaces()
isSF <- "sf" %in% loaded ||
requireNamespace("sf",quietly=.isPackageInUse())
if (!isSF) {
if (.isPackageInUse())
isSP <- FALSE
else
isSP <- "rgeos" %in% loaded || .rgeos_requireNamespace()
}
else
isSP <- FALSE
isWKT <- isSF || isSP
if (verbose)
print(c('sf'=isSF,'sp+rgeos'=isSP,'wkt'=isWKT))
src <- paste0(endpoint,"q=",loc
,"&polygon_",ifelse(isWKT,"text=1","geojson=1")
,"&format=xml"
,"&bounded=0","&accept-language=en-US,ru")
if (verbose)
message(src)
dst <- .ursaCacheDownload(src,cache=cache,quiet=!verbose)
if (verbose)
.elapsedTime("shape|180 -- parsing")
b <- readLines(dst,encoding="UTF-8",warn=FALSE)[2]
# ind1 <- unlist(gregexpr("geojson)=\\'\\{",b))
# ind2 <- unlist(gregexpr("\\}\\'",b))
##~ ind1 <- gregexpr("geo(text|json)=\\'",b)
##~ ind2 <- gregexpr("(\\)|\\})\\'",b)
ind1 <- unlist(gregexpr("geo(text|json)=(\\'|\")",b))
ind2 <- unlist(gregexpr("(\\)|\\})(\\'|\")",b))
ind3 <- which(ind1>0)
ind4 <- which(ind2>0)
if ((identical(ind3,ind4))&&(length(ind3)>0)) { ## ind3[1]==ind4[1]
ind1 <- ind1[ind3]
ind2 <- ind2[ind4]
shape <- lapply(seq_along(ind3),function(i) {
n1 <- nchar(.gsub2("(geo(text|json)=(\\'|\"))","\\1",b))
b2 <- substr(b,ind1[i]+n1,ind2[i])
if (F)
return(b2)
if (!isWKT) {
if (T) ## or overwrite cached?
dst <- tempfile(fileext=".geojson")
Fout <- file(dst,encoding="UTF-8")
writeLines(b2,Fout)
close(Fout)
d2 <- spatial_read(dst,engine="sf")
# d2 <- sf::st_read(b2,quiet=TRUE)
}
else if (isSF) {
d2 <- data.frame(id=seq_along(b2))
d2$geom <- b2
d2 <- spatial_geometry(sf::st_as_sf(d2,wkt="geom"))
}
else if (isSP) {
d2 <- .rgeos_readWKT(b2)
}
spatial_crs(d2) <- 4326
if (("top" %in% select)&&(is_spatial_points(d2)))
return(NULL)
if ("shape" %in% area)
return(d2)
if (is180) {
d2 <- spatialize(d2,style="merc")
bb2 <- matrix(spatial_bbox(d2),ncol=2,byrow=TRUE)
bb2 <- .project(bb2,spatial_crs(d2),inv=TRUE)
bb2 <- c(t(bb2))
names(bb2) <- c("xmin","ymin","xmax","ymax")
}
else
bb2 <- spatial_bbox(d2)
# print(bb2)
# d2 <- sf::st_cast(d2,"POINT")
bb2
})
if ("bounding" %in% area) {
# shape <- t(list2DF(shape))
if (T) {
# bname <- rownames(bounding)
bounding <- do.call("rbind",shape)
# rownames(bounding) <- bname
}
else {
bounding[,"minx"] <- shape[,"xmin"]
bounding[,"maxx"] <- shape[,"xmax"]
}
}
}
}
if (verbose)
.elapsedTime("shape|180 -- finish")
}
if (select=="top")
ptype <- ptype[important]
}
if ((area=="shape")&&(!is.null(shape))) {
if ("top" %in% select) {
ind <- which(sapply(shape,function(x) !is.null(x)))
if (length(ind)) {
if ((length(typeInd))&&(!is.na(ind2 <- ind[typeInd])))
ind <- ind2
shape <- shape[[ind[1]]]
# session_grid(shape)
}
}
return(shape)
}
if (area=="bounding") {
bounding <- bounding[,c(3,1,4,2),drop=FALSE]
if (FALSE) {
print(bounding)
da <- data.frame(lon=range(bounding[,c(3,4)])
,lat=range(bounding[,c(1,2)]))#,z=1:2)
}
if (select=="expand")
bounding <- c(minx=min(bounding[,1]),miny=min(bounding[,2])
,maxx=max(bounding[,3]),maxy=max(bounding[,4]))
if (select=="top") {
# attr(bounding,"type") <- ptype
bounding <- bounding[1,,drop=TRUE]
}
return(bounding)
}
if (area=="point") {
if (nrow(pt)==1) {
ptype <- rownames(pt)
ptname <- colnames(pt)
pt <- c(pt)
names(pt) <- ptname
# attr(pt,"type") <- ptype
}
return(pt)
}
}
else if (service=="google") {
src <- paste0("https://maps.googleapis.com/maps/api/geocode/xml?"
,"address=",loc)
if (proposed <- TRUE) {
apiKey <- getOption("googleMaps")
if (is.character(apiKey))
src <- paste0(src,"&key=",apiKey)
}
dst <- .ursaCacheDownload(src,cache=cache,quiet=!verbose)
xmlstring <- scan(dst,character(),quiet=!verbose)
istatus <- .grep("<status>",xmlstring)
status <- .gsub("<status>(.+)</status>","\\1",xmlstring[istatus])
if (status=="OVER_QUERY_LIMIT") {
message(paste("Over query limit for Google geocoding."
,"Try to specify `options(googleMaps=<YOUR_API>)`"))
return(NULL)
}
ilat <- .grep("<lat>",xmlstring)
ilon <- .grep("<lng>",xmlstring)
glat <- as.numeric(.gsub("<lat>(.+)</lat>","\\1",xmlstring[ilat]))
glon <- as.numeric(.gsub("<lng>(.+)</lng>","\\1",xmlstring[ilon]))
aname <- .grep("(location|southwest|northeast)",xmlstring[c(ilat,ilon)-1]
,value=TRUE)
aname <- .gsub("(<|>)","",aname)
bname <- .grep("<(viewport|bounds)>",xmlstring[c(ilat,ilon)-2]
,value=TRUE)
bname <- .gsub("(<|>)","",bname)
iname <- .grep("<(viewport|bounds)>",xmlstring)
names(glon) <- names(glat) <- aname
if ((!length(glon))||(!length(glat))) {
# loc <- RJSONIO::fromJSON("http://ip-api.com/json")
return(NULL)
}
ptype <- .grep("<location_type>",xmlstring,value=TRUE)
ptype <- .gsub("<.+>(.+)</.+>","\\1",ptype)
pt <- cbind(lon=unname(glon[.grep("location",names(glon))])
,lat=unname(glat[.grep("location",names(glat))]))
attr(pt,"type") <- ptype
glon <- glon[.grep("location",aname,invert=TRUE)]
glat <- glat[.grep("location",aname,invert=TRUE)]
lname <- paste0(rep(bname,each=2),".",names(glon))
names(glon) <- names(glat) <- lname
n <- length(bname)
bbox <- cbind(minx=rep(NA,n),miny=rep(NA,n),maxx=rep(NA,n),maxy=rep(NA,n))
rownames(bbox) <- bname
##~ for (i in seq_along(bname)) {
##~ bbox[i,"minx"] <- glon[.grep(paste0(bname[i],"\\.southwest"),lname)]
##~ bbox[i,"miny"] <- glat[.grep(paste0(bname[i],"\\.southwest"),lname)]
##~ bbox[i,"maxx"] <- glon[.grep(paste0(bname[i],"\\.northeast"),lname)]
##~ bbox[i,"maxy"] <- glat[.grep(paste0(bname[i],"\\.northeast"),lname)]
##~ }
bbox[,"minx"] <- glon[.grep("\\.southwest",lname)]
bbox[,"miny"] <- glat[.grep("\\.southwest",lname)]
bbox[,"maxx"] <- glon[.grep("\\.northeast",lname)]
bbox[,"maxy"] <- glat[.grep("\\.northeast",lname)]
if (verbose) {
print(pt)
print(bbox)
}
if (area=="point") {
if (nrow(pt)==1) {
ptype <- rownames(pt)
ptname <- colnames(pt)
pt <- c(pt)
names(pt) <- ptname
# attr(pt,"type") <- ptype
}
return(pt)
}
else if (area=="bounding") {
if (select %in% "top")
return(bbox["viewport",])
if (select %in% "expand")
return(bbox["bounds",])
return(bbox)
if (FALSE) {
glon <- range(glon)
glat <- range(glat)
dlon <- abs(diff(glon))
dlat <- abs(diff(glat))
if ((dlon<0.01)&&(dlat<0.01)) {
sc <- abs(1/cos(mean(glat)))
mul <- 1 # 3
glon <- mean(glon)+mul*abs(diff(glon))*sc*c(-1,1)/2
glat <- mean(glat)+mul*abs(diff(glat))*c(-1,1)/2
}
da <- data.frame(lon=range(glon),lat=range(glat))
}
return(bbox)
}
}
return(NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/xxx.geocode.R
|
'.geomap' <- function(loc=NULL,style="",geocode="",place="",size=NA,zoom="0"
,border=27,retina=NA,cache=TRUE,verbose=FALSE) {
# if (!nchar(style))
# style <- "google static"
geocodeList <- eval(as.list(args(.geocode))$service)
tileList <- .tileService()
if (!nchar(geocode))
geocode <- if (.lgrep("google-deprecated",style)) "google" else "nominatim"
geocode <- match.arg(geocode,geocodeList)
if (!sum(nchar(style)))
style <- paste(switch(geocode,nominatim="openstreetmap",pickpoint="openstreetmap"
,google="google","CartoDB"),"color")
if (is.na(zoom))
zoom <- "0"
isWGS84 <- .lgrep("(maps\\.yandex|^(Yandex|\u042f\u043d\u0434\u0435\u043a\u0441)$)"
,style,ignore.case=TRUE)
staticMap <- c("openstreetmap","google$","sputnikmap")
tilePatt <- paste0("(",paste0(unique(c(staticMap,tileList))
,collapse="|"),")")
tilePatt <- .gsub("\\.","\\\\.",tilePatt)
artPatt <- .gsub("\\.","\\\\.",tilePatt)
if (!.lgrep(tilePatt,style))
art <- "none"
else {
if (length(style)>1)
art <- "none"
else if (style %in% tileList)
art <- style
else if ((artStyle <- gsub("\\s(color|gr[ae](scale)*)","",style)) %in% tileList)
art <- artStyle
else
art <- .gsub2(tilePatt,"\\1",style)
# print(art);q()
# proj <- "merc"
}
canUrl <- length(unlist(regmatches(style,gregexpr("\\{[xyz]\\}",style))))==3
isSAScache <- FALSE
if (!canUrl) {
sascache <- style
if (!length(ind <- which(dir.exists(sascache))))
sascache <- file.path(getOption("SAS_Planet_cache"),style)
if (length(ind <- which(dir.exists(sascache)))>0) {
list1 <- dir(path=sascache[ind],pattern="\\.sqlitedb$",recursive=TRUE)
canUrl <- length(list1)>0
isSAScache <- TRUE
art <- "sascache"
}
}
# str(list(art=art,style=style))
# q()
if ((art=="none")&&(length(style)==1)&&
(requireNamespace("leaflet",quietly=.isPackageInUse()))&&
(requireNamespace("leaflet.providers",quietly=.isPackageInUse()))) {
# p <- leaflet::providers
cname <- file.path(.ursaCacheDir(),"leaflet_providers.rds")
if (!file.exists(cname)) {
p <- try(leaflet.providers::get_providers())
if (!inherits(p,"try-error"))
saveRDS(p,cname)
}
if (file.exists(cname))
p <- readRDS(cname)$providers_details
osmCr <- p$'OpenStreetMap'$options$attribution
osmCr <- gsub("(^.*)(<a\\s.+>)(.+)(</a>)(.*$)","\\1\\3\\5",osmCr)
osmCr <- gsub("©","\uA9",osmCr)
# style <- "Stadia" ## devel
spatt <- "^(\\w+)(\\.(\\w+))*$"
style1 <- gsub("^(\\S+)(\\s+\\S+)*$","\\1",style)
s1 <- gsub(spatt,"\\1",style1)
s2 <- gsub(spatt,"\\3",style1)
if (devel <- TRUE) {
if (s1 %in% names(p)) {
p1 <- p[[s1]]
sUrl <- p1$url
isExt <- grepl("\\{ext\\}",sUrl)
o1 <- p1$options
if ((!nchar(s2))&&(grepl("\\{variant\\}",sUrl))&&(length(p1$variants))) {
if ("variant" %in% names(o1)) {
a <- sapply(p1$variants,function(x) {
if (is.character(x))
return(x)
x$options$variant
})
s2 <- names(a)[match(o1$variant,a)]
}
else
s2 <- sample(names(p1$variants),1)
}
if (nchar(s2)>0) {
p2 <- p1$variants[[s2]]
if (is.character(p2))
o2 <- list(variant=p2)
else {
o2 <- p2$options
if (!"variant" %in% names(o2))
o2$variant=s2
}
for (oname in names(o2)) {
if (oname=="attribution") {
o1[[oname]] <- gsub(paste0("\\{attribution\\.",s1,"\\}")
,o1[[oname]],o2[[oname]])
}
else
o1[[oname]] <- o2[[oname]]
}
}
sCr <- NULL
for (oname in names(o1)) {
patt <- paste0("(^.*)(\\{",oname,"\\})(.*$)")
if (!grepl(patt,sUrl))
next
if (grepl("<insert.+here>",o1[[oname]])) {
sCr <- c(sCr,oname)
next
}
sUrl <- gsub(patt,paste0("\\1",o1[[oname]],"\\3"),sUrl)
}
if (grepl("\\{s\\}",sUrl)) {
if (!is.null(p1$options$subdomains))
sdomain <- p1$options$subdomains
else
sdomain <- "abc"
sUrl <- gsub("\\{s\\}",paste0("{",sdomain,"}"),sUrl)
}
sAttr <- o1$attribution
t1 <- unlist(gregexpr("<",sAttr))
t2 <- unlist(gregexpr(">",sAttr))
if ((length(t1)>0)&&(length(t1)==length(t2))) {
t2 <- c(1,t2+1)
t1 <- c(t1-1,nchar(sAttr))
res <- character()
for (i in seq_along(t1))
res <- c(res,substr(sAttr,t2[i],t1[i]))
sAttr <- paste(res,collapse="")
sAttr <- gsub("©","\uA9",sAttr)
sAttr <- gsub("—","\u2014",sAttr)
}
sAttr <- gsub("\\{attribution\\.OpenStreetMap\\}",osmCr,sAttr)
if (isExt)
style <- c(sUrl,sAttr)
else
style <- c(sUrl,"png",sAttr)
if (length(sCr))
attr(style,"credentials") <- sCr
}
}
else { ## to deprecate
if (s1 %in% names(p)) {
p1 <- p[[s1]]
sUrl <- p1$url
##~ cat('p1:--------\n')
##~ str(p1)
##~ cat('-----------\n')
sAttr <- p1$options$attribution
t1 <- unlist(gregexpr("<",sAttr))
t2 <- unlist(gregexpr(">",sAttr))
if ((length(t1)>0)&&(length(t1)==length(t2))) {
t2 <- c(1,t2+1)
t1 <- c(t1-1,nchar(sAttr))
res <- character()
for (i in seq_along(t1))
res <- c(res,substr(sAttr,t2[i],t1[i]))
sAttr <- paste(res,collapse="")
sAttr <- gsub("©","\uA9",sAttr)
sAttr <- gsub("—","\u2014",sAttr)
}
sAttr <- gsub("\\{attribution\\.OpenStreetMap\\}",osmCr,sAttr)
if (nchar(s2)>0) {
if (s2 %in% names(p1$variants)) {
p2 <- p1$variants[[s2]]
##~ cat('p2:--------\n')
##~ str(p2)
##~ cat('-----------\n')
if (is.list(p2)) {
if (!is.null(p2$url))
sUrl <- p2$url
if (isExt <- grepl("\\{ext\\}",sUrl))
if (!is.null(p2$options$ext))
sUrl <- gsub("\\{ext\\}",p2$options$ext,sUrl)
if (grepl("\\{variant\\}",sUrl))
if (!is.null(p2$options$variant))
sUrl <- gsub("\\{variant\\}",p2$options$variant,sUrl)
}
else {
sUrl <- gsub("\\{variant\\}",p2,p1$url)
}
}
}
if (isExt <- grepl("\\{ext\\}",sUrl))
if (!is.null(p1$options$ext))
sUrl <- gsub("\\{ext\\}",p1$options$ext,sUrl)
if (grepl("\\{variant\\}",sUrl))
if (!is.null(p1$options$variant))
sUrl <- gsub("\\{variant\\}",p1$options$variant,sUrl)
if (grepl("\\{s\\}",sUrl)) {
if (!is.null(p1$options$subdomains))
sdomain <- p1$options$subdomains
else
sdomain <- "abc"
sUrl <- gsub("\\{s\\}",paste0("{",sdomain,"}"),sUrl)
}
if (grepl("^//",sUrl))
sUrl <- paste0("https:",sUrl)
if (grepl("\\{attribution\\.OpenStreetMap\\}",sAttr))
sAttr <- gsub("\\{attribution\\.OpenStreetMap\\}",osmCr,sAttr)
# print(c(url=sUrl,attr=sAttr))
if (isExt)
style <- c(sUrl,sAttr)
else
style <- c(sUrl,"png",sAttr)
# art <- style
}
}
}
# str(list(art=art,style=style))
isStatic <- .lgrep("static",style)>0
# if ((!isStatic)&&("ursa" %in% loadedNamespaces())) {
# stop("Operation is prohibited: unable to display attribution.")
# }
len <- 640L
if (is.na(size[1]))
size <- c(len,len)
else if (is.character(size)) {
size <- as.integer(unlist(strsplit(
.gsub("(\\d+)\\D+(\\d+)","\\1 \\2",size),split="\\s")))
}
else if (is.numeric(size))
size <- rep(size,length=2)
if (is.numeric(size))
len <- as.integer(round(max(size)))
mlen <- switch(art,google=640,openstreetmap=960,sputnikmap=640)
if (isStatic) {
len[len>mlen] <- mlen
}
if (trytodeprecate20230723 <- TRUE) {
canUrl <- length(unlist(regmatches(style,gregexpr("\\{[xyz]\\}",style))))==3
if (!canUrl) {
sascache <- style
if (!length(ind <- which(dir.exists(sascache))))
sascache <- file.path(getOption("SAS_Planet_cache"),style)
if (length(ind <- which(dir.exists(sascache)))>0) {
list1 <- dir(path=sascache[ind],pattern="\\.sqlitedb$",recursive=TRUE)
canUrl <- length(list1)>0
}
}
}
isUrl <- .lgrep("^http(s)*://",style)>0 | canUrl
# canTile <- .lgrep(art,eval(as.list(args(".tileService()"))$server))>0
canTile <- isUrl | .lgrep(art,.tileService())>0 | canUrl
isTile <- .lgrep("tile",style)>0 & canTile
if ((!isStatic)&&(!isTile)) {
if (art %in% staticMap)
isStatic <- TRUE
else if (canTile)
isTile <- TRUE
else
art <- "none"
}
if ("ArcticSDI" %in% style)
art <- style
isPolar <- .lgrep("(polarmap|ArcticSDI|ArcticConnect)",art)>0
if ((isPolar)&&(!isTile))
isTile <- TRUE
# else if (isUrl)
# style <- "custom"
isColor <- if (isUrl) TRUE else .lgrep("colo(u)*r",style)>0
isGrey <- ifelse(isColor,FALSE,.lgrep("gr[ae]y(scale)*",style)>0)
if (isGrey)
isColor <- FALSE
isWeb <- .lgrep(tilePatt,art)>0 | isUrl
if (verbose)
print(data.frame(art=art,color=isColor,grey=isGrey,static=isStatic
,canTile=canTile,canUrl=canUrl,tile=isTile,web=isWeb
,row.names="geomap:"))
geocodeStatus <- FALSE
if (.isSP(loc)) {
proj4 <- sp::proj4string(loc)
if (!.lgrep("\\+proj=longlat",proj4)) {
loc <- sp::bbox(loc)
if (length(loc)==6)
loc <- loc[c(1,2,4,5)]
loc <- c(.project(matrix(c(loc),ncol=2,byrow=TRUE),proj4
,inv=TRUE))[c(1,3,2,4)]
}
}
else if (inherits(loc,c("sf","bbox"))) {
if (inherits(loc,"sf"))
loc <- sf::st_bbox(loc)
proj4 <- attr(loc,"crs")$proj4string
# if (proj4!="+proj=longlat +datum=WGS84 +no_defs")
if (!.lgrep("\\+proj=longlat",proj4))
loc <- c(.project(matrix(loc,ncol=2,byrow=TRUE),proj4
,inv=TRUE))[c(1,3,2,4)]
}
isWMS <- isUrl & .is.wms(style)
notYetGrid <- TRUE
g3 <- NULL
if ((TRUE)||(isWMS)) {
if (is.null(loc)) {
border <- 0
g3 <- g0 <- getOption("ursaSessionGrid")#session_grid()
notYetGrid <- is.null(g0)
if (notYetGrid)
loc <- c(-179,-82,179,82)
else {
if (!is.na(g0$retina)) {
g0 <- regrid(g0,mul=1/g0$retina)
retina <- g0$retina
}
else
retina <- 1
loc <- with(g0,.project(rbind(c(minx,miny),c(maxx,maxy)),crs,inv=TRUE))
loc <- c(loc)[c(1,3,2,4)]
if ((isPolar)&&(loc[1]>loc[3]))
loc <- loc[c(3,2,1,4)]
}
}
if (!((is.numeric(loc))&&(length(loc) %in% c(4,2)))) {
loc <- try(.geocode(loc,service=geocode,place=place,area="bounding"
,select="top",verbose=verbose))
if (inherits(loc,"try-error")) {
geocode <- switch(geocode,google="nominatim",nominatim="google")
loc <- try(.geocode(loc,service=geocode,place=place,area="bounding"
,select="top",verbose=verbose))
}
if (!inherits(loc,"try-error"))
geocodeStatus <- TRUE
else {
cat(geterrmessage())
return(NULL)
}
}
if ((is.numeric(loc))&&(length(loc) %in% c(2)))
geocodeStatus <- TRUE
# copyright <- attr(.tileService()(),"copyright")[art]
# str(unname(loc),digits=8)
if (length(loc)==2)
bbox <- c(loc,loc)
else
bbox <- loc
# size <- c(640,640)
B0 <- 6378137
B <- B0*pi
x <- B*bbox[c(1,3)]/180
cross180 <- x[1]>x[2]
if (cross180) {
x[1] <- x[1]-2*B
lon_0 <- round(180*mean(x)/B,6)
}
else if ((TRUE)&&(!is.null(g3))&&(.lgrep("\\+proj=(merc|laea)",g0$crs))) ## ++20180325
lon_0 <- as.numeric(.gsub(".*\\+lon_0=(\\S+)\\s.*","\\1",g0$crs))
else
lon_0 <- round(180*mean(x)/B,6)
if (isPolar) {
# 180\{deg}W, 150\{deg}W, 100\{deg}W, 40\{deg}W, 10\{deg}E, and 90\{deg}E.
lon_0[lon_0<(-165) || lon_0>=(+135)] <- -180
lon_0[lon_0>=(-165) && lon_0<(-125)] <- -150
lon_0[lon_0>=(-125) && lon_0<(-70)] <- -100
lon_0[lon_0>=(-70) && lon_0<(-25)] <- -40
lon_0[lon_0>=(-25) && lon_0<(+50)] <- 10
lon_0[lon_0>=(50) && lon_0<(+135)] <- 90
proj4 <- paste("+proj=laea +lat_0=90",paste0("+lon_0=",lon_0)
,"+x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs")
if (bbox[3]<bbox[1])
bbox[3] <- bbox[3]+360
obj <- matrix(bbox[c(1,2,1,4,3,4,3,2,1,2)],ncol=2,byrow=TRUE)
if (TRUE) {
x <- obj[,1]
y <- obj[,2]
n <- 3# 256
x <- c(seq(x[1],x[2],len=n),seq(x[2],x[3],len=n)
,seq(x[3],x[4],len=n),seq(x[4],x[5],len=n))
y <- c(seq(y[1],y[2],len=n),seq(y[2],y[3],len=n)
,seq(y[3],y[4],len=n),seq(y[4],y[5],len=n))
bbox <- cbind(x,y)
}
bbox <- .project(bbox,proj4)
bbox <- c(xmin=min(bbox[,1]),ymin=min(bbox[,2])
,xmax=max(bbox[,1]),ymax=max(bbox[,2]))
res <- max(c((bbox["xmax"]-bbox["xmin"])/size[1]
,(bbox["ymax"]-bbox["ymin"])/size[2]))
if (!FALSE) ## PolarMap.js
B <- 11000000+9036842.762+667
else
B <- 6378137*pi
s <- 2*B/(2^(1:19+8))
}
else {
if (isWGS84)
proj4 <- paste("+proj=merc",paste0("+lon_0=",lon_0)
,"+k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs")
else
proj4 <- paste("+proj=merc +a=6378137 +b=6378137"
,"+lat_ts=0.0",paste0("+lon_0=",lon_0)
,"+x_0=0.0 +y_0=0 +k=1.0"
,"+units=m +nadgrids=@null +wktext +no_defs")
bbox <- matrix(bbox,ncol=2,byrow=TRUE)
bbox <- .project(bbox,proj4,verbose=verbose)
bbox <- c(xmin=bbox[1,1],ymin=bbox[1,2],xmax=bbox[2,1],ymax=bbox[2,2])
if (bbox[1]>bbox[3]) { ## ++ 20180718
bbox <- bbox[c(3,2,1,4)]
names(bbox) <- c("xmin","ymin","xmax","ymax")
}
res <- max(c((bbox["xmax"]-bbox["xmin"])/size[1]
,(bbox["ymax"]-bbox["ymin"])/size[2]))
s <- 2*6378137*pi/(2^(1:21+8))
}
if (!notYetGrid) {
res0 <- with(g0,sqrt(resx*resy))
zoom0 <- which.min(abs(s-res0))
}
else
zoom0 <- -99
zman <- zoom
zoom <- which.min(abs(s-res))
fixRes <- FALSE
for (i in seq(max(zoom0,zoom+1),1,by=-1)) {
if (i<1)
break
res <- s[i]
if (FALSE) { ## 20170918
g0 <- regrid(ursa_grid(),res=res,crs=proj4,border=border
,setbound=unname(bbox[c("xmin","ymin","xmax","ymax")]))
}
else {
g0 <- regrid(ursa_grid(),res=res,crs=proj4
,setbound=unname(bbox[c("xmin","ymin","xmax","ymax")]))
g0 <- regrid(g0,border=border)
}
# print(data.frame(res0=res0,res=res,i=i,border=border,notYetGrid=notYetGrid))
if (!notYetGrid) {
if (identical(res0,res)) {
fixRes <- TRUE
break
}
if (softmatching <- TRUE) {
if (abs(res/res0-1)<1*1e-5) {
fixRes <- TRUE
break
}
}
}
else if ((g0$columns<=size[1])&&(g0$rows<=size[2]))
break
}
if ((isPolar)&&(!notYetGrid)) { ## more accurate checking is required
m1 <- gsub(".*\\+proj=laea\\s.+\\+lon_0=(\\S+)\\s.*","\\1",g0$crs)
m2 <- gsub(".*\\+proj=laea\\s.+\\+lon_0=(\\S+)\\s.*","\\1",g3$crs)
m3 <- !is.na(.is.near(g0$resx,g3$resx))
m4 <- !is.na(.is.near(g0$resy,g3$resy))
m <- m1==m2 & m3 & m4
if (m)
g0 <- g3
}
if ((art=="sputnikmap")&&(!isTile))
g0 <- regrid(regrid(g0,mul=1/2),mul=2,border=-1) ## even cols/rows
zoom <- i
if ((is.numeric(zman))&&(zman<=0))
zman <- as.character(zman)
if (is.numeric(zman))
zman <- round(zman)
else if (is.character(zman)) { ## "+1" "---"
zpos <- .grep("\\+",zman,value=TRUE)
zneg <- .grep("\\-",zman,value=TRUE)
if (.lgrep("^(\\+|\\-)\\d$",zman)) {
zman <- eval(parse(text=paste0(zoom,zman)))
}
else if ((length(zpos))&&(zman==zpos)) {
zman <- zoom+nchar(zman)
}
else if ((length(zneg))&&(zman==zneg)) {
zman <- zoom-nchar(zman)
}
else {
zman <- round(as.numeric(zman))
if (zman==0)
zman <- zoom
}
if (zman>18)
zman <- 18
}
if (FALSE) {
pattZoom <- "(zoom=(\\d+))"
if (.lgrep(pattZoom,style))
zman <- as.integer(.gsub2(pattZoom,"\\2",style))
else
zman <- zoom
}
if ((art=="polarmap")&&(zman>9))
zman <- 9
if (zman!=zoom) {
if (verbose)
print(c(zoomAuto=zoom,zoomManual=zman))
m <- 2^(zoom-zman)
if (!fixRes) {
if (FALSE)
g0 <- regrid(g0,mul=1/m,expand=m)
else {
bbox <- with(g0,c(minx,miny,maxx,maxy))
m2 <- if (m<1) 1 else with(g0,sqrt((maxx-minx)*(maxy-miny)))/2
# print(c(m=m,m2=m2,expand=m*m2))
g0 <- regrid(g0,mul=1/m,bbox=bbox+c(-1,-1,1,1)*m*m2)
}
}
else {
g0 <- regrid(g0,mul=1/m)
}
zoom <- zman
}
if ((TRUE)&&(geocodeStatus)) { ## <-- is this good feature to expand to 640x640?
x0 <- (g0$minx+g0$maxx)/2
y0 <- (g0$miny+g0$maxy)/2
minx <- x0-g0$resx*size[1]/2
maxx <- x0+g0$resx*size[1]/2
miny <- y0-g0$resy*size[2]/2
maxy <- y0+g0$resy*size[2]/2
g0 <- regrid(g0,minx=minx,maxx=maxx,miny=miny,maxy=maxy)
}
B <- 6378137*pi*(0.95+1*0.05)
if (g0$maxy>(+B))
g0 <- regrid(g0,maxy=+B)
if (g0$miny<(-B))
g0 <- regrid(g0,miny=-B)
# if (border>0)
# g0 <- regrid(g0,border=border)
# print(fixRes)
# print(g0)
}
else {
g0 <- session_grid()
proj4 <- g0$crs
}
##~ cat("------------- geomap ---------------\n")
##~ print(g0)
##~ cat("------------- geomap ---------------\n")
cxy <- with(g0,c(minx+maxx,miny+maxy)/2)
center <- c(.project(cxy,proj4,inv=TRUE))
bound <- .project(with(g0,rbind(c(minx,miny),c(maxx,maxy))),g0$crs
,inv=TRUE)
xr <- with(g0,seq(minx,maxx,len=32))
yr <- rep(with(g0,(miny+maxy)/2),length(xr))
lr <- .project(cbind(xr,yr),g0$crs,inv=TRUE)[,1]
cross180 <- length(which(diff(lr)<0))
isRetina <- FALSE
mul <- NA
if (isTile) {
# proj <- c("cycle","mapsurfer","sputnik")[2]
if (isPolar) { # (art=="polarmap")
if (art %in% "ArcticSDI")
B <- 6378137*pi
else
B <- 11000000+9036842.762+667
dz <- 2^(zoom)
res <- 2*B/dz ## '2*' - patch
g1 <- regrid(ursa_grid(),setbound=c(-B,-B,B,B),res=res,proj=g0$crs)
session_grid(g1)
a <- ursa_new()
cr <- coord_xy(a,x=c(g0$minx,g0$maxx),y=c(g0$maxy,g0$miny))
# xy <- coord_cr(a,c=cr[1,],r=cr[2,])
cr <- cr-1
# g3 <- regrid(g1,bbox=c(xy[1,1]-1*g2$resx/2,xy[2,2]-1*g2$resy/2
# ,xy[1,2]+1*g2$resx/2,xy[2,1]+1*g2$resy/2))
# if (is3413)
# zoom <- zoom-1
seqc <- cr[1,1]:cr[1,2]
seqr <- cr[2,1]:cr[2,2]
tgr <- expand.grid(z=zoom,y=seqr,x=seqc,minx=NA,miny=NA,maxx=NA,maxy=NA)
xy <- coord_cr(a,c=tgr$x+1,r=tgr$y+1)
tgr$minx <- xy["x",]-res/2
tgr$maxx <- xy["x",]+res/2
tgr$miny <- xy["y",]-res/2
tgr$maxy <- xy["y",]+res/2
h <- sort(unique(tgr[,"x"]))
v <- sort(unique(tgr[,"y"]))
if (F & !.isPackageInUse())
cat("-=---------------------------------------------\n")
g1 <- with(g0,regrid(g1,bbox=c(minx,miny,maxx,maxy),crs=proj4
,zero="keep",verbose=F & !.isPackageInUse()))
if (F & !.isPackageInUse())
cat("-=---------------------------------------------\n")
if (TRUE) {
x <- seq(g1$minx,g1$maxx,by=g1$resx)
y <- seq(g1$miny,g1$maxy,by=g1$resy)
x <- range(x[which(!is.na(.is.near(x,sort(unique(c(tgr$minx,tgr$maxx))))))])
y <- range(y[which(!is.na(.is.near(y,sort(unique(c(tgr$miny,tgr$maxy))))))])
g1 <- regrid(g1,bbox=c(x[1],y[1],x[2],y[2]),res=ursa(g0,"cell"))
}
else
g1 <- regrid(g1,res=ursa(g0,"cell"))
}
else {
B0 <- 6378137
B <- B0*pi
dz <- 2^zoom
res <- 2*pi*B0/dz
dx0 <- lon_0*pi/180*B0
minx <- g0$minx+dx0
maxx <- g0$maxx+dx0
if (isWGS84)
epsgWeb <- paste("+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0"
,"+datum=WGS84 +units=m +no_defs")
else
epsgWeb <- paste("+proj=merc +a=6378137 +b=6378137"
,"+lat_ts=0.0 +lon_0=0.0"
,"+x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null"
,"+wktext +no_defs")
if (FALSE) {
g2 <- regrid(g0,res=2*pi*B0/dz)
xr <- with(g2,seq(minx,maxx,by=resx)[-1]-resx/2)+dx0
yr <- rev(with(g2,seq(miny,maxy,by=resy)[-1]-resy/2))
g2 <- regrid(g2,res=c(g0$resx,g0$resy),crs=g0$crs)
# g2 <- regrid(g2,minx=g2$minx-dx0,maxx=g2$maxx-dx0)
}
else {
g1 <- regrid(g0,setbound=c(minx,g0$miny,maxx,g0$maxy),proj=epsgWeb)
g1 <- regrid(g1,res=2*pi*B0/dz)
g1 <- regrid(g1,res=c(g0$resx,g0$resy),crs=g0$crs)
g1$minx <- g1$minx-dx0
g1$maxx <- g1$maxx-dx0
}
sx <- sort(c(c(minx,maxx)
,seq(-B*3,+B*3,by=2*B)))
sx <- sx[sx>=minx & sx<=maxx]
dx <- diff(sx)
dr <- 3+2*zoom
yr <- with(g0,seq(maxy,miny,len=dr))
t0 <- NULL
h <- NULL
for (j in seq_along(dx)) {
tX <- NULL
xr <- seq(sx[j]+1e-6,sx[j+1]-1e-6,len=dr)
gr <- .project(as.matrix(expand.grid(x=xr,y=yr)),g0$crs,inv=TRUE)
gr[,1] <- gr[,1]-lon_0
# print(unique(gr[,1]))
# print(unique(gr[,2]))
if (isWGS84) {
for (i in seq(nrow(gr))) {
tX <- rbind(tX,.deg2numYa(lon=gr[i,1],lat=gr[i,2],zoom=zoom))
}
}
else {
for (i in seq(nrow(gr))) {
tX <- rbind(tX,.deg2num(lon=gr[i,1],lat=gr[i,2],zoom=zoom))
}
}
ind <- which(tX[,1]<0)
if (length(ind))
tX[ind,1] <- dz+tX[ind,1]
ind <- which(tX[,1]>=dz)
if (length(ind))
tX[ind,1] <- tX[ind,1]-dz
tX <- unique(tX)
hX <- unique(tX[,1])
# str(tX)
lon <- (c(head(hX,1),tail(hX,1))+c(0,1))/dz*360-180
# print(lon)
t0 <- rbind(t0,tX)
h <- c(h,hX)
if (j==1)
v <- unique(tX[,2])
}
dim1 <- unname(dim(g1)/256L)
dim2 <- c(length(v),length(h))
if (verbose) {
str(dim1)
str(dim2)
}
changeH <- !.is.eq(dim1[2],dim2[2]) # dim1[2]!=dim2[2]
changeV <- !.is.eq(dim1[1],dim2[1]) # dim1[1]!=dim2[1]
# changeDim <- !all(dim1==dim2)
tgr <- expand.grid(z=zoom,y=v,x=h)
n <- 2^zoom
lon1 = (tgr[,"x"]+0)/n*360-180
lon2 = (tgr[,"x"]+1)/n*360-180
lat1 = atan(sinh(pi*(1-2*(tgr[,"y"]+1)/n)))*180/pi
lat2 = atan(sinh(pi*(1-2*(tgr[,"y"]+0)/n)))*180/pi
xy1 <- .project(cbind(lon1,lat1),epsgWeb)
xy2 <- .project(cbind(lon2,lat2),epsgWeb)
tgr <- cbind(tgr
#,lon1=lon1,lat1=lat1,lon2=lon2,lat2=lat2
,minx=xy1[,1],miny=xy1[,2],maxx=xy2[,1],maxy=xy2[,2]
)
if (changeV) {
y <- sort(unique(c(xy1[,2],xy2[,2])))
nV <- dim1[1]+1
y0 <- seq(g1$miny,g1$maxy,len=nV)
ind <- na.omit(.is.near(y,y0))
if (length(ind)==nV) {
indY <- setdiff(seq_along(y),ind)
if (!anyNA(.is.near(sort(unique(xy1[,2])),y0)))
y <- xy2[,2]
else if (!anyNA(.is.near(sort(unique(xy2[,2])),y0)))
y <- xy1[,2]
else if (indY==4)
y <- xy2[,2]
else if (indY==1)
y <- xy1[,2]
else if (indY==3) { ## ++ 20180331 use case
y <- xy1[,2]
}
else if (indY==5) { #.geomap("Svalbard",style="mapnik")
y <- xy2[,2]
}
else
stop("extra vertical tile: no handler (#1)")
ind <- which(!is.na(.is.near(y,y0)))
tgr <- tgr[ind,]
v <- sort(unique(tgr[,"y"]))
}
else
stop("extra vertical tile: no handler (#2)")
}
if (changeH) {
## not appeared during tests
x <- sort(unique(c(xy1[,1],xy2[,1])))
nH <- dim1[1]+1
x0 <- seq(g1$minx,g1$maxx,len=nH)
ind <- na.omit(.is.near(x,x0))
if (length(ind)==nH) {
indX <- setdiff(seq_along(x),ind)
if (indX==4)
x <- xy2[,1]
else if (indX==1)
x <- xy1[,1]
else
stop("extra horizontal tile: no heandler (#1)")
ind <- which(!is.na(.is.near(x,x0)))
tgr <- tgr[ind,]
h <- sort(unique(tgr[,"x"]))
}
else
stop("extra horizontal tile: no handler (#2)")
}
}
igr <- expand.grid(y=seq_along(v)-1,x=seq_along(h)-1)
if (verbose) {
print(tgr)
}
tile <- if (isUrl) .tileService(style) else .tileService(art)
if (isPolar) {
epsg <- switch(as.character(lon_0),'-180'=3571,'180'=3571,'-150'=3572
,'-100'=3573,'-40'=3574,'10'=3575,'90'=3576
,stop("non-standard central longitude"))
tile$url <- .gsub("{l}",as.character(epsg),tile$url)
}
LL <- (isWMS) & (.lgrep("EPSG:(4326|4269)(\\D|$)",tile$url))
if (LL) { ## very rought 4236 -> 3857
x1 <- tgr$minx
y1 <- tgr$miny
x2 <- tgr$maxx
y2 <- tgr$maxy
tgr$minx <- tgr$lon1
tgr$miny <- tgr$lat1
tgr$maxx <- tgr$lon2
tgr$maxy <- tgr$lat2
tgr$lon1 <- x1
tgr$lat1 <- y1
tgr$lon2 <- x2
tgr$lat2 <- y2
}
img1 <- vector("list",nrow(tgr))
for (i in sample(seq(nrow(tgr)))) {
img1[[i]] <- .tileGet(z=zoom,x=tgr[i,"x"],y=tgr[i,"y"]
,minx=tgr[i,"minx"],miny=tgr[i,"miny"]
,maxx=tgr[i,"maxx"],maxy=tgr[i,"maxy"]
,retina=retina,url=tile$url
,fileext=tile$fileext,cache=cache,verbose=verbose)
}
nb <- sapply(img1,function(x) {
if (!is.array(x))
return(0)
dim(x)[3]
})
if (all(nb==0)) {
session_grid(g0)
stop("all tiles are failed")
opW <- options(warn=1)
warning("all tiles are failed")
# g2 <- session_grid()
# on.exit(session_grid(g2))
session_grid(g0)
return(NULL)
# return(ursa_new())
}
nbmax <- max(nb)
if (length(unique(nb))>1) {
img1 <- lapply(img1,function(x) {
if (!is.array(x))
return(x)
dima <- dim(x)
if (dima[3]==nbmax)
return(x)
dim(x) <- c(dima[1]*dima[2],dima[3])
if ((dima[3]==1)&&(all(c(x)==0)))
fv <- 0L
else
fv <- 255L
for (i in (dima[3]+1L):nbmax) {
x <- cbind(x,fv)
}
# apply(x,2,function(y) print(summary(y)))
dim(x) <- c(dima[1],dima[2],nbmax)
x
})
}
ind <- sapply(img1,function(x) length(dim(x))==3)
# str(lapply(img1,dim))
dimb <- apply(list2DF(lapply(img1[ind],dim)),1,max)
img <- array(0L,dim=c(dimb[1]*length(v),dimb[2]*length(h),nbmax))
for (i in sample(seq(nrow(tgr)))) {
# img[igr[i,"y"]*256L+seq(256),igr[i,"x"]*256+seq(256),] <- img2[,,1:3]
# img[igr[i,"y"]*256L+seq(256),igr[i,"x"]*256+seq(256),] <- img2[,,seq(nb)]
# img[igr[i,"y"]*256L+seq(256),igr[i,"x"]*256+seq(256),seq(nb)] <- img2[,,seq(nb)]
img2 <- img1[[i]]
dima <- dim(img2)
if (!length(dima))
next
if (inherits(img2,"try-error"))
next
if (!((dima[1]==dimb[1])&&(dima[2]==dimb[1]))) {
# .elapsedTime("everytime 0205a")
img2 <- as.array(regrid(as.ursa(img2),res=c(dima[1]/dimb[1],dima[2]/dimb[1])))
# .elapsedTime("everytime 0205b")
}
img[igr[i,"y"]*dimb[2]+seq(dimb[1]),igr[i,"x"]*dimb[2]+seq(dimb[1]),] <- img2
}
basemap <- as.ursa(img,aperm=TRUE,flip=TRUE)
if (FALSE) { ## already
str(g0$crs)
q()
lon0 <- .gsub2("\\+lon_0=(\\S+)\\s+","\\1",g0$crs)
crs <- paste0("+proj=merc +lon_0=",lon0," +k=1 +x_0=0 +y_0=0"
," +datum=WGS84 +units=m +no_defs")
g0$crs <- g1$crs <- crs
}
dimc <- dim(basemap)[1:2]
if (!identical(dim(g1),dimc)) {
mul <- sqrt(prod(dimc/dim(g1)))
# g1 <- regrid(g1,dim=dimc)
g1 <- regrid(g1,mul=mul)
g0 <- regrid(g0,mul=mul)
if (mul>2-1e-11)
isRetina <- TRUE
}
ursa(basemap,"grid") <- g1
# basemap <- as.integer(regrid(basemap,g0,resample=FALSE))
if (art=="zzzpolarmap") {
cat("------\n")
g6 <- regrid(g1,bbox=with(g0,c(minx,miny,maxx,maxy)),zero="node",verbose=TRUE)
print(g0,digits=12)
print(g6,digits=12)
# print(g1,digits=12)
q()
}
# cr <- coord_xy(basemap,x=101234,y=-1001234)
# print(coord_cr(basemap,c=cr[1,],r=cr[2,]),digits=12)
if (art=="polarmap") {
# str(g0)
# cat("-----------------------------------------\n")
g0 <- regrid(g1,bbox=with(g0,c(minx,miny,maxx,maxy)),zero="node")
}
if ((!is.na(mul))&&(mul>1)) {
g0$retina <- mul
}
# str(g1)
# str(g0)
# cat("-----------------------------------------\n")
basemap <- regrid(basemap,g0,resample=0)
if (F) {
str(identical(ursa_grid(basemap),g1))
str(g1)
str(g0)
q()
}
# cr <- coord_xy(basemap,x=101234,y=-1001234)
# print(coord_cr(basemap,c=cr[1,],r=cr[2,]),digits=12)
session_grid(basemap)
}
else { ## staticmap
php <- switch(art
,sputnikmap=paste0("http://static-api.maps.sputnik.ru/v1/"
,"?width={w}&height={h}&z={z}&clng={lon}&clat={lat}")
,google=paste0("https://maps.googleapis.com/maps/api/staticmap"
,"?center={lat},{lon}&zoom={z}&size={w}x{h}")
,openstreetmap=paste0("https://staticmap.openstreetmap.de/staticmap.php"
,"?center={lat},{lon}&zoom={z}&size={w}x{h}") ## &maptype=mapnik
)
# php <- switch(art,google="http://maps.googleapis.com/maps/api/staticmap"
# ,openstreetmap="http://staticmap.openstreetmap.de/staticmap.php")
isOSM <- .lgrep("openstreetmap",art)
if ((isGoogle <- .lgrep("google",art))&&(proposed <- TRUE)) {
apiKey <- getOption("googleMaps")
if (is.character(apiKey))
php <- paste0(php,"&key=",apiKey)
}
adv <- paste(.grep("=",unlist(strsplit(style,split="\\s+")),value=TRUE)
,collapse="&")
if ((isOSM)&&(cross180)) {
B0 <- 6378137
B <- B0*pi
minx <- g0$minx+lon_0*pi/180*B0
maxx <- g0$maxx+lon_0*pi/180*B0
sx <- sort(c(c(minx,maxx)
,seq(-B*3,+B*3,by=2*B)))
sx <- sx[sx>=minx & sx<=maxx]
dx <- diff(sx)
mx <- sx[-1]-dx/2
# print(sx)
# print(round(mx))
lon2 <- 180*mx/B
lon2[lon2<(-180)] <- lon2[lon2<(-180)]+360
lon2[lon2>(+180)] <- lon2[lon2>(+180)]-360
# print(g0$columns)
# print(g0$columns*dx/sum(dx))
col2 <- ceiling(g0$columns*dx/sum(dx))
if (sum(col2)!=g0$columns)
col2[cross180+1] <- g0$columns-sum(col2[seq(cross180)])
# print(col2)
img <- array(0,dim=c(g0$rows,g0$columns,3))
for (i in seq(cross180+1)) {
src <- php
src <- .gsub("{w}",col2[i],src)
src <- .gsub("{h}",g0$rows,src)
src <- .gsub("{lon}",round(lon2[i],11),src)
src <- .gsub("{lat}",round(center[2],11),src)
src <- .gsub("{z}",zoom,src)
if (nchar(adv)) {
# src <- paste0(src,"&",adv)
s1 <- .args2list(.gsub("&"," ",src))
s2 <- .args2list(.gsub("&"," ",adv))
ind <- match(names(s2),names(s1))
ind1 <- which(!is.na(ind))
if (length(ind1))
s1[na.omit(ind)] <- s2[ind1]
ind2 <- which(is.na(ind))
if (length(ind2))
s1 <- c(s1,s2[ind2])
src <- unlist(s1)
src <- .gsub("^=","",paste(names(src),src,sep="=",collapse="&"))
}
# fname <- tempfile()
# download.file(src,fname,mode="wb",quiet=!verbose)
fname <- .ursaCacheDownload(src,mode="wb"
,quiet=!verbose
)
j <- if (i==1) 0 else sum(col2[seq(i-1)])
img[,j+seq(col2[i]),] <- png::readPNG(fname)
# file.remove(fname)
}
basemap <- as.integer(255*as.ursa(img,aperm=TRUE,flip=TRUE))
}
else {
center <- round(center,11)
src <- php
src <- .gsub("{w}",g0$columns,src)
src <- .gsub("{h}",g0$rows,src)
src <- .gsub("{lon}",format(center[1],scientific=FALSE),src)
src <- .gsub("{lat}",format(center[2],scientific=FALSE),src)
src <- .gsub("{z}",zoom,src)
if (nchar(adv)) {
# src <- paste0(src,"&",adv)
s1 <- .args2list(.gsub("&"," ",src))
s2 <- .args2list(.gsub("&"," ",adv))
ind <- match(names(s2),names(s1))
ind1 <- which(!is.na(ind))
if (length(ind1))
s1[na.omit(ind)] <- s2[ind1]
ind2 <- which(is.na(ind))
if (length(ind2))
s1 <- c(s1,s2[ind2])
src <- unlist(s1)
src <- .gsub("^=","",paste(names(src),src,sep="=",collapse="&"))
}
if (cache)
fname <- .ursaCacheDownload(src,mode="wb"
,headers=list(#'Referer Page'="https://www.r-project.org"
'referfer'="r-ursa package"
)
,quiet=!verbose)
else {
fname <- tempfile()
download.file(src,fname,mode="wb"
,quiet=!verbose)
}
basemap <- as.integer(255L*as.ursa(png::readPNG(fname)
,aperm=TRUE,flip=TRUE))
if (!cache)
file.remove(fname)
}
mul2 <- unique(c(ursa_ncol(basemap)/ursa_ncol(g0)
,ursa_nrow(basemap)/ursa_nrow(g0)))
if (length(mul2)==1) {
g0 <- regrid(g0,mul=mul2)
}
ursa(basemap,"grid") <- g0
}
if (isGrey) {
basemap <- as.integer(round(sum(basemap*c(0.30,0.59,0.11))))
basemap <- colorize(basemap,minvalue=0,maxvalue=255,pal=c("black","white"))
}
if (isTile)
attr(basemap,"copyright") <- tile$copyright
else {
if (art=="sputnikmap")
attr(basemap,"copyright") <- paste("\uA9 OpenStreetMap contributors,"
,"\u0421\u043F\u0443\u0442\u043D\u0438\u043A","\uA9"
,"\u0420\u043E\u0441\u0442\u0435\u043B\u0435\u043A\u043E\u043C")
else
attr(basemap,"copyright") <- " "
}
# if ((FALSE)&&(!is.na(mul))&&(mul>1)) ## ++ 20200906
# g0 <- regrid(g0,mul=1/mul)
if (isRetina)
g0$retina <- mul
session_grid(g0)
ursa(basemap,"nodata") <- NA
if (isRetina)
attr(basemap,"retina") <- TRUE
basemap
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/xxx.geomap.R
|
'.isopleth' <- function(obj,engine=c("native","sf","sp")
,target=c("polygon","contour","both")
,multi=!FALSE
,...) {
if (!is_ursa(obj))
return(invisible(NULL))
if (length(obj)>1) {
ret <- do.call(spatial_bind,lapply(seq(obj),function(i)
.isopleth(obj=obj[i],engine=engine,target=target,...)))
return(ret)
}
verbose <- T
isColored <- T
# volume <- T
engine <- match.arg(engine)
target <- match.arg(target)
isContour <- !("polygon" %in% target)
isPolygon <- !("contour" %in% target)
# engine <- c("sf","sp")[2]
if (engine=="sp") {
isSF <- FALSE
isSP <- TRUE
}
else if (engine=="sf") {
isSF <- requireNamespace("sf",quietly=.isPackageInUse())
isSP <- !isSF
}
else {
loaded <- loadedNamespaces() # .loaded()
if ("sf" %in% loaded)
isSF <- TRUE
else if (("sp" %in% loaded)||("rgdal" %in% loaded))
isSF <- FALSE
else
isSF <- requireNamespace("sf",quietly=.isPackageInUse())
isSP <- !isSF
}
if ((!is.na(verbose))&&(verbose))
print(c(isSP=isSP,isSF=isSF,polygon=isPolygon,contour=isContour))
res <- .panel_contour(obj,category=isColored,...)
cl <- with(res,contourLines(x,y,z,levels=lev))
da <- data.frame(name=names(obj),level=sapply(cl,function(z) {z$level}))
lev <- sort(unique(sapply(cl,function(z) {z$level})))
# print(lev)
if (isSF) {
if (devel <- !TRUE) {
sa <- lapply(lev,function(l) {
str(cl[da$level %in% l])
q()
ch <- lapply(cl[da$level %in% l],function(z) {
a <- try(sf::st_polygon(list(cbind(z$x,z$y))))
})
# str(ch)
q()
ind <- which(!sapply(ch,inherits,"try-error"))
sa2 <- try(sf::st_multipolygon(lapply(cl[da$level %in% l][ind],function(z)
list(cbind(z$x,z$y)))))
str(sa2)
q()
})
str(cl)
q()
}
if (isPolygon) {
if (multi) {
sa <- lapply(lev,function(l) {
a <- try(sf::st_multipolygon(lapply(cl[da$level %in% l],function(z) {
list(cbind(z$x,z$y))
})))
if (inherits(a,"try-error"))
return(NULL)
a
})
}
else {
stop("polygons, not multi")
}
sa <- sa[sapply(sa,function(x) !is.null(x))]
if (!length(sa))
isPolygon <- FALSE
else
sa <- sf::st_sfc(sa,crs=ursa_crs(obj))
}
if (isContour) {
if (multi)
sl <- lapply(lev,function(l)
sf::st_multilinestring(lapply(cl[da$level %in% l],function(z)
cbind(z$x,z$y))))
else {
sl <- lapply(lev,function(l) {
ch <- lapply(cl[da$level %in% l],function(z) {
a <- sf::st_linestring(cbind(z$x,z$y))
a
})
})
sl <- do.call(c,sl)
}
sl <- sf::st_sfc(sl,crs=ursa_crs(obj))
}
}
else if (isSP) {
if (isPolygon) {
sa <- lapply(lev,function(l)
sp::Polygons(lapply(cl[which(da$level %in% l)],function(z)
sp::Polygon(cbind(z$x,z$y))),l))
sa <- sp::SpatialPolygons(sa,proj4string=sp::CRS(ursa_crs(obj)))
}
if (isContour) {
sl <- lapply(lev,function(l)
sp::Lines(lapply(cl[which(da$level %in% l)],function(z)
sp::Line(cbind(z$x,z$y))),l))
sl <- sp::SpatialLines(sl,proj4string=sp::CRS(ursa_crs(obj)))
}
}
if (multi)
da <- data.frame(name=names(obj),level=lev)
if (isPolygon)
spatial_data(sa) <- da
if (isContour)
spatial_data(sl) <- da
##~ print(spatial_area(sa)*1e-6)
##~ print(spatial_length(sl)*1e-3)
##~ print(spatial_geotype(sa))
##~ print(spatial_geotype(sl))
##~ .elapsedTime("B")
# spatial_write(sl,"res2_isopleth.geojson")
# spatial_write(sa,"res2_polygon.geojson")
# glance(sl)
if (F) {
rm(sl)
sl <- spatial_read("res2")
print(spatial_area(sl)*1e-6)
print(spatial_length(sl)*1e-3)
q()
str(da)
}
# if ((isPolygon)&&(target %in% "polygon"))
# return(sa)
# if ((isContour)&&(target %in% "contour"))
# return(sl)
if ((isContour)&&(isPolygon))
return(list(polygon=sa,contour=sl))
if (isContour)
return(sl)
if (isPolygon)
return(sa)
NULL
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/xxx.isopleth.R
|
# https://gis.stackexchange.com/questions/382131/r-how-to-write-crs-information-correctly-to-netcdf
'.read_nc' <- function(fname,var="",level=NA,verbose=FALSE) {
if (!is.character(fname))
return(NULL)
if (!requireNamespace("ncdf4",quietly=.isPackageInUse())) {
stop("package 'ncdf4' is required for reading NetCDF")
# return(NULL)
}
if (isZip <- .lgrep("\\.zip$",fname)>0) {
ziplist <- unzip(fname,exdir=tempdir());on.exit(file.remove(ziplist))
fname <- .grep("\\.(nc)$",ziplist,value=TRUE)
}
else if ((nchar(Sys.which("gzip")))&&
(isZip <- (isZip1 <- .lgrep("\\.gz$",fname)>0) ||
(isZip2 <- file.exists(paste0(fname,".gz"))))) {
# print(c(isZip1=isZip1,isZip2=isZip2))
# stop("A")
if (isZip1)
fname0 <- fname
else if (isZip2)
fname0 <- paste0(fname,".gz")
if (FALSE) {
fname <- tempfile()
# on.exit(file.remove(fname))
system2("gzip",c("-f -d -c",.dQuote(fname0)),stdout=fname,stderr=FALSE)
}
else {
fname <- .ursaCacheRaster(fname0,unpack="gzip")
}
}
else if ((nchar(Sys.which("bzip2")))&&
(isZip <- (isZip1 <- .lgrep("\\.bz2$",fname)>0)||
(isZip2 <- file.exists(paste0(fname,".bz2"))))) {
if (isZip1)
fname0 <- fname
else if (isZip2)
fname0 <- paste0(fname,".bz2")
if (FALSE) {
fname <- tempfile()
# on.exit(file.remove(fname))
system2("bzip2",c("-f -d -c",.dQuote(fname0)),stdout=fname,stderr=FALSE)
}
else {
fname <- .ursaCacheRaster(fname0,unpack="bzip2")
}
}
else if (.lgrep("^(https|http|ftp)\\://",fname)) {
fname <- .ursaCacheDownload(fname,quiet=FALSE,mode="wb")
}
nc <- try(ncdf4::nc_open(fname,suppress_dimvals=FALSE))
if (inherits(nc,"try-error")) {
# cat(geterrmessage())
return(NULL)
}
on.exit({
ncdf4::nc_close(nc)
# if (isZip)
# file.remove(fname)
})
level0 <- level
var0 <- var
varList <- names(nc$var)
if (length(varList)<0) ## ==1
varName <- varList
else if (nchar(var))
varName <- .grep(var,varList,value=TRUE)
else
stop(paste("","-----","Please specify variable (argument 'var'):"
,paste(paste(seq(along=varList),". ",varList,sep=""),collapse="\n")
,"-----",sep="\n"))
toggle <- FALSE
if (!length(varName)) {
return(list())
}
res <- vector("list",length(varName))
names(res) <- varName
for (i in seq_along(res)) {
if (verbose)
print(varName[i])
# nc2 <- nc$var[[varName[i]]]
b <- .open_nc(nc,var=varName[i],grid=TRUE,verbose=FALSE)
indS <- attr(b,"spatial")
indT <- attr(b,"temporal")
bname <- names(b)
# indL <- .grep("^(lon|lat|x$|y$|west|east|south|north|time|proj4)"
# ,bname[-c(1,2)],inv=TRUE)
indL <- which(is.na(match(seq_along(bname),c(indS,indT))))
if (length(indL)>1)
stop("extra dimenstion?")
##~ str(b)
##~ str(indT)
##~ q()
if (!length(indL)) {
# print("B1")
res[[i]] <- .open_nc(fname,var=varName[i],verbose=verbose)[]
}
else {
# indL <- indL+2
if (i>1)
level <- level0
if ((length(level)==1)&&(is.na(level)))
level <- b[[indL]]
if ((length(indL))&&(length(level)>1)&&(!identical(level,level0))) {
# print("B2")
res2 <- vector("list",length(level))
names(res2) <- level
for (j in seq_along(level)) {
res2[[j]] <- .open_nc(fname,var=varName[i],level=level[j]
,verbose=verbose)[]
}
res[[i]] <- res2
rm(res2)
toggle <- TRUE
}
else {
# print("B3")
res[[i]] <- .open_nc(fname,var=varName[i],level=level
,verbose=verbose)[]
}
}
}
if ((length(varName)==1)&&(toggle))
return(res[[1]])
if (isDF <- all(sapply(res,inherits,"data.frame"))) {
res <- as.data.frame(unlist(unname(res),recursive=FALSE),check.names=FALSE)
name1 <- names(res)
name2 <- unique(name1)
ind <- match(name1,name2)
count <- table(ind) # names(count) <- name2
sameValue <- TRUE
for (i in seq_along(name2)) {
if (count[i]==1)
next
val <- unique(apply(as.matrix(res[ind==i]),1,function(x)
length(unique(x))))
if (length(val)>1) {
sameValue <- FALSE
break
}
}
if (!sameValue)
stop("variables have not the same dimension; not implemented")
ind <- match(name2,name1)
res <- res[,ind]
return(res)
}
res
}
'.open_nc' <- function(fname,var="",level=NA,grid=FALSE,verbose=FALSE) {
if (!requireNamespace("ncdf4",quietly=.isPackageInUse())) {
stop("package 'ncdf4' is required for reading NetCDF")
# return(NULL)
}
if (inherits(fname,"ncdf4"))
nc <- fname
else if (is.character(fname)) {
if (isZip <- .lgrep("\\.zip$",fname)>0) {
ziplist <- unzip(fname,exdir=tempdir());on.exit(file.remove(ziplist))
dsn <- .grep("\\.(nc)$",ziplist,value=TRUE)
}
else if ((nchar(Sys.which("gzip")))&&
(isZip <- (isZip1 <- .lgrep("\\.gz$",fname)>0) ||
(isZip2 <- file.exists(paste0(fname,".gz"))))) {
# print(c(isZip1=isZip1,isZip2=isZip2))
if (isZip1)
fname0 <- fname
else if (isZip2)
fname0 <- paste0(fname,".gz")
fname <- .ursaCacheRaster(fname0,unpack="gzip")
}
else if ((F)&&(nchar(Sys.which("gzip")))&&(isZip <- .lgrep("\\.gz$",fname)>0)) {
fname0 <- fname
fname <- tempfile();on.exit(file.remove(fname))
system2("gzip",c("-f -d -c",.dQuote(fname0)),stdout=fname,stderr=FALSE)
}
else if ((nchar(Sys.which("bzip2")))&&(isZip <- .lgrep("\\.bz2$",fname)>0)) {
fname0 <- fname
fname <- tempfile();on.exit(file.remove(fname))
system2("bzip2",c("-f -d -k",.dQuote(fname0)),stdout=fname,stderr=FALSE)
}
else if (.lgrep("^(http|https|ftp)://",fname)) {
fname <- .ursaCacheDownload(fname,mode="wb")
}
nc <- try(ncdf4::nc_open(fname,suppress_dimvals=FALSE))
if (inherits(nc,"try-error")) {
# cat(geterrmessage())
return(NULL)
}
on.exit({
ncdf4::nc_close(nc)
# if (isZip)
# file.remove(fname)
})
}
else
return(NULL)
# opW <- options(warn=0-!verbose) ## to prevent 'GeoTransform values not available'
varList <- names(nc$var)
##~ a <- ncvar_get(nc,"Times")
##~ print(a)
##~ q()
if (length(varList)==1)
varName <- varList
else if (!is.na(var)) {
varName <- .grep(var,varList,value=TRUE)
if (length(varName)>1)
varName <- .grep(paste0("^",var),varList,value=TRUE)
if (length(varName)>1)
varName <- .grep(paste0("^",var,"$"),varList,value=TRUE)
}
if (length(varName)!=1) {
if (!grid)
stop(paste("","-----","Please specify variable (argument 'var='):"
,paste(paste(seq(along=varList),". ",varList,sep=""),collapse="\n")
,"-----",sep="\n"))
else
varName <- varList[1]
}
att <- ncdf4::ncatt_get(nc,varName)
md <- nc$var[[varName]][c("size","dimids","prec","unlim")]
md$id <- md$dim <- NULL
if (length(att))
md <- c(md,'-------------'=NA,att)
if ((verbose)&&(1)) {
str(md)
}
if (FALSE) {
nc2 <- nc$var[[varName]]
val2 <- ncdf4::ncvar_get(nc,varName)
att2 <- ncdf4::ncatt_get(nc,varName) ## $flag_values $flag_meanings -> colortable
str(nc2)
str(val2)
str(att2)
q()
}
a <- nc$var[[varName]]$dim
if (is.null(a)) {
if (verbose)
message("scalar value")
if (grid)
return(list())
if (md$prec=="char") {
val2 <- att
}
else
val2 <- ncdf4::ncvar_get(nc,varName)
# attr(val2,"metadata") <- md
# ncdf4::nc_close(nc)
return(val2)
}
b <- vector("list",length(a))
names(b) <- lapply(a,function(x) x$name)
b[] <- lapply(a,function(x){
isTime <- ((length(x$units)>0)&&(.lgrep("\\ssince\\s",x$units)))
if ((!FALSE)&&(isTime)) {
y <- .ncdf_timeunits(x$val,x$units)
}
else
y <- x$val
y
})
# b$crs <- "" #ncdf4.helpers::nc.get.proj4.string(nc,varName)
if (length(md$dimids)<2) {
if (verbose)
message("one-dimensional variable")
val3 <- ncdf4::ncvar_get(nc,varName)
# attr(val3,"metadata") <- md
# ncdf4::nc_close(nc)
# print(val3)
return(val3)
}
bname <- names(b)
indX <- 1
indY <- 2
if (length(ind <- .grep("^(lon|x$|west|east)",bname)))
indX <- ind
else
indX <- 1L
if (length(ind <- .grep("^(y$|lat|south|north)",bname)))
indY <- ind
else
indY <- 2L
if ((length(indX)!=1)||(length(indY)!=1)||(indX[1]==indY[1])) {
if (verbose)
message('dimensional variables are not detected')
indX <- 1
indY <- 2
checkDim <- TRUE
}
else
checkDim <- FALSE
nonstandard <- !((.lgrep("^(x|y)$",bname)==2) |
(.lgrep("^(lon|lat)",bname)==2) |
(.lgrep("^(west|south)",bname)==2) |
(.lgrep("^(east|north)",bname)==2))
# att <- ncdf4::ncatt_get(nc,varName,attname=NA,verbose=FALSE)
# str(att)
if ((nonstandard)&&(verbose))
message(paste("non-standard dim names:"
,paste(sQuote(grep("^proj4$",bname,invert=TRUE,value=TRUE)),collapse=",")))
flip <- TRUE
permute <- FALSE
bY <- b[[indY]]
if ((is.numeric(bY))&&((all(diff(bY)<0))||(F & nonstandard))) {
flip <- FALSE
if (verbose)
message("flip - reverse second dim")
b[[indY]] <- rev(bY)
}
if (indX>indY) {
permute <- TRUE
if (verbose)
message("permute - transpose coordinates")
names(b)[c(indX,indY)] <- bname[c(indY,indX)]
b[c(indX,indY)] <- b[c(indY,indX)]
.ind <- indX
indX <- indY
indY <- .ind
rm(.ind)
}
indS <- c(indX,indY)
indT <- which(sapply(b,inherits,c("POSIXt","Date")))
if (!length(indT))
indT <- .grep("(time|^zzzday$)",bname)
indL <- which(is.na(match(seq_along(b),c(indS,indT))))
if ((!length(indT))&&(length(indL))) {
lev <- b[[indL]]
if (length(lev)>2) {
dl <- unique(diff(lev))
if (length(dl)==1) { ## considering that levels are not regular
indT <- indL
indL <- integer()
}
}
}
if (grid) {
# ncdf4::nc_close(nc)
attr(b,"spatial") <- indS
attr(b,"temporal") <- indT
return(b)
}
cond1 <- length(dim(b[[indX]]))>1 | length(dim(b[[indY]]))>1
cond2 <- (length(b[[indX]])<=2 | length(b[[indY]])<=2) & nonstandard
if (cond2) {
if (verbose)
message("truncated to two-columns/rows matrix")
val6 <- t(ncdf4::ncvar_get(nc,varName))
if (is.character(val6)) {
val6 <- c(val6)
names(val6) <- b[[indY]]
}
else {
dimnames(val6) <- list(as.character(b[[indY]]),as.character(b[[indX]]))
}
if (length(indT)) {
tu <- try(.ncdf_timeunits(val6,attr(b[[indT]],"units")))
if (!inherits(tu,"try-error")) {
dimv <- dimnames(val6)
dima <- dim(val6)
val6 <- as.character(tu)
dim(val6) <- dima
dimnames(val6) <- dimv
}
}
# if (length(indT))
# attr(val6,"time") <- b[[indT]]
return(val6)
}
if ((cond1)||(cond2)) {
if (verbose)
message("gridded dimension coordinates; coercing to data frame")
# x <- ncdf4::ncvar_get(nc,bname[1])
val5 <- ncdf4::ncvar_get(nc,varName)
da <- data.frame(x=c(b[[indX]]),y=c(b[[indY]]),z=c(val5))
names(da) <- c(bname[c(indX,indY)],varName)
if (length(indT))
attr(da,"time") <- b[[indT]]
return(da)
}
con <- .con.skeleton()
con$driver <- "NCDF"
con$offset <- nc$var[[varName]]$size
con$seek <- FALSE
if ((length(indT))&&(indT<=2)&&(length(indS)!=2)) {
if (verbose)
message("spatial coordinates cannot be detected")
val4 <- ncdf4::ncvar_get(nc,varName)
if (!TRUE) {
dima <- dim(val4)
val4 <- as.character(.ncdf_timeunits(val4,attr(b[[indT]],"units")))
dim(val4) <- dima
}
# attr(val2,"metadata") <- md
# ncdf4::nc_close(nc)
return(val4)
}
con$fname <- nc$filename
con$handle <- varName ## temporal hiding
# attr(con$handle,"var") <- varName
attr(con$handle,"flip") <- flip
attr(con$handle,"permute") <- permute
attr(con$handle,"spatial") <- indS
attr(con$handle,"temporal") <- indT
attr(con$handle,"level (proposed)") <- indL
#indL <- which(is.na(match(seq_along(b),c(indX,indY,indT,length(b)))))
# if ((!any(is.na(level)))&&(length(indL <- .grep("(level|zlev)",bname)))) {
# if ((!any(is.na(level)))&&(length(indL))) {
if (length(indL)) {
lev <- b[[indL]]
# print(c(levels=length(lev)))
w <- rep(0,length(lev))
if (anyNA(level))
level <- lev
if (length(level)>length(lev)) ## interval
lev2 <- lev[lev>=min(level) & lev<=max(level)]
else ## match
lev2 <- lev[match(level,lev)]
ind <- match(lev,lev2)
ind2 <- which(!is.na(ind))
if (length(ind2)>1) {
dl <- rowSums(matrix(c(0,rep(abs(diff(lev2)),times=2),0),ncol=2))
w[ind2] <- dl/sum(dl)
}
else if (length(ind2)==1)
w[ind2] <- 1
else {
lev1 <- tail(lev[lev>=level],1)
lev2 <- head(lev[lev<=level],1)
dl <- abs(diff(c(lev1,level,lev2)))
ind <- match(lev,c(lev1,lev2))
w[which(!is.na(ind))] <- rev(dl/sum(dl))
}
names(w) <- lev
attr(con$handle,"weight") <- w
}
if (verbose)
print(object.size(nc))
if (!is.null(b)) {
b$crs <- ""
g1 <- .grid.skeleton()
aname <- names(b)
indx <- .grep("^(x$|lon|west|east)",aname)
indy <- .grep("^(y$|lat|south|north)",aname)
if (((!length(indx))||(!length(indy)))&&(length(aname)>=2)) {
indx <- 1L
indy <- 2L
}
proj4 <- .grep("proj4",aname)
aname <- .grep("proj4",aname,value=TRUE,invert=TRUE)
indz <- which(is.na(match(seq_along(aname),c(indx,indy))))
if ((length(indx))&&(length(indy))) {
x <- b[[indx]]
y <- b[[indy]]
dx <- diff(x)
dy <- diff(y)
rx <- range(dx)
ry <- range(dy)
regx <- diff(rx)/mean(dx)
regy <- diff(ry)/mean(dy)
irregular <- (regx>0.5)||(regy>0.5)
if (irregular) {
message("Irregular grid","\n x:",round(regx,3)," y: ",round(regy,3))
}
##~ print(sd(diff(x)))
##~ print(sd(diff(y)))
g1$resx <- mean(unique(dx))
g1$resy <- mean(unique(dy))
g1$minx <- min(x)-g1$resx/2
g1$maxx <- max(x)+g1$resx/2
g1$miny <- min(y)-g1$resy/2
g1$maxy <- max(y)+g1$resy/2
g1$columns <- length(x)
g1$rows <- length(y)
if ((length(proj4))&&(nchar(b[[proj4]]))) {
g1$crs <- b[[proj4]] # code lost: 'g1$crs <- p'
}
else if (.lgrep("(lon|lat)",aname)==2)
g1$crs <- "+proj=longlat +datum=WGS84 +no_defs"
if (TRUE)
g1 <- with(g1,regrid(g1,setbound=c(minx,miny,maxx,maxy)
,dim=c(rows,columns)))
if (T & irregular) {
g1$seqx <- c(x)
g1$seqy <- c(y)
}
session_grid(g1)
con$samples <- g1$columns
con$lines <- g1$rows
if (length(indT)==1)
con$bands <- length(b[[indT]])
else
con$bands <- 1
con$indexC <- seq(g1$columns)
con$indexR <- seq(g1$rows)
con$indexZ <- seq(con$bands)
}
}
# a <- nc$var[[varName]]
con$nodata <- nc$var[[varName]]$missval
if (verbose)
str(b,digits=5)
res <- .raster.skeleton()
res$grid <- g1
res$con <- con
res$dim <- c(con$samples*con$lines,con$bands)
detail <- FALSE
if (length(indT)==1)
res$name <- as.character(b[[indT]])
else if (length(indL)==1) {
w2 <- w[w>0]
if (length(w2)==1)
res$name <- names(w2)
else
res$name <- varName
}
else {
# res$name <- as.character(b[[indL]])
if (length(ind <- .grep("long_name",names(att)))) {
res$name <- att[[ind]]
if (length(ind <- .grep("units",names(att))))
res$name <- paste0(res$name,", ",att[[ind]])
}
else
res$name <- varName
}
res
}
'.ncdf_timeunits' <- function(x,units) {
if (is.null(units))
return(x)
or <- .gsub2("\\D(\\d+-\\d+-\\d+)\\D+(\\d+:\\d+:\\d+(\\.\\d+)*)","\\1 \\2",units)
if (or==units)
or <- .gsub2("\\D(\\d+-\\d+-\\d+)","\\1",units)
if (or==units)
stop(paste("incorrect parsing for 'origin' detection:",dQuote(units)))
if (.lgrep("second(s)* since",units))
NULL
else if (.lgrep("minute(s)* since",units))
x <- x*60
else if (.lgrep("hour(s)* since",units))
x <- x*60*60
else if (.lgrep("day(s)* since",units))
x <- x*60*60*24
else if (.lgrep("month(s)* since",units))
x <- x*60*60*24*365.25/12
else if (.lgrep("since",units))
stop(paste("incorrect parsing for 'origin' detection:",dQuote(units)))
y <- as.POSIXct(x,origin=or,tz="UTC")
attr(y,"units") <- units
attr(y,"origin") <- or
class(y) <- c(class(y),"ursaTimeUnits")
y
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/xxx.ncdf.R
|
'.compose_wms' <- function(src
,version=""
,layers=""
,epsg=""
,format=""
,bbox="" #"{minx},{miny},{maxx},{maxy}"
,styles=""
,transparent=""
,legend="topright",gdalwarp=FALSE,tile=1024L
,size=800L,fail180=FALSE
,transpose=FALSE ## 'rotate' 'reorder' ?
,extend=TRUE
,cache=TRUE
,verbose=FALSE,...) {
isCache <- (is.logical(cache))&&(isTRUE(cache))||(is.character(cache))
src <- unlist(src)
# dst <- if (.isPackageInUse()) tempfile(fileext=".xml")
# else paste0(.argv0name(),".xml")
# dst <- tempfile(fileext=".xml")
# dst <- paste0(.argv0name(),".xml")
isMetadata <- FALSE
versionList <- c("1.1.1","1.3.0","1.1.0","1.0.0")
# if (nchar(version))
# version <- match.arg(version,versionList)
# else
# version <- versionList[1]
if (!.lgrep("\\?",src))
src <- paste0(src,"?")
else if (!.lgrep("\\?&",src))
src <- .gsub("\\?","?&",src)
toStop <- 0L
multiple <- FALSE
multiple <- all(layers==" ") #.lgrep("^\\s.$",layers)>0
ind1 <- .lgrep("&version=",src)==0 ## 'version' is not in request
ind2 <- nchar(as.character(version))>0 ## 'version' is set manually
if (ind2)
version <- match.arg(version,versionList)
else if (!ind1)
version <- .gsub(".+&version=(.+)(&|$)","\\1",src)
else
version <- "" #versionList[1]
if ((!ind1)&&(ind2)) {
src <- sapply(strsplit(src,split="&"),function(x)
paste(.grep("^version=",x,invert=TRUE,value=TRUE),collapse="&"))
}
else if (ind2)
src <- paste0(src,"&version=",as.character(version))
src1 <- unlist(strsplit(src,split="&"))
src1 <- .grep("^(bbox|request|service)=",src1,value=TRUE,invert=TRUE)
src1 <- paste0(paste(src1,collapse="&"),"&service=WMS&request=GetCapabilities")
ind1 <- .lgrep("&layer(s)*=",src)==0
ind2 <- if (!multiple) sum(nchar(layers)) else 0L
if ((ind1)||(ind2)) {
if (ind2) {
# layerString <- paste(layers,collapse=",")
# layers <- unlist(strsplit(layers,split=","))
if (!ind1) {
src <- unlist(strsplit(src,split="&"))
src <- paste(.grep("^layer(s)*=",src,invert=TRUE,value=TRUE),collapse="&")
}
src <- paste0(src,"&layers=",layers)
# src <- paste0(src,"&layers=",URLencode(URLencode(iconv(layers,to="UTF-8"))))
multiple <- length(layers)>1
}
else {
# src1 <- paste0(src,"&service=WMS&request=GetCapabilities")
# if (!file.exists(dst))
# download.file(src1,dst,mode="wt",quiet=!verbose)
# else if ((verbose)&&(!isMetadata))
# message(src1)
src1 <- gsub("\\?\\&","?",src1)
if (isCache)
dst <- .ursaCacheDownload(src1,mode="wt",cache=cache,quiet=!verbose)
else {
dst <- tempfile(fileext=".xml")
download.file(src1,dst,mode="wt",quiet=!verbose)
}
if (!isMetadata)
isMetadata <- TRUE
md <- .parse_wms(dst,verbose=verbose)
if (.lgrep("<ServiceException(>|\\s)",md)) {
message("Exception is found")
message(paste(md,collapse="\n"))
return(src)
}
ind1 <- .grep("<Layer(>|\\s)",md)
ind2 <- .grep("<Name(>|\\s)",md)
ind3 <- .grep("<Title(>|\\s)",md)
dist2 <- .dist2(cbind(x=ind1,y=0),cbind(x=ind2,y=0)
,verbose=FALSE,summarize=FALSE)
ind2a <- ind2[dist2$ind]
dist3 <- .dist2(cbind(x=ind2a,y=0),cbind(x=ind3,y=0)
,verbose=FALSE,summarize=FALSE)
ind3a <- ind3[dist3$ind]
desc <- data.frame(Layer=md[ind2a+1],Title=md[ind3a+1])
if (TRUE) {
desc <- unique(desc)
rownames(desc) <- NULL
}
n1 <- max(nchar(desc$Layer))
n2 <- max(nchar(desc$Title))
n <- 77-n1-n2
if (n<0)
desc$Title <- substr(desc$Title,1,n2+n)
# print(desc[sort(sample(nrow(desc),26)),],row.names=FALSE)
res <- data.frame(ind1=ind1,ind2=ind2a,dist=dist2$dist)
layers <- unique(md[res$ind2+1])
if (!multiple) {
message("Layers are not specified. Available layers (argument 'layers'):")
# print(layers,quote=!FALSE)
print(desc,row.names=FALSE)
# layers <- NULL
# stop("Layers are not specified")
toStop <- toStop+8L
}
else {
src <- paste0(src,"&layers=",layers)
}
}
}
else {
layers <- sapply(strsplit(src,split="&"),function(x)
.gsub(".+=(.+)","\\1",.grep("^layer(s)*=",x,value=TRUE)))
}
if (multiple)
sname <- layers
isSingle <- length(layers)==1L
if (isSingle)
src1 <- paste0(src1,"&layers=",layers)
ind <- .grep("&format=",src)
if (!length(ind)) {
if (nchar(format)) {
if (.lgrep("image",format))
src <- paste0(src,format)
else
src <- paste0(src,"&format=image/",format)
}
else {
# src1 <- paste0(sample(src,1),"&service=WMS&request=GetCapabilities")
# if (!file.exists(dst))
# download.file(src1,dst,mode="wt",quiet=!verbose)
# else if ((verbose)&&(!isMetadata))
# message(src1)
src1 <- gsub("\\?\\&","?",src1)
if (isCache)
dst <- .ursaCacheDownload(src1,mode="wt",cache=cache,quiet=!verbose)
else {
dst <- tempfile(fileext=".xml")
download.file(src1,dst,mode="wt",quiet=!verbose)
}
if (!isMetadata)
isMetadata <- TRUE
md <- .parse_wms(dst,verbose=verbose)
ind1 <- .grep("<GetMap>",md)
if (length(ind1)) {
ind2 <- .grep("</GetMap>",md)
ind2 <- ind2[ind2>=ind1][1]
md <- md[(ind1+1):(ind2-1)]
ind1 <- .grep("<Format>",md)
md <- md[ind1+1]
message("Image format is not specified. Available formats:")
print(md,quote=FALSE)
# md <- .gsub("image/png; mode=8bit","image/png8",md)
# md <- .gsub("image/png; mode=24bit","image/png24",md)
message("Supported formats (argument 'format'):")
patt <- "image/(png|pngX|pngXX|jpg|jpeg|tif|tiff|gif|bmp)$"
fmt <- .gsub(patt,"\\1",.grep(patt,md,value=TRUE))
print(fmt)
toStop <- toStop+1L
}
}
}
ind1 <- .lgrep("&styles=",src)==0
ind2 <- nchar(as.character(styles))>0
if ((ind1)||(ind2)) {
if (ind1) {
if (!ind2) {
src1 <- gsub("\\?\\&","?",src1) ## move to upper level
if (isCache)
dst <- .ursaCacheDownload(src1,cache=cache,mode="wt",quiet=!verbose)
else {
dst <- tempfile(fileext=".xml")
download.file(src1,dst,mode="wt",quiet=!verbose)
}
if (!isMetadata)
isMetadata <- TRUE
md <- .parse_wms(dst,verbose=verbose)
ind1 <- .grep("<Name(>|\\s)",md)
layer <- unlist(strsplit(paste(layers,collapse=","),split=","))#[1]
if (length(layer)==1) {
ind2 <- match(layer,md[ind1+1])
if (is.na(ind2))
indS <- integer()
else {
ind1 <- ind1[ind2]
ind2 <- .grep("</Layer>",md)
ind2 <- ind2[ind2>ind1][1]
md1 <- md[ind1:(ind2-1)]
# indS <- .grep("epsg:\\d+$",md1)#+ind1-1L
# epsgL <- unique(.gsub("^.*epsg:","",.grep("epsg",md1[indL],value=TRUE)))
ind1 <- .grep("<Style>",md1)
if ((length(ind1))&&(!anyNA(ind1))) {
ind2 <- .grep("<Name>",md1[ind1+1])
if (length(ind2)==length(ind1)) {
valueStyle <- md1[ind1+2]
message("Image style is not specified. Available formats:")
message("Supported values (argument 'styles'):")
print(valueStyle)
toStop <- toStop+16L
}
}
}
}
}
else {
src <- sapply(strsplit(src,split="&"),function(x)
paste(.grep("^style(s)*=",x,invert=TRUE,value=TRUE),collapse="&"))
}
}
src <- paste0(src,"&styles=",as.character(styles))
}
ind1 <- .lgrep("&transparent=",src)==0
ind2 <- nchar(as.character(transparent))>0
if ((ind1)||(ind2)) {
if ((ind1)&&(!ind2))
transparent <- "true"
if (!ind1) {
src <- sapply(strsplit(src,split="&"),function(x)
paste(.grep("^transparent=",x,invert=TRUE,value=TRUE),collapse="&"))
}
src <- paste0(src,"&transparent=",as.character(transparent))
}
ind <- .grep("&[cs]rs=",src)
if (!length(ind)) {
src1 <- gsub("\\?\\&","?",src1)
if (isCache)
dst <- .ursaCacheDownload(src1,mode="wt",cache=cache,quiet=!verbose)
else {
dst <- tempfile(fileext=".xml")
download.file(src1,dst,mode="wt",quiet=!verbose)
}
if (nchar(as.character(epsg))) {
if (!nchar(version)) {
md <- .parse_wms(dst,verbose=verbose)
version <- .gsub("^.+(version=(\")*(\\d\\.\\d\\.\\d)(\")*)\\s.+$","\\3"
,md[.grep("^<WMS_Capabilities",md)])
}
pref <- switch(version,'1.3.0'="crs",'x.x.x'="xxx","srs")
src <- paste0(src,"&",pref,"=EPSG:",epsg)
}
else {
# src1 <- paste0(sample(src,1),"&service=WMS&request=GetCapabilities")
# if (!file.exists(dst))
# download.file(src1,dst,mode="wt",quiet=!verbose)
# else if ((verbose)&&(!isMetadata))
# message(src1)
if (!isMetadata)
isMetadata <- TRUE
md <- .parse_wms(dst,verbose=verbose)
ind1 <- .grep("<Name(>|\\s)",md)
layer <- unlist(strsplit(paste(layers,collapse=","),split=","))#[1]
if (length(layer)==1) {
ind2 <- match(layer,md[ind1+1])
if (is.na(ind2))
indL <- integer()
else {
ind1 <- ind1[ind2]
ind2 <- .grep("</Layer>",md)
ind2 <- ind2[ind2>ind1][1]
md1 <- md[ind1:(ind2-1)]
indL <- .grep("epsg:\\d+$",md1)#+ind1-1L
epsgL <- unique(.gsub("^.*epsg:","",.grep("epsg",md1[indL],value=TRUE)))
}
}
else
indL <- integer()
if ((TRUE)||(!length(ind1))) { ## search global [sc]rs
# md1 <- md
ind1 <- .grep("<[CS]RS",md)
if (length(ind1)) {
indG <- ind1+1L
ind2 <- .grep("(epsg|[cs]rs):\\d+$",md[indG])
# if (length(ind2)!=length(indG))
# indG <- integer()
indG <- indG[ind2]
}
}
if (length(indG))
epsgG <- unique(.gsub("^.*epsg:","",.grep("epsg",md[indG],value=TRUE)))
else
epsgG <- character()
ind1 <- c(indL,indG)
cat("----------\n")
if (length(ind1)) {
epsgG <- unique(epsgG)
if (length(indL)) {
epsgL <- unique(epsgL)
epsg <- unique(c(epsgL,epsgG))
indM <- which(!is.na(match(epsg,epsgL)))
epsgG <- epsg
if (length(indM))
epsgG[indM] <- paste0(epsgG[indM],"*")
}
else
indM <- integer()
# epsg <- unique(.gsub("^.*epsg:","",.grep("epsg",md1[ind1],value=TRUE)))
message("SRS/CRS is not specified. Available ESPG codes (argument 'epsg'):")
print(epsgG,quote=FALSE)
if (length(indM))
message(paste("* is specified for layer",dQuote(layer)))
if (length(epsgG))
toStop <- toStop+2L
}
}
}
else {
epsg <- sapply(strsplit(src,split="&"),function(x)
.gsub(".+=EPSG:(.+)","\\1",.grep("^[cs]rs=",x,value=TRUE)))
}
layer <- unlist(strsplit(paste(layers,collapse=","),split=","))#[1]
arglist <- list(...)
if ((length(layer)==1)&&(extend | toStop)) {
# if (!file.exists(dst))
# download.file(src1,dst,mode="wt",quiet=!verbose)
# else if ((verbose)&&(!isMetadata))
# message(src1)
src1 <- gsub("\\?\\&","?",src1)
if (isCache)
dst <- .ursaCacheDownload(src1,mode="wt",cache=cache,quiet=!verbose)
else {
dst <- tempfile(fileext=".xml")
download.file(src1,dst,mode="wt",quiet=!verbose)
}
if (!isMetadata)
isMetadata <- TRUE
md <- .parse_wms(dst,verbose=verbose)
ind1 <- .grep("<Dimension",md)
ind2 <- .grep("<Extent",md)
if (length(ind2)>1) {
ind1a <- .grep("<Name(>|\\s)",md)
ind2a <- match(layer,md[ind1a+1])
ind1a <- ind1a[ind2a]
ind2a <- .grep("</Layer>",md)
ind2a <- ind2a[ind2a>ind1a][1]
md1 <- md[ind1a:(ind2a-1)]
ind2a <- .grep("<Extent",md1)
if (length(ind2a)==1) {
if (FALSE) {
ind2 <- ind1a+ind2a-1L
}
else {
md <- md1
ind1 <- .grep("<Dimension",md)
ind2 <- .grep("<Extent",md)
}
}
}
if (length(ind2))
dname2 <- tail(unlist(strsplit(md[ind2],split="\\s+")),-1)
if ((length(ind1)>1)&&(length(layer)==1)) {
ind7a <- grep(layer,md)
ind1 <- ind1[ind1>min(ind7a)][1]
##~ print(ind1)
##~ print(md[ind1])
##~ q()
}
if (length(ind1)) {
for (i in seq_along(ind1)) {
# if (i==2)
# next
dname <- tail(unlist(strsplit(md[ind1[i]],split="\\s+")),-1)
isInline <- .lgrep("/>",tail(dname,1))
if (!isInline)
dname <- head(dname,-1)
if (length(ind2)) {
# dname2 <- tail(head(unlist(strsplit(md[ind2],split="\\s+")),-1),-1)
if (length(na.omit(match(dname2,dname)))) {
dname <- unique(c(dname,dname2))
ind1[i] <- ind2
isInline <- FALSE
}
}
dname <- unname(sapply(dname,strsplit,split="="))
dname <- sapply(dname,function(x) gsub("(\"|>|/>)","",x))
if (is.list(dname)) {
dname <- dname[sapply(dname,length)==2]
dname <- t(matrix(c(unlist(dname)),ncol=2,byrow=TRUE))
}
# dname <- do.call("rbind",t(lapply(dname,data.frame)))
res <- dname[2,,drop=FALSE]
colnames(res) <- dname[1,]
rownames(res) <- " "
if (!isInline)
val <- unlist(strsplit(md[ind1[i]+1L],split=","))
else
val <- character()
# val <- c(head(val,3),tail(val,3))
varname <- res[,"name"]
ind3a <- .lgrep(paste0("&",varname,"="),src)>0
ind3b <- .lgrep(varname,names(arglist))>0
if (ind3a+ind3b==0) {
message(paste0("Optional attribute is found "
,"(argument '",res[,"name"],"')"
,ifelse(isInline,"",":")))
if (length(val)>12) {
message(paste("From:",paste(head(val,3),collapse=" ")))
message(paste("To: ",paste(tail(val,3),collapse=" ")))
}
else if (length(val))
message(paste("Values:",paste(val,collapse=" ")))
if (nrow(res)==1)
message(paste0(colnames(res)[2],": ",res[2]))
}
toStop <- toStop+0L
}
}
}
defineGrid <- is.null(getOption("ursaSessionGrid"))
if (toStop | defineGrid) {
# src1 <- paste0(sample(src,1),"&service=WMS&request=GetCapabilities")
# if (!file.exists(dst))
# download.file(src1,dst,mode="wt",quiet=!verbose)
# else if ((verbose)&&(!isMetadata))
# message(src1)
src1 <- gsub("\\?\\&","?",src1)
if (isCache)
dst <- .ursaCacheDownload(src1,mode="wt",cache=cache,quiet=!verbose)
else {
dst <- tempfile(fileext=".xml")
download.file(src1,dst,mode="wt",quiet=!verbose)
}
if (!isMetadata)
isMetadata <- TRUE
md <- .parse_wms(dst,verbose=verbose)
tryGrid <- 0L
layer <- unlist(strsplit(paste(layers,collapse=","),split=","))
if (length(layer)==1) {
ind1 <- .grep("<Name(>|\\s)",md)
ind2 <- match(layer,md[ind1+1])
if (is.na(ind2)) {
message("Layer ",dQuote(layer)," is not found")
# q()
}
else {
ind1 <- ind1[ind2]
ind2 <- .grep("</Layer>",md)
ind2 <- ind2[ind2>ind1][1]
md2 <- md[ind1:(ind2-1)]
ind <- .grep("(boundingbox)",md2)
if (length(ind))
md <- md2
}
}
ind1 <- .grep("<(EX_Geographic|LatLon)BoundingBox",md)
bboxLL <- FALSE
if (length(ind1)) {
minxI <- .grep("<westBoundLongitude>",md)
maxxI <- .grep("<eastBoundLongitude>",md)
minyI <- .grep("<southBoundLatitude>",md)
maxyI <- .grep("<northBoundLatitude>",md)
ind <- c(minxI,maxxI,minyI,maxyI)
if (length(na.omit(ind))==4) {
minx <- md[minxI+1L]
maxx <- md[maxxI+1L]
miny <- md[minyI+1L]
maxy <- md[maxyI+1L]
a <- as.numeric(c(minx,miny,maxx,maxy))
bboxLL <- TRUE
tryGrid <- tryGrid+1L
}
else {
if (length(ind1)>1) {
minx <- md[minxI[1L]+1L]
maxx <- md[maxxI[1L]+1L]
miny <- md[minyI[1L]+1L]
maxy <- md[maxyI[1L]+1L]
a <- as.numeric(c(minx,miny,maxx,maxy))
bboxLL <- TRUE
if (length(na.omit(a))==4)
tryGrid <- tryGrid+1L
}
if (length(ind1)>1) {
lim <- .gsub("[\"</>]"," ",md[ind1[1]])
minx <- .gsub2("minx\\s*=\\s*(\\S+)\\s","\\1",lim)
miny <- .gsub2("miny\\s*=\\s*(\\S+)\\s","\\1",lim)
maxx <- .gsub2("maxx\\s*=\\s*(\\S+)\\s","\\1",lim)
maxy <- .gsub2("maxy\\s*=\\s*(\\S+)\\s","\\1",lim)
if (!tryGrid) {
a <- as.numeric(c(minx,miny,maxx,maxy))
tryGrid <- tryGrid+1L
}
}
}
}
rot <- FALSE
if ((tryGrid==0)||(toStop)) {
if (length(epsg)>1) {
if ("4326" %in% as.character(epsg))
epsg <- "4326"
else
epsg <- sample(epsg,1)
}
if (!nchar(version)) {
version <- .gsub("^.+(version=(\")*(\\d\\.\\d\\.\\d)(\")*)\\s.+$","\\3"
,md[.grep("^<WMS_Capabilities",md)])
}
if ((version=="1.3.0")&&("4326" %in% as.character(epsg))) {
ind1 <- .grep(paste0("BoundingBox CRS=\"*CRS:84"),md)
if (length(ind1)) {
lim <- .gsub("[\"</>]"," ",md[ind1[1]])
minx3 <- .gsub2("minx\\s*=\\s*(\\S+)\\s","\\1",lim)
miny3 <- .gsub2("miny\\s*=\\s*(\\S+)\\s","\\1",lim)
maxx3 <- .gsub2("maxx\\s*=\\s*(\\S+)\\s","\\1",lim)
maxy3 <- .gsub2("maxy\\s*=\\s*(\\S+)\\s","\\1",lim)
a3 <- as.numeric(c(minx3,miny3,maxx3,maxy3))
rot <- TRUE
}
}
# else
# ind1 <- integer()
# if (!length(ind1))
ind1 <- .grep(paste0("BoundingBox [CS]RS=[\"]*EPSG:",epsg,"[\"]*"),md)
if (length(ind1)) {
lim <- .gsub("[\"</>]"," ",md[ind1[1]])
minx2 <- .gsub2("minx\\s*=\\s*(\\S+)\\s","\\1",lim)
miny2 <- .gsub2("miny\\s*=\\s*(\\S+)\\s","\\1",lim)
maxx2 <- .gsub2("maxx\\s*=\\s*(\\S+)\\s","\\1",lim)
maxy2 <- .gsub2("maxy\\s*=\\s*(\\S+)\\s","\\1",lim)
a2 <- as.numeric(c(minx2,miny2,maxx2,maxy2))
if ((rot)&&(all(a2[c(2,1,4,3)]==a3))) {
message(paste("IMPORTANT NOTICE:"
,"It is required to use argument/value 'transpose=TRUE'"
,"or 'bbox={miny},{minx},{maxy},{maxx}'"))
a <- a2[c(2,1,4,3)]
}
if (!tryGrid) {
a <- if (rot) a3 else a2
}
tryGrid <- tryGrid+2L
}
}
if ((FALSE)&&(tryGrid)&&(version %in% c("1.3.0"))) {
ind1 <- .grep(paste0("BoundingBox CRS=\"*CRS:84"),md)
lim <- .gsub("[\"</>]"," ",md[ind1[1]])
minx3 <- .gsub2("minx\\s*=\\s*(\\S+)\\s","\\1",lim)
miny3 <- .gsub2("miny\\s*=\\s*(\\S+)\\s","\\1",lim)
maxx3 <- .gsub2("maxx\\s*=\\s*(\\S+)\\s","\\1",lim)
maxy3 <- .gsub2("maxy\\s*=\\s*(\\S+)\\s","\\1",lim)
a4 <- as.numeric(c(minx3,miny3,maxx3,maxy3))
ind1 <- .grep(paste0("BoundingBox CRS=\"*EPSG:4326"),md)
lim <- .gsub("[\"</>]"," ",md[ind1[1]])
minx3 <- .gsub2("minx\\s*=\\s*(\\S+)\\s","\\1",lim)
miny3 <- .gsub2("miny\\s*=\\s*(\\S+)\\s","\\1",lim)
maxx3 <- .gsub2("maxx\\s*=\\s*(\\S+)\\s","\\1",lim)
maxy3 <- .gsub2("maxy\\s*=\\s*(\\S+)\\s","\\1",lim)
a5 <- as.numeric(c(minx3,miny3,maxx3,maxy3))
rot <- TRUE
if (all(a4[c(2,1,4,3)]==a5)) {
message(paste("IMPORTANT NOTICE:"
,"It is required to use argument/value 'transpose=TRUE'"
,"or 'bbox={miny},{minx},{maxy},{maxx}'"))
}
}
if (tryGrid) {
if (!nchar(epsg)) {
epsg <- 4326
}
code <- .gsub("\\D","",epsg)
isLonLat <- code %in% "4326"
p4s <- .epsg2proj4(code,force=TRUE,verbose=FALSE) # if (!isLonLat)
if (any(abs(a)>360))
xy <- matrix(a,ncol=2,byrow=TRUE)
else {
n <- 3
if (code %in% c("3857","900913")) {
elat <- 85.051129
a[2][a[2]<(-elat)] <- -elat
a[4][a[4]>(+elat)] <- +elat
}
if (a[2]<=-90)
a[2] <- -90+1e-6
if (a[4]>=+90)
a[4] <- +90-1e-6
if (abs(a[3]-a[1])>360) {
a[1] <- -180
a[3] <- +180
}
if (TRUE) {
a <- matrix(a[c(1,2,1,4,3,4,3,2,1,2)],ncol=2,byrow=TRUE)
x <- a[,1]
y <- a[,2]
n <- 256
x <- c(seq(x[1],x[2],len=n),seq(x[2],x[3],len=n)
,seq(x[3],x[4],len=n),seq(x[4],x[5],len=n))
y <- c(seq(y[1],y[2],len=n),seq(y[2],y[3],len=n)
,seq(y[3],y[4],len=n),seq(y[4],y[5],len=n))
ll <- cbind(x,y)
}
else
ll <- expand.grid(seq(a[1],a[3],len=n),seq(a[2],a[4],len=n))
if (isLonLat)
xy <- ll
else {
xy <- .project(ll,p4s)
}
}
b <- c(min(xy[,1]),min(xy[,2]),max(xy[,1]),max(xy[,2]))
if (any(is.infinite(b))) {
print(b)
stop(paste("Unable to define grid for layer",.dQuote(layer)))
}
res <- max(c(b[3]-b[1],b[4]-b[2])/size)
g0 <- regrid(setbound=b,res=res,proj=p4s)
# print(g0);q()
if (defineGrid)
session_grid(g0)
}
else {
if (verbose)
message(paste("Unable to define grid for layer",.dQuote(layer)))
}
}
if (toStop) {
message(paste("Suggested to use",.sQuote(paste0("version=",version))))
# if ((file.exists(dst))&&(dirname(dst)==tempdir())) {
# file.remove(dst)
# }
if (TRUE)
stop("Incomplete request")
opW <- options(warn=1)
warning("Incomplete request")
options(opW)
return(src)
}
ind1 <- .lgrep("&bbox=",src)==0
ind2 <- nchar(as.character(bbox))>0
if (ind2) {
if (!ind1) {
src <- sapply(strsplit(src,split="&"),function(x)
paste(.grep("^bbox=",x,invert=TRUE,value=TRUE),collapse="&"))
}
src <- paste0(src,"&bbox=",as.character(bbox))
}
transpose <- transpose & version %in% c("","1.3.0") & as.character(epsg)=="4326"
ind1 <- .lgrep("&bbox=",src)==0
if ((ind1)&&(!ind2)) {
bbox <- if (transpose) "{miny},{minx},{maxy},{maxx}"
else "{minx},{miny},{maxx},{maxy}"
src <- paste0(src,"&bbox=",bbox)
}
if (length(arglist)) {
if (length(ind <- grep("(^fileout$|^scale$)",names(arglist))))
arglist <- arglist[-ind]
}
if (length(arglist))
src <- paste0(src,paste(paste0("&",names(arglist)),as.character(arglist)
,sep="=",collapse=""))
names(src) <- if (multiple) sname else layers
as.list(src)
}
'.get_wms' <- function(src
,version=c("1.1.1","1.3.0","1.1.0","1.0.0")
,layers=""
,epsg=""
,format=""
,bbox="" #"{minx},{miny},{maxx},{maxy}"
,styles=""
,transparent=TRUE
,legend="topright",gdalwarp=FALSE,tile=1024L
,size=800L,fail180=FALSE,transpose=FALSE
,extend=FALSE
,cache=TRUE
,verbose=FALSE,...) {
arglist <- as.list(match.call()) ## try mget(names(match.call())[-1])
if (TRUE) {
argname <- names(as.list(args(.compose_wms)))
argname <- argname[nchar(argname)]
rname <- names(arglist)
for (i in seq_along(arglist)[-1]) {
if ((inherits(arglist[[i]],c("name","call")))&&(rname[i] %in% argname)) {
# if (((is.language(arglist[[i]]))||(is.name(arglist[[i]])))&&
# (rname[i] %in% argname))
if (isTRUE(getOption("ursaNoticeMatchCall")))
message('try `mget(names(match.call())[-1])` instead of `as.list(match.call())`')
arglist[[i]] <- eval.parent(arglist[[i]])
}
}
arglist$extend <- FALSE
}
srclist <- unlist(do.call(".compose_wms",arglist[-1]))#[1]
isCache <- (is.logical(cache))&&(isTRUE(cache))||(is.character(cache))
g0 <- session_grid()
res <- vector("list",length(src))
names(res) <- names(src)
src <- sample(srclist,1)[[1]]
code <- .gsub(".+&[sc]rs=EPSG\\:(\\d+)(\\&.+|$)","\\1",src)
p4epsg <- paste0("+init=epsg:",code)
if (is.character(gdalwarp)) {
resample <- gdalwarp
gdalwarp <- TRUE
}
else
resample <- "lanczos"
if ((!FALSE)&&(gdalwarp)) {
if (!nchar(Sys.which("gdalwarp")))
message("'gdalwarp' is required to be in search paths")
}
proj4s <- unlist(strsplit(g0$crs,split="\\s+"))
ind <- .grep("\\+(proj=merc|[ab]=6378137|[xy]_0=0|k=1|units=m|lat_ts=0)",proj4s)
isMerc <- ((length(ind)==8)&&(!gdalwarp))
isLonLat <- .lgrep("\\+proj=longlat",g0$crs)>0
sc <- getOption("ursaPngScale")
g3 <- g0
if ((is.numeric(sc))&&(sc<1e11+0.75)) {
# print(g0)
g3 <- regrid(g0,mul=sc)
# print(g3)
if ((TRUE)||(isLonLat))
g3 <- regrid(g3,setbound=with(g0,c(minx,miny,maxx,maxy))
,dim=with(g3,c(rows,columns)))
## ********** NOTICE: generally, g3$resx!=g3$resy ************** ##
# print(g3,digits=15)
}
if (isMerc) {
ind <- .grep("\\+lon_0",proj4s)
lon0 <- as.numeric(.gsub(".+=(.+)","\\1",proj4s[ind]))
if (lon0==0)
isMerc <- FALSE
else {
B0 <- 6378137
B <- B0*pi
dx0 <- 6378137*lon0*pi/180
proj4s[ind] <- "+lon_0=0.000000"
g2 <- g3
g3 <- regrid(g2,minx=g2$minx+dx0,maxx=g2$maxx+dx0
,crs=paste(proj4s,collapse=" "),zero="keep")
}
}
if (gdalwarp) {
if (verbose)
print(g3,digits=15)
g2 <- g3
# .elapsedTime("a")
requireNamespace(c("sp","rgdal")[2],quietly=.isPackageInUse())
dg <- 16
xy <- with(g3,expand.grid(x=seq(minx,maxx,len=dg),y=seq(miny,maxy,len=dg)))
ll <- .project(xy,g3$crs,inv=TRUE)
p4s <- .epsg2proj4(p4epsg)
xy <- .project(ll,p4s)
# .elapsedTime("b")
nm <- max(g3$columns,g3$rows)
g3 <- regrid(ursa_grid()
,setbound=c(min(xy[,1]),min(xy[,2]),max(xy[,1]),max(xy[,2]))
,res=c(1,1)
,crs=p4s)
# print(g3)
sc <- ifelse(isLonLat,3.3,1.5)*nm/max(g3$columns,g3$rows)
g3 <- regrid(g3,mul=sc,border=5)
if (verbose)
print(g3)
session_grid(g3)
}
tc <- seq(0L,g3$columns,by=tile)
if (length(tc)==1)
nc <- g3$columns
else
nc <- c(tail(tc,-1),g3$columns)-tc
tr <- seq(0L,g3$rows,by=tile)
if (length(tr)==1)
nr <- g3$rows
else
nr <- c(tail(tr,-1),g3$rows)-tr
x <- c(seq(g3$minx,g3$maxx,by=g3$resx*tile),g3$maxx)
if (isLonLat)
B <- 180
if (isMerc) {
xn <- sort(c(x,-B,-2*B,+B,+2*B))
x <- unique(xn[xn>=min(x) & xn<=max(x)]) ## 20170723 ++ unique()
nc <- diff(x)/g3$resx
nc <- ceiling(nc)
# if (length(nc)>1)
# nc[length(nc)] <- g3$columns-sum(nc[-length(nc)])
}
if ((!FALSE)&&(isLonLat)) {
if (!fail180)
xn <- sort(c(x,-B,-3*B,+B,+3*B))
else {
xn <- sort(c(x,0,2*B,4*B,-2*B))
}
x <- unique(xn[xn>=min(x) & xn<=max(x)]) ## 20170723 ++ unique()
nc <- diff(x)/g3$resx
nc <- ceiling(nc)
# if (length(nc)>1)
# nc[length(nc)] <- g3$columns-sum(nc[-length(nc)])
}
if (length(nc)>1)
nc[length(nc)] <- g3$columns-sum(nc[-length(nc)])
else
nc <- g3$columns
# y <- c(seq(g3$miny,g3$maxy,by=g3$resy*tile),g3$maxy)
y <- rev(c(seq(g3$maxy,g3$miny,by=-g3$resy*tile),g3$miny))
tind <- .expand.grid(c=seq_along(nc),r=rev(seq_along(nr)))-1
# tind <- cbind(tind,r2=length(nr)-tind$r-1)
tcr <- .expand.grid(width=nc,height=rev(nr))
txy1 <- .expand.grid(minx=head(x,-1),miny=head(y,-1))
txy2 <- .expand.grid(maxx=tail(x,-1),maxy=tail(y,-1))
tg <- cbind(tind,tcr,txy1,txy2)
tg <- tg[tg$width>0 & tg$height>0,]
if (isMerc | (isLonLat & !fail180)) {
ind1 <- which(tg$minx>=B & tg$maxx>=B)
ind2 <- which(tg$minx<=-B & tg$maxx<=-B)
if (length(ind1)) {
tg$minx[ind1] <- tg$minx[ind1]-2*B
tg$maxx[ind1] <- tg$maxx[ind1]-2*B
}
if (length(ind2)) {
tg$minx[ind2] <- tg$minx[ind2]+2*B
tg$maxx[ind2] <- tg$maxx[ind2]+2*B
}
}
if (isLonLat & fail180) {
ind1 <- which(tg$minx>=2*B & tg$maxx>=2*B)
ind2 <- which(tg$minx<=0 & tg$maxx<=0)
if (length(ind1)) {
tg$minx[ind1] <- tg$minx[ind1]-2*B
tg$maxx[ind1] <- tg$maxx[ind1]-2*B
}
if (length(ind2)) {
tg$minx[ind2] <- tg$minx[ind2]+2*B
tg$maxx[ind2] <- tg$maxx[ind2]+2*B
}
}
cellx <- (tg[,"maxx"]-tg[,"minx"])/tg[,"width"]
celly <- (tg[,"maxy"]-tg[,"miny"])/tg[,"height"]
if (verbose)
print(tg)
for (k in seq_along(srclist)) {
src <- srclist[[k]]
isPNG <- .lgrep("\\&format=image.+png",src)>0
isJPEG <- .lgrep("\\&format=image.+(jpg|jpeg)",src)>0
if (isJPEG)
if (!requireNamespace("jpeg",quietly=.isPackageInUse()))
stop("Suggested package 'jpeg' is missed, but is required here.")
if (verbose)
print(c(png=isPNG,jpg=isJPEG,GDAL=(!isPNG & !isJPEG)))
i0 <- 0
for (i in sample(seq(nrow(tg)))) {
i0 <- i0+1
src2 <- .gsub("{maxy}",format(tg$maxy[i],sci=FALSE)
,.gsub("{maxx}",format(tg$maxx[i],sci=FALSE)
,.gsub("{miny}",format(tg$miny[i],sci=FALSE)
,.gsub("{minx}",format(tg$minx[i],sci=FALSE),src))))
if ((FALSE)&&(src2==src)) {
version <- .gsub("^.+(\\?|\\&)version=(\\d\\.\\d\\.\\d)(\\&.+|$)","\\2",src)
if ((version=="1.3.0")&&(code=="4326"))
src2 <- paste0(src2,"&bbox=",tg$miny[i],",",tg$minx[i]
,",",tg$maxy[i],",",tg$maxx[i])
else
src2 <- paste0(src2,"&bbox=",tg$minx[i],",",tg$miny[i]
,",",tg$maxx[i],",",tg$maxy[i])
}
src2 <- paste0(src2,"&width=",tg$width[i],"&height=",tg$height[i])
src2 <- paste0(src2,"&service=WMS&request=GetMap")
# dst <- tempfile()
# download.file(src2,dst,mode="wb",quiet=!verbose)
src2 <- gsub("\\?\\&","?",src2)
if (isCache)
dst <- .ursaCacheDownload(src2,mode="wb",cache=cache,quiet=!verbose)
else {
dst <- tempfile()
download.file(src2,dst,mode="wb",quiet=!verbose)
}
if (isPNG)
a <- try(png::readPNG(dst))
else if (isJPEG)
a <- try(jpeg::readJPEG(dst))
else {
a <- try(as.array(read_gdal(dst),permute=TRUE,flip=TRUE))
session_grid(NULL)
}
if (inherits(a,"try-error")) {
if (isPNG)
a <- try(jpeg::readJPEG(dst))
else if (isJPEG)
a <- try(png::readPNG(dst))
}
if (inherits(a,"try-error")) {
error <- paste(readLines(dst),collapse="\n")
}
# file.remove(dst)
if (inherits(a,"try-error")) {
message(error)
if (i0==1)
stop("Request 'GetMap' is declined")
else
next
}
if (i0==1) {
dima <- dim(a)
nb <- dima[3]
b <- array(0,dim=c(g3$rows,g3$columns,nb))
}
br <- tg$r[i]*tile+seq_len(tg$height[i])
# bc <- tg$c[i]*tile+seq_len(tg$width[i])
bc <- sum(nc[seq_len(tg$c[i])])+seq_len(tg$width[i])
if (FALSE) {
print(tg[i,])
print(range(sum(nc[seq_len(tg$c[i])])+seq_len(tg$width[i])))
message("b - recepient")
str(b)
message("a - donor")
str(a)
str(array(0,dim=c(length(br),length(bc),length(seq_len(nb)))))
str(list(range(br),range(bc),range(seq_len(nb))))
str(b[br,bc,seq_len(nb)])
}
b[br,bc,seq_len(nb)] <- a[seq_along(br),seq_along(bc),seq_len(nb)]
}
# b <- aperm(b,c(2,1,3))
# d <- if (isPNG | isJPEG) as.ursa(b*255) else as.ursa(b)
d <- if (isPNG | isJPEG) ursa_new(b*255,permute=TRUE,flip=TRUE)
else as.ursa(b)
# d <- as.integer(d)
ursa_grid(d) <- if (isMerc) g2 else g3
if (gdalwarp) {
d <- .gdalwarp(d,grid=g0,resample=resample,verbose=verbose)
}
if ((is.null(legend))||(is.logical(legend))&&(!legend))
logo2 <- NULL
else if (FALSE) {
a <- unlist(strsplit(src,split="&"))
a <- .grep("^(request|servce|bbox)=",a,value=TRUE,invert=TRUE)
a <- .gsub("^(layer)(s)*(=.+)","\\1\\3",a)
reqL <- paste(c(a,"service=WMS","request=GetLegendGraphic"),collapse="&")
# dst <- tempfile()
# if (.try(download.file(reqL,dst,mode="wb",quiet=!verbose))) {
reqL <- gsub("\\?\\&","?",reqL)
if (isCache)
dst <- try(.ursaCacheDownload(reqL,mode="wb",cache=cache,quiet=!verbose))
else {
dst <- tempfile()
a <- try(download.file(reqL,dst,mode="wb",quiet=!verbose))
if (inherits(a,"try-error"))
dst <- a
}
if (!inherits(dst,"try-error")) {
if (isPNG)
logo2 <- try(png::readPNG(dst))
else if (isJPEG)
logo2 <- try(jpeg::readJPEG(dst))
else {
logo2 <- try(as.array(read_gdal(dst),permute=TRUE,flip=TRUE))
session_grid(NULL)
}
if (inherits(logo2,"try-error")) {
error <- paste(readLines(dst),collapse="\n")
}
# file.remove(dst)
if (inherits(logo2,"try-error")) {
message(error)
opW <- options(warn=1)
warning("Request 'GetLegendGraphic' is declined")
options(opW)
}
if (!is.array(logo2))
logo2 <- NULL
}
}
else {
a <- unlist(strsplit(src,split="&"))
a <- .grep("^(request|servce|bbox)=",a,value=TRUE,invert=TRUE)
ind <- .grep("^layer(s)*=",a)
layer <- unlist(strsplit(.gsub(".+=(.+)","\\1",a[ind]),split=","))
suff <- c("service=WMS","request=GetLegendGraphic")
if (length(indV <- .grep("^version=",a))) {
ver <- .gsub(".+=(.+)","\\1",a[indV])
if (ver %in% c("1.3.0"))
suff <- c(suff,"sld_version=1.1.0")
}
a <- paste(c(a[-ind],suff),collapse="&")
reqL <- paste(a,paste0("layer=",layer),sep="&")
logo <- vector("list",length(reqL))
# dst <- tempfile()
isOK <- TRUE
reqL <- gsub("\\?\\&","?",reqL)
for (i in seq_along(logo)) {
# if (.try(download.file(reqL[i],dst,mode="wb",quiet=!verbose))) {
if (isCache)
dst <- try(.ursaCacheDownload(reqL,mode="wb",cache=cache,quiet=!verbose))
else {
dst <- tempfile()
a <- try(download.file(reqL[i],dst,mode="wb",quiet=!verbose))
if (inherits(a,"try-error"))
dst <- a
}
if (!inherits(dst,"try-error")) {
if (isPNG)
logo[[i]] <- try(png::readPNG(dst))
else if (isJPEG)
logo[[i]] <- try(jpeg::readJPEG(dst))
else {
logo[[i]] <- try(as.array(read_gdal(dst),permute=TRUE,flip=TRUE))
session_grid(NULL)
}
if (inherits(logo[[i]],"try-error")) {
error <- paste(readLines(dst),collapse="\n")
}
# file.remove(dst)
if (inherits(logo[[i]],"try-error")) {
if (verbose) {
message(error)
opW <- options(warn=1)
warning("Request 'GetLegendGraphic' is declined")
options(opW)
}
}
if (!is.array(logo[[i]]))
logo[[i]] <- NULL
}
}
if (!length(logo))
logo2 <- NULL
else
logo <- logo[sapply(logo,function(x) !is.null(x))]
if (!length(logo))
logo2 <- NULL
else {
a <- sapply(logo,dim)
dima <- c(sum(a[1,]),max(a[2,]),max(a[3,]))
adr1 <- 0
adr2 <- 0
adr3 <- 0
logo2 <- array(1,dim=dima)
for (i in seq_along(logo)) {
dima <- dim(logo[[i]])
adr1 <- max(adr1)+seq(dima[1])
adr2 <- seq(dima[2])
adr3 <- seq(dima[3])
# str(lapply(list(adr1,adr2,adr3),range))
logo2[adr1,adr2,adr3] <- logo[[i]]
}
}
}
attr(d,"copyright") <- " "
attr(d,"wmslegend") <- logo2
res[[k]] <- d
}
session_grid(g0)
res
}
'.panel_wms.alt' <- function(...) {
if (.skipPlot(TRUE))
return(NULL)
g0 <- session_grid()
arglist <- list(...)
d <- .get_wms(...)
alpha <- .getPrm(arglist,name="alpha",default=1)
leg <- attr(d,"wmslegend")
panel_raster(d,alpha=alpha)
session_grid(g0)
if (!is.null(leg)) {
legend <- .getPrm(arglist,name="legend",default="topright"
,class=c("character","integer"))
if (is.logical(legend))
legend <- "topright"
panel_annotation(leg,pos=legend,alpha=alpha)
}
}
'.panel_wms' <- function(src
,version=c("1.1.1","1.3.0","1.1.0","1.0.0")
,layers=""
,epsg=""
,format=""
,bbox="" #"{minx},{miny},{maxx},{maxy}"
,styles=""
,transparent=TRUE
,legend="topright",gdalwarp=FALSE,tile=1024L
,size=800L,fail180=FALSE,transpose=FALSE
,extend=FALSE,cache=TRUE
,alpha=1,verbose=FALSE,...) {
if (.skipPlot(TRUE))
return(NULL)
g0 <- session_grid()
arglist <- as.list(match.call()) ## try mget(names(match.call())[-1])
arglist[[2]] <- eval.parent(arglist[[2]])
res <- do.call(".get_wms",arglist[-1])
n <- length(res)
for (i in seq_along(res)) {
leg <- attr(res[[i]],"wmslegend")
panel_raster(res[[i]],alpha=alpha)
session_grid(g0)
if (!is.null(leg)) {
if (is.logical(legend))
legend <- "topright"
panel_annotation(leg,pos=legend,alpha=alpha)
}
}
invisible(NULL)
}
'.is.wms' <- function(dsn) {
if (is.list(dsn))
return(FALSE)
s <- unlist(strsplit(dsn,split="&"))
ind <- .lgrep("^[sc]rs=",s)+
.lgrep("^layer(s)*=",s)+
.lgrep("^version=",s)+
.lgrep("^format=",s)+
.lgrep("^http(s)*\\://",s)+
0
# s <- unlist(strsplit(.grep("http(s)*://",dsn,value=TRUE),split="&"))
# print(.grep("^(version=|format=|[cs]rs=|layer(s)*=)",s))
ind>=4
}
'.parse_wms' <- function(dst,verbose=FALSE) {
opW <- options(warn=ifelse(verbose,1,-1))
md <- readLines(dst)
options(opW)
md <- paste(md,collapse=" ")
md <- .gsub("\\<","___<<",md)
md <- .gsub("\\>",">>___",md)
md <- unlist(strsplit(md,split="(___<|>___)"))
md <- md[nchar(md)>0]
md <- .grep("^\\s+$",md,value=TRUE,invert=TRUE)
md
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/xxx.panel_WMS.R
|
'.compose_basemap' <- function(style="CartoDB") {
if (.skipPlot(TRUE))
return(NULL)
sc <- getOption("ursaPngScale")
if (is.null(sc)||(!is.numeric(sc)))
return(NULL)
print(sc)
invisible(NULL)
}
'.panel_basemap' <- function(style="CartoDB",...) {
if (.skipPlot(TRUE))
return(NULL)
sc <- getOption("ursaPngScale")
if (is.null(sc)||(!is.numeric(sc)))
return(NULL)
g0 <- session_grid()
str(g0)
c1 <- session_cellsize()
c2 <- 2*6378137*pi/(2^(1:21+8))
d <- abs(c2-c1)
print(d)
ind <- which.min(d)
print(ind)
print(d[ind])
print(.is.near(d[ind],0))
if (!is.na(.is.near(d[ind],0,verbose=TRUE))) {
b <- .geomap(style=style)
ret <- panel_raster(b,...)
return(invisible(ret))
}
g1 <- regrid(g0,res=c2[ind])
print(g1,digits=14)
session_grid(g1)
# .is.near(ursa(obj,"cellsize"),2*6378137*pi/(2^(1:21+8))))
# g1 <- regrid(g0,mul=sc)
b <- .geomap(style=style)
str(b)
options(warn=1)
b <- .gdalwarp(b,grid=g0,resample=c("bilinear","lanczos")[1],verbose=TRUE)
session_grid(g0)
ret <- panel_raster(b,...)
invisible(ret)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/xxx.panel_basemap.R
|
'panel_cluster' <- function(obj,overlap=1,cex=1,ratio=0.2,col=NULL
,method=c("complete","centroid","single")
,fun=c("count","sum","mean","label"),label=fun %in% "count"
,ngroup=NA,separate=FALSE,repel=20L,legend="bottomright"
,title=NULL,verbose=FALSE,...) {
##~ method <- c('1'="ward.D",'2'="ward.D2",'3'="single",'4'="complete"
##~ ,'5'="average",'6'="mcquitty",'7'="median"
##~ ,'8'="centroid")[4] ## 3 4! 8
method <- match.arg(method)
fun <- match.arg(fun)
cutted <- 1.05
da <- spatial_data(obj)
# str(colnames(da))
# str(da[,colnames(da),drop=TRUE])
if (!is.null(da)) {
indCat <- which(sapply(colnames(da),function(x)
inherits(da[,x,drop=TRUE],c("character","factor"))))[1]
isCat <- !is.na(indCat)
if (fun %in% c("count")) {
indNum <- which(sapply(colnames(da),function(x)
inherits(da[,x,drop=TRUE],c("integer"))))[1]
isNum <- !is.na(indNum)
}
else
isNum <- FALSE
}
else {
isCat <- FALSE
isNum <- FALSE
}
if ((isCat)&&(isNum)) {
if (length(ind <- which(is.na(da[[indNum]])))) {
obj <- obj[-ind,]
da <- da[-ind,]
}
}
if (isCat) {
aname <- obj[[indCat]]
nameCat <- colnames(da)[indCat]
}
else {
if (separate)
separate <- F
legend <- NULL
}
if (verbose) {
print(c('Category'=indCat))
print(c('Count'=indNum))
}
g1 <- getOption("ursaPngPanelGrid")
xy <- spatial_coordinates(spatial_transform(spatial_geometry(obj),ursa_crs(g1)))
xy <- cbind(xy,da)
n <- if (!isNum) rep(1L,spatial_count(obj)) else obj[[indNum]]
xy4 <- xy[do.call(c,lapply(seq_along(n),function(i) rep(i,n[i]))),,drop=FALSE]
rownames(xy4) <- NULL
# xy4[[colnames(da)[indNum]]] <- 1L
# print(table(as.integer(rownames(xy4))))
cell <- ursa(g1,"cellsize")
# .ursaOptions()
scale <- getOption("ursaPngScale")
dpi <- getOption("ursaPngDpi")
ps <- getOption("ursaPngPointsize")
retina <- getOption("ursaPngRetina")
s <- unname((cex*c(annotation=1.5))*overlap*ps/scale*cell*dpi/96*sqrt(2))
if (!label)
s <- s*0.5
if (verbose)
print(data.frame(cell=cell,retina=retina,scale=scale
,overlap=overlap,dpi=dpi,ps=ps,cex=cex,s=s))
if (isCat)
bname <- if (is.factor(aname)) levels(aname) else unique(aname)
else {
indFun <- which(sapply(colnames(da),function(x)
inherits(da[,x],c("integer","numeric"))))[1]
if (!is.na(indFun))
bname <- names(indFun)
else
bname <- ".undefined"
}
bname <- bname[!is.na(bname)]
if ((separate)&&(isCat)&&(!is.na(ngroup))&&(length(ngroup)!=length(bname))&&(ngroup[1]>2)) {
tg <- table(xy4[[nameCat]])
# print(tg)
# mul <- ngroup/max(tg)
# ngroup <- ceiling(as.numeric(tg)*mul)
# print(length(tg))
# print(ngroup)
if (any(nchar(names(ngroup)))) {
ng <- ngroup
ngroup <- rep(NA,length(tg))
names(ngroup) <- names(tg)
if (length(ind <- match(names(ng),names(ngroup))))
ngroup[ind] <- ng
}
else {
ngroup <- rep(ngroup,length(tg))
names(ngroup) <- names(tg)
}
# print(ngroup)
}
# print(ngroup)
print(series(xy4))
str(bname)
if ((!fun %in% c("mean","sum"))&&(ncol(xy4)>3))
bname <- bname[bname %in% xy4[[4]]]
lutSep <- if (separate | length(bname)>1e6) sample(bname) else ".+"
str(bname)
print(lutSep)
lutList <- lapply(lutSep,function(sep) {
if (verbose)
message(sQuote(sep),":")
# print(ngroup[sep])
# return(NULL)
# str(xy4)
# str(grep(paste0("^",sep,"$"),xy4[[nameCat]]))
if (isCat) {
# xy5 <- xy4[grep(paste0("^",sep,"$"),xy4[[nameCat]]),]
xy5 <- if (separate) xy4[xy4[[nameCat]] %in% sep,] else xy4
}
else
xy5 <- xy4
# print(bname)
if (nrow(xy5)<2) {
chcD <- 1L
}
else {
len <- dist(xy5[,c("x","y")])
# str(xy5)
# print(summary(len))
chc <- hclust(len,method=method)
if ((length(ngroup)>1)&&(!is.null(names(ngroup))))
ng <- ngroup[sep]
else
ng <- ngroup
if (all(len==0)) {
cat("----------------------------------------\n")
str(xy5[,c("x","y")])
str(len)
ng <- NA
}
else if (min(len[len>0])>s*0.75)
ng <- NA
# print(data.frame(ng=ng,len=min(len[len>0])))
if (!is.na(ng)) {
chcD <- cutree(chc,k=min(c(ng,nrow(xy5))))
}
else {
chcD <- cutree(chc,h=s)
}
}
ta <- table(chcD)
##~ print(ta)
##~ print(table(cutree(chc,h=s)))
##~ print(nrow(xy5))
##~ print(sum(ta))
# pal <- paste0(cubehelix(length(bname),dark=127,light=127,rotate="circle"),"A0")
lut <- array(0L,dim=c(length(ta),length(bname)),dimnames=list(names(ta),bname))
lut <- cbind(.x=NA,.y=NA,.r=NA,.n=NA,data.frame(lut,check.names=FALSE))
xy5 <- data.frame(xy5,.cluster=chcD)
for (i in seq(nrow(lut))) {
if (verbose)
print(bname)
da2 <- xy5[xy5$.cluster==i,]#c("x","y")]
# print(da2)
if (isCat) {
ta2 <- table(da2[[nameCat]])
lut[i,match(names(ta2),colnames(lut))] <- as.integer(ta2)
}
else {
if ((bname!=".undefined")&&(fun %in% c("mean"))) {
lut[i,bname] <- mean(da2[[bname]],na.rm=TRUE)
}
else if ((bname!=".undefined")&&(fun %in% c("sum"))) {
lut[i,bname] <- sum(da2[[bname]],na.rm=TRUE)
}
else
lut[i,bname] <- nrow(da2)
}
lut$.n[i] <- nrow(da2)
lut$.x[i] <- mean(da2$x)
lut$.y[i] <- mean(da2$y)
}
lut <- aggregate(lut[,-grep("^\\.[xy]",colnames(lut))]
,by=list(.x=lut$.x,.y=lut$.y),sum)
lut
})
lut <- do.call(rbind,lutList)
rownames(lut) <- NULL
# print(lut)
if (is.character("ratio") & "log" %in% ratio)
lut$.r <- log(lut$.n+1)
else
lut$.r <- lut$.n^ratio # rowSums(lut[,bname,drop=FALSE])^ratio
lut$.r <- lut$.r/min(lut$.r)
if (repel) {
if (isTRUE(repel))
repel <- 20L
else
repel <- as.integer(repel)
# S <- 1+dist(lut$.r)
# print(lut)
# gr <- expand.grid(i=seq(nrow(lut)),j=seq(nrow(lut)),KEEP.OUT.ATTRS=FALSE)
S <- 0.5*rowSums(expand.grid(a=lut$.r,b=lut$.r,KEEP.OUT.ATTRS=FALSE))
S <- as.dist(matrix(S,nrow=nrow(lut),byrow=T))
S <- as.dist(S)
xy <- as.matrix(lut[,c(".x",".y")])
dimnames(xy) <- NULL
# xy <- cbind(xy,S)
d <- s/20
iter <- 100
R2 <- 0.5*s*cutted
k <- 0L
isProgress <- FALSE
repeat({
D <- dist(xy)/S
ind1 <- which(D<2*R2)
ind1 <- ind1[!.is.eq(D[ind1],2*R2)]
if (!length(ind1))
break
if (!k) {
# str(ind1)
iter <- repel*length(ind1)
pb <- ursaProgressBar(iter,title="Repel clusters")
isProgress <- TRUE
}
if (isProgress)
setUrsaProgressBar(pb)
ind2 <- .sample(ind1,1)
D1 <- as.matrix(D)
ind3 <- match(D[ind2],c(D1))
j <- c(col(D1))[ind3]
i <- c(row(D1))[ind3]
xy2 <- xy[c(i,j),]
dxy <- c(diff(xy2[,1]),diff(xy2[,2]))
L <- sqrt(sum(dxy^2))
d2 <- if (T | L/2+d/2<R2) d else (2*R2-L)/2
alpha <- atan2(dxy[2],dxy[1])
xy2[,1] <- xy2[,1]+c(-d2,d2)*cos(alpha)
xy2[,2] <- xy2[,2]+c(-d2,d2)*sin(alpha)
xy[c(i,j),] <- xy2
if (k>iter)
break
k <- k+1L
})
if (isProgress)
close(pb)
# print(c(convergent=k,niter=iter))
lut[,c(".x",".y")] <- xy
}
lut <- lut[order(lut$.r,decreasing=TRUE),]
d <- dist(lut[,c(".x",".y")])
indCrd <- grep("^\\.[xy]$",colnames(lut))
if (F) {
p <- spatial_buffer(spatialize(lut[,indCrd],coords=c(".x",".y")
,crs=ursa_crs(g1)),s/2)
spatial_write(p,"C:/platt/R/ursa-package/run/panel_cluster/mammal.geojson")
q()
}
if (F) {
ct <- NULL
if (T & .is.colortable(col)) {
print(bname)
print(col)
ind <- na.omit(match(bname,names(col)))
if (length(ind)!=length(bname))
col <- as.character(col)
else {
print(is.character(col))
}
}
q()
print(col)
print(bname)
}
if (F & is.character(col)) {
ct <- ursa_colortable(colorize(bname
,pal=rep(col,length.out=length(bname)),alpha="A0"))
ctInd <- ct
}
else if (F & is.list(col)) {
# do.call("colorize",c(list(body),col))
ct <- colorize(bname,pal=rep(col,length.out=length(bname)),alpha="A0")
}
else if (fun %in% c("count","label")) {
hasCT <- FALSE
if (T & .is.colortable(col)) {
ind <- na.omit(match(bname,names(col)))
if (length(ind)==length(bname)) {
hasCT <- TRUE
ct <- col[ind]
}
}
if (!hasCT)
ct <- colorize(bname,alpha="A0"
,pal.dark=127,pal.light=127,pal.rotate="circle"
)
rm(hasCT)
ctInd <- ursa_colortable(ct)
}
else {
if (is.list(col)) {
if (!length(grep("stretch",names(col))))
col$stretch <- "linear"
ct <- do.call("colorize",c(list(lut[[bname]]),col))
}
else if (is.character(col)) {
ct <- colorize(lut[[bname]],stretch="linear",alpha="A0",pal=col)
}
else {
# ct <- colorize(lut[[bname]],stretch="linear",alpha="A0") ## -- 20210909
ct <- colorize(bname,stretch="linear",alpha="A0") ## ++ 20210909
}
ctInd <- ursa_colortable(ct)[ursa_colorindex(ct)]
}
bg <- if (separate) "white" else ctInd
if (length(bg)==1)
bg <- rep(bg,length(ctInd))
bg <- col2rgb(bg)/255
bg <- rgb(bg[1,],bg[2,],bg[3,],alpha=0.2)
s2 <- s/ifelse(label,2,1.5)/overlap
for (i in seq(nrow(lut))) {
x <- lut$.x[i] # <- mean(da2$x)
y <- lut$.y[i] # <- mean(da2$y)
r <- lut$.r[i]
if (fun %in% c("count","label")) {
v <- as.integer(lut[i,bname])
.panel_pie(v,x=x,y=y,radius=lut$.r[i]*s2,col=ctInd,bg=bg,ball=!label
,verbose=verbose) # lwd=0.5
}
else {
.panel_pie(1,x=x,y=y,radius=lut$.r[i]*s2,col=ctInd[i],ball=!label
,verbose=verbose)
}
p <- sf::st_as_sf(lut[i,],coords=c(".x",".y"),crs=ursa_crs(g1))
if (F)
panel_plot(spatial_buffer(p,s/2),col="transparent",border="grey40",lwd=0.5)
# panel_plot(spatial_buffer(p,s/2),col="transparent",border="white",lwd=0.5)
if (F) ## donut/bagel
panel_plot(spatial_buffer(p,(c(s-10*cell*cex,0.75*s*r)[2])/2)
,col="#FFFFFFAF",border="transparent")
if (label) {
if (fun %in% "count")
lab <- sum(v)
else
lab <- lut[i,bname]
if (fun %in% c("label")) {
lname <- names(lab)
lab <- lname[which(lab>0)]
}
# str(lab)
panel_annotation(x=x,y=y,label=as.character(lab),cex=cex,adj=c(0.5,0.53)
# ,fg="#FFFFFFA0",bg="#000000AF"
# ,buffer=2/scale
)
}
if (F) {
da2 <- xy4[xy4$.cluster==i,]
for (j in seq(nrow(da2)))
segments(x,y,da2$x[j],da2$y[j],col="#00000030",lwd=0.5)
}
}
if (!is.null(legend)) {
legend(legend,legend=bname,title=title
,col=ctInd,cex=c(1,cex)[1]/par("cex")
,pch=21,pt.lwd=ifelse(label,1,0)*2.4/par("cex"),pt.cex=1.8/par("cex")
,box.lwd=0.1,bg="#FFFFFFAF"
# ,pt.bg=ursa_colortable(colorize(seq_along(ctInd),pal=ctInd,alpha="30"))
,pt.bg=if (label) bg else ctInd
,...
)
# return(invisible(ct)) ## colortable of obj[[indCat]]
return(invisible(ursa_colortable(ct)))
}
ct <- ursa_colortable(ct)
if (F)
ret <- list(name=names(ct)
,type="POLYGON"
,fill=as.character(ct)
)
else {
ret <- .legend.skeleton()
ret$name=names(ct)
ret$col <- "white"
ret$border <- "transparent"
ret$pch <- 21
ret$pt.lwd <- ifelse(label,1,0)*2.4/par("cex")
ret$pt.cex <- 1.8/par("cex")
ret$pt.bg <- as.character(ct)
}
if (T) {
opR <- getOption("ursaPngLegend")
options(ursaPngLegend=if (is.null(opR)) list(ret) else c(opR,list(ret)))
}
# return(invisible(list(ret)))
return(invisible(ret))
##~ ret <- list(name=oname,type="default"
##~ ,col="transparent",border="transparent",lty=1,lwd=1,pch=0,cex=NA
##~ ,fill="transparent",bg="transparent",density=NA,angle=45)
}
'.panel_pie' <- function(z,x=0,y=0,radius=1,edges=200,clockwise=TRUE,init.angle=90
,col=NULL,bg="white"
,border="white",lty=NULL,lwd=NULL,ball=FALSE
,verbose=FALSE) {
if (!is.numeric(z) || any(is.na(z) | z < 0))
stop("'z' values must be positive.")
if (verbose)
cat("--------\nPIE\n----------\n")
g0 <- getOption("ursaPngPanelGrid")
if (verbose) {
print(session_grid())
print(g0)
print(getOption("ursaPngComposeGrid"))
print(getOption("ursaSessionGrid"))
}
cell <- ursa(g0,"cellsize")
z <- z/sum(z)
ind <- which(z>0)
mul <- cell/radius
# print(c(pie.cell=cell,pie.radius=radius,pie.mul=radius/cell))
if (any(z[ind]<mul)) {
z[ind] <- z[ind]+mul
z <- z/sum(z)
}
z <- c(0,cumsum(z))
dz <- diff(z)
nz <- length(dz)
if (max(dz)==0) {
border <- "transparent"
# if (!is.null(lwd))
# lwd <- NULL
}
pin <- par("pin")
usr <- par("usr")
asp <- c((pin[2]/(usr[4]-usr[3]))/(pin[1]/(usr[2]-usr[1])),1)
if (F & verbose) {
print(c('pin:'=pin))
print(c('usr:'=usr))
print(c('byy'=pin[2]/(usr[4]-usr[3])))
print(c('byy'=pin[1]/(usr[2]-usr[1])))
print(c('byx'=(usr[4]-usr[3])/pin[1]))
print(c('byy'=(usr[2]-usr[1])/pin[2]))
print(c('asp:'=asp))
print(session_grid())
.ursaOptions()
}
if (is.null(col))
col <- ursa_colortable(colorize(seq(nz)))
if (!is.null(border))
border <- rep_len(border, nz)
if (!is.null(lty))
lty <- rep_len(lty, nz)
if (!is.null(lwd))
lwd <- rep_len(lwd, nz)
twopi <- if (clockwise) -2*pi else 2*pi
# print(c(pie.asp=asp,pie.scale=c(1,0.7)))
't2xy' <- function(t,scale=c(1,0.7)) {
t2p <- twopi*t+init.angle*pi/180
if (max(dz)==1) {
if (T & verbose)
print("MAX(DZ)==1")
xp <- c(asp[1]*radius*scale[1]*cos(t2p)+x)
yp <- c(asp[2]*radius*scale[1]*sin(t2p)+y)
}
else {
if (T & verbose)
print("MAX(DZ)!=1")
xp <- c(0+x,asp[1]*radius*scale[1]*cos(t2p)+x,0+x)
yp <- c(0+y,asp[2]*radius*scale[1]*sin(t2p)+y,0+y)
}
if (length(scale)>1) {
if (max(dz)==1) {
if (T & verbose)
print("TWO SCALES: MAX(DZ)==1")
xp <- c(xp,NA,asp[1]*radius*scale[2]*cos(t2p)+x)
yp <- c(yp,NA,asp[2]*radius*scale[2]*sin(t2p)+y)
}
else {
if (T & verbose)
print("TWO SCALES: MAX(DZ)!=1")
xp <- c(xp,NA,0+x,asp[1]*radius*scale[2]*cos(t2p)+x,0+x)
yp <- c(yp,NA,0+y,asp[2]*radius*scale[2]*sin(t2p)+y,0+y)
}
}
list(x=xp,y=yp)
}
col1 <- col # ursa_colortable(colorize(seq_along(col),pal=col,alpha="A0"))
if (!is.character(bg))
col2 <- ursa_colortable(colorize(seq_along(col),pal=col,alpha="30"))
else {
col2 <- bg
}
for (i in seq_len(nz)) {
n <- max(2,floor(edges*dz[i]))
if (!ball) {
P <- t2xy(seq.int(z[i],z[i+1],length.out=n),scale=c(1,0.65))
##~ polygon(c(P$x,0+x),c(P$y,0+y),border=border[i],col=col[i]
##~ ,lty=lty[i],lwd=lwd[i]
##~ )
polypath(P$x,P$y,border=border[i],col=col1[i]
,lty=lty[i],lwd=lwd[i]
,rule=c("winding","evenodd")[2]
)
}
P <- t2xy(seq.int(z[i],z[i+1],length.out=n),scale=ifelse(ball,0.75,0.65))
polypath(P$x,P$y,border=border[i],col=if (ball) col1[i] else col2[i]
,lty=lty[i],lwd=lwd[i]
,rule=c("winding","evenodd")[2]
)
}
col
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/xxx.panel_cluster.R
|
##~ 'panel_legend' <- function(items,pos="bottomright",x,y,cex=1.5,pch=22
##~ ,box.col="transparent",bg="#FFFFFFAF"
##~ ,fill=NULL,lty,lwd,angle=45,density=NULL,bty="o"
##~ ,box.lwd=par("lwd"),box.lty=par("lty")
##~ ,xjust=0,yjust=1,x.intersp=1,y.intersp=1
##~ ,adj=c(0,0.5),text.width=NULL,text.col=par("col")
##~ ,text.font=NULL,merge=TRUE,trace=FALSE
##~ ,plot=TRUE,ncol=1,horiz=FALSE,title=NULL
##~ ,inset=0,xpd,title.col=text.col,title.adj=0.5
##~ ,seg.len=2)
'.shape_legend<-' <- function(obj,items,verbose,value) {
res <- unlist(lapply(items,function(x) x[[value]]))
if (!is.null(res)) {
if (verbose) {
str(value)
str(res)
}
obj[[value]] <- res
}
obj
}
'panel_legend' <- function(items,...)
{
# verbose <- !.isPackageInUse()
verbose <- .getPrm(list(...),name="verb(ose)*",default=!.isPackageInUse())
if (.skipPlot(TRUE))
return(NULL)
if (missing(items))
items <- getOption("ursaPngLegend")
else if (is.list(items)) {
items <- lapply(items,function(item) {
if ((length(item)==1)&&(is.list(item)))
return(item[[1]]) # return(unlist(item,recursive=FALSE))
item
})
}
items <- items[!sapply(items,is.null)]
if (!length(items))
return(invisible(NULL))
arglist <- head(as.list(args(legend)),-1)
items2 <- list(list(...))
if (verbose) {
message("-------")
str(items)
}
for (a in names(arglist)) {
.shape_legend(arglist,items,verbose) <- a
.shape_legend(arglist,items2,verbose) <- a
}
if (is.language(arglist[["lwd"]]))
arglist[["lwd"]] <- NULL
if (is.language(arglist[["lty"]]))
arglist[["lty"]] <- NULL
if (is.language(arglist[["box.lwd"]]))
arglist[["box.lwd"]] <- 0.1
if (is.language(arglist[["pt.cex"]]))
arglist[["pt.cex"]] <- 1 #arglist[["cex"]]
if (is.language(arglist[["pt.lwd"]]))
arglist[["pt.lwd"]] <- arglist[["lwd"]]
if (!nchar(as.character(arglist[["x"]])))
arglist[["x"]] <- "bottomright"
if ((!is.null(arglist[["lwd"]]))&&(all(is.na(arglist[["lwd"]]))))
arglist[["lwd"]] <- NULL
if ((!is.null(arglist[["lty"]]))&&(all(is.na(arglist[["lty"]]))))
arglist[["lty"]] <- NULL
if (all(is.na(arglist[["cex"]])))
arglist[["cex"]] <- 1
arglist[["merge"]] <- FALSE ## '$merge : language do.lines && has.pch'
for (a in names(arglist)) {
if (is.language(arglist[[a]])) {
if (!sum(nchar(as.character(arglist[[a]]))))
next
if (verbose)
message(a)
if (isTRUE(getOption("ursaNoticeMatchCall")))
message('panel_legend: try `mget(names(match.call())[-1])` instead of `as.list(match.call())`')
res <- try(eval.parent(arglist[[a]]),silent=TRUE)
if (inherits(res,"try-error")) {
next
}
arglist[[a]] <- res
}
}
arglist[["title.col"]] <- arglist[["text.col"]]
arglist[["cex"]] <- arglist[["cex"]]/par()$cex
lname <- names(items)
iname <- c(sapply(items,function(x) x$name))
if (is.null(lname))
lname <- iname
else if (length(ind <- which(!nchar(lname))))
lname[ind] <- iname[ind]
arglist[["legend"]] <- lname
# arglist[["pch"]] <- unname(sapply(items,function(x) x$pch))
# arglist[["title.cex"]] <- arglist[["cex"]]
if (length(ind <- which(sapply(arglist,class) %in% "call"))) {
# attach(arglist)
arglist[ind] <- lapply(names(arglist)[ind],function(a) {
arglist[[a]] <- with(arglist,eval(as.call(arglist[[a]])))
# arglist[[a]] <- eval(as.call(arglist[[a]]))
})
# detach("arglist")
}
if ((all(arglist$col=="transparent"))&&(all(arglist$fill=="transparent"))) {
arglist$col <- arglist$border
arglist$angle <- NULL
arglist$density <- NULL
arglist$fill <- NULL
arglist$pch <- NA
}
if (verbose)
str(arglist)
ret <- do.call("legend",arglist)
##~ ret <- legend(x="topright",legend=c("213856","213857"),fill="transparent"
##~ ,col="white",border="transparent",pch=21,density=NA
##~ ,bty="o",bg="#0000007F",box,lwd=0.1,box.lty="solid"
##~ ,box.col="black",pt.bg=c('213856'="#978035FF",'213857'="#677EC9FF")
##~ ,pt.cex=2.5,pt.lwd=2,adj=c(0,0.5),text.col="white",merge=FALSE
##~ ,horiz=TRUE,title.col="white",title.adj=0.5)
invisible(ret)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/xxx.panel_legend.R
|
'panel_wind' <- function(u,v,x,y,col="black",lwd=0.5,rarity=32,self=FALSE) {
if ((!self)&&(.skipPlot(TRUE)))
return(NULL)
if ((!missing(u))&&(missing(v))&&(missing(x))&&(missing(y))) {
v <- u[2]
u <- u[1]
}
g1 <- session_grid()
s <- 2*pi/3
b <- as.data.frame(regrid(c(u=u,v=v),mul=1/rarity))
b$r <- with(b,sqrt(u*u+v*v))
b$a <- with(b,atan2(v,u))#*180/pi
b$m <- 0.65*session_cellsize()
b$x2 <- b$x-b$m*cos(b$a)
b$y2 <- b$y-b$m*sin(b$a)
if (FALSE)
print(series(b),digits=3)
b$x3 <- with(b,x+0.8*(x2-x))
b$y3 <- with(b,y+0.8*(y2-y))
b$x4 <- with(b,x3+0.2*m*cos(a+s))
b$y4 <- with(b,y3+0.2*m*sin(a+s))
b$x5 <- b$x2
b$y5 <- b$y2
b$x6 <- with(b,x5+0.4*m*cos(a+s))
b$y6 <- with(b,y5+0.4*m*sin(a+s))
b$x7 <- with(b,x+0.6*(x2-x))
b$y7 <- with(b,y+0.6*(y2-y))
b$x8 <- with(b,x7+0.2*m*cos(a+s))
b$y8 <- with(b,y7+0.2*m*sin(a+s))
d <- as.ursa(b)
if (self) {
compose_open(scale=NA)
sc <- getOption("ursaPngScale")
panel_new()
ct <- panel_raster(d["r"])
}
ind0 <- which(b$r<2)
ind1 <- which(b$r>=2 & b$r<4)
ind2 <- which(b$r>=4 & b$r<8)
ind3 <- which(b$r>=8 & b$r<12)
ind4 <- which(b$r>=12)
if (FALSE)
print(c('0'=length(ind0),'1'=length(ind1),'2'=length(ind2)
,'3'=length(ind3),'4'=length(ind4)))
b0 <- b[ind0,]
b1 <- b[ind1,]
b2 <- b[ind2,]
b3 <- b[ind3,]
b4 <- b[ind4,]
for (i in seq(nrow(b0))) {
with(b0,{
points(x[i],y[i],col=col)
})
}
for (i in seq(nrow(b1))) {
with(b1,{
segments(x[i],y[i],x2[i],y2[i],col=col,lwd=lwd)
segments(x3,y3,x4,y4,col=col,lwd=lwd)
})
}
for (i in seq(nrow(b2))) {
with(b2,{
segments(x[i],y[i],x2[i],y2[i],col=col,lwd=lwd)
segments(x5,y5,x6,y6,col=col,lwd=lwd)
})
}
for (i in seq(nrow(b3))) {
with(b3,{
segments(x[i],y[i],x2[i],y2[i],col=col,lwd=lwd)
segments(x3,y3,x4,y4,col=col,lwd=lwd)
segments(x5,y5,x6,y6,col=col,lwd=lwd)
})
}
for (i in seq(nrow(b4))) {
with(b4,{
segments(x[i],y[i],x2[i],y2[i],col=col,lwd=lwd)
segments(x3,y3,x4,y4,col=col,lwd=lwd)
segments(x5,y5,x6,y6,col=col,lwd=lwd)
segments(x7,y7,x8,y8,col=col,lwd=lwd)
})
}
if (self) {
panel_decor()
compose_legend(ct)
compose_close(render=T)
}
session_grid(g1)
# display(d)
invisible(NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/xxx.panel_wind.R
|
# https://geoportal.arctic-sdi.org/
# https://geoportal.arctic-sdi.org/action?action_route=GetLayerTile&id=1&layer=arctic_cascading&style=default&tilematrixset=3575&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image%2Fpng&TileMatrix=5&TileCol=20&TileRow=11
'.webmap' <- function(obj) {
for (pkg in c("leaflet","leafem","leafpop"))
if (!requireNamespace(pkg,quietly=.isPackageInUse()))
stop(paste("Package",sQuote(pkg),"is required for this operation"))
if (is.character(obj)) {
if (file.exists(obj))
layer <- spatial_basename(obj)
else
layer <- obj
obj <- spatialize(obj,resetGrid=TRUE,style="longlat",engine="sf")
}
else {
layer <- as.character(as.list(match.call())[["obj"]]) ## try mget(names(match.call())[-1])
obj <- spatialize(obj,style="longlat")
}
# glance(obj);q()
m <- leaflet::leaflet()
m <- leaflet::addTiles(m)
m <- leafem::addMouseCoordinates(m)
m <- leafem::addFeatures(m,data=obj,popup=leafpop::popupTable(obj),weight=0.5)
m <- leafem::addHomeButton(m,ext=raster::extent(spatial_bbox(obj)[c(1,3,2,4)])
,layer.name=layer)
m
}
'polarmap' <- function(obj,epsg=NA,group=NULL,opacity=1
,addFeature=TRUE,addHomeButton=TRUE
,addMouseCoordinates=TRUE,addScaleBar=TRUE
,addMeasure=FALSE
,style=c("Arctic Connect","Arctic SDI")) {
isSDI <- isTRUE(.lgrep("sdi",style[1])>0)
isConnect <- !isSDI
if (onlyBasemap <- missing(obj)) {
if (is.null(getOption("ursaSessionGrid")))
obj <- spatialize(c(0,50,360,50))
else {
obj <- spatial_transform(polygonize(session_bbox()),4326)
}
addFeature <- FALSE
}
for (pkg in c("leaflet","leafem","leafpop"))
if (!requireNamespace(pkg,quietly=.isPackageInUse()))
stop(paste("Package",sQuote(pkg),"is required for this operation"))
if (is.character(epsg))
epsg <- as.integer(epsg)
style <- if (epsg %in% 3571:3576) epsg else "laea"
if (is_ursa(obj)) {
if (!addFeature)
obj <- polygonize(ursa_bbox(obj))
else if (F) {
obj <- colorize(obj,ramp=FALSE)
str(obj)
obj <- polygonize(obj)
str(obj)
obj <- aggregate(obj)
q()
}
# addFeature <- FALSE
}
if (is.character(obj)) {
if (file.exists(obj))
layer <- spatial_basename(obj)
else
layer <- obj
obj <- spatialize(obj,resetProj=TRUE,resetGrid=TRUE,style=style,engine="sf")
}
else {
layer <- as.character(as.list(match.call())[["obj"]]) ## try mget(names(match.call())[-1])
if (!length(grep("\\+proj=laea",spatial_crs(obj))))
obj <- spatialize(obj,resetProj=TRUE,resetGrid=TRUE,style=style)
}
if (is.na(epsg)) {
lon_0 <- as.numeric(gsub(".*\\+lon_0=(\\S+)\\s*.*$","\\1",spatial_crs(obj)))
epsg[lon_0<(-165) || lon_0>=(+135)] <- 3571 ## -180
epsg[lon_0>=(-165) && lon_0<(-125)] <- 3572 ## -150
epsg[lon_0>=(-125) && lon_0<(-70)] <- 3573 ## -100
epsg[lon_0>=(-70) && lon_0<(-25)] <- 3574 ## -40
epsg[lon_0>=(-25) && lon_0<(+50)] <- 3575 ## 10
epsg[lon_0>=(50) && lon_0<(+135)] <- 3576 ## 90
}
# g0 <- session_grid()
if (!addFeature)
spatialize(obj,epsg=epsg,style="polarmap",resetGrid=TRUE)
g1 <- session_grid()
bbox <- unname(spatial_bbox(spatial_transform(spatialize(spatial_bbox(obj)),4326)))
obj <- spatial_transform(obj,4326)
if ((.isSP(obj))&&(is.null(spatial_data(obj))))
spatial_data(obj) <- data.frame(fid=seq(spatial_count(obj)))
if ((!is.character(group))||(!nchar(group)))
group <- "AOI" # "\u2302" # as.character(as.list(match.call())$obj)
if (isConnect) {
extent <- 11000000 + 9036842.762 + 667
origin <- c(-extent, extent)
maxResolution <- 2*extent/256
minZoom <- 3
maxZoom <- 9
bounds <- list(c(-extent,extent),c(extent,-extent))
resolutions <- sapply(0:18,function(x) maxResolution/(2^x))
crsArctic <- leaflet::leafletCRS(crsClass="L.Proj.CRS",code=paste0("EPSG:",epsg)
,proj4def=ursa::spatial_crs(epsg)
,resolutions=resolutions,origin=origin,bounds=bounds)
m <- leaflet::leaflet(options=leaflet::leafletOptions(crs=crsArctic,minZoom=3,maxZoom=12))
m <- leaflet::addTiles(m
,urlTemplate=paste0("https://{s}.tiles.arcticconnect.ca/osm_"
,epsg,"/{z}/{x}/{y}.png")
,attribution=paste("Map: \uA9 ArcticConnect."
,"Data: \uA9 OpenStreetMap contributors")
,options=leaflet::tileOptions(subdomains="abc"
,noWrap=TRUE
,continuousWorld=FALSE
,opacity=opacity
,minZoom=minZoom
,maxZoom=maxZoom
)
,group="Arctic Connect"
)
}
else {
extentASDI <- 4889334.802955
scale0 <- 136421171.96428573131561279297
resolutions <- 0.28*1e-3*scale0/(2^seq(0,18))
minZoom <- 1
maxZoom <- 10
crsASDI <- leaflet::leafletCRS(crsClass="L.Proj.CRS"
,code=paste0("EPSG:",epsg)
,proj4def=spatial_crs(epsg)
,resolutions=resolutions
,origin=c(-extentASDI,extentASDI)
,bounds=list(c(-extentASDI,extentASDI)
,c(extentASDI,-extentASDI))
)
m <- leaflet::leaflet(options=leaflet::leafletOptions(worldCopyJump=F
,minZoom=minZoom
,maxZoom=maxZoom
,crs=crsASDI
,center=c(90,0)
)
)
m <- leaflet::addTiles(m
,urlTemplate=paste0("https://geoportal.arctic-sdi.org/action?"
,"&action_route=GetLayerTile"
,"&id=1"
,"&layer=arctic_cascading"
,"&style=default"
,"&Service=WMTS"
,"&Request=GetTile"
,"&Version=1.0.0"
,"&Format=image/png"
,"&tilematrixset={tileMatrix}"
,"&TileMatrix={z}"
,"&TileCol={x}"
,"&TileRow={y}"
)
,options=leaflet::tileOptions(tileMatrix=epsg
,opacity=opacity
)
# ,opacity=0.3 ## unused argument
,attribution=paste0("<a href=https://arctic-sdi.org"
,"/services/topografic-basemap/>"
,"Arctic SDI Topographic Basemap"
,"</a>")
,group="Arctic SDI"
)
}
# m <- leaflet::setView(m,lat=89.999,lng=-110,zoom=2)
# sink("C:/tmp/res5-SDI.Rout")
# str(m)
# sink()
if (addMouseCoordinates)
m <- leafem::addMouseCoordinates(m)
if (T) {
# z <- which.min(abs(g1$resx-resolutions))
# z[z>maxZoom] <- maxZoom
# print(bbox)
if (T)
bbox <- unname(spatial_bbox(obj))
# print(bbox)
# ll <- unname(c((bbox[1]+bbox[3])/2,(bbox[2]+bbox[4])/2))
# m <- leaflet::setView(m,lng=ll[1],lat=ll[2],zoom=z)
m <- leaflet::fitBounds(m,lng1=bbox[1],lat1=bbox[2],lng2=bbox[3],lat2=bbox[4]
,options=list(maxZoom=maxZoom))
}
if (addFeature) {
m <- leafem::addFeatures(m,data=obj
,popup=leafpop::popupTable(obj)
,weight=0.5
,group=group
)
}
else if (F) {
z <- which.min(abs(g1$resx-resolutions))
z[z>maxZoom] <- maxZoom
if (F) {
ll <- c(with(g1,.project(cbind((maxx+minx)/2,(maxy+miny)/2),crs,inv=TRUE)))
}
else {
bbox <- spatial_bbox(obj)
ll <- unname(c((bbox[1]+bbox[3])/2,(bbox[2]+bbox[4])/2))
}
# print(ll)
m <- leaflet::setView(m,lng=ll[1],lat=ll[2],zoom=z)
# m <- leaflet::fitBounds(m,bbox[1],bbox[2],bbox[3],bbox[4])
#q()
}
if (addScaleBar)
m <- leaflet::addScaleBar(m,options=leaflet::scaleBarOptions(imperial=FALSE))
if (addHomeButton) {
m <- leafem::addHomeButton(m
# ,ext=raster::extent(spatial_bbox(obj)[c(1,3,2,4)])
,ext=matrix(spatial_bbox(obj),ncol=2)
,group=group
)
}
if (addMeasure) {
m <- leaflet::addMeasure(m,primaryLengthUnit="meters",primaryAreaUnit="sqmeters")
}
m
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/xxx.polarmap.R
|
'spatialize' <- function(dsn,engine=c("native","sf","geojsonsf")
,layer=".*",field=".+",coords=c("x","y"),crs=character()
,geocode="",place="",area=c("bounding","point","shape")
,grid=NULL,size=NA,cell=NA,expand=1,border=NA
,lat0=NA,lon0=NA,resetProj=FALSE,resetGrid=FALSE
,style="auto" ## auto none internal keep
# ,zoom=NA
,subset="",verbose=FALSE,...) {
if (.isPackageInUse()) {
engine <- match.arg(engine)
}
else {
engList <- as.character(as.list(match.fun("spatialize"))[["engine"]])[-1]
if (length(engine)<length(engList)) {
engList <- c(engList,"sp")
}
engine <- match.arg(engine,engList)
}
if (resetGrid)
session_grid(NULL)
toResetGrid <- 0L
# message(paste(.parentFunc(),collapse=" -> "))
# print(c(expand=expand,border=border))
# geocode <- match.arg(geocode)
geocodeStatus <- FALSE
hasOpened <- FALSE
toUnloadMethods <- !("methods" %in% .loaded())
if (is.na(resetProj))
resetProj <- TRUE
cpg <- NULL
if (engine=="sp") {
isSF <- FALSE
isSP <- TRUE
}
else if (engine %in% c("sf","geojsonsf")) {
isSF <- requireNamespace("sf",quietly=.isPackageInUse())
isSP <- !isSF
}
else if (F) { ## deprecated 'rgdal'
loaded <- loadedNamespaces() #.loaded()
if (any(c("sf","geojsonsf") %in% loaded))
isSF <- TRUE
else if (("sp" %in% loaded)||("rgdal" %in% loaded))
isSF <- FALSE
else
isSF <- requireNamespace("sf",quietly=.isPackageInUse())
isSP <- !isSF
}
else {
isSF <- requireNamespace("sf",quietly=.isPackageInUse())
isSP <- !isSF
}
jsonSF <- FALSE
if ((length(crs))&&("auto" %in% style))
style <- .epsg2proj4(crs)
else {
crs2 <- .epsg2proj4(style)
if (.lgrep("\\+(init|proj)",crs2))
style <- crs2
}
isEPSG <- FALSE
# isPROJ4 <- nchar(style)>36 ## need more accurate detecton of proj4
isPROJ4 <- .lgrep("(\\+init=epsg\\:|\\+proj=\\w+|\\+(ellps|datum=))",style)>0
if (length(style)) {
if (is.numeric(style))
isEPSG <- TRUE
else if ((is.character(style))&&(!nchar(.gsub("\\d","",style))))
isEPSG <- TRUE
}
if ((isEPSG)&&(is.numeric(style)))
style <- as.character(style)
if (isPROJ4 | isEPSG)
session_grid(NULL)
isNative <- engine=="native"
if (is.character(dsn)) {
if (length(dsn)>1) {
pattern <- "\\.(gpkg|tab|kml|json|geojson|mif|fgb|sqlite|shp|osm|csv)(\\.(zip|rar|gz|bz2))*$"
dsn <- dsn[.grep(pattern,basename(dsn))]
if (length(dsn)!=1)
stop("Either filename is not recognized or multiple files")
}
}
proj4 <- NULL
if ((!(style %in% c("auto","keep")))&&
(isFALSE(resetProj))) { ## ++20230612
if (!((is.character(dsn))&&(style %in% .tileService())))
resetProj <- TRUE
}
if (!((is.character(dsn))&&(length(dsn)==1))) {
nextCheck <- TRUE
if ((.isSF(dsn))||(.isSP(dsn))) {
## try mget(names(match.call())[-1])
if ((resetProj)||(length(as.list(match.call())[-1])==1))
session_grid(NULL)
}
if (FALSE) { ## 20180125--
spcl <- paste0("Spatial",c("Points","Lines","Polygons"))
spcl <- c(spcl,paste0(spcl,"DataFrame"))
}
else
spcl <- "Spatial"
# if ((nextCheck)&&(inherits(dsn,spcl))) {
if ((nextCheck)&&(.isSP(dsn))) {
if ((!toUnloadMethods)&&(!("methods" %in% .loaded()))) {
if (FALSE) {
# .require("methods")
opW <- options(warn=1)
warning("Package 'methods' is required for S4 object coercion.")
options(opW)
}
toUnloadMethods <- TRUE
}
if ((!isNative)&&(isSF)) {
obj <- sf::st_as_sf(dsn)
}
else {
isSP <- TRUE
isSF <- !isSP
obj <- dsn
}
rm(dsn)
nextCheck <- FALSE
}
if ((nextCheck)&&(inherits(dsn,"sf"))) {
if (isNative) {
isSF <- TRUE
isSP <- !isSF
}
else if (isSP) { ## cross-classes
dsn <- sf::as_Spatial(dsn)
}
obj <- dsn
rm(dsn)
nextCheck <- FALSE
}
if ((nextCheck)&&(is.array(dsn))) {
return(display(dsn,...))
}
if ((nextCheck)&&(is.ursa(dsn))) {
if ((isSF)||(isSP)) {
obj <- as.data.frame(dsn)
if (style!="auto") {
crsNow <- style
session_grid(NULL)
}
else
crsNow <- ursa_proj(dsn)
isCRS <- ((!is.na(crsNow))&&(nchar(crsNow)))
if (!((is.character(coords))&&(length(coords)==2))) {
coords <- basename(.maketmp(2))
colnames(obj)[1:2] <- coords
}
if (isSF) {
if (isCRS)
obj <- sf::st_as_sf(obj,coords=coords,crs=crsNow)
else
obj <- sf::st_as_sf(obj,coords=coords)
}
else if (isSP) {
sp::coordinates(obj) <- coords
if (isCRS)
sp::proj4string(obj) <- crsNow
}
rm(dsn) ## requierd?
nextCheck <- FALSE
}
else
return(display(dsn,...))
}
if ((nextCheck)&&(is.data.frame(dsn))&&
(is.character(coords))&&(length(coords)==2)) {
if (inherits(dsn,"track_xy"))
coords <- c("x_","y_")
else if (!all(coords %in% colnames(dsn))) {
mname <- colnames(dsn)
indX <- .grep("^coords.x1$",mname)
if (!length(indX))
indX <- .grep("^x$",mname)
if (!length(indX))
indX <- .grep("^(lng$|lon)",mname)
if (!length(indX))
indX <- .grep("^east",mname)
if (!length(indX))
indX <- .grep("^x1$",mname)
indY <- .grep("^coords.x2$",mname)
if (!length(indY))
indY <- .grep("^y$",mname)
if (!length(indY))
indY <- .grep("^lat",mname)
if (!length(indY))
indY <- .grep("^north",mname)
if (!length(indY))
indY <- .grep("^x2$",mname)
if ((!length(indX))&&(!length(indY))) {
indX <- .grep("^000x1$",mname)
indY <- .grep("^000x2$",mname)
}
if ((!length(indX))&&(!length(indY))) {
indX <- .grep("^x_$",mname)
indY <- .grep("^y_$",mname)
}
if ((!length(indX))&&(!length(indY))) {
indX <- .grep(paste0("^",coords[1],"$"),mname)
indY <- .grep(paste0("^",coords[2],"$"),mname)
}
ind <- c(indX[1],indY[1])
if ((any(is.na(ind)))||(length(ind)!=2)) {
stop("unable to detect 'x' and 'y' coordinates")
}
coords <- mname[ind]
}
#isCRS <- ((!is.na(crsNow))&&(nchar(crsNow)))
if (style!="auto")
crsNow <- style
else if (inherits(dsn,"track_xy"))
crsNow <- sf::st_crs(attr(dsn,"crs_",exact=TRUE))$proj4string
else
crsNow <- NA
if (is.na(crsNow)) {
if ((.lgrep("^(lon|lng$)",coords[1])==1)&&(.lgrep("^lat",coords[2])==1))
crsNow <- "+proj=longlat +datum=WGS84 +no_defs"
else if (is.data.frame(dsn)) {
if (is.character(attr(dsn,"crs")))
crsNow <- attr(dsn,"crs")
}
}
isCRS <- ((!is.na(crsNow))&&(nchar(crsNow)))
if (isSF) {
xy <- dsn[,coords]
ind <- unique(c(which(is.na(xy[,1])),which(is.na(xy[,2]))))
if (length(ind))
dsn <- dsn[-ind,]
if (inherits(try(sf::st_crs(crsNow)),"try-error"))
obj <- sf::st_as_sf(dsn,coords=coords,crs=4326)
else if (isCRS)
obj <- sf::st_as_sf(dsn,coords=coords,crs=crsNow)
else
obj <- sf::st_as_sf(dsn,coords=coords)
}
else if (isSP) {
obj <- dsn
sp::coordinates(obj) <- coords
if (isCRS) {
if (!.try(sp::proj4string(obj) <- crsNow))
sp::proj4string(obj) <- "EPSG:4326"
}
}
rm(dsn)
nextCheck <- FALSE
}
if ((FALSE)&&(nextCheck)&&((isSF)||(isNative))) { ## has checked early
if (isNative) {
loaded <- loadedNamespaces() #.loaded() ## changed 20180226
if ("sf" %in% loaded)
isSF <- TRUE
else if (("sp" %in% loaded)||("rgdal" %in% loaded))
isSF <- FALSE
else
isSF <- requireNamespace("sf",quietly=.isPackageInUse())
isSP <- !isSF
}
# nextCheck <- isSP
}
if ((nextCheck)&&(isSF)) {
if (is.array(dsn)) {
message("process 'array' by 'sf' -- TODO (dilemma: raster is array)")
}
else if (is.numeric(dsn)) {
proj4 <- attr(dsn,"crs") ## from 'ursa_bbox()'
limLonLat <- all(dsn>=-360 & dsn<=+360)
if (length(dsn)==2) { ## point
# obj <- sf::st_sfc(sf::st_point(dsn))
obj <- sf::st_as_sf(data.frame(lon=dsn[1],lat=dsn[2])
,coords=c("lon","lat"))#,crs=4326)
}
else if (length(dsn)==4) { ## boundary
if (dsn[1]>dsn[3])
dsn[1] <- dsn[1]-360
obj <- matrix(dsn[c(1,2,1,4,3,4,3,2,1,2)],ncol=2,byrow=TRUE)
if (TRUE) {
x <- obj[,1]
y <- obj[,2]
n <- 256
x <- c(seq(x[1],x[2],len=n),seq(x[2],x[3],len=n)
,seq(x[3],x[4],len=n),seq(x[4],x[5],len=n))
y <- c(seq(y[1],y[2],len=n),seq(y[2],y[3],len=n)
,seq(y[3],y[4],len=n),seq(y[4],y[5],len=n))
obj <- cbind(x,y)
}
# colnames(obj) <- c("lon","lat")
##~ obj <- sf::st_sf(sf::st_sfc(sf::st_polygon(list(obj)))
##~ ,coords=c("lon","lat"),crs=4326)
# obj <- sf::st_sfc(sf::st_multilinestring(list(obj)))#,crs=4326)
obj <- sf::st_sfc(sf::st_polygon(list(obj)))#,crs=4326)
# obj <- sf::st_sf(obj)
}
else
obj <- NULL
if (!is.null(obj)) {
if (limLonLat)
sf::st_crs(obj) <- 4326
else if (!is.null(proj4)) {
sf::st_crs(obj) <- proj4
style <- proj4
# grid <- session_grid() ## ++ 20220702
# session_grid(NULL) ## -- 20220702 ??
}
else
sf::st_crs(obj) <- session_crs()
}
else
rm(obj)
}
else if (inherits(dsn,c("sfc","sf"))) {
obj <- dsn
dsn <- class(obj)
}
else {
if ((TRUE)&&(inherits(dsn,"list"))&&(inherits(dsn,"data.frame"))) {
if (length(unique(sapply(dsn,length)))==1)
dsn <- as.data.frame(dsn)
cl <- sapply(dsn,function(x) {
if (!inherits(x,c("integer","numeric","character","factor"
,"Date","POSIXt")))
stop("TODO #38")
})
}
obj <- try(sf::st_as_sf(dsn,coords=coords))
if (inherits(obj,"try-error")) {
cat(geterrmessage())
message(paste("(#32) unable to process object of class"
,.sQuote(paste(class(dsn),collapse=" | "))))
return(NULL) ## 32L
}
else {
limLonLat <- all(dsn[,coords]>=-360 & dsn[,coords]<=+360)
if (limLonLat)
sf::st_crs(obj) <- 4326
}
dsn <- class(dsn)
}
}
else if ((nextCheck)&&(isSP)) { # if (isSP)
proj4 <- attr(dsn,"crs")
if (is.array(dsn))
message("process 'array' by 'sp' -- TODO (dilemma: raster is array)")
else if (is.numeric(dsn)) {
limLonLat <- all(dsn>=-360 & dsn<=+360)
if (length(dsn)==2) { ## point
obj <- data.frame(lon=dsn[1],lat=dsn[2])
sp::coordinates(obj) <- ~lon+lat
# sp::proj4string(obj) <- sp::CRS("+init=epsg:4326")
}
else if (length(dsn)==4) { ## boundary
if (dsn[1]>dsn[3])
dsn[1] <- dsn[1]-360
obj <- matrix(dsn[c(1,2,1,4,3,4,3,2,1,2)],ncol=2,byrow=TRUE)
if (TRUE) {
x <- obj[,1]
y <- obj[,2]
n <- 256
x <- c(seq(x[1],x[2],len=n),seq(x[2],x[3],len=n)
,seq(x[3],x[4],len=n),seq(x[4],x[5],len=n))
y <- c(seq(y[1],y[2],len=n),seq(y[2],y[3],len=n)
,seq(y[3],y[4],len=n),seq(y[4],y[5],len=n))
obj <- cbind(x,y)
}
# obj <- sp::SpatialLines(list(sp::Lines(sp::Line(obj),1L))
# ,proj4string=sp::CRS("+init=epsg:4326"))
obj <- sp::SpatialLines(list(sp::Lines(sp::Line(obj),1L)))
}
# else
# obj <- NULL
if (limLonLat) {
sp::proj4string(obj) <- sp::CRS("EPSG:4326")
}
else if (!is.null(proj4)) {
sp::proj4string(obj) <- sp::CRS(proj4,doCheckCRSArgs=FALSE)
style <- proj4
session_grid(NULL)
}
else {
sp::proj4string(obj) <- sp::CRS(session_crs(),doCheckCRSArgs=FALSE)
}
}
else if (inherits(dsn,"data.frame")) {
obj <- dsn
sp::coordinates(obj) <- coords
limLonLat <- all(dsn[,coords]>=-360 & dsn[,coords]<=+360)
if (limLonLat)
sp::proj4string(obj) <- sp::CRS("EPSG:4326")
dsn <- class(dsn)
}
else if (inherits(dsn,"ursaGrid")) {
obj <- as.data.frame(dsn)
sp::coordinates(obj) <- c("x","y")
sp::proj4string(obj) <- sp::CRS(spatial_crs(dsn),doCheckCRSArgs=FALSE)
sp::gridded(obj) <- TRUE
}
else {
obj <- try(methods::as(dsn,"Spatial"))
}
if (inherits(obj,"try-error")) {
message(paste("(#33) unable to process object of class"
,.sQuote(class(dsn))))
return(NULL) ## 33L
}
else {
# isSP <- TRUE
# isSF <- !isSP
}
}
}
else {
if ((FALSE)&&(isNative)) { ## this check has been done early
loaded <- .loaded()
if ("sf" %in% loaded)
isSF <- TRUE
else if (("sp" %in% loaded)||("rgdal" %in% loaded))
isSF <- FALSE
else
isSF <- requireNamespace("sf",quietly=.isPackageInUse())
isSP <- !isSF
}
if (file.exists(zname <- paste0(dsn,".gz"))) {
dsn <- zname
}
else if (file.exists(zname <- paste0(dsn,".bz2"))) {
dsn <- zname
}
if (!file.exists(dsn)) {
list1 <- spatial_dir(path=dirname(dsn),pattern=basename(dsn))
if (length(list1)==1)
dsn <- list1
}
if (!file.exists(dsn)) {
aname <- paste0(dsn,".zip")
if (isZip <- file.exists(aname)) {
ziplist <- unzip(aname,exdir=tempdir());on.exit(file.remove(ziplist))
dsn <- .grep("\\.shp$",ziplist,value=TRUE)
}
else if (.lgrep("^(http|https|ftp)://",dsn)) {
mode <- ifelse(.lgrep("(txt|json)$",dsn),"wt","wb")
dsn <- .ursaCacheDownload(dsn,mode=mode)
}
else if (.lgrep("\\.(gpkg|tab|kml|json|geojson|mif|fgb|sqlite|shp|osm)(\\.(zip|gz|bz2))*$"
,basename(dsn))) {
message(paste("#40. It seems that specified non-existent file name"
,sQuote(dsn),"rather than geocode request."))
return(NULL)
}
else {
geocodeArgs <- as.list(args(.geocode))
geocodeList <- eval(geocodeArgs$service)
if ((length(geocode)==1)&&(!nchar(geocode)))
geocode <- geocodeList
if (FALSE) {
arglist <- list(...)
if (length(ind <- .grep("area",names(arglist)))) {
area <- arglist[[ind]]
}
else
area <- eval(geocodeArgs$area)
}
da <- try(.geocode(dsn,service=geocode[1],place=place
,area=area,select="top",verbose=verbose))
if ((inherits(da,"try-error"))||((is.null(da))&&(length(geocode)>1))) {
geocode <- geocode[2]
da <- .geocode(dsn,service=geocode,area=area,select="top"
,verbose=verbose)
}
else if (length(geocode)>1)
geocode <- geocode[1]
if (is.null(da)) {
cat(paste("unable to geocode request",dQuote(dsn),"\n"))
return(NULL)
}
if (is_spatial(da)) {
# obj <- data.frame(src=dsn)
# spatial_geometry(obj) <- da
obj <- da
geocodeStatus <- TRUE
hasOpened <- TRUE
}
else {
if (is.null(dim(da))) {
if (length(da)==4)
da <- da[c("minx","miny","maxx","maxy")]
else if (length(da)==2) {
arglist <- as.list(match.call()) ## try mget(names(match.call())[-1])
arglist$dsn <- da
arglist[[1]] <- tail(as.character(arglist[[1]]),1)
if ((TRUE)&&("auto" %in% style)) {
arglist$style <- switch(geocode
,nominatim="CartoDB"
,pickpoint="mapnik"
,google="google terrain color"
,"CartoDB")
}
return(do.call(arglist[[1]],arglist[-1])) ## RECURSIVE!!!
}
}
else
da <- da[,c("minx","miny","maxx","maxy")]
if (da[1]>da[3])
da[3] <- da[3]+360
da <- matrix(da[c(1,2,1,4,3,4,3,2,1,2)],ncol=2,byrow=TRUE)
if (TRUE) {
x <- da[,1]
y <- da[,2]
n <- 256
x <- c(seq(x[1],x[2],len=n),seq(x[2],x[3],len=n)
,seq(x[3],x[4],len=n),seq(x[4],x[5],len=n))
y <- c(seq(y[1],y[2],len=n),seq(y[2],y[3],len=n)
,seq(y[3],y[4],len=n),seq(y[4],y[5],len=n))
da <- cbind(x,y)
}
if (isSF) {
obj <- sf::st_sfc(sf::st_multilinestring(list(da)),crs=4326)
# sf::st_write(obj,"rect.geojson");q()
}
if (isSP) {
obj <- sp::SpatialLines(list(sp::Lines(sp::Line(da),1L))
,proj4string=sp::CRS("EPSG:4326"))
}
geocodeStatus <- TRUE
hasOpened <- TRUE
}
}
}
else {
jsonSF <- (engine %in% c("native","geojsonsf"))&&(isSF)&&(.lgrep("\\.geojson",dsn))&&
(requireNamespace("geojsonsf",quietly=.isPackageInUse()))
# print(data.frame(engine=engine,isSP=isSP,isSF=isSF,jsonSF=jsonSF))
if (jsonSF)
NULL
else if (isZip <- .lgrep("\\.zip$",dsn)>0) {
opW <- options(warn=1)
ziplist <- unzip(dsn,exdir=tempdir())
options(opW)
if ((FALSE)&&(!length(ziplist))&&(nchar(Sys.which("7z")))) {
ziplist <- system(paste("7z","l","-scsUTF-8",dsn),intern=TRUE)
print(ziplist)
}
on.exit(file.remove(ziplist))
dsn <- .grep("\\.(shp|fgb|sqlite|gpkg|geojson)$",ziplist,value=TRUE)
}
else if ((nchar(Sys.which("gzip")))&&(isZip <- .lgrep("\\.gz$",dsn)>0)) {
dsn0 <- dsn
dsn <- tempfile();on.exit(file.remove(dsn))
system2("gzip",c("-f -d -c",.dQuote(dsn0)),stdout=dsn,stderr=FALSE)
}
else if ((nchar(Sys.which("bzip2")))&&(isZip <- .lgrep("\\.bz2$",dsn)>0)) {
dsn0 <- dsn
dsn <- tempfile();on.exit(file.remove(dsn))
system2("bzip2",c("-f -d -c",.dQuote(dsn0)),stdout=dsn,stderr=FALSE)
}
else if ((T)&&(nchar(Sys.which("7z")))&&(isZip <- .lgrep("\\.rar$",dsn)>0)) {
stop(dsn,": this archive type is not supported")
ziplist <- system(paste("7z","l","-scsUTF-8",dsn),intern=TRUE)
ind <- .grep("-{19}\\s",ziplist)
ziplist <- ziplist[(ind[1]+1):(ind[2]-1)]
ziplist <- substr(ziplist,54L,nchar(ziplist))
ziplist <- .gsub("\\\\","/",ziplist)
dir1 <- dir(path=tempdir())
# print(dir1)
system(paste("7z","e","-aos",.dQuote(dsn),paste0("-o",tempdir())))
dir2 <- dir(path=tempdir())
# print(dir2)
print(ziplist)
q()
print(dir(path=tempdir()))
file.remove(ziplist)
q()
rarlist <- system(paste("rar","lb",.dQuote(dsn)),intern=TRUE)
print(rarlist)
system2("rar",c("e -o+",.dQuote(dsn),tempdir()),stdout=NULL)
# print(rarlist)
# file.remove(rarlist)
stop("RAR")
}
if (isCDF <- .lgrep("\\.(nc|hdf)$",dsn)>0) {
obj <- .read_nc(dsn,".+")
if (!inherits(obj,"data.frame"))
obj <- as.data.frame(as.ursa(obj[sapply(obj,is.ursa)]))
else {
indX <- .grep("^(lon|x$|west|east)",colnames(obj))
indY <- .grep("^(lat|y$|south|north)",colnames(obj))
if (!length(indX))
indX <- 1L
if (!length(indY))
indY <- 2L
colnames(obj)[c(indX,indY)] <- c("x","y")
}
p4s <- attr(obj,"crs")
if (isSF) {
if (!is.null(p4s))
obj <- sf::st_as_sf(obj,coords=c("x","y"),crs=attr(obj,"crs"))
else
obj <- sf::st_as_sf(obj,coords=c("x","y"))
}
if (isSP) {
sp::coordinates(obj) <- ~x+y
if (!is.null(p4s))
sp::proj4string(obj) <- sp::CRS(p4s,doCheckCRSArgs=FALSE)
}
hasOpened <- TRUE
# display(a)
}
}
if ((!hasOpened)&&((!geocodeStatus)||(file.exists(dsn)))) {
if (jsonSF) {
epsg <- "XXXXXXXXX"
inMemory <- FALSE
a <- dsn
opGeoW <- options(warn=-1)
if (T | .lgrep("\\.(gz|bz2|xz)$",a)) {
a <- readLines(a)
inMemory <- TRUE
}
obj <- try(geojsonsf::geojson_sf(a),silent=TRUE)
if (inherits(obj,"try-error")) {
if (!inMemory) {
a <- readLines(a)
inMemory <- TRUE
obj <- try(geojsonsf::geojson_sf(a),silent=TRUE)
}
}
if (inherits(obj,"try-error")) {
a <- paste(a,collapse="")
obj <- try(geojsonsf::geojson_sf(a))
}
if (inherits(obj,"try-error")) {
obj <- sf::st_read(dsn,quiet=TRUE)
if (!spatial_count(obj))
return(obj)
}
else {
if (T & inMemory) {
if (length(a)==1)
a2 <- substr(a,1,160)
else
a2 <- head(a,5)
if (length(ind <- grep("\"crs\"\\:",a2))) {
if (length(grep("EPSG",a2[ind])))
epsg <- gsub(".*EPSG\\D+(\\d+)\\D+.*","\\1",a2[ind])
}
}
if (nchar(epsg)<7)
spatial_crs(obj) <- as.integer(epsg)
}
options(opGeoW)
if (length(ind <- which(sapply(obj,inherits,"character")))) {
for (i in ind) {
a <- na.omit(obj[,i,drop=TRUE])
if (length(grep("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z"
,a))==length(a)) {
d <- as.POSIXct(obj[,i,drop=TRUE],tz="UTC"
,format="%Y-%m-%dT%H:%M:%SZ")
obj[,i] <- as.POSIXct(as.numeric(d),origin=.origin())
}
else if (length(grep("^\\d{4}-\\d{2}-\\d{2}$",a))==length(a)) {
obj[,i] <- as.Date(obj[,i,drop=TRUE],tz="UTC")
}
}
}
}
else {
opW <- options(warn=ifelse(isSP,-1,0))
if (isSF) {
lname <- try(sf::st_layers(dsn)$name)
}
else {
lname <- try(.rgdal_ogrListLayers(dsn))
}
if (inherits(lname,"try-error")) {
cat("Cannot get layers\n")
return(NULL)
}
if (!is.character(layer))
layer <- lname[layer[1]]
else
layer <- .grep(layer,lname,value=TRUE)
if (length(layer)>1) {
if (prevBehaviour <- FALSE) {
print(paste("Select only one layer:",paste(paste0(seq(layer),")")
,.sQuote(layer),collapse=", ")),quote=FALSE)
return(NULL)
}
else {
rel <- as.list(match.call()) ## try mget(names(match.call())[-1])
rname <- names(rel)
j <- NULL
for (i in seq_along(rel)[-1]) {
if (is.language(rel[[i]])) {
if (isTRUE(getOption("ursaNoticeMatchCall")))
message('spatialize: try `mget(names(match.call())[-1])` instead of `as.list(match.call())`')
res <- eval.parent(rel[[i]])
if (is.null(res))
j <- c(j,i)
else if (is.language(res)) {
res <- eval.parent(res)
if (!is.language(res)) {
assign(rname[i],res)
rel[[i]] <- res
}
else
stop("unable to evaluate agrument ",.sQuote(rname[i]))
}
else
rel[[i]] <- res
}
}
if (length(j))
rel <- rel[-j]
arglist <- c(rel,list(...))
ret <- lapply(layer,function(l) {
arglist$layer <- l
spatial_trim(do.call(as.character(arglist[[1]]),arglist[-1]))
})
names(ret) <- layer
return(ret)
}
}
if (isSF) {
# opW2 <- options(warn=0)
obj <- sf::st_read(dsn,layer=layer,quiet=TRUE)
# options(opW2)
if (!spatial_count(obj))
return(obj)
if (TRUE) {
.o <- obj
obj <- try(sf::st_zm(.o,drop=TRUE))
if (inherits(obj,"try-error"))
obj <- .o
rm(.o)
}
}
else {
if (isSHP <- .lgrep("\\.shp$",dsn)>0) {
cpgname <- .gsub("\\.shp$",".cpg",dsn)
if (file.exists(cpgname)) {
cpg <- readLines(cpgname,warn=FALSE)
}
else
cpg <- "UTF-8"
}
else {
cpg <- "UTF-8"
}
##~ obj <- readOGR(dsn,layer,pointDropZ=TRUE,encoding=enc
##~ ,use_iconv=!is.null(enc),verbose=FALSE)
obj <- .rgdal_readOGR(dsn,layer,pointDropZ=TRUE,encoding=cpg
,use_iconv=cpg %in% "UTF-8"
,verbose=FALSE)
## --20191112 use_iconv=!isSHP
if ((length(names(obj))==1)&&(names(obj)=="FID")) {
info <- .rgdal_ogrInfo(dsn,layer)
if (info$nitems==0)
methods::slot(obj,"data")$FID <- NULL
}
}
options(opW)
}
}
if (geocodeStatus) {
isSP <- .isSP(obj)
isSF <- .isSF(obj)
}
}
if ("keep" %in% style) {
crs <- spatial_crs(obj)
# style <- crs
# print(data.frame(style=style,crs=crs,isEPSG=isEPSG,isPROJ4=isPROJ4))
# print(resetProj)
}
# resetProj <- FALSE
if (verbose)
print(c('engine.sf'=isSF,'engine.sp'=isSP))
if (nchar(subset)) {
obj <- do.call("subset",list(obj,parse(text=subset)))
}
if ((geocodeStatus)&&("auto" %in% style)) {
style <- switch(geocode,nominatim=c("CartoDB","mapnik","openstreetmap color")[1]
,pickpoint="mapnik"
,google="google terrain color")
}
if ((toUnloadMethods)&&("package:methods" %in% search())) {
# print(search())
detach("package:methods",unload=FALSE)
# but namespace "methods" is not unloaded, because namespace "sp" is loaded
# 'as' is not found now
}
if (FALSE) { ## deprecated
if (isSF) {
dname <- try(names(sf::st_agr(obj)),silent=TRUE)
if (inherits(dname,"try-error"))
dname <- character()
}
else if (isSP) {
dname <- try(colnames(methods::slot(obj,"data")),silent=TRUE)
if (inherits(dname,"try-error"))
dname <- character()
}
}
else
dname <- spatial_fields(obj)
dname0 <- dname
hasTable <- length(dname)>0
if (is.na(field)[1])
field <- ".+"
else if (length(field)>1)
field <- paste0("^(",paste(field,collapse="|"),")$")
dname <- .grep(field,dname,value=TRUE)
# str(dname);q()
if ((hasTable)&&(!length(dname))) {
message("unable to get fields by name")
# str(asf)
# return(invisible(20L))
}
if ((!identical(dname0,dname))&&(length(dname))) {
if (isSF)
obj <- obj[,dname]
if (isSP) {
obj <- obj[,dname]
}
}
if (hasTable) {
if (isSF)
cl <- lapply(obj,class)[dname]
else if (isSP)
cl <- lapply(methods::slot(obj,"data"),class)[dname]
for (i in seq_along(dname)) {
cl2 <- cl[i]
if (isSF) {
da <- obj[,dname[i],drop=TRUE] ## sf>=0.5
if (inherits(da,c("track_xy","random_points")))
da <- unclass(da)
# da <- obj[,dname[i],drop=TRUE][,,drop=TRUE] ## sf>=0.4
# str(da)
}
if (isSP) {
da <- methods::slot(obj,"data")[,dname[i],drop=TRUE]
}
if (is.character(da)) {
if (jsonSF) {
ind <- which(Encoding(da) %in% c("unknown"))
if (length(ind))
Encoding(da[ind]) <- "UTF-8"
}
# str(dname[i])
isDateTime <- FALSE
skipParse <- TRUE # .isPackageInUse()
# if (dname[i]=="time")
# str(da)
nc <- try(nchar(na.omit(da)))
if (inherits(nc,"try-error")) {
msg <- attr(nc,"condition")$message
if (.lgrep("element\\s\\d+",msg)) {
ind <- as.integer(.gsub(".*element\\s(\\d+).*","\\1",msg))
if (!is.na(ind))
msg <- paste0(msg,": ",da[ind])
}
message("Data field ",.sQuote(dname[i]),": ",msg)
# str(da)
# print(c(warn=getOption("warn")))
if (F) {
opW <- options(warn=ifelse(.isPackageInUse(),1,1))
warning("Check specified encoding for input data table")
options(opW)
}
}
else if ((dev <- TRUE)&&(length(unique(nc))==1)&&
(.lgrep("\\d{4}.*\\d{2}.*\\d{2}",da))) {
nNA <- length(which(is.na(da)))
s <- sapply(gregexpr("(-|\\.|/)",da),function(x) length(x[x>=0]))
if (all(s>=2)) {
s <- sapply(gregexpr("(-|\\.|/)",da),function(x) diff(x)[1])
if (all(s==3))
da <- .gsub(".*(\\d{4})(.?)(\\d{2})(.?)(\\d{2})(.*)"
,"\\1-\\3-\\5\\6",da)
}
else if (FALSE & length(grep("(\\d{8})($|\\D.*$)",da))==length(da)) {
da <- .gsub(".*(\\d{4})(.?)(\\d{2})(.?)(\\d{2})(.+)*"
,"\\1-\\3-\\5\\6 6='\\6' 7='\\7'",da)
}
else
skipParse <- TRUE
if (!skipParse) {
# da <- .gsub(".*(\\d{4})(.?)(\\d{2})(.?)(\\d{2})(.*)","\\1-\\3-\\5\\6",da)
a <- as.POSIXct(as.POSIXlt(da,format="%Y-%m-%dT%H:%M:%SZ",tz="UTC"))
if (all(is.na(a))) {
a <- as.POSIXct(da,tz="",format="%Y-%m-%d %H:%M:%S")
}
if (all(is.na(a))) {
a <- as.POSIXct(da,tz="",format="%Y-%m-%d %H:%M")
}
if (all(is.na(a))) {
a <- as.POSIXct(da,tz="",format="%Y-%m-%dT%H:%M")
}
if (all(is.na(a))) {
a <- as.Date(da,format="%Y-%m-%d")
}
if (length(which(is.na(a)))==length(which(is.na(da)))) {
da <- a
rm(a)
if (nchar(tz <- Sys.getenv("TZ"))) {
da <- as.POSIXct(as.POSIXlt(da,tz=tz))
}
isDateTime <- TRUE
}
}
}
# if (dname[i]=="time")
# str(da)
if (!isDateTime) {
# da <- iconv(da,to="UTF-8")
# Encoding(da) <- "UTF-8"
# if (is.null(cpg)) ## ++ 20180527
# Encoding(da) <- "UTF-8"
}
if ((is.character(da))&&(anyNA(da))) {
ind <- which(!is.na(da))
# da[ind] <- paste0("a",da[ind]) ## devel
opN <- options(warn=-1)
daD <- as.numeric(da[ind])
options(opN)
if (!anyNA(daD)) {
if (.is.integer(daD))
da <- as.integer(da)
else
da <- as.numeric(da)
}
}
## if inherits(da,"POSIXlt") then 'da' is a list with 9 items
if (isSF)
obj[,dname[i]] <- da
if (isSP) {
if (!inherits(da,c("Date","POSIXct"))) {
opW <- options(warn=-1)
da2 <- as.numeric(da)
options(opW)
if ((!anyNA(da2))&&(length(grep("^0.+",da))==0)) {
da <- if (.is.integer(da2)) as.integer(round(da2)) else da2
}
}
methods::slot(obj,"data")[,dname[i]] <- da
}
}
else if (TRUE) {
cond1 <- isTRUE(!is.factor(da))
cond2 <- isTRUE(try(.is.integer(na.omit(da))))
isInt <- cond1 && cond2
# isInt <- .is.integer(da)
if (isInt) { # &&(!is.integer(da))
da <- as.integer(round(da))
if (isSF)
obj[,dname[i]] <- da
if (isSP)
methods::slot(obj,"data")[,dname[i]] <- da
}
}
else if ((FALSE)&&(isSP)) {
if (.is.integer(na.omit(da))) {
methods::slot(obj,"data")[,dname[i]] <- as.integer(da)
}
}
}
# Sys.setlocale("LC_CTYPE",lc)
# str(asf)
}
if (!exists("obj")) {
stop("Object cannot be recognized as spatial")
}
if (jsonSF) {
cname <- spatial_colnames(obj)
Encoding(cname) <- "UTF-8"
spatial_colnames(obj) <- cname
}
if ((isSF)&&(!sum(sapply(spatial_geometry(obj),length))))
return(spatial_data(obj))
##~ if ((isSP)&&(!length(methods::slot(spatial_geometry(obj),"coords")))) {
##~ stop("NULL geometry for Spatial class")
##~ return(spatial_data(obj))
##~ }
if (isSF) {
if (TRUE) { ## not tested for multiple geometries POLYGON/MULTIPOLYGON
if (inherits(obj,"sfc"))
geoType <- .grep("^sfc_.+$",class(obj),value=TRUE)
else
geoType <- .grep("^sfc_.+$",class(obj[[attr(obj,"sf_column")]]),value=TRUE)
geoType <- .gsub("^sfc_","",geoType)
if (geoType=="GEOMETRY")
geoType <- unique(as.character(sf::st_geometry_type(obj)))
}
else { ## low perfomance for long geometry
geoType <- unique(as.character(sf::st_geometry_type(obj)))
}
}
if (isSP)
geoType <- switch(class(sp::geometry(obj))
,SpatialPolygons="POLYGON"
,SpatialPoints="POINT"
,SpatialLines="LINE")
if (("POLYGON" %in% geoType)&&("MULTIPOLYGON" %in% geoType)) {
if (isSF) {
ret <- .try(obj <- sf::st_cast(obj,"MULTIPOLYGON"))
}
if (isSP) {
stop("POLYGON to MULTIPOLYGON for 'Spatial' is not implemented")
}
}
projClass <- c("longlat","stere","laea","merc")
projPatt <- paste0("(",paste(projClass,collapse="|"),")")
staticMap <- c("openstreetmap","sputnikmap","google")
tilePatt <- paste0("(",paste0(unique(c(staticMap,.tileService())),collapse="|"),")")
retina <- getOption("ursaRetina",1)
len <- 640L # as.integer(round(640*getOption("ursaRetina",1)))
if (is.na(size[1]))
size <- c(len,len)
else if (is.character(size)) {
size <- as.integer(unlist(strsplit(
.gsub("(\\d+)\\D+(\\d+)","\\1 \\2",size),split="\\s")))
}
else if (is.numeric(size))
size <- rep(size,length=2)
if (is.numeric(size))
len <- as.integer(round(max(size)))
g2 <- getOption("ursaSessionGrid")
if (any(is.na(border))) {
if ((!is.null(g2))||(!is.null(grid)))
border <- 0L
else
border <- 27L
}
if (!.lgrep("(none|auto|keep)",style)) {
if ((!is.null(proj4))&&(proj4!=style))
resetProj <- TRUE
}
if (isEPSG)
resetProj <- FALSE
# q()
# if ((proj=="internal")&&(!is.na(keepProj))) {
# g2 <- NULL
# }
if (resetProj)
g0 <- NULL
else if ((is.null(grid))&&(!is.null(g2)))
g0 <- g2
else if (is.null(grid))
g0 <- NULL
else {
g0 <- ursa_grid(grid)
}
# style <- "merc"
if (!.lgrep(projPatt,style))
proj <- "auto"
else
proj <- .gsub2(projPatt,"\\1",style)
if (!.lgrep(tilePatt,style)) {
art <- "none"
}
else {
art <- .gsub2(tilePatt,"\\1",style)
proj <- "merc" #ifelse(art=="polarmap",art,"merc")
}
isStatic <- .lgrep("static",style)>0
mlen <- switch(art,google=640,openstreetmap=960,sputnikmap=640)
if (isStatic) {
len[len>mlen] <- mlen
}
# canTile <- .lgrep(art,eval(as.list(args(".tileService"))$server))>0
if (proj %in% c("onemorekwd?",projClass))
canTile <- FALSE
else {
canTile <- .lgrep(art,.tileService())>0
if (!canTile) {
canTile <- style %in% .tileService(providers=TRUE)
# if (canTile)
# art <- style
}
}
# str(list(style=style,art=art,canTile=canTile))
isTile <- .lgrep("(tile|polarmap)",style)>0 & canTile |
.lgrep("(ArcticSDI|ArcticConnect)",style)>0
if ((!isStatic)&&(!isTile)) {
if (art %in% staticMap)
isStatic <- TRUE
else if (canTile)
isTile <- TRUE
else
art <- "none"
}
tpat <- unlist(gregexpr("\\{[xyz]\\}",style))
tpat <- length(tpat[tpat>0])
toZoom <- (isTile)||(isStatic)||("web" %in% style)||.lgrep("^tile",style)||
("polarmap" %in% style)||
(tpat==3)
# isColor <- .lgrep("colo(u)*r",style)>0
isWeb <- .lgrep(tilePatt,art)
if (verbose)
print(data.frame(proj=proj,art=art,static=isStatic
,canTile=canTile,tile=isTile,web=isWeb,row.names="spatialize:"))
# isOSM <- proj %in% "osm"
# isGoogle <- proj %in% "google"
# http://static-api.maps.sputnik.ru/v1/?width=400&height=400&z=6&clng=179&clat=70
# &apikey=5032f91e8da6431d8605-f9c0c9a00357
# isWeb <- isOSM | isGoogle | tryTile
if ((is.null(g0))||(is.numeric(lon0))||(is.numeric(lat0))) {
# if ((resetProj)||(is.ursa(g0,"grid"))||(is.numeric(lon0))||(is.numeric(lat0))) {
proj4 <- spatial_crs(obj)
if (verbose)
str(list(proj4=proj4,proj=proj,style=style,resetProj=resetProj))
if ((is.na(proj4))&&(nchar(style))&&(.lgrep("\\+proj=.+",style))) { ## ++ 20180530
proj4 <- style
# isPROJ4 <- FALSE
}
if ((proj4=="")&&(!(proj %in% c("auto","internal","keep")))) {
resetProj <- TRUE
proj4 <- "auto"
}
isLonLat <- .lgrep("(\\+proj=longlat|epsg:4326)",proj4)>0
if ((proj %in% c("auto"))&&(isLonLat)&&(!isEPSG)&&(style!="keep")) { ## added 2016-08-09
resetProj <- TRUE
proj4 <- "auto"
}
if ((isLonLat)&&(proj==style)&&(proj %in% c("laea","stere"))) {
resetProj <- TRUE
proj4 <- "auto"
}
isMerc <- .lgrep("\\+proj=merc",proj4)>0
if (isMerc) {
major <- .gsub(".+\\+a=(\\S+)\\s.+","\\1",proj4) ## 20037508
if (identical(major,proj4)) {
if (.lgrep("\\+(datum|ellps)=WGS84",proj4))
B <- 20037508
else ## yandex?
B <- 20037508
# print(B)
}
else
B <- as.numeric(major)*pi
}
if (isPROJ4)
resetProj <- FALSE
if (is.numeric(lon0) | is.numeric(lat0) | resetProj) {
if (isSF) {
asf2 <- sf::st_transform(obj,4326)
asf_geom2 <- sf::st_geometry(asf2)
xy <- lapply(asf_geom2,function(z) {
if (!is.list(z)) {
if (is.null(dim(z))) {
d <- ifelse(inherits(z,"XYZ"),3,2)
dim(z) <- c(length(z)/d,d)
}
z <- list(z)
}
xy2 <- lapply(z,function(z2) {
if (!is.list(z2))
z2 <- list(z2)
unlist(t(z2[[1]])[1:2,])
})
})
rm(asf2,asf_geom2)
}
if (isSP) {
asp2 <- sp::spTransform(obj,"EPSG:4326")
if (geoType=="POINT") {
xy <- sp::coordinates(asp2)
}
else {
asp2_geom <- switch(geoType,POLYGON=methods::slot(sp::geometry(asp2),"polygons")
,LINE=methods::slot(sp::geometry(asp2),"lines")
,POINT=sp::geometry(asp2))
xy <- lapply(asp2_geom,function(z) {
gz <- switch(geoType
,POLYGON=methods::slot(z,"Polygons")
,LINE=methods::slot(z,"Lines")
,POINT=methods::slot(z,"Points"))
lapply(gz,function(z3) t(sp::coordinates(z3)))
})
rm(asp2,asp2_geom)
}
}
if (is.list(xy)) {
xy <- unlist(xy)
if (is.null(xy)) {
if (verbose)
cat("Spatial object is NULL")
return(NULL)
}
xy <- matrix(c(xy),ncol=2,byrow=TRUE)
}
if (verbose)
print(summary(xy))
lon2 <- na.omit(xy[,1])
lat2 <- na.omit(xy[,2])
if (!length(lon2)) {
return(spatial_data(obj))
}
if ((nrow(xy)>1)&&(length(lon2))) {
# x <- cos(lon2*pi/180)
# y <- sin(lon2*pi/180)
# x <- mean(x)
# y <- mean(y)
# print(c(x=mean(x),y=mean(y)))
# theta <- rep(0,length(x))
# ind <- which(x!=0)
# theta[-ind] <- pi/2*sign(y[-ind])
# theta[ind] <- atan(y[ind]/x[ind])
# ind <- which(x<0)
# theta[ind] <- pi+theta[ind]
# theta <- theta-pi
# theta <- theta*180/pi
# theta <- mean(theta)
# lon2 <- range(lon2)
# lon2 <- theta*pi/180
# if (theta>180)
# theta <- theta-360
# else if (theta<=(-180))
# theta <- theta+360
lon3 <- lon2
lon4 <- lon2
ind3 <- which(lon3<0)
ind4 <- which(lon4>180)
lon3[ind3] <- lon3[ind3]+360
lon4[ind4] <- lon4[ind4]-360
lon5 <- lon2+360
sd2 <- sd(lon2)
sd3 <- sd(lon3)
sd4 <- sd(lon4)
sd5 <- sd(lon5)
dr2 <- diff(range(lon2))
dr3 <- diff(range(lon3))
dr4 <- diff(range(lon4))
dr5 <- diff(range(lon5))
dr0 <- min(c(dr2,dr3,dr4,dr5))
if (verbose)
print(data.frame(r2=diff(range(lon2))
,r3=diff(range(lon3))
,r4=diff(range(lon4))
,r5=diff(range(lon5))))
if (verbose)
print(data.frame(sd2=sd2,'sd3R'=sd3,'sd4L'=sd4,'sd5C'=sd5
,n3=length(ind3),n4=length(ind4)))
if ((sd3<=sd2)&&(sd3<=sd4)&&(dr3==dr0)) {
# if (length(ind3))
# selection <- 3L
lon2 <- lon3
}
else if ((sd4<=sd2)&&(sd4<=sd3)&&(dr4==dr0)) {
# if (length(ind4))
# selection <- 4L
lon2 <- lon4
}
}
# if ((any(lon2<180))&&(any(lon2>180)))
# selection <- 3L
if (verbose)
print(summary(lon2))
# selection <- 0L
if ((FALSE)&&(mean(lon2)>0))
lon2[lon2<0] <- lon2[lon2<0]+360
bbox <- c(range(lon2),range(lat2))[c(1,3,2,4)]
# options(ursaRasterizeSelection=selection)
# options(ursaRasterizeBbox=bbox)
theta2 <- mean(range(lon2))
# print(c(old=theta2,new=theta))
# lon_0 <- if (is.numeric(lon0)) lon0 else mean(range(lon2))
lon_0 <- if (is.numeric(lon0)) lon0 else round(theta2,4)
lat_ts <- if (is.numeric(lat0)) lat0 else round(mean(lat2),4)
if (proj=="laea")
lat_0 <- lat_ts
else
lat_0 <- if (lat_ts>=0) 90 else -90
if (((proj=="merc")&&(.lgrep("(polarmap|ArcticConnect|ArcticSDI|tile357[123456])",style)>0))||
((proj=="auto")&&("web" %in% style)&&(isTRUE(crs %in% 3571:3576)))) {
proj <- "laea"
}
else if (proj=="auto") {
if (("web" %in% style)||(tpat==3))
# if (style=="web")
proj <- "merc"
else if (.lgrep("tile3857",style))
proj <- "merc"
else if (.lgrep("(polarmap|ArcticConnect|ArcticSDI|tile357[123456])",style))
proj <- "laea"
else if ((any(lat2<0))&&(any(lat2>0)))
proj <- "merc"
else if (isEPSG)
proj <- "epsg"
else
proj <- "stere"
}
if (verbose)
print(data.frame(lon0=lon_0,lat0=lat_0,lat_ts=lat_ts,row.names=proj))
if (proj=="stere") {
t_srs <- paste("+proj=stere"
,paste0("+lat_0=",lat_0)
,paste0("+lat_ts=",lat_ts)
,paste0("+lon_0=",lon_0)
,"+k=1","+x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs")
}
else if (proj=="laea") {
if (.lgrep("(polarmap|ArcticConnect|ArcticSDI|^web$)",style)) {
if (length(crs)) {
lon_0 <- as.numeric(gsub(".*\\+lon_0=(\\S+)\\s.*","\\1"
,spatial_crs(crs)))
}
lon_0[lon_0<(-165) || lon_0>=(+135)] <- -180
lon_0[lon_0>=(-165) && lon_0<(-125)] <- -150
lon_0[lon_0>=(-125) && lon_0<(-70)] <- -100
lon_0[lon_0>=(-70) && lon_0<(-25)] <- -40
lon_0[lon_0>=(-25) && lon_0<(+50)] <- 10
lon_0[lon_0>=(50) && lon_0<(+135)] <- 90
}
t_srs <- paste("+proj=laea"
,paste0("+lat_0=",lat_0)
,paste0("+lon_0=",lon_0)
,"+k=1","+x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs")
}
else if (proj=="merc")
t_srs <- paste("+proj=merc +a=6378137 +b=6378137"
,"+lat_ts=0.0",paste0("+lon_0=",lon_0)
,"+x_0=0.0 +y_0=0 +k=1.0 +units=m"
# ,"+nadgrids=@null"
,"+wktext +no_defs")
else if ((proj %in% c("longlat"))||(isLonLat)) {
t_srs <- "+proj=longlat +datum=WGS84 +no_defs"
}
else if (proj %in% c("zzzgoogle")) {
if (FALSE)#(selection %in% c(1000L,3L))
t_srs <- paste("+proj=merc +a=6378137 +b=6378137"
,"+lat_ts=0.0 +lon_0=180.0 +x_0=0.0 +y_0=0 +k=1.0"
,"+units=m +nadgrids=@null +wktext +no_defs")
else
t_srs <- paste("+proj=merc +a=6378137 +b=6378137"
,"+lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0"
,"+units=m +nadgrids=@null +wktext +no_defs")
}
else
t_srs <- NULL
if (is.character(t_srs)) {
# bbox <- ursa:::.project(matrix(spatial_bbox(a),ncol=2,byrow=TRUE)
# ,proj=spatial_crs(a),inv=TRUE)
if (isSF) {
obj <- sf::st_transform(obj,t_srs)
if ((TRUE)&&(.lgrep("\\+proj=longlat",t_srs))&&(max(lon2)>180)) {
if (verbose)
.elapsedTime("lon+360 -- start")
objG0 <- spatial_geometry(obj)
objG1 <- lapply(objG0,function(g1) {
if (!is.list(g1))
return(.lonPlus360(g1))
ret1 <- lapply(g1,function(g2) {
if (!is.list(g2))
return(.lonPlus360(g2))
lapply(g2,.lonPlus360)
})
attributes(ret1) <- attributes(g1)
ret1
})
attributes(objG1) <- attributes(objG0)
spatial_geometry(obj) <- objG1
if (verbose)
.elapsedTime("lon+360 -- finish")
}
}
if (isSP) {
# print(t_srs)
# obj <- sp::spTransform(obj,t_srs)
# print(c(sp::bbox(obj)),digits=12)
obj <- spatial_transform(obj,t_srs)
if ((TRUE)&&(.lgrep("\\+proj=longlat",t_srs))&&(max(lon2)>180)) {
if (verbose)
.elapsedTime("lon+360 -- start")
geoType <- spatial_geotype(obj)
if (geoType=="POINT") {
methods::slot(obj,"coords") <- .lonPlus360(methods::slot(obj,"coords"))
}
else {
objG0 <- spatial_geometry(obj)
objG1 <- switch(geoType
,POLYGON=methods::slot(objG0,"polygons")
,LINE=methods::slot(objG0,"lines")
,POINT=g0)
xy <- lapply(objG1,function(z) {
gz <- switch(geoType
,POLYGON=methods::slot(z,"Polygons")
,LINE=methods::slot(z,"Lines")
,POINT=methods::slot(z,"Points"))
gz <- lapply(gz,function(z3) {
methods::slot(z3,"coords") <- .lonPlus360(methods::slot(z3,"coords"))
z3
})
if (geoType=="POLYGON")
methods::slot(z,"Polygons") <- gz
else if (geoType=="LINE")
methods::slot(z,"Lines") <- gz
else if (geoType=="POINT")
methods::slot(z,"Points") <- gz
z
})
if (geoType=="POLYGON")
methods::slot(objG0,"polygons") <- xy
else if (geoType=="LINE")
methods::slot(objG0,"lines") <- xy ## gz? (20190921)
else if (geoType=="POINT")
objG0 <- xy ## gz? (20190921)
spatial_geometry(obj) <- objG0
}
if (verbose)
.elapsedTime("lon+360 -- finish")
}
}
}
# xy <- .project(xy,t_srs)
# print(summary(xy))
}
else if (isEPSG | isPROJ4) {
a <- .try({
t_srs <- ifelse(isPROJ4,style,.epsg2proj4(style))
# str(style)
# str(t_srs)
if (isSF) {
patt <- "\\+init=epsg\\:(.+)\\s*$"
if (length(grep(patt,t_srs)))
t_srs <- as.integer(gsub(patt,"\\1",t_srs))
# str(sf::st_crs(obj))
obj <- sf::st_transform(obj,t_srs)
}
if (isSP) {
# str(sp::proj4string(obj))
obj <- sp::spTransform(obj,t_srs)
}
})
if (!a) {
t_srs <- ifelse(isPROJ4,style,.epsg2proj4(style,force=TRUE))
if (isSF) {
obj <- sf::st_transform(obj,t_srs)
}
if (isSP) {
obj <- sp::spTransform(obj,t_srs)
}
}
}
}
# else if (((isSF)&&(is.ursa(a,"grid")))||((isSP)&&(is.ursa(asp,"grid")))) {
else if (is.ursa(g0,"grid")) {
t_srs <- g0$crs
if (isSF) {
# opE <- options(show.error.messages=TRUE)
# print(sf::st_bbox(obj))
src0 <- sf::st_crs(obj)$proj4string
if (!is.na(src0)) {
t_srs <- spatial_crs(t_srs)
g0$crs <- t_srs
if ((!identical(src0,t_srs))&&(nchar(t_srs)>0))
obj <- sf::st_transform(obj,t_srs)
}
# print(sf::st_crs(obj)$proj4string)
# print(sf::st_bbox(obj))
# options(opE)
}
if (isSP) {
if (FALSE)
src0 <- sp::proj4string(obj)
else if (FALSE) {
src0 <- methods::slot(obj,"proj4string")
if (methods::is(src0,"CRS"))
src0 <- methods::slot(src0,"projargs")
}
else
src0 <- spatial_crs(obj)
# print(c(sp::bbox(obj)))
if ((!is.na(src0))&&(T | !identical(src0,t_srs))) {
if (.lgrep("\\+init=epsg",t_srs)) {
t_srs <- .epsg2proj4(t_srs,force=TRUE)
if (.lgrep("\\+init=epsg",src0))
src0 <- .epsg2proj4(src0,force=TRUE)
if (!identical(src0,t_srs))
obj <- sp::spTransform(obj,t_srs) ## not tested
}
else {
if ((!identical(src0,t_srs))&&(nchar(t_srs)>0)) {
opW <- options(warn=ifelse(.isPackageInUse(),-1,1))
obj <- sp::spTransform(obj,sp::CRS(t_srs,doCheckCRSArgs=FALSE))
options(opW)
}
}
}
# print(sp::proj4string(obj))
# print(c(sp::bbox(obj)))
}
}
if (FALSE) { ## deprecated
if (isSF) {
obj_geom <- sf::st_geometry(obj)
# bbox <- c(sf::st_bbox(obj_geom)) ## low performance sp<=0.5-2
if (inherits(obj,"sfc"))
bbox <- c(sf::st_bbox(obj_geom))
else
bbox <- attr(obj[[attr(obj,"sf_column")]],"bbox") ## ~ sf::st_bbox
proj4 <- sf::st_crs(obj)$proj4string
}
if (isSP) {
obj_geom <- switch(geoType,POLYGON=methods::slot(sp::geometry(obj),"polygons")
,LINE=methods::slot(sp::geometry(obj),"lines")
,POINT=sp::geometry(obj))
bbox <- c(sp::bbox(obj))
if (length(bbox)==6) {
bbox <- bbox[c(1,2,4,5)]
# names(bbox) <- c("xmin","ymin","zmin","xmax","ymax","zmax")
}
names(bbox) <- c("xmin","ymin","xmax","ymax")
proj4 <- sp::proj4string(obj)
}
}
else {
bbox <- spatial_bbox(obj)
proj4 <- spatial_crs(obj)
if ((FALSE)&&(isSP)) {
obj_geom <- spatial_geometry(obj)
obj_geom <- switch(geoType,POLYGON=methods::slot(obj_geom,"polygons")
,LINE=methods::slot(obj_geom,"lines")
,POINT=obj_geom)
}
}
if ((bbox["xmin"]==bbox["xmax"])||(bbox["ymin"]==bbox["ymax"]))
bbox <- bbox+100*c(-1,-1,1,1)
if (FALSE) {
.sc <- ifelse(.lgrep("\\+proj=(zzzlonglat|zzzmerc)",proj4)>0,0,expand-1)
indx <- c("minx","maxx")
bbox[indx] <- mean(bbox[c(1,3)])+c(-1,1)*expand*diff(bbox[c(1,3)])/2
bbox[c(2,4)] <- mean(bbox[c(2,4)])+c(-1,1)*expand*diff(bbox[c(2,4)])/2
}
else {
if ((bbox[1]>0)&&(bbox[3]<0))
bbox[3] <- bbox[3]+360
.sc <- (expand-1)*sqrt(diff(bbox[c(1,3)])*diff(bbox[c(2,4)]))/2
bbox <- bbox+c(-1,-1,1,1)*.sc
}
if (is.null(g0)) {
if (!is.na(cell)) {
res <- rep(cell,length=2)
g0 <- regrid(bbox=unname(bbox[c("xmin","ymin","xmax","ymax")]),res=res
,crs=proj4,border=0)
}
else {
res <- max(c(bbox["xmax"]-bbox["xmin"]),(bbox["ymax"]-bbox["ymin"]))/len
p <- pretty(res)
res <- p[which.min(abs(res-p))]
g1 <- ursa_grid()
g1$resx <- g1$resy <- as.numeric(res)
g1$crs <- proj4
g0 <- regrid(g1,bbox=unname(bbox[c("xmin","ymin","xmax","ymax")])
,border=0) ## border=border
}
}
if (toZoom) {
res <- with(g0,sqrt(resx*resy))
s <- 2*6378137*pi/(2^(1:21+8))
zoom <- which.min(abs(s-res))
if (("polarmap" %in% style)&&(zoom>9)) {
znew <- 9
g0 <- regrid(g0,res=s[znew],expand=ifelse(dev <-F ,2^(zoom-znew),1))
zoom <- znew
}
else
g0 <- regrid(g0,res=s[zoom])
}
if (any(border!=0)) {
g0 <- regrid(g0,border=border)
}
if ((isWeb)||("web" %in% style)) {
if (retina>1) {
if (retina<2)
retina <- 2
else if ((retina>2)&&(retina<4))
retina <- 4
g0 <- regrid(g0,mul=retina)
g0$retina <- retina
}
}
if ((FALSE)&&(isWeb)) {
bbox <- with(g0,.project(cbind(c(minx,maxx),c(miny,maxy))
,crs,inv=TRUE))[c(1,3,2,4)]
basemap <- .geomap(bbox,border=0,style=style,verbose=verbose)
g0 <- ursa(basemap,"grid")
attr(obj,"basemap") <- basemap
}
if (is.null(g2))
session_grid(g0)
geoMix <- (.lgrep("point",geoType)>0)+
(.lgrep("line",geoType)>0)+
(.lgrep("polygon",geoType)>0)>1
if (geoMix) {
geoEach <- spatial_geotype(obj,each=TRUE)
obj <- lapply(c("point","line","polygon"),function(gf) {
if (!length(ind <- .grep(gf,geoEach)))
return(NULL)
res <- obj[ind,]
da <- spatial_data(res)
ind <- rep(TRUE,ncol(da))
if (T)
for (i in seq_along(ind))
ind[i] <- !all(is.na(da[[i]]))
res[ind]
})
obj <- obj[sapply(obj,function(o) !is.null(o))]
}
# print("WORK FOR SPATIAL TRIM")
# str(list(style=style,proj=proj))
cond1 <- ((proj!=style[1])&&(!style %in% c("none","keep","web")))
if (i_am_not_ready_to_cancel_it <- cond1) {
if (!inherits(obj,"SpatialPixels"))
attr(obj,"grid") <- g0
else
attr(obj,"ursaGrid") <- g0
attr(obj,"toUnloadMethods") <- toUnloadMethods
attr(obj,"colnames") <- dname
attr(obj,"style") <- style
attr(obj,"geocodeStatus") <- geocodeStatus
# attr(obj,"engine") <- ifelse(isSF,"sf","sp")
if (exists("dsn"))
attr(obj,"dsn") <- dsn
}
# class(obj) <- c(class(obj),"ursaVectorExternal")
obj
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/xxx.spatialize.R
|
'.Cursa' <- function(...) {
if (T) ## if .isPackageInUse()
return(.C(...))
print("without package")
## without package registration:
arglist <- list(...)
# message(paste(".C:",arglist[[1]]))
if (.isPackageInUse())
arglist$PACKAGE <- "ursa"
do.call(".C",arglist)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/yyy.C.R
|
'.DeadEnd' <- function() stop("Dead End after {rgdal}/{rgeos}/{maptools} retiring")
'.open_rgdal' <- function(...) .DeadEnd()
'.rgdal_getRasterData' <- function(...) .DeadEnd()
'.rgdal_putRasterData' <- function(...) .DeadEnd()
'.shp.read' <- function(...) .DeadEnd()
'.shp.write' <- function(...) .DeadEnd()
'.rgdal_close_Transient' <- function(...) .DeadEnd()
'.rgdal_close_ReadOnly' <- function(...) .DeadEnd()
'.read_gdal' <- function(...) .DeadEnd()
'.rgdal_prepare_con' <- function(...) .DeadEnd()
'.rgdal_showWKT' <- function(...) .DeadEnd()
'.rgdal_writeOGR' <- function(...) .DeadEnd()
'.rgdal_readOGR' <- function(...) .DeadEnd()
'.rgdal_ogrListLayers' <- function(...) .DeadEnd()
'.rgdal_ogrInfo' <- function(...) .DeadEnd()
'.rgdal_CRSargs' <- function(...) .DeadEnd()
'.rgdal_project' <- function(...) .DeadEnd()
'.rgdal_showP4' <- function(...) .DeadEnd()
'.rgdal_requireNamespace' <- function(...) .DeadEnd()
'.rgdal_loadedNamespaces' <- function(...) .DeadEnd()
'.rgeos_requireNamespace' <- function(...) .DeadEnd()
'.rgeos_readWKT' <- function(...) .DeadEnd()
'.rgeos_gLength' <- function(...) .DeadEnd()
'.rgeos_gIntersection' <- function(...) .DeadEnd()
'.rgeos_gDifference' <- function(...) .DeadEnd()
'.rgeos_gSymdifference' <- function(...) .DeadEnd()
'.rgeos_gBuffer' <- function(...) .DeadEnd()
'.rgeos_gUnaryUnion' <- function(...) .DeadEnd()
'.rgeos_gUnion' <- function(...) .DeadEnd()
'.rgeos_gSimplify' <- function(...) .DeadEnd()
'.rgeos_gIsValid' <- function(...) .DeadEnd()
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/yyy.RogerBivand.R
|
## ?fastdigest::fastdigest
'.ursaCacheDir' <- function() {
fpath <- getOption("ursaCacheDir")
if (!dir.exists(fpath))
dir.create(fpath)
# fclear <- file.path(fpath,"clear.R")
# if (!file.exists(fclear))
# writeLines("ursa:::.ursaCacheDirClear(age=2,size=0.2,count=1e3)",fclear)
fpath
}
'.ursaCacheFile' <- function(pattern="ursaCache") {
# fpath <- getOption("ursaCacheDir")
# if (!dir.exists(fpath))
# dir.create(fpath)
# tempfile(tmpdir=fpath,pattern=pattern)
.normalizePath(tempfile(tmpdir=.ursaCacheDir(),pattern=pattern))
}
'.ursaCacheInventory' <- function() file.path(.ursaCacheDir(),"ursaCache_inventory.txt")
'.ursaCacheVisits' <- function() file.path(.ursaCacheDir(),"ursaCache_visits.txt")
'.ursaCacheDirClear' <- function(size=getOption("ursaCacheSize")
,age=getOption("ursaCacheAge")
,count=10000,completely=FALSE) {
if (!is.numeric(size))
size <- 16
if (!is.numeric(age))
age <- 7
fpath <- .ursaCacheDir()
if (!file.exists(fpath))
return(invisible(NULL))
if (completely) {
if (!dir.exists(fpath))
return(invisible(NULL))
file.remove(.dir(path=fpath,pattern=as.list(args(.ursaCacheFile))$pattern
,full.names=TRUE))
if (develHtmlWidgets <- TRUE) {
file.remove(.dir(path=fpath,pattern="^htmlwidgets.+\\.html$",full.names=TRUE))
dhw <- file.path(fpath,"htmlwidgets")
if (dir.exists(dhw))
unlink(dhw)
}
unlink(fpath)
return(invisible(NULL))
}
inventory <- .ursaCacheInventory()
if (!file.exists(inventory)) {
return(.ursaCacheDirClear(completely=TRUE)) ## RECURSIVE
}
was <- try(utils::read.table(inventory,sep=",",encoding="UTF-8"))
if (inherits(was,"try-error")) {
message("cache was removed completely due to damaged structure")
return(.ursaCacheDirClear(completely=TRUE)) ## RECURSIVE
}
colnames(was) <- c("time","stamp","visits","size","src","dst")
was <- was[rev(seq(nrow(was))),]
was0 <- was
was$src <- NULL
was$time <- as.POSIXct(was$time,format="%Y-%m-%dT%H:%M:%SZ",tz="UTC")
t0 <- as.POSIXct(as.numeric(Sys.time()),origin="1970-01-01",tz="UTC")
was$p1 <- unclass(difftime(t0,was$time,units="days"))
was$p2 <- cumsum(was$size/1024)
was$p3 <- row(was[,1,drop=FALSE])
ind <- which(was$p1>age | was$p2>size*1024*1024 | was$p3>count)
if (!length(ind))
return(invisible(NULL))
if (length(ind)==nrow(was)) {
message("cache was removed completely")
return(.ursaCacheDirClear(completely=TRUE)) ## RECURSIVE
}
dst <- file.path(fpath,was0$dst[ind])
dst <- dst[file.exists(dst)]
if (FALSE) {
print(was)
print(c(size=size,age=age,count=count))
print(c(toRemove=dst))
q()
}
file.remove(dst)
dst <- paste0(dst,".hdr")
dst <- dst[file.exists(dst)]
file.remove(dst)
was0 <- was0[-ind,]
was0 <- was0[rev(seq(nrow(was0))),]
##~ utils::write.table(was0,quote=TRUE,col.names=FALSE,row.name=FALSE,sep=","
##~ ,file=inventory)
.ursaCacheWrite(was0,append=FALSE)
return(invisible(NULL))
}
'.ursaCacheExpired' <- function(value) {
if (is.character(value)) {
if (!.lgrep("\\-",value))
value <- paste0("-",value)
if (!.lgrep("\\d\\s\\D",value))
value <- gsub("(^.*\\d)(\\D.+$)","\\1 \\2",value)
expired <- as.integer(tail(seq(Sys.time(),len=2,by=value),1))
# expire <- as.POSIXlt(tail(seq(Sys.time(),len=2,by=value),1),tz="UTC")
attr(expired,"cache") <- TRUE
}
else {
expired <- as.integer(tail(seq(Sys.time(),len=2,by="-1 month"),1)) ## not '+'
# expired <- as.POSIXlt(tail(seq(Sys.time(),len=2,by="-1 month"),1),tz="UTC")
attr(expired,"cache") <- value
}
expired
}
'.ursaCacheDirZero' <- function() {
list1 <- list.dirs(.ursaCacheDir())
for (i in seq(9)) {
list2 <- sapply(list1,function(x) {
list3 <- dir(path=x,recursive=FALSE)
length(list3)==0
})
list2 <- names(list2)[list2]
if (!length(list2))
break
sapply(list2,unlink,force=TRUE,recursive=TRUE)
}
0L
}
'.ursaCacheDownload' <- function(src,dst,method,quiet=FALSE,cache=TRUE
,mode="w",headers=NULL) {
enc <- "UTF-8"
inventory <- .ursaCacheInventory()
src0 <- src
attr(src0,"credentials") <- NULL
if (!is.null(cred <- attr(src,"credentials"))) {
for (cr in cred) {
m1 <- gregexpr(paste0("\\{",cr,"\\}"),src)[[1]]
if (any(m1<0))
next
m2 <- regmatches(src,m1)
m3 <- gsub("^\\{(.+)\\}$","\\1",m2)
if (grepl("thunderforest\\.com",src)) {
getCr <- getOption("ThunderforestApiKey")
}
else if (grepl("api\\.here\\.com",src)) {
getCr <- getOption("HEREapp")
}
else if (grepl("api\\.mapbox\\.com",src)) {
getCr <- getOption("mapboxToken")
}
else
getCr <- NULL
if (is.null(getCr))
next
if (is.character(getCr))
value <- getCr
else {
value <- getCr[[match(cr,names(getCr))]]
}
if ((is.character(value))&&(length(value)==1))
regmatches(src,m1) <- value
}
attr(src,"credentials") <- NULL
}
else if (grepl("tiles\\.stadiamaps\\.com",src)) {
getCr <- getOption("stadiamaps_api_key")
if (!is.null(getCr)) {
src <- paste0(src,ifelse(grepl("\\.(png|jpg)$",src),"?","&")
,"api_key=",getCr)
}
}
src1 <- src
patt <- "(^http(s)*://)\\{(.+)\\}(.+$)" ## \\1 \\3 \\4
if (.lgrep(patt,src)) {
dom <- unlist(strsplit(gsub(patt,"\\3",src),""))
src <- unname(sapply(sample(dom),function(x) gsub(patt,paste0("\\1",x,"\\4"),src1)))
# dom <- unlist(strsplit(.gsub2("\\{(.+)\\}","\\1",gsub("\\{.\\}","",src)),""))
# src <- .gsub("{.+}",sample(dom,1),src0)
# src <- unname(sapply(sample(dom),function(x) .gsub("{.+}",x,src0)))
}
if (missing(dst))
dst <- NULL
expired <- .ursaCacheExpired(cache)
# message("expired:")
# str(expired)
# str(as.POSIXct(expired,origin=.origin()))
cache <- attr(expired,"cache")
##~ if (is.character(cache)) {
##~ if (!.lgrep("\\-",cache))
##~ cache <- paste0("-",cache)
##~ if (!.lgrep("\\d\\s\\D",cache))
##~ cache <- gsub("(^.*\\d)(\\D.+$)","\\1 \\2",cache)
##~ expired <- as.POSIXlt(tail(seq(Sys.time(),len=2,by=cache),1),tz="UTC")
##~ cache <- TRUE
##~ }
##~ else
##~ expired <- as.POSIXlt(tail(seq(Sys.time(),len=2,by="-7 days"),1),tz="UTC")
if (cache) {
# message("use cache")
if (file.exists(inventory)) {
# message("check inventory")
was <- utils::read.table(inventory,sep=",",encoding=enc)
colnames(was) <- c("time","stamp","visits","size","src","dst")
if (is.character(dst)) {
stop("dst")
}
ind <- tail(which(!is.na(match(was$src,src0))),1) ## match(src0,was$src)
if ((length(ind))&&(!is.na(ind))) {
# message("found in inventory")
# str(was$stamp[ind])
# str(as.POSIXct(was$stamp[ind],origin=.origin()))
# t2 <- as.POSIXlt(was$time[ind],format="%Y-%m-%dT%H:%M:%SZ",tz="UTC")
if (was$stamp[ind]>=expired) { ## t2>=expired
# message("not expired")
dst <- file.path(.ursaCacheDir(),was$dst[ind])
}
}
}
}
if ((is.null(dst))||(!file.exists(dst))) {
# message("download is required")
if (!length(src))
return(NULL)
if (is.null(dst))
dst <- if (cache) .ursaCacheFile() else tempfile()
for (i in seq_along(src)) {
ret <- try(download.file(url=URLencode(iconv(src[i],to="UTF-8"))
,destfile=dst,method=method,quiet=quiet,mode=mode
,headers=headers))
if (!inherits(ret,"try-error"))
break
}
if (inherits(ret,"try-error"))
return(ret)
if (cache)
##~ utils::write.table(
##~ data.frame(time=format(Sys.time(),"%Y-%m-%dT%H:%M:%SZ",tz="UTC")
##~ # ,stamp=as.integer(Sys.time())
##~ ,stamp=as.integer(file.mtime(dst))
##~ ,visits=0L
##~ ,size=file.size(dst)
##~ ,src=src0,dst=basename(dst))
##~ ,quote=TRUE,col.names=FALSE,row.name=FALSE,sep=","
##~ ,file=inventory,append=TRUE,fileEncoding=enc)
.ursaCacheWrite(.ursaCacheRecord(dst,src=src0),append=TRUE)
}
else if (cache) {
Fout <- file(.ursaCacheVisits(),"at")
writeLines(basename(dst),Fout)
close(Fout)
}
dst
}
'.ursaCacheRaster' <- function(src,unpack=c("none","gzip","bzip2"),reset=FALSE) {
enc <- "UTF-8"
unpack <- match.arg(unpack)
finfo <- file.info(src)
ftime <- as.integer(finfo$mtime)
fsize <- finfo$size
dst <- NULL # .ursaCacheFile() ##
inventory <- .ursaCacheInventory()
ind <- NA
if (file.exists(inventory)) {
was <- utils::read.table(inventory,sep=",",encoding=enc)
colnames(was) <- c("time","stamp","visits","size","src","dst")
if (is.character(dst)) {
stop("dst")
}
if (FALSE) {
wasP <- was
wasP$src <- substr(wasP$src,1,12)
print(wasP)
}
if (FALSE) {
ind1 <- match(.normalizePath(src),was$src)
ind2 <- match(ftime,was$stamp)
ind3 <- ind2 ## dummy for one more check
if (!anyNA(c(ind1,ind2,ind3))&&(ind1==ind2)&&(ind2==ind3)) {
dst <- file.path(.ursaCacheDir(),was$dst[ind1[1]])
ind <- ind1
}
}
else {
ind1 <- which(!is.na(match(was$src,.normalizePath(src))))
ind2 <- which(!is.na(match(was$stamp,ftime)))
ta <- table(c(ind1,ind2))
ta <- ta[ta==2]
if (length(ta)) {
ind <- as.integer(names(ta))
dst <- file.path(.ursaCacheDir(),was$dst[ind[1]])
}
}
}
if (reset) {
if (!is.null(dst)) {
was <- was[-ind,]
file.remove(dst)
dst <- NULL
}
else
reset <- FALSE
}
if (unpack!="none") {
if ((!is.null(dst))&&(!envi_exists(dst)))
dst <- NULL
if (is.null(dst)) {
dst <- .ursaCacheFile()
if (unpack %in% c("gzip","bzip2")) {
if (unpack=="gzip") {
system2("gzip",c("-f -d -c",.dQuote(src)),stdout=dst,stderr=FALSE)
}
else if (unpack=="bzip2")
system2("bzip2",c("-f -d -c",.dQuote(src)),stdout=dst,stderr=FALSE)
if (debugExact <- F) {
str(src)
str(dst)
cat("------------\n")
str(envi_list(src,exact=TRUE))
cat("------------\n")
q()
}
if (length(listE <- envi_list(src,exact=TRUE)))
file.copy(paste0(listE,".hdr"),paste0(dst,".hdr"),copy.date=TRUE)
}
##~ da <- data.frame(time=format(Sys.time(),"%Y-%m-%dT%H:%M:%SZ",tz="UTC")
##~ ,stamp=ftime,visits=0L,size=file.size(dst)
##~ ,src=.normalizePath(src),dst=basename(dst))
da <- .ursaCacheRecord(dst,src=.normalizePath(src),ftime=ftime)
if (reset)
da <- rbind(was,da)
##~ utils::write.table(da,quote=TRUE,col.names=FALSE,row.name=FALSE,sep=","
##~ ,file=inventory,append=!reset,fileEncoding=enc)
.ursaCacheWrite(da,append=!reset)
}
else {
Fout <- file(.ursaCacheVisits(),"at")
writeLines(basename(dst),Fout)
close(Fout)
}
}
dst
}
'.ursaCacheRecord' <- function(dst,src=NULL,ftime=NULL) {
if (.lgrep("^file:///",dst))
dst <- .gsub("^file:///","",dst)
if (is.null(src))
src <- basename(dst)
if (is.null(ftime))
ftime <- file.mtime(dst)
da <- data.frame(time=format(Sys.time(),"%Y-%m-%dT%H:%M:%SZ",tz="UTC")
,stamp=as.integer(ftime)
,visits=0L
,size=file.size(dst)
,src=src
,dst=basename(dst)
)
da
}
'.ursaCacheWrite' <- function(da,append=TRUE) {
inventory <- .ursaCacheInventory()
utils::write.table(da,quote=TRUE,col.names=FALSE,row.name=FALSE,sep=","
,file=inventory,append=append,fileEncoding="UTF-8")
}
'.ursaCacheRead' <- function(fname) {
inventory <- .ursaCacheInventory()
if (!file.exists(inventory))
return(NULL)
was <- utils::read.table(inventory,sep=",",encoding="UTF-8")
stopifnot(ncol(was)==6)
colnames(was) <- c("time","stamp","visits","size","src","dst")
was
}
'.ursaCacheFind' <- function(loc) {
was <- .ursaCacheRead()
if (is.null(was))
return(0L)
ind <- match(loc,was$src)
if (is.na(ind)) {
ind <- match(basename(loc),was$dst)
}
if (is.na(ind))
return(0L)
ind
}
'.atOnceCacheRebuildAndForget' <- function() {
a <- utils::read.table("_inventory.txt",sep=",",dec=".")
a <- data.frame(a[,1:2],B=0,a[,3:5])
str(a)
utils::write.table(a,"_inventory.new",sep=",",dec=".",col.names=FALSE,row.names=FALSE)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/yyy.cache.R
|
'.prepare.con' <- function(x,...)
{
arglist <- list(...)
if (missing(x))
x <- NA
if ((!missing(x))&&(!is.ursa(x)))
{
arglist$temporal <- x
ind <- .grep("^temporal$",names(arglist))
names(arglist)[ind] <- ""
x <- .raster.skeleton()
x$grid <- session_grid()
if (.is.grid(arglist$temporal))
x$grid <- arglist$temporal
}
isCT <- FALSE
ind <- .grep("^(colortable|category)",names(arglist))
if (length(ind))
{
ct <- arglist[[ind]]
if (is.logical(ct)) {
if (ct)
ct <- ursa_colortable(x)
else {
ct <- character(0)
ursa_colortable(x) <- ct
}
}
if ((is.character(ct))&&(length(ct))) {
isCT <- TRUE
n <- length(ct)
arglist$datatype <- ifelse(n<255,1L,ifelse(n<65535,12L,13L))
arglist$nodata <- n
class(x$value) <- "ursaCategory"
x$colortable <- ct
class(x$colortable) <- "ursaColorTable"
}
}
simple <- attr(x,"copyright")
simple <- ((is.character(simple))&&(nchar(simple)>0))
if ((simple)) {
if ((!FALSE)||("ursa" %in% loadedNamespaces())) {
g1 <- ursa(x,"grid")
ursa(x,"grid") <- regrid(g1,setbound=c(0,0,g1$columns,g1$rows),crs="")
}
}
x$con <- .create.con(x,arglist)
if (!.is.con(x$con)) {
cat("Unable to create connection\n")
return(NULL)
}
ind <- .grep("^(band|layer)*name",names(arglist))
if (length(ind))
x$name <- arglist[[ind[1]]]
if ((0)&&(length(ind)))
cat(sprintf("x$name=%s\n",x$name))
if (any(is.na(x$dim)))
x$dim <- as.integer(with(x$con,c(lines*samples,bands)))
if ((x$dim[2]!=x$con$bands)&&((length(x$value)==1)&&(is.na(x$value))||(x$dim[2]!=dim(x$value)[2])))
x$dim[2] <- x$con$bands
if (length(.grep("(band|layer|names)",names(arglist))))
{
if (x$dim[2]!=x$con$bands)
x$dim[2] <- x$con$bands
}
else
{
if (x$con$bands!=x$dim[2])
x$con$bands <- x$dim[2]
}
if ((TRUE)&&(!is.na(x$name[1]))&&(!is.na(x$con$posZ[1]))) ## FALSE before 29may2010
NULL # x$name <- x$name #[x$con$posZ]
else if ((is.na(x$name[1]))||(length(x$name)!=x$dim[2])) {
x$name <- sprintf(sprintf("%s%%0%dd"
,ifelse(is.na(x$name[1]),"Band ",x$name[1])
,nchar(length(1:x$con$bands))),1:x$con$bands)
# x$name <- character()
}
if (x$con$driver %in% c("ENVI","EGDAL"))
.write.hdr(x)
else if (x$con$driver=="RGDAL") {
.rgdal_prepare_con(x)
}
x$value <- NA
# class(x$value) <- ifelse(isCT,"ursaCategory","ursaNumeric")
class(x$value) <- ifelse(.is.colortable(x),"ursaCategory","ursaNumeric")
x
}
'.create.con' <- function(x,arglist)
{
if (.is.con(x$con))
{
if (is.null(arglist$datatype))
{
if ((TRUE)&&(!is.null(dim(x$value))))
{
nodata <- if (is.null(arglist$nodata)) x$con$nodata else arglist$nodata
if ((is.na(nodata))&&(anyNA(x$value)))
arglist$nodata <- nodata <- .optimal.nodata(x$value)
arglist$datatype <- .optimal.datatype(x$value,nodata)
if (!is.na(nodata)) {
if ((arglist$datatype==2)&&((nodata>32767)||(nodata<(-32768))))
arglist$nodata <- -32768L
else if ((arglist$datatype==12)&&((nodata>65535)||(nodata<0)))
arglist$nodata <- 65535L
else if ((arglist$datatype==1)&&((nodata>255)||(nodata<0)))
arglist$nodata <- 255L
else if ((arglist$datatype==11)&&((nodata>127)||(nodata<(-128))))
arglist$nodata <- -128L
}
}
else
arglist$datatype <- x$con$datatype ## release: only these line
}
if (is.null(arglist$nodata))
arglist$nodata <- x$con$nodata
if (is.null(arglist$connection))
arglist$connection <- "file"
}
else if (!is.null(dim(x$value)))
{
if (is.null(arglist$datatype))
arglist$datatype <- .optimal.datatype(x$value,x$con$nodata)
if (is.null(arglist$nodata)) {
arglist$nodata <- .make.nodata(arglist$datatype)
}
}
obj <- .raster.skeleton()
if (is.null(x))
{
obj$grid <- session_grid()
# obj$con <- envi=.con.skeleton()
obj$con <- .con.skeleton()
obj$con$driver <- arglist$implement ## added 20170124
# obj$con$driver <- driver ## removed 20170124
}
else
{
class(x) <- "ursaRaster (no generic)"
for (i in seq(along=x))
{
myname <- names(x)[i]
if (myname!="value")
obj[[myname]] <- x[[myname]]
}
}
con <- .make.con(obj,arglist)
con
}
'.make.con' <- function(obj,arglist)
{
if (!is.ursa(obj))
return(NULL)
if (missing(arglist))
arglist <- list()
grid <- obj$grid
if (!.is.con(obj$con))
con <- .con.skeleton()
else
con <- obj$con
ignore <- NULL #obj$nodata
fname <- NULL
datatype <- NULL
byteorder <- NULL
bands <- NULL
bandnames <- NULL
connectionName <- c("file","bzfile","gzfile","xzfile")
connection <- NULL
interleaveName <- c("bsq","bil","bip")
interleave <- NULL
implementName <- c("ENVI",ifelse(.isPackageInUse(),"EGDAL","RGDAL"))
implement <- NULL
driver <- NULL
proj <- NULL
compressed <- NULL
wkt <- NULL
ext <- NULL
for (i in seq(along=arglist))
{
var <- arglist[[i]]
if (is.null(var))
next
name <- names(arglist[i])
if ((is.null(fname))&&(is.character(var))&&
((!nchar(name))||(length(.grep("fname",name)))))
{
fname <- var
next
}
if ((is.null(connection))&&(is.character(var))&&
((!length(name))||(length(.grep("con",name)))))
{
if (length(.grep("^gz",var)))
connection <- "gzfile"
else if (length(.grep("^bz",var)))
connection <- "bzfile"
else if (length(.grep("^xz",var)))
connection <- "xzfile"
else if (length(.grep("^file",var)))
connection <- "file"
if (!is.null(connection))
next
}
if ((is.null(interleave))&&(is.character(var))&&
((!length(name))||(length(.grep("interleave",name)))))
{
ind <- .grep(var,interleaveName)
if (length(ind))
{
interleave <- interleaveName[ind]
next
}
}
if ((is.null(implement))&&(is.character(var))&&
((!length(name))||(length(.grep("implement",name)))))
{
ind <- .grep(var,implementName)
if (length(ind))
{
implement <- implementName[ind]
next
}
}
if ((is.null(datatype))&&
((!length(name))||(length(.grep("datatype",name)))))
{
if (is.numeric(var))
{
if (as.integer(var) %in% c(1,2,3,4,5,12,13,11))
{
datatype <- var
next
}
}
else if (is.character(var))
{
datatype <- switch(var,byte=1L,integer=2L,real=4L,float=4L
,Byte=1L,UInt8=1L,Int8=11
,Int16=2L,UInt16=12,UInt32=13,Int32=3
,Float32=4L,Float64=5L
,NULL)
next
}
}
if ((is.null(ignore))&&(!is.ursa(var))&&((is.numeric(var))||(anyNA(var)))&&
(length(name))&&(length(.grep("(^bg$|nodata|ignore)",name))))
{
ignore <- var
next
}
if ((is.null(byteorder))&&(is.numeric(var))&&
((length(name))&&(length(.grep("byteorder",name)))))
{
byteorder <- as.integer(var)
if (byteorder)
byteorder <- 1L
next
}
# if ((is.null(bands))&&(is.numeric(var))&&((length(name))
# &&((length(.grep(name,"bands")))||(length(.grep(name,"nband")))||
# (length(.grep(name,"layers")))||(length(.grep(name,"nlayer"))))))
if ((is.null(bands))&&(is.numeric(var))&&(length(name))&&
(length(.grep("(layers|bands|nlayer|nband|length)",name))))
{
bands <- as.integer(var)
next
}
# if ((is.null(bandnames))&&(is.character(var))&&((length(name))
# &&((length(.grep(name,"bandname")))||
# (length(.grep(name,"layername")))||
# (length(.grep(name,"name"))))))
if ((is.null(bandnames))&&(is.character(var))&&(length(name))&&
(length(.grep("(bandname|layername|names)",name))))
{
bandnames <- var
next
}
if ((is.null(driver))&&(is.character(var))&&(length(name))&&
(length(.grep("driver",name))))
{
driver <- var
next
}
if ((is.null(compressed))&&((is.integer(var) || is.logical(var)))&&
((length(name))&&(length(.grep("compress",name)))))
{
compressed <- as.logical(var)
next
}
if ((is.null(wkt))&&((is.integer(var) || is.logical(var)))&&
((length(name))&&(length(.grep("wkt",name)))))
{
wkt <- as.logical(var)
next
}
if ((is.null(ext))&&(is.character(var))&&
((length(name))&&(length(.grep("ext",name)))))
{
ext <- var
next
}
}
if ((is.null(bands))&&(length(bandnames)))
bands <- length(bandnames)
if (is.null(fname))
{
fname <- .maketmp()
message(paste("Filename is assigned automatically:",fname))
}
myDir <- .dirname(fname)
if (!file.exists(myDir)) {
dir.create(myDir,recursive=TRUE)
}
con$fname <- file.path(chartr("\\","/",normalizePath(.dirname(fname)))
,.basename(fname))
if (!is.null(connection))
con$connection <- connection
else
connection <- "file"
if (is.na(con$connection))
con$connection <- connection
if (!is.null(datatype))
con$datatype <- datatype
else
datatype <- 4L
if (is.na(con$datatype))
con$datatype <- datatype
if (!is.null(ignore))
con$nodata <- ignore
else
ignore <- .make.nodata(datatype)
if (is.na(con$nodata))
con$nodata <- ignore
if (!is.null(interleave))
con$interleave <- interleave
else
interleave <- interleaveName[1]
if (is.na(con$interleave))
con$interleave <- interleave
if (!is.null(implement))
con$driver <- implement
else
implement <- implementName[1]
if (is.na(con$driver))
con$driver <- implement
if (!is.null(byteorder))
con$byteorder <- byteorder
else
byteorder <- 0L
if (is.na(con$byteorder))
con$byteorder <- byteorder
if ((con$driver %in% c("ENVI","EGDAL"))&&(TRUE)) ## forced to compress
{
if (!(is.null(compressed))) {
if (!is.na(compressed))
con$compress <- as.integer(compressed)
else
con$compress <- 1L
}
else
con$compress <- 1L
}
else
{
if (!is.null(compressed))
con$compress <- as.integer(compressed)
else
compressed <- 0L
if (is.na(con$compress))
con$compress <- compressed
con$compress <- abs(con$compress)
}
con$compress <- abs(con$compress)
if (!is.null(wkt))
con$wkt <- as.logical(wkt)
else
wkt <- FALSE
if (is.na(con$wkt))
con$wkt <- wkt
if (is.null(ext))
ext <- switch(con$driver,ENVI=".envi","")
else
{
ext <- if (nchar(ext)) paste0(".",ext) else ""
con$compress=0L
}
if (is.na(con$wkt))
con$wkt <- wkt
if (!is.null(bands))
con$bands <- bands
else if (length(obj$value))
bands <- obj$dim[2]
else
bands <- 1L
if (is.na(con$bands))
con$bands <- bands
con$mode <- if (con$datatype %in% c(1L,2L,3L,11L,12L,13L)) "integer"
else "numeric"
con$sizeof <- if (con$datatype %in% c(1L,11L)) 1L
else if (con$datatype %in% c(2L,12L)) 2L
else if (con$datatype %in% c(3L,13L,4L)) 4L else 8L
con$signed <- if (con$datatype %in% c(1L,12L,13L)) FALSE else TRUE
con$endian <- "little"
con$swap <- as.integer((.Platform$endian=="big")&(!con$byteorder)|
(.Platform$endian=="little")&(con$byteorder))
# endian != .Platform$endian
if (FALSE)
NULL
else if (length(.grep("\\.gz$",con$fname)))
con$connection <- "gzfile"
else if (length(.grep("\\.bz2$",con$fname)))
con$connection <- "bzfile"
else if (length(.grep("\\.xz$",con$fname)))
con$connection <- "xzfile"
else if (length(.grep("\\.(envi|bin|img|dat|tif|tiff|hfa)$",con$fname)))
{
con$connection <- "file"
con$compress <- 0L
}
##~ else if (length(.grep("\\.bin$",con$fname)))
##~ {
##~ con$connection <- "file"
##~ con$compress <- 0L
##~ }
##~ else if (length(.grep("\\.envi$",con$fname)))
##~ {
##~ con$connection <- "file"
##~ con$compress <- 0L
##~ }
##~ else if (length(.grep("\\.img$",con$fname)))
##~ {
##~ con$connection <- "file"
##~ con$compress <- 0L
##~ }
else if (length(.grep("\\.$",con$fname)))
{
con$fname <- substr(con$fname,1,nchar(con$fname)-1L)
con$connection <- "file"
con$compress <- 0L
}
else
con$fname <- sprintf("%s%s",con$fname,switch(con$connection
,file=ext,gzfile=".gz",bzfile=".bz2",xzfile=".xz",""))
if (!(con$connection %in% c("file")))
con$compress <- 0L
con$lines <- grid$rows
con$samples <- grid$columns
# con$offset <- as.integer(5*4+8*8+sum(nchar(obj$name))+length(obj$name)+
# nchar(obj$grid$crs)+1+
# 4*obj$dim[2]+con$sizeof)
if ((length(con$offset)>1)||(is.na(con$offset)))
con$offset <- 0L
if (is.na(con$bands))
{
if (!is.null(bandnames))
con$bands <- length(bandnames)
else
con$bands <- 1L
}
if ((!is.na(obj$dim[2]))&&(is.null(bands)))
con$bands <- obj$dim[2]
con$interleave <- with(con,switch(interleave,spatial="bsq",temporal="bil"
,interleave))
if (con$driver %in% c("ENVI","EGDAL")) {
if (con$driver=="ENVI")
con$handle <- do.call(con$connection,list(con$fname,"w+b"))
else {
ftemp <- .maketmp(1)
con$fname <- c(con$fname,ftemp)
con$handle <- do.call(con$connection,list(ftemp,"w+b"))
}
cl <- class(con$handle)
if (("bzfile" %in% cl)||("xzfile" %in% cl)||("gzfile" %in% cl)) ## gz?
con$seek <- FALSE
else
con$seek <- TRUE
rm(cl)
}
else if (con$driver %in% c("EGDAL","RGDAL")) {
if (.lgrep("\\.tif(f)*$",fname))
driver <- "GTiff"
else if (.lgrep("\\.img$",fname))
driver <- "HFA" # https://gdal.org/frmt_hfa.html
else if (.lgrep("\\.png$",fname))
driver <- "PNG"
else if (.lgrep("\\.jp(e)*g$",fname))
driver <- "JPEG"
else if (.lgrep("\\.bmp$",fname))
driver <- "BMP"
# else if (.lgrep("\\.sdat$",fname))
# driver <- "SAGA"
if (is.null(driver))
driver <- "ENVI"
dtName <- switch(as.character(datatype)
,'1'="Byte",'2'="Int16",'4'="Float32"
,'11'="Int8",'12'="UInt16",'13'="UInt32",'3'="Int32"
,'5'="Float64",stop("cannot recognize datatype"))
nb <- if (is.na(con$posZ[1])) con$bands else length(con$posZ)
if (con$driver %in% "RGDAL") {
try(con$handle <- methods::new("GDALTransientDataset"
,methods::new("GDALDriver",driver)
,con$lines,con$samples,nb,dtName))
if (!inherits(con$handle,"GDALTransientDataset"))
return(NA)
con$seek <- FALSE
}
else { ## via ENVI -> GDAL after closing
ftemp <- .maketmp(1)
con$fname <- c(con$fname,ftemp)
con$handle <- do.call(con$connection,list(ftemp,"w+b"))
con$seek <- TRUE
}
}
if ("file" %in% class(con$handle))
{
if (file.exists(oldpack <- paste0(con$fname[1],".gz")))
file.remove(oldpack)
if (file.exists(oldpack <- paste0(con$fname[1],".bz2")))
file.remove(oldpack)
if (file.exists(oldpack <- paste0(con$fname[1],".xz")))
file.remove(oldpack)
}
if (file.exists(aux <- paste0(con$fname[1],".aux.xml")))
file.remove(aux)
if (con$driver %in% c("ENVI","EGDAL")) {
if (((con$interleave %in% c("bil","bsq"))&&(con$seek))||
(con$connection %in% c("gzfile"))) #&&(!is.matrix(obj$value)))
{
nb <- ifelse(is.na(con$posZ[1]),con$bands,length(con$posZ))
seek(con,origin="start"
,where=with(con,(lines*samples*nb-1)*sizeof+offset),rw="w")
val <- 0L
storage.mode(val) <- con$mode
with(con,writeBin(val,size=sizeof,endian=endian,handle))
}
}
con$indexC <- NA
con$indexR <- NA
if ((!is.na(con$posZ[1]))&&(!is.na(con$indexZ[1])))
con$posZ <- con$indexZ[con$posZ]
con$indexZ <- NA
storage.mode(con$nodata) <- con$mode
storage.mode(con$datatype) <- "integer"
# con$driver <- "ENVI"
con$swap <- as.integer((.Platform$endian=="big")&(!con$byteorder)|
(.Platform$endian=="little")&(con$byteorder))
con
}
'.optimal.datatype' <- function(x,nodata=NULL)
{
if (is.ursa(x))
x <- x$value
if (TRUE) {
isInt <- is.integer(x)
n <- as.integer(prod(dim(x)))+as.integer(!is.null(nodata))
if (isInt) {
res <- .Cursa(C_optimalDatatypeInt,x=c(as.integer(x),as.integer(nodata))
,n=n,res=integer(1),NAOK=TRUE)$res
}
else {
res <- .Cursa(C_optimalDatatypeDouble,x=c(as.numeric(x),as.numeric(nodata))
,n=n,res=integer(1),NAOK=TRUE)$res
}
# str(res)
# print(summary(x));q()
return(res)
}
# isInteger <- is.integer(x)
dimx <- dim(x)
lend <- length(dimx)
if (!(length(dimx) %in% c(2,3)))
return(NULL)
# if (!isInteger)
# datatype <- 4
bands <- if (lend==3) dimx[3] else if (lend==2) dimx[1]
if (is.na(bands))
return(NULL)
datatypeout <- rep(NA_integer_,bands)
tmp <- if (lend==3) array(NA,dim=dimx[-lend]) else array(NA,dim=dimx[2])
for (i in seq(bands))
{
tmp[] <- if (lend==3) x[,,i] else if (lend==2) x[i,]
tmp[is.na(tmp)] <- 0
if ((all(tmp %in% 0:255))||(all(tmp %in% -128:127)))
datatypeout[i] <- 1L
else if (all(tmp %in% -32768:32767))
datatypeout[i] <- 2L
else if (all(tmp %in% 0:65536))
datatypeout[i] <- 12L
else
datatypeout[i] <- 4L
}
rm(tmp)
datatype <- unique(datatypeout)
if (length(datatype)>1)
{
if (4L %in% datatype)
datatype <- 4L
else if ((1L %in% datatype)&&(2L %in% datatype)&&(!(12L %in% datatype)))
datatype <- 2L
else if ((1L %in% datatype)&&(12L %in% datatype)&&(!(2L %in% datatype)))
datatype <- 12L
else
datatype <- 4L
}
datatype
}
'.write.hdr' <- function(x,clear=TRUE)
{
if (!is.ursa(x))
return(NULL)
grid <- x$grid
con <- x$con
if (!.is.grid(grid))
return(NULL)
if (!.is.con(con))
return(NULL)
if (is.na(con$interleave))
con$interleave <- "bsq"
if (is.na(con$samples))
con$samples <- grid$columns
if (is.na(con$lines))
con$lines <- grid$rows
if (is.na(con$bands))
con$bands <- 1L
if (is.na(con$byteorder))
con$byteorder <- 0L
if (is.na(con$datatype))
con$datatype <- 1L
indF <- ifelse(length(con$fname)>1,2L,1L)
fname <- .gsub("\\.(bin|bingz|envi|envigz|img|dat|gz|bz2|xz|unpacked(.*)~)$",""
,con$fname[indF])
if (is.na(fname))
{
fname <- x$name[1]
con$fname <- fname
}
myname <- paste(fname,".hdr",sep="")
if (clear)
{
list1 <- .dir(path=dirname(fname)
,pattern=sprintf("^%s($|\\.(envi|envigz|bin|bingz|dat|img|gz|bz2|xz|.*aux\\.xml)$)"
,basename(fname)),full.names=TRUE)
if (length(ind <- .grep(sprintf("^%s$",basename(con$fname[indF])),basename(list1))))
list1 <- list1[-ind]
file.remove(list1[which(!file.info(list1)$isdir)])
}
Fout <- file(myname,"wt")
writeLines(sprintf("%s","ENVI"),Fout)
writeLines(sprintf("description = {%s}",con$fname[indF]),Fout)
writeLines(sprintf("samples = %d",con$samples),Fout)
writeLines(sprintf("lines = %d",con$lines),Fout)
if (is.na(con$posZ[1]))
writeLines(sprintf("bands = %d",con$bands),Fout)
else
writeLines(sprintf("bands = %d",length(con$posZ)),Fout)
writeLines(sprintf("header offset = %d",0),Fout)
writeLines(sprintf("file type = %s","ENVI Standard"),Fout)
writeLines(sprintf("data type = %d",con$datatype),Fout)
writeLines(sprintf("interleave = %s",con$interleave),Fout)
if (FALSE)
writeLines(sprintf("sensor type = %s","Unknown"),Fout)
writeLines(sprintf("byte order = %d",con$byteorder),Fout)
if ((length(unique(con$nodata))==1)&&(!is.na(con$nodata)))
writeLines(sprintf("data ignore value = %s",con$nodata[1]),Fout)
projection_name <- "ursa package"
projection_ellipse <- "unknown"
projection_units <- "units=meters"
projection_info <- ""
proj4 <- grid$crs[1]
p <- NULL
if (nchar(proj4))
{
pr <- unlist(strsplit(proj4,"\\s+"))
projection_ellipse <- "unknown"
projection_units <- "units=meters"
projection_name <- "R"
semi <- NULL
if (FALSE)
semi <- c("6378137","6356752.3") ## low-precision
if (.lgrep("\\+datum=WGS84",pr))
semi <- c("6378137","6356752.314245179")
else if (.lgrep("\\+ellps=WGS84",pr))
semi <- c("6378137","6356752.314245179")
else if (.lgrep("\\+ellps=krass",pr))
semi <- c("6378245","6356863.018773047")
else
semi <- c(.gsub2("\\s\\+a=(\\S+)\\s","\\1",proj4)
,.gsub2("\\s\\+b=(\\S+)\\s","\\1",proj4))
if (.lgrep("\\+proj=laea",pr))
{
p <- c(p,"11",semi)
p <- c(p,.gsub2("\\s\\+lat_0=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+lon_0=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+x_0=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+y_0=(\\S+)\\s","\\1",proj4))
projection_name <- "Lambert Azimuthal Equal Area"
}
else if (.lgrep("\\+proj=stere",pr))
{
if (.lgrep("\\+lat_ts",proj4)) {
p <- c(p,"31",semi)
p <- c(p,.gsub2("\\s\\+lat_ts=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+lon_0=(\\S+)(\\s|$)","\\1",proj4))
if(.lgrep("\\s\\+x_0=(\\S+)(\\s|$)",proj4))
p <- c(p,.gsub2("\\s\\+x_0=(\\S+)(\\s|$)","\\1",proj4))
else
p <- c(p,"0")
if(.lgrep("\\s\\+y_0=(\\S+)(\\s|$)",proj4))
p <- c(p,.gsub2("\\s\\+y_0=(\\S+)(\\s|$)","\\1",proj4))
else
p <- c(p,"0")
projection_name <- "Polar Stereographic"
}
else {
p <- c(p,"7",semi)
p <- c(p,.gsub2("\\s\\+lat_0=(\\S+)(\\s|$)","\\1",proj4))
p <- c(p,.gsub2("\\s\\+lon_0=(\\S+)(\\s|$)","\\1",proj4))
if(.lgrep("\\s\\+x_0=(\\S+)(\\s|$)",proj4))
p <- c(p,.gsub2("\\s\\+x_0=(\\S+)(\\s|$)","\\1",proj4))
else
p <- c(p,"0")
if(.lgrep("\\s\\+y_0=(\\S+)(\\s|$)",proj4))
p <- c(p,.gsub2("\\s\\+y_0=(\\S+)(\\s|$)","\\1",proj4))
else
p <- c(p,"0")
projection_name <- "Stereographic (ellipsoid)"
}
}
else if (.lgrep("\\+proj=tmerc",pr))
{
p <- c(p,"3",semi)
p <- c(p,.gsub2("\\s\\+lat_ts=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+lon_0=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+x_0=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+y_0=(\\S+)\\s","\\1",proj4))
projection_name <- "Transverse Mercator"
}
else if (.lgrep("\\+proj=lcc",pr))
{
p <- c(p,"4",semi)
p <- c(p,.gsub2("\\s\\+lat_0=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+lon_0=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+x_0=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+y_0=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+lat_1=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+lat_2=(\\S+)\\s","\\1",proj4))
projection_name <- "Lambert Conformal Conic"
}
else if (.lgrep("\\+proj=aea",pr))
{
p <- c(p,"9",semi)
p <- c(p,.gsub2("\\s\\+lat_0=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+lon_0=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+x_0=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+y_0=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+lat_1=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+lat_2=(\\S+)\\s","\\1",proj4))
projection_name <- "Albers Conical Equal Area"
}
else if (.lgrep("\\+proj=zzzcea",pr))
{
p <- c(p,"99",semi)
p <- c(p,.gsub2("\\s\\+lon_0=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+lat_ts=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+x_0=(\\S+)\\s","\\1",proj4))
p <- c(p,.gsub2("\\s\\+y_0=(\\S+)\\s","\\1",proj4))
projection_name <- "Equal Area Cylindrical"
}
if ((FALSE)||(!nchar(projection_name)))
{
print(pr)
print(projection_info)
stop("NEW PROJECTION")
}
if (!is.null(p))
{
p <- c(p,projection_name,projection_units)
projection_info <- paste0("{",paste(p,collapse=", "),"}")
}
}
tempx <- with(grid,minx+0*0.5*resx)
tempy <- with(grid,grid$maxy-0*0.5*resy)
map_info <- c(projection_name,1,1,tempx,tempy,grid$resx,grid$resy
,projection_ellipse,projection_units)
map_info <- paste0("{",paste(map_info,collapse=", "),"}")
writeLines(sprintf("map info = %s",map_info),Fout)
if ((TRUE)&&(nchar(Sys.which("gdalsrsinfo")))) ## forced 'gdalsrsinfo'/showWKT
projection_info <- ""
if (projection_info!="")
writeLines(sprintf("projection info = %s",projection_info),Fout)
wkt <- NULL
if ((TRUE)&&(!is.null(p))) ## help QGIS to recognize EPSG
{
.epsg <- NA
if ((p[1]=="31")&&
(as.numeric(p[2])==6378137)&&(as.numeric(p[3])==6356752.314245179)&&
(as.numeric(p[4])==70)&&(as.numeric(p[5])==-45)) {
.epsg <- "3408"
wkt <- paste0("PROJCS[\"WGS_84_NSIDC_Sea_Ice_Polar_Stereographic_North\""
,",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\""
,",SPHEROID[\"WGS_1984\",6378137,298.257223563]]"
,",PRIMEM[\"Greenwich\",0]"
,",UNIT[\"Degree\",0.017453292519943295]]"
,",PROJECTION[\"Stereographic_North_Pole\"]"
,",PARAMETER[\"standard_parallel_1\",70]"
,",PARAMETER[\"central_meridian\",-45]"
,",PARAMETER[\"false_easting\",0]"
,",PARAMETER[\"false_northing\",0],UNIT[\"Meter\",1]]}")
}
else if ((p[1]=="36")&&
(as.numeric(p[2])==6378137)&&
(as.numeric(p[3])==6356752.314245179)&&
(as.numeric(p[4])==90))
{
if (as.numeric(p[5])==180)
{
.epsg <- "3571"
wkt <- paste0("PROJCS[\"WGS_84_North_Pole_LAEA_Bering_Sea\""
,",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\""
,",SPHEROID[\"WGS_1984\",6378137,298.257223563]]"
,",PRIMEM[\"Greenwich\",0]"
,",UNIT[\"Degree\",0.017453292519943295]]"
,",PROJECTION[\"Lambert_Azimuthal_Equal_Area\"]"
,",PARAMETER[\"latitude_of_origin\",90]"
,",PARAMETER[\"central_meridian\",180]"
,",PARAMETER[\"false_easting\",0]"
,",PARAMETER[\"false_northing\",0],UNIT[\"Meter\",1]]")
}
else if (as.numeric(p[5])==-150) {
.epsg <- "3572"
wkt <- paste0("PROJCS[\"WGS_84_North_Pole_LAEA_Alaska\""
,",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\""
,",SPHEROID[\"WGS_1984\",6378137,298.257223563]]"
,",PRIMEM[\"Greenwich\",0]"
,",UNIT[\"Degree\",0.017453292519943295]]"
,",PROJECTION[\"Lambert_Azimuthal_Equal_Area\"]"
,",PARAMETER[\"latitude_of_origin\",90]"
,",PARAMETER[\"central_meridian\",-150]"
,",PARAMETER[\"false_easting\",0]"
,",PARAMETER[\"false_northing\",0],UNIT[\"Meter\",1]]")
}
else if (as.numeric(p[5])==90) {
.epsg <- "3576"
wkt <- paste0("PROJCS[\"WGS_84_North_Pole_LAEA_Russia\""
,",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\""
,",SPHEROID[\"WGS_1984\",6378137,298.257223563]]"
,",PRIMEM[\"Greenwich\",0]"
,",UNIT[\"Degree\",0.017453292519943295]]"
,",PROJECTION[\"Lambert_Azimuthal_Equal_Area\"]"
,",PARAMETER[\"latitude_of_origin\",90]"
,",PARAMETER[\"central_meridian\",90]"
,",PARAMETER[\"false_easting\",0]"
,",PARAMETER[\"false_northing\",0],UNIT[\"Meter\",1]]")
}
}
# print(.epsg)
rm(.epsg)
}
if ((is.null(wkt))&&(projection_info=="")&&(nchar(proj4)))
{
lverbose <- FALSE
if (lverbose)
.elapsedTime("proj4 -> wkt start")
# loadNamespace("sf") ## for development
# (!("package:rgdal" %in% search()))) {
if ((nchar(Sys.which("gdalsrsinfo")))&&
(!(any(c("rgdal","sf") %in% loadedNamespaces())))) {
if (lverbose)
message("'gdalsrsinfo' engine (write)")
if (FALSE)
wkt <- system2("gdalsrsinfo",c("-o wkt",.dQuote(proj4))
,stdout=TRUE)
else {
wktout <- .maketmp(ext=".wkt~")
# shell(paste("gdalsrsinfo -o wkt",paste0("\"",proj4,"\""),"1>",wktout))
# 20170319 dQuote() returns non-symmetrical quotes in interactive()
system2("gdalsrsinfo",c("-o wkt_esri",.dQuote(proj4))
,stdout=wktout,stderr=FALSE)
wkt <- readLines(wktout,warn=FALSE)
file.remove(wktout)
}
}
else {
if (!("sf" %in% loadedNamespaces())) {
if (.isPackageInUse()) {
if (lverbose)
message("forced 'sf' loading")
requireNamespace("sf") ## rgdal retired
}
}
if (!("sf" %in% loadedNamespaces())) {
if (lverbose)
message("'rgdal' engine")
if (!.try(wkt <- .rgdal_showWKT(proj4,morphToESRI=TRUE)))
wkt <- NULL
}
else { ## 'sf' in namespace; 'OGC_WKT' ONLY.
if (lverbose)
message("'sf' engine")
if (!.try(wkt <- {
if (utils::packageVersion("sf")<"0.9")
ret <- sf::st_as_text(sf::st_crs(proj4),EWKT=TRUE)
else
ret <- sf::st_crs(proj4)$Wkt
ret
}))
# if (!.try(wkt <- sf::st_as_text(sf::st_crs(proj4),EWKT=TRUE)))
# wkt <- NULL
# print(proj4)
# message(wkt)
if (!TRUE) { ## 20191216 patch for EXTENSION["PROJ4","+proj=......."]
wkt <- gsub(",EXTENSION\\[\"PROJ4\".+\\]","]",wkt)
}
}
}
if (lverbose)
.elapsedTime("proj4 -> wkt finish")
}
if (!is.null(wkt)) {
if (length(wkt))
wkt <- paste(gsub("(^\\s+|\\s+$)","",wkt),collapse="")
writeLines(sprintf("coordinate system string = {%s}",wkt),Fout)
}
if ((is.character(x$name))&&(sum(nchar(x$name))>0))
{
if (.lgrep(",",x$name)) {
metaname <- paste0(.gsub("\\.(gz|bz2|xz)$","",x$con$fname[indF]),".aux.xml")
Fmeta <- file(metaname,"wt")
writeLines("<PAMDataset>",Fmeta)
writeLines(" <Metadata>",Fmeta)
for (i in seq_along(x$name))
writeLines(paste0(" <MDI key=",.dQuote(paste0("Band_",i))
,">",x$name[i],"</MDI>"),Fmeta)
writeLines(" </Metadata>",Fmeta)
writeLines("</PAMDataset>",Fmeta)
close(Fmeta)
}
else {
if (all(!is.na(x$con$posZ)))
bandnames <- paste(x$name[x$con$posZ],sep="",collapse=",\n\t")
else
bandnames <- paste(x$name,sep="",collapse=",\n\t")
writeLines(sprintf("band names = {\n\t%s}",bandnames),Fout)
}
}
if (length(x$colortable))
{
ct <- x$colortable
writeLines(sprintf("classes = %d",length(ct)),Fout)
isCol <- TRUE
if (is.numeric(ct))
val <- as.numeric(ct)
else {
val <- as.character(ct)
if (all(is.na(val)))
isCol <- FALSE
else
val <- c(col2rgb(as.character(val)))
}
if (isCol) {
val <- paste(val,sep="",collapse=",")
writeLines(sprintf("class lookup = {%s}",val),Fout)
}
if (!is.null(names(ct))) {
if (TRUE) ## if '\t' not recoginizing
{
val <- .gsub(",",";",names(x$colortable))
val <- paste(val,sep="",collapse=",")
writeLines(sprintf("class names = {%s}",val),Fout)
}
else
{
val <- paste(names(x$colortable),sep="",collapse=",\n\t")
writeLines(sprintf("class names = {\n\t%s}",val),Fout)
}
}
}
close(Fout)
invisible(chartr("\\","/",normalizePath(myname)))
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/yyy.connection.R
|
'.crop' <- function(fileout,border=5,verbose=FALSE) {
isJPEG <- .lgrep("(jpg|jpeg)",gsub(".*\\.(.+$)","\\1",fileout))>0
isWEBP <- .lgrep("(webp)",gsub(".*\\.(.+$)","\\1",fileout))>0
isSVG <- .lgrep("(svg)",gsub(".*\\.(.+$)","\\1",fileout))>0
isPNG <- .lgrep("(png)",gsub(".*\\.(.+$)","\\1",fileout))>0
frame <- as.integer(round(border))
if (!isSVG)
requireNamespace("png",quietly=.isPackageInUse())
if (isPNG)
NULL
else if (isJPEG) {
# if (!requireNamespace("jpeg",quietly=.isPackageInUse()))
# stop("Suggested package 'jpeg' missed, but is required here.")
isJPEG <- requireNamespace("jpeg",quietly=.isPackageInUse())
}
else if (isWEBP)
isWEBP <- requireNamespace("webp",quietly=.isPackageInUse())
else if (isSVG) {
if (!(isSVG <- requireNamespace("magick",quietly=.isPackageInUse())))
return(0L)
# print("A")
# imread <- purrr::safely(magick::image_read)
# a <- imread(fileout)
# print("B")
# str(a)
# q()
# tempf <- tempfile()
# sink(tempf)
a <- magick::image_raster(magick::image_read(fileout))
# sink()
# file.remove(tempf)
x <- col2rgb(a$col)/255
dim(x) <- c(dim(x)[1],max(a$x),max(a$y))
x <- aperm(x,c(3,2,1))
rm(a)
}
if (!isSVG)
x <- png::readPNG(fileout,native=FALSE,info=TRUE)
dimx <- dim(x)
isBlack <- isTRUE(getOption("ursaPngBackground") %in% (c("black","#000000")))
if (isBlack)
b <- .Cursa(C_internalMargin,x=1-as.numeric(x),dim=as.integer(dimx)
,indr=integer(dimx[1]),indc=integer(dimx[2]),NAOK=TRUE)
else
b <- .Cursa(C_internalMargin,x=as.numeric(x),dim=as.integer(dimx)
,indr=integer(dimx[1]),indc=integer(dimx[2]),NAOK=TRUE)
indentc <- rep(which(b$indc==1)[1],frame)
d <- diff(b$indc)
s1 <- which(d==-1)+1L
s2 <- which(d==1)
if (b$indc[1]==0)
s1 <- c(1L,s1)
if (b$indc[length(b$indc)]==0)
s2 <- c(s2,length(b$indc))
seqc <- s1[1]:s2[length(s2)]
indc <- c(indentc,seqc,indentc)
indentr <- rep(which(b$indr==1)[1],frame)
d <- diff(b$indr)
s1 <- which(d==-1)+1L
s2 <- which(d==1)
if (b$indr[1]==0)
s1 <- c(1L,s1)
if (b$indr[length(b$indr)]==0)
s2 <- c(s2,length(b$indr))
seqr <- s1[1]:s2[length(s2)]
indr <- c(indentr,seqr,indentc)
att <- attr(x,"info")
if (is.null(att$dpi)) { ## e.g. after Cairo::CairoPNG
dpi <- getOption("ursaPngDpi")
if (is.numeric(dpi))
att$dpi <- dpi
}
if (isSVG) {
sc <- 0.75
##~ print(range(seqc))
##~ print(range(seqr))
lenc <- round(length(seqc)*sc,2)
lenr <- round(length(seqr)*sc,2)
seqc <- round(range(seqc)*sc,2)
seqr <- round(range(seqr)*sc,2)
##~ print(seqc)
##~ print(seqr)
##~ print(lenc)
##~ print(lenr)
content <- readLines(fileout)
patt <- paste0("^(.+)(width=\\S+\\sheight=\\S+\\s)(viewBox=(\\\"|'))"
,"\\S+\\s\\S+\\s\\S+\\s\\S+((\\\"|').+)$")
if (length(ind <- grep(patt,head(content,4)))==1) {
##~ print(content[ind])
content[ind] <- gsub(patt,paste0("\\1\\3"
,seqc[1]-frame," "
,seqr[1]-frame," "
,lenc[1]+frame+frame," "
,lenr[1]+frame+frame
,"\\5"),content[ind])
##~ print(content[ind])
# file.copy(fileout,paste0(fileout,"~"))
writeLines(content,paste0(fileout,""))
}
}
else if (isJPEG)
jpeg::writeJPEG(x[indr,indc,],fileout)
else if (isWEBP)
webp::write_webp(x[indr,indc,],fileout)
else
png::writePNG(x[indr,indc,],fileout,dpi=att$dpi,text=c(source=R.version.string))
0L
}
'.crop2' <- function(fileout,border=5,verbose=FALSE) {
if (verbose)
.elapsedTime("crop2:start")
frame <- as.integer(round(border))
isJPEG <- .lgrep("(jpg|jpeg)",gsub(".*\\.(.+$)","\\1",fileout))>0
isWEBP <- .lgrep("(webp)",gsub(".*\\.(.+$)","\\1",fileout))>0
requireNamespace("png",quietly=.isPackageInUse())
if (isJPEG)
isJPEG <- requireNamespace("jpeg",quietly=.isPackageInUse())
if (isWEBP)
isWEBP <- requireNamespace("webp",quietly=.isPackageInUse())
x <- png::readPNG(fileout,native=FALSE,info=TRUE)
dimx <- dim(x)
b <- .Cursa(C_internalMargin,x=as.numeric(x),dim=as.integer(dimx)
,indr=integer(dimx[1]),indc=integer(dimx[2]),NAOK=TRUE)
indentc <- rep(which(b$indc==1)[1],frame)
d <- diff(b$indc)
s1 <- which(d==-1)+1L
s2 <- which(d==1)
if (b$indc[1]==0)
s1 <- c(1L,s1)
if (b$indc[length(b$indc)]==0)
s2 <- c(s2,length(b$indc))
d <- s1[2:length(s1)]-s2[1:(length(s2)-1)]
ind <- which(d>frame)
s1 <- s1[c(1,ind+1)]
s2 <- s2[c(ind,length(s2))]
indc <- indentc
for (i in seq_along(s1))
indc <- c(indc,s1[i]:s2[i],indentc)
indentr <- rep(which(b$indr==1)[1],frame)
d <- diff(b$indr)
s1 <- which(d==-1)+1L
s2 <- which(d==1)
if (b$indr[1]==0)
s1 <- c(1L,s1)
if (b$indr[length(b$indr)]==0)
s2 <- c(s2,length(b$indr))
d <- s1[2:length(s1)]-s2[1:(length(s2)-1)]
ind <- which(d>frame)
s1 <- s1[c(1,ind+1)]
s2 <- s2[c(ind,length(s2))]
indr <- indentr
for (i in seq_along(s1))
indr <- c(indr,s1[i]:s2[i],indentr)
att <- attr(x,"info")
if (isJPEG)
jpeg::writeJPEG(x[indr,indc,],fileout)
else if (isWEBP)
webp::write_webp(x[indr,indc,],fileout)
else
png::writePNG(x[indr,indc,],fileout,dpi=att$dpi,text=c(source=R.version.string))
if (verbose)
.elapsedTime("crop2:finish")
0L
}
'.nocrop' <- function(fileout,border,verbose) {
isJPEG <- .lgrep("(jpg|jpeg)",gsub(".*\\.(.+$)","\\1",fileout))>0
if (!isJPEG)
return(NULL)
isJPEG <- requireNamespace("jpeg",quietly=.isPackageInUse())
if (!isJPEG)
return(NULL)
requireNamespace("png",quietly=.isPackageInUse())
jpeg::writeJPEG(png::readPNG(fileout,native=FALSE,info=TRUE),fileout)
NULL
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/yyy.crop.R
|
'.zzz.zzzregrid' <- function(obj,...) {
print("regrid")
if (missing(obj))
obj <- session_grid()
UseMethod("regrid")
}
'.zzz.zzzregrid.default' <- function(obj,...) {
print(methods("regrid"))
print(paste("'regrid' is not implemented for",paste(.sQuote(class(obj)),collapse=", ")))
NULL
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/yyy.genericResize.R
|
'.getPrm' <- function(link,name="",kwd="",class=NA,index=0L,default=NULL
,valid=NULL,coerce=TRUE,verbose=FALSE) {
if (benchmark <- FALSE) {
.cum <- getOption("ursaPrm")
if (is.null(.cum))
.cum <- list(time=0,n=0L)
.begin <- proc.time()[3]
on.exit({
.delta <- proc.time()[3]-.begin
if (.delta>0) {
print(unname(.delta),digits=6)
print(name)
}
options(ursaPrm=list(time=.cum$time+.delta,n=.cum$n+1L))
})
}
if (index>0)
return(link[[index]])
if (!((is.character(class))||(is.list(class))))
class <- class(default)
myname <- names(link)
if (is.null(myname))
myname <- rep("",length(link))
if (nchar(kwd)) {
if (.lgrep("\\$$",kwd))
kwd <- substr(kwd,1,nchar(kwd)-1)
name <- c(paste0(name,"\\.",kwd),paste0(kwd,"\\.",name)
,paste0("^",name,"$"))[2:3]
if (.lgrep("\\^\\$",name))
name <- c(kwd,name)
}
if (verbose)
print(name)
xName <- expand.grid(where=myname,what=name,KEEP.OUT.ATTRS=FALSE)
if (verbose)
print(xName)
ind <- which(apply(xName,1,function(x) .lgrep(x["what"],x["where"]))>0)
# ind <- which(apply(xName,1,function(x) length(which(!is.na(match(x["what"],x["where"])))))>0)
if ((length(valid))&&(is.character(valid))&&(is.null(default)))
default <- match.arg(valid,valid)
if (!length(ind)) {
return(default)
}
if (verbose)
print(xName[ind[1],])
i <- match(xName[ind[1],"where"],myname)
cl <- class(link[[i]])
if ("ursaStack" %in% cl)
cl <- "list"
isList <- is.list(link[[i]])
if (!is.list(class))
class <- list(class)
if (verbose)
str(class)
for (j in seq_along(class)) {
toInteger <- FALSE
toLogical <- FALSE
toNumeric <- FALSE
cl2 <- class[[j]]
if (("NULL" %in% cl2)&&(length(valid)))
cl2 <- class(valid)
if (("list" %in% cl2)&&(!("list" %in% cl)))
next
# if (("list" %in% cl2)&&(!isList))
# next
if (("list" %in% cl)&&(!(("list" %in% cl2)||("" %in% cl2))))
next
# if ((isList)&&(!(("list" %in% cl2)||("" %in% cl2))))
# next
if ("" %in% cl2)
return(link[[i]])
cl2 <- .grep("list",cl2,value=TRUE,invert=TRUE)
if (verbose) {
print(c(pat=name,arg=myname[i],cl=cl,'cl2:'=cl2),quote=FALSE)
}
if (("integer" %in% cl2)&&("numeric" %in% cl)) {
toInteger <- TRUE
# m2 <- all(na.omit(.is.integer(link[[i]]))) ## removed 20161228
m2 <- all(.is.integer(na.omit(link[[i]]))) ## added 20161228
}
else if (("logical" %in% cl2)&&
(!(any(c("integer","numeric") %in% cl2)))&&
(any(c("integer","numeric") %in% cl))) {
toLogical <- TRUE
m2 <- TRUE #as.logical(link[[i]])
}
# else if (isList) { ## ("list" %in% cl)
else if ("list" %in% cl) {
# m2 <- all(sapply(link[[i]],function(x) class(x)) %in% cl2) ## removed 2016-06-10
m2 <- all(sapply(link[[i]],function(x) any(class(x) %in% cl2))) ## added 2016-06-10
}
else if ("numeric" %in% cl2) {
if (F & cl2[1]=="logical") ## added 20210425
toLogical <- TRUE
else
toNumeric <- TRUE ## before 20210425 always
m2 <- is.numeric(link[[i]]) | is.logical(link[[i]])
}
else {
m2 <- length(na.omit(match(cl2,cl)))>0 ##cl2 %in% cl
}
if (verbose)
print(m2)
if (!m2) {
if (length(valid)) {
if (!any(cl %in% cl2))
next
w <- paste(paste0(.sQuote(name),"="
,ifelse(is.character(link[[i]])
,.dQuote(link[[i]]),link[[i]]),".")
,"Expected: ",paste0(paste(valid,collapse=", "),".")
,"Use default:",default)
opW <- options(warn=1)
warning(w)
options(opW)
}
next
}
if (length(valid)) {
m2 <- FALSE
if ((is.numeric(valid))||(is.numeric(link[[i]]))) {
ind <- na.omit(which(as.numeric(link[[i]]) %in% as.numeric(valid)))
if (length(ind)) {
link[[i]] <- link[[i]][ind]
m2 <- TRUE
}
else if (nchar(myname[i])) {
w <- paste(paste0(.sQuote(myname[i]),"=",link[[i]])
,"is not in a list:"
,paste0(paste(valid,collapse=", "),".")
,"Use default:",default)
opW <- options(warn=1)
warning(w)
options(opW)
}
}
else if ((is.character(link[[i]]))||(is.character(valid))) {
ind <- na.omit(pmatch(as.character(link[[i]])
,as.character(valid)))
if (length(ind)) {
link[[i]] <- unname(sapply(as.character(link[[i]])
,function(x) match.arg(x,as.character(valid))))
m2 <- TRUE
}
else if (nchar(myname[i])) {
if (is.null(default))
default <- match.arg(valid,valid) ## valid[1]
w <- paste(paste0(.sQuote(myname[[i]]),"=",.dQuote(link[[i]]))
,"is not in a list:"
,paste0(paste(.dQuote(valid),collapse=", "),".")
,"Use default:",.dQuote(default))
opW <- options(warn=1)
warning(w)
options(opW)
print(link[[i]])
}
}
if (!m2)
next
}
if (!coerce)
return(link[[i]])
if (toInteger) {
return(as.integer(link[[i]]))
}
else if (toLogical) {
return(as.logical(link[[i]]))
}
else if (toNumeric) {
return(as.numeric(link[[i]]))
}
else
return(link[[i]])
}
default
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/yyy.getPrm.R
|
'.getBand' <- function(x,i,regexp=FALSE,new=FALSE)
{
if (!is.ursa(x))
return(NULL)
if (is.numeric(i))
return(i)
if (!is.character(i))
return(NULL)
if (!is.na(x$con$posZ[1]))
myname <- x$name[x$con$posZ]
else
myname <- x$name
m <- NULL
if (!regexp)
m <- na.omit(match(i,myname))
if ((!length(m))||(regexp))
{
m <- NULL
for (k in i)
m <- c(m,.grep(k,myname))
}
if (!length(m))
{
if (new)
return(length(x$name)+seq(i))
return(NULL)
}
return(m)
}
'.read.hdr' <- function(fname,resetGrid=TRUE)
{
opW <- options(warn=2)
x <- open_envi(fname=fname,resetGrid=resetGrid,headerOnly=TRUE)
if (!is.na(x$con$handle))
close(x$con$handle)
options(opW)
x
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/yyy.misc.R
|
# https://thomasadventure.blog/posts/how-does-the-pipe-operator-actually-work/
`.%>%.ursaRaster` <- function(lhs, rhs) {
lhs <- substitute(lhs)
rhs <- substitute(rhs)
building_blocks <- c(
rhs[[1L]],
lhs,
as.list(rhs[-1L])
)
call <- as.call(building_blocks)
eval(call, envir = parent.frame())
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/yyy.pipe.R
|
'.makeFileout' <- function(obj,fileout="")
{
if (!nchar(fileout))
{
if (!is.na(obj$con$fname))
{
f <- obj$con$fname
string <- "\\.(unpacked(.*)~|bin|bingz|envi|enviz)$"
if (.lgrep(string,f))
f <- .gsub(string,"",f)
fileout <- paste0(basename(f),basename(.maketmp()),".png")
rm(f)
}
else
fileout <- .maketmp(ext="png")
}
if (!.lgrep("\\.png$",fileout))
fileout <- paste0(fileout,".png")
fileout
}
'.repairForScatterPlot' <- function() {
g1 <- session_grid()
if ((nchar(g1$crs)==0)||(is.na(g1$crs)))
{
cexx <- cexy <- 1
x <- seq(g1,"x")
y <- seq(g1,"y")
img <- list(x=x,y=y)
labx0 <- attr(g1$seqx,"lab")
laby0 <- attr(g1$seqy,"lab")
if (!is.null(labx0)) {
if (length(g1$seqx)!=g1$columns) {
attrx <- attributes(g1$seqx)
g1$seqx <- seq(g1,"x")
attributes(g1$seqx) <- attrx
}
}
if (!is.null(laby0)) {
if (length(g1$seqy)!=g1$rows) {
attry <- attributes(g1$seqy)
g1$seqy <- seq(g1,"y")
attributes(g1$seqy) <- attry
}
}
if ((!is.null(g1$seqx))&&(length(g1$seqx)))
{
if (length(labx0))
{
if (length(names(labx0))==length(labx0))
xlab <- names(labx0)
else
xlab <- labx0
xo <- data.frame(at=NA,lab=xlab,stringsAsFactors=FALSE)
for (i in seq(nrow(xo)))
{
v <- labx0[i]
i2 <- which(v<g1$seqx)[1]
if ((is.na(i2))||(i2<2))
next
i1 <- i2-1
sc <- (v-g1$seqx[i1])/(g1$seqx[i2]-g1$seqx[i1])
xo$at[i] <- img$x[i1]+sc*(img$x[i2]-img$x[i1])
}
# xo <- subset(xo,!is.na(at))
xo <- xo[!is.na(xo$at),]
}
else
{
xo <- .prettyLabel(img$x,ncol=11)
# xo <- subset(xo,at>=g1$minx & at<=g1$maxx)
xo <- xo[xo$at>=g1$minx & xo$at<=g1$maxx,]
if (F & 0 %in% xo$at) ## WHY???
xo$at <- xo$at+1L
if (F & all(xo$at>0)) ## WHY?
xo$lab <- g1$seqx[xo$at]
if (F) ## WHY?
xo$at <- xo$at-0.5
}
}
else
{
xt <- axTicks(1)
xo <- data.frame(at=xt,lab=as.character(xt),stringsAsFactors=FALSE)
# cexx <- 0.5
}
if ((!is.null(g1$seqy))&&(length(g1$seqy)))
{
if (length(laby0))
{
if (length(names(laby0))==length(laby0))
ylab <- names(laby0)
else
ylab <- laby0
yo <- data.frame(at=NA,lab=ylab,stringsAsFactors=FALSE)
for (i in seq(nrow(yo)))
{
v <- laby0[i]
i2 <- which(v<g1$seqy)[1]
if ((is.na(i2))||(i2<2))
next
i1 <- i2-1
sc <- (v-g1$seqy[i1])/(g1$seqy[i2]-g1$seqy[i1])
yo$at[i] <- img$y[i1]+sc*(img$y[i2]-img$y[i1])
}
# yo <- subset(yo,!is.na(at))
yo <- yo[!is.na(yo$at),]
}
else
{
yo <- .prettyLabel(img$y,ncol=11)
# yo <- subset(yo,at>=g1$miny & at<=g1$maxy)
yo <- yo[yo$at>=g1$miny & yo$at<=g1$maxy,]
if (0 %in% yo$at)
yo$at <- yo$at+1L
if (all(yo$at>0))
yo$lab <- g1$seqy[yo$at]
yo$at <- yo$at-0.5
}
}
else
{
yt <- axTicks(2)
yo <- data.frame(at=yt,lab=as.character(yt),stringsAsFactors=FALSE)
# cexy <- 0.5
}
abline(v=xo$at,h=yo$at,lty=2,col="#0000002F")
panel <- options()[.grep("^ursaPng.+",names(options()))]
layout <- panel[["ursaPngLayout"]][["layout"]]
figure <- panel[["ursaPngFigure"]]
isTop <- figure %in% layout[3,]
isBottom <- figure %in% layout[nrow(layout)-2,]
isLeft <- figure %in% layout[,3]
isRight <- figure %in% layout[,ncol(layout)-2]
rm(panel,layout,figure)
# axis(side=1,at=xo$at,labels=NA,tck=-0.2,col="red")
# axis(side=2,at=yo$at,labels=NA,tck=-0.2,col="blue")
width <- strwidth(paste(xo$lab,collapse=" "),units="inches",cex=cexy)
if (width>0.5*par()$pin[1])
{
i0 <- which(seq(nrow(xo))%%2==0)
i1 <- which(seq(nrow(xo))%%2==1)
if (isTop)
mtext(side=3,text=xo$lab[i0],at=xo$at[i0],padj=-0.25,adj=0.5,line=0
,cex=cexx,las=1)
if (isBottom)
mtext(side=1,text=xo$lab[i1],at=xo$at[i1],padj=0.5,adj=0.5
,cex=cexx,las=1)
rm(i0,i1)
}
else if (isBottom)
mtext(side=1,text=xo$lab,at=xo$at,padj=0.5,adj=0.5,cex=cexx,las=1)
if (isLeft) {
mtext(side=2,text=yo$lab,at=yo$at,padj=0.4,adj=1.0,line=0.4,cex=cexy,las=1)
}
xu <- attr(g1$seqx,"units")
if ((isBottom)&&(is.character(xu)))
{
xu <- as.expression(substitute(bold(u),list(u=xu)))
mtext(xu,side=1,padj=1,adj=0.5,las=1,col="black",cex=cexx,line=0.85)
}
yu <- attr(g1$seqy,"units")
if ((isLeft)&&(is.character(yu)))
{
width <- max(strwidth(yo$lab,units="inches",cex=cexy))
height <- max(strheight(yo$lab,units="inches",cex=cexy))
yu <- as.expression(substitute(bold(u),list(u=yu)))
mtext(yu,side=2,padj=0,adj=0.5,las=3,col="black",cex=cexy
,line=0.8+width/height)
}
return(NULL)
}
NULL
}
'.getSide' <- function()
{
figN <- getOption("ursaPngFigure")
figP <- getOption("ursaPngLayout")$image
while (figN<figP) {
panel_new()
figN <- figN+1L
}
panel <- getOption("ursaPngLayout")
if (figN==panel$image) {
.panel_attribution()
if (getOption("ursaPngBox"))
panel_box()
}
figN <- figN+1L
options(ursaPngFigure=figN)
mat <- panel$layout
ind <- which(c(mat)==figN)
indr <- c(row(mat))[ind]
indc <- c(col(mat))[ind]
if (all(indr==1))
side <- 3L
else if (all(indr==nrow(mat)))
side <- 1L
else if (all(indc==ncol(mat)))
side <- 4L
else if (all(indc==1))
side <- 2L
else
stop("cannot identify side")
side
}
'.panel_attribution' <- function(pos=ifelse(vertical,"bottomright","bottomright")
,vertical=TRUE) {
g0 <- getOption("ursaPngPanelGrid") # getOption("ursaSessionGrid_prev")
g1 <- getOption("ursaSessionGrid")
prev <- !identical(g0,g1)
if (prev)
session_grid(g0)
isWindows <- (.Platform$OS.type=="ZZZwindows")&&(getOption("ursaPngDevice")=="ZZZwindows")
if (isWindows) {
wf <- do.call("grDevices::windowsFont",list("TT Arial Narrow"))
do.call("grDevices::windowsFonts",list('Arial Narrow'=wf))
}
ann <- paste0("",paste(unique(getOption("ursaPngCopyright")),collapse=" | "))
# ann <- paste(c(getOption("ursaPngCopyright")),collapse="\n")
if (nchar(ann))
panel_annotation(ann,pos=pos,cex=0.7
,font=ifelse(getOption("ursaPngDevice")=="windows"
,par("family"),"Arial Narrow")
,fg=sprintf("#000000%s","4F"),vertical=vertical
)
if (prev)
session_grid(g1)
options(ursaPngCopyright=NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/yyy.plot.R
|
'.prettyLabel' <- function(x,ncol,min=NULL,max=NULL,onPanel=TRUE)
{
if ((ncol==2L)&&(length(x)==2)) {
y <- pretty(x,n=21)
y <- y[c(1,length(y))]
return(data.frame(at=y,lab=as.character(y),stringsAsFactors=FALSE))
}
saveCriterium <- 0.1
finalY <- NULL
finalLabel <- NULL
saveCriterium <- 0.1
for (pass in 1:2)
{
for (i in 2:(ncol+5))
{
for (s in c(10,12,15,16,20,25,30,40,50,60,70,80,90))
{
y <- s*pretty(x/s,n=i)
if (!onPanel)
{
by <- diff(y[1:2])
y <- c(y[1]-by/2,y+by/2)
}
if (length(y)>ncol)
next
for (i2 in -4:+4)
{
if (all(round((y*10^(i2))%%10,digits=6) %in% 0:10))
break;
}
if (i2<0)
i2 <- 0
# label <- sprintf(sprintf("%%.%df",i2),as.double(y))
# if (length(label)!=length(unique(label)))
# label <- format(y)
label <- format(y)
if (pass==1)
{
if ((!is.null(min))&&(head(y,1)!=min))
next
if ((!is.null(max))&&(tail(y,1)!=max))
next
}
# criterium <- length(y)/(0.1+abs(ratio-0.6))
criterium <- 0L
# criterium <- criterium+diff(x)/(min(x)-min(y)+max(y)-max(x))
criterium <- criterium+2/(1+abs(ncol-length(y)))
criterium <- criterium+1/max(nchar(label))
if ((length(y)>=length(finalY))&&(criterium>saveCriterium))
{
finalY <- y
finalLabel <- label
saveCriterium <- criterium
# print(criterium)
}
}
}
if (!is.null(finalY))
break
}
data.frame(at=finalY,lab=finalLabel)
}
'.deintervale' <- function(value,mix=FALSE,verbose=FALSE) {
if (is.ursa(value))
value <- ursa_colortable(value)
if (.is.colortable(value))
value <- names(value)
opW <- options(warn=-10);on.exit(options(opW))
patt <- "^(\\d{2})\\.(\\d{2})$"
ind <- .grep(patt,value)
if (length(ind)==length(value)) {## date can be interpeted as numeric
b1 <- range(as.integer(gsub(patt,"\\1",value)))
b2 <- range(as.integer(gsub(patt,"\\2",value)))
if ((all(b1 %in% seq(12)))||(all(b2 %in% seq(12))))
return(value)
}
res <- as.numeric(value)
if (!anyNA(res)) {
if (.lgrep("^0\\d.*",value))
return(value)
return(res)
}
dev <- !FALSE
if (!dev)
patt <- "(<=|<|=|>|\\(|\\[|;|,|\\]|\\))" ## <= < = > >= [ ] ( ) ; ,
else
patt <- "(^(<=|<|>|>=).+$|^(\\(|\\[).+(\\]|\\))$)"
# patt <- "^(\\(|\\[).+]$"
found <- sum(grepl(patt,value,perl=TRUE))
# found2 <- grep(patt,value,perl=TRUE)
if (found>0) {
if (dev) {
ivalue <- value
# ivalue <- gsub("^(<=|<|>|>=)","",ivalue) ## OK
# ivalue <- gsub("^(\\(|\\[)","",ivalue)
# ivalue <- gsub("(\\]|\\))$","",ivalue)
ivalue <- gsub("^(<=|<|>|>=)(.+)$","\\2",ivalue)
ivalue <- gsub("^(\\(|\\[)(.+)(\\]|\\))$","\\2",ivalue)
l1 <- length(ivalue)
ivalue <- unlist(strsplit(ivalue,split="[,;]"))
ivalue <- gsub("^\\s+|\\s+$","",ivalue)
}
else {
ivalue <- .gsub(patt," ",value)
l1 <- length(ivalue)
ivalue <- paste(ivalue,collapse=" ")
ivalue <- unlist(strsplit(ivalue,split="\\s+"))
ivalue <- ivalue[nchar(ivalue)>0]
}
if (mix) {
tvalue <- table(ivalue)
tvalue <- tvalue[match(unique(ivalue),names(tvalue))]-1
return(tvalue)
}
invalid <- ((found<l1)||(length(unique(c(table(ivalue))))>1)) ## 20170609 intro
# print(c(invalid=invalid))
ivalue <- unique(ivalue) ## added 20161101
##~ leadingZero <- .grep("^0[1-9]",ivalue)
##~ if(!length(leadingZero))
##~ res <- as.numeric(ivalue)
##~ else
res <- ivalue
if ((anyNA(res))||(invalid)) {
return(value)
}
l2 <- length(ivalue)
}
else {
ivalue <- value
l1 <- l2 <- length(ivalue)
}
leadingZero <- .grep("^0[1-9]",ivalue)
if (!length(leadingZero))
res <- as.numeric(ivalue)
else
res <- ivalue
if (anyNA(res)) {
if (l1==l2)
return(ivalue)
else if (l1==l2+1) ## ++ 20170107
return(ivalue)
else
return(value)
}
ivalue <- res
if (l1==l2)
return(ivalue)
if ((l1-1)*2!=l2)
{
if (is.numeric(ivalue))
ivalue <- ivalue[match(sort(unique(ivalue)),ivalue)]
else
ivalue <- ivalue[match(unique(ivalue),ivalue)]
# message("dev message: is parsing of intervals correct?")
return(ivalue)
}
ivalue <- ivalue[seq(l2)%%2==1]
if ((FALSE)&&(is.character(ivalue))) { ## proposed to introduce
val <- as.integer(format(as.Date(paste0("2012",ivalue),format("%Y%d%b")),"%j"))
if (!anyNA(val))
ivalue <- val
}
ivalue
}
'.prettyNum' <- function(x,ncol=5) {
a <- .prettyLabel(x,ncol)$at
a <- a[which.min(abs(x-a))][1]
a
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/yyy.prettyLabel.R
|
'.project' <- function(xy,proj,inv=FALSE,verbose=FALSE) {
on.exit(NULL)
# verbose <- TRUE; print("ENTERED IN"); on.exit(print("ENTERED OUT"),add=TRUE)
## because of quicker load of 'proj4' package
# show.error.messages=verbose
if (isSF <- .isSF(xy)) {
# return(sf::st_transform(xy,proj))
return(spatial_transform(xy,proj))
}
else if (isSP <- .isSP(xy)) {
# return(sp::spTransform(xy,proj))
return(spatial_transform(xy,proj))
}
# print("---")
# print(class(xy))
# print("===")
opW <- options(warn=-11,show.error.messages=verbose);on.exit(options(opW),add=TRUE)
# if (("package:rgdal" %in% search())||
# (!requireNamespace("proj4",quietly=.isPackageInUse())))
# res <- project(xy=xy,proj=proj,inv=inv) ## project() from 'rgdal'
# else
# res <- proj4::project(xy=t(xy),proj=proj,inverse=inv)
a <- FALSE
# print(summary(xy))
# proj4 <- requireNamespace("proj4",quietly=.isPackageInUse())
# print(loadedNamespaces())
if (F) {
if (.lgrep("^\\s*\\+init=epsg:\\d+\\s*$",proj)) {
# proj <- .epsg2proj4(proj,force=TRUE,verbose=TRUE)
# requireNamespace("rgdal",quietly=.isPackageInUse())
}
}
## CHECK LATER (currently not quick):
# dst <- with(PROJ::proj_trans_generic(src,source="EPSG:4326",target=crs),cbind(x_,y_))
loaded <- loadedNamespaces()
is_proj4 <- (("proj4" %in% loaded)||
(!isTRUE(getOption("ursaForceSF")))&&
(requireNamespace("proj4",quietly=.isPackageInUse()))) ## `proj4` faster `sf`20220216
is_rgdal <- !.isPackageInUse() & "rgdal" %in% loaded
is_sf <- "sf" %in% loaded
if ((!is_sf)&&(!is_rgdal)&&(!is_proj4)) {
is_pro4 <- requireNamespace("proj4",quietly=.isPackageInUse())
if ((!is_proj4)&&(T | .isPackageInUse()))
is_sf <- requireNamespace("sf",quietly=.isPackageInUse())
}
if (verbose)
print(c(proj4=is_proj4,rgdal=is_rgdal,sf=is_sf))
# if ((!FALSE)&&(!("package:rgdal" %in% search()))&&
if ((!a)&&((is_proj4)||
((FALSE)&&(requireNamespace("proj4",quietly=.isPackageInUse()))))) {
if (verbose)
message("'proj4' is used")
if (F) {
dimx <- dim(xy)
if ((dimx==2)&&(dimx[1]==2)) {
str(dimx)
}
}
if (is.list(proj)) {
if ("input" %in% names(proj)) {
proj <- proj$input
}
else {
str(proj)
stop("undefined handling for `proj` specification")
}
}
if ((!is.character(proj))||(.lgrep("\\+init=epsg\\:\\d+",proj))) {
if (verbose)
message(" EPSG->proj4string conversion")
proj <- .epsg2proj4(proj,dismissEPSG=TRUE,verbose=verbose)
}
a <- .try({
# str(xy)
# str(list(xy[,1],xy[,2]))
## suppressMessages(require(proj4)) ## uncomment?
proj4version <- utils::packageVersion("proj4")
if ((proj4version>="1.0.12")&&(!nchar(Sys.getenv("PROJ_LIB")))) {
Sys.setenv(PROJ_LIB=system.file("proj",package="sf"))
if ((!.isPackageInUse())&&(!nchar(Sys.getenv("PROJ_LIB"))))
Sys.setenv(PROJ_LIB=system.file("proj",package="rgdal"))
}
if (proj4version>="1.0.10") {
res <- proj4::project(xy=xy,proj=proj,inverse=inv)
}
else
res <- proj4::project(xy=t(xy),proj=proj,inverse=inv)
# res <- proj4::project(xy=list(xy[,1],xy[,2]),proj=proj,inverse=inv)
},silent=TRUE)
if ((!FALSE)&&(!a)&&(nrow(xy)==2)) {
if (verbose) {
cat(geterrmessage())
message(" trying to not transpose matrix ('proj4')")
}
a <- .try({
## suppressMessages(require(proj4)) ## uncomment?
res <- proj4::project(xy=xy,proj=proj,inverse=inv)
},silent=TRUE)
}
}
if (!a) {
if ((!is_rgdal)&&(!.isPackageInUse())) {
is_rgdal <- .rgdal_requireNamespace()
}
if ((!is_rgdal)&&(!is_sf))
is_sf <- TRUE
}
if ((!a)&&(is_sf)) {
if (verbose)
message("'sf' is used")
if (inv) {
crs_t <- "+proj=longlat +datum=WGS84 +no_defs"
crs_s <- proj
}
else {
crs_s <- "+proj=longlat +datum=WGS84 +no_defs"
crs_t <- proj
}
if (is.list(xy))
xy <- cbind(xy[[1]],xy[[2]])
else if (!is.matrix(xy))
xy <- matrix(xy,ncol=2)
# ind <- which((is.na(xy[,1]))|(is.na(xy[,2])))
hasNA <- anyNA(xy[,1])
tryMatrix <- TRUE
if (omitOutside <- FALSE) {
# if (length(ind180 <- which(xy[,1]>180)))
# xy[ind180,1] <- xy[ind180,1]-180
lim <- c(-18000,10,180000,80)
if (length(ind180 <- which(xy[,1]<=lim[1])))
xy[ind180,1] <- lim[1]
if (length(ind180 <- which(xy[,1]>=lim[3])))
xy[ind180,1] <- lim[3]
if (length(ind180 <- which(xy[,2]<=lim[2])))
xy[ind180,2] <- lim[2]
if (length(ind180 <- which(xy[,2]>=lim[4])))
xy[ind180,4] <- lim[4]
}
if (hasNA) {
ind <- which(is.na(xy[,1])) ## less conditions
res <- matrix(NA,ncol=2,nrow=nrow(xy))
if (!tryMatrix)
a <- .try(res[-ind,] <- unclass(sf::st_transform(sf::st_sfc(
sf::st_multipoint(xy[-ind,]),crs=crs_s),crs_t)[[1]]))
else {
a <- .try(res[-ind,] <- sf::sf_project(from=crs_s,to=crs_t,pts=xy[-ind,]
,keep=TRUE))
}
}
else {
if (!tryMatrix)
a <- .try(res <- unclass(sf::st_transform(sf::st_sfc(
sf::st_multipoint(xy),crs=crs_s),crs_t)[[1]]))
else {
if (T & !sf::sf_proj_network())
try(sf::sf_proj_network(url="",TRUE))
if (F & verbose) {
print(xy)
print(crs_s)
print(crs_t)
print(sf::st_crs(crs_t)$proj4string)
}
a <- .try(res <- sf::sf_project(from=crs_s,to=crs_t,pts=xy
,keep=TRUE))
}
}
}
if (!a) {
if (verbose)
message("'rgdal' is used")
q()
if (.isPackageInUse()) {
opWG <- options(warn=1)
warning("Unable to reproject without `rgdal` package")
options(opWG)
}
if (!("rgdal" %in% loadedNamespaces())) {
.rgdal_requireNamespace()
}
if (!is.character(proj))
proj <- .epsg2proj4(proj)
if (is.list(xy))
xy <- cbind(xy[[1]],xy[[2]])
else if (!is.matrix(xy))
xy <- matrix(xy,ncol=2)
# ind <- which((is.na(xy[,1]))|(is.na(xy[,2])))
ind <- which(is.na(xy[,1])) ## less conditions
if (length(ind)) {
res <- matrix(NA,ncol=2,nrow=nrow(xy))
a <- .try(res[-ind,] <- .rgdal_project(xy=xy[-ind,],proj=proj,inv=inv))
}
else {
a <- .try(res <- .rgdal_project(xy=xy,proj=proj,inv=inv))
}
if (!a) {
if (verbose)
message("patch with backing to 'proj4' via interim projection")
.epsg3411 <- 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")
if (requireNamespace("proj4",quietly=.isPackageInUse())) {
a <- .try(res <- proj4::project(xy=xy,proj=.epsg3411))
if (a) {
a <- .try(res <- proj4::ptransform(res,.epsg3411,proj))
if (a)
return(res)
}
}
}
if ((FALSE)&&(!a)) {
str(xy)
str(proj)
if (inv) {
xy <- as.data.frame(xy)
sp::coordinates(xy) <- ~x+y
sp::proj4string(xy) <- sp::CRS(proj,doCheckCRSArgs=FALSE)
a <- .try(res <- sp::spTransform(xy,sp::CRS("+init=epsg:4326")))
str(a)
q()
}
q()
}
}
if ((FALSE)&&(!inv)&&(.lgrep("\\+proj=merc",g1$crs))) {
g1 <- session_grid()
ext <- 20037508
if (g1$maxx>ext) {
ind <- which(res[,1]<0)
# print("before:")
# print(res)
if (length(ind))
res[ind,1] <- 2*ext+res[ind,1]
# print("after:")
# print(res)
}
}
if (!exists("res"))
return(NULL)
return(res)
}
'.epsg2proj4' <- function(code,force=FALSE,dismissEPSG=FALSE,verbose=FALSE) {
# dismissEPSG: ## dev - FALSE, release and next versions - TRUE
## 'proj4::project' doesnot understand pure EPSG
# a <- try(as.integer(code),silent=TRUE)
if ((is.character(code))&&(!nchar(code)))
return(code)
if (is.matrix(code))
return(NULL)
if (!.lgrep("\\D",code))
p4epsg <- paste0(c("+init=epsg:","EPSG:")[2],code)
else if (.lgrep("^epsg:\\d+",code))
p4epsg <- c(paste0("+init=",code),toupper(code))[2]
else if (.lgrep("^(\\s+)*\\+init=epsg:\\d+",code))
p4epsg <- c(.gsub("^\\s+","",code),.gsub("^\\s+",""
,toupper(.gsub("\\+init=","",code))))[2]
else if ((force)&&(.lgrep("^ESRI\\:",code,ignore.case=FALSE)))
p4epsg <- code
else if (is.character(code))
return(code)
else
stop(code)
loaded <- loadedNamespaces()
if (dismissEPSG)
force <- TRUE
if (!force) {
if ("sf" %in% loaded) {
if (verbose)
message("force to use 'sf'")
p4s <- sf::st_crs(code)$proj4string
}
else {
if (verbose)
message("force to use 'sp/rgdal'")
# requireNamespace(c("sp","rgdal")[2],quietly=.isPackageInUse())
p4s <- p4epsg
}
}
else { ## force
fail <- TRUE
if ((fail)&&("sf" %in% loaded)) {
if (verbose)
message("'sf' loaded")
# p4s <- try(sf::st_crs(as.integer(code))$proj4string) ## 'code', not 'p4epsg'
p4s <- try(sf::st_crs(.p4s2epsg(p4epsg))$proj4string)
if (!inherits(p4s,"try-error"))
fail <- FALSE
}
if ((fail)&&(any(c("sp","rzzgdal") %in% loaded))) {
if (verbose)
message("'sp'/'rgdal' loaded")
if (dismissEPSG) {
opW <- options(warn=ifelse(verbose,0,-1))
p4s <- try(methods::slot(sp::CRS(p4epsg,doCheckCRSArgs=TRUE),"projargs"))
options(opW)
}
else {
##~ p4s <- sp::CRS(p4epsg,doCheckCRSArgs=FALSE)
##~ print(comment(p4s))
##~ p4s <- meslot(p4s,"projargs")
##~ str(p4s)
##~ # sp::CRS(SRS_string=p4epsg)
##~ q()
p4s <- try(methods::slot(sp::CRS(p4epsg,doCheckCRSArgs=TRUE),"projargs")) ## -- 20220124 FALSE
}
if (!inherits(p4s,"try-error")) {
fail <- FALSE
# if (!("rgdal" %in% loaded))
# requireNamespace("rgdal",quietly=.isPackageInUse())
}
}
if ((fail)&&(!FALSE)&&(requireNamespace("sf",quietly=.isPackageInUse()))) {
if (verbose)
message("force to load 'sf'")
p4s <- try(sf::st_crs(code)$proj4string)
if (!inherits(p4s,"try-error"))
fail <- FALSE
}
if (fail) {
if (verbose)
message("Otherwise, use 'sp' + ('rgdal' for reprojection - SKIPPED)")
if (dismissEPSG) {
opW <- options(warn=ifelse(verbose,0,-1))
p4s <- try(methods::slot(sp::CRS(p4epsg,doCheckCRSArgs=TRUE),"projargs"))
options(opW)
}
else {
p4s <- try(methods::slot(sp::CRS(p4epsg,doCheckCRSArgs=TRUE),"projargs")) ## -- 20220124 FALSE
}
if (inherits(p4s,"try-error")) {
fail <- TRUE
# if (!("rgdal" %in% loaded))
# requireNamespace("rgdal",quietly=.isPackageInUse())
}
else
fail <- FALSE
}
if (fail) {
p4s <- ""
if (verbose)
message("Unable to get 'proj4string' from EPSG code")
}
}
p4s
}
'.lonPlus360' <- function(xy) {
if (scalar <- is.null(dim(xy))) {
if (xy[1]<0)
xy[1] <- xy[1]+360
}
else if (length(ind <- which(xy[,1]<0)))
xy[ind,1] <- xy[ind,1]+360
xy
}
'.p4s2epsg' <- function(p4s) {
patt <- "\\+init=epsg\\:(\\d+)$"
if (!length(grep(patt,p4s)))
return(p4s)
code <- gsub(patt,"\\1",p4s)
if (code==p4s)
return(p4s)
as.integer(code)
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/yyy.project.R
|
'.shp.layer' <- function(fname)
{
f <- basename(fname)
if (!.lgrep("\\.shp$",f))
return(f)
.gsub("\\.shp$","",f)
}
'.shp.file' <- function(fname)
{
if (.lgrep("\\.shp$",fname))
return(fname)
paste0(fname,".shp")
}
'.shp.geometry' <- function(fname,verbose=FALSE) {
if (.lgrep("\\.zip$",basename(fname)))
fname <- .gsub("\\.zip$","",fname)
fpath <- dirname(fname)
lname <- .shp.layer(fname)
z <- file.path(fpath,paste0(lname,".zip"))
if (!file.exists(z))
z <- file.path(fpath,paste0(lname,".shp.zip"))
if (file.exists(z))
{
a <- utils::unzip(z,exdir=fpath,junkpaths=TRUE)
on.exit(file.remove(a))
}
info <- system(paste("ogrinfo",.dQuote(fname)),intern=TRUE)
patt <- paste0(".+",lname," \\((.+)\\)")
res <- .gsub(patt,"\\1",.grep(patt,info,value=TRUE))
if (verbose)
names(res) <- fname
res
}
'.shp.remove' <- function(fname) {
if (.lgrep("\\.shp$",fname))
fname <- .gsub("\\.shp$","",fname)
list1 <- .dir(path=dirname(fname)
,pattern=paste0("^",basename(fname),"\\.(cpg|dbf|prj|shp|shx)$")
,full.names=TRUE)
file.remove(list1)
}
'.sf.read' <- function(fname,reproject=TRUE,encoding="1251",verbose=0L,...)
{
## b <- sf::st_read("gde-1-1-15.shp",quiet=TRUE)
## b <- sf::st_transform(b,ursa_proj(a))
# print(fname)
if (!requireNamespace("sf",quietly=.isPackageInUse()))
return(NULL)
if (!file.exists(fname)) {
aname <- paste0(fname,".zip")
if (isZip <- file.exists(aname)) {
ziplist <- unzip(aname);on.exit(file.remove(ziplist))
fname <- .grep("\\.shp$",ziplist,value=TRUE)
}
}
else {
if (isZip <- .lgrep("\\.zip$",fname)>0) {
ziplist <- unzip(fname);on.exit(file.remove(ziplist))
fname <- .grep("\\.shp$",ziplist,value=TRUE)
}
}
if (verbose>1)
.elapsedTime("st_read:start")
res <- sf::st_read(fname,quiet=TRUE)
if (isZip)
cpgname <- .grep("\\.cpg$",ziplist,value=TRUE)
else
cpgname <- .gsub("\\.shp$",".cpg")
if ((length(cpgname))&&(file.exists(cpgname))) {
cpg <- readLines(cpgname,warn=FALSE)
if (cpg=="UTF-8")
cpg <- NULL
}
if (verbose>1)
.elapsedTime("st_read:finish")
proj4 <- session_grid()$crs
if ((reproject)&&(nchar(proj4))&&(!is.na(sf::st_crs(res)))) {
if (verbose>1)
.elapsedTime("st_transform:start")
res <- sf::st_transform(res,proj4)
if (verbose>1)
.elapsedTime("st_transform:finish")
}
res
}
|
/scratch/gouwar.j/cran-all/cranData/ursa/R/yyy.shp.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.