content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' Emission calculation based on EMFAC emission factors #' #' @description \code{\link{emis_emfac}} estimates emissions based on #' an emission factors database from EMFAC.You must download the #' emission factors from EMFAC website. #' #' @param ef Character path to EMFAC ef (g/miles) #' @param veh Vehicles data.frame #' @param lkm Distance per street-link in miles #' @param speed Speed data.frame in niles/hour #' @param vehname numeric vector for heavy good vehicles or trucks #' @param pol character, "CO_RUNEX" #' @param modelyear numeric vector, 2021:1982 #' @param noyear newest numeric year to take out from ef #' @param hours Character, name of hours in speed, paste0("S", 1:24) data-frame profile for passenger cars, 24 hours only. #' @param vkm logical, to return vkm #' @param verbose logical, to show more information #' @return data.table with emission estimation in long format #' @export #' @examples \dontrun{ #' # do not run #' } emis_emfac <- function(ef, veh, lkm, speed, vehname, pol = "CO_RUNEX", modelyear = 2021:1982, noyear = 2022, hours = paste0("S", 1:24), vkm = TRUE, verbose = TRUE){ if(!inherits(lkm, "units")){ stop("lkm neeeds to has class 'units' in 'miles'. Please, check package 'units'") } if(units(lkm) == units(units::as_units("km"))){ stop("Units of lkm is 'km', change to 'miles'") } if(units(lkm) == units(units::as_units("miles"))) { lkm <- as.numeric(lkm) } if(!inherits(speed, "Speed")){ stop("speed neeeds to has class 'Speed' with col-units'miles/h'") } if(units(speed[, 1]) != units(units::as_units("miles/h"))){ stop("Units of speed must be 'miles/h' ") } if(units(speed[, 1]) == units(units::as_units("miles/h"))){ speed <- remove_units(speed) } # ef if(is.character(ef)) { ef <- ef_emfac(ef) } ModelYear <- NULL # estimation if(verbose) cat("Estimating emissions of", pol, " for", vehname, "\n") data.table::rbindlist(lapply(seq_along(hours), function(l) { data.table::rbindlist(lapply(seq_along(modelyear), function(k) { efx <- ef[ModelYear == modelyear[k]] breaks = unique(efx$Speed) interval <- findInterval(as.numeric(speed[[hours[l]]]), breaks) dfspeed <- data.table::data.table(Speed = breaks[interval]) # match Speed with real speed dfspeed <- merge(dfspeed, efx[, c("Speed", "gmiles"), with = F], by = "Speed", all.x = T) eeff <- EmissionFactors(dfspeed$gmiles, mass = "g", dist = "miles") vv <- Vehicles(as.numeric(veh[[k]]), time = "1/h") dx <- data.table::data.table(id = 1:length(eeff), emi = eeff*lkm* vv, age = k, vehicles = vehname, pollutant = pol, hour = l) if(vkm) { vkm <- data.table::data.table(id = 1:length(eeff), emi = lkm* vv, age = k, vehicles = vehname, pollutant = "vkm", hour = l) dx <- rbind(dx, vkm) } dx })) })) -> emii return(emii) }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis_emfac.R
#' Estimation of evaporative emissions #' #' @description \code{\link{emis_evap}} estimates evaporative emissions from #' EMEP/EEA emisison guidelines #' #' @param veh Numeric or data.frame of Vehicles with untis 'veh'. #' @param x Numeric which can be either, daily mileage by age of use #' with units 'lkm', number of trips or number of proc. When it #' has units 'lkm', all the emission factors must be in 'g/km'. #' When ed is in g/day, x it is the number of days (without units). #' When hotfi, hotc or warmc are in g/trip, x it is the number of trips (without units). #' When hotfi, hotc or warmc are in g/proced, x it is the number of proced (without units). #' @param ed average daily evaporative emissions. If x has units 'lkm', the units #' of ed must be 'g/km', other case, this are simply g/day (without units). #' @param hotfi average hot running losses or soak evaporative factor #' for vehicles with fuel injection and returnless fuel systems. #' If x has units 'lkm', the units of ed must be 'g/km', #' other case, this is simply g/trip or g/proced #' @param hotc average running losses or soak evaporative factor for vehicles with #' carburetor or fuel return system #' for vehicles with fuel injection and returnless fuel systems. #' If x has units 'lkm', the units of ed must be 'g/km', #' @param warmc average cold and warm running losses or soak evaporative factor #' for vehicles with carburetor or fuel return system #' for vehicles with fuel injection and returnless fuel systems. #' If x has units 'lkm', the units of ed must be 'g/km', #' @param carb fraction of gasoline vehicles with carburetor or fuel return system. #' @param p Fraction of trips finished with hot engine #' @param params Character; Add columns with information to returning data.frame #' @param pro_month Numeric; monthly profile to distribute annual mileage in each month. #' @param verbose Logical; To show more information #' @return numeric vector of emission estimation in grams #' @seealso \code{\link{ef_evap}} #' @importFrom units as_units #' @references Mellios G and Ntziachristos 2016. Gasoline evaporation. In: #' EEA, EMEP. EEA air pollutant emission inventory guidebook-2009. European #' Environment Agency, Copenhagen, 2009 #' @note When veh is a "Vehicles" data.frame, emission factors are evaluated till the #' number of columns of veh. For instance, if the length of the emission factor is 20 #' but the number of columns of veh is 10, the 10 first emission factors are used. #' #' @export #' @examples \dontrun{ #' (a <- Vehicles(1:10)) #' (lkm <- units::as_units(1:10, "km")) #' (ef <- EmissionFactors(1:10)) #' (ev <- emis_evap(veh = a, x = lkm, hotfi = ef)) #' } emis_evap <- function(veh, x, ed, hotfi, hotc, warmc, carb = 0, p, params, pro_month, verbose = FALSE) { # Check y # if(!missing(x)){ # if(units(x)$numerator == "km"){ # if(verbose) message('Emission factors must have units g/km') # } # } # Checking sf if(inherits(veh, "sf")){ if(verbose) message("converting sf to data.frame") veh <- sf::st_set_geometry(veh, NULL) } # Check x for data.frame if(is.data.frame(veh) ){ # DO I need check for 'Vehicles'? for(i in 1:ncol(veh)){ veh[,i] <- as.numeric(veh[, i]) } # in bottom-up approach, length of x is the number of streets # in top-down, length of x is the number of columns of veh # This is top-down } else { veh <- as.numeric(veh) } # 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) } } # ed if(!missing(ed)){ ed <- remove_units(ed) if(is.data.frame(veh)){ if(!is.data.frame(ed)) stop("as veh is a data.frame ed needs to be a data.frame") if(!missing(pro_month)){ 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) ed$month <- ed$month <- rep(1:12, each = nrow(veh)) ed <- split(ed, ed$month) if(is.data.frame(pro_month)){ e <- do.call("rbind", lapply(1:12, function(j){ e <- unlist(lapply(1:ncol(veh), function(i){ veh[, i]*x[i]*ed[[j]][, i]*pro_month[, 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)) e$month <- (1:length(pro_month))[j] e })) } else if(is.numeric(pro_month)){ e <- do.call("rbind", lapply(1:12, function(j){ e <- unlist(lapply(1:ncol(veh), function(i){ veh[, i]*x[i]*ed[[j]][, i]*pro_month[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)) e$month <- (1:length(pro_month))[j] e })) } if(verbose) cat("Sum of emissions:", sum(e$emissions), "\n") } else { if(!is.data.frame(ed)) stop("'ed' must be a data.frame") e <- as.data.frame(unlist(lapply(1:ncol(veh), function(i){ veh[, i]*x[i]*ed[, i] }))) names(e) <- "emissions" e <- Emissions(e) e$rows <- row.names(veh) e$age <- rep(1:ncol(veh), each = nrow(veh)) if(verbose) cat("Sum of emissions:", sum(e$emissions), "\n") } } else { e <- Emissions(veh*x*ed) if(verbose) cat("Sum of emissions:", sum(e), "\n") } } else { if(carb > 0){ if(is.data.frame(veh)){ if(!missing(pro_month)){ 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) warmc$month <- hotc$month <- rep(1:12, each = nrow(veh)) warmc <- split(warmc, warmc$month) hotc <- split(hotc, warmc$month) if(is.data.frame(pro_month)){ e <- do.call("rbind", lapply(1:12, function(j){ e <- unlist(lapply(1:ncol(veh), function(i){ veh[, i]*x[i]*(carb*(p*hotc[[j]][, i]+(1-p)*warmc[[j]][, i])+(1-carb)*hotfi[[j]][, i])*pro_month[, 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)) e$month <- (1:length(pro_month))[j] e })) } else if (is.numeric(pro_month)){ e <- do.call("rbind", lapply(1:12, function(j){ e <- unlist(lapply(1:ncol(veh), function(i){ veh[, i]*x[i]*(carb*(p*hotc[[j]][, i]+(1-p)*warmc[[j]][, i])+(1-carb)*hotfi[[j]][, i])*pro_month[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)) e$month <- (1:length(pro_month))[j] e })) } if(verbose) cat("Sum of emissions:", sum(e$emissions), "\n") } else { if(!is.data.frame(hotc)) stop("hotc' must be a data.frame") if(!is.data.frame(warmc)) stop("warmc' must be a data.frame") e <- unlist(lapply(1:ncol(veh), function(i){ veh[, i]*x[i]*(carb*(p*hotc[, i]+(1-p)*warmc[, i])+(1-carb)*hotfi[, i]) })) 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(verbose) cat("Sum of emissions:", sum(e$emissions), "\n") } } else { e <- veh*as.numeric(x)*(carb*(p*hotc+(1-p)*warmc)+(1-carb)*hotfi) e <- Emissions(e) } } else if (carb < 0){ stop("carb is a positive fraction or 0") } else { if(is.data.frame(veh)){ if(!missing(pro_month)){ 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) hotfi$month <- rep(1:12, each = nrow(veh)) hotfi <- split(hotfi, hotfi$month) if(is.data.frame(pro_month)){ e <- do.call("rbind", lapply(1:12, function(j){ e <- unlist(lapply(1:ncol(veh), function(i){ veh[, i]*x[i]*hotfi[[j]][, i]*pro_month[, 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)) e$month <- (1:length(pro_month))[j] e })) } else if (is.numeric(pro_month)){ e <- do.call("rbind", lapply(1:12, function(j){ e <- unlist(lapply(1:ncol(veh), function(i){ veh[, i]*x[i]*hotfi[[j]][, i]*pro_month[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)) e$month <- (1:length(pro_month))[j] e })) } if(verbose) cat("Sum of emissions:", sum(e$emissions), "\n") } else { if(!is.data.frame(hotfi)) stop("'hotfi' must be a data.frame") e <- as.data.frame(unlist("rbind",lapply(1:ncol(veh), function(i){ veh[, i]*x[i]*hotfi[, i] }))) names(e) <- "emissions" e <- Emissions(e) e$rows <- row.names(veh) e$age <- rep(1:ncol(veh), each = nrow(veh)) if (verbose) cat("Sum of emissions:", sum(e$emissions), "\n") } } else { e <- veh*x*hotfi } } } if(!missing(params)){ if(is.data.frame(e)){ for (i in 1:length(params)){ e[, names(params)[i]] <- params[[i]] } } else { for (i in 1:length(params)){ e <- as.data.frame(e) e[, names(params)[i]] <- params[[i]] } } } return(e) }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis_evap.R
#' Estimation of evaporative emissions 2 #' #' @description \code{emis_evap} performs the estimation of evaporative emissions #' from EMEP/EEA emission guidelines with Tier 2. #' #' @param veh Total number of vehicles by age of use. If is a list of 'Vehicles' #' data-frames, it will sum the columns of the eight element of the list #' representing the 8th hour. It was chosen this hour because it is morning rush #' hour but the user can adapt the data to this function #' @param name Character of type of vehicle #' @param size Character of size of vehicle #' @param fuel Character of fuel of vehicle #' @param aged Age distribution vector. E.g.: 1:40 #' @param nd4 Number of days with temperature between 20 and 35 Celsius degrees #' @param nd3 Number of days with temperature between 10 and 25 Celsius degrees #' @param nd2 Number of days with temperature between 0 and 15 Celsius degrees #' @param nd1 Number of days with temperature between -5 and 10 Celsius degrees #' @param hs_nd4 average daily hot-soak evaporative emissions for days with #' temperature between 20 and 35 Celsius degrees #' @param hs_nd3 average daily hot-soak evaporative emissions for days with #' temperature between 10 and 25 Celsius degrees #' @param hs_nd2 average daily hot-soak evaporative emissions for days with #' temperature between 0 and 15 Celsius degrees #' @param hs_nd1 average daily hot-soak evaporative emissions for days with #' temperature between -5 and 10 Celsius degrees #' @param rl_nd4 average daily running losses evaporative emissions for days with #' temperature between 20 and 35 Celsius degrees #' @param rl_nd3 average daily running losses evaporative emissions for days with #' temperature between 10 and 25 Celsius degrees #' @param rl_nd2 average daily running losses evaporative emissions for days with #' temperature between 0 and 15 Celsius degrees #' @param rl_nd1 average daily running losses evaporative emissions for days with #' temperature between -5 and 10 Celsius degrees #' @param d_nd4 average daily diurnal evaporative emissions for days with #' temperature between 20 and 35 Celsius degrees #' @param d_nd3 average daily diurnal evaporative emissions for days with #' temperature between 10 and 25 Celsius degrees #' @param d_nd2 average daily diurnal evaporative emissions for days with #' temperature between 0 and 15 Celsius degrees #' @param d_nd1 average daily diurnal evaporative emissions for days with #' temperature between -5 and 10 Celsius degrees #' @return dataframe of emission estimation in grams/days #' @references Mellios G and Ntziachristos 2016. Gasoline evaporation. In: #' EEA, EMEP. EEA air pollutant emission inventory guidebook-2009. European #' Environment Agency, Copenhagen, 2009 #' @export #' @examples \dontrun{ #' data(net) #' 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") #' ef1 <- ef_evap(ef = "erhotc",v = "PC", cc = "<=1400", dt = "0_15", ca = "no") #' dfe <- emis_evap2(veh = pc1, #' name = "PC", #' size = "<=1400", #' fuel = "G", #' aged = 1:ncol(pc1), #' nd4 = 10, #' nd3 = 4, #' nd2 = 2, #' nd1 = 1, #' hs_nd4 = ef1*1:ncol(pc1), #' hs_nd3 = ef1*1:ncol(pc1), #' hs_nd2 = ef1*1:ncol(pc1), #' hs_nd1 = ef1*1:ncol(pc1), #' d_nd4 = ef1*1:ncol(pc1), #' d_nd3 = ef1*1:ncol(pc1), #' d_nd2 = ef1*1:ncol(pc1), #' d_nd1 = ef1*1:ncol(pc1), #' rl_nd4 = ef1*1:ncol(pc1), #' rl_nd3 = ef1*1:ncol(pc1), #' rl_nd2 = ef1*1:ncol(pc1), #' rl_nd1 = ef1*1:ncol(pc1)) #' lpc <- list(pc1, pc1, pc1, pc1, #' pc1, pc1, pc1, pc1) #' dfe <- emis_evap2(veh = lpc, #' name = "PC", #' size = "<=1400", #' fuel = "G", #' aged = 1:ncol(pc1), #' nd4 = 10, #' nd3 = 4, #' nd2 = 2, #' nd1 = 1, #' hs_nd4 = ef1*1:ncol(pc1), #' hs_nd3 = ef1*1:ncol(pc1), #' hs_nd2 = ef1*1:ncol(pc1), #' hs_nd1 = ef1*1:ncol(pc1), #' d_nd4 = ef1*1:ncol(pc1), #' d_nd3 = ef1*1:ncol(pc1), #' d_nd2 = ef1*1:ncol(pc1), #' d_nd1 = ef1*1:ncol(pc1), #' rl_nd4 = ef1*1:ncol(pc1), #' rl_nd3 = ef1*1:ncol(pc1), #' rl_nd2 = ef1*1:ncol(pc1), #' rl_nd1 = ef1*1:ncol(pc1)) #' } emis_evap2 <- function(veh, name, size, fuel, aged, nd4, nd3, nd2, nd1, hs_nd4, hs_nd3, hs_nd2, hs_nd1, rl_nd4, rl_nd3, rl_nd2, rl_nd1, d_nd4, d_nd3, d_nd2, d_nd1) { if (inherits(veh, "list")){ veh <- colSums(veh[[8]]) } else { veh <- colSums(veh) } df <- data.frame(name = rep(name, max(aged)*4*3), size = rep(size, max(aged)*4*3), age = rep(aged, 4*3), evaporative = c(rep("Hot Soak", 4*max(aged)), rep("Running Losses", 4*max(aged)), rep("Diurnal", 4*max(aged))), g = c(hs_nd4, hs_nd3, hs_nd2, hs_nd1, rl_nd4, rl_nd3, rl_nd2, rl_nd1, d_nd4, d_nd3, d_nd2, d_nd1)*veh, days = rep(c(rep(nd4,max(aged)), rep(nd3,max(aged)), rep(nd2,max(aged)), rep(nd1,max(aged))),3), Temperature = rep(c(rep("20_35",max(aged)), rep("10_25",max(aged)), rep("0_10",max(aged)), rep("-5_10",max(aged))),3)) message(paste0("Evaporative NMHC emissions of ", name, "_", size, " are ", round(sum(df$g*df$days, na.rm = T)/1000000,2), " t/(time-lapse)")) return(df) }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis_evap2.R
#' Allocate emissions into a grid returning point emissions or flux #' #' @description \code{\link{emis_grid}} allocates emissions proportionally to each grid #' cell. The process is performed by the intersection between geometries and the grid. #' It means that requires "sr" according to your location for the projection. #' It is assumed that spobj is a Spatial*DataFrame or an "sf" with the pollutants #' in data. This function returns an object of class "sf". #' #' It is #' #' @param spobj A spatial dataframe of class "sp" or "sf". When class is "sp" #' it is transformed to "sf". #' @param g A grid with class "SpatialPolygonsDataFrame" or "sf". #' @param sr Spatial reference e.g: 31983. It is required if spobj and g are #' not projected. Please, see http://spatialreference.org/. #' @param type type of geometry: "lines", "points" or "polygons". #' @param FN Character indicating the function. Default is "sum" #' @param flux Logical, if TRUE, it return flux (mass / area / time (implicit)) #' in a polygon grid, if false, mass / time (implicit) as points, in a similar fashion #' as EDGAR provide data. #' @param k Numeric to multiply emissions #' @importFrom sf st_sf st_dimension st_transform st_length st_cast st_intersection st_area st_geometry #' @importFrom data.table data.table .SD #' @export #' @note \strong{1) If flux = TRUE (default), emissions are flux = mass / area / time (implicit), as polygons.} #' \strong{If flux = FALSE, emissions are mass / time (implicit), as points.} #' \strong{Time untis are not displayed because each use can have different time units} #' \strong{for instance, year, month, hour second, etc.} #' #' \strong{2) Therefore, it is good practice to have time units in 'spobj'. } #' \strong{This implies that spobj MUST include units!. } #' #' \strong{3) In order to check the sum of the emissions, you must calculate the grid-area} #' \strong{in km^2 and multiply by each column of the resulting emissions grid, and then sum.} #' #' #' \strong{4) If FN = "sum", is mass conservative!. } #' @examples \dontrun{ #' data(net) #' g <- make_grid(net, 1/102.47/2) #500m in degrees #' names(net) #' netsf <- sf::st_as_sf(net) #' netg <- emis_grid(spobj = netsf[, c("ldv", "hdv")], g = g, sr= 31983) #' plot(netg["ldv"], #' axes = TRUE, #' graticule = TRUE, #' bg = "black", #' lty = 0) #' g <- sf::st_make_grid(net, 1/102.47/2, square = FALSE) #500m in degrees #' g <- st_sf(i =1, geometry = g) #' netg <- emis_grid(spobj = netsf[, c("ldv", "hdv")], g = g, sr= 31983) #' plot(netg["ldv"], #' axes = TRUE, #' graticule = TRUE, #' bg = "black", #' lty = 0) #' plot(netg["hdv"], axes = TRUE) #' netg <- emis_grid(spobj = netsf[, c("ldv", "hdv")], g = g, sr= 31983, FN = "mean") #' plot(netg["ldv"], axes = TRUE) #' plot(netg["hdv"], axes = TRUE) #' netg <- emis_grid(spobj = netsf[, c("ldv", "hdv")], g = g, sr= 31983, flux = FALSE) #' plot(netg["ldv"], #' axes = TRUE, #' pch = 16, #' pal = cptcity::cpt(colorRampPalette= TRUE, #' rev = TRUE), #' cex = 3) #' } emis_grid <- function (spobj = net, g, sr, type = "lines", FN = "sum", flux = TRUE, k = 1){ net <- sf::st_as_sf(spobj) net$id <- NULL # add as.data.frame when net comes from data.table netdata <- as.data.frame(sf::st_set_geometry(net, NULL)) if(!inherits(netdata[[1]], "units")) { message("Your data has no units") hasunits <- FALSE } else { message("Your units are: ") hasunits <- TRUE uninet <- units(netdata[[1]]) message(uninet) } for (i in 1:length(netdata)) { netdata[, i] <- as.numeric(netdata[, i]) } net <- sf::st_sf(netdata, geometry = sf::st_geometry(net)) g <- sf::st_as_sf(g) g$id <- 1:nrow(g) if (!missing(sr)) { "+init=epsg:31983" if (inherits(sr, "character")) { sr <- as.numeric(substr(sr, 12, nchar(sr))) } message("Transforming spatial objects to 'sr' ") net <- sf::st_transform(net, sr) g <- sf::st_transform(g, sr) } #lines #### if (type %in% c("lines", "line")) { net <- net[, grep(pattern = TRUE, x = sapply(net, is.numeric))] netdf <- sf::st_set_geometry(net, NULL) snetdf <- sum(netdf, na.rm = TRUE) ncolnet <- ncol(netdf) namesnet <- names(netdf) cat(paste0("Sum of street emissions ", round(snetdf, 2), "\n")) net$LKM <- sf::st_length(net) netg <- suppressMessages(suppressWarnings(sf::st_intersection(net, g))) netg$LKM2 <- sf::st_length(netg) xgg <- data.table::data.table(netg) xgg[, 1:ncolnet] <- xgg[, 1:ncolnet] * as.numeric(xgg$LKM2/xgg$LKM) xgg[is.na(xgg)] <- 0 dfm <- xgg[, lapply(.SD, eval(parse(text = FN)), na.rm = TRUE), by = "id", .SDcols = namesnet] id <- dfm$id dfm$id <- NULL area <- sf::st_area(g) area <- units::set_units(area, "km^2") for(i in 1:ncol(dfm)) dfm[[i]] <- dfm[[i]]*k if(FN == "sum") dfm <- dfm * snetdf/sum(dfm, na.rm = TRUE) dfm$id <- id gx <- data.frame(id = g$id) gx <- merge(gx, dfm, by = "id", all = TRUE) gx[is.na(gx)] <- 0 if(flux) { for(i in seq_along(namesnet)) { if(hasunits) units(gx[[namesnet[i]]]) <- uninet gx[[namesnet[i]]] <- gx[[namesnet[i]]]/area # ! } cat(paste0("Sum of gridded emissions ", round(sum(gx[namesnet]*remove_units(area)),2), "\n")) gx <- sf::st_sf(gx, geometry = g$geometry) return(gx) } else { for(i in seq_along(namesnet)) { if(hasunits) units(gx[[namesnet[i]]]) <- uninet } cat(paste0("Sum of gridded emissions ", round(sum(gx[namesnet]),2), "\n")) gx <- sf::st_sf(gx, geometry = g$geometry) gx <- suppressMessages(suppressWarnings(sf::st_centroid(gx))) return(gx) } #points#### } else if (type %in% c("points", "point")) { netdf <- sf::st_set_geometry(net, NULL) snetdf <- sum(netdf, na.rm = TRUE) cat(paste0("Sum of point emissions ", round(snetdf, 2), "\n")) ncolnet <- ncol(netdf) namesnet <- names(netdf) xgg <- data.table::data.table(sf::st_set_geometry(suppressMessages(suppressWarnings(sf::st_intersection(net, g))), NULL)) xgg[is.na(xgg)] <- 0 dfm <- xgg[, lapply(.SD, eval(parse(text = FN)), na.rm = TRUE), by = "id", .SDcols = namesnet] id <- dfm$id dfm$id <- NULL area <- sf::st_area(g) area <- units::set_units(area, "km^2") for(i in 1:ncol(dfm)) dfm[[i]] <- dfm[[i]]*k if(FN == "sum") dfm <- dfm * snetdf/sum(dfm, na.rm = TRUE) dfm$id <- id gx <- data.frame(id = g$id) gx <- merge(gx, dfm, by = "id", all = TRUE) gx[is.na(gx)] <- 0 if(flux) { for(i in seq_along(namesnet)) { if(hasunits) units(gx[[namesnet[i]]]) <- uninet gx[[namesnet[i]]] <- gx[[namesnet[i]]]/area # ! } cat(paste0("Sum of gridded emissions ", round(sum(gx[namesnet]*remove_units(area)),2), "\n")) gx <- sf::st_sf(gx, geometry = g$geometry) return(gx) } else { for(i in seq_along(namesnet)) { if(hasunits) units(gx[[namesnet[i]]]) <- uninet } cat(paste0("Sum of gridded emissions ", round(sum(gx[namesnet]),2), "\n")) gx <- sf::st_sf(gx, geometry = g$geometry) gx <- suppressMessages(suppressWarnings(sf::st_centroid(gx))) return(gx) } #polygons #### } else if(type %in% c("polygons", "polygon", "area")){ netdf <- sf::st_set_geometry(net, NULL) snetdf <- sum(netdf, na.rm = TRUE) cat(paste0("Sum of point emissions ", round(snetdf, 2), "\n")) ncolnet <- ncol(netdf) net <- net[, grep(pattern = TRUE, x = sapply(net, is.numeric))] namesnet <- names(netdf) net$area1 <- sf::st_area(net) netg <- suppressMessages(suppressWarnings(sf::st_intersection(net, g))) netg$area2 <- sf::st_area(netg) xgg <- data.table::data.table(netg) xgg[, 1:ncolnet] <- xgg[, 1:ncolnet] * as.numeric(xgg$area2/xgg$area1) xgg[is.na(xgg)] <- 0 dfm <- xgg[, lapply(.SD, eval(parse(text = FN)), na.rm = TRUE), by = "id", .SDcols = namesnet] id <- dfm$id dfm$id <- NULL area <- sf::st_area(g) area <- units::set_units(area, "km^2") for(i in 1:ncol(dfm)) dfm[[i]] <- dfm[[i]]*k if(FN == "sum") dfm <- dfm * snetdf/sum(dfm, na.rm = TRUE) cat(paste0("Sum of gridded emissions ", round(sum(dfm, na.rm = T), 2), "\n")) dfm$id <- id gx <- data.frame(id = g$id) gx <- merge(gx, dfm, by = "id", all = TRUE) gx[is.na(gx)] <- 0 if(flux) { for(i in seq_along(namesnet)) { if(hasunits) units(gx[[namesnet[i]]]) <- uninet gx[[namesnet[i]]] <- gx[[namesnet[i]]]/area # ! } cat(paste0("Sum of gridded emissions ", round(sum(gx[namesnet]*remove_units(area)),2), "\n")) gx <- sf::st_sf(gx, geometry = g$geometry) return(gx) } else { for(i in seq_along(namesnet)) { if(hasunits) units(gx[[namesnet[i]]]) <- uninet } cat(paste0("Sum of gridded emissions ", round(sum(gx[namesnet]),2), "\n")) gx <- sf::st_sf(gx, geometry = g$geometry) gx <- suppressMessages(suppressWarnings(sf::st_centroid(gx))) return(gx) } } }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis_grid.R
#' Estimation of hot exhaust emissions with a top-down approach #' #' @description \code{\link{emis_hot_td}} estimates cold start emissions with #' a top-down appraoch. This is, annual or monthly emissions or region. #' Especifically, the emissions are estimated for the 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 function, as others in this package, adapts to the class of the input data. #' providing flexibility to the user. #' #' @param veh "Vehicles" data-frame or spatial feature, where columns are the #' age distribution of that vehicle. and rows each simple feature or region. #' @param lkm Numeric; mileage by the age of use of each vehicle. #' @param ef Numeric or data.frame; emission factors. When it is a data.frame #' number of rows can be for each region, or also, each region repeated #' along 12 months. For instance, if you have 10 regions the number #' of rows of ef can also be 120 (10 * 120). #' when you have emission factors that varies with month, see \code{\link{ef_china}}. #' @param pro_month Numeric or data.frame; monthly profile to distribute annual mileage #' in each month. When it is a data.frame, each region (row) can have a different #' monthly profile. #' @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 which must be lower than max available. See \code{\link{check_nt}}. #' Only when fortran = TRUE #' @importFrom dotCall64 .C64 vector_dc #' @return Emissions data.frame #' @seealso \code{\link{ef_ldv_speed}} \code{\link{ef_china}} #' @export #' @details List to make easier to use this function. #' \enumerate{ #' \item{`pro_month` is data.frame AND rows of `ef` and `veh` are equal.} #' \item{`pro_month` is numeric AND rows of `ef` and `veh` are equal.} #' \item{`pro_month` is data.frame AND rows of `ef` is 12X rows of `veh`.} #' \item{`pro_month` is numeric AND rows of `ef` is 12X rows of `veh`.} #' \item{`pro_month` is data,frame AND class of `ef` is 'units'.} #' \item{`pro_month` is numeric AND class of `ef` is 'units'.} #' \item{NO `pro_month` AND class of `ef` is 'units'.} #' \item{NO `pro_month` AND `ef` is data.frame.} #' \item{`pro_month` is numeric AND rows of `ef` is 12 (monthly `ef`).} #' } #' @examples #' \dontrun{ #' # Do not run #' euros <- c("V", "V", "IV", "III", "II", "I", "PRE", "PRE") #' efh <- ef_ldv_speed( #' v = "PC", t = "4S", cc = "<=1400", f = "G", #' eu = euros, p = "CO", speed = Speed(34) #' ) #' lkm <- units::as_units(c(20:13), "km") * 1000 #' veh <- age_ldv(1:10, agemax = 8) #' system.time( #' a <- emis_hot_td( #' veh = veh, #' lkm = lkm, #' ef = EmissionFactors(as.numeric(efh[, 1:8])), #' verbose = TRUE #' ) #' ) #' system.time( #' a2 <- emis_hot_td( #' veh = veh, #' lkm = lkm, #' ef = EmissionFactors(as.numeric(efh[, 1:8])), #' verbose = TRUE, #' fortran = TRUE #' ) #' ) # emistd7f.f95 #' identical(a, a2) #' #' # adding columns #' emis_hot_td( #' veh = veh, #' lkm = lkm, #' ef = EmissionFactors(as.numeric(efh[, 1:8])), #' verbose = TRUE, #' params = list(paste0("data_", 1:10), "moredata") #' ) #' #' # monthly profile (numeric) with numeric ef #' veh_month <- c(rep(8, 1), rep(10, 5), 9, rep(10, 5)) #' system.time( #' aa <- emis_hot_td( #' veh = veh, #' lkm = lkm, #' ef = EmissionFactors(as.numeric(efh[, 1:8])), #' pro_month = veh_month, #' verbose = TRUE #' ) #' ) #' system.time( #' aa2 <- emis_hot_td( #' veh = veh, #' lkm = lkm, #' ef = EmissionFactors(as.numeric(efh[, 1:8])), #' pro_month = veh_month, #' verbose = TRUE, #' fortran = TRUE #' ) #' ) # emistd5f.f95 #' aa$emissions <- round(aa$emissions, 8) #' aa2$emissions <- round(aa2$emissions, 8) #' identical(aa, aa2) #' #' # monthly profile (numeric) with data.frame ef #' veh_month <- c(rep(8, 1), rep(10, 5), 9, rep(10, 5)) #' def <- matrix(EmissionFactors(as.numeric(efh[, 1:8])), #' nrow = nrow(veh), ncol = ncol(veh), byrow = TRUE #' ) #' def <- EmissionFactors(def) #' system.time( #' aa <- emis_hot_td( #' veh = veh, #' lkm = lkm, #' ef = def, #' pro_month = veh_month, #' verbose = TRUE #' ) #' ) #' system.time( #' aa2 <- emis_hot_td( #' veh = veh, #' lkm = lkm, #' ef = def, #' pro_month = veh_month, #' verbose = TRUE, #' fortran = TRUE #' ) #' ) # emistd1f.f95 #' aa$emissions <- round(aa$emissions, 8) #' aa2$emissions <- round(aa2$emissions, 8) #' identical(aa, aa2) #' #' # monthly profile (data.frame) #' dfm <- matrix(c(rep(8, 1), rep(10, 5), 9, rep(10, 5)), #' nrow = 10, ncol = 12, #' byrow = TRUE #' ) #' system.time( #' aa <- emis_hot_td( #' veh = veh, #' lkm = lkm, #' ef = EmissionFactors(as.numeric(efh[, 1:8])), #' pro_month = dfm, #' verbose = TRUE #' ) #' ) #' system.time( #' aa2 <- emis_hot_td( #' veh = veh, #' lkm = lkm, #' ef = EmissionFactors(as.numeric(efh[, 1:8])), #' pro_month = dfm, #' verbose = TRUE, #' fortran = TRUE #' ) #' ) # emistd6f.f95 #' aa$emissions <- round(aa$emissions, 2) #' aa2$emissions <- round(aa2$emissions, 2) #' identical(aa, aa2) #' #' # Suppose that we have a EmissionsFactor data.frame with number of rows for each month #' # number of rows are 10 regions #' # number of columns are 12 months #' tem <- runif(n = 6 * 10, min = -10, max = 35) #' temp <- c(rev(tem[order(tem)]), tem[order(tem)]) #' plot(temp) #' dftemp <- celsius(matrix(temp, ncol = 12)) #' dfef <- ef_evap( #' ef = c(rep("eshotfi", 8)), #' v = "PC", #' cc = "<=1400", #' dt = dftemp, #' show = F, #' ca = "small", #' ltrip = units::set_units(10, km), #' pollutant = "NMHC" #' ) #' dim(dfef) # 120 rows and 9 columns, 8 ef (g/km) and 1 for month #' system.time( #' aa <- emis_hot_td( #' veh = veh, #' lkm = lkm, #' ef = dfef, #' pro_month = veh_month, #' verbose = TRUE #' ) #' ) #' system.time( #' aa2 <- emis_hot_td( #' veh = veh, #' lkm = lkm, #' ef = dfef, #' pro_month = veh_month, #' verbose = TRUE, #' fortran = TRUE #' ) #' ) # emistd3f.f95 #' aa$emissions <- round(aa$emissions, 2) #' aa2$emissions <- round(aa2$emissions, 2) #' identical(aa, aa2) #' plot(aggregate(aa$emissions, by = list(aa$month), sum)$x) #' #' # Suppose that we have a EmissionsFactor data.frame with number of rows for each month #' # monthly profile (data.frame) #' system.time( #' aa <- emis_hot_td( #' veh = veh, #' lkm = lkm, #' ef = dfef, #' pro_month = dfm, #' verbose = TRUE #' ) #' ) #' system.time( #' aa2 <- emis_hot_td( #' veh = veh, #' lkm = lkm, #' ef = dfef, #' pro_month = dfm, #' verbose = TRUE, #' fortran = TRUE #' ) #' ) # emistd4f.f95 #' aa$emissions <- round(aa$emissions, 8) #' aa2$emissions <- round(aa2$emissions, 8) #' identical(aa, aa2) #' plot(aggregate(aa$emissions, by = list(aa$month), sum)$x) #' } emis_hot_td <- function(veh, lkm, ef, pro_month, params, verbose = FALSE, fortran = FALSE, nt = ifelse(check_nt() == 1, 1, check_nt() / 2)) { # Checking sf if (inherits(veh, "sf")) { if (verbose) message("converting sf to data.frame") veh <- sf::st_set_geometry(veh, NULL) } # Checking veh for (i in 1:ncol(veh)) { veh[, i] <- as.numeric(veh[, i]) } # 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' ") } 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 ?EmissionFactors") } if (units(ef[, 1])$numerator == "g" | units(ef[, 1])$denominator == "km") { for (i in 1:ncol(veh)) { ef[, i] <- as.numeric(ef[, i]) } } # When row = 1, transform to vector. if (nrow(ef) == 1) { if (verbose) message("Transforming 1 row data.frame into numeric") ef <- as.numeric(ef) } } else { if (!inherits(ef, "units")) { stop("ef must has class 'units' in 'g/km'. Please, check ?EmissionFactors") } if (units(ef)$numerator == "g" | units(ef)$denominator == "km") { ef <- as.numeric(ef) } } # 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) & nrow(ef) == nrow(veh)) { if (verbose) message("'pro_month' is data.frame and number of rows of 'ef' and 'veh' are equal") 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 (nrow(ef) != nrow(veh)) stop("Number of rows of 'veh' and 'ef' must be equal") if (ncol(ef) != ncol(veh)) stop("Number of cols of `ef` and `veh` must be equal") if (length(lkm) != ncol(veh)) stop("Length of `lkm` must be equal to number of columns of `veh`") if (nrow(pro_month) != nrow(veh)) stop("Number of rows of `month` and `veh` must be equal") if (fortran) { nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) pmonth <- as.integer(ncol(pro_month)) lkm <- as.numeric(lkm) ef <- as.matrix(ef[, 1:ncol(veh)]) month <- as.matrix(pro_month) # emis(i, j, k) = veh(i, j) * lkm(j) * ef(i, j)*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 emistd2fpar.f95") a <- dotCall64::.C64( .NAME = "emistd2fpar", SIGNATURE = c( rep("integer", 3), rep("double", 4), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, month = month, nt = as.integer(nt), emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 8), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emistd2f.f95") a <- dotCall64::.C64( .NAME = "emistd2f", SIGNATURE = c( rep("integer", 3), rep("double", 5) ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, month = month, emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), 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), each = ncolv * pmonth) # i e$age <- rep(seq(1, ncolv), nrowv * pmonth) # j e$month <- rep(seq(1, pmonth), ncolv * nrowv) # k } else { e <- do.call("rbind", lapply(1:12, function(k) { dfi <- unlist(lapply(1:ncol(veh), function(j) { lkm[j] * veh[, j] * pro_month[, k] * ef[, 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 })) } # is.numeric(pro_month) & nrow(ef) == nrow(veh) #### } else if (is.numeric(pro_month) & nrow(ef) == nrow(veh)) { if (verbose) message("'pro_month' is numeric and number of rows of 'ef' and 'veh' are equal") 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 (length(lkm) != ncol(veh)) stop("Length of `lkm` must be equal to number of columns of `veh`") 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)]) month <- as.numeric(pro_month) # emis(i, j, k) = veh(i, j) * lkm(j) * ef(i, j)*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 emistd1fpar.f95") a <- dotCall64::.C64( .NAME = "emistd1fpar", SIGNATURE = c( rep("integer", 3), rep("double", 4), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, month = month, nt = as.integer(nt), emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 8), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emistd1f.f95") a <- dotCall64::.C64( .NAME = "emistd1f", SIGNATURE = c( rep("integer", 3), rep("double", 5) ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, month = month, emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), 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 * pmonth) # i e$age <- rep(rep(seq(1, ncolv), each = nrowv), pmonth) # j e$month <- rep(seq(1, pmonth), each = ncolv * nrowv) # k } else { e <- do.call("rbind", lapply(1:12, function(k) { dfi <- unlist(lapply(1:ncol(veh), function(j) { lkm[j] * veh[, j] * pro_month[k] * ef[, 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 })) } # is.numeric(pro_month) & nrow(ef) == 12 #### } else if (is.numeric(pro_month) & nrow(ef) == 12) { if (verbose) message("'pro_month' is numeric and you have 12 montly ef") # 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)]) # month <- as.numeric(pro_month) # # if(verbose) message("Calling emistd1f.f95") # # a <- dotCall64::.C64("emistd1f", # nrowv = nrowv, # ncolv = ncolv, # pmonth = pmonth, # veh = as.matrix(veh), # lkm = lkm, # ef = ef, # month = month, # emis = numeric(nrowv*ncolv*pmonth))$emis # # e <- data.frame(emissions = a) # e <- Emissions(e) # e$rows <- rep(row.names(veh), ncolv*pmonth) # i # e$age <- rep(rep(seq(1, ncolv), each = nrowv), pmonth) # j # e$month <- rep(seq(1, pmonth), each = ncolv*nrowv) # k # } else { e <- do.call("rbind", lapply(1:12, function(k) { dfi <- unlist(lapply(1:ncol(veh), function(j) { lkm[j] * veh[, j] * pro_month[k] * ef[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 })) # } # is.data.frame(pro_month) & nrow(ef) == 12*nrow(veh) #### } else if (is.data.frame(pro_month) & nrow(ef) == 12 * nrow(veh)) { if (verbose) message("'pro_month' is data.frame and number of rows of 'ef' is 12*number of rows 'veh'") if (nrow(pro_month) != nrow(veh)) stop("Number of rows of 'pmonth' and 'veh' must be equal") if (length(ef2) != length(unlist(veh)) * pmonth) stop("length of `ef` and `veh`*`months` must be equal be equal") if (length(lkm) != ncol(veh)) stop("length of `lkm` must be equal to number of columns of `veh`") if (fortran) { nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) pmonth <- as.integer(ncol(pro_month)) lkm <- as.numeric(lkm) ef$month <- rep(1:12, each = nrow(veh)) ef2 <- split(ef[, 1:ncol(veh)], ef$month) ef2 <- as.numeric(unlist(lapply(ef2, unlist))) month <- as.matrix(pro_month) # emis(i, j, k) = veh(i, j) * lkm(j) * ef(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 emistd4fpar.f95") a <- dotCall64::.C64( .NAME = "emistd4fpar", SIGNATURE = c( rep("integer", 3), rep("double", 4), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef2, month = month, nt = as.integer(nt), emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 8), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emistd4f.f95") a <- dotCall64::.C64( .NAME = "emistd4f", SIGNATURE = c( rep("integer", 3), rep("double", 5) ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef2, month = month, emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), 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 * pmonth) # i e$age <- rep(rep(seq(1, ncolv), each = nrowv), pmonth) # j e$month <- rep(seq(1, pmonth), each = ncolv * nrowv) # k } else { ef$month <- rep(1:12, each = nrow(veh)) ef <- split(ef, ef$month) e <- do.call("rbind", lapply(1:12, function(k) { dfi <- unlist(lapply(1:ncol(veh), function(j) { lkm[j] * veh[, j] * pro_month[, k] * ef[[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 })) } # is.numeric(pro_month) & nrow(ef) == 12*nrow(veh) #### } else if (is.numeric(pro_month) & nrow(ef) == 12 * nrow(veh)) { if (verbose) message("'pro_month' is numeric and number of rows of 'ef' is 12*number of rows 'veh'") if (fortran) { nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) pmonth <- as.integer(length(pro_month)) ef$month <- rep(1:12, each = nrow(veh)) ef2 <- split(ef[, 1:ncol(veh)], ef$month) ef2 <- as.numeric(unlist(lapply(ef2, unlist))) lkm <- as.numeric(lkm) month <- as.numeric(pro_month) if (length(ef2) != length(unlist(veh)) * pmonth) stop("length of `ef` and `veh`*`months` must be equal be equal") if (length(lkm) != ncol(veh)) stop("length of `lkm` must be equal to number of columns of `veh`") # emis(i, j, k) = veh(i, j) * lkm(j) * ef(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 emistd3fpar.f95") a <- dotCall64::.C64( .NAME = "emistd3fpar", SIGNATURE = c( rep("integer", 3), rep("double", 4), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef2, month = month, nt = as.integer(nt), emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 8), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { a <- dotCall64::.C64( .NAME = "emistd3f", SIGNATURE = c( rep("integer", 3), rep("double", 5) ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef2, month = month, emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), 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 * pmonth) # i e$age <- rep(rep(seq(1, ncolv), each = nrowv), pmonth) # j e$month <- rep(seq(1, pmonth), each = ncolv * nrowv) # k } else { ef$month <- rep(1:12, each = nrow(veh)) ef <- split(ef, ef$month) e <- do.call("rbind", lapply(1:12, function(k) { dfi <- unlist(lapply(1:ncol(veh), function(j) { lkm[j] * veh[, j] * pro_month[k] * ef[[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 { stop("Condition is not met. Review your input data dn read the documentation, please") } # else if(nrow(ef) != nrow(veh) & nrow(ef) != 12)( # stop("The number of rows can be equal to number of rows of veh, or number of rows of veh times 12") # ) 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 (!is.data.frame(ef)) { if (verbose) message("Assuming you have the same emission factors in each simple feature") # when pro_month vary each row # is.data.frame(pro_month) | is.matrix(pro_month) #### if (is.data.frame(pro_month) | is.matrix(pro_month)) { if (verbose) message("'pro_month' is data.frame and 'ef' is numeric") 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 (length(ef) != ncol(veh)) stop("Length of `ef` and number of cols of `veh` must be equal") if (length(lkm) != ncol(veh)) stop("Length of `lkm` must be equal to number of columns of `veh`") if (nrow(pro_month) != nrow(veh)) stop("Number of rows of `month` and `veh` must be equal") 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) month <- as.matrix(pro_month) # emis(i, j, k) = veh(i,j) * lkm(j) * ef(j) * 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 emistd6fpar.f95") a <- dotCall64::.C64( .NAME = "emistd6fpar", SIGNATURE = c( rep("integer", 3), rep("double", 4), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, month = month, nt = as.integer(nt), emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 8), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emistd6f.f95") a <- dotCall64::.C64( .NAME = "emistd6f", SIGNATURE = c( rep("integer", 3), rep("double", 5) ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, month = month, emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), 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 * pmonth) # i e$age <- rep(rep(seq(1, ncolv), each = nrowv), pmonth) # j e$month <- rep(seq(1, pmonth), each = ncolv * nrowv) # k } else { e <- do.call("rbind", lapply(1:12, function(k) { dfi <- unlist(lapply(1:ncol(veh), function(j) { lkm[j] * veh[, j] * pro_month[, k] * ef[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 })) } # is.numeric(pro_month) #### } else if (is.numeric(pro_month)) { if (verbose) message("'pro_month' is numeric and 'ef' is numeric") if (length(ef) != ncol(veh)) stop("Number of columns of 'veh' and length of 'ef' must be equal") if (fortran) { nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) pmonth <- as.integer(length(pro_month)) lkm <- as.numeric(lkm) month <- as.numeric(pro_month) ef <- as.numeric(ef) if (length(ef) != ncol(veh)) stop("length of `ef` and number of cols of `veh` must be equal") if (length(lkm) != ncol(veh)) stop("length of `lkm` must be equal to number of columns of `veh`") # emis(i, j, k) = veh(i, j) * lkm(j) * ef(j) * 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 emistd5fpar.f95") a <- dotCall64::.C64( .NAME = "emistd5fpar", SIGNATURE = c( rep("integer", 3), rep("double", 4), "integer", "double" ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, month = month, nt = as.integer(nt), emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), INTENT = c( rep("r", 8), "w" ), PACKAGE = "vein", VERBOSE = 1 )$emis } else { if (verbose) message("Calling emistd5f.f95") a <- dotCall64::.C64( .NAME = "emistd5f", SIGNATURE = c( rep("integer", 3), rep("double", 5) ), nrowv = nrowv, ncolv = ncolv, pmonth = pmonth, veh = as.matrix(veh), lkm = lkm, ef = ef, month = month, emis = dotCall64::vector_dc("double", nrowv * ncolv * pmonth), 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 * pmonth) e$age <- rep(seq(1, ncolv), each = nrowv) e$month <- rep(seq(1, pmonth), each = ncolv * nrowv) } else { e <- do.call("rbind", lapply(1:12, function(k) { dfi <- unlist(lapply(1:ncol(veh), function(j) { lkm[j] * veh[, j] * pro_month[k] * ef[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 { if (verbose) message("Estimation without monthly profile") # !is.data.frame(ef) #### if (!is.data.frame(ef)) { if (verbose) message("'ef' is a numeric vector with units") if (fortran) { lkm <- as.numeric(lkm) ef <- as.numeric(ef) nrowv <- as.integer(nrow(veh)) ncolv <- as.integer(ncol(veh)) if (length(ef) != ncol(veh)) stop("length of `ef` and number of cols of `veh` must be equal") if (length(lkm) != ncol(veh)) stop("length of `lkm` must be equal to number of columns of `veh`") # emis(i, j) = veh(i,j) * lkm(j) * 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 emistd7fpar.f95") a <- dotCall64::.C64( .NAME = "emistd7fpar", SIGNATURE = c( "integer", "integer", "double", "double", "double", "integer", "double" ), nrowv = nrowv, ncolv = ncolv, veh = as.matrix(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 emistd7f.f95") a <- dotCall64::.C64( .NAME = "emistd7f", SIGNATURE = c( "integer", "integer", "double", "double", "double", "double" ), nrowv = nrowv, ncolv = ncolv, veh = as.matrix(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 } # fortran # do concurrent(i= 1:nrowv, j = 1:ncolv) # emis(i, j) = veh(i,j) * lkm(i) * ef(j) # end do e <- as.data.frame(a) names(e) <- "emissions" e <- Emissions(e) e$rows <- row.names(e) e$age <- rep(1:ncol(veh), each = nrow(veh)) } else { e <- unlist(lapply(1:ncol(veh), function(j) { lkm[j] * veh[, j] * ef[j] })) e <- as.data.frame(e) names(e) <- "emissions" e <- Emissions(e) e$rows <- row.names(e) e$age <- rep(1:ncol(veh), each = nrow(veh)) } # ef is data.frame } else { if (verbose) message("'ef' is data.frame") if (nrow(ef) != nrow(veh)) stop("Number of rows of 'ef' and 'veh' must be equal") e <- unlist(lapply(1:ncol(veh), function(j) { lkm[j] * veh[, j] * ef[, j] })) e <- as.data.frame(e) names(e) <- "emissions" e <- Emissions(e) e$rows <- row.names(e) 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_hot_td.R
#' @title Estimation with long format #' @family China #' @name emis_long #' @description Emissions estimates #' @param x Vehicles data.frame. x repeats down for each hour #' @param lkm Length of each link in km. lkm repeats down for each hour #' @param ef data.frame. ef repeats down for each hour #' @param tfs temporal factor #' @param speed Speed data.frame (nrow x) #' @param verbose Logical to show more info #' @param array Logical to return EmissionsArray or not #' @return long data.frame #' @importFrom data.table rbindlist #' @export #' @examples { #' data(net) #' net <- net[1:100, ] #' data(pc_profile) #' x <- age_ldv(net$ldv) #' pc_week <- temp_fact(net$ldv+net$hdv, pc_profile[[1]]) #' df <- netspeed(pc_week, #' net$ps, #' net$ffs, #' net$capacity, #' net$lkm, #' alpha = 1) #' #' s <- do.call("rbind",lapply(1:ncol(df), function(i) { #' as.data.frame(replicate(ncol(x), df[, i])) #' })) #' #' ef <- ef_wear(wear = "tyre", #' type = "PC", #' pol = "PM10", #' speed = as.data.frame(s)) #' #' e <- emis_long(x = x, #' lkm = net$lkm, #' ef = ef, #' tfs = pc_profile[[1]], #' speed = df) #' #' ae <- emis_long(x = x, #' lkm = net$lkm, #' ef = ef, #' tfs = pc_profile[[1]], #' speed = df, #' array = TRUE) #' } emis_long <- function(x, lkm, ef, tfs, speed, verbose = TRUE, array = FALSE){ # checks if(nrow(x) != length(lkm)) stop("length lkm and nrow x must be equal") if(length(tfs) != ncol(speed)) stop("length tfs and ncol speed must be equal") if(ncol(ef) != ncol(x)) stop("ncol of ef and x must be equal") LKM <- rep(lkm, length(tfs)) if(nrow(ef) != length(lkm)*length(tfs)) stop("nrow of ef must be equal with length lkm time length tfs") # Vehicle if(verbose) cat("\nProcessing Vehicles\n") nr <- nrow(x) nc <- ncol(x) xx <- temp_veh(x = x, tfs = tfs) if(verbose) cat("Estimating Base EF\n") # speed s <- data.table::rbindlist(lapply(1:ncol(speed), function(i) { as.data.frame(replicate(ncol(x), speed[, i])) })) if(verbose) cat("Estimating emissions\n") E <- Emissions(do.call("cbind", lapply(1:nc, function(i) { as.data.frame(ef)[, i] * as.data.frame(xx)[, i] * LKM }))) # 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/emis_long.R
#' Merge several emissions files returning data-frames or 'sf' of lines #' #' @description \code{\link{emis_merge}} reads rds files and returns a data-frame #' or an object of 'spatial feature' of streets, merging several files. #' #' @param pol Character. Pollutant. #' @param what Character. Word to search the emissions names, "STREETS", "DF" or #' whatever name. It is important to include the extension .'rds'. For instance, #' If you have several files "XX_CO_STREETS.rds", what should be "STREETS.rds" #' @param streets Logical. If true, \code{\link{emis_merge}} will read the street #' emissions created with \code{\link{emis_post}} by "streets_wide", returning an #' object with class 'sf'. If false, it will read the emissions data-frame and #' rbind them. #' @param net 'Spatial feature' or 'SpatialLinesDataFrame' with the streets. #' It is expected #' that the number of rows is equal to the number of rows of #' street emissions. If #' not, the function will stop. #' @param ignore Character; Which pollutants or other charavter would you like to remove? #' @param FN Character indicating the function. Default is "sum" #' @param path Character. Path where emissions are located #' @param crs coordinate reference system in numeric format from #' http://spatialreference.org/ to transform/project spatial data using sf::st_transform #' @param under "Character"; "after" when you stored your pollutant x as 'X_' #' "before" when '_X' and "none" for merging directly the files. #' @param as_list "Logical"; for returning the results as list or not. #' @param k factor #' @param verbose Logical to display more information or not. Default is TRUE #' @return 'Spatial feature' of lines or a dataframe of emissions #' @importFrom data.table rbindlist .SD #' @importFrom sf st_set_geometry st_sf st_geometry st_as_sf st_transform #' @export #' @examples \dontrun{ #' # Do not run #' #' } emis_merge <- function (pol = "CO", what = "STREETS.rds", streets = T, net, FN = "sum", ignore, path = "emi", crs, under = "after", as_list = FALSE, k = 1, verbose = TRUE){ # nocov start x <- list.files(path = path, pattern = what, all.files = T, full.names = T, recursive = T) if(under == "after"){ x <- x[grep(pattern = paste0(pol, "_"), x = x)] } else if (under == "before"){ x <- x[grep(pattern = paste0("_", pol), x = x)] } else { x <- x[grep(pattern = pol, x = x)] } if(!missing(ignore)) { bo <- grepl(pattern = ignore, x = x) x <- x[!bo] if(verbose) { cat("\nReading emissions from:\n") print(x) } } else { if(verbose) { cat("\nReading emissions from:\n") print(x) } } # reading x_rds <- lapply(x, readRDS) if(as_list) return(x_rds) # colnames used for aggregating data.table nombres <- names(x_rds[[1]]) if(streets){ for (i in 1:length(x_rds)){ x_rds[[i]]$id <- 1:nrow(x_rds[[i]]) } x_st <- data.table::rbindlist(x_rds) x_st <- as.data.frame(x_st[, lapply(.SD, eval(parse(text = FN)), na.rm=TRUE), by = "id", .SDcols = nombres ]) if(nrow(x_st) != nrow(net)){ stop("Number of rows of net must be equal to number of rows of estimates") } for(i in 1:ncol(x_st)) x_st[, i] <- x_st[, i]*k net <- sf::st_as_sf(net) if(!missing(crs)) { net <- sf::st_transform(net, crs) } netx <- st_sf(x_st, geometry = sf::st_geometry(net)) return(netx) } else{ x_st <- as.data.frame(data.table::rbindlist(x_rds)) x_st$g <- x_st$g*k return(x_st) } # nocov end }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis_merge.R
#' Re-order the emission to match specific hours and days #' #' @description Emissions are usually estimated for a year, 24 hours, or one week from monday to sunday (with 168 hours). This depends on the availability of traffic data. #' When an air quality simulation is going to be done, they cover #' specific periods of time. For instance, WRF Chem emissions files support periods of time, #' or two emissions sets for a representative day (0-12z 12-0z). Also a WRF Chem simulation #' scan starts a Thursday at 00:00 UTC, cover 271 hours of simulations, but hour emissions are in local #' time and cover only 168 hours starting on Monday. This function tries to transform our emissions #' in local time to the desired UTC time, by recycling the local emissions. #' #' @param x one of the following: #' \itemize{ #' \item Spatial object of class "Spatial". Columns are hourly emissions. #' \item Spatial Object of class "sf". Columns are hourly emissions. #' \item "data.frame", "matrix" or "Emissions". #'} #' #' In all cases, columns are hourly emissions. #' @param lt_emissions Local time of the emissions at the first hour. It must be #' the \strong{before} time of start_utc_time. For instance, if #' start_utc_time is 2020-02-02 00:00, and your emissions starts monday at 00:00, #' your lt_emissions must be 2020-01-27 00:00. The argument tz_lt will detect your #' current local time zone and do the rest for you. #' #' @param start_utc_time UTC time for the desired first hour. For instance, #' the first hour of the namelist.input for WRF. #' @param desired_length Integer; length to recycle or subset local emissions. For instance, the length #' of the WRF Chem simulations, states at namelist.input. #' @param tz_lt Character, Time zone of the local emissions. Default value is derived from #' Sys.timezone(), however, it accepts any other. If you enter a wrong tz, this function will show #' you a menu to choose one of the 697 time zones available. #' @param seconds Number of seconds to add #' @param k Numeric, factor. #' @param net SpatialLinesDataFrame or Spatial Feature of "LINESTRING". #' @param verbose Logical, to show more information, default is TRUE. #' @importFrom sf st_as_sf st_geometry st_set_geometry st_sf st_crs #' @aliases weekly emis_order #' @return sf or data.frame #' @seealso \code{\link{GriddedEmissionsArray}} #' @export #' @examples \dontrun{ #' #do not run #' 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) #' 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) #' head(E_CO_g) #class sf #' gr <- GriddedEmissionsArray(E_CO_g, rows = 19, cols = 23, times = 168, T) #' wCO <- emis_order(x = E_CO_g, #' lt_emissions = "2020-02-19 00:00", #' start_utc_time = "2020-02-20 00:00", #' desired_length = 241) #' } #' emis_order <- function(x, # 24 hours or one week lt_emissions, start_utc_time, desired_length, tz_lt = Sys.timezone(), seconds = 0, k = 1, net, verbose = TRUE) { if(as.POSIXct(lt_emissions) >= as.POSIXct(start_utc_time)) { stop("lt_emissions must start before start_utc_time") } if(verbose) cat("Transforming into data.frame\n") if(inherits(x, "sf")){ x <- sf::st_set_geometry(x, NULL) } # x <- remove_units(x) x$id <- NULL dfx <- data.frame(nx = names(x)) nx <- ncol(x) # check tz itz <- intersect(tz_lt, OlsonNames()) if(length(itz) == 0){ choice <- utils::menu(OlsonNames(), title="Choose your time zone") tz_lt <- OlsonNames()[choice] } if(verbose) cat("Your local_tz is: ", tz_lt, "\n") # first_hour_lt <- as.POSIXct(x = local_time, tz = "Asia/Tokyo") # first_hour_lt <- as.POSIXct(x = local_time, tz = "America/Sao_Paulo") first_hour_lt <- as.POSIXct(x = lt_emissions, tz = tz_lt) futc <- as.POSIXct(format(lt_emissions, tz = "UTC"), tz = "UTC") # primero ver start_day seq_wrf <- seq.POSIXt(from = as.POSIXct(start_utc_time, tz = "UTC"), by = 3600, length.out = desired_length) dwrf <- data.frame(seq_wrf = seq_wrf, cutc = as.character(seq_wrf)) lt <- seq.POSIXt(from = first_hour_lt, by = 3600, #I need that lt be long enoigh so that dwrf$cutc is inside df_x$cutc # Hence, recycling names(x) length.out = nx*desired_length) df_x <- data.frame(lt = lt, utc = as.POSIXct(format(lt, tz = "UTC"), tz = "UTC")+seconds, cutc = as.character(as.POSIXct(format(lt, tz = "UTC"), tz = "UTC")+seconds)) a <- data.table::hour(df_x$lt[1]) - data.table::hour(df_x$utc[1]) if(verbose) cat("Difference with UTC: ", a, "\n") df_x$nx <- names(x) df <- merge(x = dwrf, y = df_x, by = "cutc", all.x = T) x <- x[, df$nx] * k if(!missing(net)){ netsf <- sf::st_as_sf(net) dfsf <- sf::st_sf(x, geometry = sf::st_geometry(netsf)) return(dfsf) } else { return(x) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis_order.R
#' Estimation of resuspension emissions from paved roads #' #' @description \code{emis_paved} estimates vehicular emissions from paved roads. #' The vehicular emissions are estimated as the product of the vehicles on a #' road, length of the road, emission factor from AP42 13.2.1 Paved roads. #' It is assumed dry hours and annual aggregation should consider moisture factor. #' It depends on Average Daily Traffic (ADT) #' #' @param veh Numeric vector with length of elements equals to number of streets #' It is an array with dimenssions number of streets x hours of day x days of week #' @param adt Numeric vector of with Average Daily Traffic (ADT) #' @param lkm Length of each link #' @param k K_PM30 = 3.23 (g/vkm), K_PM15 = 0.77 (g/vkm), K_PM10 = 0.62 (g/vkm) #' and K_PM2.5 = 0.15 (g/vkm). #' @param sL1 Silt loading (g/m2) for roads with ADT <= 500 #' @param sL2 Silt loading (g/m2) for roads with ADT > 500 and <= 5000 #' @param sL3 Silt loading (g/m2) for roads with ADT > 5000 and <= 1000 #' @param sL4 Silt loading (g/m2) for roads with ADT > 10000 #' @param W array of dimensions of veh. It consists in the hourly averaged #' weight of traffic fleet in each road #' @param net SpatialLinesDataFrame or Spatial Feature of "LINESTRING" #' @return emission estimation g/h #' @export #' @references EPA, 2016. Emission factor documentation for AP-42. Section #' 13.2.1, Paved Roads. https://www3.epa.gov/ttn/chief/ap42/ch13/final/c13s0201.pdf #' #' CENMA Chile: Actualizacion de inventario de emisiones de contaminntes atmosfericos RM 2020 #' Universidad de Chile#' #' @note silt values can vary a lot. For comparison: #' #' \tabular{lcc}{ #' ADT \tab US-EPA g/m2 \tab CENMA (Chile) g/m2 \cr #' < 500 \tab 0.6 \tab 2.4 \cr #' 500-5000 \tab 0.2 \tab 0.7 \cr #' 5000-1000 \tab 0.06 \tab 0.6 \cr #' >10000 \tab 0.03 \tab 0.3 \cr #' } #' @examples \dontrun{ #' # Do not run #' veh <- matrix(1000, nrow = 10,ncol = 10) #' W <- veh*1.5 #' lkm <- 1:10 #' ADT <-1000:1010 #' emi <- emis_paved(veh = veh, adt = ADT, lkm = lkm, k = 0.65, W = W) #' class(emi) #' head(emi) #' } emis_paved <- function(veh, # hourly traffic flow multiplier of 24 adt, lkm, k = 0.62, # K_PM10 = 0.62 (g/vkm) sL1 = 0.6, # g/m^2 sL2 = 0.2, # g/m^2 sL3 = 0.06, # g/m^2 sL4 = 0.03, # g/m^2 W, net = net) { veh <- remove_units(veh) adt <- remove_units(adt) lkm <- remove_units(lkm) W <- remove_units(W) veh$id <- NULL sL <- ifelse(adt <= 500, sL1, ifelse(adt > 500 & adt <= 5000, sL2, ifelse(adt > 5000 & adt <=10000, sL3, sL4))) emi <- veh * lkm * k * sL^0.91 * W^1.02 emi[is.na(emi)] <- 0 if(!missing(net)) { net <- sf::st_as_sf(net) emi <- sf::st_sf(Emissions(emi), geometry = sf::st_geometry(net)) return(emi) } else { return(Emissions(emi)) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis_paved.R
#' Post emissions #' #' @description \code{emis_post} simplify emissions estimated as total per type category of #' vehicle or by street. It reads EmissionsArray and Emissions classes. It can return a dataframe #' with hourly emissions at each street, or a database with emissions by vehicular #' category, hour, including size, fuel and other characteristics. #' #' @param arra Array of emissions 4d: streets x category of vehicles x hours x days or #' 3d: streets x category of vehicles x hours #' @param veh Character, type of vehicle #' @param size Character, size or weight #' @param fuel Character, fuel #' @param type_emi Character, type of emissions(exhaust, evaporative, etc) #' @param pollutant Pollutant #' @param by Type of output, "veh" for total vehicular category , #' "streets_narrow" or "streets". "streets" returns a dataframe with #' rows as number of streets and columns the hours as days*hours considered, e.g. #' 168 columns as the hours of a whole week and "streets repeats the #' row number of streets by hour and day of the week #' @param net SpatialLinesDataFrame or Spatial Feature of "LINESTRING". Only #' when by = 'streets_wide' #' @param k Numeric, factor #' @importFrom sf st_sf st_as_sf #' @export #' @note This function depends on EmissionsArray objests which currently has #' 4 dimensions. However, a future version of VEIN will produce EmissionsArray #' with 3 dimensiones and his fungeorge soros drugsction also will change. This change will be #' made in order to not produce inconsistencies with previous versions, therefore, #' if the user count with an EmissionsArry with 4 dimension, it will be able #' to use this function. #' @examples \dontrun{ #' # Do not run #' 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) #' pc1 <- my_age(x = net$ldv, y = PC_G, name = "PC") #' # Estimation for morning rush hour and local emission factors #' speed <- data.frame(S8 = net$ps) #' p1h <- matrix(1) #' lef <- EmissionFactorsList(fe2015[fe2015$Pollutant=="CO", "PC_G"]) #' E_CO <- emis(veh = pc1,lkm = net$lkm, ef = lef, speed = speed, #' profile = p1h) #' E_CO_STREETS <- emis_post(arra = E_CO, pollutant = "CO", by = "streets_wide") #' summary(E_CO_STREETS) #' E_CO_STREETSsf <- emis_post(arra = E_CO, pollutant = "CO", #' by = "streets", net = net) #' summary(E_CO_STREETSsf) #' plot(E_CO_STREETSsf, main = "CO emissions (g/h)") #' # arguments required: arra, veh, size, fuel, pollutant ad by #' E_CO_DF <- emis_post(arra = E_CO, veh = "PC", size = "<1400", fuel = "G", #' pollutant = "CO", by = "veh") #' # Estimation 168 hours #' 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(dfcol = 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) #' # arguments required: arra, pollutant ad by #' E_CO_STREETS <- emis_post(arra = E_CO, pollutant = "CO", by = "streets") #' summary(E_CO_STREETS) #' # arguments required: arra, veh, size, fuel, pollutant ad by #' E_CO_DF <- emis_post(arra = E_CO, veh = "PC", size = "<1400", fuel = "G", #' pollutant = "CO", by = "veh") #' head(E_CO_DF) #' # recreating 24 profile #' lpc <-list(pc1*0.2, pc1*0.1, pc1*0.1, pc1*0.2, pc1*0.5, pc1*0.8, #' pc1, pc1*1.1, pc1, #' pc1*0.8, pc1*0.5, pc1*0.5, #' pc1*0.5, pc1*0.5, pc1*0.5, pc1*0.8, #' pc1, pc1*1.1, pc1, #' pc1*0.8, pc1*0.5, pc1*0.3, pc1*0.2, pc1*0.1) #' E_COv2 <- emis(veh = lpc, lkm = net$lkm, ef = lef, speed = speed[, 1:24], #' agemax = 41, hour = 24, day = 1) #' plot(E_COv2) #' E_CO_DFv2 <- emis_post(arra = E_COv2, #' veh = "PC", #' size = "<1400", #' fuel = "G", #' type_emi = "Exhaust", #' pollutant = "CO", by = "veh") #' head(E_CO_DFv2) #' } emis_post <- function(arra, veh, size, fuel, pollutant, by = "veh", net, type_emi, k = 1) { if (inherits(arra, "EmissionsArray") & length(dim(arra)) == 4){ if (by == "veh"){ x <- unlist(lapply(1:dim(arra)[4], function(j) { unlist(lapply (1:dim(arra)[3],function(i) { colSums(arra[,,i,j], na.rm = TRUE) })) })) df <- cbind(deparse(substitute(arra)), as.data.frame(x)) names(df) <- c(as.character(df[1,1]), "g") nombre <- rep(paste(as.character(df[1,1]), seq(1:dim(arra)[2]), sep = "_"), dim(arra)[3]*dim(arra)[4], by = dim(arra)[4]) df[,1] <- nombre if(!missing(veh)) { df$veh <- rep(veh, nrow(df)) } else { warning("You should add `veh`") } if(!missing(size)) { df$size <- rep(size, nrow(df)) } else { warning("You should add `size`") } if(!missing(fuel)) { df$fuel <- rep(fuel, nrow(df)) } else { warning("You should add `fuel`") } if(!missing(type_emi)) { df$type_emi <- rep(type_emi, nrow(df)) } else { warning("You should add `type_emi`") } if(!missing(pollutant)) { df$pollutant <- rep(pollutant, nrow(df)) } else { stop("At pleast write the name of the `pollutant`") } df$age <- rep(seq(1:dim(arra)[2]), dim(arra)[3]*dim(arra)[4], by = dim(arra)[4]) hour <- rep(1:(dim(arra)[3]*dim(arra)[4]), #hours x days each = dim(arra)[2]) #veh cat df$hour <- hour df$g <- Emissions(df$g)*k return(df) } else if (by == "streets_narrow") { # soon deprecated this function? x <- unlist(lapply(1:dim(arra)[4], function(j) {# dia unlist(lapply (1:dim(arra)[3],function(i) { # hora rowSums(arra[,,i,j], na.rm = TRUE) })) }))*k df <- cbind(deparse(substitute(arra)),as.data.frame(x)) hour <- rep(seq(0: (dim(arra)[3]-1) ), times = dim(arra)[4], each=dim(arra)[1]) df$hour <- hour names(df) <- c("street", "g", "hour") df[,1] <- seq(1,dim(arra)[1]) df[,2] <- Emissions(df[,2]) return(df) } else if (by %in% c("streets_wide", "streets")) { x <- unlist(lapply(1:dim(arra)[4], function(j) {# dia unlist(lapply (1:dim(arra)[3],function(i) { # hora rowSums(arra[,,i,j], na.rm = T) })) }))*k m <- matrix(x, nrow=dim(arra)[1], ncol=dim(arra)[3]*dim(arra)[4]) df <- as.data.frame(m) nombres <- lapply(1:dim(m)[2], function(i){paste0("h",i)}) if(!missing(net)){ netsf <- sf::st_as_sf(net) dfsf <- sf::st_sf(Emissions(df), geometry = sf::st_geometry(netsf)) return(dfsf) } else { return(Emissions(df)) } } } else if(inherits(arra, "EmissionsArray") & length(dim(arra) == 3)){ if (by == "veh"){ x <- as.vector(apply(X = arra, MARGIN = c(2,3), FUN = sum, na.rm = TRUE)) df <- cbind(deparse(substitute(arra)), as.data.frame(x)) names(df) <- c(as.character(df[1,1]), "g") nombre <- rep(paste(as.character(df[1,1]), seq(1:dim(arra)[2]), sep = "_"),dim(arra)[3], by=7 ) df[,1] <- nombre if(!missing(veh)) { df$veh <- rep(veh, nrow(df)) } else { warning("You should add `veh`") } if(!missing(size)) { df$size <- rep(size, nrow(df)) } else { warning("You should add `size`") } if(!missing(fuel)) { df$fuel <- rep(fuel, nrow(df)) } else { warning("You should add `fuel`") } if(!missing(type_emi)) { df$type_emi <- rep(type_emi, nrow(df)) } else { warning("You should add `type_emi`") } if(!missing(pollutant)) { df$pollutant <- rep(pollutant, nrow(df)) } else { stop("At pleast write the name of the `pollutant`") } df$age <- rep(1:dim(arra)[2], dim(arra)[3]) hour <- rep(1:dim(arra)[3], #hours x days each = dim(arra)[2]) #veh cat df$hour <- hour df$g <- Emissions(df$g)*k return(df) } else if (by %in% c("streets_narrow")) { df <- as.vector(apply(X = arra, MARGIN = c(1,3), FUN = sum, na.rm = TRUE)) df <- data.frame(street = length(df) / dim(arra)[3], g = Emissions(df), hour = rep(1:dim(arra)[3], each = dim(arra)[1])) return(df) } else if (by %in% c("streets_wide", "streets")) { df <- apply(X = arra, MARGIN = c(1,3), FUN = sum, na.rm = TRUE)*k names(df) <- paste0("h",1:length(df)) df <- as.data.frame(df) if(!missing(net)){ netsf <- sf::st_as_sf(net) dfsf <- sf::st_sf(Emissions(df), geometry = sf::st_geometry(netsf)) return(dfsf) } else { return(Emissions(df)) } } } else if(inherits(arra, "Emissions") & length(dim(arra) == 2)) { if(by != "veh") stop("Only by == 'veh' accepted") x_DF <- data.frame(array_x = paste0("array_", 1:nrow(arra))) x_DF$g <- arra$emissions*k x_DF$veh <- veh x_DF$size <- size x_DF$fuel <- fuel x_DF$type_emi <- type_emi x_DF$pollutant <- pollutant x_DF$age <- arra$age if("month" %in% names(arra)) { x_DF$month <- arra$month } return(x_DF) } else { stop("emis_post only reads `EmissionsArray` or `Emissions`") } }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis_post.R
#' A function to source vein scripts #' #' @description \code{\link{emis_source}} source vein scripts #' #' @name vein-deprecated #' @param path Character; path to source scripts. Default is "est". #' @param ignore Character; character to be excluded. Default is "~". Sometimes, #' the OS creates automatic back-ups, for instance "run.R~", the idea is to #' avoid sourcing these files. #' @param ask Logical; Check inputs or not. Default is "FALSE". It allows to #' stop inputs #' @param pattern Character; extensions of R scripts. Default is ".R". #' @param recursive Logical; recursive or not. Default is "TRUE" #' @param full.names Logical; full.names or not. Default is "TRUE". #' @param first Character; first script. #' @param echo Source with echo? #' @importFrom utils menu #' @export #' @examples \dontrun{ #' # Do not run #' } emis_source <- function(path = "est", pattern = ".R", ignore = "~", first, ask = TRUE, recursive = TRUE, full.names = TRUE, echo = FALSE){ # inputs <- list.files(path = path, pattern = pattern, # recursive = recursive, full.names = full.names) # inputs <- inputs[!grepl(pattern = ignore, x = inputs)] # if(!missing(first)){ # inputsa <- c(inputs[grepl(pattern = first, x = inputs)], # inputs[!grepl(pattern = first, x = inputs)]) # if(ask){ #nocov start # print(inputsa) # choice <- utils::menu(c("Yes", "No"), title="inputs are OK?") # if(choice == 1){ # for(i in 1:length(inputsa)){ # cat("Sourcing ",inputsa[i], "...\n") # source(inputsa[i], echo = echo) # } # } else { # stop("Change inputs") # } #nocov end # } else { # for(i in 1:length(inputsa)){ # cat("Sourcing ",inputsa[i], "...\n") # source(inputsa[i], echo = echo) # } # } # } else { # if(ask){ #nocov start # print(inputs) # choice <- utils::menu(c("Yes", "No"), title="inputs are OK?") # if(choice == 1){ # for(i in 1:length(inputs)){ # cat("Sourcing ",inputs[i], "...\n") # source(inputs[i], echo = echo) # } # } else { # stop("Change inputs") # } #nocov end # } else { # for(i in 1:length(inputs)){ # cat("Sourcing ",inputs[i], "...\n") # source(inputs[i], echo = echo) # } # } # # } .Deprecated("get_project") "emis_source" }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis_source.R
#' Emis to streets distribute top-down emissions into streets #' #' @description \code{\link{emis_to_streets}} 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 streets sf object with geometry 'LINESTRING' or 'MULTILINESTRING'. Or #' SpatialLinesDataFrame #' @param dfemis data.frame with emissions #' @param by Character indicating the columns that must be present in both #' 'street' and 'dfemis' #' @param stpro data.frame with two columns, category of streets and value. #' The name of the first column must be "stpro" and the sf streets must also #' have a column with the nam "stpro" indicating the category of streets. #' The second column must have the name "VAL" indicating the associated values #' to each category of street #' @param verbose Logical; to show more info. #' @importFrom sf st_geometry st_as_sf st_length st_set_geometry #' @export #' @seealso \code{\link{add_polid}} #' @note When spobj is a 'Spatial' object (class of sp), they are converted #' into 'sf'. #' @examples \dontrun{ #' data(net) #' stpro = data.frame(stpro = as.character(unique(net$tstreet)), #' VAL = 1:9) #' dnet <- net["ldv"] #' dnet$stpro <- as.character(net$tstreet) #' dnet$ID <- "A" #' df2 <- data.frame(BC = 10, CO = 20, ID = "A") #' ste <- emis_to_streets(streets = dnet, dfemis = df2) #' sum(ste$ldv) #' sum(net$ldv) #' sum(ste$BC) #' sum(df2$BC) #' ste2 <- emis_to_streets(streets = dnet, dfemis = df2, stpro = stpro) #' sum(ste2$ldv) #' sum(net$ldv) #' sum(ste2$BC) #' sum(df2$BC) #' } emis_to_streets <- function(streets, dfemis, by = "ID", stpro, verbose = TRUE){ if(inherits(dfemis, "sf")) { dfemis <- sf::st_set_geometry(dfemis, NULL) } outersect <- function(x, y) { sort(c(setdiff(x, y), setdiff(y, x))) } rn <- row.names(streets) streets <- sf::st_as_sf(streets) nstreets <- names(sf::st_set_geometry(streets, NULL)) geo <- sf::st_geometry(streets) streets$length <- sf::st_length(streets) streets <- sf::st_set_geometry(streets, NULL) # check stpro if(!missing(stpro)) { if(names(stpro)[1] != "stpro") stop("First name of data.frame stpro must be 'stpro'") if(names(stpro)[2] != "VAL") stop("Second name of data.frame stpro must be 'VAL'") streets <- merge(streets, stpro, by = "stpro", all.x = T) streets$VAL <- ifelse(is.na(streets$VAL), 1, streets$VAL) dfa <- do.call("rbind",lapply(1:nrow(dfemis), function(i){ if(verbose) message(paste0("filtering ", dfemis[[by]][i])) dfstreets <- streets[streets[[by]] == dfemis[[by]][i], ] dfstreets$length <- dfstreets$length*dfstreets$VAL dfstreets$p_length <- as.numeric(dfstreets$length)/sum(as.numeric(dfstreets$length)) dfs <- unlist(dfemis[dfemis[[by]] == dfemis[[by]][i], 1:(ncol(dfemis) - 1)]) dft <- as.matrix(dfstreets$p_length) %*% matrix(as.numeric(dfs), nrow = 1) a <- as.data.frame(cbind(dfstreets, dft)) a })) dfa$VAL <- NULL } else { dfa <- do.call("rbind",lapply(1:nrow(dfemis), function(i){ if(verbose) message(paste0("filtering ", dfemis[[by]][i])) dfstreets <- streets[streets[[by]] == dfemis[[by]][i], ] dfstreets$p_length <- as.numeric(dfstreets$length)/sum(as.numeric(dfstreets$length)) dfs <- unlist(dfemis[dfemis[[by]] == dfemis[[by]][i], 1:(ncol(dfemis) - 1)]) dft <- as.matrix(dfstreets$p_length) %*% matrix(as.numeric(dfs), nrow = 1) a <- as.data.frame(cbind(dfstreets, dft)) a })) } dfa$length <- NULL dfa$p_length <- NULL ndfemis <- outersect(names(dfemis), by) ldfa <- length(names(dfa)) lndfemis <- length(ndfemis) ll <- ldfa - lndfemis names(dfa) <- c(names(dfa)[1:ll], ndfemis) dfa <- sf::st_sf(dfa, geometry = geo) return(dfa) }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis_to_streets.R
#' Emission estimation from tyre, brake and road surface wear #' #' @description \code{emis_wear} estimates wear emissions. The sources are tyres, #' breaks and road surface. #' #' @param veh Object of class "Vehicles" #' @param lkm Length of the road in km. #' @param ef list of emission factor functions class "EmissionFactorsList", #' length equals to hours. #' @param what Character for indicating "tyre", "break" or "road" #' @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 hour Number of considered hours in estimation #' @param day Number of considered days in estimation #' @return emission estimation g/h #' @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 #' @export #' @examples \dontrun{ #' data(net) #' data(pc_profile) #' pc_week <- temp_fact(net$ldv[1:10] + net$hdv[1:10], pc_profile[, 1]) #' df <- netspeed(pc_week, net$ps[1:10], net$ffs[1:10], #' net$capacity[1:10], net$lkm[1:10], alpha = 1) #' ef <- ef_wear(wear = "tyre", type = "PC", pol = "PM10", speed = df) #' emi <- emis_wear(veh = age_ldv(net$ldv[1:10], name = "VEH"), #' lkm = net$lkm[1:10], ef = ef, speed = df, #' profile = pc_profile[, 1]) #' emi #' } emis_wear <- function (veh, lkm, ef, what = "tyre", speed, agemax = ncol(veh), profile, hour = nrow(profile), day = ncol(profile)) { if(units(lkm)$numerator == "m" ){ stop("Units of lkm is 'm'") } veh <- as.data.frame(veh) lkm <- as.numeric(lkm) for (i in 1:ncol(veh) ) { veh[,i] <- as.numeric(veh[,i]) } for (i in 1:ncol(speed) ) { speed[,i] <- as.numeric(speed[, i]) } #profile if(is.vector(profile)){ profile <- matrix(as.numeric(profile), ncol = 1) } # if it is data.frame or matrix, OK # if(!missing(profile) & is.vector(profile)){ # profile <- matrix(profile, ncol = 1) # } # ncol ef if(ncol(ef)/24 != day){ stop("Number of days of ef and profile must be the same") } lef <- lapply(1:day, function(i){ as.list(ef[, (24*(i-1) + 1):(24*i)]) }) # lapply(ef, as.list) if (what == "tyre"){ d <- simplify2array( lapply(1:day,function(j){ simplify2array( lapply(1:hour,function(i){ simplify2array( lapply(1:agemax, function(k){ ifelse( speed[,i] < 40, veh[, k]*profile[i,j]*lkm*lef[[j]][[i]]*1.67, ifelse( speed[,i] >= 40 & speed[,i] <= 95, veh[, k]*profile[i,j]*lkm*lef[[j]][[i]]*(-0.0270*speed[, i] + 2.75), veh[, k]*profile[i,j]*lkm*lef[[j]][[i]]*0.185 )) })) })) })) } else if(what == "break"){ d <- simplify2array( lapply(1:day,function(j){ simplify2array( lapply(1:hour,function(i){ simplify2array( lapply(1:agemax, function(k){ ifelse( speed[,i] < 40, veh[, k]*profile[i,j]*lkm*lef[[j]][[i]]*1.39, ifelse( speed[,i] >= 40 & speed[,i] < 80, veh[, k]*profile[i,j]*lkm*lef[[j]][[i]]*(-0.00974*speed[, i] + 1.78), ifelse( speed[,i] == 80, veh[, k]*profile[i,j]*lkm*lef[[j]][[i]], ifelse( speed[,i] > 80 & speed[,i] <= 90, veh[, k]*profile[i,j]*lkm*lef[[j]][[i]]*(-0.00974*speed[, i] + 1.78), veh[, k]*profile[i,j]*lkm*lef[[j]][[i]]*0.902 )))) })) })) })) } else if (what == "road"){ d <- simplify2array( lapply(1:day,function(j){ simplify2array( lapply(1:hour,function(i){ simplify2array( lapply(1:agemax, function(k){ veh[, k]*profile[i,j]*lkm*lef[[j]][[i]] })) })) })) } return(EmissionsArray(d)) }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis_wear.R
#' Generates emissions dataframe to generate WRF-Chem inputs (DEPRECATED) #' #' \code{emis_wrf} returns a dataframe with columns lat, long, id, pollutants, local time #' and GMT time. This dataframe has the proper format to be used with WRF #' assimilation system: "ASimilation System 4 WRF (AS4WRF Vera-Vala et al (2016)) #' #' @param sdf Gridded emissions, which can be a SpatialPolygonsDataFrame, or a list #' of SpatialPolygonsDataFrame, or a sf object of "POLYGON". The user must enter #' a list with 36 SpatialPolygonsDataFrame with emissions for the mechanism CBMZ. #' @param nr Number of repetitions of the emissions period #' @param dmyhm String indicating Day Month Year Hour and Minute in the format #' "d-m-Y H:M" e.g.: "01-05-2014 00:00" It represents the time of the first #' hour of emissions in Local Time #' @param tz Time zone as required in for function \code{\link{as.POSIXct}} #' @param crs Coordinate reference system, e.g: "+init=epsg:4326". Used to #' transform the coordinates of the output #' @param islist logical value to indicate if sdf is a list or not #' @name vein-deprecated #' @seealso \code{\link{vein-deprecated}} #' @keywords internal NULL #' @rdname vein-deprecated #' #' @export #' @examples \dontrun{ #' # do not run #' # Use library(eixport) #' # eixport::to_as4wrf() #' } emis_wrf <- function(sdf, nr = 1, dmyhm, tz, crs = 4326, islist){ .Deprecated("eixport::wrf_create()") # nocov "emis_wrf"# nocov }
/scratch/gouwar.j/cran-all/cranData/vein/R/emis_wrf.R
#' Emission factors from Environmental Agency of Sao Paulo CETESB #' #' A dataset containing emission factors from CETESB and its #' equivalency with EURO #' #' @format A data frame with 288 rows and 12 variables: #' \describe{ #' \item{Age}{Age of use} #' \item{Year}{Year of emission factor} #' \item{Pollutant}{Pollutants included: "CH4", "CO", "CO2", "HC", #' "N2O", "NMHC", "NOx", and "PM"} #' \item{Proconve_LDV}{Proconve emission standard: "PP", "L1", "L2", #' "L3", "L4", "L5", "L6"} #' \item{t_Euro_LDV}{Euro emission standard equivalence: "PRE_ECE", #' "I", "II", "III","IV", "V"} #' \item{Euro_LDV}{Euro emission standard equivalence: "PRE_ECE", #' "I", "II", "III","IV", "V"} #' \item{Proconve_HDV}{Proconve emission standard: "PP", "P1", "P2", #' "P3", "P4", "P5", "P7"} #' \item{Euro_HDV}{Euro emission standard equivalence: "PRE", "I", #' "II", "III", "V"} #' \item{PC_G}{CETESB emission standard for Passenger Cars with Gasoline (g/km)} #' \item{LT}{CETESB emission standard for Light Trucks with Diesel (g/km)} #' } #' @source CETESB #' @usage data(fe2015) #' @docType data "fe2015"
/scratch/gouwar.j/cran-all/cranData/vein/R/fe2015.R
#' List of functions of mileage in km fro Brazilian fleet #' #' Functions from CETESB: #' Antonio de Castro Bruni and Marcelo Pereira Bales. 2013. #' Curvas de intensidade de uso por tipo de veiculo automotor da frota da cidade de Sao Paulo #' This functions depends on the age of use of the vehicle #' #' @format A data frame with 288 rows and 12 variables: #' \describe{ #' \item{KM_PC_E25}{Mileage in km of Passenger Cars using Gasoline with 25\% Ethanol} #' \item{KM_PC_E100}{Mileage in km of Passenger Cars using Ethanol 100\%} #' \item{KM_PC_FLEX}{Mileage in km of Passenger Cars using Flex engines} #' \item{KM_LCV_E25}{Mileage in km of Light Commercial Vehicles using Gasoline with 25\% Ethanol} #' \item{KM_LCV_FLEX}{Mileage in km of Light Commercial Vehicles using Flex} #' \item{KM_PC_B5}{Mileage in km of Passenger Cars using Diesel with 5\% biodiesel} #' \item{KM_TRUCKS_B5}{Mileage in km of Trucks using Diesel with 5\% biodiesel} #' \item{KM_BUS_B5}{Mileage in km of Bus using Diesel with 5\% biodiesel} #' \item{KM_LCV_B5}{Mileage in km of Light Commercial Vehicles using Diesel with 5\% biodiesel} #' \item{KM_SBUS_B5}{Mileage in km of Small Bus using Diesel with 5\% biodiesel} #' \item{KM_ATRUCKS_B5}{Mileage in km of Articulated Trucks using Diesel with 5\% biodiesel} #' \item{KM_MOTO_E25}{Mileage in km of Motorcycles using Gasoline with 25\% Ethanol} #' \item{KM_LDV_GNV}{Mileage in km of Light Duty Vehicles using Natural Gas} ##' } #' @source CETESB #' @usage data(fkm) #' @docType data "fkm"
/scratch/gouwar.j/cran-all/cranData/vein/R/fkm.R
#' Correction due Fuel effects #' #' @description Take into account the effect of better fuels on vehicles with #' older technology. If the ratio is less than 1, return 1. It means that it is #' nota degradation function. #' #' @param euro Character; Euro standards ("PRE", "I", "II", "III", "IV", "V", #' VI, "VIc") #' @param g Numeric; vector with parameters of gasoline with the names: #' e100(vol. %), aro (vol. %), o2 (wt. %), e150 (%), olefin vol. % and s #' (sulphur, ppm) #' @param d Numeric; vector with parameters for diesel with the names: #' den (density at 15 Celsius degrees kg/m3), pah (%), cn (number), t95 #' (Back end distillation in Celsius degrees) and s (sulphur, ppm) #' @return A list with the correction of emission factors. #' @importFrom data.table rbindlist #' @note This function cannot be used to account for deterioration, therefore, #' it is restricted to values between 0 and 1. #' Parameters for gasoline (g): #' #' O2 = Oxygenates in % #' #' S = Sulphur content in ppm #' #' ARO = Aromatics content in % #' #' OLEFIN = Olefins content in % #' #' E100 = Mid range volatility in % #' #' E150 = Tail-end volatility in % #' #' Parameters for diesel (d): #' #' DEN = Density at 15 C (kg/m3) #' #' S = Sulphur content in ppm #' #' PAH = Aromatics content in % #' #' CN = Cetane number #' #' T95 = Back-end distillation in o C. #' #' @export #' @examples \dontrun{ #' f <- fuel_corr(euro = "I") #' names(f) #' } fuel_corr <- function(euro, g = c(e100 = 52, # vol. % aro = 39, # vol. % o2 = 0.4, # wt. % e150 = 86, # % olefin = 10, # vol. % s = 165), # ppm d = c(den = 840, # kg/m3 pah = 9, # % cn = 51, # number t95 = 350, # C s = 400) # ppm ){ if(length(euro) == 1) { # Pre Euro bg1996 <- c(e100 = 52, aro = 39, o2 = 0.4, e150 = 86, olefin = 10, s = 165) # Euro 3 bg2000 <- c(e100 = 52, aro = 37, o2 = 1, e150 = 86, olefin = 10, s = 130) # Euro 4 bg2005 <- c(e100 = 52, aro = 33, o2 = 1.5, e150 = 86, olefin = 10, s = 40) # Pre Euro bd1996 <- c(den = 840, pah = 9, cn = 51, t95 = 350, s = 400) # Euro 3 bd2000 <- c(den = 840, pah = 7, cn = 53, t95 = 330, s = 300) # Euro 4 bd2005 <- c(den = 835, pah = 5, cn = 53, t95 = 320, s = 40) f_co_ldv_g <- function(e100, aro, o2, s, e150) { (2.459 - 0.05513*e100 + 0.0005343*e100^2 + 0.009226*aro - 0.0003101*(97-s))*(1 - 0.037*(o2 - 1.75))*(1-0.008*(e150 - 90.2))} f_cov_ldv_g <- function(aro, e100, s, olefin, o2, e150){ (0.1347 + 0.0005489*aro + 25.7*aro*exp(-0.2642*e100) - 0.0000406*( 97 - s))*(1-0.004*(olefin - 4.97))*(1 - 0.022*(o2 - 1.75))*( 1 - 0.01*(e150 - 90.2))} f_nox_ldv_g <- function(aro, e100, s, olefin, o2, e150){ (0.1884 - 0.001438*aro + 0.00001959*aro*e100 - 0.00005302*( 97 - s))*(1 + 0.004*(olefin - 4.97))*(1 + 0.001*(o2 - 1.75))*( 1 + 0.008*(e150 - 90.2))} f_co_ldv_d <- function(den, pah, cn, t95) { -1.3250726 + 0.003037*den - 0.0025643*pah - 0.015856*cn + 0.0001706*t95} f_cov_ldv_d <- function(den, pah, cn, t95) { -0.293192 + 0.0006759*den - 0.0007306*pah - 0.0032733*cn - 0.000038*t95} f_nox_ldv_d <- function(den, pah, cn, t95) { 1.0039726 - 0.0003113*den + 0.0027263*pah - 0.0000883*cn - 0.0005805*t95} f_pm_ldv_d <- function(den, pah, cn, t95, s){ (-0.3879873 + 0.0004677*den + 0.0004488*pah + 0.0004098*cn + 0.0000788*t95)*( 1 - 0.015*(450 - s)/100)} f_co_hdv <- function(den, pah, cn, t95) { 2.24407 - 0.0011*den + 0.00007*pah - 0.00768*cn + 0.0001706*t95} f_cov_hdv <- function(den, pah, cn, t95) { 1.61466 - 0.00123*den + 0.00133*pah - 0.00181*cn - 0.00068*t95} f_nox_hdv <- function(den, pah, cn, t95) { -1.75444 + 0.00906*den - 0.0163*pah + 0.00493*cn + 0.00266*t95} f_pm_hdv <- function(den, pah, cn, t95, s){ (0.06959 + 0.00006*den + 0.00065*pah - 0.00001*cn)*(1 - 0.0086*(450 - s)/100)} # if(tveh == "LDVG"){ if(euro %in% c("PRE", "I", "II")){ fco_ldv_g <- f_co_ldv_g(e100 = g[["e100"]], aro = g[["aro"]], o2 = g[["o2"]], s = g[["s"]], e150 = g[["e150"]])/ f_co_ldv_g(e100 = bg1996[["e100"]], aro = bg1996[["aro"]], o2 = bg1996[["o2"]], s = bg1996[["s"]], e150 = bg1996[["e150"]]) fcov_ldv_g <- f_cov_ldv_g(aro = g[["aro"]], e100 = g[["e100"]], s = g[["s"]], olefin = g[["olefin"]], o2 = g[["o2"]], e150 = bg1996[["e150"]])/ f_cov_ldv_g(aro = bg1996[["aro"]], e100 = bg1996[["e100"]], s = bg1996[["s"]], olefin = bg1996[["olefin"]], o2 = bg1996[["o2"]], e150 = bg1996[["e150"]]) fnox_ldv_g <- f_nox_ldv_g(aro = g[["aro"]], e100 = g[["e100"]], s = g[["s"]], olefin = g[["olefin"]], o2 = g[["o2"]], e150 = g[["e150"]])/ f_nox_ldv_g(aro = bg1996[["aro"]], e100 = bg1996[["e100"]], s = bg1996[["s"]], olefin = bg1996[["olefin"]], o2 = bg1996[["o2"]], e150 = bg1996[["e150"]]) } else if(euro == "III"){ fco_ldv_g <- f_co_ldv_g(e100 = g[["e100"]], aro = g[["aro"]], o2 = g[["o2"]], s = g[["s"]], e150 = g[["e150"]])/ f_co_ldv_g(e100 = bg2000[["e100"]], aro = bg2000[["aro"]], o2 = bg2000[["o2"]], s = bg2000[["s"]], e150 = bg2000[["e150"]]) fcov_ldv_g <- f_cov_ldv_g(aro = g[["aro"]], e100 = g[["e100"]], s = g[["s"]], olefin = g[["olefin"]], o2 = g[["o2"]], e150 = bg2000[["e150"]])/ f_cov_ldv_g(aro = bg2000[["aro"]], e100 = bg2000[["e100"]], s = bg2000[["s"]], olefin = bg2000[["olefin"]], o2 = bg2000[["o2"]], e150 = bg2000[["e150"]]) fnox_ldv_g <- f_nox_ldv_g(aro = g[["aro"]], e100 = g[["e100"]], s = g[["s"]], olefin = g[["olefin"]], o2 = g[["o2"]], e150 = g[["e150"]])/ f_nox_ldv_g(aro = bg2000[["aro"]], e100 = bg2000[["e100"]], s = bg2000[["s"]], olefin = bg2000[["olefin"]], o2 = bg2000[["o2"]], e150 = bg2000[["e150"]]) } else if(euro == "IV"){ fco_ldv_g <- f_co_ldv_g(e100 = g[["e100"]], aro = g[["aro"]], o2 = g[["o2"]], s = g[["s"]], e150 = g[["e150"]])/ f_co_ldv_g(e100 = bg2005[["e100"]], aro = bg2005[["aro"]], o2 = bg2005[["o2"]], s = bg2005[["s"]], e150 = bg2005[["e150"]]) fcov_ldv_g <- f_cov_ldv_g(aro = g[["aro"]], e100 = g[["e100"]], s = g[["s"]], olefin = g[["olefin"]], o2 = g[["o2"]], e150 = bg2005[["e150"]])/ f_cov_ldv_g(aro = bg2005[["aro"]], e100 = bg2005[["e100"]], s = bg2005[["s"]], olefin = bg2005[["olefin"]], o2 = bg2005[["o2"]], e150 = bg2005[["e150"]]) fnox_ldv_g <- f_nox_ldv_g(aro = g[["aro"]], e100 = g[["e100"]], s = g[["s"]], olefin = g[["olefin"]], o2 = g[["o2"]], e150 = g[["e150"]])/ f_nox_ldv_g(aro = bg2005[["aro"]], e100 = bg2005[["e100"]], s = bg2005[["s"]], olefin = bg2005[["olefin"]], o2 = bg2005[["o2"]], e150 = bg2005[["e150"]]) } else if(euro %in% c("V", "VI", "VIc")){ fco_ldv_g <- fcov_ldv_g <- fnox_ldv_g <- 1 } # } else if(tveh == "LDVD"){ if(euro %in% c("PRE", "I", "II")){ fco_ldv_d <- f_co_ldv_d(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]])/ f_co_ldv_d(den = bd1996[["den"]], pah = bd1996[["pah"]], cn = bd1996[["cn"]], t95 = bd1996[["t95"]]) fcov_ldv_d <- f_cov_ldv_d(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]])/ f_cov_ldv_d(den = bd1996[["den"]], pah = bd1996[["pah"]], cn = bd1996[["cn"]], t95 = bd1996[["t95"]]) fnox_ldv_d <- f_nox_ldv_d(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]])/ f_nox_ldv_d(den = bd1996[["den"]], pah = bd1996[["pah"]], cn = bd1996[["cn"]], t95 =bd1996[["t95"]]) fpm_ldv_d <- f_pm_ldv_d(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]], s = d[["s"]])/ f_pm_ldv_d(den = bd1996[["den"]], pah = bd1996[["pah"]], cn = bd1996[["cn"]], t95 = bd1996[["t95"]], s = bd1996[["s"]]) } else if(euro == "III"){ fco_ldv_d <- f_co_ldv_d(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]])/ f_co_ldv_d(den = bd2000[["den"]], pah = bd2000[["pah"]], cn = bd2000[["cn"]], t95 = bd2000[["t95"]]) fcov_ldv_d <- f_cov_ldv_d(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]])/ f_cov_ldv_d(den = bd2000[["den"]], pah = bd2000[["pah"]], cn = bd2000[["cn"]], t95 = bd2000[["t95"]]) fnox_ldv_d <- f_nox_ldv_d(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]])/ f_nox_ldv_d(den = bd2000[["den"]], pah = bd2000[["pah"]], cn = bd2000[["cn"]], t95 =bd2000[["t95"]]) fpm_ldv_d <- f_pm_ldv_d(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]], s = d[["s"]])/ f_pm_ldv_d(den = bd2000[["den"]], pah = bd2000[["pah"]], cn = bd2000[["cn"]], t95 = bd2000[["t95"]], s = bd2000[["s"]]) } else if(euro == "IV"){ fco_ldv_d <- f_co_ldv_d(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]])/ f_co_ldv_d(den = bd2005[["den"]], pah = bd2005[["pah"]], cn = bd2005[["cn"]], t95 = bd2005[["t95"]]) fcov_ldv_d <- f_cov_ldv_d(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]])/ f_cov_ldv_d(den = bd2005[["den"]], pah = bd2005[["pah"]], cn = bd2005[["cn"]], t95 = bd2005[["t95"]]) fnox_ldv_d <- f_nox_ldv_d(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]])/ f_nox_ldv_d(den = bd2005[["den"]], pah = bd2005[["pah"]], cn = bd2005[["cn"]], t95 =bd2005[["t95"]]) fpm_ldv_d <- f_pm_ldv_d(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]], s = d[["s"]])/ f_pm_ldv_d(den = bd2005[["den"]], pah = bd2005[["pah"]], cn = bd2005[["cn"]], t95 = bd2005[["t95"]], s = bd2005[["s"]]) } else if(euro %in% c("V", "VI", "VIc")){ fco_ldv_d <- fcov_ldv_d <- fnox_ldv_d <- fpm_ldv_d <- 1 } # } else if(tveh == "HDV"){ if(euro %in% c("PRE", "I", "II")){ fco_hdv <- f_co_hdv(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]])/ f_co_hdv(den = bd1996[["den"]], pah = bd1996[["pah"]], cn = bd1996[["cn"]], t95 = bd1996[["t95"]]) fcov_hdv <- f_cov_hdv(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]])/ f_cov_hdv(den = bd1996[["den"]], pah = bd1996[["pah"]], cn = bd1996[["cn"]], t95 = bd1996[["t95"]]) fnox_hdv <- f_nox_hdv(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]])/ f_nox_hdv(den = bd1996[["den"]], pah = bd1996[["pah"]], cn = bd1996[["cn"]], t95 =bd1996[["t95"]]) fpm_hdv <- f_pm_hdv(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]], s = d[["s"]])/ f_pm_hdv(den = bd1996[["den"]], pah = bd1996[["pah"]], cn = bd1996[["cn"]], t95 = bd1996[["t95"]], s = bd1996[["s"]]) } else if(euro == "III"){ fco_hdv <- f_co_hdv(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]])/ f_co_hdv(den = bd2000[["den"]], pah = bd2000[["pah"]], cn = bd2000[["cn"]], t95 = bd2000[["t95"]]) fcov_hdv <- f_cov_hdv(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]])/ f_cov_hdv(den = bd2000[["den"]], pah = bd2000[["pah"]], cn = bd2000[["cn"]], t95 = bd2000[["t95"]]) fnox_hdv <- f_nox_hdv(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]])/ f_nox_hdv(den = bd2000[["den"]], pah = bd2000[["pah"]], cn = bd2000[["cn"]], t95 =bd2000[["t95"]]) fpm_hdv <- f_pm_hdv(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]], s = d[["s"]])/ f_pm_hdv(den = bd2000[["den"]], pah = bd2000[["pah"]], cn = bd2000[["cn"]], t95 = bd2000[["t95"]], s = bd2000[["s"]]) } else if(euro == "IV"){ fco_hdv <- f_co_hdv(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]])/ f_co_hdv(den = bd2005[["den"]], pah = bd2005[["pah"]], cn = bd2005[["cn"]], t95 = bd2005[["t95"]]) fcov_hdv <- f_cov_hdv(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]])/ f_cov_hdv(den = bd2005[["den"]], pah = bd2005[["pah"]], cn = bd2005[["cn"]], t95 = bd2005[["t95"]]) fnox_hdv <- f_nox_hdv(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]])/ f_nox_hdv(den = bd2005[["den"]], pah = bd2005[["pah"]], cn = bd2005[["cn"]], t95 =bd2005[["t95"]]) fpm_hdv <- f_pm_hdv(den = d[["den"]], pah = d[["pah"]], cn = d[["cn"]], t95 = d[["t95"]], s = d[["s"]])/ f_pm_hdv(den = bd2005[["den"]], pah = bd2005[["pah"]], cn = bd2005[["cn"]], t95 = bd2005[["t95"]], s = bd2005[["s"]]) } else if(euro %in% c("V", "VI", "VIc")){ fco_hdv <- fcov_hdv <- fnox_hdv <- fpm_hdv <- 1 } fif <- function(x) ifelse(x >= 1, 1, x) dfl <- list( LDVG = list(CO = list(fif(fco_ldv_g)), COV = list(fif(fcov_ldv_g)), NOx = list(fif(fnox_ldv_g))), LDVD = list(CO = list(fif(fco_ldv_d)), COV = list(fif(fcov_ldv_d)), NOx = list(fif(fnox_ldv_d)), PM = list(fif(fnox_ldv_d))), HDV = list(CO = list(fif(fco_hdv)), COV = list(fif(fcov_hdv)), NOx = list(fif(fnox_hdv)), PM = list(fif(fpm_hdv)))) return(dfl) } else { data.table::rbindlist(lapply(seq_along(euro), function(i) { fuel_corr(euro = euro[i]) -> fcorr value <- unlist(fcorr) names(value) fcorr <- as.data.frame(value) fcorr$vehpol <- names(value) fcorr <- cbind(fcorr, do.call("rbind", strsplit(fcorr$vehpol, "\\."))) fcorr$euro <- euro[i] fcorr })) -> fcorr return(fcorr) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/fuel_corr.R
#' Download vein project #' #' \code{\link{get_project}} downloads a project for running vein. #' The projects are available on Github.com/atmoschem/vein/projects #' #' @param directory Character; Path to an existing or a new directory to be created. #' @param case Character; One of of the following: #' \tabular{llll}{ #' \strong{case} \tab \strong{Description}\tab \strong{EF} \tab \strong{Outputs} \cr #' brazil or brazil_bu or brasil or brasil_bu\tab Bottom-up \tab CETESB \tab .rds\cr #' emislacovid \tab Bottom-up March 2020\tab CETESB \tab .rds\cr #' brazil_bu_csvgz \tab Bottom-up \tab CETESB+tunnel \tab .csv.gz\cr #' brazil_csv \tab Bottom-up. Faster but heavier\tab CETESB\tab .csv\cr #' brazil_td_chem \tab Top-down with chemical mechanisms\tab CETESB\tab .csv and .rds\cr #' brazil_bu_chem \tab Bottom-up chemical mechanisms\tab CETESB+tunnel\tab .rds\cr #' brazil_bu_chem_streets \tab Bottom-up chemical mechanisms for streets and MUNICH\tab CETESB+tunnel\tab .rds\cr #' brazil_td_chem_im \tab Top-down with chemical mechanisms+IM\tab CETESB\tab .csv and .rds\cr #' brazil_bu_chem_im \tab Bottom-up chemical mechanisms+IM\tab CETESB+tunnel\tab .rds\cr #' brazil_bu_chem_month \tab Bottom-up chemical mechanisms\tab CETESB+tunnel\tab .rds\cr #' brazil_bu_chem_streets_im \tab Bottom-up chemical mechanisms for streets and MUNICH+IM\tab CETESB+tunnel\tab .rds\cr #' sebr_cb05co2 \tab Top-down SP, MG and RJ\tab CETESB+tunnel\tab .rds\cr #' amazon2014 \tab Top-down Amazon\tab CETESB+tunnel\tab csv and.rds\cr #' curitiba \tab Bottom-down +GTFS\tab CETESB+tunnel\tab csv and.rds\cr #' masp2020 \tab Bottom-down\tab CETESB+tunnel\tab csv and.rds\cr #' ecuador_td \tab Top-down\tab EEA\tab csv and.rds\cr #' ecuador_td_im \tab Top-down\tab EEA\tab csv and.rds\cr #' ecuador_td_hot \tab Top-down\tab EEA\tab csv and.rds\cr #' ecuador_td_hot_month \tab Top-down\tab EEA\tab csv and.rds\cr #' moves_bu \tab Bottom-up\tab US/EPA MOVES \tab csv and.rds (requires MOVES >=3.0 on Windows)\cr #' manizales_bu \tab Bottom-up chemical mechanisms\tab EEA\tab csv, csv.gz, .rds\cr #' sebr_cb05co2_im \tab Top-down SP, MG and RJ IM\tab CETESB+tunnel\tab .rds\cr #' eu_bu_chem \tab Bottom-up chemical mechanisms\tab EEA 2019\tab .rds\cr #' eu_bu_chem_simple \tab Bottom-up chemical mechanisms 7 veh\tab EEA 2019\tab .rds\cr #' china_bu_chem \tab Bottom-up chemical mechanisms\tab MEE China\tab .rds\cr #' } #' @param url String, with the URL to download VEIN project #' @note default case can be any of "brasil", "brazil", "brazil_bu", "brasil_bu", they are #' the same #' In any case, if you find any error, please, send a pull request in github. #' #' In Sao Paulo the IM programs was functioning until 2011. #' #' @importFrom utils download.file untar #' @export #' @examples \dontrun{ #' #do not run #' get_project("awesomecity") #' } #' get_project <- function(directory, case = "brazil_bu_chem", url){ if(missing(directory)) stop("Please, add a path to a directory") #nocov start if(missing(url)){ # brazil #### if(case %in% c("brasil", "brazil", "brazil_bu", "brasil_bu", "brazil_bu_chem", "brazil_bu_csvgz", "brazil_bu_csv", "brazil_bu_cb05", "brazil_mech", "brazil_bu_chem_month")) { URL <- "https://raw.githubusercontent.com/atmoschem/vein/master/projects/brazil_bu_chem.tar.gz" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = tf) utils::untar(tarfile = tf, exdir = directory) message("Your directory is in ", directory) # moves_bu #### } else if(case %in% c("moves_bu", "moves")){ URL <- "https://raw.githubusercontent.com/atmoschem/vein/master/projects/moves.tar.gz" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = tf) utils::untar(tarfile = tf, exdir = directory) message("Your directory is in ", directory) # emislacovid #### } else if(case == "emislacovid"){ URL <- "https://raw.githubusercontent.com/atmoschem/vein/master/projects/emislacovid.tar.gz" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = tf) utils::untar(tarfile = tf, exdir = directory) message("Your directory is in ", directory) # brazil_bu_chem_im #### } else if(case %in% c("brazil_bu_chem_im")){ URL <- "https://raw.githubusercontent.com/atmoschem/vein/master/projects/brazil_bu_chem.tar.gz" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = tf) utils::untar(tarfile = tf, exdir = directory) x <- readLines(paste0(directory, "/main.R")) x <- gsub(pattern = "IM <- FALSE", replacement = "IM <- TRUE", x = x) writeLines(x, paste0(directory, "/main.R")) message("Your directory is in ", directory) # manizales_bu #### } else if(case %in% c("manizales_bu")){ URL <- "https://raw.githubusercontent.com/atmoschem/vein/master/projects/manizales_bu.tar.gz" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = tf) utils::untar(tarfile = tf, exdir = directory) message("Your directory is in ", directory) # brazil_bu_chem_streets #### } else if(case %in% c("brazil_bu_chem_streets", "brazil_bu_chem_streets_im")){ URL <- "https://raw.githubusercontent.com/atmoschem/vein/master/projects/brazil_bu_chem.tar.gz" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = tf) utils::untar(tarfile = tf, exdir = directory) x <- readLines(paste0(directory, "/main.R"))[1:153] x <- gsub(pattern = "type <- 'grids'", replacement = "type <- 'streets'", x = x) writeLines(x, paste0(directory, "/main.R")) message("Your directory is in ", directory) # masp2020 #### } else if(case %in% c("masp2020")){ URL <- "https://raw.githubusercontent.com/atmoschem/vein/master/projects/MASP_2020.tar.gz" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = tf) utils::untar(tarfile = tf, exdir = directory) message("Your directory is in ", directory) # brazil_td_chem #### } else if(case %in% c("brazil_td_chem")){ URL <- "https://raw.githubusercontent.com/atmoschem/vein/master/projects/brazil_td_chem.tar.gz" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = tf) utils::untar(tarfile = tf, exdir = directory) message("Your directory is in ", directory) # brazil_td_chem_im #### } else if(case %in% c("brazil_td_chem_im")){ URL <- "https://raw.githubusercontent.com/atmoschem/vein/master/projects/brazil_td_chem_im.tar.gz" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = tf) utils::untar(tarfile = tf, exdir = directory) message("Your directory is in ", directory) # ecuador_td #### } else if(case %in% c("ecuador_td", "ecuador_td_hot")){ URL <- "https://raw.githubusercontent.com/atmoschem/vein/master/projects/ecuador_td.tar.gz" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = tf) utils::untar(tarfile = tf, exdir = directory) message("Your directory is in ", directory) # ecuador_td_im #### } else if(case %in% c("ecuador_td_im")){ URL <- "https://raw.githubusercontent.com/atmoschem/vein/master/projects/ecuador_td.tar.gz" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = tf) utils::untar(tarfile = tf, exdir = directory) x <- readLines(paste0(directory, "/main.R")) x <- gsub(pattern = "IM <- FALSE", replacement = "IM <- TRUE", x = x) writeLines(x, paste0(directory, "/main.R")) message("Your directory is in ", directory) # ecuador_td_hot_month #### } else if(case %in% c("ecuador_td_hot_month")){ URL <- "https://raw.githubusercontent.com/atmoschem/vein/master/projects/ecuador_td_hot_month.tar.gz" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = tf) utils::untar(tarfile = tf, exdir = directory) message("Your directory is in ", directory) # amazon2014 #### } else if(case %in% c("amazon2014")){ URL <- "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/amazonas2014.tar.gz" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = tf) utils::untar(tarfile = tf, exdir = directory) message("Your directory is in ", directory) # eu_bu_chem #### } else if(case %in% c("eu_bu_chem")){ URL <- "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/eu_bu_chem.tar.gz" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = tf) utils::untar(tarfile = tf, exdir = directory) message("Your directory for vehicular emissions is in ", directory) # eu_bu_chem_simple #### } else if(case %in% c("eu_bu_chem_simple")){ URL <- "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/eu_bu_chem_simple.tar.gz" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = tf) utils::untar(tarfile = tf, exdir = directory) message("Your directory for vehicular emissions is in ", directory) # china_bu_chem #### } else if(case %in% c("china_bu_chem")){ URL <- "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/china_bu_chem.tar.gz" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = tf) utils::untar(tarfile = tf, exdir = directory) message("Your directory for vehicular emissions is in ", directory) # curitiba #### } else if(case %in% c("curitiba")){ URL <- "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/curitiba_all/curitiba.tar.gz" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = tf) utils::untar(tarfile = tf, exdir = directory) message("Your directory for vehicular emissions is in ", directory) URL <- "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/curitiba_all/gtfs_cur.zip" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = paste0(directory, "/network/gtfs_cur.zip")) message("GTFS Curitba is in ", paste0(directory, "/network")) URL <- "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/curitiba_all/curitiba_industrial.tar.gz" tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = URL, destfile = tf) utils::untar(tarfile = tf, exdir = paste0(directory, "/industry")) message("Your directory for industrial emissions is in ", directory) } else if(case %in% c("sebr_cb05co2")){ dir.create(directory) tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/sebr_cb05co2/MG.tar.gz", destfile = tf) utils::untar(tarfile = tf, exdir = paste0(directory, "/MG")) utils::download.file(url = "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/sebr_cb05co2/SP.tar.gz", destfile = tf) utils::untar(tarfile = tf, exdir = paste0(directory, "/SP")) utils::download.file(url = "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/sebr_cb05co2/RJ.tar.gz", destfile = tf) utils::untar(tarfile = tf, exdir = paste0(directory, "/RJ")) utils::download.file(url = "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/sebr_cb05co2/merge_wrf.R", destfile = paste0(directory, "/merge_wrf.R")) utils::download.file(url = "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/sebr_cb05co2/sebr_cb05co2.Rproj", destfile = paste0(directory, "/sebr_cb05co2.Rproj")) utils::download.file(url = "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/sebr_cb05co2_wrfi.tar.gz", destfile = paste0(directory, "/sebr_cb05co2_wrfi.tar.gz")) utils::untar(tarfile = paste0(directory, "/sebr_cb05co2_wrfi.tar.gz"), exdir = directory) message("Your directory is in ", directory) #nocov end # sebr_cb05co2_im #### } else if(case %in% c("sebr_cb05co2_im")){ dir.create(directory) tf <- paste0(tempfile(), ".tar.gz") utils::download.file(url = "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/sebr_cb05co2_im/MG.tar.gz", destfile = tf) utils::untar(tarfile = tf, exdir = paste0(directory, "/MG")) utils::download.file(url = "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/sebr_cb05co2_im/SP.tar.gz", destfile = tf) utils::untar(tarfile = tf, exdir = paste0(directory, "/SP")) utils::download.file(url = "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/sebr_cb05co2_im/RJ.tar.gz", destfile = tf) utils::untar(tarfile = tf, exdir = paste0(directory, "/RJ")) utils::download.file(url = "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/sebr_cb05co2_im/merge_wrf.R", destfile = paste0(directory, "/merge_wrf.R")) utils::download.file(url = "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/sebr_cb05co2_im/sebr_cb05co2.Rproj", destfile = paste0(directory, "/sebr_cb05co2.Rproj")) utils::download.file(url = "https://gitlab.com/ibarraespinosa/veinextras/-/raw/master/sebr_cb05co2_wrfi.tar.gz", destfile = paste0(directory, "/sebr_cb05co2_wrfi.tar.gz")) utils::untar(tarfile = paste0(directory, "/sebr_cb05co2_wrfi.tar.gz"), exdir = directory) message("Your directory is in ", directory) #nocov end } else{ stop("Other cases not supported yet") } } else { URL <- url } }
/scratch/gouwar.j/cran-all/cranData/vein/R/get_project.R
#' Allocate emissions gridded emissions into streets (grid to emis street) #' #' @description \code{\link{grid_emis}} it is sort of the opposite of #' \code{\link{emis_grid}}. It allocates gridded emissions into streets. #' This function applies \code{\link{emis_dist}} into each grid cell using #' lapply. This function is in development and pull request are welcome. #' #' @param spobj A spatial dataframe of class "sp" or "sf". When class is "sp" #' it is transformed to "sf". #' @param g A grid with class "SpatialPolygonsDataFrame" or "sf". This grid #' includes the total emissions with the column "emission". If the profile is going #' to be used, the column 'emission' must include the sum of the emissions #' for each profile. For instance, if profile covers the hourly emissions, #' the column 'emission' bust be the sum of the hourly emissions. #' @param top_down Logical; requires emissions named `emissions` and allows #' to apply profile factors. If your data is hourly emissions or a spatial #' grid with several emissions at different hours, being each hour a column, #' it is better to use top_down = FALSE. In this way all the hourly emissions #' are considered, however, each hourly emissions has to have the name "V" and the #'number of the hour like "V1" #' @param sr Spatial reference e.g: 31983. It is required if spobj and g are #' not projected. Please, see http://spatialreference.org/. #' @param pro Numeric, Matrix or data-frame profiles, for instance, pc_profile. #' @param char Character, name of the first letter of hourly emissions. New variables in R #' start with the letter "V", for your hourly emissions might start with the letter "h". This option #' applies when top_down is FALSE. For instance, if your hourly emissions are: "h1", "h2", #' "h3"... `char`` can be "h" #' #' @param verbose Logical; to show more info. #' @importFrom sf st_sf st_as_sf st_transform st_set_geometry st_length st_intersection st_geometry #' @importFrom data.table as.data.table ':=' #' @export #' @note \strong{Your gridded emissions might have flux units (mass / area / time(implicit))} #' \strong{You must multiply your emissions with the area to return to the original units.} #' @examples \dontrun{ #' data(net) #' data(pc_profile) #' 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 #' lef <- EmissionFactorsList(ef_cetesb("CO", "PC_G")) #' E_CO <- emis(veh = pc1,lkm = net$lkm, ef = lef, #' profile = 1, speed = Speed(1)) #' E_CO_STREETS <- emis_post(arra = E_CO, by = "streets", net = net) #' #' g <- make_grid(net, 1/102.47/2) #500m in degrees #' #' gCO <- emis_grid(spobj = E_CO_STREETS, g = g) #' gCO$emission <- gCO$V1 #' area <- sf::st_area(gCO) #' area <- units::set_units(area, "km^2") #Check units! #' gCO$emission <- gCO$emission*area #' # #' \dontrun{ #' #do not run #' library(osmdata) #' library(sf) #' osm <- osmdata_sf( #' add_osm_feature( #' opq(bbox = st_bbox(gCO)), #' key = 'highway'))$osm_lines[, c("highway")] #' st <- c("motorway", "motorway_link", "trunk", "trunk_link", #' "primary", "primary_link", "secondary", "secondary_link", #' "tertiary", "tertiary_link") #' osm <- osm[osm$highway %in% st, ] #' plot(osm, axes = T) #' # top_down requires name `emissions` into gCO` #' xnet <- grid_emis(osm, gCO, top_down = TRUE) #' plot(xnet, axes = T) #' # bottom_up requires that emissions are named `V` plus the hour like `V1` #' xnet <- grid_emis(osm, gCO,top_down= FALSE) #' plot(xnet["V1"], axes = T) #' } #' } grid_emis <- function(spobj, g, top_down = FALSE, sr, pro, char, verbose = FALSE){ net <- sf::st_as_sf(spobj) net$id <- NULL netdata <- sf::st_set_geometry(net, NULL) g <- sf::st_as_sf(g) g$id <- NULL g$id <- 1:nrow(g) net$lkm1 <- as.numeric(sf::st_length(net)) geo <- sf::st_geometry(net) xg <- suppressMessages(suppressWarnings(sf::st_intersection(net, g))) if(sf::st_crs(g) != sf::st_crs(net)){ if(verbose) message("Changing CRS of 'spobj' to match 'g'") #nocov net <- sf::st_transform(net, st_crs(g)) } for(i in 1:length(netdata)){ netdata[, i] <- as.numeric(netdata[, i]) } net <- sf::st_sf(netdata, geometry = sf::st_geometry(net)) if(!missing(sr)){ if(inherits(sr, "character")){ sr <- as.numeric(substr(sr, 12, nchar(sr))) } if(verbose) message("Transforming spatial objects to 'sr' ") #nocov net <- sf::st_transform(net, sr) g <- sf::st_transform(g, sr) } if(!top_down) { net$id <- NULL a <- suppressMessages(suppressWarnings(sf::st_intersection(net, g))) a$lm <- st_length(a) df <- data.table::as.data.table(a) total_lkm <- lm <- id <- NULL df[, total_lkm := sum(lm), by = id] vars <- names(g)[grep(pattern = char, x = names(g))] cdf <- colSums(sf::st_set_geometry(g, NULL)[vars], na.rm = T) for(i in 1:length(cdf)) { df[[vars[i]]] <- df[[vars[i]]]*df$lm/df$total_lkm df[[vars[i]]] <- df[[vars[i]]]*cdf[i]/sum(df[[vars[i]]], na.rm = TRUE) } data.table::setDF(df) df <- sf::st_as_sf(df, geometry = df$geometry) return(df) } else { sumg <- sum(g$emission) if(missing(pro)){ lxxy <- do.call("rbind", lapply(1:length(g$id), function(i) { emis_dist(gy = g[g$id == i,]$emission, spobj = xg[xg$id == i, ], verbose = FALSE) })) df <- st_set_geometry(lxxy, NULL) fx <- as.numeric(sumg/sum(df, na.rm = TRUE)) df <- df*fx if(verbose) { #nocov cat(paste0("Sum of gridded emissions ", round(sumg, 2), "\n")) } if(verbose) { #nocov cat(paste0("Sum of street emissions ", round(sum(df), 2), "\n")) } df <- sf::st_sf(df, geometry = sf::st_geometry(lxxy)) # if(verbose) cat("Columns:", names(df), "\n") return(df) } if(!missing(pro) ){ lxxy <- do.call("rbind", lapply(1:length(g$id), function(i) { emis_dist(gy = g[g$id == i,]$emission, spobj = xg[xg$id == i, ], pro = pro, verbose = FALSE) })) df <- st_set_geometry(lxxy, NULL) fx <- as.numeric(sumg/sum(df, na.rm = TRUE)) df <- df*fx if(verbose) { cat(paste0("Sum of gridded emissions ", round(sum(df), 2), "\n")) } if(verbose) { #nocov cat(paste0("Sum of street emissions ", round(sum(df), 2), "\n")) } df <- sf::st_sf(df, geometry = sf::st_geometry(lxxy)) return(df) } } }
/scratch/gouwar.j/cran-all/cranData/vein/R/grid_emis.R
#' Estimation of average daily hot-soak evaporative emissions #' #' @description \code{hot_soak} estimates of evaporative emissions from EMEP/EEA #' emisison guidelines #' #' @param x Mean number of trips per vehicle per day #' @param carb fraction of gasoline vehicles with carburetor or fuel return system #' @param p Fraction of trips finished with hot engine #' @param eshotc average daily hot-soak evaporative factor for vehicles with #' carburetor or fuel return system #' @param eswarmc average daily cold-warm-soak evaporative factor for vehicles #' with carburator or fuel return system #' @param eshotfi average daily hot-soak evaporative factor for vehicles #' with fuel injection and returnless fuel systems #' @return numeric vector of emission estimation in grams #' @name running_losses-deprecated #' @seealso \code{\link{vein-deprecated}} #' @keywords internal NULL #' @rdname vein-deprecated #' @section \code{Evaporative}: #' For \code{running_losses}, use \code{\link{emis_evap}}. #' #' @references Mellios G and Ntziachristos 2016. Gasoline evaporation. In: #' EEA, EMEP. EEA air pollutant emission inventory guidebook-2009. European #' Environment Agency, Copenhagen, 2009 #' @export #' @examples \dontrun{ #' # Do not run #' } hot_soak <- function(x,carb,p,eshotc,eswarmc,eshotfi) { .Deprecated("emis_evap") "Evaporative emissions" }
/scratch/gouwar.j/cran-all/cranData/vein/R/hot_soak.R
#' Helper function to copy and zip projects #' #' @description \code{invcop} help to copy and zip projects #' #' @param in_name Character; Name of current project. #' @param out_name Character; Name of output project. #' @param all Logical; copy ALL (and for once) or not. #' @param main Logical; copy or not. #' @param ef Logical; copy or not. #' @param est Logical; copy or not. #' @param network Logical; copy or not. #' @param veh_rds Logical; copy or not. #' @param veh_csv Logical; copy or not. #' @param zip Logical; zip or not. #' @return emission estimation g/h #' @note This function was created to copy and zip project without the emis. #' @export #' @examples \dontrun{ #' # Do not run #' } invcop <- function (in_name = getwd(), out_name, all = FALSE, main = TRUE, ef = TRUE, est = TRUE, network = TRUE, veh_rds = FALSE, veh_csv = TRUE, zip = TRUE) { # # nocov start # # lista carpetas # dirs <- list.dirs(path = in_name, # full.names = TRUE, # recursive = TRUE) # # #reemplaza in)_name con out_name # dirs2 <- gsub(pattern = in_name, # replacement = out_name, # x = dirs) # # if(test) return(dirs2) # # # crea out_name # for(i in 1:length(dirs2)){ # dir.create(path = dirs2[i], recursive = TRUE) # } # # # all # if(all){ # min <- list.files(path = paste0(in_name), # pattern = "*", # full.names = TRUE) # mout <- paste0(out_name) # file.copy(from = min, to = mout, overwrite = TRUE, recursive = TRUE) # } else { # # main # if(main){ # min <- list.files(path = paste0(in_name), # pattern = "*", # full.names = TRUE) # mout <- paste0(out_name) # file.copy(from = min, to = mout, overwrite = TRUE) # } # # # ef # if(ef){ # efin <- list.files(path = paste0(in_name, "/ef"), # pattern = "*", # full.names = TRUE) # efout <- paste0(out_name, "/ef") # file.copy(from = efin, to = efout, overwrite = TRUE, recursive = TRUE) # } # # # est # if(est){ # estin <- list.files(path = paste0(in_name, "/est"), # pattern = "*", # full.names = TRUE) # estout <- paste0(out_name, "/est") # file.copy(from = estin, to = estout, overwrite = TRUE, recursive = TRUE) # } # # # network # if(network){ # nin <- list.files(path = paste0(in_name, "/network"), # pattern = "*", # full.names = TRUE) # nout <- paste0(out_name, "/network") # file.copy(from = nin, to = nout, overwrite = TRUE, recursive = TRUE) # } # # # veh rds # if(veh_rds){ # vin <- list.files(path = paste0(in_name, "/veh"), # pattern = ".rds", # full.names = TRUE) # vout <- paste0(out_name, "/veh") # file.copy(from = vin, to = vout, overwrite = TRUE, recursive = TRUE) # } # # # veh csv # if(veh_csv){ # vin <- list.files(path = paste0(in_name, "/veh"), # pattern = ".csv", # full.names = TRUE) # vout <- paste0(out_name, "/veh") # file.copy(from = vin, to = vout, overwrite = TRUE, recursive = TRUE) # } # } # # # emis # # if(emis){ # # ein <- list.files(path = paste0(in_name, "/emis"), # # pattern = "*", # # full.names = TRUE) # # eout <- paste0(out_name, "/veh") # # file.copy(from = ein, to = eout, overwrite = TRUE, recursive = TRUE) # # } # # zip # if(zip){ # files2zip <- dir(out_name, full.names = TRUE) # zip(zipfile = out_name, files = files2zip) # } # nocov end .Deprecated("get_project") "Copy inventory" }
/scratch/gouwar.j/cran-all/cranData/vein/R/invcop.R
#' Inventory function. #' #' @description \code{inventory} produces an structure of directories and scripts #' in order to run vein. It is required to know the vehicular composition of the #' fleet. #' #' @param name Character, path to new main directory for running vein. #' NO BLANK SPACES #' @param vehcomp Vehicular composition of the fleet. It is required a named #' numerical vector with the names "PC", "LCV", "HGV", "BUS" and "MC". In the #' case that there are no vehicles for one category of the composition, the name #' should be included with the number zero, for example, PC = 0. The maximum #' number allowed is 99 per category. #' @param show.main Logical; Do you want to see the new main.R file? #' @param scripts Logical Do you want to generate or no R scripts? #' @param show.dir Logical value for printing the created directories. #' @param show.scripts Logical value for printing the created scripts. #' @param clear Logical value for removing recursively the directory and create #' another one. #' @param showWarnings Logical, showWarnings? #' @param rush.hour Logical, to create a template for morning rush hour. #' @return Structure of directories and scripts for automating the compilation of #' vehicular emissions inventory. The structure can be used with another type of #' sources of emissions. The structure of the directories is: daily, ef, emi, #' est, images, network and veh. This structure is a suggestion and the user can #' use another. #'' #' ef: it is for storing the emission factors data-frame, similar to data(fe2015) #' but including one column for each of the categories of the vehicular #' composition. For instance, if PC = 5, there should be 5 columns with emission #' factors in this file. If LCV = 5, another 5 columns should be present, and #' so on. #' #' emi: Directory for saving the estimates. It is suggested to use .rds #' extension instead of .rda. #' #' est: Directory with subdirectories matching the vehicular composition for #' storing the scripts named input.R. #' #' images: Directory for saving images. #' #' network: Directory for saving the road network with the required attributes. #' This file will include the vehicular flow per street to be used by age* #' functions. #' #' veh: Directory for storing the distribution by age of use of each category of #' the vehicular composition. Those are data-frames with number of columns with #' the age distribution and number of rows as the number of streets. The class #' of these objects is "Vehicles". Future versions of vein will generate #' Vehicles objects with the explicit spatial component. #' #' The name of the scripts and directories are based on the vehicular #' composition, however, there is included a file named main.R which is just #' an R script to estimate all the emissions. It is important to note that the #' user must add the emission factors for other pollutants. Also, this function #' creates the scripts input.R where the user must specify the inputs for the #' estimation of emissions of each category. Also, there is a file called #' traffic.R to generate objects of class "Vehicles". #' The user can rename these scripts. #' @export #' @importFrom utils file.edit #' @examples \dontrun{ #' name = file.path(tempdir(), "YourCity") #' inventory(name = name) #' } #' inventory <- function(name, vehcomp = c(PC = 1, LCV = 1, HGV = 1, BUS = 1, MC = 1), show.main = FALSE, scripts = TRUE, show.dir = FALSE, show.scripts = FALSE, clear = TRUE, rush.hour = FALSE, showWarnings = FALSE){ if(Sys.info()[['sysname']] == "Windows") { name <- gsub("\\\\", "/", name) } # directorys dovein <- function(){ dir.create(path = name, showWarnings = showWarnings) dir.create(path = paste0(name, "/profiles"), showWarnings = showWarnings) dir.create(path = paste0(name, "/ef"), showWarnings = showWarnings) dir.create(path = paste0(name, "/emi"), showWarnings = showWarnings) dir.create(path = paste0(name, "/post"), showWarnings = showWarnings) dir.create(path = paste0(name, "/post/grids"), showWarnings = showWarnings) dir.create(path = paste0(name, "/post/streets"), showWarnings = showWarnings) dir.create(path = paste0(name, "/post/df"), showWarnings = showWarnings) dir.create(path = paste0(name, "/est"), showWarnings = showWarnings) dir.create(path = paste0(name, "/images"), showWarnings = showWarnings) dir.create(path = paste0(name, "/network"), showWarnings = showWarnings) dir.create(path = paste0(name, "/veh"), showWarnings = showWarnings) if(vehcomp["PC"] > 0){ for(i in 1:vehcomp[1]){ if(i < 10) { dir.create(path = paste0(name, "/emi/PC_0", i), showWarnings = showWarnings) } else { dir.create(path = paste0(name, "/emi/PC_", i), showWarnings = showWarnings) }} } else {message("no PC")} if(vehcomp["LCV"] > 0){ for(i in 1:vehcomp[2]){ if(i < 10) { dir.create(path = paste0(name, "/emi/LCV_0", i), showWarnings = showWarnings) } else { dir.create(path = paste0(name, "/emi/LCV_", i), showWarnings = showWarnings) }} } else {message("no LCV")} if(vehcomp["HGV"] > 0){ for(i in 1:vehcomp[3]){ if(i < 10) { dir.create(path = paste0(name, "/emi/HGV_0", i), showWarnings = showWarnings) } else { dir.create(path = paste0(name, "/emi/HGV_", i), showWarnings = showWarnings) }} } else {message("no HGV")} if(vehcomp["BUS"] > 0){ for(i in 1:vehcomp[4]){ if(i < 10) { dir.create(path = paste0(name, "/emi/BUS_0", i), showWarnings = showWarnings) } else { dir.create(path = paste0(name, "/emi/BUS_", i), showWarnings = showWarnings) }} } else {message("no BUS")} if(vehcomp["MC"] > 0){ for(i in 1:vehcomp[5]){ if(i < 10) { dir.create(path = paste0(name, "/emi/MC_0", i), showWarnings = showWarnings) } else { dir.create(path = paste0(name, "/emi/MC_", i), showWarnings = showWarnings) }} } else {message("no MC")} } if(clear == FALSE){ dovein() } else { unlink(name, recursive=TRUE) dovein() } # # files if(scripts == FALSE){ message("no scripts") } else{ lista <- list.dirs(path = paste0(name,"/emi")) lista <- lista[2:length(lista)] lista2 <- gsub(pattern = name, x = lista, replacement = "") lista3 <- gsub(pattern = "/emi/", x = lista2, replacement = "") dirs <- list.dirs(path = name, full.names = TRUE) for (i in 1:length(lista)){ sink(paste0(dirs[1], "/est/", lista3[i],"_input.R")) cat("# Network \n") cat("net <- readRDS('network/net.rds')\n") cat("lkm <- net$lkm\n") cat("# speed <- readRDS('network/speed.rds')\n\n") cat("# Vehicles\n") cat(paste0("veh <- readRDS('veh/", lista3[[i]], ".rds')"), "\n") cat("# Profiles\n") cat("data(profiles)\n") if(rush.hour){ cat("pc <- matrix(1)\n") } else{ cat("pc <- profiles[[1]]\n") } cat("# pc <- read.csv('profiles/pc.csv') #Change with your data\n") cat("# Emission Factors data-set\n") cat("data(fe2015)\n") cat("efe <- fe2015\n") cat("# efe <- read.csv('ef/fe2015.csv')\n") cat("efeco <- 'PC_G' # Character to identify the column of the respective EF\n") cat("efero <- ifelse(is.data.frame(veh), ncol(veh), ncol(veh[[1]]))\n") cat("# efero reads the number of the vehicle distribution\n") cat("trips_per_day <- 5\n\n") cat("# Mileage, Check name of categories with names(fkm)\n") cat("# data(fkm)\n") cat("# pckm <- fkm[['KM_PC_E25']](1:efero)\n") cat("# pckm <- cumsum(pckm)\n\n") cat("# Sulphur\n") cat("# sulphur <- 50 # ppm\n\n\n") cat("# Input and Output\n\n") cat(paste0("directory <- ", deparse(lista3[i]), "\n")) cat("vfuel <- 'E_25' \n") cat("vsize <- '' # It can be small/big/<=1400, one word\n") cat("vname <- ", deparse(lista3[i]), "\n") cat("\n\n") cat("# CO \n") cat("pol <- 'CO' \n") cat("print(pol)\n") cat("message('This is just an example!\n You need to update this to your project!')\n") cat("x <- efe[efe$Pollutant == pol, 'PC_G']\n") cat("lefe <- EmissionFactorsList(x)\n") cat("array_x <- emis(veh = veh, lkm = lkm, ef = lefe, profile = pc, speed = Speed(34))\n") cat("x_DF <- emis_post(arra = array_x, veh = vname, size = vsize,\n") cat(" fuel = vfuel, pollutant = pol, by = 'veh')\n") cat("x_STREETS <- emis_post(arra = array_x, pollutant = pol,\n") cat(" by = 'streets_wide') \n") cat("saveRDS(x_DF, file = paste0('emi/',", deparse(lista3[i]), ",'_', pol, '_DF.rds'))\n") cat("saveRDS(x_STREETS, file = paste0('emi/',", deparse(lista3[i]), ",'_', pol, '_STREETS.rds'))\n") cat("rm(array_x, x_DF, x_STREETS, pol, lefe)\n\n") cat("# Other Pollutants...") sink() } dirs <- list.dirs(path = name, full.names = TRUE, recursive = TRUE) message(paste0("Project directory at ", dirs[1])) # message(paste0("main file ", name, "/main.R")) sink(paste0(name, "/main.R")) cat(paste0("prev <- getwd()\n")) cat("#Changing working directory\n") cat(paste0("print(setwd('", dirs[1], "'))\n")) cat("library(vein)\n") cat("sessionInfo()\n\n") cat("# 0 Delete previous emissions? ####\n") cat("# borrar <- list.files('emi',\n") cat("# pattern = '.rds', recursive = TRUE,\n") cat("# full.names = TRUE)\n\n") cat("# 1) Network ####\n") cat("# Edit your net information and save net.rds it in network directory\n") cat("# Your net must contain traffic per street at morning rush hour\n") cat("# Below an example using the data in VEIN\n") cat("data(net)\n") cat("net <- sf::st_as_sf(net)\n") cat("net <- sf::st_transform(net, 31983)\n") cat("saveRDS(net, 'network/net.rds')\n\n") cat("## Are you going to need Speed?\n") cat("data(pc_profile)\n") if(rush.hour){ cat("speed <- data.frame(S8 = net$ps)\n") cat("saveRDS(speed, 'network/speed.rds')\n\n") } else{ cat("pc_week <- temp_fact(net$ldv+net$hdv, pc_profile)\n") cat("speed <- netspeed(pc_week, net$ps, net$ffs, net$capacity, net$lkm, alpha = 1)\n") cat("saveRDS(speed, 'network/speed.rds')\n\n") } cat("# 2) Traffic ####\n") cat("# Edit your file traffic.R\n\n") cat("source('traffic.R') # Edit traffic.R\n\n") cat("# 3) Estimation #### \n") cat("# Edit each input.R\n") cat("# You must have all the information required in each input.R\n") cat("inputs <- list.files(path = 'est', pattern = 'input.R',\n") cat(" recursive = TRUE, full.names = TRUE)\n") cat("for (i in 1:length(inputs)){\n") cat( " print(inputs[i])\n" ) cat( " source(inputs[i])\n" ) cat("}\n") cat("# 4) Post-estimation #### \n") cat("g <- make_grid(net, 1000)\n") cat("source('post.R')\n") cat("#Changing to original working directory\n") cat("print(setwd(prev))\n") sink() sink(paste0(name, "/traffic.R")) cat("net <- readRDS('network/net.rds')\n") cat("PC_01 <- age_ldv(x = net$ldv, name = 'PC', k = 3/4)\n") cat("saveRDS(PC_01, file = 'veh/PC_01.rds')\n") cat("LCV_01 <- age_ldv(x = net$ldv, name = 'LCV', k = 1/4/2)\n") cat("saveRDS(PC_01, file = 'veh/LCV_01.rds')\n") cat("HGV_01 <- age_ldv(x = net$hdv, name = 'HGV', k = 3/4)\n") cat("saveRDS(PC_01, file = 'veh/HGV_01.rds')\n") cat("BUS_01 <- age_ldv(x = net$hdv, name = 'BUS', k = 1/4)\n") cat("# BUS only for example purposes\n") cat("# BUS a traffic simulation only for BUS, or other source of information\n") cat("saveRDS(BUS_01, file = 'veh/BUS_01.rds')\n") cat("MC_01 <- age_ldv(x = net$ldv, name = 'MC', k = 1/4/2)\n") cat("saveRDS(MC_01, file = 'veh/MC_01.rds')\n") cat(" # Add more\n") sink() sink(paste0(name, "/post.R")) cat("# streets ####\n") cat("CO <- emis_merge('CO', net = net)\n") cat("saveRDS(CO, 'post/streets/CO.rds')\n\n") cat("# grids ####\n") cat("gCO <- emis_grid(CO, g)\n") cat("print(plot(gCO['V1'], axes = TRUE)) # only an example\n\n") cat("saveRDS(gCO, 'post/grids/gCO.rds')\n\n") cat("# df ####\n") cat("dfCO <- emis_merge('CO', what = 'DF.rds', FALSE)\n") cat("saveRDS(dfCO, 'post/df/dfCO.rds')\n") cat("aggregate(dfCO$g, by = list(dfCO$veh), sum, na.rm = TRUE) # Only an example\n\n") cat(" # Add more\n") sink() } if(show.dir){ dirs <- list.dirs(path = name, full.names = TRUE, recursive = TRUE) cat("Directories:\n") print(dirs) } if(show.scripts){ sc <- list.files(path = name, pattern = ".R", recursive = TRUE) cat("Scripts:\n") print(sc) } if(show.main) utils::file.edit(paste0(name, "/main.R")) }
/scratch/gouwar.j/cran-all/cranData/vein/R/inventory.R
#' Transform data.frame from long to wide format #' #' @description \code{\link{long_to_wide}} transform data.frame from long to #' wide format #' #' @param df data.frame with three column. #' @param column_with_new_names Character, column that has new column names #' @param column_with_data Character column with data #' @param column_fixed Character, column that will remain fixed #' @param net To return a sf #' @return wide data.frame. #' @importFrom sf st_sf st_as_sf st_geometry #' @seealso \code{\link{emis_hot_td}} \code{\link{emis_cold_td}} \code{\link{wide_to_long}} #' @export #' @examples \dontrun{ #' df <- data.frame(pollutant = rep(c("CO", "propadiene", "NO2"), 10), #' emission = vein::Emissions(1:30), #' region = rep(letters[1:2], 15)) #' df #' long_to_wide(df) #' long_to_wide(df, column_fixed = "region") #' } long_to_wide <- function(df, column_with_new_names = names(df)[1], column_with_data = "emission", column_fixed, net) { # message("This function will be deprecated, use data.table::dcast.data.table") a <- as.data.frame(df) la <- split(a, a[[column_with_new_names]]) if(missing(column_fixed)) { aa <- do.call("cbind", lapply(1:length(la), function(i){ la[[i]][[column_with_data]] })) aa <- as.data.frame(aa) names(aa) <- names(la) } else { xa <- as.data.frame(df) xa$id <- xa[[column_fixed]] la <- split(xa, xa[[column_with_new_names]]) aa <- do.call("cbind", lapply(1:length(la), function(i){ dfid <- data.frame(id = unique(xa[[column_fixed]])) merge(dfid, la[[i]][, c("id", column_with_data)], by = "id", all.x = T) })) aa[is.na(aa)] <- 0 names(aa)[1] <- column_fixed aa[, grepl("id", names(aa))] <- NULL names(aa) <- c(column_fixed, names(la)) } if(missing(net)) { return(aa) } else { net <- sf::st_as_sf(net) aa <- sf::st_sf(aa, geometry = sf::st_geometry(net)) return(aa) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/long_to_wide.R
#' Creates rectangular grid for emission allocation #' #' @description \code{make_grid} creates a sf grid of polygons. The spatial #' reference is taken from the spatial object. #' #' @param spobj A spatial object of class sp or sf. #' @param width Width of grid cell. It is recommended to use projected values. #' @param height Height of grid cell. #' @param polygon Deprecated! \code{\link{make_grid}} returns only sf grid of #' polygons. #' @param crs coordinate reference system in numeric #' format from #' http://spatialreference.org/ to transform/project spatial data using sf::st_transform. #' The default value is 3857, Pseudo Mercator #' @return A grid of polygons class 'sf' #' @importFrom sf st_as_sf st_sf st_crs st_bbox st_sfc st_as_sfc #' @export #' @examples \dontrun{ #' data(net) #' grid <- make_grid(net, width = 0.5/102.47) #500 mts #' plot(grid, axes = TRUE) #class sf #' # make grid now returns warnings for crs with form +init... #' #grid <- make_grid(net, width = 0.5/102.47) #500 mts #' #' } make_grid <- function(spobj, width, height = width, polygon, crs = 3857){ if(!missing(polygon)){ message("argument 'polygon' is not needed") } if(substr(crs, 1, 5) == "+init"){ warning("GDAL Message 1: +init=epsg:XXXX syntax is deprecated. It might return a CRS with a non-EPSG compliant axis order.") } if(!inherits(spobj, "character")){ #path for wrfinput? if(inherits(spobj, "bbox")) { spobj <- sf::st_as_sfc(spobj) spobj <- sf::st_sf(geometry = spobj) } net <- sf::st_as_sf(spobj) # from sf::st_make_grid # g <- sf::st_make_grid(x = net, cellsize = width, ...) makinggrid <- function (x, cellsize = c(width, height), offset = sf::st_bbox(x)[1:2], # n = c(10, 10), crs = sf::st_crs(x), what = "polygons") { bb = sf::st_bbox(x) nx = ceiling((bb[3] - offset[1])/cellsize[1]) ny = ceiling((bb[4] - offset[2])/cellsize[2]) cat(paste0("Number of lon points: ", nx, "\n", "Number of lat points: ", ny, "\n\n")) xc = offset[1] + (0:nx) * cellsize[1] yc = offset[2] + (0:ny) * cellsize[2] if (what == "polygons") { ret = vector("list", nx * ny) square = function(x1, y1, x2, y2){ sf::st_polygon(list(matrix(c(x1, x2, x2, x1, x1, y1, y1, y2, y2, y1),5))) } for (i in 1:nx) for (j in 1:ny) ret[[(j - 1) * nx + i]] = square(xc[i], yc[j], xc[i + 1], yc[j + 1]) } sf::st_sfc(ret, crs = sf::st_crs(x)) } g <- makinggrid(x = net, cellsize = c(width, height)) gg <- sf::st_sf(id = 1:length(g), geometry = g) if(!missing(crs)){ gg <- sf::st_transform(gg, crs) } return(gg) } else { cat("If you are reading wrfinput_d0x, try:\n g <- eixport::wrf_grid(spobj,type = 'wrfinput_d0x')\n") } }
/scratch/gouwar.j/cran-all/cranData/vein/R/make_grid.R
#' MOVES emission factors #' #' @description \code{\link{moves_ef}} reads and filter MOVES #' data.frame of emission factors. #' #' @param ef emission factors from EmissionRates_running exported from MOVES #' @param vehicles Name of category, with length equal to fuel_type_id and other with id #' @param process_id Number to identify emission process defined by MOVES. #' @param source_type_id Number to identify type of vehicle as defined by MOVES. #' @param fuel_type_id Number to identify type of fuel as defined by MOVES. #' @param pollutant_id Number to identify type of pollutant as defined by MOVES. #' @param road_type_id Number to identify type of road as defined by MOVES. #' @param speed_bin Data.frame or vector of avgSpeedBinID as defined by MOVES. #' @return EmissionFactors data.frame #' @export #' @importFrom data.table rbindlist as.data.table data.table dcast.data.table melt.data.table setDT #' @note `decoder` shows a decoder for MOVES to identify #' @examples { #' data(decoder) #' decoder #' } moves_ef <- function(ef, vehicles, source_type_id = 21, #Passenger car process_id = 1, fuel_type_id = 1, # Gasoline pollutant_id = 2, # Total Energy Consumption road_type_id = 5, # Urban Unrestricted Access speed_bin) { data.table::rbindlist( lapply(seq_along(source_type_id), function(i){ data.table::rbindlist( lapply(1:ncol(speed_bin), function(j){ hourID <- processID <- pollutantID <- sourceTypeID <- fuelTypeID <- roadTypeID <- NULL def <- ef[hourID == j & pollutantID == pollutant_id & processID == process_id & sourceTypeID == source_type_id[i] & fuelTypeID == fuel_type_id[i] & roadTypeID == road_type_id, ] dt <- data.table::data.table(id =1:nrow(speed_bin), sourceTypeID = source_type_id[i], avgSpeedBinID = speed_bin[[j]]) df_net_ef <- merge(dt, def[, c("avgSpeedBinID", "ratePerDistance")], by = "avgSpeedBinID", all.x = T) df_net_ef$hour <- j df_net_ef$vehicles <- vehicles[i] df_net_ef })) }) ) -> lxspeed data.table::setorderv(lxspeed, cols = "id") data.table::dcast.data.table(lxspeed[, c("id", "hour", "ratePerDistance", "vehicles")], formula = id+vehicles~hour, value.var = "ratePerDistance") -> emi return(emi) }
/scratch/gouwar.j/cran-all/cranData/vein/R/moves_ef.R
#' MOVES estimation of using rates per distance #' #' @description \code{\link{moves_rpd}} estimates running exhaust emissions #' using MOVES emission factors. #' #' @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. #' @param lkm Length of each link in miles #' @param ef emission factors from EmissionRates_running exported from MOVES #' @param fuel_type Data.frame of fuelSubtypeID exported by MOVES. #' @param speed_bin Data.frame or vector of avgSpeedBinID as defined by MOVES. #' @param profile Data.frame or Matrix with nrows equal to 24 and ncol 7 day of #' the week #' @param source_type_id Number to identify type of vehicle as defined by MOVES. #' @param fuel_type_id Number to identify type of fuel as defined by MOVES. #' @param pollutant_id Number to identify type of pollutant as defined by MOVES. #' @param process_id Number to identify type of pollutant as defined by MOVES. #' @param road_type_id Number to identify type of road as defined by MOVES. #' @param vehicle Character, type of vehicle #' @param vehicle_type Character, subtype of vehicle #' @param fuel_subtype Character, subtype of vehicle #' @param net Road network class sf #' @param path_all Character to export whole estimation. It is not recommended since it #' is usually too heavy. #' @param verbose Logical; To show more information. Not implemented yet #' @return a list with emissions at each street and data.base aggregated by categories. See \code{link{emis_post}} #' @export #' @importFrom data.table rbindlist as.data.table data.table dcast.data.table melt.data.table setDT #' @note `decoder` shows a decoder for MOVES #' @examples { #' data(decoder) #' decoder #' } moves_rpd <- function(veh, # x <- readRDS(paste0("veh/", metadata$vehicles[i], ".rds")) lkm, ef, fuel_type, # data.frame from moves speed_bin, profile, source_type_id = 21, #Passenger car fuel_type_id = 1, # Gasoline pollutant_id = 91, # Total Energy Consumption road_type_id = 5, # Urban Unrestricted Access process_id = 1, vehicle = NULL, vehicle_type = NULL, fuel_subtype = NULL, net, path_all, #path to save RDS verbose = FALSE) { profile$Hour <- NULL ll <- if(is.data.frame(veh)) 1 else seq_along(veh) agemax <- ifelse( is.data.frame(veh), ncol(veh), ncol(veh[[1]]) ) data.table::rbindlist( lapply(ll, function(i){ data.table::rbindlist( lapply(1:ncol(speed_bin), function(j){ hourID <- processID <- pollutantID <- sourceTypeID <- fuelTypeID <- roadTypeID <- NULL def <- ef[hourID == j & pollutantID == pollutant_id & processID == process_id & sourceTypeID == source_type_id[i] & fuelTypeID == fuel_type_id[i] & roadTypeID == road_type_id, ] data.table::as.data.table(fuel_type)[, lapply(.SD, mean, na.rm = T), .SDcols = c("carbonContent", "humidityCorrectionCoeff", "energyContent", "fuelDensity"), by = fuelTypeID] -> df_fuel def <- merge(def, df_fuel, by = "fuelTypeID") dt <- data.table::data.table(sourceTypeID = source_type_id[i], avgSpeedBinID = speed_bin[[j]]) df_net_ef <- merge(dt, def[, c("avgSpeedBinID", "ratePerDistance", "carbonContent", "humidityCorrectionCoeff", "energyContent", "fuelDensity")], by = "avgSpeedBinID", all.x = T) if(pollutant_id == 91) { df_net_ef$ef <- df_net_ef$ratePerDistance/1000*1/df_net_ef$energyContent*1/df_net_ef$fuelDensity df_net_ef$ef <- units::set_units(df_net_ef$ef, "gallons/miles/veh") } else { df_net_ef$ef <- df_net_ef$ratePerDistance df_net_ef$ef <- units::set_units(df_net_ef$ef, "g/miles/veh") } if(is.data.frame(veh)) { data.table::rbindlist(lapply(1:agemax, function(k){ data.table::data.table(emi = df_net_ef$ef*veh[[k]]*lkm*profile[j, i], id = 1:nrow(df_net_ef), age = k, hour = j) }))-> lx } else if(is.list(veh)) { data.table::rbindlist(lapply(1:agemax, function(k){ data.table::data.table(emi = df_net_ef$ef*veh[[i]] [[k]]*lkm*profile[j, i], id = 1:nrow(df_net_ef), age = k, hour = j) }))-> lx } data.table::dcast.data.table(lx, formula = id+hour~age, value.var = "emi") -> emi names(emi)[3:ncol(emi)] <- paste0("age_", names(emi)[3:ncol(emi)]) emi$veh <- vehicle[i] emi$veh_type <- vehicle_type[i] emi$fuelTypeID <- fuel_subtype[i] emi$pollutantID <- pollutant_id CategoryField <- Description <- NULL emi$processID <- process_id emi$sourceTypeID <- source_type_id[i] emi }) ) }) ) -> lxspeed if(!missing(path_all)){ if(verbose) message("The table has size ", format(object.size(lxspeed), units = "Mb")) saveRDS(lxspeed, paste0(path_all, ".rds")) } # input agemax #### id <- hour <- . <- NULL by_street <- lxspeed[, lapply(.SD, sum, na.rm = T), .SDcols = paste0("age_", 1:agemax), by = .(id, hour)] by_street$age_total <- rowSums(by_street[, 3:(agemax + 2)]) age_total <- NULL by_street2 <- by_street[, sum(age_total, na.rm = T), by = .(id, hour)] data.table::dcast.data.table(by_street2, formula = id~hour, value.var = "V1") -> streets names(streets)[2:ncol(streets)] <- paste0("H", names(streets)[2:ncol(streets)]) if(!missing(net)) { streets <- cbind(net, streets) } names(lxspeed) veh <- veh_type <- fuelTypeID <- pollutantID <- processID <- sourceTypeID <- NULL by_veh <- lxspeed[, -"id"][, lapply(.SD, sum, na.rm = T), .SDcols = 2:32, by = .(hour, veh, veh_type, fuelTypeID, pollutantID, processID, sourceTypeID) ] data.table::melt.data.table(data = by_veh, id.vars = names(by_veh)[1:7], measure.vars = paste0("age_", 1:agemax)) -> veh variable <- NULL veh[, age := as.numeric(gsub("age_", "", variable))] rm(lxspeed) invisible(gc()) return( list( streets = streets, veh = veh ) ) }
/scratch/gouwar.j/cran-all/cranData/vein/R/moves_rpd.R
#' MOVES estimation of using rates per distance by model year #' #' @description \code{\link{moves_rpdy}} estimates running exhaust emissions #' using MOVES emission factors. #' #' @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. #' @param lkm Length of each link in miles #' @param ef emission factors from EmissionRates_running exported from MOVES #' @param source_type_id Number to identify type of vehicle as defined by MOVES. #' @param fuel_type_id Number to identify type of fuel as defined by MOVES. #' @param pollutant_id Number to identify type of pollutant as defined by MOVES. #' @param road_type_id Number to identify type of road as defined by MOVES. #' @param fuel_type Data.frame of fuelSubtypeID exported by MOVES. #' @param speed_bin Data.frame or vector of avgSpeedBinID as defined by MOVES. #' @param profile Data.frame or Matrix with nrows equal to 24 and ncol 7 day of #' the week #' @param vehicle Character, type of vehicle #' @param vehicle_type Character, subtype of vehicle #' @param fuel_subtype Character, subtype of vehicle #' @param process_id Character, processID #' @param net Road network class sf #' @param path_all Character to export whole estimation. It is not recommended since it #' is usually too heavy. #' @param verbose Logical; To show more information. Not implemented yet #' @return a list with emissions at each street and data.base aggregated by categories. See \code{link{emis_post}} #' @export #' @importFrom data.table rbindlist as.data.table data.table dcast.data.table melt.data.table #' @note `decoder` shows a decoder for MOVES #' @examples { #' data(decoder) #' decoder #' } moves_rpdy <- function (veh, lkm, ef, source_type_id = 21, fuel_type_id = 1, pollutant_id = 91, road_type_id = 5, fuel_type, speed_bin, profile, vehicle, vehicle_type, fuel_subtype, process_id, net, path_all, verbose = FALSE) { if("Hour" %in% names(profile)) { profile$Hour <- NULL } ll <- if (is.data.frame(veh)) 1 else seq_along(veh) agemax <- ifelse(is.data.frame(veh), ncol(veh), ncol(veh[[1]])) lxspeed <- data.table::rbindlist(lapply(ll, function(i) { if(verbose) cat("Estimating emissions of veh", i, " sourceTypeID", source_type_id[i], "and fuelTypeID", fuel_type_id[i], "\n") data.table::rbindlist(lapply(1:ncol(speed_bin), function(j) { seq_horas <- rep(1:24, ncol(speed_bin)/24) hourID <- processID <- pollutantID <- sourceTypeID <- fuelTypeID <- roadTypeID <- NULL def <- ef[hourID == seq_horas[j] & pollutantID == pollutant_id & sourceTypeID == source_type_id[i] & fuelTypeID == fuel_type_id[i],] data.table::setorderv(def, cols = "modelYearID", order = -1) # checkif there aremissing avgSpeedBins! dfbin <- data.table::data.table(bin = 0:16) efbin <- data.table::data.table(bin = unique(def$avgSpeedBinID)) efbin$id <- 1:nrow(efbin) dfbin <- merge(dfbin, efbin, by = "bin", all.x = T) if(sum(is.na(dfbin$id)) > 0){ fill_bins <- dfbin[!is.na(dfbin$id), ]$bin[1] missing_bins <- dfbin[is.na(dfbin$id), ]$bin if(verbose) warning("Detected missing bins in ef: ", paste(missing_bins, collapse = " "), "\nAssuming: ", fill_bins) } # here we rename modelYearID by age of use modelYearID <- avgSpeedBinID <- .N <- NULL def[, modelYearID :=1:.N, by = avgSpeedBinID] def_veh <- dcast.data.table(data = def, formula = avgSpeedBinID ~ modelYearID, value.var = "EF") names(def_veh)[2:ncol(def_veh)] <- paste0("age_", names(def_veh)[2:ncol(def_veh)]) if(sum(is.na(dfbin$id)) > 0){ la <- replicate(n = length(missing_bins), expr = def_veh[avgSpeedBinID == fill_bins], simplify = F) la <- data.table::rbindlist(la) la$avgSpeedBinID <- missing_bins def_veh <- rbind(def_veh, la) data.table::setorderv(def_veh, cols = "avgSpeedBinID") } df_fuel <- data.table::as.data.table(fuel_type)[fuelTypeID == fuel_type_id[i], lapply(.SD, mean, na.rm = T), .SDcols = c("carbonContent", "humidityCorrectionCoeff", "energyContent", "fuelDensity"), by = fuelTypeID] # def <- merge(def, df_fuel, by = "fuelTypeID") dt <- data.table::data.table(avgSpeedBinID = speed_bin[[j]]) df_net_ef <- merge(dt, def_veh, by = "avgSpeedBinID", all.x = T) #EmissionFactors EF <- df_net_ef[,2:ncol(df_net_ef)] if (pollutant_id == 91) { EF <- EF/1000 * 1/df_fuel$energyContent * 1/df_fuel$fuelDensity for(kk in 1:ncol(EF)) { EF[[kk]] <- units::set_units(EF[[kk]],"gallons/miles/veh") } } else { EF <- EmissionFactors(x = as.data.frame(EF), mass = "g", dist = "miles") for(kk in 1:ncol(EF)) { EF[[kk]] <- EF[[kk]]*units::set_units(1,"1/veh") } } if (is.data.frame(veh)) { if(ncol(EF) < ncol(veh)) { if(verbose) message("Number of columns of EF is lower than number of columns of veh. Fixing") dif_col <- ncol(veh) - ncol(EF) for(kk in (ncol(EF) + 1):(ncol(EF) + dif_col)) { EF[[kk]] <- EF[[ncol(EF)]] } } lx <- data.table::rbindlist(lapply(1:agemax, function(k) { data.table::data.table( emi = EF[[k]] * veh[[k]] * lkm * profile[[j]], id = 1:nrow(df_net_ef), age = k, hour = j) })) } else if (is.list(veh)) { if(ncol(EF) < ncol(veh[[i]])) { if(verbose) message("Number of columns of EF is lower than number of columns of veh. Fixing") dif_col <- ncol(veh[[i]]) - ncol(EF) for(kk in (ncol(EF) + 1):(ncol(EF) + dif_col)) { EF[[kk]] <- EF[[ncol(EF)]] } } lx <- data.table::rbindlist(lapply(1:agemax, function(k) { data.table::data.table( emi = EF[[k]] * veh[[i]][[k]] * lkm * profile[j, i], id = 1:nrow(df_net_ef), age = k, hour = j) })) } emi <- data.table::dcast.data.table(lx, formula = id + hour ~ age, value.var = "emi") names(emi)[3:ncol(emi)] <- paste0("age_", names(emi)[3:ncol(emi)]) emi$veh <- vehicle[i] emi$veh_type <- vehicle_type[i] emi$fuelTypeID <- fuel_subtype[i] emi$pollutantID <- pollutant_id CategoryField <- Description <- NULL emi$processID <- process_id emi$sourceTypeID <- source_type_id[i] emi })) })) if (!missing(path_all)) { if (verbose) message("The table has size ", format(object.size(lxspeed), units = "Mb")) saveRDS(lxspeed, paste0(path_all, ".rds")) } id <- hour <- . <- NULL by_street <- lxspeed[, lapply(.SD, sum, na.rm = T), .SDcols = paste0("age_", 1:agemax), by = .(id, hour)] by_street$age_total <- rowSums(by_street[, 3:(agemax + 2)]) age_total <- NULL by_street2 <- by_street[, sum(age_total, na.rm = T), by = .(id, hour)] streets <- data.table::dcast.data.table(by_street2, formula = id ~ hour, value.var = "V1") names(streets)[2:ncol(streets)] <- paste0("H", names(streets)[2:ncol(streets)]) if (!missing(net)) { streets <- cbind(net, streets) } names(lxspeed) veh <- veh_type <- fuelTypeID <- pollutantID <- processID <- sourceTypeID <- NULL by_veh <- lxspeed[, -"id"][, lapply(.SD, sum, na.rm = T), .SDcols = 2:(agemax+1), by = .(hour, veh, veh_type, fuelTypeID, pollutantID, processID, sourceTypeID) ] veh <- data.table::melt.data.table(data = by_veh, id.vars = names(by_veh)[1:7], measure.vars = paste0("age_", 1:agemax)) variable <- NULL veh[, age := as.numeric(gsub("age_", "", variable))] rm(lxspeed) invisible(gc()) age <- NULL return(list(streets = streets, veh = veh[age <= agemax])) }
/scratch/gouwar.j/cran-all/cranData/vein/R/moves_rpdy.R
#' MOVES estimation of using rates per distance by model year #' #' @description \code{\link{moves_rpdy_meta}} estimates running exhaust emissions #' using MOVES emission factors. #' #' @param metadata data.frame with the metadata for a vein project for MOVES. #' @param lkm Length of each link in miles #' @param ef emission factors from EmissionRates_running exported from MOVES #' @param fuel_type Data.frame of fuelSubtypeID exported by MOVES. #' @param speed_bin Data.frame or vector of avgSpeedBinID as defined by MOVES. #' @param profile Data.frame or Matrix with nrows equal to 24 and ncol 7 day of #' the week #' @param agemax Integer; max age for the fleet, assuming the same for all vehicles. #' @param net Road network class sf #' @param simplify Logical, to return the whole object or processed by streets and veh #' @param verbose Logical; To show more information. Not implemented yet #' @return a list with emissions at each street and data.base aggregated by categories. #' @export #' @importFrom data.table rbindlist as.data.table data.table dcast.data.table melt.data.table #' @note The idea is the user enter with emissions factors by pollutant #' @examples { #' data(decoder) #' decoder #' } moves_rpdy_meta <- function(metadata, lkm, ef, fuel_type, speed_bin, profile, agemax = 31, net, simplify = TRUE, verbose = FALSE){ profile$Hour <- NULL `:` <- NULL age_total <- lxstart <- NULL data.table::rbindlist(lapply(1:ncol(speed_bin), function(i) { seq_horas <- rep(1:24, ncol(speed_bin)/24) hourID <- processID <- pollutantID <- sourceTypeID <- fuelTypeID <- roadTypeID <- NULL # 1 filter by pollutantID j uni_pol <- unique(ef$pollutantID) data.table::rbindlist(lapply(seq_along(uni_pol), function(j) { if(verbose) cat(paste0("Pollutant: ", uni_pol[j], "\n")) def <- ef[pollutantID == uni_pol[j]] # 2 filter by fuelTypeID k uni_fuel <- unique(def$fuelTypeID) data.table::rbindlist(lapply(seq_along(uni_fuel), function(k) { if(verbose) cat(paste0("Fuel: ", uni_fuel[k], "\n")) def <- def[fuelTypeID == uni_fuel[k]] # 3 filter by process l uni_process <- unique(def$processID) data.table::rbindlist(lapply(seq_along(uni_fuel), function(l) { if(verbose) cat(paste0("Process: ", uni_process[l], "\n")) def <- def[processID == uni_process[l]] # 3 fi;ter by sourceTypeID uni_source <- unique(def$sourceTypeID) data.table::rbindlist(lapply(seq_along(uni_source), function(m) { if(verbose) cat(paste0("sourceTypeID: ", uni_source[m], "\n")) def <- def[sourceTypeID == uni_source[m]] # 5) filtrar horas def <- def[hourID == seq_horas[i], ] data.table::setorderv(def, cols = "modelYearID", order = -1) dfbin <- data.table::data.table(bin = 0:16) efbin <- data.table::data.table(bin = unique(def$avgSpeedBinID)) efbin$id <- 1:nrow(efbin) dfbin <- merge(dfbin, efbin, by = "bin", all.x = T) if (sum(is.na(dfbin$id)) > 0) { fill_bins <- dfbin[!is.na(dfbin$id), ]$bin[1] missing_bins <- dfbin[is.na(dfbin$id), ]$bin if (verbose) message("Detected missing bins in ef: ", paste(missing_bins, collapse = " "), "\nAssuming: ", fill_bins) } modelYearID <- avgSpeedBinID <- .N <- NULL def[, `:=`(modelYearID, 1:.N), by = avgSpeedBinID] def_veh <- dcast.data.table(data = def, formula = avgSpeedBinID ~ modelYearID, value.var = "EF") names(def_veh)[2:ncol(def_veh)] <- paste0("age_", names(def_veh)[2:ncol(def_veh)]) if (sum(is.na(dfbin$id)) > 0) { la <- replicate(n = length(missing_bins), expr = def_veh[avgSpeedBinID == fill_bins], simplify = F) la <- data.table::rbindlist(la) la$avgSpeedBinID <- missing_bins def_veh <- rbind(def_veh, la) data.table::setorderv(def_veh, cols = "avgSpeedBinID") } dt <- data.table::data.table(avgSpeedBinID = speed_bin[[j]]) df_net_ef <- merge(dt, def_veh, by = "avgSpeedBinID", all.x = T) EF <- df_net_ef[, 2:ncol(df_net_ef)] # read vehicles nveh <- metadata[fuelTypeID == uni_fuel[k] & sourceTypeID == uni_source[m]]$vehicles if(verbose) cat(paste0("Reading: veh/", nveh, ".rds\n")) veh <- readRDS(paste0("veh/", nveh, ".rds")) if (uni_pol[j] == 91) { if(missing(fuel_type)) stop("Please, add `fuel_type` data.frame from MOVES") vehicles <- NULL df_fuel <- data.table::as.data.table(fuel_type)[fuelTypeID == metadata[vehicles == nveh]$fuelTypeID, lapply(.SD, mean, na.rm = T), .SDcols = c("carbonContent", "humidityCorrectionCoeff", "energyContent", "fuelDensity"), by = fuelTypeID] EF <- EF/1000 * 1/df_fuel$energyContent * 1/df_fuel$fuelDensity for (kk in 1:ncol(EF)) { EF[[kk]] <- units::set_units(EF[[kk]], "gallons/miles/veh") } } else { EF <- EmissionFactors(x = as.data.frame(EF), mass = "g", dist = "miles") for (kk in 1:ncol(EF)) { EF[[kk]] <- EF[[kk]] * units::set_units(1, "1/veh") } } # estimation #### if (ncol(EF) < ncol(veh)) { if (verbose) message("Number of columns of EF is lower than number of columns of veh. Fixing") dif_col <- ncol(veh) - ncol(EF) for (kk in (ncol(EF) + 1):(ncol(EF) + dif_col)) { EF[[kk]] <- EF[[ncol(EF)]] } } lx <- data.table::rbindlist( lapply(1:agemax, function(n) { data.table::data.table(emi = EF[[n]] * veh[[n]] * lkm * profile[i, nveh], id = 1:nrow(df_net_ef), age = n, hour = i) })) emi <- data.table::dcast.data.table(lx, formula = id + hour ~ age, value.var = "emi") names(emi)[3:ncol(emi)] <- paste0("age_", names(emi)[3:ncol(emi)]) emi$veh <- metadata[fuelTypeID == uni_fuel[k] & sourceTypeID == uni_source[m]]$vehicles emi$veh_type <- metadata[fuelTypeID == uni_fuel[k] & sourceTypeID == uni_source[m]]$name emi$fuel <- metadata[fuelTypeID == uni_fuel[k] & sourceTypeID == uni_source[m]]$fuel emi$fuelTypeID <- metadata[fuelTypeID == uni_fuel[k] & sourceTypeID == uni_source[m]]$fuelTypeID emi$pollutantID <- uni_pol[j] emi$processID <- uni_process[l] emi$sourceTypeID <- uni_source[m] emi })) })) })) })) })) -> lxspeed lxspeed$age_total <- rowSums(lxspeed[, paste0("age_", 1:agemax), with = F], na.rm = T) if (!simplify) { message("The table has size ", format(object.size(lxspeed), units = "Mb")) return(lxspeed) } else { # To obtain NMHC by processID, fuelTypeID and sourceTypeID, !simplify must be used by_street <- lxspeed[, c("id", "hour", "age_total"), with = F][, sum(age_total), by = c("id", "hour")] streets <- data.table::dcast.data.table(by_street, formula = id ~ hour, value.var = "V1") names(streets)[2:ncol(streets)] <- paste0("H", names(streets)[2:ncol(streets)]) if (!missing(net)) { streets <- cbind(net, streets) } names(lxspeed) by_veh <- lxspeed[, lapply(.SD, sum, na.rm = T), .SDcols = paste0("age_", 1:agemax), by = c("hour", "veh", "veh_type", "fuel", "fuelTypeID", "pollutantID", "processID", "sourceTypeID")] veh <- data.table::melt.data.table(data = by_veh, id.vars = names(by_veh)[1:8], measure.vars = paste0("age_", 1:agemax)) variable <- NULL veh[, `:=`(age, as.numeric(gsub("age_", "", variable)))] rm(lxspeed) invisible(gc()) return(list(streets = streets, veh = veh)) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/moves_rpdy_meta.R
#' MOVES estimation of using rates per distance by model year #' #' @description \code{\link{moves_rpdy_sf}} estimates running exhaust emissions #' using MOVES emission factors. #' #' @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. #' @param lkm Length of each link in miles #' @param ef emission factors from EmissionRates_running exported from MOVES #' filtered by sourceTypeID and fuelTypeID. #' @param speed_bin Data.frame or vector of avgSpeedBinID as defined by MOVES. #' @param profile numeric vector of normalized traffic for the morning rush hour #' @param source_type_id Number to identify type of vehicle as defined by MOVES. #' @param vehicle Character, type of vehicle #' @param vehicle_type Character, subtype of vehicle #' @param fuel_subtype Character, subtype of vehicle #' @param path_all Character to export whole estimation. It is not recommended since it #' is usually too heavy. #' @param verbose Logical; To show more information. Not implemented yet #' @return a list with emissions at each street and data.base aggregated by categories. See \code{link{emis_post}} #' @export #' @importFrom data.table rbindlist as.data.table data.table dcast.data.table melt.data.table #' @note `decoder` shows a decoder for MOVES #' @examples { #' data(decoder) #' decoder #' } moves_rpdy_sf <- function (veh, lkm, ef, speed_bin, profile, source_type_id = 21, vehicle = NULL, vehicle_type = NULL, fuel_subtype = NULL, # net, path_all, verbose = FALSE) { ll <- if (is.data.frame(veh)) 1 else seq_along(veh) agemax <- ifelse(is.data.frame(veh), ncol(veh), ncol(veh[[1]])) data.table::rbindlist(lapply(1:ncol(speed_bin), function(i) { hourID <- processID <- pollutantID <- sourceTypeID <- fuelTypeID <- roadTypeID <- NULL # ensuring hours with length of any number of days seq_horas <- rep(1:24, ncol(speed_bin)/24) ef <- ef[hourID == seq_horas[i]] # k process #### pros <- unique(ef$processID) data.table::rbindlist(lapply(seq_along(pros), function(k) { ef <- ef[processID == pros[k]] # j pollutants #### pols <- unique(ef$pollutantID) data.table::rbindlist(lapply(seq_along(pols), function(j) { ef <- ef[pollutantID == pols[j]] data.table::setorderv(ef, cols = "modelYearID", order = -1) # checkif there aremissing avgSpeedBins! dfbin <- data.table::data.table(bin = 0:16) efbin <- data.table::data.table(bin = unique(ef$avgSpeedBinID)) efbin$id <- 1:nrow(efbin) dfbin <- merge(dfbin, efbin, by = "bin", all.x = T) if(sum(is.na(dfbin$id)) > 0){ fill_bins <- dfbin[!is.na(dfbin$id), ]$bin[1] missing_bins <- dfbin[is.na(dfbin$id), ]$bin if(verbose) warning("Detected missing bins in ef: ", paste(missing_bins, collapse = " "), "\nAssuming: ", fill_bins) } # here we rename modelYearID by age of use modelYearID <- avgSpeedBinID <- .N <- NULL ef[, modelYearID :=1:.N, by = avgSpeedBinID] def_veh <- dcast.data.table(data = ef, formula = avgSpeedBinID ~ modelYearID, value.var = "EF") names(def_veh)[2:ncol(def_veh)] <- paste0("age_", names(def_veh)[2:ncol(def_veh)]) if(sum(is.na(dfbin$id)) > 0){ la <- replicate(n = length(missing_bins), expr = def_veh[avgSpeedBinID == fill_bins], simplify = F) la <- data.table::rbindlist(la) la$avgSpeedBinID <- missing_bins def_veh <- rbind(def_veh, la) data.table::setorderv(def_veh, cols = "avgSpeedBinID") } dt <- data.table::data.table(avgSpeedBinID = speed_bin[[j]]) df_net_ef <- merge(dt, def_veh, by = "avgSpeedBinID", all.x = T) #EmissionFactors EF <- df_net_ef[,2:ncol(df_net_ef)] EF <- EmissionFactors(x = as.data.frame(EF), mass = "g", dist = "miles") for(kk in 1:ncol(EF)) { EF[[kk]] <- EF[[kk]]*units::set_units(1,"1/veh") } # estimating emissions #### if(ncol(EF) < ncol(veh)) { if(verbose) message("Number of columns of EF is lower than number of columns of veh. Fixing") dif_col <- ncol(veh) - ncol(EF) for(kk in (ncol(EF) + 1):(ncol(EF) + dif_col)) { EF[[kk]] <- EF[[ncol(EF)]] } } lx <- data.table::rbindlist(lapply(1:agemax, function(ll) { data.table::data.table( emi = EF[[ll]] * veh[[ll]] * lkm * unlist(profile)[i], id = 1:nrow(df_net_ef), age = ll, hour = i) })) emi <- data.table::dcast.data.table(lx, formula = id + hour ~ age, value.var = "emi") names(emi)[3:ncol(emi)] <- paste0("age_", names(emi)[3:ncol(emi)]) emi$veh <- vehicle emi$veh_type <- vehicle_type emi$fuelTypeID <- fuel_subtype emi$pollutantID <- pols[j] emi$processID <- pros[k] emi$sourceTypeID <- source_type_id emi })) })) })) -> lxspeed unique(lxspeed$hour) if (!missing(path_all)) { if (verbose) message("The table has size ", format(object.size(lxspeed), units = "Mb")) saveRDS(lxspeed, paste0(path_all, ".rds")) } # return(lxspeed) id <- hour <- . <- NULL by_street <- lxspeed[, lapply(.SD, sum, na.rm = T), .SDcols = paste0("age_", 1:agemax), by = .(id, pollutantID, hour, processID) ] by_street$age_total <- rowSums(by_street[, 4:(agemax + 3)]) age_total <- NULL by_street2 <- by_street[, sum(age_total, na.rm = T), by = .(id, pollutantID, hour, processID) ] streets <- data.table::dcast.data.table(by_street2, formula = id + pollutantID + processID~ hour, value.var = "V1") names(streets)[4:ncol(streets)] <- paste0("H", names(streets)[4:ncol(streets)]) # if (!missing(net)) { # streets <- cbind(net, streets) # } veh <- veh_type <- fuelTypeID <- pollutantID <- processID <- sourceTypeID <- NULL by_veh <- lxspeed[, -"id"][, lapply(.SD, sum, na.rm = T), .SDcols = 2:32, by = .(hour, veh, veh_type, fuelTypeID, pollutantID, processID, sourceTypeID)] veh <- data.table::melt.data.table(data = by_veh, id.vars = names(by_veh)[1:7], measure.vars = paste0("age_", 1:agemax)) variable <- NULL veh[, age := as.numeric(gsub("age_", "", variable))] rm(lxspeed) invisible(gc()) streets$fuel <- fuel_subtype return(list(streets = streets, veh = veh)) }
/scratch/gouwar.j/cran-all/cranData/vein/R/moves_rpdy_source.R
#' MOVES estimation of using rates per start by model year #' #' @description \code{\link{moves_rpsy_meta}} estimates running exhaust emissions #' using MOVES emission factors. #' #' @param metadata data.frame with the metadata for a vein project for MOVES. #' @param lkm Length of each link in miles #' @param ef emission factors from EmissionRates_running exported from MOVES #' @param fuel_type Data.frame of fuelSubtypeID exported by MOVES. #' @param profile Data.frame or Matrix with nrows equal to 24 and ncol 7 day of #' the week #' @param agemax Integer; max age for the fleet, assuming the same for all vehicles. #' @param net Road network class sf #' @param simplify Logical, to return the whole object or processed by streets and veh #' @param verbose Logical; To show more information. Not implemented yet #' @param colk Character identifying a column in 'metadata' to multiply the emission factor #' @param colkt Logical, TRUE if `colk` is used #' @return a list with emissions at each street and data.base aggregated by categories. #' @export #' @importFrom data.table rbindlist as.data.table data.table dcast.data.table melt.data.table #' @note The idea is the user enter with emissions factors by pollutant #' @examples { #' data(decoder) #' decoder #' } moves_rpsy_meta <- function(metadata, lkm, ef, fuel_type, profile, agemax = 31, net, simplify = TRUE, verbose = FALSE, colk, colkt = F){ profile$Hour <- sourceTypeID <- fuelTypeID <- pollutantID <- processID <- NULL `:` <- NULL age_total <- lxstart <- NULL # 3 fi;ter by sourceTypeID uni_source <- unique(ef$sourceTypeID) data.table::rbindlist(lapply(seq_along(uni_source), function(m) { if(verbose) cat(paste0("sourceTypeID: ", uni_source[m], "\n")) def <- ef[sourceTypeID == uni_source[m]] # 2 filter by fuelTypeID k uni_fuel <- unique(def$fuelTypeID) data.table::rbindlist(lapply(seq_along(uni_fuel), function(k) { if(verbose) cat(paste0("Fuel: ", uni_fuel[k], "\n")) def <- def[fuelTypeID == uni_fuel[k]] # read vehicles nveh <- metadata[fuelTypeID == uni_fuel[k] & sourceTypeID == uni_source[m]]$vehicles if(verbose) cat(paste0("Reading: veh/", nveh, ".rds\n\n")) veh <- readRDS(paste0("veh/", nveh, ".rds")) # 3 filter by process uni_process <- unique(def$processID) data.table::rbindlist(lapply(seq_along(uni_process), function(l) { if(verbose) cat(paste0("Process: ", uni_process[l], "\n")) def <- def[processID == uni_process[l]] # 1 filter by pollutantID j uni_pol <- unique(ef$pollutantID) data.table::rbindlist(lapply(seq_along(uni_pol), function(j) { if(verbose) cat(paste0("Pollutant: ", uni_pol[j], "\n")) def <- def[pollutantID == uni_pol[j]] # hours data.table::rbindlist(lapply(1:nrow(profile), function(i) { seq_horas <- rep(1:24, nrow(profile)/24) hourID <- processID <- pollutantID <- sourceTypeID <- fuelTypeID <- roadTypeID <- NULL # no EF between 10:18 # assuming that there should not exist EF in that hours # need to compare with EF ratepervehicle # if (any(uni_pol[j] == 79 & # uni_fuel[k] %in% 2:3 & # uni_process[l] == c(16, 2) & # uni_source[m] %in% 61:62)) { # # def <- def[hourID == 9, ] # def$EF <- def$EF*0 # } else { def <- def[hourID == seq_horas[i], ] if(nrow(def) == 0) return() # } data.table::setorderv(def, cols = "modelYearID", order = -1) modelYearID <- .N <- NULL def[, `:=`(modelYearID, 1:.N)] . <- NULL def_veh <- dcast.data.table(data = def, formula = . ~ modelYearID, value.var = "EF") names(def_veh)[2:ncol(def_veh)] <- paste0("age_", names(def_veh)[2:ncol(def_veh)]) la <- replicate(n = length(lkm), expr = def_veh[, 2:ncol(def_veh)], simplify = F) EF <- data.table::rbindlist(la) if(colkt){ # to convert starts (trips) to km (EF g/start * start/km => g/km) # in metadata k should be "km_trip" nk <- metadata[fuelTypeID == uni_fuel[k] & sourceTypeID == uni_source[m]][[colk]] EF <- EF/as.numeric(nk) } if (uni_pol[j] == 91) { vehicles <- NULL df_fuel <- data.table::as.data.table(fuel_type)[fuelTypeID == metadata[vehicles == nveh]$fuelTypeID, lapply(.SD, mean, na.rm = T), .SDcols = c("carbonContent", "humidityCorrectionCoeff", "energyContent", "fuelDensity"), by = fuelTypeID] EF <- EF/1000 * 1/df_fuel$energyContent * 1/df_fuel$fuelDensity for (kk in 1:ncol(EF)) { EF[[kk]] <- units::set_units(EF[[kk]], "gallons/miles/veh") } } else { EF <- EmissionFactors(x = as.data.frame(EF), mass = "g", dist = "miles") for (kk in 1:ncol(EF)) { EF[[kk]] <- EF[[kk]] * units::set_units(1, "1/veh") } } # estimation #### if (ncol(EF) < ncol(veh)) { if (verbose) message("Number of columns of EF is lower than number of columns of veh. Fixing") dif_col <- ncol(veh) - ncol(EF) for (kk in (ncol(EF) + 1):(ncol(EF) + dif_col)) { EF[[kk]] <- EF[[ncol(EF)]] } } lx <- data.table::rbindlist( lapply(1:agemax, function(n) { data.table::data.table(emi = EF[[n]] * veh[[n]] * lkm * profile[i, n], id = 1:length(lkm), age = n, hour = i) })) emi <- data.table::dcast.data.table(lx, formula = id + hour ~ age, value.var = "emi") names(emi)[3:ncol(emi)] <- paste0("age_", names(emi)[3:ncol(emi)]) emi$veh <- metadata[fuelTypeID == uni_fuel[k] & sourceTypeID == uni_source[m]]$vehicles emi$veh_type <- metadata[fuelTypeID == uni_fuel[k] & sourceTypeID == uni_source[m]]$name emi$fuel <- metadata[fuelTypeID == uni_fuel[k] & sourceTypeID == uni_source[m]]$fuel emi$fuelTypeID <- metadata[fuelTypeID == uni_fuel[k] & sourceTypeID == uni_source[m]]$fuelTypeID emi$pollutantID <- uni_pol[j] emi$processID <- uni_process[l] emi$sourceTypeID <- uni_source[m] emi })) })) })) })) })) -> lxstart lxstart$age_total <- rowSums(lxstart[, paste0("age_", 1:agemax), with = F], na.rm = T) if (!simplify) { message("The table has size ", format(object.size(lxstart), units = "Mb")) return(lxstart) } else { # To obtain NMHC by processID, fuelTypeID and sourceTypeID, !simplify must be used by_street <- lxstart[, c("id", "hour", "age_total"), with = F][, sum(age_total), by = c("id", "hour")] streets <- data.table::dcast.data.table(by_street, formula = id ~ hour, value.var = "V1") names(streets)[2:ncol(streets)] <- paste0("H", names(streets)[2:ncol(streets)]) if (!missing(net)) { streets <- cbind(net, streets) } names(lxstart) by_veh <- lxstart[, lapply(.SD, sum, na.rm = T), .SDcols = paste0("age_", 1:agemax), by = c("hour", "veh", "veh_type", "fuel", "fuelTypeID", "pollutantID", "processID", "sourceTypeID")] veh <- data.table::melt.data.table(data = by_veh, id.vars = names(by_veh)[1:8], measure.vars = paste0("age_", 1:agemax)) variable <- NULL veh[, `:=`(age, as.numeric(gsub("age_", "", variable)))] rm(lxstart) invisible(gc()) return(list(streets = streets, veh = veh)) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/moves_rpsy_meta.R
#' MOVES estimation of using rates per start by model year #' #' @description \code{\link{moves_rpsy_sf}} estimates running exhaust emissions #' using MOVES emission factors. #' #' @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 in miles #' @param ef emission factors from EmissionRates_running exported from MOVES #' filtered by sourceTypeID and fuelTypeID. #' @param profile numeric vector of normalized traffic for the morning rush hour #' @param source_type_id Number to identify type of vehicle as defined by MOVES. #' @param vehicle Character, type of vehicle #' @param vehicle_type Character, subtype of vehicle #' @param fuel_subtype Character, subtype of vehicle #' @param net Road network class sf #' @param path_all Character to export whole estimation. It is not recommended since it #' is usually too heavy. #' @param verbose Logical; To show more information. Not implemented yet #' @return a list with emissions at each street and data.base aggregated by categories. See \code{link{emis_post}} #' @export #' @importFrom data.table rbindlist as.data.table data.table dcast.data.table melt.data.table #' @note `decoder` shows a decoder for MOVES #' @examples { #' data(decoder) #' decoder #' } moves_rpsy_sf <- function (veh, lkm, ef, profile, source_type_id = 21, vehicle = NULL, vehicle_type = NULL, fuel_subtype = NULL, net, path_all, verbose = FALSE) { pollutantID <- fuelTypeID <- processID <- NULL ll <- if (is.data.frame(veh)) 1 else seq_along(veh) agemax <- ifelse(is.data.frame(veh), ncol(veh), ncol(veh[[1]])) data.table::rbindlist(lapply(seq_along(profile), function(i) { hourID <- processID <- pollutantID <- sourceTypeID <- fuelTypeID <- roadTypeID <- NULL # ensuring hours with length of any number of days seq_horas <- rep(1:24, length(profile)/24) ef <- ef[hourID == seq_horas[i]] # k process #### pros <- unique(ef$processID) data.table::rbindlist(lapply(seq_along(pros), function(k) { ef <- ef[processID == pros[k]] # j pollutants #### pols <- unique(ef$pollutantID) data.table::rbindlist(lapply(seq_along(pols), function(j) { ef <- ef[pollutantID == pols[j]] data.table::setorderv(ef, cols = "modelYearID", order = -1) # here we rename modelYearID by age of use modelYearID <- .N <- NULL ef[, modelYearID :=1:.N, by = pollutantID] def_veh <- dcast.data.table(data = ef, formula = . ~ modelYearID, value.var = "EF") names(def_veh)[2:ncol(def_veh)] <- paste0("age_", names(def_veh)[2:ncol(def_veh)]) # remove point def_veh[[1]] <- NULL #EmissionFactors EF <- EmissionFactors(x = as.data.frame(def_veh), mass = "g", dist = "miles") for(kk in 1:ncol(EF)) { EF[[kk]] <- EF[[kk]]*units::set_units(1,"1/veh") } # estimating emissions #### if(ncol(EF) < ncol(veh)) { if(verbose) message("Number of columns of EF is lower than number of columns of veh. Fixing") dif_col <- ncol(veh) - ncol(EF) for(kk in (ncol(EF) + 1):(ncol(EF) + dif_col)) { EF[[kk]] <- EF[[ncol(EF)]] } } lx <- data.table::rbindlist(lapply(1:agemax, function(ll) { data.table::data.table( emi = EF[[ll]] * veh[[ll]] * lkm * unlist(profile)[i], id = 1:nrow(veh), age = ll, hour = i) })) emi <- data.table::dcast.data.table(lx, formula = id + hour ~ age, value.var = "emi") names(emi)[3:ncol(emi)] <- paste0("age_", names(emi)[3:ncol(emi)]) emi$veh <- vehicle emi$veh_type <- vehicle_type emi$fuelTypeID <- fuel_subtype emi$pollutantID <- pols[j] emi$processID <- pros[k] emi$sourceTypeID <- source_type_id emi })) })) })) -> lxspeed unique(lxspeed$hour) if (!missing(path_all)) { if (verbose) message("The table has size ", format(object.size(lxspeed), units = "Mb")) saveRDS(lxspeed, paste0(path_all, ".rds")) } id <- hour <- . <- NULL by_street <- lxspeed[, lapply(.SD, sum, na.rm = T), .SDcols = paste0("age_", 1:agemax), by = .(id, pollutantID, hour, processID) ] by_street$age_total <- rowSums(by_street[, 4:(agemax + 3)]) age_total <- NULL by_street2 <- by_street[, sum(age_total, na.rm = T), by = .(id, pollutantID, hour)] streets <- data.table::dcast.data.table(by_street2, formula = id + pollutant ~ hour, value.var = "V1") names(streets)[3:ncol(streets)] <- paste0("H", names(streets)[3:ncol(streets)]) if (!missing(net)) { streets <- cbind(net, streets) } veh <- veh_type <- fuel <- pollutant <- type_emi <- sourceTypeID <- NULL by_veh <- lxspeed[, -"id"][, lapply(.SD, sum, na.rm = T), .SDcols = 2:32, by = .(hour, veh, veh_type, fuelTypeID, pollutantID, processID, sourceTypeID) ] veh <- data.table::melt.data.table(data = by_veh, id.vars = names(by_veh)[1:7], measure.vars = paste0("age_", 1:agemax)) variable <- NULL veh[, age := as.numeric(gsub("age_", "", variable))] rm(lxspeed) invisible(gc()) streets$fuel <- fuel_subtype return(list(streets = streets, veh = veh)) }
/scratch/gouwar.j/cran-all/cranData/vein/R/moves_rpsy_source.R
#' Return speed bins according to US/EPA MOVES model #' #' @description \code{speed_moves} return an object of average speed bins as defined by #' US EPA MOVES. The input must be speed as miles/h (mph) #' #' @param x Object with class, "sf", "data.frame", "matrix" or "numeric" with speeds #' in miles/h (mph) #' @param net optional spatial dataframe of class "sf". #' it is transformed to "sf". #' @importFrom sf st_sf st_set_geometry st_geometry #' @importFrom data.table fifelse #' @export #' @examples { #' data(net) #' net$mph <- units::set_units(net$ps, "miles/h") #' net$speed_bins <- moves_speed(net$mph) #' head(net) #' moves_speed(net["ps"]) #' } moves_speed <- function(x, net) { x <- remove_units(x) fx <- function(sp) { data.table::fifelse( sp <= 0.1, 0, data.table::fifelse( sp > 0.1 & sp <= 2.5, 1, data.table::fifelse( sp > 2.5 & sp <= 7.5, 2, data.table::fifelse( sp >= 7.5 & sp <= 12.5, 3, data.table::fifelse( sp >= 12.5 & sp <= 17.5, 4, data.table::fifelse( sp >= 17.5 & sp <= 22.5, 5, data.table::fifelse( sp >= 22.5 & sp <= 27.5, 6, data.table::fifelse( sp >= 27.5 & sp <= 32.5, 7, data.table::fifelse( sp >= 32.5 & sp <= 37.5, 8, data.table::fifelse( sp >= 37.5 & sp <= 42.5, 9, data.table::fifelse( sp >= 42.5 & sp <= 47.5, 10, data.table::fifelse( sp >= 47.5 & sp <= 52.5, 11, data.table::fifelse( sp >= 52.5 & sp <= 57.5, 12, data.table::fifelse( sp >= 57.5 & sp <= 62.5, 13, data.table::fifelse( sp >= 62.5 & sp <= 67.5, 14, data.table::fifelse( sp >= 67.5 & sp <= 72.5, 15, 16)))))))))))))))) } if(inherits(x = x, what = "sf")) { net <- sf::st_geometry(x) x <- sf::st_set_geometry(x, NULL) } if ( is.matrix(x) ) { spd <- as.data.frame(x) for(i in 1:ncol(spd)){ spd[[i]] <- fx(spd[[i]]) } } else if ( is.data.frame(x) ) { spd <- x for(i in 1:ncol(spd)){ spd[[i]] <- fx(spd[[i]]) } } else if ( is.list(x) ) { for(i in 1:length(spd)){ spd[[i]] <- fx(spd[[i]]) } } else if(inherits(x, "units")){ message("Converting original units to mph") spd <- Speed(x, dist = "miles") spd <- fx(spd) } else { spd <- x spd <- fx(spd) } if(!missing(net)) { spd <- sf::st_sf(spd, geometry = sf::st_geometry(net)) } return(spd) }
/scratch/gouwar.j/cran-all/cranData/vein/R/moves_speed.R
#' Returns amount of vehicles at each age #' #' @description \code{my_age} returns amount of vehicles at each age using a #' numeric vector. #' #' @param x Numeric; vehicles by street (or spatial feature). #' @param y Numeric or data.frame; when pro_street is not available, y must be #' 'numeric', else, a 'data.frame'. The names of the columns of this data.frame #' must be the same as the elements of pro_street and each column must have a #' profile of age of use of vehicle. When 'y' is 'numeric' the vehicles #' has the same age distribution to all streets. When 'y' is a data.frame, #' the distribution by age of use varies the streets. #' @param agemax Integer; age of oldest vehicles for that category #' @param name Character; of vehicle assigned to columns of dataframe. #' @param k Integer; multiplication factor. If its length is > 1, it must match the length of x #' @param pro_street Character; each category of profile for each street. #' The length of this character vector must be equal to the length of 'x'. The #' names of the data.frame 'y' must have the same content of 'pro_street' #' @param net SpatialLinesDataFrame or Spatial Feature of "LINESTRING" #' @param verbose Logical; message with average age and total number of vehicles. #' @param namerows Any vector to be change row.names. For instance, the name of #' regions or streets. #' @return dataframe of age distribution 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 regis)*better) 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) #' dpc <- c(seq(1,20,3), 20:10) #' PC_E25_1400 <- my_age(x = net$ldv, y = dpc, name = "PC_E25_1400") #' class(PC_E25_1400) #' plot(PC_E25_1400) #' PC_E25_1400sf <- my_age(x = net$ldv, y = dpc, name = "PC_E25_1400", net = net) #' class(PC_E25_1400sf) #' plot(PC_E25_1400sf) #' PC_E25_1400nsf <- sf::st_set_geometry(PC_E25_1400sf, NULL) #' class(PC_E25_1400nsf) #' yy <- data.frame(a = 1:5, b = 5:1) # perfiles por categoria de calle #' pro_street <- c("a", "b", "a") # categorias de cada calle #' x <- c(100,5000, 3) # vehiculos #' my_age(x = x, y = yy, pro_street = pro_street) #' } my_age <- function (x, y, agemax, name = "vehicle", k = 1, pro_street, net, verbose = FALSE, namerows){ # length k if(length(k) > 1 & length(k) < length(x)){ stop("length of 'k' must be 1 ore equal to length of 'x'") } # check y if(!is.data.frame(y)){ y <- as.numeric(y) y[is.na(y)] <- 0 } else { for(i in 1:ncol(y)) y[, i] <- as.numeric( y[, i]) y[is.na(y)] <- 0 } # # start if (missing(x) | is.null(x)) { stop("Missing vehicles") } else { if(!missing(pro_street)){ if(!inherits(y, "data.frame")){ stop("'y' must be 'data.frame'") } for(i in 1:ncol(y)) y[, i] <- y[, i]/sum( y[, i]) d <- as.data.frame(t(y / sum(y))) d$cat <- names(y) dfnet <- data.frame(cat = pro_street, veh = x) dl <- list() for(i in 1:length(x)){ if(dfnet$cat[i] %in% d$cat){ dl[[i]] <- as.matrix(x[i]) %*%matrix(y[[dfnet$cat[i]]], ncol = nrow(y), nrow = 1) } } df <- as.data.frame(do.call("rbind", dl)) names(df) <- paste(name, seq(1, length(df)), sep="_") } else { if(mode(y) != "numeric") stop("When there is no 'pro_street', 'y' must be 'numeric'") d <- matrix(data = y/sum(y), nrow = 1, ncol=length(y)) df <- as.data.frame(as.matrix(x) %*%d) names(df) <- paste(name, seq(1, length(df)), sep="_") } # check k df <- df*as.numeric(k) # verbose if(verbose){ secu <- seq(1, ncol(df)) colus <- colSums(df, na.rm = T) sumdf <- sum(df, na.rm = T) message(paste("Average age of", name, "is", round(sum(secu*colus/sumdf, na.rm = T), 2), sep=" ")) message(paste("Number of",name, "is", round(sum(df, na.rm = T), 3), " [veh]", sep=" ")) cat("\n") } } # ending df <- Vehicles(df) 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) df <- sf::st_sf(df, geometry = sf::st_geometry(netsf)) } if(!missing(agemax)) df <- df[, 1:agemax] # replace NA and NaN df[is.na(df)] <- 0 return(df) }
/scratch/gouwar.j/cran-all/cranData/vein/R/my_age.R
#' Road network of the west part of Sao Paulo city #' #' This dataset is an sf class object with roads #' from a traffic simulation made by CET Sao Paulo, Brazil #' #' @format A Spatial data.frame (sf) with 1796 rows and 1 variables: #' \describe{ #' \item{ldv}{Light Duty Vehicles (veh/h)} #' \item{hdv}{Heavy Duty Vehicles (veh/h)} #' \item{lkm}{Length of the link (km)} #' \item{ps}{Peak Speed (km/h)} #' \item{ffs}{Free Flow Speed (km/h)} #' \item{tstreet}{Type of street} #' \item{lanes}{Number of lanes per link} #' \item{capacity}{Capacity of vehicles in each link (1/h)} #' \item{tmin}{Time for travelling each link (min)} #' \item{geometry}{geometry} #' } #' @usage data(net) #' @docType data "net"
/scratch/gouwar.j/cran-all/cranData/vein/R/net.R
#' Calculate speeds of traffic network #' #' @description \code{netspeed} Creates a dataframe of speeds for different hours #' and each link based on morning rush traffic data #' #' @param q Data-frame of traffic flow to each hour (veh/h) #' @param ps Peak speed (km/h) #' @param ffs Free flow speed (km/h) #' @param cap Capacity of link (veh/h) #' @param lkm Distance of link (km) #' @param alpha Parameter of BPR curves #' @param beta Parameter of BPR curves #' @param net SpatialLinesDataFrame or Spatial Feature of "LINESTRING" #' @param scheme Logical to create a Speed data-frame with 24 hours and a #' default profile. It needs ffs and ps: #' @param dist String indicating the units of the resulting distance in speed. #' Default is units from peak speed `ps` #' \tabular{rl}{ #' 00:00-06:00 \tab ffs\cr #' 06:00-07:00 \tab average between ffs and ps\cr #' 07:00-10:00 \tab ps\cr #' 10:00-17:00 \tab average between ffs and ps\cr #' 17:00-20:00 \tab ps\cr #' 20:00-22:00 \tab average between ffs and ps\cr #' 22:00-00:00 \tab ffs\cr #' } #' @return dataframe speeds with units or sf. #' @importFrom sf st_sf st_as_sf #' @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) #' class(df) #' plot(df) #plot of the average speed at each hour, +- sd #' # net$ps <- units::set_units(net$ps, "miles/h") #' # net$ffs <- units::set_units(net$ffs, "miles/h") #' # df <- netspeed(pc_week, net$ps, net$ffs, net$capacity, net$lkm, alpha = 1) #' # class(df) #' # plot(df) #plot of the average speed at each hour, +- sd #' # df <- netspeed(ps = net$ps, ffs = net$ffs, scheme = TRUE) #' # class(df) #' # plot(df) #plot of the average speed at each hour, +- sd #' # dfsf <- netspeed(ps = net$ps, ffs = net$ffs, scheme = TRUE, net = net) #' # class(dfsf) #' # head(dfsf) #' # plot(dfsf, pal = cptcity::lucky(colorRampPalette = TRUE, rev = TRUE), #' # key.pos = 1, max.plot = 9) #' } netspeed <- function (q = 1, ps, ffs, cap, lkm, alpha = 0.15, beta = 4, net, scheme = FALSE, dist = "km"){ if (scheme == FALSE & missing(q)){ stop("No vehicles on 'q'") } else if (scheme == FALSE){ qq <- as.data.frame(q) for (i in 1:ncol(qq) ) { qq[,i] <- as.numeric(qq[,i]) } ps <- as.numeric(ps) ffs <- as.numeric(ffs) cap <- as.numeric(cap) lkm <- as.numeric(lkm) dfv <- as.data.frame(do.call("cbind",(lapply(1:ncol(qq), function(i) { lkm/(lkm/ffs*(1 + alpha*(qq[,i]/cap)^beta)) })))) names(dfv) <- unlist(lapply(1:ncol(q), function(i) paste0("S",i))) df_speed <- Speed(dfv, dist = dist) } else { ps <- as.numeric(ps) ffs <- as.numeric(ffs) dfv <- cbind(replicate(5, ffs), replicate(1, 0.5*(ps + ffs) ), replicate(3, ps), replicate(7, 0.5*(ps + ffs)), replicate(3, ps), replicate(2, 0.5*(ps + ffs)), replicate(3, ffs)) names(dfv) <- c(rep("FSS",5), "AS", rep("PS", 3), rep("AS", 7), rep("PS", 3), rep("AS", 2), rep("FSS",3)) df_speed <- Speed(as.data.frame(dfv), dist = dist) } if(!missing(net)){ netsf <- sf::st_as_sf(net) df_speedsf <- sf::st_sf(df_speed, geometry = sf::st_geometry(netsf)) return(df_speedsf) } else { return(df_speed) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/netspeed.R
#' Profile of Vehicle start patterns #' #' This dataset is a dataframe with percentage of hourly starts with a lapse #' of 6 hours with engine turned off. Data source is: #' Lents J., Davis N., Nikkila N., Osses M. 2004. Sao Paulo vehicle activity #' study. ISSRC. www.issrc.org #' #' @format A data frame with 24 rows and 1 variables: #' \describe{ #' \item{V1}{24 hours profile vehicle starts for Monday} #' } #' @usage data(pc_cold) #' @docType data "pc_cold"
/scratch/gouwar.j/cran-all/cranData/vein/R/pc_cold.R
#' Profile of traffic data 24 hours 7 n days of the week #' #' This dataset is a dataframe with traffic activity normalized #' monday 08:00-09:00. This data is normalized at 08:00-09:00. #' It comes from data of toll stations near Sao Paulo City. #' The source is ARTESP (www.artesp.com.br) #' #' @format A data frame with 24 rows and 7 variables: #' \describe{ #' \item{V1}{24 hours profile for Monday} #' \item{V2}{24 hours profile for Tuesday} #' \item{V3}{24 hours profile for Wednesday} #' \item{V4}{24 hours profile for Thursday} #' \item{V5}{24 hours profile for Friday} #' \item{V6}{24 hours profile for Saturday} #' \item{V7}{24 hours profile for Sunday} #' } #' @usage data(pc_profile) #' @docType data "pc_profile"
/scratch/gouwar.j/cran-all/cranData/vein/R/pc_profile.R
#' Data.frame with pollutants names and molar mass used in VEIN #' #' This dataset also includes MIR, MOIR and EBIR is Carter SAPRC07.xls #' https://www.engr.ucr.edu/~carter/SAPRC/ #' #' @format A data frame with 148 rows and 10 variables: #' \describe{ #' \item{n}{Number for each pollutant, from 1 to 132} #' \item{group1}{classification for pollutants including "NMHC", #' "PAH", "METALS", "PM", "criteria" and "PCDD" } #' \item{group2}{A sub classification for pollutants including "alkenes", #' "alkynes", "aromatics", "alkanes", "PAH",, "aldehydes", "ketones", "METALS", #' "PM_char", "criteria", "cycloalkanes", "NMHC", "PCDD", "PM10", "PM2.5"} #' \item{pollutant}{1 of the 132 pollutants covered} #' \item{CAS}{CAS Registry Number} #' \item{g_mol}{molar mass} #' \item{MIR}{Maximum incremental Reactivity (gm O3 / gm VOC)} #' \item{MOIR}{Reactivity (gm O3 / gm VOC)} #' \item{EBIR}{Reactivity (gm O3 / gm VOC)} #' \item{notes}{Inform some assumption for molar mass} #' } #' @usage data(pollutants) #' @docType data "pollutants"
/scratch/gouwar.j/cran-all/cranData/vein/R/pollutants.R
#' Profile of traffic data 24 hours 7 n days of the week #' #' This dataset is n a list of data-frames with traffic activity normalized #' monday 08:00-09:00. It comes from data of toll stations near Sao Paulo City. #' The source is ARTESP (www.artesp.com.br) for months January and June and #' years 2012, 2013 and 2014. The type of vehicles covered are PC, LCV, MC and #' HGV. #' #' @format A list of data-frames with 24 rows and 7 variables: #' \describe{ #' \item{PC_JUNE_2012}{168 hours} #' \item{PC_JUNE_2013}{168 hours} #' \item{PC_JUNE_2014}{168 hours} #' \item{LCV_JUNE_2012}{168 hours} #' \item{LCV_JUNE_2013}{168 hours} #' \item{LCV_JUNE_2014}{168 hours} #' \item{MC_JUNE_2012}{168 hours} #' \item{MC_JUNE_2013}{168 hours} #' \item{MC_JUNE_2014}{168 hours} #' \item{HGV_JUNE_2012}{168 hours} #' \item{HGV_JUNE_2013}{168 hours} #' \item{HGV_JUNE_2014}{168 hours} #' \item{PC_JANUARY_2012}{168 hours} #' \item{PC_JANUARY_2013}{168 hours} #' \item{PC_JANUARY_2014}{168 hours} #' \item{LCV_JANUARY_2012}{168 hours} #' \item{LCV_JANUARY_2013}{168 hours} #' \item{LCV_JANUARY_2014}{168 hours} #' \item{MC_JANUARY_2012}{168 hours} #' \item{MC_JANUARY_2014}{168 hours} #' \item{HGV_JANUARY_2012}{168 hours} #' \item{HGV_JANUARY_2013}{168 hours} #' \item{HGV_JANUARY_2014}{168 hours} #' } #' @usage data(pc_profile) #' @docType data "profiles"
/scratch/gouwar.j/cran-all/cranData/vein/R/profiles.R
#' Remove units #' #' \code{\link{remove_units}} Remove units from sf, data.frames, matrix or units. #' #' @param x Object with class "sf", "data.frame", "matrix" or "units" #' @return "sf", data.frame", "matrix" or numeric #' @keywords units #' @importFrom sf st_geometry st_set_geometry #' @export #' @examples \dontrun{ #' ef1 <- ef_cetesb(p = "CO", c("PC_G", "PC_FE")) #' class(ef1) #' sapply(ef1, class) #' a <- remove_units(ef1) #' } remove_units <- function(x){ if(inherits(x, "sf")) { geo <- sf::st_geometry(x) ef <- sf::st_set_geometry(x, NULL) for(i in 1:ncol(ef)){ ef[,i] <- as.numeric(ef[,i]) } ef <- sf::st_sf(ef, geometry = geo) } else if ( is.matrix(x) ) { ef <- as.data.frame(x) for(i in 1:ncol(ef)){ ef[,i] <- as.numeric(ef[,i]) } } else if ( is.data.frame(x) ) { ef <- x for(i in 1:ncol(ef)){ ef[,i] <- as.numeric(ef[,i]) } } else if(is.character(x) | is.list(x) | is.array(x)){ ef <- x #nada } else { ef <- as.numeric(x) } return(ef) }
/scratch/gouwar.j/cran-all/cranData/vein/R/remove_units.R
#' Estimation of average daily running losses evaporative emissions #' #' @description \code{running_losses} estimates evaporative emissions from #' EMEP/EEA emisison guidelines #' #' @param x Numeric or data.frame; Mean number of trips per vehicle per day or Vehicles. #' @param erhotfi average daily hot running losses evaporative factor #' for vehicles with fuel injection and returnless fuel systems #' @param lkm Numeric with class units and unit km. #' @param carb fraction of gasoline vehicles with carburetor or fuel return system. #' @param p Fraction of trips finished with hot engine #' @param erhotc average daily running losses evaporative factor for vehicles with #' carburator or fuel return system #' @param erwarmc average daily cold and warm running losses evaporative factor #' for vehicles with carburetor or fuel return system #' @return numeric vector of emission estimation in grams #' @name running_losses-deprecated #' @seealso \code{\link{vein-deprecated}} #' @keywords internal NULL #' @rdname vein-deprecated #' @section \code{Evaporative}: #' For \code{running_losses}, use \code{\link{emis_evap}}. #' #' @references Mellios G and Ntziachristos 2016. Gasoline evaporation. In: #' EEA, EMEP. EEA air pollutant emission inventory guidebook-2009. European #' Environment Agency, Copenhagen, 2009 #' @export #' @examples \dontrun{ #' # Do not run #' } #' running_losses <- function(x, erhotfi, lkm, carb, p, erhotc, erwarmc) { .Deprecated("emis_evap") "Evaporative emissions" }
/scratch/gouwar.j/cran-all/cranData/vein/R/running_losses.R
#' Speciation of emissions #' #' @description \code{speciate} separates emissions in different compounds. #' It covers black carbon and organic matter from particulate matter. Soon it #' will be added more speciations #' #' @param x Emissions estimation #' @param spec The speciations are: #' \itemize{ #' \item{"bcom"}{: Splits PM2.5 in black carbon and organic matter.} #' \item{"tyre" or "tire"}{: Splits PM in PM10, PM2.5, PM1 and PM0.1.} #' \item{"brake"}{: Splits PM in PM10, PM2.5, PM1 and PM0.1.} #' \item{"road"}{: Splits PM in PM10 and PM2.5.} #' \item{"nox"}{: Splits NOx in NO and NO2.} #' \item{"nmhc"}{: Splits NMHC in compounds, see \code{\link{ef_ldv_speed}}.} #' \item{"pmiag", "pmneu", "pmneu2"}{: Splits PM in groups, see note below.} #' } #' @param veh Type of vehicle: #' \itemize{ #' \item{"bcom"}{: veh can be "PC", "LCV", HDV" or "Motorcycle".} #' \item{"tyre" or "tire"}{: not necessary.} #' \item{"brake"}{: not necessary.} #' \item{"road"}{: not necessary.} #' \item{"nox"}{: veh can be "PC", "LCV", HDV" or "Motorcycle".} #' \item{"nmhc"}{see below} #' \item{""pmiag", "pmneu", "pmneu2"}{: not necessary.} #' } #' @param fuel Fuel. #' \itemize{ #' \item{"bcom"}{: "G" or "D".} #' \item{"tyre" or "tire"}{: not necessary.} #' \item{"brake"}{: not necessary.} #' \item{"road"}{: not necessary.} #' \item{"nox"}{: "G", "D", "LPG", "E85" or "CNG".} #' \item{"nmhc"}{see below} #' \item{"pmiag", "pmneu", "pmneu2"}{: not necessary.} #' } #' @param eu Emission standard #' \itemize{ #' \item{"bcom"}{: "G" or "D".} #' \item{"tyre" or "tire"}{: not necessary.} #' \item{"brake"}{: not necessary.} #' \item{"road"}{: not necessary.} #' \item{"nox"}{: "G", "D", "LPG", "E85" or "CNG".} #' \item{"nmhc"}{see below} #' \item{"pmiag", "pmneu", "pmneu2"}{: not necessary.} #' } #' @param list when TRUE returns a list with number of elements of the list as #' the number species of pollutants #' @param pmpar Numeric vector for PM speciation eg: #' c(e_so4i = 0.0077, e_so4j = 0.0623, e_no3i = 0.00247, #' e_no3j = 0.01053, e_pm25i = 0.1, e_pm25j = 0.3, #' e_orgi = 0.0304, e_orgj = 0.1296, e_eci = 0.056, #' e_ecj = 0.024, h2o = 0.277) These are default values. however, when this #' argument is present, new values are used. #' @param verbose Logical to show more information #' #' @note options for spec "nmhc": #' \tabular{ccc}{ #' veh \tab fuel \tab eu \cr #' LDV \tab G \tab PRE \cr #' LDV \tab G \tab I \cr #' LDV \tab D \tab all \cr #' HDV \tab D \tab all \cr #' LDV \tab LPG \tab all \cr #' LDV \tab G \tab Evaporative \cr #' LDV \tab E25 \tab Evaporative \cr #' LDV \tab E100 \tab Evaporative \cr #' LDV \tab E25 \tab Exhaust \cr #' LDV \tab E100 \tab Exhaust \cr #' HDV \tab B5 \tab Exhaust \cr #' LDV \tab E85 \tab Exhaust \cr #' LDV \tab E85 \tab Evaporative \cr #' LDV \tab CNG \tab Exhaust \cr #' ALL \tab E100 \tab Liquid \cr #' ALL \tab G \tab Liquid \cr #' ALL \tab E25 \tab Liquid \cr #' ALL \tab ALL \tab OM \cr #' LDV \tab G \tab OM-001 \cr #' LDV \tab D \tab OM-002 \cr #' HDV \tab D \tab OM-003 \cr #' MC \tab G \tab OM-004 \cr #' ALL \tab LPG \tab OM-005 \cr #' LDV \tab G \tab OM-001-001 \cr #' LDV \tab G \tab OM-001-002 \cr #' LDV \tab G \tab OM-001-003 \cr #' LDV \tab G \tab OM-001-004 \cr #' LDV \tab G \tab OM-001-005 \cr #' LDV \tab G \tab OM-001-006 \cr #' LDV \tab G \tab OM-001-007 \cr #' LDV \tab D \tab OM-002-001 \cr #' LDV \tab D \tab OM-002-002 \cr #' LDV \tab D \tab OM-002-003 \cr #' LDV \tab D \tab OM-002-004 \cr #' LDV \tab D \tab OM-002-005 \cr #' LDV \tab D \tab OM-002-006 \cr #' HDV \tab D \tab OM-003-001 \cr #' HDV \tab D \tab OM-003-002 \cr #' HDV \tab D \tab OM-003-003 \cr #' HDV \tab D \tab OM-003-004 \cr #' HDV \tab D \tab OM-003-005 \cr #' HDV \tab D \tab OM-003-006 \cr #' MC \tab G \tab OM-004-001 \cr #' MC \tab G \tab OM-004-002 \cr #' MC \tab G \tab OM-004-003 \cr #' ALL \tab ALL \tab urban \cr #' ALL \tab ALL \tab highway \cr #' } #' #' after eu = OM, all profiles are Chinese #' # the following specs will be removed soon #' \itemize{ #' \item{"iag_racm"}{: ethanol emissions added in hc3.} #' \item{"iag" or "iag_cb05"}{: Splits NMHC by CB05 (WRF exb05_opt1) group .} #' \item{"petroiag_cb05"}{: Splits NMHC by CB05 (WRF exb05_opt1) group .} #' \item{"iag_cb05v2"}{: Splits NMHC by CB05 (WRF exb05_opt2) group .} #' \item{"neu_cb05"}{: Splits NMHC by CB05 (WRF exb05_opt2) group alternative.} #' \item{"petroiag_cb05v2"}{: Splits NMHC by CB05 (WRF exb05_opt2) group alternative.} #' } #' @importFrom units as_units #' @importFrom sf st_as_sf st_set_geometry #' @return dataframe of speciation in grams or mols #' @references "bcom": Ntziachristos and Zamaras. 2016. Passenger cars, light #' commercial trucks, heavy-duty vehicles including buses and motorcycles. In: #' EEA, EMEP. EEA air pollutant emission inventory guidebook-2009. European #' Environment Agency, Copenhagen, 2016 #' @references "tyre", "brake" and "road": Ntziachristos and Boulter 2016. #' Automobile tyre and brake wear and road abrasion. In: EEA, EMEP. EEA air #' pollutant emission inventory #' guidebook-2009. European Environment Agency, Copenhagen, 2016 #' @references "iag": Ibarra-Espinosa S. Air pollution modeling in Sao Paulo #' using bottom-up vehicular emissions inventories. 2017. PhD thesis. Instituto de #' Astronomia, Geofisica e Ciencias Atmosfericas, Universidade de Sao Paulo, #' Sao Paulo, page 88. #' Speciate EPA: https://cfpub.epa.gov/speciate/. : #' K. Sexton, H. Westberg, "Ambient hydrocarbon and ozone measurements downwind #' of a large automotive painting plant" Environ. Sci. Tchnol. 14:329 (1980).P.A. #' Scheff, R.A. Schauer, James J., Kleeman, Mike J., Cass, Glen R., Characterization #' and Control of Organic Compounds Emitted from Air Pollution Sources, Final Report, #' Contract 93-329, prepared for California Air Resources Board Research Division, #' Sacramento, CA, April 1998. #' 2004 NPRI National Databases as of April 25, 2006, #' http://www.ec.gc.ca/pdb/npri/npri_dat_rep_e.cfm. Memorandum #' Proposed procedures for preparing composite speciation profiles using #' Environment Canada s National Pollutant Release Inventory (NPRI) for #' stationary sources, prepared by Ying Hsu and Randy Strait of E.H. Pechan #' Associates, Inc. for David Niemi, Marc Deslauriers, and Lisa Graham of #' Environment Canada, September 26, 2006. #' #' @note spec \strong{"pmiag"} speciate pm2.5 into e_so4i, e_so4j, e_no3i, #' e_no3j, e_mp2.5i, e_mp2.5j, e_orgi, e_orgj, e_eci, e_ecj and h2o. Reference: #' Rafee, S.: Estudo numerico do impacto das emissoes veiculares e fixas da #' cidade de Manaus nas concentracoes de poluentes atmosfericos da regiao #' amazonica, Master thesis, Londrina: Universidade Tecnologica Federal do #' Parana, 2015. #' #' specs: "neu_cb05", "pmneu" and "pmneu2" provided by Daniel Schuch, #' from Northeastern University. #' "pm2023" provided by Iara da Silva; Leila D. Martins #' #' Speciation with fuels \strong{"E25", "E100" and "B5"} made by Prof. Leila Martins (UTFPR), #' represents BRAZILIAN fuel #' #' #' pmiag2 pass the mass only on j fraction #' @export #' @examples #' \dontrun{ #' # Do not run #' pm <- rnorm(n = 100, mean = 400, sd = 2) #' (df <- speciate(pm, veh = "PC", fuel = "G", eu = "I")) #' (df <- speciate(pm, spec = "brake", veh = "PC", fuel = "G", eu = "I")) #' (dfa <- speciate(pm, spec = "iag", veh = "veh", fuel = "G", eu = "Exhaust")) #' (dfb <- speciate(pm, spec = "iag_cb05v2", veh = "veh", fuel = "G", eu = "Exhaust")) #' (dfb <- speciate(pm, spec = "neu_cb05", veh = "veh", fuel = "G", eu = "Exhaust")) #' pm <- units::set_units(pm, "g/km^2/h") #' #(dfb <- speciate(as.data.frame(pm), spec = "pmiag", veh = "veh", fuel = "G", eu = "Exhaust")) #' #(dfb <- speciate(as.data.frame(pm), spec = "pmneu", veh = "veh", fuel = "G", eu = "Exhaust")) #' #(dfb <- speciate(as.data.frame(pm), spec = "pmneu2", veh = "veh", fuel = "G", eu = "Exhaust")) #' # new #' (pah <- speciate(spec = "pah", veh = "LDV", fuel = "G", eu = "I")) #' (xs <- speciate(spec = "pcdd", veh = "LDV", fuel = "G", eu = "I")) #' (xs <- speciate(spec = "pmchar", veh = "LDV", fuel = "G", eu = "I")) #' (xs <- speciate(spec = "metals", veh = "LDV", fuel = "G", eu = "all")) #' } speciate <- function(x = 1, spec = "bcom", veh, fuel, eu, list = FALSE, pmpar, verbose = FALSE) { nvoc <- c( "e_eth", "e_hc3", "e_hc5", "e_hc8", "e_ol2", "e_olt", "e_oli", "e_iso", "e_tol", "e_xyl", "e_c2h5oh", "e_hcho", "e_ch3oh", "e_ket" ) pmdf <- data.frame(c( "e_so4i", "e_so4j", "e_no3i", "e_no3j", "e_pm25i", "e_pm25j", "e_orgi", "e_orgj", "e_eci", "e_ecj", "h2o" )) # bcom black carbon and organic matter#### if (spec == "bcom") { bcom <- sysdata$bcom df <- bcom[bcom$VEH == veh & bcom$FUEL == fuel & bcom$STANDARD == eu, ] dfb <- Emissions(data.frame( BC = x * df$BC / 100, OM = (df$OM / 100) * (x * df$BC / 100) )) if (list == TRUE) { dfb <- as.list(dfb) } # tyre #### } else if (spec == "tyre" | spec == "tire") { df <- data.frame( PM10 = 0.6, PM2.5 = 0.42, PM1 = 0.06, PM0.1 = 0.048 ) dfb <- Emissions(data.frame( PM10 = x * 0.6, PM2.5 = x * 0.42, PM1 = x * 0.06, PM0.1 = x * 0.048 )) if (list == TRUE) { dfb <- as.list(dfb) } # brake #### } else if (spec == "brake") { df <- data.frame( PM10 = 0.98, PM2.5 = 0.39, PM1 = 0.1, PM0.1 = 0.08 ) dfb <- Emissions(data.frame( PM10 = x * 0.98, PM2.5 = x * 0.39, PM1 = x * 0.1, PM0.1 = x * 0.08 )) if (list == TRUE) { dfb <- as.list(dfb) } # road #### } else if (spec == "road") { df <- data.frame(PM10 = 0.5, PM2.5 = 0.27) dfb <- Emissions(data.frame(PM10 = x * 0.5, PM2.5 = x * 0.27)) if (list == TRUE) { dfb <- as.list(dfb) } # iag #### } else if (spec %in% c("iag", "iag_cb05", "iag_cb05v2", "neu_cb05", "iag_racm", "petroiag_cb05", "petroiag_cb05v2")) { iag <- sysdata$iag spec <- ifelse(spec == "iag", "iag_cb05", spec) iag <- iag[iag$mech == spec, ] iag$VEH_FUEL_STANDARD <- paste(iag$VEH, iag$FUEL, iag$STANDARD, sep = "_") iag2 <- long_to_wide( df = iag, column_with_new_names = "groups", column_with_data = "x", column_fixed = "VEH_FUEL_STANDARD" ) iag2 <- cbind( iag2, do.call( "rbind", strsplit( x = iag2$VEH_FUEL_STANDARD, split = "_" ) ) ) names(iag2)[ncol(iag2)] <- "STANDARD" names(iag2)[ncol(iag2) - 1] <- "FUEL" names(iag2)[ncol(iag2) - 2] <- "VEH" iag <- iag2 iag$VEH_FUEL_STANDARD <- NULL df <- iag[iag$VEH == veh & iag$FUEL == fuel & iag$STANDARD == eu, ] df <- df[, 1:(ncol(df) - 3)] if (is.data.frame(x)) { for (i in 1:ncol(x)) { x[, i] <- as.numeric(x[, i]) } } if (list == T) { dfx <- df[, 1:ncol(df)] dfb <- lapply(1:ncol(dfx), function(i) { dfx[, i] * x / 100 }) names(dfb) <- names(dfx) for (j in 1:length(dfb)) { for (i in 1:ncol(x)) { dfb[[j]][, i] <- dfb[[j]][, i] * units::as_units("mol h-1") } } } else { dfx <- df[, 1:ncol(df)] dfb <- as.data.frame(lapply(1:ncol(dfx), function(i) { dfx[, i] * x / 100 })) names(dfb) <- names(dfx) } names(df) <- toupper(names(df)) # nmhc #### } else if (spec == "nmhc") { nmhc <- sysdata$nmhc if(!veh %in% unique(nmhc$veh)) { choice <- utils::menu(unique(nmhc$veh), title="Choose veh") veh <- unique(nmhc$veh)[choice] } nmhc <- nmhc[nmhc$veh == veh , ] if(!fuel %in% unique(nmhc$fuel)) { choice <- utils::menu(unique(nmhc$fuel), title="Choose fuel") fuel <- unique(nmhc$fuel)[choice] } nmhc <- nmhc[nmhc$fuel == fuel , ] if(!eu %in% unique(nmhc$eu)) { choice <- utils::menu(unique(nmhc$eu), title="Choose eu") eu <- unique(nmhc$eu)[choice] } df <- nmhc[nmhc$eu == eu , ] if (list == T) { dfb <- lapply(1:nrow(df), function(i) { df[i, ]$x * x / 100 }) names(dfb) <- df$species } else { dfb <- data.table::rbindlist(lapply(1:nrow(df), function(i) { data.frame(x = df[i, ]$x * x / 100, pol = df$species[i]) })) if(!is.null(names(x))) names(dfb) <- c(names(x), "pol") } # pah #### } else if (spec == "pah") { nmhc <- sysdata$pah if(!veh %in% unique(nmhc$veh)) { choice <- utils::menu(unique(nmhc$veh), title="Choose veh") veh <- unique(nmhc$veh)[choice] } nmhc <- nmhc[nmhc$veh == veh , ] if(!fuel %in% unique(nmhc$fuel)) { choice <- utils::menu(unique(nmhc$fuel), title="Choose fuel") fuel <- unique(nmhc$fuel)[choice] } nmhc <- nmhc[nmhc$fuel == fuel , ] if(!eu %in% unique(nmhc$eu)) { choice <- utils::menu(unique(nmhc$eu), title="Choose eu") eu <- unique(nmhc$eu)[choice] } df <- nmhc[nmhc$eu == eu , ] if (list == T) { dfb <- lapply(1:nrow(df), function(i) { df[i, ]$x }) names(dfb) <- df$species } else { dfb <- data.table::rbindlist(lapply(1:nrow(df), function(i) { data.frame(x = df[i, ]$x, pol = df$species[i]) })) if(!is.null(names(x))) names(dfb) <- c(names(x), "pol") } # pcdd #### } else if (spec == "pcdd") { nmhc <- sysdata$pcdd nmhc$x <- nmhc$x*1e-12 if(!veh %in% unique(nmhc$veh)) { choice <- utils::menu(unique(nmhc$veh), title="Choose veh") veh <- unique(nmhc$veh)[choice] } nmhc <- nmhc[nmhc$veh == veh , ] if(!fuel %in% unique(nmhc$fuel)) { choice <- utils::menu(unique(nmhc$fuel), title="Choose fuel") fuel <- unique(nmhc$fuel)[choice] } nmhc <- nmhc[nmhc$fuel == fuel , ] if(!eu %in% unique(nmhc$eu)) { choice <- utils::menu(unique(nmhc$eu), title="Choose eu") eu <- unique(nmhc$eu)[choice] } df <- nmhc[nmhc$eu == eu , ] if (list == T) { dfb <- lapply(1:nrow(df), function(i) { df[i, ]$x }) names(dfb) <- df$species } else { dfb <- data.table::rbindlist(lapply(1:nrow(df), function(i) { data.frame(x = df[i, ]$x, pol = df$species[i]) })) if(!is.null(names(x))) names(dfb) <- c(names(x), "pol") } # metals #### } else if (spec %in% c("metal", "metals")) { message("multiplies fuel consumption (g/km)") nmhc <- sysdata$metals if(!veh %in% unique(nmhc$veh)) { choice <- utils::menu(unique(nmhc$veh), title="Choose veh") veh <- unique(nmhc$veh)[choice] } nmhc <- nmhc[nmhc$veh == veh , ] if(!fuel %in% unique(nmhc$fuel)) { choice <- utils::menu(unique(nmhc$fuel), title="Choose fuel") fuel <- unique(nmhc$fuel)[choice] } nmhc <- nmhc[nmhc$fuel == fuel , ] if(!eu %in% unique(nmhc$eu)) { choice <- utils::menu(unique(nmhc$eu), title="Choose eu") eu <- unique(nmhc$eu)[choice] } df <- nmhc[nmhc$eu == eu , ] if (list == T) { dfb <- lapply(1:nrow(df), function(i) { df[i, ]$x }) names(dfb) <- df$species } else { dfb <- data.table::rbindlist(lapply(1:nrow(df), function(i) { data.frame(x = df[i, ]$x*x, pol = df$species[i]) })) if(!is.null(names(x))) names(dfb) <- c(names(x), "pol") } # pmchar #### } else if (spec %in% c("pmchar")) { nmhc <- sysdata$pmchar nmhc$units <- ifelse(nmhc$species %in% grep(pattern = "AS_", x = nmhc$species, value = TRUE), "cm2/km"," N/km") if(!veh %in% unique(nmhc$veh)) { choice <- utils::menu(unique(nmhc$veh), title="Choose veh") veh <- unique(nmhc$veh)[choice] } nmhc <- nmhc[nmhc$veh == veh , ] if(!fuel %in% unique(nmhc$fuel)) { choice <- utils::menu(unique(nmhc$fuel), title="Choose fuel") fuel <- unique(nmhc$fuel)[choice] } nmhc <- nmhc[nmhc$fuel == fuel , ] if(!eu %in% unique(nmhc$eu)) { choice <- utils::menu(unique(nmhc$eu), title="Choose eu") eu <- unique(nmhc$eu)[choice] } df <- nmhc[nmhc$eu == eu , ] if (list == T) { dfb <- lapply(1:nrow(df), function(i) { df[i, ]$x }) names(dfb) <- df$species } else { dfb <- data.table::rbindlist(lapply(1:nrow(df), function(i) { data.frame(x = df[i, ]$x*x, pol = df$species[i], unit = df$units[i]) })) if(!is.null(names(x))) names(dfb) <- c(names(x), "pol") } # nox #### } else if (spec == "nox") { bcom <- sysdata$nox df <- bcom[bcom$VEH == veh & bcom$FUEL == fuel & bcom$STANDARD == eu, ] dfb <- Emissions(data.frame( NO2 = x * df$NO2, NO = x * df$NO )) if (list == TRUE) { dfb <- as.list(dfb) } # PM #### } else if (spec %in% c("pmiag", "pmneu", "pmneu2")) { if(verbose) message("Input emissions must be in g/(km^2)/h\n") if(verbose) message("Output flux will be ug/(m^2)/s\n") if(verbose) message("PM.2.5-10 must be calculated as substraction of PM10-PM2.5 to enter this variable into WRF") if (inherits(x, "sf")) { x <- sf::st_set_geometry(x, NULL) } else if (inherits(x, "Spatial")) { x <- sf::st_as_sf(x) x <- sf::st_set_geometry(x, NULL) } x$id <- NULL # x (g / Xkm^2 / h) # x <- x*1000000 # g to micro grams # x <- x*(1/1000)^2 # km^2 to m^2 # x <- x/3600#*(dx)^-2 # h to seconds. Consider the DX if (!missing(pmpar)) { if (length(pmpar) != 11) stop("length 'pmpar' must be 11") df <- as.data.frame(matrix(pmpar, ncol = length(pmpar))) names(df) <- names(pmpar) } else { if (spec == "pmiag") { df <- data.frame( e_so4i = 0.0077, e_so4j = 0.0623, e_no3i = 0.00247, e_no3j = 0.01053, e_pm25i = 0.1, e_pm25j = 0.3, e_orgi = 0.0304, e_orgj = 0.1296, e_eci = 0.056, e_ecj = 0.024#,h2o = 0.277 ) } else if (spec == "pmneu") { df <- data.frame( e_so4i = 0, e_so4j = 0.0077 + 0.0623, e_no3i = 0, e_no3j = 0.00247 + 0.01053, e_pm25i = 0, e_pm25j = 0.1 + 0.3, e_orgi = 0, e_orgj = 0.0304 + 0.1296, e_eci = 0, e_ecj = 0.056 + 0.024#,h2o = 0.277 ) } else if (spec == "pm2023") { df <- data.frame( e_so4i = 0.027, e_so4j = 0.008, e_no3i = 0.015, e_no3j = 0.001, e_pm25i = 0.193, e_pm25j = 0., e_orgi = 0, e_orgj = 0.0304 + 0.1296, e_eci = 0, e_ecj = 0.056 + 0.024#,h2o = 0.277 ) } else if (spec == "pmneu2") { df <- data.frame( e_so4i = 0, e_so4j = 0.07, e_no3i = 0, e_no3j = 0.015, e_pm25i = 0, e_pm25j = 0.3, e_orgi = 0, e_orgj = 0.35, e_eci = 0, e_ecj = 0.18#,h2o = 0.277 ) } } names(df) <- toupper(names(df)) if (is.data.frame(x)) { for (i in 1:ncol(x)) { x[, i] <- units::set_units(x[, i], "ug/m^2/s") } } if (list == T) { dfx <- df dfb <- lapply(1:ncol(dfx), function(i) { dfx[, i] * x }) names(dfb) <- names(dfx) # for (j in 1:length(dfb)) { # for (i in 1:ncol(x)) { # dfb[[j]][ , i] <- units::set_units(dfb[[j]][ , i], "g/m^2/s") # } # } } else { dfx <- df dfb <- as.data.frame(lapply(1:ncol(dfx), function(i) { dfx[, i] * x })) names(dfb) <- names(dfx) # for (i in 1:ncol(x)) { # dfb[ , i] <- dfb[ , i] * units::as_units("g m-2 s-1") # } } } else { stop("Selelect another `spec`") } return(dfb) }
/scratch/gouwar.j/cran-all/cranData/vein/R/speciate.R
#' Split street emissions based on a grid #' #' @description \code{\link{split_emis}} split street emissions into a grid. #' #' @param net A spatial dataframe of class "sp" or "sf". When class is "sp" #' it is transformed to "sf" with emissions. #' @param distance Numeric distance or a grid with class "sf". #' @param add_column Character indicating name of column of distance. For instance, #' if distance is an sf object, and you wand to add one extra column to the #' resulting object. #' @param verbose Logical, to show more information. #' @importFrom sf st_sf st_as_sf st_length st_intersection st_set_geometry #' @export #' @examples \dontrun{ #' data(net) #' g <- make_grid(net, 1/102.47/2) #500m in degrees #' names(net) #' dim(net) #' netsf <- sf::st_as_sf(net)[, "ldv"] #' x <- split_emis(net = netsf, distance = g) #' dim(x) #' g$A <- rep(letters, length = 20)[1:nrow(g)] #' g$B <- rev(g$A) #' netsf <- sf::st_as_sf(net)[, c("ldv", "hdv")] #' xx <- split_emis(netsf, g, add_column = c("A", "B")) #' } split_emis <- function(net, distance, add_column, verbose = TRUE){ net <- sf::st_as_sf(net) if(is.numeric(distance)){ if(verbose) cat("Creating grid\n") g <- make_grid(spobj = net, width = distance) } else if (inherits(distance, "sf")) { g <- distance } net$id <- NULL if(verbose){ sumemis <- sum(sf::st_set_geometry(net, NULL), na.rm = T)/1000 cat("Total Emissions", sumemis, " kg \n") } ncolnet <- names(sf::st_set_geometry(net, NULL)) net$LKM <- sf::st_length(net) if(verbose) cat("Intersecting\n") gnet <- suppressMessages(suppressWarnings(st_intersection(net, g))) # check add_column and store it if(!missing(add_column)){ nc <- list() for(i in 1:length(add_column)){ nc[[i]] <- gnet[[add_column[i]]] gnet[[add_column[i]]] <- NULL } } gnet$LKM2 <- sf::st_length(gnet) geo <- sf::st_geometry(gnet) gnet <- as.data.frame(sf::st_set_geometry(gnet, NULL)) gnet[, ncolnet] <- gnet[, ncolnet] * as.numeric(gnet$LKM2/gnet$LKM) gnet <- as.data.frame(gnet[, ncolnet]) if(verbose){ sumemis <- sum(gnet, na.rm = T)/1000 cat("Total Emissions", sumemis, " kg \n") } if(!missing(add_column)){ if(verbose) cat("Adding Column\n") for(i in 1:length(add_column)){ gnet[[add_column[i]]] <- nc[[i]] } } names(gnet) <- ncolnet gnet$id <- 1:nrow(gnet) gnet <- sf::st_sf(gnet, geometry = geo) return(gnet) }
/scratch/gouwar.j/cran-all/cranData/vein/R/split_emis.R
#' Expansion of hourly traffic data #' #' @description \code{temp_fact} is a matrix multiplication between traffic and #' hourly expansion data-frames to obtain a data-frame of traffic #' at each link to every hour #' #' @param q Numeric; traffic data per each link #' @param pro Numeric; expansion factors data-frames #' @param net SpatialLinesDataFrame or Spatial Feature of "LINESTRING" #' @param time Character to be the time units as denominator, eg "1/h" #' @return data-frames of expanded traffic or sf. #' @importFrom sf st_sf st_as_sf #' @export #' @examples \dontrun{ #' # Do not run #' data(net) #' data(pc_profile) #' pc_week <- temp_fact(net$ldv+net$hdv, pc_profile) #' plot(pc_week) #' pc_weeksf <- temp_fact(net$ldv+net$hdv, pc_profile, net = net) #' plot(pc_weeksf) #' } temp_fact <- function(q, pro, net, time) { if (missing(q) | is.null(q)) { stop("No traffic data") } if(!missing(time)){ df <- Vehicles(as.data.frame(as.matrix(q) %*% matrix(unlist(pro), nrow=1)), time = time) } else { df <- Vehicles(as.data.frame(as.matrix(q) %*% matrix(unlist(pro), nrow=1))) } if(!missing(net)){ netsf <- sf::st_as_sf(net) speed <- sf::st_sf(df, geometry = sf::st_geometry(netsf)) return(speed) } else { return(df) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/temp_fact.R
#' Expanded Vehicles data.frame by hour #' #' @description \code{\link{temp_veh}} multiplies #' vehicles with temporal factor #' #' @param x Vehicles data.frame #' @param tfs temporal factor #' @param array Logical, to return an array #' @seealso \code{\link{temp_fact}} #' @return data.table #' @importFrom data.table rbindlist #' @export #' @examples \dontrun{ #' data(net) #' data(pc_profile) #' x <- age_ldv(x = net$ldv) #' dx <- temp_veh(x = x, tfs = pc_profile[[1]]) #' plot(Vehicles(as.data.frame(dx[, 1:50]))) #' dx2 <- temp_veh(x = x, #' tfs = pc_profile[[1]], #' array = TRUE) #' plot(EmissionsArray(dx2)) #' } temp_veh <- function(x, tfs, array = FALSE){ lapply(seq_along(tfs), function(i) { x <- x*tfs[i] if(!array) x$Hour <- seq_along(tfs)[i] x }) -> xx if(array) { lx <- unlist(lapply(xx, unlist)) a <- array(data = lx, dim = c(nrow(x), ncol(x), length(tfs))) return(a) } else { return(data.table::rbindlist(xx)) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/temp_veh.R
#' Check the max number of threads #' #' @description \code{get_threads} check the number of threads in this machine #' #' @return Integer with the max number of threads #' #' @useDynLib vein #' @export #' @examples #' { #' check_nt() #' } check_nt <- function() { .Fortran("checkntf", nt = integer(1L) )$nt }
/scratch/gouwar.j/cran-all/cranData/vein/R/threads.R
#' creates a .tex a table from a data.frame #' #' @description \code{\link{to_latex}} reads a data.frme an dgenerates a .tex #' table, aiming to replicate the method of tablegenerator.com #' #' @param df data.frame with three column. #' @param file Character, name of new .tex file #' @param caption Character caption of table #' @param label Character, label of table #' @family helpers #' @return a text file with extension .tex. #' @importFrom sf st_sf #' @seealso \code{\link{vein_notes}} \code{\link{long_to_wide}} #' @export #' @examples \dontrun{ #' df <- data.frame(pollutant = rep(c("CO", "propadiene", "NO2"), 10), #' emission = vein::Emissions(1:30), #' region = rep(letters[1:2], 15)) #' df #' long_to_wide(df) #' (df2 <- long_to_wide(df, column_fixed = "region")) #' to_latex(df2) #' to_latex(long_to_wide(df, column_fixed = "region"), #' file = paste0(tempfile(), ".tex")) #' } to_latex <- function (df, file, caption = "My table", label = "tab:df"){ lo <- unlist(lapply(df, is.numeric)) order <- paste0(ifelse(lo == TRUE, "r", "l")) if(missing(file)){ cat(paste0("% Generated with vein ", packageVersion("vein"), "\n")) cat("% Please add the following required packages to your document preamble:\n") cat("% \\usepackage{booktabs}\n") cat("% \\usepackage{graphicx}\n") cat("\\begin{table}[]\n") cat(paste0("\\caption{", caption, "}\n")) cat(paste0("\\label{", label, "}\n")) cat("\\resizebox{\\textwidth}{!}{%\n") cat("\\begin{tabular}{@{}", order, "@{}}\n") cat("\\toprule\n") nn <- names(df) # top top <- paste0(nn[1:(length(nn) - 1)], rep(" & ", ncol(df) - 1)) cat(top, nn[length(nn)], "\\\\ \\midrule\n") # body for(i in 1:(ncol(df) - 1)){ df[, i] <- paste0(df[, i], " & ") } df[, ncol(df)] <- paste0(df[, ncol(df)], " \\\\ ") df[nrow(df), ncol(df)] <- paste0(df[nrow(df), ncol(df)], " \\bottomrule") names(df) <- NULL for(i in 1:nrow(df)) cat(unlist(df[i, ]), "\n") # bottom cat("\\end{tabular}%\n") cat("}\n") cat("\\end{table}\n") } else { cat(file, "\n") sink(file) cat(paste0("% Generated with vein ", packageVersion("vein"), "\n")) cat("% Please add the following required packages to your document preamble:\n") cat("% \\usepackage{booktabs}\n") cat("% \\usepackage{graphicx}\n") cat("\\begin{table}[]\n") cat(paste0("\\caption{", caption, "}\n")) cat(paste0("\\label{", label, "}\n")) cat("\\resizebox{\\textwidth}{!}{%\n") cat("\\begin{tabular}{@{}", order, "@{}}\n") cat("\\toprule\n") nn <- names(df) # top top <- paste0(nn[1:(length(nn) - 1)], rep(" & ", ncol(df) - 1)) cat(top, nn[length(nn)], "\\\\ \\midrule\n") # body for(i in 1:(ncol(df) - 1)){ df[, i] <- paste0(df[, i], " & ") } df[, ncol(df)] <- paste0(df[, ncol(df)], " \\\\ ") df[nrow(df), ncol(df)] <- paste0(df[nrow(df), ncol(df)], " \\bottomrule") names(df) <- NULL for(i in 1:nrow(df)) cat(unlist(df[i, ]), "\n") # bottom cat("\\end{tabular}%\n") cat("}\n") cat("\\end{table}\n") sink() } }
/scratch/gouwar.j/cran-all/cranData/vein/R/to_latex.R
## vein-deprecated.r #' @title Deprecated functions in package \pkg{vein}. #' @description The functions listed below are deprecated and will be defunct in #' the near future. When possible, alternative functions with similar #' functionality are also mentioned. Help pages for deprecated functions are #' available at \code{help("-deprecated")}. #' @name vein-deprecated #' @keywords internal NULL
/scratch/gouwar.j/cran-all/cranData/vein/R/vein-deprecated.R
#' @keywords internal "_PACKAGE"
/scratch/gouwar.j/cran-all/cranData/vein/R/vein-package.R
#' @title Notes with sysinfo #' @description \code{\link{vein_notes}} creates aa text file '.txt' for #' writting technical notes about this emissions inventory #' #' @param file Character; Name of the file. The function will generate a file #' with an extension '.txt'. #' @param title Character; Title of this file. For instance: "Vehicular Emissions #' Inventory of Region XX, Base year XX" #' @param yourname Character; Name of the inventor compiler. #' @param approach Character; vector of notes. #' @param traffic Character; vector of notes. #' @param composition Character; vector of notes. #' @param ef Character; vector of notes. #' @param cold_start Character; vector of notes. #' @param evaporative Character; vector of notes. #' @param standards Character; vector of notes. #' @param mileage Character; vector of notes. #' @param notes Character; vector of notes. #' @return Writes a text file. #' @importFrom utils menu object.size packageVersion sessionInfo #' @export #' @examples \dontrun{ #' #do not run #' a <- "delete" #' f <- vein_notes("notes", file = a) #' file.remove(f) #' } vein_notes <- function (notes, file = "README", yourname = Sys.info()["login"], title = "Notes for this VEIN run", approach = "Top Down", traffic = "Your traffic information", composition = "Your traffic information", ef = "Your information about emission factors", cold_start = "Your information about cold starts", evaporative = "Your information about evaporative emission factors", standards = "Your information about standards", mileage = "Your information about mileage"){ file <- paste0(file, "_", gsub(" ", "_", as.character(Sys.time())),".txt") file <- gsub(":", "", file) if(file.exists(file)){ warning(paste0(file," already exists")) choice <- utils::menu(c("Yes", "No"), title="Do you want Overwrite?") x <- c("Yes", "No")[choice] if(x == "No"){ stop(paste0("NO Overwritting ", file)) }else{ message(paste0("Overwritting ", file)) } } if(missing(title)){ title <- "Vehicular Emissions Inventory on REGIONXX BASE YEAR XXXX" } if(missing(yourname)){ yourname <- Sys.info()[["user"]] } sink(file) cat("========================================\n") # 40 cat(paste0(title, "\n")) cat("========================================\n") # 40 cat(paste0("\nDirectory: ", getwd(), "\n")) cat(paste0("\nLocal Time: ", Sys.time(), "\n")) cat(paste0("Inventory compiler: ", yourname, "\n")) cat("========================================\n") # 40 cat(paste0("\nsysname = ", Sys.info()["sysname"], "\n")) cat(paste0("release = ", Sys.info()["release"], "\n")) cat(paste0("version = ", Sys.info()["version"], "\n")) cat(paste0("nodename = ", Sys.info()["nodename"], "\n")) cat(paste0("machine = ", Sys.info()["machine"], "\n")) cat(paste0("user = ", Sys.info()["user"], "\n")) cat(paste0("R version = ", paste0(version$major, ".", version$minor), "\n")) cat(paste0("nickname = ", version$nickname, "\n")) cat(paste0("Memory used = ", format(sum(sapply(environment(), object.size)), units = " Mb"), "Mb \n")) cat("========================================\n") # 40 cat("\n") cat(paste0("VEIN version = ", packageVersion("vein"), "\n")) cat("========================================\n") # 40 cat("\n") cat("Traffic:\n") for(i in 1:length(traffic)){ cat(paste0(traffic[i], "\n")) } cat("\n") cat("Approach:\n") for(i in 1:length(approach)){ cat(paste0(approach[i], "\n")) } cat("\n") cat("Vehicular composition:\n") for(i in 1:length(composition)){ cat(paste0(composition[i], "\n")) } cat("\n") cat("Emission Factors:\n") for(i in 1:length(ef)){ cat(paste0(ef[i], "\n")) } cat("\n") cat("Cold starts:\n") for(i in 1:length(cold_start)){ cat(paste0(cold_start[i], "\n")) } cat("\n") cat("Evaporative:\n") for(i in 1:length(evaporative)){ cat(paste0(evaporative[i], "\n")) } cat("\n") cat("Traffic standards:\n") for(i in 1:length(standards)){ cat(paste0(standards[i], "\n")) } cat("\n") cat("Traffic mileage:\n") for(i in 1:length(mileage)){ cat(paste0(mileage[i], "\n")) } if(!missing(notes)){ cat("\n") cat("Notes:\n") for(i in 1:length(notes)){ cat(paste0(notes[i], "\n")) } } cat("========================================\n") # 40 cat("\n") cat("Session Info:\n") print(utils::sessionInfo()) cat("\n") cat("========================================\n") # 40 cat("\n\n\nThanks for using VEIN\n") sink() # message("File at: ") return(file) }
/scratch/gouwar.j/cran-all/cranData/vein/R/vein_notes.R
#' Estimation of VKM #' #' @description \code{vkm} consists in the product of the number of vehicles and #' the distance driven by these vehicles in km. This function reads hourly #' vehicles and then extrapolates the vehicles #' #' @param veh Numeric vector with number of vehicles per street #' @param lkm Length of each link (km) #' @param profile Numerical or dataframe with nrows equal to 24 and ncol 7 day of the week #' @param hour Number of considered hours in estimation #' @param day Number of considered days in estimation #' @param array When FALSE produces a dataframe of the estimation. When TRUE expects a #' profile as a dataframe producing an array with dimensions (streets x hours x days) #' @param as_df Logical; when TRUE transform returning array in data.frame (streets x hour*days) #' @return emission estimation of vkm #' @export #' @examples \dontrun{ #' # Do not run #' pc <- lkm <- abs(rnorm(10,1,1))*100 #' pro <- matrix(abs(rnorm(24*7,0.5,1)), ncol=7, nrow=24) #' vkms <- vkm(veh = pc, lkm = lkm, profile = pro) #' class(vkms) #' dim(vkms) #' vkms2 <- vkm(veh = pc, lkm = lkm, profile = pro, as_df = FALSE) #' class(vkms2) #' dim(vkms2) #' } vkm <- function (veh, lkm, profile, hour = nrow(profile), day = ncol(profile), array = TRUE, as_df = TRUE) { if(!missing(profile) & is.vector(profile)){ profile <- matrix(profile, ncol = 1) } veh <- as.numeric(veh) lkm <- as.numeric(lkm) if(array == F){ lista <- lapply(1:day,function(j){ lapply(1:hour,function(i){ veh*profile[i,j]*lkm }) }) return(lista) } else { d <- simplify2array(lapply(1:day, function(j) { simplify2array(lapply(1:hour, function(i) { veh* profile[i, j]*lkm })) })) if(as_df == FALSE){ return(d) } else { df <- as.data.frame(matrix(data = as.vector(d), nrow = length(d[,1, 1]), ncol = length(d[1, , ]))) names(df) <- paste0("h",1:length(df)) return(df) } } }
/scratch/gouwar.j/cran-all/cranData/vein/R/vkm.R
#' Transform data.frame from wide to long format #' #' @description \code{\link{wide_to_long}} transform data.frame from wide to #' long format #' #' @param df data.frame with three column. #' @param column_with_data Character column with data #' @param column_fixed Character, column that will remain fixed #' @param geometry To return a sf #' @family helpers #' @return long data.frame. #' @importFrom sf st_sf #' @seealso \code{\link{emis_hot_td}} \code{\link{emis_cold_td}} \code{\link{long_to_wide}} #' @export #' @examples \dontrun{ #' data(net) #' net <- sf::st_set_geometry(net, NULL) #' df <- wide_to_long(df = net) #' head(df) #' } wide_to_long <- function(df, column_with_data = names(df), column_fixed, geometry) { # message("This function will be deprecated, use data.table::melt.data.table") a <- as.data.frame(df) if(!missing(column_fixed)){ df2 <- data.frame(V1 = unlist(a[, column_with_data])) df2$V2 <- unlist(a[, column_fixed]) df2$V3 <- rep(column_with_data, each = nrow(a)) } else { df2 <- data.frame(V1 = unlist(a[, column_with_data])) df2$V2 <- rep(column_with_data, each = nrow(a)) } if(missing(geometry)) { return(df2) } else { df2 <- sf::st_sf(df2, geometry = geometry) return(df2) } }
/scratch/gouwar.j/cran-all/cranData/vein/R/wide_to_long.R
#' @importFrom units install_unit remove_unit .onLoad <- function(libname, pkg) { # Use GForce Optimisations in data.table operations # details > https://jangorecki.gitlab.io/data.cube/library/data.table/html/datatable-optimize.html options(datatable.optimize = Inf) # nocov units::install_unit("veh") #nocov } # .onUnload <- function(libpath){ units::remove_unit("veh") #nocov # }
/scratch/gouwar.j/cran-all/cranData/vein/R/zzz.R
library(vein) library(sf) library(sp) library(units) library(ggplot2) #library(RColorBrewer) # library(DiagrammeR) ## ---- fig.width=8, fig.height=6------------------------------------------ # 1 #### data(net) ; net <- as_Spatial(net) class(net$ldv) <- "numeric" spplot(net, "ldv", scales=list(Draw=T),cuts=12, colorkey = list(space = "bottom", height = 1), col.regions = rev(bpy.colors(13))) # 2 #### 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") pc2 <- age_ldv(x = net$ldv,name = "PC",agemax = 41) pc3 <- age_ldv(x = net$ldv,name = "PC",b=-0.14,agemax = 41) df <- data.frame(pc = c(colSums(pc1),colSums(pc2),colSums(pc3)), Age = c(rep(15.17,41),rep(11.09,41),rep(15.53,41)), x = rep(1:41,3)) ggplot(df, aes(x = x, y = pc, colour = as.factor(Age))) + geom_point(size=3) + geom_line() + theme_bw() + labs(x="Age", y="Distribution") + theme(legend.position = c(0.8,0.8)) + guides(colour = guide_legend(keywidth = 2, keyheight = 2))+ scale_color_discrete(name = "Average age") # 3 #### data("profiles") pc_profile <- profiles$PC_JUNE_2012 df2 <- data.frame(TF = as.numeric(unlist(pc_profile)), Hour = rep(1:24,7), Day = c(rep("Monday",24), rep("Tuesday",24), rep("Wednesday",24), rep("Thursday",24), rep("Friday",24), rep("Saturday",24), rep("Sunday",24))) df2$Day <- factor(df2$Day, levels = c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")) ggplot(df2, aes(x = Hour, y = TF, colour = Day, shape = Day)) + geom_point(size = 4) + geom_line() + theme_bw() + labs(x = "Hours", y = "TF") + theme(legend.position = c(0.1,0.7))+ guides(colour = guide_legend(keywidth = 2, keyheight = 2)) # 4 #### # 5 #### data(net) net <- as_Spatial(net) data("profiles") pc_profile <- profiles$PC_JUNE_2012 pcw <- temp_fact(net$ldv+net$hdv, pc_profile) df <- netspeed(pcw, net$ps, net$ffs, net$capacity, net$lkm, alpha = 1) net@data$nts <- as.factor( ifelse( net@data$tstreet==1, "Other", ifelse( net@data$tstreet==2, "Arterial", ifelse( net@data$tstreet==3, "Arterial", ifelse( net@data$tstreet==4, "Arterial", ifelse( net@data$tstreet==5, "Collect", ifelse( net@data$tstreet==6, "Collect", ifelse( net@data$tstreet==7, "Local", ifelse( net@data$tstreet==37, "Local", ifelse( net@data$tstreet==41, "Motorway", ifelse( net@data$tstreet==42, "Motorway", "Other"))))))))))) net@data <- cbind(net@data,df) spplot(net, c("S8","S23"), scales=list(Draw=T), col.regions = rev(bpy.colors(16))) speed <- netspeed(pcw, net$ps, net$ffs, net$capacity, net$lkm, alpha = 1) # 6 #### df2 <- aggregate(net@data[,11:178], by=list(net$nts), mean ) df3 <- as.data.frame(t(df2[,2:169])) names(df3) <- as.character(t(df2[,1])) df4 <- data.frame(speed =c(df3$Arterial,df3$Collect,df3$Local,df3$Motorway), Street = c(rep("Arterial",168), rep("Collect",168), rep("Local",168), rep("Motorway",168)), Hour = rep(1:168,4)) ggplot(df4, aes(x=Hour, y=speed, colour=Street)) + geom_point(size=3) + geom_line() +theme_bw()+ labs(x=NULL, y="Spped (km/h)") + guides(colour = guide_legend(keywidth = 3))+ theme(legend.position = "bottom", legend.key.width = unit(2,units="cm")) # 7 #### fe2015 <- ef_cetesb(p = c("CO"), veh = "PC_G", full = T, agemax = 36) names(fe2015)[ncol(fe2015)] <- "PC_G" names(fe2015)[5] <- "Euro_LDV" data("profiles") pc_profile <- profiles$PC_JUNE_2012 data(fkm) pckm <- fkm[[1]](1:24) pckma <- cumsum(pckm) kma <- units::set_units(pckma[1:11], km) kmb <- units::set_units(pckma[12:24], km) cod1 <- emis_det(po = "CO", cc = 1000, eu = "III", km = kma) cod2 <- emis_det(po = "CO", cc = 1000, eu = "I", km = kmb) co1 <- fe2015[fe2015$Pollutant=="CO", ] cod <- c(co1$PC_G[1:24] * c(cod1,cod2), co1$PC_G[25:nrow(co1)]) # 8 #### fe2015 <- ef_cetesb(p = c("CO"), veh = "PC_G", full = T, agemax = 36) names(fe2015)[ncol(fe2015)] <- "PC_G" names(fe2015)[5] <- "Euro_LDV" data(fkm) pckm <- fkm[[1]](1:24); pckma <- cumsum(pckm) cod1 <- emis_det(po = "CO", cc = 1000, eu = "III", km = kma) cod2 <- emis_det(po = "CO", cc = 1000, eu = "I", km = kmb) #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(dfcol = cod, v = "PC", cc = "<=1400", f = "G",p = "CO", eu=co1$Euro_LDV) # lef <- c(lef,lef[length(lef)],lef[length(lef)],lef[length(lef)], # lef[length(lef)],lef[length(lef)]) # 9 #### data("profiles") pc_profile <- profiles$PC_JUNE_2012 data(net) ; net <- as_Spatial(net) E_CO <- emis(veh = pc1,lkm = net$lkm, ef = lef, speed = speed, profile = pc_profile) E_CO_DF <- emis_post(arra = E_CO, veh = "PC", size = "1400", fuel = "Gasoline", pollutant = "CO", by = "veh") head(E_CO_DF) # take care of units df <- aggregate(E_CO_DF$g, by=list(E_CO_DF$hour), sum) df$Day <- c( rep("Monday", 24), rep("Tuesday", 24), rep("Wednesday", 24), rep("Thursday", 24), rep("Friday", 24), rep("Saturday", 24), rep("Sunday", 24)) names(df) <- c("Hour", "g_CO", "Day" ) df$day <- factor(df$Day, levels = c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")) ggplot(df, aes(x=Hour, y=unclass(g_CO), colour = day)) + geom_line() + geom_point(size = 4) + theme_bw() + theme(legend.key.size = unit(0.6,"cm")) + labs(x="Hour", y=expression(g%.%h^-1)) df3 <- aggregate(unclass(E_CO_DF$g), by=list(E_CO_DF$age), sum) names(df3) <- c("Age", "t_CO") df3$CO <- df3$t_CO*52/1000000 ggplot(df3, aes(x=Age, y=CO, fill=unclass(CO))) + geom_bar(stat='identity') + scale_fill_continuous(low="pink", high="black") + theme_bw() + geom_line(size=0.3) + theme(legend.key.size=unit(0.8,"cm")) + labs(x="Age", y=expression(t%.%y^-1)) # 10 #### sldv <- colSums(pc1) sum(sldv[20:36]) sum(sldv[20:36]) / sum(sldv) sum(sldv) df3 <- aggregate(unclass(E_CO_DF$g), by=list(E_CO_DF$age), sum) names(df3) <- c("age", "t_CO") head(df3) df3$t_CO <- df3$t_CO*52/1000000 sum(df3$t_CO) sum(df3[20:36,]$t_CO)/ sum(df3$t_CO) dfco <- data.frame(co = c(co1$PC_G, rep(co1$PC_G[length(co1$PC_G)],5), c(cod,rep(cod[length(cod)],5))), EF = c(rep("0 km", 41),rep("Deteriorated", 41)), Age = rep(1:41,2)) ggplot(dfco, aes(x = Age, y = co, colour = EF, shape = EF)) + geom_point(size = 4) + geom_line()+theme_bw() + labs(x="Age", y="CO (g/km)") + theme(legend.position = c(0.2,0.8)) + guides(colour = guide_legend(keywidth = 2, keyheight = 2))+ scale_color_discrete(name = "EF") # 11 #### E_CO_STREETS_n <- emis_post(arra = E_CO, pollutant = "CO", by = "streets_narrow") E_CO_STREETS <- emis_post(arra = E_CO, pollutant = "CO", by = "streets_wide") data(net) ; net <- as_Spatial(net) # spplot does not plot 'units' therefore, columns needs to be converted to #numeric for (i in 1:ncol(E_CO_STREETS)) { E_CO_STREETS[,i] <- as.numeric(E_CO_STREETS[,i]) } net@data <- cbind(net@data, E_CO_STREETS) g <- make_grid(net, 1/102.47/2, 1/102.47/2) gg <- as(g, "Spatial") spplot(net, "V138", scales=list(Draw=T), cuts = 15, colorkey = list(space = "bottom", height = 1), col.regions = rev(bpy.colors(16)), sp.layout = list("sp.polygons", gg, pch = 13, cex = 2)) net@data <- net@data[,- c(1:9)] net <- st_as_sf(net) E_CO_g <- emis_grid(spobj = net, g = g, sr = 31983, type = "lines") E_CO_g <- remove_units(E_CO_g) E_CO_g <- as_Spatial(E_CO_g) spplot(E_CO_g, "V138", scales=list(Draw=T),cuts=8, colorkey = list(space = "bottom", height = 1), col.regions = rev(bpy.colors(9)), sp.layout = list("sp.lines", net, pch = 16, cex = 2, col = "black")) # 12 #### E_CO_g$id <- NULL E_CO_g <- st_as_sf(E_CO_g) ldf <- list("co" = E_CO_g) df_wrf <- eixport::to_as4wrf(ldf,nr=1,dmyhm = "04-08-2014 00:00", tz = "America/Sao_Paulo", islist=T)
/scratch/gouwar.j/cran-all/cranData/vein/demo/VEIN.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----------------------------------------------------------------------------- library(vein) ## ----------------------------------------------------------------------------- ?get_project ## ---- eval = F---------------------------------------------------------------- # get_project(directory = "awesome_city") # system("tree awesome_city") # ## ---- eval = F---------------------------------------------------------------- # install.packages(c("ggplot2", "readxl", "eixport"))
/scratch/gouwar.j/cran-all/cranData/vein/inst/doc/basics.R
--- title: "Basics for running VEIN" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Basics for running VEIN} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` This vignette shows how to install and run VEIN for people who **do not know R** ## Install VEIN You can install VEIN with - GitLab: `remotes::install_gitlab("ibarraespinosa/vein")` - GitHub: `remotes::install_github("atmoschem/vein")` - or CRAN: `install.packages("vein")` GitHub and GitLab are more updated Then, use vein ```{r} library(vein) ``` ## Download a project Check the documentation of get_project ```{r} ?get_project ``` or [here](https://atmoschem.github.io/vein/reference/get_project.html) Choose a name, for instance, "awesome_city" ```{r, eval = F} get_project(directory = "awesome_city") system("tree awesome_city") ``` The structure is: ``` awesome_city ├── config │ ├── clean.R │ ├── config.R │ ├── inventory.xlsx │ └── packages.R ├── main.R ├── main.Rproj ├── network │ ├── net.gpkg │ └── net.rds ├── scripts │ ├── evaporatives.R │ ├── exhaust.R │ ├── fuel_eval.R │ ├── net.R │ ├── pavedroads.R │ ├── plots.R │ ├── post.R │ ├── traffic.R │ └── wrf.R └── wrf └── wrfinput_d02 ``` You have to open the file `main.Rproj` with Rstudio and then open and run `main.R` To run `main.R` you will need these extra packages: - ggplot2 - readxl - eixport (If you plan to generate WRF Chem emissions file) If you do not have them already, you can install: ```{r, eval = F} install.packages(c("ggplot2", "readxl", "eixport")) ``` ## Too complicated? Watch a YouTube video in English: <iframe width="560" height="315" src="https://www.youtube.com/embed/tHSWIjg26vg" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> in Portuguese: <iframe width="560" height="315" src="https://www.youtube.com/embed/6-07Y0Eimng" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> [here](https://youtu.be/6-07Y0Eimng)
/scratch/gouwar.j/cran-all/cranData/vein/inst/doc/basics.Rmd
--- title: "Basics for running VEIN" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Basics for running VEIN} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` This vignette shows how to install and run VEIN for people who **do not know R** ## Install VEIN You can install VEIN with - GitLab: `remotes::install_gitlab("ibarraespinosa/vein")` - GitHub: `remotes::install_github("atmoschem/vein")` - or CRAN: `install.packages("vein")` GitHub and GitLab are more updated Then, use vein ```{r} library(vein) ``` ## Download a project Check the documentation of get_project ```{r} ?get_project ``` or [here](https://atmoschem.github.io/vein/reference/get_project.html) Choose a name, for instance, "awesome_city" ```{r, eval = F} get_project(directory = "awesome_city") system("tree awesome_city") ``` The structure is: ``` awesome_city ├── config │ ├── clean.R │ ├── config.R │ ├── inventory.xlsx │ └── packages.R ├── main.R ├── main.Rproj ├── network │ ├── net.gpkg │ └── net.rds ├── scripts │ ├── evaporatives.R │ ├── exhaust.R │ ├── fuel_eval.R │ ├── net.R │ ├── pavedroads.R │ ├── plots.R │ ├── post.R │ ├── traffic.R │ └── wrf.R └── wrf └── wrfinput_d02 ``` You have to open the file `main.Rproj` with Rstudio and then open and run `main.R` To run `main.R` you will need these extra packages: - ggplot2 - readxl - eixport (If you plan to generate WRF Chem emissions file) If you do not have them already, you can install: ```{r, eval = F} install.packages(c("ggplot2", "readxl", "eixport")) ``` ## Too complicated? Watch a YouTube video in English: <iframe width="560" height="315" src="https://www.youtube.com/embed/tHSWIjg26vg" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> in Portuguese: <iframe width="560" height="315" src="https://www.youtube.com/embed/6-07Y0Eimng" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> [here](https://youtu.be/6-07Y0Eimng)
/scratch/gouwar.j/cran-all/cranData/vein/vignettes/basics.Rmd
#' Create a community matrix of taxon abundances #' #' Creates a community matrix of taxon abundances, with samples as rows and species as columns, from a data frame. #' #' @param Data A data.frame of taxonomic occurrences. Must have at least two columns. One column representing the samples, and one column representing the taxa. #' @param Rows A characer string #' @param Columns A character string #' #' @details Note that older versions of this function automatically checked for and removed hanging factors. However, this is something that should really be dictated by the user, and that step is no longer a part of the function. This is unlikely to introduce any breaking changes in older scripts, but we note it here for documentation purposes.. #' #' @return A numeric matrix of taxon abundances. Samples as the rownames and species as the column names. #' #' @author Andrew A. Zaffos #' #' @examples #' #' # Download a test dataset of pleistocene bivalves. #' # DataPBDB<-downloadPBDB(Taxa="Bivalvia", StartInterval="Pleistocene", StopInterval="Pleistocene") #' #' # Clean the genus column #' # DataPBDB<-cleanTaxonomy(DataPBDB,"genus") #' #' # Create a community matrix of genera by tectonic plate id# #' # CommunityMatrix<-abundanceMatrix(Data=DataPBDB, Rows="geoplate", Columns="genus") #' #' @rdname abundanceMatrix #' @export abundanceMatrix<-function(Data,Rows="geoplate",Columns="genus") { # This function previously removed hanging factors, but that is no longer included SamplesAbundances<-by(Data,Data[,Rows],function(x) table(x[,Columns])) FinalMatrix<-sapply(SamplesAbundances,data.matrix) rownames(FinalMatrix)<-sort(unique((Data[,Columns]))) return(t(FinalMatrix)) }
/scratch/gouwar.j/cran-all/cranData/velociraptr/R/abundanceMatrix.R
#' Additive Diversity Partitioning functions #' #' Functions for calculating alpha, beta, and gamma richness of a community matrix under the Additive Diversity partitioning paradigm of R. Lande. #' #' @param CommunityMatrix a matrix #' #' @aliases taxonAlpha,meanAlpha,taxonBeta,sampleBeta,totalGamma #' #' @details Takes a community matrix (see \code{presenceMatrix} or \code{abundanceMatrix}) and returns the either the alpha, beta, or gamma richness of a community matrix. #' #' These functions were originally presented in Holland, SM (2010) "Additive diversity partitioning in palaeobiology: revisiting Sepkoski’s question" \emph{Paleontology} 53:1237-1254. #' #' \itemize{ ##' \item{\code{taxonAlpha(CommunityMatrix)}} {Calculates the contribution to alpha diversity of each taxon.} ##' \item{\code{meanAlpha(CommunityMatrix)}} {Calculates the average alpha diversity of all samples.} ##' ##' \item{\code{taxonBeta(CommunityMatrix)}} {Calculates the contribution to beta diversity of each taxon.} ##' \item{\code{sampleBeta(CommunityMatrix)}} {Calculates the contribution to beta diversity of each sample.} ##' \item{\code{totalBeta(CommunityMatrix)}} {Calculates the total beta diversity.} ##' ##' \item{\code{totalGamma(CommunityMatrix)}} {Calculates the richness of all samples in the community matrix.} ##' } #' #' @return A vector of the alpha, beta, or gamma richness of a taxon, sample, or entire community matrix. #' #' @author Andrew A. Zaffos #' #' @examples #' # Download a test dataset of pleistocene bivalves. #' # DataPBDB<-downloadPBDB(Taxa="Bivalvia",StartInterval="Pleistocene",StopInterval="Pleistocene") #' #' # Create a community matrix with tectonic plates as "samples" #' # CommunityMatrix<-abundanceMatrix(DataPBDB,"geoplate") #' #' # Calculate the average richness of all samples in a community. #' # meanAlpha(CommunityMatrix) #' #' # The beta diversity of all samples in a community. #' # totalBeta(CommunityMatrix) #' #' # This is, by definition, equivalent to the gamma diversity - mean alpha diversity. #' # totalBeta(CommunityMatrix)==(totalGamma(CommunityMatrix)-meanAlpha(CommunityMatrix)) #' #' @rdname additiveBeta #' @export # returns vector of each taxon’s contribution to alpha diversity taxonAlpha <- function(CommunityMatrix) { CommunityMatrix[CommunityMatrix>0]<-1 Nj <- apply(CommunityMatrix, 2, sum) Samples <- nrow(CommunityMatrix) Alphaj <- Nj/Samples names(Alphaj) <- colnames(CommunityMatrix) return(Alphaj) } #' @rdname additiveBeta #' @export # returns mean alpha diversity of samples meanAlpha <- function (CommunityMatrix) { return(sum(taxonAlpha(CommunityMatrix))) } #' @rdname additiveBeta #' @export # returns vector of each taxon’s contribution to beta diversity taxonBeta <- function(CommunityMatrix) { CommunityMatrix[CommunityMatrix>0]<-1 Nj <- apply(CommunityMatrix, 2, sum) Samples <- nrow(CommunityMatrix) Betaj <- (Samples - Nj) / Samples names(Betaj) <- colnames(CommunityMatrix) return(Betaj) } #' @rdname additiveBeta #' @export # returns vector of each sample’s contribution to beta diversity sampleBeta <- function(CommunityMatrix) { Betaj <- taxonBeta(CommunityMatrix) Nj <- apply(CommunityMatrix, 2, sum) NSamples <- nrow(CommunityMatrix) Betai <- vector(mode="numeric", length=NSamples) for (i in 1:NSamples) { Betai[i] <- sum(Betaj / Nj * CommunityMatrix[i, ]) } names(Betai) <- rownames(CommunityMatrix) return(Betai) } #' @rdname additiveBeta #' @export # returns beta diversity among samples totalBeta <- function (CommunityMatrix) { return(sum(taxonBeta(CommunityMatrix))) } #' @rdname additiveBeta #' @export # returns gamma diversity of all samples combined totalGamma <- function(CommunityMatrix) { return(ncol(CommunityMatrix)) }
/scratch/gouwar.j/cran-all/cranData/velociraptr/R/additiveBeta.R
#' Find the age range for each taxon in a dataframe #' #' Find the age range (first occurrence and last occurrence) for each taxon in a PBDB dataset. Can be run for any level of the taxonomic hierarchy (e.g., family, genus). #' #' @param Data A data frame downloaded from the paleobiology database API. #' @param Taxonomy A characer string identifying the desired level of the taxonomic hierarchy. #' #' @details Returns a data frame of that states gives the time of origination and extinction for each taxon as numeric values. Note that older versions of this function automatically dropped hanging factors and NA's, but that cleaning step should ideally be dictated by the user up-front. So that functionality has been dropped. This may introduce breaking chanes in legacy scripts, but is easily fixed by standard data cleaning steps. #' #' @return A numeric matrix of first and last ages for each taxon, with tax as rownames. #' #' @author Andrew A. Zaffos #' #' @examples #' #' # Download a test dataset of Cenozoic bivalves. #' # DataPBDB<-downloadPBDB(Taxa="Bivalvia",StartInterval="Cenozoic",StopInterval="Cenozoic") #' #' # Find the first occurrence and last occurrence for all Cenozoic bivalves in DataPBDB #' # AgeRanges<-ageRanges(DataPBDB,"genus") #' #' @rdname ageRanges #' @export # Find the min and max age range of a taxonomic ranking - e.g., genus. ageRanges<-function(Data,Taxonomy="genus") { PBDBEarly<-tapply(Data[,"max_ma"],Data[,Taxonomy],max) # Calculate max age PBDBLate<-tapply(Data[,"min_ma"],Data[,Taxonomy],min) # Calculate min age AgesPBDB<-cbind(PBDBEarly,PBDBLate) # Bind ages colnames(AgesPBDB)<-c("EarlyAge","LateAge") return(data.matrix(AgesPBDB)) }
/scratch/gouwar.j/cran-all/cranData/velociraptr/R/ageRanges.R
#' Clean taxonomic names #' #' Removes NAs and subgenera from the genus column. #' #' @param Data A data frame of taxonomic ocurrences downloaded from the paleobiology database API. #' @param Taxonomy A character string #' #' @details Will remove NA's and subgenera from the genus column of a PBDB dataset. It can also be used on other datasets of similar structure to convert species names to genus, or remove NAs. #' #' @return Will return a data frame identical to the original, but with the genus column cleaned. #' #' @author Andrew A. Zaffos #' #' @examples #' #' # Download a test dataset of Cenozoic bivalves. #' # DataPBDB<-downloadPBDB(Taxa="Bivalvia",StartInterval="Cenozoic",StopInterval="Cenozoic") #' #' # Clean up the genus column. #' # CleanedPBDB<-cleanTaxonomy(DataPBDB,"genus") #' #' @rdname cleanTaxonomy #' @export # Find the min and max age range of a taxonomic ranking - e.g., genus. cleanTaxonomy<-function(Data,Taxonomy="genus") { Data<-subset(Data,Data[,Taxonomy]!="") # Remove NAs Data<-subset(Data,is.na(Data[,Taxonomy])!=TRUE) # Remove NAs SpaceSeparated<-sapply(as.character(Data[,Taxonomy]),strsplit," ") Data[,Taxonomy]<-sapply(SpaceSeparated,function(S) S[1]) return(Data) }
/scratch/gouwar.j/cran-all/cranData/velociraptr/R/cleanTaxonomy.R
#' Constrain a dataset to only occurrences within a certain age-range #' #' Assign fossil occurrences to different intervals within a geologic timescale, then remove occurrences that are not temporally constrained to a single interval within that timescale. #' #' @param Data A data frame #' @param Timescale A data frame #' #' @aliases constrainAges,multiplyAges #' #' @details Cull a paleobiology database data frame to only occurrences temporally constrained to be within a certain level of the geologic timescale (e.g., period, epoch). The geologic timescale should come from the Macrostrat database, but custom time-scales can be used if structured in the same way. See \code{downloadTime} for how to download a timescale. #' #' @author Andrew A. Zaffos #' #' @return A data frame #' #' @examples #' #' # Download a test dataset of Cenozoic bivalves. #' # DataPBDB<-downloadPBDB(Taxa="Bivalvia",StartInterval="Cenozoic",StopInterval="Cenozoic") #' #' # Download the international epochs timescale from macrostrat.org #' # Epochs<-downloadTime("international epochs") #' #' # Find only occurrences that are temporally constrained to a single international epoch #' # ConstrainedPBDB<-constrainAges(DataPBDB,Timescale=Epochs) #' #' # Create mutliple instances of a single occurrence for each epoch it occurs in #' # MultipliedPBDB<-multiplyAges(DataPBDB,Timescale=Epochs) #' #' @rdname constrainAges #' @export constrainAges<-function(Data,Timescale) { Data[,"early_interval"]<-as.character(Data[,"early_interval"]) Data[,"late_interval"]<-as.character(Data[,"late_interval"]) for (i in 1:nrow(Timescale)) { EarlyPos<-which(Data[,"max_ma"]>Timescale[i,"t_age"] & Data[,"max_ma"]<=Timescale[i,"b_age"]) Data[EarlyPos,"early_interval"]<-as.character(Timescale[i,"name"]) LatePos<-which(Data[,"min_ma"]>=Timescale[i,"t_age"] & Data[,"min_ma"]<Timescale[i,"b_age"]) Data[LatePos,"late_interval"]<-as.character(Timescale[i,"name"]) } Data<-Data[Data[,"early_interval"]==Data[,"late_interval"],] # Remove taxa that range through return(Data) } #' @rdname constrainAges #' @export # A variant of constrain ages that allows for multiple ages # Assign fossil occurrences to multiple ages multiplyAges<-function(Data,Timescale) { Data[,"early_interval"]<-as.character(Data[,"early_interval"]) Data[,"late_interval"]<-as.character(Data[,"late_interval"]) for (i in 1:nrow(Timescale)) { EarlyPos<-which(Data[,"max_ma"]>Timescale[i,"t_age"] & Data[,"max_ma"]<=Timescale[i,"b_age"]) Data[EarlyPos,"early_interval"]<-as.character(Timescale[i,"name"]) LatePos<-which(Data[,"min_ma"]>=Timescale[i,"t_age"] & Data[,"min_ma"]<Timescale[i,"b_age"]) Data[LatePos,"late_interval"]<-as.character(Timescale[i,"name"]) } ConstrainedPBDB<-Data[Data[,"early_interval"]==Data[,"late_interval"],] # Find occurrences of single epoch UnconstrainedPBDB<-Data[Data[,"early_interval"]!=Data[,"late_interval"],] # Find occurrence not of a single epoch DuplicatePBDB<-UnconstrainedPBDB DuplicatePBDB[,"early_interval"]<-DuplicatePBDB[,"late_interval"] return(rbind(ConstrainedPBDB,UnconstrainedPBDB,DuplicatePBDB)) }
/scratch/gouwar.j/cran-all/cranData/velociraptr/R/constrainAges.R
#' Cull rare taxa and depauperate samples #' #' Functions for recursively culling community matrices of rare taxa and depauperate samples. #' #' @param CommunityMatrix a matrix #' @param Rarity a whole number #' @param Richness a whole number #' @param Silent logical #' #' @aliases cullMatrix,errorMatrix,culltaxa,cullSamples,occurrencesFlag,diversityFlag,softCull,softTaxa,softSamples #' #' @details Takes a community matrix (see \code{presenceMatrix} or \code{abundanceMatrix}) and removes all samples with fewer than a certain number of taxa and all taxa that occur below a certain threshold of samples. The function operates recursively, and will check to see if removing a rare taxon drops a sampe below the input minimum richness and vice-versa. This means that it is possible to eliminate all taxa and samples if the rarity and richness minimums are too high. If the \code{Silent} argument is set to \code{FALSE} the function will throw an error and print a warning if no taxa or samples are left after culling. If \code{Silent} is set to \code{TRUE} the function will simply return \code{NULL}. The latter case is useful if many matrices are being culled as a part of a loop, and you do not want to break the loop with an error. #' #' These functions originally appeared in the R script appendix of Holland, S.M. and A. Zaffos (2011) "Niche conservatism along an onshore-offshore gradient". \emph{Paleobiology} 37:270-286. #' #' @return A community matrix with depauperate samples and rare taxa removed. #' #' @author Andrew A. Zaffos #' #' @examples #' # Download a test dataset of pleistocene bivalves. #' # DataPBDB<-downloadPBDB(Taxa="Bivalvia",StartInterval="Pleistocene",StopInterval="Pleistocene") #' #' # Create a community matrix with tectonic plates as "samples". #' # CommunityMatrix<-abundanceMatrix(DataPBDB,"geoplate") #' #' # Remove taxa that occur in less than 5 samples and samples with fewer than 25 taxa. #' # cullMatrix(CommunityMatrix,Rarity=5,Richness=25,Silent=FALSE) #' #' @rdname cullMatrix #' @export # A macro for culling community matrices of depauperate samples and rare taxa cullMatrix <- function(CommunityMatrix,Rarity=2,Richness=2,Silent=FALSE) { if (Silent==TRUE) { FinalMatrix<-softCull(CommunityMatrix,MinOccurrences=Rarity,MinRichness=Richness) } else { FinalMatrix<-errorMatrix(CommunityMatrix,MinOccurrences=Rarity,MinRichness=Richness) } return(FinalMatrix) } # Steve Holland's Culling Functions errorMatrix <- function(CommunityMatrix, MinOccurrences=2, MinRichness=2) { FinalMatrix <- CommunityMatrix while (diversityFlag(FinalMatrix, MinRichness) | occurrencesFlag(FinalMatrix, MinOccurrences)) { FinalMatrix <- cullTaxa(FinalMatrix, MinOccurrences) FinalMatrix <- cullSamples(FinalMatrix, MinRichness) } return(FinalMatrix) } # Dependency of cullMatrix() cullTaxa <- function(CommunityMatrix, MinOccurrences) { PA <- CommunityMatrix PA[PA>0] <- 1 Occurrences <- apply(PA, MARGIN=2, FUN=sum) AboveMinimum <- Occurrences >= MinOccurrences FinalMatrix <- CommunityMatrix[ ,AboveMinimum] if (length(FinalMatrix)==0) {print("no taxa left!")} return(FinalMatrix) } # Dependency of cullMatrix() cullSamples <- function(CommunityMatrix, MinRichness) { PA <- CommunityMatrix PA[PA>0] <- 1 Richness <- apply(PA, MARGIN=1, FUN=sum) AboveMinimum <- Richness >= MinRichness FinalMatrix <- CommunityMatrix[AboveMinimum, ] if (length(FinalMatrix[,1])==0) {print("no samples left!")} return(FinalMatrix) } # Dependency of cullMatrix() occurrencesFlag <- function(CommunityMatrix, MinOccurrences) { PA <- CommunityMatrix PA[PA>0] <- 1 Occurrences <- apply(PA, MARGIN=2, FUN=sum) if (min(Occurrences) < MinOccurrences) { Flag <- 1 } else { Flag <- 0 } return(Flag) } # Dependency of cullMatrix() diversityFlag <- function(CommunityMatrix, MinRichness) { PA <- CommunityMatrix PA[PA>0] <- 1 Richness <- apply(PA, MARGIN=1, FUN=sum) if (min(Richness) < MinRichness) { Flag <- 1 } else { Flag <- 0 } return(Flag) } # Alternative to cullMatrix( ) that does not thrown an error, but returns a single NA softCull <- function(CommunityMatrix, MinOccurrences=2, MinRichness=2) { NewMatrix <- CommunityMatrix while (diversityFlag(NewMatrix, MinRichness) | occurrencesFlag(NewMatrix, MinOccurrences)) { NewMatrix <- softTaxa(NewMatrix, MinOccurrences) if (length(NewMatrix)==1) { return(NA) } NewMatrix <- softSamples(NewMatrix, MinRichness) if (length(NewMatrix)==1) { return(NA) } } return(NewMatrix) } # Dependency of softCull() softTaxa <- function(CommunityMatrix, MinOccurrences) { PA <- CommunityMatrix PA[PA>0] <- 1 Occurrences <- apply(PA, MARGIN=2, FUN=sum) AboveMinimum <- Occurrences >= MinOccurrences FinalMatrix <- CommunityMatrix[ ,AboveMinimum] if (length(FinalMatrix)==0) { FinalMatrix<-NA; return(NA) } return(FinalMatrix) } # Dependency of softCull() softSamples <- function(CommunityMatrix, MinRichness) { PA <- CommunityMatrix PA[PA>0] <- 1 Richness <- apply(PA, MARGIN=1, FUN=sum) AboveMinimum <- Richness >= MinRichness FinalMatrix <- CommunityMatrix[AboveMinimum, ] if (length(FinalMatrix[,1])==0) { FinalMatrix<-NA; return(NA) } return(FinalMatrix) }
/scratch/gouwar.j/cran-all/cranData/velociraptr/R/cullMatrix.R
#' Download Occurrences from the Paleobiology Database #' #' Downloads a data frame of Paleobiology Database fossil occurrences. #' #' @param Taxa a character vector #' @param StartInterval a character vector #' @param StopInterval a character vector #' #' @details Downloads a data frame of Paleobiology Database fossil occurrences matching certain taxonomic groups and age range. This is simply a convenience function for rapid data download, and only returns the most generically useful fields. Go directly to the Paleobiology Database to make more complex searches or access additional fields. This function makes use of the RCurl package. #' #' \itemize{ ##' \item{ocurrence_no:} {The Paleobiology Database occurrence number.} ##' \item{collection_no:} {The Paleobiology Database collection number.} ##' \item{reference_no:} {The Paleobiology Database reference number.} ##' \item{Classifications:} {The stated Linnean classification of the occurence from phylum through genus. See \code{cleanTaxonomy} for how to simplify these fields.} ##' \item{accepted_name:} {The highest resolution taxonomic name assigned to the occurrence.} ##' \item{Geologic Intervals:} {The earliest possible age of the occurrence and latest possible age of the occurrence, expressed in terms of geologic intervals. See \code{constrainAge} for how to simplify these fields.} ##' \item{Numeric Ages:} {The earliest possible age of the occurrence and latest possible age of the occurrence, expressed as millions of years ago.} ##' \item{Geolocation:} {Both present-day and rotated paleocoordinates of the occurrence. The geoplate id used by the rotation model is also included. The key for geoplate ids can be found in the Paleobiology Database API documentation.} #' } #' #' @return a data frame #' #' @author Andrew A. Zaffos #' #' @examples #' #' # Download a test dataset of Ypresian bivalves. #' # DataPBDB<-downloadPBDB(Taxa="Bivalvia",StartInterval="Ypresian",StopInterval="Ypresian") #' #' # Download a test dataset of Ordovician-Silurian trilobites and brachiopods. #' # DataPBDB<-downloadPBDB(c("Trilobita","Brachiopoda"),"Ordovician","Silurian") #' #' @rdname downloadPBDB #' @export # A function for downloading data from the Paleobiology database downloadPBDB<-function(Taxa,StartInterval="Pliocene",StopInterval="Pleistocene") { StartInterval<-gsub(" ","%20",StartInterval) StopInterval<-gsub(" ","%20",StopInterval) Taxa<-paste(Taxa,collapse=",") URL<-paste0("https://paleobiodb.org/data1.2/occs/list.csv?base_name=",Taxa,"&interval=",StartInterval,",",StopInterval,"&show=coords,paleoloc,class&limit=all") File<-utils::read.csv(URL,header=TRUE) # Subset to include the most generically useful columns File<-File[,c("occurrence_no","collection_no","reference_no","phylum","class","order","family","genus","accepted_name","early_interval","late_interval","max_ma","min_ma","lng","lat","paleolng","paleolat","geoplate")] return(File) }
/scratch/gouwar.j/cran-all/cranData/velociraptr/R/downloadPBDB.R
#' Downloads paleogeographic maps #' #' Download a paleogeographic map for an age expressed in millions of years ago. #' #' @param Age A whole number up to 550 #' #' @details Downloads a map of paleocontinents for a specific age from Macrostrat.org as a shapefile. The given age must be expressed as a whole number. Note that the function makes use of the rgdal and RCurl packages. #' #' @author Andrew A. Zaffos #' #' @return A simple features object #' #' @examples #' #' # Download a test dataset of Maastrichtian bivalves. #' # DataPBDB<-downloadPBDB(Taxa="Bivalvia",StartInterval="Maastrichtian",StopInterval="Maastrichtian") #' #' # Download a paleogeographic map. #' # KTBoundary<-downloadPaleogeography(Age=66) #' #' # Plot the paleogeographic map (uses rgdal) and the PBDB points. #' # plot(KTBoundary,col="grey") #' # points(x=DataPBDB[,"paleolng"],y=DataPBDB[,"paleolat"],pch=16,cex=2) #' #' @rdname downloadPaleogeography #' @export # download maps of paleocontinents from Macrostrat downloadPaleogeography<-function(Age=0) { URL<-paste0("https://macrostrat.org/api/v2/paleogeography?format=geojson_bare&age=",Age) return(sf::st_read(URL)) }
/scratch/gouwar.j/cran-all/cranData/velociraptr/R/downloadPaleogeography.R
#' Download Shapefile of Places #' #' Download a shapefile of a geolocation from the Macrostrat API's implementation of the Who's on First database by MapZen. #' #' @aliases trueWOF #' #' @param Place A character string; the name of a place #' @param Type A character string; a type of place #' #' @details Download a shapefile of a geolocation from the \href{https://macrostrat.org}{Macrostrat} API. The Macrostrat database provides a GeoJSON of a particular location given the location's \code{name} and \code{type}. Type can be of the categories: \code{"continent"}, \code{"country"}, \code{"region"}, \code{"county"}, and \code{"locality"}. #' #' If multiple locations of the same type share the same name (e.g., Alexandria), the route will return a feature collection of all matching polygons. #' #' @return An rgdal compatible shapefile #' #' @author Andrew A. Zaffos #' #' @examples #' #' # Download a polygon of Dane County, Wisconsin, United States, North America #' # DaneCounty<-downloadPlaces(Place="Dane",Type="county") #' #' # Download a polygon of Wisconsin, United States, North America #' # Wisconsin<-downloadPlaces(Place="Wisconsin",Type="region") #' #' # Download a polygon of North America #' # NorthAmerica<-downloadPlaces(Place="North America",Type="continent") #' #' @rdname downloadPlaces #' @export # Simple wrapper for the true function downloadPlaces<-function(Place="Wisconsin",Type="region") { Type<-tolower(Type) Place<-gsub(" ","%20",Place) return(queryPlaces(Place,Type)) } # We want to hide the /places route because we do not want people to attempt to download our entire dataset queryPlaces<-function(Place="Wisconsin",Type="region") { URL<-paste("https://macrostrat.org/api/v2/places?format=geojson_bare&name=",Place,"&placetype=",Type) return(sf::st_read(URL)) }
/scratch/gouwar.j/cran-all/cranData/velociraptr/R/downloadPlaces.R
#' Download geologic timescale #' #' Downloads a geologic timescale from the Macrostrat.org database. #' #' @param Timescale character string; a recognized timescale in the Macrostrat.org database #' #' @details Downloads a recognized timescale from the Macrostrat.org database. This includes the name, minimum age, maximum age, midpoint age, and official International Commission on Stratigraphy color hexcode if applicable of each interval in the timescale. Go to https://macrostrat.org/api/defs/timescales?all for a list of recognized timescales. #' #' @return A data frame #' #' @author Andrew A. Zaffos #' #' @examples #' #' # Download the ICS recognized periods timescale #' Timescale<-downloadTime(Timescale="international periods") #' #' @rdname downloadTime #' @export # Download timescales from Macrostrat downloadTime<-function(Timescale="interational epochs") { Timescale<-gsub(" ","%20",Timescale) URL<-paste0("https://macrostrat.org/api/v2/defs/intervals?format=csv&timescale=",Timescale) Intervals<-utils::read.csv(URL,header=TRUE) Midpoint<-apply(Intervals[,c("t_age","b_age")],1,stats::median) Intervals<-cbind(Intervals,Midpoint) rownames(Intervals)<-Intervals[,"name"] return(Intervals) }
/scratch/gouwar.j/cran-all/cranData/velociraptr/R/downloadTime.R
#' Download fixed-latitude equal-area grid #' #' Download an equal-area grid of the world with fixed latitudinal spacing and variable longitudinal spacing. #' #' @param LatSpacing Number of degrees desired between latitudinal bands #' @param CellArea Desired target area of the cells in km^2 as a character string #' #' @details Downloads an equal-area grid with fixed latitudinal spacing and variable longitudinal spacing. The distance between longitudinal borders of grids will adjust to the target area size within each band of latitude. The algorithm will adjust the area of the grids to ensure that the total surface of the globe is covered. #' #' @author Andrew A. Zaffos #' #' @return A simple features object #' #' @examples #' #' # Download an equal area grid with 10 degree latitudinal spacing and 1,000,000 km^2 grids #' # EqualArea<-fixedLatitude(LatSpacing=10,CellArea="1000000") #' #' @rdname fixedLatitude #' @export # Download an equal-area grid map into R # Fixed latitudinal width in degrees, Target cell size in km2 # Must pass as character string instead of numeric to avoid R converting to scientific notation fixedLatitude<-function(LatSpacing=5,CellArea="500000") { URL<-paste0("https://macrostrat.org/api/grids/longitude?format=geojson_bare&latSpacing=",LatSpacing,"&cellArea=",CellArea) return(sf::st_read(URL)) }
/scratch/gouwar.j/cran-all/cranData/velociraptr/R/fixedLatitude.R
#' Multiplicative Diversity Partitioning #' #' Calculates beta diversity under various Multiplicative Diversity Partitioning paradigms. #' #' @param CommunityMatrix a matrix #' #' @aliases multiplicativeBeta,completeTurnovers,notEndemic #' #' @details Takes a community matrix (see \code{presenceMatrix} or \code{abundanceMatrix}) and returns one of three types of multiplicative beta diversity. #' #' Refer to Tuomisto, H (2010) "A diversity of beta diversities: straightening up a concept gone awry. Part 1. Defining beta diversity as a function of alpha and gamma diversity". \emph{Ecography} 33:2-22. #' #' \itemize{ ##' \item{\code{multiplicativeBeta(CommunityMatrix):}} {Calculates the original beta diversity ratio - Gamma/Alpha. It quantifies how many times as rich gamma is than alpha.} ##' \item{\code{completeTurnovers(CommunityMatrix):}} {The number of complete effective species turnovers observed among compositonal units in the dataset - (Gamma-Alpha)/Alpha.} ##' \item{\code{notEndemic(CommunityMatrix):}} {The proportion of taxa in the dataset not limited to a single sample - (Gamma-Alpha)/Gamma} ##' } #' #' @return A numeric vector #' #' @author Andrew A. Zaffos #' #' @examples #' # Download a test dataset of pleistocene bivalves from the Paleobiology Database. #' # DataPBDB<-downloadPBDB(Taxa="Bivalvia","Pleistocene","Pleistocene") #' #' # Create a community matrix with tectonic plates as "samples". #' # CommunityMatrix<-abundanceMatrix(DataPBDB,"geoplate") #' #' # "True local diversity ratio" #' # multiplicativeBeta(CommunityMatrix) #' #' # Whittaker's effective species turnover #' # completeTurnovers(CommunityMatrix) #' #' # Proportional effective species turnover #' # notEndemic(CommunityMatrix) #' #' @rdname multiplicativeBeta #' @export # returns vector of each taxon’s contribution to alpha diversity # "True local diversity ratio" of Tuomisto 2010 # This quantifies how many times as rich effective species gamma is than alpha multiplicativeBeta<-function(CommunityMatrix) { Alpha<-meanAlpha(CommunityMatrix) Gamma<-totalGamma(CommunityMatrix) Beta<-Gamma/Alpha return(Beta) } #' @rdname multiplicativeBeta #' @export # Whittaker's effective species turnover, the number of complete effective species # turnovers among compositional units in the dataset completeTurnovers<-function(CommunityMatrix) { Alpha<-meanAlpha(CommunityMatrix) Gamma<-totalGamma(CommunityMatrix) Beta<-(Gamma-Alpha)/Alpha return(Beta) } #' @rdname multiplicativeBeta #' @export # Proportional effective species turnover, the proporition of species in the region # not limited to a single sample - i.e., the proportion of non-endemic taxa. notEndemic<-function(CommunityMatrix) { Alpha<-meanAlpha(CommunityMatrix) Gamma<-totalGamma(CommunityMatrix) Beta<-(Gamma-Alpha)/Gamma return(Beta) }
/scratch/gouwar.j/cran-all/cranData/velociraptr/R/multiplicativeBeta.R
#' Create a matrix of presences and absences #' #' Creates a community matrix of taxon presences and absences from a data frame with a column of sites and a column of species. #' #' @param Data A dataframe or matrix #' @param Rows A characer string #' @param Columns A character string #' #' @return A presence-absence matrix #' #' @author Andrew A. Zaffos #' #' @examples #' #' # Download a test dataset of pleistocene bivalves. #' # DataPBDB<-downloadPBDB(Taxa="Bivalvia","Pleistocene","Pleistocene") #' #' # Create a community matrix of genera by plates. #' # CommunityMatrix<-presenceMatrix(DataPBDB,Rows="geoplate",Columns="genus") #' #' # Create a community matrix of families by geologic interval. #' # CommunityMatrix<-presenceMatrix(DataPBDB,Rows="early_interval",Columns="family") #' #' @rdname presenceMatrix #' @export presenceMatrix<-function(Data,Rows="geoplate",Columns="genus") { FinalMatrix<-matrix(0,nrow=length(unique(Data[,Rows])),ncol=length(unique(Data[,Columns]))) rownames(FinalMatrix)<-unique(Data[,Rows]) colnames(FinalMatrix)<-unique(Data[,Columns]) ColumnPositions<-match(Data[,Columns],colnames(FinalMatrix)) RowPositions<-match(Data[,Rows],rownames(FinalMatrix)) Positions<-cbind(RowPositions,ColumnPositions) FinalMatrix[Positions]<-1 return(FinalMatrix) }
/scratch/gouwar.j/cran-all/cranData/velociraptr/R/presenceMatrix.R
#' Align horizontally #' #' Use this function to specify the horizontal alignment of the `iframe` #' within the enclosing `div`. #' #' @inheritParams use_start_time #' @param align `character`, indicates type of alignment #' #' @inherit embed return #' @export #' use_align <- function(embed, align = c("left", "right", "center", "justified")) { assertthat::assert_that( inherits(embed, "vembedr_embed"), msg = "embed is not a `vebmedr_embed` object" ) align <- match.arg(align) embed[["attribs"]][["align"]] <- align embed } #' Make size responsive #' #' If your HTML page includes #' [Twitter Bootstrap 3](https://getbootstrap.com/docs/3.3/components/#responsive-embed), #' you can use this function to make the size of the `iframe` responsive #' within the enclosing `div`. #' #' @inheritParams use_start_time #' #' @inherit embed return #' @export #' use_bs_responsive <- function(embed) { assertthat::assert_that( inherits(embed, "vembedr_embed"), msg = "embed is not a `vebmedr_embed` object" ) # ratio is set when we create the embed ratio <- attr(embed, "ratio") class_div <- c( "embed-responsive", glue::glue("embed-responsive-{ratio}") ) class_iframe <- "embed-responsive-item" # add the class to the div embed[["attribs"]][["class"]] <- to_html_class(embed[["attribs"]][["class"]], class_div) # add the class to the iframe iframe <- get_iframe(embed) iframe[["attribs"]][["class"]] <- to_html_class(iframe[["attribs"]][["class"]], class_iframe) embed <- set_iframe(embed, iframe) embed } #' Make rounded corners #' #' You can use this function to make rounded corners for the enclosing `</div>`. #' #' @inheritParams use_start_time #' @param radius `numeric` or `character`, css property for the border-radius #' for the `<iframe/>`. Numeric values will be interpreted as number of pixels. #' #' @inherit embed return #' @export #' use_rounded <- function(embed, radius = NULL) { assertthat::assert_that( inherits(embed, "vembedr_embed"), msg = "embed is not a `vebmedr_embed` object" ) # cast numeric radius as number of pixels if (is.numeric(radius)) { radius <- glue::glue("{radius}px") } # if we do this again, make an accessor div <- embed[["children"]][[1]] # add the class to the div div[["attribs"]][["class"]] <- to_html_class(div[["attribs"]][["class"]], "vembedr-rounded") # if we have a user-specified radius, use it if (!is.null(radius)) { div <- htmltools::tagAppendAttributes( div, style = as.character(glue::glue("border-radius: {radius};")) ) } embed[["children"]][[1]] <- div embed }
/scratch/gouwar.j/cran-all/cranData/vembedr/R/div.R
#' Embed video from service #' #' These functions are used to embed video into your \strong{rmarkdown} html-documents, #' or into your \strong{shiny} apps. There are functions to embed from #' YouTube, Vimeo, Microsoft Channel 9 (who host the UseR! 2016 videos), and Box. #' #' These services allow you to customize a lot of things by specifying #' an optional query string. The specification for the query string will differ #' according to the service being used: #' #' \describe{ #' \item{YouTube}{<https://developers.google.com/youtube/player_parameters>} #' \item{Vimeo}{<https://developer.vimeo.com/player/embedding>} #' \item{Box}{<https://developer.box.com/guides/embed/box-embed/#programmatically>} #' \item{Microsoft Stream}{<https://docs.microsoft.com/en-us/stream/portal-embed-video>} #' } #' #' @param id `character`, identifier provided by the service #' @param custom_domain `character`, (used by Box) name of Box-instance #' to use. It can be useful to use `getOption("vembedr.box_custom_domain")` #' if you are using a corporate instance of Box. If `NULL`, it will use #' the standard Box instance. #' @param height `numeric`, height of iframe (px) #' @param width `numeric`, width of iframe (px) #' @param ratio `character`, indicates aspect ratio for the `<iframe/>` #' @param frameborder `numeric`, size of frame border (px) #' @param allowfullscreen `logical`, indicates if to allow fullscreen #' @param query `list`, items to include in url-query string #' @param fragment `character`, string to include as url-fragment #' #' @return Object with S3 class `vembedr_embed`. #' #' @name embed #' @family embed #' @seealso [use_start_time()] #' @examples #' embed_youtube("dQw4w9WgXcQ") #' embed_vimeo("45196609") #' embed_box("m5do45hvzw32iv2aors3urf5pgkxxazx") #' embed_msstream("ae21b0ac-4a2b-41f4-b3fc-f1720dd20f48") #' NULL # internal function to create embed div create_embed <- function(iframe, name, ratio) { embed <- htmltools::div( class = "vembedr", htmltools::div(iframe) ) class(embed) <- c(name, "vembedr_embed", class(embed)) attr(embed, "ratio") <- ratio # attach html-dependency embed <- htmltools::attachDependencies(embed, vembedr_dependency()) embed }
/scratch/gouwar.j/cran-all/cranData/vembedr/R/embed.R
#' Embed video based on URL #' #' You can use this function to embed video using only the URL and you do not #' need any customization beyond the start-time. It works for all the #' services supported by the [embed()] family of functions. #' #' This function calls [suggest_embed()] then parses and evaluates the code. #' #' @param url `character`, URL of web-page for video #' #' @inherit embed return #' #' @seealso [suggest_embed()] #' @examples #' embed_url("https://youtu.be/1-vcErOPofQ?t=28s") #' @export #' embed_url <- function(url){ parse_text <- function(x){ parse(text = x) } suggest_embed_pure(url) %>% parse_text() %>% eval() } #' @rdname embed_channel9 #' @export # embed_user2016 <- function(id, width = NULL, height = 300, ratio = c("16by9", "4by3"), frameborder = 0, allowfullscreen = TRUE){ lifecycle::deprecate_warn( "1.5.0", "embed_user2016()", details = c( i = "Microsoft made breaking changes to its Channel 9 service.", i = "See <https://docs.microsoft.com/en-us/teamblog/channel9joinedmicrosoftlearn>." ), id = "channel_9" ) id <- c("Events", "useR-international-R-User-conference", "useR2016", id) embed_channel9(id, width, height, ratio, frameborder, allowfullscreen) } #' @rdname embed_channel9 #' @export # embed_user2017 <- function(id, width = NULL, height = 300, ratio = c("16by9", "4by3"), frameborder = 0, allowfullscreen = TRUE){ lifecycle::deprecate_warn( "1.5.0", "embed_user2017()", details = c( i = "Microsoft made breaking changes to its Channel 9 service.", i = "See <https://docs.microsoft.com/en-us/teamblog/channel9joinedmicrosoftlearn>." ), id = "channel_9" ) id <- c( "Events", "useR-international-R-User-conferences", "useR-International-R-User-2017-Conference", id ) embed_channel9(id, width, height, ratio, frameborder, allowfullscreen) }
/scratch/gouwar.j/cran-all/cranData/vembedr/R/embed_url.R
# helper function to convert logical into a character parameter .convert_allowfullscreen <- function(x){ if (x){ result <- "" } else { result <- NULL } result } #' Get number of seconds given a string #' #' This is a helper function to get the number of seconds. #' #' This could be useful for composing query parameters for YouTube embeds. #' #' @param x character, describes a time duration, i.e. "3m15s" #' #' @return numeric, number of seconds #' #' @seealso [embed_youtube()], [hms()] #' #' @keywords internal #' @export # secs <- function(x){ .Deprecated("use_start_time") .secs(x) } # internal function # @examples # secs("45s") # secs("3m15s") # secs("1h1m5s") .secs <- function(x) { parse <- function(x, char){ regex <- paste0("(\\d+)", char) if (stringr::str_detect(x, regex)){ num <- as.numeric(stringr::str_match(x, regex)[[2]]) } else { num <- 0 } num } hours <- parse(x, "h") minutes <- parse(x, "m") seconds <- parse(x, "s") only_seconds <- parse(x, "$") # capture one-or-more digits at the end of a string result <- only_seconds + seconds + 60*(minutes + 60*hours) result } #' Create an hours-minutes-seconds string #' #' @param x, numeric (number of seconds), or character (i.e. "3m15s") #' #' @return character string (i.e. "0h3m15s") #' @seealso [secs()] #' #' @keywords internal #' @export #' hms <- function(x){ .Deprecated("use_start_time") .hms(x) } # internal function # @examples # hms(30) # hms("3m15s") # .hms <- function(x) { seconds <- .secs(x) h <- floor(seconds/3600) m <- floor((seconds %% 3600)/60) s <- floor(seconds %% 60) paste0(h, "h", m, "m", s, "s") }
/scratch/gouwar.j/cran-all/cranData/vembedr/R/helper.R
#' Accessor methods for iframe #' #' @name iframe #' #' @inheritParams use_start_time #' @param iframe `shiny.tag` with `name` `"iframe"`, object to be set #' @param ... other args as needed #' #' @return #' \describe{ #' \item{get_iframe}{`shiny.tag` with `name` `"iframe"`, created using [htmltools::tags]`$iframe()`} #' \item{set_iframe}{`embed` object} #' } #' @keywords internal #' @export #' get_iframe <- function(embed, ...) { UseMethod("get_iframe", embed) } #' @rdname iframe #' @export #' get_iframe.default <- function(embed, ...) { stop( glue::glue("Cannot get_iframe() for object of type {class(embed)}"), call. = FALSE ) } #' @rdname iframe #' @export #' get_iframe.vembedr_embed <- function(embed, ...) { embed[["children"]][[1]][["children"]][[1]] } #' @rdname iframe #' @export #' set_iframe <- function(embed, ...) { UseMethod("set_iframe", embed) } #' @rdname iframe #' @export #' set_iframe.default <- function(embed, ...) { stop( glue::glue("Cannot set_iframe() for object of type {class(embed)}"), call. = FALSE ) } #' @rdname iframe #' @export #' set_iframe.vembedr_embed <- function(embed, iframe, ...) { assertthat::assert_that( inherits(iframe, "shiny.tag"), assertthat::are_equal(iframe$name, "iframe"), msg = "iframe is not an `iframe`" ) embed[["children"]][[1]][["children"]][[1]] <- iframe embed }
/scratch/gouwar.j/cran-all/cranData/vembedr/R/iframe.R
#' Suggest embed-code based on URL #' #' This function is meant to work with URLs from any of the supported services. #' #' \describe{ #' \item{`suggest_embed`}{Called for the side-effect of #' printing suggested code the screen. If you have a recent version #' of [usethis](https://cran.r-project.org/package=usethis), the code #' will be copied to your clipboard.} #' \item{`suggest_embed_pure`}{Returns character string #' that represents the suggested code.} #' } #' #' @inheritParams embed_url #' #' @return character, returns the suggested code (`suggest_embed` returns invisibly) #' #' @examples #' \dontrun{ #' # not run because it may copy to your clipboard #' suggest_embed("https://youtu.be/1-vcErOPofQ?t=28s") #' suggest_embed("https://www.youtube.com/watch?v=1-vcErOPofQ") #' } #' cat(suggest_embed_pure("https://youtu.be/1-vcErOPofQ?t=28")) #' @export #' suggest_embed <- function(url){ code <- suggest_embed_pure(url) # do we have a recent-enough version of usethis? has_usethis <- requireNamespace("usethis", quietly = TRUE) && utils::packageVersion("usethis") > "1.4.0" if (has_usethis) { usethis::ui_code_block(code) } else { message(code) } invisible(code) } #' @keywords internal #' @rdname suggest_embed #' @export suggest_embed_pure <- function(url){ parse_list <- parse_video_url(url) suggest_list <- build_suggestion(parse_list) str_message <- paste(unlist(suggest_list), collapse = " %>%\n ") str_message } #' Given a parse-list, generate an embed-list #' #' This is an internal function, supporting [suggest_embed()] #' #' @param parse_list, list generated using [parse_video_url()] #' with members: #' \describe{ #' \item{service}{character, describes which service is used} #' \item{id}{character, identifier for the video at the service} #' \item{start_time}{character, indicates start time} #' } #' #' @return list with members: #' \describe{ #' \item{embed}{character, code for [embed()] call} #' \item{start_time}{character, (optional) code for [use_start_time()] call} #' } #' @seealso [suggest_embed()] [parse_video_url()] #' @examples #' parse_video_url("https://youtu.be/1-vcErOPofQ?t=28s") %>% #' build_suggestion() #' @noRd #' build_suggestion <- function(parse_list){ # idea: this seems like a great place to implement tidyeval str_embed <- glue::glue('embed_{parse_list$service}("{parse_list$id}")') # if we have a custom_domain (this is getting hacky): if (!is.null(parse_list$custom_domain)) { str_embed <- glue::glue( 'embed_{parse_list$service}("{parse_list$id}", ', 'custom_domain = "{parse_list$custom_domain}")' ) } if (is.null(parse_list$start_time)){ str_start_time <- NULL } else { str_start_time <- glue::glue("use_start_time(\"{parse_list$start_time}\")") str_start_time <- as.character(str_start_time) } suggest_list <- list( embed = as.character(str_embed), start_time = str_start_time ) suggest_list } #' Determine service based on URL #' #' @inheritParams embed_url #' #' @return `character` identifying the video service #' #' @examples #' get_service("https://youtu.be/1-vcErOPofQ?t=28s") #' @export #' get_service <- function(url) { url_parsed <- httr::parse_url(url) hostname <- url_parsed$hostname # each service will match a regex regex <- c( channel9 = "^channel9\\.msdn\\.com$", youtube = "^www\\.youtube\\.com$", youtube_short = "^youtu\\.be$", vimeo = "^vimeo\\.com$", box = "app\\.box\\.com$", msstream = "web\\.microsoftstream\\.com$" ) # str_detect is vectorized over the patters is_service <- stringr::str_detect(hostname, regex) # if no service found, throw error if (!any(is_service)) { stop( glue::glue("Cannot find service to match '{hostname}'."), call. = FALSE ) } service <- names(regex)[is_service] service } #' Parse a URL to determine service and id #' #' This is an internal function, supporting [suggest_embed()] #' #' @param url character, URL to parse #' #' @return list with members: #' \describe{ #' \item{service}{character, describes which service is used} #' \item{id}{character, identifier for the video at the service} #' \item{start_time}{character, indicates start time} #' } #' #' @keywords internal #' @seealso suggest_embed #' @examples #' parse_video_url("https://youtu.be/1-vcErOPofQ?t=28s") #' @export #' parse_video_url <- function(url) { service <- get_service(url) url_parsed <- httr::parse_url(url) class(url_parsed) <- c(glue::glue("vembedr_url_{service}")) .parse(url_parsed) } .parse <- function(url_parsed, ...) { UseMethod(".parse") } .parse.default <- function(url_parsed, ...) { stop("no method available") }
/scratch/gouwar.j/cran-all/cranData/vembedr/R/parse.R
#' Pipe functions #' #' Like dplyr, vembedr also uses the pipe function, `\%>\%` to turn #' function composition into a series of imperative statements. #' #' @importFrom magrittr %>% #' @name %>% #' @rdname pipe #' @export #' @param lhs,rhs An embed object and a function to apply to it #' #' @keywords internal #' #' @examples #' # Instead of #' use_start_time(rickroll_youtube(), "1m35s") #' # you can write #' rickroll_youtube() %>% use_start_time("1m35s") NULL
/scratch/gouwar.j/cran-all/cranData/vembedr/R/pipe.R
#' Embed popular video #' #' If you want to experiment with the arguments to [embed()], #' such as `query`, but do not have a particular video in mind, this function #' may be useful to you. #' #' Please note that the YouTube video seems no longer embeddable. #' #' @param ... arguments (other than `id`) passed on to [embed()] #' #' @inherit embed return #' #' @name rickroll #' @examples #' rickroll_vimeo() #' rickroll_youtube() #' NULL #' @rdname rickroll #' @export # rickroll_vimeo <- function(...){ embed_vimeo(id = "148751763", ...) } #' @rdname rickroll #' @export # rickroll_youtube <- function(...){ embed_youtube(id = "iik25wqIuFo", ...) } #' @rdname embed_channel9 #' @export # rickroll_channel9 <- function(...){ lifecycle::deprecate_warn( "1.5.0", "rickroll_channel9()", details = c( i = "Microsoft made breaking changes to its Channel 9 service.", i = "See <https://docs.microsoft.com/en-us/teamblog/channel9joinedmicrosoftlearn>." ), id = "channel_9" ) embed_channel9( id = c("Blogs", "Dan", "BlueHat-v7-Katie-Moussouris-interviews-Dan-Kaminsky-on-some-interesting-research-hes-been-doing-late"), ... ) %>% use_start_time("05m08s") }
/scratch/gouwar.j/cran-all/cranData/vembedr/R/rickroll.R
#' vembedr S3 Classes #' #' Knowledge of these classes is not needed for day-to-day use. Rather, #' it is a bookkeeping device used to make it clearer to a developer #' how to add a new service. #' #' We use S3 classes to distinguish an embed object, and to denote which #' service it uses. Objects of these classes are created by [embed_url()] #' and each service's embed function. #' #' **`vembedr_embed`** #' #' - base class for all services #' - HTML `<div>` #' - contains the embed code #' #' There is an additional class attached according to the service: #' #' - **`vembedr_embed_youtube`** #' - **`vembedr_embed_youtube_short`** #' - **`vembedr_embed_vimeo`** #' - **`vembedr_embed_channel9`** #' - **`vembedr_embed_box`** #' - **`vembedr_embed_msstream`** #' #' To support parsing, there is an internal S3 class attached to the URL #' being processed. It is named according to the service: #' #' - **`vembedr_url_youtube`** #' - **`vembedr_url_youtube_short`** #' - **`vembedr_url_vimeo`** #' - **`vembedr_url_channel9`** #' - **`vembedr_url_box`** #' - **`vembedr_url_msstream`** #' #' @name vembedr-s3-classes #' NULL
/scratch/gouwar.j/cran-all/cranData/vembedr/R/s3-classes.R
#' @rdname embed #' @export #' embed_box <- function(id, custom_domain = getOption("vembedr.box_custom_domain"), width = NULL, height = 300, ratio = c("16by9", "4by3"), frameborder = 0, allowfullscreen = TRUE) { # adapted from: # https://developer.box.com/guides/embed/box-embed/#programmatically # <iframe # src="https://{custom_domain}.app.box.com/embed/s/{shared link value}" # width="{pixels}" # height="{pixels}" # frameborder="0" # allowfullscreen webkitallowfullscreen msallowfullscreen> # </iframe> ratio <- match.arg(ratio) dim <- get_width_height(width, height, ratio) allowfullscreen <- .convert_allowfullscreen(allowfullscreen) host <- "app.box.com" if (!is.null(custom_domain)) { host <- "{custom_domain}.app.box.com" } url <- glue::glue("https://{host}/embed/s/{id}") iframe <- htmltools::tags$iframe( src = url, width = dim$width, height = dim$height + 60, frameborder = frameborder, allowfullscreen = allowfullscreen, webkitallowfullscreen = allowfullscreen, msallowfullscreen = allowfullscreen, `data-external` = 1 ) embed <- create_embed(iframe, "vembedr_embed_box", ratio) embed } #' @rdname use_start_time #' @export #' use_start_time.vembedr_embed_box <- function(embed, ...) { warning("Start time cannot be specified for Box.") embed } .parse.vembedr_url_box <- function(url_parsed, ...) { # determine custom-domain by taking apart hostname hostname_split <- stringr::str_split(url_parsed$hostname, "\\.")[[1]] custom_domain <- NULL if (identical(length(hostname_split), 4L)) { custom_domain <- hostname_split[1] } # determine id by taking apart path path_split <- stringr::str_split(url_parsed$path, "/")[[1]] id <- path_split[2] result <- list( service = "box", id = id, custom_domain = custom_domain, start_time = NULL ) result }
/scratch/gouwar.j/cran-all/cranData/vembedr/R/service-box.R
#' Embed video from Microsoft Channel 9 #' #' @description #' `r lifecycle::badge("deprecated")` #' #' These functions are deprecated: links to Microsoft Channel 9 #' [no longer work](https://docs.microsoft.com/en-us/teamblog/channel9joinedmicrosoftlearn). #' #' @inherit embed return params #' @param ... arguments (other than `id`) passed on to [embed()] #' @export #' embed_channel9 <- function(id, width = NULL, height = 300, ratio = c("16by9", "4by3"), frameborder = 0, allowfullscreen = TRUE){ lifecycle::deprecate_warn( "1.5.0", "embed_channel9()", details = c( i = "Microsoft made breaking changes to its Channel 9 service.", i = "See <https://docs.microsoft.com/en-us/teamblog/channel9joinedmicrosoftlearn>." ), id = "channel_9" ) ratio <- match.arg(ratio) dim <- get_width_height(width, height, ratio) allowfullscreen <- .convert_allowfullscreen(allowfullscreen) url <- httr::parse_url("https://channel9.msdn.com") url$path <- paste0(url$path, c(id, "player"), collapse = "/") iframe <- htmltools::tags$iframe( src = httr::build_url(url), width = dim$width, height = dim$height, frameborder = frameborder, allowfullscreen = allowfullscreen, `data-external` = 1 ) embed <- create_embed(iframe, "vembedr_embed_channel9", ratio) embed } #' @rdname use_start_time #' @export #' use_start_time.vembedr_embed_channel9 <- function(embed, start_time, is_paused = TRUE, ...){ # get the iframe iframe <- get_iframe(embed) # get the src from the iframe src <- htmltools::tagGetAttribute(iframe, "src") # parse the url url <- httr::parse_url(src) # set the time in url$fragment frag <- paste("time", .hms(start_time), sep = "=") if (is_paused){ frag <- paste(frag, "paused", sep = ":") } url$fragment <- frag # set the url in the iframe # == need to ask about a public API for this in htmltools == iframe$attribs$src <- httr::build_url(url) # set the iframe in the embed embed <- set_iframe(embed, iframe) embed } .parse.vembedr_url_channel9 <- function(url_parsed, ...){ path_split <- url_parsed$path %>% strsplit("/") %>% `[[`(1) path_user2016 <- c("Events", "useR-international-R-User-conference", "useR2016") path_user2017 <-c( "Events", "useR-international-R-User-conferences", "useR-International-R-User-2017-Conference" ) if (identical(length(path_split), 4L) && identical(path_split[1:3], path_user2016)) { # this is a UseR!2016 link result <- list( service = "user2016", id = path_split[[4]], start_time = NULL ) } else if (identical(path_split[1:3], path_user2017)) { # this is a UseR!2017 link result <- list( service = "user2017", id = path_split[[4]], start_time = NULL ) } else { # this is a regular Channel 9 link result <- list( service = "channel9", id = url_parsed$path, start_time = NULL ) } result }
/scratch/gouwar.j/cran-all/cranData/vembedr/R/service-channel9.R
#' @rdname embed #' @export # embed_msstream <- function(id, width = NULL, height = 300, ratio = c("16by9", "4by3"), query = NULL){ ratio <- match.arg(ratio) dim <- get_width_height(width, height, ratio) url <- httr::parse_url("https://web.microsoftstream.com/embed/video") url$path <- glue::glue("{url$path}/{id}") url$query <- c(list(autoplay = "false", showinfo = "true"), query) iframe <- htmltools::tags$iframe( src = httr::build_url(url), width = dim$width, height = dim$height, allowfullscreen = NULL, style = "border:none;", `data-external` = 1 ) embed <- create_embed(iframe, "vembedr_embed_msstream", ratio) embed } #' @rdname use_start_time #' @export #' use_start_time.vembedr_embed_msstream <- function(embed, start_time, ...){ # get the iframe iframe <- get_iframe(embed) # get the src from the iframe src <- htmltools::tagGetAttribute(iframe, "src") # parse the url url <- httr::parse_url(src) # set the time in url$query url$query$st <- .secs(start_time) # set the url in the iframe # == need to ask about a public API for this in htmltools == iframe$attribs$src <- httr::build_url(url) # set the iframe in the embed embed <- set_iframe(embed, iframe) embed } .parse.vembedr_url_msstream <- function(url_parsed, ...) { path_split <- stringr::str_split(url_parsed$path, "/")[[1]] list( service = "msstream", id = path_split[[2]], start_time = url_parsed$query$st ) }
/scratch/gouwar.j/cran-all/cranData/vembedr/R/service-msstream.R
#' @rdname embed #' @export # embed_vimeo <- function(id, width = NULL, height = 300, ratio = c("16by9", "4by3"), frameborder = 0, allowfullscreen = TRUE, query = NULL, fragment = NULL){ ratio <- match.arg(ratio) dim <- get_width_height(width, height, ratio) allowfullscreen <- .convert_allowfullscreen(allowfullscreen) url <- httr::parse_url("https://player.vimeo.com/video") # update url url$path <- paste(url$path, id, sep = "/") url$query <- query url$fragment <- fragment iframe <- htmltools::tags$iframe( class = "vimeo-embed", src = httr::build_url(url), width = dim$width, height = dim$height, frameborder = frameborder, webkitallowfullscreen = allowfullscreen, mozallowfullscreen = allowfullscreen, allowfullscreen = allowfullscreen, `data-external` = 1 ) embed <- create_embed(iframe, "vembedr_embed_vimeo", ratio) embed } #' @rdname use_start_time #' @export #' use_start_time.vembedr_embed_vimeo <- function(embed, start_time, ...){ # get the iframe iframe <- get_iframe(embed) # get the src from the iframe src <- htmltools::tagGetAttribute(iframe, "src") # parse the url url <- httr::parse_url(src) # set the time in url$fragment url$fragment <- paste0("t=", .secs(start_time)) # set the url in the iframe # == need to ask about a public API for this in htmltools == iframe$attribs$src <- httr::build_url(url) # set the iframe in the embed embed <- set_iframe(embed, iframe) embed } .parse.vembedr_url_vimeo <- function(url_parsed, ...){ start_time <- NULL if (!is.null(url_parsed$fragment)){ start_time <- sub("^t=", "", url_parsed$fragment) # removes leading "t=" } list( service = "vimeo", id = url_parsed$path, start_time = start_time ) }
/scratch/gouwar.j/cran-all/cranData/vembedr/R/service-vimeo.R
#' @rdname embed #' @export # embed_youtube <- function(id, width = NULL, height = 300, ratio = c("16by9", "4by3"), frameborder = 0, allowfullscreen = TRUE, query = NULL){ ratio <- match.arg(ratio) dim <- get_width_height(width, height, ratio) allowfullscreen <- .convert_allowfullscreen(allowfullscreen) url <- httr::parse_url("https://www.youtube.com/embed") url$path <- paste(url$path, id, sep = "/") url$query <- query iframe <- htmltools::tags$iframe( src = httr::build_url(url), width = dim$width, height = dim$height, frameborder = frameborder, allowfullscreen = allowfullscreen, `data-external` = 1 ) embed <- create_embed(iframe, "vembedr_embed_youtube", ratio) embed } #' @rdname use_start_time #' @export #' use_start_time.vembedr_embed_youtube <- function(embed, start_time, ...){ # get the iframe iframe <- get_iframe(embed) # get the src from the iframe src <- htmltools::tagGetAttribute(iframe, "src") # parse the url url <- httr::parse_url(src) # set the time in url$query url$query$start <- .secs(start_time) # set the url in the iframe # == need to ask about a public API for this in htmltools == iframe$attribs$src <- httr::build_url(url) # set the iframe in the embed embed <- set_iframe(embed, iframe) embed } .parse.vembedr_url_youtube <- function(url_parsed, ...) { list( service = "youtube", id = url_parsed$query$v, start_time = url_parsed$query$t ) } .parse.vembedr_url_youtube_short <- function(url_parsed, ...) { list( service = "youtube", id = url_parsed$path, start_time = url_parsed$query$t ) }
/scratch/gouwar.j/cran-all/cranData/vembedr/R/service-youtube.R
#' Specify start time #' #' This function provides you a consistent way to specify the start time, #' regardless of the service. Please note that Box does not provide a #' means to specify the start time. #' #' The `start_time` argument can take a variety of formats; these inputs #' all evaluate to the same value: #' #' \itemize{ #' \item{`"0h1m0s"`, `"0h01m00s"`, `"0h1m"`} #' \item{`"1m0s"`, `"1m"`} #' \item{`"60s"`, `60`} #' } #' #' Please note that for Vimeo, you can specify a start time, but you can not #' specify that the video be paused at this time. In other words, it is like #' "autoplay" is set to `TRUE`, and you cannot unset it. #' #' @rdname use_start_time #' @param ... generic arguments to pass through #' @param embed `vembedr_embed` object, created using an [embed()] function #' @param start_time `numeric` (seconds), or `character` (e.g. `"3m15s"`) #' @param is_paused `logical`, for "Channel 9" specifies if the video #' should be paused at this time #' #' @inherit embed return #' #' @export #' @examples #' rickroll_youtube() %>% #' use_start_time("3m32s") #' use_start_time <- function(embed, ...) UseMethod("use_start_time") #' @rdname use_start_time #' @export #' use_start_time.default <- function(embed, ...) "Unknown class"
/scratch/gouwar.j/cran-all/cranData/vembedr/R/use_start_time.R
# concatenates arguments, returns space-delimited string of unique items to_html_class <- function(x, ...) { x <- c(x, ...) x <- unique(x) x <- glue::glue_collapse(x, sep = " ") x <- as.character(x) x } # define html-dependency vembedr_dependency <- function() { htmltools::htmlDependency( name = "vembedr", version = utils::packageVersion("vembedr"), src = "vembedr", stylesheet = c("css/vembedr.css"), package = "vembedr" ) }
/scratch/gouwar.j/cran-all/cranData/vembedr/R/utils-htmltools.R
#' @importFrom rlang `%||%`
/scratch/gouwar.j/cran-all/cranData/vembedr/R/utils-null.R
# determine height, width get_width_height <- function(width = NULL, height = 300, ratio = c("16by9", "4by3")) { ratio <- get_ratio(ratio) # width and height cannot both be NULL assertthat::assert_that( !(is.null(width) && is.null(height)), msg = "Both width and height cannot be NULL." ) if (is.null(width)) { width <- round(height * ratio) } if (is.null(height)) { height <- round(width / ratio) } # validate assertthat::assert_that( assertthat::is.number(width), assertthat::is.number(height) ) list(width = width, height = height) } get_ratio <- function(ratio = c("16by9", "4by3")) { ratio <- match.arg(ratio) ratio_catalog <- list(`16by9` = 16 / 9, `4by3` = 4 / 3) ratio <- ratio_catalog[[ratio]] ratio }
/scratch/gouwar.j/cran-all/cranData/vembedr/R/utils-size.R
#' vembedr: Package for embedding video #' #' The vembedr package lets you embed video into your HTML pages for #' these services: #' #' - YouTube #' - Vimeo #' - Box #' - Microsoft Stream #' #' It provides two categories of functions: #' #' - **embed** functions, to specify a video to embed: #' e.g. [embed_youtube()], [embed_url()] #' - **use** functions, to modify the embedding: #' e.g. [use_start_time()], [use_rounded()] #' #' You can use the pipe (`|>` or `%>%`) to chain *embed function-calls* with #' *use function-calls*. #' #' @docType package #' @name vembedr-package NULL ## usethis namespace: start #' @importFrom lifecycle deprecated ## usethis namespace: end NULL
/scratch/gouwar.j/cran-all/cranData/vembedr/R/vembedr-package.R
# not to be used yet, still buggy use_vimeo_js <- function(){ htmltools::tagList( htmltools::tags$script(src="https://player.vimeo.com/api/player.js"), htmltools::tags$script(" var embeds = $('.vimeo-embed'); console.log(embeds) for (var i = 0; i !== embeds.length; i++) { var player = new Vimeo.Player(embeds[i]); player.ready().then(function() { player.pause(); }); }; ") ) }
/scratch/gouwar.j/cran-all/cranData/vembedr/R/vimeo_js.R
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) library("htmltools") library("fs") ## ----------------------------------------------------------------------------- library("vembedr") ## ----------------------------------------------------------------------------- embed_url("https://www.youtube.com/watch?v=BD_n6ju9iRA") ## ----------------------------------------------------------------------------- suggest_embed("https://www.youtube.com/watch?v=BD_n6ju9iRA") ## ----------------------------------------------------------------------------- suggest_embed("https://youtu.be/JeaBNAXfHfQ") ## ----------------------------------------------------------------------------- embed_youtube("JeaBNAXfHfQ") ## ----------------------------------------------------------------------------- suggest_embed("https://vimeo.com/238200347") ## ----------------------------------------------------------------------------- embed_vimeo("238200347") ## ----out.width="100%", echo=FALSE--------------------------------------------- knitr::include_graphics("figures/box-binford.png") ## ----------------------------------------------------------------------------- suggest_embed("https://app.box.com/s/d75g9cr27s2jnx62b86idpgffzzxfdt2") ## ----------------------------------------------------------------------------- embed_box("d75g9cr27s2jnx62b86idpgffzzxfdt2") ## ----------------------------------------------------------------------------- suggest_embed( "https://web.microsoftstream.com/video/ae21b0ac-4a2b-41f4-b3fc-f1720dd20f48" ) ## ----------------------------------------------------------------------------- embed_msstream("ae21b0ac-4a2b-41f4-b3fc-f1720dd20f48") %>% use_rounded() %>% use_start_time(10) ## ----------------------------------------------------------------------------- rickroll_vimeo() ## ----eval=FALSE--------------------------------------------------------------- # rickroll_youtube()
/scratch/gouwar.j/cran-all/cranData/vembedr/inst/doc/embed.R
--- title: "Embed video" author: "Ian Lyttle" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Embed video} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) library("htmltools") library("fs") ``` ```{r} library("vembedr") ``` Using this package, you can embed videos into RMarkdown documents and Shiny apps for videos from: - [YouTube](https://developers.google.com/youtube/player_parameters) - [Vimeo](https://developer.vimeo.com/player/embedding) - [Box](https://developer.box.com/guides/embed/box-embed/#programmatically) - [Microsoft Stream](https://docs.microsoft.com/en-us/stream/portal-embed-video) The links above are associated with the embedding API for each of the services; these are the APIs wrapped by the `embed()` functions in this package. You can also embed the video using only the URL of the page your video is on, with `embed_url()`. To set the start time, or to change the formatting, check out the `use_*()` functions in `vignette("modify")`. ## Embded using URL Although a URL can be long and awkward, it will get the job done. If the URL is from one of the supported services, it should *just work*: ```{r} embed_url("https://www.youtube.com/watch?v=BD_n6ju9iRA") ``` If you would like to generate more-concise code using the URL, you can use the `suggest_embed()` function: ```{r} suggest_embed("https://www.youtube.com/watch?v=BD_n6ju9iRA") ``` ## Embed by service ### YouTube You can get your video's identifier by inspecting its URL at YouTube - you can use the short version, as well: ```{r} suggest_embed("https://youtu.be/JeaBNAXfHfQ") ``` The identifier is the last part of the URL. To embed this video: ```{r} embed_youtube("JeaBNAXfHfQ") ``` ### Vimeo For Vimeo, the identifier is also included in the standard URL: ```{r} suggest_embed("https://vimeo.com/238200347") ``` The Vimeo identifier is the path of the URL: ```{r} embed_vimeo("238200347") ``` ### Box To share a video on Box, the video file itself will have to be shared. From the Box web-interface, you can do this by clicking the **Share** button at the top-right corner of your file's web-page. Then create a **Share Link**: ```{r out.width="100%", echo=FALSE} knitr::include_graphics("figures/box-binford.png") ``` Then, you need to capture some information about the embed-link itself, either the URL or the `id`. Please note that you need to work with the "ugly" URL, not a custom URL: ```{r} suggest_embed("https://app.box.com/s/d75g9cr27s2jnx62b86idpgffzzxfdt2") ``` You can do the same thing using the `embed_box()` function and the `id`. The Box identifier is the last part of the path, in this case **`d75g9cr27s2jnx62b86idpgffzzxfdt2`**. ```{r} embed_box("d75g9cr27s2jnx62b86idpgffzzxfdt2") ``` If you are using a corporate instance of Box, and use the `embed_box()` function, you will also have to specify the `custom_domain`. For example, if your URL starts with `"https://acme.app.box.com"`, then your `custom_domain` is `"acme"`. ### Microsoft Stream Microsoft Stream is a service offered for use by (large) organizations so that they may share videos internally to their organization. As such, this functionality may have limited appeal. ```{r} suggest_embed( "https://web.microsoftstream.com/video/ae21b0ac-4a2b-41f4-b3fc-f1720dd20f48" ) ``` The identifier is the last part of the path of the URL, in this case **`ae21b0ac-4a2b-41f4-b3fc-f1720dd20f48`**. ```{r} embed_msstream("ae21b0ac-4a2b-41f4-b3fc-f1720dd20f48") %>% use_rounded() %>% use_start_time(10) ``` Because this video is internal to an organization, it will likely not play for you. ## Sample videos In case you need sample videos with which to experiment, this package has you covered: ```{r} rickroll_vimeo() ``` Also (mercifully, not displayed as it seems no-longer embeddable): ```{r eval=FALSE} rickroll_youtube() ```
/scratch/gouwar.j/cran-all/cranData/vembedr/inst/doc/embed.Rmd
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----------------------------------------------------------------------------- library("vembedr") ## ----------------------------------------------------------------------------- embed_youtube("2WoDQBhJCVQ") %>% use_start_time("44s") %>% use_align("center") %>% use_rounded(10) ## ----------------------------------------------------------------------------- embed_youtube(id = "8SGif63VW6E") %>% use_start_time("4m12s") ## ----------------------------------------------------------------------------- embed_vimeo("10022924") %>% use_align("center") ## ----------------------------------------------------------------------------- embed_youtube("lan-UQfN0zs") %>% use_rounded(radius = 10) ## ----------------------------------------------------------------------------- embed_youtube("FkBQc0gQkQI") %>% use_bs_responsive() ## ----------------------------------------------------------------------------- embed_youtube("KvX8MijgeW8", ratio = "4by3") %>% use_bs_responsive()
/scratch/gouwar.j/cran-all/cranData/vembedr/inst/doc/modify.R
--- title: "Modify embedding" author: "Ian Lyttle" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Modify embedding} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r} library("vembedr") ``` This article deals with modifications you can make to videos that you embed. These include: - start time - horizontal alignment - rounded corners - responsive sizing for [Bootstrap](https://getbootstrap.com/docs/3.4/components/#responsive-embed) These modifications can be made independently of each other, and can be composed: ```{r} embed_youtube("2WoDQBhJCVQ") %>% use_start_time("44s") %>% use_align("center") %>% use_rounded(10) ``` To embed videos from variety of services, please read `vignette("embed")`. ## Start time To specify a starting time for a video, you can `use_start_time()`: ```{r} embed_youtube(id = "8SGif63VW6E") %>% use_start_time("4m12s") ``` Thanks to [Aurélien Ginolhac](https://github.com/ginolhac) for suggesting this video using this start-time. The `use_start_time()` function treats these all of these inputs equivalently: - `"0h1m0s"`, `"0h01m00s"`, `"0h1m"` - `"1m0s"`, `"1m"` - `"60s"`, `60` This function works with all of the services except for Box. ## Horizontal alignment You can `use_align()` to specify the horizontal alignment: ```{r} embed_vimeo("10022924") %>% use_align("center") ``` Possible values for `align` are: `"left"` (default), `"right"`, `"center"`, `"justified"`. ## Rounded corners You can `use_rounded()` to specify the `radius` (in pixels) of the rounds: ```{r} embed_youtube("lan-UQfN0zs") %>% use_rounded(radius = 10) ``` This seems to work better in the browser than in the RStudio viewer. ## Responsive sizing If you are using Bootstrap, you can `use_bs_responsive()` to make your video responsive to the width of its container: ```{r} embed_youtube("FkBQc0gQkQI") %>% use_bs_responsive() ``` It has no arguments, but it uses the `ratio` provided to the `embed()` function: ```{r} embed_youtube("KvX8MijgeW8", ratio = "4by3") %>% use_bs_responsive() ``` The `ratio` defaults to `"16by9"`, but it can also be `"4by3"`. If you are viewing this as this HTML vignette provided by R's help, you will not see responsiveness as it does not use Bootstrap. If you are viewing this at [this package's pkgdown site](https://ijlyttle.github.io/vembedr/articles/modify.html), you will see the responsiveness.
/scratch/gouwar.j/cran-all/cranData/vembedr/inst/doc/modify.Rmd
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- library("vembedr") ## ----------------------------------------------------------------------------- embed_url("https://www.youtube.com/watch?v=_fZQQ7o16yQ") %>% use_start_time("1m32") ## ----------------------------------------------------------------------------- embed_url("https://www.youtube.com/watch?v=uV4UpCq2azs") %>% use_align("center") ## ----------------------------------------------------------------------------- embed_youtube("lGTEUtS5H7I") %>% use_rounded() ## ----------------------------------------------------------------------------- embed_url("https://www.youtube.com/watch?v=H9KYQ_tnTtc") %>% use_bs_responsive() ## ----------------------------------------------------------------------------- # does not embed, but you can watch it at Vimeo embed_vimeo("45157591")
/scratch/gouwar.j/cran-all/cranData/vembedr/inst/doc/vembedr.R
--- title: "vembedr" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{vembedr} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library("vembedr") ``` Embedding and customizing videos in RMarkdown documents might seem like a complex task. It need not be. ```{r} embed_url("https://www.youtube.com/watch?v=_fZQQ7o16yQ") %>% use_start_time("1m32") ``` Even the most seemingly-intractable issues can be brought into focus with a clarifying framework. Above, we used an `embed` function followed by a `use` function. Using `embed_url()`, you can create an embed object for any of these supported services, or you can use an `id` with a service-specific embed function: - YouTube: `embed_youtube()` - Vimeo: `embed_vimeo()` - Box: `embed_box()` - Microsoft Stream: `embed_msstream()` You can read more about these services in `vignette("embed")`. Once you create an embed object, you can modify it with `use` functions: - start time: `use_start_time()` - formatting: `use_align()`, `use_rounded()` - responsiveness (for Bootstrap): `use_bs_responsive()` You can read more about these modifications in `vignette("modify")`. ## Examples To align the video horizontally within its container, `use_align()`: ```{r} embed_url("https://www.youtube.com/watch?v=uV4UpCq2azs") %>% use_align("center") ``` To add rounded corners, `use_rounded()`: ```{r} embed_youtube("lGTEUtS5H7I") %>% use_rounded() ``` If your HTML file uses Bootstrap, and want to make the size responsive to the width of the container, `use_bs_responsive()`: ```{r} embed_url("https://www.youtube.com/watch?v=H9KYQ_tnTtc") %>% use_bs_responsive() ``` For example this **does not** work in the R vignette, but it **does** work in the pkgdown site. ## Caveats Just because a service publishes a video, this does not mean that you can embed it. For example, this is an amazing Otis Redding performance: ```{r} # does not embed, but you can watch it at Vimeo embed_vimeo("45157591") ```
/scratch/gouwar.j/cran-all/cranData/vembedr/inst/doc/vembedr.Rmd
--- title: "Embed video" author: "Ian Lyttle" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Embed video} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) library("htmltools") library("fs") ``` ```{r} library("vembedr") ``` Using this package, you can embed videos into RMarkdown documents and Shiny apps for videos from: - [YouTube](https://developers.google.com/youtube/player_parameters) - [Vimeo](https://developer.vimeo.com/player/embedding) - [Box](https://developer.box.com/guides/embed/box-embed/#programmatically) - [Microsoft Stream](https://docs.microsoft.com/en-us/stream/portal-embed-video) The links above are associated with the embedding API for each of the services; these are the APIs wrapped by the `embed()` functions in this package. You can also embed the video using only the URL of the page your video is on, with `embed_url()`. To set the start time, or to change the formatting, check out the `use_*()` functions in `vignette("modify")`. ## Embded using URL Although a URL can be long and awkward, it will get the job done. If the URL is from one of the supported services, it should *just work*: ```{r} embed_url("https://www.youtube.com/watch?v=BD_n6ju9iRA") ``` If you would like to generate more-concise code using the URL, you can use the `suggest_embed()` function: ```{r} suggest_embed("https://www.youtube.com/watch?v=BD_n6ju9iRA") ``` ## Embed by service ### YouTube You can get your video's identifier by inspecting its URL at YouTube - you can use the short version, as well: ```{r} suggest_embed("https://youtu.be/JeaBNAXfHfQ") ``` The identifier is the last part of the URL. To embed this video: ```{r} embed_youtube("JeaBNAXfHfQ") ``` ### Vimeo For Vimeo, the identifier is also included in the standard URL: ```{r} suggest_embed("https://vimeo.com/238200347") ``` The Vimeo identifier is the path of the URL: ```{r} embed_vimeo("238200347") ``` ### Box To share a video on Box, the video file itself will have to be shared. From the Box web-interface, you can do this by clicking the **Share** button at the top-right corner of your file's web-page. Then create a **Share Link**: ```{r out.width="100%", echo=FALSE} knitr::include_graphics("figures/box-binford.png") ``` Then, you need to capture some information about the embed-link itself, either the URL or the `id`. Please note that you need to work with the "ugly" URL, not a custom URL: ```{r} suggest_embed("https://app.box.com/s/d75g9cr27s2jnx62b86idpgffzzxfdt2") ``` You can do the same thing using the `embed_box()` function and the `id`. The Box identifier is the last part of the path, in this case **`d75g9cr27s2jnx62b86idpgffzzxfdt2`**. ```{r} embed_box("d75g9cr27s2jnx62b86idpgffzzxfdt2") ``` If you are using a corporate instance of Box, and use the `embed_box()` function, you will also have to specify the `custom_domain`. For example, if your URL starts with `"https://acme.app.box.com"`, then your `custom_domain` is `"acme"`. ### Microsoft Stream Microsoft Stream is a service offered for use by (large) organizations so that they may share videos internally to their organization. As such, this functionality may have limited appeal. ```{r} suggest_embed( "https://web.microsoftstream.com/video/ae21b0ac-4a2b-41f4-b3fc-f1720dd20f48" ) ``` The identifier is the last part of the path of the URL, in this case **`ae21b0ac-4a2b-41f4-b3fc-f1720dd20f48`**. ```{r} embed_msstream("ae21b0ac-4a2b-41f4-b3fc-f1720dd20f48") %>% use_rounded() %>% use_start_time(10) ``` Because this video is internal to an organization, it will likely not play for you. ## Sample videos In case you need sample videos with which to experiment, this package has you covered: ```{r} rickroll_vimeo() ``` Also (mercifully, not displayed as it seems no-longer embeddable): ```{r eval=FALSE} rickroll_youtube() ```
/scratch/gouwar.j/cran-all/cranData/vembedr/vignettes/embed.Rmd
--- title: "Modify embedding" author: "Ian Lyttle" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Modify embedding} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r} library("vembedr") ``` This article deals with modifications you can make to videos that you embed. These include: - start time - horizontal alignment - rounded corners - responsive sizing for [Bootstrap](https://getbootstrap.com/docs/3.4/components/#responsive-embed) These modifications can be made independently of each other, and can be composed: ```{r} embed_youtube("2WoDQBhJCVQ") %>% use_start_time("44s") %>% use_align("center") %>% use_rounded(10) ``` To embed videos from variety of services, please read `vignette("embed")`. ## Start time To specify a starting time for a video, you can `use_start_time()`: ```{r} embed_youtube(id = "8SGif63VW6E") %>% use_start_time("4m12s") ``` Thanks to [Aurélien Ginolhac](https://github.com/ginolhac) for suggesting this video using this start-time. The `use_start_time()` function treats these all of these inputs equivalently: - `"0h1m0s"`, `"0h01m00s"`, `"0h1m"` - `"1m0s"`, `"1m"` - `"60s"`, `60` This function works with all of the services except for Box. ## Horizontal alignment You can `use_align()` to specify the horizontal alignment: ```{r} embed_vimeo("10022924") %>% use_align("center") ``` Possible values for `align` are: `"left"` (default), `"right"`, `"center"`, `"justified"`. ## Rounded corners You can `use_rounded()` to specify the `radius` (in pixels) of the rounds: ```{r} embed_youtube("lan-UQfN0zs") %>% use_rounded(radius = 10) ``` This seems to work better in the browser than in the RStudio viewer. ## Responsive sizing If you are using Bootstrap, you can `use_bs_responsive()` to make your video responsive to the width of its container: ```{r} embed_youtube("FkBQc0gQkQI") %>% use_bs_responsive() ``` It has no arguments, but it uses the `ratio` provided to the `embed()` function: ```{r} embed_youtube("KvX8MijgeW8", ratio = "4by3") %>% use_bs_responsive() ``` The `ratio` defaults to `"16by9"`, but it can also be `"4by3"`. If you are viewing this as this HTML vignette provided by R's help, you will not see responsiveness as it does not use Bootstrap. If you are viewing this at [this package's pkgdown site](https://ijlyttle.github.io/vembedr/articles/modify.html), you will see the responsiveness.
/scratch/gouwar.j/cran-all/cranData/vembedr/vignettes/modify.Rmd
--- title: "vembedr" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{vembedr} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library("vembedr") ``` Embedding and customizing videos in RMarkdown documents might seem like a complex task. It need not be. ```{r} embed_url("https://www.youtube.com/watch?v=_fZQQ7o16yQ") %>% use_start_time("1m32") ``` Even the most seemingly-intractable issues can be brought into focus with a clarifying framework. Above, we used an `embed` function followed by a `use` function. Using `embed_url()`, you can create an embed object for any of these supported services, or you can use an `id` with a service-specific embed function: - YouTube: `embed_youtube()` - Vimeo: `embed_vimeo()` - Box: `embed_box()` - Microsoft Stream: `embed_msstream()` You can read more about these services in `vignette("embed")`. Once you create an embed object, you can modify it with `use` functions: - start time: `use_start_time()` - formatting: `use_align()`, `use_rounded()` - responsiveness (for Bootstrap): `use_bs_responsive()` You can read more about these modifications in `vignette("modify")`. ## Examples To align the video horizontally within its container, `use_align()`: ```{r} embed_url("https://www.youtube.com/watch?v=uV4UpCq2azs") %>% use_align("center") ``` To add rounded corners, `use_rounded()`: ```{r} embed_youtube("lGTEUtS5H7I") %>% use_rounded() ``` If your HTML file uses Bootstrap, and want to make the size responsive to the width of the container, `use_bs_responsive()`: ```{r} embed_url("https://www.youtube.com/watch?v=H9KYQ_tnTtc") %>% use_bs_responsive() ``` For example this **does not** work in the R vignette, but it **does** work in the pkgdown site. ## Caveats Just because a service publishes a video, this does not mean that you can embed it. For example, this is an amazing Otis Redding performance: ```{r} # does not embed, but you can watch it at Vimeo embed_vimeo("45157591") ```
/scratch/gouwar.j/cran-all/cranData/vembedr/vignettes/vembedr.Rmd
# Copyright (c) 2016 - 2024, Adrian Dusa # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, in whole or in part, are permitted provided that the # following conditions are met: # * Redistributions of enclosed data must cite this package according to # the citation("venn") command specific to this R package, along with the # appropriate weblink to the CRAN package "venn". # * Redistributions of enclosed data in other R packages must list package # "venn" as a hard dependency in the Imports: field. # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * The names of its contributors may NOT be used to endorse or promote # products derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL ADRIAN DUSA BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. `checkZone` <- function(from, zones, checkz, nofsets, ib, ellipse) { fromz <- ib[ib$s == nofsets & ib$v == as.numeric(ellipse) & ib$i == from, ] toz <- ib[ib$s == nofsets & ib$v == as.numeric(ellipse) & ib$i %in% zones[!checkz], ] toz <- toz[toz$b %in% fromz$b, , drop = FALSE] if (nrow(toz) > 0) { zs <- sort(unique(toz$i)) checkz[as.character(zs)] <- TRUE for (i in zs) { checkz <- checkz | Recall(i, zones, checkz, nofsets, ib, ellipse) } } return(checkz) }
/scratch/gouwar.j/cran-all/cranData/venn/R/checkZone.R