content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
|---|---|
#' Read, process and feature extraction of E4 data
#' @description Reads the raw ZIP file using `read_e4`,
#' performs analyses with `ibi_analysis` and `eda_analysis`.
#' @param zipfile zip file with e4 data to be read
#' @param tz timezone where data were recorded (default system timezone)
#' @return An object with processed data and analyses, object of class 'e4_analysis'.
#' @rdname read_and_process_e4
#' @importFrom utils write.csv2
#' @importFrom padr thicken
#' @importFrom dplyr all_of
#' @export
read_and_process_e4 <- function(zipfile, tz = Sys.timezone()){
data <- read_e4(zipfile, tz)
if(is.null(data)){
return(NULL)
} else {
flog.info("Raw data read and converted.")
process_e4(data)
}
}
# Join EDA binary classifier output to a dataset, based on rounded 5sec intervals.
# Rename 'label' to 'quality_flag'
join_eda_bin <- function(data, eda_bin){
if(nrow(data) == 0){
data$quality_flag <- integer(0)
return(data)
}
padr::thicken(data, interval = "5 sec") %>%
dplyr::left_join(eda_bin, by = c("DateTime_5_sec" = "id")) %>%
dplyr::select(-dplyr::all_of("DateTime_5_sec")) %>%
dplyr::rename(quality_flag = "label")
}
#' @rdname read_and_process_e4
#' @export
#' @param data object from read_e4 function
process_e4 <- function(data){
suppressMessages({
suppressWarnings({
ibi <- ibi_analysis(data$IBI)
})
})
flog.info("IBI data analyzed.")
eda_filt <- wearables::process_eda(data$EDA)
flog.info("EDA data filtered.")
eda_peaks <- find_peaks(eda_filt)
flog.info("Peak detection complete.")
eda_feat <- compute_features2(eda_filt)
flog.info("EDA Features computed")
eda_bin_pred <- predict_binary_classifier(eda_feat)
eda_mc_pred <- predict_multiclass_classifier(eda_feat)
flog.info("Model predictions generated, artifacts classified.")
# Add quality flags to data
eda_filt <- join_eda_bin(eda_filt, eda_bin_pred)
eda_peaks <- join_eda_bin(eda_peaks, eda_bin_pred)
# Time range of the data
r <- range(eda_filt$DateTime)
time_range <- as.numeric(difftime(r[2], r[1], units = "min"))
# Additional summaries
hr_summary <- list(
HR_mean = mean(data$HR$HR),
HR_median = median(data$HR$HR),
HR_min = min(data$HR$HR),
HR_max = max(data$HR$HR),
HR_sd = sd(data$HR$HR)
)
temp_summary <- list(
TEMP_mean = mean(data$TEMP$TEMP),
TEMP_median = median(data$TEMP$TEMP),
TEMP_min = min(data$TEMP$TEMP),
TEMP_max = max(data$TEMP$TEMP),
TEMP_sd = sd(data$TEMP$TEMP)
)
acc_summary <- list(
ACC_mean = mean(data$ACC$a),
ACC_median = median(data$ACC$a),
ACC_min = min(data$ACC$a),
ACC_max = max(data$ACC$a),
ACC_sd = sd(data$ACC$a)
)
eda_clean <- dplyr::filter(eda_filt, .data$quality_flag == 1)
if(nrow(eda_clean) > 0){
eda_summary <- list(
EDA_clean_mean = mean(eda_clean$EDA),
EDA_clean_median = median(eda_clean$EDA),
EDA_clean_min = min(eda_clean$EDA),
EDA_clean_max = max(eda_clean$EDA),
EDA_clean_sd = sd(eda_clean$EDA)
)
} else {
eda_summary <- list(
EDA_clean_mean = NA,
EDA_clean_median = NA,
EDA_clean_min = NA,
EDA_clean_max = NA,
EDA_clean_sd = NA
)
}
pks_clean <- dplyr::filter(eda_peaks, .data$quality_flag == 1)
if(nrow(eda_clean) > 0){
peaks_summary <- list(
peaks_clean_sum = nrow(pks_clean),
peaks_clean_per_min = nrow(pks_clean) / time_range,
peaks_clean_mean_auc = mean(pks_clean$AUC),
peaks_clean_mean_amp = mean(pks_clean$amp)
)
} else {
peaks_summary <- list(
peaks_clean_sum = 0,
peaks_clean_mean_auc = NA,
peaks_clean_mean_amp = NA
)
}
structure(list(
data = data,
ibi = ibi,
data_summary = list(
ACC = acc_summary,
TEMP = temp_summary,
HR = hr_summary,
EDA = eda_summary,
peaks = peaks_summary
),
eda_peaks = eda_peaks,
eda_bin = eda_bin_pred,
eda_mc = eda_mc_pred
),
class = "e4_analysis")
}
#' Output folder
#'
#' Create output folder for E4 analysis results
#'
#' @param obj e4 analysis object
#' @param out_path output folder
#' @export
create_e4_output_folder <- function(obj, out_path = "."){
stopifnot(inherits(obj, "e4_analysis"))
# read_e4 stored the zipname as an attribute
zipname <- basename(attr(obj$data, "zipfile"))
# Output goes to a folder with the zipfile name
out_folder <- file.path(out_path, zipname)
dir.create(out_folder)
return(invisible(out_folder))
}
#' Write CSV files of the output
#' @description Slow!
#' @param obj e4 analysis object
#' @param out_path output folder
#' @export
write_processed_e4 <- function(obj, out_path = "."){
stopifnot(inherits(obj, "e4_analysis"))
out_folder <- create_e4_output_folder(obj, out_path)
#write.csv(obj$data$ , file.path(out_folder, ...)
file_out <- function(data, name){
write.csv2(data, file.path(out_folder,name), row.names = FALSE)
}
file_out(obj$data$EDA, "EDA.csv")
file_out(obj$data$ACC, "ACC.csv")
file_out(obj$data$TEMP, "TEMP.csv")
file_out(obj$data$HR, "HR.csv")
file_out(obj$data$BVP, "BVP.csv")
file_out(obj$data$IBI, "IBI.csv")
ibi_a <- data.frame(
Time = obj$ibi$freq_analysis$Time,
HRV = obj$ibi$freq_analysis$HRV,
ULF = obj$ibi$freq_analysis$ULF,
VLF = obj$ibi$freq_analysis$VLF,
LF = obj$ibi$freq_analysis$LF,
HF = obj$ibi$freq_analysis$HF,
LFHF = obj$ibi$freq_analysis$LFHF
)
file_out(ibi_a, "IBI_FreqAnalysis.csv")
# Vector with summary variables
ibi_s <- c(obj$ibi$time_analysis, obj$ibi$summary$frequency, obj$ibi$summary$beats)
file_out(ibi_s, "IBI_SummaryPars.csv")
# EDA model predictions
file_out(obj$eda_bin, "EDA_binary_prediction.csv")
file_out(obj$eda_mc, "EDA_multiclass_prediction.csv")
}
|
/scratch/gouwar.j/cran-all/cranData/wearables/R/read_and_proces_e4.R
|
#' Read E4 data
#' @description Reads in E4 data as a list (with EDA, HR, Temp, ACC, BVP, IBI as dataframes), and prepends timecolumns
#' @details This function reads in a zipfile as exported by Empatica Connect. Then it extracts the zipfiles in a temporary folder
#' and unzips the csv files in the temporary folder.
#'
#' The EDA, HR, BVP, and TEMP csv files have a similar structure in which the
#' starting time of the recording is read from the first row of the file (in unix time). The frequency of the measurements is read from the
#' second row of the recording (in Hz). Subsequently, the raw data is read from row three onward.
#'
#' The ACC csv file contain the acceleration of the Empatica E4 on the three axes x,y and z. The first row contains the starting
#' time of the recording in unix time. The second row contains the frequency of the measurements in Hz.
#' Subsequently, the raw x, y, and z data is read from row three onward.
#'
#' The IBI file has a different structure, the starting time in unix is in the first row, first column.
#' The firs column contins the number of seconds past since the start of the recording. The number of seconds past since the
#' start of the recording represent a heartbeat as derived from the algorithms from the photo plethysmogrophy sensor. The
#' second column contains the duration of the interval from one heartbeat to the next heartbeat.
#'
#' ACC.csv = 32 Hz
#' BVP.csv = 64 Hz
#' EDA.csv = 4 HZ
#' HR.csv = 1 HZ
#' TEMP.csv = 4 Hz
#'
#' Please also see the info.txt file provided in the zip file for additional information.
#'
#' The function returns an object of class "e4_data" with a prepended datetime columns
#' that defaults to user timezone. The object contains a list with dataframes from the physiological signals.
#'
#' @param zipfile A zip file as exported by the instrument
#' @param tz The timezone used by the instrument (defaults to user timezone).
#' @examples
#' library(wearables)
#' #read_e4()
#' @export
#' @importFrom R.utils countLines
#' @importFrom stats setNames
#' @importFrom utils read.table
read_e4 <- function(zipfile = NULL,
tz = Sys.timezone()){
if(is.null(zipfile)){
stop("Please enter the ZIP file with E4 data.")
}
# Temp directory: clean before use
out_dir <- paste(sample(letters,15), collapse = "")
unlink(out_dir, recursive = TRUE)
# Clean temp directory on exit
on.exit(unlink(out_dir, recursive = TRUE))
# Unzip files to temp directory
unzip(zipfile, exdir = out_dir)
check <- check_datafiles_filled(out_dir)
if(!check){
warning(paste("One or more files in",zipfile,"is (nearly) empty."))
return(NULL)
}
# Standard datasets and filenames
datasets <- c("EDA","ACC","TEMP","HR","BVP")
fns <- file.path(out_dir, paste0(datasets, ".csv"))
# Get measurement frequency (on line 2)
get_hertz <- function(x){
read.csv(x, skip=1, nrow=1, header=FALSE)[[1]]
}
hertz <- lapply(fns, get_hertz)
names(hertz) <- datasets
# Get time start (from line 1)
get_timestart <- function(x){
read.csv(x, nrow=1, header=FALSE)[[1]]
}
timestart <- lapply(fns, get_timestart)
names(timestart) <- datasets
# Read all datasets
data <- lapply(fns, read.csv, header = FALSE, skip = 2)
names(data) <- datasets
for(d in datasets){
data[[d]] <- prepend_time_column(data[[d]], timestart[[d]], hertz[[d]],
tz = tz)
if(d %in% c("EDA","TEMP","HR","BVP")){
names(data[[d]]) <- c("DateTime", d)
} else if(d == "ACC"){
names(data[[d]]) <- c("DateTime", "x","y","z")
}
}
# Read IBI data separately (different format)
ibi_file <- file.path(out_dir, "IBI.csv")
ibi <- read.csv(ibi_file,
stringsAsFactors = FALSE,
header = FALSE, skip = 1)
ibi_timestart <- get_timestart(file.path(out_dir, "IBI.csv"))
timestart <- c(timestart, list(IBI = ibi_timestart))
ibi <- cbind(data.frame(DateTime = as_time(ibi_timestart, tz = tz) + ibi[[1]]),
seconds = ibi[[1]],
IBI = ibi[[2]])
data <- c(data, list(IBI = ibi))
# For ACC, add the geometric mean acceleration
data$ACC$a <- sqrt(data$ACC$x^2 + data$ACC$y^2 + data$ACC$z^2) / 64
# Is there a tags.csv file?
tag_file <- file.path(out_dir, "tags.csv")
if(file.exists(tag_file) && R.utils::countLines(tag_file) > 0){
data$tags <- stats::setNames(utils::read.table(tag_file), "DateTime")
data$tags$DateTime <- as_time(data$tags$DateTime,tz=tz)
} else {
data$tags <- NULL
}
# Return data, store name of original file in the attributes, which we can read with:
# attr(data, "zipfile")
structure(data,
class = "e4data",
zipfile = tools::file_path_sans_ext(zipfile),
tz = tz)
}
|
/scratch/gouwar.j/cran-all/cranData/wearables/R/read_e4.R
|
#' as_time
#' @description Converts Unix time to as.POSIXct
#' @param x takes a unixtime and converts to as.POSIXct
#' @param tz timezone is set to UTC
#' @export
# Convert time in seconds to a POSIXct.
as_time <- function(x, tz = "UTC"){
as.POSIXct(x, origin = "1970-1-1", tz = tz)
}
#' prepend_time_column
#' @description Column binds a time_column to the dataframe
#' @param data dataframe
#' @param timestart the start of the recording
#' @param hertz hertz in which the E4 data was recorded
#' @param tz The timezone, defaults to user timezone
#' @export
#' @importFrom lubridate with_tz
prepend_time_column <- function(data, timestart, hertz, tz = Sys.timezone()){
datetime <- as_time(timestart) + (1/hertz) * (1:nrow(data) - 1)
datetime <- with_tz(datetime, tz)
out <- cbind(data.frame(DateTime = datetime), data)
return(out)
}
#' pad_e4
#' @description function to combine several e4 files, and sets the length of the x-axis
#' @param x index of dataframe
#' @export
#' @importFrom dplyr left_join
#' @importFrom stats median
#' @importFrom utils unzip
#' @importFrom utils read.csv
pad_e4 <- function(x){
interval <- as.numeric(median(diff(x$DateTime)))
out <- data.frame(DateTime = seq(from = min(x$DateTime),
to = max(x$DateTime),
by = interval)
)
left_join(out, x, by = "DateTime")
}
# Are all provided data files filled?
# Returns FALSE if one or more files have 1 or 0 lines of data.
check_datafiles_filled <- function(path){
datasets <- c("EDA","ACC","TEMP","HR","BVP","IBI")
fns <- file.path(path, paste0(datasets, ".csv"))
nrows <- sapply(fns, R.utils::countLines)
all(nrows > 1)
}
|
/scratch/gouwar.j/cran-all/cranData/wearables/R/utils.R
|
#' Un-weighted Interaction Weather Indices
#' @description Converts the weekly interaction of two weather variable into yearly weighted interaction weather indices
#' @param y A vector of yearly yield data for t years
#' @param weatherp1 Weekly weather data for t years as vector of first weather variable(total observations= number of years*number of weeks in each year)
#' @param weatherp2 Weekly weather data for t years as vector of second weather variable(total observations= number of years*number of weeks in each year)
#'
#' @return A vector of interaction weather indices
#' @export
#' @references Jain, R. C., Agrawal, R., & Jha, M. P. (1980). Effect of climatic variables on rice yield and its forecast. MAUSAM, 31(4), 591-596.
#' @examples
#' data(Burdwanweather) #Weekly weather data for the rice growing season in Burdwan
#' data(Burdwanriceyield) #Yearly Yield data of rice in Burdwan
#' i.uwwi.maxmintem<-i.uwwi(Burdwanriceyield$burdwan,Burdwanweather$Max.Temperature,
#' Burdwanweather$Min.Temperature)
#' i.uwwi.maxmintem
i.uwwi=function(y,weatherp1,weatherp2){
t=1:length(y)
week=1:(length(weatherp1)/length(t))
wp1=data.frame(matrix(weatherp1,nrow=length(y),byrow=T))
colnames(wp1)=1:length(week)
wp2=data.frame(matrix(weatherp2,nrow=length(y),byrow=T))
colnames(wp2)=1:length(week)
xx=wp1*wp2
detrended.y=(y-(lm(y~t)$fitted))
cor(xx[,1:length(week)],detrended.y)
rxx=cor(xx[,1:length(week)],detrended.y)
rxxmat=matrix(rxx[,1])
xxmat=as.matrix(xx)
i.uwwi=as.vector((t(rxxmat^0)%*%t(xxmat))/sum(rxx^0))
return(i.uwwi)
}
|
/scratch/gouwar.j/cran-all/cranData/weatherindices/R/unweightedinteractionweatherindices.R
|
#' Un-weighted Weather Indices
#' @description Converts the weekly weather data into yearly un-weighted weather indices(simply averaged)
#' @param y A vector of yearly yield data for t years
#' @param weatherp Weekly weather data for t years as vector (total observations= number of years*number of weeks in each year)
#'
#'
#' @return A vector of weather indices
#' @export
#' @references Jain, R. C., Agrawal, R., & Jha, M. P. (1980). Effect of climatic variables on rice yield and its forecast. MAUSAM, 31(4), 591-596.
#' @examples
#' data(Burdwanweather) #Weekly weather data for the rice growing season in Burdwan
#' data(Burdwanriceyield) #Yearly Yield data of rice in Burdwan
#' wwi.maxtem<-wwi(Burdwanriceyield$burdwan,Burdwanweather$Max.Temperature)
#' wwi.maxtem
uwwi=function(y,weatherp){
t=1:length(y)
week=1:(length(weatherp)/length(t))
wp1=data.frame(matrix(weatherp,nrow=length(y),byrow=T))
colnames(wp1)=1:length(week)
detrended.y=(y-(lm(y~t)$fitted))
cor(wp1[,1],detrended.y)
rwp1=cor(wp1[,1:length(week)],detrended.y)
rwp1mat=matrix(rwp1[,1])
wp1mat=as.matrix(wp1)
uwwi=as.vector((t(rwp1mat^0)%*%t(wp1mat))/sum(rwp1^0))
return(uwwi)
}
|
/scratch/gouwar.j/cran-all/cranData/weatherindices/R/unweightedweatherindices.R
|
#' Weekly weather data for the rice growing season in Burdwan district of West Bengal, India over 39 years
#'
#' Contains the date, standard meteorological week, week number and four weather variables
#'
#' @format A data frame with 741 rows of 7 variables
#' \describe{
#' \item{Date}{starting date of data}
#' \item{SMW}{Standard Meteorological Week}
#' \item{Week}{week number of crop growing season}
#' \item{Max.Temperature}{Daily Maximum temperature data averaged over week}
#' \item{Min.Temperature}{Daily Minimum temperature data averaged over week}
#' \item{Precipitation}{Daily Rainfall data summed over week}
#' \item{Relative.Humidity}{Daily Relative.Humidity data averaged over week}
#' }
#'
#' @source {NASA Power Data Access Viewer(https://power.larc.nasa.gov/data-access-viewer/)}
#' @examples
#' data(Burdwanweather)
"Burdwanweather"
|
/scratch/gouwar.j/cran-all/cranData/weatherindices/R/weatherdata.R
|
#' Weighted Interaction Weather Indices
#' @description Converts the weekly interaction of two weather variable into yearly weighted interaction weather indices with weights being the correlation coefficient between weekly weather data over the years and crop yield over the years
#' @param y A vector of yearly yield data for t years
#' @param weatherp1 Weekly weather data for t years as vector for first weather variable(total observations= number of years*number of weeks in each year)
#' @param weatherp2 Weekly weather data for t years as vector for second weather variable(total observations= number of years*number of weeks in each year)
#'
#' @return A vector of interaction weather indices
#' @export
#' @references Jain, R. C., Agrawal, R., & Jha, M. P. (1980). Effect of climatic variables on rice yield and its forecast. MAUSAM, 31(4), 591-596.
#' @examples
#' data(Burdwanweather) #Weekly weather data for the rice growing season in Burdwan
#' data(Burdwanriceyield) #Yearly Yield data of rice in Burdwan
#' i.wwi.maxmintem<-i.wwi(Burdwanriceyield$burdwan,Burdwanweather$Max.Temperature,
#' Burdwanweather$Min.Temperature)
#' i.wwi.maxmintem
i.wwi=function(y,weatherp1,weatherp2){
t=1:length(y)
week=1:(length(weatherp1)/length(t))
wp1=data.frame(matrix(weatherp1,nrow=length(y),byrow=T))
colnames(wp1)=1:length(week)
wp2=data.frame(matrix(weatherp2,nrow=length(y),byrow=T))
colnames(wp2)=1:length(week)
xx=wp1*wp2
detrended.y=(y-(lm(y~t)$fitted))
cor(xx[,1:length(week)],detrended.y)
rxx=cor(xx[,1:length(week)],detrended.y)
rxxmat=matrix(rxx[,1])
xxmat=as.matrix(xx)
i.wwi=as.vector((t(rxxmat)%*%t(xxmat))/sum(rxx))
return(i.wwi)
}
|
/scratch/gouwar.j/cran-all/cranData/weatherindices/R/weightedinteractionweatherindices.R
|
#' Weighted Weather Indices
#' @description Converts the weekly weather data into yearly weighted weather indices with weights being the correlation coefficient between weekly weather data over the years and crop yield over the years
#' @param y A vector of yearly yield data for t years
#' @param weatherp Weekly weather data for t years as vector (total observations= number of years*number of weeks in each year)
#'
#'
#' @return A vector of weather indices
#' @import stats
#' @export
#' @references Jain, R. C., Agrawal, R., & Jha, M. P. (1980). Effect of climatic variables on rice yield and its forecast. MAUSAM, 31(4), 591-596.
#' @examples
#' data(Burdwanweather) #Weekly weather data for the rice growing season in Burdwan
#' data(Burdwanriceyield) #Yearly Yield data of rice in Burdwan
#' wwi.maxtem<-wwi(Burdwanriceyield$burdwan,Burdwanweather$Max.Temperature)
#' wwi.maxtem
wwi=function(y,weatherp){
t=1:length(y)
week=1:(length(weatherp)/length(t))
wp1=data.frame(matrix(weatherp,nrow=length(y),byrow=T))
colnames(wp1)=1:length(week)
detrended.y=(y-(lm(y~t)$fitted))
cor(wp1[,1],detrended.y)
rwp1=cor(wp1[,1:length(week)],detrended.y)
rwp1mat=matrix(rwp1[,1])
wp1mat=as.matrix(wp1)
wwi=as.vector((t(rwp1mat)%*%t(wp1mat))/sum(rwp1))
return(wwi)
}
|
/scratch/gouwar.j/cran-all/cranData/weatherindices/R/weightedweatherindices.R
|
#' Yearly Yield data of rice in Burdwan district of West Bengal, India over 39 years
#'
#' Contains the Years and yield data in Tonnes per hectare
#'
#' @format A data frame with 39 rows of 2 variables
#' \describe{
#' \item{Year}{starting year of data}
#' \item{burdwan}{rice yield data of burdwan district}
#' }
#'
#' @source {Bureau of Applied Economics and Statistics (BAES), Department of Planning, Statistics and Programme Monitoring (PSPM), Government of West Bengal and Area and Production Statistics portal (https://aps.dac.gov.in/APY/Public_Report1.aspx) of Ministry of Agriculture and Farmers Welfare, Government of India. }
#' @examples
#' data(Burdwanriceyield)
"Burdwanriceyield"
|
/scratch/gouwar.j/cran-all/cranData/weatherindices/R/yielddata.R
|
#' Weather in Lyon, France
#'
#' Daily values of mean temperature (Celsius) and mean dew point temperature
#' (Celsius) for the week of June 18, 2000, in Lyon, France.
#'
#' @source \href{http://www.wunderground.com/}{Weather Underground}
#'
#' @format A data frame with columns:
#' \describe{
#' \item{Date}{Date of weather observation}
#' \item{TemperatureC}{Daily mean temperature in Celsius}
#' \item{DewpointC}{Daily mean dewpoint temperature in Celsius}
#' }
"lyon"
#' Weather in New Haven, CT
#'
#' Daily values of mean temperature (Fahrenheit) and mean relative humidity
#' (\%) for the week of October 19, 2008, in New Haven, CT.
#'
#' @source \href{http://www.wunderground.com/}{Weather Underground}
#'
#' @format A data frame with columns:
#' \describe{
#' \item{Date}{Date of weather observation}
#' \item{TemperatureF}{Daily mean temperature in Fahrenheit}
#' \item{Relative.Humidity}{Daily relative humidity in \%}
#' }
"newhaven"
#' Weather in Norfolk, VA
#'
#' Daily values of mean temperature (Fahrenheit) and mean dew point
#' temperature (Fahrenheit) for the week of March 12, 2006, in Norfolk, VA.
#'
#' @source \href{http://www.wunderground.com/}{Weather Underground}
#'
#' @format A data frame with columns:
#' \describe{
#' \item{Date}{Date of weather observation}
#' \item{TemperatureF}{Daily mean temperature in Fahrenheit}
#' \item{DewpointF}{Daily mean dewpoint temperature in Fahrenheit}
#' }
"norfolk"
#' Weather in Suffolk, VA
#'
#' Daily values of mean temperature (Fahrenheit) and mean relative humidity
#' (\%) for the week of July 12, 1998, in Suffolk, VA.
#'
#' @source \href{http://www.wunderground.com/}{Weather Underground}
#'
#' @format A data frame with columns:
#' \describe{
#' \item{Date}{Date of weather observation}
#' \item{TemperatureF}{Daily mean temperature in Fahrenheit}
#' \item{Relative.Humidity}{Daily relative humidity in \%}
#' }
"suffolk"
#' Weather in Fort Collins, CO
#'
#' A dataset containing daily values of mean temperature (Fahrenheit) and mean
#' wind speed (in knots) for the week of October 11, 2015, in Fort
#' Collins, CO.
#'
#' @source \href{http://www.wunderground.com}{Weather Underground}
#'
#' @format A data frame with 7 rows and 3 variables:
#' \describe{
#' \item{date}{Date of weather observation}
#' \item{TemperatureF}{Daily mean temperature in Fahrenheit}
#' \item{knots}{Daily mean wind speed in knots}
#' }
"foco"
#' Weather in Beijing, China
#'
#' A dataset containing daily values of mean temperature (Fahrenheit) and mean
#' wind speed (in miles per hour, meters per second, feet per seconds, and
#' kilometers per hour) for the week of January 10, 2015, in Beijing, China.
#'
#' @source \href{http://www.wunderground.com}{Weather Underground}
#'
#' @format A data frame with 7 rows and 3 variables:
#' \describe{
#' \item{date}{Date of weather observation}
#' \item{TemperatureF}{Daily mean temperature in Fahrenheit}
#' \item{MPH}{Daily mean wind speed in miles per hour}
#' \item{mps}{Daily mean wind speed in meters per second}
#' \item{ftps}{Daily mean wind speed in feet per second}
#' \item{kmph}{Daily mean wind speed in kilometers per hour}
#' }
"beijing"
#' Weather in Los Angeles, CA
#'
#' Daily values of mean temperature (Kelvin) and mean dew point
#' temperature (Kelvin) for the week of December 19, 2010, in Los Angeles, CA.
#'
#' @source \href{http://www.wunderground.com/}{Weather Underground}
#'
#' @format A data frame 7 rows and 3 variables:
#' \describe{
#' \item{date}{Date of weather observation}
#' \item{TemperatureK}{Daily mean temperature in Kelvin}
#' \item{DewpointK}{Daily mean dewpoint temperature in Kelvin}
#' }
"angeles"
#' Weather in San Jose, Costa Rica
#'
#' Daily values of mean temperature (Fahrenheit) and mean wind speed (miles per
#' hour) for the week of August 02, 2015, in San Jose, Costa Rica.
#'
#' @source \href{http://www.wunderground.com/}{Weather Underground}
#'
#' @format A data frame 7 rows and 3 variables:
#' \describe{
#' \item{date}{Date of weather observation}
#' \item{TemperatureF}{Daily mean temperature in Fahrenheit}
#' \item{mph}{Daily mean wind speed in miles per hour}
#' }
"puravida"
#' Precipitation in Breckenridge, CO
#'
#' Daily values of precipitation (inches) for the week of June 28, 2015, in
#' Breckenridge, CO.
#'
#' @source \href{http://www.wunderground.com/}{Weather Underground}
#'
#' @format A data frame 7 rows and 2 variables:
#' \describe{
#' \item{date}{Date of weather observation}
#' \item{Precip.in}{Daily precipitation in inches}
#' }
"breck"
#' Precipitation in Loveland, CO
#'
#' Daily values of precipitation (millimeters) for the week of September 8,
#' 2013, in Loveland, CO.
#'
#' @source \href{http://www.wunderground.com/}{Weather Underground}
#'
#' @format A data frame 7 rows and 2 variables:
#' \describe{
#' \item{date}{Date of weather observation}
#' \item{Precip.mm}{Daily precipitation in millimeters}
#' }
"loveland"
|
/scratch/gouwar.j/cran-all/cranData/weathermetrics/R/data.R
|
#' Calculate heat index.
#'
#' \code{heat.index} creates a numeric vector of heat index values from
#' numeric vectors of air temperature and either relative humidity or
#' dew point temperature.
#'
#' @param t Numeric vector of air temperatures.
#' @param dp Numeric vector of dew point temperatures.
#' @param rh Numeric vector of relative humidity (in \%).
#' @param temperature.metric Character string indicating the temperature
#' metric of air temperature and dew point temperature. Possible values
#' are 'fahrenheit' or 'celsius'.
#' @param output.metric Character string indicating the metric into which
#' heat index should be calculated. Possible values are 'fahrenheit' or
#' 'celsius'.
#' @param round Integer indicating the number of decimal places to
#' round converted value.
#'
#' @details Include air temperature (\code{t}) and either dew point
#' temperature (\code{dp}) or relative humdity (\code{rh}). You cannot
#' specify both dew point temperature and relative humidity-- this will
#' return an error. Heat index is calculated as \code{NA} when impossible
#' values of dew point temperature or humidity are input (e.g., humidity
#' above 100\% or below 0\%, dew point temperature above air temperature).
#'
#' @return A numeric vector of heat index values in the metric specified
#' by \code{output.metric}. (If \code{output.metric} is not specified,
#' heat index will be returned in the same metric in which air
#' temperature was input, specified by \code{temperature.metric}.)
#'
#' @note Equations are from the source code for the US National Weather
#' Service's
#' \href{http://www.wpc.ncep.noaa.gov/html/heatindex.shtml}{online heat index calculator}.
#'
#' @author
#' Brooke Anderson \email{brooke.anderson@@colostate.edu},
#' Roger Peng \email{rdpeng@@gmail.com}
#'
#' @references
#' Anderson GB, Bell ML, Peng RD. 2013. Methods to calculate the heat index
#' as an exposure metric in environmental health research.
#' Environmental Health Perspectives 121(10):1111-1119.
#'
#' National Weather Service Hydrometeorological Prediction
#' Center Web Team. Heat Index Calculator. 30 Jan 2015.
#' \url{http://www.wpc.ncep.noaa.gov/html/heatindex.shtml}.
#' Accessed 18 Dec 2015.
#'
#' Rothfusz L. 1990. The heat index (or, more than you ever wanted to know
#' about heat index) (Technical Attachment SR 90-23). Fort Worth:
#' Scientific Services Division, National Weather Service.
#'
#' R. Steadman, 1979. The assessment of sultriness. Part I: A
#' temperature-humidity index based on human physiology and clothing
#' science. Journal of Applied Meteorology, 18(7):861--873.
#'
#' @examples # Calculate heat index from temperature (in Fahrenheit)
#'# and relative humidity.
#'
#' data(suffolk)
#'suffolk$heat.index <- heat.index(t = suffolk$TemperatureF,
#' rh = suffolk$Relative.Humidity)
#'suffolk
#'
#'# Calculate heat index (in Celsius) from temperature (in
#'# Celsius) and dew point temperature (in Celsius).
#'
#'data(lyon)
#'lyon$heat.index <- heat.index(t = lyon$TemperatureC,
#' dp = lyon$DewpointC,
#' temperature.metric = 'celsius',
#' output.metric = 'celsius')
#'lyon
#'
#' @export
heat.index <-
function (t = NA, dp = c(), rh = c(), temperature.metric = "fahrenheit",
output.metric = NULL, round = 0)
{
if(length(output.metric) == 0){
output.metric <- temperature.metric
}
if (length(dp) == 0 & length(rh) == 0) {
stop("You must give values for either dew point temperature ('dp') or relative humidity ('rh').")
}
else if (length(dp) > 0 & length(rh) > 0) {
stop("You can give values for either dew point temperature ('dp') or relative humidity ('rh'), but you cannot specify both to this function.")
}
if (length(dp) != length(t) & length(rh) != length(t)) {
stop("The vectors for temperature ('t') and moisture (either relative humidity, 'rh', or dew point temperature, 'dp') must be the same length.")
}
if (length(dp) > length(rh)) {
rh <- dewpoint.to.humidity(t = t, dp = dp, temperature.metric = temperature.metric)
}
else if (length(rh[!is.na(rh) & (rh > 100 | rh < 0)]) > 0) {
rh[!is.na(rh) & (rh > 100 | rh < 0)] <- NA
warning("There were observations with an impossible values for relative humidity (below 0% or above 100%). For these observations, heat index was set to NA.")
}
if (temperature.metric == "celsius") {
t <- celsius.to.fahrenheit(t)
}
hi <- mapply(heat.index.algorithm, t = t, rh = rh)
if (output.metric == "celsius") {
hi <- fahrenheit.to.celsius(hi)
}
hi <- round(hi, digits = round)
return(hi)
}
#' Algorithm for heat.index function.
#'
#' \code{heat.index.algorithm} converts a numeric scalar of temperature
#' (in Fahrenheit) and a numeric scalar of relative humidity (in \%)
#' to heat index (in Fahrenheit). This function is not meant to be used
#' outside of the \code{\link{heat.index}} function.
#'
#' @param t Numeric scalar of air temperature, in Fahrenheit.
#' @param rh Numeric scalar of relative humidity, in \%.
#'
#' @details If an impossible value of relative humidity is given
#' (below 0\% or above 100\%), heat index is returned as \code{NA}.
#'
#' @return A numeric scalar of heat index, in Fahrenheit.
#'
#' @note Equations are from the source code for the US National Weather
#' Service's
#' \href{http://www.wpc.ncep.noaa.gov/html/heatindex.shtml}{online heat index calculator}.
#'
#' @author
#' Brooke Anderson \email{brooke.anderson@@colostate.edu},
#' Roger Peng \email{rdpeng@@gmail.com}
#'
#' @references
#' Anderson GB, Bell ML, Peng RD. 2013. Methods to calculate the heat index
#' as an exposure Metric in environmental health research.
#' Environmental Health Perspectives 121(10):1111-1119.
#'
#' National Weather Service Hydrometeorological Prediction
#' Center Web Team. Heat Index Calculator. 30 Jan 2015.
#' \url{http://www.wpc.ncep.noaa.gov/html/heatindex.shtml}.
#' Accessed 18 Dec 2015.
#'
#' Rothfusz L. 1990. The heat index (or, more than you ever wanted to know
#' about heat index) (Technical Attachment SR 90-23). Fort Worth:
#' Scientific Services Division, National Weather Service.
#'
#' R. Steadman, 1979. The assessment of sultriness. Part I: A
#' temperature-humidity index based on human physiology and clothing
#' science. Journal of Applied Meteorology, 18(7):861--873.
#'
#' @seealso \code{\link{heat.index}}
#'
#' @export
heat.index.algorithm <-
function (t = NA, rh = NA)
{
if (is.na(rh) | is.na(t)) {
hi <- NA
} else if (t <= 40) {
hi <- t
} else {
alpha <- 61 + ((t - 68) * 1.2) + (rh * 0.094)
hi <- 0.5*(alpha + t)
if (hi > 79) {
hi <- -42.379 + 2.04901523 * t + 10.14333127 * rh -
0.22475541 * t * rh - 6.83783 * 10^-3 * t^2 -
5.481717 * 10^-2 * rh^2 + 1.22874 * 10^-3 * t^2 *
rh + 8.5282 * 10^-4 * t * rh^2 - 1.99 * 10^-6 *
t^2 * rh^2
if (rh <= 13 & t >= 80 & t <= 112) {
adjustment1 <- (13 - rh)/4
adjustment2 <- sqrt((17 - abs(t - 95))/17)
total.adjustment <- adjustment1 * adjustment2
hi <- hi - total.adjustment
} else if (rh > 85 & t >= 80 & t <= 87) {
adjustment1 <- (rh - 85)/10
adjustment2 <- (87 - t)/5
total.adjustment <- adjustment1 * adjustment2
hi <- hi + total.adjustment
}
}
}
return(hi)
}
|
/scratch/gouwar.j/cran-all/cranData/weathermetrics/R/heat_index.R
|
#' Calculate relative humidity.
#'
#' \code{dewpoint.to.humidity} creates a numeric vector of relative humidity
#' from numerical vectors of air temperature and dew point temperature.
#'
#' @param dp Numeric vector of dew point temperatures.
#' @param t Numeric vector of air temperatures.
#' @param temperature.metric Character string indicating the temperature
#' metric of air temperature and dew point temperature. Possible values
#' are \code{fahrenheit} or \code{celsius}.
#'
#' @details Dew point temperature and temperature must be in the same
#' metric (i.e., either both in Celsius or both in Fahrenheit). If
#' necessary, use \code{\link{convert_temperature}} to convert before
#' using this function.
#'
#' @return A numeric vector of relative humidity (in \%)
#'
#' @note Equations are from the source code for the US National Weather
#' Service's
#' \href{http://www.wpc.ncep.noaa.gov/html/heatindex.shtml}{online heat index calculator}.
#'
#' @author
#' Brooke Anderson \email{brooke.anderson@@colostate.edu},
#' Roger Peng \email{rdpeng@@gmail.com}
#'
#' @references
#' National Weather Service Hydrometeorological Prediction
#' Center Web Team. Heat Index Calculator. 30 Jan 2015.
#' \url{http://www.wpc.ncep.noaa.gov/html/heatindex.shtml}.
#' Accessed 18 Dec 2015.
#'
#' @seealso \code{\link{humidity.to.dewpoint},
#' \link{fahrenheit.to.celsius},
#' \link{celsius.to.fahrenheit}},
#' \link{convert_temperature}
#'
#' @examples # Calculate relative humidity from air temperature and
#' # dew point temperature.
#'
#' data(lyon)
#' lyon$RH <- dewpoint.to.humidity(t = lyon$TemperatureC,
#' dp = lyon$DewpointC,
#' temperature.metric = 'celsius')
#' lyon
#'
#' @export
dewpoint.to.humidity <-
function (dp = NA, t = NA,
temperature.metric = "fahrenheit")
{
if (!(temperature.metric %in% c("celsius", "fahrenheit"))) {
stop("The 'temperature.metric' option can onnly by 'celsius' or 'fahrenheit'.")
}
if (length(dp) != length(t)) {
stop("The vectors for temperature('t') and dewpoint temperature ('dp') must have the same length.")
}
if (length(dp[dp > t & !is.na(dp) & !is.na(t)]) > 0) {
dp[dp > t] <- NA
warning("For some observations, dew point temperature was higher than temperature. Since dew point temperature cannot be higher than air temperature, relative humidty for these observations was set to 'NA'.")
}
if (temperature.metric == "fahrenheit") {
t <- fahrenheit.to.celsius(t)
dp <- fahrenheit.to.celsius(dp)
}
beta <- (112 - (0.1 * t) + dp)/(112 + (0.9 * t))
relative.humidity <- 100 * beta^8
return(relative.humidity)
}
#' Calculate dew point temperature.
#'
#' \code{humidity.to.dewpoint} creates a numeric vector of dew point
#' temperature from numeric vectors of air temperature and relative
#' humidity.
#'
#' @param rh Numeric vector of relative humidity (in \%).
#' @param t Numeric vector of air temperatures.
#' @param temperature.metric Character string indicating the temperature
#' metric of air temperature. Possible values are \code{fahrenheit} or
#' \code{celsius}.
#'
#' @details Dew point temperature will be calculated in the same metric as
#' the temperature vector (as specified by the \code{temperature.metric}
#' option). If you'd like dew point temperature in a different metric,
#' use the function \code{\link{celsius.to.fahrenheit}} or
#' \code{\link{fahrenheit.to.celsius}} on the output from this function.
#'
#' @return A numeric vector of dew point temperature, in the same metric
#' as the temperature vector (as specified by the \code{temperature.metric}
#' option).
#'
#' @note Equations are from the source code for the US National Weather
#' Service's
#' \href{http://www.wpc.ncep.noaa.gov/html/heatindex.shtml}{online heat index calculator}.
#'
#' @author
#' Brooke Anderson \email{brooke.anderson@@colostate.edu},
#' Roger Peng \email{rdpeng@@gmail.com}
#'
#' @references
#' National Weather Service Hydrometeorological Prediction
#' Center Web Team. Heat Index Calculator. 30 Jan 2015.
#' \url{http://www.wpc.ncep.noaa.gov/html/heatindex.shtml}.
#' Accessed 18 Dec 2015.
#'
#' @seealso \code{\link{dewpoint.to.humidity},
#' \link{fahrenheit.to.celsius},
#' \link{celsius.to.fahrenheit}}
#'
#' @examples # Calculate dew point temperature from relative humidity and
#' # air temperature.
#'
#' data(newhaven)
#' newhaven$DP <- humidity.to.dewpoint(t = newhaven$TemperatureF,
#' rh = newhaven$Relative.Humidity,
#' temperature.metric = 'fahrenheit')
#' newhaven
#'
#' @export
humidity.to.dewpoint <-
function (rh = NA, t = NA, temperature.metric = "fahrenheit")
{
if (!(temperature.metric %in% c("celsius", "fahrenheit"))) {
stop("The 'temperature.metric' option can onnly by 'celsius' or 'fahrenheit'.")
}
if (length(rh) != length(t)) {
stop("The vectors for temperature('t') and relative humidity ('rh') must have the same length.")
}
if (length(rh[!is.na(rh) & (rh < 0 | rh > 100)]) > 0) {
rh[!is.na(rh) & (rh < 0 | rh > 100)] <- NA
warning("For some observations, relative humidity was below 0% or above 100%. Since these values are impossible for relative humidity, dew point temperature for these observations was set to 'NA'.")
}
if (temperature.metric == "fahrenheit") {
t <- fahrenheit.to.celsius(t)
}
dewpoint <- (rh/100)^(1/8) * (112 + (0.9 * t)) - 112 + (0.1 * t)
if (temperature.metric == "fahrenheit") {
dewpoint <- celsius.to.fahrenheit(dewpoint)
}
return(dewpoint)
}
|
/scratch/gouwar.j/cran-all/cranData/weathermetrics/R/moisture_conversions.R
|
#' Convert between precipitation metrics
#'
#' This function allows you to convert among the following precipitation metrics:
#' inches, millimeters, and centimeters.
#'
#' @param precip A numerical vector of precipitation to be converted.
#' @param old_metric The metric from which you want to convert. Possible options
#' are:
#' \itemize{
#' \item \code{inches}: Inches
#' \item \code{mm}: Millimeters
#' \item \code{cm}: Centimeters
#' }
#' @inheritParams convert_temperature
#'
#' @return A numeric vector with precipitation converted to the metric specified
#' by the argument \code{new_metric}.
#'
#' @author
#' Joshua Ferreri \email{joshua.m.ferreri@@gmail.com},
#' Brooke Anderson \email{brooke.anderson@@colostate.edu}
#'
#' @examples
#'
#' data(breck)
#' breck$Precip.mm <- convert_precip(breck$Precip.in,
#' old_metric = "inches", new_metric = "mm", round = 2)
#' breck
#'
#' data(loveland)
#' loveland$Precip.in <- convert_precip(loveland$Precip.mm,
#' old_metric = "mm", new_metric = "inches", round = NULL)
#' loveland$Precip.cm <- convert_precip(loveland$Precip.mm,
#' old_metric = "mm", new_metric = "cm", round = 3)
#' loveland
#' @export
convert_precip <- function(precip, old_metric, new_metric, round = 2){
if(length(precip[precip < 0])){
precip[precip < 0] <- NA
warning(paste("Some of the observations in the data gave",
"negative precipitation. Since precipitation",
"cannot have a negative value, these",
"observations were set to 'NA'."))
}
if(old_metric == new_metric){
stop("`old_metric` and `new_metric` must be different.")
}
if(old_metric == "inches"){
out <- inches_to_metric(precip, unit = new_metric, round = round)
} else if (new_metric == "inches"){
out <- metric_to_inches(precip, unit.from = old_metric, round = round)
} else {
mid <- metric_to_inches(precip, unit.from = old_metric, round = NULL)
out <- inches_to_metric(mid, unit = new_metric, round = round)
}
return(out)
}
#' Convert from inches to standard metric units of measure for precipitation
#'
#' \code{inches_to_metric} creates a numeric vector of precipitation in
#' common metric units (millimeters or centimeters) from a numeric vector of
#' precipitation in inches.
#'
#' @param inches Numeric vector of precipitation (in inches)
#' @param unit Character specifying the metric precipitation unit besides inches.
#' Possible values are:
#' \itemize{
#' \item \code{mm}: Millimeters
#' \item \code{cm}: Centimeters
#' }
#' @inheritParams convert_temperature
#'
#' @return A numeric vector of precipitation (in specified metric unit)
#'
#' @note Equations are from the source code for the National Weather Service
#' Forecast Office \url{http://www.srh.noaa.gov/ama/?n=conversions}
#'
#' @author
#' Joshua Ferreri \email{joshua.m.ferreri@@gmail.com},
#' Brooke Anderson \email{brooke.anderson@@colostate.edu}
#'
#' @seealso \code{\link{metric_to_inches}}
#'
#' @references
#'\url{http://www.srh.noaa.gov/ama/?n=conversions}
#'
#' @examples
#' data(breck)
#' breck$Precip.mm <- inches_to_metric(breck$Precip.in,
#' unit = "mm",
#' round = 2)
#' breck
#'
#' @export
inches_to_metric <- function(inches, unit, round = 2) {
if(length(inches[inches < 0])){
inches[inches < 0] <- NA
warning(paste("Some of the observations in the data gave",
"negative precipitation. Since precipitation",
"cannot have a negative value, these",
"observations were set to 'NA'."))
}
if(unit == "mm"){
metric <- inches * 25.4
} else if(unit == "cm"){
metric <- inches * 2.54
} else{
stop("`unit` must be `mm` or `cm`")
}
if(!is.null(round)){
metric <- round(metric, digits = round)
}
return(metric)
}
#' Convert between standard metric units of measure for precipitation to inches
#'
#' \code{metric_to_inches} creates a numeric vector of precipitation measures in
#' inches from a numeric vector of precipitation in common metric units
#' (millimeters or centimeters).
#'
#' @param metric Numeric vector of precipitation (in millimeters or centimeters)
#' @param unit.from A character string with the current units of the
#' observations (i.e., the units from which you want to convert)
#' @inheritParams inches_to_metric
#' @inheritParams convert_temperature
#'
#' @return A numeric vector of precipitation in inches.
#'
#' @note Equations are from the source code for the National Weather Service
#' Forecast Office \url{http://www.srh.noaa.gov/ama/?n=conversions}
#'
#' @author
#' Joshua Ferreri \email{joshua.m.ferreri@@gmail.com},
#' Brooke Anderson \email{brooke.anderson@@colostate.edu}
#'
#' @seealso \code{\link{inches_to_metric}}
#'
#' @references
#'\url{http://www.srh.noaa.gov/ama/?n=conversions}
#'
#' @examples
#' data(loveland)
#' loveland$Precip.in <- metric_to_inches(loveland$Precip.mm,
#' unit.from = "mm",
#' round = 2)
#' loveland
#'
#' @export
metric_to_inches <- function(metric, unit.from, round = 2) {
if(length(metric[metric < 0])){
metric[metric < 0] <- NA
warning(paste("Some of the observations in the data gave",
"negative precipitation. Since precipitation",
"cannot have a negative value, these",
"observations were set to 'NA'."))
}
if(unit.from == "mm"){
inches <- metric / 25.4
} else if(unit.from == "cm"){
inches <- metric / 2.54
} else{
stop("`unit.from` must be `mm` or `cm`")
}
if(!is.null(round)){
inches <- round(inches, digits = round)
}
return(inches)
}
|
/scratch/gouwar.j/cran-all/cranData/weathermetrics/R/rainmeasure_conversion.R
|
#' Convert from one temperature metric to another
#'
#' This function allows you to convert a vector of temperature values between
#' Fahrenheit, Celsius, and degrees Kelvin.
#'
#' @param temperature A numeric vector of temperatures to be converted.
#' @param old_metric The metric from which you want to convert. Possible options are:
#' \itemize{
#' \item \code{fahrenheit}, \code{f}
#' \item \code{kelvin}, \code{k}
#' \item \code{celsius}, \code{c}
#' }
#' @param new_metric The metric to which you want to convert. The same options
#' are possible as for \code{old_metric}.
#' @param round An integer indicating the number of decimal places to
#' round the converted value.
#'
#' @return A numeric vector with temperature converted to the metric specified
#' by the argument \code{new_metric}.
#'
#' @author
#' #' Joshua Ferreri \email{joshua.m.ferreri@@gmail.com},
#' Brooke Anderson \email{brooke.anderson@@colostate.edu}
#'
#' @examples
#' data(lyon)
#' lyon$TemperatureF <- convert_temperature(lyon$TemperatureC,
#' old_metric = "c", new_metric = "f")
#' lyon
#'
#' data(norfolk)
#' norfolk$TempC <- convert_temperature(norfolk$TemperatureF,
#' old_metric = "f", new_metric = "c")
#' norfolk
#'
#' data(angeles)
#' angeles$TemperatureC <- convert_temperature(angeles$TemperatureK,
#' old_metric = "kelvin", new_metric = "celsius")
#' angeles
#'
#' @export
convert_temperature <- function(temperature, old_metric, new_metric,
round = 2){
possible_metrics <- c("fahrenheit", "celsius", "kelvin", "f", "c", "k")
if(!(old_metric %in% possible_metrics) |
!(new_metric %in% possible_metrics)){
stop(paste0("The arguments `old_metric` and `new_metric` can only ",
"have one of the following values: `",
paste(possible_metrics, collapse = "`, `"), "`"))
} else if (old_metric == new_metric){
stop("`old_metric` and `new_metric` must have different values.")
}
if(old_metric %in% c("fahrenheit", "f")){
if(new_metric %in% c("celsius", "c")){
out <- fahrenheit.to.celsius(temperature, round = round)
} else if(new_metric %in% c("kelvin", "k")){
out <- fahrenheit.to.kelvin(temperature, round = round)
}
} else if(old_metric %in% c("celsius", "c")){
if(new_metric %in% c("fahrenheit", "f")){
out <- celsius.to.fahrenheit(temperature, round = round)
} else if (new_metric %in% c("kelvin", "k")){
out <- celsius.to.kelvin(temperature, round = round)
}
} else { # Kelvin for old_metric
if(new_metric %in% c("fahrenheit", "f")){
out <- kelvin.to.fahrenheit(temperature, round = round)
} else if (new_metric %in% c("celsius", "c")){
out <- kelvin.to.celsius(temperature, round = round)
}
}
return(out)
}
#' Convert from Celsius to Fahrenheit.
#'
#' \code{celsius.to.fahrenheit} creates a numeric vector of temperatures in
#' Fahrenheit from a numeric vector of temperatures in Celsius.
#'
#' @param T.celsius Numeric vector of temperatures in Celsius.
#' @inheritParams convert_temperature
#'
#' @return A numeric vector of temperature values in Fahrenheit.
#'
#' @note Equations are from the source code for the US National Weather
#' Service's
#' \href{http://www.wpc.ncep.noaa.gov/html/heatindex.shtml}{online heat index calculator}.
#'
#' @author
#' Brooke Anderson \email{brooke.anderson@@colostate.edu},
#' Roger Peng \email{rdpeng@@gmail.com}
#'
#' @seealso \code{\link{fahrenheit.to.celsius}}
#'
#' @examples # Convert from Celsius to Fahrenheit.
#' data(lyon)
#' lyon$TemperatureF <- celsius.to.fahrenheit(lyon$TemperatureC)
#' lyon
#'
#' @export
celsius.to.fahrenheit <-
function (T.celsius, round = 2)
{
T.fahrenheit <- (9/5) * T.celsius + 32
T.fahrenheit <- round(T.fahrenheit, digits = round)
return(T.fahrenheit)
}
#' Convert from Fahrenheit to Celsius.
#'
#' \code{fahrenheit.to.celsius} creates a numeric vector of temperatures in
#' Celsius from a numeric vector of temperatures in Fahrenheit.
#'
#' @param T.fahrenheit Numeric vector of temperatures in Fahrenheit.
#' @inheritParams convert_temperature
#'
#' @return A numeric vector of temperature values in Celsius.
#'
#' @note Equations are from the source code for the US National Weather
#' Service's
#' \href{http://www.wpc.ncep.noaa.gov/html/heatindex.shtml}{online heat index calculator}.
#'
#' @author
#' Brooke Anderson \email{brooke.anderson@@colostate.edu},
#' Roger Peng \email{rdpeng@@gmail.com}
#'
#' @seealso \code{\link{celsius.to.fahrenheit}}
#'
#' @examples # Convert from Fahrenheit to Celsius.
#' data(norfolk)
#' norfolk$TempC <- fahrenheit.to.celsius(norfolk$TemperatureF)
#' norfolk
#'
#' @export
fahrenheit.to.celsius <-
function (T.fahrenheit, round = 2)
{
T.celsius <- (5/9) * (T.fahrenheit - 32)
T.celsius <- round(T.celsius, digits = round)
return(T.celsius)
}
#' Convert from Celsius to Kelvin.
#'
#' \code{celsius.to.kelvin} creates a numeric vector of temperatures in
#' Kelvin from a numeric vector of temperatures in Celsius.
#'
#' @param T.celsius Numeric vector of temperatures in Celsius.
#' @inheritParams convert_temperature
#'
#' @return A numeric vector of temperature values in Kelvin.
#'
#' @note Equations are from the source code for the National Oceanic and
#' Atmospheric Association's
#' \href{http://www.srh.noaa.gov/epz/?n=wxcalc_tempconvert}{online
#' temperature converter}.
#'
#' @author
#' Joshua Ferreri \email{joshua.m.ferreri@@gmail.com},
#' Brooke Anderson \email{brooke.anderson@@colostate.edu}
#'
#' @seealso \code{\link{kelvin.to.celsius}}
#'
#' @examples # Convert from Celsius to Kelvin.
#' data(lyon)
#' lyon$TemperatureK <- celsius.to.kelvin(lyon$TemperatureC)
#' lyon
#'
#' @export
celsius.to.kelvin <-
function (T.celsius, round = 2)
{
T.kelvin <- T.celsius + 273.15
T.kelvin <- round(T.kelvin, digits = round)
return(T.kelvin)
}
#' Convert from Kelvin to Celsius.
#'
#' \code{kelvin.to.celsius} creates a numeric vector of temperatures in
#' Celsius from a numeric vector of temperatures in Kelvin.
#'
#' @param T.kelvin Numeric vector of temperatures in Kelvin.
#' @inheritParams convert_temperature
#'
#' @return A numeric vector of temperature values in Celsius.
#'
#' @note Equations are from the source code for the National Oceanic and
#' Atmospheric Association's
#' \href{http://www.srh.noaa.gov/epz/?n=wxcalc_tempconvert}{online
#' temperature converter}.
#'
#' @author
#' Joshua Ferreri \email{joshua.m.ferreri@@gmail.com},
#' Brooke Anderson \email{brooke.anderson@@colostate.edu}
#'
#' @seealso \code{\link{celsius.to.kelvin}}
#'
#' @examples # Convert from Kelvin to Celsius.
#' data(angeles)
#' angeles$TemperatureC <- kelvin.to.celsius(angeles$TemperatureK)
#' angeles
#'
#' @export
kelvin.to.celsius <-
function (T.kelvin, round = 2)
{
T.celsius <- T.kelvin - 273.15
T.celsius <- round(T.celsius, digits = round)
return(T.celsius)
}
#' Convert from Fahrenheit to Kelvin.
#'
#' \code{fahrenheit.to.kelvin} creates a numeric vector of temperatures in
#' Kelvin from a numeric vector of temperatures in Fahrenheit.
#'
#' @param T.fahrenheit Numeric vector of temperatures in Fahrenheit.
#' @inheritParams convert_temperature
#'
#' @return A numeric vector of temperature values in Kelvin.
#'
#' @note Equations are from the source code for the National Oceanic and
#' Atmospheric Association's
#' \href{http://www.srh.noaa.gov/epz/?n=wxcalc_tempconvert}{online
#' temperature converter}.
#'
#' @author
#' #' Joshua Ferreri \email{joshua.m.ferreri@@gmail.com},
#' Brooke Anderson \email{brooke.anderson@@colostate.edu}
#'
#' @seealso \code{\link{kelvin.to.fahrenheit}}
#'
#' @examples # Convert from Fahrenheit to Kelvin.
#' data(norfolk)
#' norfolk$TempuratureK <- fahrenheit.to.kelvin(norfolk$TemperatureF)
#' norfolk
#'
#' @export
fahrenheit.to.kelvin <-
function (T.fahrenheit, round = 2)
{
T.kelvin <- (.5556 * (T.fahrenheit - 32)) + 273.15
T.kelvin <- round(T.kelvin, digits = round)
return(T.kelvin)
}
#' Convert from Kelvin to Fahrenheit.
#'
#' \code{kelvin.to.fahrenheit} creates a numeric vector of temperatures in
#' Fahrenheit from a numeric vector of temperatures in Kelvin.
#'
#' @param T.kelvin Numeric vector of temperatures in Kelvin.
#' @inheritParams convert_temperature
#'
#' @return A numeric vector of temperature values in Fahrenheit.
#'
#' @note Equations are from the source code for the National Oceanic and
#' Atmospheric Association's
#' \href{http://www.srh.noaa.gov/epz/?n=wxcalc_tempconvert}{online
#' temperature converter}.
#'
#' @author
#' Joshua Ferreri \email{joshua.m.ferreri@@gmail.com},
#' Brooke Anderson \email{brooke.anderson@@colostate.edu}
#'
#' @seealso \code{\link{fahrenheit.to.kelvin}}
#'
#' @examples # Convert from Kelvin to Fahrenheit.
#' data(angeles)
#' angeles$TemperatureF <- kelvin.to.fahrenheit(angeles$TemperatureK)
#' angeles
#'
#' @export
kelvin.to.fahrenheit <-
function (T.kelvin, round = 2)
{
T.fahrenheit <- (1.8 * (T.kelvin - 273.15)) + 32
T.fahrenheit <- round(T.fahrenheit, digits = round)
return(T.fahrenheit)
}
|
/scratch/gouwar.j/cran-all/cranData/weathermetrics/R/temperature_conversions.R
|
#' weathermetrics: Functions to convert between weather metrics
#'
#' The weathermetics package provides functions to convert between Celsius
#' and Fahrenheit, to convert between dew point temperature and relative
#' humidity, and to calculate heat index.
#'
#' @section weathermetrics functions:
#' This package includes the following functions to calculate vectors of
#' weather metrics: \code{\link{celsius.to.fahrenheit}},
#' \code{\link{fahrenheit.to.celsius}},
#' \code{\link{dewpoint.to.humidity}},
#' \code{\link{humidity.to.dewpoint}}, and
#' \code{\link{heat.index}}.
#'
#' @docType package
#' @name weathermetrics
#'
#' @author
#' Brooke Anderson \email{brooke.anderson@@colostate.edu},
#' Joshua Ferreri \email{joshua.m.ferreri@@gmail.com},
#' Roger Peng \email{rdpeng@@gmail.com}
#'
#' @references
#' Anderson GB, Bell ML, Peng RD. 2013. Methods to calculate the heat index
#' as an exposure Metric in environmental health research.
#' Environmental Health Perspectives 121(10):1111-1119.
#'
#' National Weather Service Hydrometeorological Prediction
#' Center Web Team. Heat Index Calculator. 30 Jan 2015.
#' \url{http://www.wpc.ncep.noaa.gov/html/heatindex.shtml}.
#' Accessed 18 Dec 2015.
NULL
|
/scratch/gouwar.j/cran-all/cranData/weathermetrics/R/weathermetrics.R
|
#' Convert between wind speed metrics
#'
#' This function allows you to convert among the following wind speed metrics:
#' knots, miles per hour, meters per second, feet per second, and kilometers per
#' hour.
#'
#' @param wind_speed A numerical vector of wind speeds to be converted.
#' @param old_metric The metric from which you want to convert. Possible options
#' are:
#' \itemize{
#' \item \code{knots}: Knots
#' \item \code{mph}: Miles per hour
#' \item \code{mps}: Meters per second
#' \item \code{ftps}: Feet per second
#' \item \code{kmph}: Kilometers per hour
#' }
#' @inheritParams convert_temperature
#'
#' @return A numeric vector with wind speed converted to the metric specified
#' by the argument \code{new_metric}.
#'
#' @author
#' Joshua Ferreri \email{joshua.m.ferreri@@gmail.com},
#' Brooke Anderson \email{brooke.anderson@@colostate.edu}
#'
#' @examples
#'
#' data(beijing)
#' beijing$knots <- convert_wind_speed(beijing$kmph,
#' old_metric = "kmph", new_metric = "knots")
#' beijing
#'
#' data(foco)
#' foco$mph <- convert_wind_speed(foco$knots, old_metric = "knots",
#' new_metric = "mph", round = 0)
#' foco$mph <- convert_wind_speed(foco$knots, old_metric = "knots",
#' new_metric = "mps", round = NULL)
#' foco$kmph <- convert_wind_speed(foco$mph, old_metric = "mph",
#' new_metric = "kmph")
#' foco
#'
#' @export
convert_wind_speed <- function(wind_speed, old_metric, new_metric, round = 1){
if(length(wind_speed[wind_speed < 0])){
wind_speed[wind_speed < 0] <- NA
warning(paste("Some of the observations in the data gave",
"negative wind speeds. Since wind speed",
"cannot have a negative value, these",
"observations were set to 'NA'."))
}
if(old_metric == new_metric){
stop("`old_metric` and `new_metric` must be different.")
}
if(old_metric == "knots"){
out <- knots_to_speed(wind_speed, unit = new_metric, round = round)
} else if (new_metric == "knots"){
out <- speed_to_knots(wind_speed, unit = old_metric, round = round)
} else {
mid <- speed_to_knots(wind_speed, unit = old_metric, round = NULL)
out <- knots_to_speed(mid, unit = new_metric, round = round)
}
return(out)
}
#' Convert between standard units of measure for wind speed
#'
#' \code{speed_to_knots} creates a numeric vector of speed in knots from a
#' numeric vector of speed in the specified unit.
#'
#' @param x Numeric vector of wind speeds, in units specified by \code{unit}
#' @param unit Character specifying the speed unit other than knots.
#' Possible values are:
#' \itemize{
#' \item \code{mph}: Miles per hour
#' \item \code{mps}: Meters per second
#' \item \code{ftps}: Feet per second
#' \item \code{kmph}: Kilometers per hour
#' }
#' @inheritParams convert_temperature
#'
#' @return A numeric vector of speeds (in knots)
#'
#' @note Equations are from the source code for the National Oceanic and
#' and Atmospheric Administration's
#' \href{http://www.srh.noaa.gov/epz/?n=wxcalc_windconvert}{online wind speed
#' converter}
#'
#' @author
#' Joshua Ferreri \email{joshua.m.ferreri@@gmail.com},
#' Brooke Anderson \email{brooke.anderson@@colostate.edu}
#'
#' @seealso \code{\link{knots_to_speed}}
#'
#' @references
#'\url{http://www.srh.noaa.gov/epz/?n=wxcalc_windconvert}
#'
#' @examples
#' data(beijing)
#' beijing$knots <- speed_to_knots(beijing$kmph, unit = "kmph", round = 2)
#' beijing
#'
#' @export
speed_to_knots <- function(x, unit, round = 1) {
if(length(x[x < 0])){
x[x < 0] <- NA
warning(paste("Some of the observations in the data gave",
"negative wind speeds. Since wind speed",
"cannot have a negative value, these",
"observations were set to 'NA'."))
}
if(unit == "mph"){
knots <- x * 0.8689762
} else if(unit == "mps"){
knots <- x * 1.9438445
} else if(unit == "ftps"){
knots = x * 0.5924838
} else if(unit == "kmph"){
knots = x * 0.539593
} else {
stop("Unit must be one of the specified units for wind
speed")
}
if(!is.null(round)){
knots <- round(knots, digits = round)
}
return(knots)
}
#' Convert from knots to standard units of wind speed
#'
#' \code{knots_to_speed} creates a numeric vector of speed, in units
#' specified by \code{unit}, from a numeric vector of speed in knots.
#'
#' @param knots Numeric vector of speeds in knots
#' @inheritParams speed_to_knots
#' @inheritParams convert_temperature
#'
#' @return A numeric vector of speeds (in the specified unit)
#'
#' @details Output will be in the speed units specified by \code{unit}.
#'
#' @note Equations are from the source code for the National Oceanic and
#' and Atmospheric Administration's
#' \href{http://www.srh.noaa.gov/epz/?n=wxcalc_windconvert}{online wind speed
#' converter}
#'
#' @author
#' Joshua Ferreri \email{joshua.m.ferreri@@gmail.com},
#' Brooke Anderson \email{brooke.anderson@@colostate.edu}
#'
#' @seealso \code{\link{speed_to_knots}}
#'
#' @references
#'\url{http://www.srh.noaa.gov/epz/?n=wxcalc_windconvert}
#'
#' @examples
#' data(foco)
#' foco$mph <- knots_to_speed(foco$knots, unit = "mph", round = 0)
#' foco$mps <- knots_to_speed(foco$knots, unit = "mps", round = NULL)
#' foco$ftps <- knots_to_speed(foco$knots, unit = "ftps")
#' foco$kmph <- knots_to_speed(foco$knots, unit = "kmph")
#' foco
#'
#' @export
knots_to_speed <- function(knots, unit, round = 1) {
if(length(knots[knots < 0])){
knots[knots < 0] <- NA
warning(paste("Some of the observations in the data gave",
"negative wind speeds. Since wind speed",
"cannot have a negative value, these",
"observations were set to 'NA'."))
}
if(unit == "mph"){
x <- knots * 1.1507794
} else if(unit == "mps"){
x <- knots * 0.5144444
} else if(unit == "ftps"){
x <- knots * 1.6878099
} else if(unit == "kmph"){
x <- knots * 1.85325
} else{
stop("Unit must be one of the specified units for wind
speed")
}
if(!is.null(round)){
x <- round(x, digits = round)
}
return(x)
}
|
/scratch/gouwar.j/cran-all/cranData/weathermetrics/R/wind_conversions.R
|
## ----echo = FALSE--------------------------------------------------------
library(weathermetrics)
## ------------------------------------------------------------------------
#Convert from degrees Celsius to degress Fahrenheit
data(lyon)
lyon$TemperatureF <- convert_temperature(lyon$TemperatureC,
old_metric = "celsius", new_metric = "fahrenheit")
lyon$DewpointF <- convert_temperature(lyon$DewpointC,
old_metric = "celsius", new_metric = "fahrenheit")
lyon
#Convert from degrees Fahrenheit to degrees Celsius
data(norfolk)
norfolk$TemperatureC <- convert_temperature(norfolk$TemperatureF,
old_metric = "f", new_metric = "c")
norfolk$DewpointC <- convert_temperature(norfolk$DewpointF,
old_metric = "f", new_metric = "c")
norfolk
#Convert from degrees Kelvin to degrees Celsius
data(angeles)
angeles$TemperatureC <- convert_temperature(angeles$TemperatureK,
old_metric = "kelvin", new_metric = "celsius")
angeles$DewpointC <- convert_temperature(angeles$DewpointK,
old_metric = "kelvin", new_metric = "celsius")
angeles
## ------------------------------------------------------------------------
data(lyon)
lyon$RH <- dewpoint.to.humidity(t = lyon$TemperatureC,
dp = lyon$DewpointC,
temperature.metric = "celsius")
lyon
## ------------------------------------------------------------------------
data(newhaven)
newhaven$DP <- humidity.to.dewpoint(t = newhaven$TemperatureF,
rh = newhaven$Relative.Humidity,
temperature.metric = "fahrenheit")
newhaven
## ------------------------------------------------------------------------
data(newhaven)
newhaven$DP <- humidity.to.dewpoint(t = newhaven$TemperatureF,
rh = newhaven$Relative.Humidity,
temperature.metric = "fahrenheit")
newhaven$DP_C <- convert_temperature(newhaven$DP, old_metric = "f", new_metric = "c")
newhaven
## ------------------------------------------------------------------------
data(suffolk)
suffolk$HI <- heat.index(t = suffolk$TemperatureF,
rh = suffolk$Relative.Humidity,
temperature.metric = "fahrenheit",
output.metric = "fahrenheit")
suffolk
## ------------------------------------------------------------------------
data(lyon)
lyon$HI_F <- heat.index(t = lyon$TemperatureC,
dp = lyon$DewpointC,
temperature.metric = "celsius",
output.metric = "fahrenheit")
lyon
## ------------------------------------------------------------------------
data(beijing)
beijing$knots <- convert_wind_speed(beijing$kmph,
old_metric = "kmph", new_metric = "knots")
beijing
data(foco)
foco$mph <- convert_wind_speed(foco$knots, old_metric = "knots",
new_metric = "mph", round = 0)
foco$mph <- convert_wind_speed(foco$knots, old_metric = "knots",
new_metric = "mps", round = NULL)
foco$kmph <- convert_wind_speed(foco$mph, old_metric = "mph",
new_metric = "kmph")
foco
## ------------------------------------------------------------------------
data(breck)
breck$Precip.mm <- convert_precip(breck$Precip.in,
old_metric = "inches", new_metric = "mm", round = 2)
breck
data(loveland)
loveland$Precip.in <- convert_precip(loveland$Precip.mm,
old_metric = "mm", new_metric = "inches", round = NULL)
loveland$Precip.cm <- convert_precip(loveland$Precip.mm,
old_metric = "mm", new_metric = "cm", round = 3)
loveland
## ------------------------------------------------------------------------
df <- data.frame(T = c(NA, 90, 85),
DP = c(80, NA, 70))
df$RH <- dewpoint.to.humidity(t = df$T, dp = df$DP,
temperature.metric = "fahrenheit")
df
## ------------------------------------------------------------------------
df <- data.frame(T = c(90, 90, 85),
DP = c(80, 95, 70))
df$heat.index <- heat.index(t = df$T, dp = df$DP,
temperature.metric = 'fahrenheit')
df
## ------------------------------------------------------------------------
data(suffolk)
suffolk$TempC <- convert_temperature(suffolk$TemperatureF,
old_metric = "f",
new_metric = "c",
round = 5)
suffolk$HI <- heat.index(t = suffolk$TemperatureF,
rh = suffolk$Relative.Humidity,
round = 3)
suffolk
|
/scratch/gouwar.j/cran-all/cranData/weathermetrics/inst/doc/weathermetrics.R
|
---
title: "`weathermetrics` package vignette"
author: "G. Brooke Anderson, Roger D. Peng, and Joshua M. Ferreri"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{weathermetrics}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
references:
- id: anderson2013heat
title: Methods to calculate the heat index as an exposure metric in environmental health research.
author:
- family: Anderson
given: G. Brooke
- family: Bell
given: Michelle L.
- family: Peng
given: Roger D.
container-title: Environmental Health Perspectives
volume: 121
URL: 'http://ehp.niehs.nih.gov/1206273/'
DOI: 10.1289/ehp.1206273
issued:
year: 2013
issue: 10
pages: 1111-1119
type: article-journal
---
```{r echo = FALSE}
library(weathermetrics)
```
## Package contents
The `weathermetrics` package provides the following functions to calculate or convert between several weather metrics:
Weather variable | Function | Input and / or output metric choices
-----------------|---------------------|----------------
Temperature | `convert_temperature` | `"kelvin"`, `"celsius"`, `"fahrenheit"`
Wind speed | `convert_wind_speed` | `"knots"`, `"mph"`, `"mps"`, `"ftps"`, `"kmph"`
Precipitation | `convert_precip` | `"inches"`, `"mm"`, `"cm"`
Dew point temperature | `humidity.to.dewpoint` | `"celsius"`, `"fahrenheit"`
Relative humidity | `dewpoint.to.humidity` | `"celsius"`, `"fahrenheit"`
Heat index | `heat.index` | `"celsius"`, `"fahrenheit"`
Algorithms for heat index and wind speed are adapted for R from the algorithms used by the United States National Weather Service's [online heat index calculator](http://www.wpc.ncep.noaa.gov/html/heatindex.shtml) (accessed December 18, 2015) and the National Oceanic and Atmospheric Administration's [online wind speed conversion](http://www.srh.noaa.gov/epz/?n=wxcalc_windconvert) (accessed February 22, 2016).
## Converting or calculating weather metrics
### Converting between temperature measurements
This package includes a function, `convert_temperature`, that allows you to convert between common temperature measures including degrees Celsius, Fahrenheit, and Kelvin. The following examples show the use of this function for three example datasets:
To convert between degrees Celsius, Fahrenheit, and Kelvin, use the `convert_temperature` function:
```{r}
#Convert from degrees Celsius to degress Fahrenheit
data(lyon)
lyon$TemperatureF <- convert_temperature(lyon$TemperatureC,
old_metric = "celsius", new_metric = "fahrenheit")
lyon$DewpointF <- convert_temperature(lyon$DewpointC,
old_metric = "celsius", new_metric = "fahrenheit")
lyon
#Convert from degrees Fahrenheit to degrees Celsius
data(norfolk)
norfolk$TemperatureC <- convert_temperature(norfolk$TemperatureF,
old_metric = "f", new_metric = "c")
norfolk$DewpointC <- convert_temperature(norfolk$DewpointF,
old_metric = "f", new_metric = "c")
norfolk
#Convert from degrees Kelvin to degrees Celsius
data(angeles)
angeles$TemperatureC <- convert_temperature(angeles$TemperatureK,
old_metric = "kelvin", new_metric = "celsius")
angeles$DewpointC <- convert_temperature(angeles$DewpointK,
old_metric = "kelvin", new_metric = "celsius")
angeles
```
You can specify whether air temperature and dew point temperature inputs are in degrees Celsius, Fahrenheit, or Kelvin using the `old_metric` and `new_metric` options (possible values are `'celsius'`, `'fahrenheit'`, `'kelvin'`, or `'c'`, `'f'`, and `'k'` for the same). The input for `old_metric` should be the temperature measure that you want to convert from, and the input for `new_metric` should be the temperature measure you wish to convert to.
The `convert_temperature` function is a wrapper function for a variety of individual temperature conversion functions, including: `celsius.to.fahrenheit`, `fahrenheit.to.celsius`, `celsius.to.kelvin`, `kelvin.to.celsius`, `fahrenheit.to.kelvin`, and `kelvin.to.fahrenheit` functions, which you can use individually if you would like.
### Calculating relative humidity and dew point temperature
The `weathermetrics` package includes two functions for converting between air temperature, dew point temperature, and relative humidity:
`dewpoint.to.humidity` and `humidity.to.dewpoint`.
For example, the `lyon` data set includes daily values of both air temperature (`lyon$TemperatureC`) and dew point temperature (`lyon$DewpointC`). Since this data set includes both air temperature and dew point temperature, you can calculate relative humidity using the `dewpoint.to.humidity` function:
```{r}
data(lyon)
lyon$RH <- dewpoint.to.humidity(t = lyon$TemperatureC,
dp = lyon$DewpointC,
temperature.metric = "celsius")
lyon
```
You should specify whether air temperature and dew point temperature inputs are in degrees Fahrenheit or Celsius using the `temperature.metric` argument (possible values are `'fahrenheit'` and `'celsius'`). If input values for temperature and dew point temperature are in different metrics (i.e., one is in degrees Fahrenheit and the other in degrees Celsius), you must convert one of the inputs using either `celsius.to.fahrenheit` or `fahrenheit.to.celsius` before you can input the values to the `dewpoint.to.humidity` function.
As an example of calculating dew point temperature, the `newhaven` data set gives daily values of air temperature in degrees Fahrenheit (`newhaven$TemperatureF`) and relative humidity in % (`newhaven$Relative.Humidity`). Since this data set includes values for both temperature and relative humidity, you can calculate dew point temperature using the `humidity.to.dewpoint` function:
```{r}
data(newhaven)
newhaven$DP <- humidity.to.dewpoint(t = newhaven$TemperatureF,
rh = newhaven$Relative.Humidity,
temperature.metric = "fahrenheit")
newhaven
```
Relative humidity must be input as %, and you must specify the metric of air temperature using the `temperature.metric` argument (possible values: `'fahrenheit'` or `'celsius'`). The dew point temperature will be calculated using the same metric as the air temperature input to the function. If you wish to get dew point temperature in a different metric than air temperature, you can use the `convert_temperature` function. For example:
```{r}
data(newhaven)
newhaven$DP <- humidity.to.dewpoint(t = newhaven$TemperatureF,
rh = newhaven$Relative.Humidity,
temperature.metric = "fahrenheit")
newhaven$DP_C <- convert_temperature(newhaven$DP, old_metric = "f", new_metric = "c")
newhaven
```
Calculations between air temperature, relative humidity, and dew point temperature are based on algorithms used by the United States National Weather Service's [online heat index calculator](http://www.wpc.ncep.noaa.gov/html/heatindex.shtml) (accessed December 18, 2015). These are approximations rather than exact conversions.
### Calculating heat index
The `weathermetrics` package includes a function, `heat.index`, that allows you to calculate a vector of heat index values from vectors of air temperature and either dew point temperature or relative humidity. For example, the `suffolk` data set gives daily values of air temperature in degrees Fahrenheit (`suffolk$TemperatureF`) and relative humidity in % (`suffolk$Relative.Humidity`) for Suffolk, VA, for the week of July 12, 1998. To calculate daily heat index values for this data set, use the `heat.index` function:
```{r}
data(suffolk)
suffolk$HI <- heat.index(t = suffolk$TemperatureF,
rh = suffolk$Relative.Humidity,
temperature.metric = "fahrenheit",
output.metric = "fahrenheit")
suffolk
```
You must specify whether the air temperature input to the function is in degrees Celsius or Fahrenheit using the `temperature.metric` option (possible values: `'fahrenheit'` or `'celsius'`). You can choose which metric for heat index output using using the `output.metric` option (the default is to give heat index in the same metric as the air temperature values input to the function).
As another example, the `lyon` data set gives daily values of air temperature (`lyon$TemperatureC`) and dew point temperature (`lyon$DewpointC`), both in degrees Celsius. You can use this data to calculate daily heat index values in degrees Fahrenheit using:
```{r}
data(lyon)
lyon$HI_F <- heat.index(t = lyon$TemperatureC,
dp = lyon$DewpointC,
temperature.metric = "celsius",
output.metric = "fahrenheit")
lyon
```
When calculating heat index from air temperature and dew point temperature, both must be input in the same metric (either degrees Fahrenheit or degrees Celsius). If this is not the case, you can use `convert_temperature` to convert one of the metrics before using `heat.index`.
The algorithm for calculating heat index is adapted for R
from the algorithms used by the United States National Weather Service's [online heat index calculator](http://www.wpc.ncep.noaa.gov/html/heatindex.shtml) (accessed December 18, 2015). Therefore, results should agree with results from the US National Weather Service online calculator. However, heat index is sometimes calculated using a simpler algorithm. Therefore, heat index values from the \texttt{heat.index} function will sometimes differ by one or two degrees compared to other heat index calculators or charts.
### Converting between units of wind speed
The `weathermetrics` package includes a function, `convert_wind_speed`, that allows you to convert wind speed values between several common units of wind speed: knots (`'knots'`), miles per hour(`'mph'`), meters per second (`'mps'`), feet per second (`'ftps'`), and kilometers per hour (`'kmph'`). The following code shows examples of applying this function to several sample datasets:
```{r}
data(beijing)
beijing$knots <- convert_wind_speed(beijing$kmph,
old_metric = "kmph", new_metric = "knots")
beijing
data(foco)
foco$mph <- convert_wind_speed(foco$knots, old_metric = "knots",
new_metric = "mph", round = 0)
foco$mph <- convert_wind_speed(foco$knots, old_metric = "knots",
new_metric = "mps", round = NULL)
foco$kmph <- convert_wind_speed(foco$mph, old_metric = "mph",
new_metric = "kmph")
foco
```
You must specify the unit of wind speed that you wish to convert from using the `old_metric` option, and the unit of wind speed you wish to convert to using the `new_metric` option (possible values: `'knots'`, `'mph'`, `'mps'`, `'ftps'`, or `'kmph'`). The unit for `old_metric` cannot be the same as the unit for `new_metric`. You can specify the number of decimal places you wish to round to using the `round` argument. The default value for `round` is 1, consistant with the algorithms used by the National Oceanic and Atmospheric Administration's [online wind speed conversion](http://www.srh.noaa.gov/epz/?n=wxcalc_windconvert) (accessed February 22, 2016). When `round` is set to `NULL`, the output value will not be rounded.
### Converting between precipitation measurements
The `weathermetrics` package includes a function, `convert_precip`, that allows you to convert a vector of precipitation measurement values between inches (`'inches'`), millimeters (`'mm'`), and centimeters (`'cm'`). For example:
```{r}
data(breck)
breck$Precip.mm <- convert_precip(breck$Precip.in,
old_metric = "inches", new_metric = "mm", round = 2)
breck
data(loveland)
loveland$Precip.in <- convert_precip(loveland$Precip.mm,
old_metric = "mm", new_metric = "inches", round = NULL)
loveland$Precip.cm <- convert_precip(loveland$Precip.mm,
old_metric = "mm", new_metric = "cm", round = 3)
loveland
```
You must specify the unit of precipitation measure that you wish to convert from using the `old_metric` option, and the unit of precipitation measure you wish to convert to using the `new_metric` option (possible values: `'inches'`, `'mm'`, and `'cm'`). You can specify the number of decimal places you wish to round to using the `round` argument. The default value for `round` is 2. When `round` is set to `NULL`, the output value will not be rounded.
Calculations between inches and metric units for precipitation measures use the algorithms used by the United States National Weather Service's [Meteorological Conversions](http://www.srh.noaa.gov/ama/?n=conversions) (accessed March 20, 2016).
## Handling missing or impossible weather values
When any of the functions in this package encounter a missing value (`NA`) within any of the input vectors, the output weather metric for that observation will also be set as `NA`. For example:
```{r}
df <- data.frame(T = c(NA, 90, 85),
DP = c(80, NA, 70))
df$RH <- dewpoint.to.humidity(t = df$T, dp = df$DP,
temperature.metric = "fahrenheit")
df
```
Certain values of dew point temperature or relative humidity are impossible. Relative humidity cannot be lower than 0% or higher than 100%. Dew point temperature cannot be higher than air temperature (except in the case of supersaturation) . When any of these functions encounter an impossible weather metric in an input vector, it returns `NA` as the output weather metric for that observation. For example:
```{r}
df <- data.frame(T = c(90, 90, 85),
DP = c(80, 95, 70))
df$heat.index <- heat.index(t = df$T, dp = df$DP,
temperature.metric = 'fahrenheit')
df
```
Additionally, the function returns a warning to alert the user that the input data includes impossible values for some observations.
## Rounding output values
All functions have defaults for rounding that are consistent with the algorithms used by the United States National Weather Service's online converters. For several of the functions, you may also specify that outputs are rounded to a different number of digits using the `round` option. For example:
```{r}
data(suffolk)
suffolk$TempC <- convert_temperature(suffolk$TemperatureF,
old_metric = "f",
new_metric = "c",
round = 5)
suffolk$HI <- heat.index(t = suffolk$TemperatureF,
rh = suffolk$Relative.Humidity,
round = 3)
suffolk
```
## Citation for package
For conversions other than heat index, cite this package as:
G. Brooke Anderson, Roger D. Peng, and Joshua M. Ferreri. 2016. `weathermetrics`: Functions to Convert Between Weather Metrics. R package version 1.2.2.
To cite this package when calculating the heat index, use:
---
nocite: |
@anderson2013heat
...
|
/scratch/gouwar.j/cran-all/cranData/weathermetrics/inst/doc/weathermetrics.Rmd
|
---
title: "`weathermetrics` package vignette"
author: "G. Brooke Anderson, Roger D. Peng, and Joshua M. Ferreri"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{weathermetrics}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
references:
- id: anderson2013heat
title: Methods to calculate the heat index as an exposure metric in environmental health research.
author:
- family: Anderson
given: G. Brooke
- family: Bell
given: Michelle L.
- family: Peng
given: Roger D.
container-title: Environmental Health Perspectives
volume: 121
URL: 'http://ehp.niehs.nih.gov/1206273/'
DOI: 10.1289/ehp.1206273
issued:
year: 2013
issue: 10
pages: 1111-1119
type: article-journal
---
```{r echo = FALSE}
library(weathermetrics)
```
## Package contents
The `weathermetrics` package provides the following functions to calculate or convert between several weather metrics:
Weather variable | Function | Input and / or output metric choices
-----------------|---------------------|----------------
Temperature | `convert_temperature` | `"kelvin"`, `"celsius"`, `"fahrenheit"`
Wind speed | `convert_wind_speed` | `"knots"`, `"mph"`, `"mps"`, `"ftps"`, `"kmph"`
Precipitation | `convert_precip` | `"inches"`, `"mm"`, `"cm"`
Dew point temperature | `humidity.to.dewpoint` | `"celsius"`, `"fahrenheit"`
Relative humidity | `dewpoint.to.humidity` | `"celsius"`, `"fahrenheit"`
Heat index | `heat.index` | `"celsius"`, `"fahrenheit"`
Algorithms for heat index and wind speed are adapted for R from the algorithms used by the United States National Weather Service's [online heat index calculator](http://www.wpc.ncep.noaa.gov/html/heatindex.shtml) (accessed December 18, 2015) and the National Oceanic and Atmospheric Administration's [online wind speed conversion](http://www.srh.noaa.gov/epz/?n=wxcalc_windconvert) (accessed February 22, 2016).
## Converting or calculating weather metrics
### Converting between temperature measurements
This package includes a function, `convert_temperature`, that allows you to convert between common temperature measures including degrees Celsius, Fahrenheit, and Kelvin. The following examples show the use of this function for three example datasets:
To convert between degrees Celsius, Fahrenheit, and Kelvin, use the `convert_temperature` function:
```{r}
#Convert from degrees Celsius to degress Fahrenheit
data(lyon)
lyon$TemperatureF <- convert_temperature(lyon$TemperatureC,
old_metric = "celsius", new_metric = "fahrenheit")
lyon$DewpointF <- convert_temperature(lyon$DewpointC,
old_metric = "celsius", new_metric = "fahrenheit")
lyon
#Convert from degrees Fahrenheit to degrees Celsius
data(norfolk)
norfolk$TemperatureC <- convert_temperature(norfolk$TemperatureF,
old_metric = "f", new_metric = "c")
norfolk$DewpointC <- convert_temperature(norfolk$DewpointF,
old_metric = "f", new_metric = "c")
norfolk
#Convert from degrees Kelvin to degrees Celsius
data(angeles)
angeles$TemperatureC <- convert_temperature(angeles$TemperatureK,
old_metric = "kelvin", new_metric = "celsius")
angeles$DewpointC <- convert_temperature(angeles$DewpointK,
old_metric = "kelvin", new_metric = "celsius")
angeles
```
You can specify whether air temperature and dew point temperature inputs are in degrees Celsius, Fahrenheit, or Kelvin using the `old_metric` and `new_metric` options (possible values are `'celsius'`, `'fahrenheit'`, `'kelvin'`, or `'c'`, `'f'`, and `'k'` for the same). The input for `old_metric` should be the temperature measure that you want to convert from, and the input for `new_metric` should be the temperature measure you wish to convert to.
The `convert_temperature` function is a wrapper function for a variety of individual temperature conversion functions, including: `celsius.to.fahrenheit`, `fahrenheit.to.celsius`, `celsius.to.kelvin`, `kelvin.to.celsius`, `fahrenheit.to.kelvin`, and `kelvin.to.fahrenheit` functions, which you can use individually if you would like.
### Calculating relative humidity and dew point temperature
The `weathermetrics` package includes two functions for converting between air temperature, dew point temperature, and relative humidity:
`dewpoint.to.humidity` and `humidity.to.dewpoint`.
For example, the `lyon` data set includes daily values of both air temperature (`lyon$TemperatureC`) and dew point temperature (`lyon$DewpointC`). Since this data set includes both air temperature and dew point temperature, you can calculate relative humidity using the `dewpoint.to.humidity` function:
```{r}
data(lyon)
lyon$RH <- dewpoint.to.humidity(t = lyon$TemperatureC,
dp = lyon$DewpointC,
temperature.metric = "celsius")
lyon
```
You should specify whether air temperature and dew point temperature inputs are in degrees Fahrenheit or Celsius using the `temperature.metric` argument (possible values are `'fahrenheit'` and `'celsius'`). If input values for temperature and dew point temperature are in different metrics (i.e., one is in degrees Fahrenheit and the other in degrees Celsius), you must convert one of the inputs using either `celsius.to.fahrenheit` or `fahrenheit.to.celsius` before you can input the values to the `dewpoint.to.humidity` function.
As an example of calculating dew point temperature, the `newhaven` data set gives daily values of air temperature in degrees Fahrenheit (`newhaven$TemperatureF`) and relative humidity in % (`newhaven$Relative.Humidity`). Since this data set includes values for both temperature and relative humidity, you can calculate dew point temperature using the `humidity.to.dewpoint` function:
```{r}
data(newhaven)
newhaven$DP <- humidity.to.dewpoint(t = newhaven$TemperatureF,
rh = newhaven$Relative.Humidity,
temperature.metric = "fahrenheit")
newhaven
```
Relative humidity must be input as %, and you must specify the metric of air temperature using the `temperature.metric` argument (possible values: `'fahrenheit'` or `'celsius'`). The dew point temperature will be calculated using the same metric as the air temperature input to the function. If you wish to get dew point temperature in a different metric than air temperature, you can use the `convert_temperature` function. For example:
```{r}
data(newhaven)
newhaven$DP <- humidity.to.dewpoint(t = newhaven$TemperatureF,
rh = newhaven$Relative.Humidity,
temperature.metric = "fahrenheit")
newhaven$DP_C <- convert_temperature(newhaven$DP, old_metric = "f", new_metric = "c")
newhaven
```
Calculations between air temperature, relative humidity, and dew point temperature are based on algorithms used by the United States National Weather Service's [online heat index calculator](http://www.wpc.ncep.noaa.gov/html/heatindex.shtml) (accessed December 18, 2015). These are approximations rather than exact conversions.
### Calculating heat index
The `weathermetrics` package includes a function, `heat.index`, that allows you to calculate a vector of heat index values from vectors of air temperature and either dew point temperature or relative humidity. For example, the `suffolk` data set gives daily values of air temperature in degrees Fahrenheit (`suffolk$TemperatureF`) and relative humidity in % (`suffolk$Relative.Humidity`) for Suffolk, VA, for the week of July 12, 1998. To calculate daily heat index values for this data set, use the `heat.index` function:
```{r}
data(suffolk)
suffolk$HI <- heat.index(t = suffolk$TemperatureF,
rh = suffolk$Relative.Humidity,
temperature.metric = "fahrenheit",
output.metric = "fahrenheit")
suffolk
```
You must specify whether the air temperature input to the function is in degrees Celsius or Fahrenheit using the `temperature.metric` option (possible values: `'fahrenheit'` or `'celsius'`). You can choose which metric for heat index output using using the `output.metric` option (the default is to give heat index in the same metric as the air temperature values input to the function).
As another example, the `lyon` data set gives daily values of air temperature (`lyon$TemperatureC`) and dew point temperature (`lyon$DewpointC`), both in degrees Celsius. You can use this data to calculate daily heat index values in degrees Fahrenheit using:
```{r}
data(lyon)
lyon$HI_F <- heat.index(t = lyon$TemperatureC,
dp = lyon$DewpointC,
temperature.metric = "celsius",
output.metric = "fahrenheit")
lyon
```
When calculating heat index from air temperature and dew point temperature, both must be input in the same metric (either degrees Fahrenheit or degrees Celsius). If this is not the case, you can use `convert_temperature` to convert one of the metrics before using `heat.index`.
The algorithm for calculating heat index is adapted for R
from the algorithms used by the United States National Weather Service's [online heat index calculator](http://www.wpc.ncep.noaa.gov/html/heatindex.shtml) (accessed December 18, 2015). Therefore, results should agree with results from the US National Weather Service online calculator. However, heat index is sometimes calculated using a simpler algorithm. Therefore, heat index values from the \texttt{heat.index} function will sometimes differ by one or two degrees compared to other heat index calculators or charts.
### Converting between units of wind speed
The `weathermetrics` package includes a function, `convert_wind_speed`, that allows you to convert wind speed values between several common units of wind speed: knots (`'knots'`), miles per hour(`'mph'`), meters per second (`'mps'`), feet per second (`'ftps'`), and kilometers per hour (`'kmph'`). The following code shows examples of applying this function to several sample datasets:
```{r}
data(beijing)
beijing$knots <- convert_wind_speed(beijing$kmph,
old_metric = "kmph", new_metric = "knots")
beijing
data(foco)
foco$mph <- convert_wind_speed(foco$knots, old_metric = "knots",
new_metric = "mph", round = 0)
foco$mph <- convert_wind_speed(foco$knots, old_metric = "knots",
new_metric = "mps", round = NULL)
foco$kmph <- convert_wind_speed(foco$mph, old_metric = "mph",
new_metric = "kmph")
foco
```
You must specify the unit of wind speed that you wish to convert from using the `old_metric` option, and the unit of wind speed you wish to convert to using the `new_metric` option (possible values: `'knots'`, `'mph'`, `'mps'`, `'ftps'`, or `'kmph'`). The unit for `old_metric` cannot be the same as the unit for `new_metric`. You can specify the number of decimal places you wish to round to using the `round` argument. The default value for `round` is 1, consistant with the algorithms used by the National Oceanic and Atmospheric Administration's [online wind speed conversion](http://www.srh.noaa.gov/epz/?n=wxcalc_windconvert) (accessed February 22, 2016). When `round` is set to `NULL`, the output value will not be rounded.
### Converting between precipitation measurements
The `weathermetrics` package includes a function, `convert_precip`, that allows you to convert a vector of precipitation measurement values between inches (`'inches'`), millimeters (`'mm'`), and centimeters (`'cm'`). For example:
```{r}
data(breck)
breck$Precip.mm <- convert_precip(breck$Precip.in,
old_metric = "inches", new_metric = "mm", round = 2)
breck
data(loveland)
loveland$Precip.in <- convert_precip(loveland$Precip.mm,
old_metric = "mm", new_metric = "inches", round = NULL)
loveland$Precip.cm <- convert_precip(loveland$Precip.mm,
old_metric = "mm", new_metric = "cm", round = 3)
loveland
```
You must specify the unit of precipitation measure that you wish to convert from using the `old_metric` option, and the unit of precipitation measure you wish to convert to using the `new_metric` option (possible values: `'inches'`, `'mm'`, and `'cm'`). You can specify the number of decimal places you wish to round to using the `round` argument. The default value for `round` is 2. When `round` is set to `NULL`, the output value will not be rounded.
Calculations between inches and metric units for precipitation measures use the algorithms used by the United States National Weather Service's [Meteorological Conversions](http://www.srh.noaa.gov/ama/?n=conversions) (accessed March 20, 2016).
## Handling missing or impossible weather values
When any of the functions in this package encounter a missing value (`NA`) within any of the input vectors, the output weather metric for that observation will also be set as `NA`. For example:
```{r}
df <- data.frame(T = c(NA, 90, 85),
DP = c(80, NA, 70))
df$RH <- dewpoint.to.humidity(t = df$T, dp = df$DP,
temperature.metric = "fahrenheit")
df
```
Certain values of dew point temperature or relative humidity are impossible. Relative humidity cannot be lower than 0% or higher than 100%. Dew point temperature cannot be higher than air temperature (except in the case of supersaturation) . When any of these functions encounter an impossible weather metric in an input vector, it returns `NA` as the output weather metric for that observation. For example:
```{r}
df <- data.frame(T = c(90, 90, 85),
DP = c(80, 95, 70))
df$heat.index <- heat.index(t = df$T, dp = df$DP,
temperature.metric = 'fahrenheit')
df
```
Additionally, the function returns a warning to alert the user that the input data includes impossible values for some observations.
## Rounding output values
All functions have defaults for rounding that are consistent with the algorithms used by the United States National Weather Service's online converters. For several of the functions, you may also specify that outputs are rounded to a different number of digits using the `round` option. For example:
```{r}
data(suffolk)
suffolk$TempC <- convert_temperature(suffolk$TemperatureF,
old_metric = "f",
new_metric = "c",
round = 5)
suffolk$HI <- heat.index(t = suffolk$TemperatureF,
rh = suffolk$Relative.Humidity,
round = 3)
suffolk
```
## Citation for package
For conversions other than heat index, cite this package as:
G. Brooke Anderson, Roger D. Peng, and Joshua M. Ferreri. 2016. `weathermetrics`: Functions to Convert Between Weather Metrics. R package version 1.2.2.
To cite this package when calculating the heat index, use:
---
nocite: |
@anderson2013heat
...
|
/scratch/gouwar.j/cran-all/cranData/weathermetrics/vignettes/weathermetrics.Rmd
|
#' Fitting a single-species SDM
#'
#' SDMfit is used to fit a single species SDM, what we call a 'local model' of trophicSDM. It returns an object of class 'SDMfit'. Requires basically the same inputs of trophicSDM, with the requirement to specify with the parameter 'focal' the species that is modeled by the SDMfit.
#' @param focal the name of the species to be modeled
#' @param Y The sites x species matrix containing observed species distribution (e.g. presence-absence).
#' @param X The design matrix, i.e. sites x predictor matrix containing the value of each explanatory variable (e.g. the environmental conditions) at each site.
#' @param G The species interaction network (aka metaweb). Needs to be an igraph object. Links must go from predator to preys. It needs to be a directed acyclic graph.
#' @param formula.foc The formula for the abiotic part of the species distribution model.
#' @param method which SDM method to use. For now the available choices are: "glm" (frequentist) or "stan_glm" (full Bayesian MCMC, default). Notice that using "glm" does not allow error propagation when predicting.
#' @param mode "prey" if bottom-up control (default), "predators" otherwise. Notice that G needs to be such that links point from predators to prey.
#' @param family the family parameter of the glm function (see glm). family=gaussian(link ="identity") for gaussian data or family=binomial(link = "logit") or binomial(link = "probit") for presence-absence data.
#' @param iter (for method="stan_glm" only) Number of iterations for each MCMC chain if stan_glm is used
#' @param chains (for method="stan_glm" only) Number of MCMC chains (default to 2)
#' @param penal (optional, default to NULL) Penalisation method to shrink regression coefficients.If NULL (default), the model does not penalise the regression coefficient. For now, available penalisation method are "horshoe" for stan_glm, "elasticnet" for glm and "coeff.signs" (prey coefficients are set to positive and predator coefficients to negative) for glm and stan_glm.
#' @param sp.formula (optional) It allows to specify a particular definition of the biotic part of the model, e.g., using composite variables (e.g., richness), or an interaction of the biotic and abiotic component. More details in 'Details'.
#' @param sp.partition (optional) a list to specify groups of species that are used to compute composite variables, e.g., a species can be modeled as a function of the richness of each group of preys. It has to be a list, each element is a vector containing the names of species in the group.
#' @param verbose Whether to print algorithm progresses
#' @export
#' @return A list containing 'm', a "SDMfit" object and 'form.all', a string describing the formula of the SDMfit object. The "SDM" fit object contains:
#' \item{model}{The output of the function used to fit the SDM. E.g., an object of class "glm" is method = "glm", an object of class "stanreg" if method = "stan_glm".}
#' \item{Y}{A numeric vector of standard errors on parameters}
#'
#' \item{form.all}{The formula used to fit the SDM (both abiotic and biotic terms)}
#'
#' \item{method, family, penal, iter, chains}{The input parameters used to fit the SDM.}
#'
#' \item{sp.name}{The name of the species modeled}
#'
#' \item{data}{The model.frame data.frame used to fit the model}
#'
#' \item{coef}{The inferred coefficients (with credible intervals or p-values when available)}
#'
#' \item{AIC}{The AIC of the local model}
#'
#' \item{log.lik}{The log.likelihood of the local model}
#'
#' @details "sp.formula" and "sp.partition" can be combined to define any kind of composite variables for the biotic part of the formula. "sp.formula" can be :
#' \itemize{
#' \item A string defining a formula as function of "richness". E.g., sp.formula="richness+I(richness)^2" (species are modeled as a function of a quadratic polynomial of their prey richness), "I(richness>0)" (species are modeled as a function of a dummy variable that is equal to 1 when at least one species is present). Importantly, when group of preys (or predators) are specified by "sp.partition", species are modeled as a function of the composite variable specified by "sp.formula" for each of their prey groups.\cr
#' \item A more flexible option is to specify sp.formula as a list (whose names are species' names) that contains for each species the definition biotic part of the model. Notice that, in this case, the function does not check that the model is a DAG. This allow to define any kind of composite variable, or to model interactions between environmental covariates and preys (or predators).
#' }
#' @author Giovanni Poggiato and Jérémy Andréoletti
#' @importFrom igraph neighbors
#' @importFrom dplyr rename all_of
#' @importFrom stats glm model.matrix logLik deviance model.frame coef
#' @importFrom glmnet glmnet
#' @importFrom rstanarm stan_glm
#' @importFrom rstanarm hs normal
#' @importFrom brms set_prior brm bf lf bernoulli
#' @importFrom glmnet cv.glmnet
#' @examples
#' data(Y,X,G)
#' # Run a local model (i.e. a SDM) for species Y6
#' mySDM = SDMfit("Y6", Y, X, G, "~X_1 + X_2", mode = "prey",
#' method = "stan_glm", family = binomial(link = "logit"))
#' mySDM$m
#' @export
SDMfit = function(focal, Y, X, G, formula.foc, sp.formula = NULL, sp.partition = NULL,
mode = "prey", method = "stan_glm", family, penal = NULL,
iter = 1000, chains = 2,
verbose = TRUE){
# for the particular case of the stan_glm model with "coeff.signs" constraint
# another stan-for-R package is used (brsm) and formulas have to be adapted
useBRMS = !is.null(penal) && penal=="coeff.signs" & method=="stan_glm"
## Build environmental part of the formula
if(useBRMS){
# "tempX" is an intermediary variable allowing to set lower/upper-bounds on priors
form.env = "y ~ tempX"
form.env.brms = paste("tempX",as.character(formula.foc))
}else form.env = paste("y",as.character(formula.foc))
## Build final formula
neigh = names(neighbors(G,focal,mode=ifelse(mode=="prey","out","in")))
data = data.frame(X,Y)
data = dplyr::rename(data,y=all_of(focal)) # rename the focal column to be called "y"
### Include neigh as covariates
if (length(neigh)>0){
formulas = buildFormula(form.init=form.env,
species = neigh, sp.formula=sp.formula,
sp.partition=sp.partition,
useBRMS)
form.all = formulas$form.all
#### Remove duplicate variables in formula
if(!useBRMS){
temp.mf = model.frame(form.all, data)
temp.mf.all = temp.mf[!duplicated(as.list(temp.mf))]
if(length(colnames(temp.mf.all)) != length(colnames(temp.mf))){
message("Formula was modified since it led to identical columns of the design matrix (e.g. Y_1 or Y_1^2 for binary data)")}
form.all = paste0("y ~ ", paste(colnames(temp.mf.all)[-1], collapse = "+"))
}else{
for(i in 1:length(formulas$form.brms)){
form.temp = formulas$form.brms[[i]]
form.temp = sub(".*~", "y ~", as.character(form.temp))
temp.mf = model.frame(form.temp, data)
temp.mf.all = temp.mf[!duplicated(as.list(temp.mf))]
if(length(colnames(temp.mf.all)) != length(colnames(temp.mf))){
message("Formula was modified since it led to identical columns of the design matrix (e.g. Y_1 or Y_1^2 for binary data)")}
formulas$form.brms[[i]] = as.formula(paste0(sub("()","",formulas$form.brms[[i]][2]),
"~ 0 +", paste(colnames(temp.mf.all)[-1], collapse = "+")))
}
}
if (useBRMS){
# intermediary species variables are themselves defined from observed species variables
form.neigh.brms = formulas$form.brms
}
}else{
# the focal species is basal
form.all = as.character(form.env)
}
## Fit models depending on the chosen method and penalisation
### GLM
if(method=="glm"){
if(is.null(penal)){
m = glm(form.all, data=data, family=family)
}else{
if(penal=="horshoe") stop("Horshoe penalisation is not possible with glm")
if(penal=="elasticnet"){
y = as.matrix(model.frame(form.all,data=data)$y)
x = as.matrix(model.frame(form.all,data=data)[,-1])
m = glmnet(y=y,x=x,family=family$family,
lambda=cv.glmnet(y=y,x=x,family=family$family)$lambda.1se)
}
if(penal=="coeff.signs"){
stop("coeff.signs not available for glm")
}
}
}
### stan_glm
if(method == "stan_glm"){
refresh = ifelse(verbose,1000,0)
if(is.null(penal)){
m = stan_glm(form.all, data=data, family=family, iter=iter,
prior=normal(0,10),chains=chains,refresh=refresh)
}else{
if(penal=="elasticnet") stop("Elastic net is not stan_glm")
if(penal=="horshoe"){
HS_prior = hs(df = 1, global_df = 1, global_scale = 0.01, slab_df = 4, slab_scale = 2.5)
m = stan_glm(form.all, data = data, family = family, prior = HS_prior,
iter = iter,chains = chains, refresh = refresh)
}
if(penal=="coeff.signs"){
# constrain the signs of trophic interaction coefficients to remain positive (preys->preds) or negative (preds->preys)
variables = strsplit(as.character(form.all), "y ~ |\\+")[[1]][-1]
# choose priors depending on the nature of the variables
priors = Reduce(rbind, lapply(variables, function(VAR){
VAR <- gsub("\\^", "E", gsub('\\(|\\)', "", VAR)) # correct name for polynomial terms
if (grepl("X", VAR)) return(set_prior("normal(0,10)", class="b", nlpar=VAR))
if(mode=="prey"){
if (sub("temp","",VAR) %in% neigh) return(set_prior("normal(0,5)", class="b", lb=0, nlpar=VAR))
if (grepl("richness",VAR)) return(set_prior("normal(0,5)", class="b", lb=0, nlpar=VAR))
if (grepl("customform",VAR)) return(set_prior("normal(0,5)", class="b", lb=0, nlpar=VAR))
}else{
if (sub("temp","",VAR) %in% neigh) return(set_prior("normal(0,5)", class="b", ub=0, nlpar=VAR))
if (grepl("richness",VAR)) return(set_prior("normal(0,5)", class="b", ub=0, nlpar=VAR))
if (grepl("customform",VAR)) return(set_prior("normal(0,5)", class="b", lb=0, nlpar=VAR))
}
warning(paste("Variable", sub("temp","",VAR), "not present in any category"), call.=F)
}))
# each temporary variable depends on our initial variables ("false" non-linear model)
form.all = bf(form.all, nl=TRUE) + lf(form.env.brms)
if(length(neigh)>0) form.all = form.all + lf(form.neigh.brms)[[1]]
if(family$family == "binomial"){
m = brm(form.all, data=data, family=bernoulli(link = family$link),
iter=iter, prior=priors, control=list(adapt_delta = 0.9))
}else{
m = brm(form.all, data=data, family=family, iter=iter, prior=priors, control=list(adapt_delta = 0.9))
}
}
}
}
# create matrix of coefficient with postmean, post quantiles and whole samples
# return
SDM = list(model = m, form.all = form.all, method = method,family = family, penal = penal,
iter = iter, chains = chains, sp.name = focal)
class(SDM) = "SDMfit"
if("glm" %in% class(SDM$model)) SDM$data = SDM$model$model
if("glmnet" %in% class(SDM$model)) SDM$data = data.frame(y = y,x)
if(!useBRMS){
SDM$data = as.data.frame(cbind(y = SDM$data$y, model.matrix(as.formula(SDM$form.all),SDM$data)))
SDM$coef = coef(SDM) # add coefficients by calling coef.SDMfit
}
# Add AIC and log.lik
if("glm" %in% class(SDM$model)){
SDM$AIC = SDM$model$aic
SDM$log.lik = logLik(SDM$model)
}
if("glmnet" %in% class(SDM$model)){
tLL = -deviance(SDM$model)
SDM$log.lik = tLL/2
k = ncol(SDM$data)
SDM$AIC <- -tLL+2*k
}
if(SDM$method == "stan_glm"){
SDM$log.lik = sum(colMeans(log_lik(SDM$model)))
k = ncol(SDM$data) # includes intercepts
SDM$AIC <- -2*SDM$log.lik + 2*k
}
return(list(m = SDM, form.all = form.all))
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/SDMfit.R
|
#' Simulated species distribution Y
#' @name Y
#' @docType data
#'
#' @usage data(Y)
#'
#' @format A site x species matrix Y, a site x covariates matrix X and a trophic interaction network G (object igraph)
#'
#' @author Giovanni Poggiato
#'
#' @keywords datasets
#'
#'
#' @examples
#' data(Y)
NULL
#' Simulated environmental covariates X
#' @name X
#' @docType data
#'
#' @usage data(X)
#'
#' @format A site x covariates matrix X
#'
#' @author Giovanni Poggiato
#'
#' @keywords datasets
#'
#' @examples
#' data(X)
NULL
#' Simulated environemntal covariates G
#' @name G
#' @docType data
#'
#' @usage data(G)
#'
#' @format A simulated graph of trophic interactions G
#'
#' @author Giovanni Poggiato
#'
#' @keywords datasets
#'
#' @examples
#' data(G)
NULL
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/SimulData.R
|
#' Builds SDM formulae
#'
#' Builds the formula of both the abiotic and biotic terms to fit a single species SDM based on the input parameters. The function is called inside the SDMfit function
#' @param form.init The abiotic part of the formula
#' @param species The preys (or predators) of the focal species
#' @param sp.formula optional parameter for composite variables. See ?trophicSDM
#' @param sp.partition optional parameter to specify groups of species for composite variables. See ?trophicSDM
#' @param useBRMS whether brms is used (TRUE if penal = "coeff.signs" and method = "stan_glm).
#' @author Giovanni Poggiato and Jérémy Andréoletti
#' @importFrom stats formula as.formula
buildFormula <- function(form.init, species, sp.formula=NULL, sp.partition=NULL, useBRMS){
#if no composite variables are used
if(is.null(sp.formula)){
if(useBRMS){
# "tempYi" are intermediary variables allowing to set lower/upper-bounds on priors
form.all = paste(as.character(form.init), paste(paste0("temp",species), collapse="+"), sep="+")
# intermediary species variables are defined hierarchically from observed species variables
form.brms = lapply(species, function(sp) as.formula(paste0("temp",sp," ~ 0 + ",sp)))
} else form.all = paste(as.character(form.init), paste(species,collapse="+"), sep="+")
}else{
# if no group definition
if(grepl("richness",sp.formula)){
if(is.null(sp.partition)){
# we replace "richness" with the sum of all species (and all eventual other terms), both in linear and eventually other terms
form.all=as.character(form.init)
# replace richness by the observed species variables
if(useBRMS){
# hierarchical definition
form.rich = "richness"
form.brms = paste0("richness ~ 0 + ",
gsub("richness",paste0("I(",paste(paste0(species),collapse = "+"),")"),
sp.formula))
} else form.rich = gsub("richness", paste0("I(",paste(species,collapse = "+"),")"), sp.formula)
form.all = paste(form.all,form.rich,sep="+")
}else{
# all as above but repeated for every cluster
form.all=as.character(form.init)
form.rich = NULL
for(j in 1:length(sp.partition)){
species.j = species[species %in% sp.partition[[j]]]
if(length(species.j)>0){ # at least 2 species in the cluster
if(is.null(form.rich)){
# create form.rich
if(useBRMS){
form.rich = paste0("richness",j)
form.brms = list(paste0("richness", j,
" ~ 0 + ", gsub("richness",
paste0("(",paste(species.j,collapse="+"),")"),
paste0("I(",gsub("\\+", ")\\+I(",sp.formula),")"))))
} else form.rich = gsub("richness",
paste0("(",paste(species.j,collapse="+"),")"),
paste0("I(",gsub("\\+", ")\\+I(",sp.formula),")"))
}else{
# add the new formula to the already existing form.rich
if(useBRMS){
form.rich = paste(form.rich, paste0("richness", j), sep="+")
form.brms = c(form.brms, paste0("richness", j, " ~ 0 + ",
gsub("richness", paste0("(",paste(species.j,collapse="+"),")"),
paste0("I(",gsub("\\+", ")\\+I(",sp.formula),")"))))
} else form.rich = paste(form.rich, gsub("richness",
paste0("(",paste(species.j,collapse="+"),")"),
paste0("I(",gsub("\\+", ")\\+I(",sp.formula),")")),sep="+")
}
}
}
form.all = paste(form.all,form.rich,sep="+")
}
}else{
form.all=as.character(form.init)
#only access here if we have a list containing one formula per species. Notice that we don't check anything here, we trust the user.
if(useBRMS){
# hierarchical definition
form.brms = paste0("customform ~ 0 + ", sp.formula)
form.all = paste(form.all,"customform",sep="+")
}else{
form.all = as.formula(paste(form.all,sp.formula,sep="+"))
}
}
}
if (useBRMS){
return (list(form.all=form.all, form.brms=lapply(form.brms,as.formula)))
}
return (list(form.all=form.all))
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/buildFormula.R
|
#' Gets regression coefficients from a local model, i.e. a SDMfit object.
#'
#' Gets regression coefficients (eventually standardised) of a local model, i.e. a SDMfit object. p-values or credible intervals are returned when available.
#' @param object A SDMfit object, typically obtained with trophicSDM() and available in the field $model of a trophicSDMfit object
#' @param standardise Whether to standardise regression coefficients. Default to FALSE. If TRUE, coefficients are standardised using the latent variable standardisation (see Grace et al. 2018) for more details.
#' @param level The confidence level of credible intervals, only available for stan_glm method. Default to 0.95.
#' @param ... additional arguments
#' @return A table containing the inferred coefficients (with credible intervals or p-values when available).
#' @references Grace, J. B., Johnson, D. J., Lefcheck, J. S., and Byrnes, J. E. K.. 2018. Quantifying relative importance: computing standardized effects in models with binary outcomes. Ecosphere 9(6):e02283.
#' @author Giovanni Poggiato
#' @importFrom rstantools posterior_interval
#' @importFrom stats summary.glm sd predict.glm coef
#' @importFrom dplyr select
#' @method coef SDMfit
#' @examples
#' data(Y, X, G)
#' # define abiotic part of the model
#' env.formula = "~ X_1 + X_2"
#' # Run the model with bottom-up control using stan_glm as fitting method and no penalisation
#' m = trophicSDM(Y,X,G, env.formula, iter = 100,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "stan_glm")
#' # unstandardised regression coefficients
#' coef(m$model$Y5)
#' #standardised regression coefficients with 90% credible intervals
#' coef(m$model$Y5, standardised = TRUE, level = 0.9)
#' # Run the same model using glm as fitting method
#' # (set iter = 1000 to obtain reliable results)
#' m = trophicSDM(Y,X,G, env.formula,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "glm")
#' # Now we have p-values instead of credible intervals
#' coef(m$model$Y5)
#'
#' # Notice that unstandardised coefficients are always accessible
#' # in the fitted model:
#' m$model$Y5$coef
#' @export
coef.SDMfit = function(object, standardise = FALSE, level = 0.95, ...){
SDM = object
if(!is.null(object$penal)){ if(object$penal == "coeff.signs"){stop("This function is not available for coeff.signs penalisation")}}
if(!inherits(SDM, "SDMfit")) stop("SDM is not an object of class SDMfit" )
if(SDM$method == "glm"){
if(!standardise){
if(is.null(SDM$penal)){
table = cbind(estimate = SDM$model$coefficients, p_val = summary(SDM$model)$coefficients[,4])
return(table)
}else{
if(SDM$penal == "elasticnet"){
temp_coef = as.matrix(coef(SDM$model))
names(temp_coef) = rownames(coef(SDM$model))
colnames(temp_coef) = "estimate"
return(temp_coef)
}
}
}else{
if(is.null(SDM$penal)){
# standardise using the same formula in piecewiseSEM::coefs
# It does a classical standardisation for the x, then it divides by the sd of the latent y
# It comes from var(y*) = var(\beta*X) + pi^2/3. See Grace et al. 2018 Ecosphere for more details
temp_coef =
SDM$model$coefficients[-1]*apply(dplyr::select(SDM$data, -c("y", "(Intercept)" )), 2, sd)/
sqrt(var(predict(SDM$model, link = T)) + pi^2/3)
temp_coef = c("(Intercept)"= coef(SDM)[1], temp_coef)
table = cbind(estimate = temp_coef, p_val = summary(SDM$model)$coefficients[,4])
return(table)
}else{
if(SDM$penal == "elasticnet"){
temp_coef = coef(SDM)
# standardise using the same formula in piecewiseSEM::coefs
# It does a classical standardisation for the x, then it divides by the sd of the latent y
# It comes from var(y*) = var(\beta*X) + pi^2/3. See Grace et al. 2018 Ecosphere for more details
temp_coef =
temp_coef[-1]*apply(dplyr::select(SDM$data, -c("y", "(Intercept)" )), 2, sd)/
as.numeric(sqrt(var(predict(SDM$model, link = T,
newx = as.matrix(dplyr::select(SDM$data,
-c("y", "(Intercept)" ))))) + pi^2/3))
temp_coef = c(coef(SDM)[1], temp_coef)
temp_coef = as.matrix(data.frame(estimate = temp_coef))
return(temp_coef)
}
}
}
}
if(SDM$method == "stan_glm"){
if(!standardise){
if(SDM$family$family != "gaussian"){
table = cbind(mean = SDM$model$coefficients, posterior_interval(SDM$model, prob = level))
}else{
#remove sigma value from posterior
post = posterior_interval(SDM$model, prob = level)
table = cbind(mean = SDM$model$coefficients, post[-nrow(post),])
}
return(table)
}else{
# standardise using the same formula in piecewiseSEM::coefs
# It does a classical standardisation for the x, then it divides by the sd of the latent y
# It comes from var(y*) = var(\beta*X) + pi^2/3. See Grace et al. 2018 Ecosphere for more details
# standardise the mean
estimate =
SDM$model$coefficients[-1]*apply(dplyr::select(SDM$data, -c("y", "(Intercept)" )), 2, sd)/
sqrt(var(predict(SDM$model, link = T)) + pi^2/3)
# standardise the quantiles
table_quantile = posterior_interval(SDM$model, prob = level)[-1,]*
apply(dplyr::select(SDM$data, -c("y", "(Intercept)" )), 2, sd)/
sqrt(var(predict(SDM$model, link = T)) + pi^2/3)
if(SDM$family$family == "gaussian"){
table = cbind(estimate, table_quantile[-nrow(table_quantile)])
}else{
table = cbind(estimate, table_quantile)
}
table = rbind("(Intercept)" = SDM$model$coefficients[1], table)
return(table)
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/coef.SDMfit.R
|
#' Gets regression coefficients from a fitted trophicSDM model.
#'
#' Gets regression coefficients (eventually standardised) of a fitted trophicSDM. p-values or credible intervals are returned when available.
#' @param object A trophicSDMfit object obtained with trophicSDM()
#' @param standardise Whether to standardise regression coefficients. Default to FALSE. If TRUE, coefficients are standardised using the latent variable standardisation (see Grace et al. 2018) for more details.
#' @param level The confidence level of credible intervals, only available for stan_glm method. Default to 0.95.
#' @param ... additional arguments
#' @return A list containing, for each species, the inferred coefficients (with credible intervals or p-values when available).
#' @references Grace, J. B., Johnson, D. J., Lefcheck, J. S., and Byrnes, J. E. K.. 2018. Quantifying relative importance: computing standardized effects in models with binary outcomes. Ecosphere 9(6):e02283.
#' @author Giovanni Poggiato
#' @importFrom stats coef var
#' @examples
#' data(Y, X, G)
#' # define abiotic part of the model
#' env.formula = "~ X_1 + X_2"
#' # Run the model with bottom-up control using stan_glm as fitting method and no penalisation
#' # (set iter = 1000 to obtain reliable results)
#' m = trophicSDM(Y,X,G, env.formula, iter = 100,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "stan_glm")
#' # unstandardised regression coefficients
#' coef(m)
#' #standardised regression coefficients with 90% credible intervals
#' coef(m, standardised = TRUE, level = 0.9)
#' # Run the same model using glm as fitting method
#' m = trophicSDM(Y, X, G, env.formula,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "glm")
#' # Now we have p-values instead of credible intervals
#' coef(m)
#'
#' # Notice that unstandardised coefficients are always accessible
#' # in the fitted model:
#' m$coef
#' @method coef trophicSDMfit
#' @export
coef.trophicSDMfit = function(object, standardise = FALSE, level = 0.95, ...){
tSDM = object
if(!inherits(tSDM, "trophicSDMfit")) stop("object is not of class trophicSDMfit" )
if(!is.null(tSDM$model.call$penal)){if(tSDM$model.call$penal == "coeff.signs"){stop("This function is not available for coeff.signs penalisation")}}
lapply(tSDM$model, function(x) coef(x, standardise = standardise, level = level))
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/coef.trophicSDMfit.R
|
#' Computes variable importance of (groups of) variables of fitted a trophicSDM model.
#'
#' Computes variable importance of (groups of) variables of fitted a trophicSDM model, for each species. Variable importance are computed as the standardised regression coefficients (summed across species of the same group). Standardisation is done using latent variable standardisation described in Grace et al. 2018.
#' @param tSDM A trophicSDMfit object obtained with trophicSDM()
#' @param groups A list where each element is group. Each group is specified as a vector containing species or environmental covariates names of a given group. Each element of the list (i.e. each group) has to be named.
#' @return A groups x species matrix containing variable importance for each groups of variables and each species.
#' @author Giovanni Poggiato
#' @references Grace, J. B., Johnson, D. J., Lefcheck, J. S., and Byrnes, J. E. K.. 2018. Quantifying relative importance: computing standardized effects in models with binary outcomes. Ecosphere 9(6):e02283.
#' @importFrom stats coef
#' @examples
#' data(Y, X, G)
#' # define abiotic part of the model
#' env.formula = "~ X_1 + X_2"
#' # Run the model with bottom-up control using stan_glm as fitting method and no penalisation
#' # (set iter = 1000 to obtain reliable results)
#' m = trophicSDM(Y, X, G, env.formula, iter = 100,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "stan_glm")
#' #Compute the importance of each variable
#' computeVariableImportance(m)
#' #Compute the importance of three different set of variables
#' computeVariableImportance(m, groups =list("X" = c("X_1","X_2"),
#' "Ybasal" = c("Y1","Y2","Y3"),
#' "Ypredator"= c("Y4", "Y5", "Y6")))
#' @export
computeVariableImportance = function(tSDM, groups = NULL){
if(!is.null(tSDM$model.call$penal)) {if(tSDM$model.call$penal == "coeff.signs"){stop("This function is not available for coeff.signs penalisation")}}
if(!inherits(tSDM, "trophicSDMfit")) stop("tSDM is not an object of class SDMfit" )
if(!is.null(tSDM$model.call$sp.formula)) warning("If you use composite variables, you should group together species that belong to the same composite variable. For example, if sp.formula = 'richness' and sp.partition = NULL, you should put all species in the same group in the argument 'groups'. If you define a partition of species in sp.partition, then species in the same group in sp.partition should put all species in the same group in the argument 'groups'")
if(is.null(groups)) {
groups = as.list(c(colnames(tSDM$data$X)[-1], colnames(tSDM$data$Y)))
names(groups) = c(colnames(tSDM$data$X)[-1], colnames(tSDM$data$Y))
}
if(is.null(names(groups))) stop("groups should be a lists with names")
n = tSDM$data$n
p = tSDM$data$p
S = tSDM$data$S
VI = matrix(NA,nrow = length(groups), ncol = S, dimnames = list(names(groups),names(tSDM$model)))
for(j in 1:S){
coef_temp = coef(tSDM$model[[j]], standardise = T)[-1,"estimate"]
for(k in 1:length(groups)){
sel = unique(unlist(sapply(groups[[k]], grep, names(coef_temp))))
if(length(sel) > 0) VI[k,j] = sum(abs(coef_temp[sel])) else VI[k,j] = 0
}
}
return(VI)
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/computeVariableImportance.R
|
#' Evaluates prediction goodness of fit
#'
#' Evaluate goodness of fit by comparing a true versus a predicted dataset of species distribution. Ypredicted is typically predicted using a prediction method of trophicSDM (in cross-validation if \code{trophicSDM_CV()} is used).
#' @param tSDM A trophicSDMfit object obtained with \code{trophicSDM()}.
#' @param Ynew A sites x species matrix containing the true species occurrences state. If set to NULL (default), it is set to the species distribution data Y on which the model is fitted.
#' @param Ypredicted A sites x species matrix containing the predicted species occurrences state. If set to NULL (default), it is set to the fitted values, i.e. predictions on the dataset used to train the model.
#' @return A table specifying the goodness of fit metrics for each species. For presence-absence data, the model computes TSS and AUC. For Gaussian data, the R2.
#' @author Giovanni Poggiato
#' @references Grace, J. B., Johnson, D. J., Lefcheck, J. S., and Byrnes, J. E. K.. 2018. Quantifying relative importance: computing standardized effects in models with binary outcomes. Ecosphere 9(6):e02283.
#' @importFrom dismo evaluate
#' @importFrom stats cor
#' @examples
#' data(Y, X, G)
#' # define abiotic part of the model
#' env.formula = "~ X_1 + X_2"
#' # Run the model with bottom-up control using stan_glm as fitting method and no penalisation
#' # (set iter = 1000 to obtain reliable results)
#' m = trophicSDM(Y, X, G, env.formula, iter = 20,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "stan_glm")
#' # Evaluate the quality of model predictions on the training
#' # Predict (fullPost = FALSE) as we used stan_glm to fit the model
#' # but here we are only intested in the posterior mean
#' Ypred = predict(m, fullPost = FALSE)
#' # format predictions to obtain a sites x species dataset whose
#' # columns are ordered as Ynew
#' Ypred = do.call(cbind,
#' lapply(Ypred, function(x) x$predictions.mean))
#'
#' Ypred = Ypred[,colnames(Y)]
#' evaluateModelFit(m, Ynew = Y, Ypredicted = Ypred)
#'
#' # Note that this is equivalent to `evaluateModelFit(m)`
#' # If we fitted the model using "glm"
#' m = trophicSDM(Y, X, G, env.formula,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "glm")
#' Ypred = predict(m, fullPost = FALSE)
#' # format predictions to obtain a sites x species dataset whose
#' # columns are ordered as Ynew
#' Ypred = do.call(cbind, Ypred)
#' Ypred = Ypred[,colnames(Y)]
#'
#' evaluateModelFit(m, Ynew = Y, Ypredicted = Ypred)
#' # Note that this is equivalent to:
#' \donttest{
#' evaluateModelFit(m)
#' }
#' @export
evaluateModelFit = function(tSDM, Ynew = NULL, Ypredicted = NULL){
if(!inherits(tSDM, "trophicSDMfit")) stop("tSDM is not an object of class trophicSDMfit" )
if(is.null(Ynew)){
message("You did not provide Ynew, the observed species distribution Y is used as default.")
Ynew = tSDM$data$Y
}
if(is.null(Ypredicted)) {
message("You did not provide Ypredicted, species predictions are obtained using predict()")
if(tSDM$model.call$method == "glm") pred_samples =1
if(tSDM$model.call$method == "stan_glm") pred_samples = tSDM$model.call$iter/10
Ypredicted = predict(object = tSDM, pred_samples = pred_samples, fullPost = F)
if(tSDM$model.call$family$family == "binomial"){
if(tSDM$model.call$method == "glm") {
Ypredicted = do.call(cbind, Ypredicted)
}
if(tSDM$model.call$method == "stan_glm"){
Ypredicted = do.call(cbind, lapply(Ypredicted, function(x) x$predictions.mean))
}
}
if(tSDM$model.call$family$family == "gaussian"){
if(tSDM$model.call$method == "glm") {
Ypredicted = do.call(cbind, lapply(Ypredicted))
}
if(tSDM$model.call$method == "stan_glm"){
Ypredicted = do.call(cbind, lapply(Ypredicted, function(x) x$predictions.mean))
}
}
Ypredicted = Ypredicted[,colnames(Ynew)]
}
if(!all(colnames(Ypredicted) %in% tSDM$data$sp.name) | !all(colnames(Ynew) %in% tSDM$data$sp.name)){
stop("colnames of Ynew and Ypredicted must be the same of tSDM$data$sp.name)")
}
if(!all(colnames(Ypredicted) == colnames(Ynew))){
stop("colnames of Ynew and Ypredicted must coincide")
}
S = tSDM$data$S
# Compute Joint TSS and AUC
if(tSDM$model.call$family$family == "binomial"){
auc = tss = vector(length = S)
eval = lapply(1:S,function(x){
eval = dismo::evaluate(p = Ypredicted[which(Ynew[,colnames(Ypredicted)[x]]==1),x],
a = Ypredicted[which(Ynew[,colnames(Ypredicted)[x]]==0),x] )
data.frame(auc = eval@auc, tss = max(eval@TPR+eval@TNR-1))
})
metrics = do.call(rbind,eval)
metrics$species = tSDM$data$sp.name
}
if(tSDM$model.call$family$family == "gaussian"){
R2 = vector(length = S)
eval = sapply(1:S, function(s) cor(Ynew[,s], Ypredicted[,s])^2)
metrics = data.frame(R2 = eval, species = tSDM$data$sp.name)
}
return(metrics)
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/evaluateModelFit.R
|
#' Global
#'
#' Declare global variables
#' @name global
#' @importFrom utils globalVariables
NULL
if(getRversion() >= "2.15.1") utils::globalVariables(c("x", "y"), add = F)
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/global.R
|
#' Computes an approximation of loo for the whole model
#'
#' Only works if method = 'stan_glm'. The global loo is computed by summing the loo of all the local models (since the likelihood factorises, the log-likelihood can be summed)This is an implementation of the methods described in Vehtari, Gelman, and Gabry (2017) and Vehtari, Simpson, Gelman, Yao, and Gabry (2019).
#' @param x A trophicSDMfit object obtained with trophicSDM()
#' @param ... additional arguments
#' @return The value of the loo for the whole model
#' @author Giovanni Poggiato
#' @importFrom brms loo log_lik
#' @importFrom rstanarm loo
#' @examples
#' data(Y, X, G)
#' # define abiotic part of the model
#' env.formula = "~ X_1 + X_2"
#' # Run the model with bottom-up control using stan_glm as fitting method and no penalisation
#' m = trophicSDM(Y,X,G, env.formula,
#' family = binomial(link = "logit"), penal = NULL, iter = 50,
#' mode = "prey", method = "stan_glm")
#' \donttest{brms::loo(m)}
#' @method loo trophicSDMfit
#' @export
loo.trophicSDMfit = function(x, ...){
tSDM = x
if(!inherits(tSDM, "trophicSDMfit")) stop("tSDM needs to be a trophicSDMfit object")
if(tSDM$model.call$method != "stan_glm") stop("loo is available only for stan_glm method")
return(do.call(sum,lapply(tSDM$model, function(x) loo(x$model)$estimates[1,1])))
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/loo.trophicSDMfit.R
|
#' Plots the regression coefficients of a local model
#'
#' Plots the regression coefficients of a local SDMfit model
#' @param x A SDMfit object, typically obtained with trophicSDM() and available in the field $model of a trophicSDMfit object
#' @param level the confidence level of the confidence intervals
#' @param ... additional arguments
#' @return A plot of the regression coefficients of the fitted local SDM
#' @author Giovanni Poggiato
#' @examples
#' data(Y, X, G)
#' # define abiotic part of the model
#' env.formula = "~ X_1 + X_2"
#' # Run the model with bottom-up control using stan_glm as fitting method and no penalisation
#' # (set iter = 1000 to obtain reliable results)
#' m = trophicSDM(Y, X, G, env.formula, iter = 50,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "stan_glm")
#' # Plot species Y6
#' \donttest{
#' plot(m$model$Y6)
#' }
#' @import ggplot2
#' @import broom.mixed
#' @importFrom jtools plot_summs
#' @importFrom gridExtra grid.arrange
#' @importFrom stats coef
#' @importFrom utils globalVariables
#' @method plot SDMfit
#' @export
plot.SDMfit = function(x, level = 0.95,...){
SDM = x
if(!inherits(SDM, "SDMfit")) stop("SDM is not an object of class SDMfit" )
if(SDM$method == "glm"){
if(is.null(SDM$penal)){
p = plot_summs(SDM$model, robust = TRUE,plot.distributions = TRUE, inner_ci_level = level, omit.coefs = NULL) +
ggtitle(paste0("Species : ", SDM$sp.name))
return(p)
}else{
table = data.frame(x = as.vector(coef(SDM$model)), y = rownames(coef(SDM$model)))
p = ggplot(data = table) + geom_point(aes(x,y)) + labs(x = "", y = "") +
geom_vline(xintercept=0, lty =2, alpha = 0.5) +
theme_classic() + theme(axis.text.y = element_text(face="bold", size=13)) +
ggtitle(paste0("Species : ", SDM$sp.name))
return(p)
}
}
if(SDM$method == "stan_glm"){
p = plot(SDM$model, prob = level, plotfun = "areas") + ggtitle(paste0("Species : ", SDM$sp.name))
return(p)
}
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/plot.SDMfit.R
|
#' Plots the regression coefficients of a fitted trophicSDM model
#'
#' Plots the regression coefficients of a fitted trophicSDM model. A subset of species to be plotted can be specified in the parameter\code{species}.
#' @param x A trophicSDMfit object obtained with trophicSDM()
#' @param species A vector of species names to be plot. If NULL (default), all species are plotted.
#' @param ... additional arguments
#' @return A plot of the regression coefficients of the fitted tropic SDM
#' @author Giovanni Poggiato
#' @import ggplot2
#' @importFrom grDevices devAskNewPage
#' @importFrom gridExtra grid.arrange
#' @examples
#' data(Y, X, G)
#' # define abiotic part of the model
#' env.formula = "~ X_1 + X_2"
#' # Run the model with bottom-up control using stan_glm as fitting method and no penalisation
#' # (set iter = 1000 to obtain reliable results)
#' m = trophicSDM(Y, X, G, env.formula, iter = 50,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "stan_glm")
#' # Plot just the first three species
#' \donttest{
#' plot(m, species = c("Y1","Y2","Y3"))
#' }
#' # If species = NULL (default), all species are plotted.
#' @method plot trophicSDMfit
#' @export
plot.trophicSDMfit = function(x, species = NULL, ...){
tSDM = x
#########Checks
if(!inherits(tSDM, "trophicSDMfit")) stop("tSDM is not an object of class trophicSDMfit" )
if(!is.null(species) &
!all(species %in% tSDM$data$sp.name)) stop("species must be either NULL or a subset of tSDM$data$sp.name")
##########
# if is.null assign to the whole species pool
if(is.null(species)) species = tSDM$data$sp.name
plist = lapply(tSDM$model[names(tSDM$model) %in% species], function(x) plot(x))
nCol = 2
nRow = ifelse(length(species) < 6, ceiling(length(species)/2), 3)
nPage = ceiling(length(species)/6)
if(tSDM$data$S>6){
devAskNewPage(TRUE)
}
for (i in 1:nPage) do.call(grid.arrange,
c(plist[((i-1)*6+1):ifelse(((i-1)*6+6)>length(plist),
length(plist),
((i-1)*6+6))],
ncol = nCol, nrow = nRow))
devAskNewPage(options("device.ask.default")[[1]])
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/plot.trophicSDMfit.R
|
#' Plots the metaweb G
#'
#' Plots the metaweb G used to fit the trophicSDM model
#' @param tSDM A trophicSDMfit object obtained with trophicSDM()
#' @author Giovanni Poggiato
#' @return A ggnet object
#' @export
#' @import ggplot2
#' @importFrom igraph layout_with_sugiyama
#' @importFrom GGally ggnet2
#' @examples
#' data(Y, X, G)
#' # define abiotic part of the model
#' env.formula = "~ X_1 + X_2"
#' # Run the model with bottom-up control using stan_glm as fitting method and no penalisation
#' # (set iter = 1000 to obtain reliable results)
#' m = trophicSDM(Y, X, G, env.formula, iter = 100,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "stan_glm")
#' \donttest{
#' plotG(m)
#' }
plotG = function(tSDM){
#########Checks
if(!inherits(tSDM, "trophicSDMfit")) stop("tSDM is not an object of class trophicSDMfit" )
G = tSDM$data$G
layout = layout_with_sugiyama(G)$layout
rownames(layout) = tSDM$data$sp.name
ggnet2(G, mode = layout, arrow.size = 10, node.alpha = 0.5, label=T, arrow.gap = 0.04)
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/plotG.R
|
#' Plot the metaweb G according to the inferred coefficients
#'
#' Plot the metaweb G with links colored accordingly to the inferred prey-predator regression coefficients of a fitted trophicSDM model. Plots the metaweb G, where each predator-prey link is colored according to whether the related regression coefficient if inferred as positive (in red), negative (in blue) or non-significant (dashed grey line) according to the confidence level specified in "level". Estimates of the significant standardised regression coefficients are pasted on the links. Only works if species are modeled as a function of their preys or predators without composite variables (i.e., the function only works if tSDM is fitted with sp.formula = NULL and sp.partition = NULL)
#' @param tSDM A trophicSDMfit object obtained with trophicSDM()
#' @param level The confidence level used to decide whether regression coefficients are non-significant or not. Default to 0.9.
#' @return A ggnet object
#' @author Giovanni Poggiato
#' @import ggplot2
#' @importFrom igraph E get.edge.ids edge_attr edge_attr<- layout_with_sugiyama
#' @importFrom GGally ggnet2
#' @importFrom stats coef
#' @export
#' @examples
#' data(Y, X, G)
#' # define abiotic part of the model
#' env.formula = "~ X_1 + X_2"
#' # Run the model with bottom-up control using stan_glm as fitting method and no penalisation
#' # (set iter = 1000 to obtain reliable results)
#' m = trophicSDM(Y, X, G, env.formula,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "glm")
#' \donttest{
#' plotG_inferred(m)
#' }
plotG_inferred = function(tSDM, level = 0.90){
#########Checks
if(!inherits(tSDM, "trophicSDMfit")) stop("tSDM is not an object of class trophicSDMfit" )
if(!is.null(tSDM$model.call$penal)){ if(tSDM$model.call$penal == "coeff.signs"){stop("This function is not available for coeff.signs oenalisation")}}
if(!is.null(tSDM$model.call$sp.formula)) stop("plotG_inferred only works without composite variables")
G = tSDM$data$G
S = tSDM$data$S
# Take biotic coefficients only
all_bio_list = lapply(tSDM$model, function(x) {
all_coef = coef(x, standardise = T, level = level)
# In the bayesian case set to zeros links that are not significant through credible intervals
if(x$method == "stan_glm") {all_coef = apply(all_coef, 1,
function(x) ifelse(x[2] <0 & x[3]>0, 0, x[1]))
}else{
# In the frequentist case set to zeros link that are not significant through p-values
if(x$method == "glm" & is.null(x$penal)) {all_coef = apply(all_coef, 1,
function(x) ifelse(x[2] < 1-level, x[1], 0))
}else{ all_coef = all_coef[,"estimate"]}
}
#select only biotic coeff
all_coef[unlist(sapply(tSDM$data$sp.name, function(x) grep(x, names(all_coef))))]
}
)
all_bio = unlist(all_bio_list)
#Assign to each edge the inferred coefficient as attribute
idx = vector()
for(i in 1:length(all_bio)){
tmp = igraph::get.edge.ids(G, c(gsub("\\..*","",names(all_bio[i])),
gsub(".*\\.","",names(all_bio[i]))),
directed = F)
idx = c(idx,tmp )
}
edge_attr(G)$weight = all_bio[order(idx)]
layout = layout_with_sugiyama(G)$layout
rownames(layout) = tSDM$data$sp.name
edge.color_loc = sapply(1:length(igraph::E(G)), function(x) ifelse(edge_attr(G)$weight[x]>0, "#CC0000", "#0000CC"))
edge.color_loc[which(edge_attr(G)$weight == 0)] = "grey"
ggnet2(G, mode = layout, arrow.size = 8, node.alpha = 0.5, label=T, arrow.gap = 0.04,
edge.label = as.character(signif(edge_attr(G)$weight,1)), edge.color = edge.color_loc,
edge.alpha = ifelse(edge.color_loc == "grey", 0.5, 1),
edge.lty = ifelse(edge.color_loc == "grey", 2, 1))
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/plotG_inferred.R
|
#' Predicts with a local model
#'
#' Computes predicted values for a local model, i.e., a fitted SDMfit object This is sequentially called, for each species, by the function trophicSDM.predict
#' @param object A SDMfit object, typically obtained with trophicSDM() and available in the field $model of a trophicSDMfit object
#' @param newdata A matrix containing both environmental covariates and the biotic variables that the local model uses to predict the species distribution.
#' @param pred_samples Number of samples to draw from species posterior predictive distribution when method = "stan_glm". If NULL, set by the default to the number of iterations/10.
#' @param prob.cov Only for presence-absence data. If set to FALSE, it gives back also predicted presence-absences (which is then used by trophicSDM.predict to predict the predators).
#' @param ... additional arguments
#' @return A list containing for each species the predicted value at each sites. If method = "stan_glm", then each element of the list is a sites x pred_samples matrix containing the posterior predictive distribution of the species at each sites. If prob.cov = TRUE, it returns a list containing:
#' \itemize{
#' \item{predictions.prob}{Predicted probabilities of presence}
#' \item{predictions.prob}{Predicted presence-absences}
#' }
#' @author Giovanni Poggiato and Jérémy Andréoletti
#' @examples
#' data(Y, X, G)
#' # define abiotic part of the model
#' env.formula = "~ X_1 + X_2"
#' # Run the model with bottom-up control using stan_glm as fitting method and no penalisation
#' # (set iter = 1000 to obtain reliable results)
#' m = trophicSDM(Y, X, G, env.formula, iter = 100,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "stan_glm")
#' # In order to predict non-basal species, we need to also provide
#' # the predicted occurrences of its preys. Here we compute the probability of
#' # presence of species Y4 at environemntal conditions c(0.5,0.5)
#' # when its prey Y3 is present.
#' predict(m$model$Y4, newdata = data.frame(X_1 = 0.5, X_2 = 0.5, Y3 = 1), pred_samples = 10)
#' @importFrom rstanarm posterior_epred
#' @importFrom brms posterior_epred
#' @importFrom rstanarm posterior_predict
#' @importFrom brms posterior_predict
#' @importFrom stats predict model.frame rbinom
#' @method predict SDMfit
#' @export
predict.SDMfit = function(object, newdata, pred_samples = NULL, prob.cov = TRUE,...){
SDM = object
if(!inherits(SDM, "SDMfit")) stop("you need to provide a SDMfit object")
if(is.null(pred_samples)){
if(SDM$method=="glm") pred_samples = 1
if(SDM$method=="stan_glm") pred_samples = round(SDM$iter/10)
}
family = SDM$family$family
method = SDM$method
# If presence/absence data
if(family %in% c("bernoulli", "binomial")){
if(method=="stan_glm"){
# retrieve the expected predicted probability of presence
## ! for the particular case of the stan_glm model with a constraint on the coefficients
## ! signs another stan-for-R package is used (brsm) and the code has to be adapted
if (inherits(SDM$model,'brmsfit')){ # brms package
predictions.prob=t(posterior_epred(SDM$model, newdata=as.data.frame(newdata), nsamples=pred_samples))
}else{ # rstan package
predictions.prob=t(posterior_epred(SDM$model, newdata=as.data.frame(newdata), draws=pred_samples))
}
# retrieve a unique presence/absence prediction
if(!prob.cov) {
if(inherits(SDM$model,'brmsfit')){ # brms package
predictions=t(posterior_predict(SDM$model, newdata=as.data.frame(newdata), nsamples=pred_samples))
}else{ # rstan package
predictions=t(posterior_predict(SDM$model, newdata=as.data.frame(newdata), draws=pred_samples))
}
}else{
predictions = NULL
}
}
if(method=="glm") {
if(pred_samples!=1) stop("pred_sample must be 1 if method=glm!")
# retrieve the expected predicted probability of presence
if(is.null(SDM$penal)){
predictions.prob=as.matrix(predict(SDM$model,type = "response",newdata=as.data.frame(newdata)))
}else{
newx = model.frame(gsub(".*y","", SDM$form.all), as.data.frame(newdata))
predictions.prob=as.matrix(predict(SDM$model,type = "response",
newx= as.matrix(newx)))
}
# retrieve a unique presence/absence prediction
if(!prob.cov){
predictions=as.matrix(sapply(as.vector(predictions.prob),FUN=function(x) rbinom(prob=x,size=1,n=1)))
}else{
predictions = NULL
}
}
return(list(predictions.prob = predictions.prob, predictions.bin = predictions))
}
# If gaussian data
if(SDM$family$family =="gaussian"){
if(method=="stan_glm"){
predictions=t(posterior_predict(SDM$model, newdata=as.data.frame(newdata),draws=pred_samples))
}
if(method=="glm") {
if(pred_samples!=1) {
stop("pred_sample must be 1 if method=glm!")}
predictions=as.matrix(predict(SDM$model,type = "response",newdata=as.data.frame(newdata)))
}
return(predictions)
}
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/predict.SDMfit.R
|
#' Computes predicted values from the fitted trophicSDMfit model
#'
#' Computes predicted values from the fitted trophicSDMfit model at environmental conditions specified by \code{Xnew}. Once predictions have been obtained, their quality can eventually be evaluated with \code{evaluateModelFit()}.
#' @param object A trophicSDMfit object obtained with trophicSDM()
#' @param Xnew a matrix specifying the environmental covariates for the predictions to be made. If NULL (default), predictions are done on the training dataset (e.g. by setting Xnew = tSDM$data$X).
#' @param prob.cov Parameter to predict with trophicSDM with presence-absence data. Whether to use predicted probability of presence (prob.cov = T) or the transformed presence-absences (default, prov.cov = F) to predict species distribution.
#' @param pred_samples Number of samples to draw from species posterior predictive distribution when method = "stan_glm". If NULL, set by the default to the number of iterations/10.
#' @param run.parallel Whether to use parallelise code when possible. Can speed up computation time.
#' @param verbose Whether to print advances of the algorithm
#' @param fullPost Optional parameter for stan_glm only. Whether to give back the full posterior predictive distribution (default, fullPost = TRUE) or just the posterior mean, and 2.5% and 97.5% quantiles,
#' @param filter.table Optional, default to NULL, should be provided only if the users wants to filter some species predictions. A sites x species matrix of zeros and ones.
#' @param ... additional arguments
#' @return A list containing for each species the predicted value at each sites. If method = "stan_glm", then each element of the list is a sites x pred_samples matrix containing the posterior predictive distribution of the species at each sites.
#' @author Giovanni Poggiato and Jérémy Andréoletti
#' @importFrom igraph V decompose neighbors vcount
#' @importFrom parallel mclapply detectCores
#' @importFrom stats quantile
#' @method predict trophicSDMfit
#' @export
#' @examples
#' data(Y, X, G)
#' # define abiotic part of the model
#' env.formula = "~ X_1 + X_2"
#' # Run the model with bottom-up control using stan_glm as fitting method and no penalisation
#' # (set iter = 1000 to obtain reliable results)
#' m = trophicSDM(Y, X, G, env.formula, iter = 50,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "stan_glm")
#'# We can now evaluate species probabilities of presence for the environmental conditions c(0.5, 0.5)
#' predict(m, Xnew = data.frame(X_1 = 0.5, X_2 = 0.5))
#' # Obtain 50 draws from the posterior predictive distribution of species (pred_samples = 10)
#' # using predicted presence-absences of species to predict their predators (prob.cov = TRUE)
#' # Since we don't specify Xnew, the function sets Xnew = X by default
#' Ypred = predict(m, fullPost = TRUE, pred_samples = 10, prob.cov = FALSE)
#' # We can ask the function to only give back posterior mean and 95% credible intervals with
#' # fullPost = F
#' \donttest{
#' Ypred = predict(m, fullPost = TRUE, pred_samples = 30, prob.cov = FALSE)
#' }
#' # If we fit the model using in a frequentist way (e.g. glm)
#' m = trophicSDM(Y, X, G, env.formula,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "glm")
#' # We are obliged to set pred_samples = 1
#' # (this is done by default if pred_samples is not provided)
#' # In the frequentist case, fullPost is useless.
#' Ypred = predict(m, pred_samples = 1, prob.cov = FALSE)
predict.trophicSDMfit = function(object, Xnew = NULL, prob.cov = FALSE,
pred_samples = NULL, run.parallel = FALSE, verbose = FALSE,
fullPost = TRUE, filter.table = NULL, ...){
tSDM = object
############################################################
# checks & errors
if(!inherits(tSDM, "trophicSDMfit")) stop("You must provide a trophicSDMfit object")
if(is.null(pred_samples)){
if(tSDM$model.call$method=="glm") pred_samples = 1
if(tSDM$model.call$method=="stan_glm") pred_samples = round(tSDM$model.call$iter/10)
}
if(tSDM$model.call$method=="glm" & pred_samples != 1 ){stop("glm requires pred_sample = 1")}
if(is.null(Xnew)) Xnew = tSDM$data$X
# checks for filter.table ( must be a list where each element is of length nrow(Xnew))
if(!is.null(filter.table) &
(!all(unlist(lapply(filter.table,function(x) length(x) == nrow(Xnew) ))) |
length(filter.table) != tSDM$data$S)) {
stop("filter.table must be a list where each element is of length nrow(Xnew) ")
}
############################################################
family = tSDM$model.call$family
n = nrow(Xnew)
S = tSDM$data$S
G = tSDM$data$G
mode = tSDM$model.call$mode
method = tSDM$model.call$method
# Sort species
sp.prediction = as.list(vector(length=vcount(G)))
if(mode == "prey"){
#sortedV = igraph::V(G)[order(unlist(lapply(igraph::decompose(G), compute_TL_laplacian)), decreasing=T)]
sortedV = topological.sort(G, mode = "in")
}else{
#sortedV = igraph::V(G)[order(unlist(lapply(igraph::decompose(G), compute_TL_laplacian)), decreasing=F)]
sortedV = topological.sort(G, mode = "out")
}
names(sp.prediction) = sortedV$name
############################################################
# presence/absence case
if(family$family %in% c("bernoulli", "binomial")){
Neighb = lapply(sortedV, function(sV) neighbors(G, sV, ifelse(mode == "prey", "out", "in")))
# core loop on species (as in trophicSDM)
for(j in 1:vcount(G)){
# print (if verbose)
if(verbose){
print(paste("--- Species", names(sortedV[j]), "---"));
print(tSDM$model[[names(sortedV[j])]]$form.all)
}
# neighbor species (hat have already been predicted)
neighb.sp = Neighb[[sortedV$name[j]]]
# create data to predict with a call to predict.SDMfit
newdata = array(data = NA, dim = c(n, (ncol(Xnew)+length(neighb.sp)), pred_samples))
colnames(newdata) = c(colnames(Xnew), names(neighb.sp))
# fill the abiotic variables
newdata[,1:ncol(Xnew),] = as.matrix(Xnew)
#### fill the biotic part of new data
## species that have already been predicted
if (length(neighb.sp)>0){ for(k in 1:length(neighb.sp)){
if(prob.cov){
# if prob.cov=TRUE, use the species predicted probabilities of presence
newdata[, ncol(Xnew)+k,] = sp.prediction[[names(neighb.sp[k])]]$predictions.prob
}else{
newdata[, ncol(Xnew)+k,] = sp.prediction[[names(neighb.sp[k])]]$predictions.bin
}
}
}
# apply the function SDMpredict to each layer of the array (MARGIN=3)
if(run.parallel){
pred.array = mclapply(1:dim(newdata)[3],
FUN = function(x){
predict(object = tSDM$model[[names(sortedV[j])]],
newdata = newdata[,,x],
pred_samples=1,
prob.cov=prob.cov)},
mc.cores = detectCores() - 1)
}else{
pred.array = apply(newdata,
MARGIN = 3,
FUN = function(x){
predict(object = tSDM$model[[names(sortedV[j])]],
newdata = x,
pred_samples = 1,
prob.cov = prob.cov)})
}
# unlist and format
sp.prediction[[names(sortedV[j])]] = list()
sp.prediction[[names(sortedV[j])]]$predictions.prob =
do.call(cbind,
lapply(pred.array,
FUN=function(x) x$predictions.prob))
if(!is.null(filter.table)){
sp.prediction[[names(sortedV[j])]]$predictions.prob.unfiltered =
sp.prediction[[names(sortedV[j])]]$predictions.prob
sp.prediction[[names(sortedV[j])]]$predictions.prob =
filter.table[[names(sortedV[j])]] * do.call(cbind,
lapply(pred.array,
FUN=function(x) x$predictions.prob))
}
if(!prob.cov){# Here we don't care to give back $predictions.bin.unfiltered
if(!is.null(filter.table)){
sp.prediction[[names(sortedV[j])]]$predictions.bin =
filter.table[[names(sortedV[j])]] *
do.call(cbind,
lapply(pred.array,
FUN=function(x) x$predictions.bin))
}else{
sp.prediction[[names(sortedV[j])]]$predictions.bin =
do.call(cbind,
lapply(pred.array,
FUN = function(x) x$predictions.bin))
}
}
} # End loop on species
###### Wrap up results and resume (if needed)
if(pred_samples == 1){
for(j in 1:length(sp.prediction)){
sp.prediction[[j]]$predictions.prob = sp.prediction[[j]]$predictions.prob[,1]
if(!is.null(filter.table)){
sp.prediction[[j]]$predictions.prob.unfiltered = sp.prediction[[j]]$predictions.prob.unfiltered[,1]
}
}
}else{
if(!fullPost){
# predictions.prob
for(j in 1:length(sp.prediction)){
predictions.mean = rowMeans(sp.prediction[[j]]$predictions.prob)
predictions.q975 = apply(sp.prediction[[j]]$predictions.prob, 1, quantile, 0.975)
predictions.q025 = apply(sp.prediction[[j]]$predictions.prob, 1, quantile, 0.025)
sp.prediction[[j]]$predictions.prob = list(predictions.mean = predictions.mean,
predictions.q025 = predictions.q025,
predictions.q975 = predictions.q975
)
}
# predictions.prob.unfiltered (if needed)
if(!is.null(filter.table)){
for(j in 1:length(sp.prediction)){
predictions.mean = rowMeans(sp.prediction[[j]]$predictions.prob.unfiltered)
predictions.q975 = apply(sp.prediction[[j]]$predictions.prob.unfiltered,1,quantile,0.975)
predictions.q025 = apply(sp.prediction[[j]]$predictions.prob.unfiltered,1,quantile,0.025)
sp.prediction[[j]]$predictions.prob.unfiltered = list(predictions.mean = predictions.mean,
predictions.q025 = predictions.q025,
predictions.q975 = predictions.q975
)
}
}
}
}
if(is.null(filter.table)){
sp.prediction = lapply(sp.prediction, function(x) x$predictions.prob)
}
return(sp.prediction = sp.prediction)
}
# Just the same of above but predictions are directly given (no need to choose between prob or not)
if(family$family=="gaussian"){
for(j in 1:vcount(G)){ # eventually modify with apply
neigh.sp = neighbors(G,v=sortedV[j],mode="out")
newdata=array(data=NA,dim=c(n,(ncol(Xnew)+length(neigh.sp)),pred_samples))
colnames(newdata)=c(colnames(Xnew),names(neigh.sp))
# fill the abiotic variables
newdata[,1:ncol(Xnew),]=as.matrix(Xnew)
if(length((neigh.sp)>0)){
for(k in 1:length(neigh.sp)){
newdata[,ncol(Xnew)+k,] = sp.prediction[[names(neigh.sp[k])]]# here select the random samples!
}
}
if(run.parallel){
pred.array = mclapply(1:dim(newdata)[3],
FUN = function(x){
predict(object = tSDM$model[[names(sortedV[j])]],
newdata = newdata[,,x],
pred_samples = 1,
prob.cov = prob.cov)},
mc.cores = detectCores())
}else{
pred.array = apply(newdata,
MARGIN=3,
FUN = function(x){
predict(object = tSDM$model[[names(sortedV[j])]],
newdata = x,
pred_samples = 1,
prob.cov = prob.cov)})
}
if(!is.null(filter.table)){ # eventually we could change this to give back both filtered and unfilted
sp.prediction[[names(sortedV[j])]] = filter.table[[names(sortedV[j])]] * pred.array
}else{
sp.prediction[[names(sortedV[j])]] = pred.array
}
} # End loop on species
if(pred_samples == 1){
for(j in 1:length(sp.prediction)){
sp.prediction[[j]] = sp.prediction[[j]][,1]
}
}else{
if(!fullPost & method == "stan_glm"){
# if !fullPost, only take the mean and intervals
for(j in 1:length(sp.prediction)){
predictions.mean = rowMeans(sp.prediction[[j]])
predictions.q975 = apply(sp.prediction[[j]],1,quantile,0.975)
predictions.q025 = apply(sp.prediction[[j]],1,quantile,0.025)
sp.prediction[[j]] = list(predictions.mean = predictions.mean,
predictions.q025 = predictions.q025,
predictions.q975 = predictions.q975
)
}
}
}
return(sp.prediction)
}
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/predict.trophicSDMfit.R
|
#' Predicts species potential niche
#'
#' Computes predicted values of the potential niches of species from the fitted trophicSDMfit model at environmental conditions specified by \code{Xnew}. Predictions are obtained by setting preys to present when mode = "prey" or setting predators to absent when mode = "predator".
#' @param tSDM A trophicSDMfit object obtained with trophicSDM()
#' @param Xnew a matrix specifying the environmental covariates for the predictions to be made. If NULL (default), predictions are done on the training dataset (e.g. by setting Xnew = tSDM$data$X).
#' @param pred_samples Number of samples to draw from species posterior predictive distribution when method = "stan_glm". If NULL, set by the default to the number of iterations/10.
#' @param verbose Whether to print advances of the algorithm.
#' @param fullPost Optional parameter for stan_glm only. Whether to give back the full posterior predictive distribution (default, fullPost = TRUE) or just the posterior mean, and 2.5% and 97.5% quantiles.
#' @return A list containing for each species the predicted value at each sites. If method = "stan_glm", then each element of the list is a sites x pred_samples matrix containing the posterior predictive distribution of the species at each sites.
#' @export
#' @author Giovanni Poggiato and Jérémy Andréoletti
#' @importFrom igraph V decompose neighbors vcount
#' @importFrom stats quantile
#' @examples
#' data(Y, X, G)
#' # define abiotic part of the model
#' env.formula = "~ X_1 + X_2"
#' # Run the model with bottom-up control using stan_glm as fitting method and no penalisation
#' # (set iter = 1000 to obtain reliable results)
#' m = trophicSDM(Y, X, G, env.formula, iter = 100,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "stan_glm")
#' # Obtain 100 draws from the posterior predictive distribution of species potential niche
#' # (pred_samples = 50)
#' # Since we don't specify Xnew, the function sets Xnew = X by default
#' Ypred = predictPotential(m, fullPost = TRUE, pred_samples = 50)
#' # We can ask the function to only give back posterior mean and 95% credible intervals with
#' # fullPost = FALSE
#' \donttest{
#' Ypred = predictPotential(m, fullPost = FALSE, pred_samples = 50)
#' }
#' #' We can now evaluate species probabilities of presence for the enviromental
#' # conditions c(0.5, 0.5)
#' predictPotential(m, Xnew = data.frame(X_1 = 0.5, X_2 = 0.5), pred_samples = 50)
#'
#' # If we fit the model using in a frequentist way (e.g. glm)
#' m = trophicSDM(Y, X, G, env.formula,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "glm")
#' # We are obliged to set pred_samples = 1
#' # (this is done by default if pred_samples is not provided)
#' # In the frequentist case, fullPost is useless.
#' Ypred = predictPotential(m, pred_samples = 1)
predictPotential = function(tSDM, Xnew = NULL, pred_samples = NULL,
verbose = FALSE, fullPost = TRUE){
if(!inherits(tSDM, "trophicSDMfit")) stop("tSDM is not an object of class trophicSDMfit" )
if(is.null(Xnew)) Xnew = tSDM$data$X
if(is.null(pred_samples)){
if(tSDM$model.call$method=="glm") pred_samples = 1
if(tSDM$model.call$method=="stan_glm") pred_samples = tSDM$model.call$iter/10
}
family = tSDM$model.call$family
n = nrow(Xnew)
S = tSDM$data$S
G = tSDM$data$G
mode = tSDM$model.call$mode
sp.prediction = as.list(vector(length=vcount(G)))
names(sp.prediction) = names(tSDM$model)
for(s in 1:S){
sp_mod = tSDM$model[[s]]
#fix all species to oneif species are modeled as a function of their preys (i.e., all preys are present) , elsewhere they are fixed to 0 (i.e. all predators are absent).
if(mode == "prey"){
newdata = cbind(Xnew,
data.frame(matrix(1, nrow=n, ncol=ncol(tSDM$data$Y),
dimnames= list(NULL,colnames(tSDM$data$Y)))))
}else{
newdata = cbind(Xnew,
data.frame(matrix(0, nrow=n, ncol=ncol(tSDM$data$Y),
dimnames= list(NULL,colnames(tSDM$data$Y)))))
}
pred_temp = predict(sp_mod,newdata = newdata,
pred_samples = pred_samples, prob.cov = TRUE)
sp.prediction[[s]] = pred_temp$predictions.prob
}
if(tSDM$model.call$method == "stan_glm" & !fullPost ){
# predictions.prob
for(j in 1:length(sp.prediction)){
predictions.mean = rowMeans(sp.prediction[[j]])
predictions.q975 = apply(sp.prediction[[j]], 1, quantile, 0.975)
predictions.q025 = apply(sp.prediction[[j]], 1, quantile, 0.025)
sp.prediction[[j]] = list(predictions.mean = predictions.mean,
predictions.q025 = predictions.q025,
predictions.q975 = predictions.q975
)
}
}
return(sp.prediction)
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/predictPotential.R
|
#' Prints a SDMfit object
#' @param x A SDMfit object, typically obtained with trophicSDM() and available in the field $model of a trophicSDMfit object
#' @param ... additional arguments
#' @return Prints a summary of the local SDM
#' @author Giovanni Poggiato
#' @method print SDMfit
#' @export
#' @examples
#' data(Y, X, G)
#' # define abiotic part of the model
#' env.formula = "~ X_1 + X_2"
#' # Run the model with bottom-up control using stan_glm as fitting method and no penalisation
#' # (set iter = 1000 to obtain reliable results)
#' m = trophicSDM(Y, X, G, env.formula, iter = 100,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "stan_glm")
#' m$model$Y1
print.SDMfit = function(x, ...){
SDM = x
if(!inherits(SDM, "SDMfit")) stop("SDM is not an object of class SDMfit" )
summary(SDM)
#Just to fix pkgdown
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/print.SDMfit.R
|
#' Prints a fitted trophicSDM model
#'
#' @param x A trophicSDMfit object obtained with trophicSDM()
#' @param ... additional arguments
#' @return Prints a summary of the fitted trophic SDM
#' @author Giovanni Poggiato
#' @method print trophicSDMfit
#' @export
#' @examples
#' data(Y, X, G)
#' # define abiotic part of the model
#' env.formula = "~ X_1 + X_2"
#' # Run the model with bottom-up control using stan_glm as fitting method and no penalisation
#' # (set iter = 1000 to obtain reliable results)
#' trophicSDM(Y, X, G, env.formula, iter = 100,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "stan_glm")
print.trophicSDMfit = function(x, ...){
tSDM = x
if(!inherits(tSDM, "trophicSDMfit")) stop("tSDM is not an object of class trophicSDMfit" )
summary(tSDM)
#Just to fix pkgdown
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/print.trophicSDMfit.R
|
#' Summary of a fitted SDMfit model
#' @param object A SDMfit object, typically obtained with trophicSDM() and available in the field $model of a trophicSDMfit object
#' @param ... additional arguments
#' @return Prints a summary of the local SDM
#' @author Giovanni Poggiato
#' @examples
#' data(Y, X, G)
#' # define abiotic part of the model
#' env.formula = "~ X_1 + X_2"
#' # Run the model with bottom-up control using stan_glm as fitting method and no penalisation
#' # (set iter = 1000 to obtain reliable results)
#' m = trophicSDM(Y, X, G, env.formula, iter = 100,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "stan_glm")
#' summary(m$model$Y1)
#' @method summary SDMfit
#' @export
summary.SDMfit = function(object, ...){
SDM = object
if(!inherits(SDM, "SDMfit")) stop("SDM is not an object of class SDMfit" )
cat("================================================================== \n")
model = paste0("Local SDMfit for species ", SDM$sp.name, " with ",
ifelse(is.null(SDM$penal), "no", SDM$penal), " penalty ", SDM$penal,
", fitted using ", SDM$method,
" \n")
cat(model)
cat("================================================================== \n")
cat("* Useful S3 methods\n")
cat(" print(), coef(), plot(), predict()\n")
cat(paste0(" $model gives the ",class(SDM$model)[1], " class object \n"))
cat("================================================================== \n")
summary(SDM$model)
#Just to fix pkgdown
invisible(object)
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/summary.SDMfit.R
|
#' Summary of a fitted trophicSDM model
#'
#' @param object A trophicSDMfit object obtained with trophicSDM()
#' @param ... additional arguments
#' @return Prints a summary of the fitted trophic SDM
#' @author Giovanni Poggiato
#' @examples
#' data(Y, X, G)
#' # define abiotic part of the model
#' env.formula = "~ X_1 + X_2"
#' # Run the model with bottom-up control using stan_glm as fitting method and no penalisation
#' # (set iter = 1000 to obtain reliable results)
#' m = trophicSDM(Y, X, G, env.formula, iter = 100,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "stan_glm")
#' summary(m)
#' @method summary trophicSDMfit
#' @export
summary.trophicSDMfit = function(object, ...){
tSDM = object
if(!inherits(tSDM, "trophicSDMfit")) stop("tSDM is not an object of class trophicSDMfit" )
model = paste0("A trophicSDM fit with ", ifelse(is.null(tSDM$model.call$penal), "no", tSDM$model.call$penal)," penalty, ",
"fitted using ", tSDM$model.call$method,
" \n with a ", ifelse(tSDM$model.call$mode == "prey", "bottom-up", "top-down"), " approach \n",
" \n Number of species : ", tSDM$data$S,
" \n Number of links : ", length(igraph::E(tSDM$data$G)),
" \n")
cat("==================================================================\n")
cat(model)
cat("==================================================================\n")
cat("* Useful fields\n")
cat(" $coef \n")
cat("* Useful S3 methods\n")
cat(" print(), coef(), plot(), predict(), evaluateModelFit() \n")
cat(" predictPotential(), plotG(), plotG_inferred(), computeVariableImportance() \n")
cat("* Local models (i.e. single species SDM) can be accessed through \n")
cat(" $model\n")
#Just to fix pkgdown
invisible(object)
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/summary.trophicSDMfit.R
|
#' Fitting a trophic Species distribution model
#'
#' trophicSDM is used to fit a trophic species distribution model. Requires the species distribution data Y (the sites x species matrix), explanatory variables X and a directed acyclic graph G containing species interactions (i.e., the metaweb, with links going from predators to prey). The function fits the distribution of each species as a function of their preys (with mode = "prey", by default) or predators (if set mode = "predator").
#' @param Y The sites x species matrix containing observed species distribution (e.g. presence-absence).
#' @param X The design matrix, i.e. sites x predictor matrix containing the value of each explanatory variable (e.g. the environmental conditions) at each site.
#' @param G The species interaction network (aka metaweb). Needs to be an igraph object. Links must go from predator to preys. It needs to be a directed acyclic graph.
#' @param env.formula The definition of the abiotic part of the model. It can be :
#' \itemize{
#' \item a string specifying the formula (e.g. "~ X_1 + X_2"). In this case, the same environmental variables are used for every species.
#'
#' \item A list that contains for each species the formula that describes the abiotic part of the model. In this case, different species can be modeled as a function of different environmental covariates. The names of the list must coincide with the names of the species.
#' }
#' @param method which SDM method to use. For now the available choices are: \code{"glm"} (frequentist) or \code{"stan_glm"} (full bayesian MCMC, default). Notice that using "glm" does not allow error propagation when predicting.
#' @param mode "prey" if bottom-up control (default), "predators" otherwise. Notice that G needs to be such that links point from predators to prey.
#' @param family the family parameter of the glm function (see \code{glm}). \code{gaussian(link = "identity")} for gaussian data. \code{binomial(link = "logit")} or \code{binomial(link = "probit")} for presence-absence data.
#' @param iter (for \code{"stan_glm"} only) Number of iterations for each MCMC chain if stan_glm is used
#' @param chains (for \code{"stan_glm"} only) Number of MCMC chains (default to 2)
#' @param penal Penalisation method to shrink regression coefficients. If \code{NULL} (default), the model does not penalise the regression coefficient. For now, available penalization method are \code{"horshoe"} for method stan_glm, \code{"elasticnet"} for method glm. It is also possible to constrain the sign of biotic coefficients (prey coefficients are set to positive and predator coefficients to negative) by setting \code{"coeff.signs"} for methods glm and stan_glm.
#' @param sp.formula (optional) It allows to specify a particular definition of the biotic part of the model, e.g., using composite variables (e.g., richness), or an interaction of the biotic and abitic component. More details in 'Details'.
#' @param sp.partition (optional) a list to specify groups of species that are used to compute composite variables, e.g., a species can be modeled as a function of the richness of each group of preys. It has to be a list, each element is a vector containing the names of species in the group. More details in 'Details'.
#' @param run.parallel Whether species models are fitted in parallel (can speed computational up time). Default to \code{FALSE}.
#' @param verbose Whether to print algorithm progresses
#' @return A "trophicSDMfit" object, containing:
#' \item{model}{A list containing the local models (i.e. a SDM for each species). Each local model is an object of class "SDMfit". See \code{?SDMfit} for more informations.}
#' \item{Y}{A numeric vector of standard errors on parameters}
#'
#' \item{form.all}{A list describing each species formula (both biotic and abiotic terms)}
#'
#' \item{data}{A list containing all the data used to fit the model}
#'
#' \item{model.call}{A list containing the modeling choices of the fitted model (e.g. method, penalisation...)}
#'
#' \item{coef}{A list containing, for each species, the inferred coefficients (with credible intervals or p-values when available)}
#' \item{MCMC.diag}{MCMC convergence metrics, only available for MCMC methods}
#'
#' \item{AIC}{Model's AIC}
#'
#' \item{log.lik}{Model's log.likelihood}
#'
#' @details "sp.formula" and "sp.partition" can be combined to define any kind of composite variables for the biotic part of the formula. "sp.formula" can be :
#' \itemize{
#' \item A string defining a formula as function of "richness", e.g., \code{"richness+I(richness)^2"} (species are modeled as a function of a quadratic polynomial of their prey richness), \code{"I(richness>0)"} (species are modeled as a function of a dummy variable that is equal to 1 when at least one species is present). Importantly, when group of preys (or predators) are specified by "sp.partition", species are modeled as a function of the composite variable specified by "sp.formula" for each of their prey (or predator) groups.
#' \item A more flexible option is to specify sp.formula as a list (whose names are species' names) that contains for each species the definition of the biotic part of the model. Notice that, in this case, the function does not check that the model is a DAG. This allow to define any kind of composite variable, or to model interactions between environmental covariates and preys (or predators).
#'}
#' @author Giovanni Poggiato and Jérémy Andréoletti
#' @examples
#' data(Y, X, G)
#' # define abiotic part of the model
#' env.formula = "~ X_1 + X_2"
#' # Run the model with bottom-up control using stan_glm as fitting method and no penalisation
#' # Increase the number of iterations to obtain reliable results.
#' m = trophicSDM(Y,X,G, env.formula, iter = 50,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "stan_glm")
#' print(m)
#'
#' # Access local models (e.g. species "Y5")
#' m$model$Y5
#' coef(m$model$Y5)
#' # The fitted model can be plotted with `plot(m)`
#'
#' # Fit a sparse model in the Bayesian framework with the horshoe prior
#' \donttest{
#' m = trophicSDM(Y,X,G, env.formula,
#' family = binomial(link = "logit"), penal = "horshoe",
#' mode = "prey", method = "stan_glm")
#' }
#' # Fit frequentist glm
#' m = trophicSDM(Y,X,G, env.formula,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "glm")
#'
#' # With elasticnet penalty
#' m = trophicSDM(Y,X,G, env.formula,
#' family = binomial(link = "logit"), penal = "elasticnet",
#' mode = "prey", method = "glm")
#'
#' #### Composite variables
#' # See vignette 'Composite variables' for a complete introduction to the use of composite variables
#' # Model species as a function of a quadratic polynomial of prey richness
#' m = trophicSDM(Y,X,G, env.formula,
#' family = binomial(link = "logit"), penal = NULL,
#' sp.formula = "richness + I(richness^2)",
#' mode = "prey", method = "glm")
#' m$form.all
#' # Notice that for predators that feed on a single prey (with presence-absence data),
#' # their richness and the square of their richness is exactly the same variable
#' # In this case, `trophicSDM()` removes the redundant variable but prints a warning message
#'
#' # Model species as a function of a dummy variable saying whether they have at leaste one prey
#' m = trophicSDM(Y,X,G, env.formula,
#' family = binomial(link = "logit"), penal = NULL,
#' sp.formula = "I(richness>0)",
#' mode = "prey", method = "glm")
#' m$form.all
#'
#' # Define group of preys and model species as a function of the richness (with a quadratic term)
#' # of these groups of preys separately
#'
#' # Species Y1 and Y2 belong to the same group, species Y3 and Y4 are both alone in their group and
#' # species Y5 and Y6 form another group
#' sp.partition = list(c("Y1","Y2"),c("Y3"),c("Y4"), c("Y5","Y6"))
#'
#' m = trophicSDM(Y,X,G, env.formula,
#' family = binomial(link = "logit"), penal = NULL,
#' sp.partition = sp.partition,
#' sp.formula = "richness + I(richness^2)",
#' mode = "prey", method = "glm")
#' m$form.all
#'
#' @importFrom parallel mclapply detectCores
#' @importFrom bayesplot rhat neff_ratio
#' @importFrom igraph is_igraph V decompose vcount topological.sort
#' @export
trophicSDM = function(Y, X, G,
env.formula = NULL, sp.formula = NULL, sp.partition = NULL,
penal = NULL, mode = "prey", method = "stan_glm",
family, iter=500, chains = 2, run.parallel = FALSE, verbose = FALSE){
################################
# checks & errors
if(is.null(colnames(Y))) stop("Please provide species names as the column names of Y")
if(!is_igraph(G)) stop("G is not an igraph object")
if(is.null(env.formula)){
env.formula = as.list(rep("~ 1", ncol(Y)))
names(env.formula) = colnames(Y)
}else{
if(length(env.formula) == 1){
env.formula = as.list(rep(env.formula, ncol(Y)))
names(env.formula) = colnames(Y)
}
}
if(!method %in% c("glm","stan_glm")) stop("the selected method has not yet been implemented or it has been misspelled")
if(!(is.null(penal) || penal %in% c("horshoe","elasticnet","coeff.signs"))) stop("the selected penalisation has not yet been implemented or it has been misspelled")
if(!is.null(sp.partition) &
(!all(colnames(Y) %in% unlist(sp.partition)) |
!all(unlist(sp.partition) %in% colnames(Y)))){
stop("all species must be included in sp.partition")
}
if(!is.null(sp.formula) & length(sp.formula)>1){
#did the user specified a custom sp.formula?
custom.formula = T
message("We don't check that G and the graph induced by the sp.formula specified by the user match, nor that the latter is a graph. Please be careful about their consistency.")
if(!identical(names(sp.formula),colnames(Y))) stop("sp.formula has to be either NULL, richness, or a list whose name equals species names (i.e. colnames(Y))")
}else{custom.formula=F}
if(!(mode %in% c("prey","predator"))){stop("mode must be either 'prey' or 'predator'")}
if(is.null(colnames(X))) warning("columns of X must have names in order to match the env.formula argument")
if(is.character(family) | is.function(family)){stop("If you want to model Gaussian data, please provide family = gaussian(), eventually specifying a link.")}
################################
################################
# Laplacian sorting of the graph (component by component)
if(mode == "prey"){
#sortedV = igraph::V(G)[order(unlist(lapply(igraph::decompose(G), compute_TL_laplacian)), decreasing=T)]
sortedV = topological.sort(G, mode = "in")
}else{
#sortedV = igraph::V(G)[order(unlist(lapply(igraph::decompose(G), compute_TL_laplacian)), decreasing=F)]
sortedV = topological.sort(G, mode = "out")
}
# initialize empty lists of models
m = form.all = as.list(vector(length=igraph::vcount(G)))
names(m) = names(form.all) = names(sortedV)
# core part: loop on the species to fit their distribution
if(run.parallel){
m=mclapply(1:vcount(G),FUN = function(j){
if(verbose) print(paste("--- Species", names(sortedV[j]), "---"))
if(custom.formula){
sp.form = sp.formula[[names(sortedV[j])]]
}else{
sp.form = sp.formula
}
# call a function that does a SDM with j as focal species, automatically finds covariates from G and formula.foc
temp.mod = SDMfit(focal=names(sortedV[j]), Y, X, G,
sp.formula = sp.form, sp.partition, mode = mode,
formula.foc=paste(as.character(env.formula[[names(sortedV[j])]]),collapse=" "),
method=method, penal=penal, family=family, iter=iter,verbose=verbose,chains=chains)
# assign models and env.formula (that now includes biotic variables too)
temp.mod
},mc.cores=detectCores()-1)
form.all=lapply(m, `[[`, 2)
m=lapply(m, `[[`, 1)
names(m) = names(form.all) = names(sortedV)
}else{
for(j in 1:vcount(G)){
if(verbose) print(paste("--- Species", names(sortedV[j]), "---"))
if(custom.formula){
sp.form = sp.formula[[names(sortedV[j])]]
}else{
sp.form = sp.formula
}
#call a function that does a SDM with j as focal species, automatically finds covariates from G and formula.foc
temp.mod = SDMfit(focal = names(sortedV[j]), Y, X, G, sp.formula = sp.form, sp.partition, mode = mode,
formula.foc = paste(as.character(env.formula[[names(sortedV[j])]]),collapse=" "),
method = method, penal = penal, family = family,
chains = chains,iter = iter,verbose = verbose)
# assign models and env.formula (that now includes biotic variables too)
m[[names(sortedV[j])]] = temp.mod$m
form.all[[names(sortedV[j])]] = temp.mod$form.all
}
}
# return values
trophicSDMfit = list(model = m, form.all = form.all,
data = list(X = X, Y = Y, G = G,n = nrow(X),
p = ncol(X), S = ncol(Y), sp.name = colnames(Y)),
model.call = list(form.env = env.formula,
mode = mode, sp.formula = sp.formula,
sp.partition = sp.partition,
method = method, penal = penal,
iter = iter, family = family))
if(!is.null(penal)){ if(penal == "coeff.signs"){
trophicSDMfit$coef = lapply(trophicSDMfit$model,function(x) x$coef)
}}
trophicSDMfit$AIC = do.call(sum, lapply(trophicSDMfit$model, function(x) x$AIC))
trophicSDMfit$log.lik = do.call(sum, lapply(trophicSDMfit$model, function(x) x$log.lik))
if(method == "stan_glm"){
mcmc.diag = data.frame(rhat = unlist(lapply(
trophicSDMfit$model, function(x) rhat(x$model))),
neff.ratio = unlist(lapply(
trophicSDMfit$model, function(x) neff_ratio(x$model))))
mcmc.diag$species = sub("\\..*", "",rownames(mcmc.diag))
mcmc.diag$coef= sub(".*\\.", "",rownames(mcmc.diag))
trophicSDMfit$mcmc.diag = mcmc.diag
}
class(trophicSDMfit) = "trophicSDMfit"
return(trophicSDMfit)
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/trophicSDM.R
|
#' Compute K-fold cross-validation predicted values from a fitted trophicSDM model
#'
#' Once the CV predicted values are obtained, their quality can be evaluated with \code{evaluateModelFit()}.
#' @param tSDM A trophicSDMfit object obtained with trophicSDM()
#' @param K The number of folds for the K-fold cross validation
#' @param partition Optional parameter. A partition vector to specify a partition in K fold for cross validation
#' @param prob.cov Parameter to predict with trophicSDM with presence-absence data. Whether to use predicted probability of presence (prob.cov = T) or the transformed presence-absences (default, prov.cov = F) to predict species distribution.
#' @param pred_samples Number of samples to draw from species posterior predictive distribution when method = "stan_glm". If NULL, set by the default to the number of iterations/10.
#' @param iter For method = "stan_glm": number of iterations of each MCMC chains to fit the trophicSDM model. Default to the number of iterations used to fit the provided trophicSDMfit object
#' @param chains For method = "stan_glm": number of MCMC chains to fit the trophicSDM model. Default to the number of iterations used to fit the provided trophicSDMfit object
#' @param run.parallel Whether to use parallelise code when possible. Default to TRUE. Can speed up computation time
#' @param verbose Whether to print advances of the algorithm
#' @return A list containing:
#' \item{meanPred}{a sites x species matrix of predicted occurrences of species for each site (e.g. probability of presence). With stan_glm the posterior predictive mean is return}
#' \item{Pred975,Pred025}{Only for method = "stan_glm", the 97.5% and 2.5% quantiles of the predictive posterior distribution}
#' \item{partition}{the partition vector used to compute the K fold cross-validation}
#' @author Giovanni Poggiato
#' @importFrom parallel mclapply detectCores
#' @importFrom abind abind
#' @importFrom stats quantile
#' @examples
#' data(Y, X, G)
#' # define abiotic part of the model
#' env.formula = "~ X_1 + X_2"
#' # Run the model with bottom-up control using glm as fitting method and no penalisation
#' # (set iter = 1000 to obtain reliable results)
#' \donttest{
#' m = trophicSDM(Y, X, G, env.formula, iter = 50,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "stan_glm")
#'
#' # Run a 3-fold (K=3) cross validation. Predictions is done using presence-absences of preys
#' # (prob.cov = FALSE, see ?predict.trophicSDM) with 50 draws from the posterior distribution
#' # (pred_samples = 50)
#' CV = trophicSDM_CV(m, K = 3, prob.cov = FALSE, pred_samples = 10, run.parallel = FALSE)
#' # Use predicted values to evaluate model goodness of fit in cross validation
#' Ypred = CV$meanPred[,colnames(Y)]
#'
#' evaluateModelFit(m, Ynew = Y, Ypredicted = Ypred)
#' }
#' # Now with K = 2 and by specifying the partition of site
#' m = trophicSDM(Y, X, G, env.formula, iter = 50,
#' family = binomial(link = "logit"), penal = NULL,
#' mode = "prey", method = "glm")
#' partition = c(rep(1,500),rep(2,500))
#' CV = trophicSDM_CV(m, K = 2, partition = partition, prob.cov = FALSE,
#' pred_samples = 10, run.parallel = FALSE)
#' Ypred = CV$meanPred[,colnames(Y)]
#' evaluateModelFit(m, Ynew = Y, Ypredicted = Ypred)
#' @export
trophicSDM_CV = function(tSDM, K, partition = NULL, prob.cov = FALSE,
pred_samples = NULL,
iter = NULL, chains = NULL, run.parallel = FALSE, verbose = FALSE){
if(!inherits(tSDM, "trophicSDMfit")) stop("tSDM needs to be a trophicSDMfit object")
# set MCMC parameters
if(tSDM$model.call$method == "glm"){ iter = 1; pred_samples = 1
}else{
if(is.null(iter)) iter = tSDM$model.call$iter
if(is.null(pred_samples)) pred_samples = round(iter/10)
}
n = tSDM$data$n
S = tSDM$data$S
G = tSDM$data$G
# Create partition (if needed)
if(!is.null(partition)){
if(length(partition) != n) stop("partition must be a vector of length n (the number of sites)")
}else{
partition <- sample(1:K,size=n,replace=TRUE,prob=rep(n/K,K))
}
preds = array(dim=c(n,pred_samples,S))
for(i in 1:K){
train = which(partition != i)
test = which(partition == i)
Y = tSDM$data$Y[train,]
X = tSDM$data$X[train,]
m_K = trophicSDM(Y = Y, X = X, G = tSDM$data$G, env.formula = tSDM$model.call$form.env,
penal = tSDM$model.call$penal, method = tSDM$model.call$method, mode = tSDM$model.call$mode,
family = tSDM$model.call$family, iter = iter,
run.parallel = run.parallel, verbose = verbose,
chains=2)
pred_K = predict(m_K, Xnew = tSDM$data$X[test,],
prob.cov = prob.cov, pred_samples = pred_samples, run.parallel = run.parallel)
if(tSDM$model.call$method == "stan_glm"){
preds[test,,] = abind(pred_K,along=3)
}else{
preds[test,,] = do.call(cbind, pred_K)
}
print(paste0("Fold ", i, " out of ", K," \n"))
}
if(tSDM$model.call$method == "glm"){
meanPred = preds[,1,]
colnames( meanPred ) = names(pred_K)
Pred975 = Pred025 = NULL
}
if(tSDM$model.call$method == "stan_glm"){
meanPred = apply(preds,mean,MARGIN = c(1,3))
Pred975 = apply(preds, quantile, MARGIN=c(1,3),0.975)
Pred025 = apply(preds, quantile, MARGIN=c(1,3),0.025)
colnames( meanPred ) = colnames(Pred975) = colnames(Pred025) = names(pred_K)
}
list(meanPred = meanPred, Pred975 = Pred975, Pred025 = Pred025, partition = partition)
}
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/trophicSDM_CV.R
|
#' @keywords internal
"_PACKAGE"
## usethis namespace: start
## usethis namespace: end
NULL
|
/scratch/gouwar.j/cran-all/cranData/webSDM/R/webSDM-package.R
|
---
title: "Composite variables and biotic-abiotic interactions"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Composite variables and biotic-abiotic interactions}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
In this vignette we explain how to use composite variables in trophic SDM. These variables are useful especially in species-rich network, where some predators might have so many preys that assuming that each of them has a differential effect on predator distribution is not only a problem, but might seem ecologically unjustified. Instead, we could expect the richness or diversity of prey, or whether at least a prey is available, to be important. Hence, we implemented the use of composite variables, i.e., variables that summarize the information of a large number of variables from the graph in a few summary variables. Examples of composite variables are prey richness or diversity, or a binary variable set to one if the number of preys is above a certain threshold. These variables assume that all species have the same impact on the predator. An alternative is to group species in the metaweb to represent trophic groups that clump together species that feed on, or are eaten by, the same type of species. We can then construct composite variables (e.g., their richness) for each of those trophic groups to better represent the variety of resources for species like generalist or top predators.
In `webSDM` it is possible to define an extremely large set of composite variables using the arguments `sp.formula` and `sp.partition`. In general, `sp.formula` allows the definition of the composite variables, while `sp.partition` allow to define the groups of preys (or predator) for which each composite variable is calculate.
Hereafter we don't provide a complete analyses of a case-study using composite variables, but rather focus on the description of how to implement them in `webSDM`.
Finally, we will see how to include an interaction between preys and the environment.
```r
library(webSDM)
data(X ,Y, G)
```
## Composite variables
`sp.formula` can be a right hand side formula including richness (i.e. the sum of its preys) and any transformations of richness. Notice that only "richness" is allowed for now. However, we will see how this already allow to build an extremely large set of composite variable. We start with a simple case where we model species as a function of the richness of their prey, with a polynomial of degree two.
```r
m = trophicSDM(Y, X, G,
env.formula = "~ X_1 + X_1^2",
family = binomial(link = "logit"), penal = NULL,
sp.formula = "richness + I(richness^2)",
mode = "prey", method = "glm")
#> Formula was modified since it led to identical columns of the design matrix (e.g. Y_1 or Y_1^2 for binary data)
```
Notice that for predators that feed on a single prey (with presence-absence data), their richness and the square of their richness is exactly the same variable. In this case, `trophicSDM()` removes the redundant variable but prints a warning message.
We can see the formulas created by the argument `$form.all` of the fitted model.
```r
m$form.all
#> $Y1
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y2
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y3
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y5
#> [1] "y ~ X_1+I(Y1 + Y2 + Y3)+I(I(Y1 + Y2 + Y3)^2)"
#>
#> $Y4
#> [1] "y ~ X_1+I(Y3)"
#>
#> $Y6
#> [1] "y ~ X_1+I(Y3 + Y5)+I(I(Y3 + Y5)^2)"
```
We now set as composite variable a dummy variable specifying whether there is at least one available prey or not. To do so we define `sp.formula = "I(richness>0)"`.
```r
m = trophicSDM(Y,X,G,
env.formula = "~ X_1 + X_1^2",
family = binomial(link = "logit"), penal = NULL,
sp.formula = "I(richness>0)",
mode = "prey", method = "glm")
```
Which leads to the following formulas:
```r
m$form.all
#> $Y1
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y2
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y3
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y5
#> [1] "y ~ X_1+I(I(Y1 + Y2 + Y3) > 0)"
#>
#> $Y4
#> [1] "y ~ X_1+I(I(Y3) > 0)"
#>
#> $Y6
#> [1] "y ~ X_1+I(I(Y3 + Y5) > 0)"
```
## Composite variables and groups of preys
A halfway between considering that each species has a differential effect on the predator (i.e., no composite variable), or that every prey has the same effect (i.e., modeling predator as a function of prey richness), is to create group of species that we assume to have the same effect on the predator. Then, we can model predator as a function of composite variables calculated on each of these groups. To do so, we rely on the argument `sp.partition`. This parameters has to be a list, where each element contain the species of the given group.
For example, we can put species Y1 and Y2 in the same group, species Y3 and Y4 are alone in their group and Y5 and Y6 to form another group.
```r
sp.partition = list(c("Y1","Y2"),c("Y3"),c("Y4"), c("Y5","Y6"))
```
Then, we can specify whatever `sp.formula`, for example using richness (with a quadratic term).
```r
m = trophicSDM(Y,X,G, "~ X_1 + X_1^2",
family = binomial(link = "logit"), penal = NULL,
sp.partition = sp.partition,
sp.formula = "richness + I(richness^2)",
mode = "prey", method = "glm")
#> Formula was modified since it led to identical columns of the design matrix (e.g. Y_1 or Y_1^2 for binary data)
#> Formula was modified since it led to identical columns of the design matrix (e.g. Y_1 or Y_1^2 for binary data)
#> Formula was modified since it led to identical columns of the design matrix (e.g. Y_1 or Y_1^2 for binary data)
```
Which leads to the following formulas:
```r
m$form.all
#> $Y1
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y2
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y3
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y5
#> [1] "y ~ X_1+I((Y1 + Y2))+I(I((Y1 + Y2)^2))+I((Y3))"
#>
#> $Y4
#> [1] "y ~ X_1+I((Y3))"
#>
#> $Y6
#> [1] "y ~ X_1+I((Y3))+I((Y5))"
```
## Custom formula
In case we want to specify a composite variable that cannot be created from a function of richness, the user can specify directly the list of the biotic formulas in the `sp.formula` argument. Importantly, notice that in this case `trophicSDM()` will not create a new formula from the argument `G` and will not check that the user-defined formula actually derives from `G` (i.e. that predator-prey interactions described in the formulas derive from G). For example, we might want to quantify the effect of the prey Y5 on the predator Y6 when the prey Y3 is not available. To do so, we define for species Y6 an interaction term between species Y5 and one minus Y3 (i.e. a dummy variable that takes the value of 1 when species Y5 is present and Y3 is absent). To do so, we define `sp.formula` as a list describing the biotic formula for each species.
```r
sp.formula = list(Y1 = "",
Y2 = "",
Y3 = "",
Y4 = "Y3",
Y5 = "Y1",
Y6 = "I(Y5*(1-Y3))")
m = trophicSDM(Y,X,G, "~ X_1 + X_1^2",
family = binomial(link = "logit"), penal = NULL,
sp.formula = sp.formula,
mode = "prey", method = "glm")
#> We don't check that G and the graph induced by the sp.formula specified by the user match, nor that the latter is a graph. Please be careful about their consistency.
m$form.all
#> $Y1
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y2
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y3
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y5
#> [1] "y ~ X_1+Y1"
#>
#> $Y4
#> [1] "y ~ X_1+Y3"
#>
#> $Y6
#> [1] "y ~ X_1+I(Y5 * (1 - Y3))"
```
## On computeVariableImportance with composite variable
When computing the importance of variables using the function `computeVariableImportance`, you should be careful with the definition of groups. Indeed, the function computes the variable importance of each group as the sum of the standardised regression coefficients containing some variables from the groups. Therefore, if species from different groups of variable are merged in the same composite variable, `computeVariableImportance` will sum the regression coefficient of the composite variable in different groups, leading to wrong results. For example, if `sp.formula = "richness"` and `sp.partition = NULL`, you should put all species in the same group in the argument `groups`.
```r
m = trophicSDM(Y,X,G,
env.formula = "~ X_1 + X_1^2",
family = binomial(link = "logit"), penal = NULL,
sp.formula = "richness + I(richness^2)",
mode = "prey", method = "glm")
#> Formula was modified since it led to identical columns of the design matrix (e.g. Y_1 or Y_1^2 for binary data)
computeVariableImportance(m, groups = list("abiotic" = c("X_1", "X_2"),
"biotic" = c("Y1", "Y2", "Y3",
"Y4", "Y5", "Y6")))
#> Warning in computeVariableImportance(m, groups = list(abiotic = c("X_1", : If you use composite variables, you
#> should group together species that belong to the same composite variable. For example, if sp.formula = 'richness' and
#> sp.partition = NULL, you should put all species in the same group in the argument 'groups'. If you define a partition
#> of species in sp.partition, then species in the same group in sp.partition should put all species in the same group
#> in the argument 'groups'
#> Y1 Y2 Y3 Y5 Y4 Y6
#> abiotic 0 0 0 0.05380788 0.17251449 0.04623329
#> biotic 0 0 0 0.08470730 0.07633953 0.38116851
```
If you use composite variables, you should group together species that belong to the same composite variable.If you define a partition of species in sp.partition, then species in the same group in sp.partition should put all species in the same group in the argument 'groups'.
```r
sp.partition = list(c("Y1","Y2"),c("Y3"),c("Y4"), c("Y5","Y6"))
m = trophicSDM(Y,X,G, "~ X_1 + X_1^2",
family = binomial(link = "logit"), penal = NULL,
sp.partition = sp.partition,
sp.formula = "richness + I(richness^2)",
mode = "prey", method = "glm")
#> Formula was modified since it led to identical columns of the design matrix (e.g. Y_1 or Y_1^2 for binary data)
#> Formula was modified since it led to identical columns of the design matrix (e.g. Y_1 or Y_1^2 for binary data)
#> Formula was modified since it led to identical columns of the design matrix (e.g. Y_1 or Y_1^2 for binary data)
computeVariableImportance(m, groups = list("abiotic" = c("X_1", "X_2"),
"Group1" = c("Y1", "Y2"),
"Group2" = c("Y3"),
"Group3" = c("Y4", "Y5", "Y6")))
#> Warning in computeVariableImportance(m, groups = list(abiotic = c("X_1", : If you use composite variables, you
#> should group together species that belong to the same composite variable. For example, if sp.formula = 'richness' and
#> sp.partition = NULL, you should put all species in the same group in the argument 'groups'. If you define a partition
#> of species in sp.partition, then species in the same group in sp.partition should put all species in the same group
#> in the argument 'groups'
#> Y1 Y2 Y3 Y5 Y4 Y6
#> abiotic 0 0 0 0.1016899 0.17251449 0.03603087
#> Group1 0 0 0 0.8621983 0.00000000 0.00000000
#> Group2 0 0 0 0.2581345 0.07633953 0.22671385
#> Group3 0 0 0 0.0000000 0.00000000 0.11579149
```
## Interaction with biotic and abiotic terms
Assuming that the effect of prey on predators does not vary with environmental conditions might be a too strong assumption. In order to integrate species plasticity, it is possible to define a `sp.formula` that includes both biotic and abiotic terms. For example, we hereafter define an interaction between the prey and the environmental variable X_2.
```r
sp.formula = list(Y1 = "",
Y2 = "",
Y3 = "",
Y4 = "I(X_2*Y3)",
Y5 = "I(X_2*Y1)",
Y6 = "I(X_2*Y3) + I(X_2*Y5)")
m = trophicSDM(Y,X,G,
env.formula = "~ X_1 + X_1^2",
family = binomial(link = "logit"), penal = NULL,
sp.formula = sp.formula,
mode = "prey", method = "glm")
#> We don't check that G and the graph induced by the sp.formula specified by the user match, nor that the latter is a graph. Please be careful about their consistency.
```
|
/scratch/gouwar.j/cran-all/cranData/webSDM/inst/doc/Composite_variables.Rmd
|
---
title: "Subtle and obvious differences between SDM and trophic SDM"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Subtle and obvious differences between SDM and trophic SDM}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
## Compare trophic and classical SDMs: difference and equalities
Here, we present the differences between a classic SDM and our trophic SDM, starting from the simplest case when these two approaches coincide to more realistic cases where they do not.
### The simplest case
Let’s consider a very simple case with one environmental covariate $x$, and two species $y_A$ and $y_B$. We assume species $y_A$ to be basal and species $y_B$ to feed on $y_A$. This leads to the following directed acyclic graph that resumes the dependencies across variables, assuming bottom-up control.
```r
library(igraph)
G=graph_from_edgelist(as.matrix(data.frame(from = c("x","x","A"),
to = c("A","B","B"))))
plot(G)
```

We now assume that data on species distributions are continuous observable entities (e.g. basal area, biomass), that we can model with a linear regression. We name $y_{iA}$ and $y_{iB}$ the observations of species $y_A$ and $y_B$ at site $i$, respectively, and we assume that the environment has a quadratic effect on both species.
Therefore, using classical SDMs, model equations are:
$$
\begin{aligned}
y_{iA} &= \beta^{SDM}_{0A} + \beta^{SDM}_{1A} x_i + \beta^{SDM}_{2A}x_i^2 + \epsilon_{iA}, \ \ \epsilon_{iA} \sim N(0, \sigma_A^{SDM}) \\
y_{iB} &= \beta^{SDM}_{0B} + \beta^{SDM}_{1B} x_i + \beta^{SDM}_{2B}x_i^2 + \epsilon_{iB}, \ \ \epsilon_{iB} \sim N(0, \sigma_B^{SDM})
\end{aligned}
$$
Instead, our trophic model includes a dependence of $y_B$ on its prey $y_A$:
$$
\begin{aligned}
y_{iA} &= \beta^{tSDM}_{0A} + \beta^{tSDM}_{1A} x_i + \beta^{tSDM}_{2A}x_i^2 + \epsilon_{iA}, \ \ \epsilon_{iA} \sim N(0, \sigma_A^{tSDM}) \\
y_{iB} &= \beta^{tSDM}_{0B} + \beta^{tSDM}_{1B} x_i + \beta^{tSDM}_{2B}x_i^2 + \alpha y_{iA} + \epsilon_{iB}, \ \ \epsilon_{iB} \sim N(0, \sigma_B^{tSDM})
\end{aligned}
$$
We hereafter focus on the expectation of the models (corresponding to the predicted values), focusing in particular on species $y_B$ for which the two models are different. For SDMs:
$$E[y_{iB} | \ x_i] = \beta^{SDM}_{0B} + \beta^{SDM}_{1B} x_i + \beta^{SDM}_{2B}x_i^2 $$
For trophic SDM, we need to condition on a value of $y_{iA}$. We here choose to condition on the expected value of $y_{iA}$, which corresponds to using predictions from $y_A$ to predict $y_B$. In a linear model, with Gaussian data and a linear interaction between prey and predator, we have that $E_A[E_B[y_B | \ y_A]] = E_B[y_B | \ E[y_A]]$ (which is not necessarily true in other cases).
We thus have:
$$E[y_{iB} | \ x_i, E[y_{iA}] ] = \beta^{tSDM}_{0B} + \beta^{tSDM}_{1B} x_i + \beta^{tSDM}_{2B}x_i^2 + \alpha E[y_{iA}] $$
We can rewrite the expected value of $y_B$ only as a function of the environment $x$ only.
$$
\begin{aligned}
E[y_{iB} | \ x_i, E[y_{iA}] ] &= \beta^{tSDM}_{0B} + \beta^{tSDM}_{1B} x_i + \beta^{tSDM}_{2B}x_i^2 + \alpha (\beta^{tSDM}_{0A} + \beta^{tSDM}_{1A} x_i + \beta^{tSDM}_{2A}x_i^2 ) \\
& = \beta^{tSDM}_{0B} + \alpha \beta^{tSDM}_{0A} + ( \beta^{tSDM}_{1B} + \alpha \beta^{tSDM}_{1A}) x_i + (\beta^{tSDM}_{2B} + \alpha \beta^{tSDM}_{2A}) x_i^2 \\
&= \beta^{SDM}_{0B} + \beta^{SDM}_{1B} x_i + \beta^{SDM}_{2B}x_i^2
\end{aligned}
$$
In this very simple case of a linear regression model with a linear interactions between the predator and the preys, the estimation of the regression coefficients is such that
$$\beta^{SDM}_{.B} = \beta^{tSDM}_{.B} + \alpha \beta^{tSDM}_{.A} $$
As a consequence the models estimate the same realised niche, and predictions from trophic and classical SDMs coincide.
However, our trophic model allows a separation of the direct effect of the environment on $y_B$ (i.e., the potential niche of $y_B$) from its indirect effect due to the effect of $y_A$ on $y_B$. In other words, using the jargon of structural equation models, $\beta^{tSDM}_{1B}$ and $\beta^{tSDM}_{2B}$ are the direct effects of the environment on species $y_B$ (i.e., its potential niche), the terms $\alpha \beta^{tSDM}_{1A}$ and $\alpha \beta^{tSDM}_{2A}$ are the indirect effect of the environment on species $y_B$. The sum of these two effects, $\beta^{tSDM}_{1B} + \alpha \beta^{tSDM}_{1A}$ and $\beta^{tSDM}_{2B} + \alpha \beta^{tSDM}_{2A}$ corresponds to the total effect of the environment on $y_B$, i.e., the realised niche of $y_B$. In this very particular case, SDM can correctly estimate the total effect (the realised niche), but cannot separate the direct and indirect effect of the environment on $y_B$ and thus they do not correctly estimate the potential niche.
#### Simulation
We hereafter present a short example confirming the analytical derivation of these results.
First, we simulate species distribution data accordingly to the directed acyclic graph presented above. Therefore, the environment has a quadratic effect on species $y_A$ and species $y_B$, with a linear effect of $y_A$ on $y_B$.
```r
set.seed(1712)
# Create the environmental gradient
X = seq(0,5,length.out=100)
# Simulate data for the basal species A
A = 3*X + 2*X^2 + rnorm(100, sd = 5)
# Simulate data for the predator species B
B = 2*X -3*X^2 + 3*A + rnorm(100, sd = 5)
oldpar = par()
par(mfrow=c(1,3))
plot(X,A, main = "Species A realised \n and potential niche")
plot(X,B, main = "Species B realised niche")
plot(X, 2*X -3*X^2, main = "Species B potential niche")
```

```r
par(mfrow = oldpar$mfrow)
```
We now run both a classic SDM and a trophic SDM
```r
# For species A, the two models coincide
m_A = lm(A ~ X + I(X^2))
# For species B, the two models are different:
## trophic model
m_trophic = lm(B ~ X + I(X^2) + A)
## classic SDM
m_SDM = lm(B ~ X + I(X^2))
```
We can now test the relationships between the coefficients of SDM and trophic SDM.
```r
# Show the equality of coefficients
all.equal(coef(m_SDM), coef(m_trophic)[-4] + coef(m_trophic)[4]*coef(m_A))
#> [1] TRUE
# Prediction coincide
pred_SDM = m_SDM$fitted.values
pred_trophic = predict(m_trophic,
newdata = data.frame(X = X, A = m_A$fitted.values))
all.equal(pred_SDM, pred_trophic)
#> [1] TRUE
```
The coefficient of classic SDM for species $y_B$ are equal to the environmental coefficients of trophic SDM for species $y_B$ plus the indirect effect of the environment on species $y_B$ (given by the product of the biotic term and the environmental coefficients of species $y_A$).
As a consequence, the predictions of both models coincide when the predicted value of species $y_A$ is used to predict $y_B$.
However, unlike the traditional SDM, our trophic model allows to retrieve the correct potential niche of species $y_B$
```r
# Potential niche infered by SDM
plot(X, m_SDM$fitted.values, ylim = c(-65, 120), ylab = "B",
main = "Potential niche of yB")
points(X, cbind(1, X, X^2) %*% coef(m_trophic)[-4], col ="red")
points(X, 2*X -3*X^2, col ="blue")
legend(-0.1, 120, legend=c("Potential niche inferred by SDM",
"Potential niche inferred by trophic SDM",
"True fundamenta niche"), pch =1,
col=c("black","red", "blue"), cex = 0.5)
```

## Does this always hold?
We showed that SDM and trophic SDM estimate the same realized niche, and thus lead to the same predictions, when all the following conditions hold:
- The relationship between predator and prey is linear
- Species distribution are continuous abundances
- The statistical model employed is a linear regression
- The selected environmental variables are the same for prey and predators
However, as soon as at least one of these conditions does not hold, the estimations of the realized niche (and so model prediction) differ. We hereafter show that releasing just one of these constraints at a time is enough to obtain predictions from trophic SDM that are different, and better, than classical SDMs. Therefore, the example presented above is a very particular case that is useful to understand model similarities, but that rarely occurs in application.
### Non-linear relationship between prey and predator
We hereafter release the conditions on the linearity of the relationship between $y_B$ and $y_A$. Indeed, we now consider that species $y_B$ has a quadratic response to $y_A$. The classic SDM does not change, as we model species as a function of the environment only. Instead, the trophic model for species $y_B$ becomes:
$$y_{iB}= \beta^{tSDM}_{0B} + \beta^{tSDM}_{1B} x_i + \beta^{tSDM}_{2B}x_i^2 + \alpha y_{iA}^2 + \epsilon_{iB}, \ \ \epsilon_{iB} \sim N(0, \sigma_B^{tSDM})$$
Predictions between trophic SDM and SDM are now different, since:
$$
\begin{aligned}
E[y_{iB} | \ x_i, E[y_{iA}] ] &= \beta^{tSDM}_{0B} + \beta^{tSDM}_{1B} x_i + \beta^{tSDM}_{2B}x_i^2 + \alpha (\beta^{tSDM}_{0A} + \beta^{tSDM}_{1A} x_i + \beta^{tSDM}_{2A}x_i^2 )^2 \\
& = \beta^{tSDM}_{0B} + \alpha(\beta^{tSDM}_{0A})^2+ (\beta^{tSDM}_{1B} + 2\alpha\beta^{tSDM}_{0A}\beta^{tSDM}_{1A}) x_i \\
& \ \ \ \ + (\beta^{tSDM}_{2B} + \alpha (2\beta^{tSDM}_{0A}\beta^{tSDM}_{2A} + (\beta^{tSDM}_{1A})^2))x_i^2 + 2\alpha\beta^{tSDM}_{1A}\beta^{tSDM}_{2A} x_i^3 + \alpha(\beta^{tSDM}_{2A})^2x_i^4 \\
&\neq \beta^{SDM}_{0B} + \beta^{SDM}_{1B} x_i + \beta^{SDM}_{2B}x_i^2
\end{aligned}
$$
In order to correctly infer the realised niche, classic SDMs should be specified with a polynomial of degree 4. As soon as we add multiple environmental variables and link between species, classic SDM should be specified with extremely complex formula, which is unfeasible for real application.
#### Simulation
We provide a simple example to demonstrate the analytical computations with a simulation. We use the same example of above, but we now simulate a quadratic relationship of $y_B$ with respect to $y_A$.
```r
B = 2*X -3*X^2 + 3*A^2 + rnorm(100, sd = 5)
oldpar = par()
par(mfrow=c(1,3))
plot(X,A, main = "Species A realised \n and potential niche")
plot(X,B, main = "Species B realised niche")
plot(X, 2*X -3*X^2, main = "Species B potential niche")
```

```r
par(mfrow = oldpar$mfrow)
# Fit a trophic SDM
m_trophic = lm(B ~ X + I(X^2) + I(A^2))
```
We now compare the regression coefficients and predictions from the two models
```r
# Show the equality of coefficients
all.equal(coef(m_SDM), coef(m_trophic)[-4] + coef(m_trophic)[4]*coef(m_A))
#> [1] "Mean relative difference: 0.185587"
# Prediction are now different
pred_SDM = m_SDM$fitted.values
pred_trophic = predict(m_trophic,
newdata = data.frame(X = X, A = m_A$fitted.values))
all.equal(pred_SDM, pred_trophic)
#> [1] "Mean relative difference: 53.61947"
#Compare R2
cor(B, pred_SDM)^2
#> [1] 0.8339402
cor(B, pred_trophic)^2
#> [1] 0.9605349
```
The relationship between the coefficients of the two models does not hold anymore more, and predictions are now different, with trophic SDM reaching a far better predictive accuracy than classic SDM for species $y_B$ (R2 of 0.83 and 0.96 respectively).
### Non-continuous observable entities (presence-absence, counts)
Let’s now consider here the case of presence-absences (i.e., binary data), without modifying the other two conditions. Therefore, we use a (generalized) linear model like logistic regression, and we model a linear relationship (at the link level) between predator and prey. Thus, for SDM we have:
$$
\begin{aligned}
p(y_{iA}= 1) &= \text{logit}^{-1}(\beta^{SDM}_{0A} + \beta^{SDM}_{1A} x_i + \beta^{SDM}_{2A}x_i^2) \\
p(y_{iB} = 1) &= \text{logit}^{-1}(\beta^{SDM}_{0B} + \beta^{SDM}_{1B} x_i + \beta^{SDM}_{2B}x_i^2)
\end{aligned}
$$
Instead, our trophic model includes a dependence of $y_B$ on its prey $y_A$:
$$p(y_{iB} = 1) = \text{logit}^{-1} (\beta^{tSDM}_{0B} + \beta^{tSDM}_{1B} x_i + \beta^{tSDM}_{2B}x_i^2 + \alpha y_A)$$
The equality between the models does not hold anymore due to the non linearity of the logit function. Indeed:
$$
\begin{aligned}
E[y_{iB} | \ x_i, E[y_{iA}] ] &= p(y_{iB} = 1 | \ x_i, p(y_{iA} = 1)) \\
&= \text{logit}^{-1}(\beta^{tSDM}_{0B} + \beta^{tSDM}_{1B} x_i + \beta^{tSDM}_{2B}x_i^2 + \alpha \text{logit}^{-1}(\beta^{tSDM}_{0A} + \beta^{tSDM}_{1A} x_i + \beta^{tSDM}_{2A}x_i^2))\\
&\neq \text{logit}^{-1}(\beta^{SDM}_{0B} + \beta^{SDM}_{1B} x_i + \beta^{SDM}_{2B}x_i^2)
\end{aligned}
$$
#### Simulations
We now confirm this analytical derivation with a simple example. The code is very similar to the previous one, but we now generate binary data from a logistic model.
```r
# Generate the link layer basal species
V_A= 3*X - 2*X^2
# Transform to probability
prob_A = 1/(1 + exp(-V_A))
# Sample the binary data
A = rbinom(n = 100, size = 1, prob = prob_A)
# Same for species B
V_B = -3*X +1*X^2 + 3*A
prob_B = 1/(1 + exp(-V_B))
B = rbinom(n = 100, size = 1, prob = prob_B)
oldpar = par()
par(mfrow=c(1,3))
plot(X,prob_A, main = "Species A realised \n and potential niche")
plot(X,prob_B, main = "Species B realised niche")
plot(X, 1/(1+exp(-(-3*X +1*X^2))), main = "Species B potential niche")
```

```r
par(mfrow = oldpar$mfrow)
```
We then fit a classic SDM and a trophic SDM
```r
# For species A, the two models coincide
m_A = glm(A ~ X + I(X^2), family = binomial(link = "logit"))
# For species B, the two models are different:
m_SDM = glm(B ~ X + I(X^2), family = binomial(link = "logit"))
m_trophic = glm(B ~ X + I(X^2) + A, family = binomial(link = "logit"))
```
We now test the relationships between model coefficients and whether the equality of model predictions still holds
```r
# Equality of the coefficient does not hold anymore
all.equal(coef(m_SDM), coef(m_trophic)[-4] + coef(m_trophic)[4]*coef(m_A))
#> [1] "Mean relative difference: 2.305022"
# Predictions do not coincide anymore
pred_SDM = m_SDM$fitted.values
pred_trophic = predict(m_trophic,
newdata = data.frame(X = X, A = m_A$fitted.values))
all.equal(pred_SDM, pred_trophic)
#> [1] "Mean relative difference: 2.915665"
# Predictions are improved by trophic SDM
## AUC of species B for SDM
dismo::evaluate(p = pred_SDM[which(B==1)],
a = pred_SDM[which(B==0)] )@auc
#> [1] 0.8408333
## AUC of species B for trophic SDM
dismo::evaluate(p = pred_trophic[which(B==1)],
a = pred_trophic[which(B==0)] )@auc
#> [1] 0.8529167
```
The relationship between the coefficients of the two models does not hold anymore more, and predictions are now different, with trophic SDM that slightly improve classic SDM (AUC of species $y_B$ goes from 0.84 to 0.85).
### Non-linear statistical model
We finally show how using a non-linear statistical model leads to different predictions between classical SDMs and a trophic SDM with the example of a random forest. Since we cannot provide any analytical derivation for random forest, we simply provide an example.
Data are simulated exactly as in the very first examples (continuous observable entities).
```r
# Simulate data for the basal species A
A = 3*X + 2*X^2 + rnorm(100, sd = 5)
# Simulate data for the predator species B
B = 2*X -3*X^2 + 3*A + rnorm(100, sd = 5)
oldpar = par()
par(mfrow=c(1,3))
plot(X,A, main = "Species A realised \n and potential niche")
plot(X,B, main = "Species B realised niche")
plot(X, 2*X -3*X^2, main = "Species B potential niche")
```

```r
par(mfrow = oldpar$mfrow)
```
We infer statistical models with random forest
```r
library(randomForest)
#> randomForest 4.7-1.1
#> Type rfNews() to see new features/changes/bug fixes.
# Species A
m_A = randomForest(A ~ X + I(X^2))
# Species B trophic SDM
m_trophic = randomForest(B ~ X + I(X^2) + A)
# Species B classic SDM
m_SDM <- randomForest(B ~ X + I(X^2))
```
We now compare the predictions from the two models.
```r
# Prediction are now different
pred_SDM = m_SDM$predicted
pred_trophic = predict(m_trophic,
newdata = data.frame(X = X, A = m_A$predicted))
all.equal(pred_SDM, pred_trophic)
#> [1] "Mean relative difference: 0.08021014"
#Compare R2
cor(B, pred_SDM)^2
#> [1] 0.8075415
cor(B, pred_trophic)^2
#> [1] 0.8670482
```
Predictions from the model are different, and trophic SDM has a larger R2 than classical SDMs (0.86 versus 0.80).
|
/scratch/gouwar.j/cran-all/cranData/webSDM/inst/doc/Differences_with_SDMs.Rmd
|
---
title: "Introduction to trophic SDM"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Introduction to trophic SDM}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
In this vignette we explain how to fit, evaluate and interpret a trophic species distribution model (trophic SDM). Trophic SDM is a statistical model to model the distribution of species accounting for their known trophic interactions. We refer to Poggiato et al., "Integrating trophic food webs in species distribution models improves ecological niche estimation and prediction", in preparation for the full description of trophic SDM.
## Install and load webSDM
```r
library(devtools)
# Run to install webSDM
# install_github("giopogg/webSDM")
library(webSDM)
library(bayesplot)
library(gridExtra)
library(reshape2)
library(ggplot2)
library(loo)
set.seed(1234)
```
## Simulate data
For illustrative purposes, we use simulated data for which we know the parameter values. We thus simulate a trophic interaction network and species distribution for six species, whose names are ordered accordingly to their trophic level (Y1 being basal and Y6 being at the highest trophic position). We simulate data with a stronger dependence on the abiotic variables for species in lower trophic levels, and increasing dependence on the biotic terms (i.e., their preys) for species with a higher trophic level. We will then use trophic SDM and see if the model can retrieve this simulate process and the species potential niches.
### Create trophic interaction network
We first create the trophic interaction network. The network needs to be a directed acyclic graph (DAG), with arrows pointing from predator to prey. We thus simulate an interaction network such that species only have prey in a lower trophic position.
```r
# Set number of species
S = 6
# Create the adjacency matrix of the graph
A = matrix(0,nrow=S,ncol=S)
# Ensure that the graph is connected
while(!igraph::is.connected(igraph::graph_from_adjacency_matrix(A))){
A = A_w = matrix(0,nrow=S,ncol=S)
# Create links (i.e. zeros and ones of the adjacency matrix)
for(j in 1:(S-1)){
A[c((j+1):S),j] = sample(c(0,1), S-j, replace = T)
}
# Sample weights for each link
#A_w[which(A != 0)] = runif(1,min=0,max=2)
}
colnames(A) = rownames(A) = paste0("Y",as.character(1:S))
# Build an igraph object from A
G = igraph::graph_from_adjacency_matrix(A)
plot(G)
```

### Simulate data
We now simulate species distribution at 300 locations along two environmental gradients. We simulate species such that species Y1 to Y3 have a negative dependence to the first environmental variable X_1 and a positive dependence to X_2, viceversa for species Y4 to Y6. Moreover, the strength of the environmental term decreases along the trophic level, while the effect of the prey increases. Finally, preys always have a positive effect on predators.
```r
# Number of sites
n = 500
# Simulate environmental gradient
X_1= scale(runif(n, max = 1))
X_2= scale(runif(n, max = 1))
X = cbind(1, X_1^2, X_2^2)
B = matrix(c(1, 1, 1, 1, 1, 1,
-2, -2, -2, 2, 2, 2,
2, 2, 2, -2, -2, -2
), ncol = 3)
# Sample the distribution of each species as a logit model as a function of the
# environment and the distribution of preys
Y = V = prob = matrix(0, nrow = n, ncol = S)
for(j in 1:S){
# The logit of the probability of presence of each species is given by the
# effect of the environment and of the preys.
# Create the linear term. As j increases, the weight of the environmental effect
# decreases and the biotic effect increases
eff_bio = seq(0.1, 0.9, length.out = S)[j]
eff_abio = seq(0.1, 0.9, length.out = S)[S+1-j]
V[,j]= eff_abio*X%*%B[j,] + eff_bio*Y%*%A[j,]*3
# Transform to logit
prob[,j] = 1/(1 + exp(-V[,j]))
# Sample the probability of presence
Y[,j] = rbinom(n = n, size = 1, prob = prob[,j])
}
# Set names
colnames(Y) = paste0("Y",as.character(1:S))
```
## Fit trophic SDM
Now that we simulate the data, we can fit a species distribution model with the function `trophicSDM`. The function requires the species distribution data `Y` (a sites x species matrix), the environmental variables `X` and an igraph object `G` representing the trophic interaction network. Importantly, `G` must be acyclic and arrows must point from predator to prey. Finally, the user has to specify a formula for the environmental part of the model and the description of the error distribution and link function to be used in the model (parameter `family`), just as with any `glm`.
By default, `trophicSDM` models each species as a function of their prey (set `mode = "predator"` to model species as a function of their predators) and of the environmental variables (as defined in `env.formula`). Trophic SDM can be also fitted as a function of the summary variables of preys (i.e. composite variables like prey richness), instead of each prey species directly. We cover this topic in the vignette 'Composite variables'.
The algorithm behind trophic SDM fits a set of generalised linear model (glm), one for each species. These glm can be fitted in the frequentist framework by relying on the function `glm` (set `method = "glm"`), or in the Bayesian framework by relying on the function `rstanarm` (set `method = "stan_glm"`, the default choice). Model fitting is parallelised if `run.parallel = TRUE`.
These glm can be penalised to shrink regression coefficients (by default the model is run without penalisation). In the Bayesian framework set `penal = "horshoe"` to implement penalised glm using horshoe prior. In the frequentist framework set `penal = "elasticnet"` to implement penalised glm with elasticnet. See the examples in `?trophicSDM`.
Hereafter, we only fit trophic SDM in the Bayesian framework with no penalisation. However, all the functions and analyses (except for MCMC diagnostic) presented in this vignette applies straightforwardly with or without penalisation and in the frequentist framework.
Hereafter we model species as a function of preys and the two environmental covariates in the Bayesian framework without penalisation. We though need to specify the parameters of the MCMC chains. We need to decide how many chains to sample (`chains`), how many samples to obtain per chain (`iter`), and if we wish to see the progress of the MCMC sampling (`verbose`).
```r
iter = 1000
verbose = FALSE
nchains = 2
```
We are now ready to fit a trophic SDM.
```r
X = data.frame(X_1 = X_1, X_2 = X_2)
m = trophicSDM(Y = Y, X = X, G = G,
env.formula = "~ I(X_1^2) + I(X_2^2)",
family = binomial(link = "logit"),
method = "stan_glm", chains = nchains, iter = iter, verbose = verbose)
```
### A trophicSDMfit object
The fitted model `m` is of class `"trophicSDMfit"`. We also show here the formulas used to fit the each glm, where each predator is modeled as a function of the preys and of the environmental variables.
```r
m
#> ==================================================================
#> A trophicSDM fit with no penalty, fitted using stan_glm
#> with a bottom-up approach
#>
#> Number of species : 6
#> Number of links : 10
#> ==================================================================
#> * Useful fields
#> $coef
#> * Useful S3 methods
#> print(), coef(), plot(), predict(), evaluateModelFit()
#> predictFundamental(), plotG(), plotG_inferred(), computeVariableImportance()
#> * Local models (i.e. single species SDM) can be accessed through
#> $model
class(m)
#> [1] "trophicSDMfit"
m$form.all
#> $Y1
#> [1] "y ~ I(X_1^2) + I(X_2^2)"
#>
#> $Y2
#> [1] "y ~ I(X_1^2)+I(X_2^2)+Y1"
#>
#> $Y3
#> [1] "y ~ I(X_1^2)+I(X_2^2)+Y1+Y2"
#>
#> $Y4
#> [1] "y ~ I(X_1^2)+I(X_2^2)+Y1+Y3"
#>
#> $Y5
#> [1] "y ~ I(X_1^2)+I(X_2^2)+Y1+Y3+Y4"
#>
#> $Y6
#> [1] "y ~ I(X_1^2)+I(X_2^2)+Y3+Y5"
```
## Analyse a fitted trophicSDM
The field `$model` contains all the the single species glm (i.e., all the local models). `$data` and `trophicSDM` contains informations on the data and choices to fit the model respectively. `$form.all` contains the formula used to fit each glm (i.e., both abiotic and biotic terms). `$coef` contains the inferred regression coefficients of the glm for all species. `$AIC` and `$log.lik` are respectively the AIC and log-likelihood of the fitted trophic SDM. Finally, in the Bayesian framework, the field `$mcmc.diag` contains the convergence diagnostic metrics of the MCMC chains for each species.
In this vignette, we first ensure that the MCMC chains correctly converged. Then, we analyse the inferred model, by focusing in particular on the effect of the biotic versus abiotic terms. We then analyse the predictive performances of the model (comparing it to environment-only SDM) and use it to predict the species potential niches.
### MCMC convergence
First, we can have a look at effective sample size to total sample size and of the potential scale reduction factor (aka 'R hat') for each species. Each line corresponds to a given parameter.
```r
# Plot mcmc potential scale reduction factor (aka rhat)
p1 = mcmc_rhat(m$mcmc.diag$rhat)
# Plot mcmc ratio of effective sample size to total sample size
p2 = mcmc_neff(m$mcmc.diag$neff.ratio)
grid.arrange(p1, p2, ncol = 2)
```

We observe that the effective sample sizes are very close to the theoretical value of the actual number of samples, as the ratio is close to 1. In few cases the ratio is lower, and we might consider running the chains for longer, or thin them, to improve convergence. This indicates that there is very little autocorrelation among consecutive samples. The potential scale reduction factors are very close to one, which indicates that two chains gave consistent results.
We can have a closer look to the MCMC chains by looking at the traceplots of the parameters of a given model, for example here for species Y5 who feeds on species Y1, Y2, Y3 and Y4. To do so, we first assess the local model of species Y5, and in particular its field `$model` that gives us the output of the function `stan_glm`. We can then exploit the plot method of this object.
```r
plot(m$model$Y5$model, "trace")
```

Again, we see that the chains mix very well and that there's little autocorrelation among samples within the same chain.
### Parameter estimates and interpretation
We now analyse the estimates of the regression coefficients. We can have a first glance of the regression coefficients with the function plot. This function plots the posterior distribution of the regression coefficients of each species.
```r
plot(m)
```

We can visually see that the regression coefficients for the environmental part of the model match the simulated parameters, as species Y1 to Y3 have a positive response to X_1 and a negative one to X_2, viceversa for species Y3 to Y6. We also remark that the environmental coefficients are less important for basal species than for predators. Indeed, the posterior mean of the regression coefficients of the environmental part gets closer to zero and their posterior distribution tend to overlap zero more and more as we move from species Y1 to species Y6. We can quantify this visual assessment by looking at the posterior mean and quantile of the regression coefficients. The parameter `level` set the probability of the quantile (default 0.95).
```r
coef(m, level = 0.9)
#> $Y1
#> mean 5% 95%
#> (Intercept) 1.193315 0.8631366 1.551786
#> I(X_1^2) -2.153769 -2.4827322 -1.854351
#> I(X_2^2) 1.904532 1.5618766 2.281827
#>
#> $Y2
#> mean 5% 95%
#> (Intercept) 0.4378192 -0.05096073 0.9425659
#> I(X_1^2) -1.3103497 -1.64827655 -0.9781233
#> I(X_2^2) 1.6693748 1.28262664 2.0953004
#> Y1 1.1014760 0.60271353 1.6253656
#>
#> $Y3
#> mean 5% 95%
#> (Intercept) 0.9246159 0.3048754 1.537713
#> I(X_1^2) -1.3782372 -1.7729318 -1.011603
#> I(X_2^2) 1.2837309 0.8501504 1.799605
#> Y1 0.8750454 0.2487845 1.523552
#> Y2 1.3356857 0.7836524 1.874160
#>
#> $Y4
#> mean 5% 95%
#> (Intercept) -0.149971 -0.9501498 0.6711274
#> I(X_1^2) 1.132746 0.7019883 1.5938620
#> I(X_2^2) -1.138931 -1.5981180 -0.6976561
#> Y1 2.550784 1.6477388 3.4849039
#> Y3 2.000125 1.2299528 2.9196692
#>
#> $Y5
#> mean 5% 95%
#> (Intercept) 0.5422551 -0.76409358 2.0854414
#> I(X_1^2) 0.9843555 0.02913223 2.0103196
#> I(X_2^2) -1.4438633 -2.74833106 -0.2571721
#> Y1 3.0216650 0.36971766 6.3588373
#> Y3 4.4991171 2.06335620 7.4694324
#> Y4 1.9616552 0.64162409 3.4955833
#>
#> $Y6
#> mean 5% 95%
#> (Intercept) -0.18963593 -2.0485881 1.5794885
#> I(X_1^2) 0.06055848 -0.9455691 0.9899717
#> I(X_2^2) -0.18911690 -1.2013288 0.8962215
#> Y3 3.62070445 1.1223913 6.5666245
#> Y5 3.69026866 2.1993395 5.4164494
```
Notice that regression coefficients are directly available in the field `$coef` of an object trophicSDMfit (with `level = 0.95`). As we previously hinted, we see that the estimate of the regression coefficients of the environmental part get closer and closer to zero with credible interval that often overlap zero (implying they are not significant with a confidence level of 10%) for species with a higher trophic level. In order to be able to correctly quantify the effect of the different predictors across species (i.e., their relative importance), we need to standardise the regression coefficients (see Grace et al. 2018). To do so, we need to set `standardise = TRUE`.
```r
coef(m, level = 0.9, standardise = T)
#> $Y1
#> estimate 5% 95%
#> (Intercept) 1.1933152 1.1933152 1.1933152
#> I(X_1^2) -0.6032735 -0.6954163 -0.5194061
#> I(X_2^2) 0.5524401 0.4530474 0.6618806
#>
#> $Y2
#> estimate 5% 95%
#> (Intercept) 0.4378192 0.43781923 0.4378192
#> I(X_1^2) -0.3967764 -0.49910135 -0.2961777
#> I(X_2^2) 0.5234732 0.40219885 0.6570325
#> Y1 0.1815471 0.09934023 0.2678954
#>
#> $Y3
#> estimate 5% 95%
#> (Intercept) 0.9246159 0.92461585 0.9246159
#> I(X_1^2) -0.4018688 -0.51695451 -0.2949649
#> I(X_2^2) 0.3876289 0.25670715 0.5433997
#> Y1 0.1388822 0.03948565 0.2418093
#> Y2 0.2027708 0.11896649 0.2845168
#>
#> $Y4
#> estimate 5% 95%
#> (Intercept) -0.1499710 -0.1499710 -0.1499710
#> I(X_1^2) 0.4526599 0.2805236 0.6369279
#> I(X_2^2) -0.4713231 -0.6613485 -0.2887107
#> Y1 0.5548413 0.3584128 0.7580292
#> Y3 0.3802667 0.2338405 0.5550919
#>
#> $Y5
#> estimate 5% 95%
#> (Intercept) 0.5422551 0.542255094 0.54225509
#> I(X_1^2) 0.2863784 0.008475438 0.58486205
#> I(X_2^2) -0.4350071 -0.828017071 -0.07748081
#> Y1 0.4785091 0.058548274 1.00698178
#> Y3 0.6227408 0.285597372 1.03387396
#> Y4 0.1816850 0.059426083 0.32375471
#>
#> $Y6
#> estimate 5% 95%
#> (Intercept) -0.18963593 -0.1896359 -0.1896359
#> I(X_1^2) 0.02223722 -0.3472152 0.3635200
#> I(X_2^2) -0.07191471 -0.4568244 0.3408025
#> Y3 0.63254324 0.1960837 1.1472005
#> Y5 0.17891028 0.1066276 0.2625983
```
This results confirms the previous analysis. We can analyse the relative importance of different group of variables with the function `computeVariableImportance`. This function can take as input the definition of groups of variables in the argument `groups` (by default, with `groups = NULL`, each explanatory variable is a different group). The variable importance of groups of variables is computed as the standardised regression coefficients summed across variable of the same group.
We hereafter use this function to compute the relative importance of the abiotic versus biotic covariates.
```r
VarImpo = computeVariableImportance(m,
groups = list("Abiotic" = c("X_1","X_2"),
"Biotic" = c("Y1","Y2", "Y3", "Y4", "Y5", "Y6")))
VarImpo = apply(VarImpo, 2, function(x) x/(x[1]+x[2]))
tab = reshape2::melt(VarImpo)
tab$Var2 = factor(tab$Var2, levels = colnames(Y))
ggplot(tab, aes(x = Var2, y = value, fill = Var1)) + geom_bar(stat="identity") +
theme_classic()
```

We clearly see that our model correctly retrieved the simulated pattern, with the importance of biotic variables with respect to the abiotic ones becomes greater as the trophic level increases.
Finally, we can visualise the effect of each trophic interactions with the function `plotG_inferred`, which plots the metaweb `G` together with the variable importance (i.e. the standardised regression coefficient) of each link. The parameter `level` sets the confidence level with which coefficients are deemed as significant or non-significant.
```r
plotG_inferred(m, level = 0.9)
```

We see that the model correctly retrieves that preys have a posite effect on the predators and that this effect becomes more important for predators at higher trophic positions.
### Analysis of local models
In order to examine the package and practice with it, we here show how to easily manipulate local models, i.e. each glm (that can be seen as a single species SDMs), the smallest pieces of trophic SDM. These local models belong to the class "SDMfit", for which multiple methods exists. We hereafter show how to some of these methods for species Y6.
```r
SDM = m$model$Y6
# The formula used to fit the model
SDM$form.all
#> [1] "y ~ I(X_1^2)+I(X_2^2)+Y3+Y5"
# The inferred model
plot(SDM)
```

```r
# The regression coefficients
coef(SDM, level = 0.9, standardise = T)
#> estimate 5% 95%
#> (Intercept) -0.18963593 -0.1896359 -0.1896359
#> I(X_1^2) 0.02223722 -0.3472152 0.3635200
#> I(X_2^2) -0.07191471 -0.4568244 0.3408025
#> Y3 0.63254324 0.1960837 1.1472005
#> Y5 0.17891028 0.1066276 0.2625983
```
We can also predict the probability of presence of species Y6 at a site with X_1 = 0.5, X_2 = 0.5, assuming its preys to be present present.
```r
preds = predict(SDM, newdata = data.frame(X_1 = 0.5, X_2 = 0.5, Y3 = 1, Y5 = 1))
# Posterior mean of the probability of presence
mean(preds$predictions.prob)
#> [1] 0.9983807
```
We see that the species has a high probability of presence in this environmental conditions when its prey are present.
## Predictions with trophic SDM
We showed how to fit and analyse a trophic SDM and how to predict a single species (Y6 in the previous section), when we can fix the distribution of its prey. However, the distribution of prey is typically unavailable when we want to predict the distribution of species at unobserved sites and/or under future environmental conditions. Intuitively, in a simple network of two trophic level we would need to predict the prey first and use these predictions to predict the predator. To generalize this idea to complex networks, we predict species following the topological ordering of the metaweb. This order that exists for every DAG guarantees that when predicting a given species, all its prey will have already been predicted.
The function `predict` computes the topological order of species, and then predicts them sequentially. As any `predict` function, it takes into account the values of the environmental variables in the argument `Xnew`. We can provide to the function the number of samples from the posterior distribution.
```r
pred = predict(m, Xnew = data.frame(X_1 = 0.5, X_2 = 0.5), pred_samples = 100)
dim(pred$Y2)
#> [1] 1 100
```
By default, the function `predict` transforms the probability of presence of prey in presence-absence, and then use these presence-absences to predict the predator. However, we can use directly the probability of presence of prey by setting `prob.cov = TRUE`.
Pred is a list containing the posterior distribution of the predicted probability of presence of each species (i.e., number of sites x pred_samples). Notice that we can ask the function to directly provide a summary of the posterior distribution (i.e. posterior mean and 95% quantiles) of the probabilities of presence by setting `fullPost = FALSE`. As for `trophicSDM`, we can choose to parallelise some parts of the `predict` function by setting `run.parallel = TRUE` (which can speed up computational times).
```r
pred = predict(m, Xnew = data.frame(X_1 = 0.5, X_2 = 0.5), pred_samples = 100,
fullPost = FALSE, run.parallel = FALSE)
pred$Y2
#> $predictions.mean
#> 1
#> 0.7984008
#>
#> $predictions.q025
#> 1
#> 0.5854847
#>
#> $predictions.q975
#> 1
#> 0.8850332
```
## Model evaluation
We now want to evaluate how well the model fits the data and how well it generalises to new data with respect to classical SDM. We thus first run a classical SDM, by providing an empty graph to `trophicSDM`. Then, we will compare model AIC and their predictive performances both on the training data and in cross-validation. Notice that when we compare classical SDM and trophic SDM it is important to account for the fact that trophic SDM have a higher number of parameters, and will therefore have, by default, a higher fit on the the training data.
```r
empty_graph = graph_from_adjacency_matrix(matrix(0, nrow = S, ncol = S,
dimnames = list(colnames(Y), colnames(Y))))
m_classic = trophicSDM(Y = Y, X = X,
G = empty_graph,
env.formula = "~ I(X_1^2) + I(X_2^2)", family = binomial(link = "logit"),
method = "stan_glm", chains = nchains, iter = iter, verbose = verbose)
```
### AIC, loo
We first compare model AIC and an approximation of the leave-one-out cross-validation log-likelihood (loo, see Vehtari, A. et al 2017). AIC penalises the likelihood of the model as a function of the number of model parameter, while loo approximate the likelihood of the model on leave-one out cross validation. Therefore, both these metrics can be used to correctly compare the two approaches
```r
m$AIC
#> [1] 1455.775
m_classic$AIC
#> [1] 1584.531
loo(m)
#> Warning: Found 6 observation(s) with a pareto_k > 0.7. We recommend calling 'loo' again with argument 'k_threshold = 0.7' in order to calculate the ELPD without the assumption that these observations are negligible. This will refit the model 6 times to compute the ELPDs for the problematic observations directly.
#> [1] -707.626
loo(m_classic)
#> [1] -777.2048
```
We see that our trophic model has a lower AIC and a higher loo, which proves that including prey improves the model.
### Interpolation
We now compare the predictive performance of the two approaches on the training dataset. To do so, we first use the function `predict`, and then the function `evaluateModelFit` to compare how well predictions match the true data.
```r
# Trophic SDM (when Xnew is not specified, predictions are carried on
# the training dataset by setting Xnew = m$data$X)
Ypred = predict(m, fullPost = FALSE)
# Transfom in a table
Ypred = do.call(cbind,
lapply(Ypred, function(x) x$predictions.mean))
# Re order columns
Ypred = Ypred[,colnames(Y)]
metrics = evaluateModelFit(m, Ynew = Y, Ypredicted = Ypred)
# Classical SDM
Ypred_classic = predict(m, fullPost = FALSE)
Ypred_classic = do.call(cbind,
lapply(Ypred_classic, function(x) x$predictions.mean))
Ypred_classic = Ypred_classic[,colnames(Y)]
metrics_classic = evaluateModelFit(m, Ynew = Y, Ypredicted = Ypred_classic)
# Mean AUC
mean(metrics$auc)
#> [1] 0.7937958
mean(metrics_classic$auc)
#> [1] 0.8031646
# Mean TSS
mean(metrics$tss)
#> [1] 0.5325318
mean(metrics_classic$tss)
#> [1] 0.5312451
```
On the training dataset models have similar performances, with our trophic model that slightly improves SDM's TSS.
### Cross-validation
We now compare the two approaches in K-fold cross validation with the function `trophicSDM_CV`. This function creates a partition based on the specified number of fold (but can also takes a user-specified partition in the argument `partition`) and run a cross validation. This can take a bit of time. Set `run.parallel = TRUE` if you want to reduce computation time.
```r
# 3-fold cross validation
CV = trophicSDM_CV(m, K = 3, prob.cov = T, iter = 2000,
pred_samples = 500, run.parallel = FALSE)
#> [1] "Fold 1 out of 3 \n"
#> [1] "Fold 2 out of 3 \n"
#> [1] "Fold 3 out of 3 \n"
# Transfom in a table
Ypred = CV$meanPred
# Re order columns
Ypred = Ypred[,colnames(Y)]
metrics = evaluateModelFit(m, Ynew = Y, Ypredicted = Ypred)
# Classical SDM
# We specify the same partition for classic SDM so that the two cross-validations are comparable.
CV_classic = trophicSDM_CV(m_classic, K = 3, prob.cov = T, iter = 2000,
pred_samples = 500, run.parallel = FALSE,
partition = CV$partition)
#> [1] "Fold 1 out of 3 \n"
#> [1] "Fold 2 out of 3 \n"
#> [1] "Fold 3 out of 3 \n"
Ypred_classic = CV_classic$meanPred
Ypred_classic = Ypred_classic[,colnames(Y)]
metrics_classic = evaluateModelFit(m, Ynew = Y, Ypredicted = Ypred_classic)
# Mean AUC
mean(metrics$auc)
#> [1] 0.6999403
mean(metrics_classic$auc)
#> [1] 0.668446
# Mean TSS
mean(metrics$tss)
#> [1] 0.4260548
mean(metrics_classic$tss)
#> [1] 0.3773521
```
The increase in mean AUC and TSS is even higher in 3-fold cross-validation than on the fitted data. As we simulated the data with a strong biotic signal, trophic SDM proves to be a better tool than classic SDM.
## Potential niche
We also implemented a function to predict species potential niches, defined as the probability of presence of species along the environmental gradient when the biotic constrain is realised, i.e., when all its prey are set to present (vice-versa, when modeling species top-down, when the predator are absent). We here compute the probability of presence of species at environmental conditions X_1= 0.5, X_2 = 0.5 when the preys are available.
```r
preds = predictPotential(m, Xnew = data.frame(X_1 = 0.5, X_2 = 0.5))
#> Error in predictPotential(m, Xnew = data.frame(X_1 = 0.5, X_2 = 0.5)): could not find function "predictPotential"
# Take the posterior mean
lapply(preds,mean)
#> Warning in mean.default(X[[i]], ...): l'argomento non è numerico o logico: si restituisce NA
#> $predictions.prob
#> [1] 0.9983807
#>
#> $predictions.bin
#> [1] NA
```
## Author
This package is currently developed by Giovanni Poggiato from Laboratoire d’Ecologie Alpine. It is supported by the ANR GAMBAS. The framework implemented in this package is described in: "Integrating trophic food webs in species distribution models improves ecological niche estimation and prediction" Poggiato Giovanni, Jérémy Andréoletti, Laura J. Pollock and Wilfried Thuiller. In preparation.
## References
Grace, J. B., Johnson, D. J., Lefcheck, J. S., and Byrnes, J. E. K.. 2018. Quantifying relative importance: computing standardized effects in models with binary outcomes. Ecosphere 9(6):e02283.
Vehtari, A., Gelman, A., and Gabry, J. (2017). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing. 27(5), 1413–1432.
|
/scratch/gouwar.j/cran-all/cranData/webSDM/inst/doc/Introduction.Rmd
|
---
title: "Composite variables and biotic-abiotic interactions"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Composite variables and biotic-abiotic interactions}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
In this vignette we explain how to use composite variables in trophic SDM. These variables are useful especially in species-rich network, where some predators might have so many preys that assuming that each of them has a differential effect on predator distribution is not only a problem, but might seem ecologically unjustified. Instead, we could expect the richness or diversity of prey, or whether at least a prey is available, to be important. Hence, we implemented the use of composite variables, i.e., variables that summarize the information of a large number of variables from the graph in a few summary variables. Examples of composite variables are prey richness or diversity, or a binary variable set to one if the number of preys is above a certain threshold. These variables assume that all species have the same impact on the predator. An alternative is to group species in the metaweb to represent trophic groups that clump together species that feed on, or are eaten by, the same type of species. We can then construct composite variables (e.g., their richness) for each of those trophic groups to better represent the variety of resources for species like generalist or top predators.
In `webSDM` it is possible to define an extremely large set of composite variables using the arguments `sp.formula` and `sp.partition`. In general, `sp.formula` allows the definition of the composite variables, while `sp.partition` allow to define the groups of preys (or predator) for which each composite variable is calculate.
Hereafter we don't provide a complete analyses of a case-study using composite variables, but rather focus on the description of how to implement them in `webSDM`.
Finally, we will see how to include an interaction between preys and the environment.
```r
library(webSDM)
data(X ,Y, G)
```
## Composite variables
`sp.formula` can be a right hand side formula including richness (i.e. the sum of its preys) and any transformations of richness. Notice that only "richness" is allowed for now. However, we will see how this already allow to build an extremely large set of composite variable. We start with a simple case where we model species as a function of the richness of their prey, with a polynomial of degree two.
```r
m = trophicSDM(Y, X, G,
env.formula = "~ X_1 + X_1^2",
family = binomial(link = "logit"), penal = NULL,
sp.formula = "richness + I(richness^2)",
mode = "prey", method = "glm")
#> Formula was modified since it led to identical columns of the design matrix (e.g. Y_1 or Y_1^2 for binary data)
```
Notice that for predators that feed on a single prey (with presence-absence data), their richness and the square of their richness is exactly the same variable. In this case, `trophicSDM()` removes the redundant variable but prints a warning message.
We can see the formulas created by the argument `$form.all` of the fitted model.
```r
m$form.all
#> $Y1
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y2
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y3
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y5
#> [1] "y ~ X_1+I(Y1 + Y2 + Y3)+I(I(Y1 + Y2 + Y3)^2)"
#>
#> $Y4
#> [1] "y ~ X_1+I(Y3)"
#>
#> $Y6
#> [1] "y ~ X_1+I(Y3 + Y5)+I(I(Y3 + Y5)^2)"
```
We now set as composite variable a dummy variable specifying whether there is at least one available prey or not. To do so we define `sp.formula = "I(richness>0)"`.
```r
m = trophicSDM(Y,X,G,
env.formula = "~ X_1 + X_1^2",
family = binomial(link = "logit"), penal = NULL,
sp.formula = "I(richness>0)",
mode = "prey", method = "glm")
```
Which leads to the following formulas:
```r
m$form.all
#> $Y1
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y2
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y3
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y5
#> [1] "y ~ X_1+I(I(Y1 + Y2 + Y3) > 0)"
#>
#> $Y4
#> [1] "y ~ X_1+I(I(Y3) > 0)"
#>
#> $Y6
#> [1] "y ~ X_1+I(I(Y3 + Y5) > 0)"
```
## Composite variables and groups of preys
A halfway between considering that each species has a differential effect on the predator (i.e., no composite variable), or that every prey has the same effect (i.e., modeling predator as a function of prey richness), is to create group of species that we assume to have the same effect on the predator. Then, we can model predator as a function of composite variables calculated on each of these groups. To do so, we rely on the argument `sp.partition`. This parameters has to be a list, where each element contain the species of the given group.
For example, we can put species Y1 and Y2 in the same group, species Y3 and Y4 are alone in their group and Y5 and Y6 to form another group.
```r
sp.partition = list(c("Y1","Y2"),c("Y3"),c("Y4"), c("Y5","Y6"))
```
Then, we can specify whatever `sp.formula`, for example using richness (with a quadratic term).
```r
m = trophicSDM(Y,X,G, "~ X_1 + X_1^2",
family = binomial(link = "logit"), penal = NULL,
sp.partition = sp.partition,
sp.formula = "richness + I(richness^2)",
mode = "prey", method = "glm")
#> Formula was modified since it led to identical columns of the design matrix (e.g. Y_1 or Y_1^2 for binary data)
#> Formula was modified since it led to identical columns of the design matrix (e.g. Y_1 or Y_1^2 for binary data)
#> Formula was modified since it led to identical columns of the design matrix (e.g. Y_1 or Y_1^2 for binary data)
```
Which leads to the following formulas:
```r
m$form.all
#> $Y1
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y2
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y3
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y5
#> [1] "y ~ X_1+I((Y1 + Y2))+I(I((Y1 + Y2)^2))+I((Y3))"
#>
#> $Y4
#> [1] "y ~ X_1+I((Y3))"
#>
#> $Y6
#> [1] "y ~ X_1+I((Y3))+I((Y5))"
```
## Custom formula
In case we want to specify a composite variable that cannot be created from a function of richness, the user can specify directly the list of the biotic formulas in the `sp.formula` argument. Importantly, notice that in this case `trophicSDM()` will not create a new formula from the argument `G` and will not check that the user-defined formula actually derives from `G` (i.e. that predator-prey interactions described in the formulas derive from G). For example, we might want to quantify the effect of the prey Y5 on the predator Y6 when the prey Y3 is not available. To do so, we define for species Y6 an interaction term between species Y5 and one minus Y3 (i.e. a dummy variable that takes the value of 1 when species Y5 is present and Y3 is absent). To do so, we define `sp.formula` as a list describing the biotic formula for each species.
```r
sp.formula = list(Y1 = "",
Y2 = "",
Y3 = "",
Y4 = "Y3",
Y5 = "Y1",
Y6 = "I(Y5*(1-Y3))")
m = trophicSDM(Y,X,G, "~ X_1 + X_1^2",
family = binomial(link = "logit"), penal = NULL,
sp.formula = sp.formula,
mode = "prey", method = "glm")
#> We don't check that G and the graph induced by the sp.formula specified by the user match, nor that the latter is a graph. Please be careful about their consistency.
m$form.all
#> $Y1
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y2
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y3
#> [1] "y ~ X_1 + X_1^2"
#>
#> $Y5
#> [1] "y ~ X_1+Y1"
#>
#> $Y4
#> [1] "y ~ X_1+Y3"
#>
#> $Y6
#> [1] "y ~ X_1+I(Y5 * (1 - Y3))"
```
## On computeVariableImportance with composite variable
When computing the importance of variables using the function `computeVariableImportance`, you should be careful with the definition of groups. Indeed, the function computes the variable importance of each group as the sum of the standardised regression coefficients containing some variables from the groups. Therefore, if species from different groups of variable are merged in the same composite variable, `computeVariableImportance` will sum the regression coefficient of the composite variable in different groups, leading to wrong results. For example, if `sp.formula = "richness"` and `sp.partition = NULL`, you should put all species in the same group in the argument `groups`.
```r
m = trophicSDM(Y,X,G,
env.formula = "~ X_1 + X_1^2",
family = binomial(link = "logit"), penal = NULL,
sp.formula = "richness + I(richness^2)",
mode = "prey", method = "glm")
#> Formula was modified since it led to identical columns of the design matrix (e.g. Y_1 or Y_1^2 for binary data)
computeVariableImportance(m, groups = list("abiotic" = c("X_1", "X_2"),
"biotic" = c("Y1", "Y2", "Y3",
"Y4", "Y5", "Y6")))
#> Warning in computeVariableImportance(m, groups = list(abiotic = c("X_1", : If you use composite variables, you
#> should group together species that belong to the same composite variable. For example, if sp.formula = 'richness' and
#> sp.partition = NULL, you should put all species in the same group in the argument 'groups'. If you define a partition
#> of species in sp.partition, then species in the same group in sp.partition should put all species in the same group
#> in the argument 'groups'
#> Y1 Y2 Y3 Y5 Y4 Y6
#> abiotic 0 0 0 0.05380788 0.17251449 0.04623329
#> biotic 0 0 0 0.08470730 0.07633953 0.38116851
```
If you use composite variables, you should group together species that belong to the same composite variable.If you define a partition of species in sp.partition, then species in the same group in sp.partition should put all species in the same group in the argument 'groups'.
```r
sp.partition = list(c("Y1","Y2"),c("Y3"),c("Y4"), c("Y5","Y6"))
m = trophicSDM(Y,X,G, "~ X_1 + X_1^2",
family = binomial(link = "logit"), penal = NULL,
sp.partition = sp.partition,
sp.formula = "richness + I(richness^2)",
mode = "prey", method = "glm")
#> Formula was modified since it led to identical columns of the design matrix (e.g. Y_1 or Y_1^2 for binary data)
#> Formula was modified since it led to identical columns of the design matrix (e.g. Y_1 or Y_1^2 for binary data)
#> Formula was modified since it led to identical columns of the design matrix (e.g. Y_1 or Y_1^2 for binary data)
computeVariableImportance(m, groups = list("abiotic" = c("X_1", "X_2"),
"Group1" = c("Y1", "Y2"),
"Group2" = c("Y3"),
"Group3" = c("Y4", "Y5", "Y6")))
#> Warning in computeVariableImportance(m, groups = list(abiotic = c("X_1", : If you use composite variables, you
#> should group together species that belong to the same composite variable. For example, if sp.formula = 'richness' and
#> sp.partition = NULL, you should put all species in the same group in the argument 'groups'. If you define a partition
#> of species in sp.partition, then species in the same group in sp.partition should put all species in the same group
#> in the argument 'groups'
#> Y1 Y2 Y3 Y5 Y4 Y6
#> abiotic 0 0 0 0.1016899 0.17251449 0.03603087
#> Group1 0 0 0 0.8621983 0.00000000 0.00000000
#> Group2 0 0 0 0.2581345 0.07633953 0.22671385
#> Group3 0 0 0 0.0000000 0.00000000 0.11579149
```
## Interaction with biotic and abiotic terms
Assuming that the effect of prey on predators does not vary with environmental conditions might be a too strong assumption. In order to integrate species plasticity, it is possible to define a `sp.formula` that includes both biotic and abiotic terms. For example, we hereafter define an interaction between the prey and the environmental variable X_2.
```r
sp.formula = list(Y1 = "",
Y2 = "",
Y3 = "",
Y4 = "I(X_2*Y3)",
Y5 = "I(X_2*Y1)",
Y6 = "I(X_2*Y3) + I(X_2*Y5)")
m = trophicSDM(Y,X,G,
env.formula = "~ X_1 + X_1^2",
family = binomial(link = "logit"), penal = NULL,
sp.formula = sp.formula,
mode = "prey", method = "glm")
#> We don't check that G and the graph induced by the sp.formula specified by the user match, nor that the latter is a graph. Please be careful about their consistency.
```
|
/scratch/gouwar.j/cran-all/cranData/webSDM/vignettes/Composite_variables.Rmd
|
---
title: "Subtle and obvious differences between SDM and trophic SDM"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Subtle and obvious differences between SDM and trophic SDM}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
## Compare trophic and classical SDMs: difference and equalities
Here, we present the differences between a classic SDM and our trophic SDM, starting from the simplest case when these two approaches coincide to more realistic cases where they do not.
### The simplest case
Let’s consider a very simple case with one environmental covariate $x$, and two species $y_A$ and $y_B$. We assume species $y_A$ to be basal and species $y_B$ to feed on $y_A$. This leads to the following directed acyclic graph that resumes the dependencies across variables, assuming bottom-up control.
```r
library(igraph)
G=graph_from_edgelist(as.matrix(data.frame(from = c("x","x","A"),
to = c("A","B","B"))))
plot(G)
```

We now assume that data on species distributions are continuous observable entities (e.g. basal area, biomass), that we can model with a linear regression. We name $y_{iA}$ and $y_{iB}$ the observations of species $y_A$ and $y_B$ at site $i$, respectively, and we assume that the environment has a quadratic effect on both species.
Therefore, using classical SDMs, model equations are:
$$
\begin{aligned}
y_{iA} &= \beta^{SDM}_{0A} + \beta^{SDM}_{1A} x_i + \beta^{SDM}_{2A}x_i^2 + \epsilon_{iA}, \ \ \epsilon_{iA} \sim N(0, \sigma_A^{SDM}) \\
y_{iB} &= \beta^{SDM}_{0B} + \beta^{SDM}_{1B} x_i + \beta^{SDM}_{2B}x_i^2 + \epsilon_{iB}, \ \ \epsilon_{iB} \sim N(0, \sigma_B^{SDM})
\end{aligned}
$$
Instead, our trophic model includes a dependence of $y_B$ on its prey $y_A$:
$$
\begin{aligned}
y_{iA} &= \beta^{tSDM}_{0A} + \beta^{tSDM}_{1A} x_i + \beta^{tSDM}_{2A}x_i^2 + \epsilon_{iA}, \ \ \epsilon_{iA} \sim N(0, \sigma_A^{tSDM}) \\
y_{iB} &= \beta^{tSDM}_{0B} + \beta^{tSDM}_{1B} x_i + \beta^{tSDM}_{2B}x_i^2 + \alpha y_{iA} + \epsilon_{iB}, \ \ \epsilon_{iB} \sim N(0, \sigma_B^{tSDM})
\end{aligned}
$$
We hereafter focus on the expectation of the models (corresponding to the predicted values), focusing in particular on species $y_B$ for which the two models are different. For SDMs:
$$E[y_{iB} | \ x_i] = \beta^{SDM}_{0B} + \beta^{SDM}_{1B} x_i + \beta^{SDM}_{2B}x_i^2 $$
For trophic SDM, we need to condition on a value of $y_{iA}$. We here choose to condition on the expected value of $y_{iA}$, which corresponds to using predictions from $y_A$ to predict $y_B$. In a linear model, with Gaussian data and a linear interaction between prey and predator, we have that $E_A[E_B[y_B | \ y_A]] = E_B[y_B | \ E[y_A]]$ (which is not necessarily true in other cases).
We thus have:
$$E[y_{iB} | \ x_i, E[y_{iA}] ] = \beta^{tSDM}_{0B} + \beta^{tSDM}_{1B} x_i + \beta^{tSDM}_{2B}x_i^2 + \alpha E[y_{iA}] $$
We can rewrite the expected value of $y_B$ only as a function of the environment $x$ only.
$$
\begin{aligned}
E[y_{iB} | \ x_i, E[y_{iA}] ] &= \beta^{tSDM}_{0B} + \beta^{tSDM}_{1B} x_i + \beta^{tSDM}_{2B}x_i^2 + \alpha (\beta^{tSDM}_{0A} + \beta^{tSDM}_{1A} x_i + \beta^{tSDM}_{2A}x_i^2 ) \\
& = \beta^{tSDM}_{0B} + \alpha \beta^{tSDM}_{0A} + ( \beta^{tSDM}_{1B} + \alpha \beta^{tSDM}_{1A}) x_i + (\beta^{tSDM}_{2B} + \alpha \beta^{tSDM}_{2A}) x_i^2 \\
&= \beta^{SDM}_{0B} + \beta^{SDM}_{1B} x_i + \beta^{SDM}_{2B}x_i^2
\end{aligned}
$$
In this very simple case of a linear regression model with a linear interactions between the predator and the preys, the estimation of the regression coefficients is such that
$$\beta^{SDM}_{.B} = \beta^{tSDM}_{.B} + \alpha \beta^{tSDM}_{.A} $$
As a consequence the models estimate the same realised niche, and predictions from trophic and classical SDMs coincide.
However, our trophic model allows a separation of the direct effect of the environment on $y_B$ (i.e., the potential niche of $y_B$) from its indirect effect due to the effect of $y_A$ on $y_B$. In other words, using the jargon of structural equation models, $\beta^{tSDM}_{1B}$ and $\beta^{tSDM}_{2B}$ are the direct effects of the environment on species $y_B$ (i.e., its potential niche), the terms $\alpha \beta^{tSDM}_{1A}$ and $\alpha \beta^{tSDM}_{2A}$ are the indirect effect of the environment on species $y_B$. The sum of these two effects, $\beta^{tSDM}_{1B} + \alpha \beta^{tSDM}_{1A}$ and $\beta^{tSDM}_{2B} + \alpha \beta^{tSDM}_{2A}$ corresponds to the total effect of the environment on $y_B$, i.e., the realised niche of $y_B$. In this very particular case, SDM can correctly estimate the total effect (the realised niche), but cannot separate the direct and indirect effect of the environment on $y_B$ and thus they do not correctly estimate the potential niche.
#### Simulation
We hereafter present a short example confirming the analytical derivation of these results.
First, we simulate species distribution data accordingly to the directed acyclic graph presented above. Therefore, the environment has a quadratic effect on species $y_A$ and species $y_B$, with a linear effect of $y_A$ on $y_B$.
```r
set.seed(1712)
# Create the environmental gradient
X = seq(0,5,length.out=100)
# Simulate data for the basal species A
A = 3*X + 2*X^2 + rnorm(100, sd = 5)
# Simulate data for the predator species B
B = 2*X -3*X^2 + 3*A + rnorm(100, sd = 5)
oldpar = par()
par(mfrow=c(1,3))
plot(X,A, main = "Species A realised \n and potential niche")
plot(X,B, main = "Species B realised niche")
plot(X, 2*X -3*X^2, main = "Species B potential niche")
```

```r
par(mfrow = oldpar$mfrow)
```
We now run both a classic SDM and a trophic SDM
```r
# For species A, the two models coincide
m_A = lm(A ~ X + I(X^2))
# For species B, the two models are different:
## trophic model
m_trophic = lm(B ~ X + I(X^2) + A)
## classic SDM
m_SDM = lm(B ~ X + I(X^2))
```
We can now test the relationships between the coefficients of SDM and trophic SDM.
```r
# Show the equality of coefficients
all.equal(coef(m_SDM), coef(m_trophic)[-4] + coef(m_trophic)[4]*coef(m_A))
#> [1] TRUE
# Prediction coincide
pred_SDM = m_SDM$fitted.values
pred_trophic = predict(m_trophic,
newdata = data.frame(X = X, A = m_A$fitted.values))
all.equal(pred_SDM, pred_trophic)
#> [1] TRUE
```
The coefficient of classic SDM for species $y_B$ are equal to the environmental coefficients of trophic SDM for species $y_B$ plus the indirect effect of the environment on species $y_B$ (given by the product of the biotic term and the environmental coefficients of species $y_A$).
As a consequence, the predictions of both models coincide when the predicted value of species $y_A$ is used to predict $y_B$.
However, unlike the traditional SDM, our trophic model allows to retrieve the correct potential niche of species $y_B$
```r
# Potential niche infered by SDM
plot(X, m_SDM$fitted.values, ylim = c(-65, 120), ylab = "B",
main = "Potential niche of yB")
points(X, cbind(1, X, X^2) %*% coef(m_trophic)[-4], col ="red")
points(X, 2*X -3*X^2, col ="blue")
legend(-0.1, 120, legend=c("Potential niche inferred by SDM",
"Potential niche inferred by trophic SDM",
"True fundamenta niche"), pch =1,
col=c("black","red", "blue"), cex = 0.5)
```

## Does this always hold?
We showed that SDM and trophic SDM estimate the same realized niche, and thus lead to the same predictions, when all the following conditions hold:
- The relationship between predator and prey is linear
- Species distribution are continuous abundances
- The statistical model employed is a linear regression
- The selected environmental variables are the same for prey and predators
However, as soon as at least one of these conditions does not hold, the estimations of the realized niche (and so model prediction) differ. We hereafter show that releasing just one of these constraints at a time is enough to obtain predictions from trophic SDM that are different, and better, than classical SDMs. Therefore, the example presented above is a very particular case that is useful to understand model similarities, but that rarely occurs in application.
### Non-linear relationship between prey and predator
We hereafter release the conditions on the linearity of the relationship between $y_B$ and $y_A$. Indeed, we now consider that species $y_B$ has a quadratic response to $y_A$. The classic SDM does not change, as we model species as a function of the environment only. Instead, the trophic model for species $y_B$ becomes:
$$y_{iB}= \beta^{tSDM}_{0B} + \beta^{tSDM}_{1B} x_i + \beta^{tSDM}_{2B}x_i^2 + \alpha y_{iA}^2 + \epsilon_{iB}, \ \ \epsilon_{iB} \sim N(0, \sigma_B^{tSDM})$$
Predictions between trophic SDM and SDM are now different, since:
$$
\begin{aligned}
E[y_{iB} | \ x_i, E[y_{iA}] ] &= \beta^{tSDM}_{0B} + \beta^{tSDM}_{1B} x_i + \beta^{tSDM}_{2B}x_i^2 + \alpha (\beta^{tSDM}_{0A} + \beta^{tSDM}_{1A} x_i + \beta^{tSDM}_{2A}x_i^2 )^2 \\
& = \beta^{tSDM}_{0B} + \alpha(\beta^{tSDM}_{0A})^2+ (\beta^{tSDM}_{1B} + 2\alpha\beta^{tSDM}_{0A}\beta^{tSDM}_{1A}) x_i \\
& \ \ \ \ + (\beta^{tSDM}_{2B} + \alpha (2\beta^{tSDM}_{0A}\beta^{tSDM}_{2A} + (\beta^{tSDM}_{1A})^2))x_i^2 + 2\alpha\beta^{tSDM}_{1A}\beta^{tSDM}_{2A} x_i^3 + \alpha(\beta^{tSDM}_{2A})^2x_i^4 \\
&\neq \beta^{SDM}_{0B} + \beta^{SDM}_{1B} x_i + \beta^{SDM}_{2B}x_i^2
\end{aligned}
$$
In order to correctly infer the realised niche, classic SDMs should be specified with a polynomial of degree 4. As soon as we add multiple environmental variables and link between species, classic SDM should be specified with extremely complex formula, which is unfeasible for real application.
#### Simulation
We provide a simple example to demonstrate the analytical computations with a simulation. We use the same example of above, but we now simulate a quadratic relationship of $y_B$ with respect to $y_A$.
```r
B = 2*X -3*X^2 + 3*A^2 + rnorm(100, sd = 5)
oldpar = par()
par(mfrow=c(1,3))
plot(X,A, main = "Species A realised \n and potential niche")
plot(X,B, main = "Species B realised niche")
plot(X, 2*X -3*X^2, main = "Species B potential niche")
```

```r
par(mfrow = oldpar$mfrow)
# Fit a trophic SDM
m_trophic = lm(B ~ X + I(X^2) + I(A^2))
```
We now compare the regression coefficients and predictions from the two models
```r
# Show the equality of coefficients
all.equal(coef(m_SDM), coef(m_trophic)[-4] + coef(m_trophic)[4]*coef(m_A))
#> [1] "Mean relative difference: 0.185587"
# Prediction are now different
pred_SDM = m_SDM$fitted.values
pred_trophic = predict(m_trophic,
newdata = data.frame(X = X, A = m_A$fitted.values))
all.equal(pred_SDM, pred_trophic)
#> [1] "Mean relative difference: 53.61947"
#Compare R2
cor(B, pred_SDM)^2
#> [1] 0.8339402
cor(B, pred_trophic)^2
#> [1] 0.9605349
```
The relationship between the coefficients of the two models does not hold anymore more, and predictions are now different, with trophic SDM reaching a far better predictive accuracy than classic SDM for species $y_B$ (R2 of 0.83 and 0.96 respectively).
### Non-continuous observable entities (presence-absence, counts)
Let’s now consider here the case of presence-absences (i.e., binary data), without modifying the other two conditions. Therefore, we use a (generalized) linear model like logistic regression, and we model a linear relationship (at the link level) between predator and prey. Thus, for SDM we have:
$$
\begin{aligned}
p(y_{iA}= 1) &= \text{logit}^{-1}(\beta^{SDM}_{0A} + \beta^{SDM}_{1A} x_i + \beta^{SDM}_{2A}x_i^2) \\
p(y_{iB} = 1) &= \text{logit}^{-1}(\beta^{SDM}_{0B} + \beta^{SDM}_{1B} x_i + \beta^{SDM}_{2B}x_i^2)
\end{aligned}
$$
Instead, our trophic model includes a dependence of $y_B$ on its prey $y_A$:
$$p(y_{iB} = 1) = \text{logit}^{-1} (\beta^{tSDM}_{0B} + \beta^{tSDM}_{1B} x_i + \beta^{tSDM}_{2B}x_i^2 + \alpha y_A)$$
The equality between the models does not hold anymore due to the non linearity of the logit function. Indeed:
$$
\begin{aligned}
E[y_{iB} | \ x_i, E[y_{iA}] ] &= p(y_{iB} = 1 | \ x_i, p(y_{iA} = 1)) \\
&= \text{logit}^{-1}(\beta^{tSDM}_{0B} + \beta^{tSDM}_{1B} x_i + \beta^{tSDM}_{2B}x_i^2 + \alpha \text{logit}^{-1}(\beta^{tSDM}_{0A} + \beta^{tSDM}_{1A} x_i + \beta^{tSDM}_{2A}x_i^2))\\
&\neq \text{logit}^{-1}(\beta^{SDM}_{0B} + \beta^{SDM}_{1B} x_i + \beta^{SDM}_{2B}x_i^2)
\end{aligned}
$$
#### Simulations
We now confirm this analytical derivation with a simple example. The code is very similar to the previous one, but we now generate binary data from a logistic model.
```r
# Generate the link layer basal species
V_A= 3*X - 2*X^2
# Transform to probability
prob_A = 1/(1 + exp(-V_A))
# Sample the binary data
A = rbinom(n = 100, size = 1, prob = prob_A)
# Same for species B
V_B = -3*X +1*X^2 + 3*A
prob_B = 1/(1 + exp(-V_B))
B = rbinom(n = 100, size = 1, prob = prob_B)
oldpar = par()
par(mfrow=c(1,3))
plot(X,prob_A, main = "Species A realised \n and potential niche")
plot(X,prob_B, main = "Species B realised niche")
plot(X, 1/(1+exp(-(-3*X +1*X^2))), main = "Species B potential niche")
```

```r
par(mfrow = oldpar$mfrow)
```
We then fit a classic SDM and a trophic SDM
```r
# For species A, the two models coincide
m_A = glm(A ~ X + I(X^2), family = binomial(link = "logit"))
# For species B, the two models are different:
m_SDM = glm(B ~ X + I(X^2), family = binomial(link = "logit"))
m_trophic = glm(B ~ X + I(X^2) + A, family = binomial(link = "logit"))
```
We now test the relationships between model coefficients and whether the equality of model predictions still holds
```r
# Equality of the coefficient does not hold anymore
all.equal(coef(m_SDM), coef(m_trophic)[-4] + coef(m_trophic)[4]*coef(m_A))
#> [1] "Mean relative difference: 2.305022"
# Predictions do not coincide anymore
pred_SDM = m_SDM$fitted.values
pred_trophic = predict(m_trophic,
newdata = data.frame(X = X, A = m_A$fitted.values))
all.equal(pred_SDM, pred_trophic)
#> [1] "Mean relative difference: 2.915665"
# Predictions are improved by trophic SDM
## AUC of species B for SDM
dismo::evaluate(p = pred_SDM[which(B==1)],
a = pred_SDM[which(B==0)] )@auc
#> [1] 0.8408333
## AUC of species B for trophic SDM
dismo::evaluate(p = pred_trophic[which(B==1)],
a = pred_trophic[which(B==0)] )@auc
#> [1] 0.8529167
```
The relationship between the coefficients of the two models does not hold anymore more, and predictions are now different, with trophic SDM that slightly improve classic SDM (AUC of species $y_B$ goes from 0.84 to 0.85).
### Non-linear statistical model
We finally show how using a non-linear statistical model leads to different predictions between classical SDMs and a trophic SDM with the example of a random forest. Since we cannot provide any analytical derivation for random forest, we simply provide an example.
Data are simulated exactly as in the very first examples (continuous observable entities).
```r
# Simulate data for the basal species A
A = 3*X + 2*X^2 + rnorm(100, sd = 5)
# Simulate data for the predator species B
B = 2*X -3*X^2 + 3*A + rnorm(100, sd = 5)
oldpar = par()
par(mfrow=c(1,3))
plot(X,A, main = "Species A realised \n and potential niche")
plot(X,B, main = "Species B realised niche")
plot(X, 2*X -3*X^2, main = "Species B potential niche")
```

```r
par(mfrow = oldpar$mfrow)
```
We infer statistical models with random forest
```r
library(randomForest)
#> randomForest 4.7-1.1
#> Type rfNews() to see new features/changes/bug fixes.
# Species A
m_A = randomForest(A ~ X + I(X^2))
# Species B trophic SDM
m_trophic = randomForest(B ~ X + I(X^2) + A)
# Species B classic SDM
m_SDM <- randomForest(B ~ X + I(X^2))
```
We now compare the predictions from the two models.
```r
# Prediction are now different
pred_SDM = m_SDM$predicted
pred_trophic = predict(m_trophic,
newdata = data.frame(X = X, A = m_A$predicted))
all.equal(pred_SDM, pred_trophic)
#> [1] "Mean relative difference: 0.08021014"
#Compare R2
cor(B, pred_SDM)^2
#> [1] 0.8075415
cor(B, pred_trophic)^2
#> [1] 0.8670482
```
Predictions from the model are different, and trophic SDM has a larger R2 than classical SDMs (0.86 versus 0.80).
|
/scratch/gouwar.j/cran-all/cranData/webSDM/vignettes/Differences_with_SDMs.Rmd
|
---
title: "Introduction to trophic SDM"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Introduction to trophic SDM}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
In this vignette we explain how to fit, evaluate and interpret a trophic species distribution model (trophic SDM). Trophic SDM is a statistical model to model the distribution of species accounting for their known trophic interactions. We refer to Poggiato et al., "Integrating trophic food webs in species distribution models improves ecological niche estimation and prediction", in preparation for the full description of trophic SDM.
## Install and load webSDM
```r
library(devtools)
# Run to install webSDM
# install_github("giopogg/webSDM")
library(webSDM)
library(bayesplot)
library(gridExtra)
library(reshape2)
library(ggplot2)
library(loo)
set.seed(1234)
```
## Simulate data
For illustrative purposes, we use simulated data for which we know the parameter values. We thus simulate a trophic interaction network and species distribution for six species, whose names are ordered accordingly to their trophic level (Y1 being basal and Y6 being at the highest trophic position). We simulate data with a stronger dependence on the abiotic variables for species in lower trophic levels, and increasing dependence on the biotic terms (i.e., their preys) for species with a higher trophic level. We will then use trophic SDM and see if the model can retrieve this simulate process and the species potential niches.
### Create trophic interaction network
We first create the trophic interaction network. The network needs to be a directed acyclic graph (DAG), with arrows pointing from predator to prey. We thus simulate an interaction network such that species only have prey in a lower trophic position.
```r
# Set number of species
S = 6
# Create the adjacency matrix of the graph
A = matrix(0,nrow=S,ncol=S)
# Ensure that the graph is connected
while(!igraph::is.connected(igraph::graph_from_adjacency_matrix(A))){
A = A_w = matrix(0,nrow=S,ncol=S)
# Create links (i.e. zeros and ones of the adjacency matrix)
for(j in 1:(S-1)){
A[c((j+1):S),j] = sample(c(0,1), S-j, replace = T)
}
# Sample weights for each link
#A_w[which(A != 0)] = runif(1,min=0,max=2)
}
colnames(A) = rownames(A) = paste0("Y",as.character(1:S))
# Build an igraph object from A
G = igraph::graph_from_adjacency_matrix(A)
plot(G)
```

### Simulate data
We now simulate species distribution at 300 locations along two environmental gradients. We simulate species such that species Y1 to Y3 have a negative dependence to the first environmental variable X_1 and a positive dependence to X_2, viceversa for species Y4 to Y6. Moreover, the strength of the environmental term decreases along the trophic level, while the effect of the prey increases. Finally, preys always have a positive effect on predators.
```r
# Number of sites
n = 500
# Simulate environmental gradient
X_1= scale(runif(n, max = 1))
X_2= scale(runif(n, max = 1))
X = cbind(1, X_1^2, X_2^2)
B = matrix(c(1, 1, 1, 1, 1, 1,
-2, -2, -2, 2, 2, 2,
2, 2, 2, -2, -2, -2
), ncol = 3)
# Sample the distribution of each species as a logit model as a function of the
# environment and the distribution of preys
Y = V = prob = matrix(0, nrow = n, ncol = S)
for(j in 1:S){
# The logit of the probability of presence of each species is given by the
# effect of the environment and of the preys.
# Create the linear term. As j increases, the weight of the environmental effect
# decreases and the biotic effect increases
eff_bio = seq(0.1, 0.9, length.out = S)[j]
eff_abio = seq(0.1, 0.9, length.out = S)[S+1-j]
V[,j]= eff_abio*X%*%B[j,] + eff_bio*Y%*%A[j,]*3
# Transform to logit
prob[,j] = 1/(1 + exp(-V[,j]))
# Sample the probability of presence
Y[,j] = rbinom(n = n, size = 1, prob = prob[,j])
}
# Set names
colnames(Y) = paste0("Y",as.character(1:S))
```
## Fit trophic SDM
Now that we simulate the data, we can fit a species distribution model with the function `trophicSDM`. The function requires the species distribution data `Y` (a sites x species matrix), the environmental variables `X` and an igraph object `G` representing the trophic interaction network. Importantly, `G` must be acyclic and arrows must point from predator to prey. Finally, the user has to specify a formula for the environmental part of the model and the description of the error distribution and link function to be used in the model (parameter `family`), just as with any `glm`.
By default, `trophicSDM` models each species as a function of their prey (set `mode = "predator"` to model species as a function of their predators) and of the environmental variables (as defined in `env.formula`). Trophic SDM can be also fitted as a function of the summary variables of preys (i.e. composite variables like prey richness), instead of each prey species directly. We cover this topic in the vignette 'Composite variables'.
The algorithm behind trophic SDM fits a set of generalised linear model (glm), one for each species. These glm can be fitted in the frequentist framework by relying on the function `glm` (set `method = "glm"`), or in the Bayesian framework by relying on the function `rstanarm` (set `method = "stan_glm"`, the default choice). Model fitting is parallelised if `run.parallel = TRUE`.
These glm can be penalised to shrink regression coefficients (by default the model is run without penalisation). In the Bayesian framework set `penal = "horshoe"` to implement penalised glm using horshoe prior. In the frequentist framework set `penal = "elasticnet"` to implement penalised glm with elasticnet. See the examples in `?trophicSDM`.
Hereafter, we only fit trophic SDM in the Bayesian framework with no penalisation. However, all the functions and analyses (except for MCMC diagnostic) presented in this vignette applies straightforwardly with or without penalisation and in the frequentist framework.
Hereafter we model species as a function of preys and the two environmental covariates in the Bayesian framework without penalisation. We though need to specify the parameters of the MCMC chains. We need to decide how many chains to sample (`chains`), how many samples to obtain per chain (`iter`), and if we wish to see the progress of the MCMC sampling (`verbose`).
```r
iter = 1000
verbose = FALSE
nchains = 2
```
We are now ready to fit a trophic SDM.
```r
X = data.frame(X_1 = X_1, X_2 = X_2)
m = trophicSDM(Y = Y, X = X, G = G,
env.formula = "~ I(X_1^2) + I(X_2^2)",
family = binomial(link = "logit"),
method = "stan_glm", chains = nchains, iter = iter, verbose = verbose)
```
### A trophicSDMfit object
The fitted model `m` is of class `"trophicSDMfit"`. We also show here the formulas used to fit the each glm, where each predator is modeled as a function of the preys and of the environmental variables.
```r
m
#> ==================================================================
#> A trophicSDM fit with no penalty, fitted using stan_glm
#> with a bottom-up approach
#>
#> Number of species : 6
#> Number of links : 10
#> ==================================================================
#> * Useful fields
#> $coef
#> * Useful S3 methods
#> print(), coef(), plot(), predict(), evaluateModelFit()
#> predictFundamental(), plotG(), plotG_inferred(), computeVariableImportance()
#> * Local models (i.e. single species SDM) can be accessed through
#> $model
class(m)
#> [1] "trophicSDMfit"
m$form.all
#> $Y1
#> [1] "y ~ I(X_1^2) + I(X_2^2)"
#>
#> $Y2
#> [1] "y ~ I(X_1^2)+I(X_2^2)+Y1"
#>
#> $Y3
#> [1] "y ~ I(X_1^2)+I(X_2^2)+Y1+Y2"
#>
#> $Y4
#> [1] "y ~ I(X_1^2)+I(X_2^2)+Y1+Y3"
#>
#> $Y5
#> [1] "y ~ I(X_1^2)+I(X_2^2)+Y1+Y3+Y4"
#>
#> $Y6
#> [1] "y ~ I(X_1^2)+I(X_2^2)+Y3+Y5"
```
## Analyse a fitted trophicSDM
The field `$model` contains all the the single species glm (i.e., all the local models). `$data` and `trophicSDM` contains informations on the data and choices to fit the model respectively. `$form.all` contains the formula used to fit each glm (i.e., both abiotic and biotic terms). `$coef` contains the inferred regression coefficients of the glm for all species. `$AIC` and `$log.lik` are respectively the AIC and log-likelihood of the fitted trophic SDM. Finally, in the Bayesian framework, the field `$mcmc.diag` contains the convergence diagnostic metrics of the MCMC chains for each species.
In this vignette, we first ensure that the MCMC chains correctly converged. Then, we analyse the inferred model, by focusing in particular on the effect of the biotic versus abiotic terms. We then analyse the predictive performances of the model (comparing it to environment-only SDM) and use it to predict the species potential niches.
### MCMC convergence
First, we can have a look at effective sample size to total sample size and of the potential scale reduction factor (aka 'R hat') for each species. Each line corresponds to a given parameter.
```r
# Plot mcmc potential scale reduction factor (aka rhat)
p1 = mcmc_rhat(m$mcmc.diag$rhat)
# Plot mcmc ratio of effective sample size to total sample size
p2 = mcmc_neff(m$mcmc.diag$neff.ratio)
grid.arrange(p1, p2, ncol = 2)
```

We observe that the effective sample sizes are very close to the theoretical value of the actual number of samples, as the ratio is close to 1. In few cases the ratio is lower, and we might consider running the chains for longer, or thin them, to improve convergence. This indicates that there is very little autocorrelation among consecutive samples. The potential scale reduction factors are very close to one, which indicates that two chains gave consistent results.
We can have a closer look to the MCMC chains by looking at the traceplots of the parameters of a given model, for example here for species Y5 who feeds on species Y1, Y2, Y3 and Y4. To do so, we first assess the local model of species Y5, and in particular its field `$model` that gives us the output of the function `stan_glm`. We can then exploit the plot method of this object.
```r
plot(m$model$Y5$model, "trace")
```

Again, we see that the chains mix very well and that there's little autocorrelation among samples within the same chain.
### Parameter estimates and interpretation
We now analyse the estimates of the regression coefficients. We can have a first glance of the regression coefficients with the function plot. This function plots the posterior distribution of the regression coefficients of each species.
```r
plot(m)
```

We can visually see that the regression coefficients for the environmental part of the model match the simulated parameters, as species Y1 to Y3 have a positive response to X_1 and a negative one to X_2, viceversa for species Y3 to Y6. We also remark that the environmental coefficients are less important for basal species than for predators. Indeed, the posterior mean of the regression coefficients of the environmental part gets closer to zero and their posterior distribution tend to overlap zero more and more as we move from species Y1 to species Y6. We can quantify this visual assessment by looking at the posterior mean and quantile of the regression coefficients. The parameter `level` set the probability of the quantile (default 0.95).
```r
coef(m, level = 0.9)
#> $Y1
#> mean 5% 95%
#> (Intercept) 1.193315 0.8631366 1.551786
#> I(X_1^2) -2.153769 -2.4827322 -1.854351
#> I(X_2^2) 1.904532 1.5618766 2.281827
#>
#> $Y2
#> mean 5% 95%
#> (Intercept) 0.4378192 -0.05096073 0.9425659
#> I(X_1^2) -1.3103497 -1.64827655 -0.9781233
#> I(X_2^2) 1.6693748 1.28262664 2.0953004
#> Y1 1.1014760 0.60271353 1.6253656
#>
#> $Y3
#> mean 5% 95%
#> (Intercept) 0.9246159 0.3048754 1.537713
#> I(X_1^2) -1.3782372 -1.7729318 -1.011603
#> I(X_2^2) 1.2837309 0.8501504 1.799605
#> Y1 0.8750454 0.2487845 1.523552
#> Y2 1.3356857 0.7836524 1.874160
#>
#> $Y4
#> mean 5% 95%
#> (Intercept) -0.149971 -0.9501498 0.6711274
#> I(X_1^2) 1.132746 0.7019883 1.5938620
#> I(X_2^2) -1.138931 -1.5981180 -0.6976561
#> Y1 2.550784 1.6477388 3.4849039
#> Y3 2.000125 1.2299528 2.9196692
#>
#> $Y5
#> mean 5% 95%
#> (Intercept) 0.5422551 -0.76409358 2.0854414
#> I(X_1^2) 0.9843555 0.02913223 2.0103196
#> I(X_2^2) -1.4438633 -2.74833106 -0.2571721
#> Y1 3.0216650 0.36971766 6.3588373
#> Y3 4.4991171 2.06335620 7.4694324
#> Y4 1.9616552 0.64162409 3.4955833
#>
#> $Y6
#> mean 5% 95%
#> (Intercept) -0.18963593 -2.0485881 1.5794885
#> I(X_1^2) 0.06055848 -0.9455691 0.9899717
#> I(X_2^2) -0.18911690 -1.2013288 0.8962215
#> Y3 3.62070445 1.1223913 6.5666245
#> Y5 3.69026866 2.1993395 5.4164494
```
Notice that regression coefficients are directly available in the field `$coef` of an object trophicSDMfit (with `level = 0.95`). As we previously hinted, we see that the estimate of the regression coefficients of the environmental part get closer and closer to zero with credible interval that often overlap zero (implying they are not significant with a confidence level of 10%) for species with a higher trophic level. In order to be able to correctly quantify the effect of the different predictors across species (i.e., their relative importance), we need to standardise the regression coefficients (see Grace et al. 2018). To do so, we need to set `standardise = TRUE`.
```r
coef(m, level = 0.9, standardise = T)
#> $Y1
#> estimate 5% 95%
#> (Intercept) 1.1933152 1.1933152 1.1933152
#> I(X_1^2) -0.6032735 -0.6954163 -0.5194061
#> I(X_2^2) 0.5524401 0.4530474 0.6618806
#>
#> $Y2
#> estimate 5% 95%
#> (Intercept) 0.4378192 0.43781923 0.4378192
#> I(X_1^2) -0.3967764 -0.49910135 -0.2961777
#> I(X_2^2) 0.5234732 0.40219885 0.6570325
#> Y1 0.1815471 0.09934023 0.2678954
#>
#> $Y3
#> estimate 5% 95%
#> (Intercept) 0.9246159 0.92461585 0.9246159
#> I(X_1^2) -0.4018688 -0.51695451 -0.2949649
#> I(X_2^2) 0.3876289 0.25670715 0.5433997
#> Y1 0.1388822 0.03948565 0.2418093
#> Y2 0.2027708 0.11896649 0.2845168
#>
#> $Y4
#> estimate 5% 95%
#> (Intercept) -0.1499710 -0.1499710 -0.1499710
#> I(X_1^2) 0.4526599 0.2805236 0.6369279
#> I(X_2^2) -0.4713231 -0.6613485 -0.2887107
#> Y1 0.5548413 0.3584128 0.7580292
#> Y3 0.3802667 0.2338405 0.5550919
#>
#> $Y5
#> estimate 5% 95%
#> (Intercept) 0.5422551 0.542255094 0.54225509
#> I(X_1^2) 0.2863784 0.008475438 0.58486205
#> I(X_2^2) -0.4350071 -0.828017071 -0.07748081
#> Y1 0.4785091 0.058548274 1.00698178
#> Y3 0.6227408 0.285597372 1.03387396
#> Y4 0.1816850 0.059426083 0.32375471
#>
#> $Y6
#> estimate 5% 95%
#> (Intercept) -0.18963593 -0.1896359 -0.1896359
#> I(X_1^2) 0.02223722 -0.3472152 0.3635200
#> I(X_2^2) -0.07191471 -0.4568244 0.3408025
#> Y3 0.63254324 0.1960837 1.1472005
#> Y5 0.17891028 0.1066276 0.2625983
```
This results confirms the previous analysis. We can analyse the relative importance of different group of variables with the function `computeVariableImportance`. This function can take as input the definition of groups of variables in the argument `groups` (by default, with `groups = NULL`, each explanatory variable is a different group). The variable importance of groups of variables is computed as the standardised regression coefficients summed across variable of the same group.
We hereafter use this function to compute the relative importance of the abiotic versus biotic covariates.
```r
VarImpo = computeVariableImportance(m,
groups = list("Abiotic" = c("X_1","X_2"),
"Biotic" = c("Y1","Y2", "Y3", "Y4", "Y5", "Y6")))
VarImpo = apply(VarImpo, 2, function(x) x/(x[1]+x[2]))
tab = reshape2::melt(VarImpo)
tab$Var2 = factor(tab$Var2, levels = colnames(Y))
ggplot(tab, aes(x = Var2, y = value, fill = Var1)) + geom_bar(stat="identity") +
theme_classic()
```

We clearly see that our model correctly retrieved the simulated pattern, with the importance of biotic variables with respect to the abiotic ones becomes greater as the trophic level increases.
Finally, we can visualise the effect of each trophic interactions with the function `plotG_inferred`, which plots the metaweb `G` together with the variable importance (i.e. the standardised regression coefficient) of each link. The parameter `level` sets the confidence level with which coefficients are deemed as significant or non-significant.
```r
plotG_inferred(m, level = 0.9)
```

We see that the model correctly retrieves that preys have a posite effect on the predators and that this effect becomes more important for predators at higher trophic positions.
### Analysis of local models
In order to examine the package and practice with it, we here show how to easily manipulate local models, i.e. each glm (that can be seen as a single species SDMs), the smallest pieces of trophic SDM. These local models belong to the class "SDMfit", for which multiple methods exists. We hereafter show how to some of these methods for species Y6.
```r
SDM = m$model$Y6
# The formula used to fit the model
SDM$form.all
#> [1] "y ~ I(X_1^2)+I(X_2^2)+Y3+Y5"
# The inferred model
plot(SDM)
```

```r
# The regression coefficients
coef(SDM, level = 0.9, standardise = T)
#> estimate 5% 95%
#> (Intercept) -0.18963593 -0.1896359 -0.1896359
#> I(X_1^2) 0.02223722 -0.3472152 0.3635200
#> I(X_2^2) -0.07191471 -0.4568244 0.3408025
#> Y3 0.63254324 0.1960837 1.1472005
#> Y5 0.17891028 0.1066276 0.2625983
```
We can also predict the probability of presence of species Y6 at a site with X_1 = 0.5, X_2 = 0.5, assuming its preys to be present present.
```r
preds = predict(SDM, newdata = data.frame(X_1 = 0.5, X_2 = 0.5, Y3 = 1, Y5 = 1))
# Posterior mean of the probability of presence
mean(preds$predictions.prob)
#> [1] 0.9983807
```
We see that the species has a high probability of presence in this environmental conditions when its prey are present.
## Predictions with trophic SDM
We showed how to fit and analyse a trophic SDM and how to predict a single species (Y6 in the previous section), when we can fix the distribution of its prey. However, the distribution of prey is typically unavailable when we want to predict the distribution of species at unobserved sites and/or under future environmental conditions. Intuitively, in a simple network of two trophic level we would need to predict the prey first and use these predictions to predict the predator. To generalize this idea to complex networks, we predict species following the topological ordering of the metaweb. This order that exists for every DAG guarantees that when predicting a given species, all its prey will have already been predicted.
The function `predict` computes the topological order of species, and then predicts them sequentially. As any `predict` function, it takes into account the values of the environmental variables in the argument `Xnew`. We can provide to the function the number of samples from the posterior distribution.
```r
pred = predict(m, Xnew = data.frame(X_1 = 0.5, X_2 = 0.5), pred_samples = 100)
dim(pred$Y2)
#> [1] 1 100
```
By default, the function `predict` transforms the probability of presence of prey in presence-absence, and then use these presence-absences to predict the predator. However, we can use directly the probability of presence of prey by setting `prob.cov = TRUE`.
Pred is a list containing the posterior distribution of the predicted probability of presence of each species (i.e., number of sites x pred_samples). Notice that we can ask the function to directly provide a summary of the posterior distribution (i.e. posterior mean and 95% quantiles) of the probabilities of presence by setting `fullPost = FALSE`. As for `trophicSDM`, we can choose to parallelise some parts of the `predict` function by setting `run.parallel = TRUE` (which can speed up computational times).
```r
pred = predict(m, Xnew = data.frame(X_1 = 0.5, X_2 = 0.5), pred_samples = 100,
fullPost = FALSE, run.parallel = FALSE)
pred$Y2
#> $predictions.mean
#> 1
#> 0.7984008
#>
#> $predictions.q025
#> 1
#> 0.5854847
#>
#> $predictions.q975
#> 1
#> 0.8850332
```
## Model evaluation
We now want to evaluate how well the model fits the data and how well it generalises to new data with respect to classical SDM. We thus first run a classical SDM, by providing an empty graph to `trophicSDM`. Then, we will compare model AIC and their predictive performances both on the training data and in cross-validation. Notice that when we compare classical SDM and trophic SDM it is important to account for the fact that trophic SDM have a higher number of parameters, and will therefore have, by default, a higher fit on the the training data.
```r
empty_graph = graph_from_adjacency_matrix(matrix(0, nrow = S, ncol = S,
dimnames = list(colnames(Y), colnames(Y))))
m_classic = trophicSDM(Y = Y, X = X,
G = empty_graph,
env.formula = "~ I(X_1^2) + I(X_2^2)", family = binomial(link = "logit"),
method = "stan_glm", chains = nchains, iter = iter, verbose = verbose)
```
### AIC, loo
We first compare model AIC and an approximation of the leave-one-out cross-validation log-likelihood (loo, see Vehtari, A. et al 2017). AIC penalises the likelihood of the model as a function of the number of model parameter, while loo approximate the likelihood of the model on leave-one out cross validation. Therefore, both these metrics can be used to correctly compare the two approaches
```r
m$AIC
#> [1] 1455.775
m_classic$AIC
#> [1] 1584.531
loo(m)
#> Warning: Found 6 observation(s) with a pareto_k > 0.7. We recommend calling 'loo' again with argument 'k_threshold = 0.7' in order to calculate the ELPD without the assumption that these observations are negligible. This will refit the model 6 times to compute the ELPDs for the problematic observations directly.
#> [1] -707.626
loo(m_classic)
#> [1] -777.2048
```
We see that our trophic model has a lower AIC and a higher loo, which proves that including prey improves the model.
### Interpolation
We now compare the predictive performance of the two approaches on the training dataset. To do so, we first use the function `predict`, and then the function `evaluateModelFit` to compare how well predictions match the true data.
```r
# Trophic SDM (when Xnew is not specified, predictions are carried on
# the training dataset by setting Xnew = m$data$X)
Ypred = predict(m, fullPost = FALSE)
# Transfom in a table
Ypred = do.call(cbind,
lapply(Ypred, function(x) x$predictions.mean))
# Re order columns
Ypred = Ypred[,colnames(Y)]
metrics = evaluateModelFit(m, Ynew = Y, Ypredicted = Ypred)
# Classical SDM
Ypred_classic = predict(m, fullPost = FALSE)
Ypred_classic = do.call(cbind,
lapply(Ypred_classic, function(x) x$predictions.mean))
Ypred_classic = Ypred_classic[,colnames(Y)]
metrics_classic = evaluateModelFit(m, Ynew = Y, Ypredicted = Ypred_classic)
# Mean AUC
mean(metrics$auc)
#> [1] 0.7937958
mean(metrics_classic$auc)
#> [1] 0.8031646
# Mean TSS
mean(metrics$tss)
#> [1] 0.5325318
mean(metrics_classic$tss)
#> [1] 0.5312451
```
On the training dataset models have similar performances, with our trophic model that slightly improves SDM's TSS.
### Cross-validation
We now compare the two approaches in K-fold cross validation with the function `trophicSDM_CV`. This function creates a partition based on the specified number of fold (but can also takes a user-specified partition in the argument `partition`) and run a cross validation. This can take a bit of time. Set `run.parallel = TRUE` if you want to reduce computation time.
```r
# 3-fold cross validation
CV = trophicSDM_CV(m, K = 3, prob.cov = T, iter = 2000,
pred_samples = 500, run.parallel = FALSE)
#> [1] "Fold 1 out of 3 \n"
#> [1] "Fold 2 out of 3 \n"
#> [1] "Fold 3 out of 3 \n"
# Transfom in a table
Ypred = CV$meanPred
# Re order columns
Ypred = Ypred[,colnames(Y)]
metrics = evaluateModelFit(m, Ynew = Y, Ypredicted = Ypred)
# Classical SDM
# We specify the same partition for classic SDM so that the two cross-validations are comparable.
CV_classic = trophicSDM_CV(m_classic, K = 3, prob.cov = T, iter = 2000,
pred_samples = 500, run.parallel = FALSE,
partition = CV$partition)
#> [1] "Fold 1 out of 3 \n"
#> [1] "Fold 2 out of 3 \n"
#> [1] "Fold 3 out of 3 \n"
Ypred_classic = CV_classic$meanPred
Ypred_classic = Ypred_classic[,colnames(Y)]
metrics_classic = evaluateModelFit(m, Ynew = Y, Ypredicted = Ypred_classic)
# Mean AUC
mean(metrics$auc)
#> [1] 0.6999403
mean(metrics_classic$auc)
#> [1] 0.668446
# Mean TSS
mean(metrics$tss)
#> [1] 0.4260548
mean(metrics_classic$tss)
#> [1] 0.3773521
```
The increase in mean AUC and TSS is even higher in 3-fold cross-validation than on the fitted data. As we simulated the data with a strong biotic signal, trophic SDM proves to be a better tool than classic SDM.
## Potential niche
We also implemented a function to predict species potential niches, defined as the probability of presence of species along the environmental gradient when the biotic constrain is realised, i.e., when all its prey are set to present (vice-versa, when modeling species top-down, when the predator are absent). We here compute the probability of presence of species at environmental conditions X_1= 0.5, X_2 = 0.5 when the preys are available.
```r
preds = predictPotential(m, Xnew = data.frame(X_1 = 0.5, X_2 = 0.5))
#> Error in predictPotential(m, Xnew = data.frame(X_1 = 0.5, X_2 = 0.5)): could not find function "predictPotential"
# Take the posterior mean
lapply(preds,mean)
#> Warning in mean.default(X[[i]], ...): l'argomento non è numerico o logico: si restituisce NA
#> $predictions.prob
#> [1] 0.9983807
#>
#> $predictions.bin
#> [1] NA
```
## Author
This package is currently developed by Giovanni Poggiato from Laboratoire d’Ecologie Alpine. It is supported by the ANR GAMBAS. The framework implemented in this package is described in: "Integrating trophic food webs in species distribution models improves ecological niche estimation and prediction" Poggiato Giovanni, Jérémy Andréoletti, Laura J. Pollock and Wilfried Thuiller. In preparation.
## References
Grace, J. B., Johnson, D. J., Lefcheck, J. S., and Byrnes, J. E. K.. 2018. Quantifying relative importance: computing standardized effects in models with binary outcomes. Ecosphere 9(6):e02283.
Vehtari, A., Gelman, A., and Gabry, J. (2017). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing. 27(5), 1413–1432.
|
/scratch/gouwar.j/cran-all/cranData/webSDM/vignettes/Introduction.Rmd
|
#' Query https://pesticidecompendium.bcpc.org
#'
#' Query the BCPC Compendium of Pesticide Common Names
#' \url{https://pesticidecompendium.bcpc.org}
#' formerly known as Alan Woods Compendium of Pesticide Common Names
#' @import xml2
#'
#' @param query character; search string
#' @param from character; type of input ('cas' or 'name')
#' @param verbose logical; print message during processing to console?
#' @param ... additional arguments to internal utility functions
#' @param type deprecated
#' @return A list of eight entries: common-name, status, preferred IUPAC Name,
#' IUPAC Name, cas, formula, activity, subactivity, inchikey, inchi and source
#' url.
#' @note for from = 'cas' only the first matched link is returned.
#' Please respect Copyright, Terms and Conditions
#' \url{https://pesticidecompendium.bcpc.org/legal.html}!
#' @references Eduard Szöcs, Tamás Stirling, Eric R. Scott, Andreas Scharmüller,
#' Ralf B. Schäfer (2020). webchem: An R Package to Retrieve Chemical
#' Information from the Web. Journal of Statistical Software, 93(13).
#' \doi{10.18637/jss.v093.i13}.
#' @export
#' @examples
#' \dontrun{
#' bcpc_query('Fluazinam', from = 'name')
#' out <- bcpc_query(c('Fluazinam', 'Diclofop'), from = 'name')
#' out
#' # extract subactivity from object
#' sapply(out, function(y) y$subactivity[1])
#'
#' # use CAS-numbers
#' bcpc_query("79622-59-6", from = 'cas')
#' }
bcpc_query <- function(query, from = c("name", "cas"),
verbose = getOption("verbose"),
type, ...) {
if (!ping_service("bcpc")) stop(webchem_message("service_down"))
if (!missing(type)) {
message('"type" is deprecated. Please use "from" instead. ')
from <- type
}
if ("commonname" %in% from) {
message('To search by compound name use "name" instead of "commonname"')
from <- "name"
}
from <- match.arg(from)
bcpc_idx <- build_bcpc_idx(verbose, ...)
names(query) <- query
foo <- function(query, from, verbose) {
if (from == "cas") {
query <- as.cas(query, verbose = verbose)
names <- bcpc_idx$names[bcpc_idx$source == "rn"]
# select only first link
links <- bcpc_idx$links[bcpc_idx$source == "rn"]
linknames <- bcpc_idx$linknames[bcpc_idx$source == "rn"]
cname <- linknames[tolower(names) == tolower(query)]
}
if (is.na(query)) {
if (verbose) webchem_message("na")
return(NA)
}
if (verbose) webchem_message("query", query, appendLF = FALSE)
# search links in indexes
if (from == "name") {
links <- bcpc_idx$links[bcpc_idx$source == "cn"]
names <- bcpc_idx$linknames[bcpc_idx$source == "cn"]
cname <- query
}
takelink <- links[tolower(names) == tolower(query)]
if (length(takelink) == 0) {
if (verbose) message("Not found.")
return(NA)
}
if (length(takelink) > 1) {
takelink <- unique(takelink)
if (length(takelink) > 1) {
message("More then one link found. Returning first.")
takelink <- takelink[1]
}
}
qurl <- paste0("https://pesticidecompendium.bcpc.org/", takelink)
webchem_sleep(type = 'scrape')
res <- try(httr::RETRY("GET",
qurl,
httr::user_agent(webchem_url()),
terminate_on = 404,
config = httr::config(accept_encoding = "identity"),
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (verbose) message(httr::message_for_status(res))
if (res$status_code == 200){
ttt <- read_html(res)
status <- xml_text(
xml_find_all(ttt, "//tr/th[@id='r1']/following-sibling::td"))
pref_iupac_name <- xml_text(
xml_find_all(ttt, "//tr/th[@id='r2']/following-sibling::td"))
iupac_name <- xml_text(
xml_find_all(ttt, "//tr/th[@id='r3']/following-sibling::td"))
cas <- xml_text(
xml_find_all(ttt, "//tr/th[@id='r5']/following-sibling::td"))
formula <- xml_text(
xml_find_all(ttt, "//tr/th[@id='r6']/following-sibling::td"))
activity_text <- as.character(xml_find_all(ttt, "//tr/th[@id='r7']/following-sibling::td"))
a_tmp_1 <- trimws(gsub("<td.*?>(.*)</td>", "\\1", activity_text))
a_tmp_2 <- gsub("<a.*?>", "", a_tmp_1)
a_tmp_3 <- gsub("</a>", "", a_tmp_2)
a_split <- strsplit(a_tmp_3, "<br>")[[1]]
activity <- unname(sapply(a_split, function(x) gsub(" \\(.*\\)$", "", x)))
subactivity <- unname(sapply(a_split, function(x) {
if (grepl("\\(.*\\)", x)) gsub(".*\\((.*)\\)$", "\\1", x)
else NA}))
inchikey_r <- xml_text(
xml_find_all(ttt, "//tr/th[@id='r11']/following-sibling::td"))
if (length(inchikey_r) == 0) {
inchikey <- NA
} else {
if (grepl("isomer", inchikey_r)) {
inchikey <- c(
s_isomer = gsub(
".*\\(S\\)-isomer:(.*)(minor component.*)", "\\1", inchikey_r),
r_isomer = gsub(".*\\(R\\)-isomer:(.*)", "\\1", inchikey_r))
}
if (grepl("identifier", inchikey_r)) {
inchikey <- c(gsub("(.*)identifier.*", "\\1", inchikey_r),
gsub(".*identifier.*:(.*)", "\\1", inchikey_r))
names(inchikey) <- c("inchikey",
gsub(".*(identifier.*:).*", "\\1", inchikey_r)
)
}
if (!grepl("isomer", inchikey_r) & !grepl("identifier", inchikey_r))
inchikey <- inchikey_r
}
inchi <- xml_text(
xml_find_all(ttt, "//tr/th[@id='r12']/following-sibling::td"))
if (length(inchi) == 0) {
inchi <- NA
} else {
if (grepl("isomer", inchi)) {
inchi <- c(s_isomer = gsub(".*\\(S\\)-isomer:(.*)(minor component.*)",
"\\1", inchi),
r_isomer = gsub(".*\\(R\\)-isomer:(.*)", "\\1", inchi))
}
}
out <- list(cname = cname, status = status,
pref_iupac_name = pref_iupac_name, iupac_name = iupac_name,
cas = cas, formula = formula, activity = activity,
subactivity = subactivity, inchikey = inchikey, inchi = inchi,
source_url = qurl)
return(out)
}
else {
return(NA)
}
}
out <- lapply(query, function(x) foo(x, from = from, verbose = verbose))
class(out) <- c("bcpc_query", "list")
return(out)
}
#' Function to build index
#'
#' This function builds an index of the BCPC Compendium of Pesticides
#' and saves it to \code{\link{tempdir}}.
#' @import xml2
#'
#' @param verbose logical; print message during processing to console?
#' @param force_build logical; force building a new index?
#' @return a data.frame
#' @seealso \code{\link{bcpc_query}}, \code{\link{tempdir}}
#' @source \url{https://pesticidecompendium.bcpc.org}
#' @noRd
build_bcpc_idx <- function(verbose = getOption("verbose"), force_build = FALSE) {
if (!ping_service("bcpc")) stop(webchem_message("service_down"))
suppressWarnings(try(load(paste0(tempdir(), "/data/bcpc_idx.rda")),
silent = TRUE))
if (!file.exists(paste0(tempdir(), "/data/bcpc_idx.rda")) |
force_build |
try(Sys.Date() - attr(bcpc_idx, "date"), silent = TRUE) > 30) {
if (!dir.exists(paste0(tempdir(), "/data"))) {
dir.create(paste0(tempdir(), "/data"))
}
if (verbose) message("Building index. ", appendLF = FALSE)
idx1_url <- "https://pesticidecompendium.bcpc.org/index_rn.html"
idx4_url <- "https://pesticidecompendium.bcpc.org/index_cn.html"
res1 <- try(httr::RETRY("GET",
idx1_url,
httr::user_agent(webchem_url()),
config = httr::config(accept_encoding = "identity"),
terminate_on = 404,
quiet = TRUE), silent= TRUE)
if (inherits(res1, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (verbose) message(httr::message_for_status(res1))
if (res1$status_code == 200){
idx1 <- read_html(res1)
prep_idx <- function(y) {
names <- xml_text(xml_find_all(y, "//dl/dt"))
links <- xml_attr(
xml_find_all(y, "//dt/following-sibling::dd[1]/a[1]"), "href")
linknames <- xml_text(
xml_find_all(y, "//dt/following-sibling::dd[1]/a[1]"))
return(data.frame(names, links, linknames, stringsAsFactors = FALSE))
}
bcpc_idx <- rbind(prep_idx(idx1))
bcpc_idx[["source"]] <- "rn"
res4 <- try(httr::RETRY("GET",
idx4_url,
httr::user_agent(webchem_url()),
config = httr::config(accept_encoding = "identity"),
terminate_on = 404,
quiet = TRUE), silent= TRUE)
if (inherits(res4, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
idx4 <- read_html(res4)
n <- xml_find_all(idx4, "//a")
names <- xml_text(n)
rm <- names == ""
names <- names[!rm]
links <- xml_attr(n, "href")
links <- links[!rm]
idx4 <- data.frame(names = NA, links = links, linknames = names,
source = "cn", stringsAsFactors = FALSE)
bcpc_idx <- rbind(bcpc_idx, idx4)
# fix encoding
ln <- bcpc_idx$linknames
Encoding(ln) <- "latin1"
ln <- iconv(ln, from = "latin1", to = "ASCII", sub = "")
bcpc_idx$linknames <- ln
attr(bcpc_idx, "date") <- Sys.Date()
save(bcpc_idx, file = paste0(tempdir(), "/data/bcpc_idx.rda"))
}
}
return(bcpc_idx)
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/bcpc.R
|
#' Retrieve Lite Entity (identifiers) from ChEBI
#'
#' Returns a data.frame with a ChEBI entity ID (chebiid),
#' a ChEBI entity name (chebiasciiname), a search score (searchscore) and
#' stars (stars) using the SOAP protocol:
#' \url{https://www.ebi.ac.uk/chebi/webServices.do}
#' @import httr xml2
#'
#' @param query character; search term.
#' @param from character; type of input. \code{"all"} searches all types and
#' \code{"name"} searches all names. Other options include \code{'chebi id'},
#' \code{'chebi name'}, \code{'definition'}, \code{'iupac name'},
#' \code{'citations'}, \code{'registry numbers'}, \code{'manual xrefs'},
#' \code{'automatic xrefs'}, \code{'formula'}, \code{'mass'},
#' \code{'monoisotopic mass'},\code{'charge'}, \code{'inchi'},
#' \code{'inchikey'}, \code{'smiles'}, and \code{'species'}
#' @param match character; How should multiple hits be handled?, \code{"all"}
#' all matches are returned, \code{"best"} the best matching (by the ChEBI
#' searchscore) is returned, \code{"ask"} enters an interactive mode and the
#' user is asked for input, \code{"na"} returns NA if multiple hits are found.
#' @param max_res integer; maximum number of results to be retrieved from the
#' web service
#' @param stars character; "three only" restricts results to those manualy
#' annotated by the ChEBI team.
#' @param verbose logical; should a verbose output be printed on the console?
#' @param ... currently unused
#' @return returns a list of data.frames containing a chebiid, a chebiasciiname,
#' a searchscore and stars if matches were found. If not, data.frame(NA) is
#' returned
#'
#' @references Hastings J, Owen G, Dekker A, Ennis M, Kale N, Muthukrishnan V,
#' Turner S, Swainston N, Mendes P, Steinbeck C. (2016). ChEBI in 2016:
#' Improved services and an expanding collection of metabfolites. Nucleic
#' Acids Res.
#'
#' Hastings, J., de Matos, P., Dekker, A., Ennis, M., Harsha, B., Kale, N.,
#' Muthukrishnan, V., Owen, G., Turner, S., Williams, M., and Steinbeck, C.
#' (2013) The ChEBI reference database and ontology for biologically relevant
#' chemistry: enhancements for 2013. Nucleic Acids Res.
#'
#' de Matos, P., Alcantara, R., Dekker, A., Ennis, M., Hastings, J., Haug, K.,
#' Spiteri, I., Turner, S., and Steinbeck, C. (2010) Chemical entities of
#' biological interest: an update. Nucleic Acids Res. Degtyarenko, K.,
#' Hastings, J., de Matos, P., and Ennis, M. (2009). ChEBI: an open
#' bioinformatics and cheminformatics resource. Current protocols in
#' bioinformatics / editoral board, Andreas D. Baxevanis et al., Chapter 14.
#'
#' Degtyarenko, K., de Matos, P., Ennis, M., Hastings, J., Zbinden, M.,
#' McNaught, A., Alcántara, R., Darsow, M., Guedj, M. and Ashburner, M. (2008)
#' ChEBI: a database and ontology for chemical entities of biological
#' interest. Nucleic Acids Res. 36, D344–D350.
#' @references Eduard Szöcs, Tamás Stirling, Eric R. Scott, Andreas Scharmüller,
#' Ralf B. Schäfer (2020). webchem: An R Package to Retrieve Chemical
#' Information from the Web. Journal of Statistical Software, 93(13).
#' \doi{10.18637/jss.v093.i13}.
#' @export
#' @examples
#' \dontrun{
#' # might fail if API is not available
#' get_chebiid('Glyphosate')
#' get_chebiid('BPGDAMSIGCZZLK-UHFFFAOYSA-N')
#'
#' # multiple inputs
#' comp <- c('Iron', 'Aspirin', 'BPGDAMSIGCZZLK-UHFFFAOYSA-N')
#' get_chebiid(comp)
#'
#' }
get_chebiid <- function(query,
from = c('all', 'chebi id', 'chebi name', 'definition', 'name',
'iupac name', 'citations', 'registry numbers', 'manual xrefs',
'automatic xrefs', 'formula', 'mass', 'monoisotopic mass',
'charge', 'inchi', 'inchikey', 'smiles', 'species'),
match = c("all", "best", "first", "ask", "na"),
max_res = 200,
stars = c('all', 'two only', 'three only'),
verbose = getOption("verbose"),
...) {
if (!ping_service("chebi")) stop(webchem_message("service_down"))
match <- match.arg(match)
from <- toupper(match.arg(from))
if (from == "NAME") {
from <- "ALL NAMES"
}
if (from == "inchi" | from == "inchikey") {
from <- "INCHI/INCHI KEY"
}
stars <- toupper(match.arg(stars))
foo <- function(query, from, match, max_res, stars, verbose, ...) {
if (is.na(query)) {
if (verbose) webchem_message("na")
return(tibble::tibble("query" = NA_character_, "chebiid" = NA_character_))
}
# query
url <- 'http://www.ebi.ac.uk:80/webservices/chebi/2.0/webservice'
headers <- c(Accept = 'text/xml',
Accept = 'multipart/*',
`Content-Type` = 'text/xml; charset=utf-8',
SOAPAction = '')
body <- paste0('
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:chebi="https://www.ebi.ac.uk/webservices/chebi">
<soapenv:Header/>
<soapenv:Body>
<chebi:getLiteEntity>
<chebi:search>', query, '</chebi:search>
<chebi:searchCategory>', from, '</chebi:searchCategory>
<chebi:maximumResults>', max_res, '</chebi:maximumResults>
<chebi:stars>', stars, '</chebi:stars>
</chebi:getLiteEntity>
</soapenv:Body>
</soapenv:Envelope>')
webchem_sleep(type = 'API')
if (verbose) webchem_message("query", query, appendLF = FALSE)
res <- try(httr::RETRY("POST",
url,
httr::user_agent(webchem_url()),
httr::add_headers(headers),
body = body,
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(tibble::tibble("query" = query, "chebiid" = NA_character_))
}
if (verbose) message(httr::message_for_status(res))
if (res$status_code == 200) {
cont <- content(res, type = 'text/xml', encoding = 'utf-8')
out <- l2df(as_list(xml_children(xml_find_first(cont, '//d1:return'))))
names(out) <- tolower(names(out))
out <- as_tibble(out)
if (nrow(out) == 0) {
if (verbose) webchem_message("not_found")
return(tibble::tibble("query" = query, "chebiid" = NA_character_))
}
if (nrow(out) > 0) out$query <- query
if (nrow(out) == 1) return(out)
if (match == 'all') {
return(out)
}
if (match == 'best') {
if (verbose)
message('Returning best match. \n')
out <- out[with(out, order(searchscore, decreasing = TRUE)), ]
return(out[which.max(out$searchscore), ])
}
if (match == "ask") {
matched <-
matcher(
out$chebiid,
query = query,
result = out$chebiasciiname,
match = "ask",
from = match.arg(from),
verbose = verbose
)
return(out[out$chebiid == matched, ])
}
if (match == "na") {
return(tibble::tibble("query" = query, "chebiid" = NA_character_))
}
if (match == "first") {
return(out[1, ])
}
} else {
return(tibble::tibble("query" = query, "chebiid" = NA_character_))
}
}
out <- lapply(query,
foo,
from = from,
match = match,
max_res = max_res,
stars = stars,
verbose = verbose)
names(out) <- query
out <- bind_rows(out)
return(dplyr::select(out, "query", "chebiid", everything()))
}
#' Retrieve Complete Entity from ChEBI
#'
#' Returns a list of Complete ChEBI entities.
#' ChEBI data are parsed as data.frames ("properties", "chebiid_snd",
#' "synonyms", "iupacnames", "formulae", "regnumbers", "citations", "dblinks",
#' "parents", "children", "comments", "origins") or
#' as a list ("chem_structure") in the list.
#' The SOAP protocol is used \url{https://www.ebi.ac.uk/chebi/webServices.do}.
#'
#' @import httr xml2
#'
#' @param chebiid character; search term (i.e. chebiid).
#' @param verbose logical; should a verbose output be printed on the console?
#' @param ... optional arguments
#' @return returns a list of data.frames or lists containing a complete ChEBI
#' entity
#'
#' @references Hastings J, Owen G, Dekker A, Ennis M, Kale N, Muthukrishnan V,
#' Turner S, Swainston N, Mendes P, Steinbeck C. (2016). ChEBI in 2016:
#' Improved services and an expanding collection of metabolites. Nucleic Acids
#' Res.
#'
#' Hastings, J., de Matos, P., Dekker, A., Ennis, M., Harsha, B., Kale, N.,
#' Muthukrishnan, V., Owen, G., Turner, S., Williams, M., and Steinbeck, C.
#' (2013) The ChEBI reference database and ontology for biologically relevant
#' chemistry: enhancements for 2013. Nucleic Acids Res.
#'
#' de Matos, P., Alcantara, R., Dekker, A., Ennis, M., Hastings, J., Haug, K.,
#' Spiteri, I., Turner, S., and Steinbeck, C. (2010) Chemical entities of
#' biological interest: an update. Nucleic Acids Res. Degtyarenko, K.,
#' Hastings, J., de Matos, P., and Ennis, M. (2009). ChEBI: an open
#' bioinformatics and cheminformatics resource. Current protocols in
#' bioinformatics / editoral board, Andreas D. Baxevanis et al., Chapter 14.
#'
#' Degtyarenko, K., de Matos, P., Ennis, M., Hastings, J., Zbinden, M.,
#' McNaught, A., Alcántara, R., Darsow, M., Guedj, M. and Ashburner, M. (2008)
#' ChEBI: a database and ontology for chemical entities of biological
#' interest. Nucleic Acids Res. 36, D344–D350.
#' @references Eduard Szöcs, Tamás Stirling, Eric R. Scott, Andreas Scharmüller,
#' Ralf B. Schäfer (2020). webchem: An R Package to Retrieve Chemical
#' Information from the Web. Journal of Statistical Software, 93(13).
#' \doi{10.18637/jss.v093.i13}.
#' @export
#' @examples
#' \dontrun{
#' # might fail if API is not available
#' chebi_comp_entity('CHEBI:27744')
#'
#' # multiple inputs
#' comp <- c('CHEBI:27744', 'CHEBI:27744')
#' chebi_comp_entity(comp)
#'
#' }
chebi_comp_entity <- function(chebiid,
verbose = getOption("verbose"),
...) {
if (!ping_service("chebi")) stop(webchem_message("service_down"))
foo <- function(chebiid, verbose, ...) {
# chebiid = c('CHEBI:27744', 'CHEBI:17790'); verbose = TRUE # debuging
if (is.na(chebiid)) {
if (verbose) webchem_message("na")
return(NA)
}
url <- 'http://www.ebi.ac.uk:80/webservices/chebi/2.0/webservice'
headers <- c(Accept = 'text/xml',
Accept = 'multipart/*',
`Content-Type` = 'text/xml; charset=utf-8',
SOAPAction = '')
body <- paste0('
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:chebi="https://www.ebi.ac.uk/webservices/chebi">
<soapenv:Header/>
<soapenv:Body>
<chebi:getCompleteEntity>
<chebi:chebiId>', chebiid, '</chebi:chebiId>
</chebi:getCompleteEntity>
</soapenv:Body>
</soapenv:Envelope>')
if (verbose) webchem_message("query", chebiid, appendLF = FALSE)
webchem_sleep(type = 'API')
res <- try(httr::RETRY("POST",
url,
httr::user_agent(webchem_url()),
httr::add_headers(headers),
body = body,
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (verbose) message(httr::message_for_status(res))
if (res$status_code != 200) {
return(NA)
} else {
cont <- content(res, type = 'text/xml', encoding = 'utf-8')
# restricted to one entry
properties <- data.frame(
chebiid = trimws(xml_text(xml_find_first(cont, '//d1:chebiId'))),
chebiasciiname = trimws(xml_text(
xml_find_first(cont, '//d1:chebiAsciiName'))),
definition = trimws(xml_text(xml_find_first(cont, '//d1:definition'))),
status = trimws(xml_text(xml_find_first(cont, '//d1:status'))),
smiles = trimws(xml_text(xml_find_first(cont, '//d1:smiles'))),
inchi = trimws(xml_text(xml_find_first(cont, '//d1:inchi'))),
inchikey = trimws(xml_text(xml_find_first(cont, '//d1:inchiKey'))),
charge = trimws(xml_text(xml_find_first(cont, '//d1:charge'))),
mass = trimws(xml_text(xml_find_first(cont, '//d1:mass'))),
monoisotopicmass = trimws(xml_text(
xml_find_first(cont, '//d1:monoisotopicMass'))),
entitystar = trimws(xml_text(xml_find_first(cont, '//d1:entityStar'))),
stringsAsFactors = FALSE
)
# multiple entries possible
chebiid_snd <- data.frame(
chebiids = trimws(xml_text(
xml_find_all(cont, '//d1:SecondaryChEBIIds'))),
stringsAsFactors = FALSE
)
synonyms <- l2df(as_list(xml_find_all(cont, '//d1:Synonyms')))
iupacnames <- l2df(as_list(xml_find_all(cont, '//d1:IupacNames')))
formulae <- l2df(as_list(xml_find_all(cont, '//d1:Formulae')))
regnumbers <- l2df(as_list(xml_find_all(cont, '//d1:RegistryNumbers')))
citations <- l2df(as_list(xml_find_all(cont, '//d1:Citations')))
chem_structure <- as_list(xml_find_all(cont, '//d1:ChemicalStructures'))
dblinks <- l2df(as_list(xml_find_all(cont, '//d1:DatabaseLinks')))
parents <- l2df(as_list(xml_find_all(cont, '//d1:OntologyParents')))
children <- l2df(as_list(xml_find_all(cont, '//d1:OntologyChildren')))
comments <- l2df(as_list(xml_find_all(cont, '//d1:GeneralComments')))
origins <- l2df(as_list(xml_find_all(cont, '//d1:CompoundOrigins')))
# output
out <- list(
properties = properties,
chebiid_snd = chebiid_snd,
chem_structure = chem_structure,
synonyms = synonyms,
iupacnames = iupacnames,
formulae = formulae,
regnumbers = regnumbers,
citations = citations,
dblinks = dblinks,
parents = parents,
children = children,
comments = comments,
origins = origins
)
return(out)
}
}
out <- lapply(chebiid, foo, verbose = verbose)
names(out) <- chebiid
class(out) <- c("chebi_comp_entity", "list")
return(out)
}
#' Helper function to parse some ChEBI data
#'
#' @param x list; a list to bind into a data.frame
#' @return a data.frame
#' @seealso \code{\link{chebi_comp_entity}}
#' @noRd
#'
l2df <- function(x) {
out <- data.frame(rbind_named_fill(lapply(x, unlist)),
row.names = NULL,
stringsAsFactors = FALSE)
return(out)
}
#' Helper function replacing do.call(rbind, list())
#' to address the issue of different column lengths in a list of data.frames
#' taken from:
#' https://stackoverflow.com/questions/17308551/do-callrbind-list-for-uneven-number-of-column
#' @param x list; a list to bind into a data.frame
#' @seealso \code{\link{l2df}}
#' @noRd
#'
rbind_named_fill <- function(x) {
nam <- lapply(x, names)
unam <- unique(unlist(nam))
len <- lapply(x, length)
out <- vector("list", length(len))
for (i in seq_along(len)) {
out[[i]] <- unname(x[[i]])[match(unam, nam[[i]])]
}
newout <- as.data.frame(do.call(rbind, out), stringsAsFactors = FALSE)
names(newout) <- unam
return(newout)
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/chebi.R
|
#' Query ChEMBL using ChEMBL IDs
#'
#' Retrieve ChEMBL data using a vector of ChEMBL IDs.
#' @param query character; a vector of ChEMBL IDs.
#' @param resource character; the ChEMBL resource to query. Use
#' [chembl_resources()] to see all available resources.
#' @param cache_file character; the name of the cache file without the file
#' extension. If \code{NULL}, results are not cached.
#' @param verbose logical; should a verbose output be printed on the console?
#' @param test_service_down logical; this argument is only used for testing.
#' @return The function returns a list of lists, where each element of the list
#' contains a list of respective query results. Results are simplified, if
#' possible.
#' @details Each entry in ChEMBL has a unique ID. Data in ChEMBL is organized in
#' databases called resources. An entry may or may not have a record in a
#' particular resource. An entry may have a record in more than one resource,
#' e.g. a compound may be present in both the "molecule" and the "drug"
#' resource. This function queries a vector of ChEMBL IDs from a specific ChEMBL
#' resource.
#' @details If you are unsure which ChEMBL resource contains your ChEMBL ID,
#' use this function with the \code{"chembl_id_lookup"} resource to find the
#' appropriate resource for a ChEMBL ID. Note that \code{"chembl_id_lookup"} is
#' not a separate function but a resource used by \code{chembl_query}.
#' @details If \code{cache_file} is not \code{NULL} the function creates a
#' cache directory in the working directory and a cache file in the cache
#' directory. This file is used in subsequent calls of the function. The
#' function first tries to retrieve query results from the cache file and only
#' accesses the webservice if the ChEMBL ID cannot be found in the cache file.
#' The cache file is extended as new ChEMBL ID-s are queried during the session.
#' @note
#' Links to the webservice documentation:
#' \itemize{
#' \item \url{https://chembl.gitbook.io/chembl-interface-documentation},
#' \item \url{https://www.ebi.ac.uk/chembl/api/data/docs}
#' }
#' @references Gaulton, A., Bellis, L. J., Bento, A. P., Chambers, J.,
#' Davies, M., Hersey, A., ... & Overington, J. P. (2012). ChEMBL: a large-scale
#' bioactivity database for drug discovery. Nucleic acids research, 40(D1),
#' D1100-D1107.
#' @examples
#' \dontrun{
#' # Might fail if API is not available
#'
#' # Search molecules
#' chembl_query("CHEMBL1082", resource = "molecule")
#' chembl_query(c("CHEMBL25", "CHEMBL1082"), resource = "molecule")
#'
#' # Look up ChEMBL IDs in ChEMBL "resources", returns one resource per query.
#' chembl_query("CHEMBL771355", "chembl_id_lookup")
#'
#' # Search assays
#' chembl_query("CHEMBL771355", resource = "assay")
#' }
#' @importFrom httr RETRY message_for_status content
#' @export
chembl_query <- function(query,
resource = "molecule",
cache_file = NULL,
verbose = getOption("verbose"),
test_service_down = FALSE) {
resource <- match.arg(resource, chembl_resources())
stem <- "https://www.ebi.ac.uk/chembl/api/data"
foo <- function(query, verbose) {
if (is.na(query)) {
if (verbose) webchem_message("na")
return(NA)
}
if (grepl("^CHEMBL[0-9]+", query) == FALSE) {
if (verbose) message("Query is not a ChEMBL ID. Returning NA.")
return(NA)
}
if (verbose) webchem_message("query", query, appendLF = FALSE)
url <- ifelse(
test_service_down, "", paste0(stem, "/", resource, "/", query, ".json"))
webchem_sleep(type = "API")
res <- try(httr::RETRY("GET",
url,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (res$status_code != 200) {
if (verbose) message(httr::message_for_status(res))
return(NA)
}
if (verbose) message(httr::message_for_status(res))
cont <- httr::content(res, type = "application/json")
cont <- format_chembl(cont)
return(cont)
}
if (is.null(cache_file)) {
out <- lapply(query, function(x) foo(x, verbose = verbose))
} else {
if (!dir.exists("cache")) dir.create("cache")
cfpath <- paste0("cache/", cache_file, ".rds")
if (file.exists(cfpath)) {
query_results <- readRDS(file = cfpath)
} else {
query_results <- list()
}
out <- lapply(query, function(x) {
if (x %in% names(query_results)) {
if (verbose) webchem_message("query", x, appendLF = FALSE)
if (verbose) message("Already retrieved.")
return(query_results[[x]])
} else {
new <- foo(x, verbose = verbose)
if (!is.na(x)) {
query_results[[x]] <<- new
saveRDS(query_results, file = cfpath)
}
return(new)
}
})
}
return(out)
}
#' Retrieve all ATC classes
#'
#' Retrieve all available classes within the Anatomical Therapeutic Chemical
#' (ATC) classification system.
#' @param verbose logical; should a verbose output be printed on the console?
#' @param test_service_down logical; this argument is only used for testing.
#' @references Gaulton, A., Bellis, L. J., Bento, A. P., Chambers, J.,
#' Davies, M., Hersey, A., ... & Overington, J. P. (2012). ChEMBL: a large-scale
#' bioactivity database for drug discovery. Nucleic acids research, 40(D1),
#' D1100-D1107.
#' @examples
#' \dontrun{
#' # Might fail if API is not available
#'
#' atc <- atc_classes()
#' }
#' @importFrom httr RETRY user_agent message_for_status content
#' @importFrom tibble tibble as_tibble
#' @importFrom dplyr bind_rows
#' @export
chembl_atc_classes <- function(verbose = getOption("verbose"),
test_service_down = FALSE) {
i = 0
next_page <- "/chembl/api/data/atc_class.json?limit=1000&offset=0"
atc_classes <- tibble::tibble()
while (!is.null(next_page)) {
i = i + 1
url <- ifelse(
test_service_down, "", paste0("https://www.ebi.ac.uk", next_page))
webchem_sleep(type = "API")
if (verbose) webchem_message("query", paste0("Page ", i), appendLF = FALSE)
res <- try(httr::RETRY("GET",
url,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (verbose) message(httr::message_for_status(res))
cont <- httr::content(res, type = "application/json")
new_classes <- lapply(cont$atc, function(x) tibble::as_tibble(x))
new_classes <- dplyr::bind_rows(new_classes)
atc_classes <- dplyr::bind_rows(atc_classes, new_classes)
next_page <- cont$page_meta$`next`
}
atc_classes <- atc_classes[, c(
"who_name",
"level1", "level1_description",
"level2", "level2_description",
"level3", "level3_description",
"level4", "level4_description",
"level5"
)]
return(atc_classes)
}
#' List ChEMBL Resources
#'
#' Data in ChEMBL is organized in databases called resources. This function
#' lists available ChEMBL resources.
#' @note The list was compiled manually using the following url:
#' \url{https://chembl.gitbook.io/chembl-interface-documentation/web-services/chembl-data-web-services}
#' @references Gaulton, A., Bellis, L. J., Bento, A. P., Chambers, J.,
#' Davies, M., Hersey, A., ... & Overington, J. P. (2012). ChEMBL: a large-scale
#' bioactivity database for drug discovery. Nucleic acids research, 40(D1),
#' D1100-D1107.
#' @export
chembl_resources <- function() {
resources <- c(
"activity", "activity_supplementary_data_by_activity", "assay",
"assay_class", "atc_class", "binding_site", "biotherapeutic", "cell_line",
"chembl_id_lookup", "compound_record", "compound_structural_alert",
"document", "document_similarity", "drug", "drug_indication",
"drug_warning", "go_slim", "image", "mechanism", "metabolism",
"molecule", "molecule_form", "organism", "protein_class", "similarity",
"source", "status", "substructure", "target", "target_component",
"target_relation", "tissue", "xref_source"
)
return(resources)
}
#' Format ChEMBL results
#'
#' Format ChEMBL results by collapsing nested lists into tibbles.
#' @param cont list; json output from \code{chembl_query()}
#' @noRd
format_chembl <- function(cont) {
if ("atc_classifications" %in% names(cont)) {
cont$atc_classifications <- unlist(cont$atc_classifications)
}
if ("cross_references" %in% names(cont)) {
cont$cross_references <- dplyr::bind_rows(cont$cross_references)
}
if ("molecule_hierarchy" %in% names(cont)) {
cont$molecule_hierarchy <- dplyr::bind_rows(cont$molecule_hierarchy)
}
if ("molecule_properties" %in% names(cont)) {
cont$molecule_properties <- dplyr::bind_rows(cont$molecule_properties)
}
if ("molecule_structures" %in% names(cont)) {
cont$molecule_structures <- dplyr::bind_rows(cont$molecule_structures)
}
if ("molecule_synonyms" %in% names(cont)) {
cont$molecule_synonyms <- dplyr::bind_rows(cont$molecule_synonyms)
}
return(cont)
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/chembl.R
|
#' Retrieve ChemSpider API key
#'
#' Look for and retrieve ChemSpider API key stored in .Renviron or .Rprofile.
#'
#' @details To use the any of the functions in \code{webchem} that access the
#' ChemSpider database, you'll need to obtain an API key. Register at
#' \url{https://developer.rsc.org/} for an API key. Please respect the Terms &
#' Conditions \url{https://developer.rsc.org/terms}.
#' @details You can store your API key as \code{CHEMSPIDER_KEY = <your key>} in
#' .Renviron or as \code{options(chemspider_key = <your key>)} in .Rprofile.
#' This will allow you to use ChemSpider without adding your API key in the
#' beginning of each session, and will also allow you to share your analysis
#' without sharing your API key. Keeping your API key hidden is good practice.
#' @seealso \code{\link[usethis]{edit_r_environ}}
#' \code{\link[usethis]{edit_r_profile}}
#' @return an API key
#' @export
#' @examples
#' \dontrun{
#' cs_check_key()
#' }
cs_check_key <- function() {
x <- Sys.getenv("CHEMSPIDER_KEY", "")
if (x == "") {
x <- getOption("chemspider_key", "")
}
if (x == "")
stop("no API key stored for ChemSpider. See ?cs_check_key() for details")
else x
}
#' Retrieve ChemSpider data sources
#'
#' The function returns a vector of available data sources used by ChemSpider.
#' Some ChemSpider functions allow you to restrict which sources are used to
#' lookup the requested query. Restricting the sources makes these queries
#' faster.
#' @param apikey character; your API key. If NULL (default),
#' \code{cs_check_key()} will look for it in .Renviron or .Rprofile.
#' @param verbose should a verbose output be printed on the console?
#' @return Returns a character vector.
#' @note An API key is needed. Register at \url{https://developer.rsc.org/}
#' for an API key. Please respect the Terms & Conditions. The Terms & Conditions
#' can be found at \url{https://developer.rsc.org/terms}.
#' @references \url{https://developer.rsc.org/docs/compounds-v1-trial/1/overview}
#' @export
#' @examples
#' \dontrun{
#' cs_datasources()
#' }
cs_datasources <- function(apikey = NULL, verbose = getOption("verbose")) {
if (is.null(apikey)) {
apikey <- cs_check_key()
}
headers <- c("Content-Type" = "", "apikey" = apikey)
qurl <- "https://api.rsc.org/compounds/v1/lookups/datasources"
if (verbose) message("Querying list of data sources. ", appendLF = FALSE)
res <- try(httr::RETRY("GET",
url = qurl,
httr::add_headers(.headers = headers),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (res$status_code == 200) {
if (verbose) message(httr::message_for_status(res))
out <- unlist(unname(jsonlite::fromJSON(rawToChar(res$content))))
return(out)
}
else {
if (verbose) message(httr::message_for_status(res))
return(NA)
}
}
#' Control ChemSpider API requests
#'
#' For some ChemSpider API requests, you can also specify various control
#' options. This function is used to set these control options.
#' @param datasources character; specifies the databases to query. Use
#' \code{cs_datasources()} to retrieve available ChemSpider data sources.
#' @param order_by character; specifies the sort order for the results.
#' Valid values are \code{"default"}, \code{"recordId"}, \code{"massDefect"},
#' \code{"molecularWeight"}, \code{"referenceCount"}, \code{"dataSourceCount"},
#' \code{"pubMedCount"}, \code{"rscCount"}.
#' @param order_direction character; specifies the sort order for the results.
#' Valid values are \code{"default"}, \code{"ascending"}, \code{"descending"}.
#' @param include_all logical; see details.
#' @param complexity character; see details.
#' Valid values are \code{"any"} \code{"single"}, \code{"multiple"}.
#' @param isotopic character; see details.
#' Valid values are \code{"any"}, \code{"labeled"}, \code{"unlabeled"}.
#' @details The only function that currently uses \code{databases} is
#' \code{get_csid()} and only when you query a CSID from a formula. This
#' parameter is disregarded in all other queries.
#' @details Setting \code{include_all} to \code{TRUE} will consider records
#' which contain all of the filter criteria specified in the request. Setting
#' it to \code{FALSE} will consider records which contain any of the filter
#' criteria.
#' @details A compound with a \code{complexity} of \code{"multiple"} has more
#' than one disconnected system in it or a metal atom or ion.
#' @return Returns a list of specified control options.
#' @note This is a full list of all API control options.
#' However, not all of these options are used in all functions.
#' Each API uses a subset of these controls.
#' The controls that are available for a given function are indicated within the
#' documentation of the function.
#' @references \url{https://developer.rsc.org/docs/compounds-v1-trial/1/overview}
#' @seealso \code{\link{get_csid}}
#' @export
#' @examples
#' cs_control()
#' cs_control(order_direction = "descending")
cs_control <- function(datasources = vector(),
order_by = "default", order_direction = "default",
include_all = FALSE, complexity = "any",
isotopic = "any") {
order_by <- match.arg(order_by, choices = c(
"default", "recordId", "massDefect", "molecularWeight", "referenceCount",
"dataSourceCount", "pubMedCount", "rscCount"
))
order_direction <- match.arg(order_direction, choices = c(
"default", "ascending", "descending"))
include_all <- match.arg(as.character(include_all), choices = c(TRUE, FALSE))
complexity <- match.arg(complexity, choices = c("any", "single", "multiple"))
isotopic <- match.arg(isotopic, choices = c("any", "labeled", "unlabeled"))
return(list(
"datasources" = datasources,
"order_by" = order_by, "order_direction" = order_direction,
"include_all" = include_all, "complexity" = complexity,
"isotopic" = isotopic
))
}
#' ChemSpider ID from compound name, formula, SMILES, InChI or InChIKey
#'
#' Query one or more compunds by name, formula, SMILES, InChI or InChIKey and
#' return a vector of ChemSpider IDs.
#'
#' @param query character; search term.
#' @param apikey character; your API key. If NULL (default),
#' \code{cs_check_key()} will look for it in .Renviron or .Rprofile.
#' @param from character; the type of the identifier to convert from. Valid
#' values are \code{"name"}, \code{"formula"}, \code{"smiles"},
#' \code{"inchi"}, \code{"inchikey"}. The default value is \code{"name"}.
#' @param match character; How should multiple hits be handled?, "all" all
#' matches are returned, "best" the best matching is returned, "ask" enters an
#' interactive mode and the user is asked for input, "na" returns NA if
#' multiple hits are found.
#' @param verbose logical; should a verbose output be printed on the console?
#' @param ... furthrer arguments passed to \code{\link{cs_control}}
#' @details Queries by SMILES, InChI or InChiKey do not use \code{cs_control}
#' options. Queries by name use \code{order_by} and \code{order_direction}.
#' Queries by formula also use \code{datasources}. See \code{cs_control()} for
#' a full list of valid values for these control options.
#' @details \code{formula} can be expressed with and without LaTeX syntax.
#' @return Returns a tibble.
#' @note An API key is needed. Register at \url{https://developer.rsc.org/} for
#' an API key. Please respect the Terms & conditions:
#' \url{https://developer.rsc.org/terms}.
#' @references \url{https://developer.rsc.org/docs/compounds-v1-trial/1/overview}
#' @references Eduard Szöcs, Tamás Stirling, Eric R. Scott, Andreas Scharmüller,
#' Ralf B. Schäfer (2020). webchem: An R Package to Retrieve Chemical
#' Information from the Web. Journal of Statistical Software, 93(13).
#' \doi{10.18637/jss.v093.i13}.
#'
#' @export
#' @examples
#' \dontrun{
#' get_csid("triclosan")
#' get_csid(c("carbamazepine", "naproxene","oxygen"))
#' get_csid("C2H6O", from = "formula")
#' get_csid("C_{2}H_{6}O", from = "formula")
#' get_csid("CC(O)=O", from = "smiles")
#' get_csid("InChI=1S/C2H4O2/c1-2(3)4/h1H3,(H,3,4)", from = "inchi")
#' get_csid("QTBSBXVTEAMEQO-UHFFFAOYAR", from = "inchikey")
#' }
get_csid <- function(query,
from = c("name", "formula", "inchi", "inchikey", "smiles"),
match = c("all", "first", "ask", "na"),
verbose = getOption("verbose"),
apikey = NULL,
...) {
if (is.null(apikey)) {
apikey <- cs_check_key()
}
from <- match.arg(from)
match <- match.arg(match)
if (!ping_service("cs", apikey = apikey)) stop(webchem_message("service_down"))
foo <- function(x, from, match, verbose, apikey, ...) {
if (is.na(x)) {
if (verbose) webchem_message("na")
return(NA_integer_)
}
headers <- c("Content-Type" = "", "apikey" = apikey)
if (from == "name") {
body <- list(
"name" = x, "orderBy" = cs_control(...)$order_by,
"orderDirection" = cs_control(...)$order_direction
)
body <- jsonlite::toJSON(body, auto_unbox = TRUE)
}
if (from == "formula") {
body <- jsonlite::toJSON(list(
"formula" = unbox(x),
"dataSources" = cs_control(...)$datasources,
"orderBy" = unbox(cs_control(...)$order_by),
"orderDirection" = unbox(cs_control(...)$order_direction)),
auto_unbox = FALSE)
}
if (from == "inchi") {
body <- jsonlite::toJSON(list("inchi" = x), auto_unbox = TRUE)
}
if (from == "inchikey") {
body <- jsonlite::toJSON(list("inchikey" = x), auto_unbox = TRUE)
}
if (from == "smiles") {
body <- jsonlite::toJSON(list("smiles" = x), auto_unbox = TRUE)
}
if (verbose) webchem_message("query", x, appendLF = FALSE)
qurl <- paste0("https://api.rsc.org/compounds/v1/filter/", from)
webchem_sleep(type = 'API')
postres <- try(httr::RETRY("POST",
url = qurl,
httr::add_headers(.headers = headers),
body = body,
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(postres, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA_integer_)
}
if (postres$status_code == 200) {
query_id <- jsonlite::fromJSON(rawToChar(postres$content))$queryId
qurl <- paste0("https://api.rsc.org/compounds/v1/filter/",
query_id,
"/status")
webchem_sleep(type = 'API')
getstatus <- try(httr::RETRY("GET",
url = qurl,
httr::add_headers(.headers = headers),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(getstatus, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA_integer_)
}
if (getstatus$status_code == 200) {
qurl <- paste0("https://api.rsc.org/compounds/v1/filter/",
query_id,
"/results")
webchem_sleep(type = 'API')
getres <- try(httr::RETRY("GET",
url = qurl,
httr::add_headers(.headers = headers),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(getres, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA_integer_)
}
if (getres$status_code == 200) {
if (verbose) message(httr::message_for_status(getres))
res <- jsonlite::fromJSON(rawToChar(getres$content))$results
if (length(res) > 1) {
res <- matcher(res,
query = x,
match = match,
from = from,
verbose = verbose)
}
if (length(res) == 0) {
if (verbose) webchem_message("not_found")
res <- NA_integer_
}
return(res)
}
else {
if (verbose) message(httr::message_for_status(getres))
return(NA_integer_)
}
}
else {
if (verbose) message(httr::message_for_status(getstatus))
return(NA_integer_)
}
}
else {
if (verbose) message(httr::message_for_status(postres))
return(NA_integer_)
}
}
out <-
lapply(
query,
foo,
from = from,
match = match,
verbose = verbose,
apikey = apikey,
...
)
names(out) <- query
out <-
lapply(out, tibble::enframe, name = NULL, value = "csid") %>%
bind_rows(.id = "query")
return(out)
}
#' Convert identifiers using ChemSpider
#'
#' Submit one or more identifiers (CSID, SMILES, InChI, InChIKey or Mol) and
#' return one or more identifiers in another format (CSID, SMILES, InChI,
#' InChIKey or Mol).
#' @param query character; query ID.
#' @param from character; type of query ID.
#' @param to character; type to convert to.
#' @param verbose logical; should a verbose output be printed on the console?
#' @param apikey character; your API key. If NULL (default),
#' \code{cs_check_key()} will look for it in .Renviron or .Rprofile.
#' @details Not all conversions are supported. Allowed conversions:
#' \itemize{
#' \item CSID <-> InChI
#' \item CSID <-> InChIKey
#' \item CSID <-> SMILES
#' \item CSID -> Mol file
#' \item InChI <-> InChIKey
#' \item InChI <-> SMILES
#' \item InChI -> Mol file
#' \item InChIKey <-> Mol file
#' }
#' @return Returns a vector containing the converted identifier(s).
#' @note An API key is needed. Register at \url{https://developer.rsc.org/}
#' for an API key. Please respect the Terms & Conditions. The Terms & Conditions
#' can be found at \url{https://developer.rsc.org/terms}.
#' @references \url{https://developer.rsc.org/docs/compounds-v1-trial/1/overview}
#' @references Eduard Szöcs, Tamás Stirling, Eric R. Scott, Andreas Scharmüller,
#' Ralf B. Schäfer (2020). webchem: An R Package to Retrieve Chemical
#' Information from the Web. Journal of Statistical Software, 93(13).
#' \doi{10.18637/jss.v093.i13}.
#' @export
#' @examples
#' \dontrun{
#' cs_convert("BQJCRHHNABKAKU-KBQPJGBKSA-N",
#' from = "inchikey", to = "csid"
#' )
#' cs_convert("BQJCRHHNABKAKU-KBQPJGBKSA-N",
#' from = "inchikey", to = "inchi"
#' )
#' cs_convert("BQJCRHHNABKAKU-KBQPJGBKSA-N",
#' from = "inchikey", to = "mol"
#' )
#' cs_convert(160, from = "csid", to = "smiles")
#' }
cs_convert <- function(query, from, to, verbose = getOption("verbose"),
apikey = NULL) {
if (is.null(apikey)) {
apikey <- cs_check_key()
}
valid <- c("csid", "inchikey", "inchi", "smiles", "mol")
from <- match.arg(from, choices = valid)
to <- match.arg(to, choices = valid)
if (!ping_service("cs")) stop(webchem_message("service_down"))
cs_compinfo_dict <- data.frame(
"name" = c("inchi", "inchikey", "smiles", "mol"),
"cs_compinfo" = c("InChI", "InChIKey", "SMILES", "Mol2D"),
stringsAsFactors = FALSE
)
to2 <- cs_compinfo_dict[which(cs_compinfo_dict$name == to), 2]
if (from == to) {
return(query)
}
if (from == "csid") {
out <- cs_compinfo(query, fields = to2, apikey = apikey)
if (ncol(out) == 2) {
out <- out[, 2]
}
else {
out <- out[, 1]
}
return(out)
}
if (to == "csid") {
if (from == "mol") {
if (verbose) stop("Conversion not supported. Returning NA.")
return(NA_integer_)
}
else {
out <- get_csid(query, from = from, apikey = apikey)$csid
return(out)
}
}
if (from == "inchikey" & to == "smiles") {
if (verbose) stop("Conversion not supported. Returning NA.")
return(NA)
}
if (from == "smiles" & to %in% c("inchikey", "mol")) {
if (verbose) stop("Conversion not supported. Returning NA.")
return(NA)
}
if (from == "mol" & to %in% c("inchi", "smiles")) {
if (verbose) stop("Conversion not supported. Returning NA.")
return(NA)
}
foo <- function(x, from, to, verbose, apikey) {
if (is.na(x)) {
if (verbose) webchem_message("na")
return(NA)
}
headers <- c(`Content-Type` = "", `apikey` = apikey)
body <- list(
"input" = x, "inputFormat" = from,
"outputFormat" = to
)
if (verbose) webchem_message("query", x, appendLF = FALSE)
body <- jsonlite::toJSON(body, auto_unbox = TRUE)
qurl <- "https://api.rsc.org/compounds/v1/tools/convert"
webchem_sleep(type = 'API')
postres <- try(httr::RETRY("POST",
url = qurl,
httr::add_headers(.headers = headers),
body = body,
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(postres, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (postres$status_code == 200) {
if (verbose) message(httr::message_for_status(postres))
out <- jsonlite::fromJSON(rawToChar(postres$content))$output
return(out)
}
else {
if (verbose) message(httr::message_for_status(postres))
return(NA)
}
}
out <- unname(sapply(query,
foo,
from = from,
to = to,
verbose = verbose,
apikey = apikey))
return(out)
}
#' Retrieve record details by ChemSpider ID
#'
#' Submit a ChemSpider ID (CSID) and the fields you are interested in, and
#' retrieve the record details for your query.
#' @param csid numeric; can be obtained using \code{\link{get_csid}}
#' @param fields character; see details.
#' @param verbose logical; should a verbose output be printed on the console?
#' @param apikey character; your API key. If NULL (default),
#' \code{cs_check_key()} will look for it in .Renviron or .Rprofile.
#' @details Valid values for \code{fields} are \code{"SMILES"},
#' \code{"Formula"}, \code{"InChI"}, \code{"InChIKey"}, \code{"StdInChI"},
#' \code{"StdInChIKey"}, \code{"AverageMass"}, \code{"MolecularWeight"},
#' \code{"MonoisotopicMass"}, \code{"NominalMass"}, \code{"CommonName"},
#' \code{"ReferenceCount"}, \code{"DataSourceCount"}, \code{"PubMedCount"},
#' \code{"RSCCount"}, \code{"Mol2D"}, \code{"Mol3D"}. You can specify any
#' number of fields.
#' @return Returns a data frame.
#' @note An API key is needed. Register at \url{https://developer.rsc.org/}
#' for an API key. Please respect the Terms & Conditions. The Terms & Conditions
#' can be found at \url{https://developer.rsc.org/terms}.
#' @references \url{https://developer.rsc.org/docs/compounds-v1-trial/1/overview}
#' @export
#' @examples
#' \dontrun{
#' cs_compinfo(171, c("SMILES", "CommonName"))
#' cs_compinfo(171:182, "SMILES")
#' }
cs_compinfo <- function(csid, fields, verbose = getOption("verbose"),
apikey = NULL) {
if (mean(is.na(csid)) == 1) {
if (verbose) webchem_message("na")
return(NA)
}
if (is.null(apikey)) {
apikey <- cs_check_key()
}
fields <- match.arg(fields,
choices = c(
"SMILES", "Formula", "InChI", "InChIKey",
"StdInChI", "StdInChIKey", "AverageMass",
"MolecularWeight", "MonoisotopicMass",
"NominalMass", "CommonName", "ReferenceCount",
"DataSourceCount", "PubMedCount", "RSCCount",
"Mol2D", "Mol3D"
),
several.ok = TRUE
)
headers <- c("Content-Type" = "", "apikey" = apikey)
body <- list(
"recordIds" = csid[!is.na(csid)], "fields" = fields
)
body <- jsonlite::toJSON(body)
if (verbose) webchem_message("query_all", appendLF = FALSE)
qurl <- "https://api.rsc.org/compounds/v1/records/batch"
webchem_sleep(type = 'API')
postres <- try(httr::RETRY("POST",
url = qurl,
httr::add_headers(.headers = headers),
body = body,
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(postres, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (postres$status_code == 200) {
res <- jsonlite::fromJSON(rawToChar(postres$content))$records
if (length(res) == 0) {
if (verbose) webchem_message("not_found")
return(NA)
}
if (verbose) message(httr::message_for_status(postres))
out <- data.frame(id = csid)
out <- dplyr::left_join(out, res, by = "id")
return(out)
}
else {
if (verbose) message(httr::message_for_status(postres))
return(NA)
}
}
#' Get extended record details by ChemSpider ID
#'
#' Get extended info from ChemSpider, see \url{https://www.chemspider.com/}
#' @import xml2
#' @param csid character, ChemSpider ID.
#' @param token character; security token.
#' @param verbose logical; should a verbose output be printed on the console?
#' @param ... currently not used.
#' @return a data.frame with entries: 'csid', 'mf' (molecular formula),
#' 'smiles', 'inchi' (non-standard), 'inchikey' (non-standard), 'average_mass',
#' 'mw' (Molecular weight), 'monoiso_mass' (MonoisotopicMass), nominal_mass',
#' 'alogp', 'xlogp', 'common_name' and 'source_url'
#' @note A security token is needed. Please register at RSC
#' \url{https://www.rsc.org/rsc-id/register}
#' for a security token.
#' Please respect the Terms & conditions
#' \url{https://www.rsc.org/help-legal/legal/terms-conditions/}.
#' @seealso \code{\link{get_csid}} to retrieve ChemSpider IDs,
#' \code{\link{cs_compinfo}} for extended compound information.
#' @note use \code{\link{cs_compinfo}} to retrieve standard inchikey.
#' @export
#' @examples
#' \dontrun{
#' token <- "<redacted>"
#' csid <- get_csid("Triclosan")
#' cs_extcompinfo(csid, token)
#'
#' csids <- get_csid(c('Aspirin', 'Triclosan'))
#' cs_compinfo(csids)
#' }
cs_extcompinfo <- function(csid, token, verbose = getOption("verbose"), ...) {
.Deprecated("cs_compinfo()", old = "cs_extcompinfo()",
msg = "'cs_extcompinfo' is deprecated.
use 'cs_commpinfo()' instead.")
if (!ping_service("cs")) stop(webchem_message("service_down"))
foo <- function(csid, token, verbose) {
if (is.na(csid)) {
out <- as.list(rep(NA, 13))
names(out) <- c('csid', 'mf', 'smiles', 'inchi', 'inchikey',
'average_mass', 'mw', 'monoiso_mass', 'nominal_mass',
'alogp', 'xlogp', 'common_name', 'source_url')
return(out)
}
baseurl <-
'https://www.chemspider.com/MassSpecAPI.asmx/GetExtendedCompoundInfo?'
qurl <- paste0(baseurl, 'CSID=', csid, '&token=', token)
if (verbose)
message(qurl)
webchem_sleep(type = 'API')
h <- try(read_xml(qurl), silent = TRUE)
if (inherits(h, "try-error")) {
warning('CSID not found... Returning NA.')
return(NA)
}
out <- as.list(xml_text(xml_children(h)))
names(out) <- c('csid', 'mf', 'smiles', 'inchi', 'inchikey', 'average_mass',
'mw', 'monoiso_mass', 'nominal_mass', 'alogp', 'xlogp',
'common_name')
# convert to numeric
out[['average_mass']] <- as.numeric(out[['average_mass']])
out[['mw']] <- as.numeric(out[['mw']])
out[['monoiso_mass']] <- as.numeric(out[['monoiso_mass']])
out[['nominal_mass']] <- as.numeric(out[['nominal_mass']])
out[['alogp']] <- as.numeric(out[['alogp']])
out[['xlogp']] <- as.numeric(out[['xlogp']])
source_url <- paste0('https://www.chemspider.com/Chemical-Structure.', csid,
'.html')
out[['source_url']] <- source_url
return(out)
}
out <- sapply(csid, foo, token = token, verbose = verbose)
out <- data.frame(t(out), row.names = seq_len(ncol(out)))
out[['query']] <- rownames(out)
out <- data.frame(t(apply(out, 1, unlist)), stringsAsFactors = FALSE)
class(out) <- c('cs_extcompinfo', 'data.frame')
return(out)
}
#' Download images from ChemSpider
#'
#' @description Retrieve images of substances from ChemSpider and export them
#' in PNG format.
#' @param csid numeric; the ChemSpider ID (CSID) of the substance. This will
#' also be the name of the image file.
#' @param dir character; the download directory. \code{dir} accepts both
#' absolute and relative paths.
#' @param overwrite logical; should existing files in the directory with the
#' same name be overwritten?
#' @param apikey character; your API key. If NULL (default),
#' \code{cs_check_key()} will look for it in .Renviron or .Rprofile.
#' @param verbose logical; should a verbose output be printed on the console?
#' @note An API key is needed. Register at \url{https://developer.rsc.org/}
#' for an API key. Please respect the Terms & Conditions. The Terms & Conditions
#' can be found at \url{https://developer.rsc.org/terms}.
#' @references \url{https://developer.rsc.org/docs/compounds-v1-trial/1/overview}
#' @seealso \code{\link{get_csid}}, \code{\link{cs_check_key}}
#' @export
#' @examples
#' \dontrun{
#' cs_img(c(582, 682), dir = tempdir())
#' }
cs_img <- function(csid,
dir,
overwrite = TRUE,
apikey = NULL,
verbose = getOption("verbose")) {
overwrite <- match.arg(as.character(overwrite), choices = c(TRUE, FALSE))
if (is.null(apikey)) {
apikey <- cs_check_key()
}
verbose <- match.arg(as.character(verbose), choices = c(TRUE, FALSE))
if (!ping_service("cs")) stop(webchem_message("service_down"))
foo <- function(csid, dir = dir, overwrite = overwrite, apikey = apikey,
verbose = verbose) {
if (verbose) webchem_message("query", csid, appendLF = FALSE)
if (is.na(csid)) {
if (verbose) webchem_message("na")
return(tibble(query = csid, path = NA))
}
path <- paste0(dir, "/", csid, ".png")
url <- paste0("https://api.rsc.org/compounds/v1/records/", csid, "/image")
headers <- c("Content-Type" = "", "apikey" = apikey)
webchem_sleep(type = 'API')
res <- try(httr::RETRY("GET",
url,
httr::add_headers(.headers = headers),
terminate_on = 404,
quiet = TRUE), silent = FALSE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
}
else {
if (verbose) message(httr::message_for_status(res))
if (res$status_code == 200) {
cont <- httr::content(res, type = "image", encoding = "base64")
cont <- unlist(jsonlite::fromJSON(rawToChar(cont)))
cont <- base64enc::base64decode(cont)
if (overwrite) {
writeBin(cont, path)
}
else {
if (!file.exists(path)) writeBin(cont, path)
}
}
}
}
out <- lapply(csid, function(x) foo(x, dir, overwrite, apikey, verbose))
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/chemspider.R
|
#' Query Chemical Identifier Resolver
#'
#' A interface to the Chemical Identifier Resolver (CIR).
#' (\url{https://cactus.nci.nih.gov/chemical/structure_documentation}).
#'
#' @import xml2
#' @importFrom utils URLencode
#' @importFrom rlang :=
#'
#' @param identifier character; chemical identifier.
#' @param representation character; what representation of the identifier should
#' be returned. See details for possible representations.
#' @param resolver character; what resolver should be used? If NULL (default)
#' the identifier type is detected and the different resolvers are used in turn.
#' See details for possible resolvers.
#' @param match character; How should multiple hits be handled? \code{"all"}
#' returns all matches, \code{"first"} returns only the first result,
#' \code{"ask"} enters an interactive mode and the user is asked for input,
#' \code{"na"} returns \code{NA} if multiple hits are found.
#' @param choices deprecated. Use the \code{match} argument instead.
#' @param verbose logical; should a verbose output be printed on the console?
#' @param ... currently not used.
#' @return A tibble with a `query` column and a column for the requested representation.
#' @details
#' CIR can resolve can be of the following \code{identifier}: Chemical Names,
#' IUPAC names,
#' CAS Numbers, SMILES strings, IUPAC InChI/InChIKeys, NCI/CADD Identifiers,
#' CACTVS HASHISY, NSC number, PubChem SID, ZINC Code, ChemSpider ID,
#' ChemNavigator SID, eMolecule VID.
#'
#' \code{cir_query()} can handle only a part of all possible conversions of CIR.
#' Possible \code{representations} are:
#' \itemize{
#' \item \code{'smiles'}(SMILES strings),
#' \item \code{'names'} (Names),
#' \item \code{'cas'} (CAS numbers),
#' \item \code{'stdinchikey'} (Standard InChIKey),
#' \item \code{'stdinchi'} (Standard InChI),
#' \item \code{'ficts'} (FICTS Identifier),
#' \item \code{'ficus'} (FICuS Indetifier),
#' \item \code{'uuuuu'} (uuuuu Identifier),
#' \item \code{'mw'} (Molecular weight),
#' \item \code{'monoisotopic_mass'} (Monoisotopic Mass),
#' \item \code{'formula'} (Chemical Formula),
#' \item \code{'chemspider_id'} (ChemSpider ID),
#' \item \code{'pubchem_sid'} (PubChem SID),
#' \item \code{'chemnavigator_sid'} (ChemNavigator SID),
#' \item \code{'h_bond_donor_count'} (Number of Hydrogen Bond Donors),
#' \item \code{'h_bond_acceptor_count'} (Number of Hydrogen Bond Acceptors),
#' \item \code{'h_bond_center_count'} (Number of Hydrogen Bond Centers),
#' \item \code{'rule_of_5_violation_count'} (Number of Rule of 5 Violations),
#' \item \code{'rotor_count'} (Number of Freely Rotatable Bonds),
#' \item \code{'effective_rotor_count'} (Number of Effectively Rotatable Bonds),
#' \item \code{'ring_count'} (Number of Rings),
#' \item \code{'ringsys_count'} (Number of Ring Systems),
#' \item \code{'xlogp2'} (octanol-water partition coefficient),
#' \item \code{'aromatic'} (is the compound aromatic),
#' \item \code{'macrocyclic'} (is the compound macrocyclic),
#' \item \code{'heteroatom_count'} (heteroatom count),
#' \item \code{'hydrogen_atom_count'} (H atom count),
#' \item \code{'heavy_atom_count'} ( Heavy atom count),
#' \item \code{'deprotonable_group_count'} (Number of deprotonable groups),
#' \item \code{'protonable_group_count'} (Number of protonable groups).
#' }
#'
#' CIR first tries to determine the identifier type submitted and then
#' uses 'resolvers' to look up the data.
#' If no \code{resolver} is supplied, CIR tries different resolvers in
#' turn till a hit is found.
#' E.g. for names CIR tries first to look up in OPSIN and if this fails
#' the local name index of CIR.
#' However, it can be also specified which resolvers to use
#' (if you know e.g. know your identifier type)
#' Possible \code{resolvers} are:
#' \itemize{
#' \item \code{'name_by_cir'} (Lookup in name index of CIR),
#' \item \code{'name_by_opsin'} (Lookup in OPSIN),
#' \item \code{'name_by_chemspider'} (Lookup in ChemSpider,
#' \url{https://cactus.nci.nih.gov/blog/?p=1386}),
#' \item \code{'smiles'} (Lookup SMILES),
#' \item \code{'stdinchikey'}, \code{'stdinchi'} (InChI),
#' \item \code{'cas_number'} (CAS Number),
#' \item \code{'name_pattern'} (Google-like pattern search
#' (\url{https://cactus.nci.nih.gov/blog/?p=1456})
#' Note, that the pattern search can be combined with other resolvers,
#' e.g. \code{resolver = 'name_by_chemspider,name_pattern'}.
#'
#' }
#'
#' @note You can only make 1 request per second (this is a hard-coded feature).
#'
#' @references
#' \code{cir} relies on the great CIR web service created by the CADD
#' Group at NCI/NIH! \cr
#' \url{https://cactus.nci.nih.gov/chemical/structure_documentation}, \cr
#' \url{https://cactus.nci.nih.gov/blog/?cat=10}, \cr
#' \url{https://cactus.nci.nih.gov/blog/?p=1386}, \cr
#' \url{https://cactus.nci.nih.gov/blog/?p=1456}, \cr
#'
#'
#' @examples
#' \dontrun{
#' # might fail if API is not available
#' cir_query("Triclosan", "cas")
#' cir_query("3380-34-5", "cas", match = "first")
#' cir_query("3380-34-5", "cas", resolver = "cas_number")
#' cir_query("3380-34-5", "smiles")
#' cir_query("Triclosan", "mw")
#'
#' # multiple inputs
#' comp <- c("Triclosan", "Aspirin")
#' cir_query(comp, "cas", match = "first")
#'
#'}
#' @export
cir_query <- function(identifier,
representation = "smiles",
resolver = NULL,
match = c("all", "first", "ask", "na"),
verbose = getOption("verbose"),
choices = NULL,
...){
if (!ping_service("cir")) stop(webchem_message("service_down"))
if (!missing("choices")) {
stop("`choices` is deprecated. Use `match` instead.")
}
if (length(representation) > 1 | !is.character(representation)) {
stop("`representation` must be a string. See ?cir_query for options.")
}
match <- match.arg(match)
foo <- function(identifier, representation, resolver, match, verbose) {
na_tbl <- tibble(query = identifier, !!representation := NA)
if (is.na(identifier)) {
if (verbose) webchem_message("na")
return(na_tbl)
}
if (verbose) webchem_message("query", identifier, appendLF = FALSE)
id <- URLencode(identifier, reserved = TRUE)
baseurl <- "https://cactus.nci.nih.gov/chemical/structure"
qurl <- paste(baseurl, id, representation, 'xml', sep = '/')
if (!is.null(resolver)) {
qurl <- paste0(qurl, '?resolver=', resolver)
}
webchem_sleep(type = 'API')
h <- try(httr::RETRY("GET",
qurl,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(h, "try-error")) {
if (verbose) webchem_message("service_down")
return(na_tbl)
}
if (verbose) message(httr::message_for_status(h))
if (h$status_code == 200){
tt <- read_xml(content(h, as = 'raw'))
out <- xml_text(xml_find_all(tt, '//item'))
if (length(out) == 0) {
if (verbose) webchem_message("not_found")
return(na_tbl)
}
out <- matcher(out, query = identifier, match = match, verbose = verbose)
if (representation %in% c('mw', 'monoisotopic_mass', 'h_bond_donor_count',
'h_bond_acceptor_count', 'h_bond_center_count',
'rule_of_5_violation_count', 'rotor_count',
'effective_rotor_count', 'ring_count', 'ringsys_count',
'xlogp2', 'heteroatom_count', 'hydrogen_atom_count',
'heavy_atom_count', 'deprotonable_group_count',
'protonable_group_count') )
out <- as.numeric(out)
out_tbl <- tibble(query = identifier, !!representation := out)
return(out_tbl)
}
else {
return(na_tbl)
}
}
out <- lapply(identifier, foo, representation = representation,
resolver = resolver, match = match, verbose = verbose)
bind_rows(out)
}
#' Query Chemical Identifier Resolver Images
#'
#' A interface to the Chemical Identifier Resolver (CIR).
#' (\url{https://cactus.nci.nih.gov/chemical/structure_documentation}).
#'
#' @param query character; Search term. Can be any common chemical identifier
#' (e.g. CAS, INCHI(KEY), SMILES etc.)
#' @param dir character; Directory to save the image.
#' @param format character; Format of the stored image. Can be on of TODO
#' @param format character; Output format of the image. Can be one of "png",
#' "gif".
#' @param width integer; Width of the image.
#' @param height integer; Height of the image.
#' @param linewidth integer; Width of lines.
#' @param symbolfontsize integer; Fontsize of atoms in the image.
#' @param bgcolor character; E.g. transparent, white, \%23AADDEE
#' @param antialiasing logical; Should antialiasing be used?
#' @param atomcolor character; Color of the atoms in the image.
#' @param bondcolor character; Color of the atom bond lines.
#' @param csymbol character; Can be one of "special" (default - i.e. only
#' hydrogen atoms in functional groups or defining stereochemistry) or "all".
#' @param hsymbol character; Can be one of "special" (default - i.e. none are
#' shown) or "all" (all are printed).
#' @param hcolor character; Color of the hydrogen atoms.
#' @param header character; Should a header text be added to the image? Can be
#' any string.
#' @param footer character; Should a footer text be added to the image? Can be
#' any string.
#' @param verbose logical; Should a verbose output be printed on the console?
#' @param frame integer; Should a frame be plotted? Can be on of NULL (default)
#' or 1.
#' @param ... currently not used.
#'
#' @return image written to disk
#' @details
#' CIR can resolve can be of the following \code{identifier}: Chemical Names,
#' IUPAC names,
#' CAS Numbers, SMILES strings, IUPAC InChI/InChIKeys, NCI/CADD Identifiers,
#' CACTVS HASHISY, NSC number, PubChem SID, ZINC Code, ChemSpider ID,
#' ChemNavigator SID, eMolecule VID.
#'
#' For an image with transparent background use ‘transparent’ as color name and
#' switch off antialiasing (i.e. antialiasing = 0).
#'
# followed this blog post
# https://cactus.nci.nih.gov/blog/?p=136
#'
#' @note You can only make 1 request per second (this is a hard-coded feature).
#'
#' @references
#' \code{cir} relies on the great CIR web service created by the CADD
#' Group at NCI/NIH! \cr
#' \url{https://cactus.nci.nih.gov/chemical/structure_documentation}, \cr
#' \url{https://cactus.nci.nih.gov/blog/?cat=10}, \cr
#' \url{https://cactus.nci.nih.gov/blog/?p=1386}, \cr
#' \url{https://cactus.nci.nih.gov/blog/?p=1456}, \cr
#'
#'
#' @examples
#' \dontrun{
#' # might fail if API is not available
#' cir_img("CCO", dir = tempdir()) # SMILES
#'
#' # multiple query strings and different formats
#' query = c("Glyphosate", "Isoproturon", "BSYNRYMUTXBXSQ-UHFFFAOYSA-N")
#' cir_img(query, dir = tempdir(), bgcolor = "transparent", antialising = 0)
#'
#' # all parameters
#' query = "Triclosan"
#' cir_img(query,
#' dir = tempdir(),
#' format = "png",
#' width = 600,
#' height = 600,
#' linewidth = 5,
#' symbolfontsize = 30,
#' bgcolor = "red",
#' antialiasing = FALSE,
#' atomcolor = "green",
#' bondcolor = "yellow",
#' csymbol = "all",
#' hsymbol = "all",
#' hcolor = "purple",
#' header = "My funky chemical structure..",
#' footer = "..is just so awesome!",
#' frame = 1,
#' verbose = getOption("verbose"))
#'}
#' @export
#'
cir_img <- function(query,
dir,
format = c("png", "gif"),
width = 500,
height = 500,
linewidth = 2,
symbolfontsize = 16,
bgcolor = NULL,
antialiasing = TRUE,
atomcolor = NULL,
bondcolor = NULL,
csymbol = c("special", "all"),
hsymbol = c("special", "all"),
hcolor = NULL,
header = NULL,
footer = NULL,
frame = NULL,
verbose = getOption("verbose"),
...) {
if (!ping_service("cir")) stop(webchem_message("service_down"))
if (is.na(dir) || !dir.exists(dir)) {
stop('Directory does not exist.')
}
format <- match.arg(format)
csymbol <- match.arg(csymbol, c("special", "all"))
hsymbol <- match.arg(hsymbol, c("special", "all"))
foo <- function(query,
dir,
format,
width,
height,
linewidth,
symbolfontsize,
bgcolor,
antialiasing,
atomcolor,
bondcolor,
csymbol,
hsymbol,
hcolor,
header,
footer,
frame,
verbose,
...) {
# check
if (is.na(query) || query == '') {
message('NA or empty string provided. Query skipped.')
return(NULL)
}
# prolog
baseurl <- "https://cactus.nci.nih.gov/chemical/structure"
qurl <- paste(baseurl, query, "image", sep = "/")
# options
if (!is.null(format))
format <- paste0("format=", format)
if (!is.null(width))
width <- paste0("width=", width)
if (!is.null(height))
height <- paste0("height=", height)
if (!is.null(linewidth))
linewidth <- paste0("linewidth=", linewidth)
if (!is.null(symbolfontsize))
symbolfontsize <- paste0("symbolfontsize=", symbolfontsize)
if (!is.null(bgcolor))
bgcolor <- paste0("bgcolor=", bgcolor)
if (!is.null(antialiasing))
antialiasing <- paste0("antialiasing=", as.numeric(antialiasing))
if (!is.null(atomcolor))
atomcolor <- paste0("atomcolor=", atomcolor)
if (!is.null(bondcolor))
bondcolor <- paste0("bondcolor=", bondcolor)
if (!is.null(csymbol))
csymbol <- paste0("csymbol=", csymbol)
if (!is.null(hsymbol))
hsymbol <- paste0("hsymbol=", hsymbol)
if (!is.null(hcolor))
hcolor <- paste0("hcolor=", hcolor)
if (!is.null(header))
header <- paste0("header=\"", header, "\"")
if (!is.null(footer))
footer <- paste0("footer=\"", footer, "\"")
if (!is.null(frame))
frame <- paste0("frame=", frame)
opts <- c(format,
width,
height,
linewidth,
symbolfontsize,
bgcolor,
antialiasing,
atomcolor,
bondcolor,
csymbol,
hsymbol,
hcolor,
header,
footer,
frame)
opts <- paste0(opts, collapse = "&")
opts <- paste0("?", opts)
# url
qurl <- URLencode(paste0(qurl, opts))
path <- file.path(dir, paste0(query, ".", sub("format=", "", format)))
# query
webchem_sleep(type = 'API')
if (verbose) webchem_message("query", query, appendLF = FALSE)
res <- try(httr::RETRY("GET",
qurl,
quiet = TRUE,
terminate_on = 404,
httr::write_disk(path, overwrite = TRUE),
httr::user_agent(webchem_url())), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (verbose) message(httr::message_for_status(res))
if (httr::http_error(res) && file.exists(path)) {
file.remove(path)
} else {
if (verbose) message(" Image saved under: ", path)
}
}
for (i in query) {
foo(query = i,
dir = dir,
format = format,
width = width,
height = height,
linewidth = linewidth,
symbolfontsize = symbolfontsize,
bgcolor = bgcolor,
antialiasing = antialiasing,
atomcolor = atomcolor,
bondcolor = bondcolor,
csymbol = csymbol,
hsymbol = hsymbol,
hcolor = hcolor,
header = header,
footer = footer,
frame = frame,
verbose = verbose)
}
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/cir.R
|
#' Get record details from Chemical Translation Service (CTS)
#'
#' Get record details from CTS, see \url{http://cts.fiehnlab.ucdavis.edu/}
#' @import jsonlite
#' @param query character; InChIkey.
#' @param from character; currently only accepts "inchikey".
#' @param verbose logical; should a verbose output be printed on the console?
#' @param inchikey deprecated
#' @return a list of lists (for each supplied inchikey):
#' a list of 7. inchikey, inchicode, molweight, exactmass, formula, synonyms and
#' externalIds
#'
#' @references Wohlgemuth, G., P. K. Haldiya, E. Willighagen, T. Kind, and O.
#' Fiehn 2010The Chemical Translation Service -- a Web-Based Tool to Improve
#' Standardization of Metabolomic Reports. Bioinformatics 26(20): 2647–2648.
#' @export
#' @examples
#' \dontrun{
#' # might fail if API is not available
#' out <- cts_compinfo("XEFQLINVKFYRCS-UHFFFAOYSA-N")
#' # = Triclosan
#' str(out)
#' out[[1]][1:5]
#'
#' ### multiple inputs
#' inchikeys <- c("XEFQLINVKFYRCS-UHFFFAOYSA-N","BSYNRYMUTXBXSQ-UHFFFAOYSA-N" )
#' out2 <- cts_compinfo(inchikeys)
#' str(out2)
#' # a list of two
#' # extract molecular weight
#' sapply(out2, function(y) y$molweight)
#' }
cts_compinfo <- function(query, from = "inchikey",
verbose = getOption("verbose"), inchikey){
if (!ping_service("cts")) stop(webchem_message("service_down"))
names(query) <- query
if (!missing(inchikey)) {
message('"inchikey" is deprecated. Please use "query" instead.')
query <- inchikey
}
from <- match.arg(from)
foo <- function(query, verbose) {
if (is.na(query)) {
if (verbose) webchem_message("na")
return(NA)
}
if (verbose) webchem_message("query", query, appendLF = FALSE)
if (!is.inchikey(query, verbose = FALSE)) {
if (verbose) message("Input is not a valid inchikey.")
return(NA)
}
baseurl <- "http://cts.fiehnlab.ucdavis.edu/service/compound"
qurl <- paste0(baseurl, '/', query)
webchem_sleep(type = 'API')
out <- try(httr::RETRY("GET",
qurl,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(out, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (verbose) message(httr::message_for_status(out))
if (out$status_code == 200) {
out <- jsonlite::fromJSON(rawToChar(out$content))
return(out)
}
else {
return(NA)
}
}
out <- lapply(query, foo, verbose = verbose)
class(out) <- c('cts_compinfo','list')
return(out)
}
#' Convert Ids using Chemical Translation Service (CTS)
#'
#' Convert Ids using Chemical Translation Service (CTS), see
#' \url{http://cts.fiehnlab.ucdavis.edu/}
#' @import jsonlite
#' @importFrom utils URLencode
#' @param query character; query ID.
#' @param from character; type of query ID, e.g. \code{'Chemical Name'} ,
#' \code{'InChIKey'}, \code{'PubChem CID'}, \code{'ChemSpider'}, \code{'CAS'}.
#' @param to character; type to convert to.
#' @param match character; How should multiple hits be handled? \code{"all"}
#' returns all matches, \code{"first"} returns only the first result,
#' \code{"ask"} enters an interactive mode and the user is asked for input,
#' \code{"na"} returns \code{NA} if multiple hits are found.
#' @param choices deprecated. Use the \code{match} argument instead.
#' @param verbose logical; should a verbose output be printed on the console?
#' @param ... currently not used.
#' @return a list of character vectors or if \code{choices} is used, then a
#' single named vector.
#' @details See also \url{http://cts.fiehnlab.ucdavis.edu/}
#' for possible values of from and to.
#' @seealso \code{\link{cts_from}} for possible values in the 'from' argument
#' and \code{\link{cts_to}} for possible values in the 'to' argument.
#'
#' @references Wohlgemuth, G., P. K. Haldiya, E. Willighagen, T. Kind, and O.
#' Fiehn 2010The Chemical Translation Service -- a Web-Based Tool to Improve
#' Standardization of Metabolomic Reports. Bioinformatics 26(20): 2647–2648.
#' @export
#' @examples
#' \dontrun{
#' # might fail if API is not available
#' cts_convert("XEFQLINVKFYRCS-UHFFFAOYSA-N", "inchikey", "Chemical Name")
#'
#' ### multiple inputs
#' keys <- c("XEFQLINVKFYRCS-UHFFFAOYSA-N", "VLKZOEOYAKHREP-UHFFFAOYSA-N")
#' cts_convert(keys, "inchikey", "cas")
#' }
cts_convert <- function(query,
from,
to,
match = c("all", "first", "ask", "na"),
verbose = getOption("verbose"),
choices = NULL,
...){
if (!ping_service("cts")) stop(webchem_message("service_down"))
if(!missing("choices")) {
if (is.null(choices)) {
message('"choices" is deprecated. Using match = "all" instead.')
match <- "all"
} else if(choices == 1) {
message('"choices" is deprecated. Using match= "first" instead.')
match <- "first"
} else if ((is.numeric(choices) & choices > 1) | choices == "all") {
message('"choices" is deprecated. Using match = "ask" instead.')
match <- "ask"
} else {
message('"choices" is deprecated. Using match = "all" instead.')
match <- "all"
}
}
if (length(from) > 1 | length(to) > 1) {
stop('Cannot handle multiple input or output types. Please provide only one
argument for `from` and `to`.')
}
query <- as.character(query)
names(query) <- query
from <- match.arg(tolower(from), c(cts_from(), "name"))
to <- match.arg(tolower(to), c(cts_to(), "name"))
match <- match.arg(match)
if (from == "name") {
from <- "chemical name"
}
if (to == "name") {
to <- "chemical name"
}
foo <- function(query, from, to, first, verbose){
if (from == "cas"){
query <- as.cas(query, verbose = verbose)
}
if (is.na(query)) {
if (verbose) webchem_message("na")
return(NA)
}
if (verbose) webchem_message("query", query, appendLF = FALSE)
query <- URLencode(query, reserved = TRUE)
from <- URLencode(from, reserved = TRUE)
to <- URLencode(to, reserved = TRUE)
baseurl <- "http://cts.fiehnlab.ucdavis.edu/service/convert"
qurl <- paste0(baseurl, '/', from, '/', to, '/', query)
webchem_sleep(type = 'API')
res <- try(httr::RETRY("GET",
qurl,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (verbose) message(httr::message_for_status(res))
if (res$status_code == 200) {
out <- jsonlite::fromJSON(rawToChar(res$content))
if (length(out$result[[1]]) == 0) {
if (verbose) webchem_message("not_found")
return(NA)
}
out <- out$result[[1]]
out <- matcher(out, match = match, query = query, from = from,
verbose = verbose)
return(out)
}
else {
return(NA)
}
}
out <- lapply(query, foo, from = from, to = to, first = first,
verbose = verbose)
return(out)
}
#' Return a list of all possible ids
#'
#' Return a list of all possible ids that can be used in the 'from' argument
#' @import jsonlite
#' @param verbose logical; should a verbose output be printed on the console?
#' @return a character vector.
#' @details See also \url{http://cts.fiehnlab.ucdavis.edu/services}
#'
#' @seealso \code{\link{cts_convert}}
#'
#' @references Wohlgemuth, G., P. K. Haldiya, E. Willighagen, T. Kind, and O.
#' Fiehn 2010The Chemical Translation Service -- a Web-Based Tool to Improve
#' Standardization of Metabolomic Reports. Bioinformatics 26(20): 2647–2648.
#' @export
#' @examples
#' \dontrun{
#' cts_from()
#' }
cts_from <- function(verbose = getOption("verbose")){
if (!ping_service("cts")) stop(webchem_message("service_down"))
qurl <- "http://cts.fiehnlab.ucdavis.edu/service/conversion/fromValues"
res <- try(httr::RETRY("GET",
qurl,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
out <- tolower(jsonlite::fromJSON(rawToChar(res$content)))
return(out)
}
#' Return a list of all possible ids
#'
#' Return a list of all possible ids that can be used in the 'to' argument
#' @import jsonlite
#' @param verbose logical; should a verbose output be printed on the console?
#' @return a character vector.
#' @details See also \url{http://cts.fiehnlab.ucdavis.edu/services}
#'
#' @seealso \code{\link{cts_convert}}
#'
#' @references Wohlgemuth, G., P. K. Haldiya, E. Willighagen, T. Kind, and O.
#' Fiehn 2010The Chemical Translation Service -- a Web-Based Tool to Improve
#' Standardization of Metabolomic Reports. Bioinformatics 26(20): 2647–2648.
#' @export
#' @examples
#' \dontrun{
#' cts_from()
#' }
cts_to <- function(verbose = getOption("verbose")){
if (!ping_service("cts")) stop(webchem_message("service_down"))
qurl <- "http://cts.fiehnlab.ucdavis.edu/service/conversion/toValues"
res <- try(httr::RETRY("GET",
qurl,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
out <- tolower(jsonlite::fromJSON(rawToChar(res$content)))
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/cts.R
|
#' Get ETOX ID
#'
#' Query ETOX: Information System Ecotoxicology and Environmental Quality
#' Targets \url{https://webetox.uba.de/webETOX/index.do} for their substance ID
#'
#' @import xml2 httr
#' @importFrom dplyr bind_rows
#' @importFrom tibble tibble
#' @param query character; The searchterm
#' @param from character; Type of input, can be one of "name" (chemical name),
#' "cas" (CAS Number), "ec" (European Community number for regulatory purposes),
#' "gsbl" (Identifier used by \url{https://www.chemikalieninfo.de/}) and "rtecs"
#' (Identifier used by the Registry of Toxic Effects of Chemical Substances
#' database).
#' @param match character; How should multiple hits be handeled? "all" returns
#' all matched IDs, "first" only the first match, "best" the best matching (by
#' name) ID, "ask" is a interactive mode and the user is asked for input, "na"
#' returns \code{NA} if multiple hits are found.
#' @param verbose logical; print message during processing to console?
#' @return a tibble with 3 columns: the query, the match, and the etoxID
#' @note Before using this function, please read the disclaimer
#' \url{https://webetox.uba.de/webETOX/disclaimer.do}.
#' @seealso \code{\link{etox_basic}} for basic information,
#' \code{\link{etox_targets}} for quality targets and
#' \code{\link{etox_tests}} for test results.
#' @references Eduard Szöcs, Tamás Stirling, Eric R. Scott, Andreas Scharmüller,
#' Ralf B. Schäfer (2020). webchem: An R Package to Retrieve Chemical
#' Information from the Web. Journal of Statistical Software, 93(13).
#' \doi{10.18637/jss.v093.i13}.
#' @export
#' @examples
#' \dontrun{
#' # might fail if API is not available
#' get_etoxid("Triclosan")
#' # multiple inputs
#' comps <- c("Triclosan", "Glyphosate")
#' get_etoxid(comps)
#' get_etoxid(comps, match = "all")
#' get_etoxid("34123-59-6", from = "cas") # Isoproturon
#' get_etoxid("133483", from = "gsbl") # 3-Butin-1-ol
#' get_etoxid("203-157-5", from = "ec") # Paracetamol
#' }
get_etoxid <- function(query,
from = c("name", "cas", "ec", "gsbl", "rtecs"),
match = c("all", "best", "first", "ask", "na"),
verbose = getOption("verbose")) {
if (!ping_service("etox")) stop(webchem_message("service_down"))
names(query) <- query
clean_char <- function(x) {
# rm \n \t
x <- gsub("\n | \t", "", x)
# rm leading / trailling whitespace
x <- gsub("^\\s+|\\s+$", "", x)
# replace multiple spaces by one,
x <- gsub("(?<=[\\s])\\s*|^\\s+$", "", x, perl = TRUE)
return(x)
}
# checks
from <- match.arg(from)
match <- match.arg(match)
if (from != "name" & match == "best") {
warning("match = 'best' only makes sense when querying chemical names. ")
}
foo <- function(query, from, match, verbose) {
if (from == "cas"){
query <- as.cas(query, verbose = verbose)
}
if (is.na(query)) {
if (verbose) webchem_message("na")
return(tibble("query" = query, "match" = NA, "etoxid" = NA))
}
if (verbose) webchem_message("query", query, appendLF = FALSE)
baseurl <- "https://webetox.uba.de/webETOX/public/search/stoff.do"
if (from == 'name') {
body <- list("stoffname.selection[0].name" = query,
"stoffname.selection[0].type" = "",
event = "Search")
} else {
from_look <- c(cas = 69,
ec = 70,
rtecs = 72,
gsbl = 73)
type <- from_look[ names(from_look) == from ]
body <- list('stoffnummer.selection[0].name' = query,
'stoffnummer.selection[0].type' = type,
event = "Search")
}
webchem_sleep(type = 'scrape')
h <- try(httr::RETRY("POST",
url = baseurl,
httr::user_agent(webchem_url()),
handle = handle(''),
body = body,
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(h, "try-error")) {
if (verbose) webchem_message("service_down")
return(tibble::tibble("query" = query, "match" = NA, "etoxid" = NA))
}
if (verbose) message(httr::message_for_status(h))
if (h$status_code == 200) {
tt <- read_html(h)
subs <- clean_char(xml_text(xml_find_all(
tt, "//*/table[@class = 'listForm resultList']//a")))[-1]
if (length(subs) == 0) {
if (verbose) webchem_message("not_found")
hit <- tibble("query" = query,
"match" = NA,
"etoxid" = NA)
return(hit)
} else {
links <- xml_attr(xml_find_all(
tt, "//*/table[@class = 'listForm resultList']//a"), "href")[-1]
subs_names <- gsub(" \\(.*\\)", "", subs)
id <- gsub("^.*\\?id=(.*)", "\\1", links)
out <- matcher(id, query = query, result = subs_names, from = from, match = match)
hit <- tibble("query" = query,
"match" = names(out),
"etoxid" = out)
return(hit)
}
}
else {
return(tibble::tibble(query = NA, match = NA, etoxid = NA))
}
}
out <- lapply(query, foo, from = from, match = match, verbose = verbose)
out <- dplyr::bind_rows(out, .id = "query")
return(out)
}
#' Get basic information from a ETOX ID
#'
#' Query ETOX: Information System Ecotoxicology and Environmental Quality
#' Targets \url{https://webetox.uba.de/webETOX/index.do} for basic information
#'
#' @import xml2
#' @importFrom rvest html_table
#' @param id character; ETOX ID
#' @param verbose logical; print message during processing to console?
#'
#' @return a list with lists of four entries: cas (the CAS numbers), ec (the EC
#' number), gsbl (the gsbl number), a data.frame synonys with synonyms and the
#' source url.
#'
#' @note Before using this function, please read the disclaimer
#' \url{https://webetox.uba.de/webETOX/disclaimer.do}.
#'
#' @seealso \code{\link{get_etoxid}} to retrieve ETOX IDs,
#' \code{\link{etox_basic}} for basic information, \code{\link{etox_targets}}
#' for quality targets and \code{\link{etox_tests}} for test results
#' @references Eduard Szöcs, Tamás Stirling, Eric R. Scott, Andreas Scharmüller,
#' Ralf B. Schäfer (2020). webchem: An R Package to Retrieve Chemical
#' Information from the Web. Journal of Statistical Software, 93(13).
#' \doi{10.18637/jss.v093.i13}.
#' @export
#' @examples
#' \dontrun{
#' id <- get_etoxid('Triclosan', match = 'best')
#' etox_basic(id$etoxid)
#'
#' # Retrieve data for multiple inputs
#' ids <- c("20179", "9051")
#' out <- etox_basic(ids)
#' out
#'
#' # extract cas numbers
#' sapply(out, function(y) y$cas)
#' }
etox_basic <- function(id, verbose = getOption("verbose")) {
if (!ping_service("etox")) stop(webchem_message("service_down"))
names(id) <- id
foo <- function(id, verbose) {
if (is.na(id)) {
if (verbose) webchem_message("na")
return(NA)
}
baseurl <- 'https://webetox.uba.de/webETOX/public/basics/stoff.do?language=en&id='
qurl <- paste0(baseurl, id)
if(verbose) webchem_message("query", id, appendLF = FALSE)
webchem_sleep(type = 'scrape')
res <- try(httr::RETRY("GET",
qurl,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (verbose) message(httr::message_for_status(res))
if (res$status_code == 200) {
tt <- try(read_html(res), silent = TRUE)
if (inherits(tt, 'try-error')) {
if (verbose) webchem_message("not_found")
return(NA)
}
tabs <- try(suppressWarnings(html_table(tt, fill = TRUE)), silent = TRUE)
if (inherits(tabs, 'try-error')) {
webchem_message("not_found")
return(NA)
}
binf <- tabs[[length(tabs)]]
cas <- binf[, 1][binf[, 2] == 'CAS']
ec <- binf[, 1][grepl('^EC$|EINEC', binf[, 2])]
gsbl <- binf[, 1][binf[, 2] == 'GSBL']
syns <- tabs[[2]][c(1, 3, 4)]
colnames(syns) <- as.character(syns[1, ])
syns <- syns[-1, ]
syns <- syns[syns[[2]] == 'SYNONYM' & !is.na(syns[[2]]), ] #syns[[2]] or syns$ETOX_NAME?
syns <- syns[ , -2]
names(syns) <- c('name', 'language')
out <- list(cas = cas, ec = ec, gsbl = gsbl, synonyms = syns,
source_url = qurl)
return(out)
# CODE FOR A POSSIBLE FUTURE RELEASE
# binf <- tabs[[length(tabs)]]
# cas <- binf[, 1][binf[, 2] == 'CAS']
# ec <- binf[, 1][grepl('^EC$|EINEC', binf[, 2])]
# gsbl <- binf[, 1][binf[, 2] == 'GSBL']
#
# syns <- tabs[[2]][c(1, 3, 4)]
# names(syns) <- tolower(gsub('\\s+', '_', names(syns)))
# group <- tolower(syns[ syns$substance_name_typ == 'GROUP_USE' &
# syns$language == 'English', ]$notation)
# syn <- syns[ syns$substance_name_typ == 'SYNONYM', ]
# syn <- syn[ ,-2]
# names(syn) <- c('name', 'language')
# # return list of data.frames
# l <- list(cas = cas,
# ec = ec,
# gsbl = gsbl,
# source_url = qurl)
# data <- as.data.frame(t(do.call(rbind, l)),
# stringsAsFactors = FALSE)
# chem_group <- as.data.frame(t(group), stringsAsFactors = FALSE)
# names(chem_group) <- chem_group[1, ]
# chem_group[1, ] <- TRUE
# out <- list(data = data,
# chemical_group = chem_group,
# synonyms = syn)
### END
}
else {
return(NA)
}
}
out <- lapply(id, foo, verbose = verbose)
class(out) <- c('etox_basic', 'list')
return(out)
}
#' Get Quality Targets from a ETOX ID
#'
#' Query ETOX: Information System Ecotoxicology and Environmental Quality
#' Targets \url{https://webetox.uba.de/webETOX/index.do} for quality targets
#'
#' @import xml2
#' @importFrom utils read.table
#' @param id character; ETOX ID
#' @param verbose logical; print message during processing to console?
#'
#' @return A list of lists of two: \code{res} a data.frame with quality targets
#' from the ETOX database, and source_url.
#'
#' @note Before using this function, please read the disclaimer
#' \url{https://webetox.uba.de/webETOX/disclaimer.do}.
#' @seealso \code{\link{get_etoxid}} to retrieve ETOX IDs,
#' \code{\link{etox_basic}} for basic information, \code{\link{etox_targets}}
#' for quality targets and \code{\link{etox_tests}} for test results
#' @references Eduard Szöcs, Tamás Stirling, Eric R. Scott, Andreas Scharmüller,
#' Ralf B. Schäfer (2020). webchem: An R Package to Retrieve Chemical
#' Information from the Web. Journal of Statistical Software, 93(13).
#' \doi{10.18637/jss.v093.i13}.
#' @export
#' @examples
#' \dontrun{
#' id <- get_etoxid('Triclosan', match = 'best')
#' out <- etox_targets(id$etoxid)
#' out[ , c('Substance', 'CAS_NO', 'Country_or_Region', 'Designation',
#' 'Value_Target_LR', 'Unit')]
#' etox_targets( c("20179", "9051"))
#'
#' }
etox_targets <- function(id, verbose = getOption("verbose")) {
if (!ping_service("etox")) stop(webchem_message("service_down"))
names(id) <- id
foo <- function(id, verbose) {
if (is.na(id)) {
if (verbose) webchem_message("na")
return(NA)
}
baseurl <- 'https://webetox.uba.de/webETOX/public/basics/stoff.do?language=en&id='
qurl <- paste0(baseurl, id)
if(verbose) webchem_message("query", id, appendLF = FALSE)
webchem_sleep(type = 'scrape')
res <- try(httr::RETRY("GET",
qurl,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (verbose) message(httr::message_for_status(res))
if(res$status_code == 200){
tt <- try(read_html(res), silent = TRUE)
if (inherits(tt, 'try-error')) {
if (verbose) webchem_message("not_found")
return(NA)
}
link2 <-
xml_attrs(xml_find_all(tt, "//a[contains(.,'Quali') and contains(@href,'stoff')]"),
'href')
id2 <- gsub('.*=(\\d+)', '\\1', link2)
tt2 <- read_html(paste0('https://webetox.uba.de', link2, '&language=en'))
mssg <-
xml_text(
xml_find_all(
tt2,
"//div[contains(@class, 'messages')]/ul/li/span[contains(@class, 'message')]"
),
trim = TRUE
)
if (length(mssg) > 0) {
if (grepl('no result', mssg)) {
if (verbose) webchem_message("not_found")
return(NA)
} else {
if (verbose) message(paste0(" Problem found. Message: ", mssg))
}
}
csvlink <- xml_attr(xml_find_all(tt2, "//a[contains(.,'Csv')]"), 'href')
res <- read.table(paste0('https://webetox.uba.de', csvlink),
header = TRUE, sep = ',', dec = ',', fileEncoding = 'latin1',
stringsAsFactors = FALSE)
res$Value_Target_LR <- as.numeric(res$Value_Target_LR)
source_url <- paste0('https://webetox.uba.de', link2, '&language=en')
source_url <- gsub('^(.*ziel\\.do)(.*)(\\?stoff=.*)$', '\\1\\3', source_url)
out <- list(res = res, source_url = source_url)
return(out)
}
else {
return(NA)
}
}
out <- lapply(id, foo, verbose = verbose)
return(out)
}
#' Get Tests from a ETOX ID
#'
#' Query ETOX: Information System Ecotoxicology and Environmental Quality Targets
#' \url{https://webetox.uba.de/webETOX/index.do} for tests
#'
#' @import xml2
#' @importFrom utils read.table
#' @param id character; ETOX ID
#' @param verbose logical; print message during processing to console?
#'
#' @return A list of lists of two: A data.frame with test results from the ETOX database and the source_url.
#' @note Before using this function, please read the disclaimer
#' \url{https://webetox.uba.de/webETOX/disclaimer.do}.
#'
#' @seealso \code{\link{get_etoxid}} to retrieve ETOX IDs, \code{\link{etox_basic}} for basic information,
#' \code{\link{etox_targets}} for quality targets and \code{\link{etox_tests}} for test results
#'
#' @export
#' @examples
#' \dontrun{
#' id <- get_etoxid('Triclosan', match = 'best')
#' out <- etox_tests(id$etoxid)
#' out[ , c('Organism', 'Effect', 'Duration', 'Time_Unit',
#' 'Endpoint', 'Value', 'Unit')]
#' etox_tests( c("20179", "9051"))
#' }
etox_tests <- function(id, verbose = getOption("verbose")) {
if (!ping_service("etox")) stop(webchem_message("service_down"))
names(id) <- id
foo <- function(id, verbose){
if (is.na(id)) {
if (verbose) webchem_message("na")
return(NA)
}
baseurl <- 'https://webetox.uba.de/webETOX/public/basics/stoff.do?id='
qurl <- paste0(baseurl, id)
if(verbose) webchem_message("query", id, appendLF = FALSE)
webchem_sleep(type = 'scrape')
res <- try(httr::RETRY("GET",
qurl,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (verbose) message(httr::message_for_status(res))
if (res$status_code == 200) {
tt <- try(read_html(res), silent = TRUE)
if (inherits(tt, 'try-error')) {
if (verbose) webchem_message("not_found")
return(NA)
}
link2 <- xml_attrs(xml_find_all(tt, "//a[contains(.,'Tests') and contains(@href,'stoff')]"), 'href')
id2 <- gsub('.*=(\\d+)', '\\1', link2)
tt2 <- read_html(paste0('https://webetox.uba.de', link2, '&language=en'))
mssg <- xml_text(xml_find_all(tt2, "//div[contains(@class, 'messages')]/ul/li/span[contains(@class, 'message')]"), trim = TRUE)
if (length(mssg) > 0) {
if (grepl('no result', mssg)) {
if (verbose) message(" No targets found. Returning NA.")
return(NA)
} else {
if (verbose) message(paste0(" Problem found. Message: ", mssg),
appendLF = FALSE)
}
}
csvlink <- xml_attr(xml_find_all(tt2, "//a[contains(.,'Csv')]"), 'href')
# csvlink <- gsub('^(.*\\.do).*$', '\\1', csvlink)
res2 <- read.table(paste0('https://webetox.uba.de', csvlink),
header = TRUE, sep = ',', dec = ',',
fileEncoding = 'latin1',
stringsAsFactors = FALSE)
res2$Value <- as.numeric(res2$Value)
source_url <- paste0('https://webetox.uba.de', link2, '&language=en')
source_url <- gsub('^(.*test\\.do)(.*)(\\?stoff=.*)$', '\\1\\3', source_url)
out <- list(res = res2, source_url = source_url)
return(out)
}
else {
return(NA)
}
}
out <- lapply(id, foo, verbose = verbose)
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/etox.R
|
#' Extract parts from webchem objects
#' @name extractors
#' @rdname extractors
#' @param x object
#' @param ... currently not used.
#' @return a vector.
#' @references Eduard Szöcs, Tamás Stirling, Eric R. Scott, Andreas Scharmüller,
#' Ralf B. Schäfer (2020). webchem: An R Package to Retrieve Chemical
#' Information from the Web. Journal of Statistical Software, 93(13).
#' \doi{10.18637/jss.v093.i13}.
#' @export
cas <- function(x, ...){
UseMethod("cas")
}
# CAS ---------------------------------------------------------------------
#' @export
cas.default <- function(x, ...) {
stop(paste("No cas method for class", class(x)))
}
#' @export
cas.chebi_comp_entity <- function(x, ...) {
sapply(x, function(y) {
if (length(y) == 1 && is.na(y)) return(NA)
unique(y$regnumbers$data[y$regnumbers$type == "CAS Registry Number"])
})
}
#' @export
cas.opsin_query <- function(x, ...) {
stop("CAS is not returned by this datasource!")
}
#' @export
cas.bcpc_query <- function(x, ...) {
sapply(x, function(y) y$cas)
}
#' @export
cas.wd_ident <- function(x, ...) {
x$cas
}
#' @export
cas.cts_compinfo <- function(x, ...) {
stop("CAS is not returned by this data source")
}
#' @export
cas.etox_basic <- function(x, ...) {
sapply(x, function(y) {
if (length(y) == 1 && is.na(y))
return(NA)
unique(y$cas)
})
}
# InChIKey ----------------------------------------------------------------
#' @rdname extractors
#' @export
inchikey <- function(x, ...){
UseMethod("inchikey")
}
#' @export
inchikey.default <- function(x, ...) {
stop(paste(" No inchikey method for class", class(x)))
}
#' @export
inchikey.bcpc_query <- function(x, ...) {
sapply(x, function(y) {
if (length(y) == 1 && is.na(y)) return(NA)
y$inchikey
})
}
#' @export
inchikey.chebi_comp_entity <- function(x, ...) {
sapply(x, function (y) {
if (length(y) == 1 && is.na(y)) return(NA)
y$properties$inchikey
})
}
#' @export
inchikey.etox_basic <- function(x, ...) {
stop("InChIkey is not returned by this datasource!")
}
#' @export
inchikey.opsin_query <- function(x, ...) {
x$stdinchikey
}
#' @export
inchikey.pc_prop <- function(x, ...) {
if (!"InChIKey" %in% names(x)) {
stop("InChIKey not queried!")
}
x$InChIKey
}
#' @export
inchikey.wd_ident <- function(x, ...) {
x$inchikey
}
#' @export
inchikey.cts_compinfo <- function(x, ...) {
sapply(x, function(x) x$inchikey)
}
# SMILES ------------------------------------------------------------------
#' @rdname extractors
#' @export
smiles <- function(x, ...){
UseMethod("smiles")
}
#' @export
smiles.default <- function(x, ...) {
stop(paste("no smiles method for class", class(x)))
}
#' @export
smiles.chebi_comp_entity <- function(x, ...) {
sapply(x, function(y) {
if (length(y) == 1 && is.na(y)) return(NA)
y$properties$smiles
})
}
#' @export
smiles.cts_compinfo <- function(x, ...) {
stop("SMILES is not returned by this datasource!")
}
#' @export
smiles.etox_basic <- function(x, ...) {
stop("InChIkey is not returned by this datasource!")
}
#' @export
smiles.opsin_query <- function(x, ...) {
x$smiles
}
#' @export
smiles.bcpc_query <- function(x, ...) {
stop("SMILES is not returned by this datasource!")
}
#' @export
smiles.pc_prop <- function(x, ...) {
if (!"CanonicalSMILES" %in% names(x)) {
stop("CanonicalSMILES not queried!")
}
x$CanonicalSMILES
}
#' @export
smiles.wd_ident <- function(x, ...) {
x$smiles
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/extractors.R
|
#' Retrieve flavor percepts from www.flavornet.org
#'
#' Retrieve flavor percepts from \url{http://www.flavornet.org}. Flavornet is a database of 738 compounds with odors
#' perceptible to humans detected using gas chromatography olfactometry (GCO).
#'
#' @import xml2
#' @param query character; CAS number to search by. See \code{\link{is.cas}} for correct formatting
#' @param from character; currently only CAS numbers are accepted.
#' @param verbose logical; should a verbose output be printed on the console?
#' @param CAS deprecated
#' @param ... currently unused
#'
#' @return A named character vector containing flavor percepts or NA's in the case of CAS numbers that are not found
#'
#'
#' @examples
#' \dontrun{
#' # might fail if website is not available
#' fn_percept("123-32-0")
#'
#' CASs <- c("75-07-0", "64-17-5", "109-66-0", "78-94-4", "78-93-3")
#' fn_percept(CASs)
#' }
#' @export
fn_percept <- function(query, from = "cas", verbose = getOption("verbose"),
CAS, ...)
{
if (!ping_service("fn")) stop(webchem_message("service_down"))
if (!missing(CAS)) {
message('"CAS" is now deprecated. Please use "query" instead. ')
query <- CAS
}
match.arg(from)
names(query) <- query
foo <- function (query, verbose){
if (from == "cas"){
query <- as.cas(query, verbose = verbose)
}
if (is.na(query)) {
if (verbose) webchem_message("na")
return(NA)
}
qurl <- paste0("http://www.flavornet.org/info/",query,".html")
if (verbose) webchem_message("query", query, appendLF = FALSE)
webchem_sleep(type = 'scrape')
res <- try(httr::RETRY("GET",
qurl,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (verbose) message(httr::message_for_status(res))
if (res$status_code == 200){
h <- read_html(res)
doc.text = xml_text(xml_find_all(h, "/html/body/p[3]"))
pattern = "Percepts: "
percept <- gsub(pattern, "", doc.text)
return(percept)
}
else {
return(NA)
}
}
percepts <- sapply(query, foo, verbose = verbose)
return(percepts)
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/flavornet.R
|
#' Auto-translate identifiers and search databases
#'
#' Supply a query of any type (e.g. SMILES, CAS, name, InChI, etc.) along with
#' any webchem function that has \code{query} and \code{from} arguments. If the
#' function doesn't accept the type of query you've supplied, this will try to
#' automatically translate it using CTS and run the query.
#'
#' @param query character; the search term
#' @param from character; the format or type of query. Commonly accepted values
#' are "name", "cas", "inchi", and "inchikey"
#' @param .f character; the (quoted) name of a webchem function
#' @param .verbose logical; print a message when translating query?
#' @param ... other arguments passed to the function specified with \code{.f}
#' @note During the translation step, only the first hit from CTS is used.
#' Therefore, using this function to translate on the fly is not foolproof and
#' care should be taken to verify the results.
#' @return returns results from \code{.f}
#' @importFrom rlang as_function fn_fmls
#'
#' @examples
#' \dontrun{
#' with_cts("XDDAORKBJWWYJS-UHFFFAOYSA-N", from = "inchikey", .f = "get_etoxid")
#' }
with_cts <- function(query, from, .f, .verbose = getOption("verbose"), ...) {
f <- rlang::as_function(.f)
pos_froms <- eval(rlang::fn_fmls(f)$from)
if (!from %in% pos_froms) {
pos_froms <- pos_froms[pos_froms != "name"] #cts name conversion broken
new_from <- pos_froms[which(pos_froms %in% cts_to())[1]]
if (.verbose) {
message(
paste0(.f,
" doesn't accept ",
from,
".\n",
"Attempting to translate to ",
new_from,
" with CTS. ")
)
}
new_query <- cts_convert(query, from = from, to = new_from, match = "first")
#would like to try a again if cts fails the first time (as it often does).
from <- new_from
query <- new_query
}
f(query = query, from = from, ...)
}
#' Check data source coverage of compounds
#'
#' Checks if entries are found in (most) data sources included in webchem
#'
#' @param query character; the search term
#' @param from character; the format or type of query. Commonly accepted values
#' are "name", "cas", "inchi", and "inchikey"
#' @param sources character; which data sources to check. Data sources are
#' identified by the prefix associated with webchem functions that query those
#' databases. If not specified, all data sources listed will be checked.
#' @param plot logical; plot a graphical representation of results.
#'
#' @return a tibble of logical values where \code{TRUE} indicates that a data
#' source contains a record for the query
#' @export
#' @import dplyr
#' @importFrom stringr str_trunc
#' @examples
#' \dontrun{
#' find_db("hexane", from = "name")
#' }
find_db <- function(query, from,
sources = c("etox", "pc", "chebi", "cs",
"bcpc", "fn", "srs"),
plot = FALSE) {
sources <- match.arg(sources, several.ok = TRUE)
sources <- sapply(sources, switch,
"etox" = "get_etoxid",
"pc" = "get_cid",
"chebi" = "get_chebiid",
"cs" = "get_csid",
"bcpc" = "bcpc_query",
"fn" = "fn_percept",
"srs" = "srs_query")
foo <- function(.f, query, from) {
# if a function errors (e.g. API is down) then return NA
x <-
try(with_cts(
query = query,
from = from,
.f = .f,
match = "first"
))
if (inherits(x, "try-error")) {
return(NA)
}
if (inherits(x, "data.frame")) {
x <- x[[ncol(x)]]
}
return(!is.na(x))
}
out <- lapply(sources, foo, query = query, from = from)
names(out) <- names(sources)
out <- dplyr::bind_cols(query = query, out)
if (plot) {
if (!requireNamespace("plot.matrix", quietly = TRUE)) {
warning("The plot.matrix package is required for plotting results")
} else {
out <- filter(out, !is.na(query))
colorder <- select(out, -query) %>%
colSums(., na.rm = TRUE) %>%
sort(decreasing = TRUE) %>%
names()
pmat <- out %>%
select(all_of(colorder)) %>%
as.matrix()
opar <- graphics::par(no.readonly = TRUE)
query_trunc <- stringr::str_trunc(query, 25)
leftmargin <- 0.5 * max(nchar(query_trunc))
graphics::par(mar = c(5.1, leftmargin, 4.1, 4.1))
plot(
pmat,
col = c("#C7010B", "#3BC03B"),
breaks = c(FALSE, TRUE),
na.col = "grey70",
axis.col = list(side = 3),
axis.row = list(las = 2, labels = query_trunc),
xlab = NA,
ylab = NA,
main = NA
)
graphics::par(opar)
}
}
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/integration.R
|
#' Retrieve retention indices from NIST
#' @description This function scrapes NIST for literature retention indices
#' given a query or vector of queries as input. The query can be a cas
#' number, IUPAC name, or International Chemical Identifier (\code{inchikey}),
#' according to the value of the \code{from} argument. Retention indices are
#' stored in tables by \code{type}, \code{polarity} and temperature program
#' (\code{temp_prog}). The function can take multiple arguments for these
#' parameters and will return any retention times matching the specified
#' criteria in a single table.
#'
#' If a non-cas query is provided, the function will try to resolve the query
#' by searching the NIST WebBook for a corresponding CAS number. If
#' \code{from == "name"}, phonetic spellings of Greek stereo-descriptors
#' (e.g. "alpha", "beta", "gamma") will be automatically
#' converted to the corresponding letters to match the form used by NIST. If
#' a CAS number is found, it will be returned in a \code{tibble} with the
#' corresponding information from the NIST retention index database.
#'
#' @param query character; the search term
#' @param from character; type of search term. can be one of \code{"name"},
#' \code{"inchi"}, \code{"inchikey"}, or \code{"cas"}. Using an identifier is
#' preferred to \code{"name"} since \code{NA} is returned in the event of
#' multiple matches to a query. Using an identifier other than a CAS number
#' will cause this function to run slower as CAS numbers are used as internal
#' identifiers by NIST.
#' @param type Retention index type: \code{"kovats"}, \code{"linear"},
#' \code{"alkane"}, and/or \code{"lee"}. See details for more.
#' @param polarity Column polarity: \code{"polar"} and/or \code{"non-polar"}
#' to get RIs calculated for polar or non-polar columns.
#' @param temp_prog Temperature program: \code{"isothermal"},
#' \code{"ramp"}, and/or \code{"custom"}.
#' @param cas deprecated. Use \code{query} instead.
#' @param verbose logical; should a verbose output be printed on the console?
#' @details The types of retention indices included in NIST include Kovats
#' (\code{"kovats"}), Van den Dool and Kratz (\code{"linear"}), normal alkane
#' (\code{"alkane"}), and Lee (\code{"lee"}). Details about how these are
#' calculated are available on the NIST website:
#' \url{https://webbook.nist.gov/chemistry/gc-ri/}
#' @importFrom purrr map
#' @importFrom purrr map_dfr
#' @import dplyr
#'
#' @return returns a tibble of literature RIs with the following columns:
#' \itemize{
#' \item{\code{query} is the query provided to the NIST server}
#' \item{\code{cas} is the CAS number or unique record identified used by NIST}
#' \item{\code{RI} is retention index}
#' \item{\code{type} is the type of RI (e.g. "kovats", "linear", "alkane", or "lee")}
#' \item{\code{polarity} is the polarity of the column (either "polar" or "non-polar")}
#' \item{\code{temp_prog} is the type of temperature program (e.g. "isothermal", "ramp", or "custom")}
#' \item{\code{column} is the column type, e.g. "capillary"}
#' \item{\code{phase} is the stationary phase (column phase)}
#' \item{\code{length} is column length in meters}
#' \item{\code{gas} is the carrier gas used}
#' \item{\code{substrate}}
#' \item{\code{diameter} is the column diameter in mm}
#' \item{\code{thickness} is the phase thickness in µm}
#' \item{\code{program}. various columns depending on the value of
#' \code{temp_prog}}
#' \item{\code{reference} is where this retention index was published}
#' \item{\code{comment}. I believe this denotes the database these data
#' were aggregated from}
#'}
#'
#' @references NIST Mass Spectrometry Data Center, William E. Wallace, director,
#' "Retention Indices" in NIST Chemistry WebBook, NIST Standard Reference
#' Database Number 69, Eds. P.J. Linstrom and W.G. Mallard,
#' National Institute of Standards and Technology, Gaithersburg MD, 20899,
#' \doi{10.18434/T4D303}.
#'
#' @export
#' @note Copyright for NIST Standard Reference Data is governed by the Standard
#' Reference Data Act, \url{https://www.nist.gov/srd/public-law}.
#' @seealso \code{\link{is.cas}} \code{\link{as.cas}}
#'
#' @examples
#' \dontrun{
#' myRIs <-
#' nist_ri(
#' c("78-70-6", "13474-59-4"),
#' from = "cas",
#' type = c("linear", "kovats"),
#' polarity = "non-polar",
#' temp_prog = "ramp"
#' )
#' myRIs}
nist_ri <- function(query,
from = c("cas", "inchi", "inchikey", "name"),
type = c("kovats", "linear", "alkane", "lee"),
polarity = c("polar", "non-polar"),
temp_prog = c("isothermal", "ramp", "custom"),
cas = NULL,
verbose = getOption("verbose")) {
if (!is.null(cas)) {
warning("`cas` is deprecated. Using `query` instead with `from = 'cas'`.")
query <- cas
from <- "cas"
}
from <- match.arg(from)
type <- match.arg(type, c("kovats", "linear", "alkane", "lee"), several.ok = TRUE)
polarity <- match.arg(polarity, c("polar", "non-polar"), several.ok = TRUE)
temp_prog <- match.arg(temp_prog, c("isothermal", "ramp", "custom"), several.ok = TRUE)
if (from == "cas"){
query <- sapply(query, function(x){
cas <- as.cas(gsub("C","", x))
ifelse(is.cas(cas) & !is.na(cas), cas, x)
})
} else if (from == "name"){
query <- format_name_nist(query)
}
ri_tables <-
purrr::map(
query,
~ get_ri_xml(
query = .x,
from = from,
type = type,
polarity = polarity,
temp_prog = temp_prog,
verbose = verbose
)
)
querynames <- query
querynames [is.na(querynames)] <- ".NA"
names(ri_tables) <- querynames
ri_tables <- dplyr::bind_rows(ri_tables)
return(ri_tables)
}
#' Scrape Retention Indices from NIST
#'
#' @param query query of type matching the options in `from`
#' @param from one of "name", "cas", "inchi", or "inchikey"
#' @param type what kind of RI
#' @param polarity polar or non-polar
#' @param temp_prog what kind of temperature program
#' @param verbose logical; should a verbose output be printed on the console?
#' @noRd
#' @import rvest
#' @import xml2
#' @importFrom utils URLencode
#' @return an xml nodeset
#'
get_ri_xml <-
function(query,
from,
type,
polarity,
temp_prog,
verbose) {
if (!ping_service("nist")) stop(webchem_message("service_down"))
cas_found <- FALSE
from_str <- (switch(
from,
"name" = "Name",
"inchi" = "InChI",
"inchikey" = "InChI",
"cas" = "ID"
))
baseurl <- "https://webbook.nist.gov/cgi/cbook.cgi"
#handle NAs
if (is.na(query)) {
if (verbose) webchem_message("na")
return(dplyr::tibble(query=NA))
}
if (from == "cas"){
ID <- paste0("C", gsub("-", "", query))
}
# check for existence of record
qurl <- URLencode(paste0(baseurl, "?", from_str, "=", gsub(" ","+", query), "&Units=SI"))
webchem_sleep(type = 'scrape')
if (verbose) webchem_message("query", query, appendLF = FALSE)
res <- try_url(qurl)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(dplyr::tibble(query=NA))
}
if (verbose) message(httr::message_for_status(res))
if (res$status_code == 200) {
page <- xml2::read_html(res)
#Warnings
result <- page %>%
rvest::html_node("main h1") %>%
rvest::html_text()
# if query not found
if (stringr::str_detect(result, "Not Found")) {
if (verbose) webchem_message("not_found", appendLF = FALSE)
ri_xml <- construct_NA_table(query)
} else if (result == "Search Results") {
# if more than one compound found
if (verbose){
message(paste0(" More than one match for '", query,
"'. Returning NA."))
}
ri_xml <- construct_NA_table(query)
} else{
links <-
page %>%
rvest::html_nodes("li li a") %>%
rvest::html_attr("href")
gaschrom <- links[which(regexpr("Gas-Chrom", links) >= 1)]
if (length(gaschrom) == 0) {
if (verbose) webchem_message("not_available")
cas <- page %>%
rvest::html_nodes("li") %>%
grep("CAS Registry", ., value=TRUE) %>%
gsub("<li>\n<strong>CAS Registry Number:</strong> |</li>", "",.)
ri_xml <- construct_NA_table(query, cas=ifelse(length(cas) > 0, cas, NA))
} else {
if (verbose) message(" CAS found. ", appendLF = FALSE)
ID <- stringr::str_extract(gaschrom, "(?<=ID=).+?(?=&)")
cas_found <- TRUE
}
}
} else {
return(dplyr::tibble(query=NA))
}
if (cas_found){
# check which records exist
check_records <- function(gaschrom, type, polarity, temp_prog, verbose){
if (any(sapply(list(type, polarity, temp_prog), length) > 1)){
res2 <- try_url(paste0("https://webbook.nist.gov", gaschrom))
if (inherits(res2, "try-error")) {
if (verbose) webchem_message("service_down")
return(dplyr::tibble(query=NA))
}
page <- xml2::read_html(res2)
tables <- page %>% html_nodes(".data") %>% html_attr("aria-label")
tables <- format_gaschrom_tables(tables)
tables.idx <- which(tables[,1] %in% type &
tables[,2] %in% polarity &
tables[,3] %in% temp_prog)
tables <- tables[tables.idx,,drop=FALSE]
} else {
tables <- data.frame(type, polarity, temp_prog)
}
tables
}
tables <- check_records(gaschrom, type, polarity, temp_prog, verbose)
if (nrow(tables) == 0){
ri_xml <- construct_NA_table(query, cas = ID)
} else{
ri_xml <- lapply(seq_len(nrow(tables)), function(i){
ri_xml <- scrape_RI_table(ID, type=tables[i,1], polarity = tables[i,2],
temp_prog = tables[i,3], from = from, verbose = verbose,
cas_found = cas_found)
attr(ri_xml, "query") <- query
ri_xml
})
}
}
purrr::map_dfr(ri_xml, tidy_ritable)
}
#' @noRd
construct_NA_table <- function(query, cas=NA){
x <- NA
attr(x,"query") <- query
attr(x,"cas") <- as.cas(gsub("C", "", cas))
list(x)
}
#' @noRd
scrape_RI_table <- function(ID, type, polarity, temp_prog,
from, verbose, cas_found){
#scrape RI table
type_str <- toupper(paste(type, "RI", polarity, temp_prog, sep = "-"))
baseurl <- "https://webbook.nist.gov/cgi/cbook.cgi"
qurl <- paste0(baseurl, "?ID=", ID, "&Units-SI&Mask=2000&Type=", type_str)
webchem_sleep(type = 'scrape')
if (verbose) webchem_message("query", ID, appendLF = FALSE)
res2 <- try_url(qurl)
if (inherits(res2, "try-error")) {
if (verbose) webchem_message("service_down")
return(dplyr::tibble(query=NA))
}
if (verbose) message(httr::message_for_status(res2))
if (res2$status_code == 200) {
page <- xml2::read_html(res2)
ri_xml.all <- html_nodes(page, ".data")
#message if table doesn't exist at URL
if (length(ri_xml.all) == 0) {
if (verbose) webchem_message("not_available")
ri_xml <- NA
} else {
ri_xml <- ri_xml.all
cas_found <- TRUE
}
} else {
return(dplyr::tibble(query=NA))
}
#set attributes to label what type of RI
attr(ri_xml, "from") <- from
attr(ri_xml, "type") <- type
attr(ri_xml, "polarity") <- polarity
attr(ri_xml, "temp_prog") <- temp_prog
attr(ri_xml, "cas") <- ifelse(cas_found, as.cas(gsub("C","",ID)), NA)
return(ri_xml)
}
#' Tidier for webscraped RI ri_xml
#'
#' @param ri_xml captured by \code{get_ri_xml}
#'
#' @import rvest
#' @importFrom purrr map
#' @importFrom purrr map_dfr
#' @importFrom tibble as_tibble
#' @import dplyr
#' @noRd
#' @return a single table
#'
tidy_ritable <- function(ri_xml) {
#Skip all these steps if the table didn't exist at the URL and was set to NA
cas <- attr(ri_xml, "cas")
if (any(is.na(ri_xml))) {
return(tibble(query = attr(ri_xml, "query"),
cas = ifelse(is.null(cas), NA, cas), RI = NA))
} else {
# Read in the tables from xml
table.list <- purrr::map(ri_xml, html_table)
# Transpose and tidy
tidy1 <- purrr::map_dfr(
table.list,
~{
transposed <- t(.x)
colnames(transposed) <- transposed[1, ]
transposed[-1, , drop = FALSE] %>%
as_tibble()
}
)
tidy2 <- dplyr::select(tidy1,
"RI" = "I",
"column" = "Column type",
"phase" = "Active phase",
"length" = "Column length (m)",
"gas" = "Carrier gas",
"substrate" = "Substrate",
"diameter" = "Column diameter (mm)",
"thickness" = "Phase thickness (\u03bcm)",
"program" = contains("Program"),
"temp" = contains("Temperature (C)"),
"temp_start" = contains("Tstart (C)"),
"temp_end" = contains("Tend (C)"),
"temp_rate" = contains("Heat rate (K/min)"),
"hold_start" = contains("Initial hold (min)"),
"hold_end" = contains("Final hold (min)"),
"reference" = "Reference",
"comment" = "Comment") %>%
dplyr::mutate_at(vars(any_of(c("length", "diameter", "thickness", "temp",
"temp_start","temp_end","temp_rate",
"hold_start","hold_end", "RI"))), as.numeric)
# make NAs explicit and gas abbreviations consistent
output <- tidy2 %>%
mutate(across(where(is.character), ~na_if(., ""))) %>%
dplyr::mutate(
gas = case_when(
stringr::str_detect(gas, "He") ~ "Helium",
stringr::str_detect(gas, "H2") ~ "Hydrogen",
stringr::str_detect(gas, "N2") ~ "Nitrogen",
TRUE ~ as.character(NA)
)
) %>%
dplyr::mutate(query = attr(ri_xml, "query"),
cas = attr(ri_xml, "cas"),
type = attr(ri_xml, "type"),
polarity = attr(ri_xml, "polarity"),
temp_prog = attr(ri_xml, "temp_prog"),) %>%
# reorder columns
dplyr::select("query","cas", "type", "polarity", "temp_prog", "RI", "type",
"phase", everything())
}
return(output)
}
#' Format chemical names into NIST format
#'
#' NIST uses Greek letters to distinguish stereoisomers, but users may have
#' strings that spell out the letters in Latin script. This is utility
#' function to convert chemical names to NIST format.
#' @param x character; a IUPAC chemical name
#' @return a character
#' @examples
#' format_name_nist("alpha-bergatomene")
#' format_name_nist("beta-bisabolene")
#' @noRd
format_name_nist <- function(x) {
format_name <- function(x){
# format name
dictionary <- c("[^a-zA-Z]alpha[^a-zA-Z]" = "-\\u03b1-",
"^alpha[^a-zA-Z]" = "\\u03b1-",
"[^a-zA-Z]alpha$" = "-\\u03b1",
"[^a-zA-Z]beta[^a-zA-Z]" = "-\\u03b2-",
"^beta[^a-zA-Z]" = "\\u03b2-",
"[^a-zA-Z]beta$" = "-\\u03b2",
"[^a-zA-Z]gamma[^a-zA-Z]" = "-\\u03b3-",
"^gamma[^a-zA-Z]" = "\\u03b3-",
"[^a-zA-Z]gamma$" = "-\\u03b3",
"[^a-zA-Z]delta[^a-zA-Z]" = "-\\U0001d6ff-",
"^delta[^a-zA-Z]" = "\\U0001d6ff-",
"[^a-zA-Z]delta$" = "-\\U0001d6ff")
x <- stringr::str_replace_all(x, dictionary)
x
}
sapply(x, format_name)
}
#' @noRd
try_url <- function(qurl){
try(httr::RETRY("GET",
qurl,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
}
#' @noRd
format_gaschrom_tables <- function(tables){
tables <- stringr::str_split_fixed(tables,",",3)
tables[,1] <- stringr::str_replace_all(tables[,1],
pattern = c("Kovats' RI" = "kovats",
"Normal alkane RI" = "alkane",
"Van Den Dool and Kratz RI" = "linear",
"Lee's RI" = "lee")
)
tables[,2] <- stringr::str_split_fixed(tables[,2], " ", 3)[,2]
tables[,3] <- stringr::str_replace_all(tables[,3],
pattern = c(" isothermal" = "isothermal",
" custom temperature program" = "custom",
" temperature ramp" = "ramp")
)
tables
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/nist.R
|
#' OPSIN web interface
#'
#' Query the OPSIN (Open Parser for Systematic IUPAC nomenclature) web service
#' \url{https://opsin.ch.cam.ac.uk/instructions.html}.
#'
#' @import jsonlite httr xml2
#' @import tibble
#' @importFrom dplyr select everything
#' @importFrom purrr map_dfr
#' @importFrom utils URLencode URLdecode
#' @param query character; chemical name that should be queryed.
#' @param verbose logical; should a verbose output be printed on the console?
#' @param ... currently not used.
#' @return a tibble with six columnns: "query", inchi", "stdinchi", "stdinchikey", "smiles", "message", and "status"
#'
#' @references Lowe, D. M., Corbett, P. T., Murray-Rust, P., & Glen, R. C. (2011).
#' Chemical Name to Structure: OPSIN, an Open Source Solution. Journal of Chemical Information and Modeling,
#' 51(3), 739–753. \doi{10.1021/ci100384d}
#' @examples
#' \dontrun{
#' opsin_query('Cyclopropane')
#' opsin_query(c('Cyclopropane', 'Octane'))
#' opsin_query(c('Cyclopropane', 'Octane', 'xxxxx'))
#'}
#' @export
opsin_query <- function(query, verbose = getOption("verbose"), ...){
if (!ping_service("opsin")) stop(webchem_message("service_down"))
foo <- function(query, verbose){
empty <- c(query, rep(NA, 6))
names(empty) <- c("query", "inchi", "stdinchi", "stdinchikey", "smiles", "message", "status")
empty <- as_tibble(t(empty))
if (is.na(query)) {
if (verbose) webchem_message("na")
return(empty)
}
query_u <- URLencode(query, reserved = TRUE)
baseurl <- "https://opsin.ch.cam.ac.uk/opsin/"
out <- 'json'
qurl <- paste0(baseurl, query_u, '.', out)
if (verbose) webchem_message("query", query, appendLF = FALSE)
webchem_sleep(type = 'API')
res <- try(httr::RETRY("GET",
qurl,
user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(empty)
}
if (verbose) message(httr::message_for_status(res))
if (res$status_code == 200) {
cont <- content(res, as = 'text')
if (substr(cont, 1, 14) == '<!DOCTYPE html') {
cont <- read_html(cont)
if (verbose) message(xml_text(xml_find_all(cont, '//h3')),
" Returning NA.")
return(empty)
}
cont <- fromJSON(cont)
cont[['cml']] <- NULL
cont <- c(query = query, unlist(cont))
cont <- tibble::as_tibble(t(cont))
return(cont)
}
else {
return(empty)
}
}
out <- purrr::map_dfr(query, ~foo(.x, verbose = verbose))
out <- dplyr::select(out, query, everything())
class(out) <- c("opsin_query", class(out))
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/opsin.R
|
#' Ping an API used in webchem to see if it's working.
#'
#' @param service character; the same abbreviations used as prefixes in
#' \code{webchem} functions, with the exception of \code{"cs_web"}, which only
#' checks if the ChemSpider website is up, and thus doesn't require an API key.
#' @param apikey character; API key for services that require API keys
#' @import httr
#' @return A logical, TRUE if the service is available or FALSE if it isn't
#' @export
#' @examples
#' \dontrun{
#' ping_service("chembl")
#' }
ping_service <-
function(service = c(
"bcpc",
"chebi",
"chembl",
"cs",
"cs_web",
"cir",
"cts",
"etox",
"fn",
"nist",
"opsin",
"pc",
"srs",
"wd"
), apikey = NULL
) {
service <- match.arg(service)
#if pinging service requires POST request, write separate non-exported
#function, and call here:
if (service %in% c("pc", "chebi", "cs", "etox")) {
out <-
switch(service,
"pc" = ping_pubchem() & ping_pubchem_pw(),
"chebi" = ping_chebi(),
"cs" = ping_cs(apikey = apikey),
"etox" = ping_etox()
)
} else {
#if service can be pinged with simple GET request, just add URL
ping_url <-
switch(service,
"bcpc" = "https://pesticidecompendium.bcpc.org/introduction.html",
"chembl" = "https://www.ebi.ac.uk/chembl/api/data/molecule/CHEMBL1082.json",
"cir" = "http://cactus.nci.nih.gov/chemical/structure/Triclosan/cas/xml",
"cts" = "http://cts.fiehnlab.ucdavis.edu/service/compound/XEFQLINVKFYRCS-UHFFFAOYSA-N",
"cs_web" = "http://www.chemspider.com/Chemical-Structure.5363.html",
"fn" = "http://www.flavornet.org/info/121-33-5.html",
"nist" = "https://webbook.nist.gov/cgi/cbook.cgi?Name=2-hexene&Units=SI",
"opsin" = "https://opsin.ch.cam.ac.uk/opsin/cyclopropane.json",
"srs" = "https://cdxnodengn.epa.gov/cdx-srs-rest/substance/name/triclosan",
"wd" = "https://www.wikidata.org/w/api.php"
)
if (identical(service, "bcpc")) {
# For the BCPC server we need to disable gzip encoding as it currently
# (2021-11-18) results in
# Error in curl_fetch_memory(https://...):
# "Failed writing received data to disk/application"
httr_config <- httr::config(accept_encoding = "identity")
} else {
httr_config <- httr::config()
}
res <- try(httr::RETRY("GET",
ping_url,
httr::user_agent(webchem_url()),
terminate_on = 404,
config = httr_config,
quiet = FALSE), silent = FALSE)
if (inherits(res, "try-error")) {
out <- FALSE
}
else {
out <- res$status_code == 200
}
}
return(out)
}
# ETOX ---------------------------------------------------------------------
#' @import httr
#' @noRd
#' @return TRUE if ETOX is reachable
#' @examples
#' \dontrun{
#' ping_etox()
#' }
ping_etox <- function(...) {
baseurl <- "https://webetox.uba.de/webETOX/public/search/stoff.do"
body <- list("stoffname.selection[0].name" = "triclosan",
"stoffname.selection[0].type" = "",
event = "Search")
res <- try(httr::RETRY("POST",
url = baseurl,
handle = handle(''),
body = body,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
return(FALSE)
}
return(res$status_code == 200)
}
# ChemSpider -----------------------------------------------------------
#' @import httr
#' @import jsonlite
#' @noRd
#' @param apikey character; your API key. If NULL (default),
#' \code{cs_check_key()} will look for it in .Renviron or .Rprofile.
#' @return TRUE if ChemSpider is reachable
#' @examples
#' \dontrun{
#' ping_cs()
#' }
ping_cs <- function(apikey = NULL) {
if (is.null(apikey)) {
apikey <- cs_check_key()
}
headers <- c("Content-Type" = "", "apikey" = apikey)
body <- list("name" = "triclosan", "orderBy" = "recordId", "orderDirection" = "ascending")
body <- jsonlite::toJSON(body, auto_unbox = TRUE)
res <- try(httr::RETRY("POST",
"https://api.rsc.org/compounds/v1/filter/name",
add_headers(headers),
body = body,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
return(FALSE)
}
return(res$status_code == 200)
}
# ChEBI ---------------------------------------------------------------------
#' @import httr
#' @noRd
#' @return TRUE if ChEBI is reachable
#' @examples
#' \dontrun{
#' ping_chebi()
#' }
ping_chebi <- function(...) {
baseurl <- 'http://www.ebi.ac.uk:80/webservices/chebi/2.0/webservice'
headers <- c(Accept = 'text/xml',
Accept = 'multipart/*',
`Content-Type` = 'text/xml; charset=utf-8',
SOAPAction = '')
body <-
'<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:chebi="https://www.ebi.ac.uk/webservices/chebi">
<soapenv:Header/>
<soapenv:Body>
<chebi:getLiteEntity>
<chebi:search>triclosan</chebi:search>
<chebi:searchCategory>ALL</chebi:searchCategory>
<chebi:maximumResults>200</chebi:maximumResults>
<chebi:stars>ALL</chebi:stars>
</chebi:getLiteEntity>
</soapenv:Body>
</soapenv:Envelope>'
res <- try(httr::RETRY("POST",
baseurl,
add_headers(headers),
body = body,
httr::user_agent(webchem_url()),
terminate_on = 400,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
return(FALSE)
}
return(res$status_code == 200)
}
# pubchem -----------------------------------------------------------------
#' @import httr
#' @noRd
#' @return TRUE if pubchem is reachable
#' @examples
#' \dontrun{
#' # might fail if API is not available
#' ping_pubchem()
#' }
ping_pubchem <- function(...) {
query = 'Aspirin'
from = 'name'
prolog <- 'https://pubchem.ncbi.nlm.nih.gov/rest/pug'
input <- paste0('/compound/', from)
output <- '/synonyms/JSON'
qurl <- paste0(prolog, input, output)
res <- try(httr::RETRY("POST",
qurl,
body = paste0(from, '=', query),
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE,
...), silent = TRUE)
if (inherits(res, "try-error")) {
return(FALSE)
}
return(res$status_code == 200)
}
# pubchem PUG-VIEW-----------------------------------------------------------------
#' @import httr
#' @noRd
#' @return TRUE if pubchem PUG-VIEW is reachable
#' @examples
#' \dontrun{
#' # might fail if API is not available
#' ping_pubchem_pw()
#' }
ping_pubchem_pw <- function(...) {
qurl <- paste("https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data",
"compound/176/JSON", sep = "/")
res <- try(httr::RETRY("POST",
qurl,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
return(FALSE)
}
return(res$status_code == 200)
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/ping.R
|
#' Retrieve Pubchem Compound ID (CID)
#'
#' Retrieve compound IDs (CIDs) from PubChem.
#' @param query character; search term, one or more compounds.
#' @param from character; type of input. See details for more information.
#' @param domain character; query domain, can be one of \code{"compound"},
#' \code{"substance"}, \code{"assay"}.
#' @param match character; How should multiple hits be handled?, \code{"all"}
#' all matches are returned, \code{"first"} the first matching is returned,
#' \code{"ask"} enters an interactive mode and the user is asked for input,
#' \code{"na"} returns NA if multiple hits are found.
#' @param verbose logical; should a verbose output be printed on the console?
#' @param arg character; optinal arguments like "name_type=word" to match
#' individual words.
#' @param first deprecated. Use `match` instead.
#' @param ... currently unused.
#' @return a tibble.
#' @details Valid values for the \code{from} argument depend on the
#' \code{domain}:
#' \itemize{
#' \item{\code{compound}: \code{"name"}, \code{"smiles"}, \code{"inchi"},
#' \code{"inchikey"}, \code{"formula"}, \code{"sdf"}, \code{"cas"} (an alias for
#' \code{"xref/RN"}), <xref>, <structure search>, <fast search>.}
#' \item{\code{substance}: \code{"name"}, \code{"sid"},
#' \code{<xref>}, \code{"sourceid/<source id>"} or \code{"sourceall"}.}
#' \item{\code{assay}: \code{"aid"}, \code{<assay target>}.}
#' }
#' @details <structure search> is assembled as "{\code{substructure} |
#' \code{superstructure} | \code{similarity} | \code{identity}} / {\code{smiles}
#' | \code{inchi} | \code{sdf} | \code{cid}}", e.g.
#' \code{from = "substructure/smiles"}.
#' @details \code{<xref>} is assembled as "\code{xref}/\{\code{RegistryID} |
#' \code{RN} | \code{PubMedID} | \code{MMDBID} | \code{ProteinGI},
#' \code{NucleotideGI} | \code{TaxonomyID} | \code{MIMID} | \code{GeneID} |
#' \code{ProbeID} | \code{PatentID}\}", e.g. \code{from = "xref/RN"} will query
#' by CAS RN.
#' @details <fast search> is either \code{fastformula} or it is assembled as
#' "{\code{fastidentity} | \code{fastsimilarity_2d} | \code{fastsimilarity_3d} |
#' \code{fastsubstructure} | \code{fastsuperstructure}}/{\code{smiles} |
#' \code{smarts} | \code{inchi} | \code{sdf} | \code{cid}}", e.g.
#' \code{from = "fastidentity/smiles"}.
#' @details \code{<source id>} is any valid PubChem Data Source ID. When
#' \code{from = "sourceid/<source id>"}, the query is the ID of the substance in
#' the depositor's database.
#' @details If \code{from = "sourceall"} the query is one or more valid Pubchem
#' depositor names. Depositor names are not case sensitive.
#' @details Depositor names and Data Source IDs can be found at
#' \url{https://pubchem.ncbi.nlm.nih.gov/sources/}.
#' @details \code{<assay target>} is assembled as "\code{target}/\{\code{gi} |
#' \code{proteinname} | \code{geneid} | \code{genesymbol} | \code{accession}\}",
#' e.g. \code{from = "target/geneid"} will query by GeneID.
#' @references Wang, Y., J. Xiao, T. O. Suzek, et al. 2009 PubChem: A Public
#' Information System for
#' Analyzing Bioactivities of Small Molecules. Nucleic Acids Research 37:
#' 623–633.
#'
#' Kim, Sunghwan, Paul A. Thiessen, Evan E. Bolton, et al. 2016
#' PubChem Substance and Compound Databases. Nucleic Acids Research 44(D1):
#' D1202–D1213.
#'
#' Kim, S., Thiessen, P. A., Bolton, E. E., & Bryant, S. H. (2015).
#' PUG-SOAP and PUG-REST: web services for programmatic access to chemical
#' information in PubChem. Nucleic acids research, gkv396.
#' @references Eduard Szöcs, Tamás Stirling, Eric R. Scott, Andreas Scharmüller,
#' Ralf B. Schäfer (2020). webchem: An R Package to Retrieve Chemical
#' Information from the Web. Journal of Statistical Software, 93(13).
#' \doi{10.18637/jss.v093.i13}.
#' @note Please respect the Terms and Conditions of the National Library of
#' Medicine, \url{https://www.nlm.nih.gov/databases/download.html} the data
#' usage policies of National Center for Biotechnology Information,
#' \url{https://www.ncbi.nlm.nih.gov/home/about/policies/},
#' \url{https://pubchem.ncbi.nlm.nih.gov/docs/programmatic-access}, and the data
#' usage policies of the indicidual data sources
#' \url{https://pubchem.ncbi.nlm.nih.gov/sources/}.
#' @import httr
#' @importFrom purrr map map2
#' @importFrom jsonlite fromJSON
#' @importFrom tibble enframe
#' @importFrom utils URLencode
#' @export
#' @examples
#' \dontrun{
#' # might fail if API is not available
#' get_cid("Triclosan")
#' get_cid("Triclosan", arg = "name_type=word")
#' # from SMILES
#' get_cid("CCCC", from = "smiles")
#' # from InChI
#' get_cid("InChI=1S/CH5N/c1-2/h2H2,1H3", from = "inchi")
#' # from InChIKey
#' get_cid("BPGDAMSIGCZZLK-UHFFFAOYSA-N", from = "inchikey")
#' # from formula
#' get_cid("C26H52NO6P", from = "formula")
#' # from CAS RN
#' get_cid("56-40-6", from = "xref/rn")
#' # similarity
#' get_cid(5564, from = "similarity/cid")
#' get_cid("CCO", from = "similarity/smiles")
#' # from SID
#' get_cid("126534046", from = "sid", domain = "substance")
#' # sourceid
#' get_cid("VCC957895", from = "sourceid/23706", domain = "substance")
#' # sourceall
#' get_cid("Optopharma Ltd", from = "sourceall", domain = "substance")
#' # from AID (CIDs of substances tested in the assay)
#' get_cid(170004, from = "aid", domain = "assay")
#' # from GeneID (CIDs of substances tested on the gene)
#' get_cid(25086, from = "target/geneid", domain = "assay")
#'
#' # multiple inputs
#' get_cid(c("Triclosan", "Aspirin"))
#'
#' }
get_cid <-
function(query,
from = "name",
domain = c("compound", "substance", "assay"),
match = c("all", "first", "ask", "na"),
verbose = getOption("verbose"),
arg = NULL,
first = NULL,
...) {
if (!ping_service("pc")) stop(webchem_message("service_down"))
#deprecate `first`
if (!is.null(first) && first) {
message("`first = TRUE` is deprecated. Use `match = 'first'` instead")
match <- "first"
} else if (!is.null(first) && !first) {
message("`first = FALSE` is deprecated. Use `match = 'all'` instead")
match <- "all"
}
#input validation
from <- tolower(from)
from <- ifelse(from == "cas", "xref/rn", from)
if (from == "xref/rn"){
query <- as.cas(query, verbose = verbose)
}
domain <- match.arg(domain)
xref <- paste(
"xref",
c("registryid", "rn", "pubmedid", "mmdbid", "proteingi", "nucleotidegi",
"taxonomyid", "mimid", "geneid", "probeid", "patentid"),
sep = "/"
)
structure_search <- expand.grid(
c("substructure", "superstructure", "similarity", "identity"),
c("smiles", "inchi", "sdf", "cid")
)
structure_search <- paste(structure_search$Var1, structure_search$Var2,
sep = "/")
fast_search <- expand.grid(
c("fastidentity", "fastsimilarity_2d", "fastsimilarity_3d",
"fastsubstructure", "fastsuperstructure"),
c("smiles", "smarts", "inchi", "sdf", "cid")
)
fast_search <- c(with(fast_search, paste(Var1, Var2, sep = "/")),
"fastformula")
targets <- paste("target", c("gi", "proteinname", "geneid", "genesymbol",
"accession"), sep = "/")
if (domain == "compound") {
from_choices <- c("cid", "name", "smiles", "inchi", "sdf", "inchikey",
"formula", structure_search, xref, fast_search)
from <- match.arg(from, choices = from_choices)
}
if (domain == "substance") {
if (!grepl("^sourceid/", from)) {
from <- match.arg(from, choices = c("sid", "name", xref, "sourceall"))
}
}
if (domain == "assay") {
from <- match.arg(from, choices = c("aid", targets))
}
match <- match.arg(match)
foo <- function(query, from, domain, match, verbose, arg, ...) {
if (is.na(query)) {
if (verbose) webchem_message("na")
return(tibble::tibble("query" = NA, "cid" = NA))
}
if (verbose) webchem_message("query", query, appendLF = FALSE)
if (from %in% structure_search) {
qurl <- paste("https://pubchem.ncbi.nlm.nih.gov/rest/pug",
domain,
from,
URLencode(as.character(query), reserved = TRUE),
"json",
sep = "/")
} else {
if (from == "smiles") {
qurl <- paste0("https://pubchem.ncbi.nlm.nih.gov/rest/pug/",
domain, "/",
from, "/",
"cids/JSON?smiles=",
URLencode(as.character(query), reserved = TRUE))
} else {
qurl <- paste("https://pubchem.ncbi.nlm.nih.gov/rest/pug",
domain,
from,
URLencode(as.character(query), reserved = TRUE),
"cids",
"json",
sep = "/")
}
}
if (!is.null(arg)) qurl <- paste0(qurl, "?", arg)
webchem_sleep(type = 'API')
if (from == "inchi") {
qurl <- paste("https://pubchem.ncbi.nlm.nih.gov/rest/pug",
domain, from, "cids", "json", sep = "/")
res <- try(httr::RETRY("POST",
qurl,
user_agent(webchem_url()),
body = paste0("inchi=", query),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
} else {
res <- try(httr::RETRY("POST",
qurl,
user_agent(webchem_url()),
terminate_on = c(202, 404),
quiet = TRUE), silent = TRUE)
}
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(tibble::tibble("query" = query, "cid" = NA))
}
if (res$status_code != 200) {
if (res$status_code == 202) {
cont <- httr::content(res, type = "text", encoding = "UTF-8")
listkey <- jsonlite::fromJSON(cont)$Waiting$ListKey
qurl <- paste("https://pubchem.ncbi.nlm.nih.gov/rest/pug/", domain,
"listkey", listkey, "cids", "json", sep = "/")
while (res$status_code == 202) {
webchem_sleep(time = 5)
res <- try(httr::RETRY("POST",
qurl,
user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(tibble::tibble("query" = query, "cid" = NA))
}
}
if (res$status_code != 200) {
if (verbose) message(httr::message_for_status(res))
return(tibble::tibble("query" = query, "cid" = NA))
}
}
else{
if (verbose) message(httr::message_for_status(res))
return(tibble::tibble("query" = query, "cid" = NA))
}
}
if (verbose) message(httr::message_for_status(res))
cont <- httr::content(res, type = "text", encoding = "UTF-8")
if (domain == "compound") {
cont <- jsonlite::fromJSON(cont)$IdentifierList$CID
}
if (domain == "substance") {
cont <- jsonlite::fromJSON(cont)$InformationList$Information$CID
}
if (domain == "assay") {
cont <- jsonlite::fromJSON(cont)$InformationList$Information$CID
}
out <- unique(unlist(cont))
out <- matcher(x = out, query = query, match = match, from = from,
verbose = verbose)
out <- as.character(out)
return(tibble::tibble("query" = query, "cid" = out))
}
out <- map(query,
~foo(query = .x, from = from, domain = domain, match = match,
verbose = verbose, arg = arg))
out <- dplyr::bind_rows(out)
return(out)
}
#' Retrieve compound properties from a pubchem CID
#'
#' Retrieve compound information from pubchem CID, see
#' \url{https://pubchem.ncbi.nlm.nih.gov/}
#' @import httr jsonlite
#'
#' @param cid character; Pubchem ID (CID).
#' @param properties character vector; properties to retrieve, e.g.
#' c("MolecularFormula", "MolecularWeight"). If NULL (default) all available
#' properties are retrieved. See
#' \url{https://pubchem.ncbi.nlm.nih.gov/docs/pug-rest}
#' for a list of all available properties.
#' @param verbose logical; should a verbose output be printed to the console?
#' @param ... currently not used.
#'
#' @return a data.frame
#' @seealso \code{\link{get_cid}}, \code{\link{pc_sect}}
#' @references Wang, Y., J. Xiao, T. O. Suzek, et al. 2009 PubChem: A Public
#' Information System for
#' Analyzing Bioactivities of Small Molecules. Nucleic Acids Research 37:
#' 623–633.
#'
#' Kim, Sunghwan, Paul A. Thiessen, Evan E. Bolton, et al. 2016
#' PubChem Substance and Compound Databases. Nucleic Acids Research 44(D1):
#' D1202–D1213.
#'
#' Kim, S., Thiessen, P. A., Bolton, E. E., & Bryant, S. H. (2015).
#' PUG-SOAP and PUG-REST: web services for programmatic access to chemical
#' information in PubChem. Nucleic acids research, gkv396.
#' @references Eduard Szöcs, Tamás Stirling, Eric R. Scott, Andreas Scharmüller,
#' Ralf B. Schäfer (2020). webchem: An R Package to Retrieve Chemical
#' Information from the Web. Journal of Statistical Software, 93(13).
#' \doi{10.18637/jss.v093.i13}.
#' @note Please respect the Terms and Conditions of the National Library of
#' Medicine, \url{https://www.nlm.nih.gov/databases/download.html} the data
#' usage policies of National Center for Biotechnology Information,
#' \url{https://www.ncbi.nlm.nih.gov/home/about/policies/},
#' \url{https://pubchem.ncbi.nlm.nih.gov/docs/programmatic-access}, and the data
#' usage policies of the indicidual data sources
#' \url{https://pubchem.ncbi.nlm.nih.gov/sources/}.
#' @export
#' @examples
#' \dontrun{
#' # might fail if API is not available
#' pc_prop(5564)
#'
#' ###
#' # multiple CIDS
#' comp <- c("Triclosan", "Aspirin")
#' cids <- get_cid(comp)
#' pc_prop(cids$cid, properties = c("MolecularFormula", "MolecularWeight",
#' "CanonicalSMILES"))
#' }
pc_prop <- function(cid, properties = NULL, verbose = getOption("verbose"), ...) {
if (!ping_service("pc")) stop(webchem_message("service_down"))
if (mean(is.na(cid)) == 1) {
if (verbose) webchem_message("na")
return(NA)
}
napos <- which(is.na(cid))
cid_o <- cid
cid <- cid[!is.na(cid)]
prolog <- "https://pubchem.ncbi.nlm.nih.gov/rest/pug"
input <- "/compound/cid"
if (is.null(properties))
properties <- c("MolecularFormula", "MolecularWeight", "CanonicalSMILES",
"IsomericSMILES", "InChI", "InChIKey", "IUPACName",
"XLogP", "ExactMass", "MonoisotopicMass", "TPSA",
"Complexity", "Charge", "HBondDonorCount",
"HBondAcceptorCount", "RotatableBondCount", "HeavyAtomCount",
"IsotopeAtomCount", "AtomStereoCount",
"DefinedAtomStereoCount", "UndefinedAtomStereoCount",
"BondStereoCount", "DefinedBondStereoCount",
"UndefinedBondStereoCount", "CovalentUnitCount", "Volume3D",
"XStericQuadrupole3D", "YStericQuadrupole3D",
"ZStericQuadrupole3D", "FeatureCount3D",
"FeatureAcceptorCount3D", "FeatureDonorCount3D",
"FeatureAnionCount3D", "FeatureCationCount3D",
"FeatureRingCount3D", "FeatureHydrophobeCount3D",
"ConformerModelRMSD3D", "EffectiveRotorCount3D",
"ConformerCount3D", "Fingerprint2D")
properties <- paste(properties, collapse = ",")
output <- paste0("/property/", properties, "/JSON")
qurl <- paste0(prolog, input, output)
if (verbose) webchem_message("query_all", appendLF = FALSE)
webchem_sleep(type = 'API')
res <- try(httr::RETRY("POST",
qurl,
httr::user_agent(webchem_url()),
body = list("cid" = paste(cid, collapse = ",")),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (verbose) message(httr::message_for_status(res))
if (res$status_code == 200) {
cont <- jsonlite::fromJSON(rawToChar(res$content))
if (names(cont) == "Fault") {
if (verbose) {
message(cont$Fault$Message, ". ", cont$Fault$Details, ". Returning NA.")
}
return(NA)
}
out <- cont$PropertyTable[[1]]
# insert NA rows
narow <- rep(NA, ncol(out))
for (i in seq_along(napos)) {
#capture NAs at beginning
firstnna <- min(which(!is.na(cid_o)))
if (napos[i] < firstnna) {
out <- rbind(narow, out)
} else {
# capture NAs at end
if (napos[i] > nrow(out)) {
# print(napos[i])
out <- rbind(out, narow)
} else {
out <- rbind(out[1:(napos[i] - 1), ], narow, out[napos[i]:nrow(out), ])
}
}}
rownames(out) <- NULL
class(out) <- c("pc_prop", "data.frame")
return(out)
}
else {
return(NA)
}
}
#' Search synonyms in pubchem
#'
#' Search synonyms using PUG-REST,
#' see \url{https://pubchem.ncbi.nlm.nih.gov/}.
#' @import httr jsonlite
#' @importFrom utils menu
#'
#' @param query character; search term.
#' @param from character; type of input, can be one of "name" (default), "cid",
#' "sid", "aid", "smiles", "inchi", "inchikey"
#' @param match character; How should multiple hits be handled? \code{"all"}
#' returns all matches, \code{"first"} returns only the first result,
#' \code{"ask"} enters an interactive mode and the user is asked for input,
#' \code{"na"} returns \code{NA} if multiple hits are found.
#' @param choices deprecated. Use the \code{match} argument instead.
#' @param verbose logical; should a verbose output be printed on the console?
#' @param arg character; optional arguments like "name_type=word" to match
#' individual words.
#' @param ... currently unused
#' @return a named list.
#'
#' @references Wang, Y., J. Xiao, T. O. Suzek, et al. 2009 PubChem: A Public
#' Information System for
#' Analyzing Bioactivities of Small Molecules. Nucleic Acids Research 37:
#' 623–633.
#'
#' Kim, Sunghwan, Paul A. Thiessen, Evan E. Bolton, et al. 2016
#' PubChem Substance and Compound Databases. Nucleic Acids Research 44(D1):
#' D1202–D1213.
#'
#' Kim, S., Thiessen, P. A., Bolton, E. E., & Bryant, S. H. (2015).
#' PUG-SOAP and PUG-REST: web services for programmatic access to chemical
#' information in PubChem. Nucleic acids research, gkv396.
#' @note Please respect the Terms and Conditions of the National Library of
#' Medicine, \url{https://www.nlm.nih.gov/databases/download.html} the data
#' usage policies of National Center for Biotechnology Information,
#' \url{https://www.ncbi.nlm.nih.gov/home/about/policies/},
#' \url{https://pubchem.ncbi.nlm.nih.gov/docs/programmatic-access}, and the data
#' usage policies of the indicidual data sources
#' \url{https://pubchem.ncbi.nlm.nih.gov/sources/}.
#' @export
#' @examples
#' \dontrun{
#' pc_synonyms("Aspirin")
#' pc_synonyms(c("Aspirin", "Triclosan"))
#' pc_synonyms(5564, from = "cid")
#' pc_synonyms(c("Aspirin", "Triclosan"), match = "ask")
#' }
pc_synonyms <- function(query,
from = c("name", "cid", "sid", "aid", "smiles", "inchi", "inchikey"),
match = c("all", "first", "ask", "na"),
verbose = getOption("verbose"),
arg = NULL, choices = NULL, ...) {
if (!ping_service("pc")) stop(webchem_message("service_down"))
# from can be cid | name | smiles | inchi | sdf | inchikey | formula
# query <- c("Aspirin")
# from = "name"
from <- match.arg(from)
match <- match.arg(match)
names(query) <- query
if (!missing("choices"))
stop("'choices' is deprecated. Use 'match' instead.")
foo <- function(query, from, verbose, ...) {
if (is.na(query)) {
if (verbose) webchem_message("na")
return(NA)
}
prolog <- "https://pubchem.ncbi.nlm.nih.gov/rest/pug"
input <- paste0("/compound/", from)
output <- "/synonyms/JSON"
if (!is.null(arg))
arg <- paste0("?", arg)
qurl <- paste0(prolog, input, output, arg)
if (verbose) webchem_message("query", query, appendLF = FALSE)
webchem_sleep(type = 'API')
res <- try(httr::RETRY("POST",
qurl,
httr::user_agent(webchem_url()),
body = paste0(from, "=", query),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (verbose) message(httr::message_for_status(res))
if (res$status_code == 200){
cont <- httr::content(res)
if (names(cont) == "Fault") {
message(cont$Fault$Details, ". Returning NA.")
return(NA)
}
out <- unlist(cont)[-1] #first result is always an ID number
names(out) <- NULL
out <- matcher(out, query = query, match = match, from = from,
verbose = verbose)
}
else {
return(NA)
}
}
out <- lapply(query, foo, from = from, verbose = verbose)
if (!is.null(choices)) #if only one choice is returned, convert list to vector
out <- unlist(out)
return(out)
}
#' Retrieve data from PubChem content pages
#'
#' When you search for an entity at \url{https://pubchem.ncbi.nlm.nih.gov/},
#' e.g. a compound or a substance, and select the record you are interested in,
#' you will be forwarded to a PubChem content page. When you look at a PubChem
#' content page, you can see that chemical information is organised into
#' sections, subsections, etc. The chemical data live at the lowest levels of
#' these sections. Use this function to retrieve the lowest level information
#' from PubChem content pages.
#' @param id numeric or character; a vector of PubChem identifiers to search
#' for.
#' @param section character; the section of the content page to be imported.
#' @param domain character; the query domain. Can be one of \code{"compound"},
#' \code{"substance"}, \code{"assay"}, \code{"gene"}, \code{"protein"} or
#' \code{"patent"}.
#' @param verbose logical; should a verbose output be printed on the console?
#' @return Returns a tibble of query results. In the returned tibble,
#' \code{SourceName} is the name of the depositor, and \code{SourceID} is the
#' ID of the search term within the depositor's database. You can browse
#' \url{https://pubchem.ncbi.nlm.nih.gov/sources/} for more information about
#' the depositors.
#' @details \code{section} is not case sensitive but it is sensitive to typing
#' errors and it requires the full name of the section as it is printed on the
#' content page. The PubChem Table of Contents Tree can also be found at
#' \url{https://pubchem.ncbi.nlm.nih.gov/classification/#hid=72}.
#' @note Please respect the Terms and Conditions of the National Library of
#' Medicine, \url{https://www.nlm.nih.gov/databases/download.html} the data
#' usage policies of National Center for Biotechnology Information,
#' \url{https://www.ncbi.nlm.nih.gov/home/about/policies/},
#' \url{https://pubchem.ncbi.nlm.nih.gov/docs/programmatic-access}, and the data
#' usage policies of the individual data sources
#' \url{https://pubchem.ncbi.nlm.nih.gov/sources/}.
#' @references Kim, S., Thiessen, P.A., Cheng, T. et al. PUG-View: programmatic
#' access to chemical annotations integrated in PubChem. J Cheminform 11, 56
#' (2019). \doi{10.1186/s13321-019-0375-2}.
#' @seealso \code{\link{get_cid}}, \code{\link{pc_prop}}
#' @examples
#' # might fail if API is not available
#' \dontrun{
#' pc_sect(176, "Dissociation Constants")
#' pc_sect(c(176, 311), "density")
#' pc_sect(2231, "depositor-supplied synonyms", "substance")
#' pc_sect(780286, "modify date", "assay")
#' pc_sect(9023, "Ensembl ID", "gene")
#' pc_sect("1ZHY_A", "Sequence", "protein")
#' }
#' @export
pc_sect <- function(id,
section,
domain = c("compound", "substance", "assay", "gene",
"protein", "patent"),
verbose = getOption("verbose")) {
domain <- match.arg(domain)
section <- tolower(gsub(" +", "+", section))
if (section %in% c("standard non-polar",
"Semi-standard non-polar",
"Standard polar")) {
stop("use nist_ri() to obtain more information on this.")
}
res <- pc_page(id, section, domain, verbose)
out <- pc_extract(res, section)
return(out)
}
#' Import PubChem content pages
#'
#' @importFrom jsonlite fromJSON
#' @importFrom data.tree as.Node Do
#' @param id numeric or character; a vector of identifiers to search for.
#' @param section character; the section of the content page to be imported.
#' @param domain character; the query domain. Can be one of \code{"compound"},
#' \code{"substance"}, \code{"assay"}, \code{"gene"}, \code{"protein"} or
#' \code{"patent"}.
#' @return A named list of content pages where each element is either a
#' data.tree or NA.
#' @details \code{section} can be any section of a PubChem content page, e.g.
#' \code{section = "solubility"} will import the section on solubility, or
#' \code{section = "experimental properties"} will import all experimental
#' properties. The \code{section} argument is not case sensitive but it
#' is sensitive to typing errors and it requires the full name of the section as
#' it is printed on the content page. The PubChem Table of Contents Tree can
#' also be found at
#' \url{https://pubchem.ncbi.nlm.nih.gov/classification/#hid=72}.
#' @references Kim, S., Thiessen, P.A., Cheng, T. et al. PUG-View: programmatic
#' access to chemical annotations integrated in PubChem. J Cheminform 11, 56
#' (2019). \doi{10.1186/s13321-019-0375-2}.
#' @examples
#' # might fail if API is not available
#' \dontrun{
#' pc_page(c(176, 311), "Dissociation Constants")
#' pc_page(49854366, "external id", domain = "substance")
#' }
#' @noRd
pc_page <- function(id,
section,
domain = c("compound", "substance", "assay", "gene",
"protein", "patent"),
verbose = getOption("verbose")) {
if (!ping_service("pc")) stop(webchem_message("service_down"))
domain <- match.arg(domain)
section <- tolower(gsub(" +", "+", section))
foo <- function(id, section, domain) {
if (is.na(id)) {
if (verbose) webchem_message("na")
return(NA)
}
qurl <- paste0("https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data/",
domain, "/", id, "/JSON?heading=", section)
if (verbose) webchem_message("query", id, appendLF = FALSE)
webchem_sleep(type = 'API')
res <- try(httr::RETRY("POST",
qurl,
user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (verbose) message(httr::message_for_status(res))
if (res$status_code == 200) {
cont <- httr::content(res, type = "text", encoding = "UTF-8")
# Intercepting any NA cont before it gets to fromJSON.
if(is.na(cont)) {
return(NA)
}
cont <- jsonlite::fromJSON(cont, simplifyDataFrame = FALSE)
tree <- data.tree::as.Node(cont, nameName = "TOCHeading")
tree$Do(function(node) node$name <- tolower(node$name))
return(tree)
}
else {
return(NA)
}
}
cont <- lapply(id, function(x) foo(x, section, domain))
names(cont) <- id
attr(cont, "domain") <- domain
attr(cont, "id") <- switch(domain, compound = "CID", substance = "SID",
assay = "AID", gene = "GeneID", protein = "pdbID",
patent = "PatentID")
return(cont)
}
#' Extract data from PubChem content pages
#'
#' This function takes a list of PubChem content pages, and extracts the
#' required information from them.
#' @importFrom data.tree FindNode
#' @importFrom dplyr bind_rows
#' @importFrom tibble as_tibble
#' @param pages list; a list of PubChem content pages.
#' @param section character; the lowest level section of the data to be
#' accessed.
#' @return A tibble of chemical information with references.
#' @details When you look at a PubChem content page, you can see that chemical
#' information is organised into sections, subsections, etc. The chemical data
#' live at the lowest levels of these sections. Use this function to extract the
#' lowest level information from PubChem content pages, e.g. IUPAC Name, Boiling
#' Point, Lower Explosive Limit (LEL).
#' @details The \code{section} argument is not case sensitive, but it is
#' sensitive to typing errors, and requires the full name of the section as it
#' is printed on the content page. The PubChem Table of Contents Tree can also
#' be found at \url{https://pubchem.ncbi.nlm.nih.gov/classification/#hid=72}.
#' @references Kim, S., Thiessen, P.A., Cheng, T. et al. PUG-View: programmatic
#' access to chemical annotations integrated in PubChem. J Cheminform 11, 56
#' (2019). \doi{10.1186/s13321-019-0375-2}.
#' @examples
#' # might fail if API is not available
#' \dontrun{
#' comps <- pc_page(c(176, 311), "Dissociation Constants")
#' pc_extract(comps, "Dissociation Constants")
#' subs <- pc_page(49854366, "external id", domain = "substance")
#' pc_extract(subs, "external id")
#' }
#' @noRd
pc_extract <- function(page, section) {
section <- tolower(section)
ids <- names(page)
foo <- function(i, section) {
tree <- page[[i]]
if (length(tree) == 1 && is.na(tree)) return(tibble(ID = ids[i]))
node <- FindNode(tree, "information")
if (is.null(node)) return(tibble(ID = ids[i],
Name = tree$record$RecordTitle))
info <- lapply(node, function(y) {
lownode <- data.tree::FindNode(data.tree::as.Node(y), "stringwithmarkup")
if (is.null(lownode)) {
info <- tibble(Result = paste(y$value, collapse = " "),
ReferenceNumber = y$ReferenceNumber)
return(info)
}
else{
string <- sapply(lownode, function(z) z$String)
info <- tibble(Result = string,
ReferenceNumber = y$ReferenceNumber)
}
})
info <- dplyr::bind_rows(info)
info <- tibble(ID = ids[i],
Name = tree$record$RecordTitle,
info)
node <- FindNode(tree, "reference")
if (is.null(node)) return(tibble(info, SourceName = NA, SourceID = NA))
ref <- lapply(node, function(y) {
ref <- tibble(ReferenceNumber = y$ReferenceNumber,
SourceName = y$SourceName,
SourceID = y$SourceID)
return(ref)
})
ref <- dplyr::bind_rows(ref)
info$SourceName <- sapply(info$ReferenceNumber, function(x) {
ref$SourceName[ref$ReferenceNumber == x]
})
info$SourceID <- sapply(info$ReferenceNumber, function(x) {
ref$SourceID[ref$ReferenceNumber == x]
})
return(info)
}
info <- lapply(seq_along(page), function(x) foo(x, section))
info <- dplyr::bind_rows(info)
info <- info[, -which(names(info) == "ReferenceNumber")]
names(info)[1] <- attr(page, "id")
return(info)
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/pubchem.R
|
#' Get record details from U.S. EPA Substance Registry Servives (SRS)
#'
#' Get record details from SRS, see \url{https://cdxnodengn.epa.gov/cdx-srs-rest/}
#'
#'@param query character; query ID.
#'@param from character; type of query ID, e.g. \code{'itn'} , \code{'cas'},
#' \code{'epaid'}, \code{'tsn'}, \code{'name'}.
#'@param verbose logical; should a verbose output be printed on the console?
#'@param ... not currently used.
#'@return a list of lists (for each supplied query): a list of 22. subsKey,
#' internalTrackingNumber, systematicName, epaIdentificationNumber,
#' currentCasNumber, currentTaxonomicSerialNumber, epaName, substanceType,
#' categoryClass, kingdomCode, iupacName, pubChemId, molecularWeight,
#' molecularFormula, inchiNotation, smilesNotation, classifications,
#' characteristics, synonyms, casNumbers, taxonomicSerialNumbers, relationships
#'@export
#'
#' @examples
#' \dontrun{
#' # might fail if API is not available
#' srs_query(query = '50-00-0', from = 'cas')
#'
#' ### multiple inputs
#' casrn <- c('50-00-0', '67-64-1')
#' srs_query(query = casrn, from = 'cas')
#' }
srs_query <-
function(query,
from = c("itn", "cas", "epaid", "tsn", "name"),
verbose = getOption("verbose"), ...) {
if (!ping_service("srs")) stop(webchem_message("service_down"))
names(query) <- query
from <- match.arg(from)
entity_url <- "https://cdxnodengn.epa.gov/cdx-srs-rest/"
if (from == "cas"){
query <- as.cas(query, verbose = verbose)
}
rst <- lapply(query, function(x) {
if (is.na(x)){
if (verbose) webchem_message("na")
return(NA)
}
entity_query <- paste0(entity_url, "/substance/", from, "/", x)
if (verbose) webchem_message("query", x, appendLF = FALSE)
webchem_sleep(type = 'API')
response <- try(httr::RETRY("GET",
entity_query,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(response, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (verbose) message(httr::message_for_status(response))
if (response$status_code == 200) {
text_content <- httr::content(response, "text")
if (text_content == "[]") {
if (verbose) webchem_message("not_available")
return(NA)
} else {
jsonlite::fromJSON(text_content)
}
} else {
return(NA)
}
})
return(rst)
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/srs.R
|
#' Check if input is a valid inchikey
#'
#' @description This function checks if a string is a valid inchikey.
#' Inchikey must fulfill the following criteria:
#' 1) consist of 27 characters;
#' 2) be all uppercase, all letters (no numbers);
#' 3) contain two hyphens at positions 15 and 26;
#' 4) 24th character (flag character) be 'S' (Standard InChI) or 'N' (non-standard)
#' 5) 25th character (version character) must be 'A' (currently).
#'
#' @param x character; input InChIKey
#' @param type character; How should be checked? Either, by format (see above)
#' ('format') or by ChemSpider ('chemspider').
#' @param verbose logical; print messages during processing to console?
#' @return a logical
#'
#' @note This function can handle only one inchikey string.
#'
#' @references Heller, Stephen R., et al. "InChI, the IUPAC International
#' Chemical Identifier." Journal of Cheminformatics 7.1 (2015): 23.
#' @references Eduard Szöcs, Tamás Stirling, Eric R. Scott, Andreas Scharmüller,
#' Ralf B. Schäfer (2020). webchem: An R Package to Retrieve Chemical
#' Information from the Web. Journal of Statistical Software, 93(13).
#' \doi{10.18637/jss.v093.i13}.
#' @export
#' @examples
#' is.inchikey('BQJCRHHNABKAKU-KBQPJGBKSA-N')
#' is.inchikey('BQJCRHHNABKAKU-KBQPJGBKSA')
#' is.inchikey('BQJCRHHNABKAKU-KBQPJGBKSA-5')
#' is.inchikey('BQJCRHHNABKAKU-KBQPJGBKSA-n')
#' is.inchikey('BQJCRHHNABKAKU/KBQPJGBKSA/N')
#' is.inchikey('BQJCRHHNABKAKU-KBQPJGBKXA-N')
#' is.inchikey('BQJCRHHNABKAKU-KBQPJGBKSB-N')
is.inchikey = function(x, type = c('format', 'chemspider'),
verbose = getOption("verbose")) {
# x <- 'BQJCRHHNABKAKU-KBQPJGBKSA-N'
if (length(x) > 1) {
stop('Cannot handle multiple input strings.')
}
type <- match.arg(type)
out <- switch(type,
format = is.inchikey_format(x, verbose = verbose),
chemspider = is.inchikey_cs(x, verbose = verbose))
return(out)
}
#' Check if input is a valid inchikey using ChemSpider API
#'
#' @param x character; input string
#' @param verbose logical; print messages during processing to console?
#' @return a logical
#'
#' @seealso \code{\link{is.inchikey}} for a pure-R implementation.
#' @export
#' @examples
#' \dontrun{
#' # might fail if API is not available
#' is.inchikey_cs('BQJCRHHNABKAKU-KBQPJGBKSA-N')
#' is.inchikey_cs('BQJCRHHNABKAKU-KBQPJGBKSA')
#' is.inchikey_cs('BQJCRHHNABKAKU-KBQPJGBKSA-5')
#' is.inchikey_cs('BQJCRHHNABKAKU-KBQPJGBKSA-n')
#' is.inchikey_cs('BQJCRHHNABKAKU/KBQPJGBKSA/N')
#' is.inchikey_cs('BQJCRHHNABKAKU-KBQPJGBKXA-N')
#' is.inchikey_cs('BQJCRHHNABKAKU-KBQPJGBKSB-N')
#' }
is.inchikey_cs <- function(x, verbose = getOption("verbose")){
if (!ping_service("cs_web")) stop(webchem_message("service_down"))
if (length(x) > 1) {
stop('Cannot handle multiple input strings.')
}
if (is.na(x)) {
if (verbose) webchem_message("na")
return(NA)
}
baseurl <- 'http://www.chemspider.com/InChI.asmx/IsValidInChIKey?'
qurl <- paste0(baseurl, 'inchi_key=', x)
webchem_sleep(type = 'scrape')
if (verbose) webchem_message("query", x, appendLF = FALSE)
res <- try(httr::RETRY("GET",
qurl,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(NA)
}
if (verbose) message(httr::message_for_status(res))
if (res$status_code == 200){
h <- xml2::read_xml(res)
out <- as.logical(xml_text(h))
return(out)
}
else {
return(NA)
}
}
#' Check if input is a valid inchikey using format
#'
#' @description Inchikey must fulfill the following criteria:
#' 1) consist of 27 characters;
#' 2) be all uppercase, all letters (no numbers);
#' 3) contain two hyphens at positions 15 and 26;
#' 4) 24th character (flag character) be 'S' (Standard InChI) or 'N'
#' (non-standard)
#' 5) 25th character (version character) must be 'A' (currently).
#'
#' @param x character; input string
#' @param verbose logical; print messages during processing to console?
#' @return a logical
#'
#' @seealso \code{\link{is.inchikey}} for a pure-R implementation.
#' @export
#' @examples
#' \dontrun{
#' # might fail if API is not available
#' is.inchikey_format('BQJCRHHNABKAKU-KBQPJGBKSA-N')
#' is.inchikey_format('BQJCRHHNABKAKU-KBQPJGBKSA')
#' is.inchikey_format('BQJCRHHNABKAKU-KBQPJGBKSA-5')
#' is.inchikey_format('BQJCRHHNABKAKU-KBQPJGBKSA-n')
#' is.inchikey_format('BQJCRHHNABKAKU/KBQPJGBKSA/N')
#' is.inchikey_format('BQJCRHHNABKAKU-KBQPJGBKXA-N')
#' is.inchikey_format('BQJCRHHNABKAKU-KBQPJGBKSB-N')
#' }
is.inchikey_format = function(x, verbose = getOption("verbose")) {
# x <- 'BQJCRHHNABKAKU-KBQPJGBKSA-N'
if (length(x) > 1) {
stop('Cannot handle multiple input strings.')
}
nch <- nchar(x)
if (nch != 27) {
if (verbose)
message('Not 27 characters long.')
return(FALSE)
}
let <- strsplit(x, split = '')[[1]]
if (any(grepl("[[:digit:]]", let))) {
if (verbose)
message('string contains numbers.')
return(FALSE)
}
if (x != toupper(x)) {
if (verbose)
message('Not all character uppercase.')
return(FALSE)
}
if (substr(x, 15, 15) != "-" | substr(x, 26, 26) != "-") {
if (verbose)
message('Hyphens not at position 15 and 26.')
return(FALSE)
}
f <- substr(x, 24, 24)
if (f != 'S' & f != 'N') {
if (verbose)
message("Flag character not 'S' or 'N'.")
return(FALSE)
}
f <- substr(x, 25, 25)
if (f != 'A') {
if (verbose)
message("Version character not 'A'.")
return(FALSE)
}
return(TRUE)
}
#' Check if input is a valid CAS
#'
#' @description This function checks if a string is a valid CAS registry number.
#' A valid CAS is 1) separated by two hyphes into three parts; 2) the first part
#' consists from two up to seven digits; 3) the second of two digits; 4) the
#' third of one digit (check digit); 5) the check digits corresponds the
#' checksum. The checksum is found by taking the last digit (excluding the check
#' digit) multiplyingit with 1, the second last multiplied with 2, the
#' third-last multiplied with 3 etc. The modulo 10 of the sum of these is the
#' checksum.
#'
#' @import stringr
#' @param x character; input CAS
#' @param verbose logical; print messages during processing to console?
#' @return a logical
#' @note This function can only handle one CAS string
#' @references Eduard Szöcs, Tamás Stirling, Eric R. Scott, Andreas Scharmüller,
#' Ralf B. Schäfer (2020). webchem: An R Package to Retrieve Chemical
#' Information from the Web. Journal of Statistical Software, 93(13).
#' \doi{10.18637/jss.v093.i13}.
#'
#' @export
#' @examples
#' is.cas('64-17-5')
#' is.cas('64175')
#' is.cas('4-17-5')
#' is.cas('64-177-6')
#' is.cas('64-17-55')
#' is.cas('64-17-6')
is.cas <- function(x, verbose = getOption("verbose")) {
foo <- function(x, verbose) {
# pass NA's through
if (is.na(x)) return(NA)
# cas must not have any alpha characters
if (grepl(pattern = "[[:alpha:]]", x = x)) {
if (isTRUE(verbose)) {
message(x,": String contains alpha characters")
}
return(FALSE)
}
# cas must not have any white space
if (grepl(pattern = "\\s+", x = x)) {
if(isTRUE(verbose)) {
message(x, ": String contains whitespace")
}
return(FALSE)
}
# cas must have two hyphens
nsep <- str_count(x, '-')
if (nsep != 2) {
if (isTRUE(verbose))
message(x, ': Less than 2 hyphens in string.')
return(FALSE)
}
# first part 2 to 7 digits
fi <- gsub('^(.*)-(.*)-(.*)$', '\\1', x)
if (nchar(fi) > 7 | nchar(fi) < 2) {
if (isTRUE(verbose))
message(x, ': First part has more than 7 digits!')
return(FALSE)
}
# second part must be two digits
se <- gsub('^(.*)-(.*)-(.*)$', '\\2', x)
if (nchar(se) != 2) {
if (isTRUE(verbose))
message(x, ': Second part should have two digits!')
return(FALSE)
}
# third part (checksum) must be 1 digit
th <- gsub('^(.*)-(.*)-(.*)$', '\\3', x)
if (nchar(th) != 1) {
if (isTRUE(verbose))
message(x, ': Third part should have 1 digit!')
return(FALSE)
}
# check checksum
di <- as.numeric(strsplit(gsub('^(.*)-(.*)-(.*)$', '\\1\\2', x),
split = '')[[1]])
checksum <- sum(rev(seq_along(di)) * di)
if (checksum %% 10 != as.numeric(th)) {
if (isTRUE(verbose))
message(x, ': Checksum is not correct! ', checksum %% 10, ' vs. ', th)
return(FALSE)
}
return(TRUE)
}
return(sapply(x, foo, verbose))
}
#' Check if input is a SMILES string
#'
#' @description This function checks if a string is a valid SMILES by checking
#' if (R)CDK can parse it. If it cannot be parsed by rcdk FALSE is returned,
#' else TRUE.
#' @param x character; input SMILES.
#' @param verbose logical; print messages during processing to console?
#' @return a logical
#'
#' @note This function can handle only one SMILES string.
#'
#' @references Egon Willighagen (2015). How to test SMILES strings in
#' Supplementary Information.
#' \url{https://chem-bla-ics.blogspot.nl/2015/10/how-to-test-smiles-strings-in.html}
#'
#' @export
#' @examples
#' \dontrun{
#' # might fail if rcdk is not working properly
#' is.smiles('Clc(c(Cl)c(Cl)c1C(=O)O)c(Cl)c1Cl')
#' is.smiles('Clc(c(Cl)c(Cl)c1C(=O)O)c(Cl)c1ClJ')
#' }
is.smiles <- function(x, verbose = getOption("verbose")) {
if (!requireNamespace("rcdk", quietly = TRUE)) {
stop("rcdk needed for this function to work. Please install it.",
call. = FALSE)
}
# x <- 'Clc(c(Cl)c(Cl)c1C(=O)O)c(Cl)c1Cl'
if (length(x) > 1) {
stop('Cannot handle multiple input strings.')
}
out <- try(rcdk::parse.smiles(x), silent = TRUE)
if (inherits(out[[1]], 'try-error') | is.null(out[[1]])) {
return(FALSE)
} else {
return(TRUE)
}
}
#' Extract a number from a string
#' @param x character; input string
#' @return a numeric vector
#' @noRd
#' @examples
#' extr_num('aaaa -95')
#' extr_num("Melting Pt : -44.6 deg C")
extr_num <- function(x) {
if (length(x) == 0)
return(NA)
as.numeric(gsub("[^0-9\\.\\-]+", "", x))
}
#' Parse Molfile (as returned by ChemSpider) into a R-object.
#'
#' @param string molfile as one string
#' @return A list with of four entries: header (eh), counts line (cl), atom
#' block (ab) and bond block (bb).
#'
#' header: a = number of atoms, b = number of bonds, l = number of atom lists,
#' f = obsolete, c = chiral flag (0=not chiral, 1 = chiral), s = number of stext
#' entries, x, r, p, i = obsolete, m = 999, v0 version
#'
#' atom block: x, y, z = atom coordinates, a = mass difference, c= charge,
#' s= stereo parity, h = hydrogen count 1, b = stereo care box, v = valence,
#' h = h0 designator, r, i = not used, m = atom-atom mapping number,
#' n = inversion/retention flag, e = exact change flag
#'
#' bond block:
#' 1 = first atom, 2 = second atom, t = bond type, s = stereo type, x = not
#' used, r = bond typology, c = reacting center status.
#'
#' @references Grabner, M., Varmuza, K., & Dehmer, M. (2012). RMol:
#' a toolset for transforming SD/Molfile structure information into R objects.
#' Source Code for Biology and Medicine, 7, 12.
#' \doi{10.1186/1751-0473-7-12}
#' @export
parse_mol <- function(string) {
if (!is.character(string)) stop("string is not a character string")
if (length(string) > 1)
stop('string must be of length 1')
m <- readLines(textConnection(string))
# header
h <- trimws(m[1:3])
# counts line
cl <- m[4]
nchar(cl)
splits <- c(seq(1, 33, by = 3), 34)
cl <- trimws(substring(cl, splits, c(splits[-1] - 1, nchar(cl))))
# atom block
na <- as.numeric(cl[1])
ab <- m[5:(4 + na)]
ab <- read.table(text = ab)
# bound block
nb <- as.numeric(cl[2])
bb <- m[(5 + na):(4 + na + nb)]
bb <- read.table(text = bb)
return(list(eh = h, cl = cl, ab = ab, bb = bb))
}
#' Export a Chemical Structure in .mol Format.
#'
#' Some webchem functions return character strings that contain a chemical
#' structure in Mol format. This function exports a character string as a .mol
#' file so it can be imported with other chemistry software.
#' @param x a character string of a chemical structure in mol format.
#' @param file a character vector of file names
#' @export
#' @examples
#' \dontrun{
#' # export Mol file
#' csid <- get_csid("bergapten")
#' mol3d <- cs_compinfo(csid$csid, field = "Mol3D")
#' write_mol(mol3d$mol3D, file = mol3d$id)
#'
#' # export multiple Mol files
#' csids <- get_csid(c("bergapten", "xanthotoxin"))
#' mol3ds <- cs_compinfo(csids$csid, field = "Mol3D")
#' mapply(function(x, y) write_mol(x, y), x = mol3ds$mol3D, y = mol3ds$id)
#' }
write_mol <- function(x, file = "") {
if (!is.character(x)) stop("x is not a character string")
mol <- try(parse_mol(x), silent = TRUE)
if (inherits(mol, "try-error")) {
stop ("x is not a Mol string")
}
utils::write.table(x,
file = file,
row.names = FALSE,
col.names= FALSE,
quote = FALSE)
}
#' Format numbers as CAS numbers
#' @description This function attempts to format numeric (or character) vectors
#' as character vectors of CAS numbers. If they cannot be converted to CAS
#' format or don't pass \code{\link{is.cas}}, \code{NA} is returned
#' @param x numeric vector, or character vector of CAS numbers missing the
#' hyphens
#' @param verbose logical; should a verbose output be printed on the console?
#' @return character vector of valid CAS numbers
#' @seealso \code{\link{is.cas}}
#' @export
#' @examples
#' x = c(58082, 123456, "hexenol")
#' as.cas(x)
#'
as.cas <- function(x, verbose = getOption("verbose")){
format.cas <- function(x){
if(is.na(x)) {
return(NA)
} else if (suppressMessages(is.cas(x))) {
return(x)
} else {
parsed <- gsub("([0-9]+)([0-9]{2})([0-9]{1})", '\\1-\\2-\\3', x)
pass <- is.cas(parsed, verbose = verbose)
out <- ifelse(pass, parsed, NA)
return(out)
}
}
cas <- sapply(x, format.cas, USE.NAMES = TRUE)
names(cas) <- x
cas
}
#' Used internally to handle the `match` argument in most functions.
#'
#' @param x a vector of hits returned from a query
#' @param query what the query was, only used if match = "best"
#' @param result vector of results of the same type as `query` and same length
#' as `x`, only used if match = "best
#' @param match character; How should multiple hits be handled? "all" returns
#' all matched IDs, "first" only the first match, "best" the best matching (by
#' name) ID, "ask" is a interactive mode and the user is asked for input, "na"
#' @param from character; used only to check that match = "best" is used sensibly.
#' @param verbose print messages?
#' @noRd
#'
#' @examples
#' testids <- c("123", "456", "789")
#' results <- c("apple", "banana", "orange")
#' matcher(testids, query = "bananananan", result = results, match = "best")
matcher <-
function(x,
query = NULL,
result = NULL,
match = c("all", "best", "first", "ask", "na"),
from = NULL,
verbose = getOption("verbose")) {
match <- match.arg(match)
names(x) <- result
if (length(x) == 1) {
return(x)
} else {
if (verbose) message(" Multiple found. ", appendLF = FALSE)
if (!is.null(from)) {
if (!str_detect(tolower(from), "name") & match == "best") {
warning("match = 'best' only makes sense for chemical name queries.\n
Setting match = 'first'.")
match <- "first"
}
}
if (match == "all") {
if (verbose) message("Returning all.")
return(x)
}
else if (match == "best") {
#check that x and result are same length
if (length(x) != length(result))
stop("Can't use match = 'best' without query matches for each output")
if (verbose) message("Returning best.")
dd <- utils::adist(query, result) / nchar(result)
return(x[which.min(dd)])
} else if (match == "first") {
if (verbose) message("Returning first.")
return(x[1])
} else if (match == "ask" & interactive()) {
if (!is.null(result)) {
choices <- paste0(result, ": ", x)
} else {
choices <- x
}
pick <- menu(choices, graphics = FALSE, paste0("Select result for '", query, "':"))
return(x[pick])
} else if (match == "na") {
if (verbose) message("Returning NA.")
x <- NA
names(x) <- NA
return(x)
}
}
}
#' Webchem messages
#'
#' Webchem spacific messages to be used in verbose messages.
#' @noRd
webchem_message <- function(action = c("na",
"query",
"query_all",
"not_found",
"not_available",
"service_down"),
appendLF = TRUE,
...) {
action <- match.arg(action)
string <- switch(
action,
na = "Query is NA. Returning NA.",
query = paste0("Querying ", ..., ". "),
query_all = "Querying. ",
not_found = "Not found. Returning NA.",
not_available = "Not available. Returning NA.",
service_down = "Service not available. Returning NA."
)
message(string, appendLF = FALSE)
if (appendLF) message("")
}
#' Webchem URL
#'
#' URL of the webchem package to be used in httr::user_agent()
#' @noRd
webchem_url <- function() {
url <- "https://cran.r-project.org/web/packages/webchem/index.html"
return(url)
}
#' Function to wait between every web-service query
#'
#' @param time numeric; Wait time in seconds.
#' @param type character; Will be an API queried or a website scraped?
#' @noRd
#'
webchem_sleep <- function(time = NULL,
type = c('API', 'scrape')) {
type <- match.arg(type)
if (is.null(time)) {
if (type == 'API') {
time <- 0.2
}
if (type == 'scrape') {
time <- 0.3
}
} else {
if (!is.numeric(time)) {
stop('Set time is not numeric.')
}
}
Sys.sleep(time)
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/utils.R
|
#' Defunct function(s) in the webchem package
#'
#' These functions are defunct and no longer available.
#' @rdname webchem-defunct
#' @name webchem-defunct
#' @export
#' @aliases ppdb_query
#' @aliases ppdb_parse
#' @aliases ppdb
#' @aliases cir
ppdb_query <- function() {
.Defunct(
"ppdb_parse",
package = "webchem",
msg = "ppdb_query() has been removed from the package due to copyright
issues.")
}
#' @rdname webchem-defunct
#' @export
ppdb_parse <- function() {
.Defunct(
"ppdb",
package = "webchem",
msg = "ppdb_parse() has been removed from the package due to copyright
issues.")
}
#' @rdname webchem-defunct
#' @export
ppdb <- function() {
.Defunct(
"ppdb",
package = "webchem",
msg = "ppdb() has been removed from the package due to copyright issues.")
}
#' @rdname webchem-defunct
#' @export
cir <- function() {
.Defunct("cir_query", package = "webchem")
}
#' @rdname webchem-defunct
#' @export
pp_query <- function() {
.Defunct(
"pp_query",
package = "webchem",
msg = "pp_query() has been removed from the package since the Physprop API
is no longer active."
)
}
#' @rdname webchem-defunct
#' @export
cs_prop <- function() {
.Defunct(
"cs_prop",
package = "webchem",
msg = "cs_prop() has been removed from the package since RSC does not allow
the scraping of ChemSpider pages."
)
}
#' @rdname webchem-defunct
#' @export
ci_query <- function() {
.Defunct(
"ci_query",
package = "webchem",
msg = paste0(
"ci_query() has been removed from the package because NLM had retired ",
"ChemIDplus. According to NLM all data found in ChemIDplus is available ",
"in PubChem. 'webchem' provides a number of functions for ",
"programmatically accessing PubChem."
)
)
}
#' @rdname webchem-defunct
#' @export
pan_query <- function() {
.Defunct(
"pan_query",
package = "webchem",
msg = paste0(
"pan_query() has been removed from the package because programmatic ",
"access to the Pesticide Action Network database is no longer supported."
)
)
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/webchem-defunct.R
|
#' Deprecated function(s) in the webchem package
#'
#' These functions are provided for compatibility with older version of
#' the webchem package. They may eventually be completely
#' removed.
#' @rdname webchem-deprecated
#' @name webchem-deprecated
#' @param ... Parameters to be passed to the modern version of the function
#' @export
#' @aliases cid_compinfo
#' @details Deprecated functions are:
#' \tabular{rl}{
#' \code{pc_prop} \tab was formerly \code{\link{cid_compinfo}}\cr
#' \code{bcpc_query} \tab was formerly \code{\link{aw_query}}\cr
#' }
cid_compinfo <- function(...) {
.Deprecated("pc_prop", package = "webchem")
cid_compinfo(...)
}
#' @rdname webchem-deprecated
#' @aliases aw_query
#' @export
aw_query <- function(...) {
.Deprecated("bcpc_query", package = "webchem")
bcpc_query(...)
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/webchem-deprecated.R
|
#' webchem: An R package to retrieve chemical information from the web.
#'
#' Chemical information from around the web. This package interacts with a suite
#' of web APIs for chemical information.
#'
#' @docType package
#' @name webchem
#' @importFrom methods is
#' @importFrom utils globalVariables
if (getRversion() >= "2.15.1")
globalVariables(c("."))
#' Organic plant protection products in the river Jagst / Germany in 2013
#'
#' This dataset comprises environmental monitoring data of organic plant protection products
#' in the year 2013 in the river Jagst, Germany.
#' The data is publicly available and can be retrieved from the
#' LUBW Landesanstalt für Umwelt, Messungen und Naturschutz Baden-Württemberg.
#' It has been preprocessed and comprises measurements of 34 substances.
#' Substances without detects have been removed.
#' on 13 sampling occasions.
#' Values are given in ug/L.
#'
#' @format A data frame with 442 rows and 4 variables:
#' \describe{
#' \item{date}{sampling data}
#' \item{substance}{substance names}
#' \item{value}{concentration in ug/L}
#' \item{qual}{qualifier, indicating values < LOQ}
#' }
#' @source \url{https://udo.lubw.baden-wuerttemberg.de/public/pages/home/index.xhtml}
"jagst"
#' Acute toxicity data from U.S. EPA ECOTOX
#'
#' This dataset comprises acute ecotoxicity data of 124 insecticides.
#' The data is publicly available and can be retrieved from the EPA ECOTOX database
#' (\url{https://cfpub.epa.gov/ecotox/})
#' It comprises acute toxicity data (D. magna, 48h, Laboratory, 48h) and has been
#' preprocessed (remove non-insecticides, aggregate multiple value, keep only numeric data etc).
#'
#' @format A data frame with 124 rows and 2 variables:
#' \describe{
#' \item{cas}{CAS registry number}
#' \item{value}{LC50value}
#' }
#' @source \url{https://cfpub.epa.gov/ecotox/}
"lc50"
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/webchem-package.R
|
#' Get Wikidata Item ID
#'
#' Search www.wikidata.org for wikidata item identifiers. Note that this search
#' is currently not limited to chemical substances, so be sure to check your
#' results.
#'
#' @param query character; The searchterm
#' @param language character; the language to search in
#' @param match character; How should multiple hits be handeled? 'all' returns
#' all matched IDs, 'first' only the first match, 'best' the best matching (by
#' name) ID, 'ask' is a interactive mode and the user is asked for input, na'
#' returns NA if multiple hits are found.
#' @param verbose logical; print message during processing to console?
#'
#' @return if match = 'all' a list with ids, otherwise a dataframe with 4 columns:
#' id, matched text, string distance to match and the queried string
#'
#' @note Only matches in labels are returned.
#'
#' @import jsonlite httr
#' @importFrom utils URLencode URLdecode
#' @importFrom purrr map_df
#' @export
#' @examples
#' \dontrun{
#' get_wdid('Triclosan', language = 'de')
#' get_wdid('DDT')
#' get_wdid('DDT', match = 'all')
#'
#' # multiple inputs
#' comps <- c('Triclosan', 'Glyphosate')
#' get_wdid(comps)
#' }
get_wdid <-
function(query,
match = c('best', 'first', 'all', 'ask', 'na'),
verbose = getOption("verbose"),
language = 'en') {
if (!ping_service("wd")) stop(webchem_message("service_down"))
# language <- 'en'
# query <- 'Triclosan'
match <- match.arg(match)
foo <- function(query, language, match, verbose){
if (is.na(query)){
if (verbose) webchem_message("na")
id <- NA
matched_sub <- NA
} else {
query1 <- URLencode(query, reserved = TRUE)
limit <- 50
qurl <-
paste0("wikidata.org/w/api.php?action=wbsearchentities&format=json&type=item")
qurl <- paste0(qurl, "&language=", language, "&limit=", limit, "&search=", query1)
if (verbose) webchem_message("query", query, appendLF = FALSE)
webchem_sleep(type = 'API')
res <- try(httr::RETRY("GET",
qurl,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(tibble::tibble(query = query, match = NA, wdid = NA))
}
if (verbose) message(httr::message_for_status(res))
if (res$status_code == 200) {
cont <- jsonlite::fromJSON(httr::content(res,
type = "text",
encoding = "utf-8"))
search <- cont$search
if (length(search) == 0) {
if (verbose) webchem_message("not_found")
id <- NA
matched_sub <- NA
} else {
# use only matches on label
search <- search[search$match$type %in% c('label', 'alias'), ]
# # check matches
search <- search[tolower(iconv(search$match$text,
"latin1",
"ASCII",
sub = "")) == tolower(query), ]
id <-
matcher(
search$id,
query = query,
result = search$label,
match = match,
# from = from,
verbose = verbose
)
matched_sub <- names(id)
}
}
else {
id <- NA
matched_sub <- NA
}
}
out <- tibble(query = query, match = matched_sub, wdid = id)
return(out)
}
out <-
purrr::map_df(query,
~ foo(
query = .x,
match = match,
language = language,
verbose = verbose
))
return(out)
}
#! Use SPARQL to search of chemical compounds (P31)?! For a finer / better search?
#' Retrieve identifiers from Wikidata
#'
#' @import jsonlite
#' @import httr
#'
#' @param id character; identifier, as returned by \code{\link{get_wdid}}
#' @param verbose logical; print message during processing to console?
#'
#' @return A data.frame of identifiers. Currently these are 'smiles', 'cas', 'cid', 'einecs', 'csid', 'inchi', 'inchikey',
#' 'drugbank', 'zvg', 'chebi', 'chembl', 'unii', 'lipidmaps', 'swisslipids' and source_url.
#'
#' @note Only matches in labels are returned. If more than one unique hit is found,
#' only the first is returned.
#'
#' @seealso \code{\link{get_wdid}}
#'
#' @references Willighagen, E., 2015. Getting CAS registry numbers out of WikiData. The Winnower.
#' \doi{10.15200/winn.142867.72538}
#'
#' Mitraka, Elvira, Andra Waagmeester, Sebastian Burgstaller-Muehlbacher, et al. 2015
#' Wikidata: A Platform for Data Integration and Dissemination for the Life Sciences and beyond. bioRxiv: 031971.
#'
#' @export
#' @examples
#' \dontrun{
#' id <- c("Q408646", "Q18216")
#' wd_ident(id)
#' }
wd_ident <- function(id, verbose = getOption("verbose")){
if (!ping_service("wd")) stop(webchem_message("service_down"))
# id <- c( "Q163648", "Q18216")
# id <- 'Q408646'
foo <- function(id, verbose){
empty <- as.list(rep(NA, 15))
names(empty) <- c("smiles", "cas", "cid", "einecs", "csid", "inchi",
"inchikey", "drugbank", "zvg", "chebi", "chembl", "unii",
'lipidmaps', 'swisslipids', "source_url")
if (is.na(id)) {
if (verbose) webchem_message("na")
return(empty)
}
baseurl <- 'https://query.wikidata.org/sparql?format=json&query='
props <- c('P233', 'P231', 'P662', 'P232', 'P661', 'P234', 'P235', 'P715', 'P679',
'P683', 'P592', 'P652', 'P2063', 'P8691')
names <- c('smiles', 'cas', 'cid', 'einecs', 'csid', 'inchi', 'inchikey',
'drugbank', 'zvg', 'chebi', 'chembl', 'unii', 'lipidmaps', 'swisslipids')
sparql_head <- paste('PREFIX wd: <http://www.wikidata.org/entity/>',
'PREFIX wdt: <http://www.wikidata.org/prop/direct/>',
'SELECT * WHERE {')
sparql_body <- paste(paste0('OPTIONAL{wd:', id, ' wdt:', props, ' ?', names, ' .}'),
collapse = ' ')
sparql <- paste(sparql_head, sparql_body, '}')
qurl <- paste0(baseurl, sparql)
qurl <- URLencode(qurl)
webchem_sleep(type = 'API')
if (verbose) webchem_message("query", id, appendLF = FALSE)
res <- try(httr::RETRY("GET",
qurl,
httr::user_agent(webchem_url()),
terminate_on = 404,
quiet = TRUE), silent = TRUE)
if (inherits(res, "try-error")) {
if (verbose) webchem_message("service_down")
return(empty)
}
if (verbose) message(httr::message_for_status(res))
if (res$status_code == 200) {
tmp <- fromJSON(content(res, as = "text"))
vars_out <- tmp$head$vars
out <- tmp$results$bindings
if (length(out) == 0) {
if (verbose) webchem_message("not_found")
out <- as.list(rep(NA, 15))
names(out) <- c(vars_out, 'source_url')
return(out)
}
if (nrow(out) > 1) {
message("More then one unique entry found! Returning first.")
out <- out[1, ]
}
out <- lapply(out, '[[', 'value')
# check for missing entries and add to out-list
miss <- names[!names %in% names(out)]
for (i in miss) {
out[[i]] <- NA
}
out <- out[names]
out[['source_url']] <- paste0('https://www.wikidata.org/wiki/', id)
out <- unlist(out)
return(out)
}
else {
return(empty)
}
}
# ugly fixing to return data.frame
out <- data.frame(t(sapply(id, foo,verbose = verbose)), stringsAsFactors = FALSE, row.names = seq_along(id))
out[['query']] <- id
# even more ugly...
out <- data.frame(t(apply(out, 1, unlist)), stringsAsFactors = FALSE)
class(out) <- c('wd_ident', 'data.frame')
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/webchem/R/wikidata.R
|
---
title: "Getting started with webchem"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Getting started with webchem}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
<!-- Only edit webchem.Rmd.orig and compile using the script in vignettes/precompile.R -->
```r
library(webchem)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
```
The `lc50` dataset provided with `webchem` contains acute ecotoxicity of 124 insecticides. We'll work with a subset of these to obtain chemical names and octanal/water partitioning coefficients from PubChem, and gas chromatography retention indices from the NIST Web Book.
```r
head(lc50)
#> cas value
#> 4 50-29-3 12.415277
#> 12 52-68-6 1.282980
#> 15 55-38-9 12.168138
#> 18 56-23-5 35000.000000
#> 21 56-38-2 1.539119
#> 36 57-74-9 98.400000
lc50_sub <- lc50[1:15, ]
```
## Getting Identifiers
Usually a `webchem` workflow starts with translating and retrieving chemical identifiers since most chemical information databases use their own internal identifiers.
First, we will covert CAS numbers to InChIKey identifiers using the Chemical Translation Service. Then, we'll use these InChiKeys to get Pubchem CompoundID numbers, to use for retrieving chemical properties from PubChem.
```r
lc50_sub$inchikey <- unlist(cts_convert(lc50_sub$cas, from = "CAS", to = "InChIKey", match = "first", verbose = FALSE))
head(lc50_sub)
#> cas value inchikey
#> 4 50-29-3 12.415277 YVGGHNCTFXOJCH-UHFFFAOYSA-N
#> 12 52-68-6 1.282980 NFACJZMKEDPNKN-UHFFFAOYSA-N
#> 15 55-38-9 12.168138 PNVJTZOFSHSLTO-UHFFFAOYSA-N
#> 18 56-23-5 35000.000000 VZGDMQKNWNREIO-UHFFFAOYSA-N
#> 21 56-38-2 1.539119 LCCNCVORNKJIRZ-UHFFFAOYSA-N
#> 36 57-74-9 98.400000 BIWJNBZANLAXMG-UHFFFAOYSA-N
any(is.na(lc50_sub$inchikey))
#> [1] FALSE
```
Great, now we can retrieve PubChem CIDs. All `get_*()` functions return a data frame containing the query and the retrieved identifier. We can merge this with our dataset with `dplyr::full_join()`
```r
x <- get_cid(lc50_sub$inchikey, from = "inchikey", match = "first", verbose = FALSE)
library(dplyr)
lc50_sub2 <- full_join(lc50_sub, x, by = c("inchikey" = "query"))
head(lc50_sub2)
#> cas value inchikey cid
#> 1 50-29-3 12.415277 YVGGHNCTFXOJCH-UHFFFAOYSA-N 3036
#> 2 52-68-6 1.282980 NFACJZMKEDPNKN-UHFFFAOYSA-N 5853
#> 3 55-38-9 12.168138 PNVJTZOFSHSLTO-UHFFFAOYSA-N 3346
#> 4 56-23-5 35000.000000 VZGDMQKNWNREIO-UHFFFAOYSA-N 5943
#> 5 56-38-2 1.539119 LCCNCVORNKJIRZ-UHFFFAOYSA-N 991
#> 6 57-74-9 98.400000 BIWJNBZANLAXMG-UHFFFAOYSA-N 5993
```
## Retrieving Chemical Properties
Functions that query chemical information databases begin with a prefix that matches the database. For example, functions to query PubChem begin with `pc_` and functions to query ChemSpider begin with `cs_`. In this example, we'll get the names and log octanol/water partitioning coefficients for each compound using PubChem, and the number of aromatic rings within the chemical structure using ChEMBL.
```r
y <- pc_prop(lc50_sub2$cid, properties = c("IUPACName", "XLogP"))
y$CID <- as.character(y$CID)
lc50_sub3 <- full_join(lc50_sub2, y, by = c("cid" = "CID"))
head(lc50_sub3)
#> cas value inchikey cid
#> 1 50-29-3 12.415277 YVGGHNCTFXOJCH-UHFFFAOYSA-N 3036
#> 2 52-68-6 1.282980 NFACJZMKEDPNKN-UHFFFAOYSA-N 5853
#> 3 55-38-9 12.168138 PNVJTZOFSHSLTO-UHFFFAOYSA-N 3346
#> 4 56-23-5 35000.000000 VZGDMQKNWNREIO-UHFFFAOYSA-N 5943
#> 5 56-38-2 1.539119 LCCNCVORNKJIRZ-UHFFFAOYSA-N 991
#> 6 57-74-9 98.400000 BIWJNBZANLAXMG-UHFFFAOYSA-N 5993
#> IUPACName
#> 1 1-chloro-4-[2,2,2-trichloro-1-(4-chlorophenyl)ethyl]benzene
#> 2 2,2,2-trichloro-1-dimethoxyphosphorylethanol
#> 3 dimethoxy-(3-methyl-4-methylsulfanylphenoxy)-sulfanylidene-lambda5-phosphane
#> 4 tetrachloromethane
#> 5 diethoxy-(4-nitrophenoxy)-sulfanylidene-lambda5-phosphane
#> 6 1,3,4,7,8,9,10,10-octachlorotricyclo[5.2.1.02,6]dec-8-ene
#> XLogP
#> 1 6.9
#> 2 0.5
#> 3 4.1
#> 4 2.8
#> 5 3.8
#> 6 4.9
```
The IUPAC names are long and unwieldy, and one could use `pc_synonyms()` to choose better names. Several other functions return synonyms as well, even though they are not explicitly translator type functions. We'll see an example of that next.
Many of the chemical databases `webchem` can query contain vast amounts of information in a variety of structures. Therefore, some `webchem` functions return nested lists rather than data frames. `chembl_query()` is one such function.
To look up entries in ChEMBL we need ChEMBL ID-s. These can be found on the PubChem page of each compound within the ChEMBL ID section and can be programmatically retrieved using `pc_sect()`.
```r
lc50_sub3$chembl_id <- pc_sect(x$cid, "ChEMBL ID")$Result
out <- chembl_query(lc50_sub3$chembl_id, verbose = FALSE)
```
`out` is a nested list which you can inspect with `View()`. It has an element for each query, and within each query, many elements corresponding to different properties in the database. To extract a single property from all queries, we need to use a mapping function such as `sapply()`.
```r
lc50_sub3$aromatic_rings <- sapply(out, function(y) {
# return NA if entry cannot be found in ChEMBL
if (length(y) == 1 && is.na(y)) return(NA)
# return the number of aromatic rings
y$molecule_properties$aromatic_rings
})
lc50_sub3$common_name <- sapply(out, function(y) {
# return NA if entry cannot be found in ChEMBL
if (length(y) == 1 && is.na(y)) return(NA)
# return preferred name
ifelse(!is.null(y$pref_name), y$pref_name, NA)
})
```
```r
#tidy up columns
lc50_done <- dplyr::select(lc50_sub3, common_name, cas, inchikey, XLogP, aromatic_rings)
head(lc50_done)
#> common_name cas inchikey XLogP aromatic_rings
#> 1 CHLOROPHENOTHANE 50-29-3 YVGGHNCTFXOJCH-UHFFFAOYSA-N 6.9 2
#> 2 TRICHLORFON 52-68-6 NFACJZMKEDPNKN-UHFFFAOYSA-N 0.5 0
#> 3 FENTHION 55-38-9 PNVJTZOFSHSLTO-UHFFFAOYSA-N 4.1 1
#> 4 CARBON TETRACHLORIDE 56-23-5 VZGDMQKNWNREIO-UHFFFAOYSA-N 2.8 0
#> 5 PARATHION 56-38-2 LCCNCVORNKJIRZ-UHFFFAOYSA-N 3.8 1
#> 6 CHLORDANE 57-74-9 BIWJNBZANLAXMG-UHFFFAOYSA-N 4.9 0
```
|
/scratch/gouwar.j/cran-all/cranData/webchem/inst/doc/webchem.Rmd
|
# Precomplie vignettes locally
# More info here: https://ropensci.org/technotes/2019/12/08/precompute-vignettes/
library(knitr)
knit("vignettes/webchem.Rmd.orig", "vignettes/webchem.Rmd") #Get Started
|
/scratch/gouwar.j/cran-all/cranData/webchem/vignettes/precompile.R
|
---
title: "Getting started with webchem"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Getting started with webchem}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
<!-- Only edit webchem.Rmd.orig and compile using the script in vignettes/precompile.R -->
```r
library(webchem)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
```
The `lc50` dataset provided with `webchem` contains acute ecotoxicity of 124 insecticides. We'll work with a subset of these to obtain chemical names and octanal/water partitioning coefficients from PubChem, and gas chromatography retention indices from the NIST Web Book.
```r
head(lc50)
#> cas value
#> 4 50-29-3 12.415277
#> 12 52-68-6 1.282980
#> 15 55-38-9 12.168138
#> 18 56-23-5 35000.000000
#> 21 56-38-2 1.539119
#> 36 57-74-9 98.400000
lc50_sub <- lc50[1:15, ]
```
## Getting Identifiers
Usually a `webchem` workflow starts with translating and retrieving chemical identifiers since most chemical information databases use their own internal identifiers.
First, we will covert CAS numbers to InChIKey identifiers using the Chemical Translation Service. Then, we'll use these InChiKeys to get Pubchem CompoundID numbers, to use for retrieving chemical properties from PubChem.
```r
lc50_sub$inchikey <- unlist(cts_convert(lc50_sub$cas, from = "CAS", to = "InChIKey", match = "first", verbose = FALSE))
head(lc50_sub)
#> cas value inchikey
#> 4 50-29-3 12.415277 YVGGHNCTFXOJCH-UHFFFAOYSA-N
#> 12 52-68-6 1.282980 NFACJZMKEDPNKN-UHFFFAOYSA-N
#> 15 55-38-9 12.168138 PNVJTZOFSHSLTO-UHFFFAOYSA-N
#> 18 56-23-5 35000.000000 VZGDMQKNWNREIO-UHFFFAOYSA-N
#> 21 56-38-2 1.539119 LCCNCVORNKJIRZ-UHFFFAOYSA-N
#> 36 57-74-9 98.400000 BIWJNBZANLAXMG-UHFFFAOYSA-N
any(is.na(lc50_sub$inchikey))
#> [1] FALSE
```
Great, now we can retrieve PubChem CIDs. All `get_*()` functions return a data frame containing the query and the retrieved identifier. We can merge this with our dataset with `dplyr::full_join()`
```r
x <- get_cid(lc50_sub$inchikey, from = "inchikey", match = "first", verbose = FALSE)
library(dplyr)
lc50_sub2 <- full_join(lc50_sub, x, by = c("inchikey" = "query"))
head(lc50_sub2)
#> cas value inchikey cid
#> 1 50-29-3 12.415277 YVGGHNCTFXOJCH-UHFFFAOYSA-N 3036
#> 2 52-68-6 1.282980 NFACJZMKEDPNKN-UHFFFAOYSA-N 5853
#> 3 55-38-9 12.168138 PNVJTZOFSHSLTO-UHFFFAOYSA-N 3346
#> 4 56-23-5 35000.000000 VZGDMQKNWNREIO-UHFFFAOYSA-N 5943
#> 5 56-38-2 1.539119 LCCNCVORNKJIRZ-UHFFFAOYSA-N 991
#> 6 57-74-9 98.400000 BIWJNBZANLAXMG-UHFFFAOYSA-N 5993
```
## Retrieving Chemical Properties
Functions that query chemical information databases begin with a prefix that matches the database. For example, functions to query PubChem begin with `pc_` and functions to query ChemSpider begin with `cs_`. In this example, we'll get the names and log octanol/water partitioning coefficients for each compound using PubChem, and the number of aromatic rings within the chemical structure using ChEMBL.
```r
y <- pc_prop(lc50_sub2$cid, properties = c("IUPACName", "XLogP"))
y$CID <- as.character(y$CID)
lc50_sub3 <- full_join(lc50_sub2, y, by = c("cid" = "CID"))
head(lc50_sub3)
#> cas value inchikey cid
#> 1 50-29-3 12.415277 YVGGHNCTFXOJCH-UHFFFAOYSA-N 3036
#> 2 52-68-6 1.282980 NFACJZMKEDPNKN-UHFFFAOYSA-N 5853
#> 3 55-38-9 12.168138 PNVJTZOFSHSLTO-UHFFFAOYSA-N 3346
#> 4 56-23-5 35000.000000 VZGDMQKNWNREIO-UHFFFAOYSA-N 5943
#> 5 56-38-2 1.539119 LCCNCVORNKJIRZ-UHFFFAOYSA-N 991
#> 6 57-74-9 98.400000 BIWJNBZANLAXMG-UHFFFAOYSA-N 5993
#> IUPACName
#> 1 1-chloro-4-[2,2,2-trichloro-1-(4-chlorophenyl)ethyl]benzene
#> 2 2,2,2-trichloro-1-dimethoxyphosphorylethanol
#> 3 dimethoxy-(3-methyl-4-methylsulfanylphenoxy)-sulfanylidene-lambda5-phosphane
#> 4 tetrachloromethane
#> 5 diethoxy-(4-nitrophenoxy)-sulfanylidene-lambda5-phosphane
#> 6 1,3,4,7,8,9,10,10-octachlorotricyclo[5.2.1.02,6]dec-8-ene
#> XLogP
#> 1 6.9
#> 2 0.5
#> 3 4.1
#> 4 2.8
#> 5 3.8
#> 6 4.9
```
The IUPAC names are long and unwieldy, and one could use `pc_synonyms()` to choose better names. Several other functions return synonyms as well, even though they are not explicitly translator type functions. We'll see an example of that next.
Many of the chemical databases `webchem` can query contain vast amounts of information in a variety of structures. Therefore, some `webchem` functions return nested lists rather than data frames. `chembl_query()` is one such function.
To look up entries in ChEMBL we need ChEMBL ID-s. These can be found on the PubChem page of each compound within the ChEMBL ID section and can be programmatically retrieved using `pc_sect()`.
```r
lc50_sub3$chembl_id <- pc_sect(x$cid, "ChEMBL ID")$Result
out <- chembl_query(lc50_sub3$chembl_id, verbose = FALSE)
```
`out` is a nested list which you can inspect with `View()`. It has an element for each query, and within each query, many elements corresponding to different properties in the database. To extract a single property from all queries, we need to use a mapping function such as `sapply()`.
```r
lc50_sub3$aromatic_rings <- sapply(out, function(y) {
# return NA if entry cannot be found in ChEMBL
if (length(y) == 1 && is.na(y)) return(NA)
# return the number of aromatic rings
y$molecule_properties$aromatic_rings
})
lc50_sub3$common_name <- sapply(out, function(y) {
# return NA if entry cannot be found in ChEMBL
if (length(y) == 1 && is.na(y)) return(NA)
# return preferred name
ifelse(!is.null(y$pref_name), y$pref_name, NA)
})
```
```r
#tidy up columns
lc50_done <- dplyr::select(lc50_sub3, common_name, cas, inchikey, XLogP, aromatic_rings)
head(lc50_done)
#> common_name cas inchikey XLogP aromatic_rings
#> 1 CHLOROPHENOTHANE 50-29-3 YVGGHNCTFXOJCH-UHFFFAOYSA-N 6.9 2
#> 2 TRICHLORFON 52-68-6 NFACJZMKEDPNKN-UHFFFAOYSA-N 0.5 0
#> 3 FENTHION 55-38-9 PNVJTZOFSHSLTO-UHFFFAOYSA-N 4.1 1
#> 4 CARBON TETRACHLORIDE 56-23-5 VZGDMQKNWNREIO-UHFFFAOYSA-N 2.8 0
#> 5 PARATHION 56-38-2 LCCNCVORNKJIRZ-UHFFFAOYSA-N 3.8 1
#> 6 CHLORDANE 57-74-9 BIWJNBZANLAXMG-UHFFFAOYSA-N 4.9 0
```
|
/scratch/gouwar.j/cran-all/cranData/webchem/vignettes/webchem.Rmd
|
#' Parse the content type header string to return the content type and boundary
#'
#' @param x A string containing the content type header.
#' @return A named list with "content_type" and "boundary" if boundary is present.
#' @examples
#' parseContentTypeHeader("application/x-www-form-urlencoded")
parseContentTypeHeader <- function(x){
x <- strsplit(x, "; ", fixed = TRUE)[[1]]
return(
if(length(x) == 1){
list(
"content_type" = x
)
}else{
list(
"content_type" = x[1],
"boundary" = strsplit(x[2], "=", fixed = TRUE)[[1]][2]
)
}
)
}
#' Parse a query string
#'
#' @param x A string containing the query string.
#' @param split A string, the character to split by.
#' @param consolidate TRUE/FALSE, if TRUE, consolidates items with the same name.
#' @return A named list.
#' @examples
#' parseQueryString("?form_id=example&col_name=Test+String")
parseQueryString <- function(
x,
split = "&",
consolidate = TRUE
){
x <- base::sub(pattern = "^[?]", replacement = "", x)
x <- chartr("+", " ", x)
x <- strsplit(x, split, fixed = TRUE)[[1]]
args <- lapply(x, function(y) {
httpuv::decodeURIComponent(strsplit(y, "=", fixed = TRUE)[[1]])
})
values <- lapply(args, `[`, 2)
names(values) <- vapply(args, `[`, character(1), 1)
if(consolidate){
value_names <- names(values)
uvalue_names <- unique(value_names)
if(length(uvalue_names) < length(value_names)){
values <- lapply(uvalue_names, function(y){
return(unlist(values[names(values) %in% y]))
})
names(values) <- uvalue_names
}
}
return(
values
)
}
#' Helper function for parseMultiPartFormData
#'
#' @param x A vector, a chunk of multi-part form data to parse.
#' @return A named list.
#' @examples
#' parseMultiPartFormParams(c("Content-Disposition: form-data; name=\"form_name\"", "", "Example"))
parseMultiPartFormParams <- function(
x
){
meta_chunk <- strsplit(x[1], "; ", fixed = TRUE)[[1]]
p_list <- list()
if(meta_chunk[1] == "Content-Disposition: form-data"){
p_name <- strsplit(meta_chunk[2], "=")[[1]][2]
p_name <- gsub('\"', "", p_name, fixed = TRUE)
if(grepl("Content-Type", x[2], fixed = TRUE)){
filename <- unlist(strsplit(meta_chunk[3], "="))[2]
filename <- gsub('\"', "", filename)
x_data <- x[4:length(x)]
p_list <- list(
list(
"filename" = filename,
"data" = x_data
)
)
names(p_list) <- p_name
}else{
x_data <- x[3:length(x)]
p_list <- list(
x_data
)
names(p_list) <- p_name
}
}
return(p_list)
}
#' Parse multi-part form data
#'
#' @param x A vector.
#' @param boundary A string, the boundary used for the multi-part form data
#' @return A named list.
#' @examples
#' parseMultiPartFormData(
#' x = c(
#' "------WebKitFormBoundaryfBloeH49iOmYtO5A",
#' "Content-Disposition: form-data; name=\"form_name\"",
#' "",
#' "Example",
#' "------WebKitFormBoundaryfBloeH49iOmYtO5A",
#' "Content-Disposition: form-data; name=\"form_id\"",
#' "",
#' "test",
#' "------WebKitFormBoundaryfBloeH49iOmYtO5A",
#' "Content-Disposition: form-data; name=\"desktop_file\"; filename=\"limit_type.csv\"",
#' "Content-Type: text/csv",
#' "",
#' "limit_type",
#' "Aggregate",
#' "Occurrence",
#' "------WebKitFormBoundaryfBloeH49iOmYtO5A--"
#' ),
#' boundary = parseContentTypeHeader(
#' "multipart/form-data; boundary=----WebKitFormBoundaryfBloeH49iOmYtO5A")[['boundary']]
#' )
parseMultiPartFormData <- function(
x,
boundary
){
boundary <- gsub("-", "", boundary)
boundaries <- which(grepl(boundary, x, fixed = TRUE))
params <- list()
for(i in 1:length(boundaries)){
if(boundaries[i] == length(x)){
}else{
start <- boundaries[i] + 1
end <- if(i == length(boundaries)){length(x)}else{boundaries[i+1] - 1}
chunk <- x[start:end]
chunk_params <- parseMultiPartFormParams(chunk)
params <- c(params, chunk_params)
}
}
return(params)
}
#' Parse a HTTP request
#'
#' @param x The body of the HTTP request
#' @param content_type_header A string containing the content type header.
#' @param consolidate TRUE/FALSE, if TRUE, consolidates items with the same name.
#' @return A named list.
#' @examples
#' parseHTTP("?form_id=example&col_name=Test+String", "application/x-www-form-urlencoded")
parseHTTP <- function(
x,
content_type_header = NULL,
consolidate = TRUE
){
return(
if(is.null(content_type_header)){
parseQueryString(x, consolidate)
}else{
c_type <- parseContentTypeHeader(content_type_header)
if(c_type[["content_type"]] == "application/x-www-form-urlencoded"){
parseQueryString(x, consolidate = consolidate)
}else if(c_type[["content_type"]] == "multipart/form-data"){
parseMultiPartFormData(x, boundary = c_type[["boundary"]])
}
}
)
}
#' Add a prefix to an id
#'
#' @param id A string to add a prefix to.
#' @param prefix A string, the prefix to add.
#' @param sep A string, the separator to use.
#' @return A string.
#' @examples
#' idAddSuffix("example", 1)
idAddPrefix <- function(prefix, id, sep = "X"){
return(
paste0(prefix, sep, id)
)
}
#' Remove a prefix from an id
#'
#' @param id A string to remove a prefix from.
#' @param split A string, the separator to use for splitting the id.
#' @param position A integer vector, the position of the split string to return.
#' @return A vector.
#' @examples
#' idParsePrefix(idAddPrefix("example", 1))
idParsePrefix <- function(id, split = "X", position = 2){
return(
strsplit(id, split = split, fixed = TRUE)[[1]][position]
)
}
#' Add a suffix to an id
#'
#' @param id A string to add a suffix to.
#' @param suffix A string, the suffix to add.
#' @param sep A string, the separator to use.
#' @return A string.
#' @examples
#' idAddSuffix("example", 1)
idAddSuffix <- function(id, suffix, sep = "-"){
return(
paste0(id, sep, suffix)
)
}
#' Remove a suffix from an id
#'
#' @param id A string to remove a suffix from.
#' @param split A string, the separator to use for splitting the id.
#' @param position A integer vector, the position of the split string to return.
#' @return A vector.
#' @examples
#' idParseSuffix(idAddSuffix("example", 1))
idParseSuffix <- function(id, split = "-", position = 1){
return(
strsplit(id, split = split, fixed = TRUE)[[1]][position]
)
}
#' Add a prefix and suffix to an id
#'
#' @param prefix A string, the prefix to add.
#' @param id A string to add a prefix and suffix to.
#' @param suffix A string, the suffix to add.
#' @param prefix_sep A string, the prefix separator to use.
#' This should be different than suffix_sep.
#' @param suffix_sep A string, the suffix separator to use.
#' This should be different than prefix_sep.
#' @return A string.
#' @examples
#' idAddAffixes("group1", "example", 1)
idAddAffixes <- function(prefix, id, suffix, prefix_sep = "X", suffix_sep = "-"){
return(
paste0(prefix, prefix_sep, id, suffix_sep, suffix)
)
}
#' Remove a prefix and suffix from an id
#'
#' @param id A string to remove a prefix and suffix from.
#' @param split A regular expression to use for splitting the prefix and suffix from the id.
#' @return A named vector, with prefix, id, and suffix returned in that order.
#' @examples
#' idParseAffixes(idAddAffixes("group1", "example", 1))
idParseAffixes <- function(id, split = "X|-"){
x <- strsplit(id, split = split)[[1]]
names(x) <- c("prefix", "id", "suffix")
return(
x
)
}
################################################################################
#' Creates HTML option tags for each position of a list of values and labels by calling HTML5::option(),
#' returning a string of HTML to pass to a select tag through HTML5::select().
#'
#' @param x A vector which will become the value/label for each option. If named, names become values.
#' @param selected A value in the vector passed to mark as the initially selected option in the select tag.
#' @param add_blank Boolean, If TRUE, adds a blank option to the top of x.
#' @return A string, with an option tag each row of x.
#' @examples
#' create_options(
#' x = c("New York", "Los Angeles", "Chicago"),
#' selected = "Chicago"
#' )
create_options <- function(x, selected = c(), add_blank = FALSE){
name_vals <- names(x)
if(add_blank == TRUE){
x <- c("", x)
if(length(name_vals) > 0){
name_vals <- c("", name_vals)
}
}
x <- unname(x)
selected <- x %in% selected
if(length(x) > 1){
return(
if(length(name_vals) > 0){
option(
attr = list(
"value" = name_vals,
"label" = x,
"selected" = selected
),
separate = TRUE
)
}else{
option(
attr = list(
"value" = x,
"label" = x,
"selected" = selected
),
separate = TRUE
)
}
)
}else if(length(x) == 1){
return(
if(length(name_vals) > 0){
option(
attr = list(
"value" = name_vals,
"label" = x,
"selected" = selected
)
)
}else{
option(
attr = list(
"value" = x,
"label" = x,
"selected" = selected
)
)
}
)
}else{
return(
option(value = "", label = "")
)
}
}
#' Conveniently create HTTP server using httpuv::startServer() or httpuv::runServer().
#'
#' @param host A string that is a valid IPv4 or IPv6 address that is owned by this server, which the application will listen on.
#' "0.0.0.0" represents all IPv4 addresses and "::/0" represents all IPv6 addresses. Refer to host parameter of httpuv::startServer() for more details.
#' @param port The port number to listen on. Refer to port parameter of httpuv::startServer() for more details.
#' @param persistent TRUE/FALSE. If FALSE, calls httpuv::startServer(), which returns back to the R session
#' (and would therefore not work with launching a persistent server through a system service as the R session would continue and likely exit/end).
#' If TRUE, calls httpuv::runServer(), which does not return to the R session unless an error or
#' interruption occurs and is suitable for use with system services to start or stop a server.
#' @param async TRUE/FALSE, if TRUE, dynamic path requests will be served asynchronously using multicore evaluation, if possible. This is an
#' advanced option and might make it more confusing to debug your app.
#' @param static A named list, names should be URL paths, values should be paths to the files to be served statically (such as a HTML file saved somewhere)
#' or staticPath objects if lapply_staticPath is FALSE.
#' @param dynamic A named list, names should be URL paths, values should be named alists (use alist instead of list) with alist names equaling a
#' HTTP method (such as "GET" or "POST") and the values being expressions that when evaluated return a named list with valid entries
#' for status, headers, and body as specified by httpuv::startServer(). Refer to httpuv::startServer() for more details on what can be returned
#' as the response.
#' ex. list("/" = alist("GET" = get_function(req), "POST" = post_function(req)))
#' @param lapply_staticPath TRUE/FALSE, if TRUE, httpuv::staticPath will be applied to each element of static to create staticPath objects.
#' @param static_path_options A named list, passed to httpuv::staticPathOptions.
#' @return A HTTP web server on the specified host and port.
#' @details serveHTTP is a convenient way to start a HTTP server that works for both static and dynamically created pages.
#' It offers a simplified and organized interface to httpuv::startServer()/httpuv::runServer() that makes serving static and
#' dynamic pages easier. For dynamic pages, the expression evaluated when a browser requests a dynamically served path should
#' likely be an expression/function that has "req" as a parameter. Per the Rook specification implemented by httpuv, "req" is
#' the R environment in which browser request information is collected. Therefore, to access HTTP request headers, inputs, etc. in a function
#' served by a dynamic path, "req" should be a parameter of that function. For the dynamic parameter of serveHTTP,
#' list("/" = alist("GET" = get_homepage(req))) would be a suitable way to call the function get_homepage(req) when the root path of a
#' website is requested with the GET method. The req environment has the following variables:
#' request_method = req$REQUEST_METHOD,
#' script_name = req$SCRIPT_NAME,
#' path_info = req$PATH_INFO,
#' query_string = req$QUERY_STRING,
#' server_name = req$SERVER_NAME,
#' server_port = req$SERVER_PORT,
#' headers = req$HEADERS,
#' rook_input = req[["rook.input"]]$read_lines(),
#' rook_version = req[["rook.version"]]$read_lines(),
#' rook_url_scheme = req[["rook.url_scheme"]]$read_lines(),
#' rook_error_stream = req[["rook.errors"]]$read_lines()
#'
#' @examples
#' # Run both functions and go to http://127.0.0.1:5001/ in a web browser
#' get_example <- function(req){
#'
#' html <- doctype(
#' html(
#' head(),
#' body(
#' h1("Hello"),
#' p("Here is a list of some of the variables included in the req environment
#' that were associated with this request:"),
#' ul(
#' li(paste0("req$REQUEST_METHOD = ", req$REQUEST_METHOD)),
#' li(paste0("req$SCRIPT_NAME = ", req$SCRIPT_NAME)),
#' li(paste0("req$PATH_INFO = ", req$PATH_INFO)),
#' li(paste0("req$QUERY_STRING = ", req$QUERY_STRING)),
#' li(paste0("req$SERVER_NAME = ", req$SERVER_NAME)),
#' li(paste0("req$SERVER_PORT = ", req$SERVER_PORT))
#' ),
#' p("You can use parseQueryString to deal with inputs passed through query strings as
#' well as passed through the input stream."),
#' p("params <- parseQueryString(req[[\"rook.input\"]]$read_lines()) will give you a
#' named list of parameters. See also parseHTTP.")
#' )
#' )
#' )
#' return(
#' list(
#' status = 200L,
#' headers = list('Content-Type' = 'text/html'),
#' body = html
#' )
#' )
#' }
#'
#' serveHTTP(
#' host = "127.0.0.1",
#' port = 5001,
#' persistent = FALSE,
#' static = list(),
#' dynamic = list(
#' "/" = alist(
#' "GET" = get_example(req)
#' )
#' )
#' )
serveHTTP <- function(
host = "127.0.0.1",
port = 5001,
persistent = FALSE,
async = FALSE,
static = list(),
dynamic = list(),
lapply_staticPath = TRUE,
static_path_options = list(
indexhtml = TRUE,
fallthrough = FALSE,
html_charset = "utf-8",
headers = list(),
validation = character(0),
exclude = FALSE
)
){
if(length(static) > 0 & lapply_staticPath){
static <- lapply(static, staticPath)
}
if(length(dynamic) > 0){
for(i in names(dynamic)){
static[[i]] <- excludeStaticPath()
}
}
valid_dynamic_paths <- names(dynamic)
if(persistent == TRUE){
if(async){
future::plan(future::multicore)
return(
runServer(
host,
port,
app = list(
call = function(req) {
if(req$PATH_INFO %in% valid_dynamic_paths){
promises::as.promise(
future::future({
eval(dynamic[[req$PATH_INFO]][[req$REQUEST_METHOD]])
})
)
}else{
list(
status = 404,
headers = list(
'Content-Type' = 'text/html'
),
body = "404. Page not found."
)
}
},
staticPaths = static,
staticPathOptions = do.call(staticPathOptions, static_path_options)
)
)
)
}else{
return(
runServer(
host,
port,
app = list(
call = function(req) {
if(req$PATH_INFO %in% valid_dynamic_paths){
eval(dynamic[[req$PATH_INFO]][[req$REQUEST_METHOD]])
}else{
list(
status = 404,
headers = list(
'Content-Type' = 'text/html'
),
body = "404. Page not found."
)
}
},
staticPaths = static,
staticPathOptions = do.call(staticPathOptions, static_path_options)
)
)
)
}
}else{
if(async){
future::plan(future::multicore)
return(
startServer(
host,
port,
app = list(
call = function(req) {
if(req$PATH_INFO %in% valid_dynamic_paths){
promises::as.promise(
future::future({
eval(dynamic[[req$PATH_INFO]][[req$REQUEST_METHOD]])
})
)
}else{
list(
status = 404,
headers = list(
'Content-Type' = 'text/html'
),
body = "404. Page not found."
)
}
},
staticPaths = static,
staticPathOptions = do.call(staticPathOptions, static_path_options)
)
)
)
}else{
return(
startServer(
host,
port,
app = list(
call = function(req) {
if(req$PATH_INFO %in% valid_dynamic_paths){
eval(dynamic[[req$PATH_INFO]][[req$REQUEST_METHOD]])
}else{
list(
status = 404,
headers = list(
'Content-Type' = 'text/html'
),
body = "404. Page not found."
)
}
},
staticPaths = static,
staticPathOptions = do.call(staticPathOptions, static_path_options)
)
)
)
}
}
}
#' Stop HTTP server(s) by calling httpuv::stopServer() or httpuv::stopAllServers().
#'
#' @param x A server object that was previously returned from serveHTTP.
#' @param all TRUE/FALSE, if TRUE, calls httpuv::stopAllServers.
#' @return Nothing.
#' @examples
#' endServer(all = TRUE)
endServer <- function(x = NULL, all = FALSE){
if(all == TRUE){
return(stopAllServers())
}else{
return(stopServer(x))
}
}
#' Create a string to use as a placeholder variable in a HTML document.
#'
#' @param x Name of placeholder.
#' @return A string.
#' @examples
#' templateVar("my_dynamic_var")
templateVar <- function(x){
return(paste0("%%rvar-", x, "%%"))
}
#' Find the names of any placeholder variables that exist in a HTML document string.
#'
#' @param x HTML string to check for placeholder.
#' @return A vector of the names of template vars found in the HTML string.
#' @examples
#' findTemplateVars(x = html(body(templateVar("body_var"))))
findTemplateVars <- function(x){
x <- strsplit(x, "%%")[[1]]
vars <- x[grepl("rvar-", x, fixed = TRUE)]
vars <- unlist(lapply(vars, function(x){
return(
strsplit(x, "rvar-", fixed = TRUE)[[1]][2]
)
}), use.names = FALSE)
return(vars)
}
#' Replace placeholder variables in a HTML document string.
#'
#' @param x HTML string with placeholder variables that need to be replaced.
#' @param replacements A named vector or named list. Names should match a template variable acting as a placeholder in a HTML document string
#' and values should be the text to replace the placeholders with.
#' @return A string of HTML with placeholder values replaced.
#' @examples
#' dynamicTemplate(
#' x = html(body(templateVar("body_var"))),
#' replacements = c("%%rvar-body_var%%" = div(p("body replacement")))
#' )
dynamicTemplate <- function(x, replacements = c()){
return(
if(length(replacements) > 0){
stringi::stri_replace_all_fixed(x, pattern = names(replacements), replacement = replacements, vectorize_all = FALSE)
}else{
x
}
)
}
#' Replace placeholder variables in a HTML document string, after reading the file into R.
#'
#' @param file Filepath of the HTML file with placeholder variables that need to be replaced.
#' @param replacements A named vector or named list. Names should match a template variable acting as a placeholder in a HTML document string
#' and values should be the text to replace the placeholders with.
#' @return A string of HTML with placeholder values replaced.
#' @examples
#' tmp <- tempfile()
#' writeLines(html(body(templateVar("body_var"))), con = tmp)
#' dynamicTemplate2(file = tmp, replacements = c("%%rvar-body_var%%" = div(p("body replacement"))))
dynamicTemplate2 <- function(file, replacements = c()){
x <- readr::read_file(file)
return(
if(length(replacements) > 0){
stringi::stri_replace_all_fixed(x, pattern = names(replacements), replacement = replacements, vectorize_all = FALSE)
}else{
x
}
)
}
|
/scratch/gouwar.j/cran-all/cranData/webdeveloper/R/webdeveloper.R
|
is_string <- function(x) {
is.character(x) && length(x) == 1 && !is.na(x)
}
assert_string <- function(x) {
stopifnot(is_string(x))
}
assert_url <- assert_string
assert_filename <- assert_string
assert_count <- function(x) {
stopifnot(
is.numeric(x),
length(x) == 1,
!is.na(x),
x == as.integer(x),
x >= 0
)
}
assert_port <- assert_count
assert_window_size <- assert_count
assert_window_position <- assert_count
assert_timeout <- assert_count
assert_session <- function(x) {
stopifnot(
inherits(x, "Session")
)
}
assert_named <- function(x) {
stopifnot(
length(names(x)) == length(x) && all(names(x) != "")
)
}
assert_unnamed <- function(x) {
stopifnot(
is.null(names(x)) || all(names(x) == "")
)
}
assert_mouse_button <- function(x) {
if (is.numeric(x)) {
x <- as.integer(x)
stopifnot(identical(x, 1L) || identical(x, 2L) || identical(x, 3L))
} else if (is.character(x)) {
stopifnot(is_string(x), x %in% c("left", "middle", "right"))
} else {
stop("Mouse button must be 1, 2, 3, \"left\", \"middle\" or \"right\"")
}
}
|
/scratch/gouwar.j/cran-all/cranData/webdriver/R/assertions.R
|
## This is from the webshot package, see https://github.com/wch/webshot
# Wrapper for utils::download.file which works around a problem with R 3.3.0 and
# 3.3.1. In these versions, download.file(method="libcurl") issues a HEAD
# request to check if a file is available, before sending the GET request. This
# causes problems when downloading attached files from GitHub binary releases
# (like the PhantomJS binaries), because the url for the GET request returns a
# 403 for HEAD requests. See
# https://stat.ethz.ch/pipermail/r-devel/2016-June/072852.html
download <- function(url, destfile, mode = "w") {
if (getRversion() >= "3.3.0") {
download_no_libcurl(url, destfile, mode = mode)
} else if (is_windows() && getRversion() < "3.2") {
# Older versions of R on Windows need setInternet2 to download https.
download_old_win(url, destfile, mode = mode)
} else {
utils::download.file(url, destfile, mode = mode)
}
}
# Adapted from downloader::download, but avoids using libcurl.
download_no_libcurl <- function(url, ...) {
# Windows
if (is_windows()) {
method <- "wininet"
utils::download.file(url, method = method, ...)
} else {
# If non-Windows, check for libcurl/curl/wget/lynx, then call download.file with
# appropriate method.
if (nzchar(Sys.which("wget")[1])) {
method <- "wget"
} else if (nzchar(Sys.which("curl")[1])) {
method <- "curl"
# curl needs to add a -L option to follow redirects.
# Save the original options and restore when we exit.
orig_extra_options <- getOption("download.file.extra")
on.exit(options(download.file.extra = orig_extra_options))
options(download.file.extra = paste("-L", orig_extra_options))
} else if (nzchar(Sys.which("lynx")[1])) {
method <- "lynx"
} else {
stop("no download method found")
}
utils::download.file(url, method = method, ...)
}
}
# Adapted from downloader::download, for R<3.2 on Windows
download_old_win <- function(url, ...) {
# If we directly use setInternet2, R CMD CHECK gives a Note on Mac/Linux
seti2 <- `::`(utils, 'setInternet2')
# Check whether we are already using internet2 for internal
internet2_start <- seti2(NA)
# If not then temporarily set it
if (!internet2_start) {
# Store initial settings, and restore on exit
on.exit(suppressWarnings(seti2(internet2_start)))
# Needed for https. Will get warning if setInternet2(FALSE) already run
# and internet routines are used. But the warnings don't seem to matter.
suppressWarnings(seti2(TRUE))
}
method <- "internal"
# download.file will complain about file size with something like:
# Warning message:
# In download.file(url, ...) : downloaded length 19457 != reported length 200
# because apparently it compares the length with the status code returned (?)
# so we supress that
utils::download.file(url, method = method, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/webdriver/R/download.R
|
#' This is the list in the standard:
#' https://w3c.github.io/webdriver/webdriver-spec.html#keyboard-actions
#' Our list was last updated on 2016-09-30
#' I removed the keys that can be transmitted in a simpler way.
#'
#' TODO: check what is actually supported by the various drivers.
#' A fun task. :)
#' @noRd
NULL
#' Special keys, so that we can refer to them with an easier syntax
#'
#' @examples
#' \dontrun{
#' el$sendKeys("xyz")
#' el$sendKeys("x", "y", "z")
#' el$sendKeys("username", key$enter, "password", key$enter)
#'
#' ## Sending CTRL+A
#' el$sendKeys(key$control, "a")
#'
#' ## Note that modifier keys (control, alt, shift, meta) are sticky,
#' ## they remain in effect in the rest of the sendKeys() call. E.g.
#' ## this sends CTRL+X and CTRL+S
#' el$sendKeys(key$control, "x", "s")
#'
#' ## You will need multiple calls to release control and send CTRL+X S
#' el$sendKeys(key$control, "x")
#' el$sendKeys("s")
#' }
#'
#' @export
key <- list(
"unidentified" = "\uE000",
"cancel" = "\ue001",
"help" = "\ue002",
"backspace" = "\ue003",
"tab" = "\ue004",
"clear" = "\ue005",
"return" = "\ue006",
"enter" = "\ue007",
"shift" = "\ue008",
"control" = "\ue009",
"alt" = "\ue00a",
"pause" = "\ue00b",
"escape" = "\ue00c",
"pageup" = "\ue00e",
"pagedown" = "\ue00f",
"end" = "\ue010",
"home" = "\ue011",
"arrowleft" = "\ue012",
"arrowup" = "\ue013",
"arrowright" = "\ue014",
"arrowdown" = "\ue015",
"insert" = "\ue016",
"delete" = "\ue017",
"f1" = "\ue031",
"f2" = "\ue032",
"f3" = "\ue033",
"f4" = "\ue034",
"f5" = "\ue035",
"f6" = "\ue036",
"f7" = "\ue037",
"f8" = "\ue038",
"f9" = "\ue039",
"f10" = "\ue03a",
"f11" = "\ue03b",
"f12" = "\ue03c",
"meta" = "\ue03d",
"zenkakuhankaku" = "\ue040",
"shift" = "\ue050",
"control" = "\ue051",
"alt" = "\ue052",
"meta" = "\ue053",
"pageup" = "\ue054",
"pagedown" = "\ue055",
"end" = "\ue056",
"home" = "\ue057",
"arrowleft" = "\ue058",
"arrowup" = "\ue059",
"arrowright" = "\ue05a",
"arrowdown" = "\ue05b",
"insert" = "\ue05c",
"delete" = "\ue05d"
)
#' Send keys to element
#'
#' @param self object
#' @param private private object
#' @param ... see examples at \code{\link{key}}
#'
#' @keywords internal
element_sendKeys <- function(self, private, ...) {
keys <- list(...)
if (any(vapply(keys, is.null, TRUE))) {
stop("NULL key in send_key, probably a typo")
}
"!DEBUG element_sendKeys `private$id`"
response <- private$session_private$makeRequest(
"ELEMENT SEND KEYS",
list(value = I(paste(keys, collapse = ""))),
params = list(elementId = private$id)
)
invisible(self)
}
|
/scratch/gouwar.j/cran-all/cranData/webdriver/R/element-keys.R
|
#' HTML element
#'
#' @section Usage:
#' \preformatted{e <- s$findElement(css = NULL, linkText = NULL,
#' partialLinkText = NULL, xpath = NULL)
#'
#' e$findElement(css = NULL, linkText = NULL,
#' partialLinkText = NULL, xpath = NULL)
#' e$findElements(css = NULL, linkText = NULL,
#' partialLinkText = NULL, xpath = NULL)
#'
#' e$isSelected()
#' e$getValue()
#' e$setValue(value)
#' e$getAttribute(name)
#' e$getClass()
#' e$getCssValue(name)
#' e$getText()
#' e$getName()
#' e$getData(name)
#' e$getRect()
#' e$isEnabled()
#' e$click()
#' e$clear()
#' e$sendKeys(...)
#' e$moveMouseTo(xoffset = NULL, yoffset = NULL)
#'
#' e$executeScript(script, ...)
#' e$executeScriptAsync(script, ...)
#' }
#'
#' @section Arguments:
#' \describe{
#' \item{e}{An \code{Element} object.}
#' \item{s}{A \code{\link{Session}} object.}
#' \item{css}{Css selector to find an HTML element.}
#' \item{linkText}{Find \code{<a>} HTML elements based on their
#' \code{innerText}.}
#' \item{partialLinkText}{Find \code{<a>} HTML elements based on their
#' \code{innerText}. It uses partial matching.}
#' \item{xpath}{Find HTML elements using XPath expressions.}
#' \item{name}{String scalar, named of attribute, property or css key.
#' For \code{getData}, the key of the data attribute.}
#' \item{xoffset}{Horizontal offset for mouse movement, relative to the
#' position of the element. If at least of of \code{xoffset} and
#' \code{yoffset} is \code{NULL}, then they are ignored.}
#' \item{yoffset}{Vertical offset for mouse movement, relative to the
#' position of the element. If at least of of \code{xoffset} and
#' \code{yoffset} is \code{NULL}, then they are ignored.}
#' \item{value}{Value to set, a character string.}
#' \item{...}{For \code{sendKeys} the keys to send, see
#' \code{\link{key}}. For \code{executeScript} and
#' \code{executeScriptAsync} argument to supply to the script.}
#' }
#'
#' @section Details:
#'
#' To create \code{Element} objects, you need to use the \code{findElement}
#' (or \code{findElement}) method of a \code{\link{Session}} object.
#'
#' \code{e$findElement()} finds the \emph{next} HTML element from the
#' current one. You need to specify one of the \code{css}, \code{linkText},
#' \code{partialLinkText} and \code{xpath} arguments. It returns a new
#' \code{Element} object.
#'
#' \code{e$findElements()} finds all matching HTML elements starting from
#' the current element. You need to specify one of the \code{css},
#' \code{linkText}, \code{partialLinkText} and \code{xpath} arguments.
#' It returns a list of newly created \code{Element} objects.
#'
#' \code{e$isSelected()} returns \code{TRUE} is the element is currently
#' selected, and \code{FALSE} otherwise.
#'
#' \code{e$getValue()} returns the value of an input element, it is a
#' shorthand for \code{e$getAttribute("value")}.
#'
#' \code{e$setValue()} sets the value of an input element, it is
#' essentially equivalent to sending keys via \code{e$sendKeys()}.
#'
#' \code{e$getAttribute()} queries an arbitrary HTML attribute. It is
#' does not exist, \code{NULL} is returned.
#'
#' \code{e$getClass()} uses \code{e$getAttribute} to parse the
#' \sQuote{class} attribute into a character vector.
#'
#' \code{e$getCssValue()} queries a CSS property of an element.
#'
#' \code{e$getText()} returns the \code{innerText} on an element.
#'
#' \code{e$getName()} returns the tag name of an element.
#'
#' \code{e$getData()} is a shorthand for querying \code{data-*} attributes.
#'
#' \code{e$getRect()} returns the \sQuote{rectangle} of an element. It is
#' named list with components \code{x}, \code{y}, \code{height} and
#' \code{width}.
#'
#' \code{e$isEnabled()} returns \code{TRUE} if the element is enabled,
#' \code{FALSE} otherwise.
#'
#' \code{e$click()} scrolls the element into view, and clicks the
#' in-view centre point of it.
#'
#' \code{e$clear()} scrolls the element into view, and then attempts to
#' clear its value, checkedness or text content.
#'
#' \code{e$sendKeys()} scrolls the form control element into view, and
#' sends the provided keys to it. See \code{\link{key}} for a list of
#' special keys that can be sent.
#'
#' \code{e$uploadFile()} uploads a file to a \code{<input type="file">}
#' element. The \code{filename} argument can contain a single filename,
#' or multiple filenames, for file inputs that can take multiple files.
#'
#' \code{e$moveMouseTo()} moves the mouse cursor to the element, with
#' the specified offsets. If one or both offsets are \code{NULL}, then
#' it places the cursor on the center of the element. If the element is
#' not on the screen, then is scrolls it into the screen first.
#'
#' \code{e$executeScript()} and \code{e$executeScriptAsync()}
#' call the method of the same name on the \code{\link{Session}} object.
#' The first argument of the script (\code{arguments[0]}) will always
#' hold the element object itself.
#'
#' @name Element
#' @importFrom R6 R6Class
NULL
Element <- R6Class(
"Element",
public = list(
initialize = function(id, session, session_private)
element_initialize(self, private, id, session, session_private),
findElement = function(css = NULL, linkText = NULL,
partialLinkText = NULL, xpath = NULL)
element_findElement(self, private, css, linkText,
partialLinkText, xpath),
findElements = function(css = NULL, linkText = NULL,
partialLinkText = NULL, xpath = NULL)
element_findElements(self, private, css, linkText,
partialLinkText, xpath),
isSelected = function()
element_isSelected(self, private),
getValue = function()
element_getValue(self, private),
setValue = function(value)
element_setValue(self, private, value),
getAttribute = function(name)
element_getAttribute(self, private, name),
getClass = function()
element_getClass(self, private),
getCssValue = function(name)
element_getCssValue(self, private, name),
getText = function()
element_getText(self, private),
getName = function()
element_getName(self, private),
getData = function(name)
element_getData(self, private, name),
getRect = function()
element_getRect(self, private),
isEnabled = function()
element_id_enabled(self, private),
click = function()
element_click(self, private),
clear = function()
element_clear(self, private),
sendKeys = function(...)
element_sendKeys(self, private, ...),
uploadFile = function(filename)
element_uploadFile(self, private, filename),
moveMouseTo = function(xoffset = NULL, yoffset = NULL)
element_moveMouseTo(self, private, xoffset, yoffset),
executeScript = function(script, ...)
element_executeScript(self, private, script, ...),
executeScriptAsync = function(script, ...)
element_executeScriptAsync(self, private, script, ...)
),
private = list(
id = NULL,
session = NULL,
session_private = NULL
)
)
element_initialize <- function(self, private, id, session,
session_private) {
assert_string(id)
assert_session(session)
private$id <- id
private$session <- session
private$session_private <- session_private
invisible(self)
}
element_findElement <- function(self, private, css, linkText,
partialLinkText, xpath) {
"!DEBUG element_findElement `css %||% linkText %||% partialLinkText %||% xpath`"
find_expr <- parse_find_expr(css, linkText, partialLinkText, xpath)
response <- private$session_private$makeRequest(
"FIND ELEMENT FROM ELEMENT",
list(
using = find_expr$using,
value = find_expr$value
),
list(elementId = private$id)
)
Element$new(
id = response$value$ELEMENT,
session = private$session,
session_private = private$session_private
)
}
element_findElements <- function(self, private, css, linkText,
partialLinkText, xpath) {
"!DEBUG element_findElements `css %||% linkText %||% partialLinkText %||% xpath`"
find_expr <- parse_find_expr(css, linkText, partialLinkText, xpath)
response <- private$session_private$makeRequest(
"FIND ELEMENTS FROM ELEMENT",
list(
using = find_expr$using,
value = find_expr$value
),
list(elementId = private$id)
)
lapply(response$value, function(el) {
Element$new(
id = el$ELEMENT,
session = private$session,
session_private = private$session_private
)
})
}
element_isSelected <- function(self, private) {
"!DEBUG element_isSelected `private$id`"
response <- private$session_private$makeRequest(
"IS ELEMENT SELECTED",
params = list(elementId = private$id)
)
response$value
}
element_getValue <- function(self, private) {
"!DEBUG element_getValue `private$id`"
self$getAttribute("value")
}
element_setValue <- function(self, private, value) {
"!DEBUG element_setValue `private$id`"
assert_string(value)
private$session_private$makeRequest(
"SET ELEMENT VALUE",
list(value = I(value)),
params = list(elementId = private$id)
)
invisible(self)
}
element_getAttribute <- function(self, private, name) {
"!DEBUG element_getAttribute `private$id` `name`"
assert_string(name)
response <- private$session_private$makeRequest(
"GET ELEMENT ATTRIBUTE",
params = list(elementId = private$id, name = name)
)
response$value
}
element_getClass <- function(self, private) {
"!DEBUG element_getClass `private$id`"
class <- self$getAttribute("class")
strsplit(class, "\\s+")[[1]]
}
element_getCssValue <- function(self, private, name) {
"!DEBUG element_getCssValue `private$id` `name`"
assert_string(name)
response <- private$session_private$makeRequest(
"GET ELEMENT CSS VALUE",
params = list(elementId = private$id, property_name = name)
)
response$value
}
element_getText <- function(self, private) {
"!DEBUG element_getText `private$id`"
response <- private$session_private$makeRequest(
"GET ELEMENT TEXT",
params = list(elementId = private$id)
)
response$value
}
element_getData <- function(self, private, name) {
"!DEBUG element_getData `private$id` `name`"
assert_string(name)
self$getAttribute(paste0("data-", name))
}
element_getName <- function(self, private) {
"!DEBUG element_getName `private$id`"
response <- private$session_private$makeRequest(
"GET ELEMENT TAG NAME",
params = list(elementId = private$id)
)
response$value
}
## GET ELEMENT RECT is not implemented by phantomjs, but we can
## emulate it with two other endpoints: location and size
element_getRect <- function(self, private) {
"!DEBUG element_getRect `private$id`"
response1 <- private$session_private$makeRequest(
"GET ELEMENT LOCATION",
params = list(elementId = private$id)
)
response2 <- private$session_private$makeRequest(
"GET ELEMENT SIZE",
params = list(elementId = private$id)
)
list(
x = response1$value$x,
y = response1$value$y,
width = response2$value$width,
height = response2$value$height
)
}
element_id_enabled <- function(self, private) {
"!DEBUG element_id_enabled `private$id`"
response <- private$session_private$makeRequest(
"IS ELEMENT ENABLED",
params = list(elementId = private$id)
)
response$value
}
element_click <- function(self, private) {
"!DEBUG element_click `private$id`"
response <- private$session_private$makeRequest(
"ELEMENT CLICK",
params = list(elementId = private$id)
)
invisible(private$session)
}
element_clear <- function(self, private) {
"!DEBUG element_clear `private$id`"
response <- private$session_private$makeRequest(
"ELEMENT CLEAR",
params = list(elementId = private$id)
)
invisible(self)
}
element_uploadFile <- function(self, private, filename) {
# The file upload endpoint requires a CSS selector to pick out the element,
# so try to contsruct a selector for this element.
selector <- NULL
# Attempt id
id <- self$getAttribute("id")
if (length(id) > 0 && nzchar(id))
selector <- paste0("#", id)
# Attempt name
if (is.null(selector)) {
name <- self$getAttribute("name")
if (length(name) > 0 && nzchar(name))
selector <- paste0("input[type=file,name=", name, "]")
}
# Check that file exists and isn't a directory
filename <- normalizePath(filename, mustWork = FALSE)
if (!all(file.exists(filename))) {
bad_files <- filename[!file.exists(filename)]
stop(paste(bad_files, collapse = ", "), " not found.")
}
if (!all(utils::file_test("-f", filename))) {
bad_files <- filename[!utils::file_test("-f", filename)]
stop(bad_files, " is not a regular file.")
}
if (is.null(selector))
stop("File input element must have an id or name attribute.")
private$session_private$makeRequest(
"UPLOAD FILE",
data = list(
selector = selector,
filepath = as.list(filename)
)
)
}
element_moveMouseTo <- function(self, private, xoffset, yoffset) {
"!DEBUG element_moveMouseTo `private$id` `xoffset`, `yoffset`"
if (!is.null(xoffset)) assert_count(xoffset)
if (!is.null(yoffset)) assert_count(yoffset)
private$session_private$makeRequest(
"MOVE MOUSE TO",
list(
element = private$id,
xoffset = xoffset,
yoffst = yoffset
)
)
invisible(self)
}
element_executeScript <- function(self, private, script, ...) {
"!DEBUG element_executeScript `private$id`"
private$session$executeScript(script, self, ...)
}
element_executeScriptAsync <- function(self, private, script, ...) {
"!DEBUG element_executeScriptAsync `private$id`"
private$session$executeScript(script, self, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/webdriver/R/element.R
|
## Order is (mostly) according to
## https://w3c.github.io/webdriver/webdriver-spec.html#list-of-endpoints
endpoints <- list(
"NEW SESSION" = "POST /session",
"DELETE SESSION" = "DELETE /session/:sessionId",
"GO" = "POST /session/:sessionId/url",
"GET CURRENT URL" = "GET /session/:sessionId/url",
"BACK" = "POST /session/:sessionId/back",
"FORWARD" = "POST /session/:sessionId/forward",
"REFRESH" = "POST /session/:sessionId/refresh",
"GET TITLE" = "GET /session/:sessionId/title",
## windows
## This is /window in the standard, /window_handle in phantomjs
## "GET WINDOW HANDLE" = "GET /session/:sessionId/window",
"GET WINDOW HANDLE" = "GET /session/:sessionId/window_handle",
"CLOSE WINDOW" = "DELETE /session/:sessionId/window",
"SWITCH TO WINDOW" = "POST /session/:sessionId/window",
## This is window/handles in the standard, /window_handles in phantomjs
## "GET WINDOW HANDLES" = "GET /session/:sessionId/window/handles",
"GET WINDOW HANDLES" = "GET /session/:sessionId/window_handles",
## Not supported
"FULLSCREEN WINDOW" = "POST /session/:sessionId/window/fullscreen",
## non-standard
## "MAXIMIZE WINDOW" = "POST /session/:sessionId/window/maximize",
"MAXIMIZE WINDOW" = "POST /session/:sessionId/window/:window_id/maximize",
## non-standard
## "SET WINDOW SIZE" = "POST /session/:sessionId/window/size",
"SET WINDOW SIZE" = "POST /session/:sessionId/window/:window_id/size",
## non-stadard
## "GET WINDOW POSITION" = "GET /session/:sessionId/window/position",
"GET WINDOW POSITION" = "GET /session/:sessionId/window/:window_id/position",
## non-standard
## "SET WINDOW POSITION" = "POST /session/:sessionId/window/position",
"SET WINDOW POSITION" = "POST /session/:sessionId/window/:window_id/position",
## This is also non-standard
## "GET WINDOW SIZE" = "GET /session/:sessionId/window/size",
"GET WINDOW SIZE" = "GET /session/:sessionId/window/:window_id/size",
## frames
"SWITCH TO FRAME" = "POST /session/:sessionId/frame",
"SWITCH TO PARENT FRAME"
= "POST /session/:sessionId/frame/parent",
## elements
"FIND ELEMENT" = "POST /session/:sessionId/element",
"FIND ELEMENT FROM ELEMENT"
= "POST /session/:sessionId/element/:elementId/element",
"FIND ELEMENTS" = "POST /session/:sessionId/elements",
"FIND ELEMENTS FROM ELEMENT"
= "POST /session/:sessionId/element/:elementId/elements",
## In the standard this is a GET, but phantomjs expects a POST :(
"GET ACTIVE ELEMENT" = "POST /session/:sessionId/element/active",
"IS ELEMENT SELECTED" = "GET /session/:sessionId/element/:elementId/selected",
"GET ELEMENT ATTRIBUTE"= "GET /session/:sessionId/element/:elementId/attribute/:name",
"GET ELEMENT PROPERTY" = "GET /session/:sessionId/element/:elementId/property/:name",
"GET ELEMENT CSS VALUE"= "GET /session/:sessionId/element/:elementId/css/:property_name",
"GET ELEMENT TEXT" = "GET /session/:sessionId/element/:elementId/text",
"GET ELEMENT TAG NAME" = "GET /session/:sessionId/element/:elementId/name",
"GET ELEMENT RECT" = "GET /session/:sessionId/element/:elementId/rect",
"IS ELEMENT ENABLED" = "GET /session/:sessionId/element/:elementId/enabled",
"ELEMENT CLICK" = "POST /session/:sessionId/element/:elementId/click",
"ELEMENT CLEAR" = "POST /session/:sessionId/element/:elementId/clear",
"ELEMENT SEND KEYS" = "POST /session/:sessionId/element/:elementId/value",
"GET PAGE SOURCE" = "GET /session/:sessionId/source",
## "EXECUTE SCRIPT" = "POST /session/:sessionId/execute/sync",
"EXECUTE SCRIPT" = "POST /session/:sessionId/execute",
## "EXECUTE ASYNC SCRIPT" = "POST /session/:sessionId/execute/async",
"EXECUTE ASYNC SCRIPT" = "POST /session/:sessionId/execute_async",
## cookies
"GET ALL COOKIES" = "GET /session/:sessionId/cookie",
"GET NAMED COOKIE" = "GET /session/:sessionId/cookie/:name",
"ADD COOKIE" = "POST /session/:sessionId/cookie",
"DELETE COOKIE" = "DELETE /session/:sessionId/cookie/:name",
"DELETE ALL COOKIES" = "DELETE /session/:sessionId/cookie",
"SET TIMEOUT" = "POST /session/:sessionId/timeouts",
"PERFORM ACTIONS" = "POST /session/:sessionId/actions",
"RELEASE ACTIONS" = "DELETE /session/:sessionId/actions",
## alerts
"DISMISS ALERT" = "POST /session/:sessionId/alert/dismiss",
"ACCEPT ALERT" = "POST /session/:sessionId/alert/accept",
"GET ALERT TEXT" = "GET /session/:sessionId/alert/text",
"SEND ALERT TEXT" = "POST /session/:sessionId/alert/text",
## screenshots
"TAKE SCREENSHOT" = "GET /session/:sessionId/screenshot",
"TAKE ELEMENT SCREENSHOT"
= "GET /session/:sessionId/element/:elementId/screenshot",
## -------------------------------------------------------------------
## Phantom JS specific endpoints
"STATUS" = "GET /session/:sessionId",
"MOVE MOUSE TO" = "POST /session/:sessionId/moveto",
"CLICK" = "POST /session/:sessionId/click",
"DOUBLECLICK" = "POST /session/:sessionId/doubleclick",
"BUTTONDOWN" = "POST /session/:sessionId/buttondown",
"BUTTONUP" = "POST /session/:sessionId/buttonup",
"GET LOG TYPES" = "GET /session/:sessionId/log/types",
"READ LOG" = "POST /session/:sessionId/log",
"UPLOAD FILE" = "POST /session/:sessionId/file",
"GET ELEMENT LOCATION" = "GET /session/:sessionId/element/:elementId/location",
"GET ELEMENT SIZE" = "GET /session/:sessionId/element/:elementId/size",
"SET ELEMENT VALUE" = "POST /session/:sessionId/element/:elementId/value"
)
|
/scratch/gouwar.j/cran-all/cranData/webdriver/R/endpoints.R
|
#' @importFrom httr status_code
report_error <- function(response) {
if (status_code(response) < 300) {
invisible(response)
} else {
call <- sys.call(-1)
cond <- create_condition(response, "error", call = call)
# Sometimes the message from create_condition can be very long and will be
# truncated when printed. This prints the maximum possible amount.
if (nchar(cond$message) > getOption("warning.length")) {
old_options <- options(warning.length = 8170)
on.exit(options(old_options))
}
stop(cond)
}
}
#' @importFrom httr content
create_condition <- function(response,
class = c("error", "warning", "message"),
call) {
class <- match.arg(class)
message <- NULL
status <- NULL
if (grepl("^application/json", headers(response)[["content-type"]])) {
try({
cont <- content(response)
# This can error if `cont` doesn't include the fields we want.
json <- fromJSON(
cont[["value"]][["message"]],
simplifyVector = FALSE
)
message <- json[["errorMessage"]] %||% "WebDriver error"
status <- cont$status
})
}
# We can end up in this block if:
# * The error content is just a string, or raw HTML. This can happen, for
# example, when there is a problem loading execute_script.js.
# https://github.com/rstudio/shinytest/issues/165
# https://github.com/rstudio/shinytest/issues/190
# * The `cont` object was JSON, but did not include the needed fields.
if (is.null(status)) {
message <- content(response, "text")
# Need to manually set status code for UnknownError. From:
# https://github.com/detro/ghostdriver/blob/873c9d6/src/errors.js#L135
status <- 13L
}
structure(
list(message = message, status = status, call = call),
class = c("webdriver_error", class, "condition")
)
}
|
/scratch/gouwar.j/cran-all/cranData/webdriver/R/errors.R
|
## This is from the webshot package, see https://github.com/wch/webshot
#' Install PhantomJS
#'
#' Download the zip package, unzip it, and copy the executable to a system
#' directory in which \pkg{webdriver} can look for the PhantomJS executable.
#'
#' This function was designed primarily to help Windows users since it is
#' cumbersome to modify the \code{PATH} variable. Mac OS X users may install
#' PhantomJS via Homebrew. If you download the package from the PhantomJS
#' website instead, please make sure the executable can be found via the
#' \code{PATH} variable.
#'
#' On Windows, the directory specified by the environment variable
#' \code{APPDATA} is used to store \file{phantomjs.exe}. On OS X, the directory
#' \file{~/Library/Application Support} is used. On other platforms (such as
#' Linux), the directory \file{~/bin} is used. If these directories are not
#' writable, the directory \file{PhantomJS} under the installation directory of
#' the \pkg{webdriver} package will be tried. If this directory still fails, you
#' will have to install PhantomJS by yourself.
#' @param version The version number of PhantomJS.
#' @param baseURL The base URL for the location of PhantomJS binaries for
#' download. If the default download site is unavailable, you may specify an
#' alternative mirror, such as
#' \code{"https://bitbucket.org/ariya/phantomjs/downloads/"}.
#' @return \code{NULL} (the executable is written to a system directory).
#' @export
install_phantomjs <- function(version = '2.1.1',
baseURL = 'https://github.com/wch/webshot/releases/download/v0.3.1/') {
if (!grepl("/$", baseURL))
baseURL <- paste0(baseURL, "/")
owd <- setwd(tempdir())
on.exit(setwd(owd), add = TRUE)
if (is_windows()) {
zipfile <- sprintf('phantomjs-%s-windows.zip', version)
download(paste0(baseURL, zipfile), zipfile, mode = 'wb')
utils::unzip(zipfile)
zipdir <- sub('.zip$', '', zipfile)
exec <- file.path(zipdir, 'bin', 'phantomjs.exe')
} else if (is_osx()) {
zipfile <- sprintf('phantomjs-%s-macosx.zip', version)
download(paste0(baseURL, zipfile), zipfile, mode = 'wb')
utils::unzip(zipfile)
zipdir <- sub('.zip$', '', zipfile)
exec <- file.path(zipdir, 'bin', 'phantomjs')
Sys.chmod(exec, '0755') # chmod +x
} else if (is_linux()) {
zipfile <- sprintf(
'phantomjs-%s-linux-%s.tar.bz2', version,
if (grepl('64', Sys.info()[['machine']])) 'x86_64' else 'i686'
)
download(paste0(baseURL, zipfile), zipfile, mode = 'wb')
utils::untar(zipfile)
zipdir <- sub('.tar.bz2$', '', zipfile)
exec <- file.path(zipdir, 'bin', 'phantomjs')
Sys.chmod(exec, '0755') # chmod +x
} else {
# Unsupported platform, like Solaris
message("Sorry, this platform is not supported.")
return(invisible())
}
success <- FALSE
dirs <- phantom_paths()
for (destdir in dirs) {
dir.create(destdir, showWarnings = FALSE)
success <- file.copy(exec, destdir, overwrite = TRUE)
if (success) break
}
unlink(c(zipdir, zipfile), recursive = TRUE)
if (!success) stop(
'Unable to install PhantomJS to any of these dirs: ',
paste(dirs, collapse = ', ')
)
message('phantomjs has been installed to ', normalizePath(destdir))
invisible()
}
# Possible locations of the PhantomJS executable
phantom_paths <- function() {
if (is_windows()) {
path <- Sys.getenv('APPDATA', '')
path <- if (dir_exists(path)) file.path(path, 'PhantomJS')
} else if (is_osx()) {
path <- '~/Library/Application Support'
path <- if (dir_exists(path)) file.path(path, 'PhantomJS')
} else {
path <- '~/bin'
}
path <- c(path, system.file('PhantomJS', package = 'webdriver'))
path
}
# Find PhantomJS from PATH, APPDATA, system.file('webdriver'), ~/bin, etc
find_phantom <- function() {
for (d in phantom_paths()) {
exec <- if (is_windows()) "phantomjs.exe" else "phantomjs"
path <- file.path(d, exec)
if (utils::file_test("-x", path)) break else path <- ""
}
if (path == "") {
path <- Sys.which( "phantomjs" )
if (path != "") return(path)
}
if (path == "") {
# It would make the most sense to throw an error here. However, that would
# cause problems with CRAN. The CRAN checking systems may not have phantomjs
# and may not be capable of installing phantomjs (like on Solaris), and any
# packages which use webdriver in their R CMD check (in examples or vignettes)
# will get an ERROR. We'll issue a message and return NULL; other
message(
"PhantomJS not found. You can install it with webdriver::install_phantomjs(). ",
"If it is installed, please make sure the phantomjs executable ",
"can be found via the PATH variable."
)
return(NULL)
}
path.expand(path)
}
|
/scratch/gouwar.j/cran-all/cranData/webdriver/R/install-phantomjs.R
|
session_getLogTypes <- function(self, private) {
response <- private$makeRequest(
"GET LOG TYPES"
)
response$value
}
#' @importFrom utils tail
session_readLog <- function(self, private, type) {
"!DEBUG session_readLog `type`"
assert_string(type)
response <- private$makeRequest(
"READ LOG",
list(type = type)
)
logs <- response$value
## Current (2.1.1) phantomjs/ghostdriver has a bug, and the log
## buffer is not cleared, and phantomjs always sends the full log
## of the session. We count the number of lines sent, and get rid of
## the ones that we have already seen
if (identical(private$parameters$browserName, "phantomjs") &&
!is.null(ver <- private$parameters$version) &&
numeric_version(ver) <= numeric_version("2.1.1")) {
if (private$numLogLinesShown != 0) {
logs <- tail(logs, - private$numLogLinesShown)
}
private$numLogLinesShown <- length(response$value)
}
make_logs(logs)
}
make_logs <- function(logs) {
logs <- log_rows_to_df(logs)
logs$timestamp <- as.POSIXct(
logs$timestamp / 1000,
origin = "1970-01-01"
)
class(logs) <- c("webdriver_logs", class(logs))
logs
}
log_rows_to_df <- function(logs) {
data.frame(
stringsAsFactors = FALSE,
timestamp = vapply(logs, "[[", 1, "timestamp"),
level = vapply(logs, "[[", "", "level"),
message = vapply(logs, "[[", "", "message")
)
}
#' @export
format.webdriver_logs <- function(x, ...) {
s <- paste(
format(x$timestamp, "%H:%M:%S"),
substr(x$level, 1, 1),
x$message
)
paste(strwrap(s, exdent = 2), collapse = "\n")
}
#' @export
print.webdriver_logs <- function(x, ...) {
print(format(x), ...)
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/webdriver/R/logs.R
|
.onLoad <- function(libname, pkgname) {
debugme::debugme()
}
|
/scratch/gouwar.j/cran-all/cranData/webdriver/R/on-load.R
|
#' 'WebDriver' Client for 'PhantomJS'
#'
#' A client for the 'WebDriver' 'API'. It allows driving a (probably
#' headless) web browser, and can be used to test web applications,
#' including 'Shiny' apps. In theory it works with any 'WebDriver'
#' implementation, but it was only tested with 'PhantomJS'.
#'
#' @docType package
#' @name webdriver
NULL
|
/scratch/gouwar.j/cran-all/cranData/webdriver/R/package.R
|
re_match_all <- function(text, pattern, ...) {
text <- as.character(text)
stopifnot(is.character(pattern), length(pattern) == 1, !is.na(pattern))
## Need to handle this case separately, as gregexpr effectively
## does not work for this.
if (length(text) == 0) return(empty_result(text, pattern, ...))
match <- gregexpr(pattern, text, perl = TRUE, ...)
num_groups <- length(attr(match[[1]], "capture.names"))
## Non-matching strings have a rather strange special form,
## so we just treat them differently
non <- vapply(match, function(m) m[1] == -1, TRUE)
yes <- !non
res <- replicate(length(text), list(), simplify = FALSE)
if (any(non)) {
res[non] <- list(replicate(num_groups + 1, character(), simplify = FALSE))
}
if (any(yes)) {
res[yes] <- mapply(match1, text[yes], match[yes], SIMPLIFY = FALSE)
}
## Need to assemble the final data frame "manually".
## There is apparently no function for this. rbind() is almost
## good, but simplifies to a matrix if the dimensions allow it....
res <- lapply(seq_along(res[[1]]), function(i) {
lapply(res, "[[", i)
})
structure(
res,
names = c(attr(match[[1]], "capture.names"), ".match"),
row.names = seq_along(text),
class = c("data.frame")
)
}
match1 <- function(text1, match1) {
matchstr <- substring(
text1,
match1,
match1 + attr(match1, "match.length") - 1L
)
## substring fails if the index is length zero,
## need to handle special case
if (is.null(attr(match1, "capture.start"))) {
list(.match = matchstr)
} else {
gstart <- attr(match1, "capture.start")
glength <- attr(match1, "capture.length")
gend <- gstart + glength - 1L
groupstr <- substring(text1, gstart, gend)
dim(groupstr) <- dim(gstart)
c(lapply(seq_len(ncol(groupstr)), function(i) groupstr[, i]),
list(.match = matchstr)
)
}
}
empty_result <- function(text, pattern, ...) {
match <- regexpr(pattern, text, perl = TRUE, ...)
num_groups <- length(attr(match, "capture.names"))
structure(
replicate(num_groups + 1, list(), simplify = FALSE),
names = c(attr(match, "capture.names"), ".match"),
row.names = integer(0),
class = "data.frame"
)
}
|
/scratch/gouwar.j/cran-all/cranData/webdriver/R/rematch.R
|
default_headers <- c(
"Accept" = "application/json",
"Content-Type" = "application/json",
"User-Agent" = "R webdriver"
)
#' @importFrom jsonlite toJSON
#' @importFrom httr GET POST DELETE add_headers
session_makeRequest <- function(self, private, endpoint, data, params,
headers) {
"!DEBUG session_makeRequest `endpoint`"
headers <- update(default_headers, as.character(headers))
ep <- parse_endpoint(endpoint, private, params)
url <- paste0(
"http://",
private$host,
":",
private$port,
ep$endpoint
)
json <- if (!is.null(data)) toJSON(data)
response <- if (ep$method == "GET") {
GET(url, add_headers(.headers = headers))
} else if (ep$method == "POST") {
POST(url, add_headers(.headers = headers), body = json)
} else if (ep$method == "DELETE") {
DELETE(url, add_headers(.headers = headers))
} else {
stop("Unexpected HTTP verb, internal webdriver error")
}
report_error(response)
parse_response(response)
}
parse_endpoint <- function(endpoint, params, xparams) {
if (! endpoint %in% names(endpoints)) {
stop("Unknown webdriver API endpoint, internal error")
}
template <- endpoints[[endpoint]]
colons <- re_match_all(template, ":[a-zA-Z0-9_]+")$.match[[1]]
for (col in colons) {
col1 <- substring(col, 2)
value <- xparams[[col1]] %||% params[[col1]] %||%
stop("Unknown API parameter: ", col)
template <- gsub(col, value, template, fixed = TRUE)
}
if (substring(template, 1, 1) != "/") {
method <- gsub("^([^/ ]+)\\s*/.*$", "\\1", template)
template <- gsub("^[^/]+/", "/", template)
} else {
method <- "GET"
}
list(method = method, endpoint = template)
}
#' @importFrom httr headers content
#' @importFrom jsonlite fromJSON
parse_response <- function(response) {
"!DEBUG parse_response"
content_type <- headers(response)$`content-type`
if (is.null(content_type) || length(content_type) == 0) {
""
} else if (grepl("^application/json", content_type, ignore.case = TRUE)) {
fromJSON(content(response, as = "text"), simplifyVector = FALSE)
} else {
content(response, as = "text")
}
}
toJSON <- function(x, ..., auto_unbox = TRUE) {
# I(x) is so that length-1 atomic vectors get put in [] when auto_unbox is
# TRUE.
jsonlite::toJSON(I(x), auto_unbox = auto_unbox, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/webdriver/R/requests.R
|
random_port <- function(min = 3000, max = 9000) {
found <- FALSE
# base::serverSocket was added in R 4.0, and it can be used to check if a port
# is available before we actually return it. If the function isn't available,
# we'll just return a random port without checking.
serverSocket <- get0("serverSocket", as.environment("package:base"),
inherits = FALSE)
if (is.null(serverSocket)) {
port <- if (min < max) sample(min:max, 1) else min
return(port)
}
# Try up to 20 ports
n_ports <- min(20, max - min + 1)
test_ports <- if (min < max) sample(min:max, n_ports) else min
for (port in test_ports) {
open_error <- FALSE
tryCatch(
{
s <- serverSocket(port)
close(s)
},
error = function(e) {
open_error <<- TRUE
}
)
if (!open_error) {
return(port)
}
}
stop("Unable to find an available port.")
}
#' Start up phantomjs on localhost, and a random port
#'
#' Throws and error if phantom cannot be found, or cannot be started. It works
#' with a timeout of five seconds.
#'
#' @param debugLevel Phantom.js debug level, possible values: \code{"INFO"},
#' \code{"ERROR"}, \code{"WARN"}, \code{"DEBUG"}.
#' @param timeout How long to wait (in milliseconds) for the webdriver
#' connection to be established to the phantomjs process.
#'
#' @return A list of \code{process}, the \code{callr::process} object, and
#' \code{port}, the local port where phantom is running.
#'
#' @importFrom callr process
#' @export
run_phantomjs <- function(debugLevel = c("INFO", "ERROR", "WARN", "DEBUG"),
timeout = 5000) {
debugLevel <- match.arg(debugLevel)
phexe <- find_phantom()
if (is.null(phexe)) stop("No phantom.js, exiting.")
host <- "127.0.0.1"
port <- random_port()
args <- c(
"--proxy-type=none",
sprintf("--webdriver=%s:%d", host, port),
sprintf("--webdriver-loglevel=%s", debugLevel)
)
# The env vars are a workaround for :
# https://github.com/rstudio/shinytest/issues/165#issuecomment-364935112
withr::with_envvar(get_phantom_envvars(), {
ph <- process$new(
command = phexe,
args = args,
supervise = TRUE,
stdout = tempfile("webdriver-stdout-", fileext = ".log"),
stderr = "2>&1"
)
})
if (! ph$is_alive()) {
stop(
"Failed to start phantomjs. stdout + stderr:\n",
paste(collapse = "\n", "> ", readLines(ph$get_output_file()))
)
}
## Wait until has started and answers queries
url <- paste0("http://", host, ":", port)
res <- wait_for_http(url, timeout = timeout)
if (!res) {
ph$kill()
stop(
"phantom.js started, but cannot connect to it on port ", port,
". stdout + stderr:\n",
paste(collapse = "\n", "> ", readLines(ph$get_output_file()))
)
}
list(process = ph, port = port)
}
# Needed for a weird issue in Debian build of phantomjs:
# https://github.com/rstudio/shinytest/issues/165#issuecomment-364935112
get_phantom_envvars <- local({
# memoize
vars <- NULL
function() {
if (!is.null(vars)) return(vars)
vars <<- list()
phexe <- find_phantom()
if (is.null(phexe)) stop("No phantom.js, exiting.")
ph <- process$new(command = phexe, args = "--version", stdout = "|", stderr = "|")
ph$wait(5000)
if (ph$is_alive()) {
ph$kill()
stop("`phantomjs --version` timed out.")
}
if (ph$get_exit_status() != 0 &&
any(grepl("^QXcbConnection: Could not connect to display", ph$read_error_lines())))
{
vars$QT_QPA_PLATFORM <<- "offscreen"
}
vars
}
})
|
/scratch/gouwar.j/cran-all/cranData/webdriver/R/run-phantomjs.R
|
#' WebDriver session
#'
#' Drive a headless phantom.js browser via the WebDriver protocol.
#' It needs phantom.js running in WebDriver mode.
#'
#' @section Usage:
#' \preformatted{s <- Session$new(host = "127.0.0.1", port = 8910)
#'
#' s$delete()
#' s$status()
#'
#' s$go(url)
#' s$getUrl()
#' s$goBack()
#' s$goForward()
#' s$refresh()
#' s$getTitle()
#' s$getSource()
#' s$takeScreenshot(file = NULL)
#'
#' s$findElement(css = NULL, linkText = NULL,
#' partialLinkText = NULL, xpath = NULL)
#' s$findElements(css = NULL, linkText = NULL,
#' partialLinkText = NULL, xpath = NULL)
#'
#' s$executeScript(script, ...)
#' s$executeScriptAsync(script, ...)
#'
#' s$setTimeout(script = NULL, pageLoad = NULL, implicit = NULL)
#'
#' s$moveMouseTo(xoffset = 0, yoffset = 0)
#' s$click(button = c("left", "middle", "right"))
#' s$doubleClick(button = c("left", "middle", "right"))
#' s$mouseButtonDown(button = c("left", "middle", "right"))
#' s$mouseButtonUp(button = c("left", "middle", "right"))
#'
#' s$readLog(type = c("browser", "har"))
#' s$getLogTypes()
#'
#' s$waitFor(expr, checkInterval = 100, timeout = 3000)
#' }
#'
#' @section Arguments:
#'\describe{
#' \item{s}{A \code{Session} object.}
#' \item{host}{Host name of phantom.js.}
#' \item{port}{Port of phantom.js.}
#' \item{url}{URL to nagivate to.}
#' \item{file}{File name to save the screenshot to. If \code{NULL}, then
#' it will be shown on the R graphics device.}
#' \item{css}{Css selector to find an HTML element.}
#' \item{linkText}{Find HTML elements based on their \code{innerText}.}
#' \item{partialLinkText}{Find HTML elements based on their
#' \code{innerText}. It uses partial matching.}
#' \item{xpath}{Find HTML elements using XPath expressions.}
#' \item{script}{For \code{executeScript} and
#' \code{executeScriptAsync}. JavaScript code to execute. It will be
#' placed in the body of a function.}
#' \item{...}{Arguments to the script, they will be put in a list
#' called arguments. \code{\link{Element}} objects are automatically
#' transformed to DOM element in JavaScript.}
#' \item{script}{For \code{setTimeout}. Script execution timeout,
#' in milliseconds. More below.}
#' \item{pageLoad}{Page load timeout, in milliseconds. More below.}
#' \item{implicit}{Implicit wait before calls that find elements, in
#' milliseconds. More below.}
#' \item{xoffset}{Horizontal offset for mouse movement, relative to the
#' current position.}
#' \item{yoffset}{Vertical offset for mouse movement, relative to the
#' current position.}
#' \item{button}{Mouse button. Either one of \code{"left"},
#' \code{"middle"}, \code{"right"}, or an integer between 1 and 3.}
#' \item{type}{Log type, a character scalar.}
#' \item{expr}{A string scalar containing JavaScript code that
#' evaluates to the condition to wait for.}
#' \item{checkInterval}{How often to check for the condition, in
#' milliseconds.}
#' \item{timeout}{Timeout for the condition, in milliseconds.}
#' }
#'
#' @section Details:
#'
#' \code{Session$new()} creates a new WebDriver session.
#'
#' \code{s$delete()} deletes a WebDriver session.
#'
#' \code{s$status()} returns a status message from the server. It is a
#' named list, and contains version numbers and capabilities.
#'
#' \code{s$go()} navigates to the supplied URL.
#'
#' \code{s$getUrl()} returns the current URL.
#'
#' \code{s$goBack()} is like the web browser's back button. It goes back
#' to the previous page.
#'
#' \code{s$goForward()} is like the web browser's forward button.
#'
#' \code{s$refresh()} is like the web browser's refresh button.
#'
#' \code{s$getTitle()} returns the title of the current page.
#'
#' \code{s$getSource()} returns the complete HTML source of a page,
#' in a character scalar.
#'
#' \code{s$takeScreenshot()} takes a screenshot of the current page.
#' You can save it to a PNG file with the \code{file} argument, or
#' show it on the graphics device (if \code{file} is \code{NULL}).
#'
#' \code{s$findElement()} finds a HTML element using a CSS selector,
#' XPath expression, or the \code{innerHTML} of the element. If multiple
#' elements match, then the first one is returned. The return value
#' is an \code{\link{Element}} object.
#'
#' \code{s$findElements()} finds HTML elements using a CSS selector,
#' XPath expression, or the \code{innerHTML} of the element. All matching
#' elements are returned in a list of \code{\link{Element}} objects.
#'
#' \code{s$executeScript()} executes JavaScript code. It places the code
#' in the body of a function, and then calls the function with the
#' additional arguments. These can be accessed from the function via the
#' \code{arguments} array. Returned DOM elements are automatically
#' converted to \code{\link{Element}} objects, even if they are inside
#' a list (or list of list, etc.).
#'
#' \code{s$executeScriptAsync()} is similar, for asynchronous execution.
#' It place the script in a body of a function, and then calls the function
#' with the additional arguments and a callback function as the last
#' argument. The script must call this callback function when it
#' finishes its work. The first argument passed to the callback function
#' is returned. Returned DOM elements are automatically converted to
#' \code{\link{Element}} objects, even if they are inside a list (or list
#' of list, etc.).
#'
#' \code{s$setTimeout()} sets various timeouts. The \sQuote{script}
#' timeout specifies a time to wait for scripts to run. The
#' sQuote{page load} timeout specifies a time to wait for the page loading
#' to complete. The \sQuote{implicit} specifies a time to wait for the
#' implicit element location strategy when locating elements. Their defaults
#' are different in the standard and in Phantom.js. In Phantom.js the
#' \sQuote{script} and \sQuote{page load} timeouts are set to infinity,
#' and the \sQuote{implicit} waiting time is 200ms.
#'
#' \code{s$moveMouseTo()} moves the mouse cursor by the specified
#' offsets.
#'
#' \code{s$click()} clicks the mouse at its current position, using
#' the specified button.
#'
#' \code{s$doubleClick()} emulates a double click with the specified
#' mouse button.
#'
#' \code{s$button_down()} emulates pressing the specified mouse button
#' down (and keeping it down).
#'
#' \code{s$button_up()} emulates releasing the specified mouse button.
#'
#' \code{s$getLogTypes()} returns the log types supported by the
#' server, in a character vector.
#'
#' \code{s$readLog()} returns the log messages since the last
#' \code{readLog} call, in a data frame with columns \code{timestamp},
#' \code{level} and \code{message}.
#'
#' \code{s$waitFor()} waits until a JavaScript expression evaluates
#' to \code{true}, or a timeout happens. It returns \code{TRUE} is the
#' expression evaluated to \code{true}, possible after some waiting. If
#' the expression has a syntax error or a runtime error happens, it
#' returns \code{NA}.
#'
#' @seealso The WebDriver standard at
#' \url{https://w3c.github.io/webdriver/webdriver-spec.html}.
#'
#' @importFrom R6 R6Class
#' @name Session
NULL
#' @export
Session <- R6Class(
"Session",
public = list(
initialize = function(host = "127.0.0.1", port = 8910)
session_initialize(self, private, host, port),
delete = function()
session_delete(self, private),
getStatus = function()
session_getStatus(self, private),
go = function(url)
session_go(self, private, url),
getUrl = function()
session_getUrl(self, private),
goBack = function()
session_goBack(self, private),
goForward = function()
session_goForward(self, private),
refresh = function()
session_refresh(self, private),
getTitle = function()
session_getTitle(self, private),
getSource = function()
session_getSource(self, private),
takeScreenshot = function(file = NULL)
session_takeScreenshot(self, private, file = file),
## Elements ------------------------------------------------
findElement = function(css = NULL, linkText = NULL,
partialLinkText = NULL, xpath = NULL)
session_findElement(self, private, css, linkText,
partialLinkText, xpath),
findElements = function(css = NULL, linkText = NULL,
partialLinkText = NULL, xpath = NULL)
session_findElements(self, private, css, linkText,
partialLinkText, xpath),
getActiveElement = function()
session_getActiveElement(self, private),
## Windows -------------------------------------------------
getWindow = function()
session_getWindow(self, private),
getAllWindows = function()
session_getAllWindows(self, private),
## Execute script ------------------------------------------
executeScript = function(script, ...)
session_executeScript(self, private, script, ...),
executeScriptAsync = function(script, ...)
session_executeScriptAsync(self, private, script, ...),
## Timeouts ------------------------------------------------
setTimeout = function(script = NULL, pageLoad = NULL,
implicit = NULL)
session_setTimeout(self, private, script, pageLoad, implicit),
## Move mouse, clicks --------------------------------------
moveMouseTo = function(xoffset, yoffset)
session_moveMouseTo(self, private, xoffset, yoffset),
click = function(button = c("left", "middle", "right"))
session_click(self, private, button),
doubleClick = function(button = c("left", "middle", "right"))
session_doubleClick(self, private, button),
mouseButtonDown = function(button = c("left", "middle", "right"))
session_mouseButtonDown(self, private, button),
mouseButtonUp = function(button = c("left", "middle", "right"))
session_mouseButtonUp(self, private, button),
## Logs ----------------------------------------------------
getLogTypes = function()
session_getLogTypes(self, private),
readLog = function(type = "browser")
session_readLog(self, private, type),
## Polling for a condition ---------------------------------
waitFor = function(expr, checkInterval = 100, timeout = 3000)
session_waitFor(self, private, expr, checkInterval, timeout)
),
private = list(
host = NULL,
port = NULL,
sessionId = NULL,
parameters = NULL,
numLogLinesShown = 0,
makeRequest = function(endpoint, data = NULL, params = NULL,
headers = NULL)
session_makeRequest(self, private, endpoint, data, params, headers)
)
)
session_initialize <- function(self, private, host, port) {
"!DEBUG session_initialize `host`:`port`"
assert_string(host)
assert_port(port)
private$host <- host
private$port <- port
private$numLogLinesShown <- 0
response <- private$makeRequest(
"NEW SESSION",
list(
desiredCapabilities = list(
browserName = "phantomjs",
driverName = "ghostdriver"
)
)
)
private$sessionId = response$sessionId %||% stop("Got no sessionId")
private$parameters = response$value
## reg.finalizer(self, function(e) e$delete(), TRUE)
## Set implicit timeout to zero. According to the standard it should
## be zero, but phantomjs uses about 200 ms
self$setTimeout(implicit = 0)
## Set initial windows size to something sane
self$getWindow()$setSize(992, 744)
## Try to run a very basic script. If this fails, it probably means that the
## phantomjs binary was not built with ghostdriver.
## https://github.com/rstudio/shinytest/issues/165
tryCatch(
self$executeScript("1"),
error = function(e) {
if (grepl("Unable to load Atom.*ghostdriver", e$message)) {
e$message <- paste0(
e$message,
"\nThis is probably because your phantomjs binary (",
find_phantom(), ") was not built with ghostdriver support.",
"\nTry running webdriver::install_phantomjs() and restarting R."
)
}
stop(e)
})
invisible(self)
}
session_delete <- function(self, private) {
"!DEBUG session_delete"
if (! is.null(private$sessionId)) {
response <- private$makeRequest(
"DELETE SESSION",
list()
)
}
private$sessionId <- NULL
invisible()
}
session_getStatus <- function(self, private) {
"!DEBUG session_getStatus"
response <- private$makeRequest(
"STATUS"
)
response$value
}
session_go <- function(self, private, url) {
"!DEBUG session_go `url`"
assert_url(url)
private$makeRequest(
"GO",
list("url" = url)
)
invisible(self)
}
session_getUrl <- function(self, private) {
"!DEBUG session_getUrl"
response <- private$makeRequest(
"GET CURRENT URL"
)
response$value
}
session_goBack <- function(self, private) {
"!DEBUG session_goBack"
private$makeRequest(
"BACK"
)
invisible(self)
}
session_goForward <- function(self, private) {
"!DEBUG session_goForward"
private$makeRequest(
"FORWARD"
)
invisible(self)
}
session_refresh <- function(self, private) {
"!DEBUG session_refresh"
private$makeRequest(
"REFRESH"
)
invisible(self)
}
session_getTitle <- function(self, private) {
"!DEBUG session_getTitle"
response <- private$makeRequest(
"GET TITLE"
)
response$value
}
session_findElement <- function(self, private, css, linkText,
partialLinkText, xpath) {
"!DEBUG session_findElement `css %||% linkText %||% partialLinkText %||% xpath`"
find_expr <- parse_find_expr(css, linkText, partialLinkText, xpath)
response <- private$makeRequest(
"FIND ELEMENT",
list(
using = find_expr$using,
value = find_expr$value
)
)
Element$new(
id = response$value$ELEMENT,
session = self,
session_private = private
)
}
parse_find_expr <- function(css, linkText, partialLinkText, xpath) {
if (is.null(css) + is.null(linkText) + is.null(partialLinkText) +
is.null(xpath) != 3) {
stop(
"Specify one of 'css', 'linkText', ",
"'partialLinkText' and 'xpath'"
)
}
if (!is.null(css)) {
list(using = "css selector", value = css)
} else if (!is.null(linkText)) {
list(using = "link text", value = linkText)
} else if (!is.null(partialLinkText)) {
list(using = "partial link text", value = partialLinkText)
} else if (!is.null(xpath)) {
list(using = "xpath", value = xpath)
}
}
session_findElements <- function(self, private, css, linkText,
partialLinkText, xpath) {
"!DEBUG session_findElements `css %||% linkText %||% partialLinkText %||% xpath`"
find_expr <- parse_find_expr(css, linkText, partialLinkText, xpath)
response <- private$makeRequest(
"FIND ELEMENTS",
list(
using = find_expr$using,
value = find_expr$value
)
)
lapply(response$value, function(el) {
Element$new(
id = el$ELEMENT,
session = self,
session_private = private
)
})
}
session_getActiveElement <- function(self, private) {
"!DEBUG session_getActiveElement"
response <- private$makeRequest(
"GET ACTIVE ELEMENT"
)
Element$new(
id = response$value$ELEMENT,
session = self,
session_private = private
)
}
session_getSource <- function(self, private) {
"!DEBUG session_getSource"
response <- private$makeRequest(
"GET PAGE SOURCE"
)
response$value
}
#' @importFrom showimage show_image
session_takeScreenshot <- function(self, private, file) {
"!DEBUG session_takeScreenshot"
if (!is.null(file)) assert_filename(file)
response <- private$makeRequest(
"TAKE SCREENSHOT"
)
handle_screenshot(response, file)
invisible(self)
}
#' @importFrom base64enc base64decode
handle_screenshot <- function(response, file) {
if (is.null(output <- file)) {
output <- tempfile(fileext = ".png")
on.exit(unlink(output))
}
writeBin(
base64decode(response$value),
output
)
## if 'file' was NULL, then show it on the graphics device
if (is.null(file)) show_image(output)
}
session_getWindow <- function(self, private) {
"!DEBUG session_getWindow"
response <- private$makeRequest(
"GET WINDOW HANDLE"
)
Window$new(
id = response$value,
session = self,
session_private = private
)
}
session_getAllWindows <- function(self, private) {
"!DEBUG session_getAllWindows"
response <- private$makeRequest(
"GET WINDOW HANDLES"
)
lapply(response$value, function(id) {
Window$new(
id = id,
session = self,
session_private = private
)
})
}
prepare_execute_args <- function(...) {
args <- list(...)
assert_unnamed(args)
lapply(args, function(x) {
if (inherits(x, "Element") && inherits(x, "R6")) {
list(ELEMENT = x$.__enclos_env__$private$id)
} else {
x
}
})
}
parse_script_response <- function(self, private, value) {
if (is.list(value) && length(value) == 1 && !is.null(names(value)) &&
names(value) == "ELEMENT" && is.character(value[[1]]) &&
length(value[[1]]) == 1) {
## Single element
Element$new(value[[1]], self, private)
} else if (is.list(value)) {
## List of things, look if one of them is an element
lapply(value, parse_script_response, self = self, private = private)
} else {
## Do not touch
value
}
}
session_executeScript <- function(self, private, script, ...) {
"!DEBUG session_executeScript"
assert_string(script)
args <- prepare_execute_args(...)
response <- private$makeRequest(
"EXECUTE SCRIPT",
list(script = script, args = args)
)
parse_script_response(self, private, response$value)
}
session_executeScriptAsync <- function(self, private, script, ...) {
"!DEBUG session_executeScriptAsync"
assert_string(script)
args <- prepare_execute_args(...)
response <- private$makeRequest(
"EXECUTE ASYNC SCRIPT",
list(script = script, args = args)
)
parse_script_response(self, private, response$value)
}
session_setTimeout <- function(self, private, script, pageLoad,
implicit) {
"!DEBUG session_setTimeout"
if (!is.null(script)) {
assert_timeout(script)
private$makeRequest(
"SET TIMEOUT",
list(type = "script", ms = script)
)
}
if (!is.null(pageLoad)) {
assert_timeout(pageLoad)
private$makeRequest(
"SET TIMEOUT",
list(type = "page load", ms = pageLoad)
)
}
if (!is.null(implicit)) {
assert_timeout(implicit)
private$makeRequest(
"SET TIMEOUT",
list(type = "implicit", ms = implicit)
)
}
invisible(self)
}
session_moveMouseTo <- function(self, private, xoffset, yoffset) {
"!DEBUG session_moveMouseTo"
assert_count(xoffset)
assert_count(yoffset)
private$makeRequest(
"MOVE MOUSE TO",
list(xoffset = xoffset, yoffset = yoffset)
)
invisible(self)
}
session_button <- function(self, private, type, button) {
"!DEBUG session_button `type` `button`"
assert_mouse_button(button)
private$makeRequest(
toupper(type),
list(button = button)
)
invisible(self)
}
session_click <- function(self, private, button) {
"!DEBUG session_click `button`"
session_button(self, private, "click", button)
}
session_doubleClick <- function(self, private, button) {
"!DEBUG session_doubleClick `button`"
session_button(self, private, "doubleclick", button)
}
session_mouseButtonDown <- function(self, private, button) {
"!DEBUG session_mouseButtonDown `button`"
session_button(self, private, "buttondown", button)
}
session_mouseButtonUp <- function(self, private, button) {
"!DEBUG session_mouseButtonUp `button`"
session_button(self, private, "buttonup", button)
}
|
/scratch/gouwar.j/cran-all/cranData/webdriver/R/session.R
|
`%||%` <- function(l, r) if (is.null(l)) r else l
update <- function(original, new) {
if (length(new)) {
assert_named(original)
assert_named(new)
original[names(new)] <- new
}
original
}
read_file <- function(x) {
readChar(x, file.info(x)$size)
}
`%+%` <- function(l, r) {
assert_string(l)
assert_string(r)
paste0(l, r)
}
str <- function(x) {
as.character(x)
}
is_windows <- function() .Platform$OS.type == "windows"
is_osx <- function() Sys.info()[['sysname']] == 'Darwin'
is_linux <- function() Sys.info()[['sysname']] == 'Linux'
dir_exists <- function(path) utils::file_test('-d', path)
|
/scratch/gouwar.j/cran-all/cranData/webdriver/R/utils.R
|
#' @importFrom curl new_handle new_pool multi_add multi_run
wait_for_http <- function(url, timeout = 5000, interval = 100) {
end <- Sys.time() + timeout / 1000.0
try_1 <- function(timeout) {
h <- new_handle(url = url, connecttimeout = timeout)
m <- new_pool()
multi_add(h, pool = m)
out <- tryCatch(
multi_run(timeout = timeout, pool = m),
error = function(e) { print (e) ; FALSE }
)
if (identical(out, FALSE)) return(FALSE)
out$success == 1
}
remaining <- end - Sys.time()
while (remaining > 0) {
if (try_1(as.numeric(remaining))) return(TRUE)
Sys.sleep(interval / 1000.0)
remaining <- end - Sys.time()
}
FALSE
}
|
/scratch/gouwar.j/cran-all/cranData/webdriver/R/wait-for-http.R
|
#' @importFrom utils packageName
session_waitFor <- function(self, private, expr, checkInterval,
timeout) {
"!DEBUG session_waitFor"
assert_string(expr)
assert_count(checkInterval)
assert_count(timeout)
## Assemble all JS code to inject. First the code for the waiting
## function, and then we'll call it.
waitjs <- read_file(system.file(
package = packageName(),
"js", "webdriver-wait-for.js"
))
escaped <- gsub('"', '\\\\"', expr)
js <-
'var callback = arguments[0];
webdriver_wait_for(
"' %+% escaped %+% '",
callback,
{ check_interval: ' %+% str(checkInterval) %+% ',
timeout: ' %+% str(timeout) %+% ' }
);'
ret <- self$executeScriptAsync(paste0(waitjs, js))
switch(ret, "error" = NA, "true" = TRUE, "timeout" = FALSE, NA)
}
|
/scratch/gouwar.j/cran-all/cranData/webdriver/R/wait.R
|
#' A browser window
#'
#' @section Usage:
#' \preformatted{w <- s$getWindow()
#' wlist <- s$getAllWindows()
#'
#' w$close()
#' w$isActive()
#' w$switchTo()
#' w$maximize()
#' w$getSize()
#' w$setSize(width, height)
#' w$getPosition()
#' w$setPosition(x, y)
#' }
#'
#' @section Arguments:
#' \describe{
#' \item{s}{A \code{\link{Session}} object.}
#' \item{w}{A \code{Window} object.}
#' \item{wlist}{A list of \code{Window} objects.}
#' \item{width}{Integer scalar, requested width of the window.}
#' \item{height}{Integer scalar, requested height of the window.}
#' \item{x}{Integer scalar, requested horizontal window position.}
#' \item{y}{Integer scalar, requested vertical window position.}
#' }
#'
#' @section Details:
#'
#' The \code{getWindow} method of a \code{\link{Session}} object
#' returns the current browser window as a \code{Window} object.
#' The \code{getAllWindows} method returns a list of window objects,
#' all browser windows.
#'
#' \code{w$close()} closes the window.
#'
#' \code{w$isActive()} returns \code{TRUE} if the window is active,
#' \code{FALSE} otherwise.
#'
#' \code{w$switchTo} makes the window active.
#'
#' \code{w$maximize} maximizes the window. Currently it sets it to
#' a fixed size.
#'
#' \code{w$getSize} returns the size of the window, in a list with
#' elementh \code{width} and \code{height}, both integers.
#'
#' \code{w$setSize} sets the size of the window.
#'
#' \code{w$getPosition} returns the position of the window on the
#' screen. Phantom.js being headless, it always returns
#' \code{list(x = 0, y = 0)}, and it is included to have a complete
#' impelementation of the WebDriver standard.
#'
#' \code{w$setPosition(x, y)} sets the position of the window on the
#' screen. Phantom.js being headless, it has no effect, and it is included
#' to have a complete implementation of the WebDriver standard.
#'
#' @name Window
#' @importFrom R6 R6Class
NULL
Window <- R6Class(
"Window",
public = list(
initialize = function(id, session, session_private) {
window_initialize(self, private, id, session, session_private)
},
close = function()
window_close(self, private),
isActive = function()
window_isActive(self, private),
switchTo = function()
window_switchTo(self, private),
## Not supported
## make_fullscreen = function()
## window_make_fullscreen(self, private),
maximize = function()
window_maximize(self, private),
getSize = function()
window_getSize(self, private),
setSize = function(width, height)
window_setSize(self, private, width, height),
getPosition = function()
window_getPosition(self, private),
setPosition = function(x, y)
window_setPosition(self, private, x, y)
),
private = list(
id = NULL,
session = NULL,
session_private = NULL
)
)
window_initialize <- function(self, private, id, session,
session_private) {
assert_string(id)
assert_session(session)
private$id <- id
private$session <- session
private$session_private <- session_private
invisible(self)
}
window_close <- function(self, private) {
"!DEBUG window_close"
private$session_private$makeRequest(
"CLOSE WINDOW",
list(name = private$id)
)
invisible(self)
}
window_isActive <- function(self, private) {
"!DEBUG window_isActive"
active <- private$session$getWindow()
active$.__enclos_env__$private$id == private$id
}
window_switchTo <- function(self, private) {
"!DEBUG window_switchTo"
private$session_private$makeRequest(
"SWITCH TO WINDOW",
list(name = private$id)
)
invisible(self)
}
## window_make_fullscreen <- function(self, private) {
## "!DEBUG window_make_fullscreen"
## private$session_private$makeRequest(
## "FULLSCREEN WINDOW",
## )
## invisible(self)
## }
window_maximize <- function(self, private) {
"!DEBUG window_maximize"
private$session_private$makeRequest(
"MAXIMIZE WINDOW",
params = list(window_id = private$id)
)
invisible(self)
}
window_getSize <- function(self, private) {
"!DEBUG window_getSize"
response <- private$session_private$makeRequest(
"GET WINDOW SIZE",
params = list(window_id = private$id)
)
list(width = response$value$width, height = response$value$height)
}
window_setSize <- function(self, private, width, height) {
"!DEBUG window_setSize `width`x`height`"
assert_window_size(width)
assert_window_size(height)
private$session_private$makeRequest(
"SET WINDOW SIZE",
list(
width = width,
height = height
),
params = list(window_id = private$id)
)
invisible(self)
}
window_getPosition <- function(self, private) {
"!DEBUG window_getPosition"
response <- private$session_private$makeRequest(
"GET WINDOW POSITION",
params = list(window_id = private$id)
)
response$value
}
window_setPosition <- function(self, private, x, y) {
"!DEBUG window_setPosition"
assert_window_position(x)
assert_window_position(y)
private$session_private$makeRequest(
"SET WINDOW POSITION",
list(
x = x,
y = y
),
params = list(window_id = private$id)
)
invisible(self)
}
|
/scratch/gouwar.j/cran-all/cranData/webdriver/R/window.R
|
#' Add webexercises helper files to bookdown
#'
#' Adds the necessary helper files to an existing bookdown project and
#' edits the _output.yml and _bookdown.yml files accordingly. If the
#' directory does not have a bookdown project in it, a template
#' project will be set up.
#'
#' @param bookdown_dir The base directory for your bookdown project
#' @param include_dir The directory where you want to put the css and
#' js files (defaults to "include")
#' @param script_dir The directory where you want to put the .R script
#' (defaults to "R")
#' @param output_format The bookdown format you want to add
#' webexercises to (defaults to "bs4_book") This is typically your
#' default HTML format in the _output.yml file.
#' @param render Whether to render the book after updating (defaults to FALSE).
#'
#' @return No return value, called for side effects.
#' @export
#'
add_to_bookdown <- function(bookdown_dir = ".",
include_dir = "include",
script_dir = "R",
output_format = c("bs4_book",
"gitbook",
"html_book",
"tufte_html_book"),
render = FALSE) {
# check inputs
if (bookdown_dir == "") bookdown_dir <- "."
if (include_dir == "") include_dir <- "."
if (script_dir == "") script_dir <- "."
output_format <- paste0("bookdown::", match.arg(output_format))
# get helper files
css <- system.file("reports/default/webex.css", package = "webexercises")
js <- system.file("reports/default/webex.js", package = "webexercises")
script <- system.file("reports/default/webex.R", package = "webexercises")
index <- system.file("reports/default/index.Rmd", package = "webexercises")
# make sure include and script directories exist
incdir <- file.path(bookdown_dir, include_dir)
dir.create(path = incdir, showWarnings = FALSE, recursive = TRUE)
rdir <- file.path(bookdown_dir, script_dir)
dir.create(path = rdir, showWarnings = FALSE, recursive = TRUE)
# add or update helper files
file.copy(css, incdir, overwrite = TRUE)
file.copy(js, incdir, overwrite = TRUE)
file.copy(script, rdir, overwrite = TRUE)
message("webex.css, webex.js, and webex.R updated")
# add index file if needed
file.copy(index, bookdown_dir, overwrite = FALSE)
# update or create _output.yml
output_defaults <- list(
"bookdown::bs4_book" = list(
df_print = "kable",
theme = list(primary = "#0d6efd"),
lib_dir = "libs",
split_bib = FALSE
),
"bookdown::gitbook" = list(
df_print = "kable",
number_sections = TRUE,
self_contained = FALSE,
highlight = "default",
config = list(
toc = list(
collapse = "subsection",
scroll_highlight = TRUE,
before = NULL,
after = NULL
),
edit = NULL,
download = NULL,
fontsettings = list(
theme = "white",
family = "sans",
size = 2),
info = TRUE
)
),
"bookdown::html_book" = list(
theme = "default",
highlight = "default",
split_by = "chapter",
toc = FALSE
),
"bookdown::tufte_html_book" = list(
toc = FALSE
)
)
output_file <- file.path(bookdown_dir, "_output.yml")
if (!file.exists(output_file)) {
# add new format with reasonable defaults
yml <- list()
yml[[output_format]] <- output_defaults[[output_format]]
} else {
# keep default yml
yml <- yaml::read_yaml(output_file)
if (!output_format %in% names(yml)) {
# append output_format
yml[[output_format]] <- output_defaults[[output_format]]
}
}
# get previous values
old_css <- yml[[output_format]]$css
old_js <- yml[[output_format]]$includes$after_body
old_md <- yml[[output_format]]$md_extensions
# merge with new values
yml[[output_format]]$css <- union(old_css, file.path(include_dir, "webex.css"))
yml[[output_format]]$includes$after_body <- union(old_js, file.path(include_dir, "webex.js"))
yml[[output_format]]$md_extensions <- union(old_md, "-smart")
# write to _output.yml
yaml::write_yaml(yml, output_file)
message(output_file, " updated")
# update or create _bookdown.yml
bookdown_file <- file.path(bookdown_dir, "_bookdown.yml")
if (file.exists(bookdown_file)) {
yml <- yaml::read_yaml(bookdown_file)
} else {
# set reasonable defaults
yml <- list(book_filename = "_main",
new_session = "yes",
output_dir = "docs",
delete_merged_file = "yes")
}
# get previous values
old_bcs <- yml$before_chapter_script
yml$before_chapter_script <- union(old_bcs, file.path(script_dir, "webex.R"))
# write to _bookdown.yml
yaml::write_yaml(yml, bookdown_file)
message(bookdown_file, " updated")
# render and open site
if (isTRUE(render)) {
if (!requireNamespace("bookdown", quietly = TRUE)) {
stop("Package \"bookdown\" needed for this function to work. Please install it.",
call. = FALSE)
}
if (!requireNamespace("xfun", quietly = TRUE)) {
stop("Package \"xfun\" needed for this function to work. Please install it.",
call. = FALSE)
}
local_path <- xfun::in_dir(bookdown_dir, bookdown::render_book(
input = "index.Rmd",
output_format = output_format
))
utils::browseURL(local_path)
}
invisible(NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/webexercises/R/add_to_bookdown.R
|
#' Add webexercises helper files to quarto
#'
#' Adds the necessary helper files to an existing quarto project and
#' edits the _quarto.yml file accordingly. A demo file for webexercises
#' will be added and optionally rendered.
#'
#' @param quarto_dir The base directory for your quarto project
#' @param include_dir The directory where you want to put the css and
#' js files (defaults to "include")
#' @param output_format The format you want to add
#' webexercises to (only html for now)
#'
#' @return No return value, called for side effects.
#' @export
#'
add_to_quarto <- function(quarto_dir = ".",
include_dir = "include",
output_format = c("html")) {
# check inputs
if (quarto_dir == "") quarto_dir <- "."
if (include_dir == "") include_dir <- "."
output_format <- match.arg(output_format)
# get helper files
css <- system.file("reports/default/webex.css", package = "webexercises")
js <- system.file("reports/default/webex.js", package = "webexercises")
demo <- system.file("reports/default/webexercises.qmd", package = "webexercises")
# make sure include and script directories exist
incdir <- file.path(quarto_dir, include_dir)
dir.create(path = incdir, showWarnings = FALSE, recursive = TRUE)
# add or update helper files
file.copy(css, incdir, overwrite = TRUE)
file.copy(js, incdir, overwrite = TRUE)
file.copy(demo, quarto_dir, overwrite = TRUE)
message("webex.css, webex.js, and webexercises.qmd updated")
# update or create _quarto.yml
css_path <- file.path(include_dir, "webex.css")
js_path <- file.path(include_dir, "webex.js")
quarto_defaults <- list(
"html" = list(
"css" = css_path,
"include-after-body" = js_path
)
)
quarto_file <- file.path(quarto_dir, "_quarto.yml")
if (!file.exists(quarto_file)) {
# add new format with reasonable defaults
yml <- list()
yml[[output_format]] <- quarto_defaults[[output_format]]
} else {
# keep default yml
yml <- yaml::read_yaml(quarto_file)
if ( !is.list(yml$format) || !"format" %in% names(yml)) {
yml$format <- list()
}
if (!output_format %in% names(yml$format)) {
# append output_format
yml$format[[output_format]] <- quarto_defaults[[output_format]]
}
}
# get previous values
old_css <- yml$format[[output_format]]$css
old_js <- yml$format[[output_format]]$`include-after-body`
# merge with new values
yml$format[[output_format]]$css <- union(old_css, css_path)
yml$format[[output_format]]$`include-after-body` <- union(old_js, js_path)
# write to _quarto.yml
# custom handler to stop converting boolean values to yes and no
yaml::write_yaml(yml, quarto_file, handlers = list(
logical = function(x) {
result <- ifelse(x, "true", "false")
class(result) <- "verbatim"
return(result)
}
))
message(quarto_file, " updated")
# update .Rprofile
rprofile <- file.path(quarto_dir, ".Rprofile")
load_txt <- "# load webexercises before each chapter
# needs to check namespace to not bork github actions
if (requireNamespace('webexercises', quietly = TRUE)) library(webexercises)"
write(load_txt, rprofile, append = TRUE)
invisible(NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/webexercises/R/add_to_quarto.R
|
#' Create a quarto document with webexercise
#'
#' Creates a new directory with the file name and copies in a demo qmd file and the necessary helper files.
#'
#' @param name Name of the new document
#' @param open Whether to open the document in RStudio
#'
#' @return The file path to the document
#' @export
#'
create_quarto_doc <- function(name = "Untitled", open = interactive()) {
if (!file.exists(name)) dir.create(name, FALSE, TRUE)
path <- normalizePath(name)
filepath <- file.path(path, paste0(basename(name), ".qmd"))
# get helper files
css <- system.file("reports/default/webex.css", package = "webexercises")
js <- system.file("reports/default/webex.js", package = "webexercises")
index <- system.file("reports/default/index.qmd", package = "webexercises")
file.copy(css, path)
file.copy(js, path)
file.copy(index, filepath)
if (open) rstudioapi::documentOpen(filepath)
invisible(filepath)
}
|
/scratch/gouwar.j/cran-all/cranData/webexercises/R/quarto.R
|
#' Create default webexercises document
#'
#' This function wraps \code{rmarkdown::html_document} to configure
#' compilation to embed the default webexercises CSS and JavaScript files in
#' the resulting HTML.
#'
#' @details Call this function as the \code{output_format} argument
#' for the \code{\link[rmarkdown]{render}} function when compiling
#' HTML documents from RMarkdown source.
#'
#' @param ... Additional function arguments to pass to
#' \code{\link[rmarkdown]{html_document}}.
#'
#' @return R Markdown output format to pass to 'render'.
#'
#' @seealso \code{\link[rmarkdown]{render}}, \code{\link[rmarkdown]{html_document}}
#'
#' @examples
#' # copy the webexercises 'R Markdown' template to a temporary file
#' \dontrun{
#' my_rmd <- tempfile(fileext = ".Rmd")
#' rmarkdown::draft(my_rmd, "webexercises", "webexercises")
#'
#' # compile it
#' rmarkdown::render(my_rmd, webexercises::webexercises_default())
#'
#' # view the result
#' browseURL(sub("\\.Rmd$", ".html", my_rmd))
#' }
#' @export
webexercises_default <- function(...) {
css <- system.file("reports/default/webex.css", package = "webexercises")
js <- system.file("reports/default/webex.js", package = "webexercises")
setup_hide_knithook()
# smart quotes changed in rmarkdown 2.2 / pandoc 2.0.6
rmarkdown::pandoc_available(version = "2.0.6", error = TRUE)
rmarkdown::html_document(css = css,
includes = rmarkdown::includes(after_body = js),
md_extensions = "-smart",
...)
}
setup_hide_knithook <- function() {
knitr::knit_hooks$set(webex.hide = function(before, options, envir) {
if (before) {
if (is.character(options$webex.hide)) {
hide(options$webex.hide)
} else {
hide()
}
} else {
unhide()
}
})
invisible()
}
|
/scratch/gouwar.j/cran-all/cranData/webexercises/R/webexercises_default.R
|
#' Create a fill-in-the-blank question
#'
#' @param answer The correct answer (can be a vector if there is more
#' than one correct answer).
#' @param width Width of the input box in characters. Defaults to the
#' length of the longest answer.
#' @param num Whether the input is numeric, in which case allow for
#' leading zeroes to be omitted. Determined from the answer data
#' type if not specified.
#' @param tol The tolerance within which numeric answers will be
#' accepted; i.e. if \code{abs(response - true.answer) < tol}, the
#' answer is correct (implies \code{num=TRUE}).
#' @param ignore_case Whether to ignore case (capitalization).
#' @param ignore_ws Whether to ignore whitespace.
#' @param regex Whether to use regex to match answers (concatenates
#' all answers with `|` before matching).
#' @details Writes html code that creates an input box widget. Call
#' this function inline in an RMarkdown document. See the Web
#' Exercises RMarkdown template for examples of its use in
#' RMarkdown.
#'
#' @return A character string with HTML code to generate an input box.
#'
#' @examples
#' # What is 2 + 2?
#' fitb(4, num = TRUE)
#'
#' # What was the name of the Beatles drummer?
#' fitb(c("Ringo", "Ringo Starr"), ignore_case = TRUE)
#'
#' # What is pi to three decimal places?
#' fitb(pi, num = TRUE, tol = .001)
#' @export
fitb <- function(answer,
width = calculated_width,
num = NULL,
ignore_case = FALSE,
tol = NULL,
ignore_ws = TRUE,
regex = FALSE) {
# make sure answer is a numeric or character vector
answer <- unlist(answer)
if (!is.vector(answer) ||
(!is.numeric(answer) && !is.character(answer))) {
stop("The answer must be a vector of characters or numbers.")
}
# set numeric based on data type if num is NULL
if (is.null(num)) num <- is.numeric(answer)
# if tol is set, assume numeric
if (!is.null(tol)) num <- TRUE
# add zero-stripped versions if numeric
if (num) {
answer2 <- strip_lzero(answer)
answer <- union(answer, answer2)
}
# if width not set, calculate it from max length answer, up to limit of 100
calculated_width <- min(100, max(nchar(answer)))
answers <- jsonlite::toJSON(as.character(answer))
answers <- gsub("\'", "'", answers, fixed = TRUE)
# html format
html <- paste0("<input class='webex-solveme",
ifelse(ignore_ws, " nospaces", ""),
ifelse(!is.null(tol), paste0("' data-tol='", tol, ""), ""),
ifelse(ignore_case, " ignorecase", ""),
ifelse(regex, " regex", ""),
"' size='", width,
"' data-answer='", answers, "'/>")
# pdf / other format
pdf <- paste(rep("_", width), collapse = "")
# check type of knitting
out_fmt <- knitr::opts_knit$get("out.format")
pandoc_to <- knitr::opts_knit$get("rmarkdown.pandoc.to")
ifelse((is.null(out_fmt) & is.null(pandoc_to)) ||
isTRUE(out_fmt == "html") ||
isTRUE(pandoc_to == "html"),
html, pdf)
}
#' Create a multiple-choice question
#'
#' @param opts Vector of alternatives. The correct answer is the
#' element(s) of this vector named 'answer'.
#' @details Writes html code that creates an option box widget, with one or
#' more correct answers. Call this function inline in an RMarkdown document.
#' See the Web Exercises RMarkdown template for further examples.
#'
#' @return A character string with HTML code to generate a pull-down
#' menu.
#'
#' @examples
#' # How many planets orbit closer to the sun than the Earth?
#' mcq(c(1, answer = 2, 3))
#'
#' # Which actor played Luke Skywalker in the movie Star Wars?
#' mcq(c("Alec Guinness", answer = "Mark Hamill", "Harrison Ford"))
#' @export
mcq <- function(opts) {
ix <- which(names(opts) == "answer")
if (length(ix) == 0) {
stop("MCQ has no correct answer")
}
# html format
options <- sprintf("<option value='%s'>%s</option>", names(opts), opts)
html <- sprintf("<select class='webex-select'><option value='blank'></option>%s</select>",
paste(options, collapse = ""))
# pdf / other format
pdf_opts <- sprintf("* (%s) %s ", LETTERS[seq_along(opts)], opts)
pdf <- paste0("\n\n", paste(pdf_opts, collapse = "\n"), "\n\n")
# check type of knitting
out_fmt <- knitr::opts_knit$get("out.format")
pandoc_to <- knitr::opts_knit$get("rmarkdown.pandoc.to")
ifelse((is.null(out_fmt) & is.null(pandoc_to)) ||
isTRUE(out_fmt == "html") ||
isTRUE(pandoc_to == "html"),
html, pdf)
}
#' Create a true-or-false question
#'
#' @param answer Logical value TRUE or FALSE, corresponding to the correct answer.
#' @details Writes html code that creates an option box widget with TRUE or FALSE as alternatives. Call this function inline in an RMarkdown document. See the Web Exercises RMarkdown template for further examples.
#'
#' @return A character string with HTML code to generate a pull-down
#' menu with elements TRUE and FALSE.
#'
#' @examples
#' # True or False? 2 + 2 = 4
#' torf(TRUE)
#'
#' # True or False? The month of April has 31 days.
#' torf(FALSE)
#' @export
torf <- function(answer) {
opts <- c("TRUE", "FALSE")
if (answer)
names(opts) <- c("answer", "")
else
names(opts) <- c("", "answer")
# check type of knitting
out_fmt <- knitr::opts_knit$get("out.format")
pandoc_to <- knitr::opts_knit$get("rmarkdown.pandoc.to")
ifelse((is.null(out_fmt) & is.null(pandoc_to)) ||
isTRUE(out_fmt == "html") ||
isTRUE(pandoc_to == "html"),
mcq(opts), "TRUE / FALSE")
}
#' Longer MCQs with Radio Buttons
#'
#' @param opts Vector of alternatives. The correct answer is the
#' element(s) of this vector named 'answer'.
#' @details Writes html code that creates a radio button widget, with a
#' single correct answer. This is more suitable for longer answers. Call this function inline in an RMarkdown
#' document. See the Web Exercises RMarkdown template for further
#' examples.
#'
#' @return A character string containing HTML code to create a set of
#' radio buttons.
#'
#' @examples
#' # What is a p-value?
#' opts <- c(
#' "the probability that the null hypothesis is true",
#' answer = paste("the probability of the observed, or more extreme, data",
#' "under the assumption that the null-hypothesis is true"),
#' "the probability of making an error in your conclusion"
#' )
#'
#' longmcq(opts)
#'
#' @export
longmcq <- function(opts) {
ix <- which(names(opts) == "answer")
if (length(ix) == 0) {
stop("The question has no correct answer")
}
opts2 <- gsub("\'", "'", opts, fixed = TRUE)
# make up a name to group them
qname <- paste0("radio_", paste(sample(LETTERS, 10, T), collapse = ""))
options <- sprintf('<label><input type="radio" autocomplete="off" name="%s" value="%s"></input> <span>%s</span></label>', qname, names(opts), opts2)
# html format
html <- paste0("<div class='webex-radiogroup' id='", qname, "'>",
paste(options, collapse = ""),
"</div>\n")
# pdf / other format
pdf_opts <- sprintf("* (%s) %s ", LETTERS[seq_along(opts2)], opts2)
pdf <- paste0("\n\n", paste(pdf_opts, collapse = "\n"), "\n\n")
# check type of knitting
out_fmt <- knitr::opts_knit$get("out.format")
pandoc_to <- knitr::opts_knit$get("rmarkdown.pandoc.to")
ifelse((is.null(out_fmt) & is.null(pandoc_to)) ||
isTRUE(out_fmt == "html") ||
isTRUE(pandoc_to == "html"),
html, pdf)
}
#' Create button revealing hidden content
#'
#' @param button_text Text to appear on the button that reveals the hidden content.
#' @seealso \code{unhide}
#'
#' @details Writes HTML to create a content that is revealed by a
#' button press. Call this function inline in an RMarkdown
#' document. Any content appearing after this call up to an inline
#' call to \code{unhide()} will only be revealed when the user
#' clicks the button. See the Web Exercises RMarkdown Template for
#' examples.
#'
#' @return A character string containing HTML code to create a button
#' that reveals hidden content.
#'
#' @examples
#' # default behavior is to generate a button that says "Solution"
#' hide()
#'
#' # or the button can display custom text
#' hide("Click here for a hint")
#' @export
hide <- function(button_text = "Solution") {
rmd <- !is.null(getOption("knitr.in.progress"))
if (rmd) {
paste0("\n<div class='webex-solution'><button>", button_text, "</button>\n")
} else {
paste0("\n::: {.callout-note collapse='true'}\n## ", button_text, "\n\n")
}
}
#' End hidden HTML content
#'
#' @seealso \code{hide}
#'
#' @details Call this function inline in an RMarkdown document to mark
#' the end of hidden content (see the Web Exercises RMarkdown
#' Template for examples).
#'
#' @return A character string containing HTML code marking the end of
#' hiddent content.
#'
#' @examples
#' # just produce the closing </div>
#' unhide()
#' @export
unhide <- function() {
rmd <- !is.null(getOption("knitr.in.progress"))
if (rmd) {
"\n</div>\n"
} else {
"\n:::\n\n"
}
}
#' Change webexercises widget style
#'
#' @param incorrect The colour of the widgets when the answer is incorrect (defaults to pink #983E82).
#'
#' @param correct The colour of the widgets when the correct answer
#' not filled in (defaults to green #59935B).
#'
#' @param highlight The colour of the borders around hidden blocks and
#' checked sections (defaults to blue #467AAC).
#'
#' @return A character string containing HTML code to change the CSS
#' style values for widgets.
#'
#' @details Call this function in an RMarkdown document to
#' change the feedback colours using R colour names (see `colours()`)
#' or any valid CSS colour specification (e.g., red, rgb(255,0,0),
#' hsl(0, 100%, 50%) or #FF0000).
#'
#' If you want more control over the widget styles, please edit the
#' webex.css file directly.
#'
#' @examples
#' style_widgets("goldenrod", "purple")
#' @export
style_widgets <- function(incorrect = "#983E82",
correct = "#59935B",
highlight = "#467AAC") {
# default if not R colour or hex
i_border <- incorrect
i_bg <- incorrect
c_border <- correct
c_bg <- correct
h_border <- highlight
if (highlight %in% grDevices::colours()) {
hrgb <- grDevices::col2rgb(highlight, alpha = FALSE)
h_border <- paste0("rgb(", paste(hrgb, collapse = ", "), ")")
}
if (incorrect %in% grDevices::colours()) {
irgb <- grDevices::col2rgb(incorrect, alpha = FALSE)
i_border <- paste0("rgb(", paste(irgb, collapse = ", "), ")")
i_bg <- paste0("rgba(", paste(irgb, collapse = ", "), ", 0.25)")
} else if (substr(incorrect, 1, 1) == "#") {
d_bg <- paste0(incorrect, "DD")
}
if (correct %in% grDevices::colours()) {
crgb <- grDevices::col2rgb(correct, alpha = FALSE)
c_border <- paste0("rgb(", paste(crgb, collapse = ", "), ")")
c_bg <- paste0("rgba(", paste(crgb, collapse = ", "), ", 0.25)")
} else if (substr(correct, 1, 1) == "#") {
c_bg <- paste0(correct, "DD")
}
style <- paste0(
"\n<style>\n",
":root {\n",
" --incorrect: ", i_border, ";\n",
" --incorrect_alpha: ", i_bg, ";\n",
" --correct: ", c_border, ";\n",
" --correct_alpha: ", c_bg, ";\n",
" --highlight: ", h_border, ";\n",
"}\n",
" .webex-incorrect, input.webex-solveme.webex-incorrect,\n",
" .webex-radiogroup label.webex-incorrect {\n",
" border: 2px dotted var(--incorrect);\n",
" background-color: var(--incorrect_alpha);\n",
" }\n",
" .webex-correct, input.webex-solveme.webex-correct,\n",
" .webex-radiogroup label.webex-correct {\n",
" border: 2px dotted var(--correct);\n",
" background-color: var(--correct_alpha);\n",
" }\n",
" .webex-box, .webex-solution.open {\n",
" border: 2px solid var(--highlight);n",
" }\n",
" .webex-solution button, .webex-check-button {\n",
" background-color: var(--highlight);\n",
" }\n",
"</style>\n\n"
)
cat(style)
}
#' Display total correct
#'
#' @param elem The html element to display (e.g., div, h3, p, span)
#' @param args Optional arguments for css classes or styles
#'
#' @return A string with the html for displaying a total correct element.
#'
#' @export
total_correct <- function(elem = "span", args = "") {
.Deprecated(".webex-check sections",
package = "webexercises",
old = "total_correct",
msg = "The function webexercises::total_correct() is deprecated. Use sections with the class 'webex-check' to set up self-checking mini-quizzes with total correct.")
#sprintf("<%s %s class=\"webex-total_correct\"></%s>\n\n",
# elem, args, elem)
}
#' Round up from .5
#'
#' @param x A vector of numeric values.
#'
#' @param digits Integer indicating the number of decimal places (`round`) or significant digits (`signif`) to be used.
#'
#' @details Implements rounding using the "round up from .5" rule,
#' which is more conventional than the "round to even" rule
#' implemented by R's built-in \code{\link{round}} function. This
#' implementation was taken from
#' \url{https://stackoverflow.com/a/12688836}.
#'
#' @return A vector of rounded numeric values.
#'
#' @examples
#' round2(c(2, 2.5))
#'
#' # compare to:
#' round(c(2, 2.5))
#' @export
round2 <- function(x, digits = 0) {
posneg = sign(x)
z = abs(x)*10^digits
z = z + 0.5
z = trunc(z)
z = z/10^digits
z*posneg
}
#' Strip leading zero from numeric string
#'
#' @param x A numeric string (or number that can be converted to a string).
#'
#' @return A string with leading zero removed.
#'
#' @examples
#' strip_lzero("0.05")
#' @export
strip_lzero <- function(x) {
sub("^([+-]*)0\\.", "\\1.", x)
}
#' Escape a string for regex
#'
#' @param string A string to escape.
#'
#' @return A string with escaped characters.
#' @export
#'
#' @examples
#' escape_regex("library(tidyverse)")
escape_regex <- function(string) {
gsub("([.|()\\^{}+$*?]|\\[|\\])", "\\\\\\1", string)
}
|
/scratch/gouwar.j/cran-all/cranData/webexercises/R/webexercises_fns.R
|
.onLoad <- function(libname, pkgname) {
# sets up webex.hide chunk option
setup_hide_knithook()
}
|
/scratch/gouwar.j/cran-all/cranData/webexercises/R/zzz.R
|
---
title: "My Book"
author: "Me"
date: "`r Sys.Date()`"
site: bookdown::bookdown_site
documentclass: book
bibliography: packages.bib
link-citations: yes
description: |
This book ...
---
```{r cite-packages, include = FALSE}
# automatically create a bib database for R packages
# add any packages you want to cite here
knitr::write_bib(c(
.packages(), 'bookdown', 'webexercises'
), 'packages.bib')
```
```{r, echo = FALSE, results='asis'}
# Uncomment to change widget colours:
#style_widgets(incorrect = "goldenrod", correct = "purple", highlight = "firebrick")
```
# Webexercises {-}
This is a Web Exercise template created by the [#PsyTeachR team at the University of Glasgow](https://psyteachr.github.io), based on ideas from [Software Carpentry](https://software-carpentry.org/lessons/). This template shows how instructors can easily create interactive web documents that students can use in self-guided learning.
The `{webexercises}` package provides a number of functions that you use in [inline R code](https://github.com/rstudio/cheatsheets/raw/main/rmarkdown.pdf) or through code chunk options to create HTML widgets (text boxes, pull down menus, buttons that reveal hidden content). Examples are given next. Render the book to see how they work.
**NOTE: To use the widgets in the compiled HTML files, you need to have a JavaScript-enabled browser.**
## Example Questions
These functions are optimised to be used with inline r code, but you can also use them in code chunks by setting the chunk option `results = 'asis'` and using `cat()` to display the result of the widget.
```{r, results = 'asis'}
# echo = FALSE, results = 'asis'
opts <- c("install.package",
"install.packages",
answer = "library",
"libraries")
q1 <- mcq(opts)
cat("What function loads a package that is already on your computer?", q1)
```
### Fill-In-The-Blanks (`fitb()`)
Create fill-in-the-blank questions using `fitb()`, providing the answer as the first argument.
- 2 + 2 is `r fitb(4)`
You can also create these questions dynamically, using variables from your R session.
```{r echo = FALSE}
x <- sample(2:8, 1)
```
- The square root of `r x^2` is: `r fitb(x)`
The blanks are case-sensitive; if you don't care about case, use the argument `ignore_case = TRUE`.
- What is the letter after D? `r fitb("E", ignore_case = TRUE)`
If you want to ignore differences in whitespace use, use the argument `ignore_ws = TRUE` (which is the default) and include spaces in your answer anywhere they could be acceptable.
- How do you load the tidyverse package? `r fitb(c("library( tidyverse )", "library( \"tidyverse\" )", "library( 'tidyverse' )"), ignore_ws = TRUE, width = "20")`
You can set more than one possible correct answer by setting the answers as a vector.
- Type a vowel: `r fitb(c("A", "E", "I", "O" , "U"), ignore_case = TRUE)`
You can use regular expressions to test answers against more complex rules.
- Type any 3 letters: `r fitb("^[a-zA-Z]{3}$", width = 3, regex = TRUE)`
### Multiple Choice (`mcq()`)
- "Never gonna give you up, never gonna: `r mcq(c("let you go", "turn you down", "run away", answer = "let you down"))`"
- "I `r mcq(c(answer = "bless the rains", "guess it rains", "sense the rain"))` down in Africa" -Toto
### True or False (`torf()`)
- True or False? You can permute values in a vector using `sample()`. `r torf(TRUE)`
### Longer MCQs (`longmcq()`)
When your answers are very long, sometimes a drop-down select box gets formatted oddly. You can use `longmcq()` to deal with this. Since the answers are long, It's probably best to set up the options inside an R chunk with `echo=FALSE`.
**What is a p-value?**
```{r, echo = FALSE}
opts_p <- c(
"the probability that the null hypothesis is true",
answer = "the probability of the observed, or more extreme, data, under the assumption that the null-hypothesis is true",
"the probability of making an error in your conclusion"
)
```
`r longmcq(opts_p)`
**What is true about a 95% confidence interval of the mean?**
```{r, echo = FALSE}
# use sample() to randomise the order
opts_ci <- sample(c(
answer = "if you repeated the process many times, 95% of intervals calculated in this way contain the true mean",
"there is a 95% probability that the true mean lies within this range",
"95% of the data fall within this range"
))
```
`r longmcq(opts_ci)`
## Checked sections
Create sections with the class `webex-check` to add a button that hides feedback until it is pressed. Add the class `webex-box` to draw a box around the section (or use your own styles).
::: {.webex-check .webex-box}
I am going to learn a lot: `r torf(TRUE)`
```{r, echo=FALSE, results='asis'}
opts <- c(
"the probability that the null hypothesis is true",
answer = "the probability of the observed, or more extreme, data, under the assumption that the null-hypothesis is true",
"the probability of making an error in your conclusion"
)
cat("What is a p-value?", longmcq(opts))
```
:::
## Hidden solutions and hints
You can fence off a solution area that will be hidden behind a button using `hide()` before the solution and `unhide()` after, each as inline R code. Pass the text you want to appear on the button to the `hide()` function.
If the solution is an RMarkdown code chunk, instead of using `hide()` and `unhide()`, simply set the `webex.hide` chunk option to TRUE, or set it to the string you wish to display on the button.
**Recreate the scatterplot below, using the built-in `cars` dataset.**
```{r echo = FALSE}
with(cars, plot(speed, dist))
```
`r hide("I need a hint")`
See the documentation for `plot()` (`?plot`)
`r unhide()`
<!-- note: you could also just set webex.hide to TRUE -->
```{r eval = FALSE, webex.hide="Click here to see the solution"}
plot(cars$speed, cars$dist)
```
|
/scratch/gouwar.j/cran-all/cranData/webexercises/inst/reports/default/index.Rmd
|
library(webexercises)
|
/scratch/gouwar.j/cran-all/cranData/webexercises/inst/reports/default/webex.R
|
---
title: "Web Exercises"
output: webexercises::webexercises_default
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(webexercises)
```
```{r, echo = FALSE, results='asis'}
# Uncomment to change widget colours:
#style_widgets(incorrect = "goldenrod", correct = "purple")
```
This is a Web Exercise template created by the [#PsyTeachR team at the University of Glasgow](https://psyteachr.github.io), based on ideas from [Software Carpentry](https://software-carpentry.org/lessons/). This template shows how instructors can easily create interactive web documents that students can use in self-guided learning.
The `{webexercises}` package provides a number of functions that you use in [inline R code](https://github.com/rstudio/cheatsheets/raw/main/rmarkdown.pdf) or through code chunk options to create HTML widgets (text boxes, pull down menus, buttons that reveal hidden content). Examples are given below. Knit this file to HTML to see how it works.
**NOTE: To use the widgets in the compiled HTML file, you need to have a JavaScript-enabled browser.**
## Fill-In-The-Blanks (`fitb()`)
Create fill-in-the-blank questions using `fitb()`, providing the answer as the first argument.
- 2 + 2 is `r fitb(4)`
You can also create these questions dynamically, using variables from your R session.
```{r}
x <- sample(2:8, 1)
```
- The square root of `r x^2` is: `r fitb(x)`
The blanks are case-sensitive; if you don't care about case, use the argument `ignore_case = TRUE`.
- What is the letter after D? `r fitb("E", ignore_case = TRUE)`
If you want to ignore differences in whitespace use, use the argument `ignore_ws = TRUE` (which is the default) and include spaces in your answer anywhere they could be acceptable.
- How do you load the tidyverse package? `r fitb(c("library( tidyverse )", "library( \"tidyverse\" )", "library( 'tidyverse' )"), ignore_ws = TRUE, width = "20")`
You can set more than one possible correct answer by setting the answers as a vector.
- Type a vowel: `r fitb(c("A", "E", "I", "O" , "U"), ignore_case = TRUE)`
You can use regular expressions to test answers against more complex rules.
- Type any 3 letters: `r fitb("^[a-zA-Z]{3}$", width = 3, regex = TRUE)`
## Multiple Choice (`mcq()`)
- "Never gonna give you up, never gonna: `r mcq(c("let you go", "turn you down", "run away", answer = "let you down"))`"
- "I `r mcq(c(answer = "bless the rains", "guess it rains", "sense the rain"))` down in Africa" -Toto
## True or False (`torf()`)
- True or False? You can permute values in a vector using `sample()`. `r torf(TRUE)`
## Longer MCQs (`longmcq()`)
When your answers are very long, sometimes a drop-down select box gets formatted oddly. You can use `longmcq()` to deal with this. Since the answers are long, It's probably best to set up the options inside an R chunk with `echo=FALSE`.
**What is a p-value?**
```{r}
opts_p <- c(
"the probability that the null hypothesis is true",
answer = "the probability of the observed, or more extreme, data, under the assumption that the null-hypothesis is true",
"the probability of making an error in your conclusion"
)
```
`r longmcq(opts_p)`
**What is true about a 95% confidence interval of the mean?**
```{r}
# use sample() to randomise the order
opts_ci <- sample(c(
answer = "if you repeated the process many times, 95% of intervals calculated in this way contain the true mean",
"there is a 95% probability that the true mean lies within this range",
"95% of the data fall within this range"
))
```
`r longmcq(opts_ci)`
## Checked sections
Create sections with the class `webex-check` to add a button that hides feedback until it is pressed. Add the class `webex-box` to draw a box around the section (or use your own styles).
::: {.webex-check .webex-box}
I am going to learn a lot: `r torf(TRUE)`
```{r, results='asis'}
opts <- c(
"the probability that the null hypothesis is true",
answer = "the probability of the observed, or more extreme, data, under the assumption that the null-hypothesis is true",
"the probability of making an error in your conclusion"
)
cat("What is a p-value?", longmcq(opts))
```
:::
## Hidden solutions and hints
You can fence off a solution area that will be hidden behind a button using `hide()` before the solution and `unhide()` after, each as inline R code. Pass the text you want to appear on the button to the `hide()` function.
If the solution is an RMarkdown code chunk, instead of using `hide()` and `unhide()`, simply set the `webex.hide` chunk option to TRUE, or set it to the string you wish to display on the button.
**Recreate the scatterplot below, using the built-in `cars` dataset.**
```{r}
with(cars, plot(speed, dist))
```
`r hide("I need a hint")`
See the documentation for `plot()` (`?plot`)
`r unhide()`
<!-- note: you could also just set webex.hide to TRUE -->
```{r, echo = TRUE, eval = FALSE, webex.hide="Click here to see the solution"}
plot(cars$speed, cars$dist)
```
|
/scratch/gouwar.j/cran-all/cranData/webexercises/inst/rmarkdown/templates/webexercises/skeleton/skeleton.Rmd
|
#' Run a webfakes app in another process
#'
#' Runs an app in a subprocess, using [callr::r_session].
#'
#' @param app `webfakes_app` object, the web app to run.
#' @param port Port to use. By default the OS assigns a port.
#' @param opts Server options. See [server_opts()] for the defaults.
#' @param start Whether to start the web server immediately. If this is
#' `FALSE`, and `auto_start` is `TRUE`, then it is started as neeed.
#' @param auto_start Whether to start the web server process automatically.
#' If `TRUE` and the process is not running, then `$start()`,
#' `$get_port()` and `$url()` start the process.
#' @param process_timeout How long to wait for the subprocess to start, in
#' milliseconds.
#' @param callr_opts Options to pass to [callr::r_session_options()]
#' when setting up the subprocess.
#' @return A `webfakes_app_process` object.
#'
#' ## Methods
#'
#' The `webfakes_app_process` class has the following methods:
#'
#' ```r
#' get_app()
#' get_port()
#' stop()
#' get_state()
#' local_env(envvars)
#' url(path = "/", query = NULL)
#' ```
#'
#' * `envvars`: Named list of environment variables. The `{url}` substring
#' is replaced by the URL of the app.
#' * `path`: Path to return the URL for.
#' * `query`: Additional query parameters, a named list, to add to the URL.
#'
#' `get_app()` returns the app object.
#'
#' `get_port()` returns the port the web server is running on.
#'
#' `stop()` stops the web server, and also the subprocess. If the error
#' log file is not empty, then it dumps its contents to the screen.
#'
#' `get_state()` returns a string, the state of the web server:
#' * `"not running"` the server is not running (because it was stopped
#' already).
#' * `"live"` means that the server is running.
#' * `"dead"` means that the subprocess has quit or crashed.
#'
#' `local_env()` sets the given environment variables for the duration of
#' the app process. It resets them in `$stop()`. Webfakes replaces `{url}`
#' in the value of the environment variables with the app URL, so you can
#' set environment variables that point to the app.
#'
#' `url()` returns the URL of the web app. You can use the `path`
#' parameter to return a specific path.
#'
#' @aliases webfakes_app_process
#' @seealso [local_app_process()] for automatically cleaning up the
#' subprocess.
#' @export
#' @examples
#' app <- new_app()
#' app$get("/foo", function(req, res) {
#' res$send("Hello world!")
#' })
#'
#' proc <- new_app_process(app)
#' url <- proc$url("/foo")
#' resp <- curl::curl_fetch_memory(url)
#' cat(rawToChar(resp$content))
#'
#' proc$stop()
new_app_process <- function(app, port = NULL,
opts = server_opts(remote = TRUE),
start = FALSE, auto_start = TRUE,
process_timeout = NULL,
callr_opts = NULL) {
app; port; opts; start; auto_start; process_timeout; callr_opts
# WTF
tmp <- tempfile()
sink(tmp); print(app$.stack); sink(NULL)
unlink(tmp)
process_timeout <- process_timeout %||%
as.integer(Sys.getenv("R_WEBFAKES_PROCESS_TIMEOUT", 5000))
self <- new_object(
"webfakes_app_process",
start = function() {
self$.app <- app
callr_opts <- do.call(callr::r_session_options, as.list(callr_opts))
self$.process <- callr::r_session$new(callr_opts, wait = TRUE)
self$.process$call(
args = list(app, port, opts),
function(app, port, opts) {
library(webfakes)
.GlobalEnv$app <- app
app$listen(port = port, opts = opts)
}
)
if (self$.process$poll_process(process_timeout) != "ready") {
self$.process$kill()
stop("webfakes app subprocess did not start :(")
}
msg <- self$.process$read()
if (msg$code == 200 && !is.null(msg$error)) {
msg$error$message <- paste0(
"failed to start webfakes app process: ",
msg$error$message
)
stop(msg$error)
}
if (msg$code != 301) {
stop("Unexpected message from webfakes app subprocess. ",
"Report a bug please.")
}
self$.port <- msg$message$port
self$.access_log <- msg$message$access_log
self$.error_log <- msg$message$error_log
self$.set_env()
invisible(self)
},
get_app = function() self$.app,
get_port = function() {
if (self$get_state() == "not running" && auto_start) self$start()
self$.port
},
stop = function() {
self$.reset_env()
if (is.null(self$.process)) return(invisible(self))
if (!self$.process$is_alive()) {
status <- self$.process$get_exit_status()
out <- err <- NULL
try_silently(out <- self$.process$read_output())
try_silently(err <- self$.process$read_error())
cat0("webfakes process dead, exit code: ", status, "\n")
if (!is.null(out)) cat0("stdout:", out, "\n")
if (!is.null(err)) cat0("stderr:", err, "\n")
}
# The details are important here, for the sake of covr,
# so that we can test the webfakes package itself.
# 1. The subprocess serving the app is in Sys.sleep(), which we
# need to interrupt first.
# 2. Then we need to read out the result of that $call()
# (i.e. the interruption), because otherwise the subprocess is
# stuck at a blocking write() system call, and cannot be
# interrupted in the $close() call, and will be killed, and
# then it cannot write out the coverage results.
# 3. Once we $read(), we can call $close() because that will
# close the standard input of the subprocess, which is reading
# the standard input, so it will quit.
self$.process$interrupt()
self$.process$poll_process(1000)
try_silently(self$.process$read())
try_silently(self$.process$close())
self$.print_errors()
self$.process <- NULL
invisible(self)
},
get_state = function() {
if (is.null(self$.process)) {
"not running"
} else if (self$.process$is_alive()) {
"live"
} else {
"dead"
}
},
local_env = function(envvars) {
if (!is.null(self$.process)) {
local <- unlist(envvars)
local[] <- gsub("{url}", self$url(), local, fixed = TRUE)
self$.old_env <- c(self$.old_env, set_envvar(local))
} else {
self$.local_env <- utils::modifyList(
as.list(self$.local_env),
as.list(envvars)
)
}
invisible(self)
},
.set_env = function() {
local <- unlist(self$.local_env)
local[] <- gsub("{url}", self$url(), local, fixed = TRUE)
self$.old_env <- set_envvar(local)
invisible(self)
},
.reset_env = function() {
if (!is.null(self$.old_env)) {
set_envvar(self$.old_env)
self$.old_env <- NULL
}
},
url = function(path = "/", query = NULL) {
if (self$get_state() == "not running" && auto_start) self$start()
if (!is.null(query)) {
query <- paste0("?", paste0(names(query), "=", query, collapse = "&"))
}
paste0("http://127.0.0.1:", self$.port, path, query)
},
.process = NULL,
.app = NULL,
.port = NULL,
.old_env = NULL,
.access_log = NA_character_,
.error_log = NA_character_,
.auto_start = auto_start,
.print_errors = function() {
if (!is.na(self$.error_log) && file.exists(self$.error_log) &&
file.info(self$.error_log)$size > 0) {
err <- readLines(self$.error_log, warn = FALSE)
cat("webfakes web server errors:\n")
cat(err, sep = "\n")
}
}
)
reg.finalizer(self, function(x) x$.reset_env())
if (start) self$start()
self
}
|
/scratch/gouwar.j/cran-all/cranData/webfakes/R/app-process.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.