content
stringlengths
0
14.9M
filename
stringlengths
44
136
if(getRversion() >= "2.15.1") utils::globalVariables(c("lc.1")) #' Tabulates vegetation tables from Turboveg database #' @name tv.veg #' @aliases tv.veg #' #' @description Tabulates vegetation tables from Turboveg resp. VegetWeb database, including taxonomic emendation and layer combination. Using various default parameters for the included functions. #' It is a wrapper for *tv.obs*, *taxval*, *tv.coverperc* and creating a vegetation matrix #' #' @export #' @param db Name of your Turboveg database. Directory name containing tvabund.dbf, tvhabita.dbf and tvwin.set. Please specify pathnames below (if you sorted your databases in subfolders) but not above Turbowin/Data. #' @param tv_home Turbowin installation path. #' @param taxval Should taxonomic valuation (see \code{\link{taxval}}) be performed? #' @param convcode Should cover code be converted to percentage values? #' @param lc Layer combination type. Possible values: layer (default), sum, mean or max, see details #' @param pseudo List used for layer combinations, see details #' @param values Name of the variable which should be used for the vegetations matrix. #' @param spcnames Should species numbers be replaced by shortletters or ScientificNames? Layer information is appended with dot. #' @param dec Number of decimals for cover values in the resulting vegetation matrix. #' @param cover.transform If you want to transform the abundancce values within your samples #' you can choose 'pa' for presence-absence or 'sqrt' for the \code{dec} rounded square root. #' @param obs Observations, optional #' @param site plot header data, see \code{\link{tv.site}} #' @param refl Taxonomic reference list, optional #' @param RelScale Vector with Cover Scale code per Releve. #' @param ... additional arguments for included functions #' #' @usage tv.veg(db, taxval=TRUE,tv_home,convcode=TRUE, #' lc = c("layer","mean","max","sum","first"), #' pseudo, values='COVER_PERC', spcnames=c('shortletters','ScientificNames','Numbers'), #' dec = 0, cover.transform = c('no', 'pa', 'sqrt'), obs, site, refl, RelScale, ...) #' #' @details \code{layer} means, the different layers are combined assuming there independence (a species occurring in two layers with a cover of 50\% will result in a overall cover of 75\%. \code{sum} will sum up cover values of all layers With option \code{pseudo} you can decide, which layers should be combined. Give a list with a combination data.frame and second the name of the column for combination. The default is \code{pseudo = list(lc.1, c('LAYER'))}, where lc.1 is a data.frame \code{data(lc.1)}, which will combine all tree layers, all shrub layers and all layers below shrubs. An alternative would be data(lc.all), combining all layers. With option pseudo=NULL there will be no layer aggregation. #' #' @return an object of class matrix with (combined) cover values. #' #' @seealso{ #' \code{\link{taxval}}, \code{\link{tv.coverperc}}, \code{\link{tv.obs}}, \code{\link{tv.site}} #' } #' #' @examples #' \dontrun{ #' vignette("vegdata") #' #' If you have Turboveg installed on your computer try for a beginning #' #' tv.veg('databasename', tax=FALSE). #' args(tv.veg) #' help('taxval') #' #' veg <- tv.veg('taxatest') #' names(veg) #' tv.veg('taxatest', uncertain=list('DET_CERT', data.frame(0:2,c('pres','agg','agg'))), #' pseudo=list(lc.0,'LAYER'), genus = 'delete') #' } #' #' @author Florian Jansen \email{[email protected]} #' #' @keywords misc manip #' tv.veg <- function (db, taxval = TRUE, tv_home, convcode = TRUE, lc = c("layer","mean","max","sum","first"), pseudo, values = "COVER_PERC", spcnames = c('shortletters','ScientificNames','Numbers'), dec = 0, cover.transform = c('no', 'pa', 'sqrt'), obs, site, refl, RelScale, ...) { options(warn=1) ## Checks lc <- toupper(match.arg(lc)) cover.transform <- match.arg(cover.transform) spcnames = match.arg(spcnames) if(missing(tv_home)) tv_home <- tv.home() if(missing(obs)) { cat('Reading tvabund.dbf\n') obs <- tv.obs(db, tv_home) } else names(obs) <- TCS.replace(names(obs)) # if(suppressWarnings(any(obs < -1e+05, na.rm = TRUE))) # cat("\n WARNING! Values less than -100,000. \n WARNING! tvabund.dbf may be corrupt. \n WARNING! Please correct by reexporting e.g. with OpenOffice.") lc.1 <- data.frame(LAYER=0:9, COMB=c(0,rep('Tree',3),rep('Shrub',2),rep(0,4))) # data("lc.1", package = 'vegdata', envir = 'vegdata') if(missing(pseudo)) pseudo <- list(lc.1, 'LAYER') ## Taxa if(missing(refl)) refl <- tv.refl(db = db[1], tv_home = tv_home) cat('Taxonomic reference list: ', refl, '\n') if(taxval) { obs <- taxval(obs=obs, refl = refl, ...) } ## CoverCode if(missing(site)) { cat('Reading tvhabita.dbf\n') site <- tv.site(db, tv_home, verbose = FALSE) } if(convcode){ cat('converting cover code ... \n') if(missing(RelScale)) { if(missing(db)) stop('\nEither database name or a vector with CoverScale per releve has to be permitted, to cope with Cover Scale information\n') RelScale <- site[, c("PlotObservationID", "COVERSCALE")] } obs <- tv.coverperc(db=db, obs=obs, RelScale = RelScale, tv_home = tv_home, ...) } else { if (!any(names(obs) == values)) stop(paste(values, " could not be found.")) obs[,values] <- type.convert(as.character(obs[,values], as.is = TRUE)) if(is.factor(obs[,values])) { lc='first' warning("Multiple occurrences of a species in one layer of a releve can not be supported without cover code conversion. Only the first occurrence will be used!")} } ## empty plots noobs <- site$PlotObservationID[!site$PlotObservationID %in% obs$PlotObservationID] if(length(noobs) > 0) for(i in 1:length(noobs)) { obs[(nrow(obs)+1), ] <- NA obs$PlotObservationID[nrow(obs)] <- noobs[i]; obs$TaxonUsageID[nrow(obs)] <- 0; obs$LAYER[nrow(obs)] <- 0 } ## Pseudo-Species / Layer # print('Pseudo species') if(!is.null(pseudo)) { cat('creating pseudo-species ... \n') if(length(pseudo[[2]]) > 1) stop('Possibility to differentiate more than one plot-species attribute not yet implemented. \n Please contact <[email protected]>.') obs$COMB <- pseudo[[1]][, 2][match(obs[, pseudo[[2]]], pseudo[[1]][,1])] collab <- paste(obs$TaxonUsageID, obs$COMB, sep = ".") } else collab <- as.vector(obs$TaxonUsageID) rowlab <- as.vector(obs$PlotObservationID) cat('combining occurrences using type', toupper(lc), 'and creating vegetation matrix ... \n') gc(TRUE, verbose = FALSE) layerfun <- function(x) round((1 - prod(1 - x/100)) * 100, dec) # print('Inflate') results <- switch(lc, # Inflate matrix LAYER = tapply(obs[, values], list(rowlab, collab), layerfun), MEAN = tapply(obs[, values], list(rowlab, collab), mean), MAX = tapply(obs[, values], list(rowlab, collab), max), SUM = tapply(obs[, values], list(rowlab, collab), sum), FIRST = tapply(obs[, values], list(rowlab, collab), stringr::word) ) results[is.na(results)] <- 0 results <- as.data.frame(results) colnames(results) ## Names # print('names') if(spcnames %in% c('shortletters','ScientificNames')) { cat('replacing species numbers with ', spcnames, ' names ... \n') if(is.null(pseudo)) { species <- tax(as.numeric(colnames(results)), detailed=TRUE, syn=FALSE, refl = refl, tv_home=tv_home) if(spcnames=='shortletters') colnames(results) <- species$LETTERCODE[match(colnames(results), species$TaxonUsageID)] if(spcnames=='ScientificNames') colnames(results) <- gsub(' ','_', species$TaxonName[match(colnames(results), species$TaxonUsageID)] ) } else { st <- unlist(strsplit(colnames(results), ".", fixed = TRUE)) colspc <- st[seq(1, length(st), 2)] species <- tax(as.numeric(colspc), detailed=FALSE, refl = refl, tv_home=tv_home) if(spcnames=='shortletters') coln <- as.character(species$LETTERCODE[match(as.numeric(colspc), species$TaxonUsageID)]) if(spcnames=='ScientificNames') coln <- gsub(' ','_', species$TaxonName[match(as.numeric(colspc), species$TaxonUsageID)]) ll <- st[seq(2, length(st), 2)] cn <- replace(coln, which(ll != '0'), paste(coln, ll, sep = ".")[ll != '0']) colnames(results) <- cn } } if (any(is.na(colnames(results)))) warning("Some taxa without names, check reference list!") # rownames(results) <- unique(rowlab) ## Result # results <- results[, order(names(results))] if(cover.transform!='no') { if(cover.transform == 'pa') results <- as.data.frame(ifelse(results > 0, 1,0)) if(cover.transform == 'sqrt') results <- as.data.frame(round(sqrt(results),dec)) } results <- results[, colSums(results)> 0] class(results) <- c("veg", "data.frame") attr(results, 'taxreflist') <- refl return(results) }
/scratch/gouwar.j/cran-all/cranData/vegdata/R/tv.veg.r
#' Write species-plot observations and site information to Turboveg database. #' #' @name tv.write #' @description Write species-plot observations and site information to Turboveg database. #' #' @usage tv.write(x, site, name, tvadmin, remarks, dict = "", cover = c("code", "perc"), #' drop = FALSE, obl = TRUE, overwrite = FALSE, ...) #' #' @export #' @param x (data.frame) Either observations data.frame with RELEVE_NR, TaxonUsageID and COVER_CODE (see \link{tv.obs}) columns or vegetation matrix of class "veg". #' @param site (character) Header data for plots. #' @param name (character) Name of the new database. #' @param tvadmin (data.frame) Dataframe with plot UUID's and Turboveg columns from TvAdmin.dbf. A new file with new unique identifiers will be created if omitted. #' @param remarks (data.frame) Remarks in Turboveg format if the comments for individual plots exceed 254 characters. See remarks.dbf in Turboveg databases. An empty file will be created if omitted. #' @param dict (character) Turboveg dictionary name #' @param cover (logical) Use of covercodes or (mean) cover percentages, see Details. #' @param drop (logical) Drop columns which are empty or contain only NA values. #' @param obl (logical) Add obligatory fields defined in the TV dictionary but not present in the site data table. #' @param overwrite (logical) Should an existing database be overwritten. #' @param \dots additional arguments #' #' @details By default Covercode is written to Turboveg. This is only meaningful, if correct CoverScales are given in the site dataframe. Unique plot ID's are stored in *TvAdmin.dbf*. If you want to preserve already given UUID's you have to prepare an appropriate data.frame. Look for existing *TvAdmin.dbf* files for necessary columns. #' #' @return Five files will be created in "tv_home/Data/databasename" directory. *tvabund.dbf* with occurrence information n long format, *tvhabita.dbf* with plot information, remarks.dbf with comments longer then 255 characters, *TvAdmin.dbf* with plot UUID's and tvwin.dbf with information about taxonomic reference list, and dictionary used. #' #' @seealso tv.veg #' #' @author Florian Jansen @email [email protected] #' #' @keywords Turboveg if(getRversion() >= "2.15.1") utils::globalVariables(c("DoWritedbf")) tv.write <- function(x, site, name, tvadmin, remarks, dict = '', cover=c('code','perc'), drop = FALSE, obl = TRUE, overwrite = FALSE, ...) { cover <- match.arg(cover) if('veg' %in% class(x)) { X <- reShape.veg(x, ...) if(cover == 'perc') { X$COVER_CODE <- as.character(X$COVER_PERC) site$COVERSCALE <- '00' X <- X[,c('PlotObservationID','TaxonUsageID', 'COVER_CODE', 'LAYER')] } } else { if(!any(c('tv.obs','vw.obs') %in% class(x))) warning('Species observations should be either of class \"tv.obs\" or \"vw.obs\".') if(!all(c('PlotObservationID') %in% names(x))) stop('table of species observations must contain a column called PlotObservationID') X <- x binrel <- unique(X$PlotObservationID[na.omit(as.numeric(X$"COVER_CODE") > 100)]) if(length(binrel) > 0) X$"COVER_CODE"[X$PlotObservationID == binrel] <- word2bin(as.numeric(X$"COVER_CODE"[X$PlotObservationID == binrel])) X$"COVER_CODE"[X$"COVER_CODE" == '100'] <- '9X' names(X) <- TV.replace(names(X)) } refl <- if(!is.null(attr(X, "taxreflist"))) attr(X, "taxreflist") else tv.refl() if(drop) { # Delete empty columns #### na <- apply(site, 2, function(x) all(is.na(x) | x == '')) if (any(na)) site <- as.data.frame(site[, !na]) leer <- apply(site, 2, function(x) all(x == 0 | is.na(x))) if (any(leer)) site <- as.data.frame(site[, !leer]) } for(i in names(site)) if(is.character(site[,i])) { site[is.na(site[,i]),i] <- '' site[,i] <- iconv(site[,i], '', getOption('tv.iconv')) } if(obl) { ### Add obligatory fields from dictionary #### dbasedic <- read.dbf(file.path(tv.home(), 'Popup', dict, 'dbasedic.dbf'), as.is=TRUE) oblig <- dbasedic[dbasedic$FILE_NR == 2, 'FIELD_NAME'] oblig <- TCS.replace(oblig) for(m in oblig[!oblig %in% names(site)]) site[,m] <- '' site <- site[, match(unique(c(oblig, names(site))), names(site))] # order columns } if(!overwrite) if(file.exists(file.path(options('tv_home'), 'Data', name, 'tvhabita.dbf'))) stop('Database ', name, ' already exists. Nothing will be exported.') site$DATE <- gsub('-','', site$DATE) ### Write Turboveg tvhabita and tvabund #### dir.create(file.path(options('tv_home'), 'Data', name), showWarnings = if(overwrite) FALSE else TRUE) write.dbf(X, max_nchar = 250, file.path(options('tv_home'), 'Data', name, 'tvabund.dbf')) # write TvAdmin #### if(missing(tvadmin)) { tvadmin <- data.frame(PlotObservationID=site$PlotObservationID, SOURCE_DB='R', GUID=replicate(nrow(site), paste('{', uuid::UUIDgenerate(), '}', sep='')), CREAT_USER=Sys.getenv('USER'), CREAT_DATE=Sys.Date(), MOD_USER=Sys.getenv('USER'), MOD_DATE=Sys.Date(), NDFF_QUAL=as.integer(0)) } else if(is.character(tvadmin)) tvadmin <- read.dbf(file.path(options('tv_home'), 'Data', tvadmin, 'TvAdmin.dbf'), as.is=TRUE) TvAdmin <- tvadmin TvAdmin <- TvAdmin[TvAdmin$PlotObservationID %in% site$PlotObservationID,] TvAdmin$MOD_USER[is.na(TvAdmin$MOD_USER)] <- Sys.getenv('USER') TvAdmin$MOD_DATE[is.na(TvAdmin$MOD_DATE)] <- format(Sys.Date()) names(TvAdmin) <- TV.replace(names(TvAdmin)) write.dbf(TvAdmin, max_nchar = 250, file.path(options('tv_home'), 'Data', name, 'TvAdmin.dbf')) # write Remarks #### if(missing(remarks)) remarks <- data.frame(PlotObservationID=numeric(), REMARKS=character()) else if(nrow(remarks) > 0) remarks <- remarks[remarks$PlotObservationID %in% site$PlotObservationID,] names(remarks) <- TV.replace(names(remarks)) suppressWarnings( write.dbf(remarks, max_nchar = 250, file.path(options('tv_home'), 'Data', name, 'remarks.dbf')) ) options(warn=-1) # write tvwin.dbf #### write.dbf(data.frame(FLORA=refl, MINALLOW=0, MAXALLOW=0, MINACTUAL= min(site$PlotObservationID), MAXACTUAL=max(site$PlotObservationID), MAP='', DICTIONARY=dict, META=''), max_nchar = 250, file = file.path(options('tv_home'),'Data', name, 'tvwin.dbf')) # write tvhabita.dbf names(site) <- TV.replace(names(site)) write.dbf(site, max_nchar = 250, file.path(options('tv_home'), 'Data', name, 'tvhabita.dbf')) cat('Turboveg database', name, 'written to', file.path(options('tv_home'), 'Data', name),'\n') }
/scratch/gouwar.j/cran-all/cranData/vegdata/R/tv.write.R
#' Internal vegdata functions #' @name vegdata-internal #' @aliases reShape.veg bin2word word2bin #' @noRd #' @description Internal vegdata functions. #' @details These are not intended to be called directly by the user. #' tv.home tries to guess the default tv_home directory (\code{'C:\Turbowin'} or \code{'C:\Programme\Turbowin'} or \code{'O:\Turbowin'} on Windows systems and \code{'~/.wine/drive_c/Turbowin'} on Unix systems. #' As dBase is an old DOS format, Umlaute have been stored in Turboveg using the CP437 code table. Change options('tv.iconv') if you run into problems #' @keywords internal # gracefully_fail <- function(remote_file) { # try_GET <- function(x, ...) { # tryCatch( # GET(url = x, timeout(1), ...), # error = function(e) conditionMessage(e), # warning = function(w) conditionMessage(w) # ) # } # is_response <- function(x) { # class(x) == "response" # } # # First check internet connection # if (!curl::has_internet()) { # message("No internet connection.") # return(invisible(NULL)) # } # # Then try for timeout problems # resp <- try_GET(remote_file) # if (!is_response(resp)) { # message(resp) # return(invisible(NULL)) # } # # Then stop if status > 400 # if (httr::http_error(resp)) { # message_for_status(resp) # return(invisible(NULL)) # } # # # # If you are using rvest as I do you can easily read_html in the response # # xml2::read_html(resp) # } # gracefully_fail("http://httpbin.org/status/404") # http >400 # #> Not Found (HTTP 404). # gracefully_fail("http://httpbin.org/delay/2") # Timeout # #> Timeout was reached: [httpbin.org] Operation timed out after 1000 milliseconds with 0 bytes received # gracefully_fail("http://httpbin.org") #OK # #> {html_document} # #> <html lang="en"> # #> [1] <head>\n<meta http-equiv="Content-Type" content="text/html; charset=UTF-8 ... # #> [2] <body>\n <a href="https://github.com/requests/httpbin" class="github-c ... # gracefully_fail("http://httpbin.org") #OK # # remote <- "https://germansl.infinitenature.org/GermanSL/1.5/GermanSL.zip" # remote2 <- "https://german.infinitenature.org/GermanSL/1.5/GermanSL.zip" # remote3 <- "https://germansl.infinitenature.org/GermanSL/1.6/GermanSL.zip" # # # gracefully_fail(remote) #OK # # status <- tryCatch( # RCurl::getURL(url, ssl.verifypeer=FALSE, useragent="R"), # error = function(e) e # ) # # inherits(status, "error") # # # f <- function(url) { # if (!curl::has_internet()) { # message("No internet connection") # return(NULL) # } # if (httr::http_error(url)) { # message("Data source broken.") # return(NULL) # } # url(remote2) # if(as.integer(tmp) == 5) # tryCatch(http_error(GET(url)), # http_404 = function(c) "That url doesn't exist", # http_403 = function(c) "You need to authenticate!", # http_400 = function(c) "You made a mistake!", # http_500 = function(c) "The server screwed up" # ) # } # f(remote2) asc <- function(char) sapply(char, function(x) strtoi(charToRaw(x), 16L), simplify = TRUE, USE.NAMES = FALSE) chr <- function(ascii) sapply(ascii, function(x) rawToChar(as.raw(x)), USE.NAMES = FALSE) bin2word <- function(x) { c1 <- substr(x, 1,1) c2 <- substr(x, 2,2) return(255 * (asc(c1) -1) + asc(c2) - 1) } word2bin <- function(x) { c1 <- floor(x/255+1) c2 <- x - (c1-1)*255 paste (chr(c1), chr(c2 + 1), sep='') } #' @noRd "[.veg" <- function(x, s,...) { taxref <- attr(veg, 'taxreflist') out <- NextMethod("[,", drop=TRUE) class(out) <- c('veg', 'data.frame') attr(veg, 'taxreflist') <- taxref return(out) } # # first.word <- function (x, i = 1, expr = substitute(x), add.legal=NULL) { # words <- if(!missing(x)) as.character(x)[1] else as.character(unlist(expr))[1] # if (i > 2) stop("only first and second word implemented") # chars <- substring(words, 1:nchar(words, keepNA = FALSE), 1:nchar(words, keepNA = FALSE)) # legal.chars <- c(letters, LETTERS, '\u00fc','\u00e4','\u00f6','\u00df','\u00d7', "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", add.legal) # non.legal.chars <- (1:length(chars))[!chars %in% legal.chars] # # length(non.legal.chars) > 0 # if (i==1 & is.na(non.legal.chars[1])) return(words) # if (i==1 & !is.na(non.legal.chars[1])) return(substring(words, 1, non.legal.chars[1] - 1)) # if (i==2 & is.na(non.legal.chars[2])) return(substring(words, non.legal.chars[1], nchar(words, keepNA = FALSE))) # if (i==2 & !is.na(non.legal.chars[2])) return(substring(words, non.legal.chars[1]+1, non.legal.chars[2]-1)) else return(character(0)) # } # # word <- function (string, start = 1L, end = start, sep = fixed(" ")) { # n <- max(length(string), length(start), length(end)) # string <- rep(string, length.out = n) # start <- rep(start, length.out = n) # end <- rep(end, length.out = n) # breaks <- str_locate_all(string, sep) # words <- lapply(breaks, invert_match) # len <- vapply(words, nrow, integer(1)) # neg_start <- !is.na(start) & start < 0L # start[neg_start] <- start[neg_start] + len[neg_start] + 1L # neg_end <- !is.na(end) & end < 0L # end[neg_end] <- end[neg_end] + len[neg_end] + 1L # start[start > len] <- NA # end[end > len] <- NA # starts <- mapply(function(word, loc) word[loc, "start"], words, start) # ends <- mapply(function(word, loc) word[loc, "end"], words, end) # str_sub(string, starts, ends) # } # x <- c('Tortula acaulon (With.) R. H.Zander var. acaulon', 'Phascum cuspidatum Hedw. v. cuspidatum', 'Tortula acaulon var. papillosa (Lindb.) R. H. Zander', 'Phascum cuspidatum subsp. papillosum (Lindb.) J. Guerra & Ros', 'Tortula SP.') # @noRd # rbind.df <- function(df1, df2) { # cols1 <- names(df1); cols2 <- names(df2) # All <- union(cols1, cols2) # miss1 <- setdiff(All, cols1) # miss2 <- setdiff(All, cols2) # df1[, c(as.character(miss1))] <- NA # df2[,c(as.character(miss2))] <- NA # out <- rbind(df1, df2) # return(out) # } # @noRd # cbind.df <- function(df1, df2, by) { # cols1 <- names(df1); cols2 <- names(df2) # inters <- intersect(cols1, cols2) # df.m <- df2[match(df1[,by], df2[,by]), ] # for(i in inters) { # df1[,i][is.na(df1[,i])] <- df.m[,i][is.na(df1[,i])] # } # return(df1) # } # as.data.frame.list # Convert a list of vectors to a data frame. # @noRd # as.data.frame.list <- function(x, row.names=NULL, optional=FALSE, ...) { # if(!all(unlist(lapply(x, class)) %in% # c('raw','character','complex','numeric','integer','logical'))) { # warning('All elements of the list must be a vector.') # NextMethod(x, row.names=row.names, optional=optional, ...) # } # allequal <- all(unlist(lapply(x, length)) == length(x[[1]])) # havenames <- all(unlist(lapply(x, FUN=function(x) !is.null(names(x))))) # if(havenames) { #All the vectors in the list have names we can use # colnames <- unique(unlist(lapply(x, names))) # df <- data.frame(matrix( # unlist(lapply(x, FUN=function(x) { x[colnames] })), # nrow=length(x), byrow=TRUE), stringsAsFactors = FALSE) # names(df) <- colnames # } else if(allequal) { #No names, but are of the same length # df <- data.frame(matrix(unlist(x), nrow=length(x), byrow=TRUE), stringsAsFactors = FALSE, ...) # hasnames <- which(unlist(lapply(x, FUN=function(x) !is.null(names(x))))) # if(length(hasnames) > 0) { #We'll use the first element that has names # names(df) <- names(x[[ hasnames[1] ]]) # } # } else { #No names and different lengths, we'll make our best guess here! # warning(paste("The length of vectors are not the same and do not ", # "are not named, the results may not be correct.", sep='')) # #Find the largest # lsizes <- unlist(lapply(x, length)) # start <- which(lsizes == max(lsizes))[1] # df <- x[[start]] # for(i in (1:length(x))[-start]) { # y <- x[[i]] # if(length(y) < length(x[[start]])) { # y <- c(y, rep(NA, length(x[[start]]) - length(y))) # } # if(i < start) { # df <- rbind(y, df) # } else { # df <- rbind(df, y) # } # } # df <- as.data.frame(df, row.names=1:length(x)) # names(df) <- paste('Col', 1:ncol(df), sep='') # } # if(missing(row.names)) { # row.names(df) <- names(x) # } else { # row.names(df) <- row.names # } # return(df) # } #
/scratch/gouwar.j/cran-all/cranData/vegdata/R/vegdata-internal.r
#' Functions to access data from vegetation databases and evaluate taxon names #' @keywords package "_PACKAGE" #' @aliases vegdata #' @encoding UTF-8 #' #' @references #' Jansen, F., Dengler, J (2011) Plant names in vegetation databases - a neglected source of bias, Journal of vegetation science, 21(6), 1179-1186. http://dx.doi.org/10.1111/j.1654-1103.2010.01209.x #' Jansen, Florian and Dengler, Juergen (2008) GermanSL - eine universelle taxonomische Referenzliste fuer Vegetationsdatenbanken, Tuexenia, 28, 239-253. #' #' @description This package provides a set of functions to load data from vegetation databases (at present Turboveg and vegetweb.de). Taxa can be (semi-)automatically be checked and adapted depending the scientific question. For this a hierachical taxonomic reference list is needed. Use [tv.veg()] to prepare data directly for further analyses. Set option \code{taxval} to \code{TRUE}, if your database is referenced with GermanSL or equivalent taxonomic reference list and you want to realize taxonomic checks and adaptations. For more details see \code{vignette('vegdata')}. #' #' @importFrom DBI dbConnect dbDisconnect #' @importFrom RSQLite SQLite #' @importFrom curl curl_download #' @importFrom magrittr %>% #' @importFrom foreign read.dbf #' @importFrom xml2 read_xml xml_find_all xml_attr xml_attrs xml_length xml_children #' @importFrom utils find read.csv download.file head tail type.convert unzip read.csv2 write.csv2 #' @importFrom plyr ldply #' @importFrom stats na.omit NULL
/scratch/gouwar.j/cran-all/cranData/vegdata/R/vegdata-package.R
#' #' .onAttach <- function(lib, pkg) { packageStartupMessage("This is vegdata ", utils::packageDescription("vegdata", field="Version"), paste(' - build: '), utils::packageDate('vegdata'), appendLF = TRUE) if(is.null(getOption('tv.iconv'))) options(tv.iconv = 'ISO-8859-15') } mssg <- function(v, ...) if (v) message(...) assert <- function(x, y) { if (!is.null(x)) { if (!inherits(x, y)) { stop(deparse(substitute(x)), " must be of class ", paste0(y, collapse = ", "), call. = FALSE) } } }
/scratch/gouwar.j/cran-all/cranData/vegdata/R/zzz.R
## ----prep, echo=FALSE, results='hide'----------------------------------------- library(knitr) options(stringsAsFactors=FALSE) opts_chunk$set(concordance = TRUE, comment = "", warning = FALSE, message = TRUE, echo = TRUE, results = 'tex', size="footnotesize") tmp <- tempdir(check = T) suppressPackageStartupMessages(library(vegdata)) options(tv_home = tmp) dir.create(file.path(tmp, 'Species')) dir.create(file.path(tmp, 'Popup')) dir.create(file.path(tmp, 'Data')) file.copy(from = file.path(path.package("vegdata"), 'tvdata', 'Popup'), to = tmp, recursive = TRUE) file.copy(from = file.path(path.package("vegdata"), 'tvdata', 'Species'), to = tmp, recursive = TRUE) file.copy(from = file.path(path.package("vegdata"), 'tvdata', 'Data'), to = tmp, recursive = TRUE) # dim(tax('all')) ## ----load, results='hide'----------------------------------------------------- library(vegdata) ## ----eval=FALSE--------------------------------------------------------------- # tv_home <- tv.home() ## ----eval=FALSE--------------------------------------------------------------- # options(tv_home="path_to_your_Turboveg_root_directory") # options(tv_home="/home/jansen/aGitRepos/vegdata/vegdata/inst/tvdata/") ## ----dblisting---------------------------------------------------------------- tv.db() ## ----------------------------------------------------------------------------- tv.refl() ## ----eval=FALSE--------------------------------------------------------------- # tv.refl('your_preferred_list') ## ----tax, eval =TRUE---------------------------------------------------------- tax('Quercus robur') ## ----syn---------------------------------------------------------------------- tax('Elytrigia repens')$TaxonName syn('Elytrigia repens') ## ----childs, eval=FALSE------------------------------------------------------- # child(27, quiet=TRUE)$TaxonName # parent(32) # parent(32, rank = 'FAM') ## ----db----------------------------------------------------------------------- db <- 'taxatest' ## ----meta, eval=FALSE--------------------------------------------------------- # tv.metadata(db) ## ----obs---------------------------------------------------------------------- getOption('tv_home') obs <- tv.obs(db) # Adding species names species <- tax('all', refl=tv.refl(db=db)) obs$TaxonName <- species$TaxonName[match(obs$TaxonUsageID, species$TaxonUsageID)] head(obs[,c('PlotObservationID','TaxonUsageID','COVER_CODE','LAYER','TaxonName')]) ## ----data--------------------------------------------------------------------- library(vegdata) obs <- tv.obs('taxatest') sort(tax(unique(obs$TaxonUsageID))$TaxonName) ## ----adapt-------------------------------------------------------------------- obs.tax <- taxval(obs, db='taxatest', ag='adapt', rank='SPE', check.critical = FALSE, taxlevels = taxlevels, mono = 'pre') sort(tax(unique(obs.tax$TaxonUsageID), db=db)$TaxonName) ## ----conflict----------------------------------------------------------------- obs.tax <- taxval(obs, db='taxatest', ag='conflict', check.critical = FALSE) sort(tax(unique(obs.tax$TaxonUsageID), db=db)$TaxonName) ## ----maxtax, eval=FALSE------------------------------------------------------- # obs.tax <- taxval(obs, db='taxatest', ag='conflict', maxtaxlevel = 'AGG', check.critical = FALSE, interactive = TRUE) # obs.tax <- taxval(obs.tax, db='taxatest', ag='adapt', rank='SPE', check.critical = FALSE) # sort(tax(unique(obs.tax$TaxonUsageID), db=db)$TaxonName) ## ----coverperc, echo=2:4, eval=TRUE------------------------------------------------------------------------- options(width=120) obs <- tv.obs(db) # obs <- tv.coverperc(db, obs) tail(obs) options(width=110) ## ----pseudo1, eval=FALSE------------------------------------------------------------------------------------ # data(lc.0) # obs <- tv.obs(db) # tv.veg(db, pseudo = list(lc.0, c("LAYER")), lc = "layer") ## ----lc0, warning=FALSE------------------------------------------------------------------------------------- tmp <- tv.veg(db, tax=FALSE, pseudo = list(lc.0, "LAYER"), lc = "layer", quiet=TRUE) names(tmp) ## ----Season------------------------------------------------------------------------------------------------- comb <- list(data.frame(SEASON=0:4, COMB=c(0,'Spring','Summer','Autumn','Winter')),'SEASON') names(tv.veg(db, tax=FALSE, pseudo=comb, quiet=TRUE)) ## ----layer, results='hide', warning=FALSE------------------------------------------------------------------- data(lc.1) veg <- tv.veg(db, lc = "sum", pseudo = list(lc.1, 'LAYER'), dec = 1, check.critical = FALSE) veg[,1:10] ## ----------------------------------------------------------------------------------------------------------- obs.tax$TaxonUsageID[obs.tax$TaxonUsageID == 27] <- 31 ## ----replace------------------------------------------------------------------------------------------------ taxon.repl <- data.frame(old=c(27), new=c(31)) obs.tax$TaxonUsageID <- replace(obs.tax$TaxonUsageID, match(taxon.repl$old, obs.tax$TaxonUsageID), taxon.repl$new) ## ----comb.spec, eval=FALSE---------------------------------------------------------------------------------- # comb.species(veg, sel=c('QUERROB','QUERROB.Tree')) ## ----site.echo, eval=TRUE----------------------------------------------------------------------------------- site <- tv.site(db) ## ----elbaue, results='hide'--------------------------------------------------------------------------------- elbaue <- tv.veg('elbaue', check.critical = FALSE) elbaue.env <- tv.site('elbaue') ## ----cluster------------------------------------------------------------------------------------------------ clust <- vector('integer', nrow(elbaue.env)) clust[elbaue.env$MGL < -50 & elbaue.env$SDGL < 50] <- 1 # dry sites, low deviation clust[elbaue.env$MGL < -50 & elbaue.env$SDGL >= 50] <- 2 # dry sites, high deviation clust[elbaue.env$MGL >= -50 & elbaue.env$SDGL >= 50] <- 3 # wet sites, high deviation clust[elbaue.env$MGL >= -50 & elbaue.env$SDGL < 50] <- 4 # wet sites, low deviation #levels(clust) <- c('dry.ld','dry.hd', 'wet.hd','wet.ld') ## ----syntab.mupa-------------------------------------------------------------------------------------------- synt <- syntab(elbaue, clust, mupa = TRUE) ## ----nmds, quiet=TRUE, results='hide'----------------------------------------------------------------------- ## Data analyses if (requireNamespace('vegan', quietly = TRUE) ) { library(vegan) veg.nmds <- metaMDS(elbaue, distance = "bray", trymax = 5, autotransform =FALSE, noshare = 1, expand = TRUE, trace = 2) # eco <- tv.traits() F <- cwm(veg = elbaue, trait.db = 'ecodbase.dbf', ivname = 'OEK_F', method = 'mean') N <- cwm(veg = elbaue, trait.db = 'ecodbase.dbf', ivname = 'OEK_N', method = 'mean') env <- envfit(veg.nmds, env = data.frame(F, N)) } else message("package vegan not available") ## ----nmdsplot, quiet=TRUE, results='hide', warning=FALSE, eval=TRUE----------------------------------------- if (requireNamespace('interp', quietly = TRUE) & requireNamespace('labdsv', quietly = TRUE) & requireNamespace('vegan', quietly = TRUE) ) { suppressPackageStartupMessages(library(labdsv)) library(interp) color = function(x)rev(topo.colors(x)) nmds.plot <- function(ordi, site, var1, var2, disp, plottitle = 'NMDS', env = NULL, ...) { lplot <- nrow(ordi$points); lspc <- nrow(ordi$species) filled.contour(interp(ordi$points[, 1], ordi$points[, 2], site[, var1], duplicate = 'strip'), ylim = c(-1, 1.1), xlim = c(-1.4, 1.4), color.palette = color, xlab = var1, ylab = var2, main = plottitle, key.title = title(main = var1, cex.main = 0.8, line = 1, xpd = NA), plot.axes = { axis(1); axis(2) points(ordi$points[, 1], ordi$points[, 2], xlab = "", ylab = "", cex= .5, col = 2, pch = '+') points(ordi$species[, 1], ordi$species[, 2], xlab = "", ylab = "", cex=.2, pch = 19) ordisurf(ordi, site[, var2], col = 'black', choices = c(1, 2), add = TRUE) orditorp(ordi, display = disp, pch = " ") legend("topright", paste("GAM of ", var2), col = 'black', lty = 1) if(!is.null(env)) plot(env, col='red') } ,...) } nmds.plot(veg.nmds, elbaue.env, disp='species', var1="MGL", var2="SDGL", env=env, plottitle = 'Elbaue floodplain dataset') } else { message("packages interp and/or labdsv not available") }
/scratch/gouwar.j/cran-all/cranData/vegdata/inst/doc/vegdata.R
#' Ten years of daily average air temperature #' #' A dataset containing ten years (2001-01-01 - 2010-12-31) of average air #' temperature measured at the weather station Goettingen. The data is the result #' of a reanalysis of observed data using the STARS model (cf. Orlowsky et al. #' 2008). They were provided by Prof. Dr. Peter Werner (PIK). #' #' @format A data frame with 3652 rows and 6 variables: #' \tabular{ll}{ #' \strong{Variable} \tab \strong{Description}\cr #' date \tab calendar date as object of class Date\cr #' year \tab years as integer\cr #' month \tab month as integer \cr #' day \tab day of month as integer\cr #' doy \tab day of year as integer \cr #' t \tab average air temperature #' } #' @source Prof. Dr. Peter Werner (PIK) #' @references #' Orlowsky, B., Gerstengarbe, F. W., Werner, P. C. (2008) #' A resampling scheme for regional climate simulations and its performance #' compared to a dynamical RCM. #' \emph{Theoretical and Applied Climatology}, \bold{92}(3–4), 209--223. #' \doi{10.1007/s00704-007-0352-y} #' @name goe #' @usage data(goe) #' @examples #' data(goe) #' str(goe) NULL
/scratch/gouwar.j/cran-all/cranData/vegperiod/R/doc_data.R
#============================================================================== # # Fetch climate data from DWD's open data program # # Robert Nuske 2015-03-30 #============================================================================== #' Fetch list of DWD weather stations #' #' Get a listing of advertised stations of Germany's National Meteorological #' Service (Deutscher Wetterdienst, DWD). The list differs for station type, #' time period and resolution. The list of advertised stations is usually not #' identical with currently available stations. #' #' The freely accessible part of the Climate Data Center of Germany's National #' Meteorological Service (Deutscher Wetterdienst, DWD) is part of DWD's #' mandate for basic supply of information (termed "Grundversorgung"). #' This service may be used without any restrictions (no fees will be #' charged and in general there are no restrictions for the use the data), #' provided that the source is indicated as laid down in the #' \href{http://www.gesetze-im-internet.de/geonutzv/BJNR054700013.html}{"GeoNutzV"} #' ordinance. The source reference shall roughly meet the following rules: #' \itemize{ #' \item Where data are used without modification, the source reference shall #' read "Source: Deutscher Wetterdienst" or just consist of the DWD logo. #' \item If the data are modified, the source reference shall specify as #' precisely as possible the extent of such, e.g. "Based on data from #' Deutscher Wetterdienst, figures rounded". #' } #' A more detailed description of the rules can be found in the official and #' legally binding German #' \href{https://opendata.dwd.de/climate_environment/CDC/Nutzungsbedingungen_German.pdf}{Nutzungsbedingungen} #' or the translated \href{https://opendata.dwd.de/climate_environment/CDC/Terms_of_use.pdf}{Terms #' of use}. #' #' @param type string. Stations can be of type \samp{"climate"} offering a range #' of meteorological parameters or of type \samp{"precipitation"} solely #' recording rainfall. #' #' @param period string specifying a time span. The last 1.5 years are #' called \samp{"recent"}. Data from the individual beginning of measurements #' up to a year ago are labelled \samp{"historical"}. #' #' @param resolution string. Temporal resolution of the data can be #' \samp{"daily"} or \samp{"monthly"}. \samp{"daily"} being the common #' resolution. #' #' @return A data.frame with all weather stations. It's not guaranteed that all #' advertised staions are available for download. Watch out for the end data #' of observation. Stations with recent data have a current end date. #' The data.frame contains the variables id, from, to, elev, lat, long, name, #' state. #' #' @references #' Freely accessible DWD data available via the #' \href{https://www.dwd.de/EN/climate_environment/cdc/cdc_node_en.html}{Climate Data Center}. #' #' @examples #' \dontrun{ #' # stations with daily climate data #' stations <- read.DWDstations() #' #' # precipitation stations with monthly historical data #' precip <- read.DWDstations(type='precip', period='historical', #' resolution='monthly') #' #' # list stations with daily data updated within last week #' stat.daily <- read.DWDstations(period='recent') #' stat.daily.recent <- stat.daily[stat.daily$to > (Sys.Date() - 7), ] #' } #' #' @export read.DWDstations <- function(type='climate', period='recent', resolution='daily'){ # check arguments type <- match.arg(type, choices=c('climate','precipitation')) period <- match.arg(period, choices=c('historical', 'recent')) resolution <- match.arg(resolution, choices=c('daily', 'monthly')) # construct url baseURL <- "ftp://opendata.dwd.de/climate_environment/CDC/observations_germany/climate" url.type <- switch(type,'climate'='kl','precipitation'='more_precip') pre.type <- switch(type, 'climate'='KL','precipitation'='RR') pre.res <- switch(resolution, 'daily'='Tageswerte', 'monthly'='Monatswerte') fname <- paste0(pre.type, "_", pre.res, "_Beschreibung_Stationen.txt") myURL <- paste(baseURL, resolution, url.type, period, fname, sep='/') myCols <- c('id', 'from', 'to', 'elev', 'lat', 'long', 'name', 'state') myWidths <- switch(resolution, 'daily' = c(6, 9, 9, 15, 12, 10, 41, 24), 'monthly' = c(6, 9, 9, 14, 12, 10, 41, 24)) options(warn=-1) # the warning about last line is wrong -> don't show it # treat EOF as comment df <- utils::read.fwf(myURL, widths=myWidths, skip=2, comment.char="\032", strip.white=TRUE, na.strings='-999', fileEncoding='ISO-8859-1', col.names=myCols, stringsAsFactors=FALSE) df$from <- as.Date(as.character(df$from), "%Y%m%d") df$to <- as.Date(as.character(df$to), "%Y%m%d") options(warn=0) return(df) } #' Fetch meteo data of DWD weather stations #' #' Fetch observed meteorological data of German weather stations from freely #' accessible part of the Climate Data Center of Germany's National #' Meteorological Service (Deutscher Wetterdienst, DWD). #' #' An introduction to the data available at the Climate Data Center can be #' found in the German #' \href{https://opendata.dwd.de/climate_environment/CDC/Liesmich_intro_CDC-FTP.pdf}{Liesmich_intro_CDC_ftp} #' or the translated #' \href{https://opendata.dwd.de/climate_environment/CDC/Readme_intro_CDC_ftp.pdf}{Readme_intro_CDC_ftp}. #' #' The freely accessible part of the Climate Data Center of Germany's National #' Meteorological Service (Deutscher Wetterdienst, DWD) is part of the DWD's #' mandate for basic supply of information (termed "Grundversorgung"). #' These services may be used without any restrictions (no fees will be charged #' and in general there are no restrictions for the use the data), provided #' that the source is indicated as laid down in the #' \href{http://www.gesetze-im-internet.de/geonutzv/BJNR054700013.html}{"GeoNutzV"} #' ordinance. The source reference shall roughly meet the following rules: #' \itemize{ #' \item Where data are used without modification, the source reference shall #' read "Source: Deutscher Wetterdienst" or just consist of the DWD logo. #' \item If the data are modified, the source reference shall specify as #' precisely as possible the extent of such, e.g. "Based on data from #' Deutscher Wetterdienst, figures rounded". #' } #' A more detailed description of the rules can be found in the official and #' legally binding German #' \href{https://opendata.dwd.de/climate_environment/CDC/Nutzungsbedingungen_German.pdf}{Nutzungsbedingungen} #' or the translated \href{https://opendata.dwd.de/climate_environment/CDC/Terms_of_use.pdf}{Terms #' of use}. #' #' @param id integer. A valid station id (cf. \link{read.DWDstations}). #' #' @param type string. Stations can be of type \samp{"climate"} offering a range #' of meteorological parameters or of type \samp{"precipitation"} solely #' recording rainfall. There are about 400 \samp{climate} and 2000 #' \samp{precipitation} stations. #' #' @param period string specifying a time span. The last 1.5 years are #' called \samp{"recent"}. Data from the individual beginning of measurements #' up to a year ago are labelled \samp{"historical"}. #' \samp{"recent"} data have not yet gone through the full quality control #' procedure. \samp{"historical"} data have completed the operational quality #' control. But be aware there still might be gaps and inhomogeneities. #' #' @param resolution string. Temporal resolution of the data can be #' \samp{"daily"} or \samp{"monthly"}. \samp{"daily"} being the common #' resolution. #' #' @param file a string specifying the location of a dataset. \samp{"file"} #' may point to a file on a FTP server or on the local file system. #' If the file lives on a FTP server the string must start with #' \code{'ftp://'}. If it is NULL (the default), data will be downloaded #' from DWD's FTP server. #' #' @param destdir directory (string) where intermediate data (downloaded *.zip #' file) are stored. If it is NULL (the default) a subdirectory #' \samp{downloaded_packages} of the session temporary directory will be used #' (and the files will be deleted at the end of the session). #' It might be advisable to keep the .zip file since it contains the #' stations documentation and metadata (e.g. station shift, used devices, #' downtimes etc.). #' #' @param quiet If TRUE, suppress status messages (if any), and the progress bar. #' #' @return A data.frame with the observed weather data. Beware of gaps and #' inhomogeneities! \samp{colnames} contains the original header and #' hence German terms. #' #' Content of 'climate'-data.frame: #' \tabular{ll}{ #' \strong{Name} \tab \strong{Description}\cr #' STATIONS_ID \tab station id\cr #' MESS_DATUM \tab date\cr #' QN_3 \tab quality level of next columns (-)\cr #' FX \tab daily maximum of wind gust (m/s)\cr #' FM \tab daily mean of wind velocity (m/s)\cr #' QN_4 \tab quality level of next columns (-)\cr #' RSK \tab daily precipitation height (mm)\cr #' RSKF \tab precipitation form (-)\cr #' SDK \tab daily sunshine duration (h)\cr #' SHK_TAG \tab daily snow depth (cm)\cr #' NM \tab daily mean of cloud cover (1/8)\cr #' VPM \tab daily mean of vapor pressure (hPa)\cr #' PM \tab daily mean of pressure (hPa)\cr #' TMK \tab daily mean of temperature (°C)\cr #' UPM \tab daily mean of relative humidity (\%)\cr #' TXK \tab daily maximum of temperature at 2m height (°C)\cr #' TNK \tab daily minimum of temperature at 2m height (°C)\cr #' TGK \tab daily minimum of air temperature at 5cm above ground (°C) #' } #' #' Content of 'precipitation'-data.frame: #' \tabular{ll}{ #' \strong{Name} \tab \strong{Description}\cr #' STATIONS_ID \tab station id\cr #' MESS_DATUM \tab date\cr #' QN_6 \tab quality level of next columns (-)\cr #' RS \tab daily precipitation height (mm)\cr #' RSF \tab precipitation form (-)\cr #' SH_TAG \tab daily height of snow pack (cm)\cr #' } #' #' @references #' Freely accessible DWD data available via the #' \href{https://www.dwd.de/EN/climate_environment/cdc/cdc_node_en.html}{Climate Data Center}. #' #' @examples #' \dontrun{ #' # fetch last 500 days worth of data from station Göttingen #' clim <- read.DWDdata(id=1691) #' #' # save data & metadata (documentation about devices, downtimes etc.) #' clim <- read.DWDdata(id=1691, destdir='.') #' #' # find and download historical data from the Brocken #' stat.hist <- read.DWDstations(period='historical') #' brocken.id <- stat.hist[grep("^Brock", stat.hist$name), ]$id #' clim.brocken <- read.DWDdata(id=brocken.id, period='historical') #' } #' #' @export read.DWDdata <- function(id, type='climate', period='recent', resolution='daily', file=NULL, destdir=NULL, quiet=FALSE){ if(is.null(file)){ # construct url from provided pieces of information #------------------------------------------------------------------------ # check arguments if(missing(id)) stop('id is required') type <- match.arg(type, choices=c('climate','precipitation')) period <- match.arg(period, choices=c('historical', 'recent')) resolution <- match.arg(resolution, choices=c('daily', 'monthly')) # build up URL & filename baseURL <- "ftp://opendata.dwd.de/climate_environment/CDC/observations_germany/climate" url.type <- switch(type,'climate'='kl','precipitation'='more_precip') myURL <- file.path(baseURL, resolution, url.type, period) if(period == "historical"){ # historical filenames can't be guessed -> list all files & filter if(!quiet) message('Searching for file name in list of available files...') files <- .list_available_via_FTP(paste0(myURL, '/')) fname <- grep(formatC(id, width=5, flag='0'), files, value=TRUE) if(length(fname) == 0) stop(paste0('File with id ', sQuote(id),' not available at URL ', sQuote(myURL), '.')) } else { # recent fname <- paste( switch(resolution, 'daily'='tageswerte', 'monthly'='monatswerte'), switch(type,'climate'='KL','precipitation'='RR'), formatC(id, width=5, flag='0'), "akt.zip", sep='_' ) } url <- file.path(myURL, fname) pathToZip <- .download_from_ftp(url, destdir, fname, quiet) file <- .connection_to_target_within_zip(pathToZip) } else { # url for download or path in local filesystem #------------------------------------------------------------------------ if(substr(file, 1, 6) == "ftp://"){ # a url to an ftp service fname <- basename(file) pathToZip <- .download_from_ftp(file, destdir, fname, quiet) file <- .connection_to_target_within_zip(pathToZip) } else { # path in local file system if (!file.exists(file)) stop(paste("Can not find file", sQuote(file))) if(file.access(file, 4) != 0) stop("'file' is not readable") if(grepl(".zip$", file)) file <- .connection_to_target_within_zip(file) } } df <- .read.obscureDWDfiles(file) md_col <- grep("^MESS_DATUM", names(df)) for(i in md_col){ df[, i] <- as.Date(as.character(df[, i]), format="%Y%m%d") } return(df) } #============================================================================== # # Internal Helper Functions # #============================================================================== # Download data from FTP Server #-------------------------------------------------------------------------- .download_from_ftp <- function(url, destdir, fname, quiet){ # where to put the zip file ? if(is.null(destdir)){ pathToZip <- file.path(tempdir(), fname) } else { if (!dir.exists(destdir)) stop("'destdir' is not a directory") if(file.access(destdir, 2) != 0) stop("'destdir' is not writeable") if(!quiet) message(paste("Writing downloaded zip to", sQuote(destdir))) pathToZip <- file.path(destdir, fname) } # download tryCatch( utils::download.file(url, destfile=pathToZip, quiet=quiet), error=function(e) stop(paste("Could not download file. Try the URL", sQuote(url), "in a Web-Browser. \nPlease inform the package maintainer", "if you did not use the 'url' argument but the URL is", "malformed anyway.")) ) return(pathToZip) } # create connection to target file in zip file #------------------------------------------------------------------------------ .connection_to_target_within_zip <- function(pathToZip){ file.list <- utils::unzip(pathToZip, list=TRUE) hidden.file <- grep('^produkt', file.list$Name, value=TRUE) tryCatch(connection <- unz(pathToZip, hidden.file), error=function(e) stop(paste("Could not open", sQuote(hidden.file), "from zip-file", sQuote(pathToZip), "for reading.")) ) return(connection) } # argh, DWD-Data end with EOF (=Ctrl-Z, 0x1A, \032) # http://en.wikipedia.org/wiki/End-of-file # http://de.wikipedia.org/wiki/End_of_File # # Usual Treatment: # treat EOF as comment, read file in binary mode, use gsub to replace EOF #------------------------------------------------------------------------------ .read.obscureDWDfiles <- function(file){ # treat EOF as comment df <- utils::read.table(file, sep=";", dec=".", header=TRUE, comment.char="\032", strip.white=TRUE, na.strings='-999') df$eor <- NULL return(df) } .read.obscureDWDfiles2 <- function(file){ # read in binary mode, kick EOF out, write clean data, read again temp <- tempfile() binaer <- readBin(file, what="raw", n=10000000) binaer <- binaer[binaer != 0x1a] writeBin(binaer, temp) df <- utils::read.table(temp, sep=";", dec=".", header=TRUE, strip.white=TRUE, na.strings="-999") df$eor <- NULL return(df) } .read.obscureDWDfiles3 <- function(file){ # read in binary mode, ignore warnings, replace EOF with nothing while reading f <- file(file, "rb") zeilen <- readLines(f) close(f) df <- utils::read.table(textConnection(gsub("\\\032", '', zeilen)), sep=";", dec=".", header=TRUE, strip.white=TRUE, na.strings="-999") df$eor <- NULL return(df) } # List files available at ftp server #------------------------------------------------------------------------------ .list_available_via_FTP <- function(url){ if(!requireNamespace('curl', quietly=TRUE)) stop("Please install curl, e.g. install.packages('curl')") # get a list of all files within a directory h <- curl::new_handle(dirlistonly=1, ftp_use_epsv=0) con <- curl::curl(url, handle=h) filenames <- readLines(con) close(con) return(filenames) }
/scratch/gouwar.j/cran-all/cranData/vegperiod/R/read_dwd.R
#============================================================================== # # internal functions [The Ends] # #============================================================================== #============================================================================== # # End of vegetation period according to von Wilpert (1990) # #============================================================================== #' Vegetation End Method "vonWilpert" #' #' The method `vonWilpert` is based on von Wilpert (1990). It was originally #' developed for "Picea abies" in the Black Forest but is commonly used for all #' tree species throughout Germany. As usual, the rules regarding the soilmatrix #' are neglected in this implementation. #' #' @section Calculations: #' #' Orthodox are 3 criteria: **short day**, **temperature** and **drought criterion** #' we consider -as usual- only short day and temperature citerion #' #' ## Temperature criterion: #' - 7 day moving average of daily mean temperatures #' at least 5 consecutive days under 10°C #' - if afterwards more than 5 consecutive days 7 day moving average over 10°C #' vegetation period gets restarted #' #' ## Short day criterion #' - last day of the vegetation period is DOY 279 (5th of October in leap years) # #' @references #' von Wilpert, K. (1990) #' Die Jahrringstruktur von Fichten in Abhängigkeit vom Bodenwasserhaushalt #' auf Pseudogley und Parabraunerde: Ein Methodenkonzept zur Erfassung #' standortsspezifischer Wasserstreßdispostion. #' \emph{Freiburger Bodenkundliche Abhandlungen}. Pages 106--108. #' #' @md #' @name method_vonWilpert #' @keywords internal NULL .end_vonWilpert <- function(df, Treshold=10, LastDOY=279){ # Assumptions: # - data.frame 'df' contains month, DOY, Tavg # - DOYs at least till LastDOY LastDOY <- as.integer(LastDOY) # Preparation #---------------------------------------------------------------------------- # moving average with windows size 7 (symetric) df$TmovAvg <- as.numeric(stats::filter(df$Tavg, rep(1/7,7), sides=2)) # mark periods ('cold', 'warm') before LastDOY and 'ignore' the rest df$period <- ifelse(df$DOY > LastDOY, 'ignore', ifelse(df$TmovAvg < Treshold, 'cold', 'warm')) # determine continous strides of warm/cold by using run length encoding # cold period if stride at least 5 # warm period if stride more than 5 temp <- rle(df$period) temp$values[temp$lengths < 5] <- 'ignore' temp$values[temp$values == 'warm' & temp$lengths < 6] <- 'ignore' temp$values[is.na(temp$values)] <- 'ignore' df$period <- inverse.rle(temp) # Searching for the end #---------------------------------------------------------------------------- # last warm period per year last.warm <- tapply(df$DOY[df$period == 'warm'], df$year[df$period == 'warm'], FUN=max) last.warm <- data.frame(year=as.integer(row.names(last.warm)), DOY=last.warm) # loop over all years years <- unique(df$year) end <- sapply(years, # cold period after last.warm? (yes: min(cold)+4; no: LastDOY) FUN=function(x) { # cold period after warm period? temp <- df[df$year == x & df$period == 'cold', 'DOY'] temp <- temp[temp > last.warm[last.warm$year == x, 'DOY']] if(length(temp) > 0){ # 5th day of cold period is the end min(temp) + 4L } else { # no colds after last.warm -> default end LastDOY } } ) return(end) } #============================================================================== # # End of vegetation period according to LWF-BROOK90 # #============================================================================== #' Vegetation End Method "LWF-BROOK90" #' #' The method `LWF-BROOK90` is -for the sake of convenience- a reimplementation #' of the LWF-BROOK90 VBA (version 3.4) variant of "vonWilpert" (Hammel and #' Kennel 2001). Their interpretation of von Wilpert (1990) and the somewhat #' lower precision of VBA was mimicked. #' #' @section Calculations: #' #' ``` #' - starting search at June 1st #' - propose end if 7-day moving average temperature is below 10°C #' on 5 consecutive days #' - restart search for end if there is a warm periode (7-day moving average #' temperature above 10°C for 5 consecutive days #' - nevertheless the vegetation periode stops latest at DOY 279 #' ``` #' #' @references #' Hammel, K. and Kennel, M. (2001) #' Charakterisierung und Analyse der Wasserverfügbarkeit und des #' Wasserhaushalts von Waldstandorten in Bayern mit dem Simulationsmodell #' BROOK90. #' \emph{Forstliche Forschungsberichte München}. #' #' von Wilpert, K. (1990) #' Die Jahrringstruktur von Fichten in Abhängigkeit vom Bodenwasserhaushalt #' auf Pseudogley und Parabraunerde: Ein Methodenkonzept zur Erfassung #' standortsspezifischer Wasserstreßdispostion. #' \emph{Freiburger Bodenkundliche Abhandlungen}. #' #' @md #' @name method_LWF-BROOK90 #' @keywords internal NULL .end_LWF_BROOK90 <- function(df, Tmin=10, LastDOY=279){ # Assumptions: # - data.frame 'df' contains month, DOY, Tavg # - DOYs at least till 279 LastDOY <- as.integer(LastDOY) # moving average with windows size 7 (only backward looking) # round to mimic lower precision of VBA version # (14 digits might be okay, 10 is on the save side) df$movAvgT <- round(as.numeric(stats::filter(df$Tavg, rep(1/7, 7), sides=1)), 10) # introduce 2 counters 'cold' and 'warm' ('ignore' the rest) df$period <- ifelse(df$month > 5 & df$DOY <= LastDOY, ifelse(df$movAvgT < Tmin, 'cold', 'warm'), 'ignore') # reset one counter if the other enters the stage by using run length encoding # cold/warm periode only valid if >4 => ignore all counts below 5 temp <- rle(df$period) temp$values[temp$lengths < 5] <- 'ignore' temp$values[is.na(temp$values)] <- 'ignore' df$period <- inverse.rle(temp) # Searching the end #---------------------------------------------------------------------------- # last warm period per year last.warm <- tapply(df$DOY[df$period == 'warm'], df$year[df$period == 'warm'], FUN=max) last.warm <- data.frame(year=as.integer(row.names(last.warm)), DOY=last.warm) # loop over all years years <- unique(df$year) end <- sapply(years, # cold period after last.warm? (yes: min(cold)+4; no: LastDOY) FUN=function(x) { # cold period after warm period? temp <- df[df$year == x & df$period == 'cold', 'DOY'] temp <- temp[temp > last.warm[last.warm$year == x, 'DOY']] if(length(temp) > 0){ # 5th day of cold period is the end min(temp) + 4L } else { # no colds after last.warm -> default end LastDOY } } ) return(end) } #============================================================================== # # End of vegetation period according to Nuske & Albert # #============================================================================== #' Vegetation End Method "NuskeAlbert" #' #' The method `NuskeAlbert` provides a very simple method which is inspired by #' standard climatological procedures but employs a 7 day moving average and #' a 5 °C threshold (cf. Walther and Linderholm 2006). #' #' @section Calculations: #' 2 criteria: temperature & short day criterion #' #' ## Temperature criterion #' 7 day moving average of daily mean temperatures #' end if 5 consecutive days under under 5° C #' start the search at 1st of July / vegetation start #' #' ## Short day criterion #' last day of the vegetation period is 5th of October #' #' @md #' @references #' Walther, A. and Linderholm, H. W. (2006) #' A comparison of growing season indices for the Greater Baltic Area. #' \emph{International Journal of Biometeorology}, \bold{51}(2), 107--118. #' \doi{10.1007/s00484-006-0048-5}. #' #' @name method_NuskeAlbert #' @keywords internal NULL .end_NuskeAlbert <- function(df, start, Tmin=5){ # Assumptions: # - data.frame 'df' contains month, DOY, Tavg # - time range covers at least veg.start/jul1 till oct5 (save side DOY 1-279) # Calculate correct DOYs # 1. July is DOY 182 and DOY 183 in leap years # 5. October is DOY 278 and 279 in leap years years <- unique(df$year) jul1 <- ifelse((years%%4==0 & years%%100!=0) | years%%400==0, 183L, 182L) searchstart <- ifelse(!is.na(start) & start > jul1, start, jul1) oct5 <- ifelse((years%%4==0 & years%%100!=0) | years%%400==0, 279L, 278L) # 7 day moving average under 5° and after 1 July / vegperiod start # moving average with windows size 7 (symetric window) df$TmovAvg <- as.numeric(stats::filter(df$Tavg, rep(1/7,7), sides=2)) df$period <- ifelse(df$TmovAvg < Tmin, 1, 0) # ends on the 5th day if no 5 day streak end on 5oct end <- oct5 for(i in seq_along(years)){ temp <- df[df$year == years[i] & df$DOY >= searchstart[i] & df$DOY <= oct5[i], ] temp$five <- as.numeric(stats::filter(temp$period, rep(1, 5), sides=1)) possible.end <- temp[!is.na(temp$five) & temp$five == 5, "DOY"] if(length(possible.end) > 0) end[i] <- min(possible.end) } return(end) } #============================================================================== # # End of vegetation period according to standard meteo procedure aka 'ETCCDI' # # first span after July 1st of 6 consecutive days with TG < 5°C. # #============================================================================== .end_std_meteo <- function(df, Tmin=5){ # Assumptions: # - data.frame 'df' contains month, DOY, Tavg # - full years # 1. July is DOY 182 and DOY 183 in leap years years <- unique(df$year) leap_year <- ifelse((years%%4==0 & years%%100!=0) | years%%400==0, TRUE, FALSE) jul1 <- ifelse(leap_year, 183L, 182L) # mark days colder than 5°C df$period <- ifelse(df$Tavg < Tmin, 1, 0) # find first six day span per year end <- ifelse(leap_year, 366L, 365L) for(i in seq_along(years)){ temp <- df[df$year == years[i] & df$DOY > jul1[i], ] temp$six <- as.numeric(stats::filter(temp$period, rep(1, 6), sides=1)) possible.end <- temp[!is.na(temp$six) & temp$six == 6, "DOY"] if(length(possible.end) > 0) end[i] <- min(possible.end) } return(end) }
/scratch/gouwar.j/cran-all/cranData/vegperiod/R/veg_ends.R
#============================================================================== # # internal functions [The Starts] # #============================================================================== #============================================================================== # # Start of vegetation period according to Menzel (1997) # #============================================================================== #' Vegetation Start Method "Menzel" #' #' The method "Menzel" implements the algorithm described in Menzel (1997). #' The method is parameterized for 10 common tree species ( *Larix decidua*, #' *Picea abies (frueh)*, *Picea abies (spaet)*, *Picea abies (noerdl.)*, #' *Picea omorika*, *Pinus sylvestris*, *Betula pubescens*, *Quercus robur*, #' *Quercus petraea*, *Fagus sylvatica*). It needs previous year's chill days. #' #' @section Calculations: #' #' ``` #' - counting chill days in Nov & Dec of previous year if previous year available else estimate previous year's chill days #' - count chill days in current year #' - determine critical temperature per days using regression equation fitted by Menzel 1997 #' - calculate HeatSum starting from Feb #' - vegetation start if HeatSum >= criticalTemp #' ``` #' #' @references #' Menzel, A. (1997) Phänologie von Waldbäumen unter sich ändernden Klimabedingungen - Auswertung der Beobachtungen in den Internationalen Phänologischen Gärten und Möglichkeiten der Modellierung von Phänodaten. Forstliche Forschungsberichte München. #' #' @md #' @name method_Menzel #' @docType data #' @keywords internal NULL .start_menzel <- function(df, est.prev, species){ # Assumptions: # - data.frame 'df' contains month, DOY, Tavg # - full years # - last year at least till DOY 279 # - and previous Nov & Dec if est.prev==0 # - est.prev >= 0 and <= number of years # - species contains a known name years <- unique(df$year) # Menzel's Parameter Mp <- switch(species, "Larix decidua" = list(TbCD=7, TbH=3, a=1372, b=-246), "Picea abies (frueh)" = list(TbCD=9, TbH=4, a=1848, b=-317), "Picea abies (spaet)" = list(TbCD=9, TbH=5, a=1616, b=-274), "Picea abies (noerdl.)" = list(TbCD=9, TbH=4, a=2084, b=-350), "Picea omorika" = list(TbCD=7, TbH=3, a=2833, b=-484), "Pinus sylvestris" = list(TbCD=9, TbH=5, a=1395, b=-223), "Betula pubescens" = list(TbCD=9, TbH=5, a=1438, b=-261), "Quercus robur" = list(TbCD=9, TbH=4, a=1748, b=-298), "Quercus petraea" = list(TbCD=9, TbH=3, a=1741, b=-282), "Fagus sylvatica" = list(TbCD=9, TbH=6, a=1922, b=-348)) # Chill Days #---------------------------------------------------------------------------- # number of chill days in Nov and Dec trigger next years bud burst CDNovDec <- utils::stack(tapply(df[(df$month >= 11 & df$Tavg <= Mp$TbCD), "Tavg"], df[(df$month >= 11 & df$Tavg <= Mp$TbCD), "year"], FUN=length)) # shove the chill days in to next year, where they trigger veg start CDNovDec$ind <- as.integer(levels(CDNovDec$ind)) + 1 names(CDNovDec) <- c("CDprev", "year") # handle first year if(est.prev == 0){ # drop first year df <- df[df$year != years[1], ] } else { # mean "est.prev number of years" as proxy for first year's previous chill days CDNovDec <- rbind(c(mean(CDNovDec$CDprev[1:est.prev]), years[1]), CDNovDec) } # cumulative sums of chill days per year df$CD <- ifelse(df$Tavg <= Mp$TbCD, 1, 0) ChillDays <- utils::stack(tapply(df$CD, df$year, FUN=cumsum)) names(ChillDays) <- c("CDcumsum", "year") # merge and add to workhorse df ChillDays <- merge(ChillDays, CDNovDec, by="year", all.x=TRUE) df$CD <- ChillDays$CDprev + ChillDays$CDcumsum rm(ChillDays, CDNovDec) # determine vegetation start with Menzel's regression #---------------------------------------------------------------------------- # critical Temperature df$TCrit <- ifelse(df$CD > 0, Mp$a + Mp$b * log(df$CD), Mp$a) # cumsum of degrees above threshold # (start in Feb and consider only degrees above thresh) df$HeatSum <- ifelse(df$month >= 2 & df$Tavg > Mp$TbH, df$Tavg - Mp$TbH, 0) df$HeatSum <- utils::stack(tapply(df$HeatSum, df$year, FUN=cumsum))$values # vegetation period start if HeatSum >= TCrit df$start <- df$HeatSum >= df$TCrit # determine first of start candidates start <- utils::stack(tapply(df$DOY[df$start], df$year[df$start], FUN=min))$values return(start) } #============================================================================== # # Start of vegetation period according to standard meteo procedure aka 'ETCCDI' # #============================================================================== #' Vegetation Start and End Method "ETCCDI" #' #' The `ETCCDI` or `StdMeteo` method was defined by Expert Team on Climate Change Detection and Indices and is often known as Growing season Length (GSL) and widely used in climate change studies. #' #' @section Calculation: #' #' ## Implementation of start #' first span of at least 6 consecutive days with daily mean temperature TG > 5°C #' #' ``` #' # mark days warmer than 5°C #' df$period <- ifelse(df$Tavg > Tmin, 1, 0) #' #' # find first six day span per year #' start <- tapply(df$period, df$year, FUN=function(x){ #' sixer <- as.numeric(stats::filter(x, rep(1, 6), sides=1)) #' doy <- which(!is.na(sixer) & sixer == 6) #' ifelse(length(doy) == 0, NA, min(doy)) #' }) #' ``` #' #' ## Implementation of end #' first span after July 1st of 6 consecutive days with TG < 5°C. #' #' ``` #' # 1. July is DOY 182 and DOY 183 in leap years #' years <- unique(df$year) #' leap_year <- ifelse((years%%4==0 & years%%100!=0) | years%%400==0, TRUE, FALSE) #' jul1 <- ifelse(leap_year, 183L, 182L) #' #' # mark days colder than 5°C #' df$period <- ifelse(df$Tavg < Tmin, 1, 0) #' #' # find first six day span per year #' end <- ifelse(leap_year, 366L, 365L) #' for(i in seq_along(years)){ #' temp <- df[df$year == years[i] & df$DOY > jul1[i], ] #' temp$six <- as.numeric(stats::filter(temp$period, rep(1, 6), sides=1)) #' possible.end <- temp[!is.na(temp$six) & temp$six == 6, "DOY"] #' if(length(possible.end) > 0) #' end[i] <- min(possible.end) #' } #' ``` #' #' @references #' Definition recommended by the CCl/CLIVAR/JCOMM Expert Team on Climate Change Detection and Indices (ETCCDI) http://etccdi.pacificclimate.org/list_27_indices.shtml http://www.climdex.org/indices.html #' #' European Climate Assessment (ECA) http://eca.knmi.nl/indicesextremes/indicesdictionary.php #' #' ETCCDI (2009) Climate Change Indices: Definitions of the 27 core indices. http://etccdi.pacificclimate.org/list_27_indices.shtml #' Frich, P., Alexander, L., Della-Marta, P., Gleason, B., Haylock, M., Klein Tank, A. and Peterson, T. (2002) Observed coherent changes in climatic extremes during the second half of the twentieth century. Climate Research, 19, 193–212. https://doi.org/10.3354/cr019193. #' http://www.climateknowledge.org/heat_waves/Doc2004_Frich_Extremes_Index_ClimResearch_2002.pdf #' #' Zhang, X., Alexander, L., Hegerl, G. C., Jones, P., Tank, A. K., Peterson, T. C., Trewin, B. and Zwiers, F. W. (2011) Indices for monitoring changes in extremes based on daily temperature and precipitation data. Wiley Interdisciplinary Reviews: Climate Change, 2(6), 851–870. https://doi.org/10.1002/wcc.147. #' #' @md #' @keywords internal #' @name method_ETCCDI NULL .start_std_meteo <- function(df, Tmin=5){ # Assumptions: # - data.frame 'df' contains month, DOY, Tavg # - full years # mark days warmer than 5°C df$period <- ifelse(df$Tavg > Tmin, 1, 0) # find first six day span per year start <- tapply(df$period, df$year, FUN=function(x){ sixer <- as.numeric(stats::filter(x, rep(1, 6), sides=1)) doy <- which(!is.na(sixer) & sixer == 6) ifelse(length(doy) == 0, NA, min(doy)) }) return(as.vector(start)) } #============================================================================== # # Start of vegetation period according to DWD (Gooseberry, Ribes uva-crispa) # published in the klimaatlas under forest parameters # #============================================================================== #' Vegetation Start Method "Ribes uva-crispa" #' #' The method `Ribes uva-crispa` is based on leaf-out of gooseberry (Janssen 2009). #' It was developed by the Germany's National Meteorological Service #' (Deutscher Wetterdienst, DWD) and is more robust against early starts than #' common simple meteorological procedures. #' #' @section Calculation: #' #' starting from 18th February sum all day degrees above 0 °C (daily average air #' temperature). Vegetetaion period starts at the day when 164 is crossed. #' #' ``` #' # start day: February 18th == 49 doy #' # only Tavg over 0°C are summed #' df[df$DOY < 49 | df$Tavg < 0, 'Tavg'] <- 0 #' #' # find day where cum day degrees cross 164 #' start <- tapply(df$Tavg, df$year, FUN=function(x){ #' x <- cumsum(x) #' min(which(x > 164)) #' }) #' ``` #' #' @references #' Janssen, W. (2009) #' Definition des Vegetationsanfanges. #' \emph{Internal Report, Deutscher Wetterdienst, Abteilung Agrarmeteorologie}. #' #' @md #' @name method_Ribes #' @keywords internal NULL .start_ribes <- function(df){ # Assumptions: # - data.frame 'df' contains year, DOY, Tavg # - full years # start day: February 18th == 49 doy # only Tavg over 0°C are summed df[df$DOY < 49 | df$Tavg < 0, 'Tavg'] <- 0 # find day where cum day degrees cross 164 start <- tapply(df$Tavg, df$year, FUN=function(x){ x <- cumsum(x) min(which(x > 164)) }) return(as.vector(start)) }
/scratch/gouwar.j/cran-all/cranData/vegperiod/R/veg_starts.R
#============================================================================== # Vegetation Period # calculate start and end of vegetation periode # # rewrite 2015-02-15 - 2015-02-26 by Robert Nuske # Written on my way to work. # Thanks to good working conditions (no internet) in the ICE. #============================================================================== #' Determine vegetation period #' #' Calculate start and end date of vegetation periods based on daily average #' air temperature and the day of the year (DOY). #' The sum of day degrees within the vegetation period is included for convenience. #' #' #' @details #' Common methods for determining the onset and end of thermal vegetation #' periods are provided, for details see next sections. Popular choices with #' regard to forest trees in Germany are `Menzel` and `vonWilpert`. Climate #' change impact studies at NW-FVA are frequently conducted using `Menzel` with #' "Picea abies (frueh)" and `NuskeAlbert` for all tree species; with tree #' species specifics accounted for in subsequent statistical models. #' #' ## Start methods: #' The method **[`Menzel`][method_Menzel]** implements the algorithm described in #' Menzel (1997). The method is parameterized for 10 common tree species. It #' needs previous year's chill days. **[`ETCCDI`][method_ETCCDI]** resp. #' `StdMeteo` is a simple threshold based procedure as defined by the #' Expert Team on Climate Change Detection and Indices (cf. ETCCDI 2009, Frich #' et al. 2002, Zhang et al. 2011) leading to quite early vegetation starts. #' This method is widely used in climate change studies. The method #' **[`Ribes uva-crispa`][method_Ribes]** is based on leaf-out of gooseberry (Janssen #' 2009). It was developed by the Germany's National Meteorological Service #' (Deutscher Wetterdienst, DWD) and is more robust against early starts than #' common simple meteorological procedures. #' #' ## End methods: #' The end method **[`vonWilpert`][method_vonWilpert]** is based on von Wilpert (1990). It #' was originally developed for *Picea abies* in the Black Forest but is #' commonly used for all tree species throughout Germany. As usual, the rules #' regarding the soilmatrix are neglected in this implementation. #' **[`LWF-BROOK90`][method_LWF-BROOK90]** is -for the sake of convenience- a #' reimplementation of the LWF-BROOK90 VBA (version 3.4) variant of "vonWilpert" #' (Hammel and Kennel 2001). Their interpretation of von Wilpert (1990) and the #' somewhat lower precision of VBA was mimicked. **[`NuskeAlbert`][method_NuskeAlbert]** #' provide a very simple method which is inspired by standard climatological #' procedures but employs a 7 day moving average and a 5 °C threshold (cf. #' Walther and Linderholm 2006). **[`ETCCDI`][method_ETCCDI]** resp. `StdMeteo` #' is a simple threshold based procedure as defined by the Expert Team on #' Climate Change Detection and Indices (cf. ETCCDI 2009, Frich et al. 2002, #' Zhang et al. 2011) leading to quite late vegetation ends. #' #' @param dates vector of calendar dates (objects of class `Date` or something #' understood by [as.Date()]). Must contain entire years if `est.prev > 0` #' else the first year may comprise only November and December. #' @param Tavg vector of daily average air temperatures in degree Celsius. #' Same length as `dates`. #' @param start.method name of method to use for vegetation start. One of #' `"Menzel"` (needs additional argument `species`, see below), `"StdMeteo"` #' resp. `"ETCCDI"`, `"Ribes uva-crispa"`. Can be abbreviated (partial #' matching). For further discussion see Details. #' @param end.method name of method to use for vegetation end. One of #' `"vonWilpert"`, `"LWF-BROOK90"`, `"NuskeAlbert"` and `"StdMeteo"` resp. #' `"ETCCDI"`. Can be abbreviated (partial matching). For further discussion #' see Details. #' @param Tsum.out boolean. Return the sum of daily mean temperatures above #' `Tsum.crit` within vegetation period, also known as growing day degrees. #' @param Tsum.crit threshold for sum of day degrees. Only daily mean temperatures #' `> Tsum.crit` will be tallied. The default of `0` prevents negative #' daily temperatures from reducing the sum. Climate change studies often use #' a threshold of `5`. #' @param species name of tree species (required if `start.method="Menzel"` #' ignored otherwise). #' #' Must be one of `"Larix decidua"`, `"Picea abies (frueh)"`, #' `"Picea abies (spaet)"`, `"Picea abies (noerdl.)"`, `"Picea omorika"`, #' `"Pinus sylvestris"`, `"Betula pubescens"`, `"Quercus robur"`, #' `"Quercus petraea"`, `"Fagus sylvatica"`. #' @param est.prev number of years to **est**imate **prev**ious year's chill #' days for the first year (required if `start.method="Menzel"` ignored #' otherwise). #' #' `Menzel` requires the number of chill days of previous November and #' December. If `est.prev = 0` the first year is used to get the previous #' year's chill days and dropped afterwards. Thus, a year from the time #' series is lost. To avoid losing a year, `est.prev = n` estimates the #' previous year's chill days for the first year from the average of `n` #' first years of the time series. #' @param check.data Performs plausibility checks on the temperature data to #' ensure that the temperatures have not been multiplied by ten. #' Plausible range is -35 to +40°C. #' #' @return A data.frame with year and DOY of start and end day of #' vegetation period. If `Tsum.out=TRUE`, the data.frame contains an #' additional column with the sum of day degrees within vegetation periods. #' #' @references #' ETCCDI (2009) #' Climate Change Indices: Definitions of the 27 core indices. #' \url{http://etccdi.pacificclimate.org/list_27_indices.shtml} #' #' Frich, P., Alexander, L., Della-Marta, P., Gleason, B., Haylock, M., #' Klein Tank, A. and Peterson, T. (2002) #' Observed coherent changes in climatic extremes during the second half of #' the twentieth century. #' \emph{Climate Research}, \bold{19}, 193--212. #' \doi{10.3354/cr019193}. #' #' Hammel, K. and Kennel, M. (2001) #' Charakterisierung und Analyse der Wasserverfügbarkeit und des #' Wasserhaushalts von Waldstandorten in Bayern mit dem Simulationsmodell #' BROOK90. #' \emph{Forstliche Forschungsberichte München}. #' #' Janssen, W. (2009) #' Definition des Vegetationsanfanges. #' \emph{Internal Report, Deutscher Wetterdienst, Abteilung Agrarmeteorologie}. #' #' Menzel, A. (1997) #' Phänologie von Waldbäumen unter sich ändernden Klimabedingungen - #' Auswertung der Beobachtungen in den Internationalen Phänologischen Gärten #' und Möglichkeiten der Modellierung von Phänodaten. #' \emph{Forstliche Forschungsberichte München}. #' #' von Wilpert, K. (1990) #' Die Jahrringstruktur von Fichten in Abhängigkeit vom Bodenwasserhaushalt #' auf Pseudogley und Parabraunerde: Ein Methodenkonzept zur Erfassung #' standortsspezifischer Wasserstreßdispostion. #' \emph{Freiburger Bodenkundliche Abhandlungen}. #' #' Walther, A. and Linderholm, H. W. (2006) #' A comparison of growing season indices for the Greater Baltic Area. #' \emph{International Journal of Biometeorology}, \bold{51}(2), 107--118. #' \doi{10.1007/s00484-006-0048-5}. #' #' Zhang, X., Alexander, L., Hegerl, G. C., Jones, P., Tank, A. K., #' Peterson, T. C., Trewin, B. and Zwiers, F. W. (2011) #' Indices for monitoring changes in extremes based on daily temperature and #' precipitation data. #' \emph{Wiley Interdisciplinary Reviews: Climate Change}, \bold{2}(6), 851--870. #' \doi{10.1002/wcc.147}. #' #' @examples #' data(goe) #' vegperiod(dates=goe$date, Tavg=goe$t, #' start.method="Menzel", end.method="vonWilpert", #' species="Picea abies (frueh)", est.prev=5) #' #' # take chill days from first year, which is then dropped #' vegperiod(dates=goe$date, Tavg=goe$t, start="Menzel", end="vonWilpert", #' species="Picea abies (frueh)", est.prev=0) #' #' # add column with sum of day degrees in vegetation periods #' vegperiod(dates=goe$date, Tavg=goe$t, Tsum.out=TRUE, #' start="StdMeteo", end="StdMeteo") #' @md #' @export vegperiod <- function(dates, Tavg, start.method, end.method, Tsum.out=FALSE, Tsum.crit=0, species=NULL, est.prev=0, check.data=TRUE){ # Checks #---------------------------------------------------------------------------- start.method <- match.arg(start.method, choices=c('Menzel', 'StdMeteo', 'ETCCDI', 'Ribes uva-crispa')) end.method <- match.arg(end.method, choices=c('vonWilpert', 'LWF-BROOK90', 'NuskeAlbert', 'StdMeteo', 'ETCCDI')) if(start.method == 'Menzel'){ possible.species <- c("Larix decidua", "Picea abies (frueh)", "Picea abies (spaet)", "Picea abies (noerdl.)", "Picea omorika", "Pinus sylvestris", "Betula pubescens", "Quercus robur", "Quercus petraea", "Fagus sylvatica") if(is.null(species)) stop(paste0("If start.method='Menzel', species must be one of '", paste(possible.species, collapse="', '"), "'.")) species <- match.arg(species, choices=possible.species) } if(length(dates) != length(Tavg)) stop("The arguments dates and Tavg must be of same length!") # are the temperatures sound if(isTRUE(check.data)){ minimax <- range(Tavg) if(minimax[1] < -35 | minimax[2] > 40) stop("Your input temperature data exceeds the plausible range of -35 to +40\u00b0C.\n", "You may want to double check your data. ", "If you still want to use the given data, set 'check.data' to FALSE") } if(!inherits(dates, "Date")){ tryCatch(dates <- as.Date(dates), error=function(c) stop(paste("'dates' could not be coerced to", "class Date by as.Date(dates)."), call.=FALSE) ) } # set up the workhorse data.frame df <- data.frame(year = as.integer(format(dates, "%Y")), month = as.integer(format(dates, "%m")), DOY = as.integer(format(dates, "%j")), Tavg) rm(dates, Tavg) # determine leap years years <- unique(df$year) leap <- (years %% 4 == 0 & years %% 100 != 0) | years %% 400 == 0 # est.prev in valid range? # set to a high value if not Menzel if(start.method == 'Menzel'){ est.prev <- as.integer(est.prev) if(est.prev < 0 || est.prev > length(years)) stop("est.prev must be >= 0 and <= number of years.") if(est.prev == 0 && length(years) == 1) stop(paste("It's not possible to use previous year's chill days", "(est.prev=0) if only one year is provided.", "Either set est.prev=1 or provide more years.")) } else { est.prev <- 999 } # Do the provided years have the correct length (considering leap years)? # last year only till October 5th (DOY=279) needed if(est.prev == 0){ # Menzel: first year discarded -> only Nov+Dec of first year needed year.length <- c(61, 365 + leap[c(-1, -length(leap))], 279) } else { # full first year required # either not Menzel or guesstimate first year's NovDecCD from previous yrs year.length <- c(365 + leap[-length(leap)], 279) } if(!all(tapply(df$DOY, df$year, FUN=length) >= year.length)) stop("Not all years in 'dates' have expected length.") if(est.prev == 0 && length(df[df$year == years[1] & df$month >= 11, "DOY"]) != 61) stop("First year must at least contain full November & December") # calculating start and end #---------------------------------------------------------------------------- start <- switch(start.method, 'Menzel' = .start_menzel(df=df, est.prev=est.prev, species=species), 'StdMeteo' = , 'ETCCDI' = .start_std_meteo(df), 'Ribes uva-crispa' = .start_ribes(df)) # if first year only used for getting previous cold days -> drop it now if(est.prev == 0){ df <- df[df$year != years[1], ] years <- years[-1] } end <- switch(end.method, 'vonWilpert' = .end_vonWilpert(df), 'LWF-BROOK90' = .end_LWF_BROOK90(df), 'NuskeAlbert' = .end_NuskeAlbert(df, start), 'StdMeteo' = , 'ETCCDI' = .end_std_meteo(df)) # collect results #---------------------------------------------------------------------------- # if indicated calculate day degrees in vegperiod also res <- data.frame(year=years, start=start, end=end) seq_len if(Tsum.out){ res$Tsum <- numeric(nrow(res)) for(i in seq_along(res$Tsum)){ res$Tsum[i] <- sum(df$Tavg[df$year == years[i] & df$DOY >= start[i] & df$DOY <= end[i] & df$Tavg > Tsum.crit]) } } return(res) }
/scratch/gouwar.j/cran-all/cranData/vegperiod/R/vegperiod.R
# download of list of stations works ------------------------------------------ # don't run download tests on cran, travis, appveyor if(at_home()){ # Structure # . # ├── daily # │ ├── climate # │ │ ├── historic # │ │ └── recent # │ └── precip # │ ├── historic # │ └── recent # └── monthly # ├── climate # │ ├── historic # │ └── recent # └── precip # ├── historic # └── recent # Test some of the possible lists not all. # Column widths, and thus parsing, is different for daily and monthly lists. # All monthly station lists have floating point elev. # A data.frame with 8 columns ist constructed during reading/parsing. # If parsing went well, the columns should have proper types. # DAILY ===================================================================== # daily climate recent ------------------------------------------------------ expect_silent(stations <- read.DWDstations()) expect_true(is.data.frame(stations)) expect_true(length(stations) == 8) expect_true(nrow(stations) > 1000) expect_true(is.integer(stations$id)) expect_true(inherits(stations$from, "Date")) expect_true(inherits(stations$to, "Date")) expect_true(is.integer(stations$elev)) expect_true(is.numeric(stations$lat)) expect_true(is.numeric(stations$long)) # daily climate historic ---------------------------------------------------- expect_silent(stations <- read.DWDstations(period='historic')) expect_true(is.data.frame(stations)) expect_true(length(stations) == 8) expect_true(nrow(stations) > 1000) expect_true(is.integer(stations$id)) expect_true(inherits(stations$from, "Date")) expect_true(inherits(stations$to, "Date")) expect_true(is.integer(stations$elev)) expect_true(is.numeric(stations$lat)) expect_true(is.numeric(stations$long)) # daily precip recent ------------------------------------------------------- expect_silent(precip <- read.DWDstations(type='precip')) expect_true(is.data.frame(precip)) expect_true(length(precip) == 8) expect_true(nrow(precip) > 3000) expect_true(is.integer(precip$id)) expect_true(inherits(precip$from, "Date")) expect_true(inherits(precip$to, "Date")) expect_true(is.integer(precip$elev)) expect_true(is.numeric(precip$lat)) expect_true(is.numeric(precip$long)) # MONTHLY =================================================================== # monthly climate recent ---------------------------------------------------- expect_silent(stations <- read.DWDstations(resolution='monthly')) expect_true(is.data.frame(stations)) expect_true(length(stations) == 8) expect_true(nrow(stations) > 1000) expect_true(is.integer(stations$id)) expect_true(inherits(stations$from, "Date")) expect_true(inherits(stations$to, "Date")) expect_true(is.integer(stations$elev)) expect_true(is.numeric(stations$lat)) expect_true(is.numeric(stations$long)) # monthly precip historic --------------------------------------------------- expect_silent(precip <- read.DWDstations(type='precip', period='historic', resolution='monthly')) expect_true(is.data.frame(precip)) expect_true(length(precip) == 8) expect_true(nrow(precip) > 3000) expect_true(is.integer(precip$id)) expect_true(inherits(precip$from, "Date")) expect_true(inherits(precip$to, "Date")) expect_true(is.integer(precip$elev)) expect_true(is.numeric(precip$lat)) expect_true(is.numeric(precip$long)) } # download of data works ------------------------------------------------------ # don't run download tests on cran, travis, appveyor if(at_home()){ # fetch last 500 days worth of data from station Göttingen ------------------ expect_silent(clim <- read.DWDdata(id=1691, quiet=TRUE)) expect_true(file.exists(file.path(tempdir(), "tageswerte_KL_01691_akt.zip"))) expect_true(is.data.frame(clim)) expect_true(length(clim) == 18) expect_true(nrow(clim) >= 550) expect_true(is.integer(clim$STATIONS_ID)) expect_equal(unique(clim$STATIONS_ID), 1691L) expect_true(inherits(clim$MESS_DATUM, "Date")) expect_true(is.integer(clim$QN_3)) expect_true(is.numeric(clim$RSK)) expect_true(is.integer(clim$RSKF)) expect_true(is.numeric(clim$TMK)) # download monthly climate data from 1270 expect_silent(clim <- read.DWDdata(id = 1270, type="climate", period="recent", resolution="monthly", quiet=TRUE)) expect_true(file.exists(file.path(tempdir(), "monatswerte_KL_01270_akt.zip"))) expect_true(is.data.frame(clim)) expect_true(length(clim) == 16) expect_true(nrow(clim) >= 17) expect_true(is.integer(clim$STATIONS_ID)) expect_equal(unique(clim$STATIONS_ID), 1270L) expect_true(inherits(clim$MESS_DATUM_BEGINN, "Date")) expect_true(inherits(clim$MESS_DATUM_ENDE, "Date")) expect_true(is.integer(clim$QN_4)) expect_true(is.numeric(clim$MO_TN)) expect_true(is.numeric(clim$MO_RR)) # download historical data from the Brocken if curl available --------------- if(requireNamespace("curl", quietly=TRUE)){ expect_silent(climb <- read.DWDdata(722, period='historical', quiet=TRUE)) expect_true(is.data.frame(climb)) expect_true(length(climb) == 18) expect_true(nrow(climb) >= 550) expect_true(is.integer(climb$STATIONS_ID)) expect_equal(unique(climb$STATIONS_ID), 722L) expect_true(inherits(climb$MESS_DATUM, "Date")) expect_true(is.integer(climb$QN_3)) expect_true(is.numeric(climb$RSK)) expect_true(is.integer(climb$RSKF)) expect_true(is.numeric(climb$TMK)) } }
/scratch/gouwar.j/cran-all/cranData/vegperiod/inst/tinytest/test_DWD_stuff.R
#-- set up data.frame for tests --------------------------------------------- data(goe) df <- data.frame(year = as.integer(format(goe$date, "%Y")), month = as.integer(format(goe$date, "%m")), DOY = as.integer(format(goe$date, "%j")), Tavg=goe$t) #-- von Wilpert -------------------------------------------------------------- # canonical expect_equal(vegperiod:::.end_vonWilpert(df, Treshold=10, LastDOY=279), c(274L, 279L, 279L, 279L, 279L, 271L, 279L, 279L, 279L, 279L)) # change threshold expect_equal(vegperiod:::.end_vonWilpert(df, Treshold=7, LastDOY=279), c(279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L)) expect_equal(vegperiod:::.end_vonWilpert(df, Treshold=15, LastDOY=279), c(262L, 255L, 278L, 252L, 273L, 255L, 252L, 277L, 259L, 266L)) # change LastDOY expect_equal(vegperiod:::.end_vonWilpert(df, Treshold=10, LastDOY=200), c(200L, 200L, 200L, 200L, 200L, 200L, 200L, 200L, 200L, 200L)) expect_equal(vegperiod:::.end_vonWilpert(df, Treshold=10, LastDOY=300), c(274L, 300L, 292L, 300L, 300L, 271L, 300L, 291L, 295L, 300L)) #-- LWF-BROOK90 -------------------------------------------------------------- # canonical expect_equal(vegperiod:::.end_LWF_BROOK90(df, Tmin=10, LastDOY=279), c(277L, 279L, 279L, 279L, 279L, 274L, 279L, 279L, 279L, 279L)) # change threshold expect_equal(vegperiod:::.end_LWF_BROOK90(df, Tmin=7, LastDOY=279), c(279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L)) expect_equal(vegperiod:::.end_LWF_BROOK90(df, Tmin=15, LastDOY=279), c(265L, 258L, 279L, 255L, 276L, 269L, 255L, 279L, 262L, 269L)) # change LastDOY expect_equal(vegperiod:::.end_LWF_BROOK90(df, Tmin=10, LastDOY=200), c(200L, 200L, 200L, 200L, 200L, 200L, 200L, 200L, 200L, 200L)) expect_equal(vegperiod:::.end_LWF_BROOK90(df, Tmin=10, LastDOY=300), c(288L, 300L, 295L, 300L, 300L, 274L, 300L, 294L, 298L, 300L)) #-- Nuske-Albert ------------------------------------------------------------- vegstart <- list( # results of .start_menzel() with est.prev=3 c( 96L, 102L, 102L, 88L, 100L, 101L, 105L, 102L, 93L, 95L), c(119L, 127L, 125L, 116L, 124L, 126L, 124L, 125L, 115L, 116L), c(127L, 134L, 131L, 125L, 131L, 135L, 132L, 130L, 121L, 121L), c(130L, 134L, 133L, 125L, 133L, 137L, 136L, 133L, 123L, 123L), c(140L, 140L, 141L, 132L, 139L, 147L, 142L, 142L, 133L, 128L), c(133L, 137L, 135L, 128L, 137L, 140L, 138L, 135L, 126L, 125L), c(105L, 110L, 112L, 96L, 106L, 108L, 113L, 112L, 98L, 108L), c(118L, 126L, 125L, 115L, 124L, 125L, 124L, 124L, 115L, 116L), c(119L, 126L, 126L, 116L, 125L, 126L, 125L, 125L, 116L, 117L), c(127L, 133L, 128L, 124L, 128L, 133L, 126L, 128L, 119L, 120L) ) truth <- list( c(278L, 278L, 278L, 279L, 278L, 278L, 278L, 279L, 278L, 278L), c(278L, 278L, 278L, 279L, 278L, 278L, 278L, 279L, 278L, 278L), c(278L, 278L, 278L, 279L, 278L, 278L, 278L, 279L, 278L, 278L), c(278L, 278L, 278L, 279L, 278L, 278L, 278L, 279L, 278L, 278L), c(278L, 278L, 278L, 279L, 278L, 278L, 278L, 279L, 278L, 278L), c(278L, 278L, 278L, 279L, 278L, 278L, 278L, 279L, 278L, 278L), c(278L, 278L, 278L, 279L, 278L, 278L, 278L, 279L, 278L, 278L), c(278L, 278L, 278L, 279L, 278L, 278L, 278L, 279L, 278L, 278L), c(278L, 278L, 278L, 279L, 278L, 278L, 278L, 279L, 278L, 278L), c(278L, 278L, 278L, 279L, 278L, 278L, 278L, 279L, 278L, 278L) ) for(i in seq_along(vegstart)){ expect_equal(vegperiod:::.end_NuskeAlbert(df, start=vegstart[[i]], Tmin=5), truth[[i]]) } # change start expect_equal(vegperiod:::.end_NuskeAlbert(df, start = 200, Tmin = 5), c(278L, 278L, 278L, 279L, 278L, 278L, 278L, 279L, 278L, 278L)) expect_equal(vegperiod:::.end_NuskeAlbert(df, start = 100, Tmin = 5), c(278L, 278L, 278L, 279L, 278L, 278L, 278L, 279L, 278L, 278L)) expect_equal(vegperiod:::.end_NuskeAlbert(df, start = NA, Tmin = 5), c(278L, 278L, 278L, 279L, 278L, 278L, 278L, 279L, 278L, 278L)) # change Tmin expect_equal(vegperiod:::.end_NuskeAlbert(df, start = NA, Tmin = 2), c(278L, 278L, 278L, 279L, 278L, 278L, 278L, 279L, 278L, 278L)) expect_equal(vegperiod:::.end_NuskeAlbert(df, start = NA, Tmin = 10), c(274L, 278L, 278L, 279L, 278L, 271L, 278L, 279L, 278L, 278L)) expect_equal(vegperiod:::.end_NuskeAlbert(df, start = NA, Tmin = 15), c(186L, 255L, 237L, 252L, 218L, 186L, 217L, 236L, 187L, 193L)) #-- StdMeteo ----------------------------------------------------------------- # canonical expect_equal(vegperiod:::.end_std_meteo(df, Tmin = 5), c(347L, 329L, 323L, 333L, 327L, 308L, 354L, 322L, 321L, 356L)) # low Tmin expect_equal(vegperiod:::.end_std_meteo(df, Tmin = 3), c(348L, 348L, 324L, 347L, 327L, 365L, 357L, 323L, 326L, 357L)) # high Tmin expect_equal(vegperiod:::.end_std_meteo(df, Tmin = 10), c(288L,310L, 293L, 302L, 283L, 279L, 288L, 292L, 280L, 314L)) #-- clean up ---------------------------------------------------------------- rm(df)
/scratch/gouwar.j/cran-all/cranData/vegperiod/inst/tinytest/test_veg_ends.R
#-- set up data.frame for tests --------------------------------------------- data(goe) df <- data.frame(year = as.integer(format(goe$date, "%Y")), month = as.integer(format(goe$date, "%m")), DOY = as.integer(format(goe$date, "%j")), Tavg=goe$t) #-- Menzel ------------------------------------------------------------------- spec <- c("Larix decidua", "Picea abies (frueh)", "Picea abies (spaet)", "Picea abies (noerdl.)", "Picea omorika", "Pinus sylvestris", "Betula pubescens", "Quercus robur", "Quercus petraea", "Fagus sylvatica") true0 <- list(c(102L, 102L, 88L, 100L, 101L, 105L, 102L, 93L, 95L), c(127L, 125L, 116L, 124L, 126L, 124L, 125L, 115L, 116L), c(134L, 131L, 125L, 131L, 135L, 132L, 130L, 121L, 121L), c(134L, 133L, 125L, 133L, 137L, 136L, 133L, 123L, 123L), c(140L, 141L, 132L, 139L, 147L, 142L, 142L, 133L, 128L), c(137L, 135L, 128L, 137L, 140L, 138L, 135L, 126L, 125L), c(110L, 112L, 96L, 106L, 108L, 113L, 112L, 98L, 108L), c(126L, 125L, 115L, 124L, 125L, 124L, 124L, 115L, 116L), c(126L, 126L, 116L, 125L, 126L, 125L, 125L, 116L, 117L), c(133L, 128L, 124L, 128L, 133L, 126L, 128L, 119L, 120L) ) for(i in seq_along(spec)){ expect_equal(vegperiod:::.start_menzel(df, est.prev=0, species=spec[i]), true0[[i]]) } true1 <- list( c( 96L, 102L, 102L, 88L, 100L, 101L, 105L, 102L, 93L, 95L), c(119L, 127L, 125L, 116L, 124L, 126L, 124L, 125L, 115L, 116L), c(127L, 134L, 131L, 125L, 131L, 135L, 132L, 130L, 121L, 121L), c(130L, 134L, 133L, 125L, 133L, 137L, 136L, 133L, 123L, 123L), c(140L, 140L, 141L, 132L, 139L, 147L, 142L, 142L, 133L, 128L), c(132L, 137L, 135L, 128L, 137L, 140L, 138L, 135L, 126L, 125L), c(104L, 110L, 112L, 96L, 106L, 108L, 113L, 112L, 98L, 108L), c(118L, 126L, 125L, 115L, 124L, 125L, 124L, 124L, 115L, 116L), c(119L, 126L, 126L, 116L, 125L, 126L, 125L, 125L, 116L, 117L), c(126L, 133L, 128L, 124L, 128L, 133L, 126L, 128L, 119L, 120L) ) for(i in seq_along(spec)){ expect_equal(vegperiod:::.start_menzel(df, est.prev=1, species=spec[i]), true1[[i]]) } true3 <- list( c( 96L, 102L, 102L, 88L, 100L, 101L, 105L, 102L, 93L, 95L), c(119L, 127L, 125L, 116L, 124L, 126L, 124L, 125L, 115L, 116L), c(127L, 134L, 131L, 125L, 131L, 135L, 132L, 130L, 121L, 121L), c(130L, 134L, 133L, 125L, 133L, 137L, 136L, 133L, 123L, 123L), c(140L, 140L, 141L, 132L, 139L, 147L, 142L, 142L, 133L, 128L), c(133L, 137L, 135L, 128L, 137L, 140L, 138L, 135L, 126L, 125L), c(105L, 110L, 112L, 96L, 106L, 108L, 113L, 112L, 98L, 108L), c(118L, 126L, 125L, 115L, 124L, 125L, 124L, 124L, 115L, 116L), c(119L, 126L, 126L, 116L, 125L, 126L, 125L, 125L, 116L, 117L), c(127L, 133L, 128L, 124L, 128L, 133L, 126L, 128L, 119L, 120L) ) for(i in seq_along(spec)){ expect_equal(vegperiod:::.start_menzel(df, est.prev=3, species=spec[i]), true3[[i]]) } true10 <- list( c( 96L, 102L, 102L, 88L, 100L, 101L, 105L, 102L, 93L, 95L), c(119L, 127L, 125L, 116L, 124L, 126L, 124L, 125L, 115L, 116L), c(128L, 134L, 131L, 125L, 131L, 135L, 132L, 130L, 121L, 121L), c(131L, 134L, 133L, 125L, 133L, 137L, 136L, 133L, 123L, 123L), c(140L, 140L, 141L, 132L, 139L, 147L, 142L, 142L, 133L, 128L), c(133L, 137L, 135L, 128L, 137L, 140L, 138L, 135L, 126L, 125L), c(106L, 110L, 112L, 96L, 106L, 108L, 113L, 112L, 98L, 108L), c(119L, 126L, 125L, 115L, 124L, 125L, 124L, 124L, 115L, 116L), c(120L, 126L, 126L, 116L, 125L, 126L, 125L, 125L, 116L, 117L), c(128L, 133L, 128L, 124L, 128L, 133L, 126L, 128L, 119L, 120L) ) for(i in seq_along(spec)){ expect_equal(vegperiod:::.start_menzel(df, est.prev=10, species=spec[i]), true10[[i]]) } #-- StdMeteo ---------------------------------------------------------------- expect_equal(vegperiod:::.start_std_meteo(df), c(34L, 36L, 65L, 38L, 69L, 18L, 84L, 64L, 48L, 88L)) expect_equal(vegperiod:::.start_std_meteo(df, Tmin = 3), c(6L, 36L, 10L, 23L, 19L, 17L, 6L, 22L, 12L, 35L)) expect_equal(vegperiod:::.start_std_meteo(df, Tmin = 7), c(34L, 132L, 97L, 83L, 106L, 83L, 98L, 96L, 48L, 112L)) expect_equal(vegperiod:::.start_std_meteo(df, Tmin = 10), c(135L, 133L, 120L, 127L, 135L, 142L, 141L, 119L, 93L, 122L)) expect_equal(vegperiod:::.start_std_meteo(df, Tmin = 0), c(6L, 19L, 10L, 6L, 6L, 16L, 6L, 20L, 6L, 8L)) expect_equal(vegperiod:::.start_std_meteo(df, Tmin = 3.1415), c(6L, 36L, 10L, 23L, 19L, 17L, 6L, 22L, 12L, 35L)) #-- Ribes ------------------------------------------------------------------- expect_equal(vegperiod:::.start_ribes(df), c(82L, 79L, 87L, 74L, 77L, 88L, 89L, 86L, 76L, 83L)) #-- clean up ---------------------------------------------------------------- rm(df)
/scratch/gouwar.j/cran-all/cranData/vegperiod/inst/tinytest/test_veg_starts.R
data(goe) # vegperiod throws errors expect_equal(vegperiod(dates=goe$date, Tavg=goe$t, start.method="Menzel", end.method="vonWilpert", species="Picea abies (spaet)", est.prev=0, Tsum.out=FALSE), data.frame( year = 2002:2010, start = c(134L, 131L, 125L, 131L, 135L, 132L, 130L, 121L, 121L), end = c(279L, 279L, 279L, 279L, 271L, 279L, 279L, 279L, 279L) ) ) # vegperiod standard works expect_equal(vegperiod(dates=goe$date, Tavg=goe$t, start.method="Menzel", end.method="vonWilpert", species="Picea abies (spaet)", est.prev=0, Tsum.out=FALSE), data.frame( year = 2002:2010, start = c(134L, 131L, 125L, 131L, 135L, 132L, 130L, 121L, 121L), end = c(279L, 279L, 279L, 279L, 271L, 279L, 279L, 279L, 279L) ) ) # temperature is sound (not multiplied by 10) # problem showed in this case by time series > 26 years # example data set with 30 yrs from Ronald Bialozyt load('./rb30.RData') expect_error( vegperiod(dates=rb30$date, Tavg=rb30$tm, start.method="Menzel", end.method="vonWilpert", species="Picea abies (spaet)", est.prev=3, Tsum.out=FALSE), "Your input temperature data exceeds the plausible range") expect_equal( vegperiod(dates=rb30$date, Tavg=rb30$tm/10, start.method="Menzel", end.method="vonWilpert", species="Picea abies (spaet)", est.prev=3, Tsum.out=FALSE), data.frame( year = 2021:2050, start = c(134L, 122L, 125L, 137L, 133L, 127L, 121L, 123L, 132L, 120L, 132L, 134L, 116L, 132L, 107L, 119L, 119L, 120L, 120L, 123L, 123L, 131L, 128L, 120L, 130L, 117L, 129L, 119L, 125L, 120L), end = c(279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L) ) ) # there should be an error with shorter times series as well rb10 <- rb30[rb30$date <= as.Date('2030-12-31'), ] expect_error( vegperiod(dates=rb10$date, Tavg=rb10$tm, start.method="Menzel", end.method="vonWilpert", species="Picea abies (spaet)", est.prev=3, Tsum.out=FALSE), "Your input temperature data exceeds the plausible range") expect_equal( vegperiod(dates=rb10$date, Tavg=rb10$tm/10, start.method="Menzel", end.method="vonWilpert", species="Picea abies (spaet)", est.prev=3, Tsum.out=FALSE), data.frame( year = 2021:2030, start = c(134L, 122L, 125L, 137L, 133L, 127L, 121L, 123L, 132L, 120L), end = c(279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L, 279L) ) ) # Bug report by S. Timmke # StdMeteo did report 0 if it did not find an end (eg. Magdeburg in 2006) # now it returns last DOY in that case load("./md_2006.RData") expect_equal( vegperiod(dates=md_2006$date, Tavg=md_2006$t, start="StdMeteo", end="StdMeteo", Tsum.out=TRUE), data.frame( year = 2005:2007, start = c(9L, 89L, 8L), end = c(324L, 365L, 319L), Tsum = c(3505.5, 3915.6, 3844.2) ) )
/scratch/gouwar.j/cran-all/cranData/vegperiod/inst/tinytest/test_veg_vegperiod.R
#' @name Extract #' @aliases $ $,vegtable-method #' #' @title Select or replace elements in objects #' #' @description #' Methods for quick access to slot `header` of [vegtable-class] objects or for #' access to single cover scales in [coverconvert-class] objects. #' Also replacement methods are implemented. #' #' @param x Object of class [vegtable-class]. #' @param ... Further arguments passed to or from other methods. #' @param name A name to access. #' @param i,j Indices for access. #' @param drop A logical value passed to [Extract]. #' @param value Either a vectors or a list, used as replacement. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @examples #' ## Range of latitude values in database #' range(Kenya_veg$LATITUDE) #' #' ## Summary of countries #' summary(Kenya_veg$COUNTRY) #' summary(droplevels(Kenya_veg$COUNTRY)) #' #' ## First 5 samples #' summary(Kenya_veg[1:5, ]) #' @rdname Extract #' #' @exportMethod $ setMethod("$", signature(x = "vegtable"), function(x, name) { return(x@header[[name]]) }) #' @rdname Extract #' #' @aliases $<- $<-,vegtable-method #' #' @exportMethod $<- #' setReplaceMethod("$", signature(x = "vegtable"), function(x, name, value) { x@header[[name]] <- value return(x) }) #' @rdname Extract #' @aliases $,coverconvert-method setMethod( "$", signature(x = "coverconvert"), function(x, name) { x@value <- x@value[name] x@conversion <- x@conversion[name] return(x) } ) #' @rdname Extract #' @aliases [ [,coverconvert,ANY,ANY,ANY-method [,coverconvert-method #' @exportMethod [ setMethod("[", signature(x = "coverconvert"), function(x, i) { x@value <- x@value[i] x@conversion <- x@conversion[i] return(x) }) #' @rdname Extract #' @aliases $<-,coverconvert,coverconvert-method setReplaceMethod( "$", signature(x = "coverconvert", value = "coverconvert"), function(x, name, value) { if (length(names(value)) > 1) { warning(paste0( "Multiple cover scales detected in 'value'. ", "Only the first ('", names(value)[1], "') will be inserted." )) } x@value[[name]] <- value@value[[1]] x@conversion[[name]] <- value@conversion[[1]] return(x) } ) #' @rdname Extract #' @aliases [ [,vegtable,ANY,ANY,ANY-method [,vegtable-method #' @exportMethod [ setMethod("[", signature(x = "vegtable"), function(x, i, j, ..., drop = FALSE) { if (missing(i)) i <- TRUE if (missing(j)) j <- TRUE # Resolving problems with NAs if (is.logical(i)) i[is.na(i)] <- FALSE else i <- na.omit(i) if (is.logical(j)) i[is.na(j)] <- FALSE else j <- na.omit(j) x@header <- x@header[i, j, drop] # Subset on samples x@samples <- x@samples[x@samples$ReleveID %in% x@header$ReleveID, ] # Subset on species (same procedure as in import_vegtable) x <- clean(x) # Output return(x) }) #' @rdname Extract #' @aliases [<- [<-,vegtable-method #' @exportMethod [<- setReplaceMethod("[", signature(x = "vegtable"), function(x, i, j, value) { if (missing(i)) i <- TRUE if (missing(j)) j <- TRUE # Resolving problems with NAs if (is.logical(i)) i[is.na(i)] <- FALSE else i <- na.omit(i) if (is.logical(j)) i[is.na(j)] <- FALSE else j <- na.omit(j) x@header[i, j] <- value return(x) })
/scratch/gouwar.j/cran-all/cranData/vegtable/R/Extract.R
#' @name Kenya_veg-data #' @aliases Kenya_veg #' @docType data #' #' @title Vegetation-plots from Kenya #' #' @description #' A subset of \url{http://www.givd.info/ID/AF-00-006SWEA-Dataveg} including #' five references providing plots collected in Kenya. #' #' @format An object of class [vegtable-class]. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} and Michael Curran #' \email{currmi01@@gmail.com} #' #' @references \bold{Bronner G (1990).} \emph{Vegetation and land use in the #' Mathews Range area, Samburu-District, Kenya}. J. Cramer, Berlin. #' #' \bold{Bussmann RW (1994).} \emph{The forests of Mount Kenya -- vegetation, #' ecology, destruction and management of a tropical mountain forest #' ecosystem}. Universität Bayreuth. #' #' \bold{Bussmann RW (2002).} Islands in the desert -- forest vegetation of #' Kenya's smaller mountains and highland areas. \emph{Journal of East African #' Natural History} 91: 27--79. #' #' \bold{Fujiwara K, Furukawa T, Kiboi SK, Mathenge S, Mutiso P, Hayashi H, #' Meguro S (2014).} Forest types and biodiversity around the Great Rift Valley #' in Kenya. \emph{Contributii Botanice} 49: 143--178. #' #' \bold{Schmitt K (1991).} \emph{The vegetation of the Aberdare National Park #' Kenya}. Universitätsverlag Wagner, Innsbruck. #' #' @source \url{http://www.givd.info/ID/AF-00-006} #' #' @examples #' summary(Kenya_veg) "Kenya_veg"
/scratch/gouwar.j/cran-all/cranData/vegtable/R/Kenya_veg-data.R
# NULLing objects TaxonUsageID <- NULL UsageIDs <- NULL shaker <- NULL
/scratch/gouwar.j/cran-all/cranData/vegtable/R/NULLing.R
#' @name Wetlands-data #' @aliases Wetlands Wetlands_veg #' @docType data #' #' @title Vegetation-plots from Tanzania #' #' @description #' A subset of \url{http://www.givd.info/ID/AF-00-006SWEA-Dataveg} with plots #' sampled in Tanzania. #' #' @format #' An object of class [shaker-class] (`Wetlands`) and the respective companion #' as [vegtable-class] object (`Wetlands_veg`). #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @references #' \bold{Alvarez M (2017).} Classification of aquatic and #' semi-aquatic vegetation in two East African sites: Cocktail definitions and #' syntaxonomy. \emph{Phytocoenologia}. #' #' @source \url{http://www.givd.info/ID/AF-00-006}. #' #' @examples #' summary(Wetlands) #' summary(Wetlands_veg) "Wetlands"
/scratch/gouwar.j/cran-all/cranData/vegtable/R/Wetlands-data.R
#' @name add_releves #' #' @title Merge relevés from data frames into vegtable objects #' #' @description #' Addition of plot observations into existing data sets may implicate merging #' data frames with [vegtable-class] objects. #' #' Since this function will only update slots **samples** and **header**, #' consistency with slots **layers**, **relations** and **species** have to be #' checked and accordingly updated in advance. #' #' @param vegtable An object of class [vegtable-class]. #' @param releves A data frame including plot observations to be added into #' `vegtable`. #' @param value A data frame containing new plot observations. I is passed to #' parameter 'releves' by the replace method. #' @param header A data frame (optional) including header information for plots. #' @param abundance A character value (or vector of length 2) indicating the #' names of abundance variable in `vegtable`. #' @param split_string Character value used to split mixed abundance codes. #' @param usage_ids Logical value indicating whether species are as taxon usage #' ids (integers) or names in `releves`. #' @param layers Logical value indicating whether layers are included in #' `releves` or not. #' @param layers_var Name of the layer variable in `vegtable`. #' @param format Character value indicating input format of `releves` (either #' `"crosstable"` or `"databaselist"`). #' @param preserve_ids A logical value, whether IDs in input data set should #' used as `ReleveID` or not. Those IDs have to be integers and if one #' of those already exists in `vegtable`, an error will be retrieved. #' @param ... Further arguments passed to function [cross2db()] (i.e. #' `na_strings`). #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @seealso [cross2db()] #' #' @rdname add_releves #' #' @exportMethod add_releves #' setGeneric( "add_releves", function(vegtable, releves, ...) { standardGeneric("add_releves") } ) #' @rdname add_releves #' #' @aliases add_releves,vegtable,data.frame-method #' setMethod( "add_releves", signature( vegtable = "vegtable", releves = "data.frame" ), function(vegtable, releves, header, abundance, split_string, usage_ids = FALSE, layers = FALSE, layers_var, format = "crosstable", preserve_ids = FALSE, ...) { # Step 1: Make database list, if necessary format <- pmatch(tolower(format), c("crosstable", "databaselist")) if (!format %in% c(1:2)) { stop("Non valid value for 'format'.") } if (format == 1) { releves <- cross2db(releves, layers, ...) colnames(releves) <- replace_x( x = colnames(releves), old = c("plot", "species"), new = c("ReleveID", "TaxonUsageID") ) } message(paste("Imported records:", nrow(releves))) # Step 1: Recognize species if (!usage_ids & format == 1) { releves$TaxonUsageID <- match_names( releves$TaxonUsageID, vegtable@species )$TaxonUsageID } if (!usage_ids & format == 2) { if (!"TaxonName" %in% colnames(releves)) { stop(paste( "Colum 'TaxonName' is mandatory in 'releves'", "provided as database list", "with the option 'usage_ids = FALSE'." )) } releves$TaxonUsageID <- match_names( releves$TaxonName, vegtable@species )$TaxonUsageID # delete column TaxonName releves <- releves[, colnames(releves) != "TaxonName"] } message(paste( "Matched taxon usage names:", length(unique(releves$TaxonUsageID)) )) # TODO: Action needed if unmatched taxon names # Step 3: Check layers, if necessary # TODO: next code have to be tested for 'format = "databaselist"' if (layers) { if (format == 1) { colnames(releves) <- replace_x( x = colnames(releves), old = "layers", new = layers_var ) } # Add layers variables if (layers & (!layers_var %in% colnames(vegtable@samples))) { vegtable@samples[, layers_var] <- NA class(vegtable@samples[, layers_var]) <- class(releves[ , layers_var ]) } if (is.factor(vegtable@samples[, layers_var])) { releves[, layers_var] <- factor( paste(releves[, layers_var]), levels(vegtable@samples[, layers_var]) ) } else { class(releves[, layers_var]) <- class(vegtable@samples[ , layers_var ]) } # Check for the existence of layers in slot layers # Otherwise warn about missing table if ((layers_var %in% names(vegtable@layers)) & (any(!releves[, layers_var] %in% vegtable@layers[[layers_var]][ , layers_var ]))) { stop("Values of 'layers_var' missing in 'vegtable'") } if (!layers_var %in% names(vegtable@layers)) { warning(paste( "There is no table in slot 'layers' for", "'layers_var'." )) } } # Step 4: Reformat abundance (only for cross tables) if (format == 1) { if (length(abundance) == 2) { cover <- stri_split_fixed( releves[, ncol(releves)], split_string ) cover <- lapply(cover, function(x) { if (length(x) < 2) x <- c(x, NA) return(x) }) cover <- do.call(rbind, cover) releves[, ncol(releves)] <- cover[, 1] releves[, ncol(releves) + 1] <- cover[, 2] colnames(releves)[ncol(releves) - c(1, 0)] <- abundance } else { colnames(releves)[ncol(releves)] <- abundance } # Add missing abundance columns missing_ab <- abundance[!abundance %in% colnames(vegtable@samples)] if (length(missing_ab) > 0) { for (i in missing_ab) { vegtable@samples[, i] <- NA class(vegtable@samples[, i]) <- class(releves[, i]) } } # insert abundance for (i in abundance) { if (is.factor(vegtable@samples[, i])) { releves[, i] <- factor( paste(releves[, i]), levels(vegtable@samples[, i]) ) } else { class(releves[, i]) <- class(vegtable@samples[, i]) } } } # Step 5: Format header if (!missing(header)) { colnames(header)[1] <- "ReleveID" if (any(duplicated(header$ReleveID))) { stop("Duplicated plot names are not allowed.") } if (!all(releves$ReleveID %in% header$ReleveID)) { stop(paste( "Some plots in 'releves' are not included in", "'header'." )) } if (!all(header$ReleveID %in% releves$ReleveID)) { stop(paste( "Some plots in 'header' are not included in", "'releves'." )) } if (!all(colnames(header) %in% colnames(vegtable@header))) { stop(paste( "Some variables in 'header' are not yet", "included in 'vegtable'." )) } for (i in colnames(header)[-1]) { if (is.factor(vegtable@header[, i])) { header[, i] <- factor( paste(header[, i]), levels(vegtable@header[, i]) ) } else { class(header[, i]) <- class(vegtable@header[, i]) } } } else { header <- data.frame( ReleveID = unique(releves$ReleveID), stringsAsFactors = FALSE ) } # Step 6: Assembly vegtable # TODO: Added cover is not testing for presence of coverconvert if (!preserve_ids) { old_ReleveID <- header$ReleveID if (nrow(vegtable@header) > 0) { header$ReleveID <- max(vegtable$ReleveID) + 1:nrow(header) } else { header$ReleveID <- 1:nrow(header) } releves$ReleveID <- header$ReleveID[match( releves$ReleveID, old_ReleveID )] } else { if (any(header$ReleveID %in% vegtable$ReleveID)) { stop(paste( "Some IDs in 'releves' already exist in", "'vegtable' and cannot be preserved" )) } } message(paste0( "Imported relev\u00e9s: ", nrow(header), " (", min(header$ReleveID), " to ", max(header$ReleveID), ")" )) message(paste("Imported header variables:", ncol(header) - 1)) for (i in colnames(vegtable@header)) { if (!i %in% colnames(header)) header[, i] <- NA } if (nrow(vegtable@header) > 0) { vegtable@header <- do.call(rbind, list( vegtable@header, header[, colnames(vegtable@header)] )) } else { vegtable@header <- header } # in empty object add releves directly if (nrow(vegtable@samples) > 0) { for (i in colnames(vegtable@samples)) { if (!i %in% colnames(releves)) releves[, i] <- NA } vegtable@samples <- do.call(rbind, list( vegtable@samples, releves[, colnames(vegtable@samples)] )) } else { vegtable@samples <- releves } message("DONE!\n") return(vegtable) } ) #' @rdname add_releves #' #' @aliases add_releves<- #' #' @exportMethod add_releves<- #' setGeneric("add_releves<-", function(vegtable, ..., value) { standardGeneric("add_releves<-") }) #' @rdname add_releves #' #' @aliases add_releves<-,vegtable,data.frame-method #' setReplaceMethod( "add_releves", signature( vegtable = "vegtable", value = "data.frame" ), function(vegtable, ..., value) { return(add_releves(vegtable = vegtable, releves = value, ...)) } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/add_releves.R
#' @name aspect_conv-data #' @aliases aspect_conv #' @docType data #' #' @title Conversion of aspect classes to azimuth #' #' @description #' Conversion table required to transform values of aspect to azimuth in #' degrees. #' #' @format A numeric vector of values in degrees for the symbols used as names. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @examples #' aspect_conv[c("N", "S", "ENE", "SSW")] "aspect_conv"
/scratch/gouwar.j/cran-all/cranData/vegtable/R/aspect_conv-data.R
#' @name braun_blanquet-data #' @aliases braun_blanquet #' @docType data #' #' @title Conversion of Braun-Blanquet codes to cover percentage #' #' @description #' Cover values conversion as [coverconvert-class] object. #' #' Object of class [coverconvert-class] contains conversion tables #' usually from a categorical variable (a cover scale) to a numerical one #' (equivalent percentage cover value). #' Cover values are stored as range for each level in the scale (minimum and #' maximum cover value). #' #' @format An object of class \code{\linkS4class{coverconvert}}. #' #' @seealso [coverconvert-class] [cover_trans()] #' #' @examples #' names(braun_blanquet) #' summary(braun_blanquet) #' summary(braun_blanquet$b_bbds) "braun_blanquet"
/scratch/gouwar.j/cran-all/cranData/vegtable/R/braun_blanquet-data.R
#' @name clean #' #' @title Clean orphaned records in vegtable object #' #' @description #' Delete entries in slots `header` and `species` orphaned by manipulation of #' slots. #' #' Orphaned records generated by modifications in some slots may cause a loss #' on the validity of [vegtable-class] objects. #' This function should be applied to optimise the allocated size of a #' [vegtable-class] object, as well. Since running cleaning only #' once does not assure the deletion of all orphaned entries, it is recommended #' to run it at least twice. This repetition of cleaning is controlled by the #' argument `times`. #' #' @param object A [vegtable-class] object. #' @param times Numeric value indicating how many times should be the cleaning #' be repeated. #' @param ... Further arguments passed from or to other methods. #' @return A clean [vegtable-class] object. #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @examples #' ## Create an invalid object #' veg <- Kenya_veg #' veg@header <- veg@header[1:10, ] #' #' ## Resolve invalidity #' veg <- clean(veg) #' #' @rdname clean clean_once <- function(object) { # delete orphan species records object@samples <- object@samples[object@samples$ReleveID %in% object$ReleveID, , drop = FALSE] # delete layer entries missing in samples for (i in names(object@layers)) { object@layers[[i]] <- object@layers[[i]][object@layers[[i]][, i] %in% object@samples[, i], ] } # compare species and samples (delete observations # not included in species list) object@samples <- object@samples[object@samples$TaxonUsageID %in% object@species@taxonNames$TaxonUsageID, ] # delete header variables without data object@header <- object@header[, (colnames(object@header) == "ReleveID") | (!apply(object@header, 2, function(x) all(is.na(x)))), drop = FALSE] # delete samples variables without data object@samples <- object@samples[, (colnames(object@samples) %in% c("ReleveID", "TaxonUsageID")) | (!apply(object@samples, 2, function(x) all(is.na(x)))), drop = FALSE ] # delete orphaned relations object@relations <- object@relations[names(object@relations) %in% colnames(object@header)] # delete orphaned layers object@layers <- object@layers[names(object@layers) %in% colnames(object@samples)] # delete orphaned cover conversions object@coverconvert@value <- object@coverconvert@value[ names(object@coverconvert@value) %in% colnames(object@samples) ] object@coverconvert@conversion <- object@coverconvert@conversion[ names(object@coverconvert@conversion) %in% names(object@coverconvert@value) ] # output return(object) } #' @rdname clean #' #' @aliases clean,vegtable-method #' #' @exportMethod clean #' setMethod( "clean", signature(object = "vegtable"), function(object, times = 2, ...) { count <- 0 repeat { count <- count + 1 object <- clean_once(object) if (count == times) break } return(object) } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/clean.R
#' @name as #' @rdname coerce-methods #' #' @title Coerce objects to lists #' #' @description #' Coerce vegtable objects to a list with every slot as a component of the list. #' This way allows to explore content and solve problems when validity checks #' fail. #' #' Coercion is applied for different classes by vegtable. #' #' @param x An object to be coerced. #' @param ... further arguments passed from or to other methods. #' #' @return An object of class `list`. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @examples #' ## vegtable as list #' veg <- as(Kenya_veg, "list") #' names(veg) #' #' ## coverconvert as list #' as(Kenya_veg@coverconvert, "list") #' #' @aliases as.list,vegtable-method coerce,vegtable,list-method #' coerce,coverconvert,list-method #' #' @exportMethod as.list setMethod( "as.list", signature(x = "vegtable"), function(x, ...) { S4_to_list(x) } ) setAs("vegtable", "list", function(from) as.list(from)) #' @rdname coerce-methods #' @aliases as.list,coverconvert-method setMethod( "as.list", signature(x = "coverconvert"), function(x, ...) { # z <- S4_to_list(x) z <- list() for (i in names(x)) { z[[i]] <- data.frame( value = x@value[[i]], bottom = x@conversion[[i]][-(length(x@conversion[[i]]))], top = x@conversion[[i]][-1] ) for (j in seq_along(z[[i]]$value)) { if (z[[i]]$bottom[j] == z[[i]]$top[j]) { z[[i]]$bottom[j] <- z[[i]]$bottom[j - 1] } } } return(z) } ) setAs("coverconvert", "list", function(from) as.list(from))
/scratch/gouwar.j/cran-all/cranData/vegtable/R/coerce-methods.R
#' @name count_taxa #' @aliases count_taxa,vegtable,missing-method #' #' @title Count taxa included in vegtable objects #' #' @description #' Counting number of taxa within [taxlist-class] objects or character vectors #' containing taxon names. #' #' This function provides a quick calculation of taxa in [vegtable-class] #' objects, considering only records in slot samples. #' Such records can be also merged from lower ranks. #' #' For the formula method, units without any requested taxa will not appear in #' the output data frame. If no taxa at all is occurring at the requested level #' in any unit, an error message will be retrieved. #' #' @param object An object of class [vegtable-class] or a formula. #' @param value A formula passed to parameter 'object' by the replace method. #' @param data An object of class [vegtable-class]. #' @param level Character value indicating the taxonomic rank of counted taxa. #' @param include_lower Logical value, whether lower taxonomic ranks should be #' included at the requested level. #' @param suffix Character value used as suffix on the calculated variable. #' @param in_header Logical value, whether the result should be included in the #' slot header of the input [vegtable-class] object or not. #' A warning message is provided if the calculation is not done for every #' plot observation. #' @param ... further arguments passed among methods. #' #' @return #' An data frame with the number of taxa from requested level at requested #' units for the formula method, or just an integer value. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @examples #' ## Different alternatives #' count_taxa(Kenya_veg) #' head(count_taxa(~ReleveID, Kenya_veg, in_header = FALSE)) #' head(count_taxa(species ~ ReleveID, Kenya_veg, in_header = FALSE)) #' head(count_taxa(species ~ ReleveID, Kenya_veg, TRUE, in_header = FALSE)) #' head(count_taxa(family ~ ReleveID, Kenya_veg, TRUE)) #' #' @rdname count_taxa #' #' @exportMethod count_taxa #' setMethod( "count_taxa", signature(object = "vegtable", data = "missing"), function(object, level, include_lower = FALSE, ...) { concepts <- with( object@species@taxonNames, TaxonConceptID[match( object@samples$TaxonUsageID, TaxonUsageID )] ) if (!missing(level)) { if (!level %in% levels(object@species)) { stop(paste( "Value of argument 'level' is not a level", "in 'object'." )) } } if (!missing(level) & include_lower) { concept_levels <- with( object@species@taxonRelations, as.integer(Level)[match(concepts, TaxonConceptID)] ) # Skip NA's from taxon levels concepts <- concepts[!is.na(concept_levels)] concept_levels <- concept_levels[!is.na(concept_levels)] x <- which(levels(object@species) == level) - 1 for (i in 1:x) { concepts[concept_levels == i] <- with( object@species@taxonRelations, Parent[match( concepts[concept_levels == i], TaxonConceptID )] ) concept_levels <- with( object@species@taxonRelations, as.integer(Level)[match(concepts, TaxonConceptID)] ) } } if (!missing(level)) { concept_levels <- with( object@species@taxonRelations, paste(Level)[match(concepts, TaxonConceptID)] ) concepts <- concepts[concept_levels == level] } return(length(unique(concepts))) } ) #' @rdname count_taxa #' #' @aliases count_taxa,formula,vegtable-method setMethod( "count_taxa", signature(object = "formula", data = "vegtable"), function(object, data, include_lower = FALSE, suffix = "_count", in_header = TRUE, ...) { data_in <- data nr_response <- attr(terms(object), "response") name_response <- as.character(object)[2] if (nr_response > 1) { stop("More than one response in formula are not allowed.") } if (nr_response == 1) { if (!name_response %in% levels(data@species)) { stop("The response in the formula is not a rank in 'data'.") } object <- as.formula(paste( "TaxonConceptID ~", paste(attr(terms(object), "term.labels"), collapse = " + " ) )) if (include_lower) { data <- taxa2samples(data, merge_to = name_response, include_levels = name_response, add_relations = TRUE ) } else { data <- taxa2samples(data, include_levels = name_response, add_relations = TRUE ) } if (all(is.na(data@samples$TaxonConceptID))) { stop("No records for requested taxon rank.") } } else { data <- taxa2samples(data, add_relations = TRUE) object <- as.formula(paste( "TaxonUsageID ~", paste(attr(terms(object), "term.labels"), collapse = " + " ) )) } data <- aggregate(object, data@samples, function(x) length(unique(x)), ...) if (name_response == "ReleveID") name_response <- "taxa" colnames(data)[colnames(data) %in% c("TaxonUsageID", "TaxonConceptID")] <- paste0(name_response, suffix) if (colnames(data)[1] != "ReleveID" & in_header) { warning("'ReleveID' is not included as factor in formula") } if (colnames(data)[1] == "ReleveID" & in_header) { data_in@header[, colnames(data)[2]] <- with( data_in@header, data[match(ReleveID, data$ReleveID), 2] ) return(data_in) } else { return(data) } } ) #' @rdname count_taxa #' #' @aliases count_taxa<- #' #' @exportMethod count_taxa<- #' setGeneric("count_taxa<-", function(data, ..., value) { standardGeneric("count_taxa<-") }) #' @rdname count_taxa #' #' @aliases count_taxa<-,vegtable,formula-method #' setReplaceMethod( "count_taxa", signature(data = "vegtable", value = "formula"), function(data, ..., value) { return(count_taxa( object = value, data = data, in_header = TRUE, ... )) } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/count_taxa.R
#' @exportMethod cover_trans #' setGeneric("cover_trans", function(x, conversion, ...) { standardGeneric("cover_trans") }) #' @name cover_trans #' #' @title Convert cover scales to percent cover #' #' @description #' Convert values of a categorical cover scale to percentage values. #' #' This function requires as input a [coverconvert-class] object which contains #' the conversion tables. #' #' @param x Either a factor or character vector, or a [vegtable-class] object. #' @param conversion An object of class [vegtable-class]. #' @param from Scale name of values in `x` as character value. #' @param to Name of the column in slot `samples` for writing converted values. #' @param replace Logical value indicating whether existing cover values should #' be replaced by the new computed values or not. #' @param rule A character value indicating the rule applied for cover #' transformation. Three rules are implemented for transformation, #' either `top` (values transformed to the top of the range), #' `middle` (transformation at the midpoint), and #' `bottom` (conversion at the lowest value of the range). #' In the later case, if the bottom is zero cover, a fictive bottom value #' can be set by `'zeroto'` #' @param zeroto Value set for transformation of classes with bottom at 0% #' cover. #' @param ... Further arguments passed from or to other methods. #' #' @return Either a vector or a [vegtable-class] object. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @examples #' ## Check the available scales #' summary(Kenya_veg@coverconvert) #' #' ## Conversion by default 'top' rule #' Kenya_veg <- cover_trans(Kenya_veg, to = "percent") #' summary(as.factor(Kenya_veg@samples$percent)) #' #' ## Conversion by 'middle' rule #' Kenya_veg <- cover_trans(Kenya_veg, to = "percent", rule = "middle", replace = TRUE) #' summary(as.factor(Kenya_veg@samples$percent)) #' #' ## Conversion by 'bottom' rule #' Kenya_veg <- cover_trans(Kenya_veg, to = "percent", rule = "bottom", replace = TRUE) #' summary(as.factor(Kenya_veg@samples$percent)) #' @rdname cover_trans #' #' @aliases cover_trans,character,coverconvert-method #' setMethod( "cover_trans", signature( x = "character", conversion = "coverconvert" ), function(x, conversion, from = NULL, rule = "top", zeroto = 0.1, ...) { rule <- grep(rule[1], c("top", "bottom", "middle"), ignore.case = TRUE) if (!rule %in% c(1:3)) { stop("Invalid value for argument 'rule'") } if (any(!x %in% base::levels(conversion@value[[from]]))) { warning(paste( "Some values in 'x' are not valid and will be", "converted in NAs" )) } top <- conversion@conversion[[from]][-1][match( x, base::levels(conversion@value[[from]]) )] if (rule == 1) { return(top) } else { ties <- rev(duplicated(rev(conversion@conversion[[from]]))) bottom <- conversion@conversion[[from]][-length( conversion@conversion[[from]] )] for (i in 1:length(bottom)) { if (ties[i]) { bottom[i] <- bottom[i - 1] } } bottom <- bottom[match( x, base::levels(conversion@value[[from]]) )] if (rule == 3) { return((bottom + top) / 2) } if (rule == 2) { bottom[bottom == 0] <- zeroto return(bottom) } } } ) #' @rdname cover_trans #' #' @aliases cover_trans,factor,coverconvert-method setMethod( "cover_trans", signature( x = "factor", conversion = "coverconvert" ), function(x, conversion, ...) { x <- paste(x) cover_trans(x, conversion, ...) } ) #' @rdname cover_trans #' #' @aliases cover_trans,numeric,coverconvert-method setMethod( "cover_trans", signature( x = "numeric", conversion = "coverconvert" ), function(x, conversion, ...) { x <- paste(x) cover_trans(x, conversion, ...) } ) #' @rdname cover_trans #' #' @aliases cover_trans,vegtable,missing-method setMethod( "cover_trans", signature(x = "vegtable", conversion = "missing"), function(x, to, replace = FALSE, rule = "top", zeroto = 0.1, ...) { if (!to %in% colnames(x@samples)) x@samples[, to] <- NA if (replace) { Selection <- 1:length(x@samples[, to]) } else { Selection <- which(is.na(x@samples[, to])) } for (i in names(x@coverconvert)) { if (i %in% colnames(x@samples)) { Selection2 <- which(!is.na(x@samples[, i])) Selection2 <- intersect(Selection, Selection2) x@samples[Selection2, to] <- cover_trans(x@samples[Selection2, i], x@coverconvert, from = i, rule = rule, zeroto = zeroto ) } } return(x) } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/cover_trans.R
#' @name coverconvert #' @aliases coverconvert-class #' #' @title Cover conversion tables #' #' @description #' Cover conversion tables for [vegtable-class] objects. #' #' This class implements conversions from different cover scales in percentage #' cover. For transformations to percentage cover, the function [cover_trans()] #' should be than used. #' #' @slot value List containing the levels of each scale. #' @slot conversion List with the respective start and end cut levels for the #' scale levels. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @seealso [tv2coverconvert()] [braun_blanquet]. #' #' @exportClass coverconvert #' setClass("coverconvert", slots = c( value = "list", conversion = "list" ), prototype = list( value = list(), conversion = list() ), validity = function(object) { if (length(object@value) > 0) { # For whole object if (!all(names(object@value) == names(object@conversion))) { return("Names in slots 'value' and 'conversion' do not match") } } # For single scales for (i in names(object@value)) { if (length(object@value[[i]]) != length(object@conversion[[i]]) - 1) { return(paste0( "Invalid length of vectors in scale '", i, "'" )) } if (!is.numeric(object@conversion[[i]])) { return(paste0( "Values of 'conversion' in scale '", i, "' have to be of class numeric" )) } if (!is.factor(object@value[[i]])) { return(paste0( "Values of 'value' in scale '", i, "' have to be of class factor" )) } if (!all(object@conversion[[i]] == object@conversion[[i]][ order(object@conversion[[i]]) ])) { return(paste0( "Sort values of 'conversion' in scale '", i, "' in increasing order" )) } } } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/coverconvert-class.R
#' @name crosstable #' #' @title Generating cross tables from database lists #' #' @description #' cross table is the most common format required by statistical packages #' used to analyse vegetation data (e.g. #' [vegan](https://CRAN.R-project.org/package=vegan)). #' #' You may use for convenience a formula as #' `'abundance ~ plot + species + ...'`. #' Additional variables used for rows (`...`) can be for instance the #' layers. #' For objects of class [vegtable-class], the formula can also include #' variables from the species list (for example `AcceptedName`, `AuthorName`) #' or even taxon traits. #' #' If required, tables already formatted as cross tables can be converted into #' column-oriented tables by using the function `cross2db()`. #' #' @param formula A formula indicating the variables used in the cross table. #' This formula can be represented as `'abundance ~ cols + rows'`, where #' `'abundance'` is the numeric variable quantified for a row in a column, #' for instance the abundance of a species in a plot. #' Further variables can be set as additional rows indices in a cross table. #' @param data Either a data frame or an object of class [vegtable-class]. #' @param FUN Function used to aggregate values in the case of a multiple #' occurrence of a species in a plot, for instance. #' @param na_to_zero A logical value indicating whether zeros should be #' inserted into empty cells or not. #' @param use_nas Logical value indicating whether NAs should be considered as #' levels for categorical variables or not. #' @param as_matrix A logical value, whether output should be done as matrix or #' data frame. #' @param ... Further arguments passed to the function [stats::aggregate()]. #' @param object A data frame including a cross table. #' @param layers Logical value, whether the cross table includes a layer column #' or not. #' @param na_strings Character vector indicating no records in the cross table. #' #' @return An object of class [data.frame]. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @examples #' veg <- subset(Kenya_veg, REFERENCE == 2331, slot = "header") #' #' ## transform cover to percentage #' veg <- cover_trans(veg, to = "cover_perc", rule = "middle") #' #' ## cross table of the first 5 plots #' Cross <- crosstable(cover_perc ~ ReleveID + AcceptedName + AuthorName, #' veg[1:5, ], mean, #' na_to_zero = TRUE #' ) #' head(Cross) #' @rdname crosstable #' #' @exportMethod crosstable #' setGeneric("crosstable", function(formula, data, ...) { standardGeneric("crosstable") }) #' @rdname crosstable #' #' @aliases crosstable,formula,data.frame-method setMethod( "crosstable", signature(formula = "formula", data = "data.frame"), function(formula, data, FUN, na_to_zero = FALSE, use_nas = TRUE, as_matrix = FALSE, ...) { if (!all(c(as.character(formula)[2], attr( terms(formula), "term.labels" )) %in% colnames(data))) { stop("all terms in 'formula' must be a column in 'data'") } if (use_nas) { Terms <- c(as.character(formula)[2], attr( terms(formula), "term.labels" )) for (i in Terms[-1]) { if (is.factor(data[, i])) { data[, i] <- paste(data[, i]) } if (is.character(data[, i])) { data[is.na(data[, i]), i] <- "" } } } data <- aggregate(formula, data, FUN, ...) coverage <- as.character(formula)[2] plots <- attr(terms(formula), "term.labels")[1] # for multiple plot entries if (length(attr(terms(formula), "term.labels")) > 2) { data$.spp <- apply( data[attr( terms(formula), "term.labels" )[-1]], 1, paste, collapse = "." ) spp <- ".spp" } else { spp <- attr(terms(formula), "term.labels")[2] } cross <- expand.grid(unique(data[, spp]), unique(data[, plots]), stringsAsFactors = FALSE ) colnames(cross) <- c(spp, plots) cross[, coverage] <- data[match( paste(cross[, spp], cross[, plots]), paste(data[, spp], data[, plots]) ), coverage] if (na_to_zero) cross[is.na(cross[, coverage]), coverage] <- 0 cross <- matrix(cross[, coverage], ncol = length(unique(cross[, plots])), dimnames = list(unique(cross[, spp]), unique(cross[, plots])) ) # final output data frame if (spp == ".spp") { cross_margin <- unique(data[c(".spp", attr( terms(formula), "term.labels" )[-1])]) cross_margin <- cross_margin[match( rownames(cross), cross_margin$.spp ), colnames(cross_margin)[-1]] } else { cross_margin <- data.frame(unique(data[, spp]), stringsAsFactors = FALSE ) colnames(cross_margin) <- spp } if (!as_matrix) { cross <- do.call(cbind, list(cross_margin, cross)) rownames(cross) <- NULL # reseting row names } return(cross) } ) #' @rdname crosstable #' #' @aliases crosstable,formula,vegtable-method setMethod( "crosstable", signature(formula = "formula", data = "vegtable"), function(formula, data, FUN, na_to_zero = FALSE, use_nas = TRUE, ...) { Terms <- c(as.character(formula)[2], attr( terms(formula), "term.labels" )) data@samples <- data@samples[, colnames(data@samples) %in% c("ReleveID", "TaxonUsageID", Terms)] # Data from species data@samples$TaxonConceptID <- data@species@taxonNames[ match( data@samples$TaxonUsageID, data@species@taxonNames$TaxonUsageID ), "TaxonConceptID" ] if ("TaxonName" %in% Terms & "AcceptedName" %in% Terms) { stop("Terms 'TaxonName' and 'AcceptedName' are mutually exclusive in 'formula'") } # 1: when usage name requested if ("TaxonName" %in% Terms) { data@samples$TaxonName <- data@species@taxonNames[ match( data@samples$TaxonUsageID, data@species@taxonNames$TaxonUsageID ), "TaxonName" ] data@samples$AuthorName <- data@species@taxonNames[ match( data@samples$TaxonUsageID, data@species@taxonNames$TaxonUsageID ), "AuthorName" ] } # 2: when accepted name requested if ("AcceptedName" %in% Terms) { data@samples$AcceptedName <- data@species@taxonRelations[ match( data@samples$TaxonConceptID, data@species@taxonRelations$TaxonConceptID ), "AcceptedName" ] data@samples$AuthorName <- data@species@taxonNames[ match( data@samples$AcceptedName, data@species@taxonNames$TaxonUsageID ), "AuthorName" ] data@samples$AcceptedName <- data@species@taxonNames[ match( data@samples$AcceptedName, data@species@taxonNames$TaxonUsageID ), "TaxonName" ] } # Data from traits (only for Accepted Name or TaxonConceptID) traits_names <- colnames(data@species@taxonTraits)[ colnames(data@species@taxonTraits) != "TaxonConceptID" ] if (any(Terms %in% traits_names)) { traits_names <- traits_names[traits_names %in% Terms] for (i in traits_names) { data@samples[, i] <- data@species@taxonTraits[ match( data@samples$TaxonConceptID, data@species@taxonTraits$TaxonConceptID ), i ] } } # Data from header header_names <- colnames(data@header)[colnames(data@header) != "ReleveID"] if (any(header_names %in% Terms)) { header_names <- header_names[header_names %in% Terms] for (i in header_names) { data@samples[, i] <- data@header[match( data@samples$ReleveID, data@header$ReleveID ), i] } } # Continue with method data.frame return(crosstable( formula, data@samples, FUN, na_to_zero, use_nas, ... )) } ) #' @rdname crosstable #' #' @aliases cross2db #' #' @export cross2db <- function(object, layers = FALSE, na_strings) { species <- object[, 1] if (layers) { LAY <- object[, 2] Cover <- object[, -1:-2] object <- lapply(split(1:ncol(Cover), 1:ncol(Cover)), function(x, cov, spec, lay) { releve <- data.frame( plot = colnames(cov)[x], species = spec, layers = lay, cover = cov[, x], stringsAsFactors = FALSE ) return(releve) }, cov = Cover, spec = species, lay = LAY ) } else { Cover <- object[, -1, drop = FALSE] object <- lapply(split(1:ncol(Cover), 1:ncol(Cover)), function(x, cov, spec) { releve <- data.frame( plot = colnames(cov)[x], species = spec, cover = cov[, x], stringsAsFactors = FALSE ) return(releve) }, cov = Cover, spec = species ) } object <- do.call(rbind, object) if (!missing(na_strings)) { object$cover[paste(object$cover) %in% na_strings] <- NA } return(object[!is.na(object$cover), ]) }
/scratch/gouwar.j/cran-all/cranData/vegtable/R/crosstable.R
#' @name df2coverconvert #' #' @title Create coverconvert objects #' #' @description #' The class [coverconvert-class] contains tables for transforming cover values #' to percentage using the function [cover_trans()]. #' These objects can be created from conversion tables imported as data frames. #' #' @param x Either a data frame or a list of data frames containing the #' conversion table. Three columns are mandatory in such data frames, namely #' **value** (factor with the symbols for each class in the cover scale, #' sorted from the lowest to the highest value), **bottom** (numeric value #' with the bottom values of each class), and **top** (numeric value with #' the top values of each class). The values **bottom** and **top** are #' usually as cover percentage but they may refer to any other numeric #' abundance. #' @param name A character value used as name of the cover scale in the data #' frame method. In the list method, this name will be extracted from the #' names of the elements in the list. #' @param ... Further arguments passed among methods. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @examples #' ## Convert object into list #' cov <- as(Kenya_veg@coverconvert, "list") #' #' ## Convert back to coverconvert #' cov <- df2coverconvert(cov) #' #' @rdname df2coverconvert #' #' @export df2coverconvert <- function(x, ...) { UseMethod("df2coverconvert", x) } #' @rdname df2coverconvert #' @aliases df2coverconvert,list-method #' @method df2coverconvert list #' @export df2coverconvert.list <- function(x, ...) { x_names <- c("value", "bottom", "top") OUT <- new("coverconvert") for (i in names(x)) { if (!all(x_names %in% names(x[[i]]))) { x_names <- x_names[!x_names %in% names(x[[i]])] stop(paste0( "Following mandatory columns are missing in cover scale '", i, "': '", paste0(x_names, collapse = "', '"), "'." )) } OUT@value[[i]] <- factor(x[[i]]$value, levels = x[[i]]$value) OUT@conversion[[i]] <- c(x[[i]]$bottom[1], x[[i]]$top) } return(OUT) } #' @rdname df2coverconvert #' @aliases df2coverconvert,data.frame-method #' @method df2coverconvert data.frame #' @export df2coverconvert.data.frame <- function(x, name, ...) { if (missing(name)) { stop("You have to provide a 'name' for this cover scale.") } x2 <- list() x2[[name]] <- x return(df2coverconvert(x2)) }
/scratch/gouwar.j/cran-all/cranData/vegtable/R/df2coverconvert.R
#' @name df2vegtable #' #' @title Convert a data frame into a vegtable object. #' #' @description #' Conversion of a data frame containing a cross table of abundance or cover of #' species in single plots. #' #' This function coerces a data frame containing a vegetation cross table into #' a [vegtable-class] object. The input data frame `x` may include information #' on the layers or not. #' #' @param x A data frame formatted for a taxlist object. #' @param species Numeric or integer indicating the position of the column with #' species names. #' @param layer Numeric or integer indicating the position of the column with #' layers. #' @param ... Further arguments passed from or to other methods. #' #' @return A [vegtable-class] object. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @examples #' ## Creating data set 'dune_veg' #' library(vegan) #' #' ## Load data from vegan #' data(dune) #' data(dune.env) #' #' ## Conversion to vegtable #' dune_veg <- data.frame( #' species = colnames(dune), t(dune), #' stringsAsFactors = FALSE, check.names = FALSE #' ) #' dune_veg <- df2vegtable(dune_veg, species = 1) #' #' summary(dune_veg) #' #' ## Adding environmental variables #' dune.env$ReleveID <- as.integer(rownames(dune.env)) #' header(dune_veg) <- dune.env #' #' summary(dune_veg) #' @rdname df2vegtable #' #' @exportMethod df2vegtable #' setGeneric( "df2vegtable", function(x, species, layer, ...) { standardGeneric("df2vegtable") } ) #' @rdname df2vegtable #' #' @aliases df2vegtable,data.frame,numeric,numeric-method setMethod( "df2vegtable", signature( x = "data.frame", species = "numeric", layer = "numeric" ), function(x, species, layer, ...) { # First creates species list taxlist <- new("taxlist") taxlist <- add_concept(taxlist, TaxonName = unique(paste(x[ , species ]))) # Some tests previous to run the function Cover <- x[, -c(species, layer)] for (i in 1:ncol(Cover)) Cover[, i] <- paste(Cover[, i]) Layer <- as.factor(x[, layer]) ReleveID <- list() for (i in colnames(Cover)) ReleveID[[i]] <- rep(i, nrow(Cover)) ReleveID <- do.call(c, ReleveID) TaxonUsageID <- taxlist@taxonNames$TaxonUsageID[match( paste(x[ , species ]), taxlist@taxonNames$TaxonName )] TaxonUsageID <- rep(TaxonUsageID, ncol(Cover)) Layer <- rep(Layer, ncol(Cover)) Cover <- do.call(c, Cover) x <- new("vegtable", samples = data.frame( ReleveID = as.integer(ReleveID), Layer = Layer, TaxonUsageID = TaxonUsageID, Cover = Cover, stringsAsFactors = FALSE ), header = data.frame( ReleveID = unique(as.integer(ReleveID)) ), species = taxlist ) x@samples <- x@samples[!is.na(Cover), ] x@samples <- x@samples[Cover != "NA", ] return(x) } ) #' @rdname df2vegtable #' #' @aliases df2vegtable,data.frame,numeric,missing-method setMethod( "df2vegtable", signature( x = "data.frame", species = "numeric", layer = "missing" ), function(x, species, ...) { x[, ncol(x) + 1] <- NA df2vegtable(x, species, layer = ncol(x), ...) } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/df2vegtable.R
#' @name dune_veg-data #' @aliases dune_veg #' @docType data #' #' @title Dutch dune meadows as vegtable #' #' @description #' Data set from the package [vegan::vegan], converted to a [vegtable-class] #' object. #' #' @format An object of class \code{\linkS4class{vegtable}}. #' #' @references \bold{Jongman RHG, ter Braak CJF, van Tongeren OFR (1987).} #' \emph{Data analysis in community and landscape ecology.} Pudoc, Wageningen, #' NL. #' #' @source Original data were imported from [vegan::dune]. #' #' @examples #' summary(dune_veg) "dune_veg"
/scratch/gouwar.j/cran-all/cranData/vegtable/R/dune_veg-data.R
#' @name header #' #' @title Retrieve or replace slot header in vegtable objects #' #' @description #' Retrieve or replace the content of slot `header` in [vegtable-class] objects. #' #' @param x Object of class [vegtable-class]. #' @param value Data frame to be set as slot `header`. #' @param ... Further arguments passed to or from other methods. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @examples #' head(header(Kenya_veg)) #' @rdname header #' #' @exportMethod header #' setGeneric( "header", function(x, ...) { standardGeneric("header") } ) #' @rdname header #' #' @aliases header,vegtable-method setMethod( "header", signature(x = "vegtable"), function(x, ...) { return(x@header) } ) #' @rdname header #' #' @aliases header<- #' #' @exportMethod header<- #' setGeneric("header<-", function(x, value) { standardGeneric("header<-") }) #' @rdname header #' #' @aliases header<-,vegtable,data.frame-method setReplaceMethod( "header", signature(x = "vegtable", value = "data.frame"), function(x, value) { if (!"ReleveID" %in% colnames(value)) { stop("Column 'ReleveID' is mandatory in 'value'") } for (i in colnames(value)) { x@header[, i] <- value[ match(x@header$ReleveID, value$ReleveID), i ] } return(x) } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/header.R
#' @importFrom stats aggregate as.formula na.omit terms update #' @importFrom methods as is new slot slot<- slotNames validObject #' @importFrom foreign read.dbf #' @importFrom utils object.size #' @importFrom vegdata tv.home #' @importFrom qdapRegex rm_between #' @importFrom stringi stri_split_fixed #' @importFrom sp CRS coordinates coordinates<- proj4string<- #' @import taxlist NULL
/scratch/gouwar.j/cran-all/cranData/vegtable/R/imports.R
#' @name layers2samples #' #' @title Add information from slot 'layers' into slot 'samples' #' #' @description #' Slot layers may include additional information that should be moved to #' samples in order to use it by [vegtable::subset()], [vegtable::aggregate()] #' or [vegtable::crosstable()] methods. #' #' If names of variables are not provided, all variables from the respective #' layer table will be inserted in slot `samples`. #' #' @param object An object of class [vegtable-class]. #' @param layer Character value indicating a target layer. #' @param variable Character vector with the names of variables to be inserted #' in slot `samples`. #' @param ... Further arguments to be passed among methods. #' @return An object of class [vegtable-class] with variables added to samples. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com}. #' #' @rdname layers2samples #' #' @exportMethod layers2samples #' setGeneric( "layers2samples", function(object, layer, variable, ...) { standardGeneric("layers2samples") } ) #' @rdname layers2samples #' #' @aliases layers2samples,vegtable,character,character-method setMethod( "layers2samples", signature( object = "vegtable", layer = "character", variable = "character" ), function(object, layer, variable, ...) { if (!layer %in% names(object@layers)) { stop("Value of 'layer' is not occurring in slot 'layers'") } if (any(!variable %in% colnames(object@layers[[layer]]))) { stop(paste( "Some values of 'variable' are not occurring in", "the targeted layer table" )) } object@samples <- merge(object@samples, object@layers[[layer]][ , unique(c(layer, variable)) ], by = layer, sort = FALSE, all.x = TRUE, all.y = FALSE ) return(object) } ) #' @rdname layers2samples #' #' @aliases layers2samples,vegtable,character,missing-method setMethod( "layers2samples", signature( object = "vegtable", layer = "character", variable = "missing" ), function(object, layer, ...) { variable <- colnames(object@layers[[layer]]) layers2samples(object, layer, variable) } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/layers2samples.R
#' @name make_cocktail #' #' @title Produce a Cocktail classification #' #' @description #' Classification of [vegtable-class] objects according to **Cocktail** #' algorithms. #' #' Cocktail algorithms are logical functions selecting plots according to #' either occurrence of species groups and cover values of single species. A #' group will be declared as occurring in a plot when at least a half of its #' members is present in the plot. #' #' This function inserts single columns with logical values indicating whether #' a plot is classified in the vegetation unit or not. An additional column #' (name provided in argument `syntax`) compile all vegetation units, #' indicating with a `+` symbol those plots classified in more than one #' vegetation unit. #' When only a part of the formulas will be used, it should be #' specified by the argument `which`. #' #' These functions are implemented for constructing or complementing #' [shaker-class] objects. #' Note that construction of those objects will always require a `companion` #' object, which is either an object of class [taxlist-class] or #' [vegtable-class]. #' #' @param shaker An object of class [shaker-class] containing the respective #' cocktail definitions. #' @param vegtable An object of class [vegtable-class] containing the #' vegetation observations to be classified. #' @param which Integer or character indicating the definition to be applied #' for classification. #' @param cover Name of the cover variable in `vegtable`. #' @param syntax Character value indicating the name of the retrieved variable #' including the final classification of plots. #' @param FUN Function used for merging multiple occurrence of species in a #' single plot. #' @param companion Either a [taxlist-class] or a [vegtable-class] object. #' @param pseudo,group Character vector with names of taxa included in a #' pseudo-species or a species group. #' @param formula Character vector including a formula as definition of a #' vegetation unit. #' @param pseudo_id,group_id,formula_id Character value as name of the #' pseudo-species, species group or defined vegetation unit. #' @param authority Logical value indicating whether author names should be #' included in the taxon name or not. #' @param enc_cont,enc_gr Encodings used for special characters. #' @param in_header Logical value indicating whether results of Cocktail #' classification should be inserted to the header of the input vegtable or #' not. In the second case, a data frame is provided as output. #' @param ... Further arguments passes from or to other methods. #' #' @return #' A data frame corresponding to the slot `header` of input object `vegtable`, #' including the results of Cocktail classification for the respective plots. #' #' A [shaker-class] object. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @seealso [shaker-class] [vegtable-class] [Wetlands] #' #' @references #' \bold{Alvarez M (2017).} Classification of aquatic and #' semi-aquatic vegetation in two East African sites: Cocktail definitions and #' syntaxonomy. \emph{Phytocoenologia}. #' #' \bold{Bruelheide H (2000).} A new measure of fidelity and its application to #' defining species groups. \emph{Journal of Vegetation Science} 11: 167--178. #' #' \bold{Kočí M, Chytrý M, Tichý L (2003).} Formalized reproduction of an #' expert-based phytosociological classification: a case study of subalpine #' tall-forb vegetation. \emph{Journal of Vegetation Science} 14: 601--610. #' #' @examples #' ## Example from Alvarez (2017) #' Wetlands_veg <- make_cocktail(Wetlands, Wetlands_veg, cover = "percen") #' summary(as.factor(Wetlands_veg@header$Syntax)) #' #' ## Same but only for two vegetation units #' Wetlands_veg <- make_cocktail(Wetlands, Wetlands_veg, #' which = c("HY1", "HY2"), cover = "percen" #' ) #' summary(as.factor(Wetlands_veg$Syntax)) #' #' ## Construct the 'shaker' object anew #' Wetlands <- new("shaker") #' #' ## Set a pseudo-species #' Wetlands <- set_pseudo(Wetlands, Wetlands_veg, c( #' "Cyperus latifolius", #' "Cyperus exaltatus" #' )) #' #' ## Set a species group #' Wetlands <- set_group(Wetlands, Wetlands_veg, #' group_id = "Cyperus papyrus", #' group = c( #' "Cyperus papyrus", #' "Cyclosorus interruptus", #' "Lepistemon owariense" #' ) #' ) #' #' ## Set a fromula #' Wetlands <- set_formula(Wetlands, Wetlands_veg, #' formula_id = "HE1", #' formula = "groups:'Cyperus papyrus' | species:'Cyperus papyrus > 50'" #' ) #' #' ## Summaries #' summary(Wetlands) #' summary(Wetlands, Wetlands_veg) #' @rdname make_cocktail #' #' @aliases set_group #' #' @exportMethod set_group #' setGeneric( "set_group", function(shaker, companion, group, ...) { standardGeneric("set_group") } ) #' @rdname make_cocktail #' #' @aliases set_group,shaker,taxlist,character-method #' setMethod( "set_group", signature( shaker = "shaker", companion = "taxlist", group = "character" ), function(shaker, companion, group, group_id, authority = FALSE, enc_cont = "latin1", enc_gr = "utf8", ...) { companion <- accepted_name(companion) if (authority) { companion$AuthorName[is.na(companion$AuthorName)] <- "" companion$TaxonName <- with(companion, paste( TaxonName, AuthorName )) } companion$TaxonName <- iconv( companion$TaxonName, enc_cont, "ASCII//TRANSLIT" ) group <- iconv(group, enc_gr, "ASCII//TRANSLIT") if (any(!group %in% companion$TaxonName)) { stop("Some names in 'group' are not in 'companion'") } if (any(duplicated(group))) { group <- unique(group) } if (any(duplicated(companion$TaxonName))) { warning(paste( "Some duplicated names in 'companion', only", "one will be retrieved" )) } if (missing(group_id)) { group_id <- length(shaker@groups) + 1 } shaker@groups[[group_id]] <- companion[charmatch( group, companion$TaxonName ), "TaxonConceptID"] return(shaker) } ) #' @rdname make_cocktail #' #' @aliases set_group,shaker,vegtable,character-method #' setMethod( "set_group", signature( shaker = "shaker", companion = "vegtable", group = "character" ), function(shaker, companion, group, ...) { set_group(shaker, companion@species, group, ...) } ) #' @rdname make_cocktail #' #' @aliases set_pseudo #' #' @exportMethod set_pseudo #' setGeneric( "set_pseudo", function(shaker, companion, pseudo, ...) { standardGeneric("set_pseudo") } ) #' @rdname make_cocktail #' #' @aliases set_pseudo,shaker,taxlist,character-method #' setMethod( "set_pseudo", signature( shaker = "shaker", companion = "taxlist", pseudo = "character" ), function(shaker, companion, pseudo, pseudo_id, authority = FALSE, enc_cont = "latin1", enc_gr = "utf8", ...) { companion <- accepted_name(companion) if (authority) { companion$AuthorName[is.na(companion$AuthorName)] <- "" companion$TaxonName <- with(companion, paste( TaxonName, AuthorName )) } companion$TaxonName <- iconv( companion$TaxonName, enc_cont, "ASCII//TRANSLIT" ) pseudo <- iconv(pseudo, enc_gr, "ASCII//TRANSLIT") if (any(!pseudo %in% companion$TaxonName)) { stop("Some names in 'pseudo' are not in 'companion'") } if (any(duplicated(companion$TaxonName))) { warning(paste( "Some duplicated names in 'companion', only", "one will be retrieved" )) } if (missing(pseudo_id)) { pseudo_id <- length(shaker@pseudos) + 1 } shaker@pseudos[[pseudo_id]] <- companion[charmatch( pseudo, companion$TaxonName ), "TaxonConceptID"] return(shaker) } ) #' @rdname make_cocktail #' #' @aliases set_pseudo,shaker,vegtable,character-method #' setMethod( "set_pseudo", signature( shaker = "shaker", companion = "vegtable", pseudo = "character" ), function(shaker, companion, pseudo, ...) { set_pseudo(shaker, companion@species, pseudo, ...) } ) #' @rdname make_cocktail #' #' @aliases set_formula #' #' @exportMethod set_formula #' setGeneric( "set_formula", function(shaker, companion, formula, ...) { standardGeneric("set_formula") } ) #' Have to be described #' #' @keywords internal #' format_F2 <- function(x) { x <- paste(x, collapse = " ") x <- gsub(" ", "", x, fixed = TRUE) x } #' @rdname make_cocktail #' #' @aliases set_formula,shaker,taxlist,character-method #' setMethod( "set_formula", signature( shaker = "shaker", companion = "taxlist", formula = "character" ), function(shaker, companion, formula, formula_id, authority = FALSE, enc_cont = "latin1", enc_gr = "utf8", ...) { if (grepl("\'", formula)) SYM <- "\'" if (grepl('\"', formula)) SYM <- '\"' Names <- Names_old <- rm_between(formula, left = SYM, right = SYM, extract = TRUE )[[1]] Slots <- strsplit(formula, " ")[[1]] Slots[grepl("species:", Slots)] <- "species" Slots[grepl("groups:", Slots)] <- "groups" Slots <- Slots[Slots %in% c("species", "groups")] # Check existence of groups in shaker object if (any(!Names[Slots == "groups"] %in% names(shaker@groups))) { stop(paste( "Some groups mentioned in the 'formula' are not", "included in 'shaker'" )) } # Retrieve companion <- accepted_name(companion) if (authority) { companion$AuthorName[is.na(companion$AuthorName)] <- "" companion$TaxonName <- with(companion, paste( TaxonName, AuthorName )) } if (any(Slots == "species")) { dominants <- strsplit(Names[Slots == "species"], " ") # function to merge species names elements dominants <- as.data.frame(do.call(rbind, lapply( dominants, function(x) { NR <- length(x) return(c( paste(x[1:(NR - 2)], collapse = " " ), x[(NR - 1):NR] )) } )), stringsAsFactors = FALSE) colnames(dominants) <- c("TaxonConceptID", "operator", "value") # In case of use of authority companion$TaxonName <- iconv( companion$TaxonName, enc_cont, "ASCII//TRANSLIT" ) dominants$TaxonConceptID <- iconv( dominants$TaxonConceptID, enc_gr, "ASCII//TRANSLIT" ) if (any(!dominants$TaxonConceptID %in% companion$TaxonName)) { stop(paste( "Some species in 'formula' are not included", "in 'companion'" )) } dominants$TaxonConceptID <- companion[ match(dominants$TaxonConceptID, companion$TaxonName), "TaxonConceptID" ] dominants$value <- as.numeric(dominants$value) # paste rows in Names before continuing Names[Slots == "species"] <- formula_new <- apply( dominants, 1, format_F2 ) # merge slot dominants and extract duplicated if (nrow(shaker@dominants) > 0) { formula_old <- apply(shaker@dominants, 1, format_F2) dominants <- do.call(rbind, list( shaker@dominants, dominants[!formula_new %in% formula_old, ] )) rownames(dominants) <- NULL formula_new <- apply(dominants, 1, format_F2) } shaker@dominants <- dominants # reformat formula Names[Slots == "species"] <- paste(match(Names[Slots == "species"], formula_new)) } # reformat formula (continuation) Names[Slots == "groups"] <- paste0( SYM, Names[Slots == "groups"], SYM ) # Assemble new formulas Names_old <- paste0(Slots, ":", SYM, Names_old, SYM) Slots[Slots == "species"] <- "dominants" Names <- paste0(Slots, "[[", Names, "]]") for (i in 1:length(Names)) { formula <- sub(Names_old[i], Names[i], formula) } # Insert results in output object if (missing(formula_id)) { formula_id <- length(shaker@formulas) + 1 } shaker@formulas[[formula_id]] <- formula return(shaker) } ) #' @rdname make_cocktail #' #' @aliases set_formula,shaker,vegtable,character-method #' setMethod( "set_formula", signature( shaker = "shaker", companion = "vegtable", formula = "character" ), function(shaker, companion, formula, ...) { set_formula(shaker, companion@species, formula, ...) } ) #' @rdname make_cocktail #' #' @exportMethod make_cocktail #' setGeneric( "make_cocktail", function(shaker, vegtable, ...) { standardGeneric("make_cocktail") } ) #' @rdname make_cocktail #' #' @aliases make_cocktail,shaker,vegtable-method #' setMethod( "make_cocktail", signature(shaker = "shaker", vegtable = "vegtable"), function(shaker, vegtable, which, cover, syntax = "Syntax", FUN = sum, in_header = TRUE, ...) { # Preserve original species list and samples species_in <- vegtable@species samples_in <- vegtable@samples # Build pseudo-species if (length(shaker@pseudos) > 0) { for (i in 1:length(shaker@pseudos)) { vegtable@species <- merge_taxa(vegtable@species, shaker@pseudos[[i]]) } } # Insert concept IDs in samples vegtable <- taxa2samples(vegtable) # Check presence of groups OUT <- list() if (length(shaker@groups) > 0) { OUT$groups <- list() PA <- aggregate( as.formula(paste( cover, "~ ReleveID + TaxonConceptID" )), vegtable@samples, function(x) { x <- sum(x) if (x > 0) x <- 1 return(x) } ) for (i in 1:length(shaker@groups)) { PA_aux <- PA[PA$TaxonConceptID %in% shaker@groups[[i]], ] PA_aux <- aggregate( as.formula(paste(cover, "~ ReleveID")), PA_aux, sum ) PA_aux <- PA_aux[PA_aux[, cover] >= length(shaker@groups[[i]]) / 2, ] OUT$groups[[i]] <- vegtable@header$ReleveID %in% PA_aux$ReleveID } } if (!is.null(names(shaker@groups))) { names(OUT$groups) <- names(shaker@groups) } # Check for dominants if (nrow(shaker@dominants) > 0) { OUT$dominants <- list() DOM <- aggregate( as.formula(paste( cover, "~ ReleveID + TaxonConceptID" )), vegtable@samples, FUN ) for (i in 1:nrow(shaker@dominants)) { DOM_aux <- DOM[DOM$TaxonConceptID == shaker@dominants[ i, "TaxonConceptID" ], ] DOM_aux <- DOM_aux[ eval(parse(text = paste( c(cover, shaker@dominants[ i, c( "operator", "value" ) ]), collapse = " " )), DOM_aux), ] OUT$dominants[[i]] <- vegtable@header$ReleveID %in% DOM_aux$ReleveID } } # Excecute formulas OUT$units <- list() if (!missing(which)) { which <- which[which %in% names(shaker@formulas)] } else { which <- names(shaker@formulas) } for (i in which) { OUT$units[[i]] <- as.numeric(eval(parse(text = shaker@formulas[[i]]), OUT)) } OUT <- as.data.frame(OUT$units, stringsAsFactors = FALSE, check.names = FALSE ) SYNTAX <- rep(NA, nrow(OUT)) for (i in colnames(OUT)) { vegtable@header[, i] <- OUT[, i] SYNTAX[OUT[, i] == 1] <- i } SYNTAX[rowSums(OUT) > 1] <- "+" vegtable@header[, syntax] <- SYNTAX if (in_header) { vegtable@samples <- samples_in vegtable@species <- species_in return(vegtable) } else { return(vegtable@header[, c("ReleveID", which, syntax)]) } } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/make_cocktail.R
#' @name names #' #' @title Retrieve names of vegtable and coverconvert objects #' #' @description #' Quick access to column names in slot header and names of conversion codes. #' #' These methods provide a quick display of the contents in #' [coverconvert-class] and [vegtable-class] objects. #' #' @param x An object of class [coverconvert-class] or [vegtable-class]. #' @param value A character vector used for replacement methods. #' #' @return #' A list containing the names from each slot. #' #' Either a vector or a list (in the case of `dimnames()`) with #' the names of variables. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com}. #' #' @examples #' names(Kenya_veg@coverconvert) #' names(Kenya_veg) #' dimnames(Kenya_veg) #' @rdname names #' @aliases names,vegtable-method #' #' @exportMethod names setMethod( "names", signature(x = "vegtable"), function(x) { names_list <- list() for (i in slotNames(x)) { names_list[[i]] <- names(slot(x, i)) } return(names_list) } ) #' @rdname names #' @aliases dimnames dimnames,vegtable-method #' #' @exportMethod dimnames setMethod( "dimnames", signature(x = "vegtable"), function(x) { return(list(x@header$ReleveID, colnames(x@header))) } ) #' @rdname names #' @aliases names,coverconvert-method setMethod( "names", signature(x = "coverconvert"), function(x) names(x@value) ) #' @rdname names #' @aliases names<-,coverconvert-method setReplaceMethod( "names", signature(x = "coverconvert"), function(x, value) { names(x@value) <- value names(x@conversion) <- value return(x) } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/names.R
#' @name new_relation #' @rdname new_relation #' #' @title Insert a new variable as relation in vegtable object #' #' @description #' Insert a new variable in slot **header** with a respective table at slot #' **relations**. The respective variable in header will be set as factor. #' #' Existing categorical variables can also be set as relations. If such #' variables are factors, its levels can be preserved (missing argument in #' `'levels'`) or reset. #' #' @param object A [vegtable-class] object. #' @param relation,value A character value indicating the name of the new #' relation. The parameter 'value' is used for the replacement method #' @param levels A character vector with the levels for the inserted factor. #' This may be missing for variables that already exist in slot **header**. #' @param ... Further arguments passed among methods. #' #' @return #' A [vegtable-class] object with the inserted new relation. #' #' @examples #' ## A brand new variable #' new_relation(Kenya_veg, levels = c("forest", "grassland", "cropland")) <- "land_use" #' #' ## Set an existing variable as relation #' new_relation(Kenya_veg) <- "REMARKS" #' #' @export new_relation <- function(object, ...) { UseMethod("new_relation", object) } #' @rdname new_relation #' @aliases new_relation,vegtable-method #' @method new_relation vegtable #' @export new_relation.vegtable <- function(object, relation, levels, ...) { # Conditions if (length(relation) > 1) { warning(paste( "Argument in 'relation' is longer than 1.", "Only the first value will be used." )) relation <- relation[1] } if (relation %in% names(object@relations)) { stop(paste0("Relation '", relation, "' is already in 'object'.")) } # New relation already in header if (relation %in% names(object@header)) { if (is(object@header[, relation], "factor") & missing(levels)) { levels <- base::levels(object@header[, relation]) relation_vector <- factor( unique(as.character(object@header[ !is.na(object@header[, relation]), relation ])), levels = levels ) } else { if (missing(levels)) { relation_vector <- as.factor(unique(as.character(object@header[ !is.na(object@header[, relation]), relation ]))) object@header[, relation] <- factor(as.character(object@header[, relation]), levels = base::levels(relation_vector) ) } else { relation_vector <- factor( unique(as.character(object@header[ !is.na(object@header[, relation]), relation ])), levels = levels ) object@header[, relation] <- factor(as.character(object@header[, relation]), levels = levels ) } } } else { if (missing(levels)) { stop(paste( "For new relations you have to provide", "an argument for 'levels'." )) } else { relation_vector <- factor(levels, levels = levels) object@header[, relation] <- factor(NA, levels = levels) } } # Insert relation_vector into slot object@relations[[relation]] <- list() object@relations[[relation]][[relation]] <- relation_vector object@relations[[relation]] <- as.data.frame(object@relations[[relation]]) return(object) } #' @rdname new_relation #' @aliases new_relation<- #' @exportMethod new_relation<- setGeneric("new_relation<-", function(object, levels, value) { standardGeneric("new_relation<-") }) #' @rdname new_relation #' @aliases new_relation<-,vegtable,character,character-method setReplaceMethod( "new_relation", signature( object = "vegtable", levels = "character", value = "character" ), function(object, levels, value) { return(new_relation(object, value, levels)) } ) #' @rdname new_relation #' @aliases new_relation<-,vegtable,missing,character-method setReplaceMethod( "new_relation", signature( object = "vegtable", levels = "missing", value = "character" ), function(object, value) { return(new_relation(object, value)) } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/new_relation.R
#' @name relation2header #' #' @title Insert variables from relations into header #' #' @description #' Information associated to categories listed in slot **relations** can be #' inserted to slot **header** for further statistical comparisons. #' #' @param vegtable An [vegtable-class] object. #' @param relation A character value indicating the relation to be used for #' inserting new variables in slot header. #' @param vars A selection of variables from the relation to be inserted in #' header. This function will check the existence of the variables in the #' respective relation and retrieve an error if none is matching the names. #' If missing in the arguments, all variables of the respective relation #' will be inserted. #' @param ... Further arguments passed among methods #' #' @return #' A [vegtable-class] object. #' #' @author #' Miguel Alvarez, <kamapu78@@gmail.com> #' #' @examples #' ## Insert publication year of the source into header #' veg <- relation2header(Kenya_veg, "REFERENCE", "YEAR") #' #' ## Show the frequency of plots per publication year #' summary(as.factor(veg$YEAR)) #' #' @rdname relation2heder #' @export relation2header <- function(vegtable, ...) { UseMethod("relation2header", vegtable) } #' @rdname relation2heder #' @aliases relation2header,vegtable-method #' @method relation2header vegtable #' @export relation2header.vegtable <- function(vegtable, relation, vars, ...) { if (!relation %in% names(vegtable@relations)) { stop(paste0( "The relation '", relation, "' is missing in 'vegtable@relations'." )) } if (missing(vars)) { vars <- names(vegtable@relations[[relation]])[ names(vegtable@relations[[relation]]) != relation ] } else { vars <- vars[vars != relation & vars %in% names(vegtable@relations[[relation]])] } if (length(vars) == 0) { stop("Values of 'vars' are not included in 'relation'.") } vegtable@header <- merge(vegtable@header, vegtable@relations[[relation]][ , c(relation, vars) ], by = relation, all.x = TRUE, sort = FALSE, suffixes = c("", "_y") ) return(vegtable) }
/scratch/gouwar.j/cran-all/cranData/vegtable/R/relation2header.R
#' @name shaker-class #' @aliases shaker #' #' @title Class containing Cocktail algorithms. #' #' @description #' Objects used for collecting Cocktail definitions. #' #' These objects work as \bold{expert systems} for recognition of defined #' vegetation units among plots of a [vegtable-class] object. #' A `shaker` object will be always dependent on a [vegtable-class] object, #' which is called `companion`. #' Since modifications in the `companion` may affect the functionality of #' the `shaker` object, it will be recommended to create the last during #' a session by a source script instead of recycling them from old R images. #' #' @slot pseudos List containing IDs of taxa that will be merged into #' pseudo-species. #' @slot groups List containing IDs of taxa belonging to the same Cocktail #' group. #' @slot dominants A data frame including lists of species used as dominant #' species in Cocktail algorithms, as well as operators and cover values #' used in the formulas. #' @slot formulas List with formulas that will be used as definitions for #' vegetation units. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @seealso [make_cocktail()] [set_pseudo()] [set_group()] [set_formula()] #' #' @examples #' showClass("shaker") #' @exportClass shaker #' setClass("shaker", slots = c( pseudos = "list", groups = "list", dominants = "data.frame", formulas = "list" ), prototype = list( pseudos = list(), groups = list(), dominants = data.frame( TaxonConceptID = integer(), operator = character(), value = numeric(), stringsAsFactors = FALSE ), formulas = list() ), validity = function(object) { if (any(duplicated(do.call(c, object@pseudos)))) { return("Some pseudo-species are sharing taxon concepts") } if (is.null(names(object@groups))) { return("Members of slot 'groups' have to be named") } if (any(duplicated(do.call(c, object@groups)))) { return("Some species groups are sharing taxon concepts") } if (any(!c("TaxonConceptID", "operator", "value") %in% colnames(object@dominants))) { return("Columns 'TaxonConceptID', 'operator', and 'value' are mandatory in slot 'dominants'") } if (any(duplicated(apply(object@dominants, 1, function(x) { gsub(" ", "", paste(x, collapse = " "), fixed = TRUE ) })))) { return("Some rules in slot 'dominants' are duplicated") } if (is.null(names(object@formulas))) { return("Members of slot 'formulas' have to be named") } if (any(duplicated(do.call(c, object@formulas)))) { return("Some formulas are duplicated") } } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/shaker-class.R
#' @name subset #' @aliases subset,vegtable-method #' #' @title Subset functions for vegtable objects #' #' @description #' Produce subsets of [vegtable-class] objects. #' #' Logical operations can be applied either to the plots, or the #' relations, which are the main slots in that class. #' #' This method can be referred to the slot `species` the same way as #' [taxlist::subset()], then the rest of the data will include only #' references to the subset of species list. #' #' @param x A [vegtable-class] object for subset. #' @param subset Logical expression for the subset. #' @param slot Character value indicating the slot used as reference for subset. #' At the moment only the values "taxonNames", "taxonRelations", #' "taxonTraits", "header", "samples", and "relations" are accepted. #' The three first values will be applied to the respective slots in the #' contained [taxlist-class] object (slot **species**). #' @param keep_children Argument passed to [taxlist::get_children()]. #' @param keep_parents Argument passed to [taxlist::get_parents()]. #' @param relation Character value indicating the relation (slot **relations**) #' to be used as reference for subset. #' @param ... Further arguments passed from or to other methods. #' #' @return A S4 object of class [vegtable-class]. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @examples #' ## Subset by taxon name #' Kenya_sub <- subset( #' x = Kenya_veg, subset = TaxonName == "Tagetes", #' slot = "taxonNames", keep_children = TRUE, keep_parents = TRUE #' ) #' summary(Kenya_sub) #' summary(Kenya_sub@species) #' #' ## Subset by taxon relations #' Kenya_sub <- subset( #' x = Kenya_veg, subset = Level == "species", #' slot = "taxonRelations" #' ) #' summary(Kenya_sub) #' summary(Kenya_sub@species) #' #' ## Subset by taxon traits #' Kenya_sub <- subset( #' x = Kenya_veg, subset = lf_behn_2018 == "obligate_annual", #' slot = "taxonTraits" #' ) #' summary(Kenya_sub) #' summary(Kenya_sub@species) #' #' ## Subset by header #' Kenya_sub <- subset(x = Kenya_veg, subset = ALTITUDE <= 1000, slot = "header") #' summary(Kenya_sub) #' #' ## Subset by samples (after converting coverage) #' Kenya_veg <- cover_trans(x = Kenya_veg, to = "cover_percentage", rule = "middle") #' Kenya_sub <- subset(x = Kenya_veg, subset = cover_percentage >= 50, slot = "samples") #' summary(Kenya_sub) #' #' ## Subset by relations #' Kenya_sub <- subset( #' x = Kenya_veg, subset = as.integer(YEAR) >= 2000, #' slot = "relations", relation = "REFERENCE" #' ) #' summary(Kenya_sub) #' @exportMethod subset #' setMethod( "subset", signature(x = "vegtable"), function(x, subset, slot = "header", keep_children = FALSE, keep_parents = FALSE, relation, ...) { p_slots <- c( "taxonNames", "taxonRelations", "taxonTraits", "header", "samples", "relations" ) if (!slot %in% p_slots) { stop(paste0( "Only following values are allowed for argument ", "'slot':\n\"", paste0(p_slots, collapse = "\" \"" ), "\"." )) } subset <- substitute(subset) # For subsets by taxonomic list if (slot %in% p_slots[1:3]) { # Duplicate taxlist object z <- x@species # in taxonNames if (slot == p_slots[1]) { subset <- eval(subset, z@taxonNames, parent.frame()) subset[is.na(subset)] <- FALSE z@taxonNames <- z@taxonNames[subset, ] } # in taxonRelations if (slot == p_slots[2]) { subset <- eval(subset, z@taxonRelations, parent.frame()) subset <- subset[!is.na(subset)] z@taxonRelations <- z@taxonRelations[subset, ] } # in taxonTraits if (slot == p_slots[3]) { subset <- eval(subset, z@taxonTraits, parent.frame()) subset[is.na(subset)] <- FALSE z@taxonTraits <- z@taxonTraits[subset, ] z@taxonRelations <- z@taxonRelations[ z@taxonRelations$TaxonConceptID %in% z@taxonTraits$TaxonConceptID, ] } # clean invalid taxlist object z <- clean(z) # recover relatives if (keep_children) { z <- get_children(x@species, z) } if (keep_parents) { z <- get_parents(x@species, z) } # back to x x@species <- z } # in header if (slot == p_slots[4]) { subset <- eval(subset, x@header, parent.frame()) subset[is.na(subset)] <- FALSE x@header <- x@header[subset, ] } # in samples if (slot == p_slots[5]) { subset <- eval(subset, x@samples, parent.frame()) subset[is.na(subset)] <- FALSE x@samples <- x@samples[subset, ] } # in relations if (slot == p_slots[6] & !missing(relation)) { if (!relation %in% names(x@relations)) { stop(paste0("\"", relation, "\" is not a relation in x.")) } subset <- eval(subset, x@relations[[relation]], parent.frame()) subset[is.na(subset)] <- FALSE x@relations[[relation]] <- x@relations[[relation]][subset, ] x@header <- x@header[paste(x@header[, relation]) %in% paste(x@relations[[relation]][, relation]), ] } # return clean object return(clean(x)) } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/subset.R
#' @name summary #' #' @title Summary method for vegtable objects #' #' @description #' Display summaries for [vegtable-class] objects. #' #' Those methods are implemented for objects of the classes [vegtable-class], #' [coverconvert-class] and [shaker-class]. #' #' The method for class `vegtable` retrieves the metadata, the size of #' the object, its validity and additional statistics on the content of input #' object. #' #' For objects of class [shaker-class], the function `summary()` will either #' retrieve general statistics when `companion` is missing, or a more detailed #' display when accompained by a [taxlist-class] or [vegtable-class] object. #' #' @param object,x Object to be summarized. #' @param units Units used for object size (passed to [format()]). #' @param companion Companion object (either a [taxlist-class] or a #' [vegtable-class] object. #' @param authority Logical value indicating whether authors should be #' displayed or not. #' @param ... further arguments to be passed to or from other methods. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @examples #' ## Summary for 'vegtable' objects #' summary(Wetlands_veg) #' @rdname summary #' @aliases summary,vegtable-method #' #' @exportMethod summary #' setMethod( "summary", signature(object = "vegtable"), function(object, units = "Kb", ...) { # Show original attributes (metadata) cat("## Metadata", "\n") if (length(object@description) > 0) { for (i in names(object@description)) { cat(" ", i, ": ", object@description[i], sep = "", "\n") } } cat(" object size:", format(object.size(object), units = units), sep = " ", "\n" ) cat(" validity:", validObject(object), "\n") cat("\n") # Content of some slots cat("## Content", "\n") cat(" number of plots:", nrow(object@header), sep = " ", "\n") cat(" plots with records:", length(unique(object@samples$ReleveID)), sep = " ", "\n" ) cat(" variables in header:", ncol(object@header), sep = " ", "\n") cat(" number of relations:", length(object@relations), sep = " ", "\n" ) cat("\n") # Content of species list cat("## Taxonomic List", "\n") cat(" taxon names:", nrow(object@species@taxonNames), sep = " ", "\n" ) cat(" taxon concepts:", nrow(object@species@taxonRelations), sep = " ", "\n" ) cat(" validity:", validObject(object@species), sep = " ", "\n") cat("\n") } ) #' @rdname summary #' @aliases summary,coverconvert-method #' #' @examples #' ## Summary for 'coverconvert' objects #' summary(braun_blanquet) setMethod( "summary", signature(object = "coverconvert"), function(object, ...) { cat("## Number of cover scales:", length(object@value), "\n") cat("\n") for (i in names(object@value)) { Levels <- paste(object@value[[i]]) Range_1 <- paste(object@conversion[[i]])[ -length(object@conversion[[i]]) ] Range_2 <- paste(object@conversion[[i]])[-1] for (j in 1:length(Range_2)) { if (duplicated(Range_2)[j]) Range_1[j] <- Range_1[j - 1] } cat(paste0("* scale '", i, "':"), "\n") print(data.frame(Levels = Levels, Range = paste( Range_1, "-", Range_2 ), stringsAsFactors = FALSE)) cat("\n") } } ) #' Re-writing formulas for print output #' #' Mediating between syntax and print format. #' #' @param shaker A [shaker-class] object. #' @param companion A companion data set which is either missing or a #' [vegtable-class] object. #' #' @return A formated output text. #' #' @keywords internal rewrite_formulas <- function(shaker, companion) { EQ <- list() for (i in names(shaker@formulas)) { EQ[[i]] <- { x <- shaker@formulas[[i]] if (grepl("\'", x)) SYM <- "\'" if (grepl('\"', x)) SYM <- '\"' x <- gsub("groups[[", "groups:", x, fixed = TRUE) x <- gsub("dominants[[", "species:", x, fixed = TRUE) x <- gsub("]]", "", x, fixed = TRUE) Spp <- as.numeric(unlist(regmatches( x, gregexpr( "[[:digit:]]+\\.*[[:digit:]]*", x ) ))) if (length(Spp) > 0) { for (j in Spp) { subformula <- shaker@dominants[j, ] subformula$TaxonConceptID <- companion[ match( subformula$TaxonConceptID, companion$TaxonConceptID ), "TaxonName" ] subformula <- paste(subformula[1, ], collapse = " ") x <- sub(paste0("species:", j), paste0( "species:", SYM, subformula, SYM ), x) } } x } } return(EQ) } #' @rdname summary #' @aliases summary,shaker-method #' #' @examples #' ## Summary for 'shaker' objects (alone and with companion) #' summary(Wetlands, Wetlands_veg) setMethod( "summary", signature(object = "shaker"), function(object, companion, authority = FALSE, ...) { if (missing(companion)) { cat("Number of pseudo-species:", length(object@pseudos), "\n") cat("Number of species groups:", length(object@groups), "\n") cat("Number of formulas:", length(object@formulas), "\n") } else { if (is(companion, "vegtable")) { companion <- companion@species } companion <- accepted_name(companion) if (authority) { companion$AuthorName[is.na(companion$AuthorName)] <- "" companion$TaxonName <- with(companion, paste( TaxonName, AuthorName )) } if (length(object@pseudos) > 0) { cat("## Pseudo-species:", "\n") for (i in 1:length(object@pseudos)) { cat( "*", paste0( "'", companion[ match( object@pseudos[[i]][1], companion$TaxonConceptID ), "TaxonName" ], "'" ), "contains:", "\n" ) for (j in 2:length(object@pseudos[[i]])) { cat(" ", companion[ match( object@pseudos[[i]][j], companion$TaxonConceptID ), "TaxonName" ], "\n") } } cat("\n") } if (length(object@groups) > 0) { cat("## Species groups:", "\n") for (i in 1:length(object@groups)) { cat("*", paste0( "'", names(object@groups)[i], "' group:" ), "\n") for (j in 1:length(object@groups[[i]])) { cat(" ", companion[ match( object@groups[[i]][j], companion$TaxonConceptID ), "TaxonName" ], "\n") } } cat("\n") } if (length(object@formulas) > 0) { cat("## Formulas:", "\n") EQ <- rewrite_formulas(object, companion) for (i in 1:length(object@formulas)) { cat( "*", paste0(names(object@formulas)[i], ":"), EQ[[i]], "\n" ) } cat("\n") } } } ) ################################################################################ #' @rdname summary #' #' @aliases show,vegtable-method #' #' @exportMethod show setMethod( "show", signature(object = "vegtable"), function(object) { summary(object) } ) #' @rdname summary #' #' @aliases print,vegtable-method setMethod( "print", signature(x = "vegtable"), function(x, ...) { summary(x, ...) } ) ################################################################################ #' @rdname summary #' #' @aliases show,coverconvert-method #' #' @exportMethod show setMethod( "show", signature(object = "coverconvert"), function(object) { summary(object) } ) #' @rdname summary #' #' @aliases print,coverconvert-method setMethod( "print", signature(x = "coverconvert"), function(x, ...) { summary(x, ...) } ) ################################################################################ #' @rdname summary #' #' @aliases show,shaker-method #' #' @exportMethod show setMethod( "show", signature(object = "shaker"), function(object) { summary(object) } ) #' @rdname summary #' #' @aliases print,shaker-method setMethod( "print", signature(x = "shaker"), function(x, ...) { summary(x, ...) } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/summary.R
#' @name taxa2samples #' #' @title Insert taxon information into samples #' #' @description #' For statistical purposes it may be necessary to insert information on #' recorded taxa into the slot samples, which contain the records of taxa in #' sampling plots. #' This can be also done selectivelly for specific taxonomic ranks and lower #' ranks can be aggregated to their parental ones. #' #' If column **TaxonConceptID** is already existing in `'objec@@samples'`, #' this column will get overwritten, retrieving a warning message. #' #' @param object A [vegtable-class] object. #' @param merge_to Character value indicating the level (taxonomic rank) to #' which taxa of lower rank have to be merged. #' @param include_levels Character vector indicating the levels to be considered #' in the output object. This will set the values of **TaxonConceptID** and #' any respective values inserted from slots **taxonRelations** and #' **taxonTraits** as NA. #' @param add_relations A logical value indicating whether the content of slot #' **taxonRelations** have to be inserted in slot **samples** or not. #' @param add_traits A logical value indicating whether the content of slot #' **taxonTraits** have to be inserted in slot **samples** or not. #' @param ... Further arguments passed among methods. #' #' @return An object of class [vegtable-class]. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @examples #' ## Add only variable TaxonConceptID #' veg <- taxa2samples(Kenya_veg) #' head(veg@samples) #' #' ## Add also information from slots taxonRelations and taxonTraits #' veg <- taxa2samples(Kenya_veg, add_relations = TRUE, add_traits = TRUE) #' head(veg@samples) #' #' ## Different ranks recorded at samples #' veg <- taxa2samples(Kenya_veg, add_relations = TRUE) #' summary(veg@samples$Level) #' #' ## Aggregate taxa to family level #' veg <- taxa2samples(Kenya_veg, add_relations = TRUE, merge_to = "family") #' summary(veg@samples$Level) #' #' @rdname taxa2samples #' #' @aliases taxa2samples #' #' @export taxa2samples taxa2samples <- function(object, ...) { UseMethod("taxa2samples", object) } #' @rdname taxa2samples #' @aliases taxa2samples,vegtable-method #' @method taxa2samples vegtable #' @export taxa2samples.vegtable <- function(object, merge_to, include_levels, add_relations = FALSE, add_traits = FALSE, ...) { # Delete existing entries for TaxonConceptIDs if ("TaxonConceptID" %in% names(object@samples)) { warning(paste( "Entries of 'TaxonConceptID' detected in 'objec@samples'.", "They will get overwritten." )) object@samples <- object@samples[ , names(object@samples) != "TaxonConceptID" ] } # Internal objects spp <- used_concepts(object, keep_children = TRUE, keep_parents = TRUE) samples <- data.frame(TaxonUsageID = unique(object@samples$TaxonUsageID)) samples$TaxonConceptID <- spp@taxonNames$TaxonConceptID[ match(samples$TaxonUsageID, spp@taxonNames$TaxonUsageID) ] # Merge to level if (!missing(merge_to)) { if (!merge_to[1] %in% levels(spp)) { stop(paste( "Value of argument 'merge_to' is not a level in", "'object'." )) } x <- which(levels(spp) == merge_to[1]) - 1 for (i in 1:x) { Level <- spp@taxonRelations$Level[match( samples$TaxonConceptID, spp@taxonRelations$TaxonConceptID )] concept <- unique(samples$TaxonConceptID[as.integer(Level) == i & !is.na(Level)]) if (length(concept) > 0) { concept_parent <- spp@taxonRelations$Parent[match( concept, spp@taxonRelations$TaxonConceptID )] samples$TaxonConceptID <- replace_x(samples$TaxonConceptID, old = concept, new = concept_parent ) } } } # Select some ranks if (!missing(include_levels)) { no_level <- include_levels[!include_levels %in% levels(spp)] if (length(no_level) > 0) { stop(paste0( "These values of 'include_levels' are not levels ", "at slot 'species':\n'", paste0(no_level, collapse = "', '"), "'" )) } Level <- spp@taxonRelations$Level[match( samples$TaxonConceptID, spp@taxonRelations$TaxonConceptID )] samples <- samples[paste(Level) %in% include_levels & !is.na(Level), ] } if (add_relations) { samples <- merge(samples, spp@taxonRelations, sort = FALSE) } if (add_traits) { samples <- merge(samples, spp@taxonTraits, sort = FALSE, all.x = TRUE) } object@samples <- merge(object@samples, samples, by = "TaxonUsageID", sort = FALSE, all.x = TRUE, suffixes = c("", "_y") # Preserve original column name ) return(object) }
/scratch/gouwar.j/cran-all/cranData/vegtable/R/taxa2samples.R
#' @name trait_stats #' #' @title Statistics and proportion for taxon traits #' #' @description #' Calculation of statistics and proportions of taxon traits for plot #' observations or groups of observations, considering data relationships, #' taxonomic ranks and the handling of not available values. #' #' In `trait_stats()` you can use customized functions, which have to be #' defined as `foo(x, w, ...)`, where `'x'` is the (numeric) taxon trait and #' `'w'` is the weight (e.g. the abundance). #' #' With the arguments `taxon_levels` and `merge_to` the used taxonomic ranks #' can be defined, where the first one indicates which ranks #' have to be considered in the calculations and the second one determine the #' aggregation of taxa from a lower level to a parental one. #' #' @param trait Either a character value indicating the name of trait variable #' or a formula as `'trait ~ head_var'`. Note that you can add multiple #' variables in the form `trait_1 + ... + trait_n ~ head_var`. #' @param object A [vegtable-class] object. #' @param FUN A function usually defined as `foo(x, ...)` or as #' `foo(x, w, ...)` for weighted statistics. #' @param head_var Character value, the name of the variable at slot header to #' be used as aggregation level for the calculation of statistics or #' proportions. #' If not provided, the function will use **ReleveID** by default. #' @param trait_levels Character vector indicating a selection of levels from a #' trait, in the case that some levels should be ignored in the output. #' Trait levels that are skipped at output will be still used for the #' calculation of proportions. #' This argument gets only applied for the character method. #' @param taxon_levels Character vector indicating the selected taxonomic ranks #' to be considered in the output. #' @param merge_to Character value indicating the taxonomic rank for #' aggregation of taxa. #' All ranks lower than the one indicated here will be assigned to the #' respective parents at the required taxonomic rank. #' @param include_nas Logical value indicating whether NAs should be considered #' for the calculation of proportions or not. #' @param weight Character value indicating the name of the variable at slot #' **samples** used as weight for the proportions. Usually the numeric #' abundance. #' @param suffix A suffix added to the name of the trait variable or to the #' levels of categorical trait variables. I is meant to avoid homonymous #' variables within the same object. #' @param in_header Logical value indicating whether the output should be #' inserted in the slot **header** or provided as data frame. In the case #' that `'head_var'` (or the right term in the formula method) is different #' from **ReleveID**, the statistics and proportions will be inserted in the #' respective data frame at slot **relations**. #' @param na.rm A logical value indicating whether NAs should be removed for the #' calculation of statistics or not. It is passed to `'FUN'` in #' `trait_stats()`. #' @param ... Further arguments passed among methods. In the case of the #' character method, they are passed to 'FUN'. #' #' @return #' A data frame with the proportions of traits levels or statistics for #' the trait variable, or an object of class [vegtable-class] including those #' results at the slot `header`. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @examples #' veg <- cover_trans(Kenya_veg, to = "cover") #' veg <- trait_proportion("lf_behn_2018", veg, #' trait_levels = "obligate_annual", weight = "cover", include_nas = FALSE #' ) #' summary(veg$obligate_annual_prop) #' @rdname trait_stats NULL #' @name check_args #' @title Check validity of arguments for statistics #' @description #' Check validity of arguments in functions [trait_stats()] and #' [trait_proportion()]. #' @keywords internal check_args <- function(object, trait, head_var, weight, taxon_levels, merge_to, trait_levels) { if (!all(trait %in% names(object@species@taxonTraits))) { trait <- trait[!trait %in% names(object@species@taxonTraits)] stop(paste0( "Following values in 'trait' are missing at ", "'object@species@taxonTraits': ", paste0(trait, collapse = ", "), "." )) } if (!head_var %in% colnames(object@header)) { stop("Value of argument 'head_var' is not a variable at header.") } if (!missing(taxon_levels)) { if (!all(taxon_levels %in% taxlist::levels(object@species))) { taxon_levels <- taxon_levels[!taxon_levels %in% taxlist::levels(object@species)] stop(paste0( "Following values in 'taxon_levels'", "are not taxonomic ranks at 'object@species': ", paste0(taxon_levels, collapse = ", "), "." )) } } if (!missing(merge_to)) { if (!merge_to %in% taxlist::levels(object@species)) { stop(paste( "Value of in argument 'merge_to'", "is not included in the taxonomic list." )) } } if (!missing(weight)) { if (!weight %in% colnames(object@samples)) { stop("Value of argument 'weight' is not included at slot samples.") } } if (!missing(trait_levels)) { if (!all(trait_levels %in% object@species@taxonTraits[, trait])) { trait_levels <- trait_levels[!trait_levels %in% object@species@taxonTraits[, trait]] stop(paste0( "Following values of 'trait_levels' ", "are not included in trait '", trait, "': '", paste0(trait_levels, collapse = "', '"), "'." )) } } } #' @rdname trait_stats #' @exportMethod trait_stats setGeneric( "trait_stats", function(trait, object, ...) { standardGeneric("trait_stats") } ) #' @rdname trait_stats #' @aliases trait_stats,character,vegtable-method setMethod( "trait_stats", signature(trait = "character", object = "vegtable"), function(trait, object, FUN, head_var = "ReleveID", taxon_levels, merge_to, weight, suffix = "_stats", in_header = TRUE, na.rm = TRUE, ...) { # Check conditions check_args(object, trait, head_var, weight, taxon_levels, merge_to) # Retain original object object_in <- object # Transfer head variable to samples if (head_var != "ReleveID") { object@samples[, head_var] <- with( object@header, replace_x( object@samples$ReleveID, ReleveID, get(head_var) ) ) } # Get traits in slot samples if (missing(taxon_levels)) { taxon_levels <- taxlist::levels(object_in@species) } if (missing(merge_to)) { object <- taxa2samples(object, include_levels = taxon_levels, add_traits = TRUE ) } else { object <- taxa2samples(object, include_levels = taxon_levels, add_traits = TRUE, merge_to = merge_to ) } # In case of weighted statistics if (!missing(weight)) { OUT <- list() OUT[[head_var]] <- unique(object@samples[, head_var]) for (i in trait) { x <- with(object@samples, split(get(i), get(head_var))) w <- with(object@samples, split(get(weight), get(head_var))) OUT[[i]] <- mapply(FUN, x = x, w = w, na.rm = na.rm, ...) } OUT <- as.data.frame(OUT) } else { OUT <- aggregate( as.formula(paste0( "cbind(", paste0(trait, collapse = ","), ") ~ ", head_var )), object@samples, FUN, na.rm = na.rm, ... ) } names(OUT) <- replace_x(names(OUT), old = trait, new = paste0(trait, suffix) ) # Finally the output if (in_header) { if (head_var == "ReleveID") { for (i in names(OUT)[names(OUT) != head_var]) { object_in@header[, i] <- OUT[match( object_in@header[, head_var], OUT[, head_var] ), i] } return(object_in) } else { if (!head_var %in% names(object_in@relations)) { new_relation(object_in) <- head_var } for (i in names(OUT)[names(OUT) != head_var]) { object_in@relations[[head_var]][, i] <- OUT[ match( object_in@relations[[head_var]][, head_var], OUT[, head_var] ), i ] } return(object_in) } } else { return(OUT) } } ) #' @rdname trait_stats #' @aliases trait_stats,formula,vegtable-method setMethod( "trait_stats", signature(trait = "formula", object = "vegtable"), function(trait, object, ...) { head_var <- all.vars(update(trait, 0 ~ .)) trait <- all.vars(update(trait, . ~ 0)) return(trait_stats(trait, object, head_var = head_var, ...)) } ) #' @rdname trait_stats #' @aliases trait_proportion #' @exportMethod trait_proportion setGeneric( "trait_proportion", function(trait, object, ...) { standardGeneric("trait_proportion") } ) #' @rdname trait_stats #' @aliases trait_proportion,character,vegtable-method setMethod( "trait_proportion", signature(trait = "character", object = "vegtable"), function(trait, object, head_var = "ReleveID", trait_levels, taxon_levels, merge_to, include_nas = TRUE, weight, suffix = "_prop", in_header = TRUE, ...) { # Only one trait is allowed for this function if (length(trait) > 1) { stop("Only one trait can be assessed by 'trait_proportion'.") } # Check conditions check_args( object, trait, head_var, weight, taxon_levels, merge_to, trait_levels ) # Retain original object object_in <- object # Transfer head variable to samples if (head_var != "ReleveID") { object@samples[, head_var] <- with( object@header, replace_x( object@samples$ReleveID, ReleveID, get(head_var) ) ) } # Get traits in slot samples if (missing(taxon_levels)) { taxon_levels <- taxlist::levels(object_in@species) } if (missing(merge_to)) { object <- taxa2samples(object, include_levels = taxon_levels, add_traits = TRUE ) } else { object <- taxa2samples(object, include_levels = taxon_levels, add_traits = TRUE, merge_to = merge_to ) } # Include NAs if (include_nas) { object@samples[is.na(object@samples[, trait]), trait] <- "NA" } else { object@samples <- object@samples[!is.na(object@samples[, trait]), ] } # Calculate output if (missing(weight)) { weight <- "count_presence" count_presence <- rep(1, nrow(object@samples)) } OUT <- aggregate(as.formula(paste(weight, "~", trait, "+", head_var)), data = object@samples, FUN = sum ) SUM <- aggregate(as.formula(paste(weight, "~", head_var)), data = object@samples, FUN = sum ) SUM <- SUM[match(OUT[, head_var], SUM[, head_var]), weight] OUT[, weight] <- OUT[, weight] / SUM # Filter to selected trait levels if (!missing(trait_levels)) { OUT <- OUT[OUT[, trait] %in% trait_levels, ] } OUT[, trait] <- paste0(OUT[, trait], suffix) OUT <- crosstable( as.formula(paste( weight, "~", trait, "+", head_var )), OUT, sum, na_to_zero = TRUE ) # Last output if (in_header) { if (head_var == "ReleveID") { for (i in names(OUT)[names(OUT) != head_var]) { object_in@header[, i] <- OUT[match( object_in@header[, head_var], OUT[, head_var] ), i] } return(object_in) } else { if (!head_var %in% names(object_in@relations)) { new_relation(object_in) <- head_var } for (i in names(OUT)[names(OUT) != head_var]) { object_in@relations[[head_var]][, i] <- OUT[ match( object_in@relations[[head_var]][, head_var], OUT[, head_var] ), i ] } return(object_in) } } else { return(OUT) } } ) #' @rdname trait_stats #' @aliases trait_proportion,formula,vegtable-method setMethod( "trait_proportion", signature(trait = "formula", object = "vegtable"), function(trait, object, ...) { head_var <- all.vars(update(trait, 0 ~ .)) trait <- all.vars(update(trait, . ~ 0)) return(trait_proportion(trait, object, head_var = head_var, ...)) } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/trait_stats.R
#' @name tv2vegtable #' #' @title Import of vegetation data from Turboveg databases #' #' @description #' Import function for **Turboveg** databases into an object of class #' [vegtable-class]. #' Most of the contents of **Turboveg** databases are included in DBF files and #' therefore imported by the function [foreign::read.dbf()]. #' The automatic setting of database path will be done by the function #' [vegdata::tv.home()] but it can be customised by the argument `tv_home`. #' #' The species list will be imported by using the function #' [taxlist::tv2taxlist()] and therefore formatted as a [taxlist-class] object. #' Similarly, conversion tables will be handled as [coverconvert-class] objects. #' #' Empty columns in the header will be deleted in the imported object. #' #' The function `tv2coverconvert()` reads the content of cover conversion #' tables stored in **Turboveg** and attempts to reformat them in a more #' comprehensive structure. #' #' This function is used by `tv2vegtable()` to import the respective #' conversion table from **Turboveg** databases. #' Note that conversion tables in **Turboveg** have only stored the middle #' point for each cover class in a scale, thus it will be recommended to #' rebuild the `coverconvert` slot or use [braun_blanquet]. #' #' @param db Name of **Turboveg** data base as character value. #' @param tv_home **Turboveg** installation path as character value. #' @param skip_empty_relations Logical value indicating whether empty relations #' may be excluded from imported database or not. #' @param skip_scale Character value indicating scales to be excluded in slot #' `coverconvert`. #' @param clean Logical value indicating whether output object should be #' cleaned or not. #' #' @return #' A [vegtable-class] object in the case of `tv2vegtable()`. #' A [coverconvert-class] object in the case of `tv2coverconvert()`. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @seealso [taxlist::tv2taxlist()] [foreign::read.dbf()] [vegdata::tv.home()] #' #' @examples #' ## Installed 'Turboveg' version of 'Fujiwara et al. (2014)' #' # TV_Home <- file.path(path.package("vegtable"), "tv_data") #' # Veg <- tv2vegtable("Fujiwara_2014", TV_Home) #' # summary(Veg) #' @rdname tv2vegtable #' #' @export #' tv2vegtable <- function(db, tv_home = tv.home(), skip_empty_relations = TRUE, skip_scale, clean = TRUE) { # Import meta data --------------------------------------------------------- description <- unlist(c(db, read.dbf(file.path( tv_home, "Data", db, "tvwin.dbf" ), as.is = TRUE)[, c( "FLORA", "DICTIONARY" ), drop = FALSE])) names(description) <- c("db_name", "sp_list", "dictionary") # Importing samples -------------------------------------------------------- samples <- read.dbf(file.path(tv_home, "Data", db, "tvabund.dbf"), as.is = TRUE ) colnames(samples)[colnames(samples) == "RELEVE_NR"] <- "ReleveID" colnames(samples)[colnames(samples) == "SPECIES_NR"] <- "TaxonUsageID" colnames(samples)[grepl("ORIG_NAME", colnames(samples))] <- "ORIG_NAME" samples$COVER_CODE[samples$COVER_CODE == "9X"] <- "100" samples$COVER_CODE[samples$COVER_CODE == "99"] <- "100" # Importing header data ---------------------------------------------------- header <- read.dbf(file.path(tv_home, "Data", db, "tvhabita.dbf"), as.is = TRUE ) colnames(header)[colnames(header) == "RELEVE_NR"] <- "ReleveID" # Formating dates and some numeric variables header$DATE <- as.Date(header$DATE, format = "%Y%m%d") header$ALTITUDE <- as.numeric(header$ALTITUDE) header$INCLINATIO <- as.numeric(header$INCLINATIO) # replacing zero values with NAs cat("zero values will be replaced by NAs", "\n") for (i in colnames(header)) { if (is.numeric(header[, i])) header[, i][header[, i] == 0] <- NA } remarks <- read.dbf(file.path(tv_home, "Data", db, "remarks.dbf"), as.is = TRUE ) remarks <- split(remarks$REMARKS, remarks$RELEVE_NR) for (i in as.integer(names(remarks))) { header[header$ReleveID == i, "REMARKS"] <- paste( header[ header$ReleveID == i, "REMARKS" ], paste(remarks[[paste(i)]], collapse = " "), collapse = " " ) } # Importing coverconvert --------------------------------------------------- if (!is.na(description["dictionary"])) { cover_home <- file.path( tv_home, "popup", description["dictionary"], "tvscale.dbf" ) } else { cover_home <- file.path(tv_home, "popup", "tvscale.dbf") } coverconvert <- tv2coverconvert(cover_home) if (!missing(skip_scale)) { coverconvert@value <- coverconvert@value[ !names(coverconvert@value) %in% skip_scale ] coverconvert@conversion <- coverconvert@conversion[ !names(coverconvert@conversion) %in% skip_scale ] } cover_match <- read.dbf(cover_home, as.is = TRUE)[, c( "SCALE_NR", "SCALE_NAME", "SCALE_CODE" )] cover_match$SCALE_CODE <- tolower(sub("/", "_", cover_match$SCALE_CODE, fixed = TRUE )) cover_code <- samples[, c("ReleveID", "COVER_CODE")] cover_code$entry <- as.numeric(row.names(samples)) cover_code <- split(cover_code, header$COVERSCALE[match( samples$ReleveID, header$ReleveID )]) for (i in names(cover_code)) { samples[, cover_match[cover_match$SCALE_NR == i, "SCALE_CODE"]] <- cover_code[[i]][match( as.numeric(rownames(samples)), cover_code[[i]]$entry ), "COVER_CODE"] } # Get percentage to numeric cover_code <- cover_match[cover_match$SCALE_NR == "00", "SCALE_CODE"] if (cover_code %in% colnames(samples)) { samples[, cover_code] <- as.numeric(samples[, cover_code]) } for (i in slotNames(coverconvert)) { slot(coverconvert, i) <- slot(coverconvert, i)[names(slot(coverconvert, i)) != cover_code] } # Factorize cover_code <- names(coverconvert)[names(coverconvert) != cover_code] for (i in cover_code) { if (i %in% colnames(samples)) { samples[, i] <- factor(samples[, i], levels = base::levels(coverconvert@value[[i]]) ) } } # Importing relations ------------------------------------------------------ if (is.na(description["dictionary"])) { relations_path <- file.path(tv_home, "popup") } else { relations_path <- file.path( tv_home, "popup", description["dictionary"] ) } Files <- list.files(relations_path, pattern = ".dbf", ignore.case = TRUE) Files <- Files[!toupper(Files) %in% c( "dbasedic.dbf", "files.dbf", "tvscale.dbf" )] relations <- list() for (i in Files) { relations[[tolower(i)]] <- read.dbf(file.path(relations_path, i), as.is = TRUE ) } # some changes are needed in the standard relations colnames(relations$country.dbf)[1:2] <- c("COUNTRY", "COUNTRY_NAME") colnames(relations$syntaxa.dbf)[1:2] <- c("SYNTAXON", "SYNTAXON_NAME") colnames(relations$tvauthor.dbf)[1] <- c("AUTHOR") # Next cases have to be reformatted relations$tvauthor.dbf[, 1] <- as.integer(relations$tvauthor.dbf[, 1]) relations$tvprojct.dbf[, 1] <- as.integer(relations$tvprojct.dbf[, 1]) relations$tvrefenc.dbf[, 1] <- as.integer(relations$tvrefenc.dbf[, 1]) relations$syntaxa.dbf[, 1] <- as.integer(relations$syntaxa.dbf[, 1]) # Deleting empty relations if (skip_empty_relations) relations <- relations[sapply(relations, nrow) > 0] # Rename relations as first column names(relations) <- sapply(sapply(relations, colnames), "[", 1) # Insert details of cover scales in relations relations[["COVERSCALE"]] <- cover_match colnames(relations[["COVERSCALE"]])[1] <- "COVERSCALE" # Final object VEG <- new("vegtable") VEG@description <- description VEG@samples <- samples VEG@header <- header VEG@species <- tv2taxlist(description["sp_list"], tv_home) VEG@coverconvert <- coverconvert for (i in names(relations)) { if (colnames(relations[[i]])[1] %in% colnames(VEG@header)) { veg_relation(VEG) <- relations[[i]] } } if (clean) VEG <- clean(VEG) return(VEG) } #' @rdname tv2vegtable #' @aliases tv2coverconvert #' #' @param file A connection to a DBF file containing conversion table in #' **Turboveg**. #' @param as.is A logical value passed to [read.dbf()]. #' #' @examples #' ## Installed 'Turboveg' version of "Fujiwara et al. (2014)" #' TV_Home <- file.path(path.package("vegtable"), "tv_data", "popup", "Swea") #' Table <- tv2coverconvert(file.path(TV_Home, "tvscale.dbf")) #' #' ## First scale have to be deleted from conversion table #' Table@value <- Table@value[-1] #' Table@conversion <- Table@conversion[-1] #' summary(Table) #' #' ## Compare the 'Turboveg' version with a vegtable version #' data(braun_blanquet) #' summary(Table$br_bl) #' summary(braun_blanquet$br_bl) #' @export #' tv2coverconvert <- function(file, as.is = TRUE) { file <- read.dbf(file, as.is) file <- split(file, file$SCALE_NR) conversion <- new("coverconvert") for (i in names(file)) { short_name <- tolower(sub("/", "_", file[[i]]$SCALE_CODE, fixed = TRUE)) cover1 <- t(file[[i]][, seq(4, dim(file[[i]])[2], 2)])[, 1] cover2 <- t(file[[i]][, seq(5, dim(file[[i]])[2], 2)])[, 1] cover2 <- cover2[!is.na(cover1)] cover1 <- cover1[!is.na(cover1)] cover1 <- cover1[order(cover2)] cover2 <- cover2[order(cover2)] names(cover1) <- names(cover2) <- NULL conversion@value[[short_name]] <- factor(cover1, levels = cover1) conversion@conversion[[short_name]] <- c(0, cover2) } return(conversion) }
/scratch/gouwar.j/cran-all/cranData/vegtable/R/tv2vegtable.R
#' @name update_det #' #' @title Update by determined specimens #' #' @description #' Reference specimens can be integrated in slot **layers** within a #' [vegtable-class] object. #' Updated entries in the specimens can be updated in slot **samples** by using #' this function. #' Alternatively expert opinions can be inserted and applied in case of #' disagreement with the original records. #' #' @param x A [vegtable-class] object to be updated. #' @param specimens A character vector indicating the names of tables included #' in slot **layers** with updates to be applied. #' Note that they will be applied in the same order of the vector in the #' case of multiple updates. #' @param ... Further arguments (not yet in use). #' #' @rdname update_det #' #' @exportMethod update_det #' setGeneric( "update_det", function(x, specimens, ...) { standardGeneric("update_det") } ) #' @rdname update_det #' #' @aliases update_det,vegtable-method #' setMethod( "update_det", signature(x = "vegtable", specimens = "character"), function(x, specimens, ...) { if (any(!specimens %in% names(x@layers))) { stop(paste( "Some values in 'specimens' are not included", "as layer in 'x'." )) } for (i in specimens) { if (!"TaxonUsageID" %in% colnames(x@layers[[i]])) { stop(paste0( "At \"", i, "\", column 'TaxonUsageID' is ", "mandatory in list of specimens." )) } specimens_tab <- x@layers[[i]][x@layers[[i]][, i] %in% x@samples[, i], ] if (any(!specimens_tab$TaxonUsageID %in% x@species@taxonNames$TaxonUsageID)) { stop(paste0( "At \"", i, "\", some taxon usage names ", "are not included in slot 'species'." )) } x@samples$TaxonUsageID <- replace_idx( x@samples$TaxonUsageID, x@samples[, i], specimens_tab[, i], specimens_tab$TaxonUsageID ) } # In the case that taxa2samples was applied before if ("TaxonConceptID" %in% colnames(x@samples)) { warning("You may like to repeat 'taxa2samples()' on 'x'.") } return(x) } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/update_det.R
#' @name used_synonyms #' #' @title Retrieve synonyms or taxon concepts used in a data set #' #' @description #' Plots records are rather linked to plant names than plant taxon concepts and #' `used_synonyms()` lists all synonyms linked to records in a [vegtable-class] #' object, including their respective accepted names. #' #' On the other side, the function `used_concepts()` produces a subset of the #' taxonomic list embeded in the slot **species** including only taxonomic #' concepts linked to records in the slot **samples**. #' #' @param x A [vegtable-class] object. #' @param keep_children A logical argument indicating whether children of #' selected taxa should be included in the output or not. #' This argument passed to [get_children()]. #' @param keep_parents A logical argument indicating whether parents of #' selected taxa should be included in the output or not. #' This argument passed to [get_parents()]. #' @param ... Further arguments to be passed from or to another methods. #' #' @return #' The function `used_synonyms()` returns a data frame including following #' variables: #' \describe{ #' \item{SynonymID}{ID of the taxon usage name applied as synonym.} #' \item{Synonym}{The synonym itself.} #' \item{SynonymAuthor}{Author of synonym.} #' \item{TaxonConceptID}{ID of the respective taxon concept.} #' \item{AcceptedNameID}{ID of the taxon usage name set as accepted name of #' the taxon concept.} #' \item{AcceptedName}{The respective accepted name.} #' \item{AcceptedNameAuthor}{The author of the accepted name.} #' } #' #' The function `used_concepts()` returns a [taxlist-class] object including #' only taxa occurring in the plot observations of the input [vegtable-class] #' object. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @seealso [accepted_name()] #' #' @examples #' ## Synonyms used in the Kenya_veg #' Synonyms <- used_synonyms(Kenya_veg) #' head(Synonyms) #' #' ## Subset species list to used concepts #' species <- used_concepts(Kenya_veg) #' Kenya_veg@species #' species #' #' @rdname used_synonyms #' @export used_synonyms <- function(x, ...) { UseMethod("used_synonyms", x) } #' @rdname used_synonyms #' @aliases used_synonyms,vegtable-method #' @method used_synonyms vegtable #' @export used_synonyms.vegtable <- function(x, ...) { SYN <- x@samples$TaxonUsageID[!x@samples$TaxonUsageID %in% x@species@taxonRelations$AcceptedName] SYN <- data.frame(SynonymID = unique(SYN), stringsAsFactors = FALSE) SYN$Synonym <- x@species@taxonNames$TaxonName[match( SYN$SynonymID, x@species@taxonNames$TaxonUsageID )] SYN$SynonymAuthor <- x@species@taxonNames$AuthorName[ match(SYN$SynonymID, x@species@taxonNames$TaxonUsageID) ] SYN$TaxonConceptID <- x@species@taxonNames$TaxonConceptID[ match(SYN$SynonymID, x@species@taxonNames$TaxonUsageID) ] SYN$AcceptedNameID <- x@species@taxonRelations$AcceptedName[ match( SYN$TaxonConceptID, x@species@taxonRelations$TaxonConceptID ) ] SYN$AcceptedName <- x@species@taxonNames$TaxonName[ match( SYN$AcceptedNameID, x@species@taxonNames$TaxonUsageID ) ] SYN$AcceptedNameAuthor <- x@species@taxonNames$AuthorName[ match( SYN$AcceptedNameID, x@species@taxonNames$TaxonUsageID ) ] return(SYN) } #' @rdname used_synonyms #' @export used_concepts <- function(x, ...) { UseMethod("used_concepts", x) } #' @rdname used_synonyms #' @aliases used_concepts,vegtable-method #' @method used_concepts vegtable #' @export used_concepts.vegtable <- function(x, keep_children = FALSE, keep_parents = FALSE, ...) { concepts <- unique(x@species@taxonNames$TaxonConceptID[ x@species@taxonNames$TaxonUsageID %in% x@samples$TaxonUsageID ]) z <- x@species z@taxonRelations <- z@taxonRelations[ z@taxonRelations$TaxonConceptID %in% concepts, ] z <- clean(z) if (keep_children) { z <- get_children(x@species, z) } if (keep_parents) { z <- get_parents(x@species, z) } return(z) }
/scratch/gouwar.j/cran-all/cranData/vegtable/R/used_synonyms.R
#' @name veg_aggregate #' @rdname veg_aggregate #' #' @title Aggregating information into a data frame #' #' @description #' Compute summarizing tables from [vegtable-class] objects. #' This function works in a similar way as [crosstable()]. #' #' @param object A formula indicating the variables used for the summary. #' As in [crosstable()], the keywords `"TaxonName"` and `"AcceptedName"` #' can be used to retrieve taxonomic names, where the second will set the #' accepted name for names considered as synonyms. #' @param data Either a data frame or an object of class [vegtable-class]. #' @param FUN Function used to aggregate values. #' @param use_nas Logical value indicating whether NA's should be included in #' categorical variables or not. #' @param ... Further arguments passed to the function [stats::aggregate()]. #' #' @return An object of class [data.frame]. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @seealso [aggregate()] #' #' @examples #' ## Transform cover to percentage cover #' veg <- cover_trans(x = Kenya_veg, to = "cover") #' #' ## Frequency of taxa per publication #' atab <- veg_aggregate(object = cover ~ AcceptedName + REFERENCE, data = veg, FUN = length) #' head(atab) #' #' ## Life form proportions per plot #' atab <- veg_aggregate(object = cover ~ lf_behn_2018 + ReleveID, data = veg, FUN = sum) #' head(atab) #' #' @exportMethod veg_aggregate setGeneric( "veg_aggregate", function(object, data, FUN, ...) { standardGeneric("veg_aggregate") } ) #' @rdname veg_aggregate #' @aliases veg_aggregate,formula,vegtable,function-method setMethod( "veg_aggregate", signature( object = "formula", data = "vegtable", FUN = "function" ), function(object, data, FUN, use_nas = TRUE, ...) { Terms <- c(as.character(object)[2], attr( terms(object), "term.labels" )) if (any(Terms %in% names(data@species@taxonTraits))) { data <- taxa2samples(data, add_traits = TRUE) } if (any(c("TaxonName", "AcceptedName") %in% Terms)) { if (all(c("TaxonName", "AcceptedName") %in% Terms)) { stop(paste( "Terms 'TaxonName' and 'AcceptedName'", "are mutually exclusive in 'formula'" )) } data <- taxa2samples(data) } # Variables from samples if (any(Terms %in% names(data@samples))) { new_data <- data@samples[, colnames(data@samples) %in% c("ReleveID", "TaxonUsageID", "TaxonConceptID", Terms), drop = FALSE] } else { if (any(Terms %in% c("TaxonName", "AcceptedName"))) { new_data <- data@samples[ , c("ReleveID", "TaxonUsageID", "TaxonConceptID") ] } else { new_data <- data.frame(ReleveID = integer()) } } # 1: when usage name requested if ("TaxonName" %in% Terms) { new_data$TaxonName <- data@species@taxonNames$TaxonName[ match(new_data$TaxonUsageID, data@species@taxonNames$TaxonUsageID) ] new_data$AuthorName <- data@species@taxonNames$AuthorName[ match(new_data$TaxonUsageID, data@species@taxonNames$TaxonUsageID) ] } # 2: when accepted name requested if ("AcceptedName" %in% Terms) { new_data$AcceptedNameID <- data@species@taxonRelations$AcceptedName[ match( new_data$TaxonConceptID, data@species@taxonRelations$TaxonConceptID ) ] new_data$AcceptedName <- data@species@taxonNames$TaxonName[ match(new_data$AcceptedNameID, data@species@taxonNames$TaxonUsageID) ] new_data$AuthorName <- data@species@taxonNames$AuthorName[ match(new_data$AcceptedNameID, data@species@taxonNames$TaxonUsageID) ] } # Data from header if (any(Terms %in% names(data@header))) { new_data <- merge(new_data, data@header[, names(data@header) %in% c("ReleveID", Terms), drop = FALSE], sort = FALSE, all.y = TRUE) } # Call aggregate on new_data if (use_nas) { for (i in Terms[-1]) { if (is.factor(new_data[, i])) { new_data[, i] <- paste(new_data[, i]) } if (is.character(new_data[, i])) { new_data[is.na(new_data[, i]), i] <- "" } } } return(aggregate(object, new_data, FUN, ...)) } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/veg_aggregate.R
#' @name veg_diverstiy #' @rdname veg_diversity #' #' @title Calculation of statistics at plot level #' #' @description #' Calculation of diversity statistics at the plot level allowing for customized #' functions defined as `foo(x, ...)`, where `x` is the vector of abundance #' values. #' #' This function calls [taxa2samples()] to derive taxa from taxon usage names in #' slot **samples** and multiple records of species in a single plot will be #' merged by [stats::aggregate][aggregate()]. #' #' The functions `shannon()`, `evenness()`, and `dominance()` calculate the #' diversity index of Shannon, the evenness, and the dominance #' (*1 - evenness*), respectively. #' Dominance is the complementary value to evenness (i.e. `1 - evenness`). #' #' The function `simpson()` calculates the Simpson's index using the alternative #' for vegetation plot observations. #' #' The function `richness()` counts the number of taxa per plot and can be used #' as alternative to [vegtable::count_taxa][count_taxa()]. #' #' @param x A numeric vector containing the abundance of single species. #' @param na.rm A logical value indicating whether NA values should be removed #' from the abundance vector or not. #' @param object A [vegtable-class] object. #' @param weight A character value indicating the name of the column at slot #' **samples** which will be used as species abundance. #' @param FUN A function used to calculate the diversity index. #' @param aggr_fun A function used to aggregate abundance values for multiple #' records of a taxon in a plot observation. Average value is used by #' default. #' @param arg_fun A named list with parameters and arguments passed to #' [taxa2samples()], which will #' retrieve the respective taxon concept for each taxon usage name and can #' be used to merge taxa at a determined taxonomic rank, for instance to #' merge all sub-specific taxa into their respective species #' (i.e. `'merge_to = "species"'`). #' @param var_name A character value used as name for the calculated index. #' If missing, the name of the function will be used. #' @param in_header A logical value indicating whether the results should be #' included as variables in the slot **header** of the input object. #' If `'in_header = TRUE'`, you may assign the result of the function to the #' input object. #' @param ... Further arguments passed among methods. In `'evenness()'` and #' `'dominance()'`, these arguments are passed to `'shannon()'`. #' In `'veg_diversity()'`, these arguments are passed to [aggregate()] #' (actually to `'FUN'`). #' #' @return #' Functions `shannon()`, `evenness()`, `dominance()`, `simpson()`, and #' `richness()` return a numeric value (the calculated index). #' #' Funtion `veg_diversity()` produce either a data frame with calculated values #' per plot observation (option `'in_header = FALSE'`) or a [vegtable-class] #' object with the calculated values inserted in the slot **header** #' (option `'in_header = TRUE'`). #' #' @examples #' ## Compare Evenness with Shannon index #' Kenya_veg <- cover_trans(x = Kenya_veg, to = "cover") #' Kenya_veg <- veg_diversity(object = Kenya_veg, weight = "cover") #' Kenya_veg <- veg_diversity(object = Kenya_veg, weight = "cover", FUN = evenness) #' #' with(Kenya_veg@header, plot(shannon, evenness)) #' #' @aliases shannon #' @export shannon <- function(x, na.rm = TRUE, ...) { if (na.rm) x <- x[!is.na(x)] p <- x / sum(x) return(-sum(p * log(p))) } #' @aliases evenness #' @rdname veg_diversity #' @export evenness <- function(x, ...) { return(shannon(x, ...) / log(length(x))) } #' @aliases dominance #' @rdname veg_diversity #' @export dominance <- function(x, ...) { return(1 - evenness(x, ...)) } #' @aliases simpson #' @rdname veg_diversity #' @export simpson <- function(x, na.rm = TRUE, ...) { if (na.rm) x <- x[!is.na(x)] p <- x / sum(x) return(1 - sum(p^2)) } #' @aliases richness #' @rdname veg_diversity #' @export richness <- function(x, na.rm = TRUE, ...) { if (na.rm) x <- x[!is.na(x)] return(length(x)) } #' @rdname veg_diversity #' @export veg_diversity <- function(object, ...) { UseMethod("veg_diversity", object) } #' @rdname veg_diversity #' @aliases veg_diversity,vegtable-method #' @method veg_diversity vegtable #' @export veg_diversity.vegtable <- function(object, weight, FUN = shannon, aggr_fun = mean, arg_fun = list(), var_name, in_header = TRUE, ...) { if (!weight %in% names(object@samples)) { stop(paste0( "The argument in 'weight' ('", weight, "') is not a column in slot 'samples'." )) } OUT <- do.call(taxa2samples, c(list(object = object), arg_fun))@samples OUT <- aggregate(as.formula(paste(weight, "TaxonConceptID + ReleveID", sep = " ~ " )), FUN = aggr_fun, data = OUT, na.action = na.omit) OUT <- aggregate(as.formula(paste(weight, "ReleveID", sep = " ~ ")), FUN = FUN, data = OUT, ... ) if (missing(var_name)) { var_name <- as.character(substitute(FUN)) } names(OUT)[names(OUT) == weight] <- var_name if (in_header) { object@header[[var_name]] <- with( OUT, get(var_name)[match(object$ReleveID, ReleveID)] ) return(object) } else { return(OUT) } }
/scratch/gouwar.j/cran-all/cranData/vegtable/R/veg_diversity.R
#' @name veg_relation #' #' @title Retrieve or replace relations in vegtable objects #' #' @description #' Tables providing information about levels of categorical variables in the #' header are called `popups` in **Turboveg** databases #' but `relations` in [vegtable-class] objects. #' Such variables will be converted into factors in the slot `header` according #' to the levels and their sorting in the respective relation. #' #' @param vegtable An object of class [vegtable-class]. #' @param relation A character value indicating the relation table to be #' retrieved or replaced. #' @param match_header A logical vector, whether only levels occurring in slot #' `header` should be considered or all. #' @param value A data frame containing the new veg_relation. #' @param ... Further arguments to be passed among methods. #' #' @return #' This function retrieves and object of class `data.frame`. #' In the replacement method, an object of class [vegtable-class], including #' `value` in the slot `relations`. #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @examples #' ## overview of references #' veg_relation(Kenya_veg, "REFERENCE") #' #' @rdname veg_relation #' #' @exportMethod veg_relation #' setGeneric( "veg_relation", function(vegtable, relation, ...) { standardGeneric("veg_relation") } ) #' @rdname veg_relation #' #' @aliases veg_relation,vegtable,character-method #' setMethod( "veg_relation", signature(vegtable = "vegtable", relation = "character"), function(vegtable, relation, match_header = FALSE, ...) { if (match_header) { return(vegtable@relations[[relation]][ vegtable@relations[[relation]][, relation] %in% vegtable@header[, relation], ]) } else { return(vegtable@relations[[relation]]) } } ) #' @rdname veg_relation #' @aliases veg_relation<- #' @exportMethod veg_relation<- setGeneric("veg_relation<-", function(vegtable, value) { standardGeneric("veg_relation<-") }) #' @rdname veg_relation #' @aliases veg_relation<-,vegtable,data.frame-method setReplaceMethod( "veg_relation", signature( vegtable = "vegtable", value = "data.frame" ), function(vegtable, value) { relation <- names(value)[1] if (is(value[, relation], "factor")) { levels <- base::levels(value[, relation]) } else { levels <- as.character(unique(value[, relation])) value[, relation] <- factor(as.character(value[, relation]), levels = levels ) } if (relation %in% names(vegtable@header)) { if (is(vegtable@header[, relation], "factor")) { levels_in <- base::levels(vegtable@header[, relation]) } else { levels_in <- as.character(unique(vegtable@header[ !is.na(vegtable@header[, relation]), relation ])) } if (!all(levels_in %in% levels)) { missing_levels <- levels_in[!levels_in %in% levels] stop(paste0( "Following values are missing in the input relation: ", paste0(missing_levels, collapse = ", ") )) } } vegtable <- new_relation(vegtable, relation, levels) vegtable@relations[[relation]] <- value return(vegtable) } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/veg_relation.R
#' @name vegtable-class #' @aliases vegtable #' #' @title Class vegtable. #' #' @description #' Class holding vegetation-plot data sets. #' Designed to content all information stored in **Turboveg** databases in #' just one object. #' #' This class was designed to include information of relevés, header data and #' species in just one object. Objects can be created by calls of the form #' `new("vegtable", ...)`. #' #' @slot description A named character vector containing metadata. #' @slot samples A data frame with samples list. #' @slot header A data frame with plots data. #' @slot species Species list as a [taxlist-class] object. #' @slot layers A list including strata within samples as data frames. #' @slot relations A list including popup lists as data frames. #' @slot coverconvert A scale conversion object of class [coverconvert-class]. #' @slot syntax A list including syntaxonomic lists either as data frames or as #' [taxlist-class] objects. #' #' @seealso [tv2vegtable()] #' #' @examples #' showClass("vegtable") #' @exportClass vegtable setClass("vegtable", slots = c( description = "character", samples = "data.frame", layers = "list", header = "data.frame", species = "taxlist", relations = "list", coverconvert = "coverconvert", syntax = "list" ), prototype = list( description = character(), samples = data.frame(ReleveID = integer(), TaxonUsageID = integer()), layers = list(), header = data.frame(ReleveID = integer()), species = new("taxlist"), relations = list(), coverconvert = new("coverconvert"), syntax = list() ), validity = function(object) { # Mandatory names in samples (only for objects with records) ------------- if (nrow(object@samples) > 0 & any(!c("ReleveID", "TaxonUsageID") %in% colnames(object@samples))) { return(paste( "Columns 'ReleveID' and 'TaxonUsageID' are", "mandatory in slot 'samples'" )) } # TODO: Use a better message (showing missmatching names) for (i in names(object@layers)) { if (!i %in% colnames(object@samples)) { return(paste0( "Layers of '", i, "' not included in slot 'samples'" )) } if (!i %in% colnames(object@layers[[i]])) { return(paste0( "Column '", i, "' is mandatory in layer table '", i, "'" )) } } if (!"ReleveID" %in% colnames(object@header)) { return("Column 'ReleveID' is mandatory in slot 'header'") } for (i in names(object@relations)) { if (!i %in% colnames(object@header)) { return(paste0( "Relation '", i, "' not included in slot 'header'" )) } if (!i %in% colnames(as.data.frame(object@relations[[i]]))) { return(paste0("Column '", i, "' is mandatory in relation '", i, "'")) } if (any(!object@header[[i]] %in% object@relations[[i]][[i]] & !is.na(object@header[[i]]))) { return(paste0( "Some values of '", i, "' in header do not macht the values in slot relations." )) } } # Mandatory links -------------------------------------------------------- if (!all(object@samples$ReleveID %in% object@header$ReleveID)) { return(paste( "Some releve IDs from slot 'samples' are missing", "in slot 'header'" )) } if (any(is.na(object@samples$TaxonUsageID))) { return("NAs are not allowed in 'TaxonUsageID' at slot 'samples'.") } if (any(!object@samples$TaxonUsageID %in% object@species@taxonNames$TaxonUsageID)) { return("Some taxon names are missing in slot 'species'") } # Other consistency tests ------------------------------------------------ if (any(duplicated(object@header$ReleveID))) { return("Duplicated releve IDs are not allowed in slot 'header'") } # Validation for layers -------------------------------------------------- for (i in names(object@layers)) { if (any(!object@samples[!is.na(object@samples[, i]), i] %in% object@layers[[i]][, i])) { return(paste0( "Some values of'", i, "' in slot 'samples' are missing in slot 'layers'" )) } } # Validation for syntaxonomy --------------------------------------------- if (length(object@syntax) > 0) { if (!all(sapply(object@syntax, class) == "taxlist")) { return("Only 'taxlist' objects are allowed in slot 'syntax'.") } for (i in names(object@syntax)) { noNA <- object@header[[paste("syntax", i, sep = "_")]] noNA <- noNA[!is.na(noNA)] if (!all(noNA %in% object@syntax[[i]]@taxonNames$TaxonUsageID)) { return(paste0( "Not all values of 'syntax_", i, "' contained in the respective syntaxonomy." )) } } } } )
/scratch/gouwar.j/cran-all/cranData/vegtable/R/vegtable-class.R
#' @name vegtable_stat #' @rdname vegtable_stat #' #' @title General statistics from vegtable objects #' #' @description #' This function calculates general statistics of local **Turboveg** #' databases as required by GIVD (Global Index of Vegetation-Plot Databases, #' \url{https://www.givd.info}). #' #' This function is based on a script delivered by GIVD for summarising #' statistics required in the descriptions of databases (see meta data in the #' page of the Global Index for Vegetation-Plot Databases). #' #' @param vegtable An object of class [vegtable-class]. #' @param ... Further arguments passed among methods. #' #' @author GIVD. Adapted by Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @examples #' ## Statistics for GIVD #' vegtable_stat(Kenya_veg) #' #' @export vegtable_stat <- function(vegtable, ...) { UseMethod("vegtable_stat", vegtable) } #' @rdname vegtable_stat #' @aliases vegtable_stat,vegtable-method #' @method vegtable_stat vegtable #' @export vegtable_stat.vegtable <- function(vegtable, ...) { summary(vegtable) vegtable <- vegtable@header # Number of references if (!is.null(vegtable$REFERENCE)) { cat("REFERENCES", "\n") cat("Primary references: ", length(base::levels(factor(vegtable$REFERENCE))), sep = "", "\n" ) cat("\n") } # Area statistics if (!is.null(vegtable$SURF_AREA)) { cat("## AREA", "\n") area <- vegtable$SURF_AREA cat("Area range (m^2): ", min(area, na.rm = TRUE), " - ", max(area, na.rm = TRUE ), sep = "", "\n") cat("<1 m^2: ", round(sum(area < 1, na.rm = TRUE) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat("1-<10 m^2: ", round(sum(area >= 1 & area < 10, na.rm = TRUE ) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat("10-<100 m^2: ", round(sum(area >= 10 & area < 100, na.rm = TRUE ) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat("100-<1000 m^2: ", round(sum(area >= 100 & area < 1000, na.rm = TRUE ) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat("1000-<10000 m^2: ", round(sum(area >= 1000 & area < 10000, na.rm = TRUE ) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat(">=10000 m^2: ", round(sum(area >= 10000, na.rm = TRUE ) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat("unknow: ", round(sum(is.na(area)) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat("\n") } # Time statistics if (!is.null(vegtable$DATE)) { cat("## TIME", "\n") years <- as.numeric(format(vegtable$DATE, "%Y")) cat("oldest: ", min(years, na.rm = TRUE), " - youngest: ", max(years, na.rm = TRUE ), sep = "", "\n") cat("<=1919: ", round(sum(years <= 1919, na.rm = TRUE ) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat("1920-1929: ", round(sum(years > 1919 & years < 1930, na.rm = TRUE ) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat("1930-1939: ", round(sum(years > 1929 & years < 1940, na.rm = TRUE ) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat("1940-1949: ", round(sum(years > 1939 & years < 1950, na.rm = TRUE ) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat("1950-1959: ", round(sum(years > 1949 & years < 1960, na.rm = TRUE ) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat("1960-1969: ", round(sum(years > 1959 & years < 1970, na.rm = TRUE ) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat("1970-1979: ", round(sum(years > 1969 & years < 1980, na.rm = TRUE ) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat("1980-1989: ", round(sum(years > 1979 & years < 1990, na.rm = TRUE ) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat("1990-1999: ", round(sum(years > 1989 & years < 2000, na.rm = TRUE ) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat("2000-2009: ", round(sum(years > 1999 & years < 2010, na.rm = TRUE ) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat("2010-2019: ", round(sum(years > 2009 & years < 2020, na.rm = TRUE ) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat("unknow: ", round(sum(is.na(years)) / nrow(vegtable) * 100), "%", sep = "", "\n" ) cat("\n") } # Country if (!is.null(vegtable$COUNTRY)) { cat("## DISTRIBUTION", "\n") countries <- summary(factor(vegtable$COUNTRY), maxsum = 1000) for (i in names(countries)) { cat(i, ": ", round(countries[i] / nrow(vegtable) * 100), "%", sep = "", "\n" ) } cat("\n") } # Performance if (!is.null(vegtable$COVERSCALE)) { cat("## PERFORMANCE", "\n") covscale <- summary(as.factor(vegtable$COVERSCALE)) for (i in names(covscale)) { cat(i, ": ", round(covscale[i] / nrow(vegtable) * 100), "%", sep = "", "\n" ) } cat("\n") } }
/scratch/gouwar.j/cran-all/cranData/vegtable/R/vegtable_stat.R
#' @name write_juice #' #' @title Exporting tables for Juice #' #' @description #' This function produce txt files as inport formats for **Juice** #' (\url{https://www.sci.muni.cz/botany/juice/}). #' #' This function produces two output files to be imported into a **Juice** #' file: A vegetation table produced by [crosstable()] and a header table. #' Both tables share the file name plus a suffix (`table` for the #' vegetation table and `header` for the header). #' #' For the import in **Juice**, you go to the menu #' `File -> Import -> Table -> from Spreadsheet File (e.g. EXCEL Table)` and #' then follow the wizard. #' Do not forget to select the proper settings in the wizard: 1) 'Character #' delimiting columns: Comma' (for default argument values). 2) 'Use the second #' column as layer information: Unchecked'. 3) 'Cover values: Percentage #' Values'. #' #' To further import the header table you need to go to the menu #' `File -> Import -> Header Data -> From Comma Delimited File`. #' #' In the `header` (see **Value**), the first column (`Table number`) #' corresponds to the plot number assigned by **Juice** at import, while #' the column (`Releve number`) is the number originally assigned to the plot #' (e.g. **Turboveg** ID). #' #' @param data An object of class [vegtable-class]. #' @param file Character value indicating the name of output files (without #' file extension). #' @param db_name Name for data set displayed in inport wizard. #' @param formula A formula passed to [crosstable()]. #' @param FUN Funtion passed to [crosstable()]. #' @param header Variables of header to be exported. #' @param coords Names of coordinate variables in header of `data`. #' @param sep A symbol used to separate columns in the output object. #' @param ... Further arguments. While `write_juice()` passes them to the #' function [crosstable()], `read_juice()` passes those arguments to #' [readLines()]. #' #' @return #' For `read_juice()`, a list with two elements: A data frame of species by #' plot (`cross_table`), and a data frame with header data (`header`). #' #' @author Miguel Alvarez \email{kamapu78@@gmail.com} #' #' @example examples/write_juice.R #' #' @rdname write_juice #' #' @exportMethod write_juice setGeneric("write_juice", function(data, file, formula, ...) { standardGeneric("write_juice") }) #' @rdname write_juice #' #' @aliases write_juice,vegtable,character,formula-method #' setMethod( "write_juice", signature( data = "vegtable", file = "character", formula = "formula" ), function(data, file, formula, FUN, db_name = "Plot Observations", header, coords, sep = ",", ...) { # some attributes nr.plots <- nrow(data@header) # header header.in <- header if (attr(terms(formula), "term.labels")[1] != "ReleveID") { stop("'ReleveID' is mandatory as first term of formula") } if (!missing(coords)) { if (length(coords) != 2) { stop("Argument 'coords' have to be of length 2.") } header <- c(header, coords) header.in <- c(header.in, c("deg_lon", "deg_lat")) } header <- c("ReleveID", header) if (!all(header %in% colnames(data@header))) { stop("some requested headers are not included in 'data'") } header <- data@header[, header] rownames(header) <- NULL # Convert header to character header <- cbind(1:nrow(header), header) for (i in colnames(header)) { header[, i] <- paste(header[, i]) header[header[, i] == "NA", i] <- "" } colnames(header)[1:2] <- c("Table number", "Releve number") # Write header lines Lines_h <- character(nrow(header)) message("Processing header data...") for (i in 1:nrow(header)) { Lines_h[i] <- paste(header[i, ], collapse = sep) } Lines_h <- c(paste(colnames(header), collapse = sep), Lines_h) # Convert data table data <- crosstable(formula, data, FUN, ...) for (i in colnames(data)) { data[, i] <- paste(data[, i]) data[data[, i] == "NA", i] <- "" } colnames(data)[1:(length(attr( terms(formula), "term.labels" )) - 1)] <- "" # Write table lines nr_spp <- nrow(data) Lines_t <- character(nr_spp) message("Processing vegetation table...") for (i in 1:nr_spp) { Lines_t[i] <- paste(data[i, ], collapse = sep) } Lines_t <- c(paste(colnames(data), collapse = sep), Lines_t) Lines_t <- c(db_name, paste("Number of releves:", nr.plots, collapse = " " ), "", Lines_t) # Write table file con <- file(paste(file, "table.txt", sep = "_"), "wb") writeBin(charToRaw(paste0(Lines_t, collapse = "\r\n")), con, endian = "little" ) close(con) # Write header file con <- file(paste(file, "header.txt", sep = "_"), "wb") writeBin(charToRaw(paste0(Lines_h, collapse = "\r\n")), con, endian = "little" ) close(con) message(paste0( "DONE!\n\nData set name: ", db_name, "\nNumber of observations: ", nr.plots, "\nRecorded species: ", nr_spp )) } ) #' @rdname write_juice #' @aliases read_juice #' #' @param encoding Argument passed to \code{\link{readLines}}. #' @param sep Separator used to split rows into columns. #' @param na Character used as not available values. #' #' @examples #' ## Installed 'Juice' version of 'Wetlands_veg' #' Veg <- file.path(path.package("vegtable"), "juice", "Wetlands_juice.txt") #' Veg <- read_juice(Veg) #' #' summary(Veg) #' @export #' read_juice <- function(file, encoding = "LATIN-1", sep = ";", na = "", ...) { file <- readLines(file, encoding = encoding, ...) # First prepare the header if ("Table head:" %in% file) { header <- file[(which(file == "Table head:") + 2):length(file)] header <- strsplit(header, sep) # Trick for ending NAs N <- sapply(header, length) if (any(N < max(N))) { for (i in 1:length(N)) { if (N[i] < max(N)) { header[[i]] <- c( header[[i]], rep(NA, max(N) - N[i]) ) } } } header <- do.call(rbind, header) colnames(header) <- header[1, ] header <- as.data.frame(header[-1, ], stringsAsFactors = FALSE) colnames(header)[1:2] <- c("juice_nr", "db_nr") file <- file[2:(which(file == "Table head:") - 1)] } else { header <- NULL file <- file[-1] } # Now the cross table file <- file[nchar(file) != 0] file <- do.call(rbind, strsplit(file, sep)) colnames(file) <- file[1, ] N <- integer() if (colnames(file)[1] == "") { colnames(file)[1] <- "species" N <- 2 } if (colnames(file)[2] == "") { colnames(file)[2] <- "layer" N <- 3 } file <- as.data.frame(file[-1, ], stringsAsFactors = FALSE) for (i in N:ncol(file)) { file[file[, i] == na, i] <- NA file[, i] <- as.numeric(file[, i]) } return(list(cross_table = file, header = header)) }
/scratch/gouwar.j/cran-all/cranData/vegtable/R/write_juice.R
#' Construction function for class "EmissionFactors" #' #' @description \code{EmissionFactors} returns a transformed object with class #' "EmissionFactors" and units g/km. #' #' @return Objects of class "EmissionFactors" or "units" #' #' @param x Object with class "data.frame", "matrix" or "numeric" #' @param mass Character to be the time units as numerator, default "g" for grams #' @param dist String indicating the units of the resulting distance in speed. #' @param pal Palette of colors available or the number of the position #' @param object object with class "EmissionFactors' #' @param rev Logical; to internally revert order of rgb color vectors. #' @param fig1 par parameters for fig, \code{\link{par}}. #' @param mai1 par parameters for mai, \code{\link{par}}. #' @param fig2 par parameters for fig, \code{\link{par}}. #' @param mai2 par parameters for mai, \code{\link{par}}. #' @param fig3 par parameters for fig, \code{\link{par}}. #' @param mai3 par parameters for mai, \code{\link{par}}. #' @param bias positive number. Higher values give more widely spaced colors at the high end. #' @param ... ignored #' @importFrom units as_units #' @importFrom graphics par plot abline #' @importFrom cptcity cpt #' @importFrom grDevices rgb colorRamp #' @rdname EmissionFactors #' @aliases EmissionFactors print.EmissionFactors summary.EmissionFactors #' plot.EmissionFactors #' @examples \dontrun{ #' data(fe2015) #' names(fe2015) #' class(fe2015) #' df <- fe2015[fe2015$Pollutant=="CO", c(ncol(fe2015)-1,ncol(fe2015))] #' ef1 <- EmissionFactors(df) #' class(ef1) #' summary(ef1) #' plot(ef1) #' print(ef1) #' } #' @export EmissionFactors <- function(x, mass = "g", dist = "km", ...) { if ( is.matrix(x) ) { ef <- as.data.frame(x) for(i in 1:ncol(ef)){ ef[,i] <- ef[,i]*units::as_units(paste0(mass, " ", dist, "-1")) } class(ef) <- c("EmissionFactors",class(ef)) efx <- ef } else if ( is.data.frame(x) ) { ef <- x for(i in 1:ncol(ef)){ ef[,i] <- ef[,i]*units::as_units(paste0(mass, " ", dist, "-1")) } class(ef) <- c("EmissionFactors",class(ef)) } else if ( inherits(x, "units")) { ef <- x ef <- x if(as.character(units(ef)) != paste0(mass, "/", dist) ){ message("Converting ", as.character(units(ef)), " to ", mass, "/", dist) spd <- units::as_units(ef, paste0(mass, " ", dist, "-1")) } else { message("Units are the same and no cerversions will be made") } } else if( inherits(x, "numeric") | inherits(x, "integer" )) { ef <- x*units::as_units(paste0(mass, " ", dist, "-1")) } return(ef) } #' @rdname EmissionFactors #' @method print EmissionFactors #' @export print.EmissionFactors <- function(x, ...) { nr <- ifelse(nrow(x) <= 5, nrow(x), 5) if(ncol(x) == 1) { ndf <- names(x) df <- data.frame(ndf = x[1:nr, ]) names(df) <- ndf print.data.frame(df) } else { print.data.frame(x[1:nr, ]) } if(nrow(x) > 5) cat(paste0("... and ", nrow(x) - 5, " more rows\n")) } #' @rdname EmissionFactors #' @method summary EmissionFactors #' @export summary.EmissionFactors <- function(object, ...) { cat("Mean EmissionFactors in study area = \n") print(summary.data.frame(object)) } #' @rdname EmissionFactors #' @method plot EmissionFactors #' @export plot.EmissionFactors <- function(x, pal = "mpl_viridis", rev = TRUE, fig1 = c(0,0.8,0,0.8), fig2 = c(0,0.8,0.55,1), fig3 = c(0.7,1,0,0.8), mai1 = c(0.2, 0.82, 0.82, 0.42), mai2 = c(1.3, 0.82, 0.82, 0.42), mai3 = c(0.7, 0.62, 0.82, 0.42), bias = 1.5, ...) { # ef <- x # if (ncol(ef) >= 1 & ncol(ef) <= 3) { # graphics::par(mfrow=c(1, ncol(ef)), tcl = -0.5) # } else if (ncol(ef) == 4) { # graphics::par(mfrow=c(2, 2), tcl = -0.5) # } else if (ncol(ef) >= 5 & ncol(ef) <= 6 ) { # graphics::par(mfrow=c(2, 3), tcl = -0.5) # } else if (ncol(ef) >= 7 & ncol(ef) <= 9 ) { # graphics::par(mfrow=c(3, 3), tcl = -0.5) # } else { # message("Plotting first 9 plots") # graphics::par(mfrow=c(3, 3), tcl = -0.5) # } # nc <- ifelse(ncol(ef) <= 9, ncol(ef), 9) # for (i in 1:nc) { # graphics::plot(ef[,i], type = "l", ...) # } # graphics::par(mfrow=c(1,1)) # oldpar <- par(no.readonly = TRUE) # code line i on.exit(par(oldpar)) # code line i + 1 if(ncol(x) > 1) { graphics::par(fig=fig1, #new=TRUE, mai = mai1, ...) col <- grDevices::rgb(grDevices::colorRamp(colors = cptcity::cpt(pal, rev = rev), bias = bias)(seq(0, 1,0.01)), maxColorValue = 255) # fields::image.plot( # x = 1:ncol(x), # xaxt = "n", # z =t(as.matrix(x))[, nrow(x):1], # xlab = "", # ylab = paste0("EF by streets [",as.character(units(x[[1]])), "]"), # col = col, horizontal = TRUE) graphics::image(x = 1:ncol(x), xaxt = "n", z =t(as.matrix(x))[, nrow(x):1], xlab = "", ylab = paste0("EF by streets [",as.character(units(x[[1]])), "]"), col = col, axe = FALSE) axis(2) addscale(t(as.matrix(x))[, nrow(x):1], col = col) graphics::par(fig=fig2, mai = mai2, new=TRUE, ...) avage <- mean(unlist(x), na.rm = T) graphics::plot(colMeans(x, na.rm = T), type="l", ylab = paste0("Mean EF [",as.character(units(x[[1]])), "]"), xlab = "", frame = FALSE, xaxt = 'n') graphics::axis(3) graphics::abline(h = avage, col="red") cat("Weighted mean = ",round(avage,2), "\n") graphics::par(fig=fig3, new=TRUE, mai = mai3, ...) graphics::plot(x = rowMeans(x, na.rm = T), y = nrow(x):1, type = "l", frame = FALSE, yaxt = "n", ylab = "", xlab = NULL ) graphics::abline(v = avage, col="red") } else { graphics::plot(unlist(x), type = "l", main = "1 column data") } }
/scratch/gouwar.j/cran-all/cranData/vein/R/EmissionFactors.R
#' Construction function for class "EmissionFactorsList" #' #' @description \code{EmissionFactorsList} returns a transformed object with #' class"EmissionsFactorsList". #' #' @return Objects of class "EmissionFactorsList" #' #' @param x Object with class "list" #' @param object Object with class "EmissionFactorsList" #' @param default Logical value. When TRUE prints default list, when FALSE #' prints messages with description of list #' @param ... ignored #' @rdname EmissionFactorsList #' @aliases EmissionFactorsList print.EmissionFactorsList #' summary.EmissionFactorsList plot.EmissionFactorsList #' @examples \dontrun{ #' data(fe2015) #' names(fe2015) #' class(fe2015) #' df <- fe2015[fe2015$Pollutant=="CO", c(ncol(fe2015)-1,ncol(fe2015))] #' ef1 <- EmissionFactorsList(df) #' class(ef1) #' length(ef1) #' length(ef1[[1]]) #' summary(ef1) #' ef1 #' } #' @export EmissionFactorsList <- function(x, ...) { if ( is.matrix(x) || is.data.frame(x) ) { efx <- lapply(1:ncol(x), function(i) { lapply(1:nrow(x), function(j) { function(V) x[j,i] }) }) class(efx) <- c("EmissionFactorsList",class(x)) } else if ( is.numeric(x) ) { efx <- lapply(1:length(x), function(i) {function(V) x[i] }) class(efx) <- c("EmissionFactorsList",class(efx)) } else if ( is.list(x) && is.function(x[[1]]) ) { efx <- x class(efx) <- c("EmissionFactorsList",class(x)) } return(efx) } #' @rdname EmissionFactorsList #' @method print EmissionFactorsList #' @export print.EmissionFactorsList <- function(x, ..., default = FALSE) { if ( default ) { print.default(x) } else if ( is.function( x[[1]] ) ){ cat("This EmissionFactorsList has ", length(x), " functions") } else if ( is.list(x) && is.list(x[[1]]) ) { cat("This EmissionFactorsList has ", length(x), " lists\n") cat("First has ",length(x[[1]]), " functions\n") cat("Last has ", length(x[[length(x)]]), " functions") } } #' @rdname EmissionFactorsList #' @method summary EmissionFactorsList #' @export summary.EmissionFactorsList <- function(object, ...) { ef <- object if ( is.function( ef[[1]] ) ){ cat("This EmissionFactorsList has", length(ef), "functions") } else if ( is.list(ef) && is.list(ef[[1]]) ) { cat("This EmissionFactorsList has ", length(ef), "lists\n") cat("First has",length(ef[[1]]), "functions\n") cat("Last has", length(ef[[length(ef)]]), "functions") } } #' @rdname EmissionFactorsList #' @method plot EmissionFactorsList #' @export plot.EmissionFactorsList <- function(x, ...) { ef <- x if ( is.function( ef[[1]] ) ){ cat("This EmissionFactorsList has", length(ef), "functions") graphics::plot(unlist(lapply(1:length(ef), function(i) ef[[i]](34) )), ylab = "Emission factors at 34 [km/h]") } else { cat("Try other methods") } }
/scratch/gouwar.j/cran-all/cranData/vein/R/EmissionFactorsList.R
#' Construction function for class "Emissions" #' #' @description \code{Emissions} returns a transformed object with class "Emissions". #' The type of objects supported are of classes "matrix", "data.frame" and #' "numeric". If the class of the object is "matrix" this function returns a #' dataframe. #' #' @return Objects of class "Emissions" or "units" #' #' @param x Object with class "data.frame", "matrix" or "numeric" #' @param mass Character to be the time units as numerator, default "g" for grams #' @param time Character to be the time units as denominator, eg "h" #' @param object object with class "Emissions" #' @param pal Palette of colors available or the number of the position #' @param rev Logical; to internally revert order of rgb color vectors. #' @param fig1 par parameters for fig, \code{\link{par}}. #' @param mai1 par parameters for mai, \code{\link{par}}. #' @param fig2 par parameters for fig, \code{\link{par}}. #' @param mai2 par parameters for mai, \code{\link{par}}. #' @param fig3 par parameters for fig, \code{\link{par}}. #' @param mai3 par parameters for mai, \code{\link{par}}. #' @param bias positive number. Higher values give more widely spaced colors at the high end. #' @param main title of plot #' @param ... ignored #' @importFrom units as_units as_units #' @importFrom graphics par plot abline #' @importFrom grDevices rgb colorRamp #' #' @rdname Emissions #' @aliases Emissions print.Emissions summary.Emissions plot.Emissions #' @examples \dontrun{ #' data(net) #' data(pc_profile) #' data(fe2015) #' data(fkm) #' PC_G <- c(33491,22340,24818,31808,46458,28574,24856,28972,37818,49050,87923, #' 133833,138441,142682,171029,151048,115228,98664,126444,101027, #' 84771,55864,36306,21079,20138,17439, 7854,2215,656,1262,476,512, #' 1181, 4991, 3711, 5653, 7039, 5839, 4257,3824, 3068) #' veh <- data.frame(PC_G = PC_G) #' pc1 <- my_age(x = net$ldv, y = PC_G, name = "PC") #' pcw <- temp_fact(net$ldv+net$hdv, pc_profile) #' speed <- netspeed(pcw, net$ps, net$ffs, net$capacity, net$lkm, alpha = 1) #' pckm <- units::as_units(fkm[[1]](1:24), "km"); pckma <- cumsum(pckm) #' cod1 <- emis_det(po = "CO", cc = 1000, eu = "III", km = pckma[1:11]) #' cod2 <- emis_det(po = "CO", cc = 1000, eu = "I", km = pckma[12:24]) #' #vehicles newer than pre-euro #' co1 <- fe2015[fe2015$Pollutant=="CO", ] #24 obs!!! #' cod <- c(co1$PC_G[1:24]*c(cod1,cod2),co1$PC_G[25:nrow(co1)]) #' lef <- ef_ldv_scaled(co1, cod, v = "PC", cc = "<=1400", #' f = "G", p = "CO", eu=co1$Euro_LDV) #' E_CO <- emis(veh = pc1,lkm = net$lkm, ef = lef, speed = speed, agemax = 41, #' profile = pc_profile) #' dim(E_CO) # streets x vehicle categories x hours x days #' class(E_CO) #' plot(E_CO) #' #### #' Emissions(1) #' Emissions(1, time = "h") #' } #' @export Emissions <- function(x, mass = "g", time, ...) { if(inherits(x, "sf")) { geo <- sf::st_geometry(x) e <- sf::st_set_geometry(x, NULL) for(i in 1:ncol(e)){ e[,i] <- e[,i]*units::as_units(mass) } if(!missing(time)){ for(i in 1:ncol(e)) e[,i] <- e[,i]*units::as_units(1, paste0(time, "-1")) } e <- sf::st_sf(e, geometry = geo) } else if ( is.matrix(x) ) { e <- as.data.frame(x) for(i in 1:ncol(e)){ e[,i] <- e[,i]*units::as_units(mass) } if(!missing(time)){ for(i in 1:ncol(e)) e[,i] <- e[,i]*units::as_units(1, paste0(time, "-1")) } class(e) <- c("Emissions", class(e)) } else if ( is.data.frame(x) ) { e <- as.data.frame(x) for(i in 1:ncol(x)){ e[,i] <- e[,i]*units::as_units(mass) } if(!missing(time)){ for(i in 1:ncol(e)) e[,i] <- e[,i]*units::as_units(1, paste0(time, "-1")) } class(e) <- c("Emissions",class(x)) } else if ( inherits(x, "units" )) { e <- x if(as.character(units(e)) != paste0(mass, "/", time) ){ message("Converting ", as.character(units(e)), " to ", mass, "/", time) e <- units::as_units(e, paste0(mass, " ", time, "-1")) } else { message("Units are the same and no cerversions will be made") } } else if( inherits(x, "numeric") | inherits(x, "integer")) { e <- x*units::as_units("g") if(!missing(time)){ e <- e*units::as_units(1, paste0(time, "-1")) } } return(e) } #' @rdname Emissions #' @method print Emissions #' @export print.Emissions <- function(x, ...) { nr <- ifelse(nrow(x) <= 5, nrow(x), 5) if(ncol(x) == 1) { ndf <- names(x) df <- data.frame(ndf = x[1:nr, ]) names(df) <- ndf print.data.frame(df) } else { print.data.frame(x[1:nr, ]) } if(nrow(x) > 5) cat(paste0("... and ", nrow(x) - 5, " more rows\n")) } #' @rdname Emissions #' @method summary Emissions #' @export summary.Emissions <- function(object, ...) { e <- object avemi <- sum(seq(1,ncol(e))*colSums(e)/sum(e)) cat("Total emissions by column in study area = \n") print(summary(colSums(e))) cat("\nAverage = ", round(avemi,2)) cat(" \n\n") cat("Emissions by street in study area = \n") print(summary(rowSums(e))) cat(" \n\n") cat("Emissions by column and street in study area = \n") print(summary(unlist(e))) } #' @rdname Emissions #' @method plot Emissions #' @export plot.Emissions <- function(x, pal = "colo_angelafaye_Coloured_sky_in", rev = FALSE, fig1 = c(0,0.8,0,0.8), fig2 = c(0,0.8,0.55,1), fig3 = c(0.7,1,0,0.8), mai1 = c(0.2, 0.82, 0.82, 0.42), mai2 = c(1.3, 0.82, 0.82, 0.42), mai3 = c(0.7, 0.72, 0.82, 0.42), main = NULL, bias = 1.5, ...) { oldpar <- par(no.readonly = TRUE) # code line i on.exit(par(oldpar)) # code line i + 1 # e <- x # if(ncol(x) > 1) { graphics::par(fig=fig1, #new=TRUE, mai = mai1, ...) col <- grDevices::rgb(grDevices::colorRamp(colors = cptcity::cpt(pal, rev = rev), bias = bias)(seq(0, 1,0.01)), maxColorValue = 255) # fields::image.plot( # x = 1:ncol(x), # xaxt = "n", # z =t(as.matrix(x))[, nrow(x):1], # xlab = "", # ylab = paste0("Emissions by streets [",as.character(units(x[[1]])), "]"), # col = col, horizontal = TRUE) graphics::image(x = 1:ncol(x), xaxt = "n", z =t(as.matrix(x))[, nrow(x):1], xlab = "", ylab = paste0("Emissions by streets [",as.character(units(x[[1]])), "]"), col = col, axe = FALSE) axis(2) addscale(t(as.matrix(x))[, nrow(x):1], col = col) graphics::par(fig=fig2, mai = mai2, new=TRUE, ...) avage <- sum(seq(1,ncol(x)) * colSums(x)/sum(x, na.rm = T)) graphics::plot(colSums(x, na.rm = T), type="l", ylab = paste0("Emissions [",as.character(units(x[[1]])), "]"), xlab = "", frame = FALSE, xaxt = 'n') graphics::axis(3) graphics::abline(v = avage, col="red") cat("Weighted mean = ",round(avage,2), "\n") graphics::par(fig=fig3, new=TRUE, mai = mai3, ...) graphics::plot(x = rowSums(x, na.rm = T), y = nrow(x):1, type = "l", frame = FALSE, yaxt = "n", ylab = "", xlab = NULL ) graphics::abline(v = avage, col="red") } else { graphics::plot(unlist(x), type = "l", main = "1 column data") } }
/scratch/gouwar.j/cran-all/cranData/vein/R/Emissions.R
#' Construction function for class "EmissionsArray" #' #' @description \code{EmissionsArray} returns a transformed object with class #' "EmissionsArray" with 4 dimensions. #' #' @return Objects of class "EmissionsArray" #' #' @param x Object with class "data.frame", "matrix" or "numeric" #' @param object object with class "EmissionsArray' #' @param main Title for plot #' @param ... ignored #' @importFrom stats median quantile sd #' @rdname EmissionsArray #' @aliases EmissionsArray print.EmissionsArray summary.EmissionsArray #' plot.EmissionsArray #' @note Future version of this function will return an Array of 3 dimensions. #' @examples \dontrun{ #' data(net) #' data(pc_profile) #' data(fe2015) #' data(fkm) #' PC_G <- c(33491,22340,24818,31808,46458,28574,24856,28972,37818,49050,87923, #' 133833,138441,142682,171029,151048,115228,98664,126444,101027, #' 84771,55864,36306,21079,20138,17439, 7854,2215,656,1262,476,512, #' 1181, 4991, 3711, 5653, 7039, 5839, 4257,3824, 3068) #' veh <- data.frame(PC_G = PC_G) #' pc1 <- my_age(x = net$ldv, y = PC_G, name = "PC") #' pcw <- temp_fact(net$ldv+net$hdv, pc_profile) #' speed <- netspeed(pcw, net$ps, net$ffs, net$capacity, net$lkm, alpha = 1) #' pckm <- units::set_units(fkm[[1]](1:24), "km"); pckma <- cumsum(pckm) #' cod1 <- emis_det(po = "CO", cc = 1000, eu = "III", km = pckma[1:11]) #' cod2 <- emis_det(po = "CO", cc = 1000, eu = "I", km = pckma[12:24]) #' #vehicles newer than pre-euro #' co1 <- fe2015[fe2015$Pollutant=="CO", ] #24 obs!!! #' cod <- c(co1$PC_G[1:24]*c(cod1,cod2),co1$PC_G[25:nrow(co1)]) #' lef <- ef_ldv_scaled(co1, cod, v = "PC", cc = "<=1400", #' f = "G",p = "CO", eu=co1$Euro_LDV) #' E_CO <- emis(veh = pc1,lkm = net$lkm, ef = lef, speed = speed, agemax = 41, #' profile = pc_profile, simplify = TRUE) #' class(E_CO) #' summary(E_CO) #' E_CO #' plot(E_CO) #' lpc <- list(pc1, pc1) #' E_COv2 <- emis(veh = lpc,lkm = net$lkm, ef = lef, speed = speed, agemax = 41, #' profile = pc_profile, hour = 2, day = 1) #' } #' @export EmissionsArray <- function(x, ...) { e <- x if ( !is.array(e) ) { stop("Class of e must be 'array'") } else if ( is.array(e) ) { class(e) <- c("EmissionsArray",class(e)) } return(e) } #' @rdname EmissionsArray #' @method print EmissionsArray #' @export print.EmissionsArray <- function(x, ...) { e <- x if (length(dim(e)) == 3) { cat("This EmissionsArray has\n", dim(e)[1], "streets\n", dim(e)[2], "vehicle categories\n", dim(e)[3], "hours\n") print(utils::head(e)) } else { cat("This EmissionsArray has\n", dim(e)[1], "streets\n", dim(e)[2], "vehicle categories\n", dim(e)[3], "hours\n", dim(e)[4], "days\n") print(utils::head(e)) } } #' @rdname EmissionsArray #' @method summary EmissionsArray #' @export summary.EmissionsArray <- function(object, ...) { e <- object mine <- round(min(e, na.rm = T), 3) q1 <- round(stats::quantile(e, .25, na.rm = T), 3) mede <- round(stats::median(e, na.rm = T), 3) avge <- round(mean(e, na.rm = T), 3) q3 <- round(stats::quantile(e, .75, na.rm = T), 3) maxe <- round(max(e, na.rm = T), 3) sde <- round(stats::sd(e, na.rm = T), 3) a <- data.frame(Min = mine, `Qu.1` = q1, Median = mede, Mean = avge, `Qu.3` = q3, Max = maxe, sd = sde) row.names(a) <- NULL print(a) } #' @rdname EmissionsArray #' @method plot EmissionsArray #' @export plot.EmissionsArray <- function(x, main = "average emissions", ...) { e <- x if (length(dim(e)) == 4 ) { df <- Emissions(t(apply(e, c(3, 4), sum, na.rm=T))) Mean <- colMeans(df) SD <- unlist(lapply(df, stats::sd)) Min <- unlist(lapply(df, min)) Max <- unlist(lapply(df, max)) dfx <- data.frame(Mean, SD, Min, Max) graphics::plot(y = dfx$Mean, x = 1:nrow(dfx), ylim = c(min(dfx$Min), max(dfx$Max)), col = "red", type = "l", main = main, ...) graphics::lines(dfx$Mean+dfx$SD, ylim = c(min(dfx$Min), max(dfx$Max))) graphics::lines(dfx$Mean-dfx$SD, ylim = c(min(dfx$Min), max(dfx$Max))) graphics::points(dfx$Max, ylim = c(min(dfx$Min), max(dfx$Max))) graphics::points(dfx$Min, ylim = c(min(dfx$Min), max(dfx$Max))) } else { df <- Emissions(apply(e, c(1, 3), mean, na.rm=T)) graphics::plot(df, main = main, ...) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/EmissionsArray.R
#' DEPRECATED Construction function for class "EmissionsList" #' #' @description \code{EmissionsList} returns a transformed object with class "EmissionsList". #' #' @return Objects of class "EmissionsList" and numeric elements as "units" #' #' @param x object with class "EmissionList" #' @param object object with class "EmissionList" #' @param ... ignored #' @aliases EmissionsList print.EmissionsList summary.EmissionsList #' plot.EmissionsList #' @name vein-deprecated #' @seealso \code{\link{vein-deprecated}} #' @keywords internal NULL #' @rdname vein-deprecated #' #' @export #' @examples \dontrun{ #' # do not run #' # DEPRECATED #' } EmissionsList <- function(x, ...) { .Deprecated("EmissionsList") "EmissionsList" }
/scratch/gouwar.j/cran-all/cranData/vein/R/EmissionsList.R
#' Construction function for class "Evaporative" #' #' @description \code{Evaporative} returns a transformed object with class "Evaporative" and #' units g. This class represents the daily emissions presented by #' Mellios G and Ntziachristos (2016) Gasoline evaporation, Tier 2. Eventually #' it will be incorporated the techniques of Tier 3. #' #' #' @return Objects of class "Evaporative" or "units" #' #' @param x Object with class "numeric" #' @param object Object with class "Evaporative" #' @param ... ignored #' @aliases Evaporative print.Evaporative summary.Evaporative #' plot.Evaporative #' @name vein-deprecated #' @seealso \code{\link{vein-deprecated}} #' @keywords internal NULL #' @rdname vein-deprecated #' @section \code{Evaporative}: #' For \code{Evaporative}, use \code{\link{emis_evap}}. #' @export #' @examples \dontrun{ #' # do not run #' # DEPRECATED #' } Evaporative <- function(x, ...) { .Deprecated("Evaporative") "Evaporative" }
/scratch/gouwar.j/cran-all/cranData/vein/R/Evaporative.R
#' Construction function for class "GriddedEmissionsArray" #' #' @description \code{GriddedEmissionsArray} returns a transformed object with class #' "EmissionsArray" with 4 dimensions. #' #' @return Objects of class "GriddedEmissionsArray" #' #' @param x Object with class "SpatialPolygonDataFrame", "sf" "data.frame" or #' "matrix" #' @param object object with class "EmissionsArray' #' @param ... ignored #' @param rows Number of rows #' @param cols Number of columns #' @param times Number of times #' @param rotate Character, rotate array:"default", "left", "right", #' "cols","rows", "both", "br", "colsbr", "rowsbr", "bothbr". #' br means starting a matrix byrow #' @rdname GriddedEmissionsArray #' @aliases GriddedEmissionsArray print.GriddedEmissionsArray #' summary.GriddedEmissionsArray plot.GriddedEmissionsArray #' @importFrom sf st_set_geometry #' @importFrom utils head #' @examples \dontrun{ #' data(net) #' data(pc_profile) #' data(fe2015) #' data(fkm) #' PC_G <- c(33491,22340,24818,31808,46458,28574,24856,28972,37818,49050,87923, #' 133833,138441,142682,171029,151048,115228,98664,126444,101027, #' 84771,55864,36306,21079,20138,17439, 7854,2215,656,1262,476,512, #' 1181, 4991, 3711, 5653, 7039, 5839, 4257,3824, 3068) #' veh <- data.frame(PC_G = PC_G) #' pc1 <- my_age(x = net$ldv, y = PC_G, name = "PC") #' pcw <- temp_fact(net$ldv+net$hdv, pc_profile) #' speed <- netspeed(pcw, net$ps, net$ffs, net$capacity, net$lkm, alpha = 1) #' pckm <- units::set_units(fkm[[1]](1:24), "km") #' pckma <- cumsum(pckm) #' cod1 <- emis_det(po = "CO", cc = 1000, eu = "III", km = pckma[1:11]) #' cod2 <- emis_det(po = "CO", cc = 1000, eu = "I", km = pckma[12:24]) #' #vehicles newer than pre-euro #' co1 <- fe2015[fe2015$Pollutant=="CO", ] #24 obs!!! #' cod <- c(co1$PC_G[1:24]*c(cod1,cod2),co1$PC_G[25:nrow(co1)]) #' lef <- ef_ldv_scaled(co1, cod, v = "PC", t = "4S", cc = "<=1400", #' f = "G",p = "CO", eu=co1$Euro_LDV) #' E_CO <- emis(veh = pc1,lkm = net$lkm, ef = lef, speed = speed, agemax = 41, #' profile = pc_profile, simplify = TRUE) #' class(E_CO) #' E_CO_STREETS <- emis_post(arra = E_CO, pollutant = "CO", by = "streets", #' net = net, k = units::set_units(1, "1/h")) #' g <- make_grid(net, 1/102.47/2, 1/102.47/2) #500m in degrees #' E_CO_g <- emis_grid(spobj = E_CO_STREETS, g = g, sr= 31983) #' plot(E_CO_g["V9"]) #' # check all #' rots <- c("default", "left", "right", #' "cols","rows", "both", #' "br", "colsbr", "rowsbr", "bothbr") #' oldpar <- par() #' par(mfrow = c(2,5)) #' lg <- lapply(seq_along(rots), function(i){ #' x <- GriddedEmissionsArray(E_CO_g, #' rows = 19, #' cols = 23, #' times = 168, #' rotate = rots[i]) #' plot(x, main = rots[i]) #' }) #' #' par(mfrow = c(1,1)) #' } #' @export GriddedEmissionsArray <- function(x, ..., cols, rows, times = ncol(x), rotate = "default") { x$id <- NULL if(inherits(x, "Spatial")){ df <- sf::st_as_sf(x) df <- sf::st_set_geometry(df, NULL) } else if(inherits(x, "sf")){ df <- sf::st_set_geometry(x, NULL) } else { df <- x } if(times > ncol(df)) stop("`times` cannot be higher than number of columns of `x` without x$id") for (i in 1:ncol(df)) { df[, i] <- as.numeric(df[, i]) } # array # https://stackoverflow.com/a/42882677/2418532 #first reverse, then transpose, it's the same as rotate 90 degrees rotate_clockwise <- function(x) { t( apply(x, 2, rev))} #first transpose, then reverse, it's the same as rotate -90 degrees: rotate_counter_clockwise <- function(x) { apply( t(x),2, rev)} #1 default#### if(rotate == "default") { l <- lapply(1:times, function(i) { m <- t(matrix(df[, i], ncol = cols, nrow = rows, byrow = TRUE)) }) #2 left #### } else if(rotate == "left"){ l <- lapply(1:times, function(i) { m <- t(matrix(df[, i], ncol = cols, nrow = rows, byrow = TRUE)) rotate_counter_clockwise(m) }) #3 right#### } else if(rotate == "right"){ l <- lapply(1:times, function(i) { m <- t(matrix(df[, i], ncol = cols, nrow = rows, byrow = TRUE)) rotate_clockwise(m) }) #4 cols#### } else if(rotate == "cols"){ l <- lapply(1:ncol(df), function(j){ mx <- matrix(df[, j], nrow = rows, ncol = cols) mx <- mx[, ncol(mx):1] }) #5 rows#### } else if(rotate == "rows"){ l <- lapply(1:ncol(df), function(j){ mx <- matrix(df[, j], nrow = rows, ncol = cols) mx <- mx[nrow(mx):1, ] }) #6 both#### } else if(rotate == "both"){ l <- lapply(1:ncol(df), function(j){ mx <- matrix(df[, j], nrow = rows, ncol = cols) mx <- mx[nrow(mx):1, ncol(mx):1] }) #7 br#### } else if(rotate == "br"){ l <- lapply(1:ncol(df), function(j){ mx <- matrix(df[, j], nrow = rows, ncol = cols, byrow = TRUE) }) #8 colsbr#### } else if(rotate == "colsbr"){ l <- lapply(1:ncol(df), function(j){ mx <- matrix(df[, j], nrow = rows, ncol = cols, byrow = TRUE) mx <- mx[, ncol(mx):1] }) #9 rowsbr#### } else if(rotate == "rowsbr"){ l <- lapply(1:ncol(df), function(j){ mx <- matrix(df[, j], nrow = rows, ncol = cols, byrow = TRUE) mx <- mx[nrow(mx):1, ] }) #10 bothbr#### } else if(rotate == "bothbr"){ l <- lapply(1:ncol(df), function(j){ mx <- matrix(df[, j], nrow = rows, ncol = cols, byrow = TRUE) mx <- mx[nrow(mx):1, ncol(mx):1] }) } e <- simplify2array(l) class(e) <- c("GriddedEmissionsArray",class(e)) return(e) } #' @rdname GriddedEmissionsArray #' @method print GriddedEmissionsArray #' @export print.GriddedEmissionsArray <- function(x, ...) { e <- x cat(paste0("This GriddedEmissionsArray has:\n", #nocov start dim(e)[1], " lat points\n", dim(e)[2], " lon points\n", dim(e)[3], " hours\n")) #nocov end print(utils::head(e)) } #' @rdname GriddedEmissionsArray #' @method summary GriddedEmissionsArray #' @export summary.GriddedEmissionsArray <- function(object, ...) { e <- object summary(e[, , ]) } #' @rdname GriddedEmissionsArray #' @method plot GriddedEmissionsArray #' @export plot.GriddedEmissionsArray <- function(x, ..., times = 1) { oldpar <- par(no.readonly = TRUE) # code line i on.exit(par(oldpar)) # code line i + 1 e <- x graphics::image(e[ , , times], ...) }
/scratch/gouwar.j/cran-all/cranData/vein/R/GriddedEmissionsArray.R
#' Construction function for class "Speed" #' #' @description \code{Speed} returns a transformed object with class "Speed" and units #' km/h. This function includes two arguments, distance and time. Therefore, #' it is possible to change the units of the speed to "m" to "s" for example. #' This function returns a data.frame with units for speed. When this function #' is applied to numeric vectors it adds class "units". #' #' @return Constructor for class "Speed" or "units" #' #' @param x Object with class "data.frame", "matrix" or "numeric" #' @param dist String indicating the units of the resulting distance in speed. #' @param time Character to be the time units as denominator, default is "h" #' @param object Object with class "Speed" #' @param pal Palette of colors available or the number of the position #' @param rev Logical; to internally revert order of rgb color vectors. #' @param fig1 par parameters for fig, \code{\link{par}}. #' @param mai1 par parameters for mai, \code{\link{par}}. #' @param fig2 par parameters for fig, \code{\link{par}}. #' @param mai2 par parameters for mai, \code{\link{par}}. #' @param fig3 par parameters for fig, \code{\link{par}}. #' @param mai3 par parameters for mai, \code{\link{par}}. #' @param bias positive number. Higher values give more widely spaced colors at the high end. #' @param ... ignored #' Default is units is "km" #' @importFrom units as_units #' @importFrom grDevices rgb colorRamp #' @seealso \code{\link{units}} #' #' @rdname Speed #' @aliases Speed print.Speed summary.Speed plot.Speed #' @note default time unit for speed is hour #' @examples { #' data(net) #' data(pc_profile) #' speed <- Speed(net$ps) #' class(speed) #' plot(speed, type = "l") #' pc_week <- temp_fact(net$ldv+net$hdv, pc_profile) #' df <- netspeed(pc_week, net$ps, net$ffs, net$capacity, net$lkm) #' summary(df) #' plot(df) #' # changing to miles #' net$ps <- units::set_units(net$ps, "miles/h") #' net$ffs <- units::set_units(net$ffs, "miles/h") #' net$lkm <- units::set_units(net$lkm, "miles") #' df <- netspeed(pc_week, net$ps, net$ffs, net$capacity, net$lkm, dist = "miles") #' plot(df) #' } #' @export Speed <- function(x, ..., dist = "km", time = "h") { if ( is.matrix(x) ) { spd <- as.data.frame(x) for(i in 1:ncol(spd)){ spd[,i] <- spd[,i]*units::as_units(paste0(dist, " ", time, "-1")) } class(spd) <- c("Speed", "data.frame") } else if ( is.data.frame(x) ) { spd <- x for(i in 1:ncol(spd)){ spd[,i] <- spd[,i]*units::as_units(paste0(dist, " ", time, "-1")) } class(spd) <- c("Speed",class(x)) } else if ( is.list(x) ) { stop("List not supported") #SpeedList? } else if ( inherits(x, "units" )) { spd <- x if(as.character(units(spd)) != paste0(dist, "/", time) ){ message("Converting ", as.character(units(spd)), " to ", dist, "/", time) spd <- units::as_units(spd, paste0(dist, " ", time, "-1")) } else { message("Units are the same and no cerversions will be made") } } else if( inherits(x, "numeric") | inherits(x, "integer" )) { spd <- x*units::as_units(paste0(dist, " ", time, "-1")) } return(spd) } #' @rdname Speed #' @method print Speed #' @export print.Speed <- function(x, ...) { if(nrow(x) < 10 & ncol(x) < 10){ NextMethod("print", x, right = TRUE) } else if (nrow(x) > 10 & ncol(x) < 10){ print.data.frame(x[1:5, ], right = TRUE) cat(paste0("... and more ", nrow(x) - 5, " rows\n")) } else if(nrow(x) < 10 & ncol(x) > 10){ print.data.frame(x[, 1:5], right = TRUE) cat(paste0("... and more ", ncol(x) - 5, " columns\n")) } else { print.data.frame(x[1:5, 1:5], right = TRUE) cat(paste0("... and more ", nrow(x) - 5, " rows\n")) cat(paste0("... and more ", ncol(x) - 5, " columns\n")) } } #' @rdname Speed #' @method summary Speed #' @export summary.Speed <- function(object, ...) { spd <- object cat("Speeds by columns and street in study area = \n") print(summary(unlist(spd))) } #' @rdname Speed #' @method plot Speed #' @export plot.Speed <- function(x, pal = "mpl_inferno", rev = FALSE, fig1 = c(0,0.8,0,0.8), fig2 = c(0,0.8,0.55,1), fig3 = c(0.7,1,0,0.8), mai1 = c(1.0, 0.82, 0.82, 0.42), mai2 = c(1.8, 0.82, 0.50, 0.42), mai3 = c(1.0, 1.00, 0.82, 0.20), bias = 1.5, ...) { oldpar <- par(no.readonly = TRUE) # code line i on.exit(par(oldpar)) # code line i + 1 if(ncol(x) > 1) { graphics::par(fig=fig1, #new=TRUE, mai = mai1, ...) col <- grDevices::rgb(grDevices::colorRamp(colors = cptcity::cpt(pal, rev = rev), bias = bias)(seq(0, 1,0.01)), maxColorValue = 255) # fields::image.plot( # x = 1:ncol(x), # xaxt = "n", # z =t(as.matrix(x))[, nrow(x):1], # xlab = "", # ylab = paste0("Speed by streets [",as.character(units(x[[1]])), "]"), # col = col, horizontal = TRUE) graphics::image(x = 1:ncol(x), xaxt = "n", z = t(as.matrix(x))[, nrow(x):1], xlab = "", ylab = paste0("Speed by streets [",as.character(units(x[[1]])), "]"), col = col, axe = FALSE) axis(2) addscale(t(as.matrix(x))[, nrow(x):1], col = col) graphics::par(fig=fig2, mai = mai2, new=TRUE, ...) avage <- mean(unlist(x), na.rm = T) graphics::plot(colMeans(x, na.rm = T), type="l", ylab = paste0("Mean speed [",as.character(units(x[[1]])), "]"), xlab = "", frame = FALSE, xaxt = 'n') graphics::axis(3) graphics::abline(h = avage, col="red") cat("Weighted mean = ",round(avage,2), "\n") graphics::par(fig=fig3, new=TRUE, mai = mai3, ...) graphics::plot(x = rowMeans(x, na.rm = T), y = nrow(x):1, type = "l", frame = FALSE, yaxt = "n", ylab = "", xlab = NULL ) graphics::abline(v = avage, col="red") } else { graphics::plot(unlist(x), type = "l", main = "1 column data") } }
/scratch/gouwar.j/cran-all/cranData/vein/R/Speed.R
#' Construction function for class "Vehicles" #' #' @description \code{Vehicles} returns a tranformed object with class "Vehicles" and units #' 'veh'. The type of objects supported are of classes "matrix", "data.frame", #' "numeric" and "array". If the object is a matrix it is converted to data.frame. #' If the object is "numeric" it is converted to class "units". #' #' @return Objects of class "Vehicles" or "units" #' #' @param x Object with class "Vehicles" #' @param object Object with class "Vehicles" #' @param time Character to be the time units as denominator, default is NULL #' @param pal Palette of colors available or the number of the position #' @param rev Logical; to internally revert order of rgb color vectors. #' @param bk Break points in sorted order to indicate the intervals for assigning the colors. #' @param fig1 par parameters for fig, \code{\link{par}}. #' @param mai1 par parameters for mai, \code{\link{par}}. #' @param fig2 par parameters for fig, \code{\link{par}}. #' @param mai2 par parameters for mai, \code{\link{par}}. #' @param fig3 par parameters for fig, \code{\link{par}}. #' @param mai3 par parameters for mai, \code{\link{par}}. #' @param bias positive number. Higher values give more widely spaced colors at the high end. #' @param ... ignored #' @param time Character to be the time units as denominator, eg "1/h" #' @importFrom units as_units install_unit #' @importFrom graphics par plot abline #' @importFrom grDevices rgb colorRamp #' #' @rdname Vehicles #' @aliases Vehicles print.Vehicles summary.Vehicles plot.Vehicles #' @examples \dontrun{ #' lt <- rnorm(100, 300, 10) #' class(lt) #' vlt <- Vehicles(lt) #' class(vlt) #' plot(vlt) #' LT_B5 <- age_hdv(x = lt,name = "LT_B5") #' summary(LT_B5) #' plot(LT_B5) #' } #' @export Vehicles <- function(x, ..., time=NULL) { # units::install_unit("veh") if(inherits(x, "sf")) { geo <- sf::st_geometry(x) e <- sf::st_set_geometry(x, NULL) for(i in 1:ncol(e)){ e[,i] <- e[,i]*units::as_units("veh") } if(!missing(time)){ for(i in 1:ncol(e)) e[,i] <- e[,i]*units::as_units(1, time) } veh <- sf::st_sf(e, geometry = geo) } else if (is.matrix(x) ) { veh <- as.data.frame(x) for(i in 1:ncol(veh)){ veh[,i] <- veh[,i]*units::as_units("veh") } if(!missing(time)){ for(i in 1:ncol(e)) e[,i] <- e[,i]*units::as_units(1, time) } class(veh) <- c("Vehicles",class(veh)) } else if ( is.data.frame(x) ) { veh <- x for(i in 1:ncol(veh)){ veh[,i] <- veh[,i]*units::as_units("veh") } if(!missing(time)){ for(i in 1:ncol(e)) e[,i] <- e[,i]*units::as_units(1, time) } class(veh) <- c("Vehicles",class(x)) } else if ( inherits(x, "units" )) { veh <- x if(units(x)$numerator != "veh") stop("units are not 'veh'") } else if( inherits(x, "numeric") | inherits(x, "integer" )) { veh <- x*units::as_units("veh") if(!missing(time)){ veh <- veh*units::as_units(1, time) } } return(veh) } #' @rdname Vehicles #' @method print Vehicles #' @export print.Vehicles <- function(x, ...) { nr <- ifelse(nrow(x) <= 5, nrow(x), 5) if(ncol(x) == 1) { ndf <- names(x) df <- data.frame(ndf = x[1:nr, ]) names(df) <- ndf print.data.frame(df) } else { print.data.frame(x[1:nr, ]) } if(nrow(x) > 5) cat(paste0("... and ", nrow(x) - 5, " more rows\n")) } #' @rdname Vehicles #' @method summary Vehicles #' @export summary.Vehicles <- function(object, ...) { # units::install_unit("veh") veh <- object avage <- sum(seq(1,ncol(veh))*colSums(veh)/sum(veh)) cat("\nVehicles by columns in study area = \n") print(summary(colSums(veh)) ) cat("Average = ", round(avage,2),"\n") summary(rowSums(veh)) avveh <- mean(rowSums(veh), na.rm=T) cat("Vehicles by street in study area = \n") print(summary(rowSums(veh))) cat("\nAverage = ", round(avveh,2)) } #' @rdname Vehicles #' @method plot Vehicles #' @export plot.Vehicles <- function(x, pal = "colo_lightningmccarl_into_the_night", rev = TRUE, bk = NULL, fig1 = c(0,0.8,0,0.8), fig2 = c(0,0.8,0.55,1), fig3 = c(0.7,1,0,0.8), mai1 = c(1.0, 0.82, 0.82, 0.42), mai2 = c(1.8, 0.82, 0.50, 0.42), mai3 = c(1.0, 1.00, 0.82, 0.20), bias = 1.5, ...) { # # units::install_unit("veh", warn = F) # veh <- x # if ( inherits(veh, "data.frame") ) { # avage <- sum(seq(1,ncol(veh)) * colSums(veh)/sum(veh)) # Veh <- colSums(veh) # Veh <- Veh*units::as_units("veh") # graphics::plot(Veh, type = "l", ...) # graphics::abline(v = avage, col = "red") # if(message){ # cat("\nAverage = ",round(avage,2)) # }} # oldpar <- par(no.readonly = TRUE) # code line i on.exit(par(oldpar)) # code line i + 1 if(ncol(x) > 1) { graphics::par(fig=fig1, #new=TRUE, mai = mai1, ...) col <- grDevices::rgb(grDevices::colorRamp(colors = cptcity::cpt(pal, rev = rev), bias = bias)(seq(0, 1,0.01)), maxColorValue = 255) # old code using fields # fields::image.plot( # x = 1:ncol(x), # xaxt = "n", # z =t(as.matrix(x))[, nrow(x):1], # xlab = "", # ylab = paste0("Vehicles by streets [",as.character(units(x[[1]])), "]"), # breaks = bk, # col = col, horizontal = TRUE) # new using graphics and other imported code graphics::image(t(as.matrix(x))[, nrow(x):1], col = col, axe = FALSE, ylab = paste0("Vehicles by streets [",as.character(units(x[[1]])), "]")) axis(2, breaks = bk) addscale(t(as.matrix(x))[, nrow(x):1], col = col) graphics::par(fig=fig2, mai = mai2, new=TRUE, ...) avage <- sum(seq(1,ncol(x)) * colSums(x)/sum(x, na.rm = T)) graphics::plot(colSums(x, na.rm = T), type="l", ylab = paste0("Sum vehicles [",as.character(units(x[[1]])), "]"), xlab = "", frame = FALSE, xaxt = 'n') graphics::axis(3) graphics::abline(v = avage, col="red") cat("Weighted mean = ",round(avage,2), "\n") graphics::par(fig=fig3, new=TRUE, mai = mai3, ...) graphics::plot(x = rowSums(x, na.rm = T), y = nrow(x):1, type = "l", frame = FALSE, yaxt = "n", ylab = "", xlab = NULL ) graphics::abline(v = mean(rowSums(x, na.rm = T), na.rm = T), col="red") } else { graphics::plot(unlist(x), type = "l", main = "1 column data") } }
/scratch/gouwar.j/cran-all/cranData/vein/R/Vehicles.R
#' Construction function to add unit km #' #' @family Add distance unitts #' #' @description \code{add_lkm} just add unit 'km' to different R objects #' #' @return Objects of class "data.frame" or "units" #' #' @param x Object with class "data.frame", "matrix", "numeric" or "integer" #' @importFrom units as_units #' #' @examples \dontrun{ #' a <- add_lkm(rnorm(100)*10) #' plot(a) #' b <- add_lkm(matrix(rnorm(100)*10, ncol = 10)) #' print(head(b)) #' } #' @export add_lkm <- function(x) { if ( is.matrix(x) ) { e <- as.data.frame(x) for(i in 1:ncol(e)){ e[,i] <- e[,i]*units::as_units("km") } } else if ( is.data.frame(x) ) { e <- x for(i in 1:ncol(x)){ e[,i] <- e[,i]*units::as_units("km") } } else if( inherits(x, "numeric") | inherits(x, "integer" )) { e <- x*units::as_units("km") } return(e) } #' Construction function to add unit miles #' #' @family Add distance unitts #' #' @description \code{add_miles} just add unit 'miles' to different R objects #' #' @return Objects of class "data.frame" or "units" #' #' @param x Object with class "data.frame", "matrix", "numeric" or "integer" #' @importFrom units as_units #' #' @examples \dontrun{ #' a <- add_miles(rnorm(100)*10) #' plot(a) #' b <- add_miles(matrix(rnorm(100)*10, ncol = 10)) #' print(head(b)) #' } #' @export add_miles <- function(x) { if ( is.matrix(x) ) { e <- as.data.frame(x) for(i in 1:ncol(e)){ e[,i] <- e[,i]*units::as_units("miles") } } else if ( is.data.frame(x) ) { e <- x for(i in 1:ncol(x)){ e[,i] <- e[,i]*units::as_units("miles") } } else if( inherits(x, "numeric") | inherits(x, "integer" )) { e <- x*units::as_units("miles") } return(e) }
/scratch/gouwar.j/cran-all/cranData/vein/R/add_lkm.R
#' Add polygon id to lines road network #' #'@description Sometimes you need to add polygon id into your streets road network. #'\code{\link{add_polid}} add add_polid id into your road network cropping your #' network by. #' #' For instance, you have open street maps road network the you have the #' polygon of your regions. This function adds the id of your polygon #' as a new column in the streets network. #' #' @param polyg sf object POLYGON or sp #' @param street streets road network class sf or sp #' @param by Character indicating the column with the id in polyg #' @importFrom sf st_crop st_cast st_as_sf #' @export #' @seealso \code{\link{emis_to_streets}} #' @examples \dontrun{ #' data(net) #' nets <- sf::st_as_sf(net) #' bb <- sf::st_as_sf(sf::st_as_sfc(sf::st_bbox(nets))) #' bb$id <- "a" #' a <- add_polid(polyg = bb, street = nets, by = "id") #' } add_polid <- function(polyg, street, by){ polyd <- sf::st_as_sf(polyg) street <- sf::st_as_sf(street) do.call("rbind", lapply(1:nrow(polyg), function(i){ b <- suppressWarnings(sf::st_crop(x = street, polyg[i, ])) b <- sf::st_cast(b, "MULTILINESTRING") b[[by]] <- polyg[[by]][i] b })) }
/scratch/gouwar.j/cran-all/cranData/vein/R/add_polid.R
#' function to add a scale to a image plot #' #' @description method to plot a scale in image plot. #' #' @param z matrix or vector #' @param zlim z limit #' @param col color #' @param breaks interval for the tickmarks #' @param horiz TRUE (default) to a horizontal scale #' @param xlim x limit #' @param ylim y limitS #' @param ... other arguments to plot #' @importFrom graphics par axis polygon #' @importFrom grDevices heat.colors #' #' @examples \dontrun{ #' mat <- matrix(100:1,ncol = 10, byrow = F) #' cor <- grDevices::heat.colors(100) #' image(mat,axe = FALSE, main = "numbers from 1 to 100", col = cor) #' axis(2) #' addscale(mat, col = cor) #' } #' @export ## Function to plot color bar ## from https://menugget.blogspot.com/2011/08/adding-scale-to-image-plot.html#more addscale <- function(z, zlim = range(z,na.rm = TRUE), col = grDevices::heat.colors(12), breaks = pretty(zlim), horiz = TRUE, ylim = NULL, xlim = NULL, ...){ ## adapted from https://github.com/dnychka/fieldsRPackage/blob/main/fields/R/image.family.R imageplot.setup <- function(x, add = FALSE, legend.shrink = 0.9, legend.width = 1, horizontal = FALSE, legend.mar = NULL, smallplot = NULL, ...) { old.par <- par(no.readonly = TRUE) if (is.null(legend.mar)) { legend.mar <- ifelse(horizontal, 3.1, 5.1) } # compute how big a text character is char.size <- ifelse(horizontal, par()$cin[2]/par()$din[2], par()$cin[1]/par()$din[1]) # This is how much space to work with based on setting the margins in the # high level par command to leave between strip and big plot offset <- char.size * ifelse(horizontal, par()$mar[1], par()$mar[4]) # this is the width of the legned strip itself. legend.width <- char.size * legend.width # this is room for legend axis labels legend.mar <- legend.mar * char.size # smallplot is the plotting region for the legend. if (is.null(smallplot)) { smallplot <- old.par$plt if (horizontal) { smallplot[3] <- legend.mar smallplot[4] <- legend.width + smallplot[3] pr <- (smallplot[2] - smallplot[1]) * ((1 - legend.shrink)/2) smallplot[1] <- smallplot[1] + pr smallplot[2] <- smallplot[2] - pr } else { smallplot[2] <- 1 - legend.mar smallplot[1] <- smallplot[2] - legend.width pr <- (smallplot[4] - smallplot[3]) * ((1 - legend.shrink)/2) smallplot[4] <- smallplot[4] - pr smallplot[3] <- smallplot[3] + pr } } return(smallplot) } if(!missing(breaks)){ if(length(breaks) != (length(col)+1)){stop("must have one more break than colour")} } if(missing(breaks) & !missing(zlim)){ breaks <- seq(zlim[1], zlim[2], length.out=(length(col)+1)) } if(missing(breaks) & missing(zlim)){ zlim <- range(z, na.rm=TRUE) zlim[2] <- zlim[2]+c(zlim[2]-zlim[1])*(1E-3) zlim[1] <- zlim[1]-c(zlim[2]-zlim[1])*(1E-3) breaks <- seq(zlim[1], zlim[2], length.out=(length(col)+1)) } poly <- vector(mode="list", length(col)) for(i in seq(poly)){ poly[[i]] <- c(breaks[i], breaks[i+1], breaks[i+1], breaks[i]) } xaxt <- ifelse(horiz, "s", "n") yaxt <- ifelse(horiz, "n", "s") if(horiz){YLIM<-c(0,1); XLIM<-range(breaks)} if(!horiz){YLIM<-range(breaks); XLIM<-c(0,1)} if(missing(xlim)) xlim=XLIM if(missing(ylim)) ylim=YLIM old.par <- par(no.readonly = TRUE) on.exit(par(old.par)) smallplot <- imageplot.setup(legend.width = 1.2,horizontal = TRUE) par(new = TRUE, pty = "m", plt = smallplot, err = -1) plot(NA,t="n",ylim=ylim, xlim=xlim, xaxt=xaxt, yaxt=yaxt, xaxs="i", yaxs="i", xlab = "",ylab = "", ...) for(i in seq(poly)){ if(horiz){ polygon(poly[[i]], c(0,0,1,1), col=col[i], border=NA) } if(!horiz){ polygon(c(0,0,1,1), poly[[i]], col=col[i], border=NA) } } }
/scratch/gouwar.j/cran-all/cranData/vein/R/add_scale.R
#' Average daily traffic (ADT) from hourly traffic data. #' #' @description \code{\link{adt}} calculates ADT based on hourly traffic data. #' #' @param pc numeric vector for passenger cars #' @param lcv numeric vector for light commercial vehicles #' @param hgv numeric vector for heavy good vehicles or trucks #' @param bus numeric vector for bus #' @param mc numeric vector for motorcycles #' @param p_pc data-frame profile for passenger cars, 24 hours only. #' @param p_lcv data-frame profile for light commercial vehicles, 24 hours only. #' @param p_hgv data-frame profile for heavy good vehicles or trucks, 24 hours only. #' @param p_bus data-frame profile for bus, 24 hours only. #' @param p_mc data-frame profile for motorcycles, 24 hours only. #' @param feq_pc Numeric, factor equivalence #' @param feq_lcv Numeric, factor equivalence #' @param feq_hgv Numeric, factor equivalence #' @param feq_bus Numeric, factor equivalence #' @param feq_mc Numeric, factor equivalence #' @return numeric vector of total volume of traffic per link as ADT #' @export #' @examples \dontrun{ #' data(net) #' data(pc_profile) #' p1 <- pc_profile[, 1] #' adt1 <- adt(pc = net$ldv*0.75, #' lcv = net$ldv*0.1, #' hgv = net$hdv, #' bus = net$hdv*0.1, #' mc = net$ldv*0.15, #' p_pc = p1, #' p_lcv = p1, #' p_hgv = p1, #' p_bus = p1, #' p_mc = p1) #' head(adt1) #' } adt <- function(pc, lcv, hgv, bus, mc, p_pc, p_lcv, p_hgv, p_bus, p_mc, feq_pc = 1, feq_lcv = 1.5, feq_hgv = 2, feq_bus = 2, feq_mc = 0.5) { pc <- remove_units(pc) lcv <- remove_units(lcv) hgv <- remove_units(hgv) bus <- remove_units(bus) mc <- remove_units(mc) df_pc <- vein::temp_fact(q = pc*feq_pc, pro = p_pc) df_lcv <- vein::temp_fact(q = lcv*feq_lcv, pro = p_lcv) df_hgv <- vein::temp_fact(q = hgv*feq_hgv, pro = p_hgv) df_bus <- vein::temp_fact(q = bus*feq_bus, pro = p_bus) df_mc <- vein::temp_fact(q = mc*feq_mc, pro = p_mc) veq = df_pc + df_lcv + df_hgv + df_bus + df_mc n <- ncol(veq)/24 dx <- do.call("cbind", lapply(1:n, function(i){ rowSums(veq[, (24*(i-1) + 1) : (24*(i-1) + 24)]) })) ADT <- rowMeans(dx) return(Vehicles(ADT)) }
/scratch/gouwar.j/cran-all/cranData/vein/R/adt.R
#' Applies a survival rate to numeric new vehicles #' #' @family age #' #' @description \code{\link{age}} returns survived vehicles #' #' @param x Numeric; numerical vector of sales or registrations for each year #' @param type Character; any of "gompertz", "double_logistic", "weibull" and "weibull2" #' @param a Numeric; parameter of survival equation #' @param b Numeric; parameter of survival equation #' @param agemax Integer; age of oldest vehicles for that category #' @param verbose Logical; message with average age and total numer of vehicles #' regions or streets. #' @return dataframe of age distrubution of vehicles #' @importFrom sf st_sf st_as_sf #' @export #' @note #' #' The functions age* produce distribution of the circulating fleet by age of use. #' The order of using these functions is: #' #' 1. If you know the distribution of the vehicles by age of use , use: \code{\link{my_age}} #' 2. If you know the sales of vehicles, or the registry of new vehicles, #' use \code{\link{age}} to apply a survival function. #' 3. If you know the theoretical shape of the circulating fleet and you can use #' \code{\link{age_ldv}}, \code{\link{age_hdv}} or \code{\link{age_moto}}. For instance, #' you dont know the sales or registry of vehicles, but somehow you know #' the shape of this curve. #' 4. You can use/merge/transform/dapt any of these functions. #' #' #' \strong{gompertz: 1 - exp(-exp(a + b*time))}, #' defaults PC: b = -0.137, a = 1.798, LCV: b = -0.141, a = 1.618 #' MCT (2006). de Gases de Efeito Estufa-Emissoes de Gases de #' Efeito Estufa por Fontes Moveis, no Setor Energético. Ministerio da Ciencia e Tecnologia. #' This curve is also used by Guo and Wang (2012, 2015) in the form: #' V*exp(alpha*exp(beta*E)) where #' V is the saturation car ownership level and E GDP per capita #' Huo, H., & Wang, M. (2012). Modeling future vehicle sales and stock in China. #' Energy Policy, 43, 17–29. doi:10.1016/j.enpol.2011.09.063 #' Huo, Hong, et al. "Vehicular air pollutant emissions in China: evaluation of past control #' policies and future perspectives." Mitigation and Adaptation Strategies for Global Change 20.5 (2015): 719-733. #' #' \strong{double_logistic: 1/(1 + exp(a*(time + b))) + 1/(1 + exp(a*(time - b)))}, #' defaults PC: b = 21, a = 0.19, LCV: b = 15.3, a = 0.17, HGV: b = 17, a = 0.1, BUS: b = 19.1, a = 0.16 #' MCT (2006). de Gases de Efeito Estufa-Emissoes de Gases de #' Efeito Estufa por Fontes Moveis, no Setor Energético. Ministerio da Ciencia e Tecnologia. #' #' \strong{weibull: exp(-(time/a)^b)}, #' defaults PC: b = 4.79, a = 14.46, Taxi: b = +inf, a = 5, #' Government and business: b = 5.33, a = 13.11 #' Non-operating vehicles: b = 5.08, a = 11.53 #' Bus: b = +inf, a = 9, non-transit bus: b = +inf, a = 5.5 #' Heavy HGV: b = 5.58, a = 12.8, Medium HGV: b = 5.58, a = 10.09, Light HGV: b = 5.58, a = 8.02 #' Hao, H., Wang, H., Ouyang, M., & Cheng, F. (2011). Vehicle survival patterns in China. #' Science China Technological Sciences, 54(3), 625-629. #' #' \strong{weibull2: exp(-((time + b)/a)^b )}, #' defaults b = 11, a = 26 #' Zachariadis, T., Samaras, Z., Zierock, K. H. (1995). Dynamic modeling of vehicle #' populations: an engineering approach for emissions calculations. Technological #' Forecasting and Social Change, 50(2), 135-149. Cited by Huo and Wang (2012) #' #' @examples \dontrun{ #' vehLIA <- rep(1, 25) #' PV_Minia <- age(x = vehLIA) #' PV_Minib <- age(x = vehLIA, type = "weibull2", b = 11, a = 26) #' PV_Minic <- age(x = vehLIA, type = "double_logistic", b = 21, a = 0.19) #' PV_Minid <- age(x = vehLIA, type = "gompertz", b = -0.137, a = 1.798) #' dff <- data.frame(PV_Minia, PV_Minib, PV_Minic, PV_Minid) #' colplot(dff) #' } age <- function (x, type = "weibull", a = 14.46, b = 4.79, agemax, verbose = FALSE){ # check agemax if(!missing(agemax)) x <- x[1:agemax] # gompertz #### if(type == "gompertz") { surv <- function (time, a, b) {1 - exp(-exp(a + b*time))} anos <- 1:length(x) d <- surv(time = anos, a = a, b = b) df <- x*d # double logistic #### } else if(type == "double_logistic"){ surv <- function (time, a, b) { 1/(1 + exp(a*(time + b))) + 1/(1 + exp(a*(time - b))) } anos <- 1:length(x) d <- surv(time = anos, a = a, b = b) df <- x*d # weibull #### } else if(type == "weibull"){ surv <- function (time, a, b) { exp(-(time/a)^b) } anos <- 1:length(x) d <- surv(time = anos, a = a, b = b) df <- x*d } else if(type == "weibull2"){ surv <- function (time, a, b) { exp(-((time + b)/a)^b ) } anos <- 1:length(x) d <- surv(time = anos, a = a, b = b) df <- x*d } # data.frame #### if(verbose){ # message(paste("Average age of is", # round(sum(anos*sum(df, na.rm = T)/sum(df, na.rm = T)), 2), # sep=" ")) message(paste("Number of vehicles is", round(sum(df, na.rm = T)/1000, 2), "* 10^3 veh", sep=" ") ) cat("\n") } # replace NA and NaN df[is.na(df)] <- 0 return(Vehicles(df)) }
/scratch/gouwar.j/cran-all/cranData/vein/R/age.R
#' Returns amount of vehicles at each age #' #' @family age #' #' @description \code{\link{age_hdv}} returns amount of vehicles at each age #' #' @param x Numeric; numerical vector of vehicles with length equal to lines features of road network #' @param name Character; of vehicle assigned to columns of dataframe #' @param a Numeric; parameter of survival equation #' @param b Numeric; parameter of survival equation #' @param agemin Integer; age of newest vehicles for that category #' @param agemax Integer; age of oldest vehicles for that category #' @param k Numeric; multiplication factor. If its length is > 1, it must match the length of x #' @param bystreet Logical; when TRUE it is expecting that 'a' and 'b' are numeric vectors with length equal to x #' @param net SpatialLinesDataFrame or Spatial Feature of "LINESTRING" #' @param verbose Logical; message with average age and total numer of vehicles #' @param namerows Any vector to be change row.names. For instance, name of #' regions or streets. #' @param time Character to be the time units as denominator, eg "1/h" #' @return dataframe of age distrubution of vehicles at each street #' @importFrom sf st_sf st_as_sf #' @note #' The functions age* produce distribution of the circulating fleet by age of use. #' The order of using these functions is: #' #' 1. If you know the distribution of the vehicles by age of use , use: \code{\link{my_age}} #' 2. If you know the sales of vehicles, or the registry of new vehicles, #' use \code{\link{age}} to apply a survival function. #' 3. If you know the theoretical shape of the circulating fleet and you can use #' \code{\link{age_ldv}}, \code{\link{age_hdv}} or \code{\link{age_moto}}. For instance, #' you dont know the sales or registry of vehicles, but somehow you know #' the shape of this curve. #' 4. You can use/merge/transform/adapt any of these functions. #' @export #' @examples \dontrun{ #' data(net) #' LT_B5 <- age_hdv(x = net$hdv,name = "LT_B5") #' plot(LT_B5) #' LT_B5 <- age_hdv(x = net$hdv, name = "LT_B5", net = net) #' plot(LT_B5) #' } age_hdv <- function (x, name = "age", a = 0.2, b = 17, agemin = 1, agemax = 50, k = 1, bystreet = F, net, verbose = FALSE, namerows, time){ # check na x[is.na(x)] <- 0 x <- as.numeric(x) # length k if(length(k) > 1 & length(k) < length(x)){ stop("length of 'k' must be 1 ore equal to length of 'x'") } # check agemax if(agemax < 1) stop("Agemax should be bigger than 1") # bystreet = TRUE if (bystreet == TRUE){ if(length(x) != length(a)){ stop("Lengths of veh and age must be the same") } d <- suca <- list() for (i in seq_along(x)) { suca[[i]] <- function (t) {1/(1 + exp(a[i]*(t+b[i])))+1/(1 + exp(a[i]*(t-b[i])))} anos <- seq(agemin,agemax) d[[i]] <- (-1)*diff(suca[[i]](anos)) d[[i]][length(d[[i]])+1] <- d[[i]][length(d[[i]])] d[[i]] <- d[[i]] + (1 - sum(d[[i]]))/length(d[[i]]) d[[i]] <- d[[i]]*x[i] } df <- as.data.frame(matrix(0,ncol=length(anos), nrow=1)) for (i in seq_along(x)) { df[i,] <- d[[i]] } df <- as.data.frame(cbind(as.data.frame(matrix(0,ncol=agemin-1, nrow=length(x))), df)) names(df) <- paste(name,seq(1,agemax),sep="_") df <- df*k if(verbose){ message(paste("Average age of",name, "is", round(sum(seq(1,agemax)*base::colSums(df)/sum(df)), 2), sep=" ")) message(paste("Number of",name, "is", round(sum(df, na.rm = T), 3), " [veh]", sep=" ")) cat("\n") } if(!missing(namerows)) { if(length(namerows) != nrow(df)) stop("length of namerows must be the length of number of rows of veh") row.names(df) <- namerows } # replace NA and NaN df[is.na(df)] <- 0 if(!missing(net)){ netsf <- sf::st_as_sf(net) if(!missing(time)){ dfsf <- sf::st_sf(Vehicles(df*k, time = time), geometry = sf::st_geometry(netsf)) } else { dfsf <- sf::st_sf(Vehicles(df*k), geometry = sf::st_geometry(netsf)) } return(dfsf) } else { if(!missing(time)){ return(Vehicles(df*k, time = time)) } else { return(Vehicles(df*k)) } } #bystreet = FALSE } else { suca <- function (t) {1/(1 + exp(a*(t+b)))+1/(1 + exp(a*(t-b)))} anos <- seq(agemin,agemax) d <- (-1)*diff(suca(anos)) d[length(d)+1] <- d[length(d)] d <- d + (1 - sum(d))/length(d) df <- as.data.frame(as.matrix(x) %*%matrix(d,ncol=length(anos), nrow=1)) df <- as.data.frame(cbind(as.data.frame(matrix(0,ncol=agemin-1, nrow=length(x))), df)) names(df) <- paste(name,seq(1,agemax),sep="_") df <- df*k if(verbose){ message(paste("Average age of",name, "is", round(sum(seq(1,agemax)*base::colSums(df)/sum(df)), 2), sep=" ")) message(paste("Number of",name, "is", round(sum(df, na.rm = T)/1000, 2), "* 10^3 veh", sep=" ")) cat("\n") } if(!missing(namerows)) { if(length(namerows) != nrow(df)) stop("length of namerows must be the length of number of rows of veh") row.names(df) <- namerows } # replace NA and NaN df[is.na(df)] <- 0 if(!missing(net)){ netsf <- sf::st_as_sf(net) if(!missing(time)){ dfsf <- sf::st_sf(Vehicles(df, time = time), geometry = sf::st_geometry(netsf)) } else { dfsf <- sf::st_sf(Vehicles(df), geometry = sf::st_geometry(netsf)) } return(dfsf) } else { if(!missing(time)){ return(Vehicles(df, time = time)) } else { return(Vehicles(df)) } } } }
/scratch/gouwar.j/cran-all/cranData/vein/R/age_hdv.R
#' Returns amount of vehicles at each age #' #' @family age #' #' @description \code{\link{age_ldv}} returns amount of vehicles at each age #' #' @param x Numeric; numerical vector of vehicles with length equal to lines features of road network #' @param name Character; of vehicle assigned to columns of dataframe #' @param a Numeric; parameter of survival equation #' @param b Numeric; parameter of survival equation #' @param agemin Integer; age of newest vehicles for that category #' @param agemax Integer; age of oldest vehicles for that category #' @param k Numeric; multiplication factor. If its length is > 1, it must match the length of x #' @param bystreet Logical; when TRUE it is expecting that 'a' and 'b' are numeric vectors with length equal to x #' @param net SpatialLinesDataFrame or Spatial Feature of "LINESTRING" #' @param verbose Logical; message with average age and total numer of vehicles #' @param namerows Any vector to be change row.names. For instance, name of #' regions or streets. #' @param time Character to be the time units as denominator, eg "1/h" #' @return dataframe of age distrubution of vehicles #' @importFrom sf st_sf st_as_sf #' @note #' The functions age* produce distribution of the circulating fleet by age of use. #' The order of using these functions is: #' #' 1. If you know the distribution of the vehicles by age of use , use: \code{\link{my_age}} #' 2. If you know the sales of vehicles, or the registry of new vehicles, #' use \code{\link{age}} to apply a survival function. #' 3. If you know the theoretical shape of the circulating fleet and you can use #' \code{\link{age_ldv}}, \code{\link{age_hdv}} or \code{\link{age_moto}}. For instance, #' you dont know the sales or registry of vehicles, but somehow you know #' the shape of this curve. #' 4. You can use/merge/transform/adapt any of these functions. #' @export #' @note It consists in a Gompertz equation with default parameters from #' 1 national emissions inventory for green housegases in Brazil, MCT 2006 #' @examples \dontrun{ #' data(net) #' PC_E25_1400 <- age_ldv(x = net$ldv, name = "PC_E25_1400") #' plot(PC_E25_1400) #' PC_E25_1400 <- age_ldv(x = net$ldv, name = "PC_E25_1400", net = net) #' plot(PC_E25_1400) #' } age_ldv <- function (x, name = "age", a = 1.698, b = -0.2, agemin = 1, agemax = 50, k = 1, bystreet = F, net, verbose = FALSE, namerows, time){ # check na x[is.na(x)] <- 0 x <- as.numeric(x) # length k if(length(k) > 1 & length(k) < length(x)){ stop("length of 'k' must be 1 ore equal to length of 'x'") } #check agemax if(agemax < 1) stop("Agemax should be bigger than 1") #bystreet = TRUE if (bystreet == T){ if(length(x) != length(a)){ stop("Lengths of veh and age must be the same") } d <- suca <- list() for (i in seq_along(x)) { suca[[i]] <- function (t) {1 - exp(-exp(a[i] + b[i]*t))} anos <- seq(agemin,agemax) d[[i]] <- (-1)*diff(suca[[i]](anos)) d[[i]][length(d[[i]])+1] <- d[[i]][length(d[[i]])] d[[i]] <- d[[i]] + (1 - sum(d[[i]]))/length(d[[i]]) d[[i]] <- d[[i]]*x[i] } df <- as.data.frame(matrix(0,ncol=length(anos), nrow=1)) for (i in seq_along(x)) { df[i,] <- d[[i]] } df <- as.data.frame(cbind(as.data.frame(matrix(0,ncol=agemin-1, nrow=length(x))), df)) names(df) <- paste(name,seq(1,agemax),sep="_") df <- df*k if(verbose){ message(paste("Average age of",name, "is", round(sum(seq(1,agemax)*base::colSums(df, na.rm = T)/sum(df, na.rm = T)), 2), sep=" ")) message(paste("Number of",name, "is", round(sum(df, na.rm = T)/1000, 2), "* 10^3 veh", sep=" ") ) cat("\n") } if(!missing(namerows)) { if(length(namerows) != nrow(df)) stop("length of namerows must be the length of number of rows of veh") row.names(df) <- namerows } if(!missing(net)){ netsf <- sf::st_as_sf(net) if(!missing(time)){ dfsf <- sf::st_sf(Vehicles(df*k, time = time), geometry = sf::st_geometry(netsf)) } else { dfsf <- sf::st_sf(Vehicles(df*k), geometry = sf::st_geometry(netsf)) } return(dfsf) } else { if(!missing(time)){ return(Vehicles(df*k, time = time)) } else { return(Vehicles(df*k)) } } #bystreet = FALSE } else { suca <- function (t) {1 - exp(-exp(a + b*t))} anos <- seq(agemin,agemax) d <- (-1)*diff(suca(anos)) d[length(d)+1] <- d[length(d)] d <- d + (1 - sum(d))/length(d) df <- as.data.frame(as.matrix(x) %*%matrix(d,ncol=length(anos), nrow=1)) df <- as.data.frame(cbind(as.data.frame(matrix(0,ncol=agemin-1, nrow=length(x))), df)) names(df) <- paste(name,seq(1,agemax),sep="_") df <- df*k if(verbose){ message(paste("Average age of",name, "is", round(sum(seq(1,agemax)*base::colSums(df, na.rm = T)/sum(df, na.rm = T)), 2), sep=" ")) message(paste("Number of",name, "is", round(sum(df, na.rm = T), 3), " [veh]", sep=" ")) cat("\n") } if(!missing(namerows)) { if(length(namerows) != nrow(df)) stop("length of namerows must be the length of number of rows of veh") row.names(df) <- namerows } # replace NA and NaN df[is.na(df)] <- 0 if(!missing(net)){ netsf <- sf::st_as_sf(net) if(!missing(time)){ dfsf <- sf::st_sf(Vehicles(df, time = time), geometry = sf::st_geometry(netsf)) } else { dfsf <- sf::st_sf(Vehicles(df), geometry = sf::st_geometry(netsf)) } return(dfsf) } else { if(!missing(time)){ return(Vehicles(df, time = time)) } else { return(Vehicles(df)) } } } }
/scratch/gouwar.j/cran-all/cranData/vein/R/age_ldv.R
#' Returns amount of vehicles at each age #' #' @family age #' #' @description \code{\link{age_moto}} returns amount of vehicles at each age #' #' @param x Numeric; numerical vector of vehicles with length equal to lines features of road network #' @param name Character; of vehicle assigned to columns of dataframe #' @param a Numeric; parameter of survival equation #' @param b Numeric; parameter of survival equation #' @param agemin Integer; age of newest vehicles for that category #' @param agemax Integer; age of oldest vehicles for that category #' @param k Numeric; multiplication factor. If its length is > 1, it must match the length of x #' @param bystreet Logical; when TRUE it is expecting that 'a' and 'b' are numeric vectors with length equal to x #' @param net SpatialLinesDataFrame or Spatial Feature of "LINESTRING" #' @param verbose Logical; message with average age and total numer of vehicles #' @param namerows Any vector to be change row.names. For instance, name of #' regions or streets. #' @param time Character to be the time units as denominator, eg "1/h" #' @return dataframe of age distrubution of vehicles #' @importFrom sf st_sf st_as_sf #' @note #' The functions age* produce distribution of the circulating fleet by age of use. #' The order of using these functions is: #' #' 1. If you know the distribution of the vehicles by age of use , use: \code{\link{my_age}} #' 2. If you know the sales of vehicles, or the registry of new vehicles, #' use \code{\link{age}} to apply a survival function. #' 3. If you know the theoretical shape of the circulating fleet and you can use #' \code{\link{age_ldv}}, \code{\link{age_hdv}} or \code{\link{age_moto}}. For instance, #' you dont know the sales or registry of vehicles, but somehow you know #' the shape of this curve. #' 4. You can use/merge/transform/adapt any of these functions. #' @export #' @examples \dontrun{ #' data(net) #' MOTO_E25_500 <- age_moto(x = net$ldv, name = "M_E25_500", k = 0.4) #' plot(MOTO_E25_500) #' MOTO_E25_500 <- age_moto(x = net$ldv, name = "M_E25_500", k = 0.4, net = net) #' plot(MOTO_E25_500) #' } age_moto <- function (x, name = "age", a = 0.2, b = 17, agemin = 1, agemax = 50, k = 1, bystreet = FALSE, net, verbose = FALSE, namerows, time){ # check na x[is.na(x)] <- 0 x <- as.numeric(x) # length k if(length(k) > 1 & length(k) < length(x)){ stop("length of 'k' must be 1 ore equal to length of 'x'") } # check agemax if(agemax < 1) stop("Agemax should be bigger than 1") # bystreet = TRUE if (bystreet == TRUE){ if(length(x) != length(a)){ stop("Lengths of veh and age must be the same") } d <- suca <- list() for (i in seq_along(x)) { suca[[i]] <- function (t) {1/(1 + exp(a[i]*(t+b[i])))+1/(1 + exp(a[i]*(t-b[i])))} anos <- seq(agemin,agemax) d[[i]] <- (-1)*diff(suca[[i]](anos)) d[[i]][length(d[[i]])+1] <- d[[i]][length(d[[i]])] d[[i]] <- d[[i]] + (1 - sum(d[[i]]))/length(d[[i]]) d[[i]] <- d[[i]]*x[i] } df <- as.data.frame(matrix(0,ncol=length(anos), nrow=1)) for (i in seq_along(x)) { df[i,] <- d[[i]] } df <- as.data.frame(cbind(as.data.frame(matrix(0,ncol=agemin-1, nrow=length(x))), df)) names(df) <- paste(name,seq(1,agemax),sep="_") df <- df*k if(verbose){ message(paste("Average age of",name, "is", round(sum(seq(1,agemax)*base::colSums(df)/sum(df)), 2), sep=" ")) message(paste("Number of",name, "is", round(sum(df, na.rm = T), 3), " [veh]", sep=" ")) cat("\n") } if(!missing(namerows)) { if(length(namerows) != nrow(df)) stop("length of namerows must be the length of number of rows of veh") row.names(df) <- namerows } # replace NA and NaN df[is.na(df)] <- 0 if(!missing(net)){ netsf <- sf::st_as_sf(net) if(!missing(time)){ dfsf <- sf::st_sf(Vehicles(df*k, time = time), geometry = sf::st_geometry(netsf)) } else { dfsf <- sf::st_sf(Vehicles(df*k), geometry = sf::st_geometry(netsf)) } return(dfsf) } else { if(!missing(time)){ return(Vehicles(df*k, time = time)) } else { return(Vehicles(df*k)) } } #bystreet = FALSE } else { suca <- function (t) {1/(1 + exp(a*(t+b)))+1/(1 + exp(a*(t-b)))} anos <- seq(agemin,agemax) d <- (-1)*diff(suca(anos)) d[length(d)+1] <- d[length(d)] d <- d + (1 - sum(d))/length(d) df <- as.data.frame(as.matrix(x) %*%matrix(d,ncol=length(anos), nrow=1)) df <- as.data.frame(cbind(as.data.frame(matrix(0,ncol=agemin-1, nrow=length(x))), df)) names(df) <- paste(name,seq(1,agemax),sep="_") df <- df*k if(verbose){ message(paste("Average age of",name, "is", round(sum(seq(1,agemax)*base::colSums(df)/sum(df)), 2), sep=" ")) message(paste("Number of",name, "is", round(sum(df, na.rm = T)/1000, 2), "* 10^3 veh", sep=" ")) cat("\n") } if(!missing(namerows)) { if(length(namerows) != nrow(df)) stop("length of namerows must be the length of number of rows of veh") row.names(df) <- namerows } # replace NA and NaN df[is.na(df)] <- 0 if(!missing(net)){ netsf <- sf::st_as_sf(net) if(!missing(time)){ dfsf <- sf::st_sf(Vehicles(df, time = time), geometry = sf::st_geometry(netsf)) } else { dfsf <- sf::st_sf(Vehicles(df), geometry = sf::st_geometry(netsf)) } return(dfsf) } else { if(!missing(time)){ return(Vehicles(df, time = time)) } else { return(Vehicles(df)) } } } }
/scratch/gouwar.j/cran-all/cranData/vein/R/age_moto.R
#' Average Weight for hourly traffic data. #' #' @description \code{\link{aw}} average weight form traffic. #' #' @param pc numeric vector for passenger cars #' @param lcv numeric vector for light commercial vehicles #' @param hgv numeric vector for heavy good vehicles or trucks #' @param bus numeric vector for bus #' @param mc numeric vector for motorcycles #' @param p_pc data-frame profile for passenger cars, 24 hours only. #' @param p_lcv data-frame profile for light commercial vehicles, 24 hours only. #' @param p_hgv data-frame profile for heavy good vehicles or trucks, 24 hours only. #' @param p_bus data-frame profile for bus, 24 hours only. #' @param p_mc data-frame profile for motorcycles, 24 hours only. #' @param w_pc Numeric, factor equivalence #' @param w_lcv Numeric, factor equivalence #' @param w_hgv Numeric, factor equivalence #' @param w_bus Numeric, factor equivalence #' @param w_mc Numeric, factor equivalence #' @param net SpatialLinesDataFrame or Spatial Feature of "LINESTRING" #' @importFrom sf st_sf #' @return data.frame with with average weight #' @export #' @examples \dontrun{ #' data(net) #' data(pc_profile) #' p1 <- pc_profile[, 1] #' aw1 <- aw(pc = net$ldv*0.75, #' lcv = net$ldv*0.1, #' hgv = net$hdv, #' bus = net$hdv*0.1, #' mc = net$ldv*0.15, #' p_pc = p1, #' p_lcv = p1, #' p_hgv = p1, #' p_bus = p1, #' p_mc = p1) #' head(aw1) #' } aw <- function(pc, lcv, hgv, bus, mc, p_pc, p_lcv, p_hgv, p_bus, p_mc, w_pc = 1, w_lcv = 3.5, w_hgv = 20, w_bus = 20, w_mc = 0.5, net) { pc <- remove_units(pc) lcv <- remove_units(lcv) hgv <- remove_units(hgv) bus <- remove_units(bus) mc <- remove_units(mc) df_pc <- vein::temp_fact(q = pc, pro = p_pc) df_lcv <- vein::temp_fact(q = lcv, pro = p_lcv) df_hgv <- vein::temp_fact(q = hgv, pro = p_hgv) df_bus <- vein::temp_fact(q = bus, pro = p_bus) df_mc <- vein::temp_fact(q = mc, pro = p_mc) fleet <- df_pc + df_lcv + df_hgv + df_bus + df_mc df_pc_w <- vein::temp_fact(q = pc*w_pc, pro = p_pc) df_lcv_w <- vein::temp_fact(q = lcv*w_lcv, pro = p_lcv) df_hgv_w <- vein::temp_fact(q = hgv*w_hgv, pro = p_hgv) df_bus_w <- vein::temp_fact(q = bus*w_bus, pro = p_bus) df_mc_w <- vein::temp_fact(q = mc*w_mc, pro = p_mc) W <- (df_pc_w + df_lcv_w + df_hgv_w + df_bus_w + df_mc_w)/fleet W <- remove_units(W) W[is.na(W)] <- 0 if(!missing(net)) { net <- sf::st_as_sf(net) W <- sf::st_sf(W, geometry = sf::st_geometry(net)) } else { return(W) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/aw.R
#' Construction function for Celsius temperature #' #' @description \code{celsius} just add unit celsius to different R objects #' #' @return Objects of class "data.frame" or "units" #' #' @param x Object with class "data.frame", "matrix", "numeric" or "integer" #' @importFrom units as_units #' #' @examples { #' a <- celsius(rnorm(100)*10) #' plot(a) #' b <- celsius(matrix(rnorm(100)*10, ncol = 10)) #' print(head(b)) #' } #' @export celsius <- function(x) { if ( is.matrix(x) ) { e <- as.data.frame(x) for(i in 1:ncol(e)){ e[,i] <- e[,i]*units::as_units("degC") } } else if ( is.data.frame(x) ) { e <- x for(i in 1:ncol(x)){ e[,i] <- e[,i]*units::as_units("degC") } } else if( inherits(x, "numeric") | inherits(x, "integer")) { e <- x*units::as_units("degC") } return(e) }
/scratch/gouwar.j/cran-all/cranData/vein/R/celsius.R
#' Fraction of mileage driven with a cold engine or catalizer below normal temperature #' #' This function depends length of trip and on ambient temperature. #' From the guidelines EMEP/EEA air pollutant emission inventory guidebook #' http://www.eea.europa.eu/themes/air/emep-eea-air-pollutant-emission-inventory-guidebook #' #' @param ltrip Numeric; Length of trip. It must be in 'units' km. #' @param ta Numeric or data.frame; average monthly temperature Celsius. It if is a #' data.frame, it is convenient that each column is each month. #' @keywords cold mileage #' @note This function is set so that values varies between 0 and 1. #' @export #' @examples \dontrun{ #' lkm <- units::set_units(1:10, km) #' ta <- celsius(matrix(0:9, ncol = 12, nrow = 10)) #' a <- cold_mileage(lkm, ta) #' colplot(a) #' } cold_mileage <- function(ltrip, ta){ # Check units if(!inherits(ltrip, "units")){ stop("ltrip neeeds to has class 'units' in 'km'. Please, check package '?units::set_units'") } if(units(ltrip) == units(units::as_units("m"))){ stop("Units of lkm is 'm'. Please, check package '?units::set_units'") } if(units(ltrip) == units(units::as_units("km"))){ ltrip <- as.numeric(ltrip) } if(is.data.frame(ta) | is.matrix(ta)){ if(!inherits(ta[, 1], "units")) stop("ta must be units in celsius, use units::set_units(ta, degC)") ta <- as.data.frame(ta) for(i in 1:ncol(ta)) { ta[, i] <- as.numeric(ta[, i]) } clkm <- as.data.frame( sapply( 1:ncol(ta), function(i){ ifelse( 0.6474 - 0.02545 * ltrip - (0.00974 - 0.000385 * ltrip) * ta[, i] < 0, 0, ifelse( 0.6474 - 0.02545 * ltrip - (0.00974 - 0.000385 * ltrip) * ta[, i] > 1, 1, 0.6474 - 0.02545 * ltrip - (0.00974 - 0.000385 * ltrip) * ta[, i])) } ) ) } else { if(!inherits(ta, "units")) stop("ta must be units in celsius, use units::set_units(ta, degC)") ta <- as.numeric(ta) clkm <- ifelse( 0.6474 - 0.02545 * ltrip - (0.00974 - 0.000385 * ltrip) * ta < 0, 0, ifelse( 0.6474 - 0.02545 * ltrip - (0.00974 - 0.000385 * ltrip) * ta > 1, 1, 0.6474 - 0.02545 * ltrip - (0.00974 - 0.000385 * ltrip) * ta)) } return(clkm) }
/scratch/gouwar.j/cran-all/cranData/vein/R/cold_mileage.R
#' Function to plot columns of data.frames #' #' \code{\link{colplot}} plots columns of data.frame #' @param df data.frame. #' @param cols Character, columns of data.frame. #' @param xlab a label for the x axis, defaults to a description of x. #' @param ylab a label for the x axis, defaults to a description of x. #' @param xlim x limits #' @param ylim y limits #' @param main Character, a main title for the plot, see also \code{\link{title}}. #' @param theme Character; "black", "dark", "clean", "ink" #' @param col The colors for lines and points. Multiple colors can #' be specified so that each point can be given its own color. If #' there are fewer colors than points they are recycled in the #' standard fashion. Default are cptcity colour palette "kst_18_pastels" #' @param type 1-character string giving the type of plot desired. #' The following values are possible, for details, see plot: "p" for #' points, "l" for lines, "b" for both points and lines, "c" #' for empty points joined by lines, "o" for overplotted points and #' lines, "s" and "S" for stair steps and "h" for histogram-like vertical #' lines. Finally, "n" does not produce any points or lines. #' @param lwd a vector of line widths, see \code{\link{par}}. #' @param pch plotting ‘character’, i.e., symbol to use. This can either be a #' single character or an integer code for one of a set of graphics symbols. #' The full set of S symbols is available with pch = 0:18, see the #' examples below. (NB: R uses circles instead of the octagons used in S.). #' Value pch = "." (equivalently pch = 46) is handled specially. #' It is a rectangle of side 0.01 inch (scaled by cex). In addition, #' if cex = 1 (the default), each side is at least one pixel #' (1/72 inch on the pdf, postscript and xfig devices). #' For other text symbols, cex = 1 corresponds to the default fontsize #' of the device, often specified by an argument pointsize. #' For pch in 0:25 the default size is about 75% of #' the character height (see par("cin")). #' @param familyfont "Character" to specify font, default is"", options "serif", #' "sans", "mono" or more according device #' @param ... plot arguments #' @family helpers #' @return a nice plot #' @note This plot shows values > 0 by default. To plot all values, use all_values = TRUE #' @importFrom graphics legend par plot points #' @seealso \code{\link{par}} #' @export #' @examples \dontrun{ #' a <- ef_cetesb("CO", c("PC_G", "PC_FE", "PC_FG", "PC_E"), agemax = 20) #' colplot(df = a, ylab = "CO [g/km]", theme = "dark", type = "b") #' colplot(df = a, ylab = "CO [g/km]", theme = "dark", pch = NULL, type = "b") #' colplot(df = a, ylab = "CO [g/km]", theme = "clean", type = "b") #' colplot(df = a, ylab = "CO [g/km]", theme = "clean", pch = NULL, type = "b") #' #colplot(df = a, cols = "PC_FG", main = "EF", ylab = "CO [g/km]") #' #colplot(df = a, ylab = "CO [g/km]", theme = "clean") #' } colplot <- function (df, cols = names(df), xlab = "", ylab = "", xlim = c(1, nrow(df)), ylim = range(unlist(df[[cols]]), na.rm = TRUE), main = NULL, theme = "black", col = cptcity::cpt(pal = cptcity::find_cpt("pastel")[4], n = length(names(df))), type = "b", lwd = 2, pch = 1:ncol(df), familyfont = "", ...){ oldpar <- par(no.readonly = TRUE) # code line i on.exit(par(oldpar)) # code line i + 1 df <- as.data.frame(df) if (theme == "clean") { graphics::par(fg = "black", adj = 0.5, ann = TRUE, bg = "white", bty = "o", cex = 1, cex.axis = 0.7, cex.lab = 0.8, cex.main = 1, cex.sub = 0.8, col = "black", col.axis = "black", col.lab = "black", col.main = "black", col.sub = "black", family = familyfont, font = 1, font.axis = 1, font.lab = 1, font.main = 2, font.sub = 3, lab = c(5, 5, 7), las = 1, lend = "round", ljoin = "round", lmitre = 10, lty = "solid", lwd = 1, mgp = c(2, 0.5, 0), # pch = 20, tck = -0.01, xaxs = "r", xaxt = "s", xpd = FALSE, yaxs = "r", yaxt = "s") } else if (theme == "ink") { graphics::par(fg = "blue", adj = 0.5, ann = TRUE, bg = "navajowhite", bty = "o", cex = 0.8, cex.axis = 1, cex.lab = 1, cex.main = 1.5, cex.sub = 1, col = "blue", col.axis = "blue", col.lab = "blue", col.main = "blue", col.sub = "blue", family = familyfont, font = 3, font.axis = 3, font.lab = 4, font.main = 2, font.sub = 3, lab = c(5, 5, 7), las = 1, lend = "round", ljoin = "round", lmitre = 10, lty = "dotted", lwd = 2, mgp = c(2, 0.5, 0), # pch = 4, tck = -0.01, xaxs = "r", xaxt = "s", xpd = FALSE, yaxs = "r", yaxt = "s") } else if (theme == "dark") { graphics::par(fg = "#7E848C", adj = 0.5, ann = TRUE, bg = "#2E3947", bty = "n", cex = 0.8, cex.axis = 1, cex.lab = 1, cex.main = 1.5, cex.sub = 1, col = "#BEBEBE", col.axis = "#7E848C", col.lab = "#BEBEBE", col.main = "#EFF0F2", col.sub = "#737D89", family = familyfont, font = 1, font.axis = 1, font.lab = 2, font.main = 2, font.sub = 3, lab = c(5, 5, 7), las = 1, lend = "round", ljoin = "round", lmitre = 10, lty = 1, lwd = 1, mgp = c(3, 0.7, 0), # pch = 19, tck = -0.01, xaxs = "r", xaxt = "s", xpd = FALSE, yaxs = "r", yaxt = "s") } else if (theme == "black") { graphics::par(fg = "#7E848C", adj = 0.5, ann = TRUE, bg = "black", bty = "n", cex = 0.8, cex.axis = 1, cex.lab = 1, cex.main = 1.5, cex.sub = 1, col = "white", col.axis = "white", col.lab = "white", col.main = "white", col.sub = "white", family = familyfont, font = 1, font.axis = 1, font.lab = 2, font.main = 2, font.sub = 3, lab = c(5, 5, 7), las = 1, lend = "round", ljoin = "round", lmitre = 10, lty = 1, lwd = 1, mgp = c(3, 0.7, 0), # pch = 19, tck = -0.01, xaxt = "s", xpd = FALSE, yaxs = "r", yaxt = "s") } # function add legend add_legend <- function(...) { opar <- graphics::par(fig=c(0, 1, 0, 1), oma=c(0, 0, 0, 0), mar=c(0, 0, 0, 0), new=TRUE) on.exit(graphics::par(opar)) plot(0, 0, type='n', bty='n', xaxt='n', yaxt='n') graphics::legend(...) } # graphics::par(xpd = T, mar = par()$mar + c(0, 0, 0, spl)) par(mar = c(5, 4, 1.4, 0.2)) if (!missing(cols)) df <- df[cols] df <- remove_units(df) df[df == 0] <- NA # ldf <- as.list(df) # c(5, 4, 1.4, 0.2) plot(df[[1]], ylim = c(0, max(df, na.rm = TRUE)), type = type, pch = pch[1], col = col[1], ylab = ylab, xlab = xlab, main = main, lwd = lwd, ...) if(ncol(df) > 1) { for(i in 2:ncol(df)) { graphics::points(df[[i]], type = type, pch = pch[i], col = col[i], lwd = lwd) } } add_legend("topright", legend = names(df), col = col[1:ncol(df)], horiz=TRUE, bty='n', cex=1, text.font=4, pch = pch) # graphics::plot(ldf[[1]], ylim = c(0, max(df, na.rm = TRUE)), # type = type, pch = pch, col = col[1], ylab = ylab, xlab = xlab, # main = main, lwd = lwd) # graphics::legend(x = nrow(df), # y = max(unlist(ldf), # na.rm = T) * 1.04, # col = col[1:ncol(df)], legend = cols, # pch = pch, lwd = lwd) # graphics::par(xlog = FALSE, ylog = FALSE, adj = 0.5, ann = TRUE, # ask = FALSE, bg = "white", bty = "o", cex = 1, # cex.axis = 1, cex.lab = 1, cex.main = 1.2, cex.sub = 1, # col = "black", col.axis = "black", col.lab = "black", # col.main = "black", col.sub = "black", crt = 0, # err = 0, family = "", fg = "black", fig = c(0, # 1, 0, 1), fin = c(6.239583, 5.6875), font = 1, font.axis = 1, # font.lab = 1, font.main = 2, font.sub = 1, lab = c(5, # 5, 7), las = 0, lend = "round", lheight = 1, # ljoin = "round", lmitre = 10, lty = "solid", # lwd = 1, mai = c(1.02, 0.82, 0.82, 0.42), mar = c(5.1, # 4.1, 4.1, 2.1), mex = 1, mfcol = c(1, 1), mfg = rep(1, # 4), mfrow = c(1, 1), mgp = c(3, 1, 0), mkh = 0.001, # new = FALSE, oma = c(0, 0, 0, 0), omd = c(0, 1, 0, 1), # omi = rep(0, 4), pch = 1, pin = c(4.999583, 3.8475), # plt = c(0.131419, 0.9326878, 0.1793407, 0.8558242), ps = 12, # pty = "m", smo = 1, srt = 0, tck = NA, tcl = -0.5, # usr = c(0, 1, 0, 1), xaxp = c(0, 1, 5), xaxs = "r", # xaxt = "s", xpd = FALSE, yaxp = c(0, 1, 5), yaxs = "r", # yaxt = "s", ylbias = 0.2) }
/scratch/gouwar.j/cran-all/cranData/vein/R/colplot.R
#' Description data.frame for MOVES #' #' A data.frame descriptors to use MOVES functions #' #' @format A data frame with 69 rows and 4 columns: #' \describe{ #' \item{CategoryField}{dayID, sourceTypID, roadTypeID, pollutantID and procesID} #' \item{pollutantID}{Associated number} #' \item{Description}{Associatd description} #' \item{V4}{pollutants} #' } #' @source US/EPA MOVES #' @usage data(decoder) #' @docType data "decoder"
/scratch/gouwar.j/cran-all/cranData/vein/R/decoder.R
#' Number of days of the month #' #' \code{\link{ef_ldv_speed}} return the number of day sof the month #' #' #' @param year Numeric #' @param month Numeric #' @return days of the month #' @family helpers #' @export #' @examples \dontrun{ #' dmonth(2022, 1) #' } dmonth <- function(year, month) { date <- ISOdate(year, month, 1, 0, 0, 0) m <- format(date, format="%m") while (format(date, format="%m") == m) { date <- date + 1*3600 } return(as.integer(format(date - 1, format="%d"))) }
/scratch/gouwar.j/cran-all/cranData/vein/R/dmonth.R
#' Emissions factors for Environment Company of Sao Paulo, Brazil (CETESB) #' #' \code{\link{ef_cetesb}} returns a vector or data.frame of Brazilian emission factors. #' @param p Character; #' #' Pollutants: "CO", "HC", "NMHC", "CH4", "NOx", "CO2", #' "RCHO" (aldehydes + formaldehyde), "ETOH", #' "PM", "N2O", "KML", "FC", "NO2", "NO", "NH3", #' "gD/KWH", "gCO2/KWH", "RCHO_0km" (aldehydes + formaldehyde), "PM25RES", "PM10RES", #' "CO_0km", "HC_0km", "NMHC_0km", "NOx_0km", "NO2_0km" ,"NO_0km", #' "RCHO_0km" and "ETOH_0km", "FS" (fuel sales) (g/km). If scale = "tunnel" is #' used, there is also "ALD" for aldehydes and "HCHO" for formaldehydes #' Evaporative emissions at average temperature ranges: #' "D_20_35", "S_20_35", "R_20_35", "D_10_25", "S_10_25", "R_10_25", "D_0_15", #' "S_0_15" and "R_0_15" where D means diurnal (g/day), S hot/warm soak (g/trip) #' and R hot/warm running losses (g/trip). THe deteriorated emission factors are calculated inside this function. #' @param veh Character; Vehicle categories: #' "PC_G", "PC_FG", "PC_FE", "PC_E", #' "LCV_G", "LCV_FG", "LCV_FE", "LCV_E", "LCV_D", #' "TRUCKS_SL", "TRUCKS_L", "TRUCKS_M", "TRUCKS_SH", "TRUCKS_H", #' "BUS_URBAN", "BUS_MICRO", "BUS_COACH", "BUS_ARTIC", #' "MC_150_G", "MC_150_500_G", "MC_500_G", #' "MC_150_FG", "MC_150_500_FG", "MC_500_FG", #' "MC_150_FE", "MC_150_500_FE", "MC_500_FE", #' "CICLOMOTOR", "GNV" #' @param year Numeric; Filter the emission factor to start from a specific base year. #' If project is 'constant' values above 2017 and below 1980 will be repeated #' @param agemax Integer; age of oldest vehicles for that category #' @param scale Character; values "default","tunnel" o "tunnel2018". If "tunnel", emission #' factors are scaled to represent EF measurements in tunnels in Sao Paulo #' @param sppm Numeric, sulfur (sulphur) in ppm in fuel. #' @param full Logical; To return a data.frame instead or a vector adding #' Age, Year, Brazilian emissions standards and its euro equivalents. #' @param efinput data.frame with efinput structure of sysdata cetesb. Allow #' apply deterioration for future emission factors #' @param verbose Logical; To show more information #' @param csv String with the path to download the ef in a .csv file. For instance, #' ef.csv #' @return A vector of Emission Factor or a data.frame #' @importFrom data.table melt rbindlist #' @keywords emission factors #' @note The new convention for vehicles names are translated from CETESB report: #' \tabular{ll}{ #' veh \tab description \cr #' PC_G \tab Passenger Car Gasohol (Gasoline + 27perc of anhydrous ethanol) \cr #' PC_E \tab Passenger Car Ethanol (hydrous ethanol) \cr #' PC_FG \tab Passenger Car Flex Gasohol (Gasoline + 27perc of anhydrous ethanol) \cr #' PC_FE \tab Passenger Car Flex Ethanol (hydrous ethanol) \cr #' LCV_G \tab Light Commercial Vehicle Gasohol (Gasoline + 27perc of anhydrous ethanol) \cr #' LCV_E \tab Light Commercial Vehicle Ethanol (hydrous ethanol) \cr #' LCV_FG \tab Light Commercial Vehicle Flex Gasohol (Gasoline + 27perc of anhydrous ethanol) \cr #' LCV_FE \tab Light Commercial Vehicle Flex Ethanol (hydrous ethanol) \cr #' LCV_D \tab Light Commercial Vehicle Diesel (5perc bio-diesel) \cr #' TRUCKS_SL_D \tab Trucks Semi Light Diesel (5perc bio-diesel) \cr #' TRUCKS_L_D \tab Trucks Light Diesel (5perc bio-diesel) \cr #' TRUCKS_M_D \tab Trucks Medium Diesel (5perc bio-diesel) \cr #' TRUCKS_SH_D \tab Trucks Semi Heavy Diesel (5perc bio-diesel) \cr #' TRUCKS_H_D \tab Trucks Heavy Diesel (5perc bio-diesel) \cr #' BUS_URBAN_D \tab Urban Bus Diesel (5perc bio-diesel) \cr #' BUS_MICRO_D \tab Micro Urban Bus Diesel (5perc bio-diesel) \cr #' BUS_COACH_D \tab Coach (inter-state) Bus Diesel (5perc bio-diesel) \cr #' BUS_ARTIC_D \tab Articulated Urban Bus Diesel (5perc bio-diesel) \cr #' MC_150_G \tab Motorcycle engine less than 150cc Gasohol (Gasoline + 27perc of anhydrous ethanol) \cr #' MC_150_500_G \tab Motorcycle engine 150-500cc Gasohol (Gasoline + 27perc of anhydrous ethanol) \cr #' MC_500_G \tab Motorcycle greater than 500cc Gasohol (Gasoline + 27perc of anhydrous ethanol) \cr #' MC_150_FG \tab Flex Motorcycle engine less than 150cc Gasohol (Gasoline + 27perc of anhydrous ethanol) \cr #' MC_150_500_FG \tab Flex Motorcycle engine 150-500cc Gasohol (Gasoline + 27perc of anhydrous ethanol) \cr #' MC_500_FG \tab Flex Motorcycle greater than 500cc Gasohol (Gasoline + 27perc of anhydrous ethanol) \cr #' MC_150_FE \tab Flex Motorcycle engine less than 150cc Ethanol (hydrous ethanol) \cr #' MC_150_500_FE \tab Flex Motorcycle engine 150-500cc Ethanol (hydrous ethanol) \cr #' MC_500_FE \tab Flex Motorcycle greater than 500cc Ethanol (hydrous ethanol) \cr #' PC_ELEC \tab Passenger Car Electric \cr #' LCV_ELEC \tab Light Commercial Vehicle Electric \cr #' } #' #' The percentage varies of biofuels varies by law. #' #' This emission factors are not exactly the same as the report of CETESB. #' #' 1) In this emission factors, there is also NO and NO2 based on split by #' published in the EMEP/EEA air pollutant emission inventory guidebook. #' #' 2) Also, the emission factors were extended till 50 years of use, repeating #' the oldest value. #' #' 3) CNG emission factors were expanded to other pollutants by comparison #' of US.EPA-AP42 emission factor: Section 1.4 Natural Gas Combustion. #' #' In the previous versions I used the letter 'd' for deteriorated. I removed the #' letter 'd' internally to not break older code. #' #' If by mistake, the user inputs one of veh names from the old convention, #' they are internally changed to the new convention: #' "SLT", "LT", "MT", "SHT","HT", "UB", "SUB", "COACH", "ARTIC", "M_G_150", #' "M_G_150_500", "M_G_500", "M_FG_150", "M_FG_150_500", "M_FG_500", #' "M_FE_150", "M_FE_150_500","M_FE_500", #' PC_ELEC, LCV_ELEC, TRUCKS_ELEC, BUS_ELEC, #' MC_150_ELEC, MC_150_500_ELEC, MC_500_ELEC #' #' If pollutant is "SO2", it needs sppm. It is designed when veh has length 1, if it has length 2 or more, #' it will show a warning #' #' \strong{Emission factor for vehicles older than the reported by CETESB were filled with las highest EF} #' #' \itemize{ #' \item Range EF from PC and LCV otto: 2018 - 1982. EF for 1981 and older as moving average. #' \item Range LCV diesel : 2018 - 2006. EF for 2005 and older as moving average. #' \item Range Trucks and Buse: 2018 - 1998. EF for 1997 and older as moving average. #' \item Range MC Gasoline: 2018 - 2003. EF for 2002 and older as moving average. #' \item Range MC Flex 150-500cc and >500cc: 2018 - 2012. EF for 2011 and older as moving average. #'} #' @references Emissoes Veiculares no Estado de Sao Paulo 2016. Technical Report. #' url: https://cetesb.sp.gov.br/veicular/relatorios-e-publicacoes/. #' #' @note Currently, 2020, there are not any system for recovery of fuel vapors in Brazil. Hence, #' the FS takes into account the vapour that comes from the fuel tank inside the car and #' released into the atmosphere when injecting new fuel. There are discussions about #' increasing implementing stage I and II and/or ORVR these days. The ef FS is calculated #' by transforming g FC/km into (L/KM)*g/L with g/L 1.14 fgor gasoline and 0.37 #' for ethanol (CETESB, 2016). The density considered is 0.75425 for gasoline and #' 0.809 for ethanol (t/m^3) #' #' CETESB emission factors did not cover evaporative emissions from motorcycles, #' which occur. Therefore, in the absence of better data, it was assumed the #' same ratio from passenger cars. #' #' Li, Lan, et al. "Exhaust and evaporative emissions from motorcycles fueled #' with ethanol gasoline blends." Science of the Total Environment 502 (2015): 627-631. #' #' If scale is used with tunnel, the references are: #' \itemize{ #' \item Pérez-Martinez, P. J., Miranda, R. M., Nogueira, T., Guardani, M. L., #' Fornaro, A., Ynoue, R., and Andrade, M. F. (2014). Emission #' factors of air pollutants from vehicles measured inside road tunnels in #' Sao Paulo: case study comparison. International Journal of #' Environmental Science and Technology, 11(8), 2155-2168. #' \item Nogueira, T., de Souza, K. F., Fornaro, A., de Fatima Andrade, M., and #' de Carvalho, L. R. F. (2015). On-road emissions of carbonyls #' from vehicles powered by biofuel blends in traffic tunnels in the #' Metropolitan Area of Sao Paulo, Brazil. Atmospheric Environment, 108, 88-97. #' \item Nogueira, T., et al (2021). In preparation (for tunnel 2018) #'} #' #' Emission factors for resuspension applies \strong{only} with top-down approach #' as a experimental feature. Units are g/(streets*veh)/day. These values were #' derived form a bottom-up resuspension emissions from metropolitan area #' of Sao Paulo 2018, assuming 50000 streets #' #' NH3 from EEA Tier 2 #' #' @export #' @examples { #' a <- ef_cetesb(p = "CO", veh = "PC_G") #' a <- ef_cetesb(p = "NOx", veh = "TRUCKS_M_D") #' a <- ef_cetesb("R_10_25", "PC_G") #' a <- ef_cetesb("CO", c("PC_G", "PC_FE")) #' ef_cetesb(p = "CO", veh = "PC_G", year = 1970, agemax = 40) #' ef_cetesb(p = "CO", veh = "TRUCKS_L_D", year = 2018) #' ef_cetesb(p = "CO", veh = "SLT", year = 2018) # olds names #' a <- ef_cetesb(p = "NMHC", veh = c("PC_G", "PC_FG", "PC_FE", "PC_E"), year = 2018, agemax = 20) #' colplot(a, main = "NMHC EF", ylab = "[g/km]", xlab = "Years of use") #' ef_cetesb(p = "PM25RES", veh = "PC_ELEC", year = 1970, agemax = 40) #' ef_cetesb(p = "PM25RES", veh = "BUS_ELEC", year = 1970, agemax = 40) #' } ef_cetesb <- function(p, veh, year = 2017, agemax = 40, scale = "default", sppm, full = FALSE, efinput, verbose = FALSE, csv){ # load("R/sysdata.rda") if(!missing(efinput)) { # Deterioration must be applied to any base year # therefore, project the emission factors constant into the future was wrong # instead, efinput allow input any ef with the same structure of sysdata$cetesb # and apply deterioration for future emission factors ef <- efinput } else { ef <- sysdata$cetesb } if(year > max(ef$Year)) stop("For projections use argument efinput") if(year < 1949) stop("Choose a newer year at least in 1949") if(length(p) > 1) stop("One pollutant each time please") #extend ef until 120 years in past #### # rep nrow ef lef <- split(ef, ef$Pollutant) nx <- 120 - nrow(lef[[1]]) ef <- data.table::rbindlist( lapply( 1:length(lef), function(i){ rbind( lef[[i]], lef[[i]][rep(nrow(lef[[i]]), nx), ] )})) Age <- Year <- .N <- Pollutant <- NULL ef[, Age := 1:.N, by= Pollutant] ef[, Year := max(ef$Year):(max(ef$Year)-max(ef$Age) + 1), by= Pollutant] # deterioration #### ef <- ef[ef$Year <= year, ] det <- sysdata$cetesbdet # 1 year - det #### endyear <- (year - max(det$Age)+1) det$Year <- year:endyear det$mil <- ifelse( det$veh %in% c("PC_FG", "PC_FE", "LCV_FG", "LCV_FE") & det$Year <2003, 0, ifelse( det$veh %in% c("PC_E", "LCV_E") & (det$Year > 2006 | det$Year < 1979), 0, det$mil)) # 2 year - fe 0km #### ef <- ef[ef$Year %in% year:endyear, ] ef[is.na(ef)] <- 0 vehs <- c("PC_G","PC_E", "PC_FG","PC_FE", "LCV_G","LCV_E", "LCV_FG","LCV_FE") d0 <- data.table::melt(data = ef[ef$Pollutant %in% c("CO", "NMHC", "NOx", "RCHO", "NO", "NO2", "HC"), c("Year", "Pollutant", "PC_G","PC_E", "PC_FG","PC_FE", "LCV_G","LCV_E", "LCV_FG","LCV_FE")], id.vars = c("Year", "Pollutant"), measure.vars = vehs, variable.name = "veh", value.name = "ef") # 3 adding parameter for mileage #### d0$xmil <- 0 det$xmil <- ifelse( det$pol == "CO" & det$veh %in% c("PC_G", "PC_FG", "LCV_G", "LCV_FG") & det$Year > 1994, 0.0000032, ifelse( det$pol == "CO" & det$veh %in% c("PC_G", "PC_FG", "LCV_G", "LCV_FG") & det$Year <= 1994 & det$Year > 1985, 0.0000275, ifelse( det$pol == "CO" & det$veh %in% c("PC_G", "PC_FG", "LCV_G", "LCV_FG") & det$Year <= 1985, 0.0000413, ifelse( det$pol == "CO" & det$veh %in% c("PC_E", "PC_FE", "LCV_E", "LCV_FE") & det$Year > 1994, 0.0000028, ifelse( det$pol == "CO" & det$veh %in% c("PC_E", "PC_FE", "LCV_E", "LCV_FE") & det$Year <= 1994 & det$Year > 1985, 0.000016, ifelse( det$pol == "CO" & det$veh %in% c("PC_E", "PC_FE", "LCV_E", "LCV_FE") & det$Year <= 1985, 0.0000225,0)))))) det$xmil <- ifelse( det$pol %in% c("NMHC", "HC") & det$veh %in% c("PC_G", "PC_FG", "LCV_G", "LCV_FG") & det$Year > 1994, 0.000000288, ifelse( det$pol %in% c("NMHC", "HC") & det$veh %in% c("PC_G", "PC_FG", "LCV_G", "LCV_FG") & det$Year <= 1994 & det$Year > 1985, 0.0000017, ifelse( det$pol %in% c("NMHC", "HC") & det$veh %in% c("PC_G", "PC_FG", "LCV_G", "LCV_FG") & det$Year <= 1985, 0.00000319, ifelse( det$pol %in% c("NMHC", "HC") & det$veh %in% c("PC_E", "PC_FE", "LCV_E", "LCV_FE") & det$Year > 1994, 0.0000003, ifelse( det$pol %in% c("NMHC", "HC") & det$veh %in% c("PC_E", "PC_FE", "LCV_E", "LCV_FE") & det$Year <= 1994 & det$Year > 1985, 0.0000017, ifelse( det$pol %in% c("NMHC", "HC") & det$veh %in% c("PC_E", "PC_FE", "LCV_E", "LCV_FE") & det$Year <= 1985, 0.0000017, det$xmil)))))) det$xmil <- ifelse( det$pol %in% c("RCHO") & det$veh %in% c("PC_G", "PC_FG", "LCV_G", "LCV_FG") & det$Year > 1994, 0.000000008, ifelse( det$pol %in% c("RCHO") & det$veh %in% c("PC_G", "PC_FG", "LCV_G", "LCV_FG") & det$Year <= 1994 & det$Year > 1985, 0.00000005, ifelse( det$pol %in% c("RCHO") & det$veh %in% c("PC_G", "PC_FG", "LCV_G", "LCV_FG") & det$Year <= 1985, 0.00000003, ifelse( det$pol %in% c("RCHO") & det$veh %in% c("PC_E", "PC_FE", "LCV_E", "LCV_FE") & det$Year > 1994, 0.00000003, ifelse( det$pol %in% c("RCHO") & det$veh %in% c("PC_E", "PC_FE", "LCV_E", "LCV_FE") & det$Year <= 1994 & det$Year > 1985, 0.0000001, ifelse( det$pol %in% c("RCHO") & det$veh %in% c("PC_E", "PC_FE", "LCV_E", "LCV_FE") & det$Year <= 1985, 0.0000001, det$xmil)))))) det$xmil <- ifelse( det$pol %in% c("NOx", "NO", "NO2") & det$veh %in% c("PC_G", "PC_FG", "LCV_G", "LCV_FG") & det$Year > 1994, 0.000000375, ifelse( det$pol %in% c("NOx", "NO", "NO2") & det$veh %in% c("PC_G", "PC_FG", "LCV_G", "LCV_FG") & det$Year <= 1994, 1, ifelse( det$pol %in% c("NOx", "NO", "NO2") & det$veh %in% c("PC_E", "PC_FE", "LCV_E", "LCV_FE") & det$Year > 1994, 0.00000025, ifelse( det$pol %in% c("NOx", "NO", "NO2") & det$veh %in% c("PC_E", "PC_FE", "LCV_E", "LCV_FE") & det$Year <= 1994, 1, det$xmil)))) # 5 merging #### d0$ID <- paste(d0$Year, d0$Pollutant, d0$veh) det$ID <- paste(det$Year, det$pol, det$veh) det2 <- merge(det, d0[, c("ID", "ef")], by ="ID", all.x = T) # 6 fe mileages #### det2$ef80 <- ifelse(det2$Year < 1994,0, det2$x + det2$ef) det2$ef160 <- ifelse(det2$Year < 1994, det2$ef + det2$ef*0.2, det2$x + det2$ef80) # 7 constrain fe160 #### xx <- det2[det2$Year == 1984 & det2$pol == "CO" & det2$veh == "PC_G", ]$ef160 det2$ef160 <- ifelse( det2$veh == "PC_G" & det2$pol == "CO" & det2$Year < 1984, xx, det2$ef160) det2[is.na(det2)]<- 0 # 8 ef det #### det2$efd <- ifelse( det2$pol %in% c("CO", "NMHC", "RCHO", "HC") & det2$Year > 1994, det2$xmil*det2$mil + det2$ef, ifelse( det2$pol %in% c("CO", "NMHC", "RCHO", "HC") & det2$Year <= 1994 & det2$mil > 160000, det2$ef160, ifelse( det2$pol %in% c("CO", "NMHC", "RCHO", "HC") & det2$Year <= 1994 & det2$mil <= 160000, det2$xmil*det2$mil + det2$ef, ifelse( det2$pol %in% c("NO", "NO2", "NOx") & det2$Year > 1994, det2$xmil*det2$mil + det2$ef, det2$ef)))) data.table::setorderv(x = det2, cols = "Year", order = -1) # 9 efd #### efd <- ef[!ef$Pollutant %in% c("NO", "NOx", "NO2", "HC", "NMHC", "RCHO", "CO"), ] ve4s <- c("PC_G","PC_E", "PC_FG","PC_FE", "LCV_G","LCV_E", "LCV_FG","LCV_FE") efnoxd <- efnox <- ef[ef$Pollutant == "NOx", ] efnox$Pollutant <- "NOx_0km" for(i in seq_along(ve4s)) efnoxd[[ve4s[i]]] <- det2[det2$veh == ve4s[i] & det2$pol == "NOx", ]$efd efnod <- efno <- ef[ef$Pollutant == "NO", ] efno$Pollutant <- "NO_0km" for(i in seq_along(ve4s)) efnox[[ve4s[i]]] <- det2[det2$veh == ve4s[i] & det2$pol == "NO", ]$efd efno2d <- efno2 <- ef[ef$Pollutant == "NO2", ] efno2$Pollutant <- "NO2_0km" for(i in seq_along(ve4s)) efno2d[[ve4s[i]]] <- det2[det2$veh == ve4s[i] & det2$pol == "NO2", ]$efd efcod <- efco <- ef[ef$Pollutant == "CO", ] efcod$Pollutant <- "CO_0km" for(i in seq_along(ve4s)) efcod[[ve4s[i]]] <- det2[det2$veh == ve4s[i] & det2$pol == "CO", ]$efd efnmhcd <- efnmhc <- ef[ef$Pollutant == "NMHC", ] efnmhcd$Pollutant <- "NMHC_0km" for(i in seq_along(ve4s)) efnmhcd[[ve4s[i]]] <- det2[det2$veh == ve4s[i] & det2$pol == "NMHC", ]$efd efhcd <- efhc <- ef[ef$Pollutant == "HC", ] efhcd$Pollutant <- "HC_0km" for(i in seq_along(ve4s)) efhcd[[ve4s[i]]] <- det2[det2$veh == ve4s[i] & det2$pol == "HC", ]$efd efrchod <- efrcho <- ef[ef$Pollutant == "RCHO", ] efrcho$Pollutant <- "RCHO_0km" for(i in seq_along(ve4s)) efrchod[[ve4s[i]]] <- det2[det2$veh == ve4s[i] & det2$pol == "RCHO", ]$efd ef <- rbind(efd, efcod, efco, efnoxd, efnox, efnod, efno, efno2d, efno2, efhcd, efhc, efnmhcd, efnmhc, efrchod, efrcho) ef <- as.data.frame(ef) # adding PMRES #### # silt de CENMA 2013 # solo debe ser usado con TOP-DOWN! nLDV <- c(grep(pattern = "PC_", x = names(ef), value = TRUE), grep(pattern = "LCV_", x = names(ef), value = TRUE), "G_BEFORE_GNV", "G_AFTER_GNV", "GNV_AFTER_GNV") nHDV <- c(grep(pattern = "TRUCKS_", x = names(ef), value = TRUE)) nBUS <- c(grep(pattern = "BUS_", x = names(ef), value = TRUE)) nMC <- c(grep(pattern = "MC_", x = names(ef), value = TRUE), "CICLOMOTOR") pmveh <- c("BUS", "LDV", "MC", "TRUCKS", "BUS", "LDV", "MC", "TRUCKS") pmpol <- c("PM", "PM", "PM", "PM", "PM10", "PM10", "PM10", "PM10") pmg <- c(0.6148492, 0.2065113, 0.1840867, 2.2728183, 0.5413765, 0.535802, 0.7608918, 9.3943155)/2 pmdf <- data.frame(veh = pmveh, pol = pmpol, gst = pmg) pmef10 <- pmef2 <- ef[ef$Pollutant == "CO", ] pmef2$Pollutant <- "PM25RES" pmef2[, nLDV] <- ifelse(pmef2[, nLDV]>0, 1*pmdf[pmdf$pol == "PM" & pmdf$veh == "LDV", ]$gst, NA) pmef2[, nHDV] <- ifelse(pmef2[, nHDV]>0, 1*pmdf[pmdf$pol == "PM" & pmdf$veh == "HDV", ]$gst, NA) pmef2[, nBUS] <- ifelse(pmef2[, nBUS]>0, 1*pmdf[pmdf$pol == "PM" & pmdf$veh == "BUS", ]$gst, NA) pmef2[, nMC] <- ifelse(pmef2[, nMC]>0, 1*pmdf[pmdf$pol == "PM" & pmdf$veh == "MC", ]$gst, NA) pmef10$Pollutant <- "PM10RES" pmef10[, nLDV] <- ifelse(pmef10[, nLDV]>0, 1*pmdf[pmdf$pol == "PM10" & pmdf$veh == "LDV", ]$gst, NA) pmef10[, nHDV] <- ifelse(pmef10[, nHDV]>0, 1*pmdf[pmdf$pol == "PM10" & pmdf$veh == "HDV", ]$gst, NA) pmef10[, nBUS] <- ifelse(pmef10[, nBUS]>0, 1*pmdf[pmdf$pol == "PM10" & pmdf$veh == "BUS", ]$gst, NA) pmef10[, nMC] <- ifelse(pmef10[, nMC]>0, 1*pmdf[pmdf$pol == "PM10" & pmdf$veh == "MC", ]$gst, NA) pmef2$PC_ELEC <- pmef2$PC_G pmef2$LCV_ELEC <- pmef2$LCV_G pmef2$TRUCKS_ELEC <- pmef2$TRUCKS_SL_D pmef2$BUS_ELEC <- pmef2$BUS_URBAN_D pmef2$MC_150_ELEC <- pmef2$MC_150_500_ELEC <- pmef2$MC_500_ELEC <- pmef2$MC_150_G pmef10$PC_ELEC <- pmef10$PC_G pmef10$LCV_ELEC <- pmef10$LCV_G pmef10$TRUCKS_ELEC <- pmef10$TRUCKS_SL_D pmef10$BUS_ELEC <- pmef10$BUS_URBAN_D pmef10$MC_150_ELEC <- pmef10$MC_150_500_ELEC <- pmef10$MC_500_ELEC <- pmef10$MC_150_G ef <- rbind(ef, pmef2, pmef10) if(p %in% c("PM25RES", "PM10RES")) { if(verbose) message("Experimental: Use only with top-down approach. Units: g/km") } # tunnel #### if(scale %in% c("tunnel","tunnel2014")) { if(verbose) cat("scale = tunnel2014\n") # conferir valor do tunnel # I recalculated the values for tunnel 2014 # fleet 2014 from CETESB # This fleet was used by Daniel as well.- SIE # ef <- sysdata$cetesb LDV <- c(grep(pattern = "PC_", x = names(ef), value = TRUE), grep(pattern = "LCV_", x = names(ef), value = TRUE)[1:4], grep(pattern = "MC_", x = names(ef), value = TRUE)) # Tunnel measurements of heavy trucks covered only big trucks HDV <- c(grep(pattern = "TRUCKS_", x = names(ef), value = TRUE)) # CO HC NMHC (including running losses) COHC <- c("CO", "CO_0km","NMHC", "NMHC_0km","HC", "HC_0km", "R_0_15", "R_10_25", "R_0_25") ef[ef$Pollutant %in% COHC, LDV] <- ef[ef$Pollutant %in% COHC, LDV]*3.770729 ef[ef$Pollutant %in% COHC, HDV] <- ef[ef$Pollutant %in% COHC, HDV]*2.600306 # NONO2NOx NONO<- c("NOx", "NO2", "NO", "NOx_0km", "NO2_0km", "NO_0km") ef[ef$Pollutant %in% NONO, LDV] <- ef[ef$Pollutant %in% NONO, LDV]*1.003158 ef[ef$Pollutant %in% NONO, HDV] <- ef[ef$Pollutant %in% NONO, HDV]*1.25692 # PM ef[ef$Pollutant %in% "PM", LDV] <- ef[ef$Pollutant %in% "PM", LDV]*1.702909 ef[ef$Pollutant %in% "PM", HDV] <- ef[ef$Pollutant %in% "PM", HDV]*1.093566 # ALD # ja tem NMHC incrementado # these values i did not change efALD <- ef[ef$Pollutant %in% "NMHC", ] efALD$Pollutant <- "ALD" efALD[, LDV] <- efALD[, LDV]*0.05013932 efALD[, HDV] <- efALD[, HDV]*0.07298411 ef <- rbind(ef, efALD) # HCHO # ja tem NMHC incrementado efHCHO <- ef[ef$Pollutant %in% "NMHC", ] efHCHO$Pollutant <- "HCHO" efHCHO[, LDV] <- efHCHO[, LDV]*0.03862083 efHCHO[, HDV] <- efHCHO[, HDV]*0.07298411 ef <- rbind(ef, efHCHO) } else if(scale == "tunnel2018") { # Values updated by Mario if(verbose) cat("scale = tunnel2018\n") # ef <- sysdata$cetesb LDV <- c(grep(pattern = "PC_", x = names(ef), value = TRUE), grep(pattern = "LCV_", x = names(ef), value = TRUE)[1:4], grep(pattern = "MC_", x = names(ef), value = TRUE)) # Tunnel measurements of heavy trucks covered only big trucks HDV <- c(grep(pattern = "TRUCKS_", x = names(ef), value = TRUE)) # CO HC NMHC (including running losses) COHC <- c("CO", "CO_0km","NMHC", "NMHC_0km","HC", "HC_0km", "R_0_15", "R_10_25", "R_0_25") # CO2 ef[ef$Pollutant %in% "CO2", LDV] <- ef[ef$Pollutant %in% "CO2", LDV]*0.9623089 ef[ef$Pollutant %in% "CO2", HDV] <- ef[ef$Pollutant %in% "CO2", HDV]*0.8961876 ef[ef$Pollutant %in% COHC, LDV] <- ef[ef$Pollutant %in% COHC, LDV]*2.618311 ef[ef$Pollutant %in% COHC, HDV] <- ef[ef$Pollutant %in% COHC, HDV]*4.777128 # NOx NOx <- c("NOx", "NOx_0km") ef[ef$Pollutant %in% NOx, LDV] <- ef[ef$Pollutant %in% NOx, LDV]*0.7839094 ef[ef$Pollutant %in% NOx, HDV] <- ef[ef$Pollutant %in% NOx, HDV]*1.047166 # NO NO <- c("NO", "NO_0km") ef[ef$Pollutant %in% NO, LDV] <- ef[ef$Pollutant %in% NO, LDV]*0.5361807 ef[ef$Pollutant %in% NO, HDV] <- ef[ef$Pollutant %in% NO, HDV]*1.048273 # NO2 NO2 <- c("NO2", "NO2_0km") ef[ef$Pollutant %in% NO2, LDV] <- ef[ef$Pollutant %in% NO2, LDV]*1.338307 ef[ef$Pollutant %in% NO2, HDV] <- ef[ef$Pollutant %in% NO2, HDV]*1.039307 # # The following adjustments made for tunnel study for 2018 - MEGC # PM (EF_LDV = 0.0326574 g/m3, EF_HDV = 0.2749503 mg/m3, agemax = 40) ef[ef$Pollutant %in% "PM", LDV] <- ef[ef$Pollutant %in% "PM", LDV]*4.128006 ef[ef$Pollutant %in% "PM", HDV] <- ef[ef$Pollutant %in% "PM", HDV]*1.626788 # ALD # ja tem NMHC incrementado efALD <- ef[ef$Pollutant %in% "NMHC", ] efALD$Pollutant <- "ALD" efALD[, LDV] <- efALD[, LDV]*0.05013932 efALD[, HDV] <- efALD[, HDV]*0.07298411 ef <- rbind(ef, efALD) # HCHO # ja tem NMHC incrementado efHCHO <- ef[ef$Pollutant %in% "NMHC", ] efHCHO$Pollutant <- "HCHO" efHCHO[, LDV] <- efHCHO[, LDV]*0.03862083 efHCHO[, HDV] <- efHCHO[, HDV]*0.07298411 ef <- rbind(ef, efHCHO) } else { if(verbose) cat("scale = default\n") } ef[is.na(ef)] <- 0 # vehicle category #### oldt <- c("SLT", "LT", "MT", "SHT", "HT", "UB", "SUB", "COACH", "ARTIC", "M_G_150", "M_G_150_500", "M_G_500", "M_FG_150", "M_FG_150_500", "M_FG_500", "M_FE_150", "M_FE_150_500", "M_FE_500") if(any(veh %in% oldt)) { message("I guess you wanted this:") veh <- switch(veh, "SLT" = "TRUCKS_SL_D", "LT" = "TRUCKS_L_D", "MT" = "TRUCKS_M_D", "SHT" = "TRUCKS_SH_D", "HT" = "TRUCKS_H_D", "UB" = "BUS_URBAN_D", "SUB" = "BUS_MICRO_D", "COACH" = "BUS_COACH_D", "ARTIC" = "BUS_ARTIC_D", "M_G_150" = "MC_150_G", "M_G_150_500" = "MC_150_500_G", "M_G_500" = "MC_500_G", "M_FG_150" = "MC_150_FG", "M_FG_150_500" = "MC_150_500_FG", "M_FG_500" = "MC_500_FG", "M_FE_150" = "MC_150_FE", "M_FE_150_500" = "MC_150_500_FE", "M_FE_500" = "MC_500_FE") message(veh) } year1 <- ef$Year[1] p <- gsub(pattern = "d", replacement = "", x = p) #not break old code s0 <- c("PC_E", "PC_FE", "LCV_E", "LCV_FE", "MC_150_FE", "MC_150_500_FE", "MC_500_FE") if(p == "SO2"){ if(missing(sppm)) stop("if p is 'SO2', sppm must be present") if(length(veh) != length(sppm)) { stop("sppm must has the same length as veh") } } # Selecting evapd <- c("D_20_35","D_10_25","D_0_15") evap <- c("S_20_35", "R_20_35", "S_10_25", "R_10_25", "S_0_15", "R_0_15") pols <- as.character(unique(ef$Pollutant)) if(!p %in% c(pols, "SO2")){ stop(cat("Please, choose one of the following pollutants:\n", pols, "\n")) } if(p %in% evapd){ if(verbose) message("Units: [g/day]\n") } if(p %in% evap){ if(verbose) message("Units: [g/trip]\n") } nveh <- names(ef)[12:ncol(ef)] if(any(!veh %in% nveh)){ stop(cat("Please, choose on of the following categories:\n", nveh, "\n")) } pol <- p k <- ifelse(p == "SO2", sppm*2*1e-06, 1) p <- ifelse(p == "SO2", "FC", p) if(full) { if(p %in% c(evapd, evap)){ df1 <- ef[ef$Pollutant == p, 1:11] df2 <- ef[ef$Pollutant == p, veh] if(length(veh) == 1) { df2 <- units::as_units(df2, "g") } else { for(i in 1:ncol(df2)) df2[, i] <- units::as_units(df2[, i], "g") } df <- cbind(df1, df2) names(df)[ncol(df)] <- p } else { if(pol == "SO2" & length(veh) == 1){ if(veh %in% s0) k = 0 } df <- cbind(ef[ef$Pollutant == p, 1:11], EmissionFactors(ef[ef$Pollutant == p, veh]*k) ) names(df)[ncol(df)] <- p } } else { if(p %in% c(evapd, evap)){ df <- ef[ef$Pollutant == p, veh] if(length(veh) == 1) { df <- units::as_units(df, "g") } else { for(i in 1:ncol(df)) df[, i] <- units::as_units(df[, i], "g") } } else { if(pol == "SO2" & length(veh) == 1){ if(veh %in% s0) k = 0 } df <- vein::EmissionFactors(ef[ef$Pollutant == p, veh]*k) } } # agemax if(is.data.frame(df)) { if(!is.null(agemax)) df <- df[1:agemax, ] } else { if(!is.null(agemax)) df <- df[1:agemax] } if(!missing(csv)) { data.table::fwrite(x = df, file = csv) } return(df) }
/scratch/gouwar.j/cran-all/cranData/vein/R/ef_cetesb.R
#' Emissions factors from Chinese emissions guidelines #' #' \code{\link{ef_china}} returns emission factors as vector or data.frames. #' The emission factors comes from the chinese emission guidelines (v3) from the #' Chinese Ministry of Ecology and Environment #' http://www.mee.gov.cn/gkml/hbb/bgth/201407/W020140708387895271474.pdf #' #' @family China #' @param v Character; category vehicle: "PV" for Passenger Vehicles or 'Trucks" #' @param t Character; sub-category of of vehicle: PV Gasoline: "Mini", "Small","Medium", #' "Large", "Taxi", "Motorcycles", "Moped", PV Diesel: "Mediumbus", "Largebus", #' "3-Wheel". Trucks: "Mini", "Light" , "Medium", "Heavy" #' @param standard Character or data.frame; "PRE", "I", "II", "III", "IV", "V". When #' it is a data.frame, it each row is a different region and ta, humidity, #' altitud, speed, sulphur and load_factor lengths have the same as the number of #' rows. #' @param f Character;fuel: "G", "D", "CNG", "ALL" #' @param p Character; pollutant: "CO", "NOx","HC", "PM", "Evaporative_driving" #' or "Evaporative_parking" #' @param k Numeric; multiplication factor #' @param ta Numeric; temperature of ambient in celcius degrees. When standard is a #' data.frame, the length must be equal to the number of rows of standard. #' @param humidity Numeric; relative humidity. When standard is a #' data.frame, the length must be equal to the number of rows of standard. #' @param altitude Numeric; altitude in meters. When standard is a #' data.frame, the length must be equal to the number of rows of standard. #' @param speed Numeric; altitude in km/h When standard is a #' data.frame, the length must be equal to the number of rows of standard. #' @param baseyear_det Integer; any of 2014, 2015, 2016, 2017, 2018 #' @param sulphur Numeric; sulphur in ppm. When standard is a #' data.frame, the length must be equal to the number of rows of standard. #' @param load_factor Numeric; When standard is a #' data.frame, the length must be equal to the number of rows of standard. #' @param details Logical; When TRUE, it shows a description of the vehicle in chinese #' and english. Only when length standard is 1. #' @param correction_only Logical; When TRUE, return only correction factors. #' @return An emission factor #' @keywords ef_china emission factors China #' @note Combination of vehicles: #' \tabular{ccc}{ #' v \tab t \tab f \cr #' PV \tab Mini \tab G HY \cr #' PV \tab Bus \tab D HY D \cr #' PV \tab Mini \tab CNG \cr #' PV \tab Bus \tab CNG \cr #' PV \tab Mini \tab G \cr #' PV \tab Small \tab G \cr #' PV \tab Medium \tab G \cr #' PV \tab Large \tab G \cr #' PV \tab Taxi \tab G \cr #' PV \tab Bus \tab G \cr #' PV \tab Motorcycles \tab G \cr #' PV \tab Moped \tab G \cr #' PV \tab Mini \tab D \cr #' PV \tab Small \tab D \cr #' PV \tab Mediumbus \tab D \cr #' PV \tab Medium \tab D \cr #' PV \tab Largebus \tab D \cr #' PV \tab Bus \tab D \cr #' PV \tab 3-Wheel \tab D \cr #' PV \tab Small \tab ALL \cr #' PV \tab Mediumbus \tab ALL \cr #' PV \tab Largebus \tab ALL \cr #' PV \tab Taxi \tab ALL \cr #' PV \tab Bus \tab ALL \cr #' Trucks \tab Bus \tab G \cr #' Trucks \tab Light \tab G \cr #' Trucks \tab Medium \tab G \cr #' Trucks \tab Heavy \tab G \cr #' Trucks \tab Light \tab D \cr #' Trucks \tab Medium \tab D \cr #' Trucks \tab Heavy \tab D \cr #' Trucks \tab Low Speed \tab D \cr #' Trucks \tab Mini \tab D \cr #' } #' #' standard VI is assumed as V #' #' @seealso \code{\link{ef_ldv_speed}} \code{\link{emis_hot_td}} #' @importFrom units as_units #' @export #' @examples \dontrun{ #' # when standard is 'character' #' # Checking #' df_st <- rev(c(as.character(as.roman(5:1)), "PRE")) #' ef_china(t = "Mini", f = "G", standard = df_st, p = "CO") #' ef_china(t = "Mini", f = "G", standard = df_st, p = "HC") #' ef_china(t = "Mini", f = "G", standard = df_st, p = "NOx") #' ef_china(t = "Mini", f = "G", standard = df_st, p = "PM2.5") #' ef_china(t = "Mini", f = "G", standard = df_st, p = "PM10") #' #' ef_china(t = "Small", f = "G", standard = df_st, p = "CO") #' ef_china(t = "Small", f = "G", standard = df_st, p = "HC") #' ef_china(t = "Small", f = "G", standard = df_st, p = "NOx") #' ef_china(t = "Small", f = "G", standard = df_st, p = "PM2.5") #' ef_china(t = "Small", f = "G", standard = df_st, p = "PM10") #' #' #' ef_china(t = "Mini", #' standard = c("PRE"), #' p = "CO", #' k = 1, #' ta = celsius(15), #' humidity = 0.5, #' altitude = 1000, #' speed = Speed(30), #' baseyear_det = 2014, #' sulphur = 50, #' load_factor = 0.5, #' details = FALSE) #' ef_china(standard = c("PRE", "I"), p = "CO", correction_only = TRUE) #' #' # when standard is 'data.frame' #' df_st <- matrix(c("V", "IV", "III", "III", "II", "I", "PRE"), nrow = 2, ncol = 7, byrow = TRUE) #' df_st <- as.data.frame(df_st) #' a <- ef_china(standard = df_st, #' p = "PM10", #' ta = rep(celsius(15), 2), #' altitude = rep(1000, 2), #' speed = rep(Speed(30), 2), #' sulphur = rep(50, 2)) #' dim(a) #' dim(df_st) #' ef_china(standard = df_st, p = "PM2.5", ta = rep(celsius(20), 2), #' altitude = rep(1501, 2), speed = rep(Speed(29), 2), sulphur = rep(50, 2)) #' a #' #' # when standard, temperature and humidity are data.frames #' # assuming 10 regions #' df_st <- matrix(c("V", "IV", "III", "III", "II", "I", "PRE"), nrow = 10, ncol = 7, byrow = TRUE) #' df_st <- as.data.frame(df_st) #' df_t <- matrix(21:30, nrow = 10, ncol = 12, byrow = TRUE) #' df_t <- as.data.frame(df_t) #' for(i in 1:12) df_t[, i] <- celsius(df_t[, i]) #' #' # assuming 10 regions #' df_h <- matrix(seq(0.4, 0.5, 0.05), nrow = 10, ncol = 12, byrow = TRUE) #' df_h <- as.data.frame(df_h) #' a <- ef_china(standard = df_st, p = "CO", ta = df_t, humidity = df_h, #' altitude = rep(1501, 10), speed = rep(Speed(29), 10), sulphur = rep(50, 10)) #' a #' a <- ef_china(standard = df_st, p = "PM2.5", ta = df_t, humidity = df_h, #' altitude = rep(1501, 10), speed = rep(Speed(29), 10), sulphur = rep(50, 10)) #' a #' a <- ef_china(standard = df_st, p = "PM10", ta = df_t, humidity = df_h, #' altitude = rep(1501, 10), speed = rep(Speed(29), 10), sulphur = rep(50, 10)) #' a #' dim(a) #' } ef_china <- function(v = "PV", t = "Small", f = "G", standard, p, k = 1, ta = celsius(15), humidity = 0.5, altitude = 1000, speed = Speed(30), baseyear_det = 2016, sulphur = 50, load_factor = 0.5, details = FALSE, correction_only = FALSE){ ef_china <- sysdata$ef_china det_china <- sysdata$det_china sulphur_china <- sysdata$sulphur_china speed_china <- sysdata$speed_china ev <- ef_china[ef_china$POLLUTANT %in% c("Evaporative_driving", "Evaporative_parking"), ] ef_china <- ef_china[!ef_china$POLLUTANT %in% c("Evaporative_driving", "Evaporative_parking"), ] fl <- data.frame(stringsAsFactors=FALSE, POLLUTANT = c("CO", "HC", "NOx", "PM2.5", "PM10"), L0 = c(0.87, 1, 0.83, 0.9, 0.9), L50 = c(1, 1, 1, 1, 1), L60 = c(1.07, 1, 1.09, 1.05, 1.05), L75 = c(1.16, 1, 1.21, 1.13, 1.13), L100 = c(1.33, 1, 1.43, 1.26, 1.26) ) #Check standard if(is.matrix(standard) | is.data.frame(standard)){ eu <- as.data.frame(standard) for(i in 1:ncol(standard)) standard[, i] <- as.character(standard[, i]) } else { standard = as.character(standard) } # Check speed if(!inherits(speed, "units")){ stop("speed neeeds to has class 'units' in 'km/h'. Please, check package '?units::set_units'") } if(units(speed) != units(units::as_units("km/h"))){ stop("Units of speed must be 'km/h' ") } if(units(speed) == units(units::as_units("km/h"))){ speed <- as.numeric(speed) } #Check k if(length(k) > 1) stop("Length of k must be 1") #Check arguments if(!v %in% unique(ef_china$VEH)) { cat("'v' must be one of:", unique(ef_china$VEH), "\n") stop("") } if(!t %in% unique(ef_china$TYPE)) { cat("'t' must be one of:", unique(ef_china$TYPE), "\n") stop("") } if(!f %in% unique(ef_china$FUEL)) { cat("'f' must be one of:", unique(ef_china$FUEL), "\n") stop("") } if(!p %in% unique(ef_china$POLLUTANT)) { cat("'p' must be one of:", unique(ef_china$POLLUTANT), "\n") stop("") } # fun starts #### if(!is.data.frame(standard) & !is.data.frame(ta)){ dff <- lapply(1:length(standard), function(i){ df <- ef_china[ef_china$VEH == v & ef_china$TYPE == t & ef_china$FUEL == f & ef_china$STANDARD == standard[i] & ef_china$POLLUTANT == p, ] # details if(details){ cat("English: ", df$Description) cat("\n\n") cat("Chinese: ", df$CHN) cat("\n") } # Check to return only correction if(correction_only) df$EF <- 1 if(!inherits(ta, "units")) stop("ta must be units in celsius, use celsius(ta)") ta <- as.numeric(ta) # Check correction gasoline - ta if(f == "G"){ if(t != "Motorcycles"){ if(p == "CO"){ df$EF <- ifelse(ta < 10, df$EF*1.36, ifelse(ta > 25, df$EF*1.23, df$EF)) } else if(p == "HC"){ df$EF <- ifelse(ta < 10, df$EF*1.47, ifelse(ta > 25, df$EF*1.08, df$EF)) } else if(p == "NOx"){ df$EF <- ifelse(ta < 10, df$EF*1.15, ifelse(ta > 25, df$EF*1.31, df$EF)) }} } # Check correction diesel - ta if(f == "D"){ if(p == "CO"){ if(t %in% c("Small", "Light")){ df$EF <- ifelse(ta > 25, df$EF*1.33, df$EF) } else if(!t %in% c("Small", "Light")){ df$EF <- ifelse(ta > 25, df$EF*1.3, df$EF) } } else if(p == "HC"){ if(t == c("Small")){ df$EF <- ifelse(ta > 25, df$EF*1.07, df$EF) } else if(!t == c("Light")){ df$EF <- ifelse(ta > 25, df$EF*1.06, df$EF) } } else if(p == "NOx"){ if(t == c("Small")){ df$EF <- ifelse(ta > 25, df$EF*1.17, ifelse(ta < 10, df$EF*1.06, df$EF)) } else if(t == c("Light")){ df$EF <- ifelse(ta > 25, df$EF*1.17, ifelse(ta < 10, df$EF*1.05, df$EF)) } else { df$EF <- ifelse(ta > 25, df$EF*1.15, ifelse(ta < 10, df$EF*1.06, df$EF)) } } else if(p %in% c("PM2.5", "PM10")){ if(t %in% c("Small", "Bus")){ df$EF <- ifelse(ta > 25, df$EF*0.68, ifelse(ta < 10, df$EF*1.87, df$EF)) } else if(t == c("Light")){ df$EF <- ifelse(ta > 25, df$EF*0.9, ifelse(ta < 10, df$EF*1.27, df$EF)) } else { df$EF <- ifelse(ta > 25, df$EF*0.74, ifelse(ta < 10, df$EF*1.7, df$EF)) } } } # Check correction NOx - humidity if(p == "NOx" & f == "G"){ df$EF <- ifelse(humidity <0.5, df$EF*1.06, ifelse( humidity > 0.5, df$EF*0.92, df$EF)) } else if(p == "NOx" & f == "D"){ df$EF <- ifelse(humidity < 0.5, df$EF*1.04, ifelse( humidity > 0.5, df$EF*0.94, df$EF)) } # Check correction ta and humidity - gasoline if(ta > 24){ if(f == "G"){ if(p == "CO"){ df$EF <- ifelse( humidity > 0.5, df$EF*1.04, ifelse(humidity < 0.5, df$EF*0.97, df$EF)) } else if (p == "HC"){ df$EF <- ifelse( humidity > 0.5, df$EF*1.01, ifelse(humidity < 0.5, df$EF*0.99, df$EF)) } else if(p == "NOx"){ df$EF <- ifelse(humidity > 0.5, df$EF*0.87, ifelse(humidity < 0.5, df$EF*1.13, df$EF)) } } else if(f == "D"){ if(p == "NOx"){ df$EF <- ifelse(humidity > 0.5, df$EF*0.88, ifelse(humidity < 0.5, df$EF*1.12, df$EF)) } } } # Check altitude if(altitude > 1500){ if(f == "G"){ if(t %in% c("Mini", "Small", "Light", "Taxi", "Motorcycles", "Moped")){ df$EF <- ifelse(p == "CO", df$EF*1.58, ifelse(p == "HC", df$EF*2.46, ifelse(p == "NOx", df$EF*3.15, df$EF))) } else if(!t %in% c("Mini", "Small", "Light", "Taxi", "Motorcycles", "Moped")){ df$EF <- ifelse(p == "CO", df$EF*3.95, ifelse(p == "HC", df$EF*2.26, ifelse(p == "NOx", df$EF*0.88, df$EF))) } } else if(f == "D"){ if(t %in% c("Small", "Light")){ df$EF <- ifelse(p == "CO", df$EF*1.2, ifelse(p == "HC", df$EF*1.32, ifelse(p == "NOx", df$EF*1.35, df$EF*1.35))) } else if(!t %in% c("Small", "Light")){ df$EF <- ifelse(p == "CO", df$EF*2.46, ifelse(p == "HC", df$EF*2.05, ifelse(p == "NOx", df$EF*1.02, df$EF))) }} } # Check speed efspeed <- speed_china[speed_china$FUEL == f & speed_china$STANDARD == standard[i] & speed_china$POLLUTANT == p, ] df$EF <- ifelse( speed < 20, df$EF*efspeed$S20, ifelse( speed >= 20 & speed < 30, df$EF*efspeed$S20_30, ifelse( speed == 30 , df$EF, ifelse( speed > 30 & speed < 40, df$EF*efspeed$S30_40, ifelse( speed >= 40 & speed < 80, df$EF*efspeed$S40_80, ifelse(speed > 80, df$EF*efspeed$S80, 0)))))) # Check deterioration if(f == "G" & p %in% c("CO", "HC", "NOx")){ ts <- ifelse(t %in% c("Mini", "Small"),"group1", ifelse(t == "Taxi", "Taxi","group2")) detfac <- det_china[det_china$TYPE == ts & det_china$FUEL == f & det_china$STANDARD == standard[i] & det_china$POLLUTANT == p & det_china$YEAR == baseyear_det, ] } # Check sulphur sulphur_china <- sulphur_china[sulphur_china$FUEL == f & sulphur_china$STANDARD == standard[i] & sulphur_china$POLLUTANT == p, ] df$EF <- ifelse( sulphur <= 10, df$EF*sulphur_china$S10, ifelse( sulphur > 10 & sulphur <= 50, df$EF*sulphur_china$S50, ifelse( sulphur > 50 & sulphur <= 150, df$EF*sulphur_china$S150, ifelse(sulphur > 150 & sulphur <= 350, df$EF*sulphur_china$S350, ifelse( sulphur > 350 & sulphur <= 500, df$EF*sulphur_china$S500, df$EF*sulphur_china$S800))))) # Check load dfl <- fl[fl$POLLUTANT == p, ] df$EF <- ifelse( load_factor == 0, df$EF*dfl$L0, ifelse( load_factor > 0 & load_factor < 0.5, df$EF*dfl$L50, ifelse(load_factor == 0.5, df$EF, ifelse( load_factor > 0.5 & sulphur <= 0.6, df$EF*dfl$L60, ifelse( load_factor > 0.6 & sulphur <= 0.75, df$EF*dfl$L75, df$EF*dfl$L100))))) }) if(correction_only){ return(unlist(dff)*k) } else { return(EmissionFactors(unlist(dff)*k)) } # standard is data.frames #### } else if(is.matrix(standard) | is.data.frame(standard) & !is.data.frame(ta)) { standard <- as.data.frame(standard) dff <- do.call("rbind", lapply(1:nrow(standard), function(j){ do.call("cbind", lapply(1:ncol(standard), function(i){ df <- ef_china[ef_china$VEH == v & ef_china$TYPE == t & ef_china$FUEL == f & ef_china$STANDARD == standard[j,i][[1]] & ef_china$POLLUTANT == p, ] # Check to return only correction if(correction_only) df$EF <- 1 if(!inherits(ta, "units")) stop("ta must be units in celsius, use celsius(ta)") ta <- as.numeric(ta) if(length(ta) != nrow(standard)) stop("length of 'ta' must be the same as the number of rows of 'standard'") # Check correction gasoline - ta if(f == "G"){ if(t != "Motorcycles"){ if(p == "CO"){ df$EF <- ifelse(ta[j] < 10, df$EF*1.36, ifelse(ta[j] > 25, df$EF*1.23, df$EF)) } else if(p == "HC"){ df$EF <- ifelse(ta[j] < 10, df$EF*1.47, ifelse(ta[j] > 25, df$EF*1.08, df$EF)) } else if(p == "NOx"){ df$EF <- ifelse(ta[j] < 10, df$EF*1.15, ifelse(ta[j] > 25, df$EF*1.31, df$EF)) } }} # Check correction diesel - ta if(f == "D"){ if(p == "CO"){ if(t %in% c("Small", "Light")){ df$EF <- ifelse(ta[j] > 25, df$EF*1.33, df$EF) } else if(!t %in% c("Small", "Light")){ df$EF <- ifelse(ta[j] > 25, df$EF*1.3, df$EF) } } else if(p == "HC"){ if(t == c("Small")){ df$EF <- ifelse(ta[j] > 25, df$EF*1.07, df$EF) } else if(!t == c("Light")){ df$EF <- ifelse(ta[j] > 25, df$EF*1.06, df$EF) } } else if(p == "NOx"){ if(t == c("Small")){ df$EF <- ifelse(ta[j] > 25, df$EF*1.17, ifelse(ta[j] < 10, df$EF*1.06, df$EF)) } else if(t == c("Light")){ df$EF <- ifelse(ta[j] > 25, df$EF*1.17, ifelse(ta[j] < 10, df$EF*1.05, df$EF)) } else { df$EF <- ifelse(ta[j] > 25, df$EF*1.15, ifelse(ta[j] < 10, df$EF*1.06, df$EF)) } } else if(p %in% c("PM2.5", "PM10")){ if(t %in% c("Small", "Bus")){ df$EF <- ifelse(ta[j] > 25, df$EF*0.68, ifelse(ta[j] < 10, df$EF*1.87, df$EF)) } else if(t == c("Light")){ df$EF <- ifelse(ta[j] > 25, df$EF*0.9, ifelse(ta[j] < 10, df$EF*1.27, df$EF)) } else { df$EF <- ifelse(ta[j] > 25, df$EF*0.74, ifelse(ta[j] < 10, df$EF*1.7, df$EF)) } } } # Check correction NOx - humidity if(p == "NOx" & f == "G"){ df$EF <- ifelse(humidity[j] > 0.5, df$EF*0.92, df$EF*1.06) } else if(p == "NOx" & f == "D"){ df$EF <- ifelse(humidity[j] > 0.5, df$EF*0.94, df$EF*1.04) } else { df$EF <- df$EF } # Check correction ta[j] and humidity - gasoline if(ta[j] > 24){ if(f == "G"){ if(p == "CO"){ df$EF <- ifelse(humidity[j] > 0.5, df$EF*1.04, df$EF*0.97) } else if (p == "HC"){ df$EF <- ifelse(humidity[j] > 0.5, df$EF*1.01, df$EF*0.99) } else if(p == "NOx"){ df$EF <- ifelse(humidity[j] > 0.5, df$EF*0.87, df$EF*1.13) } } else if(f == "D"){ if(p == "NOx"){ df$EF <- ifelse(humidity[j] > 0.5, df$EF*0.88, df$EF*1.12) } } } # Check altitude if(length(altitude) != nrow(standard)) stop("length of 'altitude' must be the same as the number of rows of 'standard'") if(altitude[j] > 1500){ if(f == "G"){ if(t %in% c("Mini", "Small", "Light", "Taxi", "Motorcycles", "Moped")){ df$EF <- ifelse(p == "CO", df$EF*1.58, ifelse(p == "HC", df$EF*2.46, ifelse(p == "NOx", df$EF*3.15, df$EF))) } else if(!t %in% c("Mini", "Small", "Light", "Taxi", "Motorcycles", "Moped")){ df$EF <- ifelse(p == "CO", df$EF*3.95, ifelse(p == "HC", df$EF*2.26, ifelse(p == "NOx", df$EF*0.88, df$EF))) } } else if(f == "D"){ if(t %in% c("Small", "Light")){ df$EF <- ifelse(p == "CO", df$EF*1.2, ifelse(p == "HC", df$EF*1.32, ifelse(p == "NOx", df$EF*3.15, df$EF))) } else if(!t %in% c("Small", "Light")){ df$EF <- ifelse(p == "CO", df$EF*2.46, ifelse(p == "HC", df$EF*2.05, ifelse(p == "NOx", df$EF*1.02, df$EF))) }} } else { df$EF <- df$EF } # Check speed if(length(speed) != nrow(standard)) stop("length of 'speed' must be the same as the number of rows of 'standard'") efspeed <- speed_china[speed_china$FUEL == f & speed_china$STANDARD == standard[j,i][[1]] & speed_china$POLLUTANT == p, ] df$EF <- ifelse( speed[j] < 20, df$EF*efspeed$S20, ifelse( speed[j] >= 20 & speed[j] < 30, df$EF*efspeed$S20_30, ifelse( speed[j] == 30 , df$EF, ifelse( speed[j] > 30 & speed[j] < 40, df$EF*efspeed$S30_40, ifelse( speed[j] >= 40 & speed[j] < 80, df$EF*efspeed$S40_80, df$EF*efspeed$S80))))) # Check deterioration if(f == "G" & p %in% c("CO", "HC", "NOx")){ ts <- ifelse(t %in% c("Mini", "Small"),"group1", ifelse(t == "Taxi", "Taxi","group2")) detfac <- det_china[det_china$TYPE == ts & det_china$FUEL == f & det_china$STANDARD == standard[j,i][[1]] & det_china$POLLUTANT == p & det_china$YEAR == baseyear_det, ] df$EF <- df$EF*detfac$DET } # Check sulphur if(length(sulphur) != nrow(standard)) stop("length of 'sulphur' must be the same as the number of rows of 'standard'") sulphur_china <- sulphur_china[sulphur_china$FUEL == f & sulphur_china$STANDARD == standard[j,i][[1]] & sulphur_china$POLLUTANT == p, ] df$EF <- ifelse( sulphur[j] <= 10, df$EF*sulphur_china$S10, ifelse( sulphur[j] > 10 & sulphur[j] <= 50, df$EF*sulphur_china$S50, ifelse( sulphur[j] > 50 & sulphur[j] <= 150, df$EF*sulphur_china$S150, ifelse(sulphur[j] > 150 & sulphur[j] <= 350, df$EF*sulphur_china$S350, ifelse( sulphur[j] > 350 & sulphur[j] <= 500, df$EF*sulphur_china$S500, df$EF*sulphur_china$S800))))) # Check load dfl <- fl[fl$POLLUTANT == p, ] df$EF <- ifelse( load_factor == 0, df$EF*dfl$L0, ifelse( load_factor > 0 & load_factor < 0.5, df$EF*dfl$L50, ifelse(load_factor == 0.5, df$EF, ifelse( load_factor > 0.5 & sulphur <= 0.6, df$EF*dfl$L60, ifelse( load_factor > 0.6 & sulphur <= 0.75, df$EF*dfl$L75, df$EF*dfl$L100))))) df$EF })) })) if(correction_only){ return(dff) } else { dff <- EmissionFactors(dff*k) dff$speed <- Speed(speed) dff$ta <- ta dff$humidity <- humidity dff$alt <- altitude dff$sulphur <- sulphur return(dff) } # standard and ta are data.frames #### } else if (is.matrix(standard) | is.data.frame(standard) & is.data.frame(ta)){ standard <- as.data.frame(standard) if(ncol(ta) != 12) warning("This function was designed so that number of columns of ta is 12, one year") if(nrow(ta) != nrow(standard)) { stop("number of rows of 'ta' must be the same as the number of rows of 'standard'") } dff <- do.call("rbind", lapply(1:ncol(ta), function(k){ do.call("rbind", lapply(1:nrow(standard), function(j){ do.call("cbind", lapply(1:ncol(standard), function(i){ df <- ef_china[ef_china$VEH == v & ef_china$TYPE == t & ef_china$FUEL == f & ef_china$STANDARD == standard[j,i][[1]] & ef_china$POLLUTANT == p, ] # Check to return only correction if(correction_only) df$EF <- 1 # Check correction gasoline - ta ta <- ta[j, k] if(!inherits(ta, "units")) stop("ta must be units in celsius, use celsius(ta)") ta <- as.numeric(ta) humidity <- humidity[j, k] if(f == "G"){ if(t != "Motorcycles"){ if(p == "CO"){ df$EF <- ifelse(ta < 10, df$EF*1.36, ifelse(ta > 25, df$EF*1.23, df$EF)) } else if(p == "HC"){ df$EF <- ifelse(ta < 10, df$EF*1.47, ifelse(ta > 25, df$EF*1.08, df$EF)) } else if(p == "NOx"){ df$EF <- ifelse(ta < 10, df$EF*1.15, ifelse(ta > 25, df$EF*1.31, df$EF)) } else { df$EF <- df$EF } }} # Check correction diesel - ta if(f == "D"){ if(p == "CO"){ if(t %in% c("Small", "Light")){ df$EF <- ifelse(ta > 25, df$EF*1.33, df$EF) } else if(!t %in% c("Small", "Light")){ df$EF <- ifelse(ta > 25, df$EF*1.3, df$EF) } } else if(p == "HC"){ if(t == c("Small")){ df$EF <- ifelse(ta > 25, df$EF*1.07, df$EF) } else if(!t == c("Light")){ df$EF <- ifelse(ta > 25, df$EF*1.06, df$EF) } } else if(p == "NOx"){ if(t == c("Small")){ df$EF <- ifelse(ta > 25, df$EF*1.17, ifelse(ta < 10, df$EF*1.06, df$EF)) } else if(t == c("Light")){ df$EF <- ifelse(ta > 25, df$EF*1.17, ifelse(ta < 10, df$EF*1.05, df$EF)) } else { df$EF <- ifelse(ta > 25, df$EF*1.15, ifelse(ta < 10, df$EF*1.06, df$EF)) } } else if(p %in% c("PM2.5", "PM10")){ if(t %in% c("Small", "Bus")){ df$EF <- ifelse(ta > 25, df$EF*0.68, ifelse(ta < 10, df$EF*1.87, df$EF)) } else if(t == c("Light")){ df$EF <- ifelse(ta > 25, df$EF*0.9, ifelse(ta < 10, df$EF*1.27, df$EF)) } else { df$EF <- ifelse(ta > 25, df$EF*0.74, ifelse(ta < 10, df$EF*1.7, df$EF)) } } } # Check correction NOx - humidity if(p == "NOx" & f == "G"){ df$EF <- ifelse(humidity > 0.5, df$EF*0.92, df$EF*1.06) } else if(p == "NOx" & f == "D"){ df$EF <- ifelse(humidity > 0.5, df$EF*0.94, df$EF*1.04) } else { df$EF <- df$EF } # Check correction ta and humidity - gasoline if(ta > 24){ if(f == "G"){ if(p == "CO"){ df$EF <- ifelse(humidity > 0.5, df$EF*1.04, df$EF*0.97) } else if (p == "HC"){ df$EF <- ifelse(humidity > 0.5, df$EF*1.01, df$EF*0.99) } else if(p == "NOx"){ df$EF <- ifelse(humidity > 0.5, df$EF*0.87, df$EF*1.13) } } else if(f == "D"){ if(p == "NOx"){ df$EF <- ifelse(humidity > 0.5, df$EF*0.88, df$EF*1.12) } } } # Check altitude if(length(altitude) != nrow(standard)) stop("length of 'altitude' must be the same as the number of rows of 'standard'") if(altitude[j] > 1500){ if(f == "G"){ if(t %in% c("Mini", "Small", "Light", "Taxi", "Motorcycles", "Moped")){ df$EF <- ifelse(p == "CO", df$EF*1.58, ifelse(p == "HC", df$EF*2.46, ifelse(p == "NOx", df$EF*3.15, df$EF))) } else if(!t %in% c("Mini", "Small", "Light", "Taxi", "Motorcycles", "Moped")){ df$EF <- ifelse(p == "CO", df$EF*3.95, ifelse(p == "HC", df$EF*2.26, ifelse(p == "NOx", df$EF*0.88, df$EF))) } } else if(f == "D"){ if(t %in% c("Small", "Light")){ df$EF <- ifelse(p == "CO", df$EF*1.2, ifelse(p == "HC", df$EF*1.32, ifelse(p == "NOx", df$EF*3.15, df$EF))) } else if(!t %in% c("Small", "Light")){ df$EF <- ifelse(p == "CO", df$EF*2.46, ifelse(p == "HC", df$EF*2.05, ifelse(p == "NOx", df$EF*1.02, df$EF))) }} } else { df$EF <- df$EF } # Check speed if(length(speed) != nrow(standard)) stop("length of 'speed' must be the same as the number of rows of 'standard'") efspeed <- speed_china[speed_china$FUEL == f & speed_china$STANDARD == standard[j,i][[1]] & speed_china$POLLUTANT == p, ] df$EF <- ifelse( speed[j] < 20, df$EF*efspeed$S20, ifelse( speed[j] >= 20 & speed[j] < 30, df$EF*efspeed$S20_30, ifelse( speed[j] == 30 , df$EF, ifelse( speed[j] > 30 & speed[j] < 40, df$EF*efspeed$S30_40, ifelse( speed[j] >= 40 & speed[j] < 80, df$EF*efspeed$S40_80, df$EF*efspeed$S80))))) # Check deterioration if(f == "G" & p %in% c("CO", "HC", "NOx")){ ts <- ifelse(t %in% c("Mini", "Small"),"group1", ifelse(t == "Taxi", "Taxi","group2")) detfac <- det_china[det_china$TYPE == ts & det_china$FUEL == f & det_china$STANDARD == standard[j,i][[1]] & det_china$POLLUTANT == p & det_china$YEAR == baseyear_det, ] df$EF <- df$EF*detfac$DET } # Check sulphur if(length(sulphur) != nrow(standard)) stop("length of 'sulphur' must be the same as the number of rows of 'standard'") sulphur_china <- sulphur_china[sulphur_china$FUEL == f & sulphur_china$STANDARD == standard[j,i][[1]] & sulphur_china$POLLUTANT == p, ] df$EF <- ifelse( sulphur[j] <= 10, df$EF*sulphur_china$S10, ifelse( sulphur[j] > 10 & sulphur[j] <= 50, df$EF*sulphur_china$S50, ifelse( sulphur[j] > 50 & sulphur[j] <= 150, df$EF*sulphur_china$S150, ifelse(sulphur[j] > 150 & sulphur[j] <= 350, df$EF*sulphur_china$S350, ifelse( sulphur[j] > 350 & sulphur[j] <= 500, df$EF*sulphur_china$S500, df$EF*sulphur_china$S800))))) # Check load dfl <- fl[fl$POLLUTANT == p, ] df$EF <- ifelse( load_factor == 0, df$EF*dfl$L0, ifelse( load_factor > 0 & load_factor < 0.5, df$EF*dfl$L50, ifelse(load_factor == 0.5, df$EF, ifelse( load_factor > 0.5 & sulphur <= 0.6, df$EF*dfl$L60, ifelse( load_factor > 0.6 & sulphur <= 0.75, df$EF*dfl$L75, df$EF*dfl$L100))))) df$EF })) })) })) if(correction_only){ return(dff) } else { dff <- EmissionFactors(dff*k) dff$speed <- Speed(speed) dff$ta <- celsius(unlist(ta)) dff$humidity <- unlist(humidity) dff$alt <- altitude dff$sulphur <- sulphur return(dff) } } } #' @title Chinese emission factors by emissions standard #' @family China #' @name ef_china_long #' @description Chinese emission factors in long format #' @param v Character; category vehicle: "PV" for Passenger Vehicles or 'Trucks" #' @param t Character; sub-category of of vehicle: PV Gasoline: "Mini", "Small","Medium", #' "Large", "Taxi", "Motorcycles", "Moped", PV Diesel: "Mediumbus", "Largebus", #' "3-Wheel". Trucks: "Mini", "Light" , "Medium", "Heavy" #' @param standard Character vector; "PRE", "I", "II", "III", "IV", "V". #' @param f Character;fuel: "G", "D", "CNG", "ALL" #' @param p Character; pollutant: "CO", "NOx","HC", "PM", "Evaporative_driving" #' or "Evaporative_parking" #' @return long data.frame #' @importFrom data.table setDT #' @export #' @examples { #' \dontrun{ #' # Do not run #' } #' } ef_china_long <- function(v = "PV", t = "Small", f = "G", standard, p){ chi <- sysdata$ef_china data.table::setDT(chi) VEH <- TYPE <- FUEL <- POLLUTANT <- YEAR <- STANDARD <- NULL chi[VEH == v & TYPE == t & FUEL == f & POLLUTANT == p, c("STANDARD", "EF")] -> base efb <- EmissionFactors(unlist(lapply(seq_along(standard), function(i) { base[STANDARD == standard[i]]$EF }))) return(efb) } #' @title Correction of Chinese emission factors by speed #' @family China #' @name ef_china_long #' @description Correction of Chinese emission #' @param v Character; category vehicle: "PV" for Passenger Vehicles or 'Trucks" #' @param t Character; sub-category of of vehicle: PV Gasoline: "Mini", "Small","Medium", #' "Large", "Taxi", "Motorcycles", "Moped", PV Diesel: "Mediumbus", "Largebus", #' "3-Wheel". Trucks: "Mini", "Light" , "Medium", "Heavy" #' @param standard Character vector; "PRE", "I", "II", "III", "IV", "V". #' @param f Character;fuel: "G", "D", "CNG", "ALL" #' @param p Character; pollutant: "CO", "NOx","HC", "PM", "Evaporative_driving" #' or "Evaporative_parking" #' @return long data.frame #' @importFrom data.table setDT #' @export #' @examples { #' ef_china_long(standard = "I", p = "CO") #' } ef_china_long <- function(v = "PV", t = "Small", f = "G", standard, p){ chi <- sysdata$ef_china data.table::setDT(chi) VEH <- TYPE <- FUEL <- POLLUTANT <- YEAR <- STANDARD <- NULL chi[VEH == v & TYPE == t & FUEL == f & POLLUTANT == p, c("STANDARD", "EF")] -> base efb <- EmissionFactors(unlist(lapply(seq_along(standard), function(i) { base[STANDARD == standard[i]]$EF }))) return(efb) } #' @title Correction of Chinese emission factors by sulfur #' @family China #' @name ef_china_s #' @description Correction of Chinese emission #' @param s Numeric sulfur content in ppm #' @param f Character;fuel: "G", "D", "CNG", "ALL" #' @param standard Character vector; "PRE", "I", "II", "III", "IV", "V". #' @param p Character; pollutant: "CO", "NOx","HC", "PM", "Evaporative_driving" #' or "Evaporative_parking" #' @return long data.frame #' @importFrom data.table setDT melt.data.table #' @export #' @examples { #' ef_china_s(s = 1000, standard = "I", p = "CO") #' } ef_china_s <- function(s, f = "G", standard, p){ f <- ifelse(f %in% c("CNG", "G HY", "G"), "G", "D") chi <- sysdata$sulphur_china data.table::setDT(chi) VEH <- TYPE <- FUEL <- POLLUTANT <- YEAR <- STANDARD <- NULL chi <- data.table::melt.data.table(data = chi, id.vars = c("FUEL", "STANDARD", "POLLUTANT"), variable.name = "sulfur") xs <- ifelse( s >=800, "S800", ifelse( s < 800 & s >= 500, "S500", ifelse( s < 500 & s >= 350, "S350", ifelse( s < 350 & s >= 150, "S150", ifelse( s < 150 & s >= 50, "S50", "S10"))))) sulfur <- NULL chi[FUEL == f & POLLUTANT == p & sulfur == xs] -> base efb <- unlist(lapply(seq_along(standard), function(i) { base[STANDARD == standard[i]]$value })) if(nrow(base) == 0) efb <- rep(1, length(standard)) return(efb) } #' @title Correction of Chinese emission factors by deterioration #' @family China #' @name ef_china_det #' @description Correction of Chinese emission #' @param v Character; category vehicle: "PV" for Passenger Vehicles or 'Trucks" #' @param t Character; sub-category of of vehicle: PV Gasoline: "Mini", "Small","Medium", #' "Large", "Taxi", "Motorcycles", "Moped", PV Diesel: "Mediumbus", "Largebus", #' "3-Wheel". Trucks: "Mini", "Light" , "Medium", "Heavy" #' @param standard Character vector; "PRE", "I", "II", "III", "IV", "V". #' @param f Character;fuel: "G", "D", "CNG", "ALL" #' @param p Character; pollutant: "CO", "NOx","HC", "PM", "Evaporative_driving" #' or "Evaporative_parking" #' @param yeardet Integer; any of 2014, 2015, 2016, 2017, 2018 #' @return long data.frame #' @importFrom data.table setDT #' @export #' @examples { #' ef_china_det(standard = "I", p = "CO") #' ef_china_det(standard = c("I", "III"), #' p = "CO", #' f = "D") #' } ef_china_det <- function(v = "PV", t = "Small", f = "G", standard, yeardet = 2015, p){ det <- sysdata$det_china_long data.table::setDT(det) VEH <- TYPE <- FUEL <- POLLUTANT <- YEAR <- STANDARD <- NULL det[VEH == v & TYPE == t & FUEL == f & YEAR == yeardet & POLLUTANT == p, c("STANDARD", "DET")] -> basedet if(nrow(basedet) > 0) { efs <- unlist(lapply(seq_along(standard), function(i) { basedet[STANDARD == standard[i]]$DET })) } else { efs <- rep(1, length(standard)) } return(efs) } #' @title Correction of Chinese emission factors by speed #' @family China #' @name ef_china_speed #' @description Correction of Chinese emission #' @param speed numeric speed km/h #' @param f Character;fuel: "G", "D", "CNG" #' @param standard Character vector; "PRE", "I", "II", "III", "IV", "V". #' @param p Character; pollutant: "CO", "NOx","HC", "PM", "Evaporative_driving" #' or "Evaporative_parking" #' @return long data.frame #' @importFrom data.table setDT #' @export #' @examples { #' data(net) #' head(ef_china_speed(speed = net$ps, standard = "I", p = "CO")) #' head(ef_china_speed(speed = net$ps, #' standard = c("II", "I"), #' p = "NOx")) #' } ef_china_speed <- function(speed, f = "G", standard, p){ efsp <- sysdata$speed_china f <- ifelse(f %in% c("CNG", "G HY", "G"), "G", f) data.table::setDT(efsp) sp <- as.numeric(speed) VEH <- TYPE <- FUEL <- POLLUTANT <- YEAR <- STANDARD <- NULL efsp[FUEL == f & POLLUTANT == p] -> basesp efs <- lapply(seq_along(standard), function(i) { sp_std <- basesp[STANDARD == standard[i]] ifelse( sp < 20, sp_std$S20, ifelse( sp >= 20 & sp < 30, sp_std$S20_30, ifelse( sp >= 30 & sp < 40, sp_std$S30_40, ifelse( sp >= 40 & sp < 80, sp_std$S40_80, sp_std$S80 ) ) )) }) efs <- as.data.frame(do.call("cbind", efs)) return(efs) } #' @title Correction of Chinese emission factors by temperature #' @family China #' @name ef_china_te #' @description Correction of Chinese emission #' @param te numeric temperature in celsius #' @param v Character; category vehicle: "PV" for Passenger Vehicles or 'Trucks" #' @param t Character; sub-category of of vehicle: PV Gasoline: "Mini", "Small","Medium", #' "Large", "Taxi", "Motorcycles", "Moped", PV Diesel: "Mediumbus", "Largebus", #' "3-Wheel". Trucks: "Mini", "Light" , "Medium", "Heavy" #' @param f Character;fuel: "G", "D", "CNG" #' @param p Character; pollutant: "CO", "NOx","HC", "PM", "Evaporative_driving" #' or "Evaporative_parking" #' @return long data.frame #' @importFrom data.table setDT #' @export #' @examples { #' data(net) #' head(ef_china_te(te = net$ps, p = "CO")) #' head(ef_china_te(te = net$ps, #' p = "NOx")) #' } ef_china_te <- function(te, v = "PV", t = "Small", f = "G", p){ efte <- sysdata$te_china f <- ifelse(f %in% c("CNG", "G HY", "G"), "G", "D") data.table::setDT(efte) VEH <- TYPE <- FUEL <- POLLUTANT <- NULL efte[VEH == v & TYPE == t & FUEL == f & POLLUTANT == p, ] -> eftes te <- as.numeric(te) x <- ifelse( te < 10, eftes$T10, ifelse( te > 25, eftes$T25, 1)) return(x) } #' @title Correction of Chinese emission factors by humidity #' @family China #' @name ef_china_hu #' @description Correction of Chinese emission #' @param hu numeric humidity #' @param v Character; category vehicle: "PV" for Passenger Vehicles or 'Trucks" #' @param t Character; sub-category of of vehicle: PV Gasoline: "Mini", "Small","Medium", #' "Large", "Taxi", "Motorcycles", "Moped", PV Diesel: "Mediumbus", "Largebus", #' "3-Wheel". Trucks: "Mini", "Light" , "Medium", "Heavy" #' @param f Character;fuel: "G", "D", "CNG" #' @param standard Character vector; "PRE", "I", "II", "III", "IV", "V". #' @param p Character; pollutant: "CO", "NOx","HC", "PM", "Evaporative_driving" #' or "Evaporative_parking" #' @return long data.frame #' @importFrom data.table setDT #' @export #' @examples { #' ef_china_hu(hu = 60, standard = "I", p = "CO") #' } ef_china_hu <- function(hu, v = "PV", t = "Small", f = "G", standard, p){ efh <- sysdata$humidity_china f <- ifelse(f %in% c("CNG", "G HY", "G"), "G", "D") data.table::setDT(efh) VEH <- TYPE <- FUEL <- POLLUTANT <- NULL efh[VEH == v & TYPE == t & FUEL == f & POLLUTANT == p, ] -> efhs hu <- as.numeric(hu) x <- ifelse( hu < 50, efhs$L50, ifelse( hu > 50, efhs$H50, 1)) return(x) } #' @title Correction of Chinese factors by humidity when temperature > 24 #' @family China #' @name ef_china_th #' @description Correction of Chinese emission #' @param hu numeric humidity #' @param te numeric temperature in celsius #' @param v Character; category vehicle: "PV" for Passenger Vehicles or 'Trucks" #' @param t Character; sub-category of of vehicle: PV Gasoline: "Mini", "Small","Medium", #' "Large", "Taxi", "Motorcycles", "Moped", PV Diesel: "Mediumbus", "Largebus", #' "3-Wheel". Trucks: "Mini", "Light" , "Medium", "Heavy" #' @param f Character;fuel: "G", "D", "CNG" #' @param p Character; pollutant: "CO", "NOx","HC", "PM", "Evaporative_driving" #' or "Evaporative_parking" #' @return long data.frame #' @importFrom data.table setDT #' @export #' @examples { #' ef_china_th(hu = 60, te = 25, p = "CO") #' } ef_china_th <- function(hu, te, v = "PV", t = "Small", f = "G", p){ efth <- sysdata$tehu_china f <- ifelse(f %in% c("CNG", "G HY", "G"), "G", "D") data.table::setDT(efth) VEH <- TYPE <- FUEL <- POLLUTANT <- NULL efth[VEH == v & TYPE == t & FUEL == f & POLLUTANT == p, ] -> efhs hu <- as.numeric(hu) te <- as.numeric(te) x <- ifelse( te > 24 & hu < 50, efhs$TH24L50, ifelse( te > 24 & hu > 50, efhs$TH24H50, 1)) return(x) } #' @title Correction of Chinese factors by altitude #' @family China #' @name ef_china_h #' @description Correction of Chinese emission #' @param h numeric altitude #' @param v Character; category vehicle: "PV" for Passenger Vehicles or 'Trucks" #' @param t Character; sub-category of of vehicle: PV Gasoline: "Mini", "Small","Medium", #' "Large", "Taxi", "Motorcycles", "Moped", PV Diesel: "Mediumbus", "Largebus", #' "3-Wheel". Trucks: "Mini", "Light" , "Medium", "Heavy" #' @param f Character;fuel: "G", "D", "CNG" #' @param p Character; pollutant: "CO", "NOx","HC", "PM", "Evaporative_driving" #' or "Evaporative_parking" #' @return long data.frame #' @importFrom data.table setDT #' @export #' @examples { #' ef_china_h(h = 1600, p = "CO") #' } ef_china_h <- function(h, v = "PV", t = "Small", f = "G", p){ efhi <- sysdata$h_china f <- ifelse(f %in% c("CNG", "G HY", "G"), "G", "D") data.table::setDT(efhi) VEH <- TYPE <- FUEL <- POLLUTANT <- NULL efhi[VEH == v & TYPE == t & FUEL == f & POLLUTANT == p, ] -> efhis h <- as.numeric(h) x <- ifelse( h > 1500, efhis$H, 1) return(x) } #' @title Estimation with Chinese factors #' @family China #' @name emis_china #' @description Emissions estimates #' @param x Vehicles data.frame #' @param lkm Length of each link in km #' @param tfs temporal factor #' @param v Character; category vehicle: "PV" for Passenger Vehicles or 'Trucks" #' @param t Character; sub-category of of vehicle: PV Gasoline: "Mini", "Small","Medium", #' "Large", "Taxi", "Motorcycles", "Moped", PV Diesel: "Mediumbus", "Largebus", #' "3-Wheel". Trucks: "Mini", "Light" , "Medium", "Heavy" #' @param f Character;fuel: "G", "D", "CNG", "ALL" #' @param standard Character vector; "PRE", "I", "II", "III", "IV", "V". #' @param p Character; pollutant: "CO", "NOx","HC", "PM", "Evaporative_driving" #' or "Evaporative_parking" #' @param s Sulhur in ppm #' @param speed Speed (length nrow x) #' @param te Temperature (length tfs) #' @param hu Humidity (length tfs) #' @param h Altitude (length nrow x) #' @param yeardet Year, default 2016 #' @param p Character; pollutant: "CO", "NOx","HC", "PM", "Evaporative_driving" #' or "Evaporative_parking" #' @param array Logical to return EmissionsArray or not #' @param verbose Logical to show more info #' @return long data.frame #' @importFrom data.table setDT #' @export #' @examples { #' ef_china_h(h = 1600, p = "CO") #' } emis_china <- function(x, lkm, tfs, v = "PV", t = "Small", f = "G", standard, s, speed, te, hu, h, yeardet = 2016, p, verbose = TRUE, array = FALSE){ # checks if(length(tfs) != length(te)) stop("tfs, te and hu must have equal length") if(length(tfs) != length(hu)) stop("tfs, te and hu must have equal length") speed <- as.data.frame(speed) # if(ncol(speed) != ncol(x)) stop("speed and x must have equal length of cols") if(length(h) != nrow(x)) stop("length h and nrow x must have equal") # Vehicle if(verbose) cat("\nProcessing Vehicles\n") nr <- nrow(x) nc <- ncol(x) x <- temp_veh(x = x, tfs = tfs) if(verbose) cat("Estimating Base EF\n") # base std1 <- standard ef_base <- ef_china_long(v = v, t = t, f = f, standard = std1, p = p) if(verbose) cat("Correcting Base EF by sulfur\n") # sulfur ef_base_s <- ef_china_s(s = s, f = f, standard = std1, p = p) if(verbose) cat("Correcting Base EF by deterioration\n") # det ef_base_det <- ef_china_det(v = v, t = t, f = f, standard = std1, yeardet = yeardet, p = p) if(verbose) cat("Correcting Base EF by speed\n") # speed ef_base_speed <- rbindlist(lapply(seq_along(speed), function(k){ ef_china_speed(speed = speed[[k]], f = f, standard = std1, p = p) })) if(verbose) cat("Correcting Base EF by temperature\n") # temperature ef_base_temp <- ef_china_te(te = te, v = v, t = t, f = f, p = p) if(verbose) cat("Correcting Base EF by humidity\n") # humidity ef_base_hu <- ef_china_hu(hu = hu, v = v, t = t, f = f, p = p) if(verbose) cat("Correcting Base EF by humidity if T > 24\n") # temperaturehumidity ef_base_th <- ef_china_th(hu = hu, te = te, v = v, t = t, f = f, p = p) efmet <- ef_base_temp * ef_base_hu * ef_base_th # rep met each hour efmet <- rep(efmet, each = nc) if(verbose) cat("Correcting Base EF by Altitude\n") # altitude ef_base_h <- ef_china_h(h = h, v = v, t = t, f = f, p = p) ef_base_speedv2 <- ef_base_h* ef_base_speed * remove_units(ef_base) * ef_base_det* ef_base_s * efmet ef_base_speedv2 <- EmissionFactors(as.data.frame(ef_base_speedv2)) if(verbose) cat("Estimating emissions\n") E <- Emissions(do.call("cbind", lapply(1:nc, function(i) { as.data.frame(ef_base_speedv2)[, i] * as.data.frame(x)[, i] * rep(lkm, length(tfs)) }))) # return(E) E$Hour <- rep(seq_along(tfs), each = nr) if(array) { lx <- split(E, E$Hour) lxx <- unlist(lapply(seq_along(lx), function(i) { unlist(lx[[i]][, 1:nc]) })) a <- EmissionsArray(array(data = lxx, dim = c(nr, nc, length(tfs)))) return(a) } else { return(E) } return(x) }
/scratch/gouwar.j/cran-all/cranData/vein/R/ef_china.R
#' Emissions factors from European European Environment Agency #' #' \code{\link{ef_cetesb}} returns a vector or data.frame of Brazilian emission factors. #' @param category String: "PC" (Passenger Cars), "LCV" (Light Commercial Vehicles), #' "TRUCKS" (Heavy Duty Trucks), #' "BUS" (Buses) or "MC" (Motorcycles or L-Category as in EEA 2019). #' @param fuel String; "G", "G HY", "G PHEV G", #' "G PHEV ELEC", "D", "D PHEV D", #' "D PHEV ELEC", "LPG BIFUEL LPG", "LPG BIFUEL G", #' "CNG BIFUEL CNG", "CNG BIFUEL G", "D HY D", #' "D HY ELEC", "CNG", "BIO D" #' @param segment String for type of vehicle (try different, the function will show values). #' @param euro String; euro standard: #' "PRE", "IMPROVED CONVENTIONAL", "OPEN LOOP", #' "ECE 15/00-01", "ECE 15/02", "ECE 15/03", "ECE 15/04". #' "I", "II", "III", "IV", "V", #' "VI A/B/C", "VI D", "VI D-TEMP", "VI D/E", #' "EEV". #' @param tech String; technology: #' "DPF", "DPF With S/W Update", "DPF+SCR" #' "EGR", "GDI", "GDI+GPF", "LNT+DPF", "PFI", "SCR". #' @param pol String; "CO", "NOx", "NMHC" (VOC), "PM" (PM Exhaust), "EC", "CH4", "NH3", "N2O" #' @param mode String; "Urban Peak", "Urban Off Peak", "Rural", "Highway", NA. #' @param slope Numeric; 0.00, -0.06, -0.04, -0.02, 0.02, 0.04, 0.06, or NA #' @param load Numeric; 0.0,0.5, 1.0 or NA #' @param speed Numeric; optional numeric in km/h. #' @param fcorr Numeric; Correction by fuel properties by euro technology. #' See \code{\link{fuel_corr}}. The order from first to last is #' "PRE", "I", "II", "III", "IV", "V", "VI", "or other VI. Default is 1 #' @return Return a function depending of speed or numeric (g/km) #' @importFrom data.table setDT #' @keywords emission factors #' @export #' @examples { #' # ef_eea(category = "I DONT KNOW") #' ef_eea(category = "PC", #' fuel = "G", #' segment = "Small", #' euro = "I", #' tech = NA, #' pol = "CO", #' mode = NA, #' slope = 0, #' load = 0)(10) #' } ef_eea <- function( category, fuel, segment, euro, tech, pol, mode, slope, load, speed, fcorr = rep(1, 8) ) { eea <- data.table::setDT(sysdata$eea) eea$RoadSlope[is.na(eea$RoadSlope)] <- 0 eea$Load[is.na(eea$Load)] <- 0 Category <- Fuel <- Segment <- EuroStandard <- Technology <- NULL Pollutant <- Mode <- RoadSlope <- Load <- NULL #Function to case when lala <- function(x) { ifelse(x == "PRE", fcorr[1], ifelse( x == "I", fcorr[2], ifelse( x == "II", fcorr[3], ifelse( x == "III", fcorr[4], ifelse( x == "IV", fcorr[5], ifelse( x == "V", fcorr[6], ifelse( x == "VI", fcorr[7], fcorr[8])))))))} # category u_cat <- unique(eea$Category) if(any(!category %in% u_cat)) { stop("Select categories from:\n", paste(u_cat, collapse = "\n")) } ef <- eea[Category %in% category] # fuel u_fuel <- unique(ef$Fuel) if(any(!fuel %in% u_fuel)) { stop("Select categories from:\n", paste(u_fuel, collapse = "\n")) } ef <- ef[Fuel %in% fuel] # segment u_segment <- unique(ef$Segment) if(any(!segment %in% u_segment)) { stop("Select categories from:\n", paste(u_segment, collapse = "\n")) } ef <- ef[Segment %in% segment] # euro u_euro <- unique(ef$EuroStandard) if(any(!euro %in% u_euro)) { stop("Select categories from:\n", paste(u_euro, collapse = "\n")) } ef <- ef[EuroStandard %in% euro] k2 <- lala(euro) #requires length euro = 1 # tech u_tech <- unique(ef$Technology) if(any(!tech %in% u_tech)) { stop("Select categories from:\n", paste(u_tech, collapse = "\n")) } ef <- ef[Technology %in% tech] # pollutant u_pol <- unique(ef$Pollutant) if(any(!pol %in% u_pol)) { stop("Select categories from:\n", paste(u_pol, collapse = "\n")) } ef <- ef[Pollutant %in% pol] # mode u_mode <- unique(ef$Mode) if(any(!mode %in% u_mode)) { stop("Select categories from:\n", paste(u_mode, collapse = "\n")) } ef <- ef[Mode %in% mode] # slope u_slope <- unique(ef$RoadSlope) if(any(!slope %in% u_slope)) { stop("Select categories from:\n", paste(u_slope, collapse = "\n")) } ef <- ef[RoadSlope %in% slope] # load u_load <- unique(ef$Load) if(any(!slope %in% u_slope)) { stop("Select categories from:\n", paste(u_load, collapse = "\n")) } ef <- ef[Load %in% load] names(ef) # EF = (Alpha x V2 + Beta x V + Gamma + Delta / V) / (Epsilon x V2 + Zeta x V + Eta) x (1 - RF) alpha <- ef$Alpha beta <- ef$Beta gamma <- ef$Gamma delta <- ef$Delta epsilon <- ef$Epsilon zeta <- ef$Zita eta <- ef$Hta RF <- ef$ReductionFactor_perc minv <- ef$MinSpeed_kmh maxv <- ef$MaxSpeed_kmh fv <- function(V){ V <- ifelse(V < minv, minv, ifelse(V > maxv, maxv, V)) return((alpha*V*V + beta*V + gamma + delta / V) / (epsilon*V*V + zeta*V + eta)*(1-RF)) } if(missing(speed)) { return(fv) } else { return(EmissionFactors(fv(speed))) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/ef_eea.R
#' Emission Factors from EMFAC emission factors #' #' @description \code{\link{ef_emfac}} reads path to ef EMFAC. #' You must download the #' emission factors from EMFAC website. #' #' @param efpath Character path to EMFAC ef (g/miles) #' @return data.table with emission estimation in long format #' @export #' @examples \dontrun{ #' # do not run #' } ef_emfac <- function(efpath){ # ef ModelYear <- NULL # ef #### # if(verbose) cat("Reading ef\n") ef <- data.table::fread(efpath) names(ef) <- gsub(" ", "", names(ef)) if(grep(pattern = "FuelConsumption", names(ef)) > 0) { names(ef)[grep("FuelConsumption", names(ef))] <- "FC" } ef$fuel <- ifelse( ef$Fuel == "Gasoline", "G", ifelse( ef$Fuel == "Diesel", "D", ifelse( ef$Fuel == "Natural Gas", "CNG", ifelse( ef$Fuel == "Electricity", "ELEC", ifelse( ef$Fuel == "Plug-in Hybrid", "HY", "caca" ))))) unique(ef$fuel) ef$vehicles <- paste0(ef$VehicleCategory, "_", ef$fuel) runex <- grep(pattern = "RUNEX", x = names(ef), value = T) pmbw <- grep(pattern = "PMBW", x = names(ef), value = T) eff <- ef[ModelYear < 2022, c("ModelYear", "VehicleCategory", "Speed", "vehicles", "fuel", runex, pmbw, "FC"), with = F] def <- data.table::melt.data.table(data = ef, id.vars = c("ModelYear", "VehicleCategory", "Speed", "vehicles", "fuel"), measure.vars = c(runex, pmbw, "FC"), variable.name = "pollutant", value.name = "gmiles") data.table::setorderv(def, "ModelYear", -1) vehicles <- pollutant <- i <- j <- k <- l <- NULL return(def) }
/scratch/gouwar.j/cran-all/cranData/vein/R/ef_emfac.R
#' Evaporative emission factor #' #' @description \code{\link{ef_evap}} is a lookup table with tier 2 evaporative emission factors #' from EMEP/EEA emisison guidelines #' #' @param ef Name of evaporative emission factor as *eshotc*: mean hot-soak with #' carburator, *eswarmc*: mean cold and warm-soak with carburator, eshotfi: mean #' hot-soak with fuel injection, *erhotc*: mean hot running losses with #' carburator, *erwarmc* mean cold and warm running losses, *erhotfi* mean hot #' running losses with fuel injection. Length of ef 1. #' @param v Type of vehicles, "PC", "Motorcycle", "Motorcycle_2S" and "Moped" #' @param cc Size of engine in cc. PC "<=1400", "1400_2000" and ">2000" #' Motorcycle_2S: "<=50". Motorcyces: ">50", "<=250", "250_750" and ">750". #' Only engines of >750 has canister. #' @param dt Character or Numeric: Average monthly temperature variation: "-5_10", "0_15", "10_25" #' and "20_35". This argument can vector with several elements. dt can also be data.frame, #' but it is recommended that the number of columns are each month. So that dt #' varies in each row and each column. #' @param ca Size of canister: "no" meaning no canister, "small", "medium" and #' "large". #' @param pollutant Character indicating any of the covered pollutants: "NMHC", #' "ethane", "propane", "i-butane", "n-butane", "i-pentane", "n-pentane", #' "2-methylpentane", "3-methylpentane", "n-hexane", "n-heptane", "propene", #' "trans-2-butene", "isobutene", "cis-2-butene", "1,3-butadiene", #' "trans-2-pentene", "cis-2-pentene", "isoprene", "propyne", "acetylene", #' "benzene", "toluene", "ethylbenzene", "m-xylene", "o-xylene", #' "1,2,4-trimethylbenzene" and "1,3,5-trimethylbenzene". Default is "NMHC" #' @param ltrip Numeric; Length of trip. Experimental feature to conter g/trip #' and g/proced (assuming proced similar to trip) in g/km. #' @param kmday Numeric; average daily mileage. Experimental option #' to convert g/day in g/km. #' it is an information more solid than to know the average number of trips per day. #' @param k multiplication factor #' @param show when TRUE shows row of table with respective emission factor. #' @note Diurnal loses occur with daily temperature variations. Running loses #' occur during vehicles use. Hot soak emission occur following vehicles use. #' @param verbose Logical; To show more information #' @return emission factors in g/trip or g/proced. The object has class (g) #' but it order to know it is g/trip or g/proceed the argument show must by T #' @references Mellios G and Ntziachristos 2016. Gasoline evaporation. In: #' EEA, EMEP. EEA air pollutant emission inventory guidebook-2009. European #' Environment Agency, Copenhagen, 2009 #' @importFrom data.table rbindlist #' @importFrom units as_units #' @export #' @examples \dontrun{ #' # Do not run #' a <- ef_evap(ef = "eshotc", v = "PC", cc = "<=1400", dt = "0_15", ca = "no", #' pollutant = "cis-2-pentene") #' a <- ef_evap(ef = "ed", v = "PC", cc = "<=1400", dt = "0_15", ca = "no", #' show = TRUE) #' a <- ef_evap(ef = c("erhotc", "erhotc"), v = "PC", cc = "<=1400", #' dt = "0_15", ca = "no", #' show = TRUE) #' a <- ef_evap(ef = c("erhotc", "erhotc"), v = "PC", cc = "<=1400", #' dt = "0_15", ca = "no", #' show = FALSE) #' a <- ef_evap(ef = "eshotc", v = "PC", cc = "<=1400", dt = "0_15", ca = "no", #' show = TRUE) #' ef_evap(ef = "erhotc", v = "PC", cc = "<=1400", dt = "0_15", ca = "no", #' show = TRUE) #' temps <- 10:20 #' a <- ef_evap(ef = "erhotc", v = "PC", cc = "<=1400", dt = temps, ca = "no", #' show = TRUE) #' dt <- matrix(rep(1:24,5), ncol = 12) # 12 months #' dt <- celsius(dt) #' a <- ef_evap(ef ="erhotc", v = "PC", cc = "<=1400", #' dt = dt, ca = "no") #' lkm <- units::set_units(10, km) #' a <- ef_evap(ef ="erhotc", v = "PC", cc = "<=1400", ltrip = lkm, #' dt = dt, ca = "no") #' } ef_evap <- function (ef, v, cc, dt, ca, pollutant = "NMHC", k = 1, ltrip, kmday, show = FALSE, verbose = FALSE){ a <- (-5+10)/2 b <- (0+15)/2 c <- (10+25)/2 d <- (20+35)/2 ta <- "-5_10" tb <- "0_15" tc <- "10_25" td <- "20_35" ef_ev <- sysdata$ev efs <- as.character(unique(ef_ev$ef)) if(any(!ef %in% efs)) { cat("Please, select any of: \n") print(efs) cat("\n") stop() } # Check ltrip if(!missing(ltrip) & !missing(kmday)){ stop("You can convert to g/km runing losses and soak with ltrip OR diurnal with kmday. Not both at the same time") } if(is.matrix(dt)) dt <- as.data.frame(dt) # Checking length of ef and ltrip and kmday if(!missing(ltrip)){ if(length(ltrip) > 1) stop("Please, enter one value of 'ltrip'") # Check units if(!inherits(ltrip, "units")){ stop("ltrip neeeds to has class 'units' in 'km'. Please, check package '?units::set_units'") } if(units(ltrip) == units(units::as_units("m"))){ stop("Units of ltrip is 'm'. Please, check package '?units::set_units'") } if(units(ltrip) == units(units::as_units("km"))){ ltrip <- as.numeric(ltrip) } } # Check kmday if(!missing(kmday)){ if(length(kmday) > 1) stop("Please, enter one value of 'kmday'") # Check units if(!inherits(kmday, "units")){ stop("kmday neeeds to has class 'units' in 'km'. Please, check package '?units::set_units'") } if(units(kmday) == units(units::as_units("m"))){ stop("Units of kmday is 'm'. Please, check package '?units::set_units'") } if(units(kmday) == units(units::as_units("km"))){ kmday <- as.numeric(kmday) } } # check(dt) dt <- remove_units(dt) if(!is.data.frame(dt)){ # if(class(dt) == "factor"){ # stop("Please, enter numeric or character") # } if(is.numeric(dt)){ dt = ifelse(dt < a, ta, ifelse(dt >=a & dt < b, tb, ifelse(dt >= b & dt < c, tc, td ))) } if(length(dt) == 1 & length(ef) == 1){ df <- ef_ev[ef_ev$ef == ef & ef_ev$veh %in% v & ef_ev$cc %in% cc & ef_ev$dt == dt & ef_ev$canister %in% ca & ef_ev$pollutant == pollutant, ] } else if (length(dt) > 1 & length(ef) == 1){ df <- do.call("rbind", lapply(1:length(dt), function(i){ ef_ev[ef_ev$ef == ef & ef_ev$veh %in% v & ef_ev$cc %in% cc & ef_ev$dt == dt[i] & ef_ev$canister %in% ca & ef_ev$pollutant == pollutant, ] })) } else if(length(dt) == 1 & length(ef) > 1){ df <- do.call("rbind", lapply(1:length(ef), function(i){ ef_ev[ef_ev$ef == ef[i] & ef_ev$veh %in% v & ef_ev$cc %in% cc & ef_ev$dt == dt & ef_ev$canister %in% ca & ef_ev$pollutant == pollutant, ] })) } else if(length(dt) > 1 & length(ef) > 1){ df <- do.call("rbind", lapply(1:length(dt), function(j){ do.call("rbind", lapply(1:length(ef), function(i){ ef_ev[ef_ev$ef == ef[i] & ef_ev$veh %in% v & ef_ev$cc %in% cc & ef_ev$dt == dt[j] & ef_ev$canister %in% ca & ef_ev$pollutant == pollutant, ] })) })) } if(!missing(ltrip) ){ if (any(ef %in% "ed")) stop ("ef must cannot be Diurnal Evaporative ed") df$g <- EmissionFactors(df$g*k/ltrip) df$units <- NULL if (show) { return(df) } else { return(df$g) } } else if (!missing(kmday)){ if (any(!ef %in% c("eshotfi", "eswarmc", "eshotc", "erhotfi", "erwarmc", "erhotc"))){ stop ("ef must cannot be Diurnal Evaporative ed") } df$g <- EmissionFactors(df$g*k/kmday) df$units <- NULL if(show){ return(df) } else { return(df) } } df$g <- Emissions(df$g) if (show == TRUE) { return(df) } else { return(df$g) } } else if (is.data.frame(dt)){ if(is.numeric(dt[, 1])){ for(i in 1:ncol(dt)){ dt[, i] = ifelse(dt[, i] < a, ta, ifelse(dt[, i] >=a & dt[, i] < b, tb, ifelse(dt[, i] >= b & dt[, i] < c, tc, td ))) } } if(length(v) > 1 | length(cc) > 1 | length(ca) > 1){ stop("When dt is data.frame, lengths of 'v', 'cc' and 'ca' must be 1, and perhaps only works with direct injection") } if(ncol(dt) == 1 & length(ef) == 1){ df <- do.call("rbind", lapply(1:nrow(dt), function(i){ ef_ev[ef_ev$ef == ef & ef_ev$veh == v & ef_ev$cc == cc & ef_ev$dt == unlist(dt)[i] & ef_ev$canister == ca, ]$g })) if(!missing(ltrip)){ return(EmissionFactors(df*k/ltrip)) } else if(!missing(kmday)){ return(EmissionFactors(df*k/kmday)) } else if(missing(ltrip) & missing(kmday)){ return(Emissions(df*k)) } } else if (ncol(dt) > 1 & length(ef) == 1){ df <- do.call("rbind", lapply(1:ncol(dt), function(j){ df <- do.call("rbind", lapply(1:nrow(dt), function(i){ ef_ev[ef_ev$ef == ef & ef_ev$veh == v & ef_ev$cc == cc & ef_ev$dt == dt[i, j] & ef_ev$canister == ca & ef_ev$pollutant == pollutant, ]$g })) df <- as.data.frame(df) names(df) <- "ef" df$cols_temp <- j df })) if(!missing(ltrip)){ df$ef <- EmissionFactors(df$ef*k/ltrip) return(df) } else if(!missing(kmday)){ df$ef <- EmissionFactors(df$ef*k/kmday) return(df) } else if(missing(ltrip) & missing(kmday)){ df$ef <- Emissions(df$ef*k) return(df) } } else if(ncol(dt) == 1 & length(ef) > 1){ df <- do.call("cbind", lapply(1:length(ef), function(j){ do.call("rbind", lapply(1:nrow(dt), function(i){ ef_ev[ef_ev$ef == ef[j] & ef_ev$veh == v & ef_ev$cc == cc & ef_ev$dt == unlist(dt)[i] & ef_ev$canister == ca & ef_ev$pollutant == pollutant, ]$g })) })) if(!missing(ltrip)){ return(EmissionFactors(df*k/ltrip)) } else if(!missing(kmday)){ return(EmissionFactors(df*k/kmday)) } else if(missing(ltrip) & missing(kmday)){ return(Emissions(df*k)) } } else if(length(dt) > 1 & length(ef) > 1){ df <- do.call("rbind", lapply(1:ncol(dt), function(k){ df <- do.call("cbind", lapply(1:length(ef), function(j){ do.call("rbind", lapply(1:nrow(dt), function(i){ ef_ev[ef_ev$ef == ef[j] & ef_ev$veh == v & ef_ev$cc == cc & ef_ev$dt == dt[i, k] & ef_ev$canister == ca & ef_ev$pollutant == pollutant, ]$g })) })) })) if(!missing(ltrip)){ df <- EmissionFactors(df*k/ltrip) df$col_temp <- rep(1:ncol(dt), each = nrow(dt)) } else if(!missing(kmday)){ df <- EmissionFactors(df*k/kmday) df$col_temp <- rep(1:ncol(dt), each = nrow(dt)) } else if(missing(ltrip) & missing(kmday)){ df <- Emissions(df*k) df$col_temp <- rep(1:ncol(dt), each = nrow(dt)) } return(df) } } }
/scratch/gouwar.j/cran-all/cranData/vein/R/ef_evap.R
#' Experimental: Returns a function of Emission Factor by age of use #' #' @description \code{\link{ef_fun}} returns amount of vehicles at each age #' #' @param ef Numeric; numeric vector of emission factors. #' @param type Character; "logistic" by default so far. #' @param x Numeric; vector for ages of use. #' @param x0 Numeric; the x-value of the sigmoid's midpoint, #' @param k Numeric; the steepness of the curve. #' @param L Integer; the curve's maximum value. #' @return dataframe of age distrubution of vehicles at each street. #' @export #' @references https://en.wikipedia.org/wiki/Logistic_function #' @examples \dontrun{ #' data(fe2015) #' CO <- ef_cetesb(p = "CO", veh = "PC_G") #' ef_logit <- ef_fun(ef = CO, x0 = 27, k = 0.4, L = 33) #' df <- data.frame(CO, ef_logit) #' colplot(df) #' } ef_fun <- function(ef, type = "logistic", x = 1:length(ef), x0 = mean(ef), k = 1/4, L = max(ef)) { if(type == "logistic"){ FD <- function(x, x0, L, k) { L/(1 + exp(1)^(-k*(x - x0)) ) } a <- vein::EmissionFactors(FD(x, x0 = x0, k = k, L = L)) return(a) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/ef_fun.R
#' Scaling constant with speed emission factors of Heavy Duty Vehicles #' #' @description \code{\link{ef_hdv_scaled}} creates a list of scaled functions of emission factors. A scaled #' emission factor which at a speed of the dricing cycle (SDC) gives a desired value. #' This function needs a dataframe with local emission factors with a columns with #' the name "Euro_HDV" indicating the Euro equivalence standard, assuming that there are #' available local emission factors for several consecutive years. #' #' @param dfcol Column of the dataframe with the local emission factors eg df$dfcol #' @param SDC Speed of the driving cycle #' @param v Category vehicle: "Coach", "Trucks" or "Ubus" #' @param t Sub-category of of vehicle: "3Axes", "Artic", "Midi", "RT, "Std" and "TT" #' @param g Gross weight of each category: "<=18", ">18", "<=15", ">15 & <=18", "<=7.5", #' ">7.5 & <=12", ">12 & <=14", ">14 & <=20", ">20 & <=26", ">26 & <=28", ">28 & <=32", #' ">32", ">20 & <=28", ">28 & <=34", ">34 & <=40", ">40 & <=50" or ">50 & <=60" #' @param eu Euro emission standard: "PRE", "I", "II", "III", "IV" and "V" #' @param gr Gradient or slope of road: -0.06, -0.04, -0.02, 0.00, 0.02. 0.04 or 0.06 #' @param l Load of the vehicle: 0.0, 0.5 or 1.0 #' @param p Pollutant: "CO", "FC", "NOx" or "HC" #' @param df deprecated #' @return A list of scaled emission factors g/km #' @keywords speed emission factors #' @note The length of the list should be equal to the name of the age categories of #' a specific type of vehicle #' @export #' @examples { #' # Do not run #' CO <- ef_cetesb(p = "CO", veh = "TRUCKS_SL_D", full = TRUE) #' lef <- ef_hdv_scaled(dfcol = CO$CO, #' v = "Trucks", #' t = "RT", #' g = "<=7.5", #' eu = CO$Euro_EqHDV, #' gr = 0, #' l = 0.5, #' p = "CO") #' length(lef) #' ages <- c(1, 10, 20, 30, 40) #' EmissionFactors(do.call("cbind", #' lapply(ages, function(i) { #' data.frame(i = lef[[i]](1:100)) #' }))) -> df #' names(df) <- ages #' colplot(df) #' } ef_hdv_scaled <- function(df, dfcol, SDC = 34.12, v, t, g, eu, gr = 0, l = 0.5, p) { if(length(dfcol) != length(eu)) stop("Length of dfcol must be the same as length of eu") dfcol <- as.numeric(dfcol) la <- lapply(1:length(dfcol), function(i) { funIN <- ef_hdv_speed(v = v, t = t, g = g, eu = as.character(eu[i]), gr = gr, l = l, p = p, k=1, show.equation = FALSE) k <- dfcol[i]/ funIN(SDC) ef_hdv_speed(v = v, t = t, g = g, eu = as.character(eu[i]), gr = gr, l = l, p = p, k = k, show.equation = FALSE) }) class(la) <- c("EmissionFactorsList",class(la)) return(la) }
/scratch/gouwar.j/cran-all/cranData/vein/R/ef_hdv_scaled.R
#' Emissions factors for Heavy Duty Vehicles based on average speed #' #' This function returns speed dependent emission factors. The emission factors #' comes from the guidelines EMEP/EEA air pollutant emission inventory guidebook #' http://www.eea.europa.eu/themes/air/emep-eea-air-pollutant-emission-inventory-guidebook #' #' @param v Category vehicle: "Coach", "Trucks" or "Ubus" #' @param t Sub-category of of vehicle: "3Axes", "Artic", "Midi", "RT, "Std" and "TT" #' @param g Gross weight of each category: "<=18", ">18", "<=15", ">15 & <=18", "<=7.5", #' ">7.5 & <=12", ">12 & <=14", ">14 & <=20", ">20 & <=26", ">26 & <=28", ">28 & <=32", #' ">32", ">20 & <=28", ">28 & <=34", ">34 & <=40", ">40 & <=50" or ">50 & <=60" #' @param eu Euro emission standard: "PRE", "I", "II", "III", "IV", "V". Also "II+CRDPF", #' "III+CRDPF", "IV+CRDPF", "II+SCR", "III+SCR" and "V+SCR" for pollutants #' Number of particles and Active Surface. #' @param gr Gradient or slope of road: -0.06, -0.04, -0.02, 0.00, 0.02. 0.04 or 0.06 #' @param l Load of the vehicle: 0.0, 0.5 or 1.0 #' @param p Character; pollutant: "CO", "FC", "NOx", "NO", "NO2", "HC", "PM", "NMHC", "CH4", #' "CO2", "SO2" or "Pb". Only when p is "SO2" pr "Pb" x is needed. See notes. #' @param x Numeric; if pollutant is "SO2", it is sulfur in fuel in ppm, if is #' "Pb", Lead in fuel in ppm. #' @param k Multiplication factor #' @param show.equation Option to see or not the equation parameters #' @param speed Numeric; Speed to return Number of emission factor and not a function. #' It needs units in km/h #' @param fcorr Numeric; Correction by fuel properties by euro technology. #' See \code{\link{fuel_corr}}. The order from first to last is #' "PRE", "I", "II", "III", "IV", "V", VI, "VIc". Default is 1 #' @return an emission factor function which depends of the average speed V g/km #' @keywords speed emission factors #' @note #' \strong{Pollutants (g/km)}: "CO", "NOx", "HC", "PM", "CH4", "NMHC", "CO2", "SO2", #' "Pb". #' #' \strong{Black Carbon and Organic Matter (g/km)}: "BC", "OM" #' #' \strong{PAH and POP (g/km)}: See \code{\link{speciate}} #' \strong{Dioxins and furans (g equivalent toxicity / km)}: See \code{\link{speciate}} #' #' \strong{Metals (g/km)}: See \code{\link{speciate}} #' #' \emph{Active Surface (cm2/km)} See \code{\link{speciate}} #' #' \emph{Total Number of particles (N/km)}: See \code{\link{speciate}} #' #' The available standards for Active Surface or number of particles are: #' Euro II and III #' Euro II and III + CRDPF #' Euro II and III + SCR #' Euro IV + CRDPF #' Euro V + SCR #' #' The categories Pre Euro and Euro I were assigned with the factors of Euro II and Euro III #' The categories euro IV and euro V were assigned with euro III + SCR #' #' Fuel consumption for heavy VI comes from V #' #' @seealso \code{\link{fuel_corr}} \code{\link{emis}} \code{\link{ef_ldv_cold}} \code{\link{speciate}} #' @importFrom units as_units #' @export #' @examples \dontrun{ #' # Quick view #' pol <- c("CO", "NOx", "HC", "NMHC", "CH4", "FC", "PM", "CO2", "SO2") #' f <- sapply(1:length(pol), function(i){ #' print(pol[i]) #' ef_hdv_speed(v = "Trucks",t = "RT", g = "<=7.5", e = "II", gr = 0, #' l = 0.5, p = pol[i], x = 10)(30) #' }) #' f #' #' V <- 0:130 #' ef1 <- ef_hdv_speed(v = "Trucks",t = "RT", g = "<=7.5", e = "II", gr = 0, #' l = 0.5, p = "HC") #' plot(1:130, ef1(1:130), pch = 16, type = "b") #' euro <- c(rep("V", 5), rep("IV", 5), rep("III", 5), rep("II", 5), #' rep("I", 5), rep("PRE", 15)) #' lef <- lapply(1:30, function(i) { #' ef_hdv_speed(v = "Trucks", t = "RT", g = ">32", gr = 0, #' eu = euro[i], l = 0.5, p = "NOx", #' show.equation = FALSE)(25) }) #' efs <- EmissionFactors(unlist(lef)) #returns 'units' #' plot(efs, xlab = "age") #' lines(efs, type = "l") #' a <- ef_hdv_speed(v = "Trucks", t = "RT", g = ">32", gr = 0, #' eu = euro, l = 0.5, p = "NOx", speed = Speed(0:125)) #' a$speed <- NULL #' filled.contour(as.matrix(a), col = cptcity::lucky(n = 24), #' xlab = "Speed", ylab = "Age") #' persp(x = as.matrix(a), theta = 35, xlab = "Speed", ylab = "Age", #' zlab = "NOx [g/km]", col = cptcity::lucky(), phi = 25) #' aa <- ef_hdv_speed(v = "Trucks", t = "RT", g = ">32", gr = 0, #' eu = rbind(euro, euro), l = 0.5, p = "NOx", speed = Speed(0:125)) #' } ef_hdv_speed <- function(v, t, g, eu, x, gr = 0, l = 0.5 ,p, k=1, show.equation = FALSE, speed, fcorr = rep(1, 8)){ p_cri <- as.character(unique(sysdata$hdv_criteria$POLLUTANT)) p_ghg <- as.character(unique(sysdata$hdv_ghg$POLLUTANT)) #Check eu if(is.matrix(eu) | is.data.frame(eu)){ eu <- as.data.frame(eu) for(i in 1:ncol(eu)) eu[, i] <- as.character(eu[, i]) } else { eu = as.character(eu) } if(p %in% p_cri){ ef_hdv <- sysdata$hdv_criteria } else if(p %in% p_ghg){ ef_hdv <- sysdata$hdv_ghg } # Check speed if(!missing(speed)){ if(!inherits(speed, "units")){ stop("speed neeeds to has class 'units' in 'km/h'. Please, check package '?units::set_units'") } if(units(speed) != units(units::as_units("km/h"))){ stop("Units of speed must be 'km/h' ") } if(units(speed) == units(units::as_units("km/h"))){ speed <- as.numeric(speed) } } #Function to case when lala <- function(x) { ifelse(x == "PRE", fcorr[1], ifelse( x == "I", fcorr[2], ifelse( x == "II", fcorr[3], ifelse( x == "III", fcorr[4], ifelse( x == "IV", fcorr[5], ifelse( x == "V", fcorr[6], ifelse( x == "VI", fcorr[7], fcorr[8]))))))) } # fun starts if(!is.data.frame(eu)){ if(length(eu) == 1){ df <- ef_hdv[ef_hdv$VEH == v & ef_hdv$TYPE == t & ef_hdv$GW == g & ef_hdv$EURO == eu & ef_hdv$GRA == gr & ef_hdv$LOAD == l & ef_hdv$POLLUTANT == p, ] k2 <- lala(eu) if (show.equation == TRUE) { cat(paste0("a = ", df$a, ", b = ", df$b, ", c = ", df$c, ", d = ", df$d, ", e = ", df$e, ", f = ", df$f, "\n")) cat(paste0("Equation = ", "(",as.character(df$Y), ")", "*", k, "*", k2, "\n")) } if(p %in% c("SO2","Pb")){ f1 <- function(V){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f; x <- x V <- ifelse(V < df$MINV, df$MINV, ifelse(V > df$MAXV, df$MAXV, V)) eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2))) } } else { f1 <- function(V){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f V <- ifelse(V<df$MINV,df$MINV,ifelse(V>df$MAXV,df$MAXV,V)) eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2))) } } if(!missing(speed)){ f1 <- EmissionFactors(f1(speed)) return(f1) } else { return(f1) } } else if(length(eu) > 1) { if(missing(speed)) stop("if length(eu) > 1, 'speed' is needed") dff <- do.call("cbind", lapply(1:length(eu), function(i){ df <- ef_hdv[ef_hdv$VEH == v & ef_hdv$TYPE == t & ef_hdv$GW == g & ef_hdv$EURO == eu[i] & ef_hdv$GRA == gr & ef_hdv$LOAD == l & ef_hdv$POLLUTANT == p, ] k2 <- lala(eu[i]) if(p %in% c("SO2","Pb")){ f1 <- function(V){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f; x <- x V <- ifelse(V < df$MINV, df$MINV, ifelse(V > df$MAXV, df$MAXV, V)) ifelse(eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2))) < 0, 0, eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2))) ) } } else { f1 <- function(V){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f V <- ifelse(V<df$MINV,df$MINV,ifelse(V>df$MAXV,df$MAXV,V)) ifelse(eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2))) < 0, 0, eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2)))) } } f1(speed) })) dff <- EmissionFactors(dff) names(dff) <- paste0(eu, "_", 1:length(eu)) dff$speed <- speed return(dff) } } else if (is.data.frame(eu)){ if(missing(speed)) stop("Add 'speed' please for each row") dff <- do.call("rbind", lapply(1:nrow(eu), function(j){ do.call("cbind", lapply(1:ncol(eu), function(i){ df <- ef_hdv[ef_hdv$VEH == v & ef_hdv$TYPE == t & ef_hdv$GW == g & ef_hdv$EURO == eu[j,i][[1]] & ef_hdv$GRA == gr & ef_hdv$LOAD == l & ef_hdv$POLLUTANT == p, ] k2 <- lala(eu[j,i][[1]]) if(p %in% c("SO2","Pb")){ f1 <- function(V){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f; x <- x V <- ifelse(V < df$MINV, df$MINV, ifelse(V > df$MAXV, df$MAXV, V)) ifelse(eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2))) < 0, 0, eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2))) ) } } else { f1 <- function(V){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f V <- ifelse(V<df$MINV,df$MINV,ifelse(V>df$MAXV,df$MAXV,V)) ifelse(eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2))) < 0, 0, eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2)))) } } f1(speed) })) })) dff <- EmissionFactors(dff) dff$speed <- speed dff$row_eu <- rep(1:nrow(eu), each = length(speed)) return(dff) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/ef_hdv_speed.R
#' Emission factors deoending on accumulated mileage #' #' \code{\link{ef_im}} calculate the theoretical emission factors of vehicles. #' The approache is different from including deterioration factors #' (\code{\link{emis_det}}) but similar, because they represent how much emits #' a vehicle with a normal deterioration, but that it will pass the #' Inspection and Manteinance program. #' @param ef Numeric; emission factors of vehicles with \strong{0 mileage} #' (new vehicles). #' @param tc Numeric; rate of growth of emissions by year of use. #' @param amileage Numeric; Accumulated mileage by age of use. #' @param max_amileage Numeric; Max accumulated mileage. This means that after #' this value, mileage is constant. #' @param max_ef Numeric; Max ef. This means that after this value, ef is constant. #' @param verbose Logical; if you want detailed description. #' @return An emission factor of a deteriorated vehicle under normal conditions #' which would be approved in a inspection and mantainence program. #' @keywords mileage emission factors #' @export #' @examples \dontrun{ #' # Do not run #' # Passenger Cars PC #' data(fkm) #' # cumulative mileage from 1 to 50 years of use, 40:50 #' mil <- cumsum(fkm$KM_PC_E25(1:10)) #' ef_im(ef = seq(0.1, 2, 0.2), seq(0.1, 1, 0.1), mil) #' } ef_im <- function(ef, tc, amileage, max_amileage, max_ef, verbose = TRUE){ if(missing(ef)) stop("No ef") if(missing(tc)) stop("No tc") if(!missing(max_amileage)) { if(verbose) cat("adjusting amileage\n") amileage <- ifelse(amileage > max_amileage, max_amileage, amileage) } if(!missing(max_ef)) { if(verbose) cat("adjusting ef\n") ef <- ifelse(ef > max_ef, max_ef, ef) } nef <- ef * (1 + amileage * tc) return(EmissionFactors(nef)) }
/scratch/gouwar.j/cran-all/cranData/vein/R/ef_im.R
#' DEPRECATED Base emissions factors from International Vehicle Emissions (IVE) model #' #' #' This function was deprecated. If the user want some UF-based EF, run MOVES #' and extract EF #' #' \code{\link{ef_ive}} returns the base emission factors from the the IVE #' model. This function depend on vectorized mileage, which means your can #' enter with the mileage by age of use and the name of the pollutant. #' #' @name vein-deprecated #' @param description Character; "Auto/Sml Truck" "Truck/Bus" or"Sml Engine". #' @param fuel Character; "Petrol", "NG Retrofit", "Natural Gas", "Prop Retro.", #' "Propane", "EthOH Retrofit", "OEM Ethanol", "Diesel", "Ethanol" or "CNG/LPG". #' @param weight Character; "Light", "Medium", "Heavy", "Lt", "Med" or "Hvy" #' @param air_fuel_control Character; One of the following characters: "Carburetor", #' "Single-Pt FI", "Multi-Pt FI", "Carb/Mixer", "FI", "Pre-Chamber Inject.", #' "Direct Injection", "2-Cycle", "2-Cycle, FI", "4-Cycle, Carb", "4-Cycle, FI" #' "4-Cycle" #' @param exhaust Character: "None", "2-Way", "2-Way/EGR", "3-Way", "3-Way/EGR", #' "None/EGR", "LEV", "ULEV", "SULEV", "EuroI", "EuroII", "EuroIII", "EuroIV", #' "Hybrid", "Improved", "EGR+Improv", "Particulate", "Particulate/NOx", #' "EuroV", "High Tech" or "Catalyst" #' @param evaporative Character: "PCV", "PCV/Tank" or"None". #' @param mileage Numeric; mileage of vehicle by age of use km. #' @param pol Character; One of the following characters: "Carburetor", #' "Single-Pt FI", "Multi-Pt FI", "Carb/Mixer", "FI", "Pre-Chamber Inject.", #' "Direct Injection", "2-Cycle", "2-Cycle, FI", "4-Cycle, Carb", "4-Cycle, FI" #' "4-Cycle" #' #' \tabular{cccc}{ #' "VOC_gkm" \tab "CO_gkm" \tab "NOx_gkm" \tab "PM_gkm" \cr #' "Pb_gkm" \tab "SO2_gkm" \tab "NH3_gkm" \tab "1,3-butadiene_gkm" \cr #' "formaldehyde_gkm" \tab "acetaldehyde_gkm" \tab "benzene_gkm" \tab "EVAP_gkm" \cr #' "CO2_gkm" \tab "N20_gkm" \tab "CH4_gkm" \tab "VOC_gstart" \cr #' "CO_gstart" \tab "NOx_gstart" \tab "PM_gstart" \tab "Pb_gstart" \cr #' "SO2_gstart" \tab "NH3_gstart" \tab "1,3-butadiene_gstart" \tab "formaldehyde_gstart" \cr #' "acetaldehyde_gstart" \tab "benzene_gstart" \tab "EVAP_gstart" \tab "CO2_gstart" \cr #' "N20_gstart" \tab "CH4_gstart" \tab \tab \cr #' } #' @param details Logical; option to see or not more information about vehicle. #' @return An emission factor by annual mileage. #' @keywords speed emission factors ive #' @references Nicole Davis, James Lents, Mauricio Osses, Nick Nikkila, #' Matthew Barth. 2005. Development and Application of an International #' Vehicle Emissions Model. Transportation Research Board, 81st Annual Meeting, #' January 2005, Washington, D.C. #' @export #' @examples \dontrun{ #' # Do not run #' # Passenger Cars PC #' data(fkm) #' # cumulative mileage from 1 to 50 years of use, 40:50 #' mil <- cumsum(fkm$KM_PC_E25(1:50)) #' ef_ive("Truck/Bus", mileage = mil, pol = "CO_gkm") #' ef_ive(mileage = mil, pol = "CO_gkm", details = TRUE) #' } ef_ive <- function(description = "Auto/Sml Truck", fuel = "Petrol", weight = "Light", air_fuel_control = "Carburetor", exhaust = "None", evaporative = "PCV", mileage, pol, details = FALSE){ # ive <- sysdata$ive # a <- ive[ive$description == description & # ive$fuel == fuel & # ive$weight == weight & # ive$air_fuel_control == air_fuel_control & # ive$exhaust == exhaust & # ive$evaporative == evaporative, ] # if(nrow(a) == 0) stop("No data. Improve your selection") # if(details) print(a$veh[1]) # FF <- a$f[[1]] # if(pol %in% names(ive)[10:24]){ # ef <- vein::EmissionFactors(FF(mileage = mileage/1000, pol = pol, a = a)) # return(ef) # } else if(pol %in% names(ive)[25:39]){ # cat("units in g/start\n") # ef <- FF(mileage = mileage/1000, pol = pol, a = a) # return(ef) # } # } .Deprecated("ef_emfac") "ef_ive" }
/scratch/gouwar.j/cran-all/cranData/vein/R/ef_ive.R
#' Cold-Start Emissions factors for Light Duty Vehicles #' #' \code{\link{ef_ldv_cold}} returns speed functions or data.frames which depends on ambient temperature #' average speed. The emission factors comes from the guidelines EMEP/EEA air pollutant #' emission inventory guidebook #' http://www.eea.europa.eu/themes/air/emep-eea-air-pollutant-emission-inventory-guidebook #' #' @param v Character; Category vehicle: "LDV" #' @param ta Numeric vector or data.frame; Ambient temperature. Monthly mean can be used. When #' ta is a data.frame, one option is that the number of rows should be the number of #' rows of your Vehicles data.frame. This is convenient for top-down approach #' when each simple feature can be a polygon, with a monthly average temperature for #' each simple feature. In this case, the number of columns can be the 12 months. #' @param cc Character; Size of engine in cc: "<=1400", "1400_2000" or ">2000" #' @param f Character; Type of fuel: "G", "D" or "LPG" #' @param eu Character or data.frame of Characters; Euro standard: "PRE", "I", #' "II", "III", "IV", "V", "VI" or "VIc". When 'eu' is a data.frame and #' 'ta' is also a data.frame both has to have the same number of rows. For instance, #' When you want that each simple feature or region has a different emission standard. #' @param p Character; Pollutant: "CO", "FC", "NOx", "HC" or "PM" #' @param k Numeric; Multiplication factor #' @param show.equation Option to see or not the equation parameters #' @param speed Numeric; Speed to return Number of emission factor and not a function. #' @param fcorr Numeric; Correction by fuel properties by euro technology. #' See \code{\link{fuel_corr}}. The order from first to last is #' "PRE", "I", "II", "III", "IV", "V", VI, "VIc". Default is 1 #' @return an emission factor function which depends of the average speed V #' and ambient temperature. g/km #' @keywords cold emission factors #' @seealso \code{\link{fuel_corr}} #' @importFrom units as_units #' @export #' @examples \dontrun{ #' ef1 <- ef_ldv_cold(ta = 15, cc = "<=1400", f ="G", eu = "PRE", p = "CO", #' show.equation = TRUE) #' ef1(10) #' speed <- Speed(10) #' ef_ldv_cold(ta = 15, cc = "<=1400", f ="G", eu = "PRE", p = "CO", speed = speed) #' # lets create a matrix of ef cold at different speeds and temperatures #' te <- -50:50 #' lf <- sapply(1:length(te), function(i){ #' ef_ldv_cold(ta = te[i], cc = "<=1400", f ="G", eu = "I", p = "CO", speed = Speed(0:120)) #' }) #' filled.contour(lf, col= cptcity::lucky()) #' euros <- c("V", "V", "IV", "III", "II", "I", "PRE", "PRE") #' ef_ldv_cold(ta = 10, cc = "<=1400", f ="G", eu = euros, p = "CO", speed = Speed(0)) #' lf <- ef_ldv_cold(ta = 10, cc = "<=1400", f ="G", eu = euros, p = "CO", speed = Speed(0:120)) #' dt <- matrix(rep(2:25,5), ncol = 12) # 12 months #' ef_ldv_cold(ta = dt, cc = "<=1400", f ="G", eu = "I", p = "CO", speed = Speed(0)) #' ef_ldv_cold(ta = dt, cc = "<=1400", f ="G", eu = euros, p = "CO", speed = Speed(34)) #' euros2 <- c("V", "V", "V", "IV", "IV", "IV", "III", "III") #' dfe <- rbind(euros, euros2) #' ef_ldv_cold(ta = 10, cc = "<=1400", f ="G", eu = dfe, p = "CO", speed = Speed(0)) #' #' ef_ldv_cold(ta = dt[1:2,], cc = "<=1400", f ="G", eu = dfe, p = "CO", speed = Speed(0)) #' # Fuel corrections #' fcorr <- c(0.5,1,1,1,0.9,0.9,0.9,0.9) #' ef1 <- ef_ldv_cold(ta = 15, cc = "<=1400", f ="G", eu = "PRE", p = "CO", #' show.equation = TRUE, fcorr = fcorr) #' ef_ldv_cold(ta = 10, cc = "<=1400", f ="G", eu = dfe, p = "CO", speed = Speed(0), #' fcorr = fcorr) #' } ef_ldv_cold <- function(v = "LDV", ta, # can vary vertically, for each simple feature, and horizontally, for each month cc, f, eu, # can vary horizontally p, k = 1, show.equation = FALSE, speed, fcorr = rep(1, 8)){ ef_ldv <- sysdata$cold #Check eu if(is.matrix(eu) | is.data.frame(eu)){ eu <- as.data.frame(eu) for(i in 1:ncol(eu)) eu[, i] <- as.character(eu[, i]) } else { eu = as.character(eu) } # Check speed if(!missing(speed)){ if(!inherits(speed, "units")){ stop("speed neeeds to has class 'units' in 'km/h'. Please, check package '?units::set_units'") } if(units(speed) != units(units::as_units("km/h"))){ stop("Units of speed must be 'km/h' ") } if(units(speed) == units(units::as_units("km/h"))){ speed <- as.numeric(speed) } } if(is.matrix(ta)){ ta <- as.data.frame(ta) } #Function to case when lala <- function(x) { ifelse(x == "PRE", fcorr[1], ifelse( x == "I", fcorr[2], ifelse( x == "II", fcorr[3], ifelse( x == "III", fcorr[4], ifelse( x == "IV", fcorr[5], ifelse( x == "V", fcorr[6], ifelse( x == "VI", fcorr[7], fcorr[8]))))))) } # When eu is not a data.frame! if(!is.data.frame(eu)){ # Check ta, eu and speed if(is.data.frame(ta) | length(eu) > 1){ if(missing(speed)) stop("when 'ta' is data.frame or eu > 1, 'speed' is needed") } if (is.numeric(ta) & length(ta) == 1 & length(eu) == 1){ df <- ef_ldv[ef_ldv$VEH == v & ef_ldv$CC == cc & ef_ldv$FUEL == f & ef_ldv$EURO == eu & ef_ldv$POLLUTANT == p, ] k <- lala(eu) if (show.equation == TRUE) { cat(paste0("a = ", df$a, ", b = ", df$b, ", c = ", df$c, ", d = ", df$d, ", e = ", df$e, ", f = ", df$f, "\n")) cat(paste0("Equation = ", "(",as.character(df$Y), ")", "*", k)) } f1 <- function(V){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f g <- df$g; h <- df$h; i <- df$i V <- ifelse(V<df$MINV,df$MINV,ifelse(V>df$MAXV,df$MAXV,V)) ifelse(eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k))) < 0, 0, eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k)))) } if(!missing(speed)) { return(EmissionFactors(f1(speed))) } else { return(f1) } } else if(is.numeric(ta) & length(ta) == 1 & length(eu) > 1){ dff <- do.call("cbind", lapply(1:length(eu), function(i){ df <- ef_ldv[ef_ldv$VEH == v & ef_ldv$CC == cc & ef_ldv$FUEL == f & ef_ldv$EURO == eu[i] & ef_ldv$POLLUTANT == p, ] f1 <- function(V){ k <- lala(eu[i]) a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f g <- df$g; h <- df$h; i <- df$i V <- ifelse(V<df$MINV,df$MINV,ifelse(V>df$MAXV,df$MAXV,V)) ifelse(eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k))) < 0, 0, eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k)))) } f1(speed) })) dff <- EmissionFactors(dff) names(dff) <- paste0(eu) dff$speed <- speed dff$ta <- ta return(dff) } else if(is.data.frame(ta)){ dff <- do.call("rbind", lapply(1:ncol(ta), function(k){ do.call("rbind", lapply(1:nrow(ta), function(j){ dff <- do.call("cbind", lapply(1:length(eu), function(i){ df <- ef_ldv[ef_ldv$VEH == v & ef_ldv$CC == cc & ef_ldv$FUEL == f & ef_ldv$EURO == eu[i] & ef_ldv$POLLUTANT == p, ] f1 <- function(V){ ta <- ta[j, k] k <- lala(eu[i]) a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f g <- df$g; h <- df$h; i <- df$i V <- ifelse(V<df$MINV,df$MINV,ifelse(V>df$MAXV,df$MAXV,V)) ifelse(eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k))) < 0, 0, eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k)))) } f1(speed) })) dff <- EmissionFactors(dff) names(dff) <- paste0(eu, "_", 1:length(eu)) dff$speed <- speed dff$ta <- ta[j,k] dff })) })) return(dff) } # This is new!!!!!!!! } else if(is.data.frame(eu) | is.matrix(eu)){ # Check ta, eu and speed if(is.data.frame(ta) | length(eu) > 1){ if(missing(speed)) stop("when 'ta' is data.frame or eu > 1, 'speed' is needed") } if(is.numeric(ta) & length(ta) == 1){ dff <- do.call("rbind", lapply(1:nrow(eu), function(j){ dff <- do.call("cbind", lapply(1:ncol(eu), function(i){ df <- ef_ldv[ef_ldv$VEH == v & ef_ldv$CC == cc & ef_ldv$FUEL == f & ef_ldv$EURO == eu[j,i][[1]] & ef_ldv$POLLUTANT == p, ] f1 <- function(V){ k <- lala(eu[j,i][[1]]) a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f g <- df$g; h <- df$h; i <- df$i V <- ifelse(V<df$MINV,df$MINV,ifelse(V>df$MAXV,df$MAXV,V)) ifelse(eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k))) < 0, 0, eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k)))) } f1(speed) })) dff <- EmissionFactors(dff) dff$speed <- speed # dff$euros <- rep(paste0("Row eu ", 1:nrow(eu)), each = length(speed)) dff$ta <- ta dff })) return(dff) } else if(is.data.frame(ta)){ # if(nrow(ta) != nrow(eu)) { # cat("Number of rows of 'eu': ", nrow(eu), "\n") # cat("Number of rows of 'ta': ", nrow(ta), "\n") # stop("Number of rows of 'eu' and 'ta' must be the same") # } dff <- do.call("rbind", lapply(1:ncol(ta), function(k){ do.call("rbind", lapply(1:nrow(ta), function(j){ dff <- do.call("cbind", lapply(1:ncol(eu), function(i){ df <- ef_ldv[ef_ldv$VEH == v & ef_ldv$CC == cc & ef_ldv$FUEL == f & ef_ldv$EURO == eu[j,i][[1]] & ef_ldv$POLLUTANT == p, ] f1 <- function(V){ ta <- ta[j, k] k <- lala(eu[j,i][[1]]) a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f g <- df$g; h <- df$h; i <- df$i V <- ifelse(V<df$MINV,df$MINV,ifelse(V>df$MAXV,df$MAXV,V)) ifelse(eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k))) < 0, 0, eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k)))) } f1(speed) })) dff <- EmissionFactors(dff) dff$speed <- speed dff$ta <- ta[j,k] dff$row_eu <- j dff })) })) return(dff) } } }
/scratch/gouwar.j/cran-all/cranData/vein/R/ef_ldv_cold.R
#' List of cold start emission factors of Light Duty Vehicles #' #' This function creates a list of functions of cold start emission factors #' considering different euro emission standard to the elements of the list. #' #' @param df Dataframe with local emission factor #' @param v Category vehicle: "LDV" #' @param ta ambient temperature. Montly average van be used #' @param cc Size of engine in cc: <=1400", "1400_2000" and ">2000" #' @param f Type of fuel: "G" or "D" #' @param eu character vector of euro standards: "PRE", "I", "II", "III", "IV", #' "V", "VI" or "VIc". #' @param p Pollutant: "CO", "FC", "NOx", "HC" or "PM" #' @return A list of cold start emission factors g/km #' @keywords cold start emission factors #' @note The length of the list should be equal to the name of the age categories of #' a specific type of vehicle #' @export #' @examples \dontrun{ #' # Do not run #' df <- data.frame(age1 = c(1,1), #' age2 = c(2,2)) #' eu = c("I", "PRE") #' l <- ef_ldv_cold(t = 17, cc = "<=1400", f = "G", #' eu = "I", p = "CO") #' l_cold <- ef_ldv_cold_list(df, t = 17, cc = "<=1400", f = "G", #' eu = eu, p = "CO") #' length(l_cold) #' } ef_ldv_cold_list <- function(df,v = "LDV", ta, cc, f, eu, p) { lista <- lapply(1:length(df[,1]), function(i) { funIN <- ef_ldv_cold(v = "LDV", ta, cc, f, eu = as.character(eu[i]), p = p, k = 1, show.equation = FALSE) }) return(lista) }
/scratch/gouwar.j/cran-all/cranData/vein/R/ef_ldv_cold_list.R
#' Scaling constant with speed emission factors of Light Duty Vehicles #' #' This function creates a list of scaled functions of emission factors. A scaled #' emission factor which at a speed of the driving cycle (SDC) gives a desired value. #' #' This function calls "ef_ldv_speed" and calculate the specific k value, dividing the #' local emission factor by the respective speed emissions factor at the speed representative #' of the local emission factor, e.g. If the local emission factors were tested with the #' FTP-75 test procedure, SDC = 34.12 km/h. #' #' @param dfcol Column of the dataframe with the local emission factors eg df$dfcol #' @param SDC Speed of the driving cycle #' @param v Category vehicle: "PC", "LCV", "Motorcycle" or "Moped #' @param t Sub-category of of vehicle: PC: "ECE_1501", "ECE_1502", #' "ECE_1503", "ECE_1504" , "IMPROVED_CONVENTIONAL", "OPEN_LOOP", "ALL", #' "2S" or "4S". LCV: "4S", Motorcycle: "2S" or "4S". Moped: "2S" or "4S" #' @param cc Size of engine in cc: PC: "<=1400", ">1400", "1400_2000", ">2000", #' "<=800", "<=2000". Motorcycle: ">=50" (for "2S"), "<=250", "250_750", ">=750". #' Moped: "<=50". LCV : "<3.5" for gross weight. #' @param f Type of fuel: "G", "D", "LPG" or "FH" (Full Hybrid: starts by electric motor) #' @param eu Euro standard: "PRE", "I", "II", "III", "III+DPF", "IV", "V", "VI", "VIc" #' @param p Pollutant: "CO", "FC", "NOx", "HC" or "PM". If your pollutant dfcol #' is based on fuel, use "FC", if it is based on "HC", use "HC". #' @param df deprecated #' @return A list of scaled emission factors g/km #' @keywords speed emission factors #' @note The length of the list should be equal to the name of the age categories of #' a specific type of vehicle. Thanks to Glauber Camponogara for the help. #' @seealso ef_ldv_seed #' @export #' @examples { #' CO <- ef_cetesb(p = "CO", veh = "PC_FG", full = TRUE) #' lef <- ef_ldv_scaled(dfcol = CO$CO, #' v = "PC", #' t = "4S", #' cc = "<=1400", #' f = "G", #' eu = CO$EqEuro_PC, #' p = "CO") #' length(lef) #' ages <- c(1, 10, 20, 30, 40) #' EmissionFactors(do.call("cbind", #' lapply(ages, function(i) { #' data.frame(i = lef[[i]](1:100)) #' }))) -> df #' names(df) <- ages #' colplot(df) #' } ef_ldv_scaled <- function(df, dfcol , SDC = 34.12, v, t = "4S", cc, f, eu, p) { if(length(dfcol) != length(eu)) stop("Length of dfcol must be the same as length of eu") dfcol <- as.numeric(dfcol) la <- lapply(1:length(dfcol), function(i) { funIN <- ef_ldv_speed(v = v, t = t, cc = cc, f = f, eu = as.character(eu[i]), p = p, k = 1, show.equation = FALSE) k <- dfcol[i]/ funIN(SDC) ef_ldv_speed(v = v, t = t, cc = cc, f = f, eu = as.character(eu[i]), p = p, k = k, show.equation = FALSE) }) class(la) <- c("EmissionFactorsList", class(la)) return(la) }
/scratch/gouwar.j/cran-all/cranData/vein/R/ef_ldv_scaled.R
#' Emissions factors for Light Duty Vehicles and Motorcycles #' #' \code{\link{ef_ldv_speed}} returns speed dependent emission factors, data.frames or #' list of emission factors. The emission factors #' comes from the guidelines EMEP/EEA air pollutant emission inventory guidebook #' http://www.eea.europa.eu/themes/air/emep-eea-air-pollutant-emission-inventory-guidebook #' #' The argument of this functions have several options which results in #' different combinations that returns emission factors. If a combination of #' any option is wrong it will return an empty value. Therefore, it is #' important ti know the combinations. #' #' #' @param v Character; category vehicle: "PC", "LCV", "Motorcycle" or "Moped #' @param t Character; sub-category of of vehicle: PC: "ECE_1501", "ECE_1502", #' "ECE_1503", "ECE_1504" , "IMPROVED_CONVENTIONAL", "OPEN_LOOP", "ALL", #' "2S" or "4S". LCV: "4S", Motorcycle: "2S" or "4S". Moped: "2S" or "4S" #' @param cc Character; size of engine in cc: PC: "<=1400", ">1400", "1400_2000", ">2000", #' "<=800", "<=2000". Motorcycle: ">=50" (for "2S"), "<=250", "250_750", ">=750". #' Moped: "<=50". LCV : "<3.5" for gross weight. #' @param f Character; type of fuel: "G", "D", "LPG" or "FH" (Gasoline Full Hybrid). #' Full hybrid vehicles cannot be charged from the grid and recharge; only its own engine #' may recharge tis batteries. #' @param eu Character or data.frame of characters; euro standard: #' "PRE", "I", "II", "III", "III+DPF", "IV", "V", "VI" or "VIc". #' When the pollutan is active surface or number of particles, eu can also be "III+DISI" #' @param p Character; pollutant: "CO", "FC", "NOx", "NO", "NO2", "HC", "PM", "NMHC", "CH4", #' "CO2", "SO2" or "Pb". Only when p is "SO2" pr "Pb" x is needed. Also #' polycyclic aromatic hydrocarbons (PAHs), persistent organi pollutants (POPs), #' and Number of particles and Active Surface. #' @param x Numeric; if pollutant is "SO2", it is sulphur in fuel in ppm, if is #' "Pb", Lead in fuel in ppm. #' @param k Numeric; multiplication factor #' @param show.equation Logical; option to see or not the equation parameters. #' @param speed Numeric; Speed to return Number of emission factor and not a function. #' @param fcorr Numeric; Correction by fuel properties by euro technology. #' See \code{\link{fuel_corr}}. The order from first to last is #' "PRE", "I", "II", "III", "IV", "V", VI, "VIc". Default is 1 #' @return An emission factor function which depends of the average speed V g/km #' @keywords speed emission factors #' @note t = "ALL" and cc == "ALL" works for several pollutants because emission #' fators are the same. Some exceptions are with NOx and FC because size of engine. #' #' \strong{Hybrid cars}: the only cover "PC" and according to EMEP/EEA air pollutant emission inventory #' guidebook 2016 (Ntziachristos and Samaras, 2016) only for euro IV. When new literature #' is available, I will update these factors. #' #' \strong{Pollutants (g/km)}: "CO", "NOx", "HC", "PM", "CH4", "NMHC", "CO2", "SO2", #' "Pb", "FC". #' #' \strong{Black Carbon and Organic Matter (g/km)}: "BC", "OM" #' #' \strong{PAH and POP (g/km)}: \code{\link{speciate}} #' \strong{Dioxins and furans(g equivalent toxicity / km)}: \code{\link{speciate}} #' \strong{Metals (g/km)}: \code{\link{speciate}} #' #' \strong{NMHC (g/km)}: \code{\link{speciate}} #' #' \emph{Active Surface (cm2/km)}: \code{\link{speciate}}"AS_urban", "AS_rural", "AS_highway" #' #' \emph{Total Number of particles (N/km)}: \code{\link{speciate}} "N_urban", "N_rural", "N_highway", #' "N_50nm_urban", "N_50_100nm_rural", "N_100_1000nm_highway". #' #' The available standards for Active Surface or number of particles are Euro I, #' II, III, III+DPF dor diesle and III+DISI for gasoline. Pre euro vehicles #' has the value of Euro I and euro IV, V, VI and VIc the value of euro III. #' @seealso \code{\link{fuel_corr}} \code{\link{emis}} \code{\link{ef_ldv_cold}} #' @export #' @examples \dontrun{ #' # Passenger Cars PC #' # Emission factor function #' V <- 0:150 #' ef1 <- ef_ldv_speed(v = "PC",t = "4S", cc = "<=1400", f = "G", eu = "PRE", #' p = "CO") #' efs <- EmissionFactors(ef1(1:150)) #' plot(Speed(1:150), efs, xlab = "speed[km/h]", type = "b", pch = 16, col = "blue") #' #' # Quick view #' pol <- c("CO", "NOx", "HC", "NMHC", "CH4", "FC", "PM", "CO2", "SO2", #' "1-butyne", "propyne") #' f <- sapply(1:length(pol), function(i){ #' ef_ldv_speed("PC", "4S", "<=1400", "G", "PRE", pol[i], x = 10)(30) #' }) #' f #' # PM Characteristics #' pol <- c("AS_urban", "AS_rural", "AS_highway", #' "N_urban", "N_rural", "N_highway", #' "N_50nm_urban", "N_50_100nm_rural", "N_100_1000nm_highway") #' f <- sapply(1:length(pol), function(i){ #' ef_ldv_speed("PC", "4S", "<=1400", "D", "PRE", pol[i], x = 10)(30) #' }) #' f #' # PAH POP #' ef_ldv_speed(v = "PC",t = "4S", cc = "<=1400", f = "G", eu = "PRE", #' p = "indeno(1,2,3-cd)pyrene")(10) #' ef_ldv_speed(v = "PC",t = "4S", cc = "<=1400", f = "G", eu = "PRE", #' p = "napthalene")(10) #' #' # Dioxins and Furans #' ef_ldv_speed(v = "PC",t = "4S", cc = "<=1400", f = "G", eu = "PRE", #' p = "PCB")(10) #' #' # NMHC #' ef_ldv_speed(v = "PC",t = "4S", cc = "<=1400", f = "G", eu = "PRE", #' p = "hexane")(10) #' #' # List of Copert emission factors for 40 years fleet of Passenger Cars. #' # Assuming a euro distribution of euro V, IV, III, II, and I of #' # 5 years each and the rest 15 as PRE euro: #' euro <- c(rep("V", 5), rep("IV", 5), rep("III", 5), rep("II", 5), #' rep("I", 5), rep("PRE", 15)) #' speed <- 25 #' lef <- lapply(1:40, function(i) { #' ef_ldv_speed(v = "PC", t = "4S", cc = "<=1400", f = "G", #' eu = euro[i], p = "CO") #' ef_ldv_speed(v = "PC", t = "4S", cc = "<=1400", f = "G", #' eu = euro[i], p = "CO", show.equation = FALSE)(25) }) #' # to check the emission factor with a plot #' efs <- EmissionFactors(unlist(lef)) #returns 'units' #' plot(efs, xlab = "age") #' lines(efs, type = "l") #' euros <- c("VI", "V", "IV", "III", "II") #' ef_ldv_speed(v = "PC", t = "4S", cc = "<=1400", f = "G", #' eu = euros, p = "CO") #' a <- ef_ldv_speed(v = "PC", t = "4S", cc = "<=1400", f = "G", #' eu = euros, p = "CO", speed = Speed(0:120)) #' head(a) #' filled.contour(as.matrix(a)[1:10, 1:length(euros)], col = cptcity::cpt(n = 18)) #' filled.contour(as.matrix(a)[110:120, 1:length(euros)], col = cptcity::cpt(n = 16)) #' filled.contour(as.matrix(a)[, 1:length(euros)], col = cptcity::cpt(n = 21)) #' filled.contour(as.matrix(a)[, 1:length(euros)], #' col = cptcity::cpt("mpl_viridis", n = 21)) #' filled.contour(as.matrix(a)[, 1:length(euros)], #' col = cptcity::cpt("mpl_magma", n = 21)) #' persp(as.matrix(a)[, 1:length(euros)], phi = 0, theta = 0) #' persp(as.matrix(a)[, 1:length(euros)], phi = 25, theta = 45) #' persp(as.matrix(a)[, 1:length(euros)], phi = 0, theta = 90) #' persp(as.matrix(a)[, 1:length(euros)], phi = 25, theta = 90+45) #' persp(as.matrix(a)[, 1:length(euros)], phi = 0, theta = 180) #' new_euro <- c("VI", "VI", "V", "V", "V") #' euro <- c("V", "V", "IV", "III", "II") #' old_euro <- c("III", "II", "I", "PRE", "PRE") #' meuros <- rbind(new_euro, euro, old_euro) #' aa <- ef_ldv_speed(v = "PC", t = "4S", cc = "<=1400", f = "G", #' eu = meuros, p = "CO", speed = Speed(10:11)) #' # Light Commercial Vehicles #' V <- 0:150 #' ef1 <- ef_ldv_speed(v = "LCV",t = "4S", cc = "<3.5", f = "G", eu = "PRE", #' p = "CO") #' efs <- EmissionFactors(ef1(1:150)) #' plot(Speed(1:150), efs, xlab = "speed[km/h]") #' lef <- lapply(1:5, function(i) { #' ef_ldv_speed(v = "LCV", t = "4S", cc = "<3.5", f = "G", #' eu = euro[i], p = "CO", show.equation = FALSE)(25) }) #' # to check the emission factor with a plot #' efs <- EmissionFactors(unlist(lef)) #returns 'units' #' plot(efs, xlab = "age") #' lines(efs, type = "l") #' #' # Motorcycles #' V <- 0:150 #' ef1 <- ef_ldv_speed(v = "Motorcycle",t = "4S", cc = "<=250", f = "G", #' eu = "PRE", p = "CO",show.equation = TRUE) #' efs <- EmissionFactors(ef1(1:150)) #' plot(Speed(1:150), efs, xlab = "speed[km/h]") #' # euro for motorcycles #' eurom <- c(rep("III", 5), rep("II", 5), rep("I", 5), rep("PRE", 25)) #' lef <- lapply(1:30, function(i) { #' ef_ldv_speed(v = "Motorcycle", t = "4S", cc = "<=250", f = "G", #' eu = eurom[i], p = "CO", #' show.equation = FALSE)(25) }) #' efs <- EmissionFactors(unlist(lef)) #returns 'units' #' plot(efs, xlab = "age") #' lines(efs, type = "l") #' a <- ef_ldv_speed(v = "Motorcycle", t = "4S", cc = "<=250", f = "G", #' eu = eurom, p = "CO", speed = Speed(0:125)) #' a$speed <- NULL #' filled.contour(as.matrix(a), col = cptcity::lucky(), #' xlab = "Speed", ylab = "Age") #' persp(x = as.matrix(a), theta = 35, xlab = "Speed", ylab = "Euros", #' zlab = "CO [g/km]", col = cptcity::lucky(), phi = 25) #' } ef_ldv_speed <- function( v, t = "4S", cc, f, eu, p, x, k = 1, speed, show.equation = FALSE, fcorr = rep(1, 8)){ ef_ldv <- sysdata$ldv xas <- c("AS_urban", "AS_rural", "AS_highway") npm <- c("N_urban", "N_rural", "N_highway", "N_50nm_urban", "N_50_100nm_rural", "N_100_1000nm_highway") # try to solve error of negative values present in EEA guidelines if(v == "LCV" && eu == "V") { warning("When `v` is 'LCV' and `eu` is 'V', I replaces `v` by 'PC' and `cc` by >'2000' see issue #204") v <- "PC" cc <- ">2000" } #Check eu if(is.matrix(eu) | is.data.frame(eu)){ eu <- as.data.frame(eu) for(i in 1:ncol(eu)) eu[, i] <- as.character(eu[, i]) } else { eu = as.character(eu) } # Check speed if(!missing(speed)){ if(!class(speed)[1] %in% c("units", "Speed")){ stop("speed neeeds to has class 'Speed' or 'units' in 'km/h'. Please, check package '?units::set_units'") } speed <- remove_units(speed) } #Function to case when lala <- function(x) { ifelse(x == "PRE", fcorr[1], ifelse( x == "I", fcorr[2], ifelse( x == "II", fcorr[3], ifelse( x == "III", fcorr[4], ifelse( x == "IV", fcorr[5], ifelse( x == "V", fcorr[6], ifelse( x == "VI", fcorr[7], fcorr[8])))))))} # Message for units if(!missing(speed)){ if( p %in% xas) { cat("Units of Active Surface: cm^2/km\n") } else if (p %in% npm){ cat("Units of Number of Particles: n/km\n") } } # fun starts if(!is.data.frame(eu)){ if(length(eu) == 1){ df <- ef_ldv[ef_ldv$VEH == v & ef_ldv$TYPE == t & ef_ldv$CC == cc & ef_ldv$FUEL == f & ef_ldv$EURO == eu & ef_ldv$POLLUTANT == p, ] k2 <- lala(eu) if (show.equation == TRUE) { cat(paste0("a = ", df$a, ", b = ", df$b, ", c = ", df$c, ", d = ", df$d, ", e = ", df$e, ", f = ", df$f, "\n")) cat(paste0("Equation = ", "(",as.character(df$Y), ")", "*", k, "*", k2, "\n")) } if(p %in% c("SO2","Pb")){ f1 <- function(V){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f; x <- x V <- ifelse(V < df$MINV, df$MINV, ifelse(V > df$MAXV, df$MAXV, V)) eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k))) } } else { f1 <- function(V){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f V <- ifelse(V<df$MINV,df$MINV,ifelse(V>df$MAXV,df$MAXV,V)) eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k))) } } # check for speed as numeric or data.frame if(!missing(speed)){ if(is.numeric(speed)){ f1 <- EmissionFactors(f1(speed)) return(f1) } else if(is.data.frame(speed)){ f1 <- EmissionFactors(sapply(speed, f1)) return(f1) } } else { return(f1) } } else if(length(eu) > 1){ if(!missing(speed)){ if(is.numeric(speed)) { dff <- do.call("cbind", lapply(1:length(eu), function(i){ df <- ef_ldv[ef_ldv$VEH == v & ef_ldv$TYPE == t & ef_ldv$CC == cc & ef_ldv$FUEL == f & ef_ldv$EURO == eu[i] & ef_ldv$POLLUTANT == p, ] k2 <- lala(eu[i]) if(p %in% c("SO2","Pb")){ f1 <- function(V){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f; x <- x V <- ifelse(V < df$MINV, df$MINV, ifelse(V > df$MAXV, df$MAXV, V)) ifelse(eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2))) < 0, 0, eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2))) ) } } else { f1 <- function(V){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f V <- ifelse(V<df$MINV,df$MINV,ifelse(V>df$MAXV,df$MAXV,V)) ifelse(eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2))) < 0, 0, eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2)))) } } f1(speed) })) dff <- EmissionFactors(dff) names(dff) <- paste0(eu, 1:length(eu)) dff$speed <- speed return(dff) } else if (is.data.frame(speed)){} } else { dff <- lapply(1:length(eu), function(i){ df <- ef_ldv[ef_ldv$VEH == v & ef_ldv$TYPE == t & ef_ldv$CC == cc & ef_ldv$FUEL == f & ef_ldv$EURO == eu[i] & ef_ldv$POLLUTANT == p, ] k2 <- lala(eu[i]) if(p %in% c("SO2","Pb")){ f1 <- function(V){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f; x <- x V <- ifelse(V < df$MINV, df$MINV, ifelse(V > df$MAXV, df$MAXV, V)) ifelse(eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2))) < 0, 0, eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2))) ) } } else { f1 <- function(V){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f V <- ifelse(V<df$MINV,df$MINV,ifelse(V>df$MAXV,df$MAXV,V)) ifelse(eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2))) < 0, 0, eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2)))) } } f1 }) names(dff) <- paste0(eu, 1:length(eu)) return(EmissionFactorsList(dff)) } } # New stuffs! } else if (is.data.frame(eu)){ if(missing(speed)) stop("Add 'speed' please") dff <- do.call("rbind", lapply(1:nrow(eu), function(j){ do.call("cbind", lapply(1:ncol(eu), function(i){ df <- ef_ldv[ef_ldv$VEH == v & ef_ldv$TYPE == t & ef_ldv$CC == cc & ef_ldv$FUEL == f & ef_ldv$EURO == eu[j,i][[1]] & ef_ldv$POLLUTANT == p, ] k2 <- lala(eu[j,i][[1]]) if(p %in% c("SO2","Pb")){ f1 <- function(V){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f; x <- x V <- ifelse(V < df$MINV, df$MINV, ifelse(V > df$MAXV, df$MAXV, V)) ifelse(eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2))) < 0, 0, eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2))) ) } } else { f1 <- function(V){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f V <- ifelse(V<df$MINV,df$MINV,ifelse(V>df$MAXV,df$MAXV,V)) ifelse(eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2))) < 0, 0, eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k, "*", k2)))) } } f1(speed) })) })) dff <- EmissionFactors(dff) dff$speed <- speed dff$row_eu <- rep(1:nrow(eu), each = length(speed)) return(dff) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/ef_ldv_speed.R
#' Local Emissions factors #' #' \code{\link{ef_local}} process an data.frame delivered by the user, but adding #' similar funcionality and arguments as \code{\link{ef_cetesb}}, which are classification, filtering #' and projections #' #' returns a vector or data.frame of Brazilian emission factors. #' #' @param p Character; pollutant delivered by the user. the name of the column of the data.frame must be #' \strong{Pollutant}. #' #' @param veh Character; Vehicle categories available in the data.frame provided by the user #' @param year Numeric; Filter the emission factor to start from a specific base year. #' If project is 'constant' values above 2017 and below 1980 will be repeated #' @param agemax Integer; age of oldest vehicles for that category #' @param ef data.frame, for local the emission factors. The names of the ef must #' be `Age` `Year` `Pollutant` and all the vehicle categories... #' @param full Logical; To return a data.frame instead or a vector adding #' Age, Year, Brazilian emissions standards and its euro equivalents. #' @param project Character showing the method for projecting emission factors in #' future. Currently the only value is "constant" #' @param verbose Logical; To show more information #' @return A vector of Emission Factor or a data.frame #' @keywords emission factors #' @note The names of the ef must be `Age` `Year` `Pollutant` and all the vehicle categories... #' @seealso \code{\link{ef_cetesb}} #' @export #' @examples \dontrun{ #' #do not run #' } ef_local <- function(p, veh, year = 2017, agemax = 40, ef, full = FALSE, project = "constant", verbose = TRUE){ ef[is.na(ef)] <- 0 # Check names if(verbose) { cat("\nNames of the ef data.frame: \n") print(names(ef)) } # Check column Pollutant iss <- unique(grepl(pattern = "Year", x = names(ef))) if(length(iss) == 1) stop("Please, add a column named `Year` in your ef data.frame") year1 <- ef$Year[1] # Check names if(verbose) { cat("\nRange Year:", range(ef$Year), "\n") } if(year < min(ef$Year)) stop("Min Year:", min(ef$Year), "\n") # Check column Pollutant iss <- unique(grepl(pattern = "Pollutant", x = names(ef))) if(length(iss) == 1) stop("Please, add a column named `Pollutant` in your ef data.frame") pols <- as.character(unique(ef$Pollutant)) if(verbose) cat("\nNames of the Pollutants: ", unique(ef$Pollutant), "\n") # Selecting ef <- ef[ef$Year <= year, ] if(!p %in% pols){ stop(cat("\nPlease, choose one of the following pollutants:\n", pols, "\n")) } if(full) { df <- cbind(ef[ef$Pollutant %in% p, 1:3], EmissionFactors(ef[ef$Pollutant == p, veh])) names(df)[ncol(df)] <- p } else{ df <- vein::EmissionFactors(ef[ef$Pollutant == p, veh]) row.names(df) } if(is.data.frame(df)){ # project future EF if(project == "constant"){ if(year > year1){ dif <- year - year1 eff <- do.call("rbind",(lapply(1:dif, function(i){ df[1, ] }))) edff <- rbind(eff, df[1:(agemax - dif), ]) } } #Filling older ef if(!missing(agemax)){ if(nrow(df) < agemax){ dif <- agemax - nrow(df) df[nrow(df):(nrow(df)+dif), ] <- df[nrow(df), ] } df <- df[1:agemax, ] } } else { # project future EF if(project == "constant"){ if(year > year1){ dif <- year - year1 eff <- rep(df[1], dif) df <- c(eff, df[1:(agemax - dif)]) } } #Filling older ef if(!missing(agemax)){ if(length(df) < agemax){ dif <- agemax - length(df) df[length(df):(length(df)+dif)] <- df[length(df)] } df <- df[1:agemax] } } return(df) }
/scratch/gouwar.j/cran-all/cranData/vein/R/ef_local.R
#' Emissions factors of N2O and NH3 #' #' \code{\link{ef_nitro}} returns emission factors as a functions of acondumulated mileage. #' The emission factors comes from the guidelines EMEP/EEA air pollutant #' emission inventory guidebook #' http://www.eea.europa.eu/themes/air/emep-eea-air-pollutant-emission-inventory-guidebook #' #' @param v Category vehicle: "PC", "LCV", "Motorcycles_2S", "Motorcycles", #' "Trucks", "Trucks-A", "Coach" and "BUS" #' @param t Type: "Cold" or "Hot" #' @param cond "Urban", "Rural", "Highway" #' @param cc PC: "<=1400", "1400_2000", ">2000". LCV: "<3.5". Motorcycles: ">=50", #' Motorcycles_2S, "<50", ">=50". Trucks: ">3.5", "7.5_12", "12_28", "28_34". #' Trucks_A: ">34". BUS: "<=15", ">15 & <= 18". Coach: "<=18", ">18" #' @param f Type of fuel: "G", "D" or "LPG" #' @param eu Euro standard: "PRE", "I", "II", "III", "IV", "V", "VI", #' "VIc" #' @param p Pollutant: "N2O", "NH3" #' @param S Sulphur (ppm). Number. #' @param k Multiplication factor #' @param show.equation Option to see or not the equation parameters #' @param cumileage Numeric; Acondumulated mileage to return number of emission factor and not a function. #' @param fcorr Numeric; Correction by by euro technology. #' @return an emission factor function which depends on the acondumulated mileage, #' or an EmissionFactor #' @keywords cumileage emission factors #' @note if length of eu is bigger than 1, cumileage can have values of length 1 #' or length equal to length of eu #' @importFrom units as_units #' @export #' @examples \dontrun{ #' efe10 <- ef_nitro(v = "PC", t = "Hot", cond = "Urban", f = "G", cc = "<=1400", #' eu = "III", p = "NH3", S = 10, #' show.equation = FALSE) #' efe50 <- ef_nitro(v = "PC", t = "Hot", cond = "Urban", f = "G", cc = "<=1400", #' eu = "III", p = "NH3", S = 50, #' show.equation = TRUE) #' efe10(10) #' efe50(10) #' efe10 <- ef_nitro(v = "PC", t = "Hot", cond = "Urban", f = "G", cc = "<=1400", #' eu = "III", p = "NH3", S = 10, cumileage = units::set_units(25000, "km")) #' } ef_nitro <- function(v, t = "Hot", cond = "Urban", cc, f, eu, p = "NH3", S = 10, cumileage, k = 1, show.equation = FALSE, fcorr = rep(1, 8)) { ef <- sysdata$nitro #Check eu if(is.matrix(eu) | is.data.frame(eu)){ eu <- as.data.frame(eu) for(i in 1:ncol(eu)) eu[, i] <- as.character(eu[, i]) } else { eu = as.character(eu) } # Check cumileage if(!missing(cumileage)){ if(!inherits(cumileage, "units")){ stop("cumileage neeeds to has class 'units' in 'km'. Please, check package '?units::set_units'") } if(units(cumileage) != units(units::as_units("km"))){ stop("Units of cumileage must be 'km' ") } if(units(cumileage) == units(units::as_units("km"))){ cumileage <- as.numeric(cumileage) } } #Function to case when lala <- function(x) { ifelse(x == "PRE", fcorr[1], ifelse( x == "I", fcorr[2], ifelse( x == "II", fcorr[3], ifelse( x == "III", fcorr[4], ifelse( x == "IV", fcorr[5], ifelse( x == "V", fcorr[6], ifelse( x == "VI", fcorr[7], fcorr[8])))))))} # fun starts if(!is.data.frame(eu)){ if(length(eu) == 1){ df <- ef[ef$VEH == v & ef$TYPE == t & ef$CONDITION == cond & ef$CC == cc & ef$FUEL == f & ef$EURO == eu & ef$POLLUTANT == p, ] k2 <- lala(eu) Equation = paste0("(",as.character(df$Y), ")", "*", k) if (show.equation == TRUE) { cat(paste0("a = ", df$a, ", b = ", df$b, ", c = ", df$c, ", d = ", df$d, ", e = ", df$e, ", f = ", df$f, ", ef = ", df$eff, "\n")) cat(paste0("Equation = ", Equation, "\n")) } f1 <- function(km){ a = df$a; b = df$b; ab = df$ab; c = df$c; d = df$d cd = df$cd; e = df$e; f = df$f; ef = df$ef eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k))) } if(!missing(cumileage)){ f1 <- EmissionFactors(f1(cumileage)) return(f1) } else { return(f1) } } else if(length(eu) > 1){ if(!missing(cumileage)){ dff <- do.call("cbind", lapply(1:length(eu), function(i){ df <- ef[ef$VEH == v & ef$TYPE == t & ef$CONDITION == cond & ef$CC == cc & ef$FUEL == f & ef$EURO == eu[i] & ef$POLLUTANT == p, ] k2 <- lala(eu[i]) f1 <- function(km){ a = df$a; b = df$b; ab = df$ab; c = df$c; d = df$d cd = df$cd; e = df$e; f = df$f; ef = df$ef eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k))) } ifelse(length(cumileage) == 1, f1(cumileage), f1(cumileage[i])) })) dff <- EmissionFactors(dff) names(dff) <- paste0(eu, 1:length(eu)) dff$cumileage <- cumileage return(dff) } else { dff <- lapply(1:length(eu), function(i){ df <- ef[ef$VEH == v & ef$TYPE == t & ef$CONDITION == cond & ef$CC == cc & ef$FUEL == f & ef$EURO == eu[i] & ef$POLLUTANT == p, ] k2 <- lala(eu[i]) f1 <- function(km){ a = df$a; b = df$b; ab = df$ab; c = df$c; d = df$d cd = df$cd; e = df$e; f = df$f; ef = df$ef eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k))) } f1 }) names(dff) <- paste0(eu, 1:length(eu)) return(EmissionFactorsList(dff)) } } # New stuffs! } else if (is.data.frame(eu)){ if(missing(cumileage)) stop("Add 'cumileage' please") dff <- do.call("rbind", lapply(1:nrow(eu), function(j){ do.call("cbind", lapply(1:ncol(eu), function(i){ df <- ef[ef$VEH == v & ef$TYPE == t & ef$CONDITION == cond & ef$CC == cc & ef$FUEL == f & ef$EURO == eu[j,i][[1]] & ef$POLLUTANT == p, ] k2 <- lala(eu[j,i][[1]]) f1 <- function(km){ a = df$a; b = df$b; ab = df$ab; c = df$c; d = df$d cd = df$cd; e = df$e; f = df$f; ef = df$ef eval(parse(text = paste0("(",as.character(df$Y), ")", "*", k))) } ifelse(length(cumileage) == 1, f1(cumileage), f1(cumileage[i])) })) })) dff <- EmissionFactors(dff) return(dff) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/ef_nitro.R
#' Emissions factors from tyre, break and road surface wear #' #' @description \code{\link{ef_wear}} estimates wear emissions. #' The sources are tyres, breaks and road surface. #' #' @param wear Character; type of wear: "tyre" (or "tire"), #' "break" (or "brake") and "road" #' @param type Character; type of vehicle: "2W", "MC", "Motorcycle", "PC", #' "LCV", 'HDV", "BUS", "TRUCKS" #' @param pol Character; pollutant: "TSP", "PM10", "PM2.5", "PM1" and "PM0.1" #' @param speed Data.frame of speeds #' @param load Load of the HDV #' @param axle Number of axle of the HDV #' @param road Type of road "urban", "rural", "motorway". #' Only applies when type is "E6DV" or "BEV" #' @param verbose Logical to show more information. #' Only applies when type is "E6DV" or "BEV" #' @return emission factors grams/km #' @references Ntziachristos and Boulter 2016. Automobile tyre and break wear #' and road abrasion. In: EEA, EMEP. EEA air pollutant emission inventory #' guidebook-2009. European Environment Agency, Copenhagen, 2016 #' #' When type is "E6DV" or "BEV": #' Tivey J., Davies H., Levine J., Zietsman J., Bartington S., #' Ibarra-Espinosa S., Ropkins K. 2022. Meta Analysis as Early #' Evidence on the Particulate Emissions Impact of EURO VI to #' Battery Electric Bus Fleet Transitions. Paper under development. #' @export #' @examples { #' data(net) #' data(pc_profile) #' pc_week <- temp_fact(net$ldv+net$hdv, pc_profile) #' df <- netspeed(pc_week, net$ps, net$ffs, net$capacity, net$lkm, alpha = 1) #' ef <- ef_wear(wear = "tyre", type = "PC", pol = "PM10", speed = df) #' #' ef_wear(wear = "tyre", #' type = c("E6DV"), #' pol = "PM10", #' verbose = TRUE) #' #' ef_wear(wear = "tyre", #' type = c("E6DV"), #' pol = "PM10", #' verbose = FALSE) #' #' } ef_wear <- function (wear, type, pol = "TSP", speed, load = 0.5, axle=2, road = "urban", verbose = FALSE) { if(length(type) > 1) stop("only 1 type") if(!type %in% c("E6DV", "BEV")) { if(is.vector(speed)){ speed <- matrix(as.numeric(speed), ncol = 1) } for (i in 1:ncol(speed) ) { speed[, i] <- as.numeric(speed[, i]) } if (wear %in% c("tyre", "tire")) { ef <- ifelse( type %in% c("2W", "MC", "Motorcycle"), 0.0046, ifelse( type=="PC",0.0107, ifelse( type=="LCV", 0.0109, ifelse( type %in% c("HDV", "BUS", "TRUCKS"), (axle/2)*(1.41 + 1.38*load)*0.0107)))) f <- ifelse( pol=="TSP", 1, ifelse( pol=="PM10", 0.6, ifelse( pol=="PM2.5", 0.42, ifelse( pol=="PM1",0.06, ifelse( pol=="PM0.1",0.048,"pol"))))) sv <- do.call("cbind",lapply(1:ncol(speed), function(i){ ifelse( speed[, i] > 40, 1.39, ifelse( speed[, i] >= 40 & speed <= 90, -0.00974*speed[, i] + 1.78, 0.902)) })) } else if (wear %in% c("break", "brake")){ ef <- ifelse( type%in% c("2W", "MC", "Motorcycle"), 0.0037, ifelse( type=="PC",0.0075, ifelse( type=="LCV", 0.0117, ifelse( type %in% c("HDV", "BUS", "TRUCKS"), 3.13*(1 + 0.79*load)*0.0037)))) f <- ifelse( pol=="TSP", 1, ifelse( pol=="PM10",0.98, ifelse( pol=="PM2.5", 0.39, ifelse( pol=="PM1",0.1, ifelse( pol=="PM0.1",0.08,"pol"))))) sv <- do.call("cbind",lapply(1:ncol(speed), function(i){ ifelse( speed[, i] > 40, 1.67, ifelse( speed[, i] >= 40 & speed <= 90, -0.0270*speed[, i] + 2.75, 0.185)) })) } else if (wear == "road"){ sv <- 1 ef <- ifelse( type%in% c("2W", "MC", "Motorcycle"), 0.0060, ifelse( type=="PC",0.0150, ifelse( type=="LCV", 0.0150, ifelse( type %in% c("HDV", "BUS", "TRUCKS"), 0.0760)))) f <- ifelse( pol=="TSP", 1, ifelse( pol=="PM10",0.5, ifelse( pol=="PM2.5", 0.27, ifelse( pol=="PM1", 0.27, ifelse( pol=="PM0.1", 0.27,"pol"))))) } efw <- EmissionFactors(ef*f*sv) return(efw) } else { data.frame( stringsAsFactors = FALSE, wear = c("brake","brake", "brake","brake","brake","brake","brake","brake", "brake","brake","brake","brake","tyre","tyre", "tyre","tyre","tyre","tyre","tyre","tyre","tyre", "tyre","tyre","tyre","road","road","road","road", "road","road","road","road","road","road", "road","road","res","res","res","res","res","res", "res","res","res","res","res","res"), veh = c("E6DV","E6DV","E6DV", "E6DV","E6DV","E6DV","BEV","BEV","BEV","BEV", "BEV","BEV","E6DV","E6DV","E6DV","E6DV","E6DV", "E6DV","BEV","BEV","BEV","BEV","BEV","BEV", "E6DV","E6DV","E6DV","E6DV","E6DV","E6DV","BEV", "BEV","BEV","BEV","BEV","BEV","E6DV","E6DV", "E6DV","E6DV","E6DV","E6DV","BEV","BEV","BEV", "BEV","BEV","BEV"), road = c("urban","rural", "motorway","urban","rural","motorway","urban","rural", "motorway","urban","rural","motorway","urban", "rural","motorway","urban","rural","motorway", "urban","rural","motorway","urban","rural", "motorway","urban","rural","motorway","urban","rural", "motorway","urban","rural","motorway","urban", "rural","motorway","urban","rural","motorway", "urban","rural","motorway","urban","rural", "motorway","urban","rural","motorway"), pol = c("PM2.5","PM2.5", "PM2.5","PM10","PM10","PM10","PM2.5","PM2.5","PM2.5", "PM10","PM10","PM10","PM2.5","PM2.5","PM2.5", "PM10","PM10","PM10","PM2.5","PM2.5","PM2.5", "PM10","PM10","PM10","PM2.5","PM2.5","PM2.5", "PM10","PM10","PM10","PM2.5","PM2.5","PM2.5","PM10", "PM10","PM10","PM2.5","PM2.5","PM2.5","PM10", "PM10","PM10","PM2.5","PM2.5","PM2.5","PM10", "PM10","PM10"), ef = c(18,11,3.4,47,28, 8.4,19,12,3.7,50,31,9.1,19,15,13,27,21,18, 20,16,13,29,22,19,18,18,18,32,32,32,19, 19,19,35,35,35,25,25,25,100,100,100,27,27, 27,110,110,110), efi = c(12,4.2,0,31,9.8,0, 12,4.4,0,33,10,0,15,12,9.8,21,16,14,15, 12,10,22,17,15,13,13,13,24,24,24,14,14, 14,25,25,25,7.6,7.6,7.6,32,32,32,8.2,8.2, 8.2,34,34,34), efs = c(27L,27L,17L,70L,69L, 43L,29L,30L,20L,74L,76L,49L,27L,21L,18L, 38L,30L,25L,29L,22L,19L,40L,31L,27L,24L,24L, 24L,43L,43L,43L,26L,26L,26L,47L,47L,47L, 150L,150L,150L,590L,590L,590L,170L,170L,170L, 690L,690L,690L) ) -> dx #wear uwear <- unique(dx$wear) if(any(!wear %in% uwear)) { stop("Select wear from:\n", paste(uwear, collapse = "\n")) } dx <- dx[dx$wear == wear, ] #veh uveh <- unique(dx$veh) if(any(!type %in% uveh)) { stop("Select type from:\n", paste(uveh, collapse = "\n")) } dx <- dx[dx$veh == type, ] #road uroad <- unique(dx$road) if(any(!road %in% uroad)) { stop("Select road from:\n", paste(uroad, collapse = "\n")) } dx <- dx[dx$road == road, ] #pol upol <- unique(dx$pol) if(any(!pol %in% upol)) { stop("Select pol from:\n", paste(upol, collapse = "\n")) } dx <- dx[dx$pol %in% pol, ] if(verbose) print(dx) return(EmissionFactors(dx$ef)) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/ef_wear.R
#' Emission factor that incorporates the effect of high emitters #' #' \code{\link{ef_whe}} return weighted emission factors of vehicles considering #' that one part of the fleet has a normal deterioration and another has a #' deteriorated fleet that would be rejected in a inspection and mantainence #' program but it is still in circulation. This emission factor might be #' applicable in cities without a inspection and mantainence program and with #' Weighted emission factors considering that part of the fleet are high emitters. #' #' @param efhe Numeric; Emission factors of high emitters vehicles. This vehicles #' would be rejected in a inspection and mantainnence program. #' @param phe Numeric; Percentage of high emitters. #' @param ef Numeric; Emission factors deteriorated vehicles under normal #' conditions. These vehicles would be approved in a inspection and mantainence #' program. #' @return An emission factor by annual mileage. #' @keywords emission factors high emitters #' @export #' @examples { #' # Do not run #' # Let's say high emitter is 5 times the normal ef. #' co_efhe <- ef_cetesb(p = "COd", "PC_G") * 5 #' # Let's say that the perfil of high emitters increases linearly #' # till 30 years and after that percentage is constant #' perc <- c(seq(0.01, 0.3, 0.01), rep(0.3, 10)) #' # Now, lets use our ef with normal deterioration #' co_ef_normal <- ef_cetesb(p = "COd", "PC_G") #' efd <- ef_whe(efhe = co_efhe, #' phe = perc, #' ef = co_ef_normal) #' # now, we can plot the three ef #' colplot(data.frame(co_efhe, co_ef_normal, efd)) #' } ef_whe <- function(efhe, phe, ef){ if(missing(efhe)) stop("No high emitter emission factor 'he'") if(missing(phe)) stop("No percentage of high emitter vehicles 'phe'") if(missing(ef)) stop("No emission factors with normal deterioration 'ef'") eff <- as.numeric(efhe) * as.numeric(phe) + as.numeric(ef) * (1 - phe) return(EmissionFactors(eff)) }
/scratch/gouwar.j/cran-all/cranData/vein/R/ef_whe.R
#' Estimation of emissions #' #' @description \code{\link{emis}} estimates vehicular emissions as the product of the #' vehicles on a road, length of the road, emission factor avaliated at the #' respective speed. \eqn{E = VEH*LENGTH*EF(speed)} #' #' @param veh "Vehicles" data-frame or list of "Vehicles" data-frame. Each data-frame #' as number of columns matching the age distribution of that ype of vehicle. #' The number of rows is equal to the number of streets link. If this is a list, #' the length of the list is the vehicles for each hour. #' @param lkm Length of each link in km #' @param ef List of functions of emission factors #' @param speed Speed data-frame with number of columns as hours. The default value is 34km/h #' @param agemax Age of oldest vehicles for that category #' @param profile Dataframe or Matrix with nrows equal to 24 and ncol 7 day of #' the week #' @param simplify Logical; to determine if EmissionsArray should les dimensions, #' being streets, vehicle categories and hours or default (streets, vehicle #' categories, hours and days). Default is FALSE to avoid break old code, but #' the recommendation is that new estimations use this parameter as TRUE #' @param fortran Logical; to try the fortran calculation when speed is not used. #' I will add fortran for EmissionFactorsList soon. #' @param hour Number of considered hours in estimation. Default value is number #' of rows of argument profile #' @param day Number of considered days in estimation #' @param verbose Logical; To show more information #' @param nt Integer; Number of threads wich must be lower than max available. #' See \code{\link{check_nt}}. Only when fortran = TRUE #' @useDynLib vein, .registration = TRUE #' @return If the user applies a top-down approach, the resulting units will be #' according its own data. For instance, if the vehicles are veh/day, the units #' of the emissions implicitly will be g/day. #' @note Hour and day will be deprecated because they can be infered from the profile #' matrix. #' @export #' @importFrom sf st_set_geometry #' @importFrom dotCall64 .C64 vector_dc #' @examples #' \dontrun{ #' # Do not run #' data(net) #' data(pc_profile) #' data(profiles) #' data(fe2015) #' data(fkm) #' PC_G <- c( #' 33491, 22340, 24818, 31808, 46458, 28574, 24856, 28972, 37818, 49050, 87923, #' 133833, 138441, 142682, 171029, 151048, 115228, 98664, 126444, 101027, #' 84771, 55864, 36306, 21079, 20138, 17439, 7854, 2215, 656, 1262, 476, 512, #' 1181, 4991, 3711, 5653, 7039, 5839, 4257, 3824, 3068 #' ) #' pc1 <- my_age(x = net$ldv, y = PC_G, name = "PC") #' #' # Estimation for morning rush hour and local emission factors and speed #' speed <- data.frame(S8 = net$ps) #' lef <- EmissionFactorsList(ef_cetesb("CO", "PC_G", agemax = ncol(pc1))) #' system.time(E_CO <- emis(veh = pc1, lkm = net$lkm, ef = lef, speed = speed)) #' system.time(E_CO_2 <- emis(veh = pc1, lkm = net$lkm, ef = lef, speed = speed, simplify = TRUE)) #' identical(E_CO, E_CO_2) #' #' # Estimation for morning rush hour and local emission factors without speed #' lef <- ef_cetesb("CO", "PC_G", agemax = ncol(pc1)) #' system.time(E_CO <- emis(veh = pc1, lkm = net$lkm, ef = lef)) #' system.time(E_CO_2 <- emis(veh = pc1, lkm = net$lkm, ef = lef, fortran = TRUE)) #' identical(E_CO, E_CO_2) #' #' # Estimation for 168 hour and local factors and speed #' pcw <- temp_fact(net$ldv + net$hdv, pc_profile) #' speed <- netspeed(pcw, net$ps, net$ffs, net$capacity, net$lkm, alpha = 1) #' lef <- EmissionFactorsList(ef_cetesb("CO", "PC_G", agemax = ncol(pc1))) #' system.time( #' E_CO <- emis( #' veh = pc1, #' lkm = net$lkm, #' ef = lef, #' speed = speed, #' profile = profiles$PC_JUNE_2014 #' ) #' ) #' system.time( #' E_CO_2 <- emis( #' veh = pc1, #' lkm = net$lkm, #' ef = lef, #' speed = speed, #' profile = profiles$PC_JUNE_2014, #' simplify = TRUE #' ) #' ) #' #' # Estimation for 168 hour and local factors and without speed #' lef <- ef_cetesb("CO", "PC_G", agemax = ncol(pc1)) #' system.time( #' E_CO <- emis( #' veh = pc1, #' lkm = net$lkm, #' ef = lef, #' profile = profiles$PC_JUNE_2014 #' ) #' ) #' sum(E_CO) #' system.time( #' E_CO_2 <- emis( #' veh = pc1, #' lkm = net$lkm, #' ef = lef, #' profile = profiles$PC_JUNE_2014, #' fortran = TRUE #' ) #' ) #' sum(E_CO) #' system.time( #' E_CO_3 <- emis( #' veh = pc1, #' lkm = net$lkm, #' ef = lef, #' profile = profiles$PC_JUNE_2014, #' simplify = TRUE #' ) #' ) #' sum(E_CO) #' system.time( #' E_CO_4 <- emis( #' veh = pc1, #' lkm = net$lkm, #' ef = lef, #' profile = profiles$PC_JUNE_2014, #' simplify = TRUE, #' fortran = TRUE #' ) #' ) #' sum(E_CO) #' identical(round(E_CO, 2), round(E_CO_2, 2)) #' identical(round(E_CO_3, 2), round(E_CO_4, 2)) #' identical(round(E_CO_3[, , 1], 2), round(E_CO_4[, , 1], 2)) #' dim(E_CO_3) #' dim(E_CO_4) #' # but #' a <- unlist(lapply(1:41, function(i) { #' unlist(lapply(1:168, function(j) { #' identical(E_CO_3[, i, j], E_CO_4[, i, j]) #' })) #' })) #' unique(a) #' #' # Estimation with list of vehicles #' lpc <- list(pc1, pc1) #' lef <- EmissionFactorsList(ef_cetesb("CO", "PC_G", agemax = ncol(pc1))) #' E_COv2 <- emis(veh = lpc, lkm = net$lkm, ef = lef, speed = speed) #' #' # top down #' veh <- age_ldv(x = net$ldv[1:4], name = "PC_E25_1400", agemax = 4) #' mil <- fkm$KM_PC_E25(1:4) #' ef <- ef_cetesb("COd", "PC_G")[1:4] #' emis(veh, units::set_units(mil, "km"), ef) #' #' # group online #' bus1 <- age_hdv(30, agemax = 4) #' veh <- bus1 #' lkm <- units::set_units(400, "km") #' speed <- 40 #' efco <- ef_cetesb("COd", "UB", agemax = 4) #' lef <- ef_hdv_scaled( #' dfcol = as.numeric(efco), #' v = "Ubus", #' t = "Std", #' g = ">15 & <=18", #' eu = rep("IV", 4), #' gr = 0, #' l = 0.5, #' p = "CO" #' ) #' for (i in 1:length(lef)) print(lef[[i]](10)) #' (a <- emis(veh = bus1, lkm = lkm, ef = efco, verbose = TRUE)) #' (b <- emis(veh = bus1, lkm = lkm, ef = efco, verbose = TRUE, fortran = TRUE)) #' } emis <- function(veh, lkm, ef, speed, agemax = ifelse(is.data.frame(veh), ncol(veh), ncol(veh[[1]]) ), profile, simplify = FALSE, fortran = FALSE, hour = nrow(profile), day = ncol(profile), verbose = FALSE, nt = ifelse(check_nt() == 1, 1, check_nt() / 2)) { # Check units if (!inherits(lkm, "units")) { stop("lkm neeeds to has class 'units' in 'km'. Please, check package 'units'") } if (units(lkm) == units(units::as_units("m"))) { stop("Units of lkm is 'm'. Please, check package '?units::set_units'") } # At least, on e of these # ommented because I need to evaluate withinherits and I will do it someday # if (any(!class(ef) %in% c( # "list", "units", "EmissionFactorsList", # "EmissionFactors", "data.frame" # ))) { # stop("ef must be either of 'list', 'units', 'EmissionFactorsList', 'EmissionFactors' or 'data.frame'") # } # Checking sf if (inherits(veh, "sf")) { if (verbose) message("Converting sf to data.frame") veh <- sf::st_set_geometry(veh, NULL) } if (!missing(hour) | !missing(day)) { warning("Arguments hour and day will be deprecated, they will derived from profile") } lkm <- as.numeric(lkm) # veh is "Vehicles" data-frame #### if (!inherits(x = veh, what = "list")) { veh <- remove_units(veh) # top down sin perfil, FE numerico if (missing(profile) & is.numeric(ef)) { if (verbose) { message( paste0( "If this is a top down approach, you may try emis_hot_td\n", "With this approach speed is not necessary\n" ) ) } if (nrow(veh) != length(lkm)) stop("Number of rows of `veh` must be the same as the length of `lkm`` ") if (fortran) { veh <- as.matrix(veh) lkm <- as.numeric(lkm) ef <- as.numeric(ef) nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) if (length(lkm) != nrow(veh)) stop("length of `lkm` must be equal to number of rows of `veh`") if (length(ef) != ncol(veh)) stop("length of `ef` and number of cols of `veh` must be equal") # emis(i, j) = veh(i,j) * lkm(i) * ef(j) if (!missing(nt)) { if (nt >= check_nt()) { stop( "Your machine has ", check_nt(), " threads and nt must be lower" ) } if (verbose) message("Calling emis2dfpar.f95") a <- dotCall64::.C64( .NAME = "emis2dfpar", SIGNATURE = c( rep("integer", 2), rep("double", 3), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, veh = veh, lkm = lkm, ef = ef, nt = as.integer(nt), emis = dotCall64::vector_dc("double",nrowv * ncolv), INTENT = c( "r", "r", "r", "r", "r", "r", "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emis2df.f95") a <- dotCall64::.C64( .NAME = "emis2df", SIGNATURE = c( rep("integer", 2), rep("double", 4) ), nrowv = nrowv, ncolv = ncolv, veh = veh, lkm = lkm, ef = ef, emis = dotCall64::vector_dc("double",nrowv * ncolv), INTENT = c( "r", "r", "r", "r", "r", "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } e <- matrix(a, nrow = nrowv, ncol = ncolv) return(Emissions(e)) } else { a <- lapply(1:ncol(veh), function(i) { veh[, i] * as.numeric(lkm) * as.numeric(ef)[i] }) a <- Emissions(do.call("cbind", a)) return(a) } # top down sin perfil, FE lista y con velocidad } else if (missing(profile) & inherits(ef, "EmissionFactorsList")) { # Check speed if (missing(speed)) stop("Add speed to be read by the EmissionFactorsList") speed <- remove_units(speed) if (nrow(veh) != length(lkm)) stop("Number of rows of `veh` must be the same as the length of `lkm`") if (nrow(veh) != length(unlist(speed))) stop("Number of rows of `veh` must be the same rows of `speed`") if (fortran) message("Not implemented yet when ef is 'EmissionsFactorsList`, changing to default") a <- lapply(1:ncol(veh), function(i) { veh[, i] * as.numeric(lkm) * ef[[i]](speed) }) a <- Emissions(do.call("cbind", a)) return(a) } # bottom up if (!missing(profile) & is.vector(profile)) { profile <- matrix(profile, ncol = 1) } if (inherits(x = ef, what = "list")) { if (verbose) message("Emission factors inherits from list") # Check length if (ncol(veh) != length(ef)) { if (verbose) { message( paste0( "Number of columns of 'veh' is different than length of 'ef'\n", "adjusting length of ef to the number of colums of 'veh'\n" ) ) } if (ncol(veh) > length(ef)) { for (i in (length(ef) + 1):ncol(veh)) { ef[[i]] <- ef[[length(ef)]] } } else if (ncol(veh) < length(ef)) { ff <- list() for (i in 1:ncol(veh)) { ff[[i]] <- ef[[i]] } ef <- ff } } # Check speed if (missing(speed)) stop("Add speed to be read by the EmissionFactorsList") speed <- remove_units(speed) # simplify? if (simplify) { if (fortran) message("Not implemented yet when ef is 'EmissionsFactorsList`, changing to default") d <- simplify2array( lapply(1:length(unlist(profile)), function(j) { # 7 dias simplify2array( lapply(1:agemax, function(k) { # categorias veh[, k] * unlist(profile)[j] * lkm * ef[[k]](speed[, j]) }) ) }) ) } else { if (fortran) message("Not implemented yet when ef is 'EmissionsFactorsList`, changing to default") d <- simplify2array( lapply(1:ncol(profile), function(j) { # 7 dias simplify2array( lapply(1:nrow(profile), function(i) { # 24 horas simplify2array( lapply(1:agemax, function(k) { # categorias veh[, k] * profile[i, j] * lkm * ef[[k]](speed[, (1:nrow(profile))[i] + nrow(profile) * (j - 1)]) }) ) }) ) }) ) } } else { if (verbose) message("Emission factors does not inherits from list") # Check length if (ncol(veh) != length(ef)) { if (verbose) { message( paste0( "Number of columns of 'veh' is different than length of 'ef'\n", "adjusting length of ef to the number of colums of 'veh'\n" ) ) } if (ncol(veh) > length(ef)) { for (i in (length(ef) + 1):ncol(veh)) { ef[[i]] <- ef[[length(ef)]] } } else if (ncol(veh) < length(ef)) { ff <- list() for (i in 1:ncol(veh)) { ff[[i]] <- ef[i] } ef <- unlist(ff) } } # Check speed if (!missing(speed)) warning("When ef is not EmissionFactorsList, speed is not needed") # simplify? if (simplify) { if (fortran) { veh <- as.matrix(veh) lkm <- as.numeric(lkm) ef <- as.numeric(ef) profile <- as.numeric(unlist(profile)) nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) prok <- as.integer(length(unlist(profile))) if (length(lkm) != nrow(veh)) stop("length of `lkm` must be equal to number of rows of `veh`") if (length(ef) != ncol(veh)) stop("length of `ef` and number of cols of `veh` must be equal") # emis(i, j, k) = veh(i, j) * lkm(i) * ef(j)*pro(k) if (!missing(nt)) { if (nt >= check_nt()) { stop( "Your machine has ", check_nt(), " threads and nt must be lower" ) } if (verbose) message("Calling emis3dfpar.f95") a <- dotCall64::.C64( .NAME = "emis3dfpar", SIGNATURE = c( rep("integer", 3), rep("double", 4), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, prok = prok, veh = veh, lkm = lkm, ef = ef, pro = profile, nt = as.integer(nt), emis = dotCall64::vector_dc("double",nrowv * ncolv * prok), INTENT = c( "r", "r", "r", "r", "r", "r", "r", "r", "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emis3df.f95") a <- dotCall64::.C64( .NAME = "emis3df", SIGNATURE = c( rep("integer", 3), rep("double", 5) ), nrowv = nrowv, ncolv = ncolv, prok = prok, veh = veh, lkm = lkm, ef = ef, pro = profile, emis = dotCall64::vector_dc("double",nrowv * ncolv * prok), INTENT = c( "r", "r", "r", "r", "r", "r", "r", "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } # fortran # do concurrent(i= 1:nrowv, j = 1:ncolv, k = 1:prok) # emis(i, j,k) = veh(i,j) * lkm(i) * ef(j)*pro(k) # end do e <- array(a, dim = c(nrowv, ncolv, prok)) return(EmissionsArray(e)) } else { vkm <- veh * lkm vkmef <- t(t(vkm) * ef) d <- simplify2array(lapply(unlist(profile), "*", vkmef)) } } else { if (fortran) { veh <- as.matrix(veh) profile <- as.matrix(profile) lkm <- as.numeric(lkm) ef <- as.numeric(ef) nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) proh <- as.integer(nrow(profile)) prod <- as.integer(ncol(profile)) if (length(lkm) != nrow(veh)) stop("length of `lkm` must be equal to number of rows of `veh`") if (length(ef) != ncol(veh)) stop("length of `ef` and number of cols of `veh` must be equal") # emis(i, j, k, l) = veh(i,j) * lkm(i) * ef(j)*pro(k,l) if (!missing(nt)) { if (nt >= check_nt()) { stop( "Your machine has ", check_nt(), " threads and nt must be lower" ) } if (verbose) message("Calling emis4dfpar.f95") a <- dotCall64::.C64( .NAME = "emis4dfpar", SIGNATURE = c( rep("integer", 4), rep("double", 4), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, proh = proh, prod = prod, veh = veh, lkm = lkm, ef = ef, pro = profile, nt = as.integer(nt), emis = dotCall64::vector_dc("double",nrowv * ncolv * proh * prod), INTENT = c( "r", "r", "r", "r", "r", "r", "r", "r", "r", "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emis4df.f95") a <- dotCall64::.C64( .NAME = "emis4df", SIGNATURE = c( rep("integer", 4), rep("double", 5) ), nrowv = nrowv, ncolv = ncolv, proh = proh, prod = prod, veh = veh, lkm = lkm, ef = ef, pro = profile, emis = dotCall64::vector_dc("double",nrowv * ncolv * proh * prod), INTENT = c( "r", "r", "r", "r", "r", "r", "r", "r", "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } e <- array(a, dim = c(nrowv, ncolv, proh, prod)) return(EmissionsArray(e)) } else { d <- simplify2array( lapply(1:ncol(profile), function(j) { # 7 dias simplify2array( lapply(1:nrow(profile), function(i) { # 24 horas simplify2array( lapply(1:agemax, function(k) { # categorias veh[, k] * profile[i, j] * lkm * ef[k] }) ) }) ) }) ) # checked with for(j in 1:7) for(i in 1:24) print((1:24)[i] + 24*(j - 1)) } } } if (verbose) message(round(sum(d, na.rm = T) / 1000, 2), " kg emissions") return(EmissionsArray(d)) # veh is a list of "Vehicles" data-frames # each member of the list is an hour } else { if (ncol(veh[[1]]) != length(ef)) { # check speed speed <- as.data.frame(speed) for (i in 1:ncol(speed)) { speed[, i] <- as.numeric(speed[, i]) } if (verbose) { message( paste0( "Number of columns of 'veh' is different than length of 'ef'\n", "adjusting length of ef to the number of colums of 'veh'\n" ) ) } if (ncol(veh[[1]]) > length(ef)) { for (i in (length(ef) + 1):ncol(veh[[1]])) { ef[[i]] <- ef[[length(ef)]] } } else if (ncol(veh[[1]]) < length(ef)) { ff <- list() for (i in 1:ncol(veh[[1]])) { ff[[i]] <- ef[[i]] } ef <- ff } } for (j in 1:length(veh)) { for (i in 1:ncol(veh[[j]])) { veh[[j]][, i] <- as.numeric(veh[[j]][, i]) } } # if(array == F){ # lista <- lapply(1:length(veh),function(i){ # lapply(1:agemax, function(k){ # veh[[i]][, k]*lkm*ef[[k]](speed[, i]) # } ) } ) # return(EmissionsList(lista)) # } else { d <- simplify2array( lapply(1:length(veh), function(i) { simplify2array( lapply(1:agemax, function(k) { veh[[i]][, k] * lkm * ef[[k]](speed[, i]) }) ) }) ) if (verbose) message(round(sum(d, na.rm = T) / 1000, 2), " kg emissions ") return(EmissionsArray(d)) # } } }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis.R
#' (in development, needs checks) Aggregate emissions by lumped groups in chemical mechanism #' #' @description \code{\link{emis_chem}} aggregates emissions by chemical mechanism #' and convert grams to mol. This function reads all hydrocarbos and respective #' criteria polluants specified in \code{\link{ef_ldv_speed}} and \code{\link{ef_hdv_speed}}. #' #' @param dfe data.frame with column `emissions` in grams and `pollutant` in long format. It is supposed #' that each line is the pollution of some region. Then the `coldby` argument is for include the #' name of the region. #' @param mechanism Character, #' "SAPRC", "RACM", "RADM2", "CBMZ", "MOZART", "SAPRC99", "CB05", #' "CB06CMAQ", "CB05CMAQ", "RACM2CMAQ", "SAPRC99CMAQ", "SAPRC07CMAQ", #' "SAPRC07A", "RADM2_SORG", "CBMZ_MOSAIC", "CPTEC", #' "GOCART_CPTEC", "MOZEM", "MOZCEM", "CAMMAM", "MOZMEM", #' "MOZC_T1_EM", "CB05_OPT1", "CB05_OPT2", "CRIMECH" #' @param colby Character indicating column name for aggregating extra column. #' For instance, region or province. #' @param long Logical. Do you want data in long format? #' @return data.frame with lumped groups by chemical mechanism. It transform #' emissions in grams to mol. #' @importFrom data.table setDF as.data.table #' @importFrom utils data #' @importFrom units as_units #' @seealso \code{\link{ef_ldv_speed}} \code{\link{ef_hdv_speed}} \code{\link{speciate}} \code{\link{ef_evap}} #' @export #' @note This feature is experimental and the mapping of pollutants and lumped #' species may change in future. #' This function is converting the intial data.frame input into data.table. #' To have a comprehensive speciation is necessary enter with a data.frame #' with colum 'emission' in long format including another column named 'pollutant' with #' species of NMHC, CO, NO, NO2, NH3, SO2, PM2.5 and coarse PM10. #' #' Groups derived from gases has units 'mol' and from aersols 'g'. The aersol #' units for WRF-Chem are ug/m^2/s while for CMAQ and CAMx are g/s. So, #' leaving the units just in g, allow to make further change while #' providing flexibility for several models. #' TODO: Enter with wide data.frame, with each line as a each street, each column for pollutant #' @examples \dontrun{ #' # CO #' df <- data.frame(emission = Emissions(1:10)) #' df$pollutant = "CO" #' emis_chem(dfe = df, "CBMZ_MOSAIC") #' # hexanal #' df$pollutant = "hexanal" #' emis_chem(df, "CBMZ_MOSAIC") #' # propadiene and NO2 #' df2 <- df1 <- df #' df1$pollutant = "propadiene" #' df2$pollutant = "NO2" #' (dfe <- rbind(df1, df2)) #' emis_chem(dfe, "CBMZ_MOSAIC") #' dfe$region <- rep(letters[1:2], 10) #' emis_chem(dfe, "CBMZ_MOSAIC", "region") #' emis_chem(dfe, "CBMZ_MOSAIC", "region", TRUE) #' } emis_chem <- function(dfe, mechanism, colby, long = FALSE) { dfe <- as.data.frame(dfe) #Check column pollutant if(!any(grepl(pattern = "pollutant", x = names(dfe)))){ stop("The column 'pollutant' is present in 'dfe'") } #Check column emissions if(!any(grepl(pattern = "emission", x = names(dfe)))){ stop("The column 'emission' is not present in 'dfe'") } # Check units if(!inherits(dfe$emission, "units")){ stop("dfe$emission neeeds to has class 'units' in 'g'. Check '?units::set_units'") } # loading mechanisms data-base df <- sysdata$mechx df <- df[df$MECH == mechanism, ] # loading pollutants with g_mol utils::data("pollutants") pollutants <- pollutants[, c("pollutant", "g_mol")] # merging and filtering g_mol dfe <- merge(dfe, pollutants, by = "pollutant", all = TRUE) # converting to mol dfe$mol <- ifelse(!is.na(dfe$g_mol), dfe$emission/dfe$g_mol, dfe$emission) # merging with mechanism df_mech <- merge(dfe, df, by = "pollutant", all = TRUE) df_mech <- data.table::as.data.table(df_mech) df_mech$mol <- ifelse(df_mech$type == "gas", df_mech$mol*df_mech$k, df_mech$emission*df_mech$k) if(!missing(colby)){ ss <- df_mech[, lapply(.SD, sum, na.rm=TRUE), keyby = list(df_mech$LUMPED, df_mech[[colby]]), .SDcols = "mol" ] names(ss) <- c("group", colby,"emission") } else { ss <- df_mech[, lapply(.SD, sum, na.rm=TRUE), keyby = list(df_mech$LUMPED), .SDcols = "mol" ] names(ss) <- c("group", "emission") } data.table::setDF(ss) gases <- unique(df[df$type == "gas", "LUMPED"]) ss$units <- ifelse(ss$group %in% gases, "mol", "g") ss <- ss[!is.na(ss$group), ] pollutants <- as.data.frame(pollutants) if(long){ return(ss) } else { if(missing(colby)){ ss <- suppressWarnings(long_to_wide(df = ss, column_with_new_names = "group", column_with_data = "emission")) } else { ss <- suppressWarnings(long_to_wide(df = ss, column_with_new_names = "group", column_with_data = "emission", column_fixed = colby)) sscolby <- ss[, colby] ss[, colby] <- NULL } } # putting units for(i in 1:(ncol(ss))){ if(names(ss)[i] %in% gases) { ss[, names(ss)[i]] <- units::as_units(ss[, names(ss)[i]], "mol") } else { ss[, names(ss)[i]] <- units::as_units(ss[, names(ss)[i]], "g") } } if(!missing(colby)) { ss[, colby] <- sscolby ss <- ss[!is.na(ss[colby]), ] } return(ss) }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis_chem.R
#' Aggregate emissions by lumped groups in chemical mechanism #' #' @description \code{\link{emis_chem2}} aggregates VOC emissions by chemical mechanism #' and convert grams to mol. #' #' @param df data.frame with emissions including columns "id" and "pol". #' @param mech Character, "CB4", "CB05", "S99", "S7","CS7", "S7T", "S11", #' "S11D","S16C","S18B","RADM2", "RACM2","MOZT1", "CBMZ", "CB05opt2" #' @param nx Character, colnames for emissions data, for instance "V1", "V2"... #' @param na.rm Logical, to remove lines with NA from group #' @return data.frame with lumped groups by chemical mechanism. #' @importFrom data.table setDF as.data.table setDT setorderv melt #' @seealso \code{\link{speciate}} #' @export #' @references Carter, W. P. (2015). Development of a database for #' chemical mechanism assignments for volatile organic emissions. #' Journal of the Air & Waste Management Association, 65(10), 1171-1184. #' @note #' \itemize{ #' \item \strong{CB05}: "ALD" "ALDX" "ETH" "HC3" "HC5" "HC8" "HCHO" "KET" #' "OL2" "OLI" "OLT" "TOL" "XYL" #' \item \strong{CB05opt2}: "ALD2" "ALDX" "BENZENE" "ETH" "ETHA" "FORM" #' "IOLE" "OLE" "PAR" "TOL" "XYL" #' \item \strong{RADM2}: "ALD" "ETH" "HC3" "HC5" "HC8" "HCHO" "KET" #' "MACR" "OL2" "OLI" "OLT" "TOL" "XYL" #' \item \strong{RACM2}: ACD" "ACE" "ACT" "ALD" "BALD" "BEN" "DIEN" #' "ETE" "ETH" "HC3" "HC5" "HC8" "HCHO" "MACR" "MEK" "OLI" "OLT" #' "TOL" "UALD" "XYM" "XYO" "XYP" #' \item \strong{CB4}: "ALD2" "ETH" "FORM" "OLE" "PAR" "TOL" "XYL" #' \item \strong{S99}: "ACET" "ALK1" "ALK2" "ALK3" "ALK4" "ALK5" "ARO1NBZ" #' "ARO2" "BALD" "BENZENE" "CCHO" "ETHENE" "HCHO" "IPROD" "MACR" "MEK" #' "OLE1" "OLE2" "RCHO" #' \item \strong{CB4}: "ACET" "ACYE" "ALK1" "ALK2" "ALK3" "ALK4" "ALK5" #' "ARO1" "ARO2" "BALD" "BENZ" "CCHO" "ETHE" "HCHO" "IPRD" "MACR" "MEK" #' "OLE1" "OLE2" "RCHO" #' \item \strong{CS7}: "ALK3" "ALK4" "ARO1" "ARO2" "CCHO" "ETHE" "HCHO" #' "IPRD" "NROG" "OLE1" "OLE2" "PRD2" "RCHO" #' \item \strong{S7}: "ACET" "ACYE" "ALK1" "ALK2" "ALK3" "ALK4" "ALK5" #' "ARO1" "ARO2" "BALD" "BENZ" "CCHO" "ETHE" "HCHO" "IPRD" "MACR" #' "MEK" "OLE1" "OLE2" "RCHO" #' \item \strong{S7T}: "13BDE" "ACET" "ACRO" "ACYE" "ALK1" "ALK2" #' "ALK3" "ALK4" "ALK5" "ARO1" "ARO2" "B124" "BALD" "BENZ" "CCHO" #' "ETHE" "HCHO" "IPRD" "MACR" "MEK" "MXYL" "OLE1" "OLE2" "OXYL" #' "PRPE" "PXYL" "RCHO" "TOLU" #' \item \strong{S11}: "ACET" "ACYL" "ALK1" "ALK2" "ALK3" "ALK4" "ALK5" #' "ARO1" "ARO2" "BALD" "BENZ" "CCHO" "ETHE" "HCHO" "IPRD" "MACR" #' "MEK" "OLE1" "OLE2" "RCHO" #' \item \strong{S11D}: "ACET" "ACRO" "ACYL" "ALLENE" "BALD" "BENZ" #' "BUTDE13" "BUTENE1" "C2BENZ" "C2BUTE" "C2PENT" "C4RCHO1" "CCHO" #' "CROTALD" "ETACTYL" "ETHANE" "ETHE" "HCHO" "HEXENE1" "ISOBUTEN" "M2C3" #' "M2C4" "M2C6" "M2C7" "M3C6" "M3C7" "MACR" "MEACTYL" "MEK" "MXYLENE" #' "NC1" "NC4" NC5" "NC6" "NC7" "NC8" "NC9" "OLE2" "OTH2" "OTH4" #' "OTH5" "OXYLENE" "PENTEN1" "PROPALD" "PROPANE" "PROPENE" "PXYLENE" "RCHO" #' "STYRENE" "TMB123" "TMB124" "TMB135" "TOLUENE" #' \item \strong{S16C}:"ACET" "ACETL" "ACRO" "ACYLS" "ALK3" #' "ALK4" "ALK5" "BALD" "BENZ" "BUT13" "BZ123" "BZ124" #' "BZ135" "C2BEN" "ETCHO" "ETHAN" "ETHEN" "HCHO" "MACR" #' "MECHO" "MEK" "MXYL" "NC4" "OLE1" #' "OLE2" "OLE3" "OLE4" "OLEA1" "OTH1" "OTH3" "OTH4" #' "OXYL" "PROP" "PROPE" "PXYL" "RCHO" "STYRS" "TOLU" #' \item \strong{S18B}:"ACET" "ACETL" "ACRO" "ACYLS" "ALK3" #' "ALK4" "ALK5" "BALD" "BENZ" "BUT13" "BZ123" "BZ124" #' "BZ135" "C2BEN" "ETCHO" "ETHAN" "ETHEN" "HCHO" #' "MACR" "MECHO" "MEK" "MXYL" "NC4" "OLE1" #' "OLE2" "OLE3" "OLE4" "OLEA1" "OTH1" "OTH3" "OTH4" "OXYL" #' "PROP" "PROPE" "PXYL" "RCHO" "STYRS" "TOLU" #'} #' @examples { #' id <-1:2 #' df <- data.frame(V1 = 1:2, V2 = 1:2) #' dx <- speciate(x = df, #' spec = "nmhc", #' fuel = "E25", #' veh = "LDV", #' eu = "Exhaust") #' dx$id <- rep(id, length(unique(dx$pol))) #' names(dx) #' vocE25EX <- emis_chem2(df = dx, #' mech = "CB05", #' nx = c("V1", "V2")) #' } emis_chem2 <- function(df, mech, nx, na.rm = FALSE) { chem <- sysdata$chem if(!any(grepl("id", names(df))))stop("Add 'id' column") id <- df$id if(missing(nx)) stop("Add colnames of emissions data") data.table::setDT(chem) pol <- mol<- NULL if(mech %in% c("CB05", "CB4", "CBMZ","CB05opt2")) { cheml <- suppressWarnings( data.table::melt( data = chem,#[pol %in% unique(df[["pol"]])], id.vars = c("ID", "pol", "Mwt"), measure.vars = grep(pattern = paste0(mech, "_"), x = names(chem), value = TRUE), # variable.name = "CB05", value.name = "mol", na.rm = TRUE, verbose = FALSE )) # cheml <- cheml[mol > 0] names(cheml)[4] <- "mech" names(cheml)[5] <- "factor" # if(verbose) print(head(cheml)) } else { # ..nd <- NULL # nd <- c("ID", "pol", "Mwt", mech, paste0("F", mech)) # cheml <- suppressWarnings(chem[pol %in% unique(df[["pol"]]), ..nd]) # names(cheml)[length(cheml)] <- "mol" # cheml <- cheml[!is.na(cheml[[mech]])] #TODO Check nd <- c("ID", "pol", "Mwt", mech, paste0("F", mech)) cheml <- chem[, nd, with = FALSE] names(cheml)[length(cheml) -1] <- "mech" names(cheml)[length(cheml) ] <- "factor" } # important # df$id <- rep(id, length(unique(df$pol))) data.table::setDF(df) data.table::setDF(cheml) y <- merge(x = df, y = cheml, by = "pol", all = T) # key! for(i in seq_along(nx)) { y[[nx[i]]] <- y[[nx[i]]]/y$Mwt*y$factor } data.table::setDT(y) y[["mech"]] <- gsub(pattern = mech, replacement = "", x = y[["mech"]]) y[["mech"]] <- gsub(pattern = "_", replacement = "", x = y[["mech"]]) id <- NULL dy <- y[, lapply(.SD, sum, na.rm = T), .SDcols = nx, by = list(id, group = mech)] data.table::setorderv(dy, c("group", "id")) group <- NULL if(na.rm) dy <- dy[!is.na(group)] # remove NA in id dy <- dy[!is.na(dy$id), ] return(dy) }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis_chem2.R
#' Estimation of cold start emissions hourly for the of the week #' #' @description \code{emis_cold} emissions are estimated as the product of the #' vehicles on a road, length of the road, emission factor evaluated at the #' respective speed. The estimation considers the beta parameter, the fraction of #' mileage driven #' #' @param veh "Vehicles" data-frame or list of "Vehicles" data-frame. Each data-frame #' as number of columns matching the age distribution of that type of vehicle. #' The number of rows is equal to the number of streets link #' @param lkm Length of each link #' @param ef List of functions of emission factors of vehicular categories #' @param efcold List of functions of cold start emission factors of vehicular categories #' @param beta Dataframe with the hourly cold-start distribution to each day #' of the period. Number of rows are hours and columns are days #' @param speed Speed data-frame with number of columns as hours #' @param agemax Age of oldest vehicles for that category #' @param profile Numerical or dataframe with nrows equal to 24 and ncol 7 day #' of the week #' @param simplify Logical; to determine if EmissionsArray should les dimensions, #' being streets, vehicle categories and hours or default (streets, vehicle #' categories, hours and days). Default is FALSE to avoid break old code, but #' the recommendation is that new estimations use this parameter as TRUE #' @param hour Number of considered hours in estimation #' @param day Number of considered days in estimation #' @param array Deprecated! \code{\link{emis_cold}} returns only arrays. #' When TRUE and veh is not a list, expects a profile as a dataframe producing #' an array with dimensions (streets x columns x hours x days) #' @param verbose Logical; To show more information #' @return EmissionsArray g/h #' @export #' @examples \dontrun{ #' # Do not run #' data(net) #' data(pc_profile) #' data(fe2015) #' data(fkm) #' data(pc_cold) #' pcf <- as.data.frame(cbind(pc_cold,pc_cold,pc_cold,pc_cold,pc_cold,pc_cold, #' pc_cold)) #' PC_G <- c(33491,22340,24818,31808,46458,28574,24856,28972,37818,49050,87923, #' 133833,138441,142682,171029,151048,115228,98664,126444,101027, #' 84771,55864,36306,21079,20138,17439, 7854,2215,656,1262,476,512, #' 1181, 4991, 3711, 5653, 7039, 5839, 4257,3824, 3068) #' veh <- data.frame(PC_G = PC_G) #' pc1 <- my_age(x = net$ldv, y = PC_G, name = "PC") #' pcw <- temp_fact(net$ldv+net$hdv, pc_profile) #' speed <- netspeed(pcw, net$ps, net$ffs, net$capacity, net$lkm, alpha = 1) #' pckm <- units::set_units(fkm[[1]](1:24), "km"); pckma <- cumsum(pckm) #' cod1 <- emis_det(po = "CO", cc = 1000, eu = "III", km = pckma[1:11]) #' cod2 <- emis_det(po = "CO", cc = 1000, eu = "I", km = pckma[12:24]) #' #vehicles newer than pre-euro #' co1 <- fe2015[fe2015$Pollutant=="CO", ] #24 obs!!! #' cod <- c(co1$PC_G[1:24]*c(cod1,cod2),co1$PC_G[25:nrow(co1)]) #' lef <- ef_ldv_scaled(co1, cod, v = "PC", cc = "<=1400", #' f = "G",p = "CO", eu=co1$Euro_LDV) #' # Mohtly average temperature 18 Celcius degrees #' lefec <- ef_ldv_cold_list(df = co1, ta = 18, cc = "<=1400", f = "G", #' eu = co1$Euro_LDV, p = "CO" ) #' lefec <- c(lefec,lefec[length(lefec)], lefec[length(lefec)], #' lefec[length(lefec)], lefec[length(lefec)], #' lefec[length(lefec)]) #' length(lefec) == ncol(pc1) #' #emis change length of 'ef' to match ncol of 'veh' #' class(lefec) #' PC_CO_COLD <- emis_cold(veh = pc1, #' lkm = net$lkm, #' ef = lef, #' efcold = lefec, #' beta = pcf, #' speed = speed, #' profile = pc_profile) #' class(PC_CO_COLD) #' plot(PC_CO_COLD) #' lpc <- list(pc1, pc1) #' PC_CO_COLDv2 <- emis_cold(veh = pc1, #' lkm = net$lkm, #' ef = lef, #' efcold = lefec, #' beta = pcf, #' speed = speed, #' profile = pc_profile, #' hour = 2, #' day = 1) #' } emis_cold <- function (veh, lkm, ef, efcold, beta, speed = 34, agemax = if (!inherits(x = veh, what = "list")) { ncol(veh) } else { ncol(veh[[1]]) }, profile, simplify = FALSE, hour = nrow(profile), day = ncol(profile), array = TRUE, verbose = FALSE) { # Check units if(!inherits(lkm, "units")){ stop("lkm neeeds to has class 'units' in 'km'. Please, check package 'units'") } if(units(lkm) == units(units::as_units("m"))){ stop("Units of lkm is 'm', change to 'km'") } if(units(lkm) == units(units::as_units("km"))) { lkm <- as.numeric(lkm) } # At least, on e of these if(any(!class(ef) %in% c("list", "units", "EmissionFactorsList", "EmissionFactors", "data.frame"))){ stop("ef must be either of 'list', 'units', 'EmissionFactorsList', 'EmissionFactors' or 'data.frame'") } # Checking sf if(inherits(veh, "sf")){ if(verbose) message("Transforming sf to data.frame") veh <- sf::st_set_geometry(veh, NULL) } lkm <- as.numeric(lkm) speed <- as.data.frame(speed) for (i in 1:ncol(speed) ) { speed[, i] <- as.numeric(speed[, i]) } # veh is "Vehicles" data-frame if (!inherits(x = veh, what = "list")) { veh <- as.data.frame(veh) lkm <- as.numeric(lkm) for(i in 1:ncol(veh)){ veh[,i] <- as.numeric(veh[,i]) } # top down if(missing(profile)){ stop("For top down approach, use 'emis_cold_td'") } if(!missing(profile) & is.vector(profile)){ profile <- matrix(profile, ncol = 1) } if(ncol(veh) != length(ef)){ if(verbose) message( paste0("Number of columns of 'veh' is different than length of 'ef'\n", "adjusting length of ef to the number of colums of 'veh'\n")) if(ncol(veh) > length(ef)){ for(i in (length(ef) + 1):ncol(veh) ){ # for(i in (ncol(veh) - length(ef)):ncol(veh) ){ ef[[i]] <- ef[[length(ef)]] } } else if (ncol(veh) < length(ef)){ ff <- list() for(i in 1:ncol(veh)){ ff[[i]] <- ef[[i]] } ef <- ff } } # if(array == F){ # lista <- lapply(1:day,function(j){ # lapply(1:hour,function(i){ # lapply(1:agemax, function(k){ # beta[i,j]*veh[, k]*profile[i,j]*lkm*ef[[k]](speed[, i])* # ifelse((efcold[[k]](speed[, i]) - 1) < 0, 0, # (efcold[[k]](speed[, i]) - 1)) # }) # }) # }) # return(EmissionsList(lista)) # } else { veh <- as.data.frame(veh) for(i in 1:ncol(veh)){ veh[,i] <- as.numeric(veh[,i]) } if(simplify) { d <- simplify2array( lapply(1:length(unlist(profile)) ,function(j){ # 7 dias simplify2array( lapply(1:agemax, function(k){ # categorias unlist(beta)[j]*veh[, k]*unlist(profile)[j]*lkm*ef[[k]](speed[, j])* ifelse((efcold[[k]](speed[, j])- 1) < 0, 0, (efcold[[k]](speed[, j]) - 1)) }) ) }) ) } else { d <- simplify2array( lapply(1:day,function(j){ simplify2array( lapply(1:hour,function(i){ simplify2array( lapply(1:agemax, function(k){ beta[i,j]*veh[, k]*profile[i,j]*lkm*ef[[k]](speed[, (1:nrow(profile))[i] + nrow(profile)*(j - 1)])* ifelse((efcold[[k]](speed[, (1:nrow(profile))[i] + nrow(profile)*(j - 1)]) - 1) < 0, 0, (efcold[[k]](speed[, (1:nrow(profile))[i] + nrow(profile)*(j - 1)]) - 1)) }) ) }) ) }) ) } if(verbose) message(round(sum(d, na.rm = TRUE)/1000,2), " kg emissions in ", hour, " hours and ", day, " days") return(EmissionsArray(d)) # } } else { if(ncol(veh[[1]]) != length(ef)){ if(verbose) message( paste0("Number of columns of 'veh' is different than length of 'ef'\n", "adjusting length of ef to the number of colums of 'veh'\n")) if(ncol(veh[[1]]) > length(ef)){ for(i in (length(ef) + 1):ncol(veh[[1]]) ){ ef[[i]] <- ef[[length(ef)]] } } else if (ncol(veh[[1]]) < length(ef)){ ff <- list() for(i in 1:ncol(veh[[1]])){ ff[[i]] <- ef[[i]] } ef <- ff } } for (j in 1:length(veh)) { for (i in 1:ncol(veh[[j]]) ) { veh[[j]][,i] <- as.numeric(veh[[j]][,i]) } } # if(array == F){ # lista <- lapply(1:length(veh),function(i){ # lapply(1:agemax, function(k){ # unlist(beta)[i]*veh[[i]][, k]*lkm*ef[[k]](speed[, i])* # ifelse((efcold[[k]](speed[, i]) - 1) < 0, 0, # (efcold[[k]](speed[, i]) - 1)) # }) }) # return(EmissionsList(lista)) # } else { d <- simplify2array( lapply(1:length(veh),function(i){ simplify2array( lapply(1:agemax, function(k){ unlist(beta)[i]*veh[[i]][, k]*lkm*ef[[k]](speed[, i])* ifelse((efcold[[k]](speed[, i]) - 1) < 0, 0, (efcold[[k]](speed[, i]) - 1)) }) ) }) ) if(verbose) message(round(sum(d, na.rm = TRUE)/1000,2), " kg emissions in ", hour, " hours and ", day, " days") return(EmissionsArray(d)) # } } }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis_cold.R
#' Estimation of cold start emissions with top-down approach #' #' @description \code{\link{emis_cold_td}} estimates cld start emissions with #' a top-down appraoch. This is, annual or monthly emissions or region. #' Especifically, the emissions are esitmated for row of the simple feature (row #' of the spatial feature). #' #' In general was designed so that each simple feature is a region with #' different average monthly temperature. #' This funcion, as other in this package, adapts to the class of the input data. #' providing flexibility to the user. #' #' @param veh "Vehicles" data-frame or spatial feature, wwhere columns are the #' age distribution of that vehicle. and rows each simple feature or region. #' The number of rows is equal to the number of streets link #' @param lkm Numeric; mileage by the age of use of each vehicle. #' @param ef Numeric; emission factor with #' @param efcold Data.frame. When it is a data.frame, each column is for each #' type of vehicle by age of use, rows are are each simple feature. When you have #' emission factors for each month, the order should a data.frame ina long format, #' as rurned by \code{\link{ef_ldv_cold}}. #' @param beta Data.frame with the fraction of cold starts. The rows are the fraction #' for each spatial feature or subregion, the columns are the age of use of vehicle. #' @param pro_month Numeric; montly profile to distribuite annual mileage in each month. #' @param params List of parameters; Add columns with information to returning data.frame #' @param verbose Logical; To show more information #' @param fortran Logical; to try the fortran calculation. #' @param nt Integer; Number of threads wich must be lower than max available. #' See \code{\link{check_nt}}. Only when fortran = TRUE #' @return Emissions data.frame #' @importFrom dotCall64 .C64 vector_dc #' @seealso \code{\link{ef_ldv_cold}} #' @export #' @examples #' \dontrun{ #' # Do not run #' veh <- age_ldv(1:10, agemax = 8) #' euros <- c("V", "V", "IV", "III", "II", "I", "PRE", "PRE") #' dt <- matrix(rep(2:25, 5), ncol = 12, nrow = 10) # 12 months, 10 rows #' row.names(dt) <- paste0("Simple_Feature_", 1:10) #' efc <- ef_ldv_cold(ta = dt, cc = "<=1400", f = "G", eu = euros, p = "CO", speed = Speed(34)) #' efh <- ef_ldv_speed( #' v = "PC", t = "4S", cc = "<=1400", f = "G", #' eu = euros, p = "CO", speed = Speed(runif(nrow(veh), 15, 40)) #' ) #' lkm <- units::as_units(18:11, "km") * 1000 #' cold_lkm <- cold_mileage(ltrip = units::as_units(20, "km"), ta = celsius(dt)) #' names(cold_lkm) <- paste0("Month_", 1:12) #' veh_month <- c(rep(8, 1), rep(10, 5), 9, rep(10, 5)) #' system.time( #' a <- emis_cold_td( #' veh = veh, #' lkm = lkm, #' ef = efh[1, ], #' efcold = efc[1:10, ], #' beta = cold_lkm[, 1], #' verbose = TRUE #' ) #' ) #' system.time( #' a2 <- emis_cold_td( #' veh = veh, #' lkm = lkm, #' ef = efh[1, ], #' efcold = efc[1:10, ], #' beta = cold_lkm[, 1], #' verbose = TRUE, #' fortran = TRUE #' ) #' ) # emistd2coldf.f95 #' a$emissions <- round(a$emissions, 8) #' a2$emissions <- round(a2$emissions, 8) #' identical(a, a2) #' #' # Adding parameters #' emis_cold_td( #' veh = veh, #' lkm = lkm, #' ef = efh[1, ], #' efcold = efc[1:10, ], #' beta = cold_lkm[, 1], #' verbose = TRUE, #' params = list( #' paste0("data_", 1:10), #' "moredata" #' ) #' ) #' system.time( #' aa <- emis_cold_td( #' veh = veh, #' lkm = lkm, #' ef = efh, #' efcold = efc, #' beta = cold_lkm, #' pro_month = veh_month, #' verbose = TRUE #' ) #' ) #' system.time( #' aa2 <- emis_cold_td( #' veh = veh, #' lkm = lkm, #' ef = efh, #' efcold = efc, #' beta = cold_lkm, #' pro_month = veh_month, #' verbose = TRUE, #' fortran = TRUE #' ) #' ) # emistd5coldf.f95 #' aa$emissions <- round(aa$emissions, 8) #' aa2$emissions <- round(aa2$emissions, 8) #' identical(aa, aa2) #' } emis_cold_td <- function(veh, lkm, ef, efcold, beta, pro_month, params, verbose = FALSE, fortran = FALSE, nt = ifelse(check_nt() == 1, 1, check_nt() / 2)) { # Check units if (!inherits(lkm,"units")) { stop("lkm neeeds to has class 'units' in 'km'. Please, check package '?units::set_units'") } if (units(lkm) == units(units::as_units("m"))) { stop("Units of lkm is 'm', change to 'km'") } if (units(lkm) == units(units::as_units("km"))) { lkm <- as.numeric(lkm) } if (length(lkm) != ncol(veh)) stop("Length of 'lkm' must be the as the number of columns of 'veh'") # Checking ef if (is.matrix(ef) | is.data.frame(ef)) { ef <- as.data.frame(ef) if (!inherits(ef[, 1], "units")) { stop("columns of ef must has class 'units' in 'g/km'. Please, check package '?units::set_units'") } if (units(ef[, 1]) != units(units::as_units("g/km"))) { stop("Units of ef must be 'g/km' ") } if (units(ef[, 1]) == units(units::as_units("g/km"))) { for (i in 1:ncol(veh)) { ef[, i] <- as.numeric(ef[, i]) } } } else { if (!inherits(ef, "units")) { stop("ef must has class 'units' in 'g/km'. Please, check package '?units::set_units'") } if (units(ef) != units(units::as_units("g/km"))) { stop("Units of ef must be 'g/km' ") } # if(units(ef)$numerator == "g" || units(ef)$denominator == "km"){ # not tested # ef <- as.numeric(ef) # } } # Checking ef cold if (!inherits(efcold[, 1], "units")) { stop("columns of efcold must has class 'units' in 'g/km'. Please, check package '?units::set_units'") } if (units(efcold[, 1]) != units(units::as_units("g/km"))) { stop("Units of efcold must be 'g/km' ") } if (units(efcold[, 1]) == units(units::as_units("g/km"))) { for (i in 1:ncol(veh)) { efcold[, i] <- as.numeric(efcold[, i]) } } # Checking veh for (i in 1:ncol(veh)) { veh[, i] <- as.numeric(veh[, i]) } # Checking sf if (inherits(veh, "sf")) { if (verbose) message("converting sf to data.frame") veh <- sf::st_set_geometry(veh, NULL) } # checking beta beta <- as.data.frame(beta) # pro_month if (!missing(pro_month)) { if (is.data.frame(pro_month) | is.matrix(pro_month)) { pro_month <- as.data.frame(pro_month) for (i in 1:nrow(pro_month)) { pro_month[i, ] <- pro_month[i, ] / sum(pro_month[i, ]) } } else if (is.numeric(pro_month)) { pro_month <- pro_month / sum(pro_month) } } # Checking pro_month if (!missing(pro_month)) { if (verbose) message("Estimation with monthly profile") if (length(pro_month) != 12) stop("Length of pro_month must be 12") mes <- ifelse(nchar(1:12) < 2, paste0(0, 1:12), 1:12) if (is.data.frame(ef)) { if (verbose) message("Assuming you have emission factors for each simple feature and then for each month") # when pro_month varies in each simple feature if (is.data.frame(pro_month)) { if (nrow(pro_month) == 1) { message("Replicating one-row matrix to match number of rows of `veh`") pro_month <- matrix(as.numeric(pro_month), nrow = nrow(veh), ncol = ncol(pro_month)) } if (fortran) { efcold$month <- rep(1:12, each = nrow(veh)) efcold <- split(efcold[, 1:ncol(veh)], efcold$month) efcold <- as.numeric(unlist(lapply(efcold, unlist))) nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) pmonth <- as.integer(ncol(pro_month)) lkm <- as.numeric(lkm) ef <- as.matrix(ef) month <- as.matrix(pro_month) beta <- as.matrix(beta) if (nrow(beta) != nrow(veh)) stop("number of rows of 'beta' and 'veh' must be equal") if (ncol(beta) != ncol(month)) stop("number of cols of 'beta' and 'month' must be equal") if (length(efcold) != length(unlist(veh)) * pmonth) stop("`efcold` and `veh` must be dimensionally compatible") if (length(lkm) != ncol(veh)) stop("length of `lkm` must be equal to number of columns of `veh`") if (nrow(ef) != nrow(veh)) stop("number of rows of `ef` and `veh` must be equal") if (ncol(ef) != ncol(veh)) stop("number of cols of `ef` and `veh` must be equal") if (nrow(month) != nrow(veh)) stop("number of rows of `month` and `veh` must be equal") # emis(i, j, k) = beta(i, k) * veh(i, j) * lkm(j) * ef(i, j) * efcold(i, j, k) * month(i, k) if (!missing(nt)) { if (nt >= check_nt()) { stop( "Your machine has ", check_nt(), " threads and nt must be lower" ) } if (verbose) message("Calling emistd4coldfpar.f95") a <- dotCall64::.C64( .NAME = "emistd4coldfpar", SIGNATURE = c( rep("integer", 3), rep("double", 6), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, efcold = efcold, beta = beta, month = month, nt = as.integer(nt), emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 10), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emistd4coldf.f95") a <- dotCall64::.C64( .NAME = "emistd4coldf", SIGNATURE = c( rep("integer", 3), rep("double", 7) ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, efcold = efcold, beta = beta, month = month, emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 9), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } e <- data.frame(emissions = a) e <- Emissions(e) e$rows <- rep(row.names(veh), ncolv * pmonth) e$age <- rep(rep(seq(1, ncolv), each = nrowv), pmonth) e$month <- rep(seq(1, pmonth), each = ncolv * nrowv) } else { efcold$month <- rep(1:12, each = nrow(veh)) efcold <- split(efcold, efcold$month) e <- do.call("rbind", lapply(1:12, function(k) { dfi <- unlist(lapply(1:ncol(veh), function(j) { beta[, k] * lkm[j] * veh[, j] * pro_month[, k] * ef[, j] * efcold[[k]][, j] })) dfi <- as.data.frame(dfi) names(dfi) <- "emissions" dfi <- Emissions(dfi) dfi$rows <- row.names(veh) dfi$age <- rep(1:ncol(veh), each = nrow(veh)) dfi$month <- (1:length(pro_month))[k] dfi })) } } else if (is.numeric(pro_month)) { if (fortran) { nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) pmonth <- as.integer(length(pro_month)) lkm <- as.numeric(lkm) ef <- as.matrix(ef[, 1:ncol(veh)]) efcold$month <- rep(1:12, each = nrow(veh)) efcold <- split(efcold[, 1:ncol(veh)], efcold$month) efcold <- as.numeric(unlist(lapply(efcold, unlist))) month <- as.numeric(pro_month) beta <- as.matrix(beta) if (nrow(beta) != nrow(veh)) stop("number of rows of 'beta' and 'veh' must be equal") if (ncol(beta) != length(month)) stop("number of cols of 'beta' length of 'month' must be equal") if (length(efcold) != length(unlist(veh)) * pmonth) stop("`efcold` and `veh` must be dimensionally compatible") if (length(lkm) != ncol(veh)) stop("length of `lkm` must be equal to number of columns of `veh`") if (nrow(ef) != nrow(veh)) stop("number of rows of `ef` and `veh` must be equal") if (ncol(ef) != ncol(veh)) stop("number of cols of `ef` and `veh` must be equal") # emis(i, j, k) = beta(i, k) * veh(i, j) * lkm(j) * ef(i, j) * efcold(i, j, k) * month(k) if (!missing(nt)) { if (nt >= check_nt()) { stop( "Your machine has ", check_nt(), " threads and nt must be lower" ) } if (verbose) message("Calling emistd5coldfpar.f95") a <- dotCall64::.C64( .NAME = "emistd5coldfpar", SIGNATURE = c( rep("integer", 3), rep("double", 6), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, ef = efcold, beta = beta, month = month, nt = as.integer(nt), emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 10), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emistd5coldf.f95") a <- dotCall64::.C64( .NAME = "emistd5coldf", SIGNATURE = c( rep("integer", 3), rep("double", 7) ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, ef = efcold, beta = beta, month = month, emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 9), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } e <- data.frame(emissions = a) e <- Emissions(e) e$rows <- rep(row.names(veh), ncolv * pmonth) e$age <- rep(rep(seq(1, ncolv), each = nrowv), pmonth) e$month <- rep(seq(1, pmonth), each = ncolv * nrowv) } else { efcold$month <- rep(1:12, each = nrow(veh)) efcold <- split(efcold, efcold$month) e <- do.call("rbind", lapply(1:12, function(k) { dfi <- unlist(lapply(1:ncol(veh), function(j) { beta[, k] * lkm[j] * veh[, j] * pro_month[k] * ef[, j] * efcold[[k]][, j] })) dfi <- as.data.frame(dfi) names(dfi) <- "emissions" dfi <- Emissions(dfi) dfi$rows <- row.names(veh) dfi$age <- rep(1:ncol(veh), each = nrow(veh)) dfi$month <- (1:length(pro_month))[k] dfi })) } } if (!missing(params)) { if (!is.list(params)) stop("'params' must be a list") if (is.null(names(params))) { if (verbose) message("Adding names to params") names(params) <- paste0("P_", 1:length(params)) } for (i in 1:length(params)) { e[, names(params)[i]] <- params[[i]] } } if (verbose) cat("Sum of emissions:", sum(e$emissions), "\n") } else { # ef inherits numeric if (verbose) message("Assuming you have emission factors for each simple feature and then for each month") # when pro_month vary each month if (is.data.frame(pro_month)) { if (nrow(pro_month) == 1) { message("Replicating one-row matrix to match number of rows of `veh`") pro_month <- matrix(as.numeric(pro_month), nrow = nrow(veh), ncol = ncol(pro_month)) } if (fortran) { nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) pmonth <- as.integer(ncol(pro_month)) lkm <- as.numeric(lkm) ef <- as.numeric(ef) efcold$month <- rep(1:12, each = nrow(veh)) efcold <- split(efcold[, 1:ncol(veh)], efcold$month) efcold <- as.numeric(unlist(lapply(efcold, unlist))) month <- as.matrix(pro_month) beta <- as.matrix(beta) if (nrow(beta) != nrow(veh)) stop("number of rows of 'beta' and 'veh' must be equal") if (ncol(beta) != ncol(month)) stop("number of cols of 'beta' and 'month' must be equal") if (length(efcold) != length(unlist(veh)) * pmonth) stop("`efcold` and `veh` must be dimensionally compatible") if (length(lkm) != ncol(veh)) stop("length of `lkm` must be equal to number of columns of `veh`") if (length(ef) != ncol(veh)) stop("length of `ef` and number of cols of `veh` must be equal") if (nrow(month) != nrow(veh)) stop("number of rows of `month` and `veh` must be equal") # emis(i, j, k) = beta(i, k) * veh(i, j) * lkm(j) * ef(j) * efcold(i, j, k) * month(i, k) if (!missing(nt)) { if (nt >= check_nt()) { stop( "Your machine has ", check_nt(), " threads and nt must be lower" ) } if (verbose) message("Calling emistd6coldfpar.f95") a <- dotCall64::.C64( .NAME = "emistd6coldfpar", SIGNATURE = c( rep("integer", 3), rep("double", 6), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, ef = efcold, beta = beta, month = month, nt = as.integer(nt), emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 10), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emistd6coldf.f95") a <- dotCall64::.C64( .NAME = "emistd6coldf", SIGNATURE = c( rep("integer", 3), rep("double", 7) ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, ef = efcold, beta = beta, month = month, emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 9), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } e <- data.frame(emissions = a) e <- Emissions(e) e$rows <- rep(row.names(veh), ncolv * pmonth) e$age <- rep(rep(seq(1, ncolv), each = nrowv), pmonth) e$month <- rep(seq(1, pmonth), each = ncolv * nrowv) } else { efcold$month <- rep(1:12, each = nrow(veh)) efcold <- split(efcold, efcold$month) e <- do.call("rbind", lapply(1:12, function(k) { dfi <- unlist(lapply(1:ncol(veh), function(j) { beta[, k] * lkm[j] * veh[, j] * pro_month[, k] * ef[j] * efcold[[k]][, j] })) dfi <- as.data.frame(dfi) names(dfi) <- "emissions" dfi <- Emissions(dfi) dfi$rows <- row.names(veh) dfi$age <- rep(1:ncol(veh), each = nrow(veh)) dfi$month <- (1:length(pro_month))[k] dfi })) } } else if (is.numeric(pro_month)) { if (fortran) { nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) pmonth <- as.integer(length(pro_month)) lkm <- as.numeric(lkm) ef <- as.numeric(ef) efcold <- split(efcold[, 1:ncol(veh)], efcold[ncol(efcold)]) efcold <- as.numeric(unlist(lapply(efcold, unlist))) month <- as.numeric(pro_month) beta <- as.matrix(beta) if (nrow(beta) != nrow(veh)) stop("number of rows of 'beta' and 'veh' must be equal") if (ncol(beta) != length(month)) stop("number of cols of 'beta' length of 'month' must be equal") if (length(efcold) != length(unlist(veh)) * pmonth) stop("`efcold` and `veh` must be dimensionally compatible") if (length(lkm) != ncol(veh)) stop("length of `lkm` must be equal to number of columns of `veh`") if (length(ef) != ncol(veh)) stop("number of rows of `ef` and `veh` must be equal") # emis(i, j, k) = beta(i, k) * veh(i, j) * lkm(j) * ef(j) * efcold(i, j, k) * month(k) if (!missing(nt)) { if (nt >= check_nt()) { stop( "Your machine has ", check_nt(), " threads and nt must be lower" ) } if (verbose) message("Calling emistd3coldfpar.f95") a <- dotCall64::.C64( .NAME = "emistd3coldfpar", SIGNATURE = c( rep("integer", 3), rep("double", 6), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, ef = efcold, beta = beta, month = month, nt = as.integer(nt), emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 10), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emistd3coldf.f95") a <- dotCall64::.C64( .NAME = "emistd3coldf", SIGNATURE = c( rep("integer", 3), rep("double", 7) ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, ef = efcold, beta = beta, month = month, emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 9), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } e <- data.frame(emissions = a) e <- Emissions(e) e$rows <- rep(row.names(veh), ncolv * pmonth) e$age <- rep(rep(seq(1, ncolv), each = nrowv), pmonth) e$month <- rep(seq(1, pmonth), each = ncolv * nrowv) } else { efcold$month <- rep(1:12, each = nrow(veh)) efcold <- split(efcold, efcold$month) e <- do.call("rbind", lapply(1:12, function(k) { dfi <- unlist(lapply(1:ncol(veh), function(j) { beta[, k] * lkm[j] * veh[, j] * pro_month[k] * ef[j] * efcold[[k]][, j] t })) dfi <- as.data.frame(dfi) names(dfi) <- "emissions" dfi <- Emissions(dfi) dfi$rows <- row.names(veh) dfi$age <- rep(1:ncol(veh), each = nrow(veh)) dfi$month <- (1:length(pro_month))[k] dfi })) } } if (!missing(params)) { if (!is.list(params)) stop("'params' must be a list") if (is.null(names(params))) { if (verbose) message("Adding names to params") names(params) <- paste0("P_", 1:length(params)) } for (i in 1:length(params)) { e[, names(params)[i]] <- params[[i]] } } if (verbose) cat("Sum of emissions:", sum(e$emissions), "\n") } } else { if (verbose) message("Estimation without monthly profile") if (fortran) { nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) lkm <- as.numeric(lkm) ef <- as.numeric(ef) efcold <- as.matrix(efcold[, 1:ncol(veh)]) beta <- as.numeric(unlist(beta)) if (length(beta) != nrow(veh)) stop("length of 'beta' and number of rows of 'veh' must be equal") if (nrow(efcold) != nrow(veh)) stop("number of rows of 'efcold' and 'veh' must be equal") if (ncol(efcold) != ncol(veh)) stop("number of cols of 'efcold' and 'veh' must be equal") if (length(lkm) != ncol(veh)) stop("length of `lkm` must be equal to number of columns of `veh`") if (length(ef) != ncol(veh)) stop("number of rows of `ef` and `veh` must be equal") # emis(i, j) = beta(i) * veh(i, j) * lkm(j) * ef(j) * efcold(i, j) if (!missing(nt)) { if (nt >= check_nt()) { stop( "Your machine has ", check_nt(), " threads and nt must be lower" ) } if (verbose) message("Calling emistd2coldfpar.f95") a <- dotCall64::.C64( .NAME = "emistd2coldfpar", SIGNATURE = c( rep("integer", 2), rep("double", 5), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, veh = as.matrix(veh), lkm = lkm, ef = ef, ef = efcold, beta = beta, nt = as.integer(nt), emis = dotCall64::vector_dc("double", nrowv * ncolv), INTENT = c( rep("r", 8), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emistd2coldf.f95") a <- dotCall64::.C64( .NAME = "emistd2coldf", SIGNATURE = c( rep("integer", 2), rep("double", 6) ), nrowv = nrowv, ncolv = ncolv, veh = as.matrix(veh), lkm = lkm, ef = ef, ef = efcold, beta = beta, emis = dotCall64::vector_dc("double", nrowv * ncolv), INTENT = c( rep("r", 7), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } e <- data.frame(emissions = a) e <- Emissions(e) e$rows <- rep(row.names(veh), ncolv) e$age <- rep(seq(1, ncolv), each = nrowv) } else { e <- unlist(lapply(1:ncol(veh), function(j) { unlist(beta) * as.numeric(lkm[j]) * veh[, j] * as.numeric(ef[j]) * as.numeric(efcold[, j]) })) e <- as.data.frame(e) names(e) <- "emissions" e <- Emissions(e) e$rows <- row.names(veh) e$age <- rep(1:ncol(veh), each = nrow(veh)) } if (!missing(params)) { if (!is.list(params)) stop("'params' must be a list") if (is.null(names(params))) { if (verbose) message("Adding names to params") names(params) <- paste0("P_", 1:length(params)) } for (i in 1:length(params)) { e[, names(params)[i]] <- params[[i]] } } if (verbose) cat("Sum of emissions:", sum(e$emissions), "\n") } return(e) }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis_cold_td.R
#' Determine deterioration factors for urban conditions #' #' @description \code{\link{emis_det}} returns deterioration factors. The emission #' factors comes from the guidelines for developing emission factors of the #' EMEP/EEA air pollutant emission inventory guidebook #' http://www.eea.europa.eu/themes/air/emep-eea-air-pollutant-emission-inventory-guidebook #' This function subset an internal database of emission factors with each argument #' #' @param po Character; Pollutant "CO", "NOx" or "HC" #' @param cc Character; Size of engine in cc covering "<=1400", "1400_2000" or ">2000" #' @param eu Character; Euro standard: "I", "II", "III", "III", "IV", "V", "VI", "VIc" #' @param speed Numeric; Speed to return Number of emission factor and not a function. #' It needs units in km/h #' @param km Numeric; accumulated mileage in km. #' @param verbose Logical; To show more information #' @param show.equation Option to see or not the equation parameters #' @return It returns a numeric vector representing the increase in emissions due to normal deterioring #' @keywords deterioration emission factors #' @note The deterioration factors functions are available for technologies #' euro "II", "III" and "IV". In order to cover all euro technologies, this #' function assumes that the deterioration function of "III" and "IV" applies #' for "V", "VI" and "VIc". However, as these technologies are relative #' new, accumulated milage is low and hence, deteerioration factors small. #' @export #' @examples \dontrun{ #' data(fkm) #' pckm <- fkm[[1]](1:24); pckma <- cumsum(pckm) #' km <- units::set_units(pckma[1:11], km) #' # length eu = length km = 1 #' emis_det(po = "CO", cc = "<=1400", eu = "III", km = km[5], show.equation = TRUE) #' # length eu = length km = 1, length speed > 1 #' emis_det(po = "CO", cc = "<=1400", eu = "III", km = km[5], speed = Speed(1:10)) #' # length km != length eu error #' # (cod1 <- emis_det(po = "CO", cc = "<=1400", eu = c("III", "IV"), speed = Speed(30), #' # km = km[4])) #' # length eu = 1 length km > 1 #' emis_det(po = "CO", cc = "<=1400", eu = "III", km = km) #' # length eu = 2, length km = 2 (if different length, error!) #' (cod1 <- emis_det(po = "CO", cc = "<=1400", eu = c("III", "IV"), km = km[4:5])) #' # length eu = 2, length km = 2, length speed > 1 #' (cod1 <- emis_det(po = "CO", cc = "<=1400", eu = c("III", "IV"), speed = Speed(0:130), #' km = km[4:5])) #' euros <- c("V","V","V", "IV", "IV", "IV", "III", "III", "III", "III") #' # length eu = 2, length km = 2, length speed > 1 #' (cod1 <- emis_det(po = "CO", cc = "<=1400", eu = euros, speed = Speed(1:100), #' km = km[1:10])) #' cod1 <- as.matrix(cod1[, 1:11]) #' filled.contour(cod1, col = cptcity::cpt(6277, n = 20)) #' filled.contour(cod1, col = cptcity::lucky(n = 19)) #' euro <- c(rep("V", 5), rep("IV", 5), "III") #' euros <- rbind(euro, euro) #' (cod1 <- emis_det(po = "CO", cc = "<=1400", eu = euros, km = km)) #' } emis_det <- function(po, cc, eu, speed = Speed(18.9), km, verbose = FALSE, show.equation = FALSE) { ldv_det <- sysdata$ldv_det # Check km if(!inherits(km, "units")){ stop("km neeeds to has class 'units' in 'km'. Please, check package '?units::set_units'") } if(units(km) == units(units::as_units("m"))){ stop("Units of km is 'm', change to 'km'") } if(units(km) == units(units::as_units("km"))) { km <- as.numeric(km) } #Check cc if(is.numeric(cc)){ cc <- ifelse(cc <= 1400, "<=1400", ifelse(cc >= 1400 & cc < 2000, "1400_2000", ">2000" )) } #Check eu if(is.matrix(eu) | is.data.frame(eu)){ eu <- as.data.frame(eu) for(i in 1:ncol(eu)) eu[, i] <- as.character(eu[, i]) } else { eu = as.character(eu) } if(!inherits(speed, "units")){ stop("speed neeeds to has class 'units' in 'km/h'. Please, check package '?units::set_units'") } if(units(speed) != units(units::as_units("km/h"))){ stop("Units of speed must be 'km/h' ") } if(units(speed) == units(units::as_units("km/h"))){ speed <- as.numeric(speed) } if(!is.data.frame(eu)){ if (any(eu %in% c("V", "VI", "VIc"))) { if (verbose) message("Assuming the same deterioration as euro III and IV") } if (length(eu) == 1 & length(km) == 1){ df <- ldv_det[ldv_det$POLLUTANT == po & ldv_det$CC == cc & ldv_det$EURO == eu, ] if (show.equation) { cat(paste0("b = ", df$b, ", c = ", df$c, ", MAX MC URBAN = ", df$d, ", \nf = ", df$f,", g = ", df$g , ", MAX MC ROAD = ", df$h, "\n")) cat("V < 19: MC_URBAN = b*km + c\n") cat("V >= 63: MC_ROAD = f*km + g\n") cat("19 <= V < 63: MC_URBAN + (V - 19)*(MC_ROAD - MC_URBAN)/44\n") } f1 <- function(V, km){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f; g <- df$g; h <- df$h MC_URBAN <- ifelse(km<a, b*km+c, d) MC_ROAD <- ifelse(km<e, f*km+g, h) ifelse( V<19, MC_URBAN, ifelse(V>63, MC_ROAD, MC_URBAN + (V - 19)*(MC_ROAD - MC_URBAN)/44)) } mc <- f1(V = speed, km = km) if(length(speed) > 1) { if(verbose) message("As speed has many values, this a data.frame") mc <- as.data.frame(mc) mc$speed <- Speed(speed) } return(mc) } else if(length(km) > 1 & length(eu) == 1){ if(length(eu) > length(km)) stop("length 'eu' cant be bigger than length 'km'") mc <- lapply(1:length(km), function(i){ df <- ldv_det[ldv_det$POLLUTANT == po & ldv_det$CC == cc & ldv_det$EURO == eu, ] f1 <- function(V, km){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f; g <- df$g; h <- df$h MC_URBAN <- ifelse(km<a, b*km+c, d) MC_ROAD <- ifelse(km<e, f*km+g, h) ifelse( V<19, MC_URBAN, ifelse(V>63, MC_ROAD, MC_URBAN + (V - 19)*(MC_ROAD - MC_URBAN)/44)) } ifelse(f1(V = speed, km = km[i]) < 1 , 1 , f1(V = speed, km = km[i])) }) if(length(speed) > 1) { if(verbose) message("As speed has many values, this a data.frame") mc <- do.call("cbind", mc) mc <- as.data.frame(mc) names(mc) <- paste0("km", 1:length(km)) mc$speed <- Speed(speed) } else { if(verbose) message("As speed has 1 value, this a vector") mc <- unlist(mc) } return(mc) } else if(length(km) > 1 & length(eu) > 1){ if(length(eu) != length(km)) stop("length 'eu' cant be bigger than length 'km'") mc <- lapply(1:length(km), function(i){ df <- ldv_det[ldv_det$POLLUTANT == po & ldv_det$CC == cc & ldv_det$EURO == eu[i], ] f1 <- function(V, km){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f; g <- df$g; h <- df$h MC_URBAN <- ifelse(km<a, b*km+c, d) MC_ROAD <- ifelse(km<e, f*km+g, h) ifelse( V<19, MC_URBAN, ifelse(V>63, MC_ROAD, MC_URBAN + (V - 19)*(MC_ROAD - MC_URBAN)/44)) } ifelse(f1(V = speed, km = km[i]) < 1 , 1 , f1(V = speed, km = km[i])) }) if(length(speed) > 1) { if(verbose) message("As speed has many values, this a data.frame") mc <- do.call("cbind", mc) mc <- as.data.frame(mc) names(mc) <- paste0("km", 1:length(km)) mc$speed <- Speed(speed) } else { if(verbose) message("As speed has 1 value, this a vector") mc <- unlist(mc) } return(mc) } else { # print("aqui") f1 <- function(V, km){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f; g <- df$g; h <- df$h MC_URBAN <- ifelse(km<a, b*km+c, d) MC_ROAD <- ifelse(km<e, f*km+g, h) ifelse( V<19, MC_URBAN, ifelse(V>63, MC_ROAD, MC_URBAN + (V - 19)*(MC_ROAD - MC_URBAN)/44)) } mc <- ifelse(f1(V = speed, km = km) <1, 1, f1(V = speed, km = km)) return(mc) if(length(speed) > 1) { if(verbose) message("As speed has many values, this a data.frame") mc <- do.call("cbind", mc) mc <- as.data.frame(mc) mc$speed <- Speed(speed) } else { if(verbose) message("As speed has 1 value, this a vector") mc <- unlist(mc) } } return(mc) } else if(is.data.frame(eu) & !is.data.frame(km)){ if(ncol(eu) != length(km)) stop("Length of km must be the same as number of columns of 'eu'") mc <- do.call("rbind", lapply(1:nrow(eu), function(j){ dff <- do.call("cbind", lapply(1:ncol(eu), function(i){ df <- ldv_det[ldv_det$POLLUTANT == po & ldv_det$CC == cc & ldv_det$EURO == eu[j,i], ] f1 <- function(V, km){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f; g <- df$g; h <- df$h MC_URBAN <- ifelse(km<a, b*km+c, d) MC_ROAD <- ifelse(km<e, f*km+g, h) ifelse( V<19, MC_URBAN, ifelse(V>63, MC_ROAD, MC_URBAN + (V - 19)*(MC_ROAD - MC_URBAN)/44)) } ifelse(f1(V = speed, km = km[i]) < 1 , 1 , f1(V = speed, km = km[i])) })) if(verbose) message("as 'eu' is a data.frame, this is a data.frame") dff <- as.data.frame(dff) dff$speed <- Speed(speed) dff })) return(mc) } else if(is.data.frame(eu) & is.data.frame(km)){ mc <- do.call("rbind", lapply(1:nrow(eu), function(j){ mc <- do.call("cbind", lapply(1:ncol(eu), function(i){ df <- ldv_det[ldv_det$POLLUTANT == po & ldv_det$CC == cc & ldv_det$EURO == eu[j,i], ] f1 <- function(V, km){ a <- df$a; b <- df$b; c <- df$c; d <- df$d; e <- df$e; f <- df$f; g <- df$g; h <- df$h MC_URBAN <- ifelse(km<a, b*km+c, d) MC_ROAD <- ifelse(km<e, f*km+g, h) ifelse( V<19, MC_URBAN, ifelse(V>63, MC_ROAD, MC_URBAN + (V - 19)*(MC_ROAD - MC_URBAN)/44)) } ifelse(f1(V = speed, km = km[i,j]) < 1 , 1 , f1(V = speed, km = km[i,j])) })) if(verbose) message("as 'eu' is a data.frame, this is a data.frame") mc <- as.data.frame(mc) mc$speed <- Speed(speed) })) return(mc) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis_det.R
#' Allocate emissions into spatial objects (street emis to grid) #' #' @description \code{\link{emis_dist}} allocates emissions proportionally to #' each feature. "Spatial" objects are converter to "sf" objects. Currently, #' 'LINESTRING' or 'MULTILINESTRING' supported. The emissions are distributed #' in each street. #' #' @param gy Numeric; a unique total (top-down) #' @param spobj A spatial dataframe of class "sp" or "sf". When class is "sp" #' it is transformed to "sf". #' @param pro Matrix or data-frame profiles, for instance, pc_profile. #' @param osm Numeric; vector of length 5, for instance, c(5, 3, 2, 1, 1). #' The first element covers 'motorway' and 'motorway_link. #' The second element covers 'trunk' and 'trunk_link'. #' The third element covers 'primary' and 'primary_link'. #' The fourth element covers 'secondary' and 'secondary_link'. #' The fifth element covers 'tertiary' and 'tertiary_link'. #' @param verbose Logical; to show more info. #' @importFrom sf st_sf st_as_sf st_length st_geometry_type st_set_geometry #' @importFrom units as_units #' @export #' @note When spobj is a 'Spatial' object (class of sp), they are converted #' into 'sf'. #' @examples \dontrun{ #' data(net) #' data(pc_profile) #' po <- 1000 #' t1 <- emis_dist(gy = po, spobj = net) #' head(t1) #' sum(t1$gy) #' #t1 <- emis_dist(gy = po, spobj = net, osm = c(5, 3, 2, 1, 1) ) #' t1 <- emis_dist(gy = po, spobj = net, pro = pc_profile) #' } emis_dist <- function(gy, spobj, pro, osm, verbose = FALSE){ net <- sf::st_as_sf(spobj) if(any( !unique(as.character( sf::st_geometry_type(net))) %in% c("LINESTRING", "MULTILINESTRING"))){ stop("Currently, geometries supported are 'LINESTRING' or 'MULTILINESTRING'") } net$lkm1 <- as.numeric(sf::st_length(net)) geo <- suppressMessages(suppressWarnings(sf::st_geometry(net))) lkm <- net$lkm1/sum(net$lkm1) e_street <- lkm*as.numeric(gy) # PROFILE SECTION if(missing(pro) & missing(osm)){ if(verbose) message("Selecting column geometry") net <- net[, "geometry"] net$emission <- e_street if(verbose) cat("Columns:", names(net), "\n") return(net) } if(!missing(pro) & missing(osm)){ pro <- pro/sum(pro) df <- as.data.frame(as.matrix(e_street) %*% matrix(unlist(pro), nrow = 1)) net <- sf::st_sf(df, geometry = geo) if(verbose) { cat(paste0("Columns: ",names(net),"\n")) } return(net) } if(missing(pro) & !missing(osm)){ if(!"highway" %in% names(net)) stop("Need OpenStreetMap network with colum highway") if(verbose) message("Selecting column highway") net <- net[,c("highway", "lkm1")] st <- c("motorway", "motorway_link", "trunk", "trunk_link", "primary", "primary_link", "secondary", "secondary_link", "tertiary", "tertiary_link") if(verbose) cat("Selecting:", st, "\n") net <- net[net$highway %in% st, ] # if(length(osm) != 5) stop("length of osm must be 5") osm <- osm/sum(osm) #motorway net_m <- net[net$highway %in% st[1:2], ] net_m$gy <- net_m$lkm1 / sum(net_m$lkm1) * gy * osm[1] #trunk net_t <- net[net$highway %in% st[3:4], ] net_t$gy <- net_t$lkm1 / sum(net_t$lkm1) * gy * osm[2] #primary net_p <- net[net$highway %in% st[5:6], ] net_p$gy <- net_p$lkm1 / sum(net_p$lkm1) * gy * osm[3] #secondary net_s <- net[net$highway %in% st[7:8], ] net_s$gy <- net_s$lkm1 / sum(net_s$lkm1) * gy * osm[4] #tertiary net_te <- net[net$highway %in% st[9:10], ] net_te$gy <- net_te$lkm1 / sum(net_te$lkm1) * gy * osm[5] net_all <- rbind(net_m, net_t, net_p, net_s, net_te) net_all <- net_all[, c("gy", "highway")] names(net_all) <- c("emission", "highway", "geometry") if(verbose) cat("Columns:", names(net_all), "\n") return(net_all) } if(!missing(pro) & !missing(osm)){ if(!"highway" %in% names(net)) stop("Need OpenStreetMap network with colum highway") if(verbose) message("Selecting column highway") net <- net[,c("highway", "lkm1")] st <- c("motorway", "motorway_link", "trunk", "trunk_link", "primary", "primary_link", "secondary", "secondary_link", "tertiary", "tertiary_link") if(verbose) cat("Selecting:", st, "\n") net <- net[net$highway %in% st, ] pro <- pro/sum(pro) # if(length(osm) != 5) stop("length of osm must be 5") osm <- osm/sum(osm) #motorway net_m <- net[net$highway %in% st[1:2], ] net_m$gy <- net_m$lkm1 / sum(net_m$lkm1) * gy * osm[1] #trunk net_t <- net[net$highway %in% st[3:4], ] net_t$gy <- net_t$lkm1 / sum(net_t$lkm1) * gy * osm[2] #primary net_p <- net[net$highway %in% st[5:6], ] net_p$gy <- net_p$lkm1 / sum(net_p$lkm1) * gy * osm[3] #secondary net_s <- net[net$highway %in% st[7:8], ] net_s$gy <- net_s$lkm1 / sum(net_s$lkm1) * gy * osm[4] #tertiary net_te <- net[net$highway %in% st[9:10], ] net_te$gy <- net_te$lkm1 / sum(net_te$lkm1) * gy * osm[5] net_all <- rbind(net_m, net_t, net_p, net_s, net_te) df <- as.data.frame(as.matrix(net_all$gy) %*% matrix(unlist(pro), nrow = 1)) df$highway <- net_all$highway net_all <- sf::st_sf(df, geometry = sf::st_geometry(net_all)) if(verbose) { cat("Columns: ", names(net_all), "\n") } return(net_all) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis_dist.R