content
stringlengths
0
14.9M
filename
stringlengths
44
136
# {{{ Wally plot function # {{{ header ##' ##' Wally plots to assess calibration of a risk or survival prediction ##' ##' @title Wally plots to assess calibration of a risk or survival prediction ##' @param object Probabilistic survival predictions or probabilistic event risk predictions ##' evaluated at \code{time} for the subjects in \code{data}. Either ##' given in form of a numeric vector of probabilistic predictions or ##' as an object which has a \code{predictRisk} method ##' @param time Time interest for evaluating calibration of the ##' predictions. ##' @param formula A survival or event history formula. The left hand ##' side is used to compute the expected event status. If ##' \code{formula} is \code{missing}, try to extract a formula from ##' the first element in object. ##' @param data A data frame in which to validate the prediction ##' models and to fit the censoring model. If \code{data} is missing, ##' try to extract a data set from the first element in object. ##' @param cause For competing risks settings the cause of interest. ##' @param q The number of quantiles. Defaults to 10. ##' @param ylim Limits of y-axis. If missing the function tries to ##' find appropriate limits based on the simulated and real data. ##' @param hanging If \code{TRUE}, hang bars corresponding to observed ##' frequencies at the value of the corresponding prediction. ##' @param seed A seed value to make results reproducible. ##' @param mar Plot margins passed to par. ##' @param colbox Color of the box which identifies the real data ##' calibration plot. ##' @param verbose If \code{TRUE} warn about missing formula and data. ##' @param col Colour of the bars. ##' @param xlab Label for x-axis ##' @param labels Label below the bars. Either \code{"quantiles"} or \code{"quantiles.label"} ##' @param ... Further arguments passed to the subroutine \code{wallyCalPlot} and if \code{hanging} ##' is \code{TRUE} also to subroutine \code{lines}. ##' @return List of simulated and real data. ##' @references ##' Blanche P, Gerds T A, Ekstrom C T (2017). The Wally plot approach to assess the ##' calibration of clinical prediction models, submitted. ##' ##' ##' ##' @examples ##' ##' # Survival setting ##' library(prodlim) ##' library(data.table) ##' library(survival) ##' set.seed(180) ##' d = SimSurv(180) ##' f = coxph(Surv(time,status)~X1+X2,data=d,x=TRUE) ##' \dontrun{ ##' wallyPlot(f, ##' time=4, ##' q=10, ##' data=d, ##' formula=Surv(time,status)~1) ##' wallyPlot(f, ##' time=4, ##' q=10, ##' hanging=TRUE, ##' data=d, ##' formula=Surv(time,status)~1) ##' } ##' ##' # Competing risks setting ##' library(prodlim) ##' library(survival) ##' library(riskRegression) ##' set.seed(180) ##' d2 = SimCompRisk(180) ##' f2 = CSC(Hist(time,event)~X1+X2,data=d2) ##' \dontrun{ ##' wallyPlot(f2, ##' time=5, ##' q=3, ##' hanging=TRUE, ##' data=d2, ##' formula=Hist(time,event)~1) ##' ##' } ##' ##' # Reproduce Wally plots presented in Blanche et al. (2017) ##' \dontrun{ ##' data(threecity) ##' wallyPlot(threecity$pi, ##' time=5, ##' hanging=TRUE, ##' formula=Hist(time,status)~1, ##' data=threecity, ##' ylim=c(-.1,.25), ##' seed= 511, ##' hline.lwd=3, ##' mar=c(1.01, 4.1, 1.15, 2)) ##' } ##' ##' \dontrun{ ##' data(divat) ##' wallyPlot(divat$pi, ##' time=5, ##' hanging=TRUE, ##' formula=Hist(time,status)~1, ##' data=divat, ##' ylim=c(-.1,.60), ##' seed= 123459, ##' hline.lwd=3, ##' mar=c(1.01, 4.1, 1.15, 2)) ##' } ##' ##' ##' @export ##' @author Paul F. Blanche <paulfblanche@@gmail.com> and Thomas A. Gerds <tag@@biostat.ku.dk> # }}} wallyPlot <- function(object, time, formula, data, cause=1, q=10, ylim, hanging=FALSE, seed=NULL, mar=c(4.1,4.1, 2, 2), colbox="red", verbose=TRUE, col=c("grey90","grey30"), xlab="Risk groups", labels="quantiles.labels", ...){ # {{{ prepare graphics output oldpar <- par(no.readonly = TRUE) par(mar = mar) par(mfrow=c(3,3),oma=c(3,0,0,0)) # }}} # {{{ data & formula if (missing(data)){ trydata <- try(data <- eval(object$call$data),silent=TRUE) if (("try-error" %in% class(trydata))|| match("data.frame",class(data),nomatch=0)==0) stop("Argument data is missing.") else if (verbose) warning("Argument data is missing. I use the data from the call to the first model instead.") } if (data.table::is.data.table(data)) data <- as.data.frame(data) if (missing(formula)){ tryformula <- try(as.character(object$call$formula),silent=TRUE) if (("try-error" %in% class(tryformula))||length(grep("~",as.character(object$call$formula)))==0){ stop(paste("Argument formula is missing and first model has no usable formula.")) } else{ ftry <- try(formula <- eval(object$call$formula),silent=TRUE) if ((class(ftry)=="try-error") || match("formula",class(formula),nomatch=0)==0) stop("Argument formula is missing and first model has no usable formula.") else if (verbose) warning("Formula missing. Using formula from first model") ## remove covariates formula <- update.formula(formula,".~1") } } m <- model.frame(formula,data,na.action=na.fail) response <- model.response(m) if (match("Surv",class(response),nomatch=FALSE)) model.type <- "survival" else model.type <- attr(response,"model") if (is.null(model.type) & length(unique(response))==2) model.type <- "binary" if (!(model.type=="binary")){ neworder <- order(response[,"time"],-response[,"status"]) response <- response[neworder,,drop=FALSE] Y <- response[,"time"] status <- response[,"status"] if (model.type=="competing.risks"){ event <- as.numeric(response[,"event"]) event[status==0] <- 0 status <- event rm(event) } data <- data[neworder,] if (missing(time)) time <- median(Y) else if (length(time)>1) stop("Please specify only one time point.") } # }}} # {{{ extract predicted risks if (class(object)[1] %in% c("numeric","double")) object <- matrix(object,ncol=1) predict.args <- list(object,newdata=data) if (model.type=="survival") predict.args <- c(predict.args,times=time) if (model.type=="competing.risks") predict.args <- c(predict.args,times=time,cause=cause) pred <- as.vector(do.call(riskRegression::predictRisk,predict.args)) ## if given as a vector we need to re-order if (class(object)[[1]]%in% c("matrix","numeric")) pred <- pred[neworder] if (any(is.na(pred))) stop("Missing values in prediction. Maybe time interest needs to be set earlier?") # }}} # {{{ define risk groups according to quantiles quant <- quantile(pred,seq(0,1,1/q)) riskGroups <- cut(pred,breaks=quant,labels=1:(length(quant)-1),include.lowest=TRUE) predictedRisk <- tapply(pred,riskGroups,mean) # }}} # {{{ create labels to appear below the bars if ((is.logical(labels[1]) && labels[1]==TRUE) || labels[1] %in% c("quantiles.labels","quantiles")){ qq <- quant if (labels[1]=="quantiles.labels"){ pp <- seq(0,1,1/q) barlabels <- paste0("(", sprintf("%1.0f",100*pp[-length(pp)]),",", sprintf("%1.0f",100*pp[-1]), ")\n", sprintf("%1.1f",100*qq[-length(qq)])," - ", sprintf("%1.1f",100*qq[-1])) } else barlabels <- paste0(sprintf("%1.1f",100*qq[-length(qq)])," - ", sprintf("%1.1f",100*qq[-1])) }else{ barlabels <- "" } # }}} # {{{ Test if time is ok if (any((tooshortFollowup <- tapply(Y,riskGroups,max))<time)){ stop(paste0("The following risk groups have too short followup. Nth quantile of predicted risks: ", paste(names(tooshortFollowup),collapse=", "), "\nThe minimum of the maximal followup in the risk groups is: ", signif(min(tooshortFollowup),2))) } # }}} # {{{ set seed for making the Wally plot repoducible set.seed(seed) Allseed <- round(runif(length(levels(riskGroups))+1)*10000) # }}} # {{{ loop to create the simulated data sets ## - we loop over the groups (of subjects of homogeneous predicted risks) ## - we call the function to create 8 Bootstrap new datasets under the calibration assumption ## - we merge data from all subgroups to create 8 new datasets which mimic the actual data under the calibration assumption. ListofListsPerGroups <- vector("list", length(levels(riskGroups))) for(g in 1:length(levels(riskGroups))){ Predg <- mean(pred[riskGroups==(levels(riskGroups)[g])]) datag <- data[riskGroups==(levels(riskGroups)[g]),all.vars(formula)] names(datag) <- c("time","status") if(model.type!="competing.risks"){ # {{{ without competing risks ListofListsPerGroups[[g]] <- GenSurvDataKMCons(tstar=time, pstar=1-Predg, # we want risk not survival M = 8, data=datag, myseed=Allseed[g]) # }}} }else{ # {{{ with competing risks # we should seperate the two cases : wether or not there are competing events # Here is the case where we observe the two competing events if(c(1) %in% unique(datag$status) & c(2) %in% unique(datag$status)){ # The current version of the GenCRDataAJCons function does not handle ties, # so we add a little bit of jitter if there are ties # {{{ to handle ties with competing risks if(!all(!duplicated(datag$time))){ thelocations <- which(duplicated(datag$time)) set.seed(Allseed[g]) datag$time[thelocations] <- jitter(datag$time[thelocations], amount=NULL, factor=1/(length(datag$time)*2)) } # }}} ListofListsPerGroups[[g]] <- GenCRDataAJCons(tstar=time, pstar=Predg, M = 8, data=datag, myseed=Allseed[g])$l }else{ # Here is the case where we observe only one of the two competing events # if only event 2 is observerved, we need a trick (transform to event 1 to generate the data # and then transform back to event 1) if(c(2) %in% unique(datag$status)){ # case in which we do not observe event 1 (the main event) datag$status[datag$status==2] <- 1 ListofListsPerGroups[[g]] <- GenSurvDataKMCons(tstar=time, pstar=1-Predg, # be careful here we want prob of event ! (not survival..) M = 8, data=datag, myseed=Allseed[g]) for(j in 1:8){ datag018 <- ListofListsPerGroups[[g]][[j]] datag018$status[datag018$status==1] <- 2 # transform back 1 to 2 ListofListsPerGroups[[g]][[j]] <- datag018 } }else{ # case in which we do not observe event 2 (the competing event), # we can do as without any competing risk ListofListsPerGroups[[g]] <- GenSurvDataKMCons(tstar=time, pstar=1-Predg, # be careful here we want prob of event ! (not survival..) M = 8, data=datag, myseed=Allseed[g]) } } } # }}} # {{{ Merge data to create the new data # add predictions to the table and remove useless column for(j in 1:8){ datag018 <- ListofListsPerGroups[[g]][[j]] ## ListofListsPerGroups[[g]][[j]] <- cbind.data.frame(datag018[,c("time","status")],riskGroups=riskGroups[riskGroups==(levels(riskGroups)[g])]) ListofListsPerGroups[[g]][[j]] <- cbind.data.frame(datag018[,c("time","status")], riskGroups=riskGroups[riskGroups==(levels(riskGroups)[g])], risk=pred[riskGroups==(levels(riskGroups)[g])]) } # }}} } DataList <- lapply(1:8,function(i){do.call("rbind", sapply(lapply(ListofListsPerGroups,"[",i),"[",1))}) ## add real data at the last position realData <- cbind(data[,all.vars(update(formula,".~1")),drop=FALSE],riskGroups=riskGroups) data.table::setDT(realData) DataList <- c(DataList,list(realData)) # }}} # {{{ sample the order of the data in the list pos <- 1:9 set.seed(Allseed[length(Allseed)]) pos <- sample(pos) figpos <- order(pos)[9] # where is the actual plot (with the true data) # }}} # {{{ control of plot arguments superuser.defaults <- list(hide=TRUE,choice=6,zoom=FALSE) hline.defaults <- list(col=2, lwd=2.5, type="s") ## if (missing(ylim)) if (hanging) ylim <- c(-1,1) else ylim <- c(0,1) if (missing(ylim)) { user.ylim <- FALSE if (hanging) ylim <- c(-1,1) else ylim <- c(0,1) }else{ user.ylim <- TRUE } axis2.DefaultArgs <- list(side=2,las=2,at=seq(0,ylim[2],ylim[2]/4),mgp=c(4,1,0)) legend.DefaultArgs <- list(legend=c("Predicted risks","Observed frequencies"),col=col,cex=par()$cex,bty="n",x="topleft") barlabels.DefaultArgs <- list(cex=.7*par()$cex, y=c(-abs(diff(ylim))/15,-abs(diff(ylim))/25), text=barlabels) frequencies.DefaultArgs <- list(cex=.7*par()$cex,percent=FALSE,offset=0) lines.DefaultArgs <- list(type="l") abline.DefaultArgs <- list(lwd=1,col="red") barplot.DefaultArgs <- list(ylim = ylim, col=col, axes=FALSE, ylab="", xlab=xlab, beside=TRUE, legend.text=NULL, cex.axis=par()$cex.axis, cex.lab=par()$cex.lab) smartA <- prodlim::SmartControl(call= list(...), keys=c("superuser","barplot","legend","axis2","abline","barlabels","frequencies","hline"), ignore=NULL, ignore.case=TRUE, defaults=list("superuser"=superuser.defaults, "barplot"=barplot.DefaultArgs, "abline"=abline.DefaultArgs, "legend"=legend.DefaultArgs, "barlabels"=barlabels.DefaultArgs, "frequencies"=frequencies.DefaultArgs, "axis2"=axis2.DefaultArgs, "hline"=hline.defaults), forced=list("abline"=list(h=0)), verbose=TRUE) # }}} # {{{ loop to create the 9 plots TabList <- vector("list",9) printleg <- c(rep(FALSE,4),TRUE,rep(FALSE,4)) for(i in pos){ if (i==9) riskformula <- formula else riskformula <- formula("Hist(time,status)~1") # compute observed risk in groups xgroups <- (quant[-(length(quant))]+quant[-1])/2 groupFormula <- update(riskformula,paste(".~riskGroups")) Obs <- as.vector(riskRegression::predictRisk(prodlim::prodlim(groupFormula,data=DataList[[i]]), cause=cause, newdata=data.frame(riskGroups=levels(riskGroups)), times=time)) if (any(is.na(Obs))) { Obs[is.na(Obs)] <- max(Obs,na.rm=TRUE) warning("Missing values in expected frequencies. Maybe too many quantiles relative to the number of observations? Or time interest set too late?") } TabList[[i]] <- list(Pred=predictedRisk, Obs=Obs, time=time, cause=cause, summary=summary, control=smartA, legend=legend, diag=diag, legend=FALSE, labels=labels, model.type=model.type, hanging=hanging, ## showFrequencies=1L, showFrequencies=FALSE, col=col, ylim=ylim, axes=1L) } if (hanging){ ## FIXME minY <- min(sapply(TabList,function(x){min(x$Pred-x$Obs)})) maxY <- max(sapply(TabList,function(x){max(x$Pred)})) # rangeY <- range(sapply(TabList,function(x){c(min(x$Pred-x$Obs),max(x$Pred))})) minY <- min(0,seq(-1,1,0.05)[prodlim::sindex(eval.times=minY,jump.times=seq(-1,1,0.05))]) } else{ maxY <- max(sapply(TabList,function(x){max(x$Obs)})) maxY <- c(seq(0,1,0.05),1)[1+prodlim::sindex(eval.times=maxY,jump.times=seq(0,1,0.05))] minY <- 0 } if (user.ylim){ if (minY<0) minY <- min(ylim,minY) maxY <- ylim[2] } for (j in 1:9){ i = pos[j] px <- TabList[[i]] px$control$barplot$ylim <- c(minY,maxY) px$control$barlabels$y <- c(-abs(diff(c(minY,maxY)))/15,-abs(diff(c(minY,maxY)))/25) ## need to round to avoid strange results px$control$axis2$at <- sort(round(seq(minY,maxY,(maxY-minY)/4),3)) ## place a legend below panel 8 if (j==8) { px$legend <- TRUE px$control$legend$legend <- c("Predicted risk","Observed frequency") px$control$legend$xpd <- NA px$control$legend$x <- "bottom" px$control$legend$ncol=2 px$control$legend$inset=c(0,-0.4) px$control$legend$cex <- 1.3 }else{ px$legend <- FALSE } ## add the plot to the grid px$labels <- FALSE calibrationBarplot(px) upleft <- par("usr")[c(1,4)] points(x=upleft[1],y=upleft[2],xpd=NA,pch=19,cex=5,col="orange") text(j,x=upleft[1],y=upleft[2],xpd=NA,col="black",cex=1.2) } ## mtext(side=1,line=1,"Can you find wally?",cex=1.5*par()$cex) # }}} # {{{ interact with user if (is.null(smartA$superuser$choice)){ par(oldpar) invisible(TabList[order(pos)]) }else{ if (smartA$superuser$hide!=FALSE){ # {{{ ask to show the actual plot xx <- select.list(1:9, multiple=FALSE, title="\nWhere is Wally? Can you find the plot which is based on the real data?\nSelect an orange number: ") # }}} }else xx <- smartA$superuser$choice par(mfg = c(xx%/%3.1 + 1, xx - (xx%/%3.1) * 3)) box(col = "green", lwd= 3) # {{{ show the actual plot by adding a red box if (xx==figpos) { mtext("Correct: real data!",col="green",cex=1.2,line=-3,xpd=NA) }else{ mtext("Not correct!",col="red",cex=1.2,line=-3,xpd=NA) par(mfg = c(figpos%/%3.1 + 1, figpos - (figpos%/%3.1) * 3)) mtext("Real data",col="red",cex=1.2,line=-3,side=3,xpd=NA) box(col = colbox, lwd = 5) } # }}} # {{{ ask to press a key to zoom in on the actual plot ## readline("Hit <Enter> to better show the original plot. ") if (smartA$superuser$zoom==FALSE && smartA$superuser$hide!=FALSE){ zoom <- select.list(c("yes","no"),title="Zoom in on real data calibration plot? ") }else zoom <- "no" # }}} # {{{ show the actual plot if((smartA$superuser$zoom==TRUE) || (zoom=="yes")){ par(mfrow=c(1,1),oma=c(2,2,2,2),mar=c(4.1,4.1, 4.1, 4.1)) px <- TabList[[9]] px$control$barplot$ylim <- c(minY,maxY) px$control$barlabels$y <- c(-abs(diff(c(minY,maxY)))/15,-abs(diff(c(minY,maxY)))/25) ## need to round to avoid strange results like in px$control$axis2$at <- sort(round(seq(minY,maxY,(maxY-minY)/4),3)) px$control$barplot$legend.text=c("Predicted risk","Observed frequency") px$control$legend$legend <- c("Predicted risk","Observed frequency") px$control$barplot$xlab <- "Risk groups" px$control$legend$xpd <- NA px$control$legend$x <- "top" px$control$legend$ncol <- 2 px$control$legend$inset <- c(0,-0.2) px$showFrequencies <- TRUE px$legend=TRUE px$labels <- labels calibrationBarplot(px) } # }}} par(oldpar) } # }}} invisible(list(Tables=TabList[order(pos)],Data=DataList)) } # }}}
/scratch/gouwar.j/cran-all/cranData/wally/R/wallyPlot.R
#' Save API credentials for later use #' #' This functions caches the credentials to avoid need for entering it when #' calling other functions #' @param app_key application key #' @examples #' # since not checking is preformed not to waste API calls #' # it falls on the user to save correct information #' save_walmart_credentials("APP_KEY") #' @export save_walmart_credentials <- function(app_key) { if (app_key != "") { assign("KEY", app_key, envir = auth_cache) } }
/scratch/gouwar.j/cran-all/cranData/walmartAPI/R/client.R
if(getRversion() >= "2.15.1") utils::globalVariables(c(".")) auth_cache <- new.env()
/scratch/gouwar.j/cran-all/cranData/walmartAPI/R/global.R
#' Subsets up to n elements in a vector #' #' @param x A vector. #' @param n A number. #' @return vector of length equal to length of x or n, whichever is smallest. #' @examples #' smart_subset(1:10, 5) #' smart_subset(1:10, 50) #' @export smart_subset <- function(x, n) { if(length(x) >= n) { x[1:n] } else { x } } #' Returns NA if input is null, else returns input #' #' @param x A number. #' @return A number or NA. #' @examples #' ifelse_null(NA) #' ifelse_null(1) #' @export ifelse_null <- function(x) { ifelse(is.null(x), NA, x) } #' Returns tibble of items in base response format #' #' response formats are described at the url #' \url{https://developer.walmartlabs.com/docs/read/Item_Field_Description}. #' #' @param x A List. #' @return A tibble with 15 columns in base response format. #' @export item_base_response <- function(x) { purrr::map_df(x, ~ tibble::tibble( itemId = ifelse_null(.$itemId), name = ifelse_null(.$name), msrp = ifelse_null(.$msrp), salePrice = ifelse_null(.$salePrice), upc = ifelse_null(.$upc), categoryPath = ifelse_null(.$categoryPath), longDescription = ifelse_null(.$longDescription), thumbnailImage = ifelse_null(.$thumbnailImage), productTrackingUrl = ifelse_null(.$productTrackingUrl), standardShipRate = ifelse_null(.$standardShipRate), marketplace = ifelse_null(.$marketplace), productUrl = ifelse_null(.$productUrl), availableOnline = ifelse_null(.$availableOnline), offerType = ifelse_null(.$offerType), shippingPassEligible = ifelse_null(.$shippingPassEligible) ) ) }
/scratch/gouwar.j/cran-all/cranData/walmartAPI/R/helper_functions.R
#' Looks up product information #' #' \code{\link{lookup}} gives access to item price and availability in real-time. #' #' An API key will be required to run this function and can be acquired by #' creating an account on the following website #' \url{https://developer.walmartlabs.com/member}. #' #' For more information refer to the original documentation #' \url{https://developer.walmartlabs.com/docs/read/Home}. #' #' Response formats are described at the url #' \url{https://developer.walmartlabs.com/docs/read/Item_Field_Description}. #' #' @param key Your API access key. #' @param lsPublisherId Your LinkShare Publisher Id. #' @param id vector of item ids. #' @param upc upc of the item. #' @param list_output Indicator for list output. #' @return A tibble with 15 columns in base response format. #' @examples #' \dontrun{ #' key <- "************************" #' #' ## Up to 20 ids can be called at once. #' lookup(id = c(12417882:12417937), key = key) #' #' lookup(id = 12417832, key = key) #' #' lookup(upc = 10001137891, key = key) #' #' ## First argument will be used with conflicting arguments. #' lookup(id = 12417837, upc = 10001137891, key = key) #' #' lookup(id = 12417832, key = key, list_output = TRUE) #' } #' @export lookup <- function(key = auth_cache$KEY, lsPublisherId = NULL, id = NULL, upc = NULL, list_output = FALSE) { if(is.null(key)) stop("No arguemnt to 'key'. Use save_walmart_credentials or supply appropriate arguments") base_url <- "http://api.walmartlabs.com/v1/items?&format=json" if(!is.null(upc)) { url <- glue::glue("{base_url}&apiKey={key}&upc={upc}") } if(!is.null(id)) { id <- stringr::str_c(smart_subset(id, 20), collapse = ",") url <- glue::glue("{base_url}&apiKey={key}&ids={id}") } if(!is.null(lsPublisherId)) { url <- glue::glue("{url}&lsPublisherId={lsPublisherId}") } response <- httr::GET(url) if (httr::http_type(response) != "application/json") { stop("API did not return json", call. = FALSE) } if(list_output) { return(httr::content(response)) } response %>% httr::content() %>% purrr::flatten() %>% item_base_response() }
/scratch/gouwar.j/cran-all/cranData/walmartAPI/R/lookup.R
#' Looks up product information #' #' \code{\link{lookup}} gives access to item price and availability in #' real-time. #' #' An API key will be required to run this function and can be acquired by #' creating an account on the following website #' \url{https://developer.walmartlabs.com/member}. #' #' For more information refer to the original documentation #' \url{https://developer.walmartlabs.com/docs/read/Home}. #' #' Response formats are described at the url #' \url{https://developer.walmartlabs.com/docs/read/Item_Field_Description}. #' #' @param key Your API access key. #' @param lsPublisherId Your LinkShare Publisher Id. #' @param category Category id of the desired category. This should match the #' id field from \code{\link{taxonomy}} function. #' @param brand Brand name. #' @param specialOffer Special offers like (rollback, clearance, specialBuy). #' @param list_output Indicator for list output. #' @return A tibble with 16 columns. First 15 is the items in base response #' format, followed by a column containing the URL path for the next page. #' @examples #' \dontrun{ #' key <- "************************" #' #' paginted(key = key, brand = "Apple") #' #' paginted(key = key, category = 3944) #' #' paginted(key = key, category = 3944, specialOffer = "rollback") #' #' paginted(key = key, brand = "Apple", list_output = TRUE) #' } #' @export paginted <- function(key = auth_cache$KEY, lsPublisherId = NULL, category = NULL, brand = NULL, specialOffer = NULL, list_output = FALSE) { if(is.null(key)) stop("No arguemnt to 'key'. Use save_walmart_credentials or supply appropriate arguments") base_url <- "http://api.walmartlabs.com/v1/paginated/items" url <- glue::glue("{base_url}?apiKey={key}") if(!is.null(specialOffer)) { url <- glue::glue("{url}&specialOffer={specialOffer}") } if(!is.null(brand)) { url <- glue::glue("{url}&brand={brand}") } if(!is.null(category)) { url <- glue::glue("{url}&category={category}") } if(!is.null(lsPublisherId)) { url <- glue::glue("{url}&lsPublisherId={lsPublisherId}") } response <- httr::GET(url) if (httr::http_type(response) != "application/json") { stop("API did not return json", call. = FALSE) } if(list_output) { return(httr::content(response)) } response %>% httr::content() %>% .[["items"]] %>% item_base_response() %>% dplyr::mutate(next_page = response %>% httr::content() %>% .$nextPage) }
/scratch/gouwar.j/cran-all/cranData/walmartAPI/R/paginated.R
#' searching with text the Walmart catalogue #' #' \code{searching} allows text search on the Walmart.com catalogue and #' returns matching items available for sale online. #' An API key will be required to run this function and can be acquired by #' creating an account on the following website #' \url{https://developer.walmartlabs.com/member}. #' #' For more information refer to the original documentation #' \url{https://developer.walmartlabs.com/docs/read/Search_API}. #' #' Response formats are described at the url #' \url{https://developer.walmartlabs.com/docs/read/Item_Field_Description}. #' #' @param key Your API access key. #' @param lsPublisherId Your LinkShare Publisher Id. #' @param query Search text - whitespace separated sequence of keywords to #' search for. #' @param categoryId Category id of the category for search within a category. #' This should match the id field from Taxonomy API. #' @param start Starting point of the results within the matching set of #' items - up to 10 items will be returned starting from this item. #' @param sort Sorting criteria, allowed sort types are (relevance, price, #' title, bestseller, customerRating, new). Default sort is by relevance. #' @param order Sort ordering criteria, allowed values are (asc, desc). #' This parameter is needed only for the sort types (price, title, #' customerRating). #' @param numItems Number of matching items to be returned, max value 25. #' Default is 10. #' @param facet Logical. Enables facets. Default value is FALSE. #' Set this to on to enable facets. #' @param facet.filter Filter on the facet attribute values. This parameter #' can be set to <facet-name>:<facet-value> (without the angles). Here #' facet-name and facet-value can be any valid facet picked from the search #' API response when facets are on. #' @param list_output Indicator for list output. #' @return A tibble with 15 columns in base response format. #' @examples #' \dontrun{ #' key <- "************************" #' #' searching(query = "ipod", key = key) #' #' searching(query = "ipod", key = key, categoryId = 3944) #' #' searching(query = "ipod", key = key, start = 44) #' #' searching(query = "ipod", key = key, numItems = 44) #' #' searching(query = "ipod", key = key, sort = "price", order = "asc") #' #' searching(query = "ipod", key = key, sort = "bestseller") #' #' searching(query = "ipod", key = key, list_output = TRUE) #' } #' @export searching <- function(query, key = auth_cache$KEY, lsPublisherId = NULL, categoryId = NULL, start = NULL, sort = NULL, order = NULL, numItems = NULL, facet = FALSE, facet.filter = NULL, list_output = FALSE) { if(is.null(key)) stop("No arguemnt to 'key'. Use save_walmart_credentials or supply appropriate arguments") base_url <- "http://api.walmartlabs.com/v1/search" url <- glue::glue("{base_url}?apiKey={key}&query={query}") if(!is.null(facet.filter)) { url <- glue::glue("{url}&facet.filter={facet.filter}") } if(facet) { url <- glue::glue("{url}&facet=on") } if(!is.null(numItems)) { if(numItems > 25) { warning("numItems was larger then 25, set to maximal 25.") numItems <- 25 } url <- glue::glue("{url}&numItems={numItems}") } if(!is.null(order)) { url <- glue::glue("{url}&order={order}") } if(!is.null(sort)) { url <- glue::glue("{url}&sort={sort}") } if(!is.null(start)) { url <- glue::glue("{url}&start={start}") } if(!is.null(categoryId)) { url <- glue::glue("{url}&categoryId={categoryId}") } if(!is.null(lsPublisherId)) { url <- glue::glue("{url}&lsPublisherId={lsPublisherId}") } response <- httr::GET(url) if (httr::http_type(response) != "application/json") { stop("API did not return json", call. = FALSE) } if(list_output) { return(httr::content(response)) } response %>% httr::content() %>% .[["items"]] %>% item_base_response() }
/scratch/gouwar.j/cran-all/cranData/walmartAPI/R/search.R
#' Locale nearby Walmart stores #' #' \code{\link{store_locator}} helps locate nearest Walmart Stores by letting #' you users search for stores by latitude and longitude, by zip code and by #' city. #' #' An API key will be required to run this function and can be acquired by #' creating an account on the following website #' \url{https://developer.walmartlabs.com/member}. #' #' For more information refer to the original documentation #' \url{https://developer.walmartlabs.com/docs/read/Store_Locator_API}. #' #' @param key Your API access key. #' @param lat latitude. #' @param lon longitude. #' @param city city. #' @param zip zip code. #' @param list_output Indicator for list output. #' @return A tibble with 12 columns in base response format. #' @examples #' \dontrun{ #' key <- "************************" #' #' store_locator(key = key, lat = 29, lon = -95) #' #' store_locator(key = key, city = "Houston") #' #' store_locator(key = key, zip = 77063) #' #' store_locator(key = key, zip = 77063, list_output = TRUE) #' } #' @export store_locator <- function(key = auth_cache$KEY, lat = NULL, lon = NULL, city = NULL, zip = NULL, list_output = FALSE) { if(is.null(key)) stop("No arguemnt to 'key'. Use save_walmart_credentials or supply appropriate arguments") base_url <- glue::glue("http://api.walmartlabs.com/v1/stores?apiKey={key}") if(!is.null(zip)) { url <- glue::glue("{base_url}&zip={zip}") } if(!is.null(city)) { url <- glue::glue("{base_url}&city={city}") } if(sum(c(!is.null(lat), !is.null(lon))) == 1) { stop("Both lon and lat needs to specified.") } if(all(c(!is.null(lat), !is.null(lon)))) { url <- glue::glue("{base_url}&lon={lon}&lat={lat}") } response <- httr::GET(url) if (httr::http_type(response) != "application/json") { stop("API did not return json", call. = FALSE) } if(list_output) { return(httr::content(response)) } response %>% httr::content() %>% purrr::map_df(~ tibble::tibble(no = ifelse_null(.$no), name = ifelse_null(.$name), country = ifelse_null(.$country), lon = ifelse_null(.$coordinates[[1]]), lat = ifelse_null(.$coordinates[[2]]), streetAddress = ifelse_null(.$streetAddress), city = ifelse_null(.$city), stateProvCode = ifelse_null(.$stateProvCode), zip = ifelse_null(.$zip), phoneNumber = ifelse_null(.$phoneNumber), sundayOpen = ifelse_null(.$sundayOpen), timezone = ifelse_null(.$timezone),)) }
/scratch/gouwar.j/cran-all/cranData/walmartAPI/R/store_locator.R
#' The category taxonomy used by walmart.com to categorize items #' #' This function returns the top level of categories only, for further levels #' run function with \code{list_output = FALSE} for nested list. #' #' \code{\link{taxonomy}} gives returns the category taxonomy used by #' walmart.com to categorize items. #' #' An API key will be required to run this function and can be acquired by #' creating an account on the following website #' \url{https://developer.walmartlabs.com/member}. #' #' For more information refer to the original documentation #' \url{https://developer.walmartlabs.com/docs/read/Taxonomy_API}. #' #' @param key Your API access key. #' @param list_output Indicator for list output. #' @return A tibble with 15 columns in base response format. #' @examples #' \dontrun{ #' key <- "************************" #' #' taxonomy(key = key) #' #' taxonomy(key = key, list_output = TRUE) #'} #' @export taxonomy <- function(key = auth_cache$KEY, list_output = FALSE) { if(is.null(key)) stop("No arguemnt to 'key'. Use save_walmart_credentials or supply appropriate arguments") url <- glue::glue("http://api.walmartlabs.com/v1/taxonomy?apiKey={key}") response <- httr::GET(url) if (httr::http_type(response) != "application/json") { stop("API did not return json", call. = FALSE) } if(list_output) { return(httr::content(response)) } response %>% httr::content() %>% purrr::flatten() %>% purrr::map_df(~ tibble::tibble(id = .x$id, name = .x$name)) }
/scratch/gouwar.j/cran-all/cranData/walmartAPI/R/taxonomy.R
#' Trending products at Walmart.com #' #' \code{\link{trending}} gives information on what is bestselling on #' Walmart.com right now. #' #' An API key will be required to run this function and can be acquired by #' creating an account on the following website #' \url{https://developer.walmartlabs.com/member}. #' #' For more information refer to the original documentation #' \url{https://developer.walmartlabs.com/docs/read/Trending_API}. #' #' Response formats are described at the url #' \url{https://developer.walmartlabs.com/docs/read/Item_Field_Description}. #' #' @param key Your API access key. #' @param lsPublisherId Your LinkShare Publisher Id. #' @param list_output Indicator for list output. #' @return A tibble with 15 columns in base response format. #' @examples #' \dontrun{ #' key <- "************************" #' #' trending(key = key) #' #' trending(key = key, list_output = TRUE) #'} #' @export trending <- function(key = auth_cache$KEY, lsPublisherId = NULL, list_output = FALSE) { if(is.null(key)) stop("No arguemnt to 'key'. Use save_walmart_credentials or supply appropriate arguments") url <- glue::glue("http://api.walmartlabs.com/v1/trends?apiKey={key}&format=json") if(!is.null(lsPublisherId)) { url <- glue::glue("{url}&lsPublisherId={lsPublisherId}") } response <- httr::GET(url) if (httr::http_type(response) != "application/json") { stop("API did not return json", call. = FALSE) } if(list_output) { return(httr::content(response)) } response %>% httr::content() %>% .[["items"]] %>% item_base_response() }
/scratch/gouwar.j/cran-all/cranData/walmartAPI/R/trending.R
#' Pipe operator #' #' See \code{magrittr::\link[magrittr]{\%>\%}} for details. #' #' @name %>% #' @rdname pipe #' @keywords internal #' @export #' @importFrom magrittr %>% #' @usage lhs \%>\% rhs NULL
/scratch/gouwar.j/cran-all/cranData/walmartAPI/R/utils-pipe.R
#' Value of the day #' #' \code{\link{VOD}} provides the Value of the Day item at walmart. #' #' An API key will be required to run this function and can be acquired by #' creating an account on the following website #' \url{https://developer.walmartlabs.com/member}. #' #' Response formats are described at the url #' \url{https://developer.walmartlabs.com/docs/read/Item_Field_Description}. #' #' @param key Your API access key. #' @param list_output Indicator for list output. #' @return A tibble with 15 columns in base response format. #' @examples #' \dontrun{ #' key <- "************************" #' #' VOD(key = key) #' #' VOD(key = key, list_output = TRUE) #' } #' @export VOD <- function(key = auth_cache$KEY, list_output = FALSE) { if(is.null(key)) stop("No arguemnt to 'key'. Use save_walmart_credentials or supply appropriate arguments") url <- glue::glue("http://api.walmartlabs.com/v1/vod?format=json&apiKey={key}") response <- httr::GET(url) if (httr::http_type(response) != "application/json") { stop("API did not return json", call. = FALSE) } if(list_output) { return(httr::content(response)) } response %>% httr::content() %>% list() %>% item_base_response() }
/scratch/gouwar.j/cran-all/cranData/walmartAPI/R/vod.R
# This file is automatically generated, you probably don't want to edit this .jmvrefs <- list( `w`=list( `authors`="Love, J., & Mair, P.", `year`=2017, `title`="Walrus: Robust Statistical Methods", `publisher`="[jamovi module]", `url`="https://github.com/jamovi/walrus/"), `wrs2`=list( `authors`="Mair, P., & Wilcox, R.", `year`=2017, `title`="WRS2: A Collection of Robust Statistical Methods", `publisher`="[R package]. Retrieved from https://cran.r-project.org/package=WRS2", `url`="https://cran.r-project.org/package=WRS2"), `wilcox`=list( `authors`="Wilcox, R. R.", `year`=2011, `title`="Introduction to robust estimation and hypothesis testing", `publisher`="Academic press", `url`="https://www.amazon.com/Introduction-Estimation-Hypothesis-Statistical-Modeling/dp/012804733X"))
/scratch/gouwar.j/cran-all/cranData/walrus/R/00jmv.R
# This file is a generated template, your changes will not be overwritten ranovaClass <- R6::R6Class( "ranovaClass", inherit = ranovaBase, private = list( .cleanData = function() { dep <- self$options$dep factors <- self$options$factors data <- self$data if ( ! is.null(dep)) data[[dep]] <- jmvcore::toNumeric(data[[dep]]) for (factor in factors) data[[factor]] <- as.factor(data[[factor]]) data }, .init = function() { main <- self$results$main factors <- self$options$factors method <- self$options$method if (length(factors) == 0) return() data <- private$.cleanData() for (f in private$.ff()) { term <- jmvcore::stringifyTerm(f) main$addRow(rowKey=f, values=list(name=term)) } for (factor in factors) { ph <- self$results$phs$get(factor) rowNo <- 1 lvls <- base::levels(data[[factor]]) combns <- combn(lvls, 2) for (col in 1:ncol(combns)) { pair <- combns[,col] ph$addRow(rowKey=rowNo, values=list(v1=pair[1], v2=pair[2])) rowNo <- rowNo + 1 } } if (length(factors) == 1) { if (method == 'trim') { main$setNote('method', jmvcore::format('Method of trimmed means, trim level {}', self$options$tr)) } else if (method == 'median') { main$setNote('method', 'Median method') } else { # bootstrap # bootstrap of 1 way designs is more like the trim method, and # doesn't look anything like the bootstrap 2 way stuff jmvcore::reject('Bootstrap method is unavailable for 1-way designs') main$getColumn('s')$setTitle('F*') } } else if (length(factors) == 2) { main$getColumn('s')$setTitle('Q') if (method == 'trim') { main$setNote('method', jmvcore::format('Method of trimmed means, trim level {}', self$options$tr)) } else if (method == 'median') { main$setNote('method', 'Median method') } else { # bootstrap if (self$options$est == 'onestep') estimator <- 'one-step' else if (self$options$est == 'mom') estimator <- 'modified one-step' else if (self$options$est == 'median') estimator <- 'median' else estimator <- 'unknown' if (self$options$dist == 'maha') distances <- 'Mahalanobis' else if (self$options$dist == 'proj') distances <- 'projection' else distances <- 'unknown' main$setNote('method', jmvcore::format( 'Bootstrap method, {} estimator, {} samples, {} distances', estimator, self$options$nboot, distances)) main$setNote('nostat', 'Test statistics are not available for 2-way bootstrapped designs') } } else if (length(factors) == 3) { main$getColumn('s')$setTitle('Q') if (method == 'trim') { main$setNote('method', jmvcore::format('Method of trimmed means, trim level {}', self$options$tr)) } else if (method == 'median') { jmvcore::reject('Median method is unavailable for 3-way designs') } else { # bootstrap jmvcore::reject('Bootstrap method is unavailable for 3-way designs') } } else { jmvcore::reject("More than 3 factors is not supported") } }, .run = function() { dep <- self$options$dep factors <- self$options$factors method <- self$options$method if (is.null(dep) || length(factors) == 0) return() main <- self$results$main phTables <- self$results$phs data <- private$.cleanData() colnames(data) <- jmvcore::toB64(colnames(data)) factors <- jmvcore::toB64(factors) dep <- jmvcore::toB64(dep) fmla <- paste(dep, '~', paste(factors, collapse='*')) fmla <- as.formula(fmla) if (length(factors) == 1) { if (method == 'trim') { result <- WRS2::t1way(fmla, data, tr=self$options$tr) main$setRow(rowNo=1, values=list( s=result$test, p=result$p.value)) private$.checkpoint() result <- try(WRS2::lincon(fmla, data, tr=self$options$tr)$comp) if ( ! jmvcore::isError(result)) { ph <- phTables$get(index=1) for (rowNo in seq_len(ph$rowCount)) { psi <- result[rowNo,'psihat'] p <- result[rowNo,'p.value'] cil <- result[rowNo,'ci.lower'] ciu <- result[rowNo,'ci.upper'] ph$setRow(rowNo=rowNo, values=list( psi=psi, p=p, cil=cil, ciu=ciu)) } } else { message <- jmvcore::extractErrorMessage(result) phTables$setError(message) } } else if (method == 'median') { result <- WRS2::med1way(fmla, data) main$setRow(rowNo=1, values=list( s=result$test, p=result$p.value)) phTables$setError('Post hoc tests are not available for the median method') } else { # bootstrap if ( ! main$isFilled()) { result <- WRS2::t1waybt(fmla, data, nboot=self$options$nboot) main$setRow(rowNo=1, values=list( s=result$test, p=result$p.value)) private$.checkpoint() } result <- try(WRS2::mcppb20(fmla, data, nboot=self$options$nboot)$comp) if ( ! jmvcore::isError(result)) { ph <- phTables$get(index=1) for (rowNo in seq_len(ph$rowCount)) { psi <- result[rowNo,'psihat'] p <- result[rowNo,'p-value'] cil <- result[rowNo,'ci.lower'] ciu <- result[rowNo,'ci.upper'] ph$setRow(rowNo=rowNo, values=list( psi=psi, p=p, cil=cil, ciu=ciu)) } } else { message <- jmvcore::extractErrorMessage(result) phTables$setError(message) } } } else if (length(factors) == 2) { if (method == 'trim') { result <- WRS2::t2way(fmla, data, tr=self$options$tr) main$setRow(rowNo=1, values=list( s=result$Qa, p=result$A.p.value)) main$setRow(rowNo=2, values=list( s=result$Qb, p=result$B.p.value)) main$setRow(rowNo=3, values=list( s=result$Qab, p=result$AB.p.value)) private$.checkpoint() result <- try(WRS2::mcp2atm(fmla, data, tr=self$options$tr)$effects) if ( ! jmvcore::isError(result)) { for (key in phTables$itemKeys) { b64 <- jmvcore::toB64(key) values <- result[[b64]] table <- phTables$get(key) for (rowNo in seq_len(table$rowCount)) { psi <- values$psihat[rowNo] ci <- values$conf.int if (length(dim(ci)) > 1) ci <- ci[rowNo,] cil <- ci[1] ciu <- ci[2] p <- values$p.value[rowNo] table$setRow(rowNo=rowNo, values=list( psi=psi, p=p, cil=cil, ciu=ciu)) } } } else { message <- jmvcore::extractErrorMessage(result) phTables$setError(message) } } else if (method == 'median') { result <- WRS2::med2way(fmla, data) main$setRow(rowNo=1, values=list( s=result$Qa, p=result$A.p.value)) main$setRow(rowNo=2, values=list( s=result$Qb, p=result$B.p.value)) main$setRow(rowNo=3, values=list( s=result$Qab, p=result$AB.p.value)) phTables$setError('Post hoc tests are not available for the median method') } else { # bootstrap nboot <- self$options$nboot est <- self$options$est if (self$options$dist == 'proj') pro.dis <- TRUE else pro.dis <- FALSE if ( ! main$isFilled()) { result <- WRS2::pbad2way(fmla, data, est=est, nboot=nboot, pro.dis=pro.dis) main$setRow(rowNo=1, values=list( s=NaN, p=result$A.p.value)) main$setRow(rowNo=2, values=list( s=NaN, p=result$B.p.value)) main$setRow(rowNo=3, values=list( s=NaN, p=result$AB.p.value)) private$.checkpoint() } result <- try(WRS2::mcp2a(fmla, data, est=est, nboot=nboot)$effects) if ( ! jmvcore::isError(result)) { for (key in phTables$itemKeys) { b64 <- jmvcore::toB64(key) values <- result[[b64]] table <- phTables$get(key) for (rowNo in seq_len(table$rowCount)) { psi <- values$psihat[rowNo] ci <- values$conf.int if (length(dim(ci)) > 1) ci <- ci[rowNo,] cil <- ci[1] ciu <- ci[2] p <- values$p.value[rowNo] table$setRow(rowNo=rowNo, values=list( psi=psi, p=p, cil=cil, ciu=ciu)) } } } else { message <- jmvcore::extractErrorMessage(result) phTables$setError(message) } } } else if (length(factors) == 3) { ph <- NULL if (method == 'trim') { result <- WRS2::t3way(fmla, data, tr=self$options$tr) main$setRow(rowNo=1, values=list( s=result$Qa, p=result$A.p.value)) main$setRow(rowNo=2, values=list( s=result$Qb, p=result$B.p.value)) main$setRow(rowNo=3, values=list( s=result$Qc, p=result$C.p.value)) main$setRow(rowNo=4, values=list( s=result$Qab, p=result$AB.p.value)) main$setRow(rowNo=5, values=list( s=result$Qac, p=result$AC.p.value)) main$setRow(rowNo=6, values=list( s=result$Qbc, p=result$BC.p.value)) main$setRow(rowNo=7, values=list( s=result$Qabc, p=result$ABC.p.value)) phTables$setError('Post hoc tests are not available for 3-way designs') } else if (method == 'median') { jmvcore::reject('Median method is unavailable for 3-way designs') } else { # bootstrap jmvcore::reject('Bootstrap method is unavailable for 3-way designs') } } }, .ff=function() { factors <- self$options$factors if (length(factors) > 1) { formula <- as.formula(paste('~', paste(paste0('`', factors, '`'), collapse='*'))) terms <- attr(stats::terms(formula), 'term.labels') modelTerms <- sapply(terms, function(x) as.list(strsplit(x, ':')), USE.NAMES=FALSE) } else { modelTerms <- as.list(factors) } for (i in seq_along(modelTerms)) { term <- modelTerms[[i]] quoted <- grepl('^`.*`$', term) term[quoted] <- substring(term[quoted], 2, nchar(term[quoted])-1) modelTerms[[i]] <- term } modelTerms }) )
/scratch/gouwar.j/cran-all/cranData/walrus/R/ranova.b.R
# This file is automatically generated, you probably don't want to edit this ranovaOptions <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "ranovaOptions", inherit = jmvcore::Options, public = list( initialize = function( dep = NULL, factors = NULL, method = "trim", ph = FALSE, tr = 0.2, est = "mom", nboot = 599, dist = "proj", ...) { super$initialize( package="walrus", name="ranova", requiresData=TRUE, ...) private$..dep <- jmvcore::OptionVariable$new( "dep", dep, suggested=list( "continuous"), permitted=list( "numeric")) private$..factors <- jmvcore::OptionVariables$new( "factors", factors, suggested=list( "nominal", "ordinal"), permitted=list( "factor"), default=NULL) private$..method <- jmvcore::OptionList$new( "method", method, options=list( "median", "trim", "boot"), default="trim") private$..ph <- jmvcore::OptionBool$new( "ph", ph, default=FALSE) private$..tr <- jmvcore::OptionNumber$new( "tr", tr, min=0, max=0.5, default=0.2) private$..est <- jmvcore::OptionList$new( "est", est, options=list( "onestep", "mom", "median"), default="mom") private$..nboot <- jmvcore::OptionInteger$new( "nboot", nboot, min=0, default=599) private$..dist <- jmvcore::OptionList$new( "dist", dist, options=list( "maha", "proj"), default="proj") self$.addOption(private$..dep) self$.addOption(private$..factors) self$.addOption(private$..method) self$.addOption(private$..ph) self$.addOption(private$..tr) self$.addOption(private$..est) self$.addOption(private$..nboot) self$.addOption(private$..dist) }), active = list( dep = function() private$..dep$value, factors = function() private$..factors$value, method = function() private$..method$value, ph = function() private$..ph$value, tr = function() private$..tr$value, est = function() private$..est$value, nboot = function() private$..nboot$value, dist = function() private$..dist$value), private = list( ..dep = NA, ..factors = NA, ..method = NA, ..ph = NA, ..tr = NA, ..est = NA, ..nboot = NA, ..dist = NA) ) ranovaResults <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "ranovaResults", inherit = jmvcore::Group, active = list( main = function() private$.items[["main"]], phs = function() private$.items[["phs"]]), private = list(), public=list( initialize=function(options) { super$initialize( options=options, name="", title="Robust ANOVA") self$add(jmvcore::Table$new( options=options, name="main", title="Robust ANOVA", clearWith=list( "dep", "factors", "method", "nboot", "tr", "est", "dist"), columns=list( list( `name`="name", `title`="", `type`="text"), list( `name`="s", `title`="F", `type`="number"), list( `name`="p", `title`="p", `type`="number", `format`="zto,pvalue")))) self$add(jmvcore::Array$new( options=options, name="phs", title="Post Hoc Tests", items="(factors)", visible="(ph)", template=jmvcore::Table$new( options=options, name="ph", title="Post Hoc Tests - $key", clearWith=list( "dep", "factors", "method", "nboot", "tr", "est", "dist"), columns=list( list( `name`="v1", `title`="", `type`="text"), list( `name`="v2", `title`="", `type`="text"), list( `name`="psi", `title`="psi-hat", `type`="number"), list( `name`="p", `title`="p", `type`="number", `format`="zto,pvalue"), list( `name`="cil", `title`="Lower", `superTitle`="95% Confidence interval", `type`="number"), list( `name`="ciu", `title`="Upper", `superTitle`="95% Confidence interval", `type`="number")))))})) ranovaBase <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "ranovaBase", inherit = jmvcore::Analysis, public = list( initialize = function(options, data=NULL, datasetId="", analysisId="", revision=0) { super$initialize( package = "walrus", name = "ranova", version = c(1,0,0), options = options, results = ranovaResults$new(options=options), data = data, datasetId = datasetId, analysisId = analysisId, revision = revision, pause = NULL, completeWhenFilled = TRUE, requiresMissings = FALSE) })) #' Robust ANOVA #' #' Robust Analysis of Variance #' #' @examples #' data('goggles', package='WRS2') #' #' ranova(goggles, #' dep = 'attractiveness', #' factors = c('gender', 'alcohol'), #' ph = TRUE) #' #' # #' # ROBUST ANOVA #' # #' # Robust ANOVA #' # ------------------------------------ #' # Q p #' # ------------------------------------ #' # gender 1.67 0.209 #' # alcohol 48.28 0.001 #' # gender:alcohol 26.26 0.001 #' # ------------------------------------ #' # Note. Method of trimmed means, #' # trim level 0.2 #' # #' # #' # POST HOC TESTS #' # #' # Post Hoc Tests - gender #' # -------------------------------------------------------- #' # psi-hat p Lower Upper #' # -------------------------------------------------------- #' # Female Male 10.0 0.209 -6.00 26.0 #' # -------------------------------------------------------- #' # #' # #' # Post Hoc Tests - alcohol #' # ------------------------------------------------------------- #' # psi-hat p Lower Upper #' # ------------------------------------------------------------- #' # None 2 Pints -3.33 0.611 -20.5 13.8 #' # None 4 Pints 35.83 < .001 19.3 52.3 #' # 2 Pints 4 Pints 39.17 < .001 22.5 55.9 #' # ------------------------------------------------------------- #' # #' #' @param data the data as a data frame #' @param dep a string naming the dependent variable from \code{data}; the #' variable must be numeric #' @param factors a vector of strings naming the fixed factors from #' \code{data} #' @param method \code{'median'}, \code{'trim'} (default) or \code{'boot'}; #' the method to use, median, trimmed means, or bootstrapped #' @param ph \code{TRUE} or \code{FALSE} (default), provide post hoc tests #' @param tr a number between 0 and 0.5, (default: 0.2), the proportion of #' measurements to trim from each end, when using the trim and bootstrap #' methods #' @param est \code{'onestep'}, \code{'mom'} (default) or \code{'median'}, the #' M-estimator to use; One-step, Modified one-step or Median respectively #' @param nboot a number (default: 599) specifying the number of bootstrap #' samples to use when using the bootstrap method #' @param dist \code{'maha'} or \code{'proj'} (default), whether to use #' Mahalanobis or Projection distances respectively #' @return A results object containing: #' \tabular{llllll}{ #' \code{results$main} \tab \tab \tab \tab \tab the table of ANOVA results \cr #' \code{results$phs} \tab \tab \tab \tab \tab the table of posthoc tests \cr #' } #' #' Tables can be converted to data frames with \code{asDF} or \code{\link{as.data.frame}}. For example: #' #' \code{results$main$asDF} #' #' \code{as.data.frame(results$main)} #' #' @export ranova <- function( data, dep, factors = NULL, method = "trim", ph = FALSE, tr = 0.2, est = "mom", nboot = 599, dist = "proj") { if ( ! requireNamespace("jmvcore", quietly=TRUE)) stop("ranova requires jmvcore to be installed (restart may be required)") if ( ! missing(dep)) dep <- jmvcore::resolveQuo(jmvcore::enquo(dep)) if ( ! missing(factors)) factors <- jmvcore::resolveQuo(jmvcore::enquo(factors)) if (missing(data)) data <- jmvcore::marshalData( parent.frame(), `if`( ! missing(dep), dep, NULL), `if`( ! missing(factors), factors, NULL)) for (v in factors) if (v %in% names(data)) data[[v]] <- as.factor(data[[v]]) options <- ranovaOptions$new( dep = dep, factors = factors, method = method, ph = ph, tr = tr, est = est, nboot = nboot, dist = dist) analysis <- ranovaClass$new( options = options, data = data) analysis$run() analysis$results }
/scratch/gouwar.j/cran-all/cranData/walrus/R/ranova.h.R
# This file is a generated template, your changes will not be overwritten rdescClass <- R6::R6Class( "rdescClass", inherit = rdescBase, private = list( .init = function() { vars <- self$options$vars table <- self$results$table if (is.null(self$options$splitBy)) { for (i in seq_along(vars)) table$addRow(rowKey=i, values=list("var"=vars[i])) } else { levels <- levels(self$data[[self$options$splitBy]]) rowNo <- 1 for (var in vars) { for (level in levels) { table$addRow(rowKey=rowNo, values=list("var"=var, "level"=level)) rowNo <- rowNo + 1 } } } }, .run = function() { vars <- self$options$vars table <- self$results$table data <- self$data if (is.null(self$options$splitBy)) { for (i in seq_along(vars)) { v <- jmvcore::toNumeric(data[[vars[i]]]) v <- na.omit(v) r <- private$.means(v) table$setRow(rowNo=i, values=list( `m[m]`=r$m, `se[m]`=r$mse, `m[tr]`=r$mtr, `se[tr]`=r$mtrse, `m[w]`=r$w, `se[w]`=r$wse, `m[med]`=r$med, `se[med]`=r$medse, `m[est]`=r$mest, `se[est]`=r$mestse)) } } else { f <- factor(data[[self$options$splitBy]]) levels <- levels(f) rowNo <- 1 for (i in seq_along(vars)) { v <- jmvcore::toNumeric(data[[vars[i]]]) df <- data.frame(v=v, f=f) df <- jmvcore::naOmit(df) means <- tapply(df$v, df$f, private$.means) for (j in seq_along(levels)) { r <- means[[levels[j]]] table$setRow(rowNo=rowNo, values=list( `m[m]`=r$m, `se[m]`=r$mse, `m[tr]`=r$mtr, `se[tr]`=r$mtrse, `m[w]`=r$w, `se[w]`=r$wse, `m[med]`=r$med, `se[med]`=r$medse, `m[est]`=r$mest, `se[est]`=r$mestse)) rowNo <- rowNo + 1 } } } }, .means = function(v) { tr <- self$options$tr wl <- self$options$wl bend <- self$options$bend m <- jmvcore::tryNaN(mean(v)) mse <- jmvcore::tryNaN(WRS2::trimse(v, tr=0)) mtr <- jmvcore::tryNaN(mean(v, trim=tr)) mtrse <- jmvcore::tryNaN(WRS2::trimse(v, tr=tr)) w <- jmvcore::tryNaN(WRS2::winmean(v, tr=wl)) wse <- jmvcore::tryNaN(WRS2::winse(v, tr=wl)) med <- jmvcore::tryNaN(median(v)) medse <- jmvcore::tryNaN(WRS2::msmedse(v, sewarn=FALSE)) mest <- jmvcore::tryNaN(WRS2::mest(v, bend=bend)) mestse <- jmvcore::tryNaN(WRS2::mestse(v, bend=bend)) r <- list("m"=m, "mse"=mse, "mtr"=mtr, "mtrse"=mtrse, "w"=w, "wse"=wse, "med"=med, "medse"=medse, "mest"=mest, "mestse"=mestse) return(r) }) )
/scratch/gouwar.j/cran-all/cranData/walrus/R/rdesc.b.R
# This file is automatically generated, you probably don't want to edit this rdescOptions <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "rdescOptions", inherit = jmvcore::Options, public = list( initialize = function( vars = NULL, splitBy = NULL, mean = TRUE, trim = TRUE, tr = 0.2, win = FALSE, wl = 0.2, mest = FALSE, bend = 1.28, med = FALSE, ...) { super$initialize( package="walrus", name="rdesc", requiresData=TRUE, ...) private$..vars <- jmvcore::OptionVariables$new( "vars", vars, suggested=list( "continuous"), permitted=list( "numeric")) private$..splitBy <- jmvcore::OptionVariable$new( "splitBy", splitBy, default=NULL, suggested=list( "nominal"), permitted=list( "factor")) private$..mean <- jmvcore::OptionBool$new( "mean", mean, default=TRUE) private$..trim <- jmvcore::OptionBool$new( "trim", trim, default=TRUE) private$..tr <- jmvcore::OptionNumber$new( "tr", tr, default=0.2, min=0, max=0.5) private$..win <- jmvcore::OptionBool$new( "win", win, default=FALSE) private$..wl <- jmvcore::OptionNumber$new( "wl", wl, default=0.2, min=0, max=0.5) private$..mest <- jmvcore::OptionBool$new( "mest", mest, default=FALSE) private$..bend <- jmvcore::OptionNumber$new( "bend", bend, default=1.28) private$..med <- jmvcore::OptionBool$new( "med", med, default=FALSE) self$.addOption(private$..vars) self$.addOption(private$..splitBy) self$.addOption(private$..mean) self$.addOption(private$..trim) self$.addOption(private$..tr) self$.addOption(private$..win) self$.addOption(private$..wl) self$.addOption(private$..mest) self$.addOption(private$..bend) self$.addOption(private$..med) }), active = list( vars = function() private$..vars$value, splitBy = function() private$..splitBy$value, mean = function() private$..mean$value, trim = function() private$..trim$value, tr = function() private$..tr$value, win = function() private$..win$value, wl = function() private$..wl$value, mest = function() private$..mest$value, bend = function() private$..bend$value, med = function() private$..med$value), private = list( ..vars = NA, ..splitBy = NA, ..mean = NA, ..trim = NA, ..tr = NA, ..win = NA, ..wl = NA, ..mest = NA, ..bend = NA, ..med = NA) ) rdescResults <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "rdescResults", inherit = jmvcore::Group, active = list( table = function() private$.items[["table"]]), private = list(), public=list( initialize=function(options) { super$initialize( options=options, name="", title="Robust Descriptives") self$add(jmvcore::Table$new( options=options, name="table", title="Robust Descriptives", clearWith=list( "tr", "wl", "bend", "splitBy"), columns=list( list( `name`="var", `title`="", `type`="text", `combineBelow`=TRUE), list( `name`="level", `title`="", `type`="text", `visible`="(splitBy)"), list( `name`="s[m]", `title`="", `type`="text", `content`="Mean", `visible`="(mean)"), list( `name`="m[m]", `title`="", `visible`="(mean)"), list( `name`="se[m]", `title`="SE", `visible`="(mean)"), list( `name`="s[tr]", `title`="", `type`="text", `content`="Trimmed mean", `visible`="(trim)"), list( `name`="m[tr]", `title`="", `visible`="(trim)"), list( `name`="se[tr]", `title`="SE", `visible`="(trim)"), list( `name`="s[w]", `title`="", `type`="text", `content`="Winsorized mean", `visible`="(win)"), list( `name`="m[w]", `title`="", `visible`="(win)"), list( `name`="se[w]", `title`="SE", `visible`="(win)"), list( `name`="s[est]", `title`="", `type`="text", `content`="M-estimator", `visible`="(mest)"), list( `name`="m[est]", `title`="", `visible`="(mest)"), list( `name`="se[est]", `title`="SE", `visible`="(mest)"), list( `name`="s[med]", `title`="", `type`="text", `content`="Median", `visible`="(med)"), list( `name`="m[med]", `title`="", `visible`="(med)"), list( `name`="se[med]", `title`="SE", `visible`="(med)"))))})) rdescBase <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "rdescBase", inherit = jmvcore::Analysis, public = list( initialize = function(options, data=NULL, datasetId="", analysisId="", revision=0) { super$initialize( package = "walrus", name = "rdesc", version = c(1,0,0), options = options, results = rdescResults$new(options=options), data = data, datasetId = datasetId, analysisId = analysisId, revision = revision, pause = NULL, completeWhenFilled = FALSE, requiresMissings = FALSE) })) #' Robust Descriptives #' #' Robust Descriptives #' #' @examples #' #' data('eurosoccer', package='WRS2') #' #' SpainGermany <- subset(eurosoccer, eurosoccer$League == 'Spain' | eurosoccer$League == 'Germany') #' SpainGermany <- droplevels(SpainGermany) #' #' walrus::rdesc( #' data = SpainGermany, #' vars = "GoalsGame", #' splitBy = "League", #' med = TRUE) #' #' # #' # ROBUST DESCRIPTIVES #' # #' # Robust Descriptives #' # ---------------------------------------------------------- #' # SE #' # ---------------------------------------------------------- #' # GoalsGame Germany Mean 1.46 0.105 #' # Trimmed mean 1.45 0.1341 #' # Median 1.43 0.1599 #' # #' # Spain Mean 1.45 0.101 #' # Trimmed mean 1.33 0.0601 #' # Median 1.30 0.0766 #' # ---------------------------------------------------------- #' # #' #' @param data the data as a data frame #' @param vars a vector of strings naming the variables in \code{data} of #' interest #' @param splitBy a string naming the variable in \code{data} to split the #' data by #' @param mean \code{TRUE} (default) or \code{FALSE}, provide a 'normal' #' arithmetic mean #' @param trim \code{TRUE} (default) or \code{FALSE}, provide a trimmed mean #' @param tr a number between 0 and 0.5 (default: 0.2); the proportion of #' measurements to trim from each end when producing trimmed means #' @param win \code{TRUE} or \code{FALSE} (default), provide a 'Winsorized' #' mean #' @param wl a number between 0 and 0.5 (default: 0.2); the level of #' 'winsorizing' when producing winsorized means #' @param mest \code{TRUE} or \code{FALSE} (default), provide an 'M-estimated' #' value #' @param bend a number (default: 1.28), the bending constant to use when #' using M-estimators #' @param med \code{TRUE} or \code{FALSE} (default), provide medians #' @return A results object containing: #' \tabular{llllll}{ #' \code{results$table} \tab \tab \tab \tab \tab the table of descriptives \cr #' } #' #' Tables can be converted to data frames with \code{asDF} or \code{\link{as.data.frame}}. For example: #' #' \code{results$table$asDF} #' #' \code{as.data.frame(results$table)} #' #' @export rdesc <- function( data, vars, splitBy = NULL, mean = TRUE, trim = TRUE, tr = 0.2, win = FALSE, wl = 0.2, mest = FALSE, bend = 1.28, med = FALSE) { if ( ! requireNamespace("jmvcore", quietly=TRUE)) stop("rdesc requires jmvcore to be installed (restart may be required)") if ( ! missing(vars)) vars <- jmvcore::resolveQuo(jmvcore::enquo(vars)) if ( ! missing(splitBy)) splitBy <- jmvcore::resolveQuo(jmvcore::enquo(splitBy)) if (missing(data)) data <- jmvcore::marshalData( parent.frame(), `if`( ! missing(vars), vars, NULL), `if`( ! missing(splitBy), splitBy, NULL)) for (v in splitBy) if (v %in% names(data)) data[[v]] <- as.factor(data[[v]]) options <- rdescOptions$new( vars = vars, splitBy = splitBy, mean = mean, trim = trim, tr = tr, win = win, wl = wl, mest = mest, bend = bend, med = med) analysis <- rdescClass$new( options = options, data = data) analysis$run() analysis$results }
/scratch/gouwar.j/cran-all/cranData/walrus/R/rdesc.h.R
# This file is a generated template, your changes will not be overwritten rplotsClass <- R6::R6Class( "rplotsClass", inherit = rplotsBase, private = list( .run = function() { vars <- self$options$vars factor <- self$options$splitBy for (var in vars) { image <- self$results$plots$get(key=var) v <- jmvcore::toNumeric(self$data[[var]]) df <- data.frame(v=v) if ( ! is.null(self$options$splitBy)) df$f <- factor(self$data[[factor]]) else df$f <- factor(rep('var', length(v))) df <- jmvcore::naOmit(df) image$setState(df) } }, .plot = function(image, ggtheme, theme, ...) { if (is.null(image$state)) return(FALSE) factor <- self$options$splitBy p <- ggplot2::ggplot(data=image$state, ggplot2::aes(x = f, y = v)) + ggtheme + ggplot2::theme(legend.position = "none") + ggplot2::labs(x=factor, y=image$key) if (self$options$violin) p <- p + ggplot2::geom_violin(fill=theme$fill[1], color=theme$color[1]) if (self$options$dot) { if (self$options$dotType == 'jitter') p <- p + ggplot2::geom_jitter(color=theme$color[1], width=0.1, alpha=0.4) else p <- p + ggplot2::geom_dotplot(binaxis = "y", stackdir = "center", color=theme$color[1], alpha=0.4, stackratio=0.9, dotsize=0.7) } if (self$options$boxplot) p <- p + ggplot2::geom_boxplot(color=theme$color[1], width=0.2, alpha=0.9, fill=theme$fill[2], outlier.colour=theme$color[1]) if (is.null(self$options$splitBy)) { p <- p + ggplot2::theme(axis.text.x = ggplot2::element_blank(), axis.ticks.x = ggplot2::element_blank(), axis.title.x = ggplot2::element_blank()) } suppressWarnings({ suppressMessages({ print(p) }) # suppressMessages }) # suppressWarnings TRUE }) )
/scratch/gouwar.j/cran-all/cranData/walrus/R/rplots.b.R
# This file is automatically generated, you probably don't want to edit this rplotsOptions <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "rplotsOptions", inherit = jmvcore::Options, public = list( initialize = function( vars = NULL, splitBy = NULL, violin = TRUE, boxplot = FALSE, dot = TRUE, dotType = "stack", ...) { super$initialize( package="walrus", name="rplots", requiresData=TRUE, ...) private$..vars <- jmvcore::OptionVariables$new( "vars", vars, suggested=list( "continuous"), permitted=list( "numeric")) private$..splitBy <- jmvcore::OptionVariable$new( "splitBy", splitBy, default=NULL, suggested=list( "nominal"), permitted=list( "factor")) private$..violin <- jmvcore::OptionBool$new( "violin", violin, default=TRUE) private$..boxplot <- jmvcore::OptionBool$new( "boxplot", boxplot, default=FALSE) private$..dot <- jmvcore::OptionBool$new( "dot", dot, default=TRUE) private$..dotType <- jmvcore::OptionList$new( "dotType", dotType, options=list( "jitter", "stack"), default="stack") self$.addOption(private$..vars) self$.addOption(private$..splitBy) self$.addOption(private$..violin) self$.addOption(private$..boxplot) self$.addOption(private$..dot) self$.addOption(private$..dotType) }), active = list( vars = function() private$..vars$value, splitBy = function() private$..splitBy$value, violin = function() private$..violin$value, boxplot = function() private$..boxplot$value, dot = function() private$..dot$value, dotType = function() private$..dotType$value), private = list( ..vars = NA, ..splitBy = NA, ..violin = NA, ..boxplot = NA, ..dot = NA, ..dotType = NA) ) rplotsResults <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "rplotsResults", inherit = jmvcore::Group, active = list( plots = function() private$.items[["plots"]]), private = list(), public=list( initialize=function(options) { super$initialize( options=options, name="", title="Box & Violin Plots") self$add(jmvcore::Array$new( options=options, name="plots", title="Plots", items="(vars)", template=jmvcore::Image$new( options=options, title="$key", renderFun=".plot", clearWith=list( "splitBy", "violin", "boxplot", "dot", "dotType"))))})) rplotsBase <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "rplotsBase", inherit = jmvcore::Analysis, public = list( initialize = function(options, data=NULL, datasetId="", analysisId="", revision=0) { super$initialize( package = "walrus", name = "rplots", version = c(1,0,0), options = options, results = rplotsResults$new(options=options), data = data, datasetId = datasetId, analysisId = analysisId, revision = revision, pause = NULL, completeWhenFilled = FALSE, requiresMissings = FALSE) })) #' Box & Violin Plots #' #' Box & Violin Plots #' #' @examples #' data('eurosoccer', package='WRS2') #' #' # violin plots #' #' walrus::rplots( #' data = eurosoccer, #' vars = "GoalsGame", #' splitBy = "League") #' #' #' # box plots #' #' walrus::rplots( #' data = eurosoccer, #' vars = "GoalsGame", #' splitBy = "League", #' violin = FALSE, #' boxplot = TRUE, #' dot = FALSE) #' #' @param data the data as a data frame #' @param vars a vector of strings naming the variables in \code{data} of #' interest #' @param splitBy a string naming the variable in \code{data} to split the #' data by #' @param violin \code{TRUE} (default) or \code{FALSE}, provide violin plots #' @param boxplot \code{TRUE} or \code{FALSE} (default), provide box plots #' @param dot \code{TRUE} (default) or \code{FALSE}, plot each measurement as #' a dot #' @param dotType \code{'jitter'} or \code{'stack'} (default); whether data #' dots are jittered or stacked #' @return A results object containing: #' \tabular{llllll}{ #' \code{results$plots} \tab \tab \tab \tab \tab an array of images \cr #' } #' #' @export rplots <- function( data, vars, splitBy = NULL, violin = TRUE, boxplot = FALSE, dot = TRUE, dotType = "stack") { if ( ! requireNamespace("jmvcore", quietly=TRUE)) stop("rplots requires jmvcore to be installed (restart may be required)") if ( ! missing(vars)) vars <- jmvcore::resolveQuo(jmvcore::enquo(vars)) if ( ! missing(splitBy)) splitBy <- jmvcore::resolveQuo(jmvcore::enquo(splitBy)) if (missing(data)) data <- jmvcore::marshalData( parent.frame(), `if`( ! missing(vars), vars, NULL), `if`( ! missing(splitBy), splitBy, NULL)) for (v in splitBy) if (v %in% names(data)) data[[v]] <- as.factor(data[[v]]) options <- rplotsOptions$new( vars = vars, splitBy = splitBy, violin = violin, boxplot = boxplot, dot = dot, dotType = dotType) analysis <- rplotsClass$new( options = options, data = data) analysis$run() analysis$results }
/scratch/gouwar.j/cran-all/cranData/walrus/R/rplots.h.R
rttestISClass <- R6::R6Class( "rttestISClass", inherit = rttestISBase, private = list( .init = function() { est <- self$options$method ttestTable <- self$results$ttest method = 'Unknown' if (est == 'onestep') method = 'One-step' else if (est == 'mom') method = 'Modified one-step' else if (est == 'mean') method = 'Mean' else if (est == 'median') method = 'Median' for (dep in ttestTable$rowKeys) ttestTable$addFootnote(rowKey=dep, col='test[mest]', paste(method, 'estimator used')) }, .run = function() { group <- self$options$group deps <- self$options$deps all <- c(group, deps) if (is.null(group) || length(deps) == 0) return() trim <- self$options$tr data <- self$data for (dep in deps) data[[dep]] <- jmvcore::toNumeric(data[[dep]]) ttestTable <- self$results$ttest for (dep in deps) { fmla <- jmvcore::constructFormula(dep, group) fmla <- formula(fmla) res <- try(WRS2::yuen(fmla, data, tr=trim)) if ( ! jmvcore::isError(res)) { ttestTable$setRow(rowKey=dep, values=list( `t[yuen]`=res$test, `df[yuen]`=res$df, `p[yuen]`=res$p.value, `md[yuen]`=res$diff, `cil[yuen]`=res$conf.int[1], `ciu[yuen]`=res$conf.int[2])) } else { ttestTable$setRow(rowKey=dep, values=list( `t[yuen]`=NaN, `df[yuen]`='', `p[yuen]`='')) error <- jmvcore::extractErrorMessage(res) ttestTable$addFootnote(rowKey=dep, col='t[yuen]', error) } res <- try(WRS2::yuen.effect.ci(fmla, data, tr=trim)) if ( ! jmvcore::isError(res)) { ttestTable$setRow(rowKey=dep, values=list( `es[yuen]`=res$effsize, `escil[yuen]`=res$CI[1], `esciu[yuen]`=res$CI[2])) } else { ttestTable$setRow(rowKey=dep, values=list( `es[yuen]`=NaN, `escil[yuen]`='', `esciu[yuen]`='')) error <- jmvcore::extractErrorMessage(res) ttestTable$addFootnote(rowKey=dep, col='es[yuen]', error) } if (self$options$yuenbt) { private$.checkpoint() res <- try(WRS2::yuenbt(fmla, data, tr=trim, nboot=self$options$nboot)) if ( ! jmvcore::isError(res)) { ttestTable$setRow(rowKey=dep, values=list( `t[yuenbt]`=res$test, `df[yuenbt]`='', `p[yuenbt]`=res$p.value)) } else { ttestTable$setRow(rowKey=dep, values=list( `t[yuenbt]`=NaN, `df[yuenbt]`='', `p[yuenbt]`='')) error <- jmvcore::extractErrorMessage(res) ttestTable$addFootnote(rowKey=dep, col='t[yuenbt]', error) } } if (self$options$mest) { private$.checkpoint() method <- self$options$method res <- try(WRS2::pb2gen(fmla, data, est=method)) if ( ! jmvcore::isError(res)) { ttestTable$setRow(rowKey=dep, values=list( `t[mest]`=res$test, `df[mest]`='', `p[mest]`=res$p.value)) } else { ttestTable$setRow(rowKey=dep, values=list( `t[mest]`=NaN, `df[mest]`='', `p[mest]`='')) error <- jmvcore::extractErrorMessage(res) ttestTable$addFootnote(rowKey=dep, col='t[mest]', error) } } private$.checkpoint() } }) )
/scratch/gouwar.j/cran-all/cranData/walrus/R/rttestis.b.R
# This file is automatically generated, you probably don't want to edit this rttestISOptions <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "rttestISOptions", inherit = jmvcore::Options, public = list( initialize = function( deps = NULL, group = NULL, yuen = TRUE, tr = 0.2, mest = FALSE, method = "mom", yuenbt = FALSE, nboot = 599, md = FALSE, ci = FALSE, es = FALSE, esci = FALSE, ...) { super$initialize( package="walrus", name="rttestIS", requiresData=TRUE, ...) private$..deps <- jmvcore::OptionVariables$new( "deps", deps, suggested=list( "continuous"), permitted=list( "numeric")) private$..group <- jmvcore::OptionVariable$new( "group", group, suggested=list( "nominal"), permitted=list( "factor")) private$..yuen <- jmvcore::OptionBool$new( "yuen", yuen, default=TRUE) private$..tr <- jmvcore::OptionNumber$new( "tr", tr, default=0.2, min=0, max=0.5) private$..mest <- jmvcore::OptionBool$new( "mest", mest, default=FALSE) private$..method <- jmvcore::OptionList$new( "method", method, options=list( "onestep", "mom", "median", "mean"), default="mom") private$..yuenbt <- jmvcore::OptionBool$new( "yuenbt", yuenbt, default=FALSE) private$..nboot <- jmvcore::OptionInteger$new( "nboot", nboot, min=0, default=599) private$..md <- jmvcore::OptionBool$new( "md", md, default=FALSE) private$..ci <- jmvcore::OptionBool$new( "ci", ci, default=FALSE) private$..es <- jmvcore::OptionBool$new( "es", es, default=FALSE) private$..esci <- jmvcore::OptionBool$new( "esci", esci, default=FALSE) self$.addOption(private$..deps) self$.addOption(private$..group) self$.addOption(private$..yuen) self$.addOption(private$..tr) self$.addOption(private$..mest) self$.addOption(private$..method) self$.addOption(private$..yuenbt) self$.addOption(private$..nboot) self$.addOption(private$..md) self$.addOption(private$..ci) self$.addOption(private$..es) self$.addOption(private$..esci) }), active = list( deps = function() private$..deps$value, group = function() private$..group$value, yuen = function() private$..yuen$value, tr = function() private$..tr$value, mest = function() private$..mest$value, method = function() private$..method$value, yuenbt = function() private$..yuenbt$value, nboot = function() private$..nboot$value, md = function() private$..md$value, ci = function() private$..ci$value, es = function() private$..es$value, esci = function() private$..esci$value), private = list( ..deps = NA, ..group = NA, ..yuen = NA, ..tr = NA, ..mest = NA, ..method = NA, ..yuenbt = NA, ..nboot = NA, ..md = NA, ..ci = NA, ..es = NA, ..esci = NA) ) rttestISResults <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "rttestISResults", inherit = jmvcore::Group, active = list( ttest = function() private$.items[["ttest"]]), private = list(), public=list( initialize=function(options) { super$initialize( options=options, name="", title="Robust Independent Samples T-Test") self$add(jmvcore::Table$new( options=options, name="ttest", title="Robust Independent Samples T-Test", rows="(deps)", clearWith=list( "group", "method", "tr", "nboot"), columns=list( list( `name`="var", `title`="", `type`="text", `content`="($key)"), list( `name`="test[yuen]", `title`="", `type`="text", `content`="Yuen's test", `visible`="(yuen)"), list( `name`="t[yuen]", `title`="t", `type`="number", `visible`="(yuen)"), list( `name`="df[yuen]", `title`="df", `type`="number", `visible`="(yuen)"), list( `name`="p[yuen]", `title`="p", `type`="number", `format`="zto,pvalue", `visible`="(yuen)"), list( `name`="md[yuen]", `title`="Mean diff", `type`="number", `visible`="(yuen && md)"), list( `name`="cil[yuen]", `superTitle`="95% Confidence Interval", `title`="Lower", `type`="number", `visible`="(yuen && ci)"), list( `name`="ciu[yuen]", `superTitle`="95% Confidence Interval", `title`="Upper", `type`="number", `visible`="(yuen && ci)"), list( `name`="es[yuen]", `title`="\u03BE", `type`="number", `visible`="(yuen && es)"), list( `name`="escil[yuen]", `superTitle`="95% \u03BE Confidence Interval", `title`="Lower", `type`="number", `visible`="(yuen && esci)"), list( `name`="esciu[yuen]", `superTitle`="95% \u03BE Confidence Interval", `title`="Upper", `type`="number", `visible`="(yuen && esci)"), list( `name`="test[yuenbt]", `title`="", `type`="text", `content`="Yuen's bootstrapped", `visible`="(yuen && yuenbt)"), list( `name`="t[yuenbt]", `title`="t", `type`="number", `visible`="(yuen && yuenbt)"), list( `name`="df[yuenbt]", `title`="df", `type`="number", `visible`="(yuen && yuenbt)"), list( `name`="p[yuenbt]", `title`="p", `type`="number", `format`="zto,pvalue", `visible`="(yuen && yuenbt)"), list( `name`="test[mest]", `title`="", `type`="text", `content`="M-estimator", `visible`="(mest)"), list( `name`="t[mest]", `title`="t", `type`="number", `visible`="(mest)"), list( `name`="df[mest]", `title`="df", `type`="number", `visible`="(mest)"), list( `name`="p[mest]", `title`="p", `type`="number", `format`="zto,pvalue", `visible`="(mest)"))))})) rttestISBase <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "rttestISBase", inherit = jmvcore::Analysis, public = list( initialize = function(options, data=NULL, datasetId="", analysisId="", revision=0) { super$initialize( package = "walrus", name = "rttestIS", version = c(1,0,0), options = options, results = rttestISResults$new(options=options), data = data, datasetId = datasetId, analysisId = analysisId, revision = revision, pause = NULL, completeWhenFilled = TRUE, requiresMissings = FALSE) })) #' Robust Independent Samples T-Test #' #' Robust Independent Samples T-Test #' #' @examples #' data('eurosoccer', package='WRS2') #' #' SpainGermany <- subset(eurosoccer, eurosoccer$League == 'Spain' | eurosoccer$League == 'Germany') #' SpainGermany <- droplevels(SpainGermany) #' #' rttestIS(SpainGermany, #' dep = 'GoalsScored', #' group = 'League', #' yuen = TRUE, #' mest = TRUE) #' #' # #' # ROBUST INDEPENDENT SAMPLES T-TEST #' # #' # Robust Independent Samples T-Test #' # --------------------------------------------------------- #' # t df p #' # --------------------------------------------------------- #' # GoalsScored Yuen's test 0.297 17.3 0.770 #' # M-estimator -0.933 0.993 #' # --------------------------------------------------------- #' # #' #' @param data the data as a data frame #' @param deps a vector of strings naming the dependent variables in #' \code{data} #' @param group a string naming the grouping variable in \code{data}; must #' have 2 levels #' @param yuen \code{TRUE} (default) or \code{FALSE}, use the Yuen's trim #' method #' @param tr a number between 0 and 0.5, (default: 0.2), the proportion of #' measurements to trim from each end, when using the trim and bootstrap #' methods #' @param mest \code{TRUE} or \code{FALSE} (default), use an M-estimator #' @param method \code{'onestep'}, \code{'mom'} (default) or \code{'median'}, #' the M-estimator to use; One-step, Modified one-step or Median respectively #' @param yuenbt \code{TRUE} or \code{FALSE} (default), use the Yuen's #' bootstrap method #' @param nboot a number (default: 599) specifying the number of bootstrap #' samples to use when using the bootstrap method #' @param md \code{TRUE} or \code{FALSE} (default), provide the mean #' difference #' @param ci \code{TRUE} or \code{FALSE} (default), provide a 95\% confidence #' interval on the mean difference #' @param es \code{TRUE} or \code{FALSE} (default), provide the effect-size #' @param esci \code{TRUE} or \code{FALSE} (default), provide a 95\% #' confidence interval on the effect-size #' @return A results object containing: #' \tabular{llllll}{ #' \code{results$ttest} \tab \tab \tab \tab \tab the table of t-test results \cr #' } #' #' Tables can be converted to data frames with \code{asDF} or \code{\link{as.data.frame}}. For example: #' #' \code{results$ttest$asDF} #' #' \code{as.data.frame(results$ttest)} #' #' @export rttestIS <- function( data, deps, group, yuen = TRUE, tr = 0.2, mest = FALSE, method = "mom", yuenbt = FALSE, nboot = 599, md = FALSE, ci = FALSE, es = FALSE, esci = FALSE) { if ( ! requireNamespace("jmvcore", quietly=TRUE)) stop("rttestIS requires jmvcore to be installed (restart may be required)") if ( ! missing(deps)) deps <- jmvcore::resolveQuo(jmvcore::enquo(deps)) if ( ! missing(group)) group <- jmvcore::resolveQuo(jmvcore::enquo(group)) if (missing(data)) data <- jmvcore::marshalData( parent.frame(), `if`( ! missing(deps), deps, NULL), `if`( ! missing(group), group, NULL)) for (v in group) if (v %in% names(data)) data[[v]] <- as.factor(data[[v]]) options <- rttestISOptions$new( deps = deps, group = group, yuen = yuen, tr = tr, mest = mest, method = method, yuenbt = yuenbt, nboot = nboot, md = md, ci = ci, es = es, esci = esci) analysis <- rttestISClass$new( options = options, data = data) analysis$run() analysis$results }
/scratch/gouwar.j/cran-all/cranData/walrus/R/rttestis.h.R
# This file is a generated template, your changes will not be overwritten rttestPSClass <- R6::R6Class( "rttestPSClass", inherit = rttestPSBase, private = list( .init = function() { table <- self$results$ttest for (key in table$rowKeys) table$setRow(rowKey=key, values=list(var1=key[[1]], var2=key[[2]])) }, .run = function() { table <- self$results$ttest data <- self$data for (col in colnames(data)) data[[col]] <- jmvcore::toNumeric(data[[col]]) for (key in table$rowKeys) { if (is.null(key[[1]]) || is.null(key[[2]])) next() v1 <- data[[key[[1]]]] v2 <- data[[key[[2]]]] res <- WRS2::yuend(v1, v2, self$options$tr) table$setRow(rowKey=key, values=list( t=res$test, df=res$df, p=res$p.value, md=res$diff, se=res$se, es=res$effsize, cil=res$conf.int[1], ciu=res$conf.int[2])) } }) )
/scratch/gouwar.j/cran-all/cranData/walrus/R/rttestps.b.R
# This file is automatically generated, you probably don't want to edit this rttestPSOptions <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "rttestPSOptions", inherit = jmvcore::Options, public = list( initialize = function( pairs = NULL, tr = 0.2, md = FALSE, es = FALSE, ci = FALSE, ...) { super$initialize( package="walrus", name="rttestPS", requiresData=TRUE, ...) private$..pairs <- jmvcore::OptionPairs$new( "pairs", pairs, suggested=list( "continuous"), permitted=list( "numeric")) private$..tr <- jmvcore::OptionNumber$new( "tr", tr, min=0, max=0.5, default=0.2) private$..md <- jmvcore::OptionBool$new( "md", md, default=FALSE) private$..es <- jmvcore::OptionBool$new( "es", es, default=FALSE) private$..ci <- jmvcore::OptionBool$new( "ci", ci, default=FALSE) self$.addOption(private$..pairs) self$.addOption(private$..tr) self$.addOption(private$..md) self$.addOption(private$..es) self$.addOption(private$..ci) }), active = list( pairs = function() private$..pairs$value, tr = function() private$..tr$value, md = function() private$..md$value, es = function() private$..es$value, ci = function() private$..ci$value), private = list( ..pairs = NA, ..tr = NA, ..md = NA, ..es = NA, ..ci = NA) ) rttestPSResults <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "rttestPSResults", inherit = jmvcore::Group, active = list( ttest = function() private$.items[["ttest"]]), private = list(), public=list( initialize=function(options) { super$initialize( options=options, name="", title="Robust Paired Samples T-Test") self$add(jmvcore::Table$new( options=options, name="ttest", title="Robust Paired Samples T-Test", rows="(pairs)", clearWith=list( "tr"), columns=list( list( `name`="var1", `title`="", `type`="text"), list( `name`="var2", `title`="", `type`="text"), list( `name`="t", `title`="t"), list( `name`="df", `title`="df", `type`="number"), list( `name`="p", `title`="p", `type`="number", `format`="zto,pvalue"), list( `name`="md", `title`="Mean difference", `visible`="(md)"), list( `name`="se", `title`="SE", `visible`="(md)"), list( `name`="cil", `title`="Lower", `superTitle`="95% Confidence Interval", `visible`="(ci)"), list( `name`="ciu", `title`="Upper", `superTitle`="95% Confidence Interval", `visible`="(ci)"), list( `name`="es", `title`="Cohen's d", `visible`="(es)"))))})) rttestPSBase <- if (requireNamespace("jmvcore", quietly=TRUE)) R6::R6Class( "rttestPSBase", inherit = jmvcore::Analysis, public = list( initialize = function(options, data=NULL, datasetId="", analysisId="", revision=0) { super$initialize( package = "walrus", name = "rttestPS", version = c(1,0,0), options = options, results = rttestPSResults$new(options=options), data = data, datasetId = datasetId, analysisId = analysisId, revision = revision, pause = NULL, completeWhenFilled = TRUE, requiresMissings = FALSE) })) #' Robust Paired Samples T-Test #' #' Robust Paired Samples T-Test #' #' @examples #' data(anorexia, package='MASS') #' anorexiaFT <- subset(anorexia, subset = Treat == "FT") #' #' rttestPS(anorexiaFT, #' pairs = list( #' list(i1 = 'Prewt', i2 = 'Postwt'))) #' #' # #' # ROBUST PAIRED SAMPLES T-TEST #' # #' # Robust Paired Samples T-Test #' # --------------------------------------------- #' # t df p #' # --------------------------------------------- #' # Prewt Postwt -3.83 10.0 0.003 #' # --------------------------------------------- #' # #' #' @param data the data as a data frame #' @param pairs a list of lists specifying the pairs of measurement in #' \code{data} #' @param tr a number between 0 and 0.5, (default: 0.2), the proportion of #' measurements to trim from each end, when using the trim and bootstrap #' methods #' @param md \code{TRUE} or \code{FALSE} (default), provide means and standard #' errors #' @param es \code{TRUE} or \code{FALSE} (default), provide effect sizes #' @param ci \code{TRUE} or \code{FALSE} (default), provide confidence #' intervals #' @return A results object containing: #' \tabular{llllll}{ #' \code{results$ttest} \tab \tab \tab \tab \tab the table of t-test results \cr #' } #' #' Tables can be converted to data frames with \code{asDF} or \code{\link{as.data.frame}}. For example: #' #' \code{results$ttest$asDF} #' #' \code{as.data.frame(results$ttest)} #' #' @export rttestPS <- function( data, pairs, tr = 0.2, md = FALSE, es = FALSE, ci = FALSE) { if ( ! requireNamespace("jmvcore", quietly=TRUE)) stop("rttestPS requires jmvcore to be installed (restart may be required)") if (missing(data)) data <- jmvcore::marshalData( parent.frame()) options <- rttestPSOptions$new( pairs = pairs, tr = tr, md = md, es = es, ci = ci) analysis <- rttestPSClass$new( options = options, data = data) analysis$run() analysis$results }
/scratch/gouwar.j/cran-all/cranData/walrus/R/rttestps.h.R
#' @import jmvcore NULL #' Walrus #' #' A toolbox of common robust statistical tests, including robust #' descriptives, robust t-tests, and robust ANOVA. It is also available as a #' module for 'jamovi' (see \href{https://www.jamovi.org}{www.jamovi.org} for #' more information). #' Walrus is based on the \code{WRS2} package by Patrick Mair, which is in turn based on #' the scripts and work of Rand Wilcox. These analyses are described in depth in #' the book \href{https://www.amazon.com/Introduction-Estimation-Hypothesis-Statistical-Modeling/dp/012804733X}{Introduction to Robust Estimation & Hypothesis Testing}. #' #' \tabular{llllll}{ #' Box & Violin Plots \tab \tab \tab \tab \code{\link{rplots}()} \cr #' Robust Descriptives \tab \tab \tab \tab \code{\link{rdesc}()} \cr #' Robust Independent Samples T-Test \tab \tab \tab \tab \code{\link{rttestIS}}() \cr #' Robust Paired Samples T-Test \tab \tab \tab \tab \code{\link{rttestIS}()} \cr #' Robust ANOVA \tab \tab \tab \tab \code{\link{ranova}()} \cr #' } #' #' \preformatted{ #' Ravi: #' "Should we create a logo for walrus?" #' #' Jonathon: #' "Yeah, I guess. Maybe a walrus, or a #' skewed distribution? #' Bonus points if it somehow contains both." #' #' Ravi gets bonus points #' #' } #' #' \if{html}{\figure{walrus.svg}{options: width=72 style="padding-left: 50px"}} #' \if{latex}{\figure{walrus.pdf}{options: width=1in}} #' "_PACKAGE"
/scratch/gouwar.j/cran-all/cranData/walrus/R/walrus.R
#' File extension-to-MIME mapping data frame #' #' @docType data #' @export structure(list(extension = c("pyc", "dwg", "ez", "aw", "arj", "atom", "xml", "atomcat", "atomsvc", "mm", "mme", "hqx", "hqx", "boo", "book", "ccxml", "cdf", "cdmia", "cdmic", "cdmid", "cdmio", "cdmiq", "ccad", "dp", "cu", "csm", "davmount", "dbk", "drw", "tsp", "dssc", "xdssc", "dxf", "es", "ecma", "js", "emma", "evy", "epub", "xl", "xla", "xlb", "xlc", "xld", "xlk", "xll", "xlm", "xls", "xlt", "xlv", "xlw", "exi", "pfr", "woff", "fif", "frl", "spl", "gml", "tgz", "gpx", "vew", "gxf", "hlp", "hta", "stk", "unv", "iges", "igs", "inf", "ink", "inkml", "acx", "ipfix", "class", "jar", "class", "ser", "class", "js", "json", "jsonml", "lha", "lostxml", "lzx", "bin", "hqx", "hqx", "cpt", "bin", "mads", "mrc", "mrcx", "ma", "nb", "mb", "mathml", "mbd", "mbox", "mcd", "mscml", "metalink", "meta4", "mets", "aps", "mods", "m21", "mp21", "mp4", "m4p", "mp4s", "mdb", "one", "onetoc2", "onetmp", "onepkg", "pot", "pps", "ppt", "ppz", "doc", "dot", "w6w", "wiz", "word", "wri", "mxf", "mcp", "bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "a", "arc", "arj", "com", "exe", "lha", "lhx", "lzh", "lzx", "o", "psd", "saveme", "uu", "zoo", "class", "buffer", "deploy", "hqx", "obj", "lib", "zip", "gz", "dmg", "iso", "oda", "opf", "ogx", "ogg", "axs", "omdoc", "onetoc", "onetoc2", "onetmp", "onepkg", "oxps", "xer", "pdf", "pgp", "key", "asc", "pgp", "sig", "prf", "p12", "crl", "p10", "p7m", "p7c", "p7s", "p8", "ac", "cer", "crt", "crl", "pkipath", "pki", "text", "pls", "ai", "eps", "ps", "ppt", "part", "prt", "cww", "pskcxml", "rar", "rdf", "rif", "rnc", "rl", "rld", "rng", "rs", "gbr", "mft", "roa", "rsd", "rss", "xml", "rtf", "rtx", "sbml", "scq", "scs", "spq", "spp", "sdp", "sea", "set", "setpay", "setreg", "shf", "stl", "smi", "smil", "smi", "smil", "sol", "sdr", "rq", "srx", "gram", "grxml", "sru", "ssdl", "ssml", "step", "stp", "ssm", "tei", "teicorpus", "tfi", "tsd", "tbk", "vda", "plb", "psb", "pvb", "tcap", "pwn", "aso", "imp", "acu", "atc", "acutc", "air", "fcdt", "fxp", "fxpl", "xdp", "xfdf", "ahead", "azf", "azs", "azw", "acc", "ami", "apk", "cii", "fti", "atx", "mpkg", "m3u8", "swi", "swi", "iota", "aep", "mpm", "bmi", "rep", "cdxml", "mmd", "cdy", "cla", "rp9", "c4g", "c4d", "c4f", "c4p", "c4u", "c11amc", "c11amz", "csp", "cdbcmsg", "cmc", "clkx", "clkk", "clkp", "clkt", "clkw", "wbs", "pml", "ppd", "car", "pcurl", "dart", "rdz", "uvf", "uvvf", "uvd", "uvvd", "uvt", "uvvt", "uvx", "uvvx", "uvz", "uvvz", "fe_launch", "dna", "mlp", "dpg", "dfac", "kpxx", "ait", "svc", "geo", "mag", "nml", "esf", "msf", "qam", "slt", "ssf", "es3", "et3", "ez2", "ez3", "fdf", "mseed", "seed", "dataless", "gph", "ftc", "fm", "frame", "maker", "book", "fnc", "ltf", "fsc", "oas", "oa2", "oa3", "fg5", "bh2", "ddd", "xdw", "xbd", "fzs", "txd", "ggb", "ggt", "gex", "gre", "gxt", "g2w", "g3w", "gmx", "kml", "kmz", "gqf", "gqs", "gac", "ghf", "gim", "grv", "gtm", "tpl", "vcg", "hal", "zmm", "hbci", "les", "hgl", "hpg", "hpgl", "hpid", "hps", "jlt", "pcl", "pclxl", "sfd-hdstx", "x3d", "mpy", "afp", "listafp", "list3820", "irm", "sc", "icc", "icm", "igl", "ivp", "ivu", "igm", "xpw", "xpx", "i2g", "qbo", "qfx", "rcprofile", "irp", "xpr", "fcs", "jam", "rms", "jisp", "joda", "ktz", "ktr", "karbon", "chrt", "kfo", "flw", "kon", "kpr", "kpt", "ksp", "kwd", "kwt", "htke", "kia", "kne", "knp", "skp", "skd", "skt", "skm", "sse", "lasxml", "lbd", "lbe", "123", "apr", "pre", "nsf", "org", "scm", "lwp", "portpkg", "mcd", "mc1", "cdkey", "mwf", "mfm", "flo", "igx", "mif", "daf", "dis", "mbk", "mqy", "msl", "plc", "txf", "mpn", "mpc", "xul", "cil", "cab", "xls", "xlm", "xla", "xlc", "xlt", "xlb", "xll", "xlw", "xlam", "xlam", "xlsb", "xlsb", "xlsm", "xlsm", "xltm", "xltm", "eot", "chm", "ims", "lrm", "thmx", "msg", "sst", "pko", "cat", "stl", "sst", "cat", "stl", "ppt", "pps", "pot", "ppa", "pwz", "ppam", "ppam", "pptm", "potm", "pptm", "potm", "sldm", "sldm", "ppsm", "ppsm", "potm", "potm", "mpp", "mpt", "docm", "docm", "dotm", "dotm", "wps", "wks", "wcm", "wdb", "wpl", "xps", "mseq", "mus", "msty", "taglet", "nlu", "ntf", "nitf", "nnd", "nns", "nnw", "ncm", "ngdat", "n-gage", "rpst", "rpss", "rng", "edm", "edx", "ext", "edm", "edx", "ext", "odc", "otc", "odb", "odf", "odft", "odg", "otg", "odi", "oti", "odp", "otp", "ods", "ots", "odt", "odm", "otm", "ott", "oth", "xo", "dd2", "oxt", "pptx", "sldx", "ppsx", "potx", "xlsx", "xltx", "docx", "dotx", "mgp", "dp", "esa", "pdb", "pqa", "oprc", "paw", "str", "ei6", "efif", "wg", "plf", "pbd", "box", "mgz", "qps", "ptid", "qxd", "qxt", "qwd", "qwt", "qxl", "qxb", "bed", "mxl", "musicxml", "cryptonote", "cod", "rm", "rmvb", "rnx", "link66", "st", "see", "sema", "semd", "semf", "ifm", "itp", "iif", "ipk", "twd", "twds", "mmf", "teacher", "sdkm", "sdkd", "dxp", "sfs", "sdc", "sda", "sdd", "sdp", "smf", "sdw", "vor", "sgl", "smzip", "sm", "sxc", "stc", "sxd", "std", "sxi", "sti", "sxm", "sxw", "sxg", "stw", "sus", "susp", "svd", "sis", "sisx", "xsm", "bdm", "xdm", "tao", "pcap", "cap", "dmp", "tmo", "tpt", "mxs", "tra", "ufd", "ufdl", "utz", "umj", "unityweb", "uoml", "vcx", "vsd", "vst", "vss", "vsw", "vis", "vsf", "sic", "slc", "wbxml", "wmlc", "wmlsc", "wtb", "nbp", "wpd", "wqd", "stf", "xar", "web", "xfdl", "hvd", "hvs", "hvp", "osf", "osfpvg", "saf", "spf", "cmp", "zir", "zirz", "zaz", "vmd", "vmf", "vxml", "wgt", "hlp", "wp", "wp5", "wp6", "wpd", "wp5", "w60", "wp5", "w61", "wsdl", "wspolicy", "wk1", "wk", "7z", "abw", "ace", "aim", "dmg", "aab", "x32", "u32", "vox", "aam", "aas", "bcpio", "bin", "hqx", "torrent", "blb", "blorb", "bsh", "sh", "shar", "elc", "elc", "bz", "bz2", "boz", "cbr", "cba", "cbt", "cbz", "cb7", "cdf", "vcd", "cfs", "chat", "cha", "pgn", "chm", "crx", "ras", "cco", "cpt", "z", "gz", "tgz", "z", "zip", "nsc", "cpio", "cpt", "csh", "deb", "udeb", "deepv", "dgc", "dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa", "dms", "wad", "ncx", "dtb", "res", "dvi", "elc", "env", "evy", "es", "eva", "xla", "xlb", "xlc", "xld", "xlk", "xll", "xlm", "xls", "xlt", "xlv", "xlw", "flac", "pfa", "pfb", "gsf", "pcf", "pcf.Z", "bdf", "gsf", "psf", "otf", "pcf", "snf", "ttf", "ttc", "pfa", "pfb", "pfm", "afm", "woff", "mif", "arc", "pre", "spl", "gca", "ulx", "gnumeric", "sgf", "gramps", "gcf", "gsp", "gss", "gtar", "tgz", "taz", "gz", "gzip", "tgz", "hdf", "help", "hlp", "imap", "phtml", "pht", "php", "phps", "php3", "php3p", "php4", "ica", "ima", "install", "ins", "isp", "ins", "iv", "ip", "iii", "iso", "jar", "class", "jcm", "jnlp", "ser", "class", "js", "chrt", "kil", "skd", "skm", "skp", "skt", "kpr", "kpt", "ksh", "ksp", "kwd", "kwt", "latex", "ltx", "lha", "lsp", "ivy", "wq1", "scm", "luac", "lzh", "lzh", "lha", "lzx", "hqx", "bin", "mc$", "frm", "maker", "frame", "fm", "fb", "book", "fbdoc", "mcd", "mm", "mid", "midi", "mie", "mif", "nix", "prc", "mobi", "m3u8", "asx", "application", "lnk", "wmd", "wmz", "xbap", "mdb", "obd", "crd", "clp", "com", "exe", "bat", "dll", "exe", "dll", "com", "bat", "msi", "xla", "xls", "xlw", "msi", "mvb", "m13", "m14", "wmf", "wmz", "emf", "emz", "mny", "ppt", "pub", "scd", "trm", "wri", "ani", "nvd", "map", "stl", "nc", "cdf", "pkg", "aos", "pac", "nwc", "nzb", "o", "omc", "omcd", "omcr", "oza", "pm4", "pm5", "pcl", "pma", "pmc", "pml", "pmr", "pmw", "plx", "p10", "p12", "pfx", "p7b", "spc", "p7r", "crl", "p7c", "p7m", "p7a", "p7s", "css", "pnm", "mpc", "mpt", "mpv", "mpx", "pyc", "pyo", "wb1", "qtl", "rar", "rpm", "ris", "rpm", "rtf", "sdp", "sea", "sl", "sh", "shar", "sh", "swf", "swfl", "xap", "sit", "spr", "sprite", "sql", "sit", "sitx", "srt", "sv4cpio", "sv4crc", "t3", "gam", "tar", "sbk", "tbk", "tcl", "tex", "gf", "pk", "tfm", "texinfo", "texi", "obj", "~", "%", "bak", "old", "sik", "roff", "t", "tr", "man", "me", "ms", "avi", "ustar", "vsd", "vst", "vsw", "mzz", "xpix", "vrml", "src", "wsrc", "webapp", "wz", "hlp", "wtk", "svr", "wrl", "wpd", "wri", "der", "cer", "crt", "crt", "xcf", "fig", "xlf", "xpi", "xz", "zip", "z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8", "xaml", "xdf", "xenc", "xhtml", "xht", "xml", "xsl", "xpdl", "dtd", "xop", "xpl", "xslt", "xspf", "mxml", "xhvml", "xvml", "xvm", "yang", "yin", "pko", "zip", "adp", "aif", "aifc", "aiff", "au", "snd", "flac", "it", "funk", "my", "pfunk", "pfunk", "rmi", "mid", "mid", "midi", "kar", "rmi", "mod", "mp4a", "m4a", "mpga", "mp2", "mp2a", "mp3", "m2a", "mpa", "mpg", "m3a", "mpega", "m4a", "mp3", "m3u", "la", "lma", "oga", "ogg", "spx", "sid", "s3m", "sil", "tsi", "tsp", "uva", "uvva", "eol", "dra", "dts", "dtshd", "lvp", "pya", "ecelp4800", "ecelp7470", "ecelp9600", "qcp", "rip", "voc", "vox", "wav", "weba", "aac", "snd", "aif", "aiff", "aifc", "au", "caf", "flac", "gsd", "gsm", "jam", "lam", "mka", "mid", "midi", "mid", "midi", "mod", "mp2", "mp3", "m3u", "m3u", "wax", "wma", "la", "lma", "ram", "ra", "rm", "rmm", "rmp", "rmp", "ra", "rpm", "sid", "ra", "pls", "sd2", "vqf", "vqe", "vql", "mjf", "voc", "wav", "xm", "cdx", "cif", "cmdf", "cml", "csml", "pdb", "xyz", "xyz", "dwf", "dwf", "otf", "ivr", "bmp", "bm", "cgm", "cod", "ras", "rast", "fif", "flo", "turbot", "g3", "gif", "ief", "iefs", "jpeg", "jpg", "jfif", "jfif-tbnl", "jpe", "jut", "ktx", "nap", "naplps", "pcx", "pic", "pict", "jfif", "jfif", "jpe", "jpeg", "jpg", "png", "x-png", "btif", "sgi", "svg", "svgz", "tiff", "tif", "mcf", "psd", "uvi", "uvvi", "uvg", "uvvg", "djvu", "djv", "sub", "dwg", "dxf", "svf", "dxf", "fbs", "fpx", "fpix", "fst", "mmr", "rlc", "mdi", "wdp", "npx", "fpx", "rf", "rp", "wbmp", "xif", "webp", "3ds", "ras", "ras", "cmx", "cdr", "pat", "cdt", "cpt", "dwg", "dxf", "svf", "fh", "fhc", "fh4", "fh5", "fh7", "ico", "art", "jng", "jps", "sid", "bmp", "nif", "niff", "pcx", "psd", "pic", "pct", "pnm", "pbm", "pgm", "pgm", "ppm", "qif", "qti", "qtif", "rgb", "tga", "tif", "tiff", "bmp", "xbm", "xpm", "xbm", "xpm", "pm", "xwd", "xwd", "xbm", "xpm", "eml", "mht", "mhtml", "mime", "nws", "igs", "iges", "msh", "mesh", "silo", "dae", "dwf", "gdl", "gtw", "mts", "vtu", "wrl", "vrml", "wrz", "pov", "x3db", "x3dbz", "x3dv", "x3dvz", "x3d", "x3dz", "gzip", "ustar", "zip", "mid", "midi", "kar", "pvu", "asp", "appcache", "manifest", "ics", "ifb", "icz", "csv", "css", "csv", "js", "event-stream", "323", "html", "acgi", "htm", "htmls", "htx", "shtml", "stm", "uls", "js", "mml", "mcf", "n3", "pas", "txt", "text", "conf", "def", "list", "log", "c", "c++", "cc", "com", "cxx", "f", "f90", "for", "g", "h", "hh", "idc", "jav", "java", "lst", "m", "mar", "pl", "sdml", "bas", "in", "asc", "diff", "pot", "el", "ksh", "par", "dsc", "rtx", "rt", "rtf", "rtf", "wsc", "sct", "wsc", "sgml", "sgm", "tsv", "tm", "ts", "t", "tr", "roff", "man", "me", "ms", "ttl", "uri", "uris", "uni", "unis", "urls", "vcard", "abc", "curl", "dcurl", "mcurl", "scurl", "sub", "fly", "flx", "gv", "3dml", "spot", "rt", "jad", "si", "sl", "wml", "wmls", "vtt", "htt", "s", "asm", "aip", "c", "cc", "cxx", "cpp", "h", "hh", "dic", "h++", "hpp", "hxx", "hh", "c++", "cpp", "cxx", "cc", "h", "htc", "csh", "c", "f", "for", "f77", "f90", "h", "hh", "java", "java", "jav", "lsx", "lua", "m", "markdown", "md", "mkd", "moc", "nfo", "opml", "p", "pas", "gcd", "pl", "pm", "py", "hlb", "csh", "el", "scm", "ksh", "lsp", "pl", "pm", "py", "rexx", "scm", "sh", "tcl", "tcsh", "zsh", "shtml", "ssi", "etx", "sfv", "sgm", "sgml", "sh", "spc", "talk", "tcl", "tk", "tex", "ltx", "sty", "cls", "uil", "uu", "uue", "vcs", "vcf", "xml", "3gp", "3g2", "ts", "afl", "avi", "avs", "dl", "flc", "fli", "flc", "fli", "gl", "h261", "h263", "h264", "jpgv", "jpm", "jpgm", "mj2", "mjp2", "mp4", "mp4v", "mpg4", "mpeg", "mpg", "mpe", "m1v", "m2v", "mp2", "mp3", "mpa", "mpv2", "avi", "ogv", "qt", "moov", "mov", "vdo", "viv", "vivo", "uvh", "uvvh", "uvm", "uvvm", "uvp", "uvvp", "uvs", "uvvs", "uvv", "uvvv", "dvb", "fvt", "mxu", "m4u", "pyv", "rv", "uvu", "uvvu", "viv", "vivo", "vos", "webm", "xdr", "xsr", "fmf", "dl", "dif", "dv", "f4v", "fli", "flv", "gl", "isu", "lsf", "lsx", "m4v", "mkv", "mk3d", "mks", "mng", "mjpg", "mp2", "mp3", "mp2", "asf", "asx", "asr", "asx", "vob", "wm", "wmv", "wmx", "wvx", "avi", "qtc", "scm", "movie", "mv", "smv", "wmf", "mime", "ice", "mid", "midi", "3dm", "3dmf", "qd3", "qd3d", "svr", "vrml", "wrl", "wrz", "flr", "xaf", "xof", "vrm", "vrt", "xgz", "xmz", "ma nb mb", "doc dot", "bin dms lha lrf lzh so iso dmg dist distz pkg bpk dump elc deploy", "onetoc onetoc2 onetmp onepkg", "asc sig", "p7m p7c", "ai eps ps", "smi smil", "atc acutc", "c4g c4d c4f c4p c4u", "es3 et3", "seed dataless", "fm frame maker book", "gex gre", "gqf gqs", "afp listafp list3820", "icc icm", "xpw xpx", "ktz ktr", "kpr kpt", "kwd kwt", "kne knp", "skp skd skt skm", "xls xlm xla xlc xlt xlw", "ppt pps pot", "mpp mpt", "wps wks wcm wdb", "pdb pqa oprc", "qxd qxt qwd qwt qxl qxb", "twd twds", "sdkm sdkd", "sus susp", "sis sisx", "ufd ufdl", "vsd vst vss vsw", "zir zirz", "aab x32 u32 vox", "bz2 boz", "deb udeb", "dir dcr dxr cst cct cxt w3d fgd swa", "ttf ttc", "pfa pfb pfm afm", "prc mobi", "exe dll com bat msi", "mvb m13 m14", "nc cdf", "p12 pfx", "p7b spc", "texinfo texi", "der crt", "xhtml xht", "xml xsl", "mxml xhvml xvml xvm", "au snd", "mid midi kar rmi", "mpga mp2 mp2a mp3 m2a m3a", "oga ogg spx", "aif aiff aifc", "ram ra", "jpeg jpg jpe", "svg svgz", "tiff tif", "djvu djv", "fh fhc fh4 fh5 fh7", "pic pct", "eml mime", "igs iges", "msh mesh silo", "wrl vrml", "ics ifb", "html htm", "txt text conf def list log in", "sgml sgm", "t tr roff man me ms", "uri uris urls", "s asm", "c cc cxx cpp h hh dic", "f for f77 f90", "p pas", "jpm jpgm", "mj2 mjp2", "mp4 mp4v mpg4", "mpeg mpg mpe m1v m2v", "qt mov", "mxu m4u", "asf asx"), mime_type = c("application/x-bytecode.python", "application/acad", "application/andrew-inset", "application/applixware", "application/arj", "application/atom+xml", "application/atom+xml", "application/atomcat+xml", "application/atomsvc+xml", "application/base64", "application/base64", "application/binhex", "application/binhex4", "application/book", "application/book", "application/ccxml+xml", "application/cdf", "application/cdmi-capability", "application/cdmi-container", "application/cdmi-domain", "application/cdmi-object", "application/cdmi-queue", "application/clariscad", "application/commonground", "application/cu-seeme", "application/cu-seeme", "application/davmount+xml", "application/docbook+xml", "application/drafting", "application/dsptype", "application/dssc+der", "application/dssc+xml", "application/dxf", "application/ecmascript", "application/ecmascript", "application/ecmascript", "application/emma+xml", "application/envoy", "application/epub+zip", "application/excel", "application/excel", "application/excel", "application/excel", "application/excel", "application/excel", "application/excel", "application/excel", "application/excel", "application/excel", "application/excel", "application/excel", "application/exi", "application/font-tdpfr", "application/font-woff", "application/fractals", "application/freeloader", "application/futuresplash", "application/gml+xml", "application/gnutar", "application/gpx+xml", "application/groupwise", "application/gxf", "application/hlp", "application/hta", "application/hyperstudio", "application/i-deas", "application/iges", "application/iges", "application/inf", "application/inkml+xml", "application/inkml+xml", "application/internet-property-stream", "application/ipfix", "application/java", "application/java-archive", "application/java-byte-code", "application/java-serialized-object", "application/java-vm", "application/javascript", "application/json", "application/jsonml+json", "application/lha", "application/lost+xml", "application/lzx", "application/mac-binary", "application/mac-binhex", "application/mac-binhex40", "application/mac-compactpro", "application/macbinary", "application/mads+xml", "application/marc", "application/marcxml+xml", "application/mathematica", "application/mathematica", "application/mathematica", "application/mathml+xml", "application/mbedlet", "application/mbox", "application/mcad", "application/mediaservercontrol+xml", "application/metalink+xml", "application/metalink4+xml", "application/mets+xml", "application/mime", "application/mods+xml", "application/mp21", "application/mp21", "application/mp4", "application/mp4", "application/mp4", "application/msaccess", "application/msonenote", "application/msonenote", "application/msonenote", "application/msonenote", "application/mspowerpoint", "application/mspowerpoint", "application/mspowerpoint", "application/mspowerpoint", "application/msword", "application/msword", "application/msword", "application/msword", "application/msword", "application/mswrite", "application/mxf", "application/netmc", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/octet-stream", "application/oda", "application/oebps-package+xml", "application/ogg", "application/ogg", "application/olescript", "application/omdoc+xml", "application/onenote", "application/onenote", "application/onenote", "application/onenote", "application/oxps", "application/patch-ops-error+xml", "application/pdf", "application/pgp-encrypted", "application/pgp-keys", "application/pgp-signature", "application/pgp-signature", "application/pgp-signature", "application/pics-rules", "application/pkcs-12", "application/pkcs-crl", "application/pkcs10", "application/pkcs7-mime", "application/pkcs7-mime", "application/pkcs7-signature", "application/pkcs8", "application/pkix-attr-cert", "application/pkix-cert", "application/pkix-cert", "application/pkix-crl", "application/pkix-pkipath", "application/pkixcmp", "application/plain", "application/pls+xml", "application/postscript", "application/postscript", "application/postscript", "application/powerpoint", "application/pro_eng", "application/pro_eng", "application/prs.cww", "application/pskc+xml", "application/rar", "application/rdf+xml", "application/reginfo+xml", "application/relax-ng-compact-syntax", "application/resource-lists+xml", "application/resource-lists-diff+xml", "application/ringing-tones", "application/rls-services+xml", "application/rpki-ghostbusters", "application/rpki-manifest", "application/rpki-roa", "application/rsd+xml", "application/rss+xml", "application/rss+xml", "application/rtf", "application/rtf", "application/sbml+xml", "application/scvp-cv-request", "application/scvp-cv-response", "application/scvp-vp-request", "application/scvp-vp-response", "application/sdp", "application/sea", "application/set", "application/set-payment-initiation", "application/set-registration-initiation", "application/shf+xml", "application/sla", "application/smil", "application/smil", "application/smil+xml", "application/smil+xml", "application/solids", "application/sounder", "application/sparql-query", "application/sparql-results+xml", "application/srgs", "application/srgs+xml", "application/sru+xml", "application/ssdl+xml", "application/ssml+xml", "application/step", "application/step", "application/streamingmedia", "application/tei+xml", "application/tei+xml", "application/thraud+xml", "application/timestamped-data", "application/toolbook", "application/vda", "application/vnd.3gpp.pic-bw-large", "application/vnd.3gpp.pic-bw-small", "application/vnd.3gpp.pic-bw-var", "application/vnd.3gpp2.tcap", "application/vnd.3m.post-it-notes", "application/vnd.accpac.simply.aso", "application/vnd.accpac.simply.imp", "application/vnd.acucobol", "application/vnd.acucorp", "application/vnd.acucorp", "application/vnd.adobe.air-application-installer-package+zip", "application/vnd.adobe.formscentral.fcdt", "application/vnd.adobe.fxp", "application/vnd.adobe.fxp", "application/vnd.adobe.xdp+xml", "application/vnd.adobe.xfdf", "application/vnd.ahead.space", "application/vnd.airzip.filesecure.azf", "application/vnd.airzip.filesecure.azs", "application/vnd.amazon.ebook", "application/vnd.americandynamics.acc", "application/vnd.amiga.ami", "application/vnd.android.package-archive", "application/vnd.anser-web-certificate-issue-initiation", "application/vnd.anser-web-funds-transfer-initiation", "application/vnd.antix.game-component", "application/vnd.apple.installer+xml", "application/vnd.apple.mpegurl", "application/vnd.arastra.swi", "application/vnd.aristanetworks.swi", "application/vnd.astraea-software.iota", "application/vnd.audiograph", "application/vnd.blueice.multipass", "application/vnd.bmi", "application/vnd.businessobjects", "application/vnd.chemdraw+xml", "application/vnd.chipnuts.karaoke-mmd", "application/vnd.cinderella", "application/vnd.claymore", "application/vnd.cloanto.rp9", "application/vnd.clonk.c4group", "application/vnd.clonk.c4group", "application/vnd.clonk.c4group", "application/vnd.clonk.c4group", "application/vnd.clonk.c4group", "application/vnd.cluetrust.cartomobile-config", "application/vnd.cluetrust.cartomobile-config-pkg", "application/vnd.commonspace", "application/vnd.contact.cmsg", "application/vnd.cosmocaller", "application/vnd.crick.clicker", "application/vnd.crick.clicker.keyboard", "application/vnd.crick.clicker.palette", "application/vnd.crick.clicker.template", "application/vnd.crick.clicker.wordbank", "application/vnd.criticaltools.wbs+xml", "application/vnd.ctc-posml", "application/vnd.cups-ppd", "application/vnd.curl.car", "application/vnd.curl.pcurl", "application/vnd.dart", "application/vnd.data-vision.rdz", "application/vnd.dece.data", "application/vnd.dece.data", "application/vnd.dece.data", "application/vnd.dece.data", "application/vnd.dece.ttml+xml", "application/vnd.dece.ttml+xml", "application/vnd.dece.unspecified", "application/vnd.dece.unspecified", "application/vnd.dece.zip", "application/vnd.dece.zip", "application/vnd.denovo.fcselayout-link", "application/vnd.dna", "application/vnd.dolby.mlp", "application/vnd.dpgraph", "application/vnd.dreamfactory", "application/vnd.ds-keypoint", "application/vnd.dvb.ait", "application/vnd.dvb.service", "application/vnd.dynageo", "application/vnd.ecowin.chart", "application/vnd.enliven", "application/vnd.epson.esf", "application/vnd.epson.msf", "application/vnd.epson.quickanime", "application/vnd.epson.salt", "application/vnd.epson.ssf", "application/vnd.eszigno3+xml", "application/vnd.eszigno3+xml", "application/vnd.ezpix-album", "application/vnd.ezpix-package", "application/vnd.fdf", "application/vnd.fdsn.mseed", "application/vnd.fdsn.seed", "application/vnd.fdsn.seed", "application/vnd.flographit", "application/vnd.fluxtime.clip", "application/vnd.framemaker", "application/vnd.framemaker", "application/vnd.framemaker", "application/vnd.framemaker", "application/vnd.frogans.fnc", "application/vnd.frogans.ltf", "application/vnd.fsc.weblaunch", "application/vnd.fujitsu.oasys", "application/vnd.fujitsu.oasys2", "application/vnd.fujitsu.oasys3", "application/vnd.fujitsu.oasysgp", "application/vnd.fujitsu.oasysprs", "application/vnd.fujixerox.ddd", "application/vnd.fujixerox.docuworks", "application/vnd.fujixerox.docuworks.binder", "application/vnd.fuzzysheet", "application/vnd.genomatix.tuxedo", "application/vnd.geogebra.file", "application/vnd.geogebra.tool", "application/vnd.geometry-explorer", "application/vnd.geometry-explorer", "application/vnd.geonext", "application/vnd.geoplan", "application/vnd.geospace", "application/vnd.gmx", "application/vnd.google-earth.kml+xml", "application/vnd.google-earth.kmz", "application/vnd.grafeq", "application/vnd.grafeq", "application/vnd.groove-account", "application/vnd.groove-help", "application/vnd.groove-identity-message", "application/vnd.groove-injector", "application/vnd.groove-tool-message", "application/vnd.groove-tool-template", "application/vnd.groove-vcard", "application/vnd.hal+xml", "application/vnd.handheld-entertainment+xml", "application/vnd.hbci", "application/vnd.hhe.lesson-player", "application/vnd.hp-hpgl", "application/vnd.hp-hpgl", "application/vnd.hp-hpgl", "application/vnd.hp-hpid", "application/vnd.hp-hps", "application/vnd.hp-jlyt", "application/vnd.hp-pcl", "application/vnd.hp-pclxl", "application/vnd.hydrostatix.sof-data", "application/vnd.hzn-3d-crossword", "application/vnd.ibm.minipay", "application/vnd.ibm.modcap", "application/vnd.ibm.modcap", "application/vnd.ibm.modcap", "application/vnd.ibm.rights-management", "application/vnd.ibm.secure-container", "application/vnd.iccprofile", "application/vnd.iccprofile", "application/vnd.igloader", "application/vnd.immervision-ivp", "application/vnd.immervision-ivu", "application/vnd.insors.igm", "application/vnd.intercon.formnet", "application/vnd.intercon.formnet", "application/vnd.intergeo", "application/vnd.intu.qbo", "application/vnd.intu.qfx", "application/vnd.ipunplugged.rcprofile", "application/vnd.irepository.package+xml", "application/vnd.is-xpr", "application/vnd.isac.fcs", "application/vnd.jam", "application/vnd.jcp.javame.midlet-rms", "application/vnd.jisp", "application/vnd.joost.joda-archive", "application/vnd.kahootz", "application/vnd.kahootz", "application/vnd.kde.karbon", "application/vnd.kde.kchart", "application/vnd.kde.kformula", "application/vnd.kde.kivio", "application/vnd.kde.kontour", "application/vnd.kde.kpresenter", "application/vnd.kde.kpresenter", "application/vnd.kde.kspread", "application/vnd.kde.kword", "application/vnd.kde.kword", "application/vnd.kenameaapp", "application/vnd.kidspiration", "application/vnd.kinar", "application/vnd.kinar", "application/vnd.koan", "application/vnd.koan", "application/vnd.koan", "application/vnd.koan", "application/vnd.kodak-descriptor", "application/vnd.las.las+xml", "application/vnd.llamagraphics.life-balance.desktop", "application/vnd.llamagraphics.life-balance.exchange+xml", "application/vnd.lotus-1-2-3", "application/vnd.lotus-approach", "application/vnd.lotus-freelance", "application/vnd.lotus-notes", "application/vnd.lotus-organizer", "application/vnd.lotus-screencam", "application/vnd.lotus-wordpro", "application/vnd.macports.portpkg", "application/vnd.mcd", "application/vnd.medcalcdata", "application/vnd.mediastation.cdkey", "application/vnd.mfer", "application/vnd.mfmp", "application/vnd.micrografx.flo", "application/vnd.micrografx.igx", "application/vnd.mif", "application/vnd.mobius.daf", "application/vnd.mobius.dis", "application/vnd.mobius.mbk", "application/vnd.mobius.mqy", "application/vnd.mobius.msl", "application/vnd.mobius.plc", "application/vnd.mobius.txf", "application/vnd.mophun.application", "application/vnd.mophun.certificate", "application/vnd.mozilla.xul+xml", "application/vnd.ms-artgalry", "application/vnd.ms-cab-compressed", "application/vnd.ms-excel", "application/vnd.ms-excel", "application/vnd.ms-excel", "application/vnd.ms-excel", "application/vnd.ms-excel", "application/vnd.ms-excel", "application/vnd.ms-excel", "application/vnd.ms-excel", "application/vnd.ms-excel.addin.macroEnabled.12", "application/vnd.ms-excel.addin.macroenabled.12", "application/vnd.ms-excel.sheet.binary.macroEnabled.12", "application/vnd.ms-excel.sheet.binary.macroenabled.12", "application/vnd.ms-excel.sheet.macroEnabled.12", "application/vnd.ms-excel.sheet.macroenabled.12", "application/vnd.ms-excel.template.macroEnabled.12", "application/vnd.ms-excel.template.macroenabled.12", "application/vnd.ms-fontobject", "application/vnd.ms-htmlhelp", "application/vnd.ms-ims", "application/vnd.ms-lrm", "application/vnd.ms-officetheme", "application/vnd.ms-outlook", "application/vnd.ms-pki.certstore", "application/vnd.ms-pki.pko", "application/vnd.ms-pki.seccat", "application/vnd.ms-pki.stl", "application/vnd.ms-pkicertstore", "application/vnd.ms-pkiseccat", "application/vnd.ms-pkistl", "application/vnd.ms-powerpoint", "application/vnd.ms-powerpoint", "application/vnd.ms-powerpoint", "application/vnd.ms-powerpoint", "application/vnd.ms-powerpoint", "application/vnd.ms-powerpoint.addin.macroEnabled.12", "application/vnd.ms-powerpoint.addin.macroenabled.12", "application/vnd.ms-powerpoint.presentation.macroEnabled.12", "application/vnd.ms-powerpoint.presentation.macroEnabled.12", "application/vnd.ms-powerpoint.presentation.macroenabled.12", "application/vnd.ms-powerpoint.presentation.macroenabled.12", "application/vnd.ms-powerpoint.slide.macroEnabled.12", "application/vnd.ms-powerpoint.slide.macroenabled.12", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12", "application/vnd.ms-powerpoint.slideshow.macroenabled.12", "application/vnd.ms-powerpoint.template.macroEnabled.12", "application/vnd.ms-powerpoint.template.macroenabled.12", "application/vnd.ms-project", "application/vnd.ms-project", "application/vnd.ms-word.document.macroEnabled.12", "application/vnd.ms-word.document.macroenabled.12", "application/vnd.ms-word.template.macroEnabled.12", "application/vnd.ms-word.template.macroenabled.12", "application/vnd.ms-works", "application/vnd.ms-works", "application/vnd.ms-works", "application/vnd.ms-works", "application/vnd.ms-wpl", "application/vnd.ms-xpsdocument", "application/vnd.mseq", "application/vnd.musician", "application/vnd.muvee.style", "application/vnd.mynfc", "application/vnd.neurolanguage.nlu", "application/vnd.nitf", "application/vnd.nitf", "application/vnd.noblenet-directory", "application/vnd.noblenet-sealer", "application/vnd.noblenet-web", "application/vnd.nokia.configuration-message", "application/vnd.nokia.n-gage.data", "application/vnd.nokia.n-gage.symbian.install", "application/vnd.nokia.radio-preset", "application/vnd.nokia.radio-presets", "application/vnd.nokia.ringing-tone", "application/vnd.novadigm.EDM", "application/vnd.novadigm.EDX", "application/vnd.novadigm.EXT", "application/vnd.novadigm.edm", "application/vnd.novadigm.edx", "application/vnd.novadigm.ext", "application/vnd.oasis.opendocument.chart", "application/vnd.oasis.opendocument.chart-template", "application/vnd.oasis.opendocument.database", "application/vnd.oasis.opendocument.formula", "application/vnd.oasis.opendocument.formula-template", "application/vnd.oasis.opendocument.graphics", "application/vnd.oasis.opendocument.graphics-template", "application/vnd.oasis.opendocument.image", "application/vnd.oasis.opendocument.image-template", "application/vnd.oasis.opendocument.presentation", "application/vnd.oasis.opendocument.presentation-template", "application/vnd.oasis.opendocument.spreadsheet", "application/vnd.oasis.opendocument.spreadsheet-template", "application/vnd.oasis.opendocument.text", "application/vnd.oasis.opendocument.text-master", "application/vnd.oasis.opendocument.text-master", "application/vnd.oasis.opendocument.text-template", "application/vnd.oasis.opendocument.text-web", "application/vnd.olpc-sugar", "application/vnd.oma.dd2+xml", "application/vnd.openofficeorg.extension", "application/vnd.openxmlformats-officedocument.presentationml.presentation", "application/vnd.openxmlformats-officedocument.presentationml.slide", "application/vnd.openxmlformats-officedocument.presentationml.slideshow", "application/vnd.openxmlformats-officedocument.presentationml.template", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.openxmlformats-officedocument.spreadsheetml.template", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "application/vnd.openxmlformats-officedocument.wordprocessingml.template", "application/vnd.osgeo.mapguide.package", "application/vnd.osgi.dp", "application/vnd.osgi.subsystem", "application/vnd.palm", "application/vnd.palm", "application/vnd.palm", "application/vnd.pawaafile", "application/vnd.pg.format", "application/vnd.pg.osasli", "application/vnd.picsel", "application/vnd.pmi.widget", "application/vnd.pocketlearn", "application/vnd.powerbuilder6", "application/vnd.previewsystems.box", "application/vnd.proteus.magazine", "application/vnd.publishare-delta-tree", "application/vnd.pvi.ptid1", "application/vnd.quark.quarkxpress", "application/vnd.quark.quarkxpress", "application/vnd.quark.quarkxpress", "application/vnd.quark.quarkxpress", "application/vnd.quark.quarkxpress", "application/vnd.quark.quarkxpress", "application/vnd.realvnc.bed", "application/vnd.recordare.musicxml", "application/vnd.recordare.musicxml+xml", "application/vnd.rig.cryptonote", "application/vnd.rim.cod", "application/vnd.rn-realmedia", "application/vnd.rn-realmedia-vbr", "application/vnd.rn-realplayer", "application/vnd.route66.link66+xml", "application/vnd.sailingtracker.track", "application/vnd.seemail", "application/vnd.sema", "application/vnd.semd", "application/vnd.semf", "application/vnd.shana.informed.formdata", "application/vnd.shana.informed.formtemplate", "application/vnd.shana.informed.interchange", "application/vnd.shana.informed.package", "application/vnd.simtech-mindmapper", "application/vnd.simtech-mindmapper", "application/vnd.smaf", "application/vnd.smart.teacher", "application/vnd.solent.sdkm+xml", "application/vnd.solent.sdkm+xml", "application/vnd.spotfire.dxp", "application/vnd.spotfire.sfs", "application/vnd.stardivision.calc", "application/vnd.stardivision.draw", "application/vnd.stardivision.impress", "application/vnd.stardivision.impress", "application/vnd.stardivision.math", "application/vnd.stardivision.writer", "application/vnd.stardivision.writer", "application/vnd.stardivision.writer-global", "application/vnd.stepmania.package", "application/vnd.stepmania.stepchart", "application/vnd.sun.xml.calc", "application/vnd.sun.xml.calc.template", "application/vnd.sun.xml.draw", "application/vnd.sun.xml.draw.template", "application/vnd.sun.xml.impress", "application/vnd.sun.xml.impress.template", "application/vnd.sun.xml.math", "application/vnd.sun.xml.writer", "application/vnd.sun.xml.writer.global", "application/vnd.sun.xml.writer.template", "application/vnd.sus-calendar", "application/vnd.sus-calendar", "application/vnd.svd", "application/vnd.symbian.install", "application/vnd.symbian.install", "application/vnd.syncml+xml", "application/vnd.syncml.dm+wbxml", "application/vnd.syncml.dm+xml", "application/vnd.tao.intent-module-archive", "application/vnd.tcpdump.pcap", "application/vnd.tcpdump.pcap", "application/vnd.tcpdump.pcap", "application/vnd.tmobile-livetv", "application/vnd.trid.tpt", "application/vnd.triscape.mxs", "application/vnd.trueapp", "application/vnd.ufdl", "application/vnd.ufdl", "application/vnd.uiq.theme", "application/vnd.umajin", "application/vnd.unity", "application/vnd.uoml+xml", "application/vnd.vcx", "application/vnd.visio", "application/vnd.visio", "application/vnd.visio", "application/vnd.visio", "application/vnd.visionary", "application/vnd.vsf", "application/vnd.wap.sic", "application/vnd.wap.slc", "application/vnd.wap.wbxml", "application/vnd.wap.wmlc", "application/vnd.wap.wmlscriptc", "application/vnd.webturbo", "application/vnd.wolfram.player", "application/vnd.wordperfect", "application/vnd.wqd", "application/vnd.wt.stf", "application/vnd.xara", "application/vnd.xara", "application/vnd.xfdl", "application/vnd.yamaha.hv-dic", "application/vnd.yamaha.hv-script", "application/vnd.yamaha.hv-voice", "application/vnd.yamaha.openscoreformat", "application/vnd.yamaha.openscoreformat.osfpvg+xml", "application/vnd.yamaha.smaf-audio", "application/vnd.yamaha.smaf-phrase", "application/vnd.yellowriver-custom-menu", "application/vnd.zul", "application/vnd.zul", "application/vnd.zzazz.deck+xml", "application/vocaltec-media-desc", "application/vocaltec-media-file", "application/voicexml+xml", "application/widget", "application/winhlp", "application/wordperfect", "application/wordperfect", "application/wordperfect", "application/wordperfect", "application/wordperfect5.1", "application/wordperfect6.0", "application/wordperfect6.0", "application/wordperfect6.1", "application/wsdl+xml", "application/wspolicy+xml", "application/x-123", "application/x-123", "application/x-7z-compressed", "application/x-abiword", "application/x-ace-compressed", "application/x-aim", "application/x-apple-diskimage", "application/x-authorware-bin", "application/x-authorware-bin", "application/x-authorware-bin", "application/x-authorware-bin", "application/x-authorware-map", "application/x-authorware-seg", "application/x-bcpio", "application/x-binary", "application/x-binhex40", "application/x-bittorrent", "application/x-blorb", "application/x-blorb", "application/x-bsh", "application/x-bsh", "application/x-bsh", "application/x-bytecode.elisp", "application/x-bytecode.elisp(compiledelisp)", "application/x-bzip", "application/x-bzip2", "application/x-bzip2", "application/x-cbr", "application/x-cbr", "application/x-cbr", "application/x-cbr", "application/x-cbr", "application/x-cdf", "application/x-cdlink", "application/x-cfs-compressed", "application/x-chat", "application/x-chat", "application/x-chess-pgn", "application/x-chm", "application/x-chrome-extension", "application/x-cmu-raster", "application/x-cocoa", "application/x-compactpro", "application/x-compress", "application/x-compressed", "application/x-compressed", "application/x-compressed", "application/x-compressed", "application/x-conference", "application/x-cpio", "application/x-cpt", "application/x-csh", "application/x-debian-package", "application/x-debian-package", "application/x-deepv", "application/x-dgc-compressed", "application/x-director", "application/x-director", "application/x-director", "application/x-director", "application/x-director", "application/x-director", "application/x-director", "application/x-director", "application/x-director", "application/x-dms", "application/x-doom", "application/x-dtbncx+xml", "application/x-dtbook+xml", "application/x-dtbresource+xml", "application/x-dvi", "application/x-elc", "application/x-envoy", "application/x-envoy", "application/x-esrehber", "application/x-eva", "application/x-excel", "application/x-excel", "application/x-excel", "application/x-excel", "application/x-excel", "application/x-excel", "application/x-excel", "application/x-excel", "application/x-excel", "application/x-excel", "application/x-excel", "application/x-flac", "application/x-font", "application/x-font", "application/x-font", "application/x-font", "application/x-font", "application/x-font-bdf", "application/x-font-ghostscript", "application/x-font-linux-psf", "application/x-font-otf", "application/x-font-pcf", "application/x-font-snf", "application/x-font-ttf", "application/x-font-ttf", "application/x-font-type1", "application/x-font-type1", "application/x-font-type1", "application/x-font-type1", "application/x-font-woff", "application/x-frame", "application/x-freearc", "application/x-freelance", "application/x-futuresplash", "application/x-gca-compressed", "application/x-glulx", "application/x-gnumeric", "application/x-go-sgf", "application/x-gramps-xml", "application/x-graphing-calculator", "application/x-gsp", "application/x-gss", "application/x-gtar", "application/x-gtar", "application/x-gtar", "application/x-gzip", "application/x-gzip", "application/x-gzip", "application/x-hdf", "application/x-helpfile", "application/x-helpfile", "application/x-httpd-imap", "application/x-httpd-php", "application/x-httpd-php", "application/x-httpd-php", "application/x-httpd-php-source", "application/x-httpd-php3", "application/x-httpd-php3-preprocessed", "application/x-httpd-php4", "application/x-ica", "application/x-ima", "application/x-install-instructions", "application/x-internet-signup", "application/x-internet-signup", "application/x-internett-signup", "application/x-inventor", "application/x-ip2", "application/x-iphone", "application/x-iso9660-image", "application/x-java-archive", "application/x-java-class", "application/x-java-commerce", "application/x-java-jnlp-file", "application/x-java-serialized-object", "application/x-java-vm", "application/x-javascript", "application/x-kchart", "application/x-killustrator", "application/x-koan", "application/x-koan", "application/x-koan", "application/x-koan", "application/x-kpresenter", "application/x-kpresenter", "application/x-ksh", "application/x-kspread", "application/x-kword", "application/x-kword", "application/x-latex", "application/x-latex", "application/x-lha", "application/x-lisp", "application/x-livescreen", "application/x-lotus", "application/x-lotusscreencam", "application/x-lua-bytecode", "application/x-lzh", "application/x-lzh-compressed", "application/x-lzh-compressed", "application/x-lzx", "application/x-mac-binhex40", "application/x-macbinary", "application/x-magic-cap-package-1.0", "application/x-maker", "application/x-maker", "application/x-maker", "application/x-maker", "application/x-maker", "application/x-maker", "application/x-maker", "application/x-mathcad", "application/x-meme", "application/x-midi", "application/x-midi", "application/x-mie", "application/x-mif", "application/x-mix-transfer", "application/x-mobipocket-ebook", "application/x-mobipocket-ebook", "application/x-mpegURL", "application/x-mplayer2", "application/x-ms-application", "application/x-ms-shortcut", "application/x-ms-wmd", "application/x-ms-wmz", "application/x-ms-xbap", "application/x-msaccess", "application/x-msbinder", "application/x-mscardfile", "application/x-msclip", "application/x-msdos-program", "application/x-msdos-program", "application/x-msdos-program", "application/x-msdos-program", "application/x-msdownload", "application/x-msdownload", "application/x-msdownload", "application/x-msdownload", "application/x-msdownload", "application/x-msexcel", "application/x-msexcel", "application/x-msexcel", "application/x-msi", "application/x-msmediaview", "application/x-msmediaview", "application/x-msmediaview", "application/x-msmetafile", "application/x-msmetafile", "application/x-msmetafile", "application/x-msmetafile", "application/x-msmoney", "application/x-mspowerpoint", "application/x-mspublisher", "application/x-msschedule", "application/x-msterminal", "application/x-mswrite", "application/x-navi-animation", "application/x-navidoc", "application/x-navimap", "application/x-navistyle", "application/x-netcdf", "application/x-netcdf", "application/x-newton-compatible-pkg", "application/x-nokia-9000-communicator-add-on-software", "application/x-ns-proxy-autoconfig", "application/x-nwc", "application/x-nzb", "application/x-object", "application/x-omc", "application/x-omcdatamaker", "application/x-omcregerator", "application/x-oz-application", "application/x-pagemaker", "application/x-pagemaker", "application/x-pcl", "application/x-perfmon", "application/x-perfmon", "application/x-perfmon", "application/x-perfmon", "application/x-perfmon", "application/x-pixclscript", "application/x-pkcs10", "application/x-pkcs12", "application/x-pkcs12", "application/x-pkcs7-certificates", "application/x-pkcs7-certificates", "application/x-pkcs7-certreqresp", "application/x-pkcs7-crl", "application/x-pkcs7-mime", "application/x-pkcs7-mime", "application/x-pkcs7-signature", "application/x-pkcs7-signature", "application/x-pointplus", "application/x-portable-anymap", "application/x-project", "application/x-project", "application/x-project", "application/x-project", "application/x-python-code", "application/x-python-code", "application/x-qpro", "application/x-quicktimeplayer", "application/x-rar-compressed", "application/x-redhat-package-manager", "application/x-research-info-systems", "application/x-rpm", "application/x-rtf", "application/x-sdp", "application/x-sea", "application/x-seelogo", "application/x-sh", "application/x-shar", "application/x-shar", "application/x-shockwave-flash", "application/x-shockwave-flash", "application/x-silverlight-app", "application/x-sit", "application/x-sprite", "application/x-sprite", "application/x-sql", "application/x-stuffit", "application/x-stuffitx", "application/x-subrip", "application/x-sv4cpio", "application/x-sv4crc", "application/x-t3vm-image", "application/x-tads", "application/x-tar", "application/x-tbook", "application/x-tbook", "application/x-tcl", "application/x-tex", "application/x-tex-gf", "application/x-tex-pk", "application/x-tex-tfm", "application/x-texinfo", "application/x-texinfo", "application/x-tgif", "application/x-trash", "application/x-trash", "application/x-trash", "application/x-trash", "application/x-trash", "application/x-troff", "application/x-troff", "application/x-troff", "application/x-troff-man", "application/x-troff-me", "application/x-troff-ms", "application/x-troff-msvideo", "application/x-ustar", "application/x-visio", "application/x-visio", "application/x-visio", "application/x-vnd.audioexplosion.mzz", "application/x-vnd.ls-xpix", "application/x-vrml", "application/x-wais-source", "application/x-wais-source", "application/x-web-app-manifest+json", "application/x-wingz", "application/x-winhelp", "application/x-wintalk", "application/x-world", "application/x-world", "application/x-wpwin", "application/x-wri", "application/x-x509-ca-cert", "application/x-x509-ca-cert", "application/x-x509-ca-cert", "application/x-x509-user-cert", "application/x-xcf", "application/x-xfig", "application/x-xliff+xml", "application/x-xpinstall", "application/x-xz", "application/x-zip-compressed", "application/x-zmachine", "application/x-zmachine", "application/x-zmachine", "application/x-zmachine", "application/x-zmachine", "application/x-zmachine", "application/x-zmachine", "application/x-zmachine", "application/xaml+xml", "application/xcap-diff+xml", "application/xenc+xml", "application/xhtml+xml", "application/xhtml+xml", "application/xml", "application/xml", "application/xml", "application/xml-dtd", "application/xop+xml", "application/xproc+xml", "application/xslt+xml", "application/xspf+xml", "application/xv+xml", "application/xv+xml", "application/xv+xml", "application/xv+xml", "application/yang", "application/yin+xml", "application/ynd.ms-pkipko", "application/zip", "audio/adpcm", "audio/aiff", "audio/aiff", "audio/aiff", "audio/basic", "audio/basic", "audio/flac", "audio/it", "audio/make", "audio/make", "audio/make", "audio/make.my.funk", "audio/mid", "audio/mid", "audio/midi", "audio/midi", "audio/midi", "audio/midi", "audio/mod", "audio/mp4", "audio/mp4", "audio/mpeg", "audio/mpeg", "audio/mpeg", "audio/mpeg", "audio/mpeg", "audio/mpeg", "audio/mpeg", "audio/mpeg", "audio/mpeg", "audio/mpeg", "audio/mpeg3", "audio/mpegurl", "audio/nspaudio", "audio/nspaudio", "audio/ogg", "audio/ogg", "audio/ogg", "audio/prs.sid", "audio/s3m", "audio/silk", "audio/tsp-audio", "audio/tsplayer", "audio/vnd.dece.audio", "audio/vnd.dece.audio", "audio/vnd.digital-winds", "audio/vnd.dra", "audio/vnd.dts", "audio/vnd.dts.hd", "audio/vnd.lucent.voice", "audio/vnd.ms-playready.media.pya", "audio/vnd.nuera.ecelp4800", "audio/vnd.nuera.ecelp7470", "audio/vnd.nuera.ecelp9600", "audio/vnd.qcelp", "audio/vnd.rip", "audio/voc", "audio/voxware", "audio/wav", "audio/webm", "audio/x-aac", "audio/x-adpcm", "audio/x-aiff", "audio/x-aiff", "audio/x-aiff", "audio/x-au", "audio/x-caf", "audio/x-flac", "audio/x-gsm", "audio/x-gsm", "audio/x-jam", "audio/x-liveaudio", "audio/x-matroska", "audio/x-mid", "audio/x-mid", "audio/x-midi", "audio/x-midi", "audio/x-mod", "audio/x-mpeg", "audio/x-mpeg-3", "audio/x-mpegurl", "audio/x-mpequrl", "audio/x-ms-wax", "audio/x-ms-wma", "audio/x-nspaudio", "audio/x-nspaudio", "audio/x-pn-realaudio", "audio/x-pn-realaudio", "audio/x-pn-realaudio", "audio/x-pn-realaudio", "audio/x-pn-realaudio", "audio/x-pn-realaudio-plugin", "audio/x-pn-realaudio-plugin", "audio/x-pn-realaudio-plugin", "audio/x-psid", "audio/x-realaudio", "audio/x-scpls", "audio/x-sd2", "audio/x-twinvq", "audio/x-twinvq-plugin", "audio/x-twinvq-plugin", "audio/x-vnd.audioexplosion.mjuicemediafile", "audio/x-voc", "audio/x-wav", "audio/xm", "chemical/x-cdx", "chemical/x-cif", "chemical/x-cmdf", "chemical/x-cml", "chemical/x-csml", "chemical/x-pdb", "chemical/x-pdb", "chemical/x-xyz", "drawing/x-dwf", "drawing/x-dwf(old)", "font/opentype", "i-world/i-vrml", "image/bmp", "image/bmp", "image/cgm", "image/cis-cod", "image/cmu-raster", "image/cmu-raster", "image/fif", "image/florian", "image/florian", "image/g3fax", "image/gif", "image/ief", "image/ief", "image/jpeg", "image/jpeg", "image/jpeg", "image/jpeg", "image/jpeg", "image/jutvision", "image/ktx", "image/naplps", "image/naplps", "image/pcx", "image/pict", "image/pict", "image/pipeg", "image/pjpeg", "image/pjpeg", "image/pjpeg", "image/pjpeg", "image/png", "image/png", "image/prs.btif", "image/sgi", "image/svg+xml", "image/svg+xml", "image/tiff", "image/tiff", "image/vasa", "image/vnd.adobe.photoshop", "image/vnd.dece.graphic", "image/vnd.dece.graphic", "image/vnd.dece.graphic", "image/vnd.dece.graphic", "image/vnd.djvu", "image/vnd.djvu", "image/vnd.dvb.subtitle", "image/vnd.dwg", "image/vnd.dwg", "image/vnd.dwg", "image/vnd.dxf", "image/vnd.fastbidsheet", "image/vnd.fpx", "image/vnd.fpx", "image/vnd.fst", "image/vnd.fujixerox.edmics-mmr", "image/vnd.fujixerox.edmics-rlc", "image/vnd.ms-modi", "image/vnd.ms-photo", "image/vnd.net-fpx", "image/vnd.net-fpx", "image/vnd.rn-realflash", "image/vnd.rn-realpix", "image/vnd.wap.wbmp", "image/vnd.xiff", "image/webp", "image/x-3ds", "image/x-cmu-rast", "image/x-cmu-raster", "image/x-cmx", "image/x-coreldraw", "image/x-coreldrawpattern", "image/x-coreldrawtemplate", "image/x-corelphotopaint", "image/x-dwg", "image/x-dwg", "image/x-dwg", "image/x-freehand", "image/x-freehand", "image/x-freehand", "image/x-freehand", "image/x-freehand", "image/x-icon", "image/x-jg", "image/x-jng", "image/x-jps", "image/x-mrsid-image", "image/x-ms-bmp", "image/x-niff", "image/x-niff", "image/x-pcx", "image/x-photoshop", "image/x-pict", "image/x-pict", "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-greymap", "image/x-portable-pixmap", "image/x-quicktime", "image/x-quicktime", "image/x-quicktime", "image/x-rgb", "image/x-tga", "image/x-tiff", "image/x-tiff", "image/x-windows-bmp", "image/x-xbitmap", "image/x-xbitmap", "image/x-xbm", "image/x-xpixmap", "image/x-xpixmap", "image/x-xwd", "image/x-xwindowdump", "image/xbm", "image/xpm", "message/rfc822", "message/rfc822", "message/rfc822", "message/rfc822", "message/rfc822", "model/iges", "model/iges", "model/mesh", "model/mesh", "model/mesh", "model/vnd.collada+xml", "model/vnd.dwf", "model/vnd.gdl", "model/vnd.gtw", "model/vnd.mts", "model/vnd.vtu", "model/vrml", "model/vrml", "model/vrml", "model/x-pov", "model/x3d+binary", "model/x3d+binary", "model/x3d+vrml", "model/x3d+vrml", "model/x3d+xml", "model/x3d+xml", "multipart/x-gzip", "multipart/x-ustar", "multipart/x-zip", "music/crescendo", "music/crescendo", "music/x-karaoke", "paleovu/x-pv", "text/asp", "text/cache-manifest", "text/cache-manifest", "text/calendar", "text/calendar", "text/calendar", "text/comma-separated-values", "text/css", "text/csv", "text/ecmascript", "text/event-stream", "text/h323", "text/html", "text/html", "text/html", "text/html", "text/html", "text/html", "text/html", "text/iuls", "text/javascript", "text/mathml", "text/mcf", "text/n3", "text/pascal", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain", "text/plain-bas", "text/prs.lines.tag", "text/richtext", "text/richtext", "text/richtext", "text/rtf", "text/scriplet", "text/scriptlet", "text/scriptlet", "text/sgml", "text/sgml", "text/tab-separated-values", "text/texmacs", "text/texmacs", "text/troff", "text/troff", "text/troff", "text/troff", "text/troff", "text/troff", "text/turtle", "text/uri-list", "text/uri-list", "text/uri-list", "text/uri-list", "text/uri-list", "text/vcard", "text/vnd.abc", "text/vnd.curl", "text/vnd.curl.dcurl", "text/vnd.curl.mcurl", "text/vnd.curl.scurl", "text/vnd.dvb.subtitle", "text/vnd.fly", "text/vnd.fmi.flexstor", "text/vnd.graphviz", "text/vnd.in3d.3dml", "text/vnd.in3d.spot", "text/vnd.rn-realtext", "text/vnd.sun.j2me.app-descriptor", "text/vnd.wap.si", "text/vnd.wap.sl", "text/vnd.wap.wml", "text/vnd.wap.wmlscript", "text/vtt", "text/webviewhtml", "text/x-asm", "text/x-asm", "text/x-audiosoft-intra", "text/x-c", "text/x-c", "text/x-c", "text/x-c", "text/x-c", "text/x-c", "text/x-c", "text/x-c++hdr", "text/x-c++hdr", "text/x-c++hdr", "text/x-c++hdr", "text/x-c++src", "text/x-c++src", "text/x-c++src", "text/x-c++src", "text/x-chdr", "text/x-component", "text/x-csh", "text/x-csrc", "text/x-fortran", "text/x-fortran", "text/x-fortran", "text/x-fortran", "text/x-h", "text/x-h", "text/x-java", "text/x-java-source", "text/x-java-source", "text/x-la-asf", "text/x-lua", "text/x-m", "text/x-markdown", "text/x-markdown", "text/x-markdown", "text/x-moc", "text/x-nfo", "text/x-opml", "text/x-pascal", "text/x-pascal", "text/x-pcs-gcd", "text/x-perl", "text/x-perl", "text/x-python", "text/x-script", "text/x-script.csh", "text/x-script.elisp", "text/x-script.guile", "text/x-script.ksh", "text/x-script.lisp", "text/x-script.perl", "text/x-script.perl-module", "text/x-script.phyton", "text/x-script.rexx", "text/x-script.scheme", "text/x-script.sh", "text/x-script.tcl", "text/x-script.tcsh", "text/x-script.zsh", "text/x-server-parsed-html", "text/x-server-parsed-html", "text/x-setext", "text/x-sfv", "text/x-sgml", "text/x-sgml", "text/x-sh", "text/x-speech", "text/x-speech", "text/x-tcl", "text/x-tcl", "text/x-tex", "text/x-tex", "text/x-tex", "text/x-tex", "text/x-uil", "text/x-uuencode", "text/x-uuencode", "text/x-vcalendar", "text/x-vcard", "text/xml", "video/3gpp", "video/3gpp2", "video/MP2T", "video/animaflex", "video/avi", "video/avs-video", "video/dl", "video/flc", "video/flc", "video/fli", "video/fli", "video/gl", "video/h261", "video/h263", "video/h264", "video/jpeg", "video/jpm", "video/jpm", "video/mj2", "video/mj2", "video/mp4", "video/mp4", "video/mp4", "video/mpeg", "video/mpeg", "video/mpeg", "video/mpeg", "video/mpeg", "video/mpeg", "video/mpeg", "video/mpeg", "video/mpeg", "video/msvideo", "video/ogg", "video/quicktime", "video/quicktime", "video/quicktime", "video/vdo", "video/vivo", "video/vivo", "video/vnd.dece.hd", "video/vnd.dece.hd", "video/vnd.dece.mobile", "video/vnd.dece.mobile", "video/vnd.dece.pd", "video/vnd.dece.pd", "video/vnd.dece.sd", "video/vnd.dece.sd", "video/vnd.dece.video", "video/vnd.dece.video", "video/vnd.dvb.file", "video/vnd.fvt", "video/vnd.mpegurl", "video/vnd.mpegurl", "video/vnd.ms-playready.media.pyv", "video/vnd.rn-realvideo", "video/vnd.uvvu.mp4", "video/vnd.uvvu.mp4", "video/vnd.vivo", "video/vnd.vivo", "video/vosaic", "video/webm", "video/x-amt-demorun", "video/x-amt-showrun", "video/x-atomic3d-feature", "video/x-dl", "video/x-dv", "video/x-dv", "video/x-f4v", "video/x-fli", "video/x-flv", "video/x-gl", "video/x-isvideo", "video/x-la-asf", "video/x-la-asf", "video/x-m4v", "video/x-matroska", "video/x-matroska", "video/x-matroska", "video/x-mng", "video/x-motion-jpeg", "video/x-mpeg", "video/x-mpeg", "video/x-mpeq2a", "video/x-ms-asf", "video/x-ms-asf", "video/x-ms-asf", "video/x-ms-asf-plugin", "video/x-ms-vob", "video/x-ms-wm", "video/x-ms-wmv", "video/x-ms-wmx", "video/x-ms-wvx", "video/x-msvideo", "video/x-qtc", "video/x-scm", "video/x-sgi-movie", "video/x-sgi-movie", "video/x-smv", "windows/metafile", "www/mime", "x-conference/x-cooltalk", "x-music/x-midi", "x-music/x-midi", "x-world/x-3dmf", "x-world/x-3dmf", "x-world/x-3dmf", "x-world/x-3dmf", "x-world/x-svr", "x-world/x-vrml", "x-world/x-vrml", "x-world/x-vrml", "x-world/x-vrml", "x-world/x-vrml", "x-world/x-vrml", "x-world/x-vrml", "x-world/x-vrt", "xgl/drawing", "xgl/movie", "application/mathematica", "application/msword", "application/octet-stream", "application/onenote", "application/pgp-signature", "application/pkcs7-mime", "application/postscript", "application/smil+xml", "application/vnd.acucorp", "application/vnd.clonk.c4group", "application/vnd.eszigno3+xml", "application/vnd.fdsn.seed", "application/vnd.framemaker", "application/vnd.geometry-explorer", "application/vnd.grafeq", "application/vnd.ibm.modcap", "application/vnd.iccprofile", "application/vnd.intercon.formnet", "application/vnd.kahootz", "application/vnd.kde.kpresenter", "application/vnd.kde.kword", "application/vnd.kinar", "application/vnd.koan", "application/vnd.ms-excel", "application/vnd.ms-powerpoint", "application/vnd.ms-project", "application/vnd.ms-works", "application/vnd.palm", "application/vnd.quark.quarkxpress", "application/vnd.simtech-mindmapper", "application/vnd.solent.sdkm+xml", "application/vnd.sus-calendar", "application/vnd.symbian.install", "application/vnd.ufdl", "application/vnd.visio", "application/vnd.zul", "application/x-authorware-bin", "application/x-bzip2", "application/x-debian-package", "application/x-director", "application/x-font-ttf", "application/x-font-type1", "application/x-mobipocket-ebook", "application/x-msdownload", "application/x-msmediaview", "application/x-netcdf", "application/x-pkcs12", "application/x-pkcs7-certificates", "application/x-texinfo", "application/x-x509-ca-cert", "application/xhtml+xml", "application/xml", "application/xv+xml", "audio/basic", "audio/midi", "audio/mpeg", "audio/ogg", "audio/x-aiff", "audio/x-pn-realaudio", "image/jpeg", "image/svg+xml", "image/tiff", "image/vnd.djvu", "image/x-freehand", "image/x-pict", "message/rfc822", "model/iges", "model/mesh", "model/vrml", "text/calendar", "text/html", "text/plain", "text/sgml", "text/troff", "text/uri-list", "text/x-asm", "text/x-c", "text/x-fortran", "text/x-pascal", "video/jpm", "video/mj2", "video/mp4", "video/mpeg", "video/quicktime", "video/vnd.mpegurl", "video/x-ms-asf")), row.names = c(NA, -1763L), class = c("tbl_df", "tbl", "data.frame"), .Names = c("extension", "mime_type")) -> simplemagic_mime_db
/scratch/gouwar.j/cran-all/cranData/wand/R/aaa.r
check_office <- function(hdr, path) { # [Content_Types.xml] || length 19 c( 0x5b,0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x5f,0x54, 0x79,0x70,0x65,0x73,0x5d,0x2e,0x78,0x6d,0x6c ) -> pat_content_types # _rels/.rels || length 11 pat_rels <- c(0x5f,0x72,0x65,0x6c,0x73,0x2f,0x2e,0x72,0x65,0x6c,0x73) if ((all(pat_content_types == hdr[31:49])) || (all(pat_rels == hdr[31:41]))) { hdr <- readBin(path, "raw", n=4096) pat_word <- c(0x77,0x6f,0x72,0x64,0x2f) if (length(seq_in(hdr, pat_word)) > 0) return("application/vnd.openxmlformats-officedocument.wordprocessingml.document") pat_ppt <- c(0x70,0x70,0x74,0x2f) if (length(seq_in(hdr, pat_ppt)) > 0) return("application/vnd.openxmlformats-officedocument.presentationml.presentation") pat_xl <- c(0x78,0x6c,0x2f) if (length(seq_in(hdr, pat_xl)) > 0) return("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") } return(NULL) }
/scratch/gouwar.j/cran-all/cranData/wand/R/check-office.R
#' Discover MIME type of a file based on contents #' #' There are a limited number of header "magic" bytes checked directly by #' this function but cover quite a bit of ground. After that, [guess_content_type()] is called which uses #' file extension-to-MIME mappings. File an issue or PR if more magic-byte-level #' comparisons are required/desired. If no match is found, `???` is returned. #' #' @details #' Initial in-R header mapping logic borrowed from `MimeTypes.java` from #' [`servoy-client`](https://github.com/Servoy/servoy-client) #' #' @md #' @param path path to a file #' @return character vector #' @export #' @examples #' get_content_type(system.file("extdat", "test.pdf", package="wand")) get_content_type <- function(path) { path <- path.expand(path) if (!file.exists(path)) stop("File not found.", call.=FALSE) hdr <- readBin(path, "raw", n=1024) if (all(c(0x4F,0x62,0x6A,0x01) == hdr[1:4])) return("application/vnd.apache.avro+binary") if (all(c(0x50,0x41,0x52,0x31) == hdr[1:4])) return("application/x-parquet") if (all(c(0xCA,0xFE,0xBA,0xBE) == hdr[1:4])) return("application/java-vm") if (all(c(0xD0,0xCF,0x11,0xE0,0xA1,0xB1,0x1A,0xE1) == hdr[1:8])) { guessed_name <- guess_content_type(path) if ((length(guessed_name) == 1) && (guessed_name != "???")) return(guessed_name) return("application/msword") } if (all(c(0x25,0x50,0x44,0x46,0x2d,0x31,0x2e) == hdr[1:7])) return("application/pdf") if (all(c(0x25,0x50,0x44,0x46) == hdr[1:4])) return("application/x-pdf") if (all(c(0x38,0x42,0x50,0x53,0x00,0x01) == hdr[1:6])) return("image/photoshop") if (all(c(0x25,0x21,0x50,0x53) == hdr[1:4])) return("application/postscript") if (all(c(0xff,0xfb,0x30) == hdr[1:3])) return("audio/mp3") if (all(c(0xff,0xfb,0xd0) == hdr[1:3])) return("audio/mp3") if (all(c(0xff,0xfb,0x90) == hdr[1:3])) return("audio/mp3") if (all(c(0x49,0x44,0x33) == hdr[1:3])) return("audio/mp3") if (all(c(0xAC,0xED) == hdr[1:2])) return("application/x-java-serialized-object") if (all(c(0x4c,0x5a,0x49,0x50) == hdr[1:4])) return("application/x-lzip") if (hdr[1] == 0x3c) { # "<" if (all(c(0x68,0x74,0x6d,0x6c) == hdr[2:5])) return("text/html") # "html" if (all(c(0x48,0x54,0x4d,0x4c) == hdr[2:5])) return("text/html") # "HTML" if (all(c(0x48,0x45,0x41,0x44) == hdr[2:5])) return("text/html") # "HEAD" if (all(c(0x68,0x65,0x61,0x64) == hdr[2:5])) return("text/html") # "head" if (all(c(0x3f,0x78,0x6d,0x6c,0x20) == hdr[2:6])) return("application/xml") } if (all(c(0x0a,0x0d,0x0d,0x0a) == hdr[1:4])) "application/x-pcapng" if (all(c(0xa1,0xb2,0xc3,0xd4) == hdr[1:4]) || all(c(0xd4,0xc3,0xb2,0xa1) == hdr[1:4])) return("application/x-cap") if (all(c(0xfe,0xff) == hdr[1:2])) { if (all(c(0x00,0x3c,0x00,0x3f,0x00,0x78) == hdr[3:8])) return("application/xml") } if (all(c(0x42,0x4d) == hdr[1:2])) return("image/bmp") if (all(c(0x49,0x49,0x2a,0x00) == hdr[1:4])) return("image/tiff") if (all(c(0x4D,0x4D,0x00,0x2a) == hdr[1:4])) return("image/tiff") if (all(c(0x47,0x49,0x46,0x38) == hdr[1:4])) return("image/gif") if (all(c(0x23,0x64,0x65,0x66) == hdr[1:4])) return("image/x-bitmap") if (all(c(0x21,0x20,0x58,0x50,0x4d,0x32) == hdr[1:6])) return("image/x-pixmap") if (all(c(137,80,78,71,13,10,26,10) == hdr[1:8])) return("image/png") if (all(c(0x23,0x21,0x2f,0x62,0x69,0x6e,0x2f,0x6e,0x6f,0x64,0x65) == hdr[1:11])) return("application/javascript") if (all(c(0x23,0x21,0x2f,0x62,0x69,0x6e,0x2f,0x6e,0x6f,0x64,0x65,0x6a,0x73) == hdr[1:13])) return("application/javascript") if (all(c(0x23,0x21,0x2f,0x75,0x73,0x72,0x2f,0x62,0x69,0x6e,0x2f,0x6e,0x6f,0x64,0x65) == hdr[1:15])) return("application/javascript") if (all(c(0x23,0x21,0x2f,0x75,0x73,0x72,0x2f,0x62,0x69,0x6e,0x2f,0x6e,0x6f,0x64,0x65,0x6a,0x73) == hdr[1:17])) return("application/javascript") if (all(c(0x23,0x21,0x2f,0x75,0x73,0x72,0x2f,0x62,0x69,0x6e,0x2f,0x65,0x6e,0x76,0x20,0x6e,0x6f,0x64,0x65) == hdr[1:19])) return("application/javascript") if (all(c(0x23,0x21,0x2f,0x75,0x73,0x72,0x2f,0x62,0x69,0x6e,0x2f,0x65,0x6e,0x76,0x20,0x6e,0x6f,0x64,0x65,0x6a,0x73) == hdr[1:21])) return("application/javascript") if (all(c(0xFF,0xD8,0xFF) == hdr[1:3])) { if (0xDB == hdr[4]) return("image/jpeg") if (0xE0 == hdr[4]) return("image/jpeg") if (0xE1 == hdr[4]) { if (all(c(0x45,0x78,0x69,0x66,0x00) == hdr[7:11])) return("image/jpeg") # Exif } if (0xEE == hdr[4]) return("image/jpg") } if (all(c(0x41,0x43) == hdr[1:2]) && all(c(0x00,0x00,0x00,0x00,0x00) == hdr[7:11])) return("application/acad") if (all(c(0x2E,0x73,0x6E,0x64) == hdr[1:4])) return("audio/basic") if (all(c(0x64,0x6E,0x73,0x2E) == hdr[1:4])) return("audio/basic") if (all(c(0x52,0x49,0x46,0x46) == hdr[1:4])) return("audio/x-wav") # "RIFF" if (all(c(0x50, 0x4b) == hdr[1:2])) { # "PK" office_type <- check_office(hdr, path) if (length(office_type) > 0) return(office_type) guessed_name <- guess_content_type(path) if ((length(guessed_name) == 1) && (guessed_name != "???")) return(guessed_name) return("application/zip") } if (all(c(0x00,0x61,0x73,0x6d) == hdr[1:4])) return("application/wasm") if (all(c(0x37,0x7A,0xBC,0xAF,0x27,0x1C) == hdr[1:6])) return("application/x-7z-compressed") if (all(c(0x5a,0x4d) == hdr[1:2])) return("x-system/exe") if (all(c(0x75,0x73,0x74,0x61,0x72) == hdr[258:262])) { if (all(c(0x00,0x30,0x30) == hdr[263:265]) || all(c(0x20,0x20,0x00) == hdr[263:265])) { return("application/tar") } else { return("application/pax") } } if (all(c(0x00,0x00,0x01,0xBA) == hdr[1:4])) return("video/mpeg") if (all(c(0x00,0x00,0x01,0xB3) == hdr[1:4])) return("video/mpeg") return(guess_content_type(path)) }
/scratch/gouwar.j/cran-all/cranData/wand/R/get-content-type.R
#' Guess MIME type from filename (extension) #' #' Uses an internal database of over 1,500 file extension-to-MIME mappings to #' return one or more associated types for a given input path. If no match is #' found, `???` is returned. #' #' @details #' Incorporates standard IANA MIME extension mappings and those from #' [`servoy-client`](https://github.com/Servoy/servoy-client) and #' [stevenwdv](https://github.com/stevenwdv)'s #' [`allMimeTypes.json`](https://s-randomfiles.s3.amazonaws.com/mime/allMimeTypes.json). #' #' @md #' @param path path to file #' @return character vector #' @export #' @examples #' guess_content_type(system.file("extdat", "test.pdf", package="wand")) guess_content_type <- function(path) { path <- path.expand(path) if (!file.exists(path)) stop("File not found.", call.=FALSE) extension <- trimws(tolower(tools::file_ext(path))) res <- simplemagic_mime_db[(simplemagic_mime_db$extension == extension),]$mime_type if (length(res) == 0) return("???") return(unique(res)) }
/scratch/gouwar.j/cran-all/cranData/wand/R/guess-content-type.R
seq_in <- function(source_vector, pattern_vector) { which( Reduce( '+', lapply( seq_along(y <- lapply(pattern_vector, '==', source_vector)), function(x) { y[[x]][x:(length(source_vector) - length(pattern_vector) + x)] } ) ) == length(pattern_vector) ) }
/scratch/gouwar.j/cran-all/cranData/wand/R/util.R
#' Retrieve 'Magic' Attributes from Files and Directories #' #' The 'libmagic' library provides functions to determine 'MIME' type and other #' metadata from files through their "magic" attributes. This is useful when you #' do not wish to rely solely on the honesty of a user or the extension on a #' file name. It also incorporates other metadata from the mime-db database #' <https://github.com/jshttp/mime-db> #' #' @section Some important details: #' #' The header checking is minimal (i.e. nowhere near as comprehensive as `libmagic`) but #' covers quite a bit of ground. If there are content-check types from #' [`magic sources`](https://github.com/threatstack/libmagic/tree/master/magic/) #' that you would like coded into the package, please file an issue and #' _include the full line(s)_ from that linked `magic.tab` that you would like mapped. #' #' @md #' @name wand #' @docType package #' @author Bob Rudis (bob@@rud.is) #' @importFrom tools file_ext NULL
/scratch/gouwar.j/cran-all/cranData/wand/R/wand-package.R
library(wand) list( actions.csv = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", actions.txt = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", actions.xlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", test_128_44_jstereo.mp3 = "audio/mp3", test_excel_2000.xls = "application/msword", test_excel_spreadsheet.xml = "application/xml", test_excel_web_archive.mht = "message/rfc822", test_excel.xlsm = "application/zip", test_excel.xlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", test_nocompress.tif = "image/tiff", test_powerpoint.pptm = "application/zip", test_powerpoint.pptx = "application/vnd.openxmlformats-officedocument.presentationml.presentation", test_word_2000.doc = "application/msword", test_word_6.0_95.doc = "application/msword", test_word.docm = "application/zip", test_word.docx = "application/vnd.openxmlformats-officedocument.wordprocessingml.document", test.au = "audio/basic", test.bin = c( "application/mac-binary", "application/macbinary", "application/octet-stream", "application/x-binary", "application/x-macbinary" ), test.bmp = "image/bmp", test.dtd = "application/xml-dtd", test.emf = "application/x-msmetafile", test.eps = "application/postscript", test.fli = c("video/flc", "video/fli", "video/x-fli"), test.gif = "image/gif", test.ico = "image/x-icon", test.jpg = "image/jpeg", test.mp3 = "audio/mp3", test.odt = "application/vnd.oasis.opendocument.text", test.ogg = c( "application/ogg", "audio/ogg" ), test.pcx = c("image/pcx", "image/x-pcx"), test.pdf = "application/pdf", test.pl = c("text/plain", "text/x-perl", "text/x-script.perl"), test.png = "image/png", test.pnm = c( "application/x-portable-anymap", "image/x-portable-anymap" ), test.ppm = "image/x-portable-pixmap", test.ppt = "application/msword", test.ps = "application/postscript", test.psd = "image/photoshop", test.py = c( "text/x-python", "text/x-script.phyton" ), test.rtf = c( "application/rtf", "application/x-rtf", "text/richtext", "text/rtf" ), test.sh = c( "application/x-bsh", "application/x-sh", "application/x-shar", "text/x-script.sh", "text/x-sh" ), test.tar = "application/tar", test.tar.gz = c( "application/octet-stream", "application/x-compressed", "application/x-gzip" ), test.tga = "image/x-tga", test.txt = "text/plain", test.txt.gz = c( "application/octet-stream", "application/x-compressed", "application/x-gzip" ), test.wav = "audio/x-wav", test.wmf = c("application/x-msmetafile", "windows/metafile"), test.xcf = "application/x-xcf", test.xml = "application/xml", test.xpm = c("image/x-xbitmap", "image/x-xpixmap", "image/xpm"), test.zip = "application/zip" ) -> results fils <- list.files(system.file("extdat", package="wand"), full.names=TRUE) tst <- lapply(fils, get_content_type) names(tst) <- basename(fils) for(n in names(tst)) expect_identical(results[[n]], tst[[n]])
/scratch/gouwar.j/cran-all/cranData/wand/inst/tinytest/test_wand.R
#' Warabandi data for generate after making for calculation #' @docType data #' @usage data(finalReport) #' @format It comprises all data required to mention in the final report #' @example b = finalReport #' Time_Schedule = b$Time_schedule #' "finalReport"
/scratch/gouwar.j/cran-all/cranData/warabandi/R/finalReport.R
#' @title Warabandi #' @author Harvinder Singh, #' PhD scholar, Department of Pharmacology, PGIMER, Chandigarh (160012) #' harvindermaan4[@]gmail.com #' ORCID https://orcid.org/0000-0002-6349-3143 #' @description #' To generate a roster for a week (168 hrs. or 24X7) as used in warabandi #' system. Flow time of a watercourse to an individual farmer calculate based #' on their holding area (bigga or hectares), This flow time roster generated by #' this function known as "warabandi" in canal irrigated agricultural areas #' (Punjab, Rajasthan, Haryana and Some areas of Pakistan) #' @details #' A regulated irrigation system, from source (reservoir or river) down to gate #' of farm known as 'nakka' known as warabandi. Water from reservoir or source #' is carried out by main canal which supplies sub-canal or sub-distributaries. #' Sub-distributaries run with full supply to secondary-sub-distributaries with #' rotations. These secondary-sub-distributaries supplies to watercourse #' through #' outlets. For water supply to different farms or fields situated along the #' web of watercourse by a time roster of week i.e., "Warabandi". Watercourse #' runs at full supply when secondary-sub-distributaries are in flow. This is #' 3° distributary system. The main objective of warabandi is to attain maximum #' efficiency of water use by implementing water scarcity on every user. #' Warabandi justifies equality and safe guards to every farmer even in the #' case of farm is located at the end of the watercourse. The roster of turn #' in the first we have to define various terminology used in warabandi; #' #' Bharai: #' #' When water start to fill-up the empty watercourse, time spent to fill #' the empty watercourse (length of the head to the farm gate i.e., Nakka) or we #' can say filling time or compensation to the farmer, known as 'bharai'. #' #' Jharai: #' #' When tail or end of the watercourse farmer has his turn and head or at #' the start of watercourse farmer diverted his shared water then rest of the #' flowed water will goes to the tail end farmer as compensation, i.e., empty #' time. #' #' Rakva: #' #' Culturable area owned by farmer or Area subjected to irrigation. #' Flow Time per unit area = It is a calculatable time by using following #' formula; #' #' "168 hours - (Total bharai - Total jharai) / Total culturable command area". #' #' Flow time for farmer<- It is a calculatable time by following formula; #' #' (Flow time per unit area X Area owned by farmer) + (bharai for his field's #' gate location - jharai for his field's gate location) #' #' Roster of turn #' #' Basically, warabandi or roster of turn starts from Monday, 6:00 PM to next #' Monday, 6:00 PM throughout all week days. Time and date calculation can be #' done by “lubridate” R package, but it’s not able to perform divide and #' multiplication tasks with numeric. In our knowledge there is no software or #' package to generate directly warabandi based on data available with “patwari”. #' Data required to generate the warabandi can be found from related irrigation #' department officer known as "Patwari". #' @note Data structure: #' There should be at least 4 column containing header with; #' 1. Names of Farmer #' #' 2. Rakva: There can be multiple columns for this section but be sure header #' should be specified as (x.1, x.2, x.3.....x.N) #' #' 3. Bharai: This column should have data of compensation in the format of H:M #' (1:10). If there is no compensation to give a farmer then put it as '0:0'. #' #' 4. Jharai: This column should have data of Jharai in the same format as #' described in case of bharai. If there is no jharai to deduct from a farmer #' flow time then put it as '0:0'. #' #' @note #' Input data should be in the ".txt" or ".csv" format. Which can be generated #' in in any data entry software like excel, libra etc. #' That's enough to calculate warabandi and it will generate full a week roaster #' as Output.csv. Output file will be saved in working directory #' #' Required external packages: #' a) “lubridate” #' b) “readtext” #' d) “flextable” #' Or #' It can be said: #' Imports: #' lubridate #' readtext #' flextable #' #'@keywords warabandi #'@keywords roster for weekdays #'@kewords Flow time #' #'@references #'1. G. Asawa.Irrigation and water resources engineering. New Age International, #' 2006 #' #'2. Bandaragoda DJ(1995) <https://publications.iwmi.org/pdf/H_17571i.pdf> #' #'3. V. Narain. Warabandi as a sociotechnical system for canal water #' allocation: opportunities and challenges for reform.Water Policy, #' 10(4):409â422, 2008 #' #'4. Ajmera S, Shrivastava RK. Water distribution schedule under warabandi #' system considering seepage losses for an irrigation project: A case study. #' Intl. J. Innov. Eng. Tech. 2013;2(4):178-87. #' #' @concept wararabandi #' @concept Roster #' @concept weekdays #' @concept Flow time per unit area #' @return A list of different objects i.e. Flow Time per Unit Area, Total rakva, #' Total bharai, Total jharai, Full week Hours and Final report #' To generate final report saved output file has to be supplied into #' My_file.Rmd by editing it as per your need i.e. format of output document or #' headers and footers for the output table report. #' @param file = Contains data for calculation #' @param output = TRUE or FALSE to write output file #' @param nof = "My_report" specify output file name #' @import utils #' @export warabandi<-function(file, output= c(TRUE, FALSE), nof){ #library(rJava) if(is.data.frame(file)){in.dt <- file} else if( grepl(".txt", file )){in.dt <- readtext::readtext(file = file, header = T)} else if(grepl(".csv", file)){in.dt <- utils::read.csv(file = file, header = T)} Nakka <- in.dt[, grep(pattern = '^Nk.*', names(in.dt))] P1 <- in.dt[, grep(pattern = '^x.*', names(in.dt))] P1[is.na(P1)] <- 0 P2 <- in.dt[, grep(pattern = '^M.*', names(in.dt))] P2[is.na(P2)] <- 0 P3 <- t(P2) P5 <- t(P1) D_rkva <- apply(P5, 2, paste, collapse=", ") MuNo <- apply(P3, 2, paste, collapse=", ") Drkva <- paste(D_rkva, "\n", "MNo", MuNo) rakva_only <- P1 bharai <- as.POSIXlt(strptime(in.dt$Bharai, "%H:%M")) bharai[is.na.POSIXlt(bharai)] <- as.POSIXlt(strptime("0:0", "%H:%M")) jharai <- as.POSIXlt(strptime(in.dt$Katai, "%H:%M")) jharai[is.na.POSIXlt(jharai)] <- as.POSIXlt(strptime("0:0", "%H:%M")) Individual_rakva_sum <- rowSums(rakva_only) Total_rakva <- sum(Individual_rakva_sum) total_bharai_microseconds <- (sum(bharai$hour) * 3600000000) + (sum(bharai$min) * 60000000) total_jharai_microseconds <- (sum(jharai$hour) * 3600000000) + (sum(jharai$min) * 60000000) total_microsecond_in_a_week <- 604800000000 Total_bharai <- as.character(lubridate::seconds_to_period( total_bharai_microseconds / 1000000)) Total_jharai <- as.character(lubridate::seconds_to_period( total_jharai_microseconds / 1000000)) FlowTime_per_Unit_Area_microseconds <- (((total_microsecond_in_a_week - total_bharai_microseconds) + total_jharai_microseconds) / (Total_rakva)) tpb <- lubridate::seconds_to_period(FlowTime_per_Unit_Area_microseconds / 1000000) FlowTime_per_Unit_Area <- lubridate::minute(tpb) total_FlowTime_microseconds <- (Individual_rakva_sum * FlowTime_per_Unit_Area_microseconds) jharai_in_microseconds <-(((jharai$hour) * 3600000000) + (jharai$min) * 60000000) bharai_in_microseconds <- (((bharai$hour) * 3600000000) + (bharai$min) * 60000000) actual_FlowTime_in_microseconds <- ((total_FlowTime_microseconds + bharai_in_microseconds) - jharai_in_microseconds) Full_week_H <- as.character(lubridate::seconds_to_period(sum( actual_FlowTime_in_microseconds) / 1000000)) actual_FlowTime_in_minutes <- lubridate::seconds_to_period( actual_FlowTime_in_microseconds / 1000000) actual_FlowTime_H <- paste(lubridate::hour(actual_FlowTime_in_minutes), lubridate::minute(actual_FlowTime_in_minutes), sep = ":") actual_FlowTime_H Cum_sum_list <- cumsum(actual_FlowTime_in_microseconds) SEconds <- (Cum_sum_list/1000000) Final_time_table <- lubridate::ymd_hm("2021-05-24 18:00") + SEconds round.POSIXt(Final_time_table, units = "mins") exp7 <- (Cum_sum_list) - (actual_FlowTime_in_microseconds) Seconds2 <- (exp7/1000000) Final_time_table2 <- lubridate::ymd_hm("2021-05-24 18:00") + Seconds2 round.POSIXt(Final_time_table2, units = "mins") time_breakage_1_day2 <- paste(lubridate::hour(Final_time_table2), lubridate::minute(Final_time_table2), sep=":") Pani_lene_ka_time <- paste(weekdays.Date(Final_time_table2), time_breakage_1_day2, sep = ', ') time_breakage_1_day <- paste(lubridate::hour(Final_time_table), lubridate::minute(Final_time_table), sep=":") Start_from_Monday_evening_6_pm <- paste(weekdays.Date(Final_time_table), time_breakage_1_day, sep = ', ') Time_schedule <- paste(Pani_lene_ka_time, Start_from_Monday_evening_6_pm, sep = "-") RakvaSum <- Individual_rakva_sum; FTPUA <- FlowTime_per_Unit_Area; TotalTurn <- actual_FlowTime_H; Name <- in.dt$Name_of_Farmer; Bharai <- in.dt$Bharai; Jharai <- in.dt$Katai CompleteTable4 <- data.frame(Name, Nakka, Drkva, RakvaSum, TotalTurn, Bharai, Jharai, Time_schedule) ########## Witting the output if(output == TRUE){ outputname<-as.character(nof) utils::write.csv(CompleteTable4, file = paste(outputname)) } else { print(CompleteTable4) } final_list_Report<-list(FlowTime_per_Unit_Area, Total_rakva, Total_bharai, Total_jharai, Full_week_H, CompleteTable4) final_list_Report }
/scratch/gouwar.j/cran-all/cranData/warabandi/R/warabandi.R
#' Warabandi data required for calculation #' @docType data #' @usage data(warabandi_data) #' @format It comprises name of farmer, Rakva, bharai, katai etc #' @example a = warabandi_data #' name_of_farmer = a$Name_of_Farmer #' "warabandi_data"
/scratch/gouwar.j/cran-all/cranData/warabandi/R/warabandi_data.R
## ----setup-------------------------------------------------------------------- library(warabandi) ## ----------------------------------------------------------------------------- head(warabandi_data) ## ----------------------------------------------------------------------------- output<-warabandi(file = warabandi_data, output = FALSE, nof = "my_file.csv") ## ----------------------------------------------------------------------------- output[1:5] Report_Table<-data.frame(output[6]) head(Report_Table) ## ----------------------------------------------------------------------------- data2<-Report_Table ## ----------------------------------------------------------------------------- flextable::flextable(head(data2)) ## ----------------------------------------------------------------------------- data3 <- data.frame(head(data2)) invisible(by(data3, seq_len(nrow((data3))), function(row) { chak<-"Chak-38 R.B" distributries<- "R.B II" dateOI<-date() dateOd<-"Date of distribution __/__/____" note1<-"Note: All schedules issued before this, are cancelled" Year_o_Valid<-"Year: April 2019 to 2025" Issue<-"Issue Serial No:________/___" Jal_upbhokta<-"Jal Upbhokta Sangam:" d5 <-flextable::fit_to_width(flextable::flextable(row), max_width = 7, inc=1L, max_iter = 20) d5 <- flextable::add_header_lines(d5, c(paste(Year_o_Valid,"\t","\t", chak), paste(Jal_upbhokta, distributries, "\t","\t", Issue, "\t","\t","\t","\t", dateOI))) d5 <-flextable::add_footer_lines(d5, c(paste(dateOd, "\t", "\t", note1), paste("President", "\n", "\n", "\n", Jal_upbhokta, distributries))) #flextable::flextable_to_rmd(d5) }))
/scratch/gouwar.j/cran-all/cranData/warabandi/inst/doc/warabandi.R
--- title: "warabandi" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{warabandi} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- # Warabandi or Roster of Turn **Introduction:** This function will generate roster for a week (168 hrs. or 24X7). Flow time of a watercourse to an individual farmer calculate based on their holding area (bigga or hectares), This flow time roster generated by this function known as "warabandi" in canal irrigated agricultural areas (Punjab, Rajasthan, Haryana and Some areas of Pakistan) # Load Package ```{r setup} library(warabandi) ``` ## data structure of input data ```{r} head(warabandi_data) ``` #Calulation of roster Here we are not writing output to reduce vignettes and space ```{r} output<-warabandi(file = warabandi_data, output = FALSE, nof = "my_file.csv") ``` #Lets take a look at output Output generated by package is a list of different objects. 1. Flow time per unit area in minutes 2. Rakva or total area under command subject to be irrigated 3. Bharai or fillig time; as a compensation 4. Jharai or empty time 5. Weekdays or total duration has to be divided 6. Final table calculated by warabandi saved as a output file to the working directory ```{r} output[1:5] Report_Table<-data.frame(output[6]) head(Report_Table) ``` # Report generation of warabandi Generation of the report in printable format which can be supplied or distribut- ed among all the farmers. This step is highle depend on the external packages (knitr, flextable). Code chunk provide below is a sample which can be modified as per user need like header and fotters. Lets read output file generated by warabandi package ```{r} data2<-Report_Table ``` # Lets make table ```{r} flextable::flextable(head(data2)) ``` # Lets generate report for individual farmer ```{r} data3 <- data.frame(head(data2)) invisible(by(data3, seq_len(nrow((data3))), function(row) { chak<-"Chak-38 R.B" distributries<- "R.B II" dateOI<-date() dateOd<-"Date of distribution __/__/____" note1<-"Note: All schedules issued before this, are cancelled" Year_o_Valid<-"Year: April 2019 to 2025" Issue<-"Issue Serial No:________/___" Jal_upbhokta<-"Jal Upbhokta Sangam:" d5 <-flextable::fit_to_width(flextable::flextable(row), max_width = 7, inc=1L, max_iter = 20) d5 <- flextable::add_header_lines(d5, c(paste(Year_o_Valid,"\t","\t", chak), paste(Jal_upbhokta, distributries, "\t","\t", Issue, "\t","\t","\t","\t", dateOI))) d5 <-flextable::add_footer_lines(d5, c(paste(dateOd, "\t", "\t", note1), paste("President", "\n", "\n", "\n", Jal_upbhokta, distributries))) #flextable::flextable_to_rmd(d5) })) ``` # Lets take a look at report for individual farmer ![](TableIndividual.png) # Contact us That's all! Thanks for being here. Let me know if you heve any doubt about this package or issue Harvinder Singh Department of pharmacology PGIMER, Chandigarh (160012) [email protected] ORCID https://orcid.org/0000-0002-6349-3143
/scratch/gouwar.j/cran-all/cranData/warabandi/inst/doc/warabandi.Rmd
--- title: "warabandi" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{warabandi} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- # Warabandi or Roster of Turn **Introduction:** This function will generate roster for a week (168 hrs. or 24X7). Flow time of a watercourse to an individual farmer calculate based on their holding area (bigga or hectares), This flow time roster generated by this function known as "warabandi" in canal irrigated agricultural areas (Punjab, Rajasthan, Haryana and Some areas of Pakistan) # Load Package ```{r setup} library(warabandi) ``` ## data structure of input data ```{r} head(warabandi_data) ``` #Calulation of roster Here we are not writing output to reduce vignettes and space ```{r} output<-warabandi(file = warabandi_data, output = FALSE, nof = "my_file.csv") ``` #Lets take a look at output Output generated by package is a list of different objects. 1. Flow time per unit area in minutes 2. Rakva or total area under command subject to be irrigated 3. Bharai or fillig time; as a compensation 4. Jharai or empty time 5. Weekdays or total duration has to be divided 6. Final table calculated by warabandi saved as a output file to the working directory ```{r} output[1:5] Report_Table<-data.frame(output[6]) head(Report_Table) ``` # Report generation of warabandi Generation of the report in printable format which can be supplied or distribut- ed among all the farmers. This step is highle depend on the external packages (knitr, flextable). Code chunk provide below is a sample which can be modified as per user need like header and fotters. Lets read output file generated by warabandi package ```{r} data2<-Report_Table ``` # Lets make table ```{r} flextable::flextable(head(data2)) ``` # Lets generate report for individual farmer ```{r} data3 <- data.frame(head(data2)) invisible(by(data3, seq_len(nrow((data3))), function(row) { chak<-"Chak-38 R.B" distributries<- "R.B II" dateOI<-date() dateOd<-"Date of distribution __/__/____" note1<-"Note: All schedules issued before this, are cancelled" Year_o_Valid<-"Year: April 2019 to 2025" Issue<-"Issue Serial No:________/___" Jal_upbhokta<-"Jal Upbhokta Sangam:" d5 <-flextable::fit_to_width(flextable::flextable(row), max_width = 7, inc=1L, max_iter = 20) d5 <- flextable::add_header_lines(d5, c(paste(Year_o_Valid,"\t","\t", chak), paste(Jal_upbhokta, distributries, "\t","\t", Issue, "\t","\t","\t","\t", dateOI))) d5 <-flextable::add_footer_lines(d5, c(paste(dateOd, "\t", "\t", note1), paste("President", "\n", "\n", "\n", Jal_upbhokta, distributries))) #flextable::flextable_to_rmd(d5) })) ``` # Lets take a look at report for individual farmer ![](TableIndividual.png) # Contact us That's all! Thanks for being here. Let me know if you heve any doubt about this package or issue Harvinder Singh Department of pharmacology PGIMER, Chandigarh (160012) [email protected] ORCID https://orcid.org/0000-0002-6349-3143
/scratch/gouwar.j/cran-all/cranData/warabandi/vignettes/warabandi.Rmd
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #' @title Calculates the absolute amplitude envelope #' @usage envelope(x, ssmooth = 0) #' @param x Numeric vector with amplitude values. Required. #' @param ssmooth Numeric vector of length 1 indicating the size of the sliding window use to smooth envelopes. Default is 0 (no smoothing). #' @return An amplitude envelope. #' @export #' @name envelope #' @details The function calculates the absolute amplitude envelope of an amplitude vector using compiled C code which is usually several times faster. #' @seealso \code{\link[seewave]{env}}. #' @rawNamespace useDynLib(warbleR) #' @examples{ #' data(tico) #' #' amp_env <- envelope(tico@left, ssmooth = 100) #' } #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) & Paula Monge NULL envelope <- function(x, ssmooth = 0L) { .Call('_warbleR_envelope', PACKAGE = 'warbleR', x, ssmooth) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/RcppExports.R
#' #' \code{auto_detec} automatically detects the start and end of vocalizations in sound files based #' on amplitude, duration, and frequency range attributes. #' @usage auto_detec(X = NULL, wl = 512, threshold = 15, parallel = 1, power = 1, #' output = 'data.frame', thinning = 1, path = NULL, pb = TRUE, ssmooth = 0, #' bp = NULL, flist = NULL, hold.time = 0, mindur = NULL, maxdur = NULL, envt = NULL, #' msmooth = NULL, osci = NULL, xl = NULL, picsize = NULL, res = NULL, flim = NULL, #' ls = NULL, sxrow = NULL, rows = NULL, redo = NULL, img = NULL, it = NULL, #' set = NULL, smadj = NULL, pal = NULL, fast.spec = NULL) #' @param X 'selection_table' object or a data frame with columns #' for sound file name (sound.files), selection number (selec), and start and end time of signal #' (start and end). If provided the detection will be conducted only within #' the selections in 'X'. Alternatively, an 'autodetec.output' object can be input. These objects are also generated by this function when \code{output = "list"}. If so the detection runs much faster as envelopes have been already calculated. #' @param wl A numeric vector of length 1 specifying the window used internally by #' \code{\link[seewave]{ffilter}} for bandpass filtering (so only applied when 'bp' is supplied). Default is 512. #' @param threshold A numeric vector of length 1 specifying the amplitude threshold for detecting #' signals (in \%). #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param power A numeric vector of length 1 indicating a power factor applied to the amplitude envelope. Increasing power will reduce low amplitude modulations and increase high amplitude modulations, in order to reduce background noise. Default is 1 (no change). #' @param output Character string indicating if the output should be a 'data.frame' with the detections (default) or a list (of class 'autodetec.output') containing both 1) the detections and 2) the amplitude envelopes (time vs amplitude) for each sound file. The list can be input into \code{\link{full_spectrograms}} to explore detections and associated amplitude envelopes. #' @param thinning Numeric vector of length 1 in the range 0~1 indicating the proportional reduction of the number of #' samples used to represent amplitude envelopes (i.e. the thinning of the envelopes). Usually amplitude envelopes have many more samples #' than those needed to accurately represent amplitude variation in time, which affects the size of the #' output (usually very large R objects / files). Default is \code{1} (no thinning). Higher sampling rates can afford higher size reduction (e.g. lower thinning values). Reduction is conducted by interpolation using \code{\link[stats]{approx}}. Note that thinning may decrease time precision, and the higher the thinning the less precise the time detection. #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @param ssmooth A numeric vector of length 1 to smooth the amplitude envelope #' with a sum smooth function. Default is 0. Note that smoothing is applied before thinning (see 'thinning' argument). #' @param bp Numeric vector of length 2 giving the lower and upper limits of a #' frequency bandpass filter (in kHz). Default is \code{NULL}. #' @param flist character vector or factor indicating the subset of files that will be analyzed. Ignored #' if X is provided. #' @param hold.time Numeric vector of length 1. Specifies the time range at which selections will be merged (i.e. if 2 selections are separated by less than the specified hold.time they will be merged in to a single selection). Default is \code{0}. #' @param mindur Numeric vector of length 1 giving the shortest duration (in #' seconds) of the signals to be detected. It removes signals below that #' threshold. #' @param maxdur Numeric vector of length 1 giving the longest duration (in #' seconds) of the signals to be detected. It removes signals above that #' threshold. #' @param osci DEPRECATED. #' @param msmooth DEPRECATED. #' @param envt DEPRECATED. #' @param xl DEPRECATED #' @param picsize DEPRECATED #' @param res DEPRECATED #' @param flim DEPRECATED #' @param ls DEPRECATED #' @param sxrow DEPRECATED #' @param rows DEPRECATED #' @param redo DEPRECATED. #' @param img DEPRECATED. #' @param it DEPRECATED. #' @param set DEPRECATED. #' @param smadj DEPRECATED. #' @param pal DEPRECATED. #' @param fast.spec DEPRECATED. #' @return A data frame containing the start and end of each signal by #' sound file and selection number. If 'output = "list"' then a list including 1) a detection data frame, 2) amplitude envelopes and 3) parameters will be return. An additional column 'org.selec' is added when 'X' is provided (so detection can be traced back to the selections in 'X'). #' @export #' @name auto_detec #' @details This function determines the start and end of signals in the sound file selections listed #' in the input data frame ('X'). Alternatively, if no data frame is provided, the function detects signals across #' each entire sound file. It can also create long spectrograms highlighting the start and of the detected #' signals for all sound files in the working directory (if \code{img = TRUE}). Sound files should be located in the #' working directory or the path to the sound files should be provided using the 'path' argument. The input #' data frame should have the following columns: c("sound.files","selec","start","end"). This function uses a modified version of the \code{\link[seewave]{timer}} function from seewave package to detect signals. Note that warbleR function for signal detection will be deprecated in future warbleR versions. Look at the ohun package for automatic signal detection functions. #' #' @examples { #' # Save to temporary working directory #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' #' ad <- auto_detec( #' threshold = 5, ssmooth = 300, #' bp = c(2, 9), wl = 300, path = tempdir() #' ) #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @seealso \code{\link{cross_correlation}} #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}). Implements a #' modified version of the timer function from seewave. auto_detec <- function(X = NULL, wl = 512, threshold = 15, parallel = 1, power = 1, output = "data.frame", thinning = 1, path = NULL, pb = TRUE, ssmooth = 0, bp = NULL, flist = NULL, hold.time = 0, mindur = NULL, maxdur = NULL, envt = NULL, msmooth = NULL, osci = NULL, xl = NULL, picsize = NULL, res = NULL, flim = NULL, ls = NULL, sxrow = NULL, rows = NULL, redo = NULL, img = NULL, it = NULL, set = NULL, smadj = NULL, pal = NULL, fast.spec = NULL) { warning2("This function will be deprecated in future warbleR versions, please look at the ohun package for automatic signal detection functions (https://marce10.github.io/ohun/index.html)") # message deprecated if (!is.null(smadj)) { warning2("'smadj' has been deprecated") } if (!is.null(envt)) { warning2("'envt' has been deprecated. Only absolute envelopes can be used now") } if (!is.null(msmooth)) { warning2("'msmooth' has been deprecated. Only 'ssmooth' is available for smoothing") } if (!is.null(img)) { warning2("'img' has been deprecated. Use full_spectrograms() to create images from auto_detec() output") } if (!is.null(xl)) { warning2("'xl' has been deprecated. Use full_spectrograms() to create images from auto_detec() output") } if (!is.null(picsize)) { warning2("'picsize' has been deprecated. Use full_spectrograms() to create images from auto_detec() output") } if (!is.null(flim)) { warning2("'flim' has been deprecated. Use full_spectrograms() to create images from auto_detec() output") } if (!is.null(rows)) { warning2("'rows' has been deprecated. Use full_spectrograms() to create images from auto_detec() output") } if (!is.null(sxrow)) { warning2("'sxrow' has been deprecated. Use full_spectrograms() to create images from auto_detec() output") } if (!is.null(osci)) { warning2("'osci' has been deprecated. Use full_spectrograms() to create images from auto_detec() output") } if (!is.null(res)) { warning2("'res' has been deprecated. Use full_spectrograms() to create images from auto_detec() output") } if (!is.null(ls)) { warning2("'ls' has been deprecated. Use full_spectrograms() to create images from auto_detec() output") } if (!is.null(redo)) { warning2("'redo' has been deprecated. Use full_spectrograms() to create images from auto_detec() output") } if (!is.null(it)) { warning2("'it' has been deprecated. Use full_spectrograms() to create images from auto_detec() output") } if (!is.null(set)) { warning2("'set' has been deprecated. Use full_spectrograms() to create images from auto_detec() output") } #### set arguments from options # get function arguments argms <- methods::formalArgs(auto_detec) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) { getOption("warbleR") } else { SILLYNAME <- 0 } # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path if not provided set to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # if bp is not vector or length!=2 stop if (!is.null(bp)) { if (!is.vector(bp)) { stop2("'bp' must be a numeric vector of length 2") } else { if (!length(bp) == 2) { stop2("'bp' must be a numeric vector of length 2") } } } # if ssmooth is not vector or length!=1 stop if (!is.vector(ssmooth)) { stop2("'ssmooth' must be a numeric vector of length 1") } else { if (!length(ssmooth) == 1) { stop2("'ssmooth' must be a numeric vector of length 1") } } # if thinning is not vector or length!=1 between 1 and 0 if (!is.vector(thinning) | !is.numeric(thinning)) { stop2("'thinning' must be a numeric vector of length 1") } if (thinning[1] > 1 | thinning[1] <= 0) { stop2("'thinning' must be greater than 0 and lower than or equal to 1") } # if wl is not vector or length!=1 stop if (is.null(wl)) { stop2("'wl' must be a numeric vector of length 1") } else { if (!is.vector(wl)) { stop2("'wl' must be a numeric vector of length 1") } else { if (!length(wl) == 1) { stop2("'wl' must be a numeric vector of length 1") } } } # if threshold is not vector or length!=1 stop if (is.null(threshold)) { if (!is.numeric(threshold)) { stop2("'threshold' must be a numeric vector of length 1") } else { if (!is.vector(threshold)) { stop2("'threshold' must be a numeric vector of length 1") } else { if (!length(threshold) == 1) { stop2("'threshold' must be a numeric vector of length 1") } } } } # if flist is not character vector if (!is.null(flist) & is.null(X) & any(!is.character(flist), !is.vector(flist))) { stop2("'flist' must be a character vector") } # if parallel is not numeric if (!is.numeric(parallel)) { stop2("'parallel' must be a numeric vector of length 1") } if (any(!(parallel %% 1 == 0), parallel < 1)) { stop2("'parallel' should be a positive integer") } # check hold time if (!is.numeric(hold.time)) { stop2("'hold.time' must be a numeric vector of length 1") } # stop if power is 0 if (power == 0) { stop2("'power' cannot equal to 0") } if (!is.null(X)) { # extract selection table and envelopes if (is(X, "autodetec.output")) { X.class <- "autodetec.output" if (pb) { message2(x = "Working on an 'autodetec.output' object", color = "cyan") } # warn if thinning is used twice if (!is.null(X$parameters$thinning) & pb) { if (X$parameters$thinning < 1 & thinning < 1) { message2(color = "cyan", x = "'thinning' was already applied when creating 'X'. Keep in mind that when 'thinning' is too high it can affect detection precision") } } # warn if thinning is used twice if (!is.null(X$parameters$ssmooth)) { if (X$parameters$ssmooth < 1 & !is.null(ssmooth) & pb) { message2(color = "cyan", x = "'smooth' was already applied when creating 'X'. Keep in mind that it won't be a 1:1 relation to amplitude samples any longer") } if (!is.null(X$parameters$thinning) & pb) { if (X$parameters$thinning < 1 & !is.null(ssmooth)) { message2(color = "cyan", x = "'thinning' was applied when creating 'X' so 'ssmooth' doesn't represent amplitude samples any longer") } } } # set variable to state S was provided xprov <- TRUE } else { X.class <- "selection.table" } # if is selection table if (X.class == "selection.table") { # if files not found if (length(list.files( path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE )) == 0) { if (is.null(path)) { stop2("No sound files in working directory") } else { stop2("No sound files found") } } # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X))) { stop2("X is not of a class 'data.frame' or 'selection_table'") } # check if all columns are found if (any(!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X)))) { stop2(paste(paste( c("sound.files", "selec", "start", "end")[!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))], collapse = ", " ), "column(s) not found in data frame")) } # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) { stop2("NAs found in start and/or end columns") } # if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) { stop2("'start' and 'end' must be numeric") } # if any start higher than end stop if (any(X$end - X$start <= 0)) { stop2(paste( "Start is higher than or equal to end in", length(which(X$end - X$start <= 0)), "case(s)" )) } # return warning if not all sound files were found fs <- list.files( path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE ) if (length(unique(X$sound.files[(X$sound.files %in% fs)])) != length(unique(X$sound.files))) { warning(paste( length(unique(X$sound.files)) - length(unique(X$sound.files[(X$sound.files %in% fs)])), "sound file(s) not found" )) } # count number of sound files in working directory and if 0 stop d <- which(X$sound.files %in% fs) if (length(d) == 0) { stop2("The sound files are not in the working directory") } else { X <- X[d, ] } xprov <- TRUE # to replace X if not provided } else { # extract selection table and envelopes as separate objects envelopes <- X$envelopes X <- X$org.selection.table } } else { if (!is.null(flist)) { X <- warbleR::duration_wavs(files = flist, path = path) } else { X <- warbleR::duration_wavs(path = path) } X$start <- 0 X$selec <- 1 names(X)[2] <- "end" xprov <- FALSE # to replace X if not provided if (nrow(X) == 0) { stop2("Files in 'flist' not in working directory") } X.class <- "selection.table" } # if parallel was not called if (pb) { message2("Detecting signals in sound files:") } # function for detecting signals adFUN <- function(i, X, wl, bp, envt, thinning, threshold, ssmooth, mindur, maxdur, output, power, X.class) { # set threshold as proportion thres <- threshold / 100 if (X.class == "selection.table") { # read wave object song <- warbleR::read_sound_file( X = X, path = path, index = i ) # set sample rate and duration f <- [email protected] # filter frequnecies below 1000 Hz if (!is.null(bp)) { f.song <- seewave::ffilter( song, f = f, from = bp[1] * 1000, to = bp[2] * 1000, bandpass = TRUE, wl = wl, output = "Wave" ) } else { f.song <- song } # detect songs based on amplitude (modified from seewave::timer function) amp_vector <- f.song@left n <- length(amp_vector) # extract envelope envp <- envelope( x = amp_vector, ssmooth = ssmooth ) # flat edges (first and last 100 ms) if lower than lowest amp value if (length(envp) > f / 5) { min.envp <- min(envp[(f / 10):(length(envp) - f / 5)]) if (envp[1] < min.envp) envp[1:min(which(envp >= min.envp))] <- min.envp if (envp[length(envp)] < min.envp) envp[max(which(envp >= min.envp)):length(envp)] <- min.envp } # force to be in the range 0-1 envp <- envp - min(envp) envp <- envp / max(envp) envp <- matrix(envp, ncol = 1) } # if autodetec output if (X.class == "autodetec.output") { # if is and autodetec.output object # extract envelopes from autodetec.output object if (is.null(X$org.selec)) { envp <- envelopes[envelopes$sound.files == X$sound.files[i], ] } else { envp <- envelopes[envelopes$sound.files == X$sound.files[i] & envelopes$org.selec == X$org.selec[i], ] } if (nrow(envp) == 0) stop2(paste("amplitude envelope not found for ", X$sound.files[i])) # set sample rate f <- nrow(envp) / (X$end[i] - X$start[i]) if (ssmooth > 0) { envelope(x = envp$amplitude, ssmooth = ssmooth) } # convert to matrix of 1 column as the output of env() envp <- matrix(data = envp$amplitude, ncol = 1) } # thin if (!is.null(thinning)) { # reduce size of envelope app_env <- stats::approx( x = seq(0, X$end[i] - X$start[i], length.out = nrow(envp)), y = envp[, 1], n = round(nrow(envp) * thinning), method = "linear" )$y # back into a 1 column matrix envp <- matrix(data = app_env, ncol = 1) f <- (X$end[i] - X$start[i]) / nrow(envp) } n <- nrow(envp) if (n < 2) stop2("thinning is too high, no enough samples left for at least 1 sound file") #### detection #### # add power if (power != 1) { envp <- envp^power envp <- envp / max(envp) } # get binary values if above or below threshold binary_treshold <- ifelse(envp <= thres, yes = 1, no = 2) n2 <- length(binary_treshold) cross <- sapply(2:length(binary_treshold), function(x) { if (binary_treshold[x] > binary_treshold[x - 1]) out <- "u" # u means going up if (binary_treshold[x] < binary_treshold[x - 1]) out <- "d" # d means going down if (binary_treshold[x] == binary_treshold[x - 1]) { if (binary_treshold[x] == 2) { out <- "a" } else { # a means above out <- "b" } } # b means below return(out) }) cross <- c(if (binary_treshold[1] == 1) "b" else "a", cross) # time series cross_ts <- ts(cross, start = X$start[i], end = X$end[i], frequency = length(cross) / (X$end[i] - X$start[i]) ) starts <- time(cross_ts)[cross_ts == "u"] ends <- time(cross_ts)[cross_ts == "d"] # if there are both starts and ends detected if (length(starts) > 0 & length(ends) > 0) { # if start is not the first detection if (starts[1] > ends[1]) starts <- c(0, starts) if (starts[length(starts)] > ends[length(ends)]) ends <- c(ends, X$end[i] - X$start[i]) } # if there is no end if (length(starts) > 0 & length(ends) == 0) ends <- X$end[i] - X$start[i] # if there is no start if (length(ends) > 0 & length(starts) == 0) starts <- 0 # put time of detection in data frame detec_tab <- data.frame( sound.files = X$sound.files[i], duration = if (length(starts) > 0) ends - starts else NA, org.selec = X$selec[i], # this one allows to relate to segments in a segmented sound file n X (several selection for the same sound file) selec = NA, start = if (length(starts) > 0) starts else NA, end = if (length(ends) > 0) ends else NA, stringsAsFactors = FALSE ) # remove signals based on duration if (!is.null(mindur)) { detec_tab <- detec_tab[detec_tab$duration > mindur, ] } if (!is.null(maxdur)) { detec_tab <- detec_tab[detec_tab$duration < maxdur, ] } if (nrow(detec_tab) > 0) { if (xprov) { detec_tab$selec <- paste(X$selec[i], 1:nrow(detec_tab), sep = "-") } else { detec_tab$selec <- 1:nrow(detec_tab) } } # if nothing was detected if (nrow(detec_tab) == 0) { detec_tab <- data.frame( sound.files = X$sound.files[i], duration = NA, org.selec = X$selec[i], selec = NA, start = NA, end = NA, stringsAsFactors = FALSE ) } if (output == "data.frame") { # return data frame or list return(detec_tab) } else { output_list <- list( selec.table = detec_tab, envelopes = data.frame( sound.files = X$sound.files[i], org.selec = X$selec[i], time = seq(X$start[i], X$end[i], along.with = envp), # abs.time = NA, amplitude = envp, stringsAsFactors = FALSE ) ) return(output_list) } } # Apply over each sound file # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makeCluster(parallel) } else { cl <- parallel } # run function over sound files or selections in loop ad <- pblapply_wrblr_int( pbar = pb, X = 1:nrow(X), cl = cl, FUN = function(i) { adFUN( i, X, wl, bp, envt, thinning, threshold, ssmooth, mindur, maxdur, output, power, X.class ) } ) if (output == "data.frame") { detections <- do.call(rbind, ad) } else { # if output is a list detections <- do.call(rbind, lapply(ad, "[[", 1)) # envelopes envelopes <- do.call(rbind, lapply(ad, "[[", 2)) # make sound files a factor to reduce size envelopes$sound.files <- as.factor(envelopes$sound.files) if (!xprov) { envelopes$org.selec <- NULL } } # remove NAs in detections detections <- detections[!is.na(detections$sound.files), ] # rename rows if (nrow(detections) > 0) { rownames(detections) <- 1:nrow(detections) } # remove org.selec if X was not provided if (!xprov) { detections$org.selec <- NULL } # merge selections based on hold time if (hold.time > 0 & nrow(detections) > 1) { # detections$end <- detections$end + hold.time detections$ovlp.sels <- NA # label overlapping signals (as in ovlp_sels()) # calculate overlapping selection after adding hope time for (e in 1:(nrow(detections) - 1)) { # if overlap if (detections$sound.files[e] == detections$sound.files[e + 1]) { if (detections$end[e] + hold.time >= detections$start[e + 1]) { if (all(is.na(detections$ovlp.sels))) { detections$ovlp.sels[c(e, e + 1)] <- 1 } else # return 1 if is the first overlap if (is.na(detections$ovlp.sels[e])) { # if current is NA add 1 detections$ovlp.sels[c(e, e + 1)] <- max(detections$ovlp.sels, na.rm = TRUE) + 1 } else { detections$ovlp.sels[e + 1] <- detections$ovlp.sels[e] } } } # otherwise use current for next } # subset non-overlapping and overlapping no_ovlp <- detections[is.na(detections$ovlp.sels), ] ovlp <- detections[!is.na(detections$ovlp.sels), ] # if some overlaps detected if (nrow(ovlp) > 0) { # loop to merge selections out <- pblapply_wrblr_int(pbar = pb, X = unique(ovlp$ovlp.sels), cl = cl, FUN = function(x) { # subset for one level Y <- ovlp[ovlp$ovlp.sels == x, ] # keep only one per overlapping group label Z <- Y[1, , drop = FALSE] # start is the minimum of all starts Z$start <- min(Y$start) # end is the maximum of all ends Z$end <- max(Y$end) # # omit merging if result is larger than maximum duration # if (Z$end - Z$start <= maxdur) # return(Z) else return(Y) return(Z) }) # put list together in a data frame ovlp <- do.call(rbind, out) # add non-overlapping selections detections <- rbind(ovlp, no_ovlp) # order selections by sound file and time detections <- detections[order(detections$sound.files, detections$start), ] } else { detections <- no_ovlp } # if not return non-overlapping } # remove extra column detections$ovlp.sels <- NULL # recalculate duration (gets messed up when using hold time) detections$duration[!is.na(detections$start)] <- detections$end[!is.na(detections$start)] - detections$start[!is.na(detections$start)] # output as data frame or list if (output == "data.frame") { return(detections) } else { output_list <- list( selection.table = detections, envelopes = envelopes, parameters = lapply(call.argms, eval), call = base::match.call(), org.selection.table = X, hop.size.ms = warbleR::read_sound_file(X, 1, header = TRUE, path = path)$sample.rate / wl, warbleR.version = packageVersion("warbleR") ) # add class autodetec class(output_list) <- c("list", "autodetec.output") return(output_list) } } ############################################################################################################## #' alternative name for \code{\link{auto_detec}} #' #' @keywords internal #' @details see \code{\link{auto_detec}} for documentation. \code{\link{autodetec}} will be deprecated in future versions. #' @export autodetec <- auto_detec ############################################################################################################## #' print method for class \code{autodetec.output} #' #' @param x Object of class \code{autodetec.output}, generated by \code{\link{auto_detec}}. #' @param ... further arguments passed to or from other methods. Ignored when printing selection tables. #' @keywords internal #' #' @export #' print.autodetec.output <- function(x, ...) { message2(x = paste("Object of class", cli::style_bold("'autodetec.output' \n")), "cyan") message2(x = paste(cli::style_bold("\nContains: \n"), "The output of the following", cli::style_italic("auto_detec()"), "call: \n"), "silver") cll <- paste0(deparse(x$call)) message2(cli::style_italic(gsub(" ", "", cll), "\n"), "silver") message2(x = paste(cli::style_bold("\nIncludes"), "(as elements in a list): \n* A selection table data frame ('selection.table') of detections with", nrow(x$selection.table), "rows and", ncol(x$selection.table), "columns: \n"), "silver") # print data frame # define columns to show cols <- if (ncol(x$selection.table) > 6) 1:6 else seq_len(ncol(x$selection.table)) kntr_tab <- knitr::kable(head(x$selection.table[, cols]), escape = FALSE, digits = 4, justify = "centre", format = "pipe") for (i in seq_len(length(kntr_tab))) message2(paste0(kntr_tab[i], "\n"), "silver") if (ncol(x$selection.table) > 6) message2(paste0("... ", ncol(x$selection.table) - 6, " more column(s) (", paste(colnames(x$selection.table)[7:ncol(x$selection.table)], collapse = ", "), ")"), "silver") if (nrow(x$selection.table) > 6) message2(paste0(if (ncol(x$selection.table) <= 6) "..." else "", " and ", nrow(x$selection.table) - 6, " more row(s) \n"), "silver") message2(paste("\n* A data frame ('envelopes',", nrow(x$envelopes), "rows) with the wave envelopes from", length(unique(x$envelopes$sound.files)), "sound file(s) included in the", cli::style_italic("auto_detec()"), "call \n"), "silver") message2(paste("\n* A selection table data frame ('org.selection.table') in which detections were run, with", nrow(x$org.selection.table), "rows and", ncol(x$selection.table), "columns \n"), "silver") if (any(names(x$parameters) == "thinning")) { message2(paste0("\n A thinning of ", x$parameters$thinning, " was applied to wave envelopes \n"), "silver") } # print warbleR version if (!is.null(x$warbleR.version)) { message2(paste0("\n Created by warbleR ", x$warbleR.version), "silver") } else { message2("\n Created by warbleR < 1.1.27", "silver") } }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/auto_detec.R
#' Convert a by-song extended selection table to by-element #' #' \code{by_element_est} converts a by-song extended selection table to by-element. #' @usage by_element_est(X, mar = 0.1, pb = FALSE, parallel = 1) #' @param X object of class 'extended_selection_table' (see \code{\link{selection_table}}). #' @param mar Numeric vector of length 1 specifying the margins (in seconds) #' adjacent to the start and end points of the selections when creating the ''by element' extended #' selection table. Default is 0.1. #' @param pb Logical argument to control progress bar. Default is \code{FALSE}. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @return A 'by element' extended selection table (see \code{\link{selection_table}}). #' @export #' @name by_element_est #' @details This function converts extended selection tables in 'by song' format (several selection per wave object) to a 'by element' format (one wave object per selection). #' @examples #' \dontrun{ #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' #' # create extended selection table #' by_song_est <- selection_table(lbh_selec_table, #' path = tempdir(), #' extended = TRUE, by.song = "song", confirm.extended = FALSE #' ) #' #' # conver o by element #' by_element_est <- by_element_est(by_song_est, mar = 0.05) #' } #' @family extended selection table manipulation #' @seealso \code{\link{mp32wav}}, \code{\link{fix_wavs}} #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) #' #last modification on nov-9-2022 (MAS) by_element_est <- function(X, mar = 0.1, pb = FALSE, parallel = 1) { # if X is not a data frame if (!is_extended_selection_table(X)) stop2("X is not of class 'extended_selection_table'") # if extended only by song if (!attributes(X)$by.song$by.song) stop2("extended selection tables must be created 'by.song' to be used in song.param()") #### set arguments from options # get function arguments argms <- methods::formalArgs(by_element_est) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # set clusters for windows OS and no soz if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # extract single wave object per row attributes(X)$wave.objects <- pblapply_wrblr_int(pbar = pb, X = seq_len(nrow(X)), FUN = function(x) { # reset time coordinates of sounds if lower than 0 o higher than duration stn <- X$start[x] - mar enn <- X$end[x] + mar mar1 <- mar if (stn < 0) { mar1 <- mar1 + stn stn <- 0 } # get sampling rate r <- warbleR::read_sound_file( X = X, index = x, path = NULL, header = TRUE ) mar2 <- mar1 + X$end[x] - X$start[x] if (enn > r$samples / r$sample.rate) { enn <- r$samples / r$sample.rate } # read sound and margin wav <- warbleR::read_sound_file( X = X, index = x, from = stn, to = enn, path = NULL ) return(wav) }) # fix check results check_res_list <- lapply(seq_len(nrow(X)), function(x) { check_res <- attributes(X)$check.res[attributes(X)$check.res$sound.files == X$sound.files[x] & attributes(X)$check.res$selec == X$selec[x], ] check_res$start <- if (check_res$mar.before < mar) check_res$mar.before else mar check_res$end <- check_res$start + check_res$duration check_res$mar.before <- check_res$start check_res$mar.after <- seewave::duration(attributes(X)$wave.objects[[x]]) - check_res$end check_res$sound.files <- paste(X$sound.files[x], X$selec[x], sep = "-") check_res$n.samples <- length(attributes(X)$wave.objects[[x]]@left) check_res$bits <- length(attributes(X)$wave.objects[[x]]@bit) check_res$wave.size <- object.size(attributes(X)$wave.objects[[x]]) check_res$selec <- 1 return(check_res) }) # fix attributes names(attributes(X)$wave.objects) <- X$sound.files <- paste(X$sound.files, X$selec, sep = "-") attributes(X)$check.results <- do.call(rbind, check_res_list) attributes(X)$by.song <- c(by.song = FALSE, song.column = NULL) attributes(X)$call <- base::match.call() attributes(X)$warbleR.version <- packageVersion("warbleR") # fix selec, start and end in X X$selec <- 1 X$start <- attributes(X)$check.results$start X$end <- attributes(X)$check.results$end return(X) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/by_element_est.R
#' Create catalogs of vocal signals #' #' \code{catalog} produces spectrograms of selections (signals) split into multiple rows and columns. #' @usage catalog(X, flim = NULL, nrow = 4, ncol = 3, same.time.scale = TRUE, #' collevels = seq(-40, 0, 1), ovlp = 50, parallel = 1, mar = 0.05, prop.mar = NULL, #' lab.mar = 1, wl = 512, wn = "hanning", gr = FALSE, pal = reverse.gray.colors.2, #' it = "jpeg", path = NULL, pb = TRUE, fast.spec = FALSE, res = 100, #' orientation = "v", labels = c("sound.files", "selec"), height = NULL, #' width = NULL, tags = NULL, tag.pal = list(temp.colors, heat.colors, topo.colors), #' legend = 3, cex = 1, leg.wd = 1, img.suffix = NULL, img.prefix = NULL, #' tag.widths = c(1, 1), hatching = 0, breaks = c(5, 5), group.tag = NULL, #' spec.mar = 0, spec.bg = "white", max.group.cols = NULL, sub.legend = FALSE, #' rm.axes = FALSE, title = NULL, by.row = TRUE, box = TRUE, highlight = FALSE, alpha = 0.5) #' @param X 'selection_table', 'extended_selection_table' or data frame with columns for sound file name (sound.files), selection number (selec), #' and start and end time of signal (start and end). Default is \code{NULL}. #' @param flim A numeric vector of length 2 indicating the highest and lowest #' frequency limits (kHz) of the spectrogram, as in #' \code{\link[seewave]{spectro}}. Default is \code{NULL}. #' @param nrow A numeric vector of length 1. Specifies number of rows. Default is 4. #' @param ncol A numeric vector of length 1. Specifies number of columns. Default is 3. #' @param same.time.scale Logical. Controls if all spectrograms are in the same time scale #' (i.e. have the same duration). #' @param collevels A numeric vector of length 3. Specifies levels to partition the #' amplitude range of the spectrogram (in dB). The more levels the higher the #' resolution of the spectrogram. Default is seq(-40, 0, 1). seq(-115, 0, 1) will produces spectrograms #' similar to other acoustic analysis software packages. #' @param ovlp Numeric vector of length 1 specifying \% of overlap between two #' consecutive windows, as in \code{\link[seewave]{spectro}}. Default is 50. High values of ovlp #' slow down the function but produce more accurate selection limits (when X is provided). #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param mar Numeric vector of length 1. Specifies the margins (in seconds) adjacent to the start and end points of selections, #' delineating spectrogram limits. Default is 0.05. #' @param prop.mar Numeric vector of length 1. Specifies the margins adjacent to the #' start and end points of selections as a proportion of the duration of the signal. If #' provided 'mar' argument is ignored. Default is \code{NULL}. Useful when having high #' variation in signal duration. Ignored if \code{same.time.scale = FALSE}. Must be > 0 and <= 1. #' @param lab.mar Numeric vector of length 1. Specifies the space allocated to labels and tags (the upper margin). Default is 1. #' @param wl A numeric vector of length 1 specifying the window length of the spectrogram, default #' is 512. #' @param wn Character vector of length 1 specifying the window function name. See \code{\link[seewave]{ftwindow}} #' for name options. Default is "hanning". #' @param gr Logical argument to add grid to spectrogram. Default is \code{FALSE}. #' @param pal Color palette function for spectrogram. Default is reverse.gray.colors.2. See #' \code{\link[seewave]{spectro}} for more palettes. Palettes as \code{\link[monitoR:specCols]{gray.2}} may work better when \code{fast.spec = TRUE}. #' @param it A character vector of length 1 giving the image type to be used. Currently only #' "tiff" and "jpeg" are admitted. Default is "jpeg". #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @param fast.spec Logical. If \code{TRUE} then image function is used internally to create spectrograms, which substantially #' increases performance (much faster), although some options become unavailable, as collevels, and sc (amplitude scale). #' This option is indicated for signals with high background noise levels. Palette colors \code{\link[monitoR:specCols]{gray.1}}, \code{\link[monitoR:specCols]{gray.2}}, #' \code{\link[monitoR:specCols]{gray.3}}, \code{\link[monitoR:specCols]{topo.1}} and \code{\link[monitoR:specCols]{rainbow.1}} (which should be imported from the package monitoR) seem #' to work better with 'fast.spec' spectrograms. Palette colors \code{\link[monitoR:specCols]{gray.1}}, \code{\link[monitoR:specCols]{gray.2}}, #' \code{\link[monitoR:specCols]{gray.3}} offer #' decreasing darkness levels. #' @param res Numeric argument of length 1. Controls image resolution. Default is 100 (faster) #' although 300 is recommended for publication/presentation quality. Note that high resolution #' produce significantly bigger image files. This could be problematic when creating pdf files #' using \code{\link{catalog}}. #' @param orientation String. Indicates whether a letter page size image is produced in vertical ('v' option) or #' horizontal orientation ('h' option). Note that width and height can also be specified. #' @param labels String vector. Provides the column names that will be used as labels above the corresponding spectrograms. #' @param height Numeric. Single value (in inches) indicating the height of the output image files. Default is 11 #' for vertical orientation. #' @param width Numeric. Single value (in inches) indicating the width of the output image files. Default is 8.5 #' for vertical orientation. #' @param tags String vector. Provides the column names that will be used for the color tagging legend above. Tags can also be numeric. Continuous variables would be break down in 10 color classes. #' @param tag.pal List of color palette function for tags. Should be of length 1, 2 or 3. Default is \code{list(temp.colors, heat.colors, topo.colors)}. #' @param legend A numeric vector of length 1 controlling a legend for color tags is added. #' Ignored if no tags are provided. Four values are allowed: #' \itemize{ #' \item \code{0}: No label #' \item \code{1}: Label for the first color tag #' \item \code{2}: Label for the second color tag #' \item \code{3}: Labels both color tags #' } #' Default is 3. Currently no legend can be set for group tags. Use labels instead. #' @param cex A numeric vector of length 1 giving the amount by which text #' (including labels and axis) should be magnified. Default is 1. #' @param leg.wd Numeric. Controls the width of the legend column. Default is 1. #' @param img.suffix A character vector of length 1 with a suffix (label) to add at the end of the names of #' image files. Default is \code{NULL} (no suffix). Useful to label catalogs from different individuals, #' species or sites. #' @param img.prefix A character vector of length 1 with a prefix (label) to add at the beginning of the names of #' image files. Default is \code{NULL} (no prefix). Useful to label catalogs from different individuals, #' species or sites and ensure they will be grouped together when sorted by file name. #' @param tag.widths A numeric vector of length 2 to control the relative width of the color tags (when 2 tags are provided). #' @param hatching A numeric vector of length 1 controlling cross-hatching is used for color tags. Several cross-hatching #' patterns are used to make tags with similar colors more distinguishable. Four values are allowed: #' \itemize{ #' \item \code{0}: No cross-hatching #' \item \code{1}: Cross-hatching the first color tag #' \item \code{2}: Cross-hatching the second color tag #' \item \code{3}: Cross-hatching both color tags #' } #' @param breaks Numeric vector of length 1 or 2 controlling the number of intervals in which a #' numeric tag will be divided. The numbers control the first and second tags respectively. #' Ignored if tags are not numeric. Default is \code{c(5, 5)}. #' @param group.tag Character vector of length 1 indicating the column name to be used to color #' the empty plot areas around the spectrograms. If provided selections that belong to the same #' tag level are clumped together in the catalog (the 'X' data frame is sorted by that column). #' This tags cannot be included in the legend so it would be better to use the label field to identify the different levels. #' @param spec.mar Numeric vector of length 1 to add space at the top, left and right sides of #' the spectrogram. Useful to better display the grouping of selections when 'group.tag' is #' provided. Internally applied for setting 'mar' using \code{\link[graphics]{par}}. #' @param spec.bg Character vector of length 1 to control the background color of the spectrogram. Default is 'white'. Ignored if \code{group.tag = NULL}. #' @param max.group.cols Numeric vector of length 1 indicating the number of different colors #' that will be used for group tags (see 'group.tag' argument). If provided (and the number is #' smaller than the number of levels in the 'group.tag' column) the colors will be recycled, #' although ensuring that adjacent groups do not share the same color. Useful when the #' 'group.tag' has many levels and the colors assigned become very similar. Default is \code{NULL}. #' @param sub.legend Logical. If \code{TRUE} then only the levels present on each #' page are shown in the legend. Default is \code{FALSE}. #' @param rm.axes Logical. If \code{TRUE} frequency and time axes are excluded. Default is \code{FALSE}. #' @param title Character vector of length 1 to set the title of catalogs. #' @param by.row Logical. If \code{TRUE} (default) catalogs are filled by rows. #' @param box Logical. If \code{TRUE} (default) a box is drawn around spectrograms and #' corresponding labels and tags. #' @param highlight Logical. If \code{TRUE} a transparent white layer is plotted on the spectrogram areas outside the selection. The level of transparency is controlled with the argument 'alpha'. Default is \code{FAlSE}. #' @param alpha Numeric vector of length 1 controlling the level of transparency when highlighting selections (i.e. when \code{highlight = TRUE}, see highlight argument. Default is 0.5. #' @return Image files with spectrogram catalogs in the working directory. Multiple pages #' can be returned, depending on the length of each sound file. #' @export #' @name catalog #' @details This functions aims to simplify the visual exploration of multiple vocalizations. The function plots a #' matrix of spectrograms from a selection table. Spectrograms can be labeled or color tagged to facilitate #' exploring variation related to a parameter of interest (e.g. location, song type). A legend will be added to #' help match colors with tag levels (if legend is > 0). Different color palettes can #' be used for each tag. Numeric tags are split in intervals (the number of intervals can be #' controlled with break argument). The width and height can also be adjusted to fit more column and/or rows. #' This files can be put together in a single pdf file with \code{\link{catalog2pdf}}. #' We recommend using low resolution (~60-100) and smaller dimensions (width & height < 10) if #' aiming to generate pdfs (otherwise pdfs could be pretty big). #' @seealso \code{\link{catalog2pdf}} #' @examples #' \dontrun{ #' # save sound file examples #' data(list = c("Phae.long1", "Phae.long2","lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' #' #' catalog(X = lbh_selec_table, flim = c(1, 10), nrow = 4, ncol = 2, same.time.scale = T, #' ovlp = 90, parallel = 1, mar = 0.01, wl = 200, gr = FALSE, #' orientation = "v", labels = c("sound.files", "selec"), legend = 0, #' path = tempdir()) #' #' #different time scales and tag palette #' catalog(X = lbh_selec_table, flim = c(1, 10), nrow = 4, ncol = 2, same.time.scale = F, #' ovlp = 90, parallel = 1, mar = 0.01, wl = 200, #' orientation = "v", labels = c("sound.files", "selec"), legend = 0, #' tag.pal = list(terrain.colors), #' path = tempdir()) #' #' #adding tags and changing spectro palette #' catalog(X = lbh_selec_table, flim = c(1, 10), nrow = 4, ncol = 2, same.time.scale = F, #' ovlp = 90, parallel = 1, mar = 0.01, wl = 200, pal = reverse.heat.colors, #' orientation = "v", labels = c("sound.files", "selec"), legend = 1, #' tag.pal = list(terrain.colors), tags = "sound.files", #' path = tempdir()) #' #' #create a bigger selection table #' X <- rbind(lbh_selec_table, lbh_selec_table, lbh_selec_table, lbh_selec_table) #' X <- rbind(X, X) #' #' #create some simulated labels #' X$songtype <- sample(letters[13:15], nrow(X), replace = T) #' X$indiv <- sample(letters[1:12], nrow(X), replace = T) #' #' # 12 columns in 5 rows, 2 tags #' catalog(X = X, flim = c(1, 10), nrow = 5, ncol = 12, same.time.scale = F, #' ovlp = 90, parallel = 1, mar = 0.01, wl = 200, #' orientation = "v", labels = c("sound.files", "selec"), legend = 3, #' collevels = seq(-65, 0, 5), tag.pal = list(terrain.colors), tags = c("songtype", "indiv"), #' path = tempdir()) #' #' # with legend #' catalog(X = X, flim = c(1, 10), nrow = 5, ncol = 12, same.time.scale = F, #' ovlp = 90, parallel = 1, mar = 0.01, wl = 200, gr = FALSE, #' orientation = "v", labels = c("sound.files", "selec"), legend = 3, #' width = 20, collevels = seq(-65, 0, 5), tag.pal = list(terrain.colors), #' tags = c("songtype", "indiv"), #' path = tempdir()) #' #' # horizontal orientation #' catalog(X = X, flim = c(1, 10), nrow = 5, ncol = 12, same.time.scale = F, #' ovlp = 90, parallel = 1, mar = 0.01, wl = 200, gr = FALSE, #' orientation = "h", labels = c("sound.files", "selec"), legend = 3, #' width = 20, collevels = seq(-65, 0, 5), tag.pal = list(terrain.colors), #' tags = c("songtype", "indiv"), #' path = tempdir()) #' #' check this floder #' tempdir() #' } #' @references {Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191.} #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) #last modification on feb-09-2017 (MAS) catalog <- function(X, flim = NULL, nrow = 4, ncol = 3, same.time.scale = TRUE, collevels = seq(-40, 0, 1), ovlp = 50, parallel = 1, mar = 0.05, prop.mar = NULL, lab.mar = 1, wl = 512, wn = "hanning", gr = FALSE, pal = reverse.gray.colors.2, it = "jpeg", path = NULL, pb = TRUE, fast.spec = FALSE, res = 100, orientation = "v", labels = c("sound.files", "selec"), height = NULL, width = NULL, tags = NULL, tag.pal = list(temp.colors, heat.colors, topo.colors), legend = 3, cex = 1, leg.wd = 1, img.suffix = NULL, img.prefix = NULL, tag.widths = c(1, 1), hatching = 0, breaks = c(5, 5), group.tag = NULL, spec.mar = 0, spec.bg = "white", max.group.cols = NULL, sub.legend = FALSE, rm.axes = FALSE, title = NULL, by.row = TRUE, box = TRUE, highlight = FALSE, alpha = 0.5) { #### set arguments from options # get function arguments argms <- methods::formalArgs(catalog) # get warbleR options opt.argms <- if(!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) for (q in seq_len(length(opt.argms))) assign(names(opt.argms)[q], opt.argms[[q]]) #if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X))) stop2("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") #check path to working directory if (is.null(path)) path <- getwd() else if (!dir.exists(path)) stop2("'path' provided does not exist") else path <- normalizePath(path) #read files if (!is_extended_selection_table(X)) { #return warning if not all sound files were found recs.wd <- list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE) if (length(unique(X$sound.files[(X$sound.files %in% recs.wd)])) != length(unique(X$sound.files))) (paste(length(unique(X$sound.files))-length(unique(X$sound.files[(X$sound.files %in% recs.wd)])), "sound file(s) not found")) #count number of sound files in working directory and if 0 stop d <- which(X$sound.files %in% recs.wd) if (length(d) == 0){ stop2("The sound files are not in the working directory") } else { X <- X[d, ] } } else X.orig <- X # expand arguments for spec_param if (is.null(X$...ovlp...)) X$...ovlp... <- ovlp if (is.null(X$...wl...)) X$...wl... <- wl if (is.null(X$...wn...)) X$...wn... <- wn #set collevels for spec_param if (collevels[1] != "collev.min") X$collev.min <- collevels[1] else collevels <- NULL #nrow must be equal or higher than 2 if (nrow < 2) stop2("number of rows must be equal or higher than 2") #rows must be equal or higher than 2 if (ncol < 1) stop2("number of columns (ncol) must be equal or higher than 1") #missing columns if (!all(c("sound.files", "selec", "start", "end") %in% colnames(X))) stop2(paste(paste(c("sound.files", "selec", "start", "end")[!(c("sound.files", "selec", "start", "end") %in% colnames(X))], collapse=", "), "column(s) not found in data frame")) #tag.pal must be a color function if (!is.list(tag.pal) & !is.null(tag.pal)) stop2("'tag.pal' must be a list of color palette functions of length 1, 2 or 3") if (length(tag.pal) == 1) tag.pal[[2]] <- tag.pal[[1]] if (length(tag.pal) == 2 & !is.null(group.tag)) tag.pal[[3]] <- tag.pal[[2]] if (!is.null(max.group.cols) & length(tag.pal) == 3) {fc <- tag.pal[[3]](max.group.cols) tag.pal[[3]] <- function(n) rep(fc, ceiling(n/max.group.cols))[1:n]} if (length(breaks) == 1) breaks[2] <- breaks[1] #pal must be a color function if (is.function(unlist(pal))) X$pal <- list(pal) # orientation if (!orientation %in% c("v", "h")) stop2("orientation should be either 'v' or 'h'") #missing label columns if (!all(labels %in% colnames(X))) stop2(paste(paste(labels[!(labels %in% colnames(X))], collapse=", "), "label column(s) not found in data frame")) #if tags> 2 if (length(tags) > 2) stop2("No more than 2 tags can be used at a time") #missing tag columns if (!all(tags %in% colnames(X))) stop2(paste(paste(tags[!(tags %in% colnames(X))], collapse=", "), "tag column(s) not found in data frame")) #missing tag columns if (!all(tags %in% colnames(X))) stop2(paste(paste(tags[!(tags %in% colnames(X))], collapse=", "), "tag column(s) not found in data frame")) #if NAs in tags if (!is.null(tags)) if (anyNA(X[,tags])) stop2("NAs are not allowed in tag columns") if (!is.null(group.tag)){ if (!group.tag %in% colnames(X)) stop2("group.tag column not found in data frame") else X <- X[order(X[[group.tag]]),] if (is.numeric(X[, group.tag])) stop2("group tag cannot be numeric") if (anyNA(X[,group.tag])) stop2("NAs are not allowed in 'group.tag' column") } #if sel.comment column not found create it if (is.null(X$sel.comment) & !is.null(X)) X <- data.frame(X,sel.comment="") #if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop2("NAs found in start and/or end") #if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) stop2("'start' and 'end' must be numeric") #if any start higher than end stop if (any(X$end - X$start <= 0)) stop2(paste("Start is higher than or equal to end in", length(which(X$end - X$start <= 0)), "case(s)")) #if it argument is not "jpeg" or "tiff" if (!any(it == "jpeg", it == "tiff")) stop2(paste("Image type", it, "not allowed")) #if flim is not vector or length!=2 stop if (is.null(flim)) { if (!is.vector(flim)) stop2("'flim' must be a numeric vector of length 2") else if (!length(flim) == 2) stop2("'flim' must be a numeric vector of length 2")} #if wl is not vector or length!=1 stop if (is.null(wl)) stop2("'wl' must be a numeric vector of length 1") else { if (!is.vector(wl)) stop2("'wl' must be a numeric vector of length 1") else{ if (!length(wl) > 2) wl <- wl[1]}} #if rows is not vector or length!=1 stop if (is.null(nrow)) stop2("'nrow' must be a numeric vector of length 1") else { if (!is.vector(nrow)) stop2("'nrow' must be a numeric vector of length 1") else{ if (!length(nrow) == 1) stop2("'nrow' must be a numeric vector of length 1")}} #if ncol is not vector or length!=1 stop if (is.null(ncol)) stop2("'ncol' must be a numeric vector of length 1") else { if (!is.vector(ncol)) stop2("'ncol' must be a numeric vector of length 1") else{ if (!length(ncol) == 1) stop2("'ncol' must be a numeric vector of length 1")}} # if levels are shared between tags if (length(tags) == 2) if (any(unique(X[ ,tags[1]]) %in% unique(X[ ,tags[2]]))) stop2("Tags cannot contained levels with the same labels") #legend if (!is.numeric(legend) | legend < 0 | legend > 3) stop2("legend should be be a value between 0 and 3") #lab.mar if (!is.numeric(lab.mar) | lab.mar < 0) stop2("lab.mar should be >= 0") #prop.mar if (!is.null(prop.mar)) { if (prop.mar < 0) stop2("prop.mar should be > 0 and <= 1") # if (!same.time.scale){ # prop.mar <- NULL # message2("'prop.mar' ignored as same.time.scale = FALSE") # } } #spec.mar if (!is.numeric(spec.mar) | spec.mar < 0) stop2("spec.mar should be >= 0") #hatching if (!is.numeric(hatching) | hatching < 0 | hatching > 3) stop2("hatching should be be a value between 0 and 3") #set dimensions if (is.null(width)) {if (orientation == "v") width <- 8.5 else width <- 11} if (is.null(height)) {if (orientation == "h") height <- 8.5 else height <- 11} #fix hatching based on tags if (length(tags) == 1 & hatching == 2) hatching <- 0 if (length(tags) == 1 & hatching == 3) hatching <- 1 if (is.null(tags)) hatching <- 0 #box colors if (!is.null(tags)) { if (length(tags) == 1 & legend == 2) legend <- 0 #convert to character Y <- as.data.frame(rapply(X, as.character, classes="factor", how="replace"), stringsAsFactors = FALSE) #if tag is numeric if (is.numeric(X[, tags[1]])) { if (is.integer(X[, tags[1]])) { if ( length(unique(X[, tags[1]])) > 1) boxcols <- tag.pal[[1]](length(unique(X[, tags[1]])))[as.numeric(cut(X[, tags[1]],breaks = length(unique(X[, tags[1]]))))] else boxcols <- tag.pal[[1]](1) } else boxcols <- tag.pal[[1]](breaks[1]) } else boxcols <- tag.pal[[1]](length(unique(Y[, tags[1]]))) if (length(tags) == 2) { boxcols <- c(boxcols, tag.pal[[2]](length(unique(Y[, tags[2]])))) } #convert characters to factors X <- as.data.frame(rapply(X, as.factor, classes="character", how="replace")) X$col1 <- X[,tags[1]] if (is.numeric(X[,tags[1]]) & !is.integer(X[,tags[1]])) { X$col1 <- rev(tag.pal[[1]](breaks[1]))[as.numeric(cut(X[, tags[1]],breaks = breaks[1]))] X$col.numeric1 <- cut(X[, tags[1]],breaks = breaks[1]) } else { X$col1 <- as.factor(X$col1) X$col1 <- droplevels(X$col1) levels(X$col1) <- boxcols[seq_len(length(unique(X$col1)))] } #add to df for legend if (is.numeric(X[,tags[1]]) & !is.integer(X[,tags[1]])) tag.col.df <- X[!duplicated(X[,"col.numeric1"]), c("col.numeric1", "col1")] else tag.col.df <- X[!duplicated(X[,tags[1]]), c(tags[1], "col1")] tag.col.df$tag.col <- tags[1] names(tag.col.df) <- c("tag", "col", "tag.col") if (length(tags) == 2) { X$col2 <- X[,tags[2]] if (is.numeric(X[,tags[2]]) & !is.integer(X[,tags[2]])) { X$col2 <- rev(tag.pal[[2]](breaks[2]))[as.numeric(cut(X[, tags[2]],breaks = breaks[2]))] X$col.numeric2 <- cut(X[, tags[2]],breaks = breaks[2]) } else { X$col2 <- as.factor(X$col2) X$col2 <- droplevels(X$col2) levels(X$col2) <- boxcols[(length(unique(X$col1))+1):length(boxcols)] } if (is.numeric(X[,tags[2]]) & !is.integer(X[,tags[2]])) W <- X[!duplicated(X[ ,"col.numeric2"]), c("col.numeric2", "col2")] else W <- X[!duplicated(X[,tags[2]]), c(tags[2], "col2")] W$tag.col <- tags[2] names(W) <- c("tag", "col", "tag.col") W$tag <- as.character(W$tag) tag.col.df <- rbind(tag.col.df, W) } # add hatching lines for color tags if (hatching == 0 | is.null(tags)) { tag.col.df$pattern <- "no.pattern" X$pattern.1 <- "no.pattern" X$pattern.2 <- "no.pattern" } else { tag.col.df$pattern <- rep(c("diamond", "grid", "forward", "backward", "horizontal", "vertical"), ceiling(nrow(tag.col.df)/6))[1:nrow(tag.col.df)] if (hatching == 1 & length(tags) == 2) {if (is.numeric(X[,tags[2]]) & !is.integer(X[,tags[2]])) tag.col.df$pattern[tag.col.df$tag %in% as.character(X$col.numeric2)] <- "no.pattern" else tag.col.df$pattern[tag.col.df$tag %in% X[,tags[2]]] <- "no.pattern" } if (hatching == 2 & length(tags) == 2) if (is.numeric(X[,tags[1]]) & !is.integer(X[,tags[1]])) tag.col.df$pattern[tag.col.df$tag %in% as.character(X$col.numeric1)] <- "no.pattern" else tag.col.df$pattern[tag.col.df$tag %in% X[,tags[1]]] <- "no.pattern" } X <- do.call(rbind, lapply(1:nrow(X), function(x) { W <- X[x, ] if (is.numeric(X[,tags[1]]) & !is.integer(X[,tags[1]])) W$pattern.1 <-tag.col.df$pattern[tag.col.df$tag == as.character(W$col.numeric1)] else W$pattern.1 <- tag.col.df$pattern[tag.col.df$tag == as.character(W[,tags[1]])] if (length(tags) == 2) { if (is.numeric(X[,tags[2]]) & !is.integer(X[,tags[2]])) W$pattern.2 <-tag.col.df$pattern[tag.col.df$tag == as.character(W$col.numeric2)] else W$pattern.2 <- tag.col.df$pattern[tag.col.df$tag == as.character(W[,tags[2]])] } else Y$pattern.2 <- "no.pattern" return(W) })) tag.col.df <- as.data.frame(rapply(tag.col.df, as.character, classes="factor", how="replace"), stringsAsFactors = FALSE) } else legend <- 0 # grouping color if (!is.null(group.tag)) { #convert to character Y <- as.data.frame(rapply(X, as.character, classes="factor", how="replace")) #if tag is numeric grcl <- tag.pal[[3]](length(unique(Y[, group.tag]))) #convert characters to factors X <- rapply(X, as.factor, classes="character", how="replace") X$colgroup <- X[,group.tag] X$colgroup <- droplevels(as.factor(X$colgroup)) levels(X$colgroup) <- grcl[seq_len(length(unique(X$colgroup)))] } ## repair sel table if (exists("X.orig")) X <- fix_extended_selection_table(X = as.data.frame(X), Y = X.orig) #calculate time and freq ranges based on all recs rangs <- lapply(1:nrow(X), function(i){ r <- read_sound_file(X = X, path = path, index = i, header = TRUE) f <- r$sample.rate # change mar to prop.mar (if provided) adj.mar <- if (!is.null(prop.mar)) (X$end[i] - X$start[i]) * prop.mar else mar t <- c(X$start[i] - adj.mar, X$end[i] + adj.mar) if (t[1] < 0) t[1] <- 0 if (t[2] > r$samples/f) t[2] <- r$samples/f #in case flim its higher than can be due to sampling rate fl <- flim if (is.null(fl)) fl <- c(0, ceiling(f / 2000) - 1) if (fl[2] > ceiling(f / 2000) - 1) fl[2] <- ceiling(f / 2000) - 1 return(data.frame(fl1 = fl[1], fl2 = fl[2], mardur = t[2] - t[1])) }) rangs <- do.call(rbind, rangs) flim[2] <- min(rangs$fl2) # adjust times if same.time.scale = T if (same.time.scale) { X2 <- lapply(1:nrow(X), function(x) { Y <- as.data.frame(X)[x, ] Y$orig.end <- Y$end Y$orig.start <- Y$start dur <- Y$end - Y$start if (dur < max(rangs$mardur)) { Y$end <- Y$end + (max(rangs$mardur) - dur)/2 Y$start <- Y$start - (max(rangs$mardur) - dur)/2 if (Y$start < 0) { Y$end <- Y$end - Y$start Y$start <- 0 } } return(Y) }) X <- do.call(rbind, X2) if (exists("X.orig")) X <- fix_extended_selection_table(X = as.data.frame(X), Y = X.orig) on.exit(message2(paste0("Time range: ", round(max(X$end - X$start) + (2 * mar), 3), "s;", " frequency range: ", min(rangs$fl1), "-", flim[2], " kHz"))) } # function to run on data frame subset catalFUN <- function(X, nrow, ncol, page, labels, grid, fast.spec, flim,pal, width, height, tag.col.df, legend, cex, img.suffix, img.prefix, title) { #set layout for screensplit #rows if (is.null(tags)) rws <- rep(c(5, (nrow / 8) * lab.mar), nrow) else rws <- rep(c(5, (nrow / 4) * lab.mar), nrow) if (same.time.scale) rws <- c((nrow / 1.7) * lab.mar, rws) else rws <- c((nrow / 8) * lab.mar, rws) #define row width csrws <- cumsum(rws) rws <- csrws/max(csrws) minrws <- min(rws) tp <- sort(rws[-1], decreasing = TRUE) tp <- rep(tp, each = ncol + 1) btm <- c(sort(rws[-length(rws)], decreasing = TRUE)) btm <- rep(btm, each = ncol + 1) #columns lfcol.width <- ncol / 27 faxis.width <- ncol / 37 if (faxis.width < 0.2) faxis.width <- 0.2 if (ncol > 1) { spectroclms <- c(lfcol.width, faxis.width, rep(1, ncol)) csclms <- cumsum(spectroclms) cls <- csclms/max(csclms) lf <- c(0, cls[-length(cls)]) rgh <- cls } else { lf <- c(0, lfcol.width, 0.014 + lfcol.width) rgh <- c(lfcol.width, 0.014 + lfcol.width, 1) } lf <- lf[-1] rgh <- rgh[-1] #duplicate for label box and spectro lf <- rep(lf, length(btm)/(ncol + 1)) rgh <- rep(rgh, length(btm)/(ncol + 1)) #put them together m <- cbind(lf, rgh, btm, tp) m <- m[order(m[,1], -m[,4]),] m <- m[c(((nrow * 2) + 1):((ncol + 1) * nrow * 2), 1:(nrow * 2)), ] #set parameters used to pick up spectros with freq axis minlf <- sort(unique(m[,1]))[2] minbtm <- min(m[,3]) #add freq col for freq axis m <- rbind(m, c(0, min(m[,1]), 0, 1)) #add bottom row for time axis m <- rbind(m, c(minlf, 1, 0, minbtm)) fig.type <- c(rep(c("lab", "spec"), nrow * ncol), rep("freq.ax", nrow * 2), c("flab", "tlab")) #remove axis space if (rm.axes) { m <- m[!fig.type %in% c("flab", "tlab", "freq.ax"),] m[,2] <- m[,2] - min(m[,1]) m[,1] <- m[,1] - min(m[,1]) m[,1] <- m[,1]/max(m[,2]) m[,2] <- m[,2]/max(m[,2]) m[,4] <- m[,4] - min(m[,3]) m[,3] <- m[,3] - min(m[,3]) m[,3] <- m[,3]/max(m[,4]) m[,4] <- m[,4]/max(m[,4]) # minlf <- min(m[,1]) fig.type <- fig.type[!fig.type %in% c("flab", "tlab", "freq.ax")] } #add legend col if (legend > 0) { leg.wd <- 1.08 + leg.wd/100 m <- rbind(m, c(1, leg.wd, 0, 1)) m[,1] <- m[,1]/leg.wd m[,2] <- m[,2]/leg.wd fig.type <- c(fig.type, "legend") } if (!is.null(title)) { m <- rbind(m, c(0, 1, 1, 1.05)) m[,3] <- m[,3]/1.05 m[,4] <- m[,4]/1.05 fig.type <- c(fig.type, "title") } X3 <- X3.1 <- X[rep(1:nrow(X), each = 2), ] #convert factors to character X3 <- data.frame(rapply(X3, as.character, classes="factor", how="replace"), stringsAsFactors = FALSE) if (is_extended_selection_table(X3.1)) X3 <- fix_extended_selection_table(X3, X3.1) #start graphic device if (!is.null(img.suffix)) img.suffix <- paste0("-", img.suffix) if (!is.null(img.prefix)) img.prefix <- paste0(img.prefix, "-") img_wrlbr_int(filename = paste0(img.prefix, "Catalog_p", page, img.suffix, ".", it), units = "in", width = width, height = height, res = res, path = path) # sort by row if (by.row) { c1 <- seq(1, nrow * ncol * 2, by = nrow * 2) neor2 <- neor <- sort(c(c1, c1 + 1)) for(i in 1:nrow) neor2 <- c(neor2, neor + i * 2) neor2 <- neor2[!duplicated(neor2)] neor2 <- neor2[1:(nrow * ncol * 2)] m <- m[c(neor2, which(!1:nrow(m) %in% neor2)),] } # split graphic window invisible(close.screen(all.screens = TRUE)) split.screen(figs = m) #testing layout screens # for(i in 1:nrow(m)) # {screen(i) # par( mar = rep(0, 4)) # plot(0.5, xlim = c(0,1), ylim = c(0,1), type = "n", axes = FALSE, xlab = "", ylab = "", xaxt = "n", yaxt = "n") # box() # text(x = 0.5, y = 0.5, labels = i) # } # close.screen(all.screens = T) #selec which screens will be plot if X has less signals than the maximum in the plot if (nrow(X) < nrow * ncol) sqplots <- c(1:(nrow(X) * 2), which(!fig.type %in% c("spec", "lab", "freq.ax"))) else sqplots <- which(!fig.type %in% "freq.ax") out <- lapply(sqplots, function(i) { if (fig.type[i] %in% c("lab", "spec") & !is.null(group.tag)) par(bg = X3$colgroup[i], new = TRUE) else par(bg = "white", new = TRUE) screen(i) if (fig.type[i] == "spec") #plot spectros { #Read sound files, initialize frequency and time limits for spectrogram r <- warbleR::read_sound_file(X = X3, path = path, index = i, header = TRUE) f <- r$sample.rate # change mar to prop.mar (if provided) adj.mar <- if (!is.null(prop.mar))(X3$end[i] - X3$start[i]) * prop.mar else mar t <- c(X3$start[i] - adj.mar, X3$end[i] + adj.mar) if (t[1] < 0) t[1] <- 0 if (t[2] > r$samples/f) t[2] <- r$samples/f rec <- warbleR::read_sound_file(X = X3, path = path, index = i, from = t[1], to = t[2]) #add xaxis to bottom spectros if (!same.time.scale & !rm.axes) { axisX = TRUE btm = 2.6 } else { axisX = FALSE btm = 0 } #add f axis ticks if (m[i,1] == min(m[fig.type == "spec",1]) & !rm.axes) axisY <- TRUE else axisY <- FALSE par(mar = c(btm, rep(spec.mar, 3))) if (!is.null(group.tag)) plot(x=-1, y=-1, axes = FALSE,col = spec.bg, xlab = "", ylab = "", xaxt = "n", yaxt = "n", type = "n", panel.first={points(0, 0, pch=16, cex=1e6, col = spec.bg)}) # draw spectro if (fast.spec & !is.null(group.tag)) par(bg = X3$colgroup[i], new = TRUE) spectro_wrblr_int2(wave = rec, f = [email protected], flim = flim, wl = X3$...wl...[i], wn = X3$...wn...[i], ovlp = X3$...ovlp...[i], axisX = axisX, axisY = axisY, tlab = NULL, flab = NULL, palette = X3$pal[i], fast.spec = fast.spec, main = NULL, grid = gr, rm.zero = TRUE, cexlab = cex * 1.2, collevels = collevels, collev.min = X3$collev.min[i], cexaxis = cex * 1.2, add = TRUE) #add transparent boxes around to highlight signals if (highlight){ if (!same.time.scale) sig.pos <- c(adj.mar - (t[1] - (X3$start[i] - adj.mar)), X3$end[i] - X3$start[i] + adj.mar - (t[1] - (X3$start[i] - adj.mar))) else sig.pos <- c(adj.mar - (t[1] - (X3$orig.start[i] - adj.mar)), X3$orig.end[i] - X3$orig.start[i] + adj.mar - (t[1] - (X3$orig.start[i] - adj.mar))) rect(xleft = c(par("usr")[1], sig.pos[2]), xright = c(sig.pos[1], par("usr")[2]), ybottom = flim[1], ytop = flim[2], border = NA, col = adjustcolor("white", alpha.f = alpha)) if (!is.null(X3$bottom.freq[i])) rect(xleft = sig.pos[c(1, 1)], xright = sig.pos[c(2, 2)], ybottom = c(flim[1], X3$top.freq[i]), ytop = c(X3$bottom.freq[i], flim[2]), border = NA, col = adjustcolor("white", alpha.f = alpha)) } #add box if (box) boxw_wrblr_int(xys = m[i,], bty = "u", lwd = 1.5) } if (fig.type[i] == "lab") #plot labels { par(mar = rep(0, 4)) plot(0.5, xlim = c(0, 1), ylim = c(0, 1), type = "n", axes = FALSE, xlab = "", ylab = "", xaxt = "n", yaxt = "n") #color boxes if (!is.null(tags)) { #plot labels text(x = 0.5, y = 0.8, labels = paste(X3[i, labels], collapse = " "), cex = (ncol * nrow * 1.5 * cex)/((ncol * nrow)^1.2)) cutbox1 <- 0 cutbox2 <- tag.widths[1]/(tag.widths[1] + tag.widths[2]) lim <- par("usr") if (length(tags) == 1) rectw_wrblr_int(xl = lim[1] + cutbox1 + spec.mar/20, yb = lim[3], xr = lim[2] - spec.mar/20, yt = 0.5, bor = "black", lw = 0.7, cl = X3$col1[i], den = 10, ang = NULL, pattern = X3$pattern.1[i]) else { rectw_wrblr_int(xl = lim[1] + cutbox1 + spec.mar/20, yb = lim[3], xr = cutbox2, yt = 0.5, bor = "black", lw = 0.7, cl = X3$col1[i], den = 10, ang = NULL, pattern = X3$pattern.1[i]) rectw_wrblr_int(xl = cutbox2, yb = lim[3], xr = lim[2] - spec.mar/20, yt = 0.5, bor = "black", lw = 0.7, cl = X3$col2[i], den = 10, ang = NULL, pattern = X3$pattern.2[i]) } } else text(x = 0.5, y = 0.33, labels = paste(X3[i, labels], collapse = " "), cex = (ncol * nrow * 2 * cex)/((ncol * nrow)^1.2)) if (box) boxw_wrblr_int(xys = m[i,], bty = "^", lwd = 1.5) } #add Freq axis label if (fig.type[i] == "flab") { par(mar = c(0, 0, 0, 0), bg = "white", new = T) plot(1, frame.plot = FALSE, type = "n") text(x = 1, y = 1.05, "Frequency (kHz)", srt = 90, cex = 1.2 * cex) } #add time axis label if (fig.type[i] == "tlab") { par(mar = c(0, 0, 0, 0), oma = c(0, 0, 0, 0)) plot(0.5, xlim = c(0, 1), ylim = c(0, 1), type = "n", axes = FALSE, xlab = "", ylab = "", xaxt = "n", yaxt = "n") if (same.time.scale) { # add title text(x = 0.5, y = 0.25, "Time (s)", cex = 1.2 * cex) # max duration maxdur <- max(X$end - X$start) xlab <- pretty(seq(0, maxdur, length.out = 3), min.n = 5) xlab <- xlab[xlab < maxdur & xlab > 0] xs <- xlab/mean(X$end - X$start) xs <- xs/ncol finncol <- which(nrow(X) >= seq(0, nrow * ncol, nrow)[-1]) if (length(finncol) > 0) { usr <- par("usr") sq <- c(seq(min(usr), max(usr), length.out = ncol + 1)) sq <- sq[-length(sq)] sq <- sq[finncol] out <- lapply(sq, function(p) { out <- lapply(seq_len(length(xs)), function(w) { lines(y = c(0.9, 1.04), x = c(xs[w], xs[w]) + p) text(y = 0.75, x = xs[w] + p, labels = xlab[w], cex = cex) }) }) } } else text(x = 0.5, y = 0.5, "Time (s)", cex = 1.2 * cex) } #add legend if (fig.type[i] == "legend") { par( mar = rep(0, 4)) plot(0.5, xlim = c(0, 1), ylim = c(0, 1), type = "n", axes = FALSE, xlab = "", ylab = "", xaxt = "n", yaxt = "n") # define y limits for legend labels y1 <- 0.2 y2 <- 0.8 #remove rows if legend != 3 if (legend == 1) tag.col.df <- droplevels(tag.col.df[tag.col.df$tag.col == tags[1], ]) if (legend == 2) tag.col.df <- droplevels(tag.col.df[tag.col.df$tag.col == tags[2], ]) #add left right if 2 tags if (length(tags) == 2) { if (legend == 3) { labtag1 <- paste("left:", tags[1]) labtag2 <- paste("right:", tags[2]) } else { labtag2 <- tags[2] labtag1 <- tags[1] } } else labtag1 <- tags[1] #adjust if numeric if (is.numeric(X[,tags[1]]) & !is.integer(X[,tags[1]])) { aa <- as.character(sapply(strsplit(as.character(tag.col.df$tag[tag.col.df$tag.col == tags[1]]), ",", fixed = T), "[", 1)) tag.col.df[tag.col.df$tag.col == tags[1],] <- tag.col.df[order(as.numeric(substr(aa, 2, nchar(aa)))),] } # subset legend if (sub.legend) { if (is.numeric(X[,tags[1]]) & !is.integer(X[,tags[1]])) levs <- as.character(unique(X$col.numeric1)) else levs <- as.character(unique(X[,tags[1]])) if (legend > 1 & length(tags) == 2){ if (is.numeric(X[,tags[2]]) & !is.integer(X[,tags[2]])) levs <- c(levs, as.character(unique(X$col.numeric2))) else levs <- c(levs, as.character(unique(X[,tags[2]]))) } tag.col.df <- droplevels(tag.col.df[tag.col.df$tag %in% levs,]) } if (nrow(tag.col.df) > 15) { y1 <- 0.03 y2 <- 0.97 } y <- seq(y1, y2, length.out = nrow(tag.col.df) + length(unique(tag.col.df$tag.col))) y <- y[length(y):1] step <- y[1] - y[2] if (legend %in% c(1, 3)) { text(x = 0.5, y = max(y) + step, labels = labtag1, cex = cex, font = 2) out <- lapply(which(tag.col.df$tag.col == tags[1]), function(w) { # plot label text(x = 0.5, y = y[w], labels = tag.col.df$tag[w], cex = cex) #plot color box rectw_wrblr_int(xl = 0.3, yb = y[w] - (step/2) - (step/6), xr = 0.7, yt = y[w] - (step/2) + (step/6), bor = "black", cl = tag.col.df$col[w], den = 10, ang = NULL, pattern = tag.col.df$pattern[w]) }) } nrowtag1 <- nrow(tag.col.df[tag.col.df$tag.col == tags[1], ]) if (length(tags) == 2 & legend %in% c(2, 3)) { #remove first tag tag.col.df <- tag.col.df[tag.col.df$tag.col == tags[2],] if (is.numeric(X[,tags[2]]) & !is.integer(X[,tags[2]])) { aa <- as.character(sapply(strsplit(as.character(tag.col.df$tag), ",", fixed = T), "[", 1)) tag.col.df <- tag.col.df[order(as.numeric(substr(aa, 2, nchar(aa)))),] } if (legend == 3) text(x = 0.5, y = y[nrowtag1 + 2], labels = labtag2, cex = cex, font = 2) else text(x = 0.5, y = ifelse(max(y) + step < 1, max(y) + step, 0.99), labels = labtag2, cex = cex, font = 2) if (legend == 3) y <- y - step * 2 out <- lapply(1:nrow(tag.col.df), function(w) { # plot label text(x = 0.5, y = y[w + nrowtag1], labels = tag.col.df$tag[w], cex = cex) #plot color box rectw_wrblr_int(xl = 0.3, yb = y[w + nrowtag1] - (step/2) - (step/6), xr = 0.7, yt = y[w + nrowtag1] - (step/2) + (step/6), bor = "black", cl = tag.col.df$col[w], den = 10, ang = NULL, pattern = tag.col.df$pattern[w]) }) } } if (fig.type[i] == "title") { par(mar = rep(0, 4)) plot(0.5, xlim = c(0, 1), ylim = c(0, 1), type = "n", axes = FALSE, xlab = "", ylab = "", xaxt = "n", yaxt = "n") text(x = 0.5, y = 0.5, title, cex = 1.5 * cex) } } ) close.screen(all.screens = TRUE) dev.off() } #run function over X to split it in subset data frames cel <- ceiling((nrow(X)/(ncol * nrow))) if (cel < 1) Xlist <- list(X) else Xlist <- lapply(1:cel, function(x) { if (x < cel) X[((((ncol * nrow) * (x - 1)) + 1):((ncol * nrow) * (x))), ] else X[((((ncol * nrow) * (x - 1)) + 1):nrow(X)), ] }) #Apply over each sound file # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) else cl <- parallel out <- pblapply_wrblr_int(pbar = pb, X = seq_len(length(Xlist)), cl = cl, FUN = function(z) { catalFUN(X = Xlist[[z]], nrow, ncol, page = z, labels, grid, fast.spec, flim,pal, width, height, tag.col.df, legend, cex, img.suffix, img.prefix, title)} ) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/catalog.R
#' Combine \code{\link{catalog}} images into pdfs #' #' \code{catalog2pdf} combines \code{\link{catalog}} jpeg images into pdfs #' @usage catalog2pdf(keep.img = TRUE, overwrite = FALSE, parallel = 1, path = NULL, #' pb = TRUE, by.img.suffix = FALSE, ...) #' @param keep.img Logical argument. Indicates whether jpeg files should be kept (default) or remove. #' @param overwrite Logical argument. If \code{TRUE} all jpeg pdf will be produced again #' when code is rerun. If \code{FALSE} only the ones missing will be produced. Default is \code{FALSE}. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param path Character string containing the directory path where the catalog image files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @param by.img.suffix Logical. If \code{TRUE} catalogs with the same image suffix will be #' put together in a single pdf (so one pdf per image suffix in the catalog #' images). Default is \code{FALSE} (i.e. no suffix). #' @param ... Additional arguments to be passed to the internal pdf creating function \code{\link[grDevices]{pdf}} for customizing output. #' @export #' @name catalog2pdf #' @details The function combines catalog images in .jpeg format from the \code{\link{catalog}} function into pdfs. Images must be saved in .jpeg format. Note that using lower resolution and smaller dimension (width and height) when creating catalogs will substantially decrease the size of pdf files (which could be pretty big). #' @seealso \code{\link{full_spectrogram2pdf}}, \code{\link{catalog}} #' @return Image files in pdf format with spectrogram catalogs in the working directory. #' @examples #' \dontrun{ #' # save sound file examples #' data(list = c("Phae.long1", "Phae.long2")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' #' catalog(X = lbh_selec_table, nrow = 2, ncol = 4) #' #' # now create single pdf removing jpeg #' catalog2pdf(keep.img = FALSE, path = tempdir()) #' #' # check this floder #' tempdir() #' } #' @references {Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191.} #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on mar-13-2018 (MAS) catalog2pdf <- function(keep.img = TRUE, overwrite = FALSE, parallel = 1, path = NULL, pb = TRUE, by.img.suffix = FALSE, ...) { # error message if jpeg package is not installed if (!requireNamespace("jpeg", quietly = TRUE)) { stop2("must install 'jpeg' to use this function") } #### set arguments from options # get function arguments argms <- methods::formalArgs(catalog2pdf) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # list jpeg files imgs <- list.files(pattern = "\\.jpeg$|\\.jpeg$", path = path, ignore.case = TRUE) if (length(imgs) == 0) stop2("No .jpeg files were found in the working directory") # remove images that don't have the catalog_pX.jpeg ending imgs <- grep("Catalog_p\\d+", imgs, value = TRUE) # remove page info at the end of file names to get sound file names if (by.img.suffix) { or.sf <- gsub("Catalog_p\\d+\\-|\\.jpeg", "", imgs) } else { or.sf <- by.img.suffix } pdf.options(useDingbats = TRUE) # loop over each sound file name cat2pdfFUN <- function(i, overwrite, keep.img) { if (!is.logical(i)) filnam <- paste0(i, ".pdf") else filnam <- "Catalog.pdf" if (any(!overwrite & !file.exists(filnam), overwrite)) { # order imgs so they look order in the pdf if (!is.logical(i)) subimgs <- imgs[or.sf == i] else subimgs <- imgs if (length(subimgs) > 1) { pgs <- as.numeric(sapply(strsplit(substr(subimgs, start = regexpr("Catalog_p", subimgs) + 9, nchar(subimgs)), "-|.jpeg"), "[", 1)) if (!is.logical(i)) { pgs <- as.numeric(gsub(paste0("-", i, "|\\.jpeg|\\.jpg"), "", pgs, ignore.case = TRUE)) } else { pgs <- as.numeric(gsub(paste0("|\\.jpeg|\\.jpg"), "", pgs, ignore.case = TRUE)) } subimgs <- subimgs[order(pgs)] } # get dimensions imgdm <- dim(jpeg::readJPEG(file.path(path, subimgs[1]), native = T)) dimprop <- imgdm[1] / imgdm[2] # start graphic device if (!is.logical(i)) { grDevices::pdf(file = file.path(path, paste0(i, ".pdf")), width = 10, height = dimprop * 10, ...) } else { grDevices::pdf(file = file.path(path, "Catalog.pdf"), width = 10, height = dimprop * 10, ...) } # plot img <- jpeg::readJPEG(file.path(path, subimgs[1])) par(mar = rep(0, 4), oma = rep(0, 4), pty = "m") plot.new() mr <- par("usr") graphics::rasterImage(img, mr[1], mr[3], mr[2], mr[4]) # loop over the following pages if more than 1 page if (length(subimgs) > 1) { no.out <- lapply(subimgs[-1], function(y) { plot.new() mr <- par("usr") img2 <- jpeg::readJPEG(file.path(path, y)) graphics::rasterImage(img2, mr[1], mr[3], mr[2], mr[4]) }) } dev.off() if (!keep.img) unlink(subimgs) } } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function a1 <- pblapply_wrblr_int(pbar = pb, X = unique(or.sf), cl = cl, FUN = function(i) { cat2pdfFUN(i, overwrite, keep.img) }) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/catalog2pdf.R
#' Check selection data frames #' #' \code{check_sels} checks whether selections can be read by subsequent functions. #' @usage check_sels(X, parallel = 1, path = NULL, check.header = FALSE, pb = TRUE, #' wav.size = FALSE, verbose = TRUE, fix.selec = FALSE) #' @param X 'selection_table' object or data frame with the following columns: 1) "sound.files": name of the .wav #' files, 2) "sel": number of the selections, 3) "start": start time of selections, 4) "end": #' end time of selections. Alternatively, a 'selection_table' class object can be input to double check selections. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param check.header Logical. Controls whether sound file headers correspond to the actual file properties #' (i.e. if is corrupted). This could significantly affect the performance of the function (much slower) particularly #' with long sound files. #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @param wav.size Logical argument to control if the size of the wave object #' when the selection is imported into R (as when using \code{\link[tuneR]{readWave}} #' is calculated and added as a column. Size is return in MB. Default is \code{FALSE}. #' @param verbose Logical to control whether the summary messages are printed to the console. Defaut is \code{TRUE}. #' @param fix.selec Logical to control if labels in 'selec' column should be fixed. This column should not be duplicated within a sound file. If that happens and \code{fix.selec = TRUE} duplicated labels will be changed. Default is \code{FALSE}. #' @return A data frame including the columns in the input data frame (X) and the following additional columns: #' \itemize{ #' \item \code{check.res}: diagnose for each selection #' \item \code{duration}: duration of selection in seconds #' \item \code{min.n.samples} number of samples in a selection. Note the number of samples available #' in a selection limits the minimum window length (wl argument in other functions) that can be used in batch analyses. #' \item \code{sample.rate}: sampling rate in kHz #' \item \code{channels}: number of channels #' \item \code{bits}: bit depth #' \item \code{sound.file.samples}: number of samples in the sound file #' } #' @details This function checks the information in a selection data frame or selection table (i.e. data frame with annotations on sound files) #' to avoid problems in any warbleR analysis downstream. It specifically checks if: #' \itemize{ #' \item 'X' is an object of class 'data.frame' or 'selection_table' (see \code{\link{selection_table}}) and contains #' the required columns to be used on any warbleR function ('sound.files', 'selec', 'start', 'end', if not returns an error) #' \item 'sound.files' in 'X' correspond to sound files in the working directory or in the provided 'path' #' (if no file is found returns an error, if some files are not found returns error info in the ouput data frame) #' \item time ('start', 'end') and frequency ('bottom.freq', 'top.freq', if provided) limit parameters are numeric and #' don't contain NAs (if not returns an error) #' \item there are no duplicated selection labels ('selec') within a sound file (if not returns an error) #' \item sound files can be read (error info in the ouput data frame) #' \item the start and end time of the selections are found within the duration of the sound files (error info in the ouput data frame) #' \item sound files can be read (error info in the ouput data frame) #' \item sound files header is not corrupted (only if \code{header = TRUE}, error info in the ouput data frame) #' \item selection time position (start and end) doesn't exceeds sound file length (error info in the ouput data frame) #' \item 'top.freq' is lower than half the sample rate (nyquist frequency, error info in the ouput data frame) #' \item negative values aren't found in time or frequency limit parameters (error info in the ouput data frame) #' \item 'start' higher than 'end' or 'bottom.freq' higher than 'top.freq' (error info in the ouput data frame) #' \item 'channel' value is not higher than number of channels in sound files (error info in the ouput data frame) #' } #' The function returns a data frame that includes the information in 'X' plus additional columns about the format of sound #' files (see 'Value') as well as the result of the checks ('check.res' column, value is 'OK' if everything is fine). #' Sound files should be in the working directory (or the directory provided in 'path'). Corrupt files can be fixed using #' \code{\link{fix_wavs}}. #' @seealso \code{\link{check_wavs}} #' @export #' @name check_sels #' @export #' @examples{ #' # save wav file examples #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' #' check_sels(X = lbh_selec_table, path = tempdir()) #' } #' @references {Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191.} #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on jul-5-2016 (MAS) check_sels <- function(X = NULL, parallel = 1, path = NULL, check.header = FALSE, pb = TRUE, wav.size = FALSE, verbose = TRUE, fix.selec = FALSE) { #### set arguments from options # get function arguments argms <- methods::formalArgs(check_sels) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # if X is not a data frame if (all(!any(is.data.frame(X), is_selection_table(X)))) stop2("X is not of a class 'data.frame' or 'selection_table'") if (is_extended_selection_table(X)) stop2("check_sels does not work on objects of class 'extended_selection_table'") if (!all(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))) { stop2(paste(paste(c("sound.files", "selec", "start", "end")[!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } # if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) stop2("'start' and 'end' must be numeric") # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop2("NAs found in start and/or end") # check for duplicates and if fix.selec = TRUE if (any(duplicated(paste(X$sound.files, X$selec)))) { if (fix.selec) { X$selec <- do.call(c, lapply(unique(X$sound.files), function(x) seq_len(sum(X$sound.files == x)))) } else { stop2("Duplicated selection labels ('selec' column) for one or more sound files (can be fixed by setting fix.selec = TRUE)") } } # check additional columns if (!"channel" %in% colnames(X)) { X$channel <- 1 } else { if (!is.numeric(X$channel)) stop2("'channel' must be numeric") if (any(is.na(X$channel))) { message2("NAs in 'channel', assumed to be channel 1 \n") X$channel[is.na(X$channel)] <- 1 } } # check if files are in working directory files <- file.exists(file.path(path, unique(X$sound.files))) if (all(!files)) { stop2("no sound files found") } # update to new frequency range column names if (any(grepl("low.freq|high.freq", names(X)))) { names(X)[names(X) == "low.freq"] <- "bottom.freq" names(X)[names(X) == "high.freq"] <- "top.freq" message2("'low.freq' and 'high.freq' renamed as 'bottom.freq' and 'top.freq' \n") } # check if freq lim are numeric if (any(names(X) == "bottom.freq")) { if (!is(X$bottom.freq, "numeric")) stop2("'bottom.freq' is not numeric") } if (any(names(X) == "top.freq")) { if (!is(X$top.freq, "numeric")) stop2("'top.freq' is not numeric") } # check if NAs in freq limits if (any(names(X) %in% c("bottom.freq", "top.freq"))) { if (any(is.na(c(X$bottom.freq, X$top.freq)))) stop2("NAs found in 'top.freq' and/or 'bottom.freq' \n") } # function to run over each sound file csFUN <- function(x, X, pth) { Y <- as.data.frame(X[X$sound.files == x, , drop = FALSE]) if (file.exists(file.path(pth, x))) { rec <- try(suppressWarnings(read_sound_file(X = x, path = pth, header = TRUE)), silent = TRUE) # if it was read if (!is(rec, "try-error")) { if (check.header) # look for mismatchs between file header & file content { recfull <- try(suppressWarnings(read_sound_file(X = x, path = pth, header = FALSE)), silent = TRUE) if (any(methods::slotNames(recfull) == "stereo")) { if (rec$channels == 2) { channel.check <- ifelse(recfull@stereo, FALSE, TRUE) } else { channel.check <- ifelse(!recfull@stereo, FALSE, TRUE) } samples.check <- ifelse(rec$samples == length(recfull@left), FALSE, TRUE) } else { channel.check <- FALSE samples.check <- ifelse(rec$samples == length([email protected]), FALSE, TRUE) } if (any(rec$sample.rate != [email protected], rec$bits != recfull@bit, channel.check, samples.check)) { Y$check.res <- "file header corrupted" Y$duration <- NA Y$min.n.samples <- NA Y$sample.rate <- NA Y$channels <- NA Y$bits <- NA Y$sound.file.samples <- NA } else { maxdur <- rec$samples / rec$sample.rate Y$check.res <- "OK" if (any(Y$end > maxdur)) Y$check.res[Y$end > maxdur] <- "exceeds sound file length" Y$duration <- Y$end - Y$start Y$min.n.samples <- floor(Y$duration * rec$sample.rate) Y$sample.rate <- rec$sample.rate / 1000 Y$channels <- rec$channels Y$bits <- rec$bits Y$sound.file.samples <- rec$samples } } else { maxdur <- rec$samples / rec$sample.rate Y$check.res <- "OK" if (any(Y$end > maxdur)) Y$check.res[Y$end > maxdur] <- "exceeds sound file length" Y$duration <- Y$end - Y$start Y$min.n.samples <- floor(Y$duration * rec$sample.rate) Y$sample.rate <- rec$sample.rate / 1000 Y$channels <- rec$channels Y$bits <- rec$bits Y$sound.file.samples <- rec$samples } } else { Y$check.res <- "Sound file can't be read" Y$duration <- NA Y$min.n.samples <- NA Y$sample.rate <- NA Y$channels <- NA Y$bits <- NA Y$sound.file.samples <- NA } } else { Y$check.res <- "sound file not found" Y$duration <- NA Y$min.n.samples <- NA Y$sample.rate <- NA Y$channels <- NA Y$bits <- NA Y$sound.file.samples <- NA } return(Y) } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function out <- pblapply_wrblr_int(pbar = pb, X = unique(X$sound.files), cl = cl, FUN = function(x) { csFUN(x, X, pth = path) }) res <- do.call(rbind, out) res <- res[match(paste(X$sound.files, X$selec), paste(res$sound.files, res$selec)), ] if ("top.freq" %in% names(res)) { # nyquist frequency try(res$check.res <- ifelse((res$sample.rate / 2) - res$top.freq < 0 & !is.na(res$sample.rate), gsub("OK\\|", "", paste(res$check.res, "'Top.freq' higher than half the sample rate", sep = "|")), res$check.res), silent = TRUE) # if bottom.freq is negative res$check.res <- ifelse(res$bottom.freq < 0, gsub("OK\\|", "", paste(res$check.res, "Negative values in 'bottom.freq'", sep = "|")), res$check.res) # if fre range is equal or lower than 0 res$check.res <- ifelse(res$top.freq - res$bottom.freq <= 0, gsub("OK\\|", "", paste(res$check.res, "'bottom.freq' is equal or higher than the 'top.freq'", sep = "|")), res$check.res) } # if start higher or equal than end res$check.res <- ifelse(res$end - res$start <= 0, gsub("OK\\|", "", paste(res$check.res, "'start' is equal or higher than the 'end'", sep = "|")), res$check.res) # if start is negative res$check.res <- ifelse(res$start < 0, gsub("OK\\|", "", paste(res$check.res, "Negative values in 'start'", sep = "|")), res$check.res) # if channel number is equal or smaller than the number of channels in the wav file if (any(res$channel[!is.na(res$duration)] > res$channels[!is.na(res$duration)])) { message2("\n some selections listed as having more than 1 channel found in sound files with only 1 channel; channel field relabeled as '1' \n") res$channel[!is.na(res$duration)][any(res$channel[!is.na(res$duration)] > res$channels[!is.na(res$duration)])] <- 1 } if (wav.size) res$wav.size <- round(res$bits * res$channel * res$sample.rate * res$duration / 4) / 10 if (verbose) { # inform result if (all(res$check.res == "OK")) { if (any(res$min.n.samples < 20)) { message2("all selections are OK but some have very few samples (less than 20, potentially problematic for some analyses) \nCheck 'min.n.samples' column") } else if (length(unique(res$sample.rate)) > 1) { message2("all selections are OK but not all sound files have the same sampling rate (potentially problematic, particularly for cross_correlation())") } else { message2("all selections are OK \n") } } else { message2(paste(sum(res$check.res != "OK"), "selection(s) are not OK \n")) } } # return data frame res <- res } ############################################################################################################## #' alternative name for \code{\link{check_sels}} #' #' @keywords internal #' @details see \code{\link{check_sels}} for documentation. \code{\link{checksels}} will be deprecated in future versions. #' @export checksels <- check_sels
/scratch/gouwar.j/cran-all/cranData/warbleR/R/check_sels.R
#' Check sound files #' #' \code{check_sound_files} checks whether sound files can be read by subsequent functions. #' @usage check_sound_files(X = NULL, path = NULL) #' @param X Optional. 'selection_table' object or data frame with the following columns: 1) "sound.files": name of the sound #' files, 2) "sel": number of the selections, 3) "start": start time of selections, 4) "end": #' end time of selections. If provided the function also returns the #' smallest number of samples from the listed selections, which limits the minimum window #' length (wl argument in other functions) that can be used in batch analyses. #' This could be useful for avoiding errors in downstream functions (e.g. \code{\link{spectro_analysis}}). #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @return If all sound files are ok, returns message "All files can be read". #' Otherwise returns the names of the corrupted sound files. #' @details This function checks if sound files in the working directory can be read. #' Users must set the working directory where they wish to check sound files beforehand. #' If X is provided it also returns the smallest number of samples from #' the selections listed in X (if all files can be read). Note that corrupt files can be #' fixed using \code{\link{fix_wavs}}) ('sox' must be installed to be able to run this function). #' The function is intended for a "quick and dirty" check of the sound files in a selections data #' frame. For a more thorough analysis see \code{\link{check_sels}}. #' @export #' @seealso \code{\link{check_sels}} \code{\link{tailor_sels}} #' @name check_sound_files #' @examples{ #' # save wav file examples #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' #' # without selection data frame #' check_sound_files(path = tempdir()) #' #' # with selection data frame #' check_sound_files(X = lbh_selec_table, path = tempdir()) #' } #' @references {Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191.} #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on jul-5-2016 (MAS) check_sound_files <- function(X = NULL, path = NULL) { #### set arguments from options # get function arguments argms <- methods::formalArgs(check_sound_files) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # return warning if not all sound files were found files <- list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE) if (length(files) == 0) stop2("no sound files in working directory") if (!is.null(X)) { # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X))) stop2("X is not of a class 'data.frame' or 'selection_table'") if (!all(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))) { stop2(paste(paste(c("sound.files", "selec", "start", "end")[!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop2("NAs found in start and/or end") # if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) stop2("'start' and 'end' must be numeric") # if any start higher than end stop if (any(X$end - X$start <= 0)) stop2(paste("Start is higher than or equal to end in", length(which(X$end - X$start <= 0)), "case(s)")) if (length(unique(X$sound.files[(X$sound.files %in% files)])) != length(unique(X$sound.files))) { message2(paste( length(unique(X$sound.files)) - length(unique(X$sound.files[(X$sound.files %in% files)])), "sound file(s) not found" )) } # count number of sound files in working directory and if 0 stop d <- which(X$sound.files %in% files) if (length(d) == 0) { stop2("The sound files are not in the working directory") } else { X <- X[d, , drop = FALSE] } files <- files[files %in% X$sound.files] } samp.rate <- sapply(files, function(x) { # print(x) r <- try(suppressWarnings(warbleR::read_sound_file(X = x, path = path, header = TRUE)), silent = TRUE) if (is(r, "try-error")) { return(NA) } else { return(r$sample.rate) } }) if (length(files[is.na(samp.rate)]) > 0) { message2("Some file(s) cannot be read") return(files[is.na(samp.rate)]) } else { message2("All files can be read\n") if (!is.null(X)) { df <- merge(X, data.frame(f = samp.rate, sound.files = names(samp.rate)), by = "sound.files") message2(paste("smallest number of samples: ", floor(min((df$end - df$start) * df$f)), " (sound file:", as.character(df$sound.files[which.min((df$end - df$start) * df$f)]), "; selection label: ", df$selec[which.min((df$end - df$start) * df$f)], ")\n", sep = "")) } } if (length(unique(samp.rate)) > 1) { message2("Not all sound files have the same sampling rate (potentially problematic, particularly for cross_correlation())") } } ############################################################################################################## #' alternative name for \code{\link{check_sound_files}} #' #' @keywords internal #' @details see \code{\link{check_sound_files}} for documentation. \code{\link{check_wavs}} will be deprecated in future versions. #' @export check_wavs <- check_sound_files
/scratch/gouwar.j/cran-all/cranData/warbleR/R/check_sound_files.R
#' Highlight spectrogram regions #' #' \code{color_spectro} highlights spectrogram regions specified by users #' @usage color_spectro(wave, wl = 512, wn = "hanning", ovlp = 70, #' dB = "max0", collevels = NULL, selec.col = "red2", col.clm = NULL, #' base.col = "black", bg.col = "white", strength = 1, #' cexlab = 1, cexaxis = 1, tlab = "Time (s)", flab = "Frequency (kHz)", #' title = NULL, axisX = TRUE, axisY = TRUE, flim = NULL, #' rm.zero = FALSE, X = NULL, fast.spec = FALSE, t.mar = NULL, #' f.mar = NULL, interactive = NULL, add = FALSE) #' @param wave A 'wave' object produced by \code{\link[tuneR]{readWave}} or similar functions. #' @param wl A numeric vector of length 1 specifying the window length of the spectrogram. Default #' is 512. #' @param wn Character vector of length 1 specifying window name. Default is #' "hanning". See function \code{\link[seewave]{ftwindow}} for more options. #' @param ovlp Numeric vector of length 1 specifying the percent overlap between two #' consecutive windows, as in \code{\link[seewave]{spectro}}. Default is 70. #' @param dB Character vector of length 1 controlling the amplitude weights as in #' \code{\link[seewave]{spectro}}. Default is 'max0'. #' @param collevels Numeric. Levels used to partition amplitude range as in \code{\link[seewave]{spectro}}. #' Default is \code{NULL}. #' @param selec.col Character vector of length 1 specifying the color to be used to highlight selection. #' See 'col.clm' for specifying unique colors for each selection. Default is 'red2'. Ignored if 'col.cm' #' and 'X' are provided. #' @param col.clm Character vector of length 1 indicating the name of the column in 'X' that contains the #' color names for each selection. Ignored if \code{X == NULL} or \code{interactive != NULL}. Default is \code{NULL}. #' @param base.col Character vector of length 1 specifying the color of the background spectrogram. #' Default is 'black'. #' @param bg.col Character vector of length 1 specifying the background color for both base #' and highlighted spectrograms. Default is 'white'. #' @param strength Numeric vector of length 1 controlling the strength of the highlighting color (actually how many times it is repeated in the internal color palette). Must be a positive integer. Default is 1. #' @param cexlab Numeric vector of length 1 specifying the relative size of axis #' labels. See \code{\link[seewave]{spectro}}. Default is 1. #' @param cexaxis Numeric vector of length 1 specifying the relative size of axis. See #' \code{\link[seewave]{spectro}}. Default is 1. #' @param tlab Character vector of length 1 specifying the label of the time axis. #' @param flab Character vector of length 1 specifying the label of the frequency axis. #' @param title Logical argument to add a title to individual spectrograms. #' Default is \code{TRUE}. #' @param axisX Logical to control whether time axis is plotted. Default is \code{TRUE}. #' @param axisY Logical to control whether frequency axis is plotted. Default is \code{TRUE}. #' @param flim A numeric vector of length 2 for the frequency limit (in kHz) of #' the spectrogram, as in \code{\link[seewave]{spectro}}. Default is \code{NULL}. #' @param rm.zero Logical indicated if the 0 at the start of the time axis should be removed. Default is \code{FALSE}. #' @param X Optional. Data frame containing columns for start and end time of signals ('start' and 'end') and low and high frequency ('bottom.freq' and 'top.freq'). #' @param fast.spec Logical. If \code{TRUE} then image function is used internally to create spectrograms, which substantially #' increases performance (much faster), although some options become unavailable, as collevels, and sc (amplitude scale). #' This option is indicated for signals with high background noise levels. Palette colors \code{\link[monitoR:specCols]{gray.1}}, \code{\link[monitoR:specCols]{gray.2}}, #' \code{\link[monitoR:specCols]{gray.3}}, \code{\link[monitoR:specCols]{topo.1}} and \code{\link[monitoR:specCols]{rainbow.1}} (which should be imported from the package monitoR) seem #' to work better with 'fast' spectrograms. Palette colors \code{\link[monitoR:specCols]{gray.1}}, \code{\link[monitoR:specCols]{gray.2}}, #' \code{\link[monitoR:specCols]{gray.3}} offer #' decreasing darkness levels. #' @param t.mar Numeric vector of length 1. Specifies the margins adjacent to the start and end points to be added when highlighting selection. Default is \code{NULL}. #' @param f.mar Numeric vector of length 1. Specifies the margins adjacent to the low and high frequencies to be added when highlighting selection. Default is \code{NULL}. #' @param interactive Numeric. Allow user to interactively select the signals to be highlighted by clicking #' on the graphic device. Users must select the opposite corners of a square delimiting the spectrogram region #' to be highlighted. Controls the number of signals that users would be able to select (2 clicks per signal). #' @param add Logical. If \code{TRUE} new highlighting can be applied to the current plot (which means #' that the function with \code{add = FALSE} should be run first). Default is \code{FALSE}. #' @return A plot is produced in the graphic device. #' @family spectrogram creators #' @seealso \code{\link{track_freq_contour}} for creating spectrograms to visualize #' frequency measurements by \code{\link{spectro_analysis}}, \code{\link{snr_spectrograms}} for #' creating spectrograms to optimize noise margins used in \code{\link{sig2noise}} #' @export #' @name color_spectro #' @details This function highlights regions of the spectrogram with different colors. The regions to be #' highlighted can be provided in a selection table (as the example data 'lbh_selec_table') or interactively ('interactive' argument). #' @examples #' \dontrun{ #' data(list = c("Phae.long1", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) # save sound files #' #' # subset selection table #' st <- lbh_selec_table[lbh_selec_table$sound.files == "Phae.long1.wav", ] #' #' # read wave file as an R object #' sgnl <- tuneR::readWave(file.path(tempdir(), st$sound.files[1])) #' #' # create color column #' st$colors <- c("red2", "blue", "green") #' #' # highlight selections #' color_spectro( #' wave = sgnl, wl = 300, ovlp = 90, flim = c(1, 8.6), collevels = seq(-40, 0, 5), #' dB = "B", X = st, col.clm = "colors", base.col = "skyblue", t.mar = 0.07, f.mar = 0.1, #' interactive = NULL #' ) #' #' # interactive (selected manually: you have to select them by clicking on the spectrogram) #' color_spectro( #' wave = sgnl, wl = 300, ovlp = 90, flim = c(1, 8.6), collevels = seq(-40, 0, 5), #' dB = "B", col.clm = "colors", t.mar = 0.07, f.mar = 1, interactive = 2 #' ) #' } #' #' @references {Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191.} #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) and Grace Smith Vidaurre # last modification on jul-5-2016 (MAS) color_spectro <- function(wave, wl = 512, wn = "hanning", ovlp = 70, dB = "max0", collevels = NULL, selec.col = "red2", col.clm = NULL, base.col = "black", bg.col = "white", strength = 1, cexlab = 1, cexaxis = 1, tlab = "Time (s)", flab = "Frequency (kHz)", title = NULL, axisX = TRUE, axisY = TRUE, flim = NULL, rm.zero = FALSE, X = NULL, fast.spec = FALSE, t.mar = NULL, f.mar = NULL, interactive = NULL, add = FALSE) { #### set arguments from options # get function arguments argms <- methods::formalArgs(color_spectro) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # error if dB wrong if (!is.null(dB) && all(dB != c("max0", "A", "B", "C", "D"))) { stop("'dB' has to be one of the following character strings: 'max0', 'A', 'B', 'C' or 'D'") } drtn <- duration(wave, f = [email protected]) # filter to keep selections within the tlim range if (!is.null(X)) { sel.tab <- X[X$end < drtn, ] } else { sel.tab <- col.clm <- NULL } # add time margins if (!is.null(t.mar) & !is.null(sel.tab)) { sel.tab$start <- sel.tab$start - t.mar sel.tab$end <- sel.tab$end + t.mar # fix the ones lower than 0 or longer than duration sel.tab$start[sel.tab$start < 0] <- 0 sel.tab$end[sel.tab$end > drtn] <- drtn } # interactive to NULL if 0 if (!is.null(interactive)) if (interactive == 0) interactive <- NULL # set colors for colored signals if (!is.null(sel.tab)) { if (!is.null(col.clm)) { colors <- sel.tab[, col.clm] } else { colors <- rep(selec.col, nrow(sel.tab)) } } # pallete for background spectro if (is.null(collevels)) { collevels <- seq(-40, 0, 5) } # set background spectro color basepal <- colorRampPalette(c(bg.col, base.col)) # adjust flim if lower than higher top.freq # if (!is.null(flim) & !is.null(sel.tab)) { # if (flim[1] > min(sel.tab$bottom.freq)) flim[1] <- min(sel.tab$bottom.freq) # if (flim[2] < max(sel.tab$top.freq)) flim[2] <- max(sel.tab$top.freq) # } # add frequency margins if (!is.null(f.mar)) { sel.tab$bottom.freq <- sel.tab$bottom.freq - f.mar sel.tab$top.freq <- sel.tab$top.freq + f.mar # fix the ones lower than 0 or longer than duration sel.tab$bottom.freq[sel.tab$bottom.freq < flim[1]] <- flim[1] sel.tab$top.freq[sel.tab$top.freq > flim[2]] <- flim[2] } # read wave object input <- inputw(wave = wave, f = [email protected]) wave <- input$w f <- input$f n <- nrow(wave) step <- seq(1, n - wl, wl - (ovlp * wl / 100)) # to fix function name change in after version 2.0.5 # if (exists("stdft")) stft <- stdft z <- stft_wrblr_int( wave = wave, f = f, wl = wl, zp = 0, step = step, wn = wn, fftw = FALSE, scale = TRUE, complex = FALSE ) X <- seq(0, n / f, length.out = length(step)) if (is.null(flim)) { Y <- seq(0, (f / 2) - (f / wl), length.out = nrow(z)) / 1000 } else { fl1 <- flim[1] * nrow(z) * 2000 / f fl2 <- flim[2] * nrow(z) * 2000 / f z <- z[(fl1:fl2) + 1, ] Y <- seq(flim[1], flim[2], length.out = nrow(z)) } if (!is.null(dB)) z <- 20 * log10(z) if (dB != "max0") { if (dB == "A") { z <- seewave::dBweight(Y * 1000, dBref = z)$A } if (dB == "B") { z <- seewave::dBweight(Y * 1000, dBref = z)$B } if (dB == "C") { z <- seewave::dBweight(Y * 1000, dBref = z)$C } if (dB == "D") { z <- seewave::dBweight(Y * 1000, dBref = z)$D } } Z <- t(z) maxz <- round(max(z, na.rm = TRUE)) if (is.null(collevels)) { if (!is.null(dB)) { collevels <- seq(maxz - 30, maxz, by = 1) } else { collevels <- seq(0, maxz, length = 30) } } # opar <- par # par(bg = bg.col) # on.exit(par(opar), add = TRUE) # if (!fast.spec) { # seewave spectro # plot background spectro if (!add) { filled_contour_color_wrblr_int( x = X, y = Y, z = Z, levels = collevels, nlevels = 20, plot.title = title( main = title, xlab = tlab, ylab = flab ), color.palette = basepal, axisX = FALSE, axisY = axisY, col.lab = "black", colaxis = "black", bg.col = bg.col ) } if (!is.null(interactive)) { message2(x = "Select the signal(s) you want to highlight:") xy <- locator(interactive * 2) xy <- as.data.frame(xy) xy$selec <- rep(1:interactive, each = 2) out <- lapply(unique(xy$selec), function(i) data.frame(start = min(xy$x[xy$selec == i]), end = max(xy$x[xy$selec == i]), bottom.freq = min(xy$y[xy$selec == i]), top.freq = max(xy$y[xy$selec == i]))) sel.tab <- do.call(rbind, out) colors <- rep(selec.col, nrow(sel.tab)) } # plot colored signals if (!is.null(sel.tab)) { out <- lapply(1:nrow(sel.tab), function(i) { filled_contour_color_wrblr_int( x = X[X > sel.tab$start[i] & X < sel.tab$end[i]], y = Y[Y > sel.tab$bottom.freq[i] & Y < sel.tab$top.freq[i]], z = Z[X > sel.tab$start[i] & X < sel.tab$end[i], Y > sel.tab$bottom.freq[i] & Y < sel.tab$top.freq[i]], nlevels = 20, plot.title = FALSE, color.palette = colorRampPalette(c(rep(bg.col, 1), rep(colors[i], strength)), alpha = TRUE), levels = collevels, axisX = FALSE, axisY = FALSE, col.lab = "black", colaxis = "black", add = TRUE, bg.col = bg.col ) }) } } else { # fast spectro image # plot background spectro if (!add) { image(x = X, y = Y, z = Z, col = basepal(length(collevels) - 1), xlab = tlab, ylab = flab, axes = FALSE) } if (!is.null(interactive)) { xy <- locator(interactive * 2) xy <- as.data.frame(xy) xy$selec <- rep(1:interactive, each = 2) out <- lapply(unique(xy$selec), function(i) data.frame(start = min(xy$x[xy$selec == i]), end = max(xy$x[xy$selec == i]), bottom.freq = min(xy$y[xy$selec == i]), top.freq = max(xy$y[xy$selec == i]))) sel.tab <- do.call(rbind, out) colors <- rep(selec.col, nrow(sel.tab)) } # plot colored signals if (!is.null(sel.tab)) { out <- lapply(1:nrow(sel.tab), function(i) { image(x = X[X > sel.tab$start[i] & X < sel.tab$end[i]], y = Y[Y > sel.tab$bottom.freq[i] & Y < sel.tab$top.freq[i]], z = Z[X > sel.tab$start[i] & X < sel.tab$end[i], Y > sel.tab$bottom.freq[i] & Y < sel.tab$top.freq[i]], col = colorRampPalette(c(rep(bg.col, 2), rep(colors[i], strength)), alpha = TRUE)(30), xlab = tlab, ylab = flab, axes = FALSE, xlim = range(X), add = TRUE) }) } if (axisY) axis(2, at = pretty(Y), labels = pretty(Y), cex.axis = cexlab) box() if (!is.null(title)) title(title) } # add axis if (axisX) { if (rm.zero) { axis(1, at = pretty(X)[-1], labels = pretty(X)[-1], cex.axis = cexaxis) } else { axis(1, at = pretty(X), labels = pretty(X), cex.axis = cexaxis) } } } ############################################################################################################## #' alternative name for \code{\link{color_spectro}} #' #' @keywords internal #' @details see \code{\link{color_spectro}} for documentation. \code{\link{color.spectro}} will be deprecated in future versions. #' @export color.spectro <- color_spectro
/scratch/gouwar.j/cran-all/cranData/warbleR/R/color_spectro.R
#' Example matrix listing selections to be compared by \code{\link{cross_correlation}} #' #' A character matrix with 2 columns indicating the selections to be compared (column 1 vs column 2) by \code{\link{cross_correlation}}. The first column contain the ID of the selection, which is given by combining the 'sound.files' and 'selec' columns of 'X', separated by '-' (i.e. \code{paste(X$sound.files, X$selec, sep = "-")}). The selection id's refer to those on the example data "lbh_selec_table". The second column refers to the sound files in which to search for the templates. #' #' @format A data frame with 11 rows and 6 variables: \describe{ #' \item{sound.files}{recording names} #' \item{channel}{channel in which signal is found} #' \item{selec}{selection numbers within recording} #' \item{start}{start times of selected signal} #' \item{end}{end times of selected signal} #' \item{bottom.freq}{lower limit of frequency range} #' \item{top.freq}{upper limit of frequency range} #' } #' #' @usage data(comp_matrix) #' #' @source Marcelo Araya Salas, warbleR #' #' @description \code{comp_matrix} is a character matrix with 2 columns indicating the selections to be compared (column 1 vs column 2) by \code{\link{cross_correlation}}. #' "comp_matrix"
/scratch/gouwar.j/cran-all/cranData/warbleR/R/comp_matrix-data.R
#' @title Assessing the performance of acoustic distance measurements #' #' @description \code{compare_methods} creates graphs to visually assess performance of acoustic distance measurements #' @usage compare_methods(X = NULL, flim = NULL, bp = NULL, mar = 0.1, wl = 512, ovlp = 90, #' res = 150, n = 10, length.out = 30, #' methods = NULL, #' it = "jpeg", parallel = 1, path = NULL, sp = NULL, custom1 = NULL, #' custom2 = NULL, pb = TRUE, grid = TRUE, clip.edges = TRUE, #' threshold = 15, na.rm = FALSE, scale = FALSE, pal = reverse.gray.colors.2, #' img = TRUE, ...) #' @param X 'selection_table' object or data frame with results from \code{\link{auto_detec}} #' function, or any data frame with columns for sound file name (sound.files), #' selection number (selec), and start and end time of signal (start and end). #' Default \code{NULL}. #' @param flim A numeric vector of length 2 for the frequency limit in kHz of #' the spectrogram, as in \code{\link[seewave]{spectro}}. Default is \code{NULL}. #' @param bp numeric vector of length 2 giving the lower and upper limits of the #' frequency bandpass filter (in kHz) used in the acoustic distance methods. Default is \code{NULL}. #' @param mar Numeric vector of length 1. Specifies plot margins around selection in seconds. Default is 0.1. #' @param wl A numeric vector of length 1 specifying the window length of the spectrogram and cross-correlation, default #' is 512. #' @param ovlp Numeric vector of length 1 specifying the percent overlap between two #' consecutive windows, as in \code{\link[seewave]{spectro}}. Default is 90. #' @param res Numeric argument of length 1. Controls image resolution. #' Default is 150. #' @param n Numeric argument of length 1. Defines the number of plots to be produce. #' Default is 10. #' @param length.out A character vector of length 1 giving the number of measurements of fundamental or dominant #' frequency desired (the length of the time series). Default is 30. #' @param methods A character vector of length 2 giving the names of the acoustic distance #' methods that would be compared. The methods available are: #' \itemize{ #' \item \code{XCORR}: cross-correlation (\code{\link{cross_correlation}} function) #' \item \code{dfDTW}: dynamic time warping on dominant frequency contours (\code{\link{freq_DTW}} function) #' \item \code{ffDTW}: dynamic time warping on fundamental frequency contours (\code{\link{freq_DTW}} function) #' \item \code{SP}: spectral parameters (\code{\link{spectro_analysis}} function) #' \item \code{SPharm}: spectral parameters (\code{\link{spectro_analysis}} function with argument \code{harmonicity = TRUE}) #' \item \code{MFCC}: statistical descriptors of Mel frequency cepstral coefficients (\code{\link{mfcc_stats}} function) #' } #' Default \code{NULL}. #' @param it A character vector of length 1 giving the image type to be used. Currently only #' "tiff" and "jpeg" are admitted. Default is "jpeg". #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param sp DEPRECATED. #' @param custom1 Data frame containing user parameters. The data frame must have 4 columns: the first 2 columns are 'sound.files' #' and "selec' columns as in 'X', the other 2 (columns 3 and 4) are #' 2 numeric columns to be used as the 2 parameters representing custom measurements. If the data has more than 2 parameters try using PCA (i.e. \code{\link[stats]{prcomp}} function)to summarize it in 2 dimensions before using it as an input. Default is \code{NULL}. #' @param custom2 Data frame containing user parameters with the same format as 'custom1'. 'custom1' must be provided first. Default is \code{NULL}. #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @param grid Logical argument to control the presence of a grid on the spectrograms (default is \code{TRUE}). #' @param clip.edges Logical argument to control whether edges (start or end of signal) in #' which amplitude values above the threshold were not detected will be removed when using dfDTW and #' ffDTW methods. If \code{TRUE} this edges will be excluded and signal contour will be calculated on the #' remaining values. Default is \code{TRUE}. #' @param threshold amplitude threshold (\%) for dominant and/or fundamental frequency detection when using dfDTW, ffDTW #' and SP methods. Default is 15. #' @param na.rm Logical. If \code{TRUE} all NAs produced when pairwise cross-correlations failed are removed from the #' results. This means that all selections with at least 1 cross-correlation that failed are excluded in both methods under #' comparison. Only apply if XCORR is one of the methods being compared. #' @param scale Logical. If \code{TRUE} dominant and/or fundamental frequency values are z-transformed using the \code{\link[base]{scale}} function, which "ignores" differences in absolute frequencies between the signals in order to focus the #' comparison in the frequency contour, regardless of the pitch of signals. Default is \code{TRUE}. #' @param pal A color palette function to be used to assign colors in the #' spectrograms, as in \code{\link[seewave]{spectro}}. Default is reverse.gray.colors.2. #' @param img A logical argument specifying whether an image files would be produced. Default is \code{TRUE}. #' @param ... Additional arguments to be passed to a modified version of \code{\link[seewave]{spectro}} for customizing #' graphical output. This includes fast.spec, an argument that speeds up the plotting of spectrograms (see description in #' \code{\link{spectrograms}}). #' @return Image files with 4 spectrograms of the selection being compared and scatterplots #' of the acoustic space of all signals in the input data frame 'X'. #' @export #' @name compare_methods #' @details This function produces graphs with spectrograms from 4 signals in the #' provided data frame that allow visual inspection of the performance of acoustic #' distance methods at comparing those signals. The signals are randomly picked up #' from the provided data frame (X argument).The spectrograms are all plotted with #' the same frequency and time scales. The function compares 2 methods at a time. The #' methods available are: cross-correlation #' (XCORR, from \code{\link{cross_correlation}}), dynamic time warping on dominant frequency time #' series (dfDTW, from \code{\link[dtw]{dtw}} applied on \code{\link{freq_ts}} output), dynamic time #' warping on dominant frequency time series (ffDTW, from \code{\link[dtw]{dtw}} applied on #' \code{\link{freq_ts}} output), spectral parameters (SP, from \code{\link{spectro_analysis}}). The graph also #' contains 2 scatterplots (1 for each method) of the acoustic space of all signals in the #' input data frame 'X', including the centroid as black dot. The compared selections are randomly picked up from the pool of #' selections in the input data frame. The argument 'n' defines the number of comparisons (i.e. graphs) #' to be produced. The acoustic pairwise distance between signals is shown next #' to the arrows linking them. The font color of a distance value correspond to the font #' color of the method that generated it, as shown in the scatterplots. Distances are #' standardized, being 0 the distance of a signal to itself and 1 the farthest pairwise #' distance in the pool of signals. Principal Component Analysis (\code{\link[stats]{prcomp}}) #' is applied to calculate distances when using spectral parameters (SP) and descriptors of cepstral coefficients (MFCC). In those cases the first 2 PC's are used. Classical #' Multidimensional Scalling (also known as Principal Coordinates Analysis, #' (\code{\link[stats]{cmdscale}})) is used for cross-correlation (XCORR) and any dynamic time warping method. The graphs are return as image files in the #' working directory. The file name contains the methods being compared and the #' row number of the selections. This function uses internally a modified version #' of the \code{\link[seewave]{spectro}} function from seewave package to create spectrograms. Custom data can also be compared against the available methods (or against each other) using the arguments 'custom1' and 'custom2'. #' @seealso \code{\link{catalog}} #' @examples #' \dontrun{ #' # Save to temporary working directory #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' #' compare_methods( #' X = lbh_selec_table, flim = c(0, 10), bp = c(0, 10), mar = 0.1, wl = 300, #' ovlp = 90, res = 200, n = 10, length.out = 30, #' methods = c("XCORR", "dfDTW"), parallel = 1, it = "jpeg", path = tempdir() #' ) #' #' # remove progress bar #' compare_methods( #' X = lbh_selec_table, flim = c(0, 10), bp = c(0, 10), mar = 0.1, wl = 300, #' ovlp = 90, res = 200, n = 10, length.out = 30, #' methods = c("XCORR", "dfDTW"), parallel = 1, it = "jpeg", pb = FALSE, path = tempdir() #' ) #' #' # check this folder! #' getwd() #' #' #' # compare SP and XCORR #' compare_methods( #' X = lbh_selec_table, flim = c(0, 10), bp = c(0, 10), mar = 0.1, wl = 300, #' ovlp = 90, res = 200, n = 10, length.out = 30, #' methods = c("XCORR", "SP"), parallel = 1, it = "jpeg", path = tempdir() #' ) #' #' # compare SP method against dfDTW #' compare_methods( #' X = lbh_selec_table, flim = c(0, 10), bp = c(0, 10), mar = 0.1, wl = 300, #' ovlp = 90, res = 200, n = 10, length.out = 30, #' methods = c("dfDTW", "SP"), parallel = 1, it = "jpeg", #' path = tempdir() #' ) #' #' # alternatively we can provide our own SP matrix #' Y <- spectro_analysis(lbh_selec_table, path = tempdir()) #' #' # selec a subset of variables #' Y <- Y[, 1:7] #' #' # PCA #' Y <- prcomp(Y[, 3:ncol(Y)])$x #' #' # add sound files and selec columns #' Y <- data.frame(lbh_selec_table[, c(1, 3)], Y[, 1:2]) #' #' compare_methods( #' X = lbh_selec_table, methods = c("dfDTW"), custom1 = Y, #' path = tempdir() #' ) #' } #' #' @references {Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191.} #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}). It uses #' internally a modified version of the \code{\link[seewave]{spectro}} function from #' seewave package to create spectrograms. # last modification on mar-13-2018 (MAS) compare_methods <- function(X = NULL, flim = NULL, bp = NULL, mar = 0.1, wl = 512, ovlp = 90, res = 150, n = 10, length.out = 30, methods = NULL, it = "jpeg", parallel = 1, path = NULL, sp = NULL, custom1 = NULL, custom2 = NULL, pb = TRUE, grid = TRUE, clip.edges = TRUE, threshold = 15, na.rm = FALSE, scale = FALSE, pal = reverse.gray.colors.2, img = TRUE, ...) { # define number of steps in analysis to print message steps <- c(current = 1, total = 0) if (pb) { steps[2] <- 3 if (any(methods == "XCORR")) steps[2] <- steps[2] + 1 if (!is.null(custom1)) steps[2] <- steps[2] - 1 if (!is.null(custom2)) steps[2] <- steps[2] - 1 # for functions with no internal step count total.steps <- steps[2] current.step <- 1 # set internally options("int_warbleR_steps" = steps) on.exit(options("int_warbleR_steps" = c(current = 0, total = 0)), add = TRUE) } #### set arguments from options # get function arguments argms <- methods::formalArgs(compare_methods) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 options(warn = -1) on.exit(options(warn = 0), add = TRUE) # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop("'path' provided does not exist") } else { path <- normalizePath(path) } # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X))) stop("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") # check basic columns in X if (!all(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))) { stop(paste(paste(c("sound.files", "selec", "start", "end")[!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } # if parallel is not numeric if (!is.numeric(parallel)) stop("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop("'parallel' should be a positive integer") # methods if (is.null(methods)) { if (is.null(custom1) & is.null(custom2)) stop("'methods' or custom data should be provided") else methods <- c(NA, NA) } else { if (length(methods) < 2 & is.null(custom1) & is.null(custom2)) stop("must provide 2 methods or custom data") if (length(methods) > 1 & !is.null(custom1) & is.null(custom2)) stop("only 1 method needed") if (length(setdiff(methods, c("XCORR", "dfDTW", "ffDTW", "SP", "SPharm", "MFCC"))) > 0) { stop(paste(setdiff(methods, c("XCORR", "dfDTW", "ffDTW", "SP", "SPharm", "MFCC")), "is (are) not valid method(s)")) } } # if flim is not vector or length!=2 stop if (!is.null(flim)) { if (!is.vector(flim)) { stop("'flim' must be a numeric vector of length 2") } else { if (!length(flim) == 2) stop("'flim' must be a numeric vector of length 2") } } # if bp is not vector or length!=2 stop if (!is.null(bp)) { if (!is.vector(bp)) { stop("'bp' must be a numeric vector of length 2") } else { if (!length(bp) == 2) stop("'bp' must be a numeric vector of length 2") } } # if wl is not vector or length!=1 stop if (is.null(wl)) { stop("'wl' must be a numeric vector of length 1") } else { if (!is.vector(wl)) { stop("'wl' must be a numeric vector of length 1") } else { if (!length(wl) == 1) stop("'wl' must be a numeric vector of length 1") } } # if res is not vector or length!=1 stop if (is.null(res)) { stop("'res' must be a numeric vector of length 1") } else { if (!is.vector(res)) { stop("'res' must be a numeric vector of length 1") } else { if (!length(res) == 1) stop("'res' must be a numeric vector of length 1") } } # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop("NAs found in start and/or end") # if any start higher than end stop if (any(X$end - X$start <= 0)) stop(paste("Start is higher than or equal to end in", length(which(X$end - X$start <= 0)), "case(s)")) # if any selections longer than 20 secs stop if (any(X$end - X$start > 20)) stop(paste(length(which(X$end - X$start > 20)), "selection(s) longer than 20 sec")) # If n is not numeric if (!is.numeric(n)) stop("'n' must be a numeric vector of length 1") if (any(!(n %% 1 == 0), n < 1)) stop("'n' should be a positive integer") # If length.out is not numeric if (!is.numeric(length.out)) stop("'length.out' must be a numeric vector of length 1") if (any(!(length.out %% 1 == 0), length.out < 1)) stop("'length.out' should be a positive integer") # return warning if not all sound files were found if (!is_extended_selection_table(X)) { fs <- list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE) if (length(unique(X$sound.files[(X$sound.files %in% fs)])) != length(unique(X$sound.files))) { message2(paste( length(unique(X$sound.files)) - length(unique(X$sound.files[(X$sound.files %in% fs)])), "sound file(s) not found" )) } # count number of sound files in working directory and if 0 stop d <- which(X$sound.files %in% fs) if (length(d) == 0) { stop("The sound files are not in the working directory") } else { X <- X[d, ] } } # check sp data frame if (!is.null(sp)) warning2(x = "'sp' has been deprecated and will be ignored. Use 'custom1' instead") # check custom1 data frame if (!is.null(custom1)) { if (!is.data.frame(custom1)) stop("'custom1' must be a data frame") if (nrow(custom1) != nrow(X)) stop("'custom1' must have the same number of selections than X") if (ncol(custom1) != 4) stop("'custom1' must have 4 columns") if (!all(c("sound.files", "selec") %in% names(custom1))) stop("'sound.files' or 'selec' columns missing in 'custom1'") # over write method names if (is.null(custom2)) { methods[2] <- "custom1" } else { methods[1] <- "custom1" } } # check custom2 data frame if (!is.null(custom2)) { if (!is.null(custom2) & is.null(custom1)) stop("please provide 'custom1' first") if (!is.data.frame(custom2)) stop("'custom1' must be a data frame") if (nrow(custom2) != nrow(X)) stop("'custom1' must have the same number of selections than X") if (ncol(custom2) != 4) stop("'custom2' must have 4 columns") if (!all(c("sound.files", "selec") %in% names(custom2))) stop("'sound.files' or 'selec' columns missing in 'custom1'") methods[2] <- "custom2" } # if it argument is not "jpeg" or "tiff" if (!any(it == "jpeg", it == "tiff")) stop(paste("Image type", it, "not allowed")) # create empty list for method results bidims <- list() if ("custom1" %in% methods) { if (anyNA(custom1)) stop("NAs were found in 'custom1'") if (length(setdiff(paste(custom1$sound.files, custom1$selec), paste(X$sound.files, X$selec))) > 0) stop("some/all custom 1 'sound.files' and/or 'selec' values don't match with those in 'X'") custom1 <- custom1[match(paste(custom1$sound.files, custom1$selec), paste(X$sound.files, X$selec)), ] bidims[[length(bidims) + 1]] <- custom1[, 3:4] } if ("custom2" %in% methods) { if (anyNA(custom2)) stop("NAs were found in 'custom2'") if (length(setdiff(paste(custom2$sound.files, custom2$selec), paste(X$sound.files, X$selec))) > 0) stop("some/all custom 2 'sound.files' and/or 'selec' values don't match with those in 'X'") custom2 <- custom2[match(paste(X$sound.files, X$selec), paste(custom2$sound.files, custom2$selec)), ] bidims[[length(bidims) + 1]] <- custom2[, 3:4] } if ("XCORR" %in% methods) { xcmat <- warbleR::cross_correlation(X, wl = wl, bp = bp, ovlp = ovlp, parallel = parallel, pb = pb, na.rm = na.rm, path = path, dens = NULL) MDSxcorr <- stats::cmdscale(1 - xcmat) MDSxcorr <- scale(MDSxcorr) bidims[[length(bidims) + 1]] <- MDSxcorr # remove the ones that failed cross-corr if (na.rm) X <- X[paste(X$sound.files, X$selec, sep = "-") %in% rownames(MDSxcorr), ] # update number of steps current.step <- steps[1] <- steps[1] + 2 options("int_warbleR_steps" = steps) } if ("dfDTW" %in% methods) { if (pb) { message2(x = paste0("measuring dominant frequency contours (step ", current.step, " of ", total.steps, "):"), color = "black") } dtwmat <- warbleR::freq_ts(X, wl = wl, flim = flim, ovlp = ovlp, img = FALSE, parallel = parallel, length.out = length.out, pb = pb, clip.edges = clip.edges, threshold = threshold, path = path ) dtwmat <- dtwmat[, 3:ncol(dtwmat)] if (scale) { dtwmat <- t(apply(dtwmat, 1, scale)) } dm <- dtw::dtwDist(dtwmat, dtwmat, method = "DTW") MDSdtw <- stats::cmdscale(dm) MDSdtw <- scale(MDSdtw) bidims[[length(bidims) + 1]] <- MDSdtw # update number of steps current.step <- steps[1] <- steps[1] + 1 options("int_warbleR_steps" = steps) } if ("ffDTW" %in% methods) { if (pb) { message2(x = paste0("measuring fundamental frequency contours (step ", current.step, " of ", total.steps, "):"), "black") } dtwmat <- warbleR::freq_ts(X, type = "fundamental", bp = bp, wl = wl, flim = flim, ovlp = ovlp, img = FALSE, parallel = parallel, length.out = length.out, ff.method = "seewave", pb = pb, clip.edges = clip.edges, threshold = threshold, path = path ) dtwmat <- dtwmat[, 3:ncol(dtwmat)] if (scale) { dtwmat <- t(apply(dtwmat, 1, scale)) } dm <- dtw::dtwDist(dtwmat, dtwmat, method = "DTW") MDSdtw <- stats::cmdscale(dm) MDSdtw <- scale(MDSdtw) bidims[[length(bidims) + 1]] <- MDSdtw # update number of steps current.step <- steps[1] <- steps[1] + 1 options("int_warbleR_steps" = steps) } if ("SP" %in% methods) { if (pb) { message2(x = paste0("measuring spectral parameters (step ", current.step, " of ", total.steps, "):"), color = "black") } spmat <- warbleR::spectro_analysis(X, wl = wl, bp = bp, parallel = parallel, pb = pb, threshold = threshold, harmonicity = FALSE, path = path) PCsp <- prcomp(scale(spmat[, 3:ncol(spmat)]), center = TRUE, scale. = TRUE, rank. = 2)$x bidims[[length(bidims) + 1]] <- PCsp # update number of steps current.step <- steps[1] <- steps[1] + 1 options("int_warbleR_steps" = steps) } if ("SPharm" %in% methods) { if (pb) { message2(x = paste0("measuring spectral parameters + harmonicity (step ", current.step, " of ", total.steps, "):"), "black") } spmat <- warbleR::spectro_analysis(X, wl = wl, bp = bp, parallel = parallel, pb = pb, threshold = threshold, harmonicity = TRUE, path = path) if (any(sapply(spmat, anyNA))) { spmat <- spmat[, !sapply(spmat, anyNA)] warning2("some NAs prdouced by SPharm, columns were removed") } PCsp <- prcomp(scale(spmat[, 3:ncol(spmat)]), center = TRUE, scale. = TRUE, rank. = 2)$x bidims[[length(bidims) + 1]] <- PCsp # update number of steps current.step <- steps[1] <- steps[1] + 1 options("int_warbleR_steps" = steps) } if ("MFCC" %in% methods) { if (pb) { message2(x = paste0("measuring mel frequency cepstral coefficients (step ", current.step, " of ", total.steps, "):"), "black") } mfcc <- warbleR::mfcc_stats(X, wl = wl, bp = bp, parallel = parallel, pb = pb, path = path) if (any(sapply(mfcc, anyNA))) stop("NAs generated when calculated MFCC's, try a higher 'wl'") PCmfcc <- prcomp(mfcc[, 3:ncol(mfcc)], center = TRUE, scale. = TRUE, rank. = 2)$x bidims[[length(bidims) + 1]] <- PCmfcc # update number of steps current.step <- steps[1] <- steps[1] + 1 options("int_warbleR_steps" = steps) } # name matchs changing order to match order in whic methods are ran nms <- match(c("custom1", "custom2", "XCORR", "dfDTW", "ffDTW", "SP", "SPharm", "MFCC"), methods) # add names names(bidims) <- c("custom1", "custom2", "XCORR", "dfDTW", "ffDTW", "SP", "SPharm", "MFCC")[!is.na(nms)] # maxdist <- lapply(bidims, function(x) max(stats::dist(x))) X$labels <- 1:nrow(X) # maximum of 100 items for combinations smps <- sample(x = 1:nrow(X), size = ifelse(nrow(X) > 100, 100, nrow(X))) combs <- combn(smps, 4) if (nrow(X) == 4) { n <- 1 combs <- as.matrix(1:4) message2("Only 1 possible combination of signals") } else if (n > ncol(combs)) { n <- ncol(combs) message2(paste("Only", n, "possible combinations of signals")) } if (nrow(X) > 4) combs <- as.data.frame(combs[, sample(seq_len(ncol(combs)), n)]) # create matrix for sppliting screen m <- rbind( c(0, 2.5 / 7, 3 / 10, 5 / 10), # 1 c(4.5 / 7, 1, 3 / 10, 5 / 10), # 2 c(0, 2.5 / 7, 0, 2 / 10), # 3 c(4.5 / 7, 1, 0, 2 / 10), # 4 c(0, 1 / 2, 5 / 10, 9 / 10), # 5 c(1 / 2, 1, 5 / 10, 9 / 10), # 6 c(0, 2.5 / 7, 2 / 10, 3 / 10), # 7 c(2.5 / 7, 4.5 / 7, 0, 5 / 10), # 8 c(4.5 / 7, 1, 2 / 10, 3 / 10), # 9 c(0, 3.5 / 7, 9 / 10, 10 / 10), # 10 c(3.5 / 7, 1, 9 / 10, 10 / 10) ) # 11 # screen 1:4 for spectros # screen 5,6 for scatterplots # screen 7:9 for similarities/arrows # screen 10:11 method labels comp.methFUN <- function(X, u, res, bidims, m, mar, flim) { rs <- combs[, u] X <- X[rs, ] if (img) { img_wrlbr_int(filename = paste("comp.meth-", names(bidims)[1], "-", names(bidims)[2], "-", paste(X$labels, collapse = "-"), paste0(".", it), sep = ""), path = path, width = 16.25, height = 16.25, units = "cm", res = res) } graphics::split.screen(m, erase = FALSE) mxdur <- max(X$end - X$start) + mar * 2 # set colors for numbers in scatterplots and spectrograms col <- rep("gray40", nrow(bidims[[1]])) col <- adjustcolor(col, alpha.f = 0.5) col[rs] <- hcl(h = seq(15, 375, length = 4 + 1), l = 65, c = 100)[1:4] col[rs] <- adjustcolor(col[rs], alpha.f = 0.8) invisible(lapply(c(7:9, 1:4, 5:6, 10:11), function(x) { graphics::screen(x, new = FALSE) par(mar = rep(0, 4)) if (x < 5) { r <- warbleR::read_sound_file(X = X, path = path, index = x, header = TRUE) tlim <- c((X$end[x] - X$start[x]) / 2 + X$start[x] - mxdur / 2, (X$end[x] - X$start[x]) / 2 + X$start[x] + mxdur / 2) mar1 <- X$start[x] - tlim[1] mar2 <- mar1 + X$end[x] - X$start[x] if (tlim[1] < 0) { tlim1.fix <- TRUE tlim[2] <- abs(tlim[1]) + tlim[2] mar1 <- mar1 + tlim[1] mar2 <- mar2 + tlim[1] tlim[1] <- 0 } else { tlim1.fix <- FALSE } if (tlim[2] > r$samples / r$sample.rate) { if (!tlim1.fix) { tlim[1] <- tlim[1] - (r$samples / r$sample.rate - tlim[2]) mar1 <- X$start[x] - tlim[1] mar2 <- mar1 + X$end[x] - X$start[x] tlim[2] <- r$samples / r$sample.rate } else { tlim[2] <- r$samples / r$sample.rate } } if (is.null(flim)) { flim <- c(0, floor(r$sample.rate / 2000)) } if (flim[2] > floor(r$sample.rate / 2000)) flim[2] <- floor(r$sample.rate / 2000) r <- warbleR::read_sound_file(X = X, path = path, index = x, from = tlim[1], to = tlim[2]) spectro_wrblr_int2(wave = r, f = [email protected], flim = flim, wl = wl, ovlp = ovlp, axisX = FALSE, axisY = FALSE, tlab = FALSE, flab = FALSE, palette = pal, grid = grid, ...) box(lwd = 2) if (x == 1 | x == 3) { text(tlim[2] - tlim[1], ((flim[2] - flim[1]) * 0.86) + flim[1], labels = X$labels[x], col = col[rs[x]], cex = 1.5, font = 2, pos = 2) } else { text(0, ((flim[2] - flim[1]) * 0.86) + flim[1], labels = X$labels[x], col = col[rs[x]], cex = 1.5, font = 2, pos = 4) } if (grid) { abline(v = c(mar1, mar2), lty = 4, col = "gray") } } # upper left if (x == 5) { plot(bidims[[1]], col = "white", xaxt = "n", yaxt = "n", xlim = c(min(bidims[[1]][, 1]) * 1.1, max(bidims[[1]][, 1]) * 1.1), ylim = c(min(bidims[[1]][, 2]) * 1.1, max(bidims[[1]][, 2]) * 1.1)) box(lwd = 4) centro <- apply(bidims[[1]], 2, mean) points(centro[1], centro[2], pch = 20, cex = 2, col = "gray3") cex <- rep(1, nrow(bidims[[1]])) cex[rs] <- 1.4 text(bidims[[1]], labels = 1:nrow(bidims[[1]]), col = col, cex = cex, font = 2) } # upper right if (x == 6) { plot(bidims[[2]], col = "white", xaxt = "n", yaxt = "n", xlim = c(min(bidims[[2]][, 1]) * 1.1, max(bidims[[2]][, 1]) * 1.1), ylim = c(min(bidims[[2]][, 2]) * 1.1, max(bidims[[2]][, 2]) * 1.1)) box(lwd = 4) centro <- apply(bidims[[2]], 2, mean) points(centro[1], centro[2], pch = 20, cex = 2, col = "gray3") cex <- rep(1, nrow(bidims[[2]])) cex[rs] <- 1.4 text(bidims[[2]], labels = 1:nrow(bidims[[2]]), col = col, cex = cex, font = 2) } # lower mid if (x == 8) { plot(0.5, xlim = c(0, 1), ylim = c(0, 1), type = "n", axes = FALSE, xlab = "", ylab = "", xaxt = "n", yaxt = "n") lim <- par("usr") rect(lim[1], lim[3] - 1, lim[2], lim[4] + 1, border = adjustcolor("#EFAA7B", alpha.f = 0), col = adjustcolor("#EFAA7B", alpha.f = 0.15)) arrows(0, 5.5 / 7, 1, 5.5 / 7, code = 3, length = 0.09, lwd = 2) text(0.5, 5.36 / 7, labels = round(stats::dist(bidims[[1]][rs[c(1, 2)], ]) / maxdist[[1]], 2), col = "black", font = 2, pos = 3) text(0.5, 5.545 / 7, labels = round(stats::dist(bidims[[2]][rs[c(1, 2)], ]) / maxdist[[2]], 2), col = "gray50", font = 2, pos = 1) arrows(0, 1.5 / 7, 1, 1.5 / 7, code = 3, length = 0.09, lwd = 2) text(0.5, 1.4 / 7, labels = round(stats::dist(bidims[[1]][rs[c(3, 4)], ]) / maxdist[[1]], 2), col = "black", font = 2, pos = 3) text(0.5, 1.63 / 7, labels = round(stats::dist(bidims[[2]][rs[c(3, 4)], ]) / maxdist[[2]], 2), col = "gray50", font = 2, pos = 1) arrows(0, 2 / 7, 1, 5 / 7, code = 3, length = 0.09, lwd = 2) text(0.69, 4.16 / 7, labels = round(stats::dist(bidims[[1]][rs[c(2, 3)], ]) / maxdist[[1]], 2), col = "black", font = 2, pos = 3) text(0.85, 4.4 / 7, labels = round(stats::dist(bidims[[2]][rs[c(2, 3)], ]) / maxdist[[2]], 2), col = "gray50", font = 2, pos = 1) arrows(0, 5 / 7, 1, 2 / 7, code = 3, length = 0.09, lwd = 2) text(0.3, 4.16 / 7, labels = round(stats::dist(bidims[[1]][rs[c(1, 4)], ]) / maxdist[[1]], 2), col = "black", font = 2, pos = 3) text(0.15, 4.4 / 7, labels = round(stats::dist(bidims[[2]][rs[c(1, 4)], ]) / maxdist[[2]], 2), col = "gray50", font = 2, pos = 1) } # in between left if (x == 7) { plot(0.5, xlim = c(0, 1), ylim = c(0, 1), type = "n", axes = FALSE, xlab = "", ylab = "", xaxt = "n", yaxt = "n") lim <- par("usr") rect(lim[1], lim[3] - 1, lim[2], lim[4] + 1, border = adjustcolor("#EFAA7B", alpha.f = 0.15), col = adjustcolor("#EFAA7B", alpha.f = 0.15)) arrows(0.5, 0, 0.5, 1, code = 3, length = 0.09, lwd = 2) text(0.53, 0.5, labels = round(stats::dist(bidims[[1]][rs[c(1, 3)], ]) / maxdist[[1]], 2), col = "black", font = 2, pos = 2) text(0.47, 0.5, labels = round(stats::dist(bidims[[2]][rs[c(1, 3)], ]) / maxdist[[2]], 2), col = "gray50", font = 2, pos = 4) } # in between right if (x == 9) { plot(0.5, xlim = c(0, 1), ylim = c(0, 1), type = "n", axes = FALSE, xlab = "", ylab = "", xaxt = "n", yaxt = "n") lim <- par("usr") rect(lim[1], lim[3] - 1, lim[2], lim[4] + 1, border = adjustcolor("#EFAA7B", alpha.f = 0.15), col = adjustcolor("#EFAA7B", alpha.f = 0.15)) arrows(0.5, 0, 0.5, 1, code = 3, length = 0.09, lwd = 2) text(0.53, 0.5, labels = round(stats::dist(bidims[[1]][rs[c(2, 4)], ]) / maxdist[[1]], 2), col = "black", font = 2, pos = 2) text(0.47, 0.5, labels = round(stats::dist(bidims[[2]][rs[c(2, 4)], ]) / maxdist[[2]], 2), col = "gray50", font = 2, pos = 4) } # top (for method labels) if (x == 10) { plot(0.5, xlim = c(0, 1), ylim = c(0, 1), type = "n", axes = FALSE, xlab = "", ylab = "", xaxt = "n", yaxt = "n") lim <- par("usr") rect(lim[1], lim[3] - 1, lim[2], lim[4] + 1, border = "black", col = adjustcolor("#4ABDAC", alpha.f = 0.3)) text(0.5, 0.5, labels = names(bidims)[1], col = "black", font = 2, cex = 1.2) box(lwd = 4) } if (x == 11) { plot(0.5, xlim = c(0, 1), ylim = c(0, 1), type = "n", axes = FALSE, xlab = "", ylab = "", xaxt = "n", yaxt = "n") lim <- par("usr") rect(lim[1], lim[3] - 1, lim[2], lim[4] + 1, border = "black", col = adjustcolor("#4ABDAC", alpha.f = 0.3)) text(0.5, 0.5, labels = names(bidims)[2], col = "gray50", font = 2, cex = 1.2) box(lwd = 4) } })) if (img) { invisible(dev.off()) } on.exit(invisible(close.screen(all.screens = TRUE))) } # save image files if (pb) { message2(x = paste0("creating image files (step ", current.step, " of ", total.steps, "):"), "black") } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } a1 <- pblapply_wrblr_int(pbar = pb, X = seq_len(ncol(combs)), cl = cl, FUN = function(u) { comp.methFUN(X, u, res, bidims, m, mar, flim) }) return(NULL) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/compare_methods.R
#' Consolidate (sound) files into a single directory #' #' \code{consolidate} copies (sound) files scattered in several directories into a single one. #' @export consolidate #' @usage consolidate(files = NULL, path = NULL, dest.path = NULL, pb = TRUE, file.ext = ".wav$", #' parallel = 1, save.csv = TRUE, ...) #' @param files character vector indicating the subset of files that will be consolidated. File names should include the full file path. Optional. #' @param path Character string containing the directory path where the sound files are located. #' 'wav.path' set by \code{\link{warbleR_options}} is ignored. #' If \code{NULL} (default) then the current working directory is used. #' @param dest.path Character string containing the directory path where the sound files will be saved. #' If \code{NULL} (default) then the current working directory is used. #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @param file.ext Character string defining the file extension (i.e. format) for the files to be consolidated. Default is \code{'.wav$'} ignoring case. Several formats can be used: \code{"\\.wav$|\\.wac$|\\.mp3$|\\.flac$"}. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param save.csv Logical. Controls whether a data frame containing sound file information is saved in the new directory. Default is \code{TRUE}. #' @param ... Additional arguments to be passed to the internal \code{\link[base:files]{file.copy}} function for customizing file copying. #' @return All (sound) files are consolidated (copied) to a single directory ("consolidated_files"). The function returns a data frame with each of the files that were copied in a row and the following information: #' \itemize{ #' \item \code{original_dir} the path to the original file #' \item \code{old_name} the name of the original file #' \item \code{new_name} the name of the new file. This will be the same as 'old_name' if the name was not duplicated (i.e. no files in other directories with the same name). #' \item \code{file_size_bytes} size of the file in bytes. #' \item \code{duplicate} indicates whether a file is likely to be duplicated (i.e. if files with the same name were found in other directories). If so it will be labeled as 'possible.dupl', otherwise it will contain NAs. #' } #' If \code{csv = TRUE} (default) #' a 'file_names_info.csv' file with the same information as the output data frame is also saved in the consolidated directory. #' @family sound file manipulation #' @seealso \code{\link{fix_wavs}} for making sound files readable in R #' @name consolidate #' @details This function allows users to put files scattered in several directories into a #' single one. By default it works on sound files in '.wav' format but can work with #' other type of files (for instance '.txt' selection files). #' @examples{ #' # save wav file examples #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) #' #' # create first folder with 2 sound files #' dir.create(file.path(tempdir(), "folder1")) #' writeWave(Phae.long1, file.path(tempdir(), "folder1", "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "folder1", "Phae.long2.wav")) #' #' # create second folder with 2 sound files #' dir.create(file.path(tempdir(), "folder2")) #' writeWave(Phae.long3, file.path(tempdir(), "folder2", "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "folder2", "Phae.long4.wav")) #' #' # consolidate in a single folder #' # consolidate(path = tempdir(), dest.path = tempdir()) #' #' # check this folder #' tempdir() #' } #' #' @references {Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191.} #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on jan-29-2018 (MAS) consolidate <- function(files = NULL, path = NULL, dest.path = NULL, pb = TRUE, file.ext = ".wav$", parallel = 1, save.csv = TRUE, ...) { # reset pb #### set arguments from options # get function arguments argms <- methods::formalArgs(consolidate) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # check path to working directory if (!is.null(dest.path)) { if (!dir.exists(dest.path)) { stop2("'dest.path' provided does not exist") } else { dest.path <- normalizePath(dest.path) } } else { dir.create(dest.path <- file.path(path, "consolidated_files"), showWarnings = FALSE) } # list files if (!is.null(files)) { fe <- file.exists(as.character(files)) # stop if files are not in working directory if (length(fe) == 0) stop2("files were not found") if (length(fe) < length(files)) message2("some files were not found") files <- files[fe] } else { files <- list.files(path = path, pattern = file.ext, ignore.case = TRUE, recursive = TRUE, full.names = TRUE) } # stop if files are not in working directory if (length(files) == 0) stop2("no files found in working directory and/or subdirectories") else message2(paste(length(files), "files were found\n")) # collect file metadata message2("Collecting file metadata (can take some time)\n") # create new names for duplicated songs old_name <- basename(files) files <- files[order(old_name)] old_name <- old_name[order(old_name)] file_size_bytes <- file.size(files) # rename if any duplicated names new_name <- unlist(lapply( unique(old_name), function(x) { on <- old_name[old_name == x] if (length(on) > 1) { return(paste0(gsub(file.ext, "", on, ignore.case = TRUE), "-", seq_len(length(on)), gsub("$", "", file.ext, fixed = TRUE))) } else { return(x) } } )) new_name <- gsub("\\", "", new_name, fixed = TRUE) # create data frame with info from old and new names X <- data.frame(original_dir = gsub("\\.", path, dirname(files), fixed = TRUE), old_name, new_name, file_size_bytes, stringsAsFactors = FALSE) # label possible duplicates X$duplicate <- sapply(paste0(X$old_name, X$file_size_bytes), function(y) { if (length(which(paste0(X$old_name, X$file_size_bytes) == y)) > 1) { return("possible.dupl") } else { return(NA) } }) # If parallel is not numeric if (!is.numeric(parallel)) stop2("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop2("'parallel' should be a positive integer") # create function to run within Xapply functions downstream copyFUN <- function(i, dp, df) file.copy(from = file.path(df$original_dir[i], df$old_name[i]), to = file.path(dp, df$new_name[i]), ...) # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function a1 <- pblapply_wrblr_int(pbar = pb, X = 1:nrow(X), cl = cl, FUN = function(i) { copyFUN(i, dp = dest.path, df = X) }) if (save.csv) write.csv(X, row.names = FALSE, file = file.path(dest.path, "file_names_info.csv")) return(X) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/consolidate.R
#' Time-frequency cross-correlation #' #' \code{cross_correlation} estimates the similarity of two sound waves by means of time-frequency cross-correlation #' @usage cross_correlation(X, wl = 512, bp = "pairwise.freq.range", ovlp = 70, #' dens = NULL, wn = 'hanning', cor.method = "pearson", parallel = 1, #' path = NULL, pb = TRUE, na.rm = FALSE, cor.mat = NULL, output = "cor.mat", #' templates = NULL, surveys = NULL, compare.matrix = NULL, type = "fourier", #' nbands = 40, method = 1) #' @param X 'selection_table', 'extended_selection_table' or data frame containing columns for sound files (sound.files), #' selection number (selec), and start and end time of signal (start and end). #' All selections must have the same sampling rate. #' @param wl A numeric vector of length 1 specifying the window length of the spectrogram, default #' is 512. #' @param bp A numeric vector of length 2 for the lower and upper limits of a #' frequency bandpass filter (in kHz). If columns for bottom and top frequency ('bottom.freq' and 'top.freq') are supplied "pairwise.freq.range" ca be used (default). If so, the lowest values in 'bottom.freq' #' and the highest values in 'top.freq' for the selections involved in a pairwise comparison will be used as bandpass limits. #' @param ovlp Numeric vector of length 1 specifying \% of overlap between two #' consecutive windows, as in \code{\link[seewave]{spectro}}. Default is 70. High values of ovlp #' slow down the function but produce more accurate results. #' @param dens DEPRECATED. #' @param wn A character vector of length 1 specifying the window name as in \code{\link[seewave]{ftwindow}}. #' @param cor.method A character vector of length 1 specifying the correlation method as in \code{\link[stats]{cor}}. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @param na.rm Logical. If \code{TRUE} all NAs produced when pairwise cross-correlations failed are removed from the #' results. This means that all selections with at least 1 cross-correlation that failed are excluded. #' @param cor.mat DEPRECATED. Use 'compare.matrix' instead. #' @param output Character vector of length 1 to determine if only the correlation matrix is returned ('cor.mat', default) or a list ('list') containing 1) the correlation matrix and 2) a data frame with correlation values at each sliding step for each comparison. The list, which is also of class 'xcorr.output', can be used to find detection peaks with \code{\link{find_peaks}} or to graphically explore detections using \code{\link{lspec}}. #' @param templates Character vector with the selections in 'X' to be used as templates for cross-correlation detection. To refer to specific selections in 'X' the user must use the format "sound.file-selec" (e.g. "file1.wav-1"). If only the sound file name is included then the entire sound file is used as template. #' @param surveys Character vector with the selections in 'X' to be used as surveys for cross-correlation detection. To refer to specific selections in 'X' the user must use the format "sound.file-selec" (e.g. "file1.wav-1"). If only the sound file name is included then the entire sound file is used as survey. #' @param compare.matrix A character matrix with 2 columns indicating the selections to be compared (column 1 vs column 2). The columns must contained the ID of the selection, which is given by combining the 'sound.files' and 'selec' columns of 'X', separated by '-' (i.e. \code{paste(X$sound.files, X$selec, sep = "-")}). Default is \code{NULL}. If the 'selec' ID is not supplied then the entire sound file is used instead. If 'compare.matrix' is supplied only those comparisons will be calculated (as opposed to all pairwise comparisons as the default behavior) and the output will be a data frame composed of the supplied matrix and the correspondent cross-correlation values. Note that 'method' is automatically set to 2 (create spectrograms on the fly) when 'compare.matrix' is supplied but can be set back to 1. When supplied 'output' is forced to be 'list'. Note that the use of this function for signal detection (with 'compare.matrix') will be deprecated in future warbleR versions. Look at the ohun package for automatic signal detection functions. #' @param type A character vector of length 1 specifying the type of cross-correlation; either "fourier" (i.e. spectrographic cross-correlation using Fourier transform; internally using \code{\link[seewave]{spectro}}; default) or "mfcc" (Mel cepstral coefficient spectrogram cross-correlation; internally using \code{\link[tuneR]{melfcc}}). #' @param nbands Numeric vector of length 1 controlling the number of warped spectral bands to calculate when using \code{type = "mfcc"} (see \code{\link[tuneR]{melfcc}}). Default is 40. #' @param method Numeric vector of length 1 to control the method used to create spectrogram matrices. Two option are available: #' \itemize{ #' \item \code{1}: matrices are created first (keeping them internally as a list) and cross-correlation is calculated on a second step. Note that this method may require lots of memory if selection and or sound files are large. #' \item \code{2}: matrices are created "on the fly" (i.e. at the same time that cross-correlation is calculated). More memory efficient but may require extracting the same matrix several times, which will affect performance. Note that when using this method the function does not check if sound files have the same sampling rate which if not, may produce an error. #' } #' @return If \code{output = "cor.mat"} the function returns a matrix with #' the maximum (peak) correlation for each pairwise comparison (if 'compare.matrix' is not supplied) or the peak correlation for each comparison in the supplied 'compare.matrix'. Otherwise it will return a list that includes 1) a matrix with #' the maximum correlation for each pairwise comparison ('max.xcorr.matrix') and 2) a data frame with the correlation statistic for each "sliding" step ('scores'). #' @export #' @name cross_correlation #' @details This function calculates the pairwise similarity of multiple signals by means of time-frequency cross-correlation. Fourier or Mel frequency ceptral coefficients spectrograms can be used as time-frequency representations of sound. #' This method "slides" the spectrogram of the shortest selection over the longest one calculating a correlation of the amplitude values at each step. #' The function runs pairwise cross-correlations on several signals and returns a list including the correlation statistic #' for each "sliding" step as well as the maximum (peak) correlation for each pairwise comparison. #' The correlation matrix could have NA's if some of the pairwise correlation did not work (common when sound files have been modified by band-pass filters). Make sure all sound files have the same sampling rate (can be checked with \code{\link{check_sels}} or \code{\link{check_sound_files}}). #' #' @examples #' { #' # load data #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) #' #' # save sound files #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' #' # run cross correlation on spectrograms (SPCC) #' xcor <- cross_correlation(X = lbh_selec_table, wl = 300, ovlp = 90, path = tempdir()) #' #' # run cross correlation on Mel cepstral coefficients (mfccs) #' xcor <- cross_correlation( #' X = lbh_selec_table, wl = 300, ovlp = 90, path = tempdir(), #' type = "mfcc" #' ) #' #' # using the 'compare.matrix' argument to specify pairwise comparisons #' # create matrix with ID of signals to compare #' cmp.mt <- cbind( #' paste(lbh_selec_table$sound.files[1:10], lbh_selec_table$selec[1:10], sep = "-"), #' paste(lbh_selec_table$sound.files[2:11], lbh_selec_table$selec[2:11], sep = "-") #' ) #' #' # run cross-correlation on the selected pairwise comparisongs #' xcor <- cross_correlation( #' X = lbh_selec_table, compare.matrix = cmp.mt, #' wl = 300, ovlp = 90, path = tempdir() #' ) #' } #' @seealso \code{\link{mfcc_stats}}, \code{\link{spectro_analysis}}, \code{\link{freq_DTW}} #' @author Marcelo Araya-Salas \email{marcelo.araya@@ucr.ac.cr}) #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' #' H. Khanna, S.L.L. Gaunt & D.A. McCallum (1997). Digital spectrographic cross-correlation: tests of sensitivity. Bioacoustics 7(3): 209-234 #' #' Lyon, R. H., & Ordubadi, A. (1982). Use of cepstra in acoustical signal analysis. Journal of Mechanical Design, 104(2), 303-306. #' } # last modification on jan-03-2020 (MAS) cross_correlation <- function(X = NULL, wl = 512, bp = "pairwise.freq.range", ovlp = 70, dens = NULL, wn = "hanning", cor.method = "pearson", parallel = 1, path = NULL, pb = TRUE, na.rm = FALSE, cor.mat = NULL, output = "cor.mat", templates = NULL, surveys = NULL, compare.matrix = NULL, type = "fourier", nbands = 40, method = 1) { if (!is.null(compare.matrix) | !is.null(surveys)) { warning2("The use of this function for signal detection (with 'compare.matrix') will be deprecated in future warbleR versions, please look at the ohun package for automatic signal detection functions (https://marce10.github.io/ohun/index.html)") } #### set arguments from options # get function arguments argms <- methods::formalArgs(cross_correlation) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path) & !warbleR::is_extended_selection_table(X)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # if X is not a data frame if (!any(is.data.frame(X), warbleR::is_selection_table(X), warbleR::is_extended_selection_table(X))) stop2("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") # if is extended all should have the same sampling rate if (warbleR::is_extended_selection_table(X) & length(unique(attr(X, "check.results")$sample.rate)) > 1) stop2("all wave objects in the extended selection table must have the same sampling rate (they can be homogenized using resample_est_waves())") # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop2("NAs found in start and/or end") # stop if only 1 selection if (nrow(X) == 1 & is.null(compare.matrix)) stop2("you need more than one selection to do cross-correlation") # bp needed when no bottom and top freq if (bp[1] == "pairwise.freq.range" & is.null(X$bottom.freq)) stop2("'bp' must be supplied when no frequency range columns are found in 'X' (bottom.freq & top.freq)") # stop if no bp if (is.null(bp[1])) stop2("'bp' must be supplied") # dens deprecated if (!is.null(dens)) warning2(x = "'dens' has been deprecated and will be ignored") # dens deprecated if (!is.null(cor.mat)) warning2(x = "'cor.mat' has been deprecated and will be ignored") # check output if (!any(output %in% c("cor.mat", "list"))) stop2("'output' must be either 'cor.mat' or 'list'") # if wl is not vector or length!=1 stop if (!is.numeric(wl)) { stop2("'wl' must be a numeric vector of length 1") } else { if (!is.vector(wl)) { stop2("'wl' must be a numeric vector of length 1") } else { if (!length(wl) == 1) stop2("'wl' must be a numeric vector of length 1") } } # if ovlp is not vector or length!=1 stop if (!is.numeric(ovlp)) { stop2("'ovlp' must be a numeric vector of length 1") } else { if (!is.vector(ovlp)) { stop2("'ovlp' must be a numeric vector of length 1") } else { if (!length(ovlp) == 1) stop2("'ovlp' must be a numeric vector of length 1") } } # extended selection table only need sound files in the working directory when doing detection if (!warbleR::is_extended_selection_table(X) | warbleR::is_extended_selection_table(X) & !is.null(templates) | warbleR::is_extended_selection_table(X) & !is.null(compare.matrix)) { # return warning if not all sound files were found fs <- list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE) if (length(unique(X$sound.files[(X$sound.files %in% fs)])) != length(unique(X$sound.files)) & !warbleR::is_extended_selection_table(X)) { warning2(x = paste( length(unique(X$sound.files)) - length(unique(X$sound.files[(X$sound.files %in% fs)])), "sound file(s) not found" )) } # count number of sound files in working directory and if 0 stop if (!warbleR::is_extended_selection_table(X) | warbleR::is_extended_selection_table(X) & !is.null(templates) | warbleR::is_extended_selection_table(X) & !is.null(compare.matrix) & any(grep(pattern = "\\.wav$", x = compare.matrix[, 2], ignore.case = TRUE))) { d <- which(X$sound.files %in% fs) if (length(d) == 0) { stop2("The sound files are not in the working directory") } else { X <- X[d, ] } } } # If parallel is not numeric if (!is.numeric(parallel)) stop2("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop2("'parallel' should be a positive integer") # check sampling rate is the same for all selections if not a selection table if (warbleR::is_extended_selection_table(X) & length(unique(attr(X, "check.results")$sample.rate)) > 1) stop2("sampling rate must be the same for all selections") # add selection id column to X X$selection.id <- paste(X$sound.files, X$selec, sep = "-") # if templates were supplied if (!is.null(templates)) { if (!all(templates %in% X$selection.id)) { stop2("not all templates are referenced in 'X'") } } # check surveys if (!all(surveys %in% list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE))) { stop2("not all sound files in 'surveys' are found in the working directory or 'path'") } # if templates were supplied but no compare.matrix use files in working directory if (!is.null(templates) & is.null(compare.matrix)) { if (is.null(surveys)) { compare.matrix <- data.frame(X1 = rep(templates, length(fs)), X2 = fs) } else { compare.matrix <- data.frame(X1 = rep(templates, length(surveys)), X2 = surveys) } } if (!is.null(compare.matrix)) { output <- "list" } # keep only selections in supplied compare.matrix to improve performance if (!is.null(compare.matrix)) { X <- X[X$selection.id %in% unique(unlist(c(compare.matrix))), , drop = FALSE] # set method to 2 if not provided in call if (!any(names(call.argms) == "method")) { method <- 2 } } # define number of steps in analysis to print message if (pb) { steps <- getOption("int_warbleR_steps") if (steps[2] > 0) { current.step <- steps[1] total.steps <- steps[2] } else { if (method == 1) total.steps <- 2 else total.steps <- 1 current.step <- 1 } } # generate all possible combinations of selections, keep one with the original order of rows to create cor.table output if (is.null(compare.matrix)) { spc.cmbs.org <- spc.cmbs <- t(combn(X$selection.id, 2)) } else { # if all selections in compare.matrix are from X if (all(unlist(c(compare.matrix)) %in% X$selection.id)) { spc.cmbs.org <- spc.cmbs <- compare.matrix } else { # if some are complete sound files entire.sf <- setdiff(unlist(c(compare.matrix)), X$selection.id) # get duration of files wvdr <- warbleR::info_sound_files(path = path, pb = FALSE, skip.error = TRUE, files = entire.sf) # wvdr <- wvdr[wvdr$sound.files %in% entire.sf, ] # put it in a data frame names(wvdr)[2] <- "end" wvdr$start <- 0 wvdr$selec <- "entire.file" wvdr$selection.id <- paste(wvdr$sound.files, wvdr$selec, sep = "-") out <- lapply(1:nrow(wvdr), function(x) { # get selection that are compared against each complete sound file sls <- setdiff(c(compare.matrix[compare.matrix[, 1] %in% wvdr$sound.files[x] | compare.matrix[, 2] %in% wvdr$sound.files[x], ]), wvdr$sound.files[x]) # get freq range as min bottom and max top of all selections to be compared against a given sound file # channel is also the lowest suppressWarnings(df <- data.frame( wvdr[x, ], channel = min(X$channel[X$selection.id %in% sls]), bottom.freq = min(X$bottom.freq[X$selection.id %in% sls]), top.freq = max(X$top.freq[X$selection.id %in% sls]) )) return(df) }) wvdr <- do.call(rbind, out) if (length(unique(wvdr$sample.rate)) > 1) { stop2("not all sound files have the same sampling rate") } if (warbleR::is_extended_selection_table(X)) { if (unique(wvdr$sample.rate) != unique(attr(X, "check.results")$sample.rate)) { stop2("not all sound files have the same sampling rate than the wave objects in the extended selection table") } } # get intersect of column names int.nms <- intersect(names(X), names(wvdr)) X <- rbind(as.data.frame(X)[, int.nms, drop = FALSE], wvdr[, int.nms]) # change complete file names in compare matrix for (i in entire.sf) { compare.matrix[compare.matrix == i] <- paste(i, "entire.file", sep = "-") } # set new matrices to allow changes down stream spc.cmbs.org <- spc.cmbs <- compare.matrix } } # function to get spectrogram matrices spc_FUN <- function(j, pth, W, wlg, ovl, w, nbnds) { clp <- warbleR::read_sound_file(X = W, index = j, path = pth) if (type == "fourier" | type == "spectrogram") { spc <- seewave::spectro(wave = clp, wl = wlg, ovlp = ovl, wn = w, plot = FALSE, fftw = TRUE, norm = TRUE) } if (type == "mfcc" | type == "mel") { # calculate MFCCs spc <- melfcc(clp, nbands = nbnds, hoptime = (wlg / [email protected]) * ((if (ovl > 0) ovl else 100) / 100), wintime = wlg / [email protected], dcttype = "t3", fbtype = "htkmel", spec_out = TRUE) # change name of target element so it maches spectrogram output names names(spc)[2] <- "amp" # and flip spc$amp <- t(spc$amp) # add element with freq values for each band spc$freq <- seq(0, [email protected] / 2000, length.out = nbnds) } # replace inf by NA spc$amp[is.infinite(spc$amp)] <- NA return(spc) } if (method == 1) { # create spectrograms if (pb) { message2(x = paste0("creating spectrogram matrices (step ", current.step, " of ", total.steps, "):")) } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # get spectrogram for each selection spcs <- pblapply_wrblr_int(pbar = pb, X = 1:nrow(X), cl = cl, FUN = function(e) spc_FUN(j = e, pth = path, W = X, wlg = wl, ovl = ovlp, w = wn, nbnds = nbands)) # check sampling rate is the same for all selections if not a selection table if (!warbleR::is_extended_selection_table(X) & length(unique(sapply(spcs, function(x) length(x$freq)))) > 1) stop2("sampling rate must be the same for all selections") # add selection name names(spcs) <- X$selection.id } # create function to calculate correlation between 2 spectrograms XC_FUN <- function(spc1, spc2, b = bp, cm = cor.method) { # filter frequency ranges spc1$amp <- spc1$amp[spc1$freq >= b[1] & spc1$freq <= b[2], ] spc2$amp <- spc2$amp[which(spc2$freq >= b[1] & spc2$freq <= b[2]), ] # define short and long envelope for sliding one (short) over the other (long) if (ncol(spc1$amp) > ncol(spc2$amp)) { lg.spc <- spc1$amp shrt.spc <- spc2$amp } else { lg.spc <- spc2$amp shrt.spc <- spc1$amp } # get length of shortest minus 1 (1 if same length so it runs a single correlation) shrt.lgth <- ncol(shrt.spc) - 1 # steps for sliding one signal over the other stps <- ncol(lg.spc) - ncol(shrt.spc) # set sequence of steps, if <= 1 then just 1 step if (stps <= 1) stps <- 1 else stps <- 1:stps # calculate correlations at each step cors <- sapply(stps, function(x, cor.method = cm) { warbleR::try_na(cor(c(lg.spc[, x:(x + shrt.lgth)]), c(shrt.spc), method = cm, use = "pairwise.complete.obs")) }) return(cors) } # shuffle spectrograms index so are not compared in sequence, which makes progress bar more precise when some selections are much longer than others ord.shuf <- sample(1:nrow(spc.cmbs)) spc.cmbs <- spc.cmbs[ord.shuf, , drop = FALSE] # run cross-correlation if (pb) { message2(x = paste0("running cross-correlation (step ", if (current.step + 1 <= total.steps) current.step + 1 else total.steps, " of ", total.steps, "):")) } # set parallel cores if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # get correlation xcrrs <- pblapply_wrblr_int(pbar = pb, X = 1:nrow(spc.cmbs), cl = cl, FUN = function(j, BP = bp, cor.meth = cor.method) { if (BP[1] %in% c("pairwise.freq.range", "frange")) { BP <- c(min(X$bottom.freq[X$selection.id %in% spc.cmbs[j, ]]), max(X$top.freq[X$selection.id %in% spc.cmbs[j, ]])) } # extract amplitude matrices if (method == 1) { spc1 <- spcs[[spc.cmbs[j, 1]]] spc2 <- spcs[[spc.cmbs[j, 2]]] } if (method == 2) { spc1 <- spc_FUN(j = which(X$selection.id == spc.cmbs[j, 1]), pth = path, W = X, wlg = wl, ovl = ovlp, w = wn, nbnds = nbands) spc2 <- spc_FUN(j = which(X$selection.id == spc.cmbs[j, 2]), pth = path, W = X, wlg = wl, ovl = ovlp, w = wn, nbnds = nbands) } # get cross correlation XC_FUN(spc1 = spc1, spc2 = spc2, b = BP, cm = cor.meth) }) # order as originally xcrrs <- xcrrs[order(ord.shuf)] # extract maximum correlation mx.xcrrs <- sapply(xcrrs, max, na.rm = TRUE) # only create correlation matrix if compare matrix was not supplied if (is.null(compare.matrix)) { # create a similarity matrix with the max xcorr mat <- matrix(nrow = nrow(X), ncol = nrow(X)) mat[] <- 1 colnames(mat) <- rownames(mat) <- X$selection.id # add max correlations mat[lower.tri(mat, diag = FALSE)] <- mx.xcrrs mat <- t(mat) mat[lower.tri(mat, diag = FALSE)] <- mx.xcrrs # remove NA's if any if (na.rm) { com.case <- intersect(rownames(mat)[stats::complete.cases(mat)], colnames(mat)[stats::complete.cases(t(mat))]) if (length(which(is.na(mat))) > 0) { warning2(paste(length(which(is.na(mat))), "pairwise comparisons failed and were removed")) } # remove them from mat mat <- mat[rownames(mat) %in% com.case, colnames(mat) %in% com.case] if (nrow(mat) == 0) stop2("Not selections remained after removing NAs (na.rm = TRUE)") } } else { mat <- data.frame(compare.matrix, score = mx.xcrrs) if (na.rm) mat <- mat[!is.infinite(mat$score), ] } ## create correlation data matrix (keeps all correlation values, not only the maximum) # time is the one of the longest selection as the shortest is used as template if (output == "list") { cor.lst <- lapply(1:nrow(spc.cmbs.org), function(x) { # get duration of both selections durs <- c( (X$end - X$start)[X$selection.id == spc.cmbs.org[x, 1]], (X$end - X$start)[X$selection.id == spc.cmbs.org[x, 2]] ) # put in a data frame df <- suppressWarnings(data.frame( dyad = paste(spc.cmbs.org[x, ], collapse = "/"), sound.files = spc.cmbs.org[x, which.max(durs)], template = spc.cmbs.org[x, which.min(durs)], time = if (!is.null(xcrrs[[x]])) c(X$start[X$selection.id == spc.cmbs.org[x, 1]], X$start[X$selection.id == spc.cmbs.org[x, 2]])[which.max(durs)] + seq(min(durs) / 2, max(durs) - min(durs) / 2, length.out = length(xcrrs[[x]])) else NA, score = if (!is.null(xcrrs[[x]])) xcrrs[[x]] else NA )) return(df) }) # put together in a single dataframe cor.table <- do.call(rbind, cor.lst) # remove missing values if (na.rm) { if (exists("com.case")) { cor.table <- cor.table[cor.table$sound.files %in% com.case & cor.table$template %in% com.case, ] } errors <- cor.table[is.na(cor.table$score), ] errors$score <- NULL cor.table <- cor.table[!is.infinite(cor.table$score), ] } } # list results if (output == "cor.mat") { return(mat) } else { output_list <- list( max.xcorr.matrix = mat, scores = cor.table, org.selection.table = X, hop.size.ms = warbleR::read_sound_file(X, 1, header = TRUE, path = path)$sample.rate / wl, errors = if (na.rm) errors else NA, # parameters = lapply(call.argms, eval), parameters = call.argms, call = base::match.call(), spectrogram = type, warbleR.version = packageVersion("warbleR") ) class(output_list) <- c("list", "xcorr.output") return(output_list) } } ############################################################################################################## #' alternative name for \code{\link{cross_correlation}} #' #' @keywords internal #' @details see \code{\link{cross_correlation}} for documentation. \code{\link{xcorr}} will be deprecated in future versions. #' @export xcorr <- cross_correlation ############################################################################################################## #' print method for class \code{xcorr.output} #' #' @param x Object of class \code{xcorr.output}, generated by \code{\link{cross_correlation}}. #' @param ... further arguments passed to or from other methods. Ignored when printing selection tables. #' @keywords internal #' #' @export #' print.xcorr.output <- function(x, ...) { message2(color = "cyan", x = paste("Object of class", cli::style_bold("'xcorr.output'"))) message2(color = "silver", x = paste(cli::style_bold("\nContains:"), "The output of a detection routine from the following", cli::style_italic("cross_correlation()"), "call:")) cll <- paste0(deparse(x$call)) message2(color = "silver", x = cli::style_italic(gsub(" ", "", cll))) max.scores <- x$max.xcorr.matrix max.scores$X2 <- gsub("-entire.file", "", max.scores$X2) max.scores$score <- NULL names(max.scores) <- c("template", "survey") message2(color = "silver", x = paste("\n The routine was run on", x$spectrogram, "spectrograms using the following templates and surveys (selections or files in which templates were looked for):")) # print data frame # define columns to show cols <- if (ncol(max.scores) > 6) 1:6 else seq_len(ncol(max.scores)) kntr_tab <- knitr::kable(head(max.scores[, cols]), escape = FALSE, digits = 4, justify = "centre", format = "pipe") for (i in seq_len(length(kntr_tab))) { message2(color = "silver", x = paste0(kntr_tab[i])) } if (nrow(max.scores) > 6) { message2(color = "silver", x = paste0(if (ncol(max.scores) <= 6) "..." else "", " and ", nrow(max.scores) - 6, " more row(s) (run ", cli::style_italic(paste0(gsub("[^[:alnum:]=\\.]", "", x$call[2]), "$max.xcorr.matrix[, 1:2]")), " to see it all)")) } message2(color = "silver", x = paste(cli::style_bold("\nIncludes:"), "\n* A data frame ('max.xcorr.matrix') with the highest correlation value for each pair of templates and surveys")) message2(color = "silver", x = paste("\n* A data frame ('scores',", nrow(x$scores), "rows) with the cross correlation scores for each of the", nrow(max.scores), "template/survey combination(s)")) message2(color = "silver", x = paste("\n* A selection table data frame ('org.selection.table') referencing the templates location in sound files")) message2(color = "silver", x = paste("\n Use", cli::style_bold(cli::style_italic("full_spectrograms()")), "to plot cross_correlation scores along spectrograms")) message2(color = "silver", x = paste("\n Use", cli::style_bold(cli::style_italic("find_peaks()")), "to extract detections from this object")) # print warbleR version if (!is.null(x$warbleR.version)) { message2(color = "silver", x = paste0("\n Created by warbleR ", x$warbleR.version)) } else { message2(color = "silver", x = "\n Created by warbleR < 1.1.27") } }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/cross_correlation.R
#' Cut selections into individual sound files #' #' \code{cut_sels} cuts selections from a selection table into individual sound files. #' @export cut_sels #' @usage cut_sels(X, mar = 0.05, parallel = 1, path = NULL, dest.path = NULL, pb = TRUE, #' labels = c("sound.files", "selec"), overwrite = FALSE, norm = FALSE, #' keep.stereo = FALSE, ...) #' @param X object of class 'selection_table', 'extended_selection_table' or data frame containing columns for sound file name (sound.files), #' selection number (selec), and start and end time of signals (start and end). #' @param mar Numeric vector of length 1. Specifies the margins adjacent to the start and end points of selections, #' delineating spectrogram limits. Default is 0.05. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param dest.path Character string containing the directory path where the cut sound files will be saved. #' If \code{NULL} (default) then the directory containing the sound files will be used instead. #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @param labels String vector. Provides the column names that will be used as labels to #' create sound file names. Note that they should provide unique names (otherwise #' sound files will be overwritten). Default is \code{c("sound.files", "selec")}. #' @param overwrite Logical. If \code{TRUE} sound files with the same name will be #' overwritten. Default is \code{FALSE}. #' @param norm Logical indicating whether wave objects must be normalized first using the function \code{\link[tuneR]{normalize}}. Additional arguments can be passed to \code{\link[tuneR]{normalize}} using `...`.` Default is \code{FALSE}. See \code{\link[tuneR]{normalize}} for available options. #' @param keep.stereo Logical. If \code{TRUE} both channels are kept in the clips, oterwise it will keep the channel referenced in the channel column (if supplied) or the first channel if a 'channel' column is not found in 'X'. Only applies to stereo (2-channel) files. #' @param ... Additional arguments to be passed to the internal \code{\link[tuneR]{normalize}} function for customizing sound file output. Ignored if \code{norm = FALSE}. #' @return Sound files of the signals listed in the input data frame. #' @family selection manipulation #' @seealso \code{\link{seltailor}} for tailoring selections #' @name cut_sels #' @details This function allow users to produce individual sound files from the selections #' listed in a selection table as in \code{\link{lbh_selec_table}}. Note that wave objects with a bit depth of 32 might not be readable by some programs after exporting. In this case they should be "normalized" (argument 'norm") with a lower bit depth. The function keeps the original number of channels in the output clips only for 1- and 2-channel files. #' @examples{ #' # save wav file examples #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' #' # cut selections #' cut_sels(lbh_selec_table, path = tempdir()) #' #' #check this folder!! #' tempdir() #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) and Grace Smith Vidaurre # last modification on mar-12-2018 (MAS) cut_sels <- function(X, mar = 0.05, parallel = 1, path = NULL, dest.path = NULL, pb = TRUE, labels = c("sound.files", "selec"), overwrite = FALSE, norm = FALSE, keep.stereo = FALSE, ...) { #### set arguments from options # get function arguments argms <- methods::formalArgs(cut_sels) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # check path to destiny directory if (!is.null(dest.path)) { if (!dir.exists(dest.path)) { stop2("'dest.path' provided does not exist") } else { dest.path <- normalizePath(dest.path) } } else { dest.path <- path } # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X))) stop2("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") if (!all(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))) { stop2(paste(paste(c("sound.files", "selec", "start", "end")[!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } # create channel if not found if (!is.null(X$channel)) { X$channel <- 1 } # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop2("NAs found in start and/or end") # if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) stop2("'start' and 'end' must be numeric") # if any start higher than end stop if (any(X$end - X$start <= 0)) stop2(paste("Start is higher than or equal to end in", length(which(X$end - X$start <= 0)), "case(s)")) # missing label columns if (!all(labels %in% colnames(X))) { stop2(paste(paste(labels[!(labels %in% colnames(X))], collapse = ", "), "label column(s) not found in data frame")) } if (!is_extended_selection_table(X)) { # return warning if not all sound files were found recs.wd <- list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE) if (length(unique(X$sound.files[(X$sound.files %in% recs.wd)])) != length(unique(X$sound.files))) { (paste( length(unique(X$sound.files)) - length(unique(X$sound.files[(X$sound.files %in% recs.wd)])), "sound file(s) not found" )) } # count number of sound files in working directory and if 0 stop d <- which(X$sound.files %in% recs.wd) if (length(d) == 0) { stop2("The sound files are not in the working directory") } else { X <- X[d, ] } } else { X.orig <- X } # convert factors to characters X[, sapply(X, is.factor)] <- apply(X[, sapply(X, is.factor), drop = FALSE], 2, as.character) # remove .wav from sound file names X2 <- X X2$sound.files <- gsub("\\.wav$|\\.wac$|\\.mp3$|\\.flac$", "", X2$sound.files, ignore.case = TRUE) # If parallel is not numeric if (!is.numeric(parallel)) stop2("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop2("'parallel' should be a positive integer") # create function to run within Xapply functions downstream cutFUN <- function(X, i, mar, labels, dest.path, keep.stereo) { # Read sound files, initialize frequency and time limits for spectrogram r <- warbleR::read_sound_file(X = X, index = i, header = TRUE, path = path) f <- r$sample.rate t <- c(X$start[i] - mar, X$end[i] + mar) # fix margins if below 0 or length of recordings mar1 <- mar mar2 <- mar1 + X$end[i] - X$start[i] if (t[1] < 0) t[1] <- 0 if (t[2] > r$samples / f) t[2] <- r$samples / f # Cut wave wvcut <- warbleR::read_sound_file(X = X, path = path, index = i, from = t[1], to = t[2], channel = X$channel[i]) # add second channel if stereo if (keep.stereo & r$channels == 2) { wvcut_ch2 <- warbleR::read_sound_file(X = X, path = path, index = i, from = t[1], to = t[2], channel = setdiff(1:2, X$channel[i])) if (X$channel[i] == 1) { wvcut <- Wave(left = wvcut@left, right = wvcut_ch2@left, samp.rate = [email protected], bit = wvcut@bit) } else { wvcut <- Wave(left = wvcut_ch2@left, right = wvcut@left, samp.rate = [email protected], bit = wvcut@bit) } } # save cut if (overwrite) unlink(file.path(dest.path, paste0(paste(X2[i, labels], collapse = "-"), ".wav"))) if (norm) wvcut <- normalize(object = wvcut, ...) suppressWarnings(tuneR::writeWave(extensible = FALSE, object = wvcut, filename = file.path(dest.path, paste0(paste(X2[i, labels], collapse = "-"), ".wav")))) } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function out <- pblapply_wrblr_int(pbar = pb, X = 1:nrow(X), cl = cl, FUN = function(i) { cutFUN(X = X, i = i, mar = mar, labels = labels, dest.path = dest.path, keep.stereo) }) return(NULL) } ############################################################################################################## #' alternative name for \code{\link{cut_sels}} #' #' @keywords internal #' @details see \code{\link{cut_sels}} for documentation. \code{\link{cut_sels}} will be deprecated in future versions. #' @export cut_sels <- cut_sels
/scratch/gouwar.j/cran-all/cranData/warbleR/R/cut_sels.R
############################################################################################################## #' deprecated functions and function names #' #' @keywords internal #' @details functions that have been deprecated or moved to other packages. #' @export ffDTW <- ff_DTW <- function(...) warning2(x = "This function has been deprecated. DTW distances between fundamental frequency contours can be calculated using `freq_DTW`") freq_ts <- ff_ts <- function(...) warning2(x = "This function has been deprecated. Fundamental frequency contours can be calculated using `freq_ts`") dfts <- df_ts <- function(...) warning2(x = "This function has been deprecated. Dominant frequency contours can be calculated using `freq_ts`") sp.en.ts <- entropy_ts <- function(...) warning2(x = "This function has been deprecated. Spectral entropy contours can be calculated using `freq_ts`") quer_ml <- function(...) warning2(x = "This function has been removed temporarily due to API changes at Macaulay Library") xcorr.graph <- function(...) warning2(x = "This function has been deprecated as it was not compatible with changes to improve performance in 'xcorr()' (use corrplot package instead)") manualoc <- manual_loc <- function(...) warning2(x = "This function has been deprecated. Try Raven Software (Cornell Lab of Ornithology) or Audacity to manually annotate. The Rraven package (imp_raven) can be used for importing Raven annotations: try `install.packages('Rraven')`") compare.methods <- function(...) warning2(x = "This name has been deprecated. Please use `compare_methods` instead") find_annotations <- function(...) warning2(x = "This function has been removed due to API changes at audioblast.org") optimize_auto_detec <- function(...) warning2(x = "This function has been deprecated. Look at the package ohun for signal detection tools")
/scratch/gouwar.j/cran-all/cranData/warbleR/R/deprec_funs.R
#' Measure the duration of sound files #' #' \code{duration_sound_files} measures the duration of sound files #' @usage duration_sound_files(files = NULL, path = NULL, skip.error = FALSE, #' file.format = "\\\.wav$|\\\.wac$|\\\.mp3$|\\\.flac$") #' @param files Character vector with the names of the sound files to be measured. The sound files should be in the working directory or in the directory provided in 'path'. #' @param path Character string containing the directory path where the sound files are located. #' @param file.format Character string with the format of sound files. By default all sound file formats supported by warbleR are included ("\\.wav$|\\.wac$|\\.mp3$|\\.flac$"). Note that several formats can be included using regular expression syntax as in \code{\link[base]{grep}}. For instance \code{"\\.wav$|\\.mp3$"} will only include .wav and .mp3 files. #' @param skip.error Logical to control if errors are omitted. If so, files that could not be read will return \code{NA} in the 'duration' column. Default is \code{FALSE}, which will return an error if some files are problematic. #' If \code{NULL} (default) then the current working directory is used. #' @return A data frame with the duration (in seconds) of the sound files. #' @export #' @name duration_sound_files #' @details This function returns the duration (in seconds) of sound files. #' @examples #' { #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' #' duration_sound_files(path = tempdir()) #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on jul-5-2016 (MAS) duration_sound_files <- function(files = NULL, path = NULL, skip.error = FALSE, file.format = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$") { #### set arguments from options # get function arguments argms <- methods::formalArgs(duration_sound_files) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # stop if files is not a character vector if (!is.null(files) & !is.character(files)) stop2("'files' must be a character vector") if (is.null(files)) { files <- list.files(path = path, pattern = file.format, ignore.case = TRUE) } # list .wav files in working director # stop if no wav files are found if (length(files) == 0) stop2("no sound files in working directory") durs <- sapply(files, function(x) { # remove temporary file on.exit(rm(rec)) if (!skip.error) { rec <- read_sound_file(X = x, path = path, header = TRUE) dur <- rec$samples / rec$sample.rate } else { suppressWarnings(rec <- try(read_sound_file(X = x, path = path, header = TRUE), silent = TRUE)) if (is(rec, "try-error")) { dur <- NA } else { dur <- rec$samples / rec$sample.rate } } return(dur) }) return(data.frame(sound.files = files, duration = durs, row.names = NULL)) } ############################################################################################################## #' alternative name for \code{\link{duration_sound_files}} #' #' @keywords internal #' @details see \code{\link{duration_sound_files}} for documentation. \code{\link{wavdur}} will be deprecated in future versions. #' @export wavdur <- duration_sound_files ############################################################################################################## #' alternative name for \code{\link{duration_sound_files}} #' #' @keywords internal #' @details see \code{\link{duration_sound_files}} for documentation. \code{\link{wavdur}} will be deprecated in future versions. #' @export wav_dur <- duration_sound_files ############################################################################################################## #' alternative name for \code{\link{duration_sound_files}} #' #' @keywords internal #' @details see \code{\link{duration_sound_files}} for documentation. \code{\link{duration_wavs}} will be deprecated in future versions. #' @export duration_wavs <- duration_sound_files
/scratch/gouwar.j/cran-all/cranData/warbleR/R/duration_sound_files.R
#' Subset selection data frames based on manually filtered image files #' #' \code{filter_sels} subsets selection data frames based on image files that have been manually filtered. #' @usage filter_sels(X, path = NULL, lspec = FALSE, img.suffix = NULL, it = "jpeg", #' incl.wav = TRUE, missing = FALSE, index = FALSE) #' @param X object of class 'selection_table', 'extended_selection_table' or data frame with the following columns: 1) "sound.files": name of the .wav #' files, 2) "sel": number of the selections. #' @param path Character string containing the directory path where the image files are located. #' If \code{NULL} (default) then the current working directory is used. #' \code{\link{warbleR_options}} 'wav.path' argument does not apply. #' @param lspec A logical argument indicating if the image files to be use for filtering were produced by the function \code{\link{full_spectrograms}}. #' All the image files that correspond to a sound file must be deleted in order to be #' filtered out. #' @param img.suffix A character vector of length 1 with the suffix (label) at the end #' of the names of the image files. Default is \code{NULL} (i.e. no suffix as in the images #' produced by \code{\link{spectrograms}}). Ignored if \code{lspec = TRUE}. #' @param it A character vector of length 1 giving the image type ("tiff", "jpeg" or "pdf") Default is "jpeg". Note that pdf files can only be generated by \code{\link{lspec2pdf}}. #' @param incl.wav Logical. To indicate if sound files extensions are included ( \code{TRUE}, default) or not in the image #' file names. #' @param missing Logical. Controls whether the output data frame (or row index if is \code{index = TRUE}) #' contains the selections with images in the working directory (Default, \code{missing = FALSE}) #' or the ones with no image. #' @param index Logical. If \code{TRUE} and \code{missing = FALSE} the row index for the selections with images in the working directory is returned. If \code{missing = TRUE}) then the row index of the ones with no image is returned instead. Default is \code{FALSE}. #' @return If all sound files are ok, returns message "All files are ok!". #' Otherwise returns "These file(s) cannot be read" message with names of the #' corrupted sound files. #' @details This function subsets selections (or sound files if \code{lspec} is \code{TRUE}) listed in a data frame #' based on the image files from spectrogram-creating functions (e.g. \code{\link{spectrograms}}) in the #' working directory. Only the selections/sound files with and image in the working directory will remain. #' This is useful for excluding selections from undesired signals. Note that the #' image files should be in the working directory (or the directory provided in 'path'). #' @export #' @name filter_sels #' @examples \dontrun{ #' # save wav file examples #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' #' spectrograms(lbh_selec_table, #' flim = c(0, 11), inner.mar = c(4, 4.5, 2, 1), outer.mar = c(4, 2, 2, 1), #' picsize = 2, res = 300, cexlab = 2, mar = 0.05, wl = 300, path = tempdir() #' ) #' #' # go to the working directory (tempdir()) and delete some images #' #' # filter selection data frame #' fmloc <- filter_sels(X = lbh_selec_table, path = tempdir()) #' #' # this data frame does not have the selections corresponding to the images that were deleted #' fmloc #' #' # now using lspec images #' full_spectrograms( #' sxrow = 2, rows = 8, pal = reverse.heat.colors, wl = 300, ovlp = 10, #' path = tempdir() #' ) #' #' # go to the working directory (tempdir()) and delete lspec #' # images (the ones with several rows of spectrograms) #' #' # filter selection data frame #' fmloc2 <- filter_sels( #' X = lbh_selec_table, lspec = TRUE, #' path = tempdir() #' ) #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on feb-6-2017 (MAS) filter_sels <- function(X, path = NULL, lspec = FALSE, img.suffix = NULL, it = "jpeg", incl.wav = TRUE, missing = FALSE, index = FALSE) { #### set arguments from options # get function arguments argms <- methods::formalArgs(filter_sels) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X))) stop2("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") # if it argument is not "jpeg" or "tiff" if (!any(it == "jpeg", it == "tiff", it == "pdf")) stop2(paste("Image type", it, "not allowed")) if (!all(c("sound.files", "selec") %in% colnames(X))) { stop2(paste(paste(c("sound.files", "selec")[!(c("sound.files", "selec") %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } if (it != "pdf") { # check if files are in working directory imgs <- list.files(path = path, pattern = "\\.jpeg$|\\.tiff$", ignore.case = FALSE) if (length(imgs) == 0) { stop2("No image files in working directory") } # if not long spec if (!lspec) { # if img suffix not provided if (is.null(img.suffix)) { # if .wav extension is included if (incl.wav) { imgn <- paste(paste(X$sound.files, X$selec, sep = "-"), it, sep = ".") } else { imgn <- paste(paste(gsub("\\.wav$|\\.wac$|\\.mp3$|\\.flac$", "", X$sound.files, ignore.case = TRUE), X$selec, sep = "-"), it, sep = ".") } } else { if (incl.wav) { imgn <- paste(paste(X$sound.files, X$selec, img.suffix, sep = "-"), it, sep = ".") } else { imgn <- paste(paste(gsub("\\.wav$|\\.wac$|\\.mp3$|\\.flac$", "", X$sound.files, ignore.case = TRUE), X$selec, img.suffix, sep = "-"), it, sep = ".") } } # subset data frame X miss.index <- imgn %in% imgs if (!index) { if (missing) Y <- X[!miss.index, , drop = FALSE] else Y <- X[miss.index, , drop = FALSE] } else if (missing) Y <- which(!miss.index) else Y <- which(miss.index) } else { # #remove the ones with no pX.it ending imgs <- grep("p\\d+\\.jpeg|p\\d+\\.tiff", imgs, value = TRUE) if (length(imgs) == 0) stop2("Images have not been produced by 'full_spectrograms' function") # subset selection table miss.index <- gsub("\\.wav$|\\.wac$|\\.mp3$|\\.flac$", "", X$sound.files, ignore.case = TRUE) %in% gsub("-p\\d+\\.jpeg$|-p\\d+\\.tiff$", "", imgs) if (!index) { if (missing) Y <- X[!miss.index, , drop = FALSE] else Y <- X[miss.index, , drop = FALSE] } else if (missing) Y <- which(!miss.index) else Y <- which(miss.index) } } else { # check if pdf files are in working directory imgs <- list.files(path = path, pattern = ".pdf$", ignore.case = FALSE) if (length(imgs) == 0) { stop2("No pdf files in working directory") } # subset selection table miss.index <- gsub("\\.wav$|\\.wac$|\\.mp3$|\\.flac$", "", X$sound.files, ignore.case = TRUE) %in% gsub(".pdf$", "", imgs) if (!index) { if (missing) miss.index <- !miss.index Y <- X[miss.index, , drop = FALSE] if (is_extended_selection_table(X)) { attributes(X)$check.results <- droplevels(attributes(X)$check.results[miss.index, ]) } } else { Y <- which(miss.index) } } if (!index) { if (nrow(Y) == 0) stop2("Image files in working directory do not match sound file names in X (wrong working directory?)") return(Y) } else { if (length(Y) == 0) message2("Index vector is of length 0") return(Y) } } ############################################################################################################## #' alternative name for \code{\link{filter_sels}} #' #' @keywords internal #' @details see \code{\link{filter_sels}} for documentation. \code{\link{filtersels}} will be deprecated in future versions. #' @export filtersels <- filter_sels
/scratch/gouwar.j/cran-all/cranData/warbleR/R/filter_sels.R
#' Find clipped selections #' #' \code{find_clipping} gets the proportion of samples that are clipped. #' @usage find_clipping(X, path = NULL, parallel = 1, pb = TRUE) #' @param X 'selection_table', 'extended_selection_table' or data frame with the following columns: 1) "sound.files": name of the sound #' files, 2) "selec": number of the selections, 3) "start": start time of selections, 4) "end": #' end time of selections. #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param pb Logical argument to control progress bar and messages. Default is \code{TRUE}. #' @return A data frame with the 'sound.files' and 'selec' columns in X plus an additional column ('prop.clipped') indicating #' the proportion of clipped samples for each row. If sound files are stereo the average proportion of the two channels is returned. #' @export #' @name find_clipping #' @examples #' { #' # load data #' data(list = c("Phae.long1", "Phae.long2", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) # save sound files #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' #' find_clipping(X = lbh_selec_table[1:5, ], path = tempdir()) #' } #' @details Clipping (i.e. saturation) occurs when an audio signal is amplified above the maximum limit of the recorder. This leads to distortion and a lowering of audio quality. If stereo the mean proportion of both channels is returned. The function assumes specific range values for different bit depths as detailed in \code{\link[tuneR]{normalize}}. #' @seealso \code{\link{sig2noise}} #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on mar-13-2018 (MAS) find_clipping <- function(X, path = NULL, parallel = 1, pb = TRUE) { #### set arguments from options # get function arguments argms <- methods::formalArgs(compare_methods) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 options(warn = -1) on.exit(options(warn = 0), add = TRUE) # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X))) stop2("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") # check basic columns in X if (!all(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))) { stop2(paste(paste(c("sound.files", "selec", "start", "end")[!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } # if parallel is not numeric if (!is.numeric(parallel)) stop2("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop2("'parallel' should be a positive integer") out <- pblapply_wrblr_int(1:nrow(X), pbar = pb, cl = parallel, function(x) { # read wave wv <- read_wave(X, index = x, path = path) # table with expected range of amplitudes by bit depth bit_ranges <- data.frame(bit = c(1, 8, 16, 24, 32, 64), low = c(-1, 0, -32767, -8388607, -2147483647, -1), high = c(1, 254, 32767, 8388607, 2147483647, 1)) bit_range <- bit_ranges[bit_ranges$bit == wv@bit, c("low", "high"), drop = TRUE] # proportion clipped prop.clipped <- sum(wv@left >= bit_range$high) / length(wv@left) if (wv@stereo) { prop.clipped <- mean(prop.clipped, sum(wv@right >= bit_range$high) / length(wv@right)) } # put all in a data frame out_df <- data.frame(sound.files = X$sound.files[x], selec = X$selec[x], prop.clipped) return(out_df) }) output <- do.call(rbind, out) return(output) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/find_clipping.R
#' Find cross-correlation peaks #' #' \code{find_peaks} find peaks in cross-correlation scores from \code{\link{cross_correlation}} #' @usage find_peaks(xc.output, parallel = 1, cutoff = 0.4, path = NULL, pb = TRUE, #' max.peak = FALSE, output = "data.frame") #' @param xc.output output of \code{\link{cross_correlation}} after setting \code{output = "list"}. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param cutoff Numeric vector of length 1 with a value between 0 and 1 specifying the correlation cutoff for detecting peaks. Default is 0.4. #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @param max.peak Logical argument to control whether only the peak with the highest correlation value is returned (if TRUE; cutoff will be ignored). Default is \code{FALSE}. #' @param output Character vector of length 1 to determine if only the detected peaks are returned ('cormat') or a list ('list') containing 1) the peaks and 2) a data frame with correlation values at each sliding step for each comparison. The list, which is also of class 'peaks.output', can be used to graphically explore detections using \code{\link{full_spectrograms}}. #' @return The function returns a data frame with time and correlation score for the #' detected peaks. #' @export #' @name find_peaks #' @details This function finds cross-correlation peaks along signals (analogous to \code{\link[monitoR]{findPeaks}}). #' @examples #' { #' # load data #' data(list = c("Phae.long4", "Phae.long2", "lbh_selec_table2", "comp_matrix")) #' #' # save sound files #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' #' # run cross-correlation #' xc.output <- cross_correlation( #' X = lbh_selec_table2, output = "list", #' compare.matrix = comp_matrix, path = tempdir() #' ) #' #' # find peaks #' pks <- find_peaks(xc.output = xc.output, path = tempdir()) #' } #' @seealso \code{\link{auto_detec}}, \code{\link[monitoR]{findPeaks}} #' @author Marcelo Araya-Salas \email{marcelo.araya@@ucr.ac.cr}) #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' #' H. Khanna, S.L.L. Gaunt & D.A. McCallum (1997). Digital spectrographic cross-correlation: tests of sensitivity. Bioacoustics 7(3): 209-234 #' } # last modification on jan-03-2020 (MAS) find_peaks <- function(xc.output, parallel = 1, cutoff = 0.4, path = NULL, pb = TRUE, max.peak = FALSE, output = "data.frame") { warning2("This function will be deprecated in future warbleR versions, please look at the ohun package for automatic signal detection functions (https://marce10.github.io/ohun/index.html)") #### set arguments from options # get function arguments argms <- methods::formalArgs(find_peaks) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # set clusters for windows OS and no soz if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # loop over scores of each dyad pks <- pblapply_wrblr_int(pbar = pb, X = unique(xc.output$scores$dyad), cl = cl, FUN = function(i) { # extract data for a dyad dat <- xc.output$scores[xc.output$scores$dyad == i, ] # check xc.output being a autodetec.output object if (!(is(xc.output, "xcorr.output") | is(xc.output, "xc.output"))) { stop2("'xc.output' must be and object of class 'xcorr.output'") } ## get peaks as the ones higher than previous and following scores pks <- dat[c(FALSE, diff(dat$score) > 0) & c(rev(diff(rev(dat$score)) > 0), FALSE) & dat$score > cutoff, , drop = FALSE] # get the single highest peak if (max.peak) { pks <- dat[which.max(dat$score), , drop = FALSE] } return(pks) }) # put results in a data frame peaks <- do.call(rbind, pks) # relabel rows if (nrow(peaks) > 0) { rownames(peaks) <- 1:nrow(peaks) # remove dyad column peaks$dyad <- NULL #### name as in a warbleR selection table # remove selec info at the end peaks$sound.files <- substr(peaks$sound.files, start = 0, regexpr("\\-[^\\-]*$", peaks$sound.files) - 1) #### add start and end # add template column to selection table in xc.output Y <- xc.output$org.selection.table Y$template <- paste(Y$sound.files, Y$selec, sep = "-") # Y <- Y[Y$template %in% comp_mat[, 1], ] # add start as time - half duration of template peaks$start <- sapply(1:nrow(peaks), function(i) { peaks$time[i] - ((Y$end[Y$template == peaks$template[i]] - Y$start[Y$template == peaks$template[i]]) / 2) }) # add end as time + half duration of template peaks$end <- sapply(1:nrow(peaks), function(i) { peaks$time[i] + ((Y$end[Y$template == peaks$template[i]] - Y$start[Y$template == peaks$template[i]]) / 2) }) # add selec labels peaks$selec <- 1 if (nrow(peaks) > 1) { for (i in 2:nrow(peaks)) { if (peaks$sound.files[i] == peaks$sound.files[i - 1]) { peaks$selec[i] <- peaks$selec[i - 1] + 1 } } } # sort columns in a intuitive order peaks <- sort_colms(peaks) # output results if (output == "data.frame") { return(peaks) } else { output_list <- list( selection.table = peaks, scores = xc.output$scores, cutoff = cutoff, call = base::match.call(), spectrogram = xc.output$spectrogram, warbleR.version = packageVersion("warbleR") ) class(output_list) <- c("list", "find_peaks.output") return(output_list) } } else { # no detections warning2(x = "no peaks above cutoff were detected") return(NULL) } } ############################################################################################################## #' print method for class \code{xcorr.output} #' #' @param x Object of class \code{find_peaks.output}, generated by \code{\link{find_peaks}}. #' @param ... further arguments passed to or from other methods. Ignored when printing selection tables. #' @keywords internal #' #' @export #' print.find_peaks.output <- function(x, ...) { message2(color = "cyan", x = paste("Object of class", cli::style_bold("'find_peaks.output'"))) message2(color = "silver", x = paste(cli::style_bold("\nContains: \n"), "The output of a detection routine from the following", cli::style_italic("find_peaks()"), "call:")) cll <- paste0(deparse(x$call)) message2(color = "silver", x = cli::style_italic(gsub(" ", "", cll))) # print count of detections per sound file # define columns to show if (nrow(x$selection.table) > 0) { tab <- aggregate(selec ~ sound.files, data = x$selection.table, FUN = length) } names(tab)[2] <- "detections" message2(color = "silver", x = "\n The following peaks (i.e. detections, found in the 'selection.table' list element) per sound files were found:") kntr_tab <- knitr::kable(head(tab), escape = FALSE, digits = 4, justify = "centre", format = "pipe") for (i in seq_len(length(kntr_tab))) message2(color = "silver", x = paste0(kntr_tab[i], "\n")) message2(color = "silver", x = "\n The peaks are found in the 'selection.table' list element") message2(color = "silver", x = paste("\n Use", cli::style_bold(cli::style_italic("full_spectrograms()")), "to plot detections along spectrograms")) # print warbleR version if (!is.null(x$warbleR.version)) { message2(color = "silver", x = paste0("\n Created by warbleR ", x$warbleR.version)) } else { message2(color = "silver", x = "\n Created by warbleR < 1.1.27 \n") } }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/find_peaks.R
#' Fix .wav files to allow importing them into R #' #' \code{fix_wavs} fixes sound files in .wav format so they can be imported into R. #' @usage fix_wavs(checksels = NULL, files = NULL, samp.rate = NULL, bit.depth = NULL, #' path = NULL, mono = FALSE) #' @param checksels Data frame with results from \code{\link{check_sels}}. Default is \code{NULL}. If both 'checksels' and 'files' are \code{NULL} #' then all files in 'path' are converted. Note that it only fixes/convert sound files in .wav format. #' @param files Character vector with the names of the .wav files to fix. Default is \code{NULL}. If both 'checksels' and 'files' are \code{NULL} #' then all files in 'path' are converted. #' @param samp.rate Numeric vector of length 1 with the sampling rate (in kHz) for output files. Default is \code{NULL}. #' (remain unchanged). #' @param bit.depth Numeric vector of length 1 with the dynamic interval (i.e. bit depth) for output files. #' Default is \code{NULL} (remain unchanged). #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param mono Logical indicating if stereo (2 channel) files should be converted to mono (1 channel). Default is \code{FALSE} (remain unchanged). # #' @param sox Logical indicating if \href{https://sourceforge.net/projects/sox/}{SOX} should be used for resampling. If \code{TRUE} SOX must be installed. Default is \code{FALSE}. #' @return A folder inside the working directory (or path provided) all 'converted_sound_files', containing #' sound files in a format that can be imported in R. #' @export #' @name fix_wavs #' @details This function aims to simplify the process of converting sound files that cannot be imported into R and/or homogenizing sound files. Problematic files can be determined using \code{\link{check_wavs}} or \code{\link{check_sels}}. The #' \code{\link{check_sels}} output can be directly input using the argument 'checksels'. Alternatively a vector of file #' names to be "fixed" can be provided (argument 'files'). If neither of those 2 are provided the function will convert #' all .wav sound files in the working directory to the specified sample rate/bit depth. Files are saved in a new directory #' ('converted_sound_files'). Internally the function calls \href{https://sourceforge.net/projects/sox/}{SOX} (\href{https://sourceforge.net/projects/sox/}{SOX} must be installed). If both 'checksels' and 'files' are \code{NULL} #' then all files in 'path' are converted. Note that it only fixes/convert sound files in .wav format. #' #' @examples #' \dontrun{ #' # Load example files and save to temporary working directory # data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) # writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) # writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) # writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) # writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' # # fix_wavs(files = lbh_selec_table$sound.files, path = tempdir()) #' #' # check this folder #' tempdir() #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on oct-22-2018 (MAS) fix_wavs <- function(checksels = NULL, files = NULL, samp.rate = NULL, bit.depth = NULL, path = NULL, mono = FALSE) { # error message if bioacoustics is not installed if (!requireNamespace("bioacoustics", quietly = TRUE) & !is.null(samp.rate)) { stop2("must install 'bioacoustics' to use for changing sampling rate") } #### set arguments from options # get function arguments argms <- methods::formalArgs(fix_wavs) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # If both 'checksels' and 'files' are NULL if (is.null(checksels) & is.null(files)) files <- list.files(path = path, pattern = ".wav$", ignore.case = TRUE) if (!is.null(checksels)) { fls <- unique(checksels$sound.files[checksels$check.res == "Sound file can't be read" | checksels$check.res == "file header corrupted"]) if (length(fls) == 0) stop2("All files were OK according tochecksels") # if X is not a data frame if (!is(checksels, "data.frame")) stop2("checksels is not a data frame") if (!all(c("sound.files", "check.res") %in% colnames(checksels))) { stop2(paste(paste(c("sound.files", "check.res")[!(c("sound.files", "check.res") %in% colnames(checksels))], collapse = ", "), "column(s) not found in data frame (does not seem to be the output of checksels)")) } } else { fls <- unique(files) } if (length(list.files(pattern = "\\.wav$", ignore.case = TRUE, path = path)) == 0) if (is.null(path)) stop2("No .wav files in working directory") else stop2("No .wav files in 'path' provided") if (!is.null(samp.rate)) { if (!is.vector(samp.rate)) stop2("'samp.rate' must be a numeric vector of length 1") else if (!length(samp.rate) == 1) stop2("'samp.rate' must be a numeric vector of length 1") } if (!is.null(bit.depth)) { if (!is.vector(bit.depth)) stop2("'bit.depth' must be a numeric vector of length 1") else if (!length(bit.depth) == 1) stop2("'bit.depth' must be a numeric vector of length 1") } if (!is.null(samp.rate) & is.null(bit.depth)) bit.depth <- 16 dir.create(file.path(path, "converted_sound_files"), showWarnings = FALSE) # fix_bio_FUN <- function(x) { # # # read waves # wv <- try(warbleR::read_wave(X = x, path = path), silent = TRUE) # # # downsample and filter if samp.rate different than mp3 # if(is(wv, "Wave") & !is.null(samp.rate)) # { # if ([email protected] != samp.rate * 1000) { # # # filter first to avoid aliasing # if ([email protected] > samp.rate * 1000) # wv <- seewave::fir(wave = wv , f = [email protected], from = 0, to = samp.rate * 1000 / 2, bandpass = TRUE, output = "Wave") # # #downsample # wv <- warbleR::resample(wave = wv, to = samp.rate * 1000) # } # # # normalize # wv <- tuneR::normalize(object = wv, unit = as.character(bit.depth)) # } # # wv <- try(tuneR::writeWave(extensible = FALSE, object = wv, filename = file.path(path, "converted_sound_files", paste0(substr(x, 0, nchar(x) - 4), ".wav"))), silent = TRUE) # # return(NULL) # } fix_sox_FUN <- function(x) { x <- normalizePath(file.path(path, x)) # name and path of original file cll <- paste0("sox '", x, "' -t wavpcm") if (!is.null(bit.depth)) { cll <- paste(cll, paste("-b", bit.depth)) } cll <- paste0(cll, " '", file.path(normalizePath(path), "converted_sound_files/", basename(x)), "'") if (!is.null(samp.rate)) { cll <- paste(cll, "rate", samp.rate * 1000) } if (!is.null(mono)) { cll <- paste(cll, "remix 1") } if (!is.null(bit.depth)) { cll <- paste(cll, "dither -s") } if (Sys.info()[1] == "Windows") { cll <- gsub("'", "\"", cll) } out <- system(cll, ignore.stdout = FALSE, intern = TRUE) } # fix_FUN <- if (sox) fix_sox_FUN else fix_bio_FUN out <- pblapply_wrblr_int(pbar = TRUE, X = fls, FUN = fix_sox_FUN) return(NULL) } ############################################################################################################## #' alternative name for \code{\link{fix_wavs}} #' #' @keywords internal #' @details see \code{\link{fix_wavs}} for documentation. \code{\link{fixwavs}} will be deprecated in future versions. #' @export fixwavs <- fix_wavs
/scratch/gouwar.j/cran-all/cranData/warbleR/R/fix_wavs.R
#' Acoustic dissimilarity using dynamic time warping on dominant frequency contours #' #' \code{freq_DTW} calculates acoustic dissimilarity of frequency contours using dynamic #' time warping. Internally it applies the \code{\link[dtw]{dtwDist}} function from the \code{dtw} package. #' @usage freq_DTW(X = NULL, type = "dominant", wl = 512, wl.freq = 512, length.out = 20, #' wn = "hanning", ovlp = 70, bp = NULL, threshold = 15, threshold.time = NULL, #' threshold.freq = NULL, img = TRUE, parallel = 1, path = NULL, ts.df = NULL, #' img.suffix = "dfDTW", pb = TRUE, clip.edges = TRUE, window.type = "none", #' open.end = FALSE, scale = FALSE, frange.detec = FALSE, fsmooth = 0.1, #' adjust.wl = TRUE, ...) #' @param X object of class 'selection_table', 'extended_selection_table' or data #' frame containing columns for sound file name (sound.files), #' selection number (selec), and start and end time of signal (start and end). #' The output of \code{\link{auto_detec}} can be used as the input data frame. #' @param type Character string to determine the type of contour to be detected. Three options are available, "dominant" (default), "fundamental" and "entropy". #' @param wl A numeric vector of length 1 specifying the window length of the spectrogram, default #' is 512. #' @param length.out A numeric vector of length 1 giving the number of measurements of frequency desired (the length of the time series). #' @param wn Character vector of length 1 specifying window name. Default is #' "hanning". See function \code{\link[seewave]{ftwindow}} for more options. #' @param wl.freq A numeric vector of length 1 specifying the window length of the spectrogram #' for measurements on the frequency spectrum. Default is 512. Higher values would provide #' more accurate measurements. #' @param ovlp Numeric vector of length 1 specifying \% of overlap between two #' consecutive windows, as in \code{\link[seewave]{spectro}}. Default is 70. #' @param bp A numeric vector of length 2 for the lower and upper limits of a #' frequency bandpass filter (in kHz). Default is \code{NULL}. #' @param threshold amplitude threshold (\%) for frequency detection. Default is 15. #' @param threshold.time amplitude threshold (\%) for the time domain. Use for frequency detection. If \code{NULL} (default) then the 'threshold' value is used. #' @param threshold.freq amplitude threshold (\%) for the frequency domain. Use for frequency range detection from the spectrum (see 'frange.detec'). If \code{NULL} (default) then the #' 'threshold' value is used. #' @param img Logical argument. If \code{FALSE}, image files are not produced. Default is \code{TRUE}. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param ts.df Optional. Data frame with frequency contour time series of signals to be compared. If provided "X" is ignored. #' @param img.suffix A character vector of length 1 with a suffix (label) to add at the end of the names of #' image files. Default is \code{NULL}. #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @param clip.edges Logical argument to control whether edges (start or end of signal) in #' which amplitude values above the threshold were not detected will be removed. If #' \code{TRUE} (default) this edges will be excluded and contours will be calculated on the #' remaining values. Note that DTW cannot be applied if missing values (e.i. when amplitude is not detected). #' @param window.type \code{\link[dtw]{dtw}} windowing control parameter. Character: "none", "itakura", or a function (see \code{\link[dtw]{dtw}}). #' @param open.end \code{\link[dtw]{dtw}} control parameter. Performs #' open-ended alignments (see \code{\link[dtw]{dtw}}). #' @param scale Logical. If \code{TRUE} frequency values are z-transformed using the \code{\link[base]{scale}} function, which "ignores" differences in absolute frequencies between the signals in order to focus the #' comparison in the frequency contour, regardless of the pitch of signals. Default is \code{TRUE}. #' @param frange.detec DEPRECATED. #' @param fsmooth A numeric vector of length 1 to smooth the frequency spectrum with a mean #' sliding window (in kHz) used for frequency range detection (when \code{frange.detec = TRUE}). This help to average amplitude "hills" to minimize the effect of #' amplitude modulation. Default is 0.1. #' @param adjust.wl Logical. If \code{TRUE} 'wl' (window length) is reset to be lower than the #' number of samples in a selection if the number of samples is less than 'wl'. Default is \code{TRUE}. #' @param ... Additional arguments to be passed to \code{\link{track_freq_contour}} for customizing #' graphical output. #' @return A matrix with the pairwise dissimilarity values. If img is #' \code{FALSE} it also produces image files with the spectrograms of the signals listed in the #' input data frame showing the location of the dominant frequencies. #' @family spectrogram creators #' @seealso \code{\link{spectrograms}} for creating spectrograms from selections, #' \code{\link{snr_spectrograms}} for creating spectrograms to #' optimize noise margins used in \code{\link{sig2noise}} and \code{\link{freq_ts}}, \code{\link{freq_ts}}, for frequency contour overlaid spectrograms. #' @export #' @name freq_DTW #' @details This function extracts the dominant frequency values as a time series and #' then calculates the pairwise acoustic dissimilarity using dynamic time warping. #' The function uses the \code{\link[stats:approxfun]{approx}} function to interpolate values between dominant #' frequency measures. If 'img' is \code{TRUE} the function also produces image files #' with the spectrograms of the signals listed in the input data frame showing the #' location of the dominant frequencies. #' @examples { #' # load data #' data(list = c("Phae.long1", "Phae.long2", "lbh_selec_table")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) # save sound files #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' #' # dominant frequency #' freq_DTW(lbh_selec_table, #' length.out = 30, flim = c(1, 12), bp = c(2, 9), #' wl = 300, path = tempdir() #' ) #' #' # fundamental frequency #' freq_DTW(lbh_selec_table, #' type = "fundamental", length.out = 30, flim = c(1, 12), #' bp = c(2, 9), wl = 300, path = tempdir() #' ) #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on nov-31-2016 (MAS) freq_DTW <- function(X = NULL, type = "dominant", wl = 512, wl.freq = 512, length.out = 20, wn = "hanning", ovlp = 70, bp = NULL, threshold = 15, threshold.time = NULL, threshold.freq = NULL, img = TRUE, parallel = 1, path = NULL, ts.df = NULL, img.suffix = "dfDTW", pb = TRUE, clip.edges = TRUE, window.type = "none", open.end = FALSE, scale = FALSE, frange.detec = FALSE, fsmooth = 0.1, adjust.wl = TRUE, ...) { #### set arguments from options # get function arguments argms <- methods::formalArgs(freq_DTW) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } if (is.null(X) & is.null(ts.df)) stop("either 'X' or 'ts.df' should be provided") # define number of steps in analysis to print message if (pb) { steps <- getOption("int_warbleR_steps") if (steps[2] > 0) { current.step <- steps[1] total.steps <- steps[2] } else { total.steps <- 2 current.step <- 1 } } if (!is.null(X)) { # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X))) stop("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") } # stop if only 1 selection if (is.null(ts.df)) { if (nrow(X) == 1) stop("you need more than one selection for freq_DTW") # threshold adjustment if (is.null(threshold.time)) threshold.time <- threshold if (is.null(threshold.freq)) threshold.freq <- threshold # run freq_ts function if (pb) { message2(x = paste0("measuring dominant frequency contours (step ", current.step, " of ", total.steps, "): \n")) } # get contours res <- freq_ts(X, type = type, wl = wl, length.out = length.out, wn = wn, ovlp = ovlp, wl.freq = wl.freq, bp = bp, threshold.time = threshold.time, threshold.freq = threshold.freq, img = img, parallel = parallel, path = path, img.suffix = img.suffix, pb = pb, clip.edges = clip.edges, adjust.wl = adjust.wl, ... ) } else { if (!all(c("sound.files", "selec") %in% names(ts.df))) { stop(paste(paste(c("sound.files", "selec")[!(c("sound.files", "selec") %in% names(ts.df))], collapse = ", "), "column(s) not found in ts.df")) } res <- ts.df } # matrix of dom freq time series mat <- res[, 3:ncol(res)] if (scale) { mat <- t(apply(mat, 1, scale)) } # stop if NAs in matrix if (any(is.na(mat))) stop("missing values in time series (frequency was not detected at the start and/or end of the signal)") if (pb & is.null(ts.df)) { message2(x = paste0("calculating DTW distances (step ", current.step + 1, " of ", total.steps, ", no progress bar):")) } dm <- dtw::dtwDist(mat, mat, window.type = window.type, open.end = open.end) rownames(dm) <- colnames(dm) <- paste(res$sound.files, res$selec, sep = "-") return(dm) } ############################################################################################################## #' alternative name for \code{\link{freq_DTW}} #' #' @keywords internal #' @details see \code{\link{freq_DTW}} for documentation. \code{\link{dfDTW}} will be deprecated in future versions. #' @export dfDTW <- freq_DTW ############################################################################################################## #' alternative name for \code{\link{freq_DTW}} #' #' @keywords internal #' @details see \code{\link{freq_DTW}} for documentation. \code{\link{freq_DTW}} will be deprecated in future versions. #' @export df_DTW <- freq_DTW
/scratch/gouwar.j/cran-all/cranData/warbleR/R/freq_DTW.R
#' Detect frequency range iteratively #' #' \code{freq_range} detect frequency range iteratively from signals in a selection table. #' @usage freq_range(X, wl = 512, it = "jpeg", line = TRUE, fsmooth = 0.1, threshold = 10, #' dB.threshold = NULL, wn = "hanning", flim = NULL, bp = NULL, #' propwidth = FALSE, xl = 1, picsize = 1, res = 100, fast.spec = FALSE, ovlp = 50, #' pal = reverse.gray.colors.2, parallel = 1, widths = c(2, 1), main = NULL, #' img = TRUE, mar = 0.05, path = NULL, pb = TRUE, impute = FALSE) #' @param X object of class 'selection_table', 'extended_selection_table' or data frame with the following columns: 1) "sound.files": name of the sound #' files, 2) "sel": number of the selections, 3) "start": start time of selections, 4) "end": #' end time of selections. The output of \code{\link{auto_detec}} can #' also be used as the input data frame. #' @param wl A numeric vector of length 1 specifying the window length of the spectrogram, default #' is 512. This is used for calculating the frequency spectrum (using \code{\link[seewave]{meanspec}}) #' and producing the spectrogram (using \code{\link[seewave]{spectro}}, if \code{img = TRUE}). #' @param it A character vector of length 1 giving the image type to be used. Currently only #' "tiff" and "jpeg" are admitted. Default is "jpeg". #' @param line Logical argument to add red lines (or box if bottom.freq and top.freq columns are provided) at start and end times of selection. Default is \code{TRUE}. #' @param fsmooth A numeric vector of length 1 to smooth the frequency spectrum with a mean #' sliding window in kHz. This help to average amplitude "hills" to minimize the effect of #' amplitude modulation. Default is 0.1. #' @param threshold Amplitude threshold (\%) for frequency range detection. The frequency range (not the cumulative amplitude) is represented as percentage (100\% = highest amplitude). Default is 10. Ignored if 'dB.threshold' is supplied. #' @param dB.threshold Amplitude threshold for frequency range detection (in dB). The value indicates the decrease in dB in relation to the highest amplitude (e.g. the peak frequency) in which range will be detected. For instance a dB.threshold = 20 means that the amplitude threshold would be 20 dB below the highest amplitude. If provided 'threshold' is ignored. Default is \code{NULL}. #' Note that the power spectrum is normalized when using a dB scale, so it looks different than the one produced when no dB scale is used (e.g. when using 'threshold' argument). #' @param wn Character vector of length 1 specifying window name. Default is #' "hanning". See function \code{\link[seewave]{ftwindow}} for more options. This is used for calculating the frequency spectrum (using \code{\link[seewave]{meanspec}}) and producing the spectrogram (using \code{\link[seewave]{spectro}}, if \code{img = TRUE}). #' @param flim A numeric vector of length 2 for the frequency limit of #' the spectrogram (in kHz), as in \code{\link[seewave]{spectro}}. Default is \code{NULL}. #' @param bp A numeric vector of length 2 for the lower and upper limits of a #' frequency bandpass filter (in kHz) or "frange" to indicate that values in 'bottom.freq' #' and 'top.freq' columns will be used as bandpass limits. Default is c(0, 22). #' @param propwidth Logical argument to scale the width of spectrogram #' proportionally to duration of the selected call. Default is \code{FALSE}. #' @param xl Numeric vector of length 1. A constant by which to scale #' spectrogram width. Default is 1. #' @param picsize Numeric argument of length 1. Controls relative size of #' spectrogram. Default is 1. #' @param res Numeric argument of length 1. Controls image resolution. #' Default is 100 (faster) although 300 - 400 is recommended for publication/ #' presentation quality. #' @param fast.spec Logical. If \code{TRUE} then image function is used internally to create spectrograms, which substantially #' increases performance (much faster), although some options become unavailable, as collevels, and sc (amplitude scale). #' This option is indicated for signals with high background noise levels. Palette colors \code{\link[monitoR:specCols]{gray.1}}, \code{\link[monitoR:specCols]{gray.2}}, #' \code{\link[monitoR:specCols]{gray.3}}, \code{\link[monitoR:specCols]{topo.1}} and \code{\link[monitoR:specCols]{rainbow.1}} (which should be imported from the package monitoR) seem #' to work better with 'fast.spec' spectrograms. Palette colors \code{\link[monitoR:specCols]{gray.1}}, \code{\link[monitoR:specCols]{gray.2}}, #' \code{\link[monitoR:specCols]{gray.3}} offer #' decreasing darkness levels. #' @param pal Color palette function for spectrogram. Default is reverse.gray.colors.2. See #' \code{\link[seewave]{spectro}} for more palettes. Palettes as \code{\link[monitoR:specCols]{gray.2}} may work better when \code{fast.spec = TRUE}. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param ovlp Numeric vector of length 1 specifying \% of overlap between two #' consecutive windows, as in \code{\link[seewave]{spectro}}. Default is 50. This is used for calculating the frequency spectrum (using \code{\link[seewave]{meanspec}}) and producing the spectrogram (using \code{\link[seewave]{spectro}}, if \code{img = TRUE}). #' @param widths Numeric vector of length 2 to control the relative widths of the spectro (first element) and spectrum (second element). #' @param main Character vector of length 1 specifying the img title. Default is \code{NULL}. #' @param img Logical. Controls whether a plot is produced. Default is \code{TRUE}. #' @param mar Numeric vector of length 1. Specifies the margins adjacent to the selections #' to set spectrogram limits. Default is 0.05. #' @param pb Logical argument to control progress bar and messages. Default is \code{TRUE}. #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param impute Logical. If \code{TRUE} then missing range values are imputed #' with the corresponding bandpass value (hence ignored when \code{bp = NULL}). Default is \code{FALSE}. #' @return The original data frame with an additional 2 columns for low and high frequency values. A plot is produced in the working directory if \code{img = TRUE} (see details). #' @export #' @name freq_range #' @details This functions aims to automatize the detection of frequency ranges. The frequency range is calculated as follows: #' \itemize{ #' \item bottom.freq = the start frequency of the amplitude 'hill' containing the highest amplitude at the given threshold. #' \item top.freq = the end frequency of the amplitude 'hill' containing the highest amplitude at the given threshold. #' } #' If \code{img = TRUE} a graph including a spectrogram and a frequency spectrum is #' generated for each selection (saved as an image file in the working directory). The graph would include gray areas in the frequency ranges excluded by the bandpass ('bp' argument), dotted lines highlighting the detected range. The function \code{\link{freq_range_detec}} is used internally. #' @seealso \code{\link{freq_range_detec}}, \code{\link{auto_detec}} #' @examples #' { #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' #' freq_range( #' X = lbh_selec_table, wl = 112, fsmooth = 1, threshold = 13, widths = c(4, 1), #' img = TRUE, pb = TRUE, it = "tiff", line = TRUE, mar = 0.1, bp = c(1, 10.5), #' flim = c(0, 11), path = tempdir() #' ) #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on mar-12-2018 (MAS) freq_range <- function(X, wl = 512, it = "jpeg", line = TRUE, fsmooth = 0.1, threshold = 10, dB.threshold = NULL, wn = "hanning", flim = NULL, bp = NULL, propwidth = FALSE, xl = 1, picsize = 1, res = 100, fast.spec = FALSE, ovlp = 50, pal = reverse.gray.colors.2, parallel = 1, widths = c(2, 1), main = NULL, img = TRUE, mar = 0.05, path = NULL, pb = TRUE, impute = FALSE) { #### set arguments from options # get function arguments argms <- methods::formalArgs(freq_range) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop("'path' provided does not exist") } else { path <- normalizePath(path) } # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X))) stop("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") if (!all(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))) { stop(paste(paste(c("sound.files", "selec", "start", "end")[!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop("NAs found in start and/or end") # if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) stop("'start' and 'end' must be numeric") # if any start higher than end stop if (any(X$end - X$start <= 0)) stop(paste("Start is higher than or equal to end in", length(which(X$end - X$start <= 0)), "case(s)")) # if any selections longer than 20 secs warning if (any(X$end - X$start > 20)) warning2(paste(length(which(X$end - X$start > 20)), "selection(s) longer than 20 sec")) # return warning if not all sound files were found if (!is_extended_selection_table(X)) { fs <- list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE) if (length(unique(X$sound.files[(X$sound.files %in% fs)])) != length(unique(X$sound.files))) { message2(paste( length(unique(X$sound.files)) - length(unique(X$sound.files[(X$sound.files %in% fs)])), "sound file(s) not found" )) } # count number of sound files in working directory and if 0 stop d <- which(X$sound.files %in% fs) if (length(d) == 0) { stop("The sound files are not in the working directory") } else { X <- X[d, ] } } # internal function to detect freq range frangeFUN <- function(X, i, img, bp, wl, fsmooth, threshold, wn, flim, ovlp, fast.spec, pal, widths) { r <- warbleR::read_sound_file(X = X, path = path, index = i, header = TRUE) f <- r$sample.rate t <- c(X$start[i] - mar, X$end[i] + mar) # adjust margins if signal is close to start or end of sound file mar1 <- mar if (t[1] < 0) { t[1] <- 0 mar1 <- X$start[i] } mar2 <- mar1 + X$end[i] - X$start[i] if (t[2] > r$samples / f) t[2] <- r$samples / f # read rec segment r <- warbleR::read_sound_file(X = X, path = path, index = i, from = t[1], to = t[2]) frng <- frd_wrblr_int(wave = seewave::cutw(r, from = mar1, to = mar2, output = "Wave"), wl = wl, fsmooth = fsmooth, threshold = threshold, dB.threshold = dB.threshold, wn = wn, bp = bp, ovlp = ovlp) if (img) { # Spectrogram width can be proportional to signal duration if (propwidth) { pwc <- (13.16) * ((t[2] - t[1]) / 0.27) * xl * picsize } else { pwc <- (13.16) * xl * picsize } # call image function img_wrlbr_int( filename = paste0(X$sound.files[i], "-", X$selec[i], "-", "freq_range.", it), path = path, width = pwc, height = (10.16), units = "cm", res = res ) frd_plot_wrblr_int(wave = r, detections = frng, wl = wl, wn = wn, flim = flim, bp = bp, fast.spec = fast.spec, ovlp = ovlp, pal = pal, widths = widths, main = paste(X$sound.files[i], X$selec[i], sep = "-"), all.detec = F) dev.off() } # return low and high freq return(data.frame(X[i, grep("bottom.freq|top.freq", names(X), invert = TRUE)], bottom.freq = frng$frange$bottom.freq, top.freq = frng$frange$top.freq)) } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function fr <- pblapply_wrblr_int(pbar = pb, X = 1:nrow(X), cl = cl, FUN = function(i) { # if bp is frange if (!is.null(bp)) { if (bp[1] == "frange") b <- c(X$bottom.freq[i], X$top.freq[i]) else b <- bp } else { b <- bp } frangeFUN(X = X, i = i, img = img, bp = b, wl = wl, fsmooth = fsmooth, threshold = threshold, wn = wn, flim = flim, ovlp = ovlp, fast.spec = fast.spec, pal = pal, widths = widths) }) fr <- do.call(rbind, fr) if (impute & !is.null(bp)) { fr$bottom.freq[is.na(fr$bottom.freq)] <- bp[1] fr$top.freq[is.na(fr$top.freq)] <- bp[2] } if (any(!sapply(fr[, c("start", "end", "bottom.freq", "top.freq")], is.numeric))) fr[, c("start", "end", "bottom.freq", "top.freq")] <- rapply(fr[, c("start", "end", "bottom.freq", "top.freq")], as.numeric) row.names(fr) <- 1:nrow(fr) return(fr) } ############################################################################################################## #' alternative name for \code{\link{freq_range}} #' #' @keywords internal #' @details see \code{\link{freq_range}} for documentation. \code{\link{frange}} will be deprecated in future versions. #' @export frange <- freq_range
/scratch/gouwar.j/cran-all/cranData/warbleR/R/freq_range.R
#' Detect frequency range on wave objects #' #' \code{freq_range_detec} detects the frequency range of acoustic signals on wave objects. #' @usage freq_range_detec(wave, wl = 512, fsmooth = 0.1, threshold = 10, #' dB.threshold = NULL, wn = "hanning", flim = NULL, bp = NULL, #' fast.spec = FALSE, ovlp = 50, pal = reverse.gray.colors.2, #' widths = c(2, 1), main = NULL, plot = TRUE, all.detec = FALSE) #' @param wave A 'wave' object produced by \code{\link[tuneR]{readWave}} or similar functions. #' @param wl A numeric vector of length 1 specifying the window length of the spectrogram, default #' is 512. This is used for calculating the frequency spectrum (using \code{\link[seewave]{meanspec}}) #' and producing the spectrogram (using \code{\link[seewave]{spectro}}, if \code{plot = TRUE}). #' @param fsmooth A numeric vector of length 1 to smooth the frequency spectrum with a mean #' sliding window in kHz. This help to average amplitude "hills" to minimize the effect of #' amplitude modulation. Default is 0.1. #' @param threshold Amplitude threshold (\%) for frequency range detection. The frequency range (not the cumulative amplitude) is represented as percentage (100\% = highest amplitude). Default is 10. Ignored if 'dB.threshold' is supplied. #' @param dB.threshold Amplitude threshold for frequency range detection (in dB). The #' value indicates the decrease in dB in relation to the highest amplitude (e.g. #' the peak frequency) in which range will be detected. For instance a #' \code{dB.threshold = 20} means that the amplitude threshold would be 20 dB below #' the highest amplitude. If provided 'threshold' is ignored. Default is \code{NULL}. #' Note that the power spectrum is normalized when using a dB scale, so it looks different than the one produced when no dB scale is used (e.g. when using 'threshold' argument). #' @param wn Character vector of length 1 specifying window name. Default is #' "hanning". See function \code{\link[seewave]{ftwindow}} for more options. This is used for calculating the frequency spectrum (using \code{\link[seewave]{meanspec}}) and producing the spectrogram (using \code{\link[seewave]{spectro}}, if \code{plot = TRUE}). #' @param flim A numeric vector of length 2 for the frequency limit of #' the spectrogram (in kHz), as in \code{\link[seewave]{spectro}}. Default is \code{NULL}. #' @param bp A numeric vector of length 2 for the lower and upper limits of a #' frequency bandpass filter (in kHz) or "frange" to indicate that values in 'bottom.freq' #' and 'top.freq' columns will be used as bandpass limits. Default is \code{NULL}. #' @param fast.spec Logical. If \code{TRUE} then image function is used internally to create spectrograms, which substantially #' increases performance (much faster), although some options become unavailable, as collevels, and sc (amplitude scale). #' This option is indicated for signals with high background noise levels. Palette colors \code{\link[monitoR:specCols]{gray.1}}, \code{\link[monitoR:specCols]{gray.2}}, #' \code{\link[monitoR:specCols]{gray.3}}, \code{\link[monitoR:specCols]{topo.1}} and \code{\link[monitoR:specCols]{rainbow.1}} (which should be imported from the package monitoR) seem #' to work better with 'fast.spec' spectrograms. Palette colors \code{\link[monitoR:specCols]{gray.1}}, \code{\link[monitoR:specCols]{gray.2}}, #' \code{\link[monitoR:specCols]{gray.3}} offer #' decreasing darkness levels. #' @param pal Color palette function for spectrogram. Default is reverse.gray.colors.2. See #' \code{\link[seewave]{spectro}} for more palettes. Palettes as \code{\link[monitoR:specCols]{gray.2}} may work better when \code{fast.spec = TRUE}. #' @param ovlp Numeric vector of length 1 specifying \% of overlap between two #' consecutive windows, as in \code{\link[seewave]{spectro}}. Default is 50. This is used for calculating the frequency spectrum (using \code{\link[seewave]{meanspec}}) and producing the spectrogram (using \code{\link[seewave]{spectro}}, if \code{plot = TRUE}). #' @param widths Numeric vector of length 2 to control the relative widths of the spectro (first element) and spectrum (second element). #' @param main Character vector of length 1 specifying the plot title. Default is \code{NULL}. #' @param plot Logical. Controls whether an image file is produced for each selection (in the #' working directory). Default is \code{TRUE}. #' @param all.detec Logical. If \code{TRUE} returns the start and end of all detected amplitude #' "hills". Otherwise only the range is returned. Default is \code{FALSE}. #' @return A data frame with 2 columns for low and high frequency values. A plot is produced (in the graphic device) if \code{plot = TRUE} (see details). #' @export #' @name freq_range_detec #' @details This functions aims to automatize the detection of frequency ranges. The frequency range is calculated as follows: #' \itemize{ #' \item bottom.freq = the start frequency of the amplitude 'hill' containing the highest amplitude at the given threshold. #' \item top.freq = the end frequency of the amplitude 'hill' containing the highest amplitude at the given threshold. #' } #' If \code{plot = TRUE} a graph including a spectrogram and a frequency spectrum is #' produced in the graphic device. The graph would include gray areas in the frequency ranges excluded by the bandpass ('bp' argument), dotted lines highlighting the detected range. #' @seealso \code{\link{frange}}, \code{\link{autodetec}} #' @examples #' { #' data(tico) #' freq_range_detec( #' wave = tico, wl = 512, fsmooth = 0.01, threshold = 1, bp = c(2, 8), #' widths = c(4, 2) #' ) #' #' data(sheep) #' freq_range_detec( #' wave = sheep, wl = 512, fsmooth = 0.2, threshold = 50, bp = c(0.3, 1), #' flim = c(0, 1.5), pal = reverse.heat.colors, main = "sheep" #' ) #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on apr-28-2017 (MAS) freq_range_detec <- function(wave, wl = 512, fsmooth = 0.1, threshold = 10, dB.threshold = NULL, wn = "hanning", flim = NULL, bp = NULL, fast.spec = FALSE, ovlp = 50, pal = reverse.gray.colors.2, widths = c(2, 1), main = NULL, plot = TRUE, all.detec = FALSE) { # close screens on.exit(invisible(close.screen(all.screens = TRUE))) #### set arguments from options # get function arguments argms <- methods::formalArgs(freq_range_detec) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } frng <- frd_wrblr_int(wave = wave, wl = wl, fsmooth = fsmooth, threshold = threshold, dB.threshold = dB.threshold, wn = wn, bp = bp, ovlp = ovlp) if (plot) { frd_plot_wrblr_int(wave = wave, detections = frng, wl = wl, wn = wn, flim = flim, bp = bp, fast.spec = fast.spec, ovlp = ovlp, pal = pal, widths = widths, main = main, all.detec = all.detec) } # return low and high freq if (all.detec) { return(frng$detections) } else { return(frng$frange) } } ############################################################################################################## #' alternative name for \code{\link{freq_range_detec}} #' #' @keywords internal #' @details see \code{\link{freq_range_detec}} for documentation. \code{\link{frange.detec}} will be deprecated in future versions. #' @export frange.detec <- freq_range_detec
/scratch/gouwar.j/cran-all/cranData/warbleR/R/freq_range_detec.R
#' Extract frequency contours as time series #' #' \code{freq_ts} extracts the fundamental frequency values as a time series. #' @usage freq_ts(X, type = "dominant", wl = 512, length.out = 20, wn = "hanning", #' ovlp = 70, bp = NULL, threshold = 15, img = TRUE, parallel = 1, path = NULL, #' img.suffix = "frequency.ts", pb = TRUE, clip.edges = FALSE, leglab = "frequency.ts", #' track.harm = FALSE, raw.contour = FALSE, adjust.wl = TRUE, #' ff.method = "seewave", entropy.range = c(2, 10), ...) #' @param X object of class 'selection_table', 'extended_selection_table' or data #' frame containing columns for sound file name (sound.files), #' selection number (selec), and start and end time of signal (start and end). #' @param type Character string to determine the type of contour to be detected. Three options are available, "dominant" (default), "fundamental" and "entropy". #' @param wl A numeric vector of length 1 specifying the window length of the spectrogram, default #' is 512. #' @param length.out A numeric vector of length 1 giving the number of measurements of fundamental #' frequency desired (the length of the time series). #' @param wn Character vector of length 1 specifying window name. Default is #' "hanning". See function \code{\link[seewave]{ftwindow}} for more options. #' @param ovlp Numeric vector of length 1 specifying \% of overlap between two #' consecutive windows, as in \code{\link[seewave]{spectro}}. Default is 70. #' @param bp A numeric vector of length 2 for the lower and upper limits of a #' frequency bandpass filter (in kHz). Default is \code{NULL}. #' @param threshold amplitude threshold (\%) for fundamental frequency detection. Default is 15. #' @param img Logical argument. If \code{FALSE}, image files are not produced. Default is \code{TRUE}. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param img.suffix A character vector of length 1 with a suffix (label) to add at the end of the names of #' image files. #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @param clip.edges Logical argument to control whether edges (start or end of signal) in #' which amplitude values above the threshold were not detected will be removed. If #' \code{TRUE} this edges will be excluded and signal contour will be calculated on the #' remaining values. Default is \code{FALSE}. #' #' @param leglab A character vector of length 1 or 2 containing the label(s) of the frequency contour legend #' in the output image. #' @param leglab A character vector of length 1 or 2 containing the label(s) of the frequency contour legend #' in the output image. #' @param ff.method Character. Selects the method used to detect fundamental #' frequency contours. Either 'tuneR' (using \code{\link[tuneR]{FF}}) or 'seewave' (using #' \code{\link[seewave]{fund}}). Default is 'seewave'. 'tuneR' performs #' faster (and seems to be more accurate) than 'seewave'. #' @param raw.contour Logical. If \code{TRUE} then a list with the original contours #' (i.e. without interpolating values to make all contours of equal length) is returned (and no images are produced). #' @param track.harm Logical. If \code{TRUE} warbleR's \code{\link{track_harmonic}} function is #' used to track dominant frequency contours. Otherwise seewave's \code{\link[seewave]{dfreq}} is used by default. Default is \code{FALSE}. #' @param adjust.wl Logical. If \code{TRUE} 'wl' (window length) is reset to be lower than the #' number of samples in a selection if the number of samples is less than 'wl'. Default is \code{TRUE}. Used only for dominant frequency detection. #' @param entropy.range Numeric vector of length 2. Range of frequency in which to display the entropy values #' on the spectrogram (when img = TRUE). Default is c(2, 10). Negative values can be used in order to stretch more #' the range. #' @param ... Additional arguments to be passed to \code{\link{track_freq_contour}}. for customizing #' graphical output. #' @return A data frame with the fundamental frequency values measured across the signals. If img is #' \code{TRUE} it also produces image files with the spectrograms of the signals listed in the #' input data frame showing the location of the fundamental frequencies #' (see \code{\link{track_freq_contour}} description for more details). #' @seealso \code{\link{sig2noise}}, \code{\link{track_freq_contour}}, \code{\link{freq_ts}}, \code{\link{freq_DTW}} #' @export #' @name freq_ts #' @details This function extracts the dominant frequency, fundamental frequency or spectral entropy contours as time series. #' The function uses the \code{\link[stats:approxfun]{approx}} function to interpolate values between frequency measures. If there are no frequencies above the amplitude threshold (for dominant and fundamental) at the beginning or end #' of the signals then NAs will be generated. On the other hand, if there are no frequencies #' above the amplitude theshold in between signal segments in which amplitude was #' detected then the values of this adjacent segments will be interpolated #' to fill out the missing values (e.g. no NAs in between detected amplitude segments). #' @examples{ #' #load data #' data(list = c("Phae.long1", "Phae.long2","lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #save sound files #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #save sound files #' #' # run function with dominant frequency #' freq_ts(X = lbh_selec_table, length.out = 30, flim = c(1, 12), bp = c(2, 9), #' wl = 300, pb = FALSE, path = tempdir()) #' #' # note a NA in the row 4 column 3 (dfreq-1) #' # this can be removed by clipping edges (removing NAs at the start and/or end #' # when no freq was detected) #' #' freq_ts(X = lbh_selec_table, length.out = 30, flim = c(1, 12), bp = c(2, 9), #' wl = 300, pb = FALSE, clip.edges = TRUE, path = tempdir()) #' #' # run function with fundamental frequency #' freq_ts(lbh_selec_table, type = "fundamental", length.out = 50, #' flim = c(1, 12), bp = c(2, 9), wl = 300, path = tempdir()) #' #' # run function with spectral entropy #' # without clip edges #' freq_ts(X = lbh_selec_table, type = "entropy", threshold = 10, #' clip.edges = FALSE, length.out = 10, sp.en.range = c(-25, 10), path = tempdir(), #' img = FALSE) #' #' # with clip edges and length.out 10 #' freq_ts(X = lbh_selec_table, type = "entropy", threshold = 10, bp = c(2, 12), #' clip.edges = TRUE, length.out = 10, path = tempdir(), img = FALSE) #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on mar-2021 (MAS) freq_ts <- function(X, type = "dominant", wl = 512, length.out = 20, wn = "hanning", ovlp = 70, bp = NULL, threshold = 15, img = TRUE, parallel = 1, path = NULL, img.suffix = "frequency.ts", pb = TRUE, clip.edges = FALSE, leglab = "frequency.ts", track.harm = FALSE, raw.contour = FALSE, adjust.wl = TRUE, ff.method = "seewave", entropy.range = c(2, 10), ...) { #### set arguments from options # get function arguments argms <- methods::formalArgs(freq_ts) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop("'path' provided does not exist") } else { path <- normalizePath(path) } # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X))) stop("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") if (!all(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))) { stop(paste(paste(c("sound.files", "selec", "start", "end")[!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop("NAs found in start and/or end") # if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) stop("'start' and 'end' must be numeric") # if any start higher than end stop if (any(X$end - X$start <= 0)) stop(paste("Start is higher than or equal to end in", length(which(X$end - X$start <= 0)), "case(s)")) # if any selections longer than 20 secs stop if (any(X$end - X$start > 20)) stop(paste(length(which(X$end - X$start > 20)), "selection(s) longer than 20 sec")) options(show.error.messages = TRUE) # bp checking if (!is.null(bp)) { if (bp[1] != "frange") { if (!is.vector(bp)) { stop("'bp' must be a numeric vector of length 2 or 'frange'") } else { if (!length(bp) == 2) stop("'bp' must be a numeric vector of length 2 or 'frange'") } } else { if (!any(names(X) == "bottom.freq") & !any(names(X) == "top.freq")) stop("'bp' = 'frange' requires bottom.freq and top.freq columns in X") if (any(is.na(c(X$bottom.freq, X$top.freq)))) stop("NAs found in bottom.freq and/or top.freq") if (any(c(X$bottom.freq, X$top.freq) < 0)) stop("Negative values found in bottom.freq and/or top.freq") if (any(X$top.freq - X$bottom.freq < 0)) stop("top.freq should be higher than bottom.freq") } } # if type argument if (!any(type == "dominant", type == "fundamental", type == "entropy")) stop(paste("type", type, "is not recognized")) # if ff.method argument if (!any(ff.method == "seewave", ff.method == "tuneR")) stop(paste("ff.method", ff.method, "is not recognized")) # return warning if not all sound files were found if (!is_extended_selection_table(X)) { recs.wd <- list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE) if (length(unique(X$sound.files[(X$sound.files %in% recs.wd)])) != length(unique(X$sound.files)) & pb) { message2(paste( length(unique(X$sound.files)) - length(unique(X$sound.files[(X$sound.files %in% recs.wd)])), "sound file(s) not found" )) } # count number of sound files in working directory and if 0 stop d <- which(X$sound.files %in% recs.wd) if (length(d) == 0) { stop("The sound files are not in the working directory") } else { X <- X[d, , drop = FALSE] } } # if parallel is not numeric if (!is.numeric(parallel)) stop("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop("'parallel' should be a positive integer") if (pb) { if (img) { message2("Creating spectrograms overlaid with fundamental frequency measurements:") } else { message2("Measuring fundamental frequency:") } } if (type == "dominant") { contour_FUN <- function(X, i, bp, wl, threshold, entropy.range, raw.contour, track.harm, adjust.wl) { # Read sound files to get sample rate and length r <- warbleR::read_sound_file(X = X, path = path, index = i, header = TRUE) f <- r$sample.rate # if bp is frange if (!is.null(bp)) { if (bp[1] == "frange") bp <- c(X$bottom.freq[i], X$top.freq[i]) } b <- bp # in case bp its higher than can be due to sampling rate if (!is.null(b)) { if (b[2] > floor(f / 2000)) { b[2] <- floor(f / 2000) } b <- b * 1000 } r <- warbleR::read_sound_file(X = X, path = path, index = i) # calculate dominant frequency at each time point dfrq1 <- track_harmonic( wave = r, f = f, wl = wl, plot = FALSE, ovlp = ovlp, bandpass = b, fftw = TRUE, threshold = threshold, dfrq = !track.harm, adjust.wl = adjust.wl ) dfrq <- dfrq1[!is.na(dfrq1[, 2]), , drop = FALSE] # make NA's the ones outside banpass freqs dfrq[dfrq[, 2] < b[1] / 1000, ] <- NA if (any(is.na(dfrq[1, ]))) { dfrq <- dfrq[!is.na(dfrq[, 1]), , drop = FALSE] } # make a matrix containing results and name/order columns dfrq <- data.frame(dfrq, X$start[i] + dfrq[, 1]) if (!is.data.frame(dfrq)) dfrq <- as.data.frame(t(dfrq)) colnames(dfrq) <- c("relative.time", "frequency", "absolute.time") if (!is.data.frame(dfrq)) dfrq <- as.data.frame(t(dfrq)) dfrq <- dfrq[, c(3, 1, 2), drop = FALSE] # remove NAs on edges only if more than if (clip.edges & nrow(dfrq) > 2) { dfrq <- dfrq[which(as.numeric(is.na(dfrq$frequency)) == 0)[1]:nrow(dfrq), , drop = FALSE] # clip end edges dfrq <- dfrq[1:max(which(as.numeric(is.na(dfrq$frequency)) == 0)), , drop = FALSE] } # interpolate if no raw.contour if (!raw.contour) { # if more than one detection extrapolate else repeat value if (nrow(dfrq) > 1 | all(is.na(dfrq[, 3]))) { apdom <- try(approx( x = dfrq$relative.time[!is.na(dfrq$frequency)], y = dfrq$frequency[!is.na(dfrq$frequency)], xout = seq( from = min(dfrq$relative.time, na.rm = TRUE), to = max(dfrq$relative.time, na.rm = TRUE), length.out = length.out ), method = "linear" ), silent = TRUE) if (is(apdom, "try-error")) { apdom <- list(x = seq( from = 0, to = X$end[i] - X$start[i], length.out = length.out ), y = rep(NA, length.out)) } } else # repeat same value length.out times if only 1 detection { apdom <- dfrq[rep(1, length.out), , drop = FALSE] apdom[, 1] <- seq( from = X$start[i], to = X$end[i], length.out = length.out ) apdom[, 2] <- apdom[, 1] - X$start[i] colnames(apdom)[3] <- "y" } if (clip.edges & !raw.contour) { # fix for ploting with trackfreqs dfrq1[, 2][is.na(dfrq1[, 2])] <- 0 # calculate time at start and end with no amplitude detected (duration of clipped edges) durend1 <- suppressWarnings(diff(range(dfrq1[, 1][rev(cumsum(rev(dfrq1[, 2])) == 0)]))) durend <- durend1 if (is.infinite(durend) | is.na(durend)) durend <- 0 durst1 <- suppressWarnings(diff(range(dfrq1[, 1][cumsum(dfrq1[, 2]) == 0]))) durst <- durst1 if (is.infinite(durst) | is.na(durst)) durst <- 0 by.dur <- mean(diff(apdom$x)) clipst <- length(seq(from = 0, to = durst, by = by.dur)) clipend <- length(seq(from = 0, to = durend, by = by.dur)) apdom1 <- apdom apdom1 <- list(x = apdom$x, y = apdom$y) apdom1$y <- c(rep(NA, clipst), apdom, rep(NA, clipend)) if (is.infinite(durst1) | is.na(durst1)) apdom1$y <- apdom1$y[-1] if (is.infinite(durend1) | is.na(durend1)) apdom1$y <- apdom1$y[-length(apdom1$y)] cstm.cntr <- data.frame(sound.files = X$sound.files[i], selec = X$selec[i], t(apdom1$y)) } if (!raw.contour) { cstm.cntr <- data.frame(sound.files = X$sound.files[i], selec = X$selec[i], t(apdom$y)) } else { cstm.cntr <- dfrq } } if (img) { warbleR::track_freq_contour( X = X[i, , drop = FALSE], wl = wl, osci = FALSE, leglab = leglab, pb = FALSE, wn = wn, bp = bp, parallel = 1, path = path, img.suffix = img.suffix, ovlp = ovlp, custom.contour = cstm.cntr, frange.detec = FALSE, ... ) } if (!raw.contour) { return(t(apdom$y)) } else { return(dfrq) } } } if (type == "fundamental") { contour_FUN <- function(X, i, bp, wl, threshold, entropy.range, raw.contour, track.harm, adjust.wl) { # Read sound files to get sample rate and length r <- warbleR::read_sound_file(X = X, path = path, index = i, header = TRUE) f <- r$sample.rate b <- bp if (!is.null(b)) { if (b[2] > floor(f / 2000)) b[2] <- floor(f / 2000) b <- b * 1000 } r <- warbleR::read_sound_file(X = X, path = path, index = i) # calculate fundamental frequency at each time point if (ff.method == "seewave") { ffreq1 <- seewave::fund(r, fmax = b[2], f = f, ovlp = ovlp, threshold = threshold, plot = FALSE) } else { if (any(slotNames(r) == "stereo")) if (r@stereo) r <- mono(r, which = "both") suppressWarnings(ff1 <- tuneR::FF(tuneR::periodogram(r, width = wl, overlap = wl * ovlp / 100), peakheight = (100 - threshold) / 100) / 1000) ff2 <- seq(0, X$end[i] - X$start[i], length.out = length(ff1)) ffreq1 <- cbind(ff2, ff1) } ffreq <- matrix(ffreq1[!is.na(ffreq1[, 2]), ], ncol = 2) ffreq <- matrix(ffreq[ffreq[, 2] > b[1] / 1000, ], ncol = 2) if (nrow(ffreq) < 2) { apfund <- list() apfund$x <- ffreq1[, 1] apfund$y <- rep(NA, length.out) apfund1 <- apfund } else { if (!clip.edges) { # clip start edges ffreq <- ffreq[which(as.numeric(is.na(ffreq[, 2])) == 0)[1]:nrow(ffreq), ] # clip end edges ffreq <- ffreq[1:max(which(as.numeric(is.na(ffreq[, 2])) == 0)), ] # interpolate apfund <- approx(ffreq[, 1], ffreq[, 2], xout = seq( from = ffreq1[1, 1], to = ffreq1[nrow(ffreq1), 1], length.out = length.out ), method = "linear" ) apfund1 <- apfund } else { if (!raw.contour) { apfund <- approx(ffreq[, 1], ffreq[, 2], xout = seq( from = ffreq[1, 1], to = ffreq[nrow(ffreq), 1], length.out = length.out ), method = "linear" ) } else { apfund <- ffreq } # fix for ploting with trackfreqs # calculate time at start and end with no amplitude detected (duration of clipped edges) durend1 <- suppressWarnings(diff(range(ffreq1[, 1][rev(cumsum(rev(ffreq1[, 2])) == 0)]))) durend <- durend1 if (is.infinite(durend) | is.na(durend)) durend <- 0 durst1 <- suppressWarnings(diff(range(ffreq1[, 1][cumsum(ffreq1[, 2]) == 0]))) durst <- durst1 if (is.infinite(durst) | is.na(durst)) durst <- 0 by.dur <- mean(diff(apfund$x)) clipst <- length(seq(from = 0, to = durst, by = by.dur)) clipend <- length(seq(from = 0, to = durend, by = by.dur)) apfund1 <- apfund apfund1$y <- c(rep(NA, clipst), apfund$y, rep(NA, clipend)) if (is.infinite(durst1) | is.na(durst1)) apfund1$y <- apfund1$y[-1] if (is.infinite(durend1) | is.na(durend1)) apfund1$y <- apfund1$y[-length(apfund1$y)] } } if (img) { warbleR::track_freq_contour(X[i, , drop = FALSE], wl = wl, osci = FALSE, leglab = leglab, pb = FALSE, wn = wn, parallel = 1, path = path, img.suffix = img.suffix, ovlp = ovlp, custom.contour = data.frame(sound.files = X$sound.files[i], selec = X$selec[i], t(apfund$y)), ... ) } return(apfund$y) } } if (type == "entropy") { contour_FUN <- function(X, i, bp, wl, threshold, entropy.range, raw.contour, track.harm, adjust.wl) { # Read sound files to get sample rate and length r <- warbleR::read_sound_file(X = X, path = path, index = i, header = TRUE) f <- r$sample.rate # if bp is frange if (!is.null(bp)) { if (bp[1] == "frange") bp <- c(X$bottom.freq[i], X$top.freq[i]) } # in case bp its higher than can be due to sampling rate b <- bp if (!is.null(b)) { if (b[2] > floor(f / 2000)) b[2] <- floor(f / 2000) b <- b * 1000 } r <- warbleR::read_sound_file(X = X, path = path, index = i) # filter if this was needed if (!is.null(bp)) r <- ffilter(wave = r, from = b[1], to = b[2]) # measure espectral entropy sp.en <- csh( wave = r, f = f, wl = wl, ovlp = ovlp, wn = wn, threshold = threshold, plot = F ) if (clip.edges) { # remove initial values with 0 sp.en1 <- sp.en[cumsum(sp.en[, 2]) != 0, ] # remove end values with 0 sp.en1 <- sp.en1[rev(cumsum(rev(sp.en1[, 2])) != 0), ] } else { sp.en1 <- sp.en } apen <- approx(sp.en1[, 1], sp.en1[, 2], xout = seq( from = sp.en1[1, 1], to = sp.en1[nrow(sp.en1), 1], length.out = length.out ), method = "linear" ) # fix for ploting with trackfreqs if (clip.edges) { apen1 <- approx(sp.en[, 1], sp.en[, 2], xout = seq( from = sp.en[1, 1], to = sp.en[nrow(sp.en), 1], length.out = length.out ), method = "linear" ) # make 0s at start and end NAs so they are plot at the bottom by trackfreqs apen1$y[cumsum(apen1$y) == 0] <- NA apen1$y[rev(cumsum(rev(apen1$y))) == 0] <- NA } else { apen1 <- apen } correc.apen <- entropy.range[1] + (entropy.range[2] - entropy.range[1]) * apen1$y if (img) { warbleR::track_freq_contour(X[i, , drop = FALSE], wl = wl, osci = FALSE, leglab = leglab, pb = FALSE, wn = wn, parallel = 1, path = path, img.suffix = img.suffix, ovlp = ovlp, custom.contour = data.frame(sound.files = X$sound.files[i], selec = X$selec[i], t(correc.apen)), ... ) } return(apen$y) } } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function lst <- pblapply_wrblr_int(pbar = pb, X = 1:nrow(X), cl = cl, FUN = function(i) { round(contour_FUN(X, i, bp, wl, threshold, entropy.range, raw.contour, track.harm, adjust.wl), 4) }) df <- data.frame(sound.files = X$sound.files, selec = X$selec, as.data.frame(matrix(unlist(lst), nrow = length(X$sound.files), byrow = TRUE))) colnames(df)[3:ncol(df)] <- paste("ffreq", 1:(ncol(df) - 2), sep = "-") return(df) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/freq_ts.R
# Combine full_spectrograms images to single pdf files #' #' \code{full_spectrogram2pdf} combines \code{\link{full_spectrograms}} images in .jpeg format to a single pdf file. #' @usage full_spectrogram2pdf(keep.img = TRUE, overwrite = FALSE, #' parallel = 1, path = NULL, pb = TRUE) #' @param keep.img Logical argument. Indicates whether jpeg files should be kept (default) or remove. #' (including sound file and page number) should be magnified. Default is 1. #' @param overwrite Logical argument. If \code{TRUE} all jpeg pdf will be produced again #' when code is rerun. If \code{FALSE} only the ones missing will be produced. Default is \code{FALSE}. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @export #' @name full_spectrogram2pdf #' @details The function combines spectrograms for complete sound files from the \code{\link{full_spectrograms}} function into #' a single pdf (for each sound file). #' @seealso \code{\link{full_spectrograms}}, \code{\link{catalog2pdf}} #' @return Image files in pdf format with spectrograms of entire sound files in the working directory. #' @examples #' \dontrun{ #' # save sound file examples #' data(list = c("Phae.long1", "Phae.long2")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' #' full_spectrograms( #' sxrow = 2, rows = 8, pal = reverse.heat.colors, wl = 300, #' it = "jpeg", path = tempdir() #' ) #' #' # now create single pdf removing jpeg #' full_spectrogram2pdf(keep.img = FALSE, path = tempdir()) #' #' # check this floder #' tempdir() #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on mar-12-2018 (MAS) full_spectrogram2pdf <- function(keep.img = TRUE, overwrite = FALSE, parallel = 1, path = NULL, pb = TRUE) { # error message if jpeg package is not installed if (!requireNamespace("jpeg", quietly = TRUE)) { stop2("must install 'jpeg' to use this function") } #### set arguments from options # get function arguments argms <- methods::formalArgs(full_spectrogram2pdf) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # list jpeg files imgs <- list.files(path = path, pattern = "\\.jpeg$", ignore.case = TRUE) if (length(imgs) == 0) stop2("No .jpeg files were found in the working directory") # remove images that don't have the pX.jpeg ending imgs <- grep("p\\d+\\.jpeg", imgs, value = TRUE) # remove page info at the end of file names to get sound file names or.sf <- gsub("-p\\d+\\.jpeg", "", imgs) # loop over each sound file name # no.out <- parallel::mclapply(unique(or.sf), mc.cores = parallel, function(x) l2pdfFUN <- function(i, overwrite, keep.img) { if (any(!overwrite & !file.exists(file.path(path, paste0(i, ".pdf"))), overwrite)) { pdf(file = file.path(path, paste0(i, ".pdf")), width = 8.5, height = 11) # order imgs so they look order in the pdf subimgs <- imgs[or.sf == i] if (length(subimgs) > 1) { pgs <- substr(subimgs, regexpr("p\\d+\\.jpeg", subimgs), nchar(subimgs)) pgs <- as.numeric(gsub("p|.jpeg|.jpg", "", pgs, ignore.case = TRUE)) subimgs <- subimgs[order(pgs)] } # plot img <- jpeg::readJPEG(file.path(path, subimgs[1])) par(mar = rep(0, 4)) plot.new() mr <- par("usr") graphics::rasterImage(img, mr[1], mr[3], mr[2], mr[4]) # loop over the following pages if more than 1 page if (length(subimgs) > 1) { no.out <- lapply(subimgs[-1], function(y) { plot.new() par(mar = rep(0, 4)) mr <- par("usr") img2 <- jpeg::readJPEG(file.path(path, y)) graphics::rasterImage(img2, mr[1], mr[3], mr[2], mr[4]) }) } dev.off() if (!keep.img) unlink(subimgs) } } # ) # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function lst <- pblapply_wrblr_int(pbar = pb, X = unique(or.sf), cl = cl, FUN = function(i) { l2pdfFUN(i, overwrite, keep.img) }) } ############################################################################################################## #' alternative name for \code{\link{full_spectrogram2pdf}} #' #' @keywords internal #' @details see \code{\link{full_spectrogram2pdf}} for documentation #' @export lspec2pdf <- full_spectrogram2pdf
/scratch/gouwar.j/cran-all/cranData/warbleR/R/full_spectrogram2pdf.R
#' Create long spectrograms of entire sound files #' #' \code{full_spectrograms} produces image files with spectrograms of entire sound files split into multiple #' rows. #' @usage full_spectrograms(X = NULL, flim = NULL, sxrow = 5, rows = 10, #' collevels = seq(-40, 0, 1), ovlp = 50, parallel = 1, wl = 512, gr = FALSE, #' pal = reverse.gray.colors.2, cex = 1, it = "jpeg", flist = NULL, #' overwrite = TRUE, path = NULL, pb = TRUE, fast.spec = FALSE, labels = "selec", #' horizontal = FALSE, song = NULL, suffix = NULL, dest.path = NULL, #' only.annotated = FALSE, ...) #' @param X 'selection_table' object or any data frame with columns #' for sound file name (sound.files), selection number (selec), and start and end time of signal #' (start and end). If given, a transparent box is plotted around each selection and the selections are labeled with the selection number #' (and selection comment, if available). Default is \code{NULL}. Alternatively, it can also take the output of \code{\link{cross_correlation}} or \code{\link{auto_detec}} (when 'output' is a 'list', see \code{\link{cross_correlation}} or \code{\link{auto_detec}}). If supplied a secondary row is displayed under each spectrogram showing the detection (either cross-correlation scores or wave envelopes) values across time. #' @param flim A numeric vector of length 2 indicating the highest and lowest #' frequency limits (kHz) of the spectrogram, as in #' \code{\link[seewave]{spectro}}. Default is \code{NULL}. Alternatively, a character vector similar to \code{c("-1", "1")} in which the first number is the value to be added to the minimum bottom frequency in 'X' and the second the value to be added to the maximum top frequency in 'X'. This is computed independently for each sound file so the frequency limit better fits the frequency range of the annotated signals. This is useful when plotting annotated spectrograms with marked differences in the frequency range of annotations among sond files. Note that top frequency adjustment is ignored if 'song' labels are included (argument 'song'). #' @param sxrow A numeric vector of length 1. Specifies seconds of spectrogram #' per row. Default is 5. #' @param rows A numeric vector of length 1. Specifies number of rows per #' image file. Default is 10. #' @param collevels A numeric vector of length 3. Specifies levels to partition the #' amplitude range of the spectrogram (in dB). The more levels the higher the #' resolution of the spectrogram. Default is seq(-40, 0, 1). #' @param ovlp Numeric vector of length 1 specifying \% of overlap between two #' consecutive windows, as in \code{\link[seewave]{spectro}}. Default is 50. High values of ovlp #' slow down the function but produce more accurate selection limits (when X is provided). #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param wl A numeric vector of length 1 specifying the window length of the spectrogram, default #' is 512. #' @param gr Logical argument to add grid to spectrogram. Default is \code{FALSE}. #' @param pal Color palette function for spectrogram. Default is reverse.gray.colors.2. See #' \code{\link[seewave]{spectro}} for more palettes. #' @param cex A numeric vector of length 1 giving the amount by which text #' (including sound file and page number) should be magnified. Default is 1. #' @param it A character vector of length 1 giving the image type to be used. Currently only #' "tiff" and "jpeg" are admitted. Default is "jpeg". #' @param flist character vector or factor indicating the subset of files that will be analyzed. Ignored #' if X is provided. #' @param overwrite Logical argument. If \code{TRUE} all selections will be analyzed again #' when code is rerun. If \code{FALSE} only the selections that do not have a image #' file in the working directory will be analyzed. Default is \code{FALSE}. #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @param fast.spec Logical. If \code{TRUE} then image function is used internally to create spectrograms, which substantially #' increases performance (much faster), although some options become unavailable, as collevels, and sc (amplitude scale). #' This option is indicated for signals with high background noise levels. Palette colors \code{\link[monitoR:specCols]{gray.1}}, \code{\link[monitoR:specCols]{gray.2}}, #' \code{\link[monitoR:specCols]{gray.3}}, \code{\link[monitoR:specCols]{topo.1}} and \code{\link[monitoR:specCols]{rainbow.1}} (which should be imported from the package monitoR) seem #' to work better with 'fast' spectrograms. Palette colors \code{\link[monitoR:specCols]{gray.1}}, \code{\link[monitoR:specCols]{gray.2}}, #' \code{\link[monitoR:specCols]{gray.3}} offer #' decreasing darkness levels. #' @param labels Character string with the name of the column(s) for selection #' labeling. Default is 'selec'. Set to \code{NULL} to remove labels. #' @param horizontal Logical. Controls if the images are produced as horizontal or vertical pages. Default is \code{FALSE}. #' @param song Character string with the name of the column to used as a label a for higher #' organization level in the song (similar to 'song_colm' in \code{\link{song_analysis}}). If supplied then lines above the selections belonging to the same #' 'song' are plotted. Ignored if 'X' is not provided. #' @param suffix Character vector of length 1. Suffix for the output image file (to be added at the end of the default file name). Default is \code{NULL}. #' @param dest.path Character string containing the directory path where the image files will be saved. #' If \code{NULL} (default) then the folder containing the sound files will be used instead. #' @param only.annotated Logical argument to control if only the pages that contained annotated sounds (from 'X') are printed. Only used if 'X' is supplied. #' @param ... Additional arguments for image formatting. It accepts 'width', 'height' (which will overwrite 'horizontal') and 'res' as in \code{\link[grDevices]{png}}. #' @return image files with spectrograms of entire sound files in the working directory. Multiple pages #' can be returned, depending on the length of each sound file. #' @export #' @name full_spectrograms #' @details The function creates spectrograms for complete sound files, printing #' the name of the sound files and the "page" number (p1-p2...) at the upper #' right corner of the image files. If 'X' is #' supplied, the function delimits and labels the selections. #' This function aims to facilitate visual inspection of multiple files as well as visual classification #' of vocalization units and the analysis of animal vocal sequences. #' @seealso \code{\link{full_spectrogram2pdf}}, \code{\link{catalog2pdf}}, \code{\link{cross_correlation}}, \code{\link{auto_detec}} #' @examples #' \dontrun{ #' # save sound file examples to temporary working directory #' data(list = c("Phae.long1", "Phae.long2", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' #' full_spectrograms( #' sxrow = 2, rows = 8, pal = reverse.heat.colors, wl = 300, #' path = tempdir() #' ) #' #' # including selections #' full_spectrograms( #' sxrow = 2, rows = 8, X = lbh_selec_table, #' pal = reverse.heat.colors, overwrite = TRUE, wl = 300, path = tempdir() #' ) #' #' # check this floder #' # tempdir() #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on mar-13-2018 (MAS) full_spectrograms <- function(X = NULL, flim = NULL, sxrow = 5, rows = 10, collevels = seq(-40, 0, 1), ovlp = 50, parallel = 1, wl = 512, gr = FALSE, pal = reverse.gray.colors.2, cex = 1, it = "jpeg", flist = NULL, overwrite = TRUE, path = NULL, pb = TRUE, fast.spec = FALSE, labels = "selec", horizontal = FALSE, song = NULL, suffix = NULL, dest.path = NULL, only.annotated = FALSE, ...) { #### set arguments from options # get function arguments argms <- methods::formalArgs(full_spectrograms) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call()) # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop("'path' provided does not exist") } else { path <- normalizePath(path) } # check dest.path if (is.null(dest.path)) { dest.path <- getwd() } else if (!dir.exists(dest.path)) { stop("'path' provided does not exist") } else { dest.path <- normalizePath(dest.path) } # read files files <- list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE) # stop if files are not in working directory if (length(files) == 0) stop("no sound files in working directory") # subet based on file list provided (flist) if (!is.null(flist)) files <- files[files %in% flist] if (length(files) == 0) stop("selected sound files are not in working directory") # set W to null by default (this is the detection data.frame) W <- NULL # if X provided and comes from cross_correlation if (!is.null(X)) { if (is(X, "xcorr.output")) { # no cutoff in only xcorr cutoff <- NA # extract scores W <- X$scores # remove whole.file from sound file name W$sound.files <- gsub("-whole.file", "", W$sound.files) # set X to null X <- NULL } } # if X is not from xcorr.output if (!is.null(X)) { # if is a data frame or st/est if (!is(X, "find_peaks.output") & !is(X, "autodetec.output")) { # list only files in X files <- files[files %in% X$sound.files] # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X))) stop("X is not of a class 'data.frame' or 'selection_table'") # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop("NAs found in start and/or end columns") # check if all columns are found if (any(!(c("sound.files", "selec", "start", "end") %in% colnames(X)))) { stop(paste(paste(c("sound.files", "selec", "start", "end")[!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } # if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) stop("'start' and 'end' must be numeric") # if any start higher than end stop if (any(X$end - X$start <= 0)) stop(paste("Start is higher than or equal to end in", length(which(X$end - X$start <= 0)), "case(s)")) } # if coming from find_peaks if (is(X, "find_peaks.output")) { # cut off for detection lines cutoff <- X$cutoff # get time contours W <- X$scores # remove whole.file from sound file name W$sound.files <- gsub("-whole.file", "", W$sound.files) # leave only sound file names if (any(!grepl("\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE, W$sound.files))) { W$sound.files <- substr(x = W$sound.files, start = 0, stop = sapply(gregexpr(pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE, W$sound.files), "[[", 1) + 3) } # get selection table and overwrite X X <- X$selection.table # add label of type of detection X$type <- "find_peaks" # list only files in W files <- files[files %in% W$sound.files] } # if coming from autodetec if (is(X, "autodetec.output")) { # cut off for detection lines if (is.null(X$bottom.line.thresholds)) { cutoff <- X$parameters$threshold } else { cutoff <- X$bottom.line.thresholds } # get time contours W <- X$envelopes # rename column with contours names(W)[names(W) == "amplitude"] <- "scores" # get selection table and overwrite X X <- X$selection.table # add label of type of detection X$type <- "autodetec" # list only files in W files <- files[files %in% W$sound.files] } # stop if files are not in working directory if (length(files) == 0) stop("sound files in X are not in working directory") } # if flim is not vector or length!=2 stop if (!is.null(flim)) { if (!is.vector(flim)) { stop("'flim' must be a vector of length 2") } else if (!length(flim) == 2) stop("'flim' must be a vector of length 2") else if (is.character(flim) & is.null(X)) stop("'X' must be supplied when 'flim' is a character vector (dynamic frequency limits)") else if (is.character(flim) & (is.null(X$top.freq) | is.null(X$top.freq))) stop("'X' must contain 'top.freq' and 'bottom.freq' columns if 'flim' is a character vector (dynamic frequency limits)") } # if wl is not vector or length!=1 stop if (is.null(wl)) { stop("'wl' must be a numeric vector of length 1") } else { if (!is.vector(wl)) { stop("'wl' must be a numeric vector of length 1") } else { if (!length(wl) == 1) stop("'wl' must be a numeric vector of length 1") } } # if sxrow is not vector or length!=1 stop if (is.null(sxrow)) { stop("'sxrow' must be a numeric vector of length 1") } else { if (!is.vector(sxrow)) { stop("'sxrow' must be a numeric vector of length 1") } else { if (!length(sxrow) == 1) stop("'sxrow' must be a numeric vector of length 1") } } # if rows is not vector or length!=1 stop if (is.null(rows)) { stop("'rows' must be a numeric vector of length 1") } else { if (!is.vector(rows)) { stop("'rows' must be a numeric vector of length 1") } else { if (!length(rows) == 1) stop("'rows' must be a numeric vector of length 1") } } # if picsize is not vector or length!=1 stop if (is.null(cex)) { stop("'picsize' must be a numeric vector of length 1") } else { if (!is.vector(cex)) { stop("'picsize' must be a numeric vector of length 1") } else { if (!length(cex) == 1) stop("'picsize' must be a numeric vector of length 1") } } # if it argument is not "jpeg" or "tiff" if (!any(it == "jpeg", it == "tiff")) stop(paste("Image type", it, "not allowed")) # if parallel is not numeric if (!is.numeric(parallel)) stop("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop("'parallel' should be a positive integer") ## calculate song level parameters if (!is.null(X) & !is.null(song)) { if (!any(names(X) == song)) stop(paste(song, "column not found")) Xsong <- song_analysis(X, song_colm = song, pb = FALSE) } # overwrite if (!overwrite) { files <- files[!gsub("\\.wav$|\\.wac$|\\.mp3$|\\.flac$", "", list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE), ignore.case = TRUE) %in% unlist(sapply(strsplit(as.character(list.files(path = path, pattern = paste(it, "$", sep = "" ), ignore.case = TRUE)), "-p", fixed = TRUE), "[", 1))] } files <- files[!is.na(files)] # stop if all files have been analyzed if (length(files) == 0) stop("all sound files have been processed") # create function for making spectrograms lspecFUN <- function(z, fl, sl, li, X, W) { rec <- warbleR::read_sound_file(X = z, path = path) # read wave file f <- [email protected] # set sampling rate if (is.null(fl)) { fl <- c(0, floor(f / 2000)) } else # if fl is dynamic if (is.character(fl)) { fl <- c(min(X$bottom.freq[X$sound.files == z]) + as.numeric(fl[1]), max(X$top.freq[X$sound.files == z]) + as.numeric(fl[2])) } if (fl[1] < 0) { fl[1] <- 0 } # in case flim is higher than can be due to sampling rate frli <- fl if (frli[2] > ceiling(f / 2000) - 1) frli[2] <- ceiling(f / 2000) - 1 # set duration dur <- seewave::duration(rec) # if duration is multiple of sl if (!length(grep("[^[:digit:]]", as.character(dur / sl)))) { rec <- seewave::cutw(wave = rec, f = f, from = 0, to = dur - 0.001, output = "Wave") } # cut a 0.001 s segment of rec dur <- seewave::duration(rec) # reset duration # get page id pages <- 1:ceiling(dur / (li * sl)) pages_df <- data.frame(page = pages, start = li * sl * (pages - 1), end = li * sl * (pages)) pages_df$annotated <- TRUE if (!is.null(X)) { Y <- X[X$sound.files == z, ] # subset X data # get id of pages to print if only.annotated = TRUE if (only.annotated) { pages_df$annotated <- vapply(seq_len(nrow(pages_df)), function(x) { any_annotation <- sum(Y$start > pages_df$start[x] & Y$start < pages_df$end[x] | Y$end > pages_df$start[x] & Y$end < pages_df$end[x]) annotated <- if (any_annotation > 0) TRUE else FALSE return(annotated) }, FUN.VALUE = logical(1)) } } if (!is.null(X) & !is.null(song)) Ysong <- Xsong[Xsong$sound.files == z, , drop = FALSE] # loop over pages no.out <- lapply(pages_df$page[pages_df$annotated], function(j) { img_wrlbr_int(filename = paste0(substring(z, first = 1, last = nchar(z) - 4), "-", suffix, "-p", j, ".", it), path = dest.path, units = "in", horizontal = horizontal, ...) # set number of rows mfrow <- c(li, 1) # if detections should be printed if (!is.null(W)) { if (any(W$sound.files == z)) { mfrow <- c(li * 2, 1) } } par(mfrow = mfrow, cex = 0.6, mar = c(0, 1, 0, 0), oma = c(2, 2, 0.5, 0.5), tcl = -0.25) # creates spectrogram rows x <- 0 while (x <= li - 1) { x <- x + 1 # for rows with complete spectro if (all(((x) * sl + li * (sl) * (j - 1)) - sl < dur & (x) * sl + li * (sl) * (j - 1) < dur)) { suppressWarnings(spectro_wrblr_int(rec, f = f, wl = wl, flim = frli, tlim = c(((x) * sl + li * (sl) * (j - 1)) - sl, (x) * sl + li * (sl) * (j - 1)), ovlp = ovlp, collevels = collevels, grid = gr, scale = FALSE, palette = pal, axisX = TRUE, fast.spec = fast.spec )) if (x == 1) { text((sl - 0.01 * sl) + (li * sl) * (j - 1), frli[2] - (frli[2] - frli[1]) / 10, paste(substring(z, first = 1, last = nchar(z) - 4 ), "-p", j, sep = ""), pos = 2, font = 2, cex = cex) } # add annotations if (!is.null(X)) { # loop for elements if (nrow(Y) > 0) { for (e in 1:nrow(Y)) { # if freq columns are not provided ys <- if (is.null(Y$top.freq)) { frli[c(1, 2, 2, 1)] } else { c(Y$bottom.freq[e], Y$top.freq[e], Y$top.freq[e], Y$bottom.freq[e]) } # plot polygon polygon(x = rep(c(Y$start[e], Y$end[e]), each = 2), y = ys, lty = 2, border = "#07889B", col = adjustcolor("#07889B", alpha.f = 0.12), lwd = 1.2) if (!is.null(labels)) { text(labels = paste(Y[e, labels], collapse = "-"), x = (Y$end[e] + Y$start[e]) / 2, y = if (is.null(Y$top.freq)) frli[2] - 2 * ((frli[2] - frli[1]) / 12) else Y$top.freq[e], pos = 3) } } } # loop for songs if (!is.null(song)) { for (w in 1:nrow(Ysong)) { lines(y = rep(frli[2] - 0.7 * ((frli[2] - frli[1]) / 12), 2), x = c(Ysong$start[w], Ysong$end[w]), lwd = 5, col = adjustcolor("#E37222", 0.5), lend = 0) if (!is.null(labels)) { text(labels = Ysong[w, song], x = (Ysong$end[w] + Ysong$start[w]) / 2, y = frli[2] - 0.7 * ((frli[2] - frli[1]) / 12), adj = 0, cex = 1.5) } } } } } else { # for rows with incomplete spectro (final row) if (all(((x) * sl + li * (sl) * (j - 1)) - sl < dur & (x) * sl + li * (sl) * (j - 1) > dur)) { spectro_wrblr_int( seewave::pastew(seewave::noisew( f = f, d = (x) * sl + li * (sl) * (j - 1) - dur + 1, type = "unif", listen = FALSE, output = "Wave" ), seewave::cutw( wave = rec, f = f, from = ((x) * sl + li * (sl) * (j - 1)) - sl, to = dur, output = "Wave" ), f = f, output = "Wave"), f = f, wl = wl, flim = frli, tlim = c(0, sl), ovlp = ovlp, collevels = collevels, grid = gr, scale = FALSE, palette = pal, axisX = FALSE, fast.spec = fast.spec ) if (x == 1) { text((sl - 0.01 * sl) + (li * sl) * (j - 1), frli[2] - (frli[2] - frli[1]) / 10, paste(substring(z, first = 1, last = nchar(z) - 4 ), "-p", j, sep = ""), pos = 2, font = 2, cex = cex) } # add white polygon add final row on part without signal usr <- par("usr") polygon(x = rep(c(sl - ((x) * sl + li * (sl) * (j - 1) - dur), usr[2]), each = 2), y = c(usr[3], usr[4], usr[4], usr[3]), col = "white") # add X lines and labels if (!is.null(X)) { adjx <- ((x) * sl + li * (sl) * (j - 1)) - sl if (nrow(Y) > 0) { for (e in 1:nrow(Y)) { ys <- if (is.null(Y$top.freq)) { frli[c(1, 2, 2, 1)] } else { c(Y$bottom.freq[e], Y$top.freq[e], Y$top.freq[e], Y$bottom.freq[e]) } polygon(x = rep(c(Y$start[e], Y$end[e]), each = 2) - adjx, y = ys, lty = 2, border = "#07889B", col = adjustcolor("#07889B", alpha.f = 0.12), lwd = 1.2) if (!is.null(labels)) { text(labels = paste(Y[e, labels], collapse = "-"), x = (Y$end[e] + Y$start[e]) / 2 - adjx, y = if (is.null(Y$top.freq)) frli[2] - 2 * ((frli[2] - frli[1]) / 12) else Y$top.freq[e], adj = 0, pos = 3) } } } # loop for songs if (!is.null(song)) { for (w in 1:nrow(Ysong)) { lines(y = rep(frli[2] - 0.7 * ((frli[2] - frli[1]) / 12), 2), x = c(Ysong$start[w], Ysong$end[w]) - adjx, lwd = 5, col = adjustcolor("#E37222", 0.5), lend = 0) if (!is.null(labels)) { text(labels = Ysong[w, song], x = ((Ysong$end[w] + Ysong$start[w]) / 2) - adjx, y = frli[2] - 0.7 * ((frli[2] - frli[1]) / 12), adj = 0, cex = 1.5) } } } } # add axis to last spectro row axis(1, at = c(0:sl), labels = c((((x) * sl + li * (sl) * (j - 1)) - sl):((x) * sl + li * (sl) * (j - 1))), tick = TRUE) # add text indicating end of sound.files text(dur - (((x) * sl + li * (sl) * (j - 1)) - sl), frli[2] - (frli[2] - frli[1]) / 2, "End of sound file", pos = 4, font = 2, cex = 1.1) # add line indicating end of sound file abline(v = dur - (((x) * sl + li * (sl) * (j - 1)) - sl), lwd = 2.5) } else { plot(1, 1, col = "white", col.axis = "white", col.lab = "white", xaxt = "n", yaxt = "n") } } if (!is.null(W)) { if (any(W$sound.files == z)) { # multiply by 100 if from autodetec y.fctr <- 1 if (!is.null(X)) if (X$type[1] == "autodetec") y.fctr <- 100 # set time and scores xtime <- W$time[W$sound.files == z] yscore <- W$score[W$sound.files == z] * y.fctr # pad to 0 xtime <- c(0, xtime, dur) yscore <- c(0, yscore, 0) # plot detection contour plot(x = xtime, y = yscore, type = "l", xlim = c(((x) * sl + li * (sl) * (j - 1)) - sl, (x) * sl + li * (sl) * (j - 1)), col = adjustcolor("#E37222", 0.7), ylim = c(0, 1.36) * y.fctr, xaxs = "i", yaxs = "i", xaxt = "n", yaxt = "n") # add for all except after last row if (((x) * sl + li * (sl) * (j - 1)) - sl < dur) { axis(2, at = seq(0.2, 1, by = 0.2) * y.fctr, labels = seq(0.2, 1, by = 0.2) * y.fctr, tick = TRUE) } # add fill polygon polygon(cbind(xtime, yscore), col = adjustcolor("#E37222", 0.3), border = NA) if (!is.null(X$score)) { points(x = X$time[X$sound.files == z], X$score[X$sound.files == z], pch = 21, col = adjustcolor("#E37222", 0.7), cex = 3.3) } # add cutoff line if (!is.null(cutoff)) { lines( x = c(0, dur), y = if (length(cutoff) == 1) { rep(cutoff, 2) } else { rep(cutoff[names(cutoff) == paste(X$sound.files[X$sound.files == z][1], X$org.selec[X$sound.files == z][1], sep = "-")][1], 2) }, lty = 2, col = adjustcolor("#07889B", 0.7), lwd = 1.4 ) } abline(v = dur, lwd = 2.5) # loop for elements boxes Q <- X[X$sound.files == z, ] if (!is.null(Q)) { # if not from xcorr.output if (nrow(Q) > 0) { # if some detections were found for (e in 1:nrow(Q)) { # plot polygon polygon(x = rep(c(Q$start[e], Q$end[e]), each = 2), y = c(0, 1.4, 1.4, 0) * y.fctr, lty = 2, border = "#07889B", col = adjustcolor("#07889B", alpha.f = 0.12), lwd = 1.2) } } } } } } dev.off() # reset graphic device }) } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function sp <- pblapply_wrblr_int(pbar = pb, X = files, cl = cl, FUN = function(i) { lspecFUN(z = i, fl = flim, sl = sxrow, li = rows, X = X, W = W) }) } ############################################################################################################## #' alternative name for \code{\link{full_spectrograms}} #' #' @keywords internal #' @details see \code{\link{full_spectrograms}} for documentation. \code{\link{lspec}} will be deprecated in future versions. #' @export lspec <- full_spectrograms
/scratch/gouwar.j/cran-all/cranData/warbleR/R/full_spectrograms.R
#' Gap duration #' #' \code{gaps} measures gap duration #' @usage gaps(X = NULL, by = "sound.files", parallel = 1, pb = TRUE) #' @param X 'selection_table', 'extended_selection_table' (created 'by.song') or data frame with the following columns: 1) "sound.files": name of the sound #' files, 2) "selec": number of the selections, 3) "start": start time of selections, 4) "end": #' end time of selections. #' @param by Character vector with column names. Controls the levels at which gaps will be measured. "sound.files" must always be included. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param pb Logical argument to control progress bar and messages. Default is \code{TRUE}. #' @return A data frame identical to that supplied in 'X', with and additional column ('gaps') with the duration of the time interval between selections. #' @export #' @name gaps #' @details The function measures the time intervals (i.e. gaps) between selections. The gap for a given selection is calculated as the time interval to the selection immediately after. Hence, there is no gap for the last selection in a sound file (or level determined by the 'by' argument). Gap is set to 0 when selections overlap in time. Note that the sound files are not required. #' @seealso \code{\link{inflections}}, \code{\link{song_analysis}}, #' @examples{ #' # get warbleR sound file examples #' data(list = "lbh_selec_table") #' #' # get gaps #' gaps(X = lbh_selec_table) #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on mar-27-2018 (MAS) gaps <- function(X = NULL, by = "sound.files", parallel = 1, pb = TRUE) { #### set arguments from options # get function arguments argms <- methods::formalArgs(gaps) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # if parallel is not numeric if (!is.numeric(parallel)) stop("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop("'parallel' should be a positive integer") # if character is not character if (!is.character(by)) stop("'by' must be a character vector") # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X))) stop("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") # if extended only by song if (is_extended_selection_table(X)) { if (!attributes(X)$by.song$by.song) stop("extended selection tables must be created 'by.song' to be used in song.param()") } # function to calculate gaps gaps_FUN <- function(Y) { # sort Y <- Y[order(Y$start), ] # fill with NAs Y$gaps <- NA # if more than 1 row calculate gaps if (nrow(Y) > 1) { Y$gaps[-nrow(Y)] <- Y$start[-1] - Y$end[-nrow(Y)] # make 0 those negatives as those come from overlapping selections Y$gaps[Y$gaps < 0 & !is.na(Y$gaps)] <- 0 } Y <- as.data.frame(Y) return(Y) } # add sound files to by if (all(by != "sound.files")) { by <- c("sound.files", by) } # set levels for splitting X$..by <- apply(X[, by, drop = FALSE], 1, paste, collapse = "-") # add order column to sort data after calculations X$..order <- 1:nrow(X) # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function gaps_l <- pblapply_wrblr_int(pbar = pb, X = unique(X$..by), cl = cl, FUN = function(i) { Y <- X[X$..by == i, ] return(gaps_FUN(Y)) }) # put into a data frame gaps_df <- do.call(rbind, gaps_l) # order as original gaps_df <- gaps_df[order(gaps_df$..order), ] # remove extra columns gaps_df$..by <- gaps_df$..order <- NULL return(gaps_df) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/gaps.R
#' Convert images into wave objects #' #' \code{image_to_wave} converts images in 'png' format into wave objects using the inverse Fourier transformation #' @export image_to_wave #' @usage image_to_wave(file, duration = 1, samp.rate = 44.1, #' bit.depth = 16, flim = c(0, samp.rate / 2), plot = TRUE) #' @param file Character with the name of image file to be converted. File must be in 'png' format. #' @param duration duration of the output wave object (in s). #' @param samp.rate Numeric vector of length 1 indicating the sampling rate of the output wave object (in kHz). Default is 44.1. #' @param bit.depth Numeric vector of length 1 with the dynamic interval (i.e. bit depth) for output files. Default is 16. #' @param flim Numeric vector of length 2 indicating the highest and lowest #' frequency limits (kHz) in which the image would be located. Default is \code{c(0, samp.rate / 2)}. #' @param plot Logical argument to control if image is plotted after being imported into R. #' @return A single wave object. #' @name image_to_wave #' @details This function converts images in 'png' format into wave objects using the inverse Fourier transformation. #' @examples \donttest{ #' ### create image with text to use in the spectrogram #' # remove margins of plot #' par(mar = rep(0, 4)) #' #' # empty plot #' plot(0, type = "n", axes = FALSE, ann = FALSE, xlim = c(0, 1), ylim = c(0, 1)) #' #' # text to include #' text <- " warbleR " #' #' # add text #' text(x = 0.5, y = 0.5, labels = text, cex = 11, font = 1) #' #' # save image in temporary directory #' dev2bitmap(file.path(tempdir(), "temp-img.png"), type = "pngmono", res = 30) #' #' # read it #' wv <- image_to_wave(file = file.path(tempdir(), "temp-img.png"), plot = TRUE, flim = c(1, 12)) #' #' # output wave object #' # wv #' #' ## plot it #' # reset margins #' par(mar = c(5, 4, 4, 2) + 0.1) #' #' # plot spectrogram #' # spectro(wave = wv, scale = FALSE, collevels = seq(-30, 0, 5), #' # palette = reverse.terrain.colors, ovlp = 90, grid = FALSE, flim = c(2, 11)) #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on dec-27-2019 (MAS) image_to_wave <- function(file, duration = 1, samp.rate = 44.1, bit.depth = 16, flim = c(0, samp.rate / 2), plot = TRUE) { # error message if jpeg package is not installed if (!requireNamespace("png", quietly = TRUE)) { stop2("must install 'png' to use this function") } # get previous graphic settings back when done opar <- par(mar = c(5, 4, 4, 2) + 0.1) on.exit(par(opar)) # check file if (!file.exists(file)) stop2("'file' supplied was not found") # no higher than nyquist frequency if (flim[2] > samp.rate / 2) stop2("high frequency cannot be higher than half the sampling rate (Nyquist frequency)") # read image mat <- png::readPNG(file) # get dimensions dms <- dim(mat) # convert to a single layer if array if (length(dms) == 3) { mat <- 0.21 * mat[, , 1] + 0.71 * mat[, , 1] + 0.07 * mat[, , 3] mat <- mat / max(mat) } # flip horizontally mat <- mat[dms[1]:1, ] # plot if requested if (plot) { par(mar = c(0, 0, 0, 0)) image(t(mat), useRaster = TRUE, col = gray.colors(10)) } # get inverse of color values so darker is louder sound mat <- 1 - mat # if flim is not to whole freq range if (!identical(flim, c(0, samp.rate / 2))) { # calculate difference in freq range to force it to be in supplied flim low.dff <- flim[1] / diff(flim) upp.dff <- ((samp.rate / 2) - flim[2]) / diff(flim) # calculate number of extra rows to add low.extr <- round(dms[1] * low.dff, 0) upp.extr <- round(dms[1] * upp.dff, 0) # add empty cells if (low.extr > 0) { mat <- rbind(matrix(0, nrow = low.extr, ncol = dms[2]), mat) } if (upp.extr > 0) { mat <- rbind(mat, matrix(0, nrow = upp.extr, ncol = dms[2])) } } # base on number of columns calculate wl given the supplied sampling rate crrnt.wl <- (samp.rate * 1000) / dms[2] * duration # get FT windows win <- seewave::ftwindow(wl = crrnt.wl, wn = "hamming") # get inverse Fourier transformation for each column in image (modified from seewave::istft) inv.ft <- c(sapply(seq(0, crrnt.wl * (dms[2] - 1), by = crrnt.wl), function(b) { X <- mat[, 1 + b / crrnt.wl] mirror <- rev(X[-1]) mirror <- complex(real = Re(mirror), imaginary = -Im(mirror)) X <- c(X, complex(real = Re(X[length(X)]), imaginary = 0), mirror) xprim <- Re(stats::fft(X, inverse = TRUE) / length(X)) y <- xprim[1:crrnt.wl] * win return(y) })) # convert to wave object wave.obj <- seewave::outputw(wave = inv.ft, f = samp.rate * 1000, bit = bit.depth, format = "Wave") return(wave.obj) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/image_to_wave.R
#' Count number of inflections in a frequency contour #' #' \code{inflections} counts the number of inflections in a frequency contour (or any time series) #' @usage inflections(X = NULL, parallel = 1, pb = TRUE) #' @param X data frame with the columns for "sound.files" (sound file name), "selec" (unique identifier for each selection) and columns for each of the frequency values of the contours. No other columns should be included. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param pb Logical argument to control progress bar and messages. Default is \code{TRUE}. #' @return A data frame with 3 columns: "sound.files", "selec" and "infls" (number of inflections). #' @export #' @name inflections #' @details The function counts the number of inflections in a frequency contour. #' @seealso \code{\link{freq_ts}}, \code{\link{track_freq_contour}}, \code{\link{gaps}} #' @examples{ #' # get warbleR sound file examples #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' #' # measure frequency contours #' dom.freq.ts <- freq_ts(X = lbh_selec_table, path = tempdir()) #' #' # get number of inflections #' inflections(X = dom.freq.ts) #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on mar-27-2018 (MAS) inflections <- function(X = NULL, parallel = 1, pb = TRUE) { # if parallel is not numeric if (!is.numeric(parallel)) stop2("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop2("'parallel' should be a positive integer") #### set arguments from options # get function arguments argms <- methods::formalArgs(inflections) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } infls.FUN <- function(Y, l) { if (l) ts <- Y$frequency else ts <- Y[, !names(Y) %in% c("sound.files", "selec")] if (is.data.frame(ts)) ts <- unlist(ts) infls <- length(which(c(FALSE, diff(diff(ts) > 0) != 0))) Y$inflections <- infls Y <- Y[1, colnames(Y) %in% c("sound.files", "selec", "inflections"), drop = FALSE] return(Y) } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } if (is.data.frame(X)) lvs <- 1:nrow(X) else lvs <- seq_len(length(X)) # run loop apply function out <- pblapply_wrblr_int(pbar = pb, X = lvs, cl = cl, FUN = function(i) { is.df <- is.data.frame(X) if (is.df) Y <- X[i, , drop = FALSE] else Y <- X[[i]] return(infls.FUN(Y, l = !is.df)) }) return(do.call(rbind, out)) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/inflections.R
#' Get sound file parameter information #' #' \code{info_sound_files} summariz sound file information #' @usage info_sound_files(path = NULL, files = NULL, parallel = 1, pb = TRUE, skip.error = FALSE, #' file.format = "\\\.wav$|\\\.wac$|\\\.mp3$|\\\.flac$") #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param files character vector indicating the set of files that will be consolidated. File names should not include the full file path. Optional. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param pb Logical argument to control progress bar and messages. Default is \code{TRUE}. #' @param skip.error Logical to control if errors are omitted. If so, files that could not be read will be excluded and their name printed in the console. Default is \code{FALSE}, which will return an error if some files are problematic. #' @param file.format Character string with the format of sound files. By default all sound file formats supported by warbleR are included ("\\\.wav$|\\\.wac$|\\\.mp3$|\\\.flac$"). Note that several formats can be included using regular expression syntax as in \code{\link[base]{grep}}. For instance \code{"\\\.wav$|\\\.mp3$"} will only include .wav and .mp3 files. #' @return A data frame with descriptive information about the sound files in the working directory (or 'path'). See "details". #' @export #' @name info_sound_files #' @details This function is a wrapper for \code{\link{selection_table}} that returns a data frame with the following descriptive parameters for each sound file in the working directory (or 'path'): #' \itemize{ #' \item \code{duration}: duration of selection in seconds #' \item \code{sample.rate}: sampling rate in kHz #' \item \code{channels}: number of channels #' \item \code{bits}: bit depth #' \item \code{wav.size}: sound file size in MB #' \item \code{samples}: number of samples in the sound file #' } #' #' @seealso \code{\link{fix_wavs}}, \code{\link{selection_table}} & \code{\link{check_sels}} #' @examples{ #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' #' #get info #' info_sound_files(path = tempdir()) #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on aug-15-2018 (MAS) info_sound_files <- function(path = NULL, files = NULL, parallel = 1, pb = TRUE, skip.error = FALSE, file.format = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$") { #### set arguments from options # get function arguments argms <- methods::formalArgs(info_sound_files) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # make a selection table from files st <- selection_table(whole.recs = TRUE, path = path, parallel = parallel, pb = pb, verbose = FALSE, skip.error = skip.error, file.format = file.format, files = files) # extract check sels cs <- attributes(st)$check.results # remove 'selec' column and rename 'n.samples' cs$selec <- NULL names(cs)[names(cs) == "n.samples"] <- "samples" # return cs data frame return(cs) } ############################################################################################################## #' alternative name for \code{\link{info_sound_files}} #' #' @keywords internal #' @details see \code{\link{info_sound_files}} for documentation. \code{\link{wav_info}} will be deprecated in future versions. #' @export wav_info <- info_sound_files ############################################################################################################## #' alternative name for \code{\link{info_sound_files}} #' #' @keywords internal #' @details see \code{\link{info_sound_files}} for documentation. \code{\link{info_wavs}} will be deprecated in future versions. #' @export info_wavs <- info_sound_files
/scratch/gouwar.j/cran-all/cranData/warbleR/R/info_sound_files.R
# internal warbleR function called by catalog. Type argument similar to par("bty") but added _ for only bottom and - for top # xys must be a 4 element numeric vector c(x1, x2, y1, y2) #' @noRd #' boxw_wrblr_int <- function(xys = NULL, bty = "o", col = "black", lwd = 1, lty = 1) { if (is.null(xys)) { wh <- par("din") xs <- c(0, wh[1]) ys <- c(0, wh[2]) } else { xys <- c(xys) xs <- xys[1:2] ys <- xys[3:4] } xs <- grconvertX(xs, from = "nic", to = "user") ys <- grconvertY(ys, from = "nic", to = "user") cmb <- rbind(combn(rep(xs, 2), 2), combn(rep(ys, 2), 2)[, c(2:6, 1)])[, -c(3, 6)] if (bty == "c") { cmb <- cmb[, -4] } if (bty == "l") { cmb <- cmb[, -(3:4)] } if (bty == "7") { cmb <- cmb[, 3:4] } if (bty == "u") { cmb <- cmb[, -3] } if (bty == "^") { cmb <- cmb[, -1] } if (bty == "]") { cmb <- cmb[, -2] } if (bty == "_") { cmb <- matrix(cmb[, 1], nrow = 4) } if (bty == "-") { cmb <- matrix(cmb[, 3], nrow = 4) } for (i in seq_len(ncol(cmb))) { lines( x = cmb[1:2, i], y = cmb[3:4, i], xpd = TRUE, col = col, lwd = lwd, lty = lty ) } } # author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on aug-3-2017 (MAS) # internal warbleR function, not to be called by users. It is a modified version of seewave::fadew # fades the start and end of an amplitude envelope # last modification on feb-23-2018 (MAS) fade_env_wrblr_int <- function(nvlp, fin = 0.1, fout = 0.2, shape = "linear") { if (fin + fout > 1) { stop2("'fin' + 'fout' cannot be higher than 1") } if (fin < 0 | fout < 0) { stop2("'fin' and 'fout' cannot be negative") } n <- length(nvlp) IN <- seq(0, 1, length.out = fin * n) OUT <- seq(0, 1, length.out = fout * n) # applied exponential if (shape == "exp") { IN <- exp(IN) IN <- IN - 1 IN <- IN / max(IN) OUT <- exp(OUT) OUT <- OUT - 1 OUT <- OUT / max(OUT) } # applied cosine if (shape == "cos") { if (fin == 0) { IN <- integer(0) } else { IN <- cos(rev(IN)) IN <- IN - min(IN) IN <- IN / max(IN) } if (fout == 0) { OUT <- integer(0) } else { OUT <- cos(rev(OUT)) OUT <- OUT - min(OUT) OUT <- OUT / max(OUT) } } MID <- rep(1, n - (length(IN) + length(OUT))) MID <- nvlp[(length(IN) + 1):(n - length(OUT))] return(c(IN, MID, rev(OUT))) } # internal warbleR function, not to be called by users. It is a modified version of seewave::filled.contour.modif2 # that allows to plot spectrograms on top of each other. filled_contour_color_wrblr_int <- function(x = seq(0, 1, len = nrow(z)), y = seq(0, 1, len = ncol(z)), z, xlim = range(x, finite = TRUE), ylim = range(y, finite = TRUE), col.lab, colaxis, zlim = range(z, finite = TRUE), levels = pretty(zlim, nlevels), add = FALSE, nlevels = 20, color.palette = cm.colors, col = color.palette(length(levels) - 1), plot.title, plot.axes, key.title, asp = NA, xaxs = "i", yaxs = "i", las = 1, axisX = TRUE, axisY = TRUE, bg.col = "white") { if (missing(z)) { if (!missing(x)) { if (is.list(x)) { z <- x$z y <- x$y x <- x$x } else { z <- x x <- seq(0, 1, len = nrow(z)) } } else { stop2("no 'z' matrix specified") } } else if (is.list(x)) { y <- x$y x <- x$x } if (any(diff(x) <= 0) || any(diff(y) <= 0)) { stop2("increasing 'x' and 'y' values expected") } if (!add) { plot.new() plot.window( xlim, ylim, "", xaxs = xaxs, yaxs = yaxs, asp = asp, bg = bg.col ) usr <- par("usr") rect( xleft = usr[1], xright = usr[2], ybottom = usr[3], usr[4], col = bg.col, border = bg.col ) if (!is.matrix(z) || nrow(z) <= 1 || ncol(z) <= 1) { stop2("no proper 'z' matrix specified") } } if (!is.double(z)) { storage.mode(z) <- "double" } .filled.contour(as.double(x), as.double(y), z, as.double(levels), col = col ) if (missing(plot.axes)) { if (axisX) { title( main = "", xlab = "", ylab = "" ) axis(1) } if (axisY) { title( main = "", xlab = "", ylab = "" ) axis(2) } } else { plot.axes } box() if (missing(plot.title)) { title() } else { plot.title } invisible() } # internal warbleR function, not to be called by users. It is a modified version of seewave::filled.contour.modif2 # that allows to plot spectrograms on top of each other. filled_contour_wrblr_int <- function(x = seq(0, 1, len = nrow(z)), y = seq(0, 1, len = ncol(z)), z, xlim = range(x, finite = TRUE), ylim = range(y, finite = TRUE), col.lab, colaxis, zlim = range(z, finite = TRUE), levels = pretty(zlim, nlevels), add = FALSE, nlevels = 20, color.palette = cm.colors, col = color.palette(length(levels) - 1), plot.title, plot.axes, key.title, asp = NA, xaxs = "i", yaxs = "i", las = 1, axisX = TRUE, axisY = TRUE, bg.col = "white", bx = TRUE, cex.axis = 1) { if (missing(z)) { if (!missing(x)) { if (is.list(x)) { z <- x$z y <- x$y x <- x$x } else { z <- x x <- seq(0, 1, len = nrow(z)) } } else { stop2("no 'z' matrix specified") } } else if (is.list(x)) { y <- x$y x <- x$x } if (any(diff(x) <= 0) || any(diff(y) <= 0)) { stop2("increasing 'x' and 'y' values expected") } if (!add) { plot.new() } plot.window(xlim, ylim, "", xaxs = xaxs, yaxs = yaxs, asp = asp ) usr <- par("usr") rect( xleft = usr[1], xright = usr[2], ybottom = usr[3], usr[4], col = bg.col, border = bg.col ) if (!is.matrix(z) || nrow(z) <= 1 || ncol(z) <= 1) { stop2("no proper 'z' matrix specified") } if (!is.double(z)) { storage.mode(z) <- "double" } .filled.contour(as.double(x), as.double(y), z, as.double(levels), col = col ) if (missing(plot.axes)) { if (axisX) { title( main = "", xlab = "", ylab = "" ) axis(1) } if (axisY) { title( main = "", xlab = "", ylab = "" ) axis(2) } } else { plot.axes } if (bx) { box() } if (missing(plot.title)) { title() } else { plot.title } invisible() } # internal warbleR function, not to be called by users. Plots detected frequency range. frd_plot_wrblr_int <- function(wave, detections, wl = 512, wn = "hanning", flim = NULL, bp = NULL, fast.spec = FALSE, ovlp = 50, pal = reverse.gray.colors.2, widths = c(2, 1), main = NULL, all.detec = F) { # attach freq and amplitude values z <- detections$af.mat[, 1] zf <- detections$af.mat[, 2] # sampling rate f <- [email protected] dur <- seewave::duration(wave) # detection limits if (!all.detec) { min.start <- detections$frange$bottom.freq max.end <- detections$frange$top.freq } else { min.start <- detections$detections[, 1] max.end <- detections$detections[, 2] } # fix flim if (!is.null(flim)) { if (flim[2] > floor(f / 2000)) { flim[2] <- f / 2000 } } else { flim <- c(0, floor(f / 2000)) } # set limits for color rectangles down if (is.null(bp)) { lims <- flim } else { lims <- bp } # split screen m <- rbind( c(0, widths[1] / sum(widths), 0, 0.93), # 1 c(widths[1] / sum(widths), 1, 0, 0.93), c(0, 1, 0.93, 1) ) # 3 try(invisible(close.screen(all.screens = TRUE)), silent = TRUE) split.screen(m) screen(1) par(mar = c(3.4, 3.4, 0.5, 0)) # create spectro spectro_wrblr_int2( wave = wave, f = f, flim = flim, fast.spec = fast.spec, palette = pal, ovlp = ovlp, wl = wl, grid = F, tlab = "", flab = "", wn = wn ) # add gray polygon on detected frequency bands out <- lapply(seq_len(length(min.start)), function(e) { rect( xleft = 0, ybottom = ifelse(is.na(min.start[e]), lims[1], min.start[e]), xright = dur, ytop = ifelse(is.na(max.end[e]), lims[2], max.end[e]), col = adjustcolor("#07889B", alpha.f = 0.1), border = adjustcolor("gray", 0.2) ) }) # add line highlighting freq range abline( h = c(min.start, max.end), col = "#80C3FF", lty = 3, lwd = 2 ) # add axis labels mtext( side = 1, text = "Time (s)", line = 2.3 ) mtext( side = 2, text = "Frequency (kHz)", line = 2.3 ) # second plot screen(2) par(mar = c(3.4, 0, 0.5, 0.8)) plot( z, zf, type = "l", ylim = flim, yaxs = "i", xaxs = "i", yaxt = "n", xlab = "", col = "white", xaxt = "n" ) minz <- min(z) maxz <- max(z) # add axis& labels if (detections$type == "percentage") { axis(1, at = seq(0.2, 1, by = 0.4)) mtext( side = 1, text = "Amplitude (%)", line = 2.3 ) } else { axis(1, at = round(seq(0, maxz, by = 10), 0)) mtext( side = 1, text = "Amplitude (dB)", line = 2.3 ) } # fix amplitude values to close polygon (just for ploting) z3 <- c(minz, z, minz) # addd extremes to make polygon close fine zf3 <- c(lims[1], zf, lims[2]) # plot amplitude values curve polygon(cbind(z3, zf3), col = adjustcolor("#E37222", 0.8)) # add border line points(z3, zf3, type = "l", col = adjustcolor("gray", 0.3)) # add background color rect( xleft = minz, ybottom = flim[1], xright = maxz, ytop = flim[2], col = adjustcolor("#4D69FF", 0.05) ) # add gray polygon on detected frequency bands lapply(seq_len(length(min.start)), function(e) { rect( xleft = minz, ybottom = ifelse(is.na(min.start[e]), lims[1], min.start[e]), xright = maxz, ytop = ifelse(is.na(max.end[e]), lims[2], max.end[e]), col = adjustcolor("#07889B", alpha.f = 0.1), border = adjustcolor("gray", 0.2) ) }) # add gray boxes in filtered out freq bands if (!is.null(bp)) { rect( xleft = minz, ybottom = bp[2], xright = maxz, ytop = flim[2], col = adjustcolor("gray", 0.5) ) rect( xleft = minz, ybottom = flim[1], xright = maxz, ytop = bp[1], col = adjustcolor("gray", 0.5) ) } # add line to highligh freq range abline( v = ifelse( detections$type == "percentage", detections$threshold / 100, detections$threshold ), col = adjustcolor("#07889B", 0.7), lty = 3, lwd = 2 ) abline( h = c(min.start, max.end), col = "#80C3FF", lty = 3, lwd = 2 ) if (!is.null(main)) { screen(3) par(mar = rep(0, 4)) plot( 0.5, xlim = c(0, 1), ylim = c(0, 1), type = "n", axes = FALSE, xlab = "", ylab = "", xaxt = "n", yaxt = "n" ) text( x = 0.5, y = 0.35, labels = main, font = 2 ) } # close screens on.exit(invisible(close.screen(all.screens = TRUE))) } # internal warbleR function, not to be called by users. it plots contours, runs locator and return tailored contours # @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on mar-12-2016 (MAS) fix_cntr_wrblr_int <- function(X, j, ending.buttons = 1:4, ncl, tlim, xs, ys, flim, col, alpha, l) { prev.plot <- recordPlot() if (!l) { ts.df.t <- seq(X$start[j], X$end[j], length.out = length(ncl)) - tlim[1] ts.df <- X[, ncl] ncl2 <- ncl } else { ts.df.t <- X[j, grep("...TIME", ncl, value = TRUE, fixed = TRUE)] - tlim[1] ncl2 <- grep("...FREQ", ncl, value = TRUE, fixed = TRUE) ts.df.f <- X[j, ncl2] ts.df <- X[, ncl] } out <- TRUE x <- 1 while (all(out)) { if (x > 1) { replayPlot(prev.plot) } points( x = ts.df.t, y = ts.df[j, ncl2], pch = 20, cex = 1.2, col = adjustcolor(col, alpha.f = alpha) ) if (any(is.na(ts.df[j, seq_len(which.max(ts.df.t))]))) { points( x = ts.df.t[is.na(ts.df.f[seq_len(which.max(ts.df.t))])], y = ((flim[2] - flim[1]) * 0.02) + flim[1], pch = 20, cex = 1.2, col = adjustcolor("gray", alpha.f = alpha) ) } # select second point xy <- locator(n = 1, type = "n") # if on buttoms out <- sapply(ending.buttons, function(w) { out <- !all(xy$x > min(xs) & xy$x < max(xs) & xy$y > min(ys[[w]]) & xy$y < max(ys[[w]])) }) if (!all(out)) { break } else { ts.df[j, ncl2[which.min(abs(ts.df.t - xy$x))]] <- xy$y # if selected is lower than 0 make it xy$x[xy$x < 0] <- 0 xy$y[xy$y < 0] <- 0 } x <- x + 1 } return(list(ts.df = ts.df, xy = xy)) } # internal warbleR function, not to be called by users. Detects frequency range. frd_wrblr_int <- function(wave, wl = 512, fsmooth = 0.1, threshold = 10, wn = "hanning", bp = NULL, ovlp = 50, dB.threshold = NULL) { # get sampling rate f <- [email protected] if (wl >= length(wave@left)) { wl <- length(wave@left) - 1 } if (wl %% 2 != 0) { wl <- wl - 1 } # mean spectrum if (is.null(dB.threshold)) { spc <- meanspec( wave, plot = FALSE, wl = wl, f = f, wn = wn, ovlp = ovlp ) # get frequency windows length for smoothing step <- [email protected] / wl / 1000 # number of samples n <- nrow(spc) # smoothing parameter if (!is.null(fsmooth)) { fsmooth <- fsmooth / step FWL <- fsmooth - 1 # smooth z <- apply(as.matrix(1:(n - FWL)), 1, function(y) { sum(spc[y:(y + FWL), 2]) }) zf <- seq(min(spc[, 1]), max(spc[, 1]), length.out = length(z)) } else { z <- spc[, 2] zf <- spc[, 1] } # remove range outside bp if (!is.null(bp)) { # if there are complete freq bins within freq range if (any(zf > bp[1] & zf < bp[2])) { fbins <- which(zf > bp[1] & zf < bp[2]) } else { # select the one that contains the freq range fbins <- which.max(ifelse(zf - bp[1] > 0, NA, zf - bp[1])):which.max(ifelse(zf - bp[2] > 0, NA, zf - bp[1])) } z <- z[fbins] zf <- zf[fbins] } # make minimum amplitude 0 z <- z - min(z) z[z < 0] <- 0 # normalize amplitude from 0 to 1 if (length(z) > 1) { z <- z / max(z) } # get freqs crossing threshold z1 <- rep(0, length(z)) z1[z > threshold / 100] <- 1 z2 <- z1[2:length(z1)] - z1[1:(length(z1) - 1)] # add 0 to get same length than z z2 <- c(0, z2) # determine start and end of amplitude hills strt <- zf[z2 == 1] nd <- zf[z2 == -1] # add NAs when some ends or starts where not found if (length(strt) != length(nd)) { if (z1[1] == 0) { nd <- c(nd, NA) } else { strt <- c(NA, strt) } } if (length(strt) == 1) { if (z1[1] == 1 & z1[length(z1)] == 1 & strt > nd) { strt <- c(NA, strt) nd <- c(nd, NA) } } # substract half a step to calculate mid point between the 2 freq windows in which the theshold has passed nd <- nd - (step / 2) strt <- strt - (step / 2) meanpeakf <- zf[which.max(z)] + (step / 2) } else { spc <- meanspec( wave, plot = FALSE, wl = wl, f = f, wn = wn, ovlp = ovlp, dB = "max0", dBref = 2 * 10e-5 ) # get frequency windows length for smoothing step <- [email protected] / wl / 1000 # number of samples n <- nrow(spc) # smoothing parameter if (!is.null(fsmooth)) { fsmooth <- fsmooth / step FWL <- fsmooth - 1 # smooth z <- apply(as.matrix(1:(n - FWL)), 1, function(y) { sum(spc[y:(y + FWL), 2]) }) zf <- seq(min(spc[, 1]), max(spc[, 1]), length.out = length(z)) z <- (max(spc[, 2]) - min(spc[, 2])) / (max(z) - min(z)) * (z - max(z)) + max(spc[, 2]) } else { z <- spc[, 2] zf <- spc[, 1] } if (!is.null(bp)) { # remove range outsde bp z <- z[zf > bp[1] & zf < bp[2]] zf <- zf[zf > bp[1] & zf < bp[2]] } z1 <- rep(0, length(z)) z1[z > max(z) - dB.threshold] <- 1 z2 <- z1[2:length(z1)] - z1[1:(length(z1) - 1)] # add 0 to get same length than z z2 <- c(0, z2) # determine start and end of amplitude hills strt <- zf[z2 == 1] nd <- zf[z2 == -1] # add NAs when some ends or starts where not found if (length(strt) != length(nd)) { if (z1[1] == 0) { nd <- c(nd, NA) } else { strt <- c(NA, strt) } } if (length(strt) == 1) { if (z1[1] == 1 & z1[length(z1)] == 1 & strt > nd) { strt <- c(NA, strt) nd <- c(nd, NA) } } # step <- mean(zf[-1] - zf[1:(length(zf) - 1)]) # substract half a step to calculate mid point between the 2 freq windows in which the theshold has passed nd <- nd - (step / 2) strt <- strt - (step / 2) meanpeakf <- zf[which.max(z)] + (step / 2) } # fix range # only start lower than peakf strt <- strt[strt <= meanpeakf] # only ends higher than peakf nd <- nd[nd >= meanpeakf] # get freq range min.strt <- ifelse(length(strt) == 1, strt, strt[which.min(meanpeakf - strt)]) max.nd <- ifelse(length(nd) == 1, nd, nd[which.min(nd - meanpeakf)]) if (!any(is.na(c(min.strt, max.nd)))) { if (min.strt > max.nd) { min.strt <- NA max.nd <- NA } } # force nd and strt the same length adding NAs if (length(nd) > length(strt)) { strt <- c(strt, rep(NA, length(nd) - length(strt))) } if (length(strt) > length(nd)) { nd <- c(nd, rep(NA, length(strt) - length(nd))) } # save everything in a list rl <- list( frange = data.frame(bottom.freq = min.strt, top.freq = max.nd), af.mat = cbind(z, zf), meanpeakf = meanpeakf, detections = cbind(start.freq = strt, end.freq = nd), threshold = ifelse(is.null(dB.threshold), threshold, max(z) - dB.threshold), type = ifelse(is.null(dB.threshold), "percentage", "dB") ) # return rl list return(rl) } # internal warbleR function to save image files in jpeg and tiff format, arguments similar to jpeg # filename must include the image type (jpeg, jpg or tiff) img_wrlbr_int <- function(filename, path = NULL, res = 160, units = "in", width = 8.5, height = 11, horizontal = FALSE) { if (horizontal & missing(width)) { width <- 11 height <- 8.5 } # add path to filename flnm <- file.path(path, filename) # jpeg if (grepl("jpeg$|jpg$", filename)) { jpeg( filename = flnm, res = res, units = units, width = width, height = height ) } else { # or tiff tiff( filename = flnm, res = res, units = units, width = width, height = height ) } } # author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on jun-02-2020 (MAS) # internal warbleR function, not to be called by users. It is a modified version of pbapply::pblapply # that allows to define internally if progress bar would be used (pbapply::pblapply uses pboptions to do this) # last modification on aug-10-2021 (MAS) #' pblapply_wrblr_int <- function(X, FUN, cl = 1, pbar = TRUE, ...) { # conver parallel 1 to null if (!inherits(cl, "cluster")) { if (cl == 1) { cl <- NULL } } FUN <- match.fun(FUN) if (!is.vector(X) || is.object(X)) { X <- as.list(X) } if (!length(X)) { return(lapply(X, FUN, ...)) } if (!is.null(cl)) { if (.Platform$OS.type == "windows") { if (!inherits(cl, "cluster")) { cl <- NULL } } else { if (inherits(cl, "cluster")) { if (length(cl) < 2L) { cl <- NULL } } else { if (cl < 2) { cl <- NULL } } } } if (is.null(cl)) { if (!pbar) { return(lapply(X, FUN, ...)) } Split <- pbapply::splitpb(length(X), 1L, nout = 100) B <- length(Split) pb <- pbapply::startpb(0, B) on.exit(pbapply::closepb(pb), add = TRUE) rval <- vector("list", B) for (i in seq_len(B)) { rval[i] <- list(lapply(X[Split[[i]]], FUN, ...)) pbapply::setpb(pb, i) } } else { if (inherits(cl, "cluster")) { PAR_FUN <- parallel::parLapply if (pbar) { return(PAR_FUN(cl, X, FUN, ...)) } Split <- pbapply::splitpb(length(X), length(cl), nout = 100) B <- length(Split) pb <- pbapply::startpb(0, B) on.exit(pbapply::closepb(pb), add = TRUE) rval <- vector("list", B) for (i in seq_len(B)) { rval[i] <- list(PAR_FUN( cl, X[Split[[i]]], FUN, ... )) pbapply::setpb(pb, i) } } else { if (!pbar) { return(parallel::mclapply(X, FUN, ..., mc.cores = as.integer(cl))) } Split <- pbapply::splitpb(length(X), as.integer(cl), nout = 100) B <- length(Split) pb <- pbapply::startpb(0, B) on.exit(pbapply::closepb(pb), add = TRUE) rval <- vector("list", B) for (i in seq_len(B)) { rval[i] <- list(parallel::mclapply(X[Split[[i]]], FUN, ..., mc.cores = as.integer(cl) )) pbapply::setpb(pb, i) } } } rval <- do.call(c, rval, quote = TRUE) names(rval) <- names(X) rval } # internal warbleR function called by catalog rectw_wrblr_int <- function(xl, yb, xr, yt, bor, cl, ang = NULL, den = NULL, pattern = "no.pattern", lw = 2, lt = 1) { if (pattern == "no.pattern") { rect( xleft = xl, ybottom = yb, xright = xr, ytop = yt, border = bor, col = cl, angle = ang, density = den, lwd = lw, lty = lt ) } else { rect( xleft = xl, ybottom = yb, xright = xr, ytop = yt, border = bor, col = "white", angle = ang, density = den, lwd = lw, lty = lt ) if (pattern == "diamond") { rect( xleft = xl, ybottom = yb, xright = xr, ytop = yt, border = bor, col = cl, density = den, angle = 45, lwd = lw, lty = lt ) rect( xleft = xl, ybottom = yb, xright = xr, ytop = yt, border = bor, col = cl, density = den, angle = 135, lwd = lw, lty = lt ) } if (pattern == "grid") { rect( xleft = xl, ybottom = yb, xright = xr, ytop = yt, border = bor, col = cl, density = den, angle = 0, lwd = lw, lty = lt ) rect( xleft = xl, ybottom = yb, xright = xr, ytop = yt, border = bor, col = cl, density = den, angle = 90, lwd = lw, lty = lt ) } if (pattern == "forward") { rect( xleft = xl, ybottom = yb, xright = xr, ytop = yt, border = bor, col = cl, density = den, angle = 45, lwd = lw, lty = lt ) } if (pattern == "backward") { rect( xleft = xl, ybottom = yb, xright = xr, ytop = yt, border = bor, col = cl, density = den, angle = 315, lwd = lw, lty = lt ) } if (pattern == "vertical") { rect( xleft = xl, ybottom = yb, xright = xr, ytop = yt, border = bor, col = cl, density = den, angle = 90, lwd = lw, lty = lt ) } if (pattern == "horizontal") { rect( xleft = xl, ybottom = yb, xright = xr, ytop = yt, border = bor, col = cl, density = den, angle = 0, lwd = lw, lty = lt ) } } } # author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on aug-3-2017 (MAS) specprop_wrblr_int <- function(spec, f = NULL, flim = NULL, ...) { fhz <- f if (is.null(f)) { if (is.vector(spec)) { stop2("'f' is missing") } else if (is.matrix(spec)) { f <- spec[nrow(spec), 1] * 2000 * nrow(spec) / (nrow(spec) - 1) } } if (is.matrix(spec)) { freq <- spec[, 1] freq <- freq * 1000 spec <- spec[, 2] } L <- length(spec) wl <- L * 2 if (any(spec < 0)) { stop2("The frequency spectrum to be analysed should not be in dB") } if (!is.null(flim)) { if (flim[1] < 0 || flim[2] > fhz / 2) { stop2("'flim' should range between 0 and f/2") } } else { flim <- c(0, (f / 2 - f / wl) / 1000) } g <- (1000 * wl / 2) / (f / 2 - f / wl) spec <- spec[(flim[1] * g):(flim[2] * g)] spec <- spec[!is.na(spec)] L <- length(spec) amp <- spec / sum(spec) cumamp <- cumsum(amp) freq <- seq( from = flim[1] * 1000, to = flim[2] * 1000, length.out = L ) mean <- sum(amp * freq) sd <- sqrt(sum(amp * ((freq - mean)^2))) sem <- sd / sqrt(L) median <- freq[length(cumamp[cumamp <= 0.5]) + 1] mode <- freq[which.max(amp)] Q25 <- freq[length(cumamp[cumamp <= 0.25]) + 1] Q75 <- freq[length(cumamp[cumamp <= 0.75]) + 1] IQR <- Q75 - Q25 cent <- sum(freq * amp) z <- amp - mean(amp) w <- sd(amp) skew <- (sum(z^3) / (L - 1)) / w^3 kurt <- (sum(z^4) / (L - 1)) / w^4 sfm <- sfm(amp) sh <- sh(amp) prec <- f / wl results <- list( mean = mean, sd = sd, median = median, sem = sem, mode = mode, Q25 = Q25, Q75 = Q75, IQR = IQR, cent = cent, skewness = skew, kurtosis = kurt, sfm = sfm, sh = sh, prec = prec ) return(results) } # internal warbleR function, not to be called by users. It is a modified version of seewave::spectro # that allows to plot spectrograms using image() which substantially increases speed (although makes some options unavailable) # there is also a soscillo function (soscillo_wrblr_int) down below copied from seewave v2.0.5 (later versions give problems with oscillogram in spectrogram apparently due to fastdisp) # last modification on feb-09-2018 (MAS) spectro_wrblr_int <- function(wave, f, wl = 512, wn = "hanning", zp = 0, ovlp = 0, fast.spec = FALSE, complex = FALSE, norm = TRUE, correction = "none", fftw = FALSE, dB = "max0", dBref = NULL, plot = TRUE, flog = FALSE, grid = TRUE, osc = FALSE, scale = TRUE, cont = FALSE, collevels = NULL, palette = spectro.colors, contlevels = NULL, colcont = "black", colbg = "white", colgrid = "black", colaxis = "black", collab = "black", cexlab = 1, cexaxis = 1, tlab = "Time (s)", flab = "Frequency (kHz)", alab = "Amplitude", scalelab = "Amplitude\n(dB)", main = NULL, scalefontlab = 1, scalecexlab = 0.75, axisX = TRUE, axisY = TRUE, tlim = NULL, trel = TRUE, flim = NULL, flimd = NULL, widths = c(6, 1), heights = c(3, 1), oma = rep(0, 4), rnd = NULL, rm.lwst = FALSE, colwave = adjustcolor("#07889B", alpha.f = 0.7), box = TRUE, ...) { if (wl >= length(wave@left)) { wl <- length(wave@left) - 1 } if (wl %% 2 != 0) { wl <- wl - 1 } # remove scale if fast.spec if (fast.spec) { scale <- FALSE } if (!is.null(dB) && all(dB != c("max0", "A", "B", "C", "D"))) { stop2("'dB' has to be one of the following character strings: 'max0', 'A', 'B', 'C' or 'D'") } if (complex) { if (plot) { plot <- FALSE warning2("\n'plot' was turned to 'FALSE'") } if (norm) { norm <- FALSE warning2("\n'norm' was turned to 'FALSE'") } if (!is.null(dB)) { dB <- NULL warning2("\n'dB' was turned to 'NULL'") } } input <- inputw(wave = wave, f = [email protected]) if (!is.null(tlim) && trel && osc) { wave <- wave0 <- input$w } else { wave <- input$w } f <- input$f rm(input) if (!is.null(tlim)) { wave <- cutw(wave, f = f, from = tlim[1], to = tlim[2] ) } if (!is.null(flimd)) { mag <- round((f / 2000) / (flimd[2] - flimd[1])) wl <- wl * mag if (ovlp == 0) { ovlp <- 100 } ovlp <- 100 - round(ovlp / mag) flim <- flimd } n <- nrow(wave) step <- seq(1, n - wl, wl - (ovlp * wl / 100)) # to fix function name change in version 2.0.5 # if (exists("stdft")) stft <- stdft z <- stft_wrblr_int( wave = wave, f = f, wl = wl, zp = zp, step = step, wn = wn, fftw = fftw, scale = norm, complex = complex, correction = correction ) if (!is.null(tlim) && trel) { X <- seq(tlim[1], tlim[2], length.out = length(step)) } else { X <- seq(0, n / f, length.out = length(step)) } pl <- pretty(X) if (any(pl < 0)) { pl <- pl + abs(min(pl)) } xat <- xlabel <- pl if (!is.null(rnd)) { xlabel <- round(xlabel, rnd) } if (is.null(flim)) { Y <- seq(0, (f / 2) - (f / (wl + zp)), by = f / (wl + zp)) / 1000 } else { fl1 <- flim[1] * nrow(z) * 2000 / f fl2 <- flim[2] * nrow(z) * 2000 / f z <- z[(fl1:fl2) + 1, , drop = FALSE] Y <- seq(flim[1], flim[2], length.out = nrow(z)) } yat <- ylabel <- pretty(Y) if (rm.lwst) { ylabel[1] <- "" } if (flog) { Y <- log(Y + 1) yat <- log(yat + 1) } if (!is.null(dB)) { if (is.null(dBref)) { z <- 20 * log10(z) } else { z <- 20 * log10(z / dBref) } if (dB != "max0") { if (dB == "A") { z <- dBweight(Y * 1000, dBref = z)$A } if (dB == "B") { z <- dBweight(Y * 1000, dBref = z)$B } if (dB == "C") { z <- dBweight(Y * 1000, dBref = z)$C } if (dB == "D") { z <- dBweight(Y * 1000, dBref = z)$D } } } Z <- t(z) # fix when no amplitude variation is found i wave if (all(is.nan(Z))) { Z[, ] <- -Inf } if (plot) { if (!isTRUE(norm) && isTRUE(scale)) { stop2("dB colour scale cannot be plot when 'norm' is FALSE") } suppressWarnings(maxz <- round(max(z, na.rm = TRUE))) if (!is.null(dB)) { if (is.null(collevels)) { collevels <- seq(maxz - 30, maxz, by = 1) } if (is.null(contlevels) & cont) { contlevels <- seq(maxz - 30, maxz, by = 10) } } else { if (is.null(collevels)) { collevels <- seq(0, maxz, length = 30) } if (is.null(contlevels) & cont) { contlevels <- seq(0, maxz, length = 3) } } suppressWarnings(Zlim <- range(Z, finite = TRUE, na.rm = TRUE)) if (osc & scale) { layout(matrix(c(3, 1, 2, 0), ncol = 2, byrow = TRUE), widths = widths, heights = heights ) par( las = 0, oma = oma, col = "white", col = colaxis, col.lab = collab, cex.lab = cexlab, cex.axis = cexaxis, bg = colbg ) par(mar = c(0, 1, 4.5, 3)) seewave::dBscale( collevels = collevels, palette = palette, fontlab = scalefontlab, cexlab = scalecexlab, collab = collab, textlab = scalelab, colaxis = colaxis ) par(mar = c(5, 4.1, 0, 0)) if (!is.null(tlim) && trel) { wave <- wave0 from <- tlim[1] to <- tlim[2] } else { from <- FALSE to <- FALSE } soscillo_wrblr_int( wave = wave, f = f, bty = "u", from = from, to = to, collab = collab, colaxis = colaxis, colline = colaxis, ylim = c( -max(abs(wave)), max(abs(wave)) ), tickup = max(abs(wave), na.rm = TRUE), tlab = tlab, alab = alab, cexlab = cexlab, cexaxis = cexaxis, xaxt = { if (!axisX) { "n" } }, ... ) par( mar = c(0, 4.1, 1, 0), las = 1, cex.lab = cexlab + 0.2 ) if (!fast.spec) { seewave::filled.contour.modif2( x = X, y = Y, z = Z, levels = collevels, nlevels = 20, plot.title = title( main = main, xlab = "", ylab = flab ), plot.axes = { if (axisY) { axis(2, at = yat, labels = ylabel) } else { NULL } }, color.palette = palette ) } else { image( x = X, y = Y, z = Z, col = palette(30), xlab = tlab, ylab = flab ) title(main) } if (grid) { abline( h = yat, col = colgrid, lty = "dotted" ) } if (cont) { contour( X, Y, Z, add = TRUE, levels = contlevels, nlevels = 5, col = colcont, ... ) } if (colaxis != colgrid) { abline(h = 0, col = colaxis) } else { abline(h = 0, col = colgrid) } } if (osc == FALSE & scale) { layout(matrix(c(2, 1), ncol = 2, byrow = TRUE), widths = widths ) par( mar = c(5, 1, 4.5, 3), oma = oma, las = 0, bg = colbg ) seewave::dBscale( collevels = collevels, palette = palette, fontlab = scalefontlab, cexlab = scalecexlab, collab = collab, textlab = scalelab, colaxis = colaxis ) par( mar = c(5, 4.1, 1, 0), las = 1, cex = 1, col = colaxis, col.axis = colaxis, col.lab = collab, bg = colbg, cex.lab = cexlab + 0.2 ) if (!fast.spec) { filled_contour_wrblr_int( x = X, y = Y, z = Z, levels = collevels, nlevels = 20, plot.title = title( main = main, xlab = tlab, ylab = flab ), plot.axes = { if (axisX) { axis(1, at = xat, labels = xlabel) } if (axisY) { axis(2, at = yat, labels = ylabel) } }, color.palette = palette, bx = box ) } else { image( x = X, y = Y, z = Z, col = palette(30), xlab = tlab, ylab = flab ) title(main) } if (grid) { abline( h = yat, col = colgrid, lty = "dotted" ) } if (colaxis != colgrid) { abline(h = 0, col = colaxis) } else { abline(h = 0, col = colgrid) } if (cont) { contour( X, Y, Z, add = TRUE, levels = contlevels, nlevels = 5, col = colcont, ... ) } } if (osc & scale == FALSE) { layout(matrix(c(2, 1), nrow = 2, byrow = TRUE), heights = heights ) par( mar = c(5.1, 4.1, 0, 2.1), las = 0, oma = oma, bg = colbg ) if (!is.null(tlim) && trel) { wave <- wave0 from <- tlim[1] to <- tlim[2] } else { from <- FALSE to <- FALSE } soscillo_wrblr_int( wave = wave, f = f, bty = "u", from = from, to = to, collab = collab, colaxis = colaxis, colline = colaxis, tickup = max(abs(wave), na.rm = TRUE), ylim = c(-max(abs(wave)), max(abs(wave))), tlab = tlab, alab = alab, cexlab = cexlab, cexaxis = cexaxis, colwave = colwave, xaxt = { if (!axisX) { "n" } }, ... ) par( mar = c(0, 4.1, 2.1, 2.1), las = 1, cex.lab = cexlab ) if (!fast.spec) { filled_contour_wrblr_int( x = X, y = Y, z = Z, levels = collevels, nlevels = 20, plot.title = title( main = main, xlab = "", ylab = flab ), color.palette = palette, plot.axes = { if (axisY) { axis(2, at = yat, labels = ylabel) } else { NULL } }, col.lab = collab, colaxis = colaxis, bx = box, ... ) } else { image( x = X, y = Y, z = Z, col = palette(30), xlab = tlab, ylab = flab, axes = FALSE ) if (axisY) { axis(2, at = yat, labels = ylabel) } if (box) { box() } if (!is.null(main)) { title(main) } } if (grid) { abline( h = yat, col = colgrid, lty = "dotted" ) } if (cont) { contour( X, Y, Z, add = TRUE, levels = contlevels, nlevels = 5, col = colcont, ... ) } if (colaxis != colgrid) { abline(h = 0, col = colaxis) } else { abline(h = 0, col = colgrid) } } if (osc == FALSE & scale == FALSE) { par( las = 1, col = colaxis, col.axis = colaxis, col.lab = collab, bg = colbg, cex.axis = cexaxis, cex.lab = cexlab ) if (!fast.spec) { filled_contour_wrblr_int( x = X, y = Y, z = Z, levels = collevels, nlevels = 20, plot.title = title( main = main, xlab = tlab, ylab = flab ), plot.axes = { if (axisX) { axis(1, at = xat, labels = xlabel) } if (axisY) { axis(2, at = yat, labels = ylabel) } }, color.palette = palette, col.lab = collab, colaxis = colaxis, bx = box ) } else { image( x = X, y = Y, z = Z, col = palette(30), xlab = tlab, ylab = flab ) title(main) } if (grid) { abline( h = yat, col = colgrid, lty = "dotted" ) } if (cont) { contour( X, Y, Z, add = TRUE, levels = contlevels, nlevels = 5, col = colcont, ... ) } if (colaxis != colgrid) { abline(h = 0, col = colaxis) } else { abline(h = 0, col = colgrid) } } invisible(list( time = X, freq = Y, amp = z )) } else { return(list( time = X, freq = Y, amp = z )) } } soscillo_wrblr_int <- function(wave, f, from = FALSE, to = FALSE, colwave = "black", coltitle = "black", collab = "black", colline = "black", colaxis = "black", cexaxis = 1, coly0 = "grey47", tlab = "Times (s)", alab = "Amplitude", cexlab = 1, fontlab = 1, title = FALSE, xaxt = "s", yaxt = "n", tickup = NULL, ...) { input <- inputw(wave = wave, f = f) wave <- input$w f <- input$f rm(input) if (from | to) { if (from == 0) { a <- 1 b <- round(to * f) } if (from == FALSE) { a <- 1 b <- round(to * f) from <- 0 } if (to == FALSE) { a <- round(from * f) b <- nrow(wave) to <- nrow(wave) / f } else { a <- round(from * f) b <- round(to * f) } wave <- as.matrix(wave[a:b, ]) n <- nrow(wave) } else { n <- nrow(wave) from <- 0 to <- n / f } par( tcl = 0.5, col.axis = colaxis, cex.axis = cexaxis, col = colline, col.lab = collab, las = 0 ) wave <- ts(wave[0:n, ], start = from, end = to, frequency = f ) plot( wave, col = colwave, type = "l", xaxs = "i", yaxs = "i", xlab = "", ylab = "", xaxt = xaxt, yaxt = yaxt, bty = "l", ... ) axis( side = 1, col = colline, labels = FALSE ) axis( side = 2, at = tickup, col = colline, labels = FALSE ) mtext( tlab, col = collab, font = fontlab, cex = cexlab, side = 1, line = 3 ) mtext( alab, col = collab, font = fontlab, cex = cexlab, side = 2, line = 3 ) abline(h = 0, col = coly0, lty = 2) } # internal warbleR function, not to be called by users. It is a modified version of seewave::spectro # that allows to plot spectrograms without resetting the graphic device, which is useful for multipannel figures. It also allow using image() # which substantially increases speed (although makes some options unavailable) # last modification on feb-27-2019 (MAS) spectro_wrblr_int2 <- function(wave, f, wl = 512, wn = "hanning", zp = 0, ovlp = 0, complex = FALSE, norm = TRUE, fftw = FALSE, dB = "max0", dBref = NULL, plot = TRUE, grid = TRUE, cont = FALSE, collevels = NULL, palette = spectro.colors, contlevels = NULL, colcont = "black", colbg = "white", colgrid = "gray", colaxis = "black", collab = "black", cexlab = 1, cexaxis = 1, tlab = "Time (s)", flab = "Frequency (kHz)", alab = "Amplitude", scalelab = "Amplitude\n(dB)", main = NULL, scalefontlab = 1, scalecexlab = 0.75, axisX = TRUE, axisY = TRUE, tlim = NULL, trel = TRUE, flim = NULL, flimd = NULL, widths = c(6, 1), heights = c(3, 1), oma = rep(0, 4), listen = FALSE, fast.spec = FALSE, rm.zero = FALSE, amp.cutoff = NULL, X = NULL, palette.2 = reverse.topo.colors, bx = TRUE, add = FALSE, collev.min = NULL) { if (!is.null(dB) && all(dB != c("max0", "A", "B", "C", "D"))) { stop2("'dB' has to be one of the following character strings: 'max0', 'A', 'B', 'C' or 'D'") } sel.tab <- X if (is.list(palette)) { palette <- unlist(palette[[1]]) } if (is.null(palette)) { palette <- spectro.colors } if (!is.function(palette)) { palette <- get(palette) } if (is.null(collevels) & !is.null(collev.min)) { collevels <- seq(collev.min, 0, 1) } if (!is.null(sel.tab)) { fast.spec <- TRUE } if (complex & norm) { norm <- FALSE warning2("\n'norm' was turned to 'FALSE'") } if (complex & !is.null(dB)) { dB <- NULL warning2("\n'dB' was turned to 'NULL'") } input <- seewave::inputw(wave = wave, f = f) wave <- input$w f <- input$f rm(input) if (!is.null(tlim)) { wave <- cutw(wave, f = f, from = tlim[1], to = tlim[2] ) } if (!is.null(flimd)) { mag <- round((floor(f / 2000)) / (flimd[2] - flimd[1])) wl <- wl * mag if (ovlp == 0) { ovlp <- 100 } ovlp <- 100 - round(ovlp / mag) flim <- flimd } n <- nrow(wave) step <- seq(1, n - wl, wl - (ovlp * wl / 100)) # to fix function name change in after version 2.0.5 # if (exists("stdft")) stft <- stdft z <- stft_wrblr_int( wave = wave, f = f, wl = wl, zp = zp, step = step, wn = wn, fftw = fftw, scale = norm, complex = complex ) if (!is.null(tlim) && trel) { X <- seq(tlim[1], tlim[2], length.out = length(step)) } else { X <- seq(0, n / f, length.out = length(step)) } if (is.null(flim)) { Y <- seq(0, (f / 2) - (f / wl), length.out = nrow(z)) / 1000 } else { fl1 <- flim[1] * nrow(z) * 2000 / f fl2 <- flim[2] * nrow(z) * 2000 / f z <- z[(fl1:fl2) + 1, ] Y <- seq(flim[1], flim[2], length.out = nrow(z)) } if (!is.null(dB)) { if (is.null(dBref)) { z <- 20 * log10(z) } else { z <- 20 * log10(z / dBref) } if (dB != "max0") { if (dB == "A") { z <- dBweight(Y * 1000, dBref = z)$A } if (dB == "B") { z <- dBweight(Y * 1000, dBref = z)$B } if (dB == "C") { z <- dBweight(Y * 1000, dBref = z)$C } if (dB == "D") { z <- dBweight(Y * 1000, dBref = z)$D } } } Z <- t(z) maxz <- round(max(z, na.rm = TRUE)) if (!is.null(dB)) { if (is.null(collevels)) { collevels <- seq(maxz - 30, maxz, by = 1) } if (is.null(contlevels)) { contlevels <- seq(maxz - 30, maxz, by = 10) } } else { if (is.null(collevels)) { collevels <- seq(0, maxz, length = 30) } if (is.null(contlevels)) { contlevels <- seq(0, maxz, length = 3) } } Zlim <- range(Z, finite = TRUE, na.rm = TRUE) if (!is.null(amp.cutoff)) { Z[Z >= (diff(range(Z)) * amp.cutoff) + min(Z)] <- 0 } if (!fast.spec) { filled_contour_wrblr_int( x = X, y = Y, z = Z, bg.col = colbg, levels = collevels, nlevels = 20, plot.title = title( main = main, xlab = tlab, ylab = flab ), color.palette = palette, axisX = FALSE, axisY = axisY, col.lab = collab, colaxis = colaxis, add = add ) } else { image( x = X, y = Y, z = Z, col = palette(30), xlab = tlab, ylab = flab, axes = FALSE ) if (!is.null(sel.tab)) { out <- lapply(1:nrow(sel.tab), function(i) { image( x = X[X > sel.tab$start[i] & X < sel.tab$end[i]], y = Y[Y > sel.tab$bottom.freq[i] & Y < sel.tab$top.freq[i]], z = Z[X > sel.tab$start[i] & X < sel.tab$end[i], Y > sel.tab$bottom.freq[i] & Y < sel.tab$top.freq[i]], col = palette.2(30), xlab = tlab, ylab = flab, axes = FALSE, xlim = range(X), add = TRUE ) }) } if (axisY) { axis(2, at = pretty(Y), labels = pretty(Y), cex.axis = cexlab ) } if (bx) { box() } if (!is.null(main)) { title(main) } } if (axisX) { if (rm.zero) { axis(1, at = pretty(X)[-1], labels = pretty(X)[-1], cex.axis = cexaxis ) } else { axis(1, at = pretty(X), labels = pretty(X), cex.axis = cexaxis ) } } if (grid) { grid(nx = NA, ny = NULL, col = colgrid) } } # internal warbleR function, not to be called by users. It is a modified version of seewave::stft # last modification on feb-09-2018 (MAS) stft_wrblr_int <- function(wave, f, wl, zp, step, wn, scale = TRUE, norm = FALSE, correction = "none", fftw = FALSE, complex = FALSE) { if (zp < 0) { stop2("zero-padding cannot be negative") } W <- ftwindow( wl = wl, wn = wn, correction = correction ) if (fftw) { p <- fftw::planFFT(wl + zp) z <- apply(as.matrix(step), 1, function(x) { fftw::FFT(c(wave[x:(wl + x - 1), ] * W, rep(0, zp)), plan = p) }) } else { z <- apply(as.matrix(step), 1, function(x) { stats::fft(c(wave[x:(wl + x - 1), ] * W, rep(0, zp))) }) } z <- z[1:((wl + zp) %/% 2), , drop = FALSE] z <- z / (wl + zp) if (complex == FALSE) { z <- 2 * Mod(z) if (scale) { if (norm) { z <- z / apply( X = z, MARGIN = 2, FUN = max ) } else { z <- z / max(z) } } } return(z) } # internal warbleR function, not to be called by users. it calculates descriptors of wavelet packet decompositions # based on A. Selin, J. Turunen, and J. T. Tanttu, "Wavelets in recognition of bird sounds" EURASIP Journal on Advances in Signal Pro- cessing, vol. 2007, Article ID 51806, 9 pages, 2007. # @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on oct-7-2019 (MAS) wpd_feature_wrblr_int <- function(wave, normalize = FALSE, thr1 = 6, thr2 = 0.5) { # force wave object to have a length exp2 # get target duration exp2 <- `^`(2, 1:1000) # target duration trg <- exp2[which.min(!exp2 > length(wave@left))] # margin to add at both sides mar <- rep(0, (trg - length(wave@left)) / 2) # amplitude vector amp.vctr <- c(mar, wave@left, mar) # fix if still not exp2 if (length(amp.vctr) < trg) { amp.vctr <- c(amp.vctr, trg - length(amp.vctr)) } # compute wavelet packet decomposition out <- wavethresh::wp(amp.vctr, filter.number = 4) # coefficients mat <- out$wp bins <- dim(mat)[2] num_wpd_coefs <- dim(mat)[1] # sum of mean of Eb for each bin arr_meanEb <- sapply(1:bins, function(e) { sum(sapply(1:num_wpd_coefs, function(i) { mat[i, e]^2 })) / num_wpd_coefs }) # find max E and position of max E mx <- max(arr_meanEb) # max ps <- which.max(arr_meanEb) # position # spread # s <- Spread(mat, bins, num_wpd_coefs) sprds <- sapply(1:bins, function(w) { # caculate threshold as in equation 6 umbral <- (sum(sapply(1:num_wpd_coefs, function(i) { mat[i, w]^2 })) / num_wpd_coefs) / thr1 value <- mat[, w]^2 j <- rep(1, length(value)) # make lower values 0 j[value <= umbral] <- 0 # convert to NA the one lower than value value[value <= umbral] <- NA return(c(sum(value, na.rm = TRUE) / sum(j))) }) s <- colSums(t(sprds)) # measure spread sprd <- s[1] / s[2] # add up square coefs by bin sum.coefs <- sapply(1:bins, function(e) { sum(sapply(1:num_wpd_coefs, function(i) { mat[i, e]^2 })) }) # force to a range 0-1 (proportional to maximum) sum.coefs <- sum.coefs / max(sum.coefs) # get the ones above threshold w <- sum(sum.coefs > thr2) # w <- sum(sapply(1:bins, function(e){ # if(sum(sapply(1:num_wpd_coefs, function(i) mat[i, e]^2)) > thr) return(1) else return(0) # })) result <- c(mx, ps, sprd, w) if (normalize) { count <- sum(mat[, result[2]] > (sum( sapply(1:num_wpd_coefs, function(i) { mat[i, w]^2 }) ) / num_wpd_coefs) / 6) if (count > 0) { result[1] <- result[1] / count } result <- result * c(1, 1 / 16, 1 / 100, 1 / 20) } names(result) <- c("max.energy", "position", "spread", "width") return(result) } # stop function that doesn't print call stop2 <- function(...) { stop(..., call. = FALSE) } # warning function that doesn't print call warning2 <- function(...) { warning(..., call. = FALSE) } # message function that changes colors message2 <- function(x, color = "black") { message(colortext(x, as = color)) } colortext <- function(text, as = c("red", "blue", "green", "magenta", "cyan", "orange", "black", "silver")) { if (has_color()) { unclass(cli::make_ansi_style(warbleR_style(as))(text)) } else { text } } has_color <- function() { cli::num_ansi_colors() > 1 } warbleR_style <- function(color = c("red", "blue", "green", "magenta", "cyan", "orange", "black", "silver")) { type <- match.arg(color) c( red = "red", blue = "blue", green = "green", magenta = "magenta", cyan = "cyan", orange = "orange", black = "black", silver = "silver" )[[color]] } ## internal function to subtract SPL from background noise # signal = signal SPL # noise = noise SPL lessdB <- lessdB_wrblr_int <- function(signal.noise, noise) { puttative_SPLs <- seq(0.01, signal.noise, by = 0.01) sum_SPLs <- 20 * log10((10^(puttative_SPLs / 20)) + (10^(noise / 20))) signal_SPL <- puttative_SPLs[which.min(abs(sum_SPLs - signal.noise))] return(signal_SPL) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/internal_functions.R
#' Example data frame of selections (i.e. selection table). #' #' A data frame containing the start, end, low and high frequency of #' \emph{Phaethornis longirostris} (Long-billed Hermit) songs from the #' example sound files included in this package. Same data than 'selec_table'. #' 'selec_table' will be removed in future package version. #' #' @format A data frame with 11 rows and 7 variables: \describe{ #' \item{sound.files}{recording names} #' \item{channel}{channel in which signal is found} #' \item{selec}{selection numbers within recording} #' \item{start}{start times of selected signal} #' \item{end}{end times of selected signal} #' \item{bottom.freq}{lower limit of frequency range} #' \item{top.freq}{upper limit of frequency range} #' } #' #' @usage data(lbh_selec_table) #' #' @source Marcelo Araya-Salas, warbleR #' #' @description \code{lbh_selec_table} alternative name for \code{selec.table}. \code{selec.table} will be deprecated in #' future versions. #' "lbh_selec_table"
/scratch/gouwar.j/cran-all/cranData/warbleR/R/lbh_selec_table-data.R
#' Example data frame of selections (i.e. selection table). #' #' A data frame containing the start, end, low and high frequency of #' \emph{Phaethornis longirostris} (Long-billed Hermit) songs from the #' example sound files included in this package. Similar than 'lbh_selec_table'. #' but it contains only 2 selections. #' #' @format A data frame with 2 rows and 7 variables: \describe{ #' \item{sound.files}{recording names} #' \item{channel}{channel in which signal is found} #' \item{selec}{selection numbers within recording} #' \item{start}{start times of selected signal} #' \item{end}{end times of selected signal} #' \item{bottom.freq}{lower limit of frequency range} #' \item{top.freq}{upper limit of frequency range} #' } #' #' @usage data(lbh_selec_table2) #' #' @source Marcelo Araya-Salas, warbleR #' #' @description \code{lbh_selec_table2} is a data frame containing the start, end, low and high frequency of 2 selections. Mostly to be used as an example in \code{\link{find_peaks}}. #' "lbh_selec_table2"
/scratch/gouwar.j/cran-all/cranData/warbleR/R/lbh_selec_table2-data.R
#' Calculate descriptive statistics on Mel-frequency cepstral coefficients #' #' \code{mfcc_stats} calculates descriptive statistics on Mel-frequency cepstral coefficients and its derivatives. #' @usage mfcc_stats(X, ovlp = 50, wl = 512, bp = 'frange', path = NULL, numcep = 25, #' nbands = 40, parallel = 1, pb = TRUE, ...) #' @param X 'selection_table', 'extended_selection_table' or data frame with the following columns: 1) "sound.files": name of the sound #' files, 2) "sel": number of the selections, 3) "start": start time of selections, 4) "end": #' end time of selections. The output of \code{\link{auto_detec}} can #' be used as the input data frame. #' @param ovlp Numeric vector of length 1 specifying \% of overlap between two #' consecutive windows. Internally this is used to set the 'hoptime' argument in \code{\link[tuneR]{melfcc}}. Default is 50. #' @param wl A numeric vector of length 1 specifying the spectrogram window length. Default is 512. See 'wl.freq' for setting windows length independently in the frequency domain. #' @param bp A numeric vector of length 2 for the lower and upper limits of a #' frequency bandpass filter (in kHz) or "frange" (default) to indicate that values in minimum of 'bottom.freq' #' and maximum of 'top.freq' columns will be used as bandpass limits. #' @param path Character string containing the directory path where the sound files are located. #' @param numcep Numeric vector of length 1 controlling the number of cepstra to #' return (see \code{\link[tuneR]{melfcc}}). #' @param nbands Numeric vector of length 1 controlling the number of warped spectral bands to use (see \code{\link[tuneR]{melfcc}}). Default is 40. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param pb Logical argument to control progress bar and messages. Default is \code{TRUE}. #' @param ... Additional parameters to be passed to \code{\link[tuneR]{melfcc}}. #' @return A data frame containing the descriptive statistics for each of the Mel-frequency #' cepstral coefficients (set by 'numcep' argument). See details. #' @export #' @name mfcc_stats #' @details The function calculates descriptive statistics on Mel-frequency cepstral coefficients (MFCCs) for each of the signals (rows) in a selection #' data frame. The descriptive statistics are: minimum, maximum, mean, median, skewness, kurtosis and #' variance. #' It also returns the mean and variance for the first and second derivatives of the coefficients. These parameters are commonly used in acoustic signal processing and detection (e.g. Salamon et al 2014). #' @seealso \code{\link{fix_wavs}}, \code{\link{remove_silence}}, \code{\link{spectro_analysis}} #' @examples{ #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' #' # run function #' mel_st <- mfcc_stats(X = lbh_selec_table, pb = FALSE, path = tempdir()) #' #' head(mel_st) #' #' # measure 12 coefficients #' mel_st12 <- mfcc_stats(X = lbh_selec_table, numcep = 12, pb = FALSE, path = tempdir()) #' #' head(mel_st) #' } #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' #' Lyon, R. H., & Ordubadi, A. (1982). Use of cepstra in acoustical signal analysis. Journal of Mechanical Design, 104(2), 303-306. #' #' Salamon, J., Jacoby, C., & Bello, J. P. (2014). A dataset and taxonomy for urban sound research. In Proceedings of the 22nd ACM international conference on Multimedia. 1041-1044. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on Jul-30-2018 (MAS) mfcc_stats <- function(X, ovlp = 50, wl = 512, bp = "frange", path = NULL, numcep = 25, nbands = 40, parallel = 1, pb = TRUE, ...) { # error message if wavethresh is not installed if (!requireNamespace("Sim.DiffProc", quietly = TRUE)) { stop2("must install 'Sim.DiffProc' to use this function") } #### set arguments from options # get function arguments argms <- methods::formalArgs(mfcc_stats) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X))) stop2("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") if (!all(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))) { stop2(paste(paste(c("sound.files", "selec", "start", "end")[!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop2("NAs found in start and/or end") # if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) stop2("'start' and 'end' must be numeric") # if any start higher than end stop if (any(X$end - X$start <= 0)) stop2(paste("Start is higher than or equal to end in", length(which(X$end - X$start <= 0)), "case(s)")) # if any selections longer than 20 secs warning if (any(X$end - X$start > 20)) warning2(paste(length(which(X$end - X$start > 20)), "selection(s) longer than 20 sec")) # bp checking if (bp[1] != "frange") { if (!is.vector(bp)) { stop2("'bp' must be a numeric vector of length 2 or 'frange'") } else { if (!length(bp) == 2) stop2("'bp' must be a numeric vector of length 2 or 'frange'") } } else { if (!any(names(X) == "bottom.freq") & !any(names(X) == "top.freq")) stop2("'bp' = 'frange' requires bottom.freq and top.freq columns in X") if (any(is.na(c(X$bottom.freq, X$top.freq)))) stop2("NAs found in bottom.freq and/or top.freq") if (any(c(X$bottom.freq, X$top.freq) < 0)) stop2("Negative values found in bottom.freq and/or top.freq") if (any(X$top.freq - X$bottom.freq < 0)) stop2("top.freq should be higher than bottom.freq") bp <- c(min(X$bottom.freq), max(X$top.freq)) } if (!is_extended_selection_table(X)) { # return warning if not all sound files were found fs <- list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE) if (length(unique(X$sound.files[(X$sound.files %in% fs)])) != length(unique(X$sound.files))) { warning2(x = paste( length(unique(X$sound.files)) - length(unique(X$sound.files[(X$sound.files %in% fs)])), "sound files file(s) not found" )) } # count number of sound files in working directory and if 0 stop d <- which(X$sound.files %in% fs) if (length(d) == 0) { stop2("The sound files are not in the working directory") } else { X <- X[d, ] } } # If parallel is not numeric if (!is.numeric(parallel)) stop2("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop2("'parallel' should be a positive integer") mfcc_FUN <- function(i, X, bp, wl, numcep, nbands) { # read wave file r <- warbleR::read_sound_file(X = X, path = path, index = i) # set bandpass if (!is.null(bp)) { if (bp[1] == "frange") bp <- c(X$bottom.freq[i], X$top.freq[i]) } b <- bp # in case bp its higher than can be due to sampling rate if (b[2] > floor([email protected] / 2000)) b[2] <- floor([email protected] / 2000) # add a bit above and below to ensure range limits are included bpfr <- b bpfr <- bpfr + c(-0.2, 0.2) if (bpfr[1] < 0) bpfr[1] <- 0 if (bpfr[2] > floor([email protected] / 2000)) bpfr[2] <- floor([email protected] / 2000) # measure MFCCs m <- try(melfcc(r, wintime = wl / [email protected], hoptime = wl / [email protected] * (1 - (ovlp / 100)), numcep = numcep, nbands = nbands, minfreq = bpfr[1] * 1000, maxfreq = bpfr[2] * 1000, ... ), silent = TRUE) clm.nms <- paste(rep(c("min", "max", "median", "mean", "var", "skew", "kurt"), each = numcep), paste0("cc", 1:numcep), sep = ".") # if cepstral coefs were calculated if (!is(m, "try-error")) { # put them in a data frame outdf <- data.frame(t(c( apply(m, 2, min), apply(m, 2, max), apply(m, 2, stats::median), apply(m, 2, mean), apply(m, 2, stats::var), apply(m, 2, Sim.DiffProc::skewness), apply(m, 2, Sim.DiffProc::kurtosis) )), stringsAsFactors = FALSE) # name columns names(outdf) <- clm.nms # measure MFCC first and second derivatives var and mean m2 <- deltas(m) m3 <- deltas(m2) vm.d <- c(mean.d1.cc = mean(c(m2)), var.d1.cc = stats::var(c(m2)), mean.d2.cc = mean(c(m3)), var.d2.cc = stats::var(c(m3))) out.df <- cbind(X[i, c("sound.files", "selec")], outdf, t(vm.d), stringsAsFactors = FALSE) } else { out.df <- data.frame(X[i, c("sound.files", "selec")], t(rep(NA, length(clm.nms) + 4))) names(out.df)[-c(1:2)] <- c(clm.nms, "mean.d1.cc", "var.d1.cc", "mean.d2.cc", "var.d2.cc") } return(out.df) } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function ccs <- pblapply_wrblr_int(pbar = pb, X = 1:nrow(X), cl = cl, FUN = function(i) { mfcc_FUN(i = i, X = X, bp, wl = wl, numcep = numcep, nbands = nbands) }) # put results in a single data frame ccs <- do.call(rbind, ccs) # fix row names row.names(ccs) <- 1:nrow(ccs) # convert to numeric in case there is any non-numeric value # if(anyNA(ccs)){ ccs$sound.files <- X$sound.files ccs$selec <- X$selec ccs[, -c(1, 2)] <- data.frame(apply(ccs[, -c(1, 2)], 2, as.numeric)) # } return(ccs) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/mfcc_stats.R
#' Move/copy image files between directories #' #' \code{move_images} moves/copies image files created by \code{\link{warbleR}} between #' directories (folders). #' @usage move_images(from = NULL, to = NULL, it = "all", cut = TRUE, #' overwrite = FALSE, create.folder = TRUE, folder.name = "image_files", #' parallel = 1, pb = TRUE) #' @param from Directory path where image files to be copied are found. #' If \code{NULL} (default) then the current working directory is used. #' @param to Directory path where image files will be copied to. #' @param it A character vector of length 1 giving the image type to be used. "all", #' "tiff", "jpeg" and "pdf" are admitted ("all" includes all the rest). Default is "all". #' @param cut Logical. Determines if files are removed from the original location after #' being copied (cut) or not (just copied). Default is \code{TRUE}. #' @param overwrite Logical. Determines if files that already exist in the destination directory #' should be overwritten. Default is \code{FALSE}. #' @param create.folder Logical. Determines if files are moved to a new folder (which is named with the #' "folder.name" argument). Ignored if 'to' is provided. Default is \code{TRUE}. #' @param folder.name Character string with the name of the new folder where the files will be #' copied to. Ignored if 'to' is provided. Default is \code{"image_files"}. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @family data manipulation #' @seealso \code{\link{filtersels}} #' @export #' @name move_images #' @details This function aims to simplify the manipulation of the image files generated by many #' of the \code{\link{warbleR}} function. It copies/cuts files between directories. #' @return Image files moved into user-defined folders. #' @examples #' { #' # load data #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' #' # create spectrograms #' spectrograms(lbh_selec_table[1:5, ], path = tempdir(), pb = FALSE) #' #' # create folder to move image files #' dir.create(file.path(tempdir(), "imgs")) #' #' # copy files #' move_images(cut = FALSE, from = tempdir(), to = file.path(tempdir(), "imgs")) #' #' # cut files #' move_images( #' cut = TRUE, from = tempdir(), #' to = file.path(tempdir(), "imgs"), overwrite = TRUE #' ) #' #' # Check this folder #' file.path(tempdir(), "imgs") #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on feb-09-2017 (MAS) move_images <- function(from = NULL, to = NULL, it = "all", cut = TRUE, overwrite = FALSE, create.folder = TRUE, folder.name = "image_files", parallel = 1, pb = TRUE) { if (is.null(from)) from <- getwd() if (is.null(to) & !create.folder) stop2("Either 'to' must be provided or 'create.folder' set to TRUE") if (is.null(to) & create.folder) { to <- file.path(from, folder.name) if (dir.exists(to)) stop2("Directory with folder name provided already exists") dir.create(to) } # Check directory permissions if (file.access(to, 2) == -1) stop2(paste("You don't have permission to copy files into", to)) #### set arguments from options # get function arguments argms <- methods::formalArgs(move_images) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # define what image type will be copied if (it == "all") pattern <- "\\.jpeg$|\\.tiff$|\\.pdf$" if (it == "tiff") pattern <- "\\.tiff$" if (it == "jpeg") pattern <- "\\.jpeg$|\\.jpg$" if (it == "pdf") pattern <- "\\.pdf$" # list images imgs <- list.files(path = from, pattern = pattern, ignore.case = TRUE) if (length(imgs) == 0) { message2(paste("No image files were found in", from)) } else { # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } a <- pblapply_wrblr_int(pbar = pb, X = seq(1, length(imgs), by = 10), cl = cl, FUN = function(x) { if (length(imgs) <= x + 9) y <- length(imgs) else y <- x + 9 file.copy(from = file.path(from, imgs[x:y]), to = file.path(to, imgs[x:y]), overwrite = overwrite) }) a <- unlist(a) # a <- file.copy(from = file.path(from, imgs), to = file.path(to, imgs), overwrite = overwrite) if (all(!a) & !overwrite) message2(paste("All files already existed in", to)) else if (any(!a) & !overwrite) message2(paste("Some files already existed in 'to'", to)) if (cut) unlink(file.path(from, imgs)[a]) } } ############################################################################################################## #' alternative name for \code{\link{move_images}} #' #' @keywords internal #' @details see \code{\link{move_images}} for documentation. \code{\link{move_imgs}} will be deprecated in future versions. #' @export move_imgs <- move_images
/scratch/gouwar.j/cran-all/cranData/warbleR/R/move_images.R
#' Convert .mp3 files to .wav #' #' \code{mp32wav} converts several .mp3 files in working directory to .wav format #' @usage mp32wav(samp.rate = NULL, parallel = 1, path = NULL, #' dest.path = NULL, bit.depth = 16, pb = TRUE, overwrite = FALSE) #' @param samp.rate Sampling rate in kHz at which the .wav files should be written. If not provided the sample rate of the original .mp3 file is used. THIS FEATURE IS CURRENTLY NOT AVAILABLE. However, downsampling can be done after .mp3's have been converted using the \code{\link{fix_wavs}} function (which uses \href{https://sourceforge.net/projects/sox/}{SOX} instead). Default is \code{NULL} (e.g. keep original sampling rate). #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param path Character string containing the directory path where the .mp3 files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param dest.path Character string containing the directory path where the .wav files will be saved. #' If \code{NULL} (default) then the folder containing the sound files will be used. #' @param bit.depth Character string containing the units to be used for amplitude normalization. Check #' \code{\link[tuneR]{normalize}} for details. Default is 16. #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @param overwrite Logical. Control whether a .wav sound file that is already in the working directory should be #' overwritten. #' @return .wav files saved in the working directory with same name as original mp3 files. #' @export #' @details The function will convert all mp3 files in working directory or 'path' supplied to wav format. \href{https://cran.r-project.org/package=bioacoustics}{bioacoustics package} must be installed when changing sampling rates (i.e. if 'samp.rate' is supplied). Note that sound files are normalized using \code{\link[tuneR]{normalize}} so they can be written by \code{\link[tuneR]{writeWave}}. #' @name mp32wav #' @examples #' \dontrun{ #' # download mp3 files from xeno-canto #' query_xc(qword = "Phaethornis aethopygus", download = TRUE, path = tempdir()) #' #' # Convert all files to .wav format #' mp32wav(path = tempdir(), dest.path = tempdir()) #' #' # check this folder!! #' tempdir() #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @details convert all .mp3 files in working directory to .wav format. Function used internally to read .mp3 files (\code{\link[tuneR]{readMP3}}) sometimes crashes. #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) and Grace Smith Vidaurre # last modification on mar-13-2018 (MAS) mp32wav <- function(samp.rate = NULL, parallel = 1, path = NULL, dest.path = NULL, bit.depth = 16, pb = TRUE, overwrite = FALSE) { # error message if bioacoustics is not installed if (!requireNamespace("bioacoustics", quietly = TRUE) & !is.null(samp.rate)) { stop2("must install 'bioacoustics' to use mp32wav() for changing sampling rate") } # error message if sox is not installed sox_installed <- system(paste("which sox", sep = " "), ignore.stderr = TRUE, intern = FALSE, ignore.stdout = TRUE ) if (sox_installed == 1) { stop2("Sox is not installed or is not available in path") } #### set arguments from options # get function arguments argms <- methods::formalArgs(mp32wav) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # check dest.path to working directory if (is.null(dest.path)) { dest.path <- getwd() } else if (!dir.exists(dest.path)) { stop2("'dest.path' provided does not exist") } else { dest.path <- normalizePath(dest.path) } # normalize if (length(bit.depth) > 1) stop2("'bit.depth' should have a single value") bit.depth <- as.character(bit.depth) if (!bit.depth %in% c("1", "8", "16", "24", "32", "64", "0")) stop2('only this "bit.depth" values allowed c("1", "8", "16", "24", "32", "64", "0") \n see ?tuneR::normalize') # if parallel is not numeric if (!is.numeric(parallel)) stop2("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop2("'parallel' should be a positive integer") files <- list.files(path = path, pattern = ".mp3$", ignore.case = TRUE) # list .mp3 files in working directory if (length(files) == 0) stop2("no 'mp3' files in working directory") # exclude the ones that already have a .wav version if (!overwrite) { wavs <- list.files(path = dest.path, pattern = "\\.wav$", ignore.case = TRUE) files <- files[!substr(files, 0, nchar(files) - 4) %in% substr(wavs, 0, nchar(wavs) - 4)] if (length(files) == 0) stop2("all 'mp3' files have been converted") } # function to convert single mp3 mp3_conv_FUN <- function(x, bit.depth) { print(x) # read mp3 wv <- try(tuneR::readMP3(filename = file.path(path, x)), silent = TRUE) # downsample and filter if samp.rate different than mp3 if (is(wv, "Wave") & !is.null(samp.rate)) { if ([email protected] != samp.rate * 1000) { message2("'samp.rate' modification currently not available") # # filter first to avoid aliasing # if ([email protected] > samp.rate * 1000) # wv <- seewave::fir(wave = wv , f = [email protected], from = 0, to = samp.rate * 1000 / 2, bandpass = TRUE, output = "Wave") # # #downsample # wv <- warbleR::resample(wave = wv, to = samp.rate * 1000) } # normalize wv <- tuneR::normalize(object = wv, unit = as.character(bit.depth)) } wv <- try(tuneR::writeWave(extensible = FALSE, object = wv, filename = file.path(dest.path, paste0(substr(x, 0, nchar(x) - 4), ".wav"))), silent = TRUE) return(NULL) } ###### fix_sox_FUN <- function(x) { px <- normalizePath(file.path(path, x)) # name and path of original file cll <- paste0("sox '", px, "' -t wavpcm") if (!is.null(bit.depth)) { cll <- paste(cll, paste("-b", bit.depth)) } cll <- paste0(cll, " '", file.path(dest.path, paste0(substr(x, 0, nchar(x) - 4), ".wav")), "'") if (!is.null(samp.rate)) { cll <- paste(cll, "rate", samp.rate * 1000) } if (!is.null(mono)) { cll <- paste(cll, "remix 1") } if (!is.null(bit.depth)) { cll <- paste(cll, "dither -s") } if (Sys.info()[1] == "Windows") { cll <- gsub("'", "\"", cll) } out <- system(cll, ignore.stdout = FALSE, intern = TRUE) } ###### # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function out_l <- pblapply_wrblr_int(pbar = pb, X = files, cl = cl, FUN = function(i) { # suppressWarnings(mp3_conv_FUN(x = i, bit.depth)) fix_sox_FUN(i) }) # make it a vector out <- unlist(out_l) if (any(sapply(out, function(x) is(x, "try-error")))) { message2(paste("the following file(s) could not be converted:\n", paste(files[sapply(out, function(x) is(x, "try-error"))], collapse = ", "))) message2(paste("\nErrors found: \n", paste(unique(out[sapply(out, function(x) is(x, "try-error"))]), collapse = ", "))) } } ############################################################################################################## #' alternative name for \code{\link{mp32wav}} #' #' @keywords internal #' @details see \code{\link{mp32wav}} for documentation. \code{\link{mp32wav}} will be deprecated in future versions. #' @export mp3_2_wav <- mp32wav
/scratch/gouwar.j/cran-all/cranData/warbleR/R/mp32wav.R
#' A wrapper on \code{\link[dtw]{dtwDist}} for comparing multivariate contours #' #' \code{multi_DTW} is a wrapper on \code{\link[dtw]{dtwDist}} that simplify applying dynamic time warping on multivariate contours. #' @usage multi_DTW(ts.df1 = NULL, ts.df2 = NULL, pb = TRUE, parallel = 1, #' window.type = "none", open.end = FALSE, scale = FALSE, dist.mat = TRUE, ...) #' @param ts.df1 Optional. Data frame with frequency contour time series of signals to be compared. #' @param ts.df2 Optional. Data frame with frequency contour time series of signals to be compared. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). Not available in Windows OS. #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. Note that progress bar is only used #' when parallel = 1. #' @param window.type \code{\link[dtw]{dtw}} windowing control parameter. Character: "none", "itakura", or a function (see \code{\link[dtw]{dtw}}). #' @param open.end \code{\link[dtw]{dtw}} control parameter. Performs #' open-ended alignments (see \code{\link[dtw]{dtw}}). #' @param scale Logical. If \code{TRUE} dominant frequency values are z-transformed using the \code{\link[base]{scale}} function, which "ignores" differences in absolute frequencies between the signals in order to focus the #' comparison in the frequency contour, regardless of the pitch of signals. Default is \code{TRUE}. #' @param dist.mat Logical controlling whether a distance matrix (\code{TRUE}, #' default) or a tabular data frame (\code{FALSE}) is returned. #' @param ... Additional arguments to be passed to \code{\link{track_freq_contour}} for customizing #' graphical output. #' @return A matrix with the pairwise dissimilarity values. If img is #' \code{FALSE} it also produces image files with the spectrograms of the signals listed in the #' input data frame showing the location of the dominant frequencies. #' @family spectrogram creators #' @seealso \code{\link{freq_ts}} #' @export #' @name multi_DTW #' @details This function extracts the dominant frequency values as a time series and #' then calculates the pairwise acoustic dissimilarity using dynamic time warping. #' The function uses the \code{\link[stats:approxfun]{approx}} function to interpolate values between dominant #' frequency measures. If 'img' is \code{TRUE} the function also produces image files #' with the spectrograms of the signals listed in the input data frame showing the #' location of the dominant frequencies. #' @examples #' \dontrun{ #' # load data #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) #' #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) # save sound files #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' #' # measure #' df <- freq_ts(X = lbh_selec_table, threshold = 10, img = FALSE, path = tempdir()) #' se <- freq_ts(X = lbh_selec_table, threshold = 10, img = FALSE, path = tempdir(), type = "entropy") #' #' # run function #' multi_DTW(df, se) #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on nov-31-2016 (MAS) multi_DTW <- function(ts.df1 = NULL, ts.df2 = NULL, pb = TRUE, parallel = 1, window.type = "none", open.end = FALSE, scale = FALSE, dist.mat = TRUE, ...) { options(digits = 5) #### set arguments from options # get function arguments argms <- methods::formalArgs(freq_ts) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } if (is.null(ts.df1) & is.null(ts.df2)) stop2("both 'ts.df1' or 'ts.df2' must be provided") if (!all.equal(dim(ts.df1), dim(ts.df2))) stop2("both time series data frames must have the same dimensions") # stop if only 1 selection if (nrow(ts.df1) < 2) stop2("you need more than one selection for DTW") if (!all(c("sound.files", "selec") %in% names(ts.df1))) { stop2(paste(paste(c("sound.files", "selec")[!(c("sound.files", "selec") %in% names(ts.df1))], collapse = ", "), "column(s) not found in ts.df1")) } if (!all(c("sound.files", "selec") %in% names(ts.df2))) { stop2(paste(paste(c("sound.files", "selec")[!(c("sound.files", "selec") %in% names(ts.df2))], collapse = ", "), "column(s) not found in ts.df2")) } if (!all(sapply(ts.df1[, 3:ncol(ts.df1)], is.numeric))) stop2(" columns 3:ncol(ts.df) must be numeric") # order time series data frames ts.df1 <- ts.df1[order(ts.df1$sound.files, ts.df1$selec), ] ts.df2 <- ts.df2[order(ts.df2$sound.files, ts.df2$selec), ] if (!all.equal(ts.df1[, names(ts.df1) %in% c("sound.files", "selec")], ts.df2[, names(ts.df2) %in% c("sound.files", "selec")])) stop2("Selections/sound file labels differ between the two time series data frames") if (any(is.na(ts.df1)) | any(is.na(ts.df2))) stop2("missing values in time series are not allowed") if (scale) { ts.df1[, 3:ncol(ts.df1)] <- t(apply(ts.df1[, 3:ncol(ts.df1)], 1, scale)) ts.df2[, 3:ncol(ts.df2)] <- t(apply(ts.df2[, 3:ncol(ts.df2)], 1, scale)) } multi.dtw.FUN <- function(ts.df1, ts.df2, combs, i, ...) { mts1 <- cbind(t(ts.df1[ts.df1$sf.sels == combs[i, 1], 3:ncol(ts.df2)]), t(ts.df2[ts.df1$sf.sels == combs[i, 1], 3:ncol(ts.df2)])) mts2 <- cbind(t(ts.df1[ts.df1$sf.sels == combs[i, 2], 3:ncol(ts.df2)]), t(ts.df2[ts.df1$sf.sels == combs[i, 2], 3:ncol(ts.df2)])) dst <- try(dtw::dtw(mts1, mts2, open.end = open.end, window.type = window.type, ...)$distance, silent = TRUE) if (is(dst, "try-error")) dst <- NA return(dst) } ts.df1$sf.sels <- paste(ts.df1$sound.files, ts.df1$selec, sep = "-") combs <- t(utils::combn(ts.df1$sf.sels, 2)) # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function out <- pblapply_wrblr_int(pbar = pb, X = 1:nrow(combs), cl = cl, FUN = function(i) { multi.dtw.FUN(ts.df1, ts.df2, combs, i, ...) }) # Run parallel in windows # if(parallel > 1) { # if(Sys.info()[1] == "Windows") { # # i <- NULL #only to avoid non-declared objects # # cl <- parallel::makeCluster(parallel) # # doParallel::registerDoParallel(cl) # # out <- foreach::foreach(i = 1:nrow(combs)) %dopar% { # multi.dtw.FUN(ts.df1, ts.df2, combs, i, ...) # # } # # parallel::stopCluster(cl) # # } # if(Sys.info()[1] == "Linux") { # Run parallel in Linux # if(pb) # out <- pbmcapply::pbmclapply(1:nrow(combs), mc.cores = parallel, function (i) { # multi.dtw.FUN(ts.df1, ts.df2, combs, i, ...) # }) else # out <- parallel::mclapply(1:nrow(combs), mc.cores = parallel, function (i) { # multi.dtw.FUN(ts.df1, ts.df2, combs, i, ...) # }) # } # if(!any(Sys.info()[1] == c("Linux", "Windows"))) # parallel in OSts.df1 # { # cl <- parallel::makeForkCluster(getOption("cl.cores", parallel)) # # doParallel::registerDoParallel(cl) # # out <- foreach::foreach(i = 1:nrow(combs)) %dopar% { # multi.dtw.FUN(ts.df1, ts.df2, combs, i, ...) # } # # parallel::stopCluster(cl) # # } # } # else { # if(pb) # out <- pblapply_wrblr_int(pbar = pb, X = 1:nrow(combs), FUN = function(i) # multi.dtw.FUN(ts.df1, ts.df2, combs, i, ...) # ) else # out <- lapply(1:nrow(combs), function(i) multi.dtw.FUN(ts.df1, ts.df2, combs, i, ...)) # # } dist.df <- data.frame(sound.file.selec.1 = combs[, 1], sound.file.selec.2 = combs[, 2], dtw.dist = unlist(out)) if (dist.mat) { # create a similarity matrix with the max xcorr mat <- matrix(nrow = nrow(ts.df1), ncol = nrow(ts.df1)) diag(mat) <- 0 colnames(mat) <- rownames(mat) <- paste(ts.df1$sound.files, ts.df1$selec, sep = "-") mat[lower.tri(mat, diag = FALSE)] <- dist.df$dtw.dist mat <- t(mat) mat[lower.tri(mat, diag = FALSE)] <- dist.df$dtw.dist return(mat) } else { return(dist.df) } }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/multi_DTW.R
#' Data frame detailing function name changes #' #' A data frame containing the old and new names for \code{\link{warbleR}} functions #' @usage data(new_function_names) #' #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) "new_function_names"
/scratch/gouwar.j/cran-all/cranData/warbleR/R/new_function_names.R
#' Open working directory #' #' \code{open_wd} opens the working directory in the default file browser. #' @usage open_wd(path = getwd(), verbose = TRUE) #' @param path Directory path to be opened. By default it's the working directory. #' 'wav.path' set by \code{\link{warbleR_options}} is ignored in this case. #' @param verbose Logical to control whether the 'path' is printed in the console. Defaut is \code{TRUE}. #' @family data manipulation #' @seealso \code{\link{move_imgs}} #' @export #' @name open_wd #' @details The function opens the working directory using the default file browser #' and prints the working directory in the R console. This function aims to simplify #' the manipulation of sound files and other files produced by many of the \code{\link{warbleR}} function. #' @return Opens the working directory using the default file browser. #' @examples #' { #' \donttest{open_wd()} #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) #last modification on apr-16-2018 (MAS) open_wd <- function(path = getwd(), verbose = TRUE){ #check path to working directory if (!dir.exists(path)) stop2("'path' provided does not exist") else path <- normalizePath(path) if (.Platform['OS.type'] == "windows"){ shell.exec(path) } else { system(paste(Sys.getenv("R_BROWSER"), path), ignore.stdout = TRUE, ignore.stderr = TRUE) } if (verbose) print(paste(path, "opened in file browser")) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/open_wd.R
#' Find overlapping selections #' #' \code{overlapping_sels} finds which selections overlap in time within a given sound file. #' @usage overlapping_sels(X, index = FALSE, pb = TRUE, max.ovlp = 0, relabel = FALSE, #' drop = FALSE, priority = NULL, priority.col = NULL, unique.labs = NULL, #' indx.row = FALSE, parallel = 1, verbose = TRUE) #' @param X 'selection_table' object or data frame with the following columns: 1) "sound.files": name of the sound #' files, 2) "selec": number of the selections, 3) "start": start time of selections, 4) "end": #' end time of selections. #' @param index Logical. Indicates if only the index of the overlapping selections would be returned. #' Default is \code{FALSE}. #' @param pb Logical argument to control progress bar and messages. Default is \code{TRUE}. #' @param max.ovlp Numeric vector of length 1 specifying the maximum overlap allowed (in seconds) #' . Default is 0. #' @param relabel Logical. If \code{TRUE} then selection names ('selec' column) are reset within each sound files. #' Default is \code{FALSE}. #' @param drop Logical. If \code{TRUE}, when 2 or more selections overlap the function will remove #' all but one of the overlapping selection. Default is \code{FALSE}. #' @param priority Character vector. Controls the priority criteria used for removing overlapped selections. It #' must list the levels of the column used to determine priority (argument priority.col) in the desired #' priority order. Default is \code{NULL}. #' @param priority.col Character vector of length 1 with the name of the column use to determine the priority of #' overlapped selections. Default is \code{NULL}. #' @param unique.labs DEPRECATED. #' @param indx.row Logical. If \code{TRUE} then a character column with the indices of all selections that overlapped with #' each selection is added to the ouput data frame (if \code{index = TRUE}). For instance, if the selections in rows 1,2 #' and 3 all overlapped with each other, the 'indx.row' value would be "1/2/3" for all. However, if selection 3 only overlaps #' with 2 but not with 1, then it returns, "1/2" for row 1, "1/2/3" for row 2, and "2/3" for row 3. Default is \code{FALSE}. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param verbose Logical to control if messages are printed to the console. #' @return A data frame with the columns in X plus an additional column ('ovlp.sels') indicating #' which selections overlap. For instance, if the selections in rows 1,2 #' overlap and 2 and 3 also overlap, the 'ovlp.sels' label would be the same for all 3 selections. If #' \code{drop = TRUE} only the non-overlapping selections are returned.and if 2 or more selections #' overlap only the first one is kept. The arguments 'priority' and 'priority.col' can be used to modified the criterium for droping overlapping selections. #' @export #' @name overlapping_sels #' @examples #' { #' # no overlap #' overlapping_sels(X = lbh_selec_table) #' #' # modified lbh_selec_table to make the first and second selection overlap #' Y <- lbh_selec_table #' Y$end[4] <- 1.5 #' #' overlapping_sels(X = Y) #' #' # drop overlapping #' overlapping_sels(X = Y, drop = TRUE) #' #' # get index instead #' overlapping_sels(X = Y, index = TRUE) #' } #' @details This function detects selections within a selection table that overlap in time. Selections must be #' listed in a data frame similar to \code{\link{lbh_selec_table}}. Note that row names are set to \code{1:nrow(X)}. #' @seealso \code{\link{filtersels}}, \code{\link{lbh_selec_table}} #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on mar-13-2018 (MAS) overlapping_sels <- function(X, index = FALSE, pb = TRUE, max.ovlp = 0, relabel = FALSE, drop = FALSE, priority = NULL, priority.col = NULL, unique.labs = NULL, indx.row = FALSE, parallel = 1, verbose = TRUE) { #### set arguments from options # get function arguments argms <- methods::formalArgs(overlapping_sels) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } if (!is.null(unique.labs)) { warning2("'unique.labs' has been deprecated") } # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X))) stop2("X is not of a class 'data.frame', 'selection_table'") # check column names if (!all(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))) { stop2(paste(paste(c("sound.files", "selec", "start", "end")[!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop2("NAs found in start and/or end") # if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) stop2("'start' and 'end' must be numeric") # if any start higher than end stop if (any(X$end - X$start <= 0)) stop2(paste("Start is higher than or equal to end in", length(which(X$end - X$start <= 0)), "case(s)")) # priority if (!is.null(priority.col) & !is.null(priority)) { # if col not found if (!priority.col %in% names(X)) stop2(paste("priority.col", priority.col, "not found")) # all levels of priority col should be in priority if (!all(priority %in% unique(X[, priority.col]))) stop2("Not all levels of 'priority.col' included in 'priority'") } # order by start time X <- X[order(X$sound.files, X$start), ] # save rowname X$...ROWNAME... <- 1:nrow(X) # function that runs on a data frame from a single sound file ovlpFUN <- function(w) { Y <- X[X$sound.files == w, ] # only if there is more than 1 selection for that sound file if (nrow(Y) > 1) { # relabel if (relabel) { Y$selec <- 1:nrow(Y) } # determine which ones overlap Y$indx.row <- sapply(1:nrow(Y), function(i) { # if any of those after i overlap ovlp_rows <- Y$...ROWNAME...[(Y$end - max.ovlp) > Y$start[i] & as.numeric(Y$...ROWNAME...) < as.numeric(Y$...ROWNAME...[i]) | Y$start < (Y$end[i] - max.ovlp) & as.numeric(Y$...ROWNAME...) > as.numeric(Y$...ROWNAME...[i])] if (length(ovlp_rows) > 0) { out <- paste(sort(as.numeric(c(Y$...ROWNAME...[i], ovlp_rows))), collapse = "/") } else { out <- NA } return(out) }) } else { Y$indx.row <- NA } return(as.data.frame(Y)) } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function ovlp_df_l <- pblapply_wrblr_int(pbar = pb, X = unique(X$sound.files), cl = cl, FUN = ovlpFUN) ovlp_df <- do.call(rbind, ovlp_df_l) rownames(ovlp_df) <- 1:nrow(ovlp_df) ovlp_df$ovlp.sels <- NA # give unique label to each group of overlapping selections if (any(!is.na(ovlp_df$indx.row))) { overlap_row_id <- strsplit((ovlp_df$indx.row), split = "/") for (i in which(!is.na(ovlp_df$indx.row))) { ovlp_df$ovlp.sels[i] <- if (i == 1) 1 else if (any(overlap_row_id[[i]] %in% overlap_row_id[[i - 1]])) ovlp_df$ovlp.sels[i - 1] else if (any(!is.na(ovlp_df$ovlp.sels[1:(i - 1)]))) max(ovlp_df$ovlp.sels[1:(i - 1)], na.rm = TRUE) + 1 else 1 } } if (index) { return(which(!is.na(ovlp_df$ovlp.sels))) } else { # remove the ones overlapped if (drop) { # remove based on priority if (!is.null(priority.col) & !is.null(priority) & length(priority) > 1) { # remove duplicated labels priority <- priority[!duplicated(priority)] # create numeric vector to order resulting data frame before dropping ordr <- as.character(ovlp_df[, priority.col]) for (i in seq_len(length(priority))) { ordr[ordr == priority[i]] <- i } # order based on priority ovlp_df <- ovlp_df[order(ovlp_df$sound.files, as.numeric(ordr)), ] } org.ovlp <- sum(!is.na(ovlp_df$ovlp.sels)) ovlp_df <- ovlp_df[dups <- !duplicated(ovlp_df[, c("ovlp.sels", "sound.files")]) | is.na(ovlp_df$ovlp.sels), ] } if (pb & verbose) { if (any(!is.na(ovlp_df$ovlp.sels))) { if (drop) { message2(paste(org.ovlp, "selections overlapped,", sum(!is.na(ovlp_df$ovlp.sels)), "were removed")) } else { message2(paste(sum(!is.na(ovlp_df$ovlp.sels)), "selections overlapped")) } } else { message2("No overlapping selections were found") } } # rename rows rownames(ovlp_df) <- ovlp_df$...ROWNAME... # remove ...ROWNAME... ovlp_df$...ROWNAME... <- NULL # set indx.row to NA when no ovlp.sels if (!indx.row) { ovlp_df$indx.row <- NULL } return(ovlp_df) } } ############################################################################################################## #' alternative name for \code{\link{overlapping_sels}} #' #' @keywords internal #' @details see \code{\link{overlapping_sels}} for documentation. \code{\link{ovlp_sels}} will be deprecated in future versions. #' @export ovlp_sels <- overlapping_sels
/scratch/gouwar.j/cran-all/cranData/warbleR/R/overlapping_sels.R
#' Add spectrograms onto phylogenetic trees #' #' \code{phylo_spectro} Add spectrograms to the tips of an objects of class phylo. #' @usage phylo_spectro(X, tree, type = "phylogram", par.mar = rep(1, 4), #' size = 1, offset = 0, path = NULL, ladder = NULL, horizontal = TRUE, axis = TRUE, #' box = TRUE, ...) #' @param X 'selection_table', 'extended_selection_table' or data frame containing columns for sound file name #' (sound.files), selection number (selec), and start and end time of signals (start and end). #' 'top.freq' and 'bottom.freq' columns are optional. In addition, the data frame must include the column 'tip.label' that contains the names of the tip labels found in the tree (e.g. '\code{tree$tip.label}). This column is used to match rows and tip labels. If using an #' 'extended_selection_table' the sound files are not required (see \code{\link{selection_table}}). #' @param tree Object of class 'phylo' (i.e. a phylogenetic tree). Ultrametric trees may produce better results. #' If \code{NULL} (default) then the current working directory is used. Tip labels must match the names provided in the 'tip.label' column in 'X' (see 'X' argument). #' @param type Character string of length 1 specifying the type of phylogeny to be drawn #' (as in \code{\link[ape]{plot.phylo}}). Only 'phylogram' (default) and 'fan' are allowed. #' @param par.mar Numeric vector with 4 elements, default is \code{rep(1, 4)}. Specifies the number of lines #' in inner plot margins where axis labels fall, with form c(bottom, left, top, right). #' See \code{\link[graphics]{par}}. See 'inner.par' argument for controlling spectrogram margins. #' @param size Numeric vector of length 1 controlling the relative size of spectrograms. Higher numbers increase the height of spectrograms. Default is 1. #' Numbers between range \code{c(>0, Inf)} are allowed. #' @param offset Numeric vector of length 1 controlling the space between tips and spectrograms. Default is 0. #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param ladder Character string controlling whether the phylogeny is ladderized (i.e. the internal structure of the #' tree is reorganized to get the ladderized effect when plotted). Only 'left' of 'right' values are accepted. Default is #' \code{NULL} (no ladderization). See \code{\link[ape]{ladderize}} for more details. #' @param horizontal Logical. Controls whether spectrograms in a fan phylogeny are place in a horizontal position #' \code{FALSE} or in the same angle as the tree tips. Currently only horizontal spectrograms are available. #' @param box Logical to control if the box around spectrograms is plotted (see \code{\link[graphics]{box}}). Default is \code{TRUE}. #' @param axis Logical to control if the Y and X axis of spectrograms are plotted (see \code{\link[graphics]{box}}). Default is \code{TRUE}. #' @param ... Additional arguments to be passed to the internal spectrogram #' creating function (\code{\link{spectrograms}}) or phylogeny plotting function (\code{\link[ape]{plot.phylo}}) for #' customizing graphical output. Only rightwards phylogenies can be plotted. #' @return A phylogenetic tree with spectrograms on tree tips is plotted in the current graphical device. #' @family spectrogram creators #' @seealso \code{\link{spectrograms}}, \code{\link[ape]{plot.phylo}} #' @export #' @name phylo_spectro #' @details The function add the spectrograms of sounds annotated in a selection table ('X' argument) onto the tips of a phylogenetic tree. #' The 'tip.label' column in 'X' is used to match spectrograms and tree tips. The function uses internally the \code{\link[ape]{plot.phylo}} function to plot the tree #' and the \code{\link{spectrograms}} function to create the spectrograms. Arguments for both of these functions #' can be provided for further customization. #' @examples { #' \donttest{ #' # First set empty folder #' #' #' # save example sound files #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' #' # set spectrogram options (can be done at the phylo_spectro() function too) #' warbleR_options(wl = 200, ovlp = 90, flim = "frange", wav.path = tempdir()) #' #' # subset example selection table #' X <- lbh_selec_table[1:8, ] #' #' # create random tree (need ape to be installed) #' set.seed(1) #' tree <- ape::rtree(nrow(X)) #' #' # Force tree to be ultrametric #' tree <- ape::chronoMPL(tree) #' #' # add tip label column to example selection table (just for the sake of the example) #' X$tip.label <- tree$tip.label #' #' # print phylogram with spectros #' phylo_spectro(X = X, tree = tree, par.mar = c(0, 0, 0, 8), size = 2) #' #' # no margin in spectrograms and showing tip labels (higher offset) #' phylo_spectro(X = X, tree = tree, offset = 0.1, par.mar = c(0, 0, 0, 6), #' inner.mar = rep(0, 4), size = 2, box = FALSE, axis = FALSE) #' #' # print fan tree and no margin in spectrograms #' phylo_spectro(X = X, tree = tree, offset = 0.6, par.mar = rep(3, 4), #' inner.mar = rep(0, 4), size = 2, type = "fan", show.tip.label = FALSE, box = FALSE, axis = FALSE) #' #' # changing edge color and witdh #' phylo_spectro(X = X, tree = tree, offset = 0.2, par.mar = rep(3, 4), inner.mar = rep(0, 4), #' size = 2, type = "fan", show.tip.label = FALSE, edge.color = "red", edge.width = 2, #' box = FALSE, axis = FALSE) #' #' # plotting a tree representing cross-correlation distances #' xcorr_mat <- cross_correlation(X, bp = c(1, 10)) #' #' xc.tree <- ape::chronoMPL(ape::as.phylo(hclust(as.dist(1 - xcorr_mat)))) #' #' X$tip.label <- xc.tree$tip.label #' #' phylo_spectro(X = X, tree = xc.tree, offset = 0.03, par.mar = rep(3, 4), #' inner.mar = rep(0, 4), size = 0.3, type = "fan", show.tip.label = FALSE, #' edge.color = "red", edge.width = 2, box = FALSE, axis = FALSE) #' } #' } #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) #last modification on oct-1-2018 (MAS) phylo_spectro <- function(X, tree, type = "phylogram", par.mar = rep(1, 4), size = 1, offset = 0, path = NULL, ladder = NULL, horizontal = TRUE, axis = TRUE, box = TRUE, ...) { # error message if ape is not installed if (!requireNamespace("ape",quietly = TRUE)) stop2("must install 'ape' to use phylo_spectro()") # error message if jpeg package is not installed if (!requireNamespace("jpeg",quietly = TRUE)) stop2("must install 'jpeg' to use this function") # currenlt only horizontal is allowed if (!horizontal) message2("Currently only horizontal spectrograms are allowed") horizontal <- TRUE #check path if not provided set to working directory if (is.null(path)) path <- getwd() else if (!dir.exists(path)) stop2("'path' provided does not exist") else path <- normalizePath(path) ## save par current setting and restores it later opar <- par # save on.exit(opar) # restore #### set arguments from options # get function arguments argms <- methods::formalArgs(phylo_spectro) # get warbleR options opt.argms <- if(!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) for (q in seq_len(length(opt.argms))) assign(names(opt.argms)[q], opt.argms[[q]]) # ladderize if (!is.null(ladder)) tree <- ape::ladderize(phy = tree, right = ladder == "right") # check tip labels match if (!identical(sort(as.character(X$tip.label)), sort(tree$tip.label))) stop2("tree tip labels (tree$tip.label) and 'tip.label' column in 'X' do not match") #sort X as in tip labels X <- X[match(tree$tip.label, X$tip.label), ] # map arguments provided argus <- c(opt.argms, call.argms) ## SPECTROGRAMS (save in temporary directory) # save specreator call cll.spec <- quote(spectrograms(line = FALSE, pb = FALSE, dest.path = tempdir())) # keep arguments in ... found in specreator shr.args <- argus[names(argus) %in% names(formals(spectrograms))] # add new arguments to call (if present rewrite if no add) if (length(shr.args) > 0) for(i in seq_len(length(shr.args))) if( any(names(cll.spec) == names(shr.args)[i])) cll.spec[names(cll.spec) == names(shr.args)[i]] <- shr.args[[i]] else { cll.spec[[length(cll.spec) + 1]] <- shr.args[[i]] names(cll.spec)[length(cll.spec)] <- names(shr.args)[i] } # call specreator to save jpegs in temporary directory suppressWarnings(eval(cll.spec)) ## PHYLOGENY # keep arguments in ... found in specreator cll.phylo <- quote(ape::plot.phylo(x = tree, direction = "rightwards")) # keep arguments in ... found in specreator shr.args2 <- argus[names(argus) %in% names(formals(ape::plot.phylo))] # add new arguments to call (if present rewrite if no add) if (length(shr.args2) > 0) for(i in seq_len(length(shr.args2))) if( any(names(cll.phylo) == names(shr.args2)[i])) cll.phylo[names(cll.phylo) == names(shr.args2)[i]] <- shr.args2[[i]] else { cll.phylo[[length(cll.phylo) + 1]] <- shr.args2[[i]] names(cll.phylo)[length(cll.phylo)] <- names(shr.args2)[i] } # set graphic parameter margins par(mar = par.mar) # plot tree eval(cll.phylo) # get border coordinates usr <- par()$usr # plt <- par()$plt # # # correct for margins # usr[2] <- usr[2] + ((usr[2] - usr[1]) * (1 - plt[2])) # usr[1] <- usr[1] - ((usr[2] - usr[1]) * plt[1]) # y limits plt.y.rng <- usr[4] - usr[3] # fix size according to number of tips in tree size <- plt.y.rng / nrow(X) * size # get coordinates for spectrograms lastPP <- get("last_plot.phylo", envir = ape::.PlotPhyloEnv) xs <- lastPP$xx[1:nrow(X)] ys <- lastPP$yy[1:nrow(X)] # fix offset (taken from ape::tiplabels) if (offset != 0) { if (lastPP$type %in% c("phylogram", "cladogram")) { switch(lastPP$direction, rightwards = { xs <- xs + offset }, leftwards = { xs <- xs - offset }, upwards = { ys <- ys + offset }, downwards = { ys <- ys - offset }) } if (lastPP$type %in% c("fan", "radial")) { tmp <- ape::rect2polar(xs, ys) tmp <- ape::polar2rect(tmp$r + offset, tmp$angle) xs <- tmp$x ys <- tmp$y } } # get degrees dgs <- rep(0, length(xs)) # if position of not horizontal if (!horizontal & lastPP$type %in% c("fan", "radial")) { # cuadrant I dgs[xs > 0 & ys > 0] <- asin(abs(ys[xs > 0 & ys > 0])/ sqrt((xs[xs > 0 & ys > 0])^2 + (ys[xs > 0 & ys > 0])^2)) * 180 /pi # cuadrant II dgs[xs > 0 & ys < 0] <- asin((ys[xs > 0 & ys < 0])/ sqrt((xs[xs > 0 & ys < 0])^2 + (ys[xs > 0 & ys < 0])^2)) * 180 /pi # cuadrant III dgs[xs < 0 & ys < 0] <- asin(abs(ys[xs < 0 & ys < 0])/ sqrt((xs[xs < 0 & ys < 0])^2 + (ys[xs < 0 & ys < 0])^2)) * 180 /pi # cuadrant IV dgs[xs < 0 & ys > 0] <- (acos((xs[xs < 0 & ys > 0])/ sqrt((xs[xs < 0 & ys > 0])^2 + (ys[xs < 0 & ys > 0])^2)) * 180 /pi) + 180 } # empty list for images imgs <- list() # image coordinate data frame coors <- data.frame(xs, ys, size, dgs, asp = NA, xleft = NA, xright = NA, ybottom = NA, ytop = NA) # read images and calculate margins for spectrograms for(y in 1:nrow(X)) { # read images imgs[[1 + length(imgs)]] <- jpeg::readJPEG(source = file.path(tempdir(), paste0(X$sound.files[y], "-", X$selec[y], ".jpeg"))) # get image dimensions dims <- dim(imgs[[length(imgs)]]) # get image aspect coors$asp[y] <- 1 / (dims[1] / dims[2]) # calculate image limits # if (lastPP$type == "phylogram") coors$xleft[y] <- coors$xs[y] coors$xright[y] <- coors$xs[y] + size * coors$asp[y] coors$difx[y] <- size * coors$asp[y] coors$ybottom[y] <- coors$ys[y] - (size / 2) coors$ytop[y] <- coors$ys[y] + (size / 2) } # add spectros to phylogeny for(y in 1:nrow(X)) { # allow to plot outside main image area par(xpd = TRUE) # add spectrograms if (lastPP$type == "phylogram") graphics::rasterImage(image = imgs[[y]], xleft = coors$xleft[y], ybottom = coors$ybottom[y], xright = coors$xleft[y] + coors$difx[y], ytop = coors$ytop[y], angle = dgs[y]) else graphics::rasterImage(image = imgs[[y]], xleft = xs[y] - (size / 2), ybottom = ys[y] - (size / 2 * coors$asp[y]), xright = xs[y] + (size / 2), ytop = ys[y] + (size * coors$asp[y] / 2), angle = dgs[y]) } }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/phylo_spectro.R
#' Coordinated singing graphs #' #' \code{plot_coordination} creates graphs of coordinated singing and highlights the signals that overlap #' in time. The signals are represented by polygons of different colors. #' @usage plot_coordination(X, only.coor = FALSE, ovlp = TRUE, xl = 1, res= 80, it = "jpeg", #' img = TRUE, tlim = NULL, pb = TRUE) #' @param X Data frame containing columns for singing event (sing.event), #' individual (indiv), and start and end time of signal (start and end). #' @param only.coor Logical. If \code{TRUE} only the segment in which both individuals are singing is #' included (solo singing is removed). Default is \code{FALSE}. #' @param ovlp Logical. If \code{TRUE} the vocalizations that overlap in time are highlighted. #' Default is \code{TRUE}. #' @param xl Numeric vector of length 1, a constant by which to scale #' spectrogram width. Default is 1. #' @param res Numeric argument of length 1. Controls image resolution. Default is 80. #' @param it A character vector of length 1 giving the image type to be used. Currently only #' "tiff" and "jpeg" are admitted. Default is "jpeg". #' @param img Logical argument. If \code{FALSE}, image files are not produced and #' the graphs are shown in the current graphic device. Default is \code{TRUE}. #' @param tlim Numeric vector of length 2 indicating the start and end time of the coordinated singing events #' to be displayed in the graphs. #' @param pb Logical argument to control progress bar and messages. Default is #' \code{TRUE}. #' @return The function returns a list of graphs, one for each singing event in the input data frame. The graphs can be plotted by simply calling the list. If 'img' is \code{TRUE} then the graphs are also saved in the working #' directory as files. #' #' @export #' @name plot_coordination #' @details This function provides visualization for coordination of acoustic signals. Signals are shown as #' polygon across a time axis. It also shows which signals overlap, the amount of overlap, and #' highlights the individual responsible for the overlap using a color code. The width of the polygons #' depicting the time of overlap. #' @examples #' \dontrun{ #' # load simulate singing events (see data documentation) #' data(sim_coor_sing) #' #' #' # make plot_coordination in graphic device format #' cgs <- plot_coordination(X = sim_coor_sing, ovlp = TRUE, only.coor = FALSE, img = FALSE) #' #' cgs #' } #' #' @references {Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191.} #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on aug-13-2016 (MAS) plot_coordination <- function(X = NULL, only.coor = FALSE, ovlp = TRUE, xl = 1, res = 80, it = "jpeg", img = TRUE, tlim = NULL, pb = TRUE) { # error message if ggplot2 is not installed if (!requireNamespace("ggplot2", quietly = TRUE)) { stop2("must install 'ggplot2' to use plot_coordination()") } #### set arguments from options # get function arguments argms <- methods::formalArgs(plot_coordination) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } if (!is.data.frame(X)) stop2("X is not a data frame") # stop if some events have less than 10 observations if (any(table(X$sing.event) < 10)) warning2("At least one singing event with less than 10 vocalizations") # stop if some cells are not labeled if (any(is.na(X$sing.event))) stop2("NA's in singing event names ('sing.event' column) not allowed") if (any(is.na(X$indiv))) stop2("NA's in individual names ('indiv' column) not allowed") if (any(is.na(X$start))) stop2("NA's in 'start' column not allowed") if (any(is.na(X$end))) stop2("NA's in 'end' column not allowed") if (!is.null(tlim)) X <- X[X$start > tlim[1] & X$end < tlim[2], ] # if it argument is not "jpeg" or "tiff" if (!any(it == "jpeg", it == "tiff")) stop2(paste("Image type", it, "not allowed")) # stop if some events do not have 2 individuals qw <- as.data.frame((tapply(X$sing.event, list(X$sing.event, X$indiv), length))) qw <- tapply(X$indiv, X$sing.event, function(x) length(unique(x))) if (any(qw != 2)) stop2("Some singing events don't have 2 interacting individuals ('indiv' column)") # if xl is not vector or length!=1 stop if (is.null(xl)) { stop2("'xl' must be a numeric vector of length 1") } else { if (!is.vector(xl)) { stop2("'xl' must be a numeric vector of length 1") } else { if (!length(xl) == 1) stop2("'xl' must be a numeric vector of length 1") } } # if res is not vector or length==1 stop if (!is.vector(res)) { stop2("'res' must be a numeric vector of length 1") } else { if (!length(res) == 1) stop2("'res' must be a numeric vector of length 1") } X$sing.event <- as.character(X$sing.event) # to avoid "notes" when submitting to CRAN xmin <- xmax <- ymin <- ymax <- NULL # run loop invisible(ggs <- pblapply_wrblr_int(pbar = pb, X = unique(X$sing.event), FUN = function(x) { y <- X[X$sing.event == x, ] y <- y[!is.na(y$start), ] y <- y[!is.na(y$end), ] y <- y[order(y$start), ] if (only.coor) { fst <- max(c( which(y$start == min(y$start[y$indiv == unique(y$indiv)[1]])), which(y$start == min(y$start[y$indiv == unique(y$indiv)[2]])) )) - 1 lst <- min(c( which(y$start == max(y$start[y$indiv == unique(y$indiv)[1]])), which(y$start == max(y$start[y$indiv == unique(y$indiv)[2]])) )) + 1 y <- y[fst:lst, ] } # data for indiv 1 y1 <- y[y$indiv == unique(y$indiv)[1], ] # data for indiv 2 y2 <- y[y$indiv == unique(y$indiv)[2], ] if (any(nrow(y1) == 0, nrow(y2) == 0)) { paste("in", x, "singing bouts do not overlap in time") } else { df1 <- data.frame( xmin = y1$start, ymin = rep(0.8, nrow(y1)), xmax = y1$end, ymax = rep(1.1, nrow(y1)), id = unique(y$indiv)[1], col = "#F9766E" ) df2 <- data.frame( xmin = y2$start, ymin = rep(1.4, nrow(y2)), xmax = y2$end, ymax = rep(1.7, nrow(y2)), id = unique(y$indiv)[2], col = "#00BFC4" ) df <- rbind(df1, df2) # determine which ones overlap if (ovlp) { btc <- max(c(min(y1$start), min(y2$start))) z <- y[c((which(y$start == btc) - 1):nrow(y)), ] et1 <- max(z$start[z$indiv == unique(z$indiv)[1]]) et2 <- max(z$start[z$indiv == unique(z$indiv)[2]]) etc <- min(c(et1, et2)) z <- z[1:c((which(z$start == etc) + 1)), ] ov <- sapply(2:nrow(z), function(i) { if (z$start[i] > z$start[i - 1] & z$start[i] < z$end[i - 1]) { "ovlp" } else { "No ovlp" } }) if (length(ov[ov == "ovlp"]) > 0) { z1 <- data.frame(z, ovl = c("No ovlp", ov)) recdf <- NULL for (i in 1:nrow(z1)) { if (z1$ovl[i] == "ovlp") { if (z1$indiv[z1$start == min(z1$start[i], z1$start[i - 1])] == unique(z$indiv)[1]) { col <- "#00BFC496" id <- "#!" } else { col <- "#F9766E96" id <- "^%" } if (is.null(recdf)) { recdf <- data.frame( xmin = mean(z1$start[i], z1$end[i]), xmax = min(z1$end[i], z1$end[i - 1]), ymin = 1.1, ymax = 1.4, id, col ) } else { recdf <- rbind(recdf, data.frame( xmin = mean(z1$start[i], z1$end[i]), xmax = min(z1$end[i], z1$end[i - 1]), ymin = 1.1, ymax = 1.4, id, col )) } } } df <- rbind(df, recdf) } } cols <- c("#F9766E66", "#00BFC466") ids <- c(as.character(unique(y$indiv)[2]), as.character(unique(y$indiv)[1])) if (all(exists("recdf"), ovlp)) { if (nrow(recdf) > 0) { if (suppressWarnings(min(which(df$id == "#!"))) < suppressWarnings(min(which(df$id == "^%")))) { cols <- c("#00BFC466", "#F9766E66") ids <- c(as.character(unique(y$indiv)[2]), as.character(unique(y$indiv)[1])) } else { cols <- c("#F9766E66", "#00BFC466") ids <- c(as.character(unique(y$indiv)[1]), as.character(unique(y$indiv)[2])) } } } ggp <- ggplot2::ggplot(df, ggplot2::aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, group = id, fill = col)) + ggplot2::geom_rect() + ggplot2::scale_x_continuous("Time (s)") + ggplot2::scale_y_continuous(name = NULL, breaks = c(0.95, 1.55), labels = c(unique(y$indiv)[1], unique(y$indiv)[2])) + ggplot2::scale_fill_manual( values = c("#F9766E", "#00BFC4", cols), name = "", labels = c( as.character(unique(y$indiv)[1]), as.character(unique(y$indiv)[2]), paste("overlap from", ids[1]), paste("overlap from", ids[2]) ) ) + ggplot2::theme(legend.position = "top") + ggplot2::ggtitle(x) if (img) { if (it == "jpeg") ite <- "coor.singing.jpeg" else ite <- "coor.singing.tiff" ggplot2::ggsave( plot = ggp, filename = paste(x, ite, sep = "-"), dpi = res, units = "in", width = 9 * xl, height = 2.5 ) } return(ggp) } })) } ############################################################################################################## #' alternative name for \code{\link{plot_coordination}} #' #' @keywords internal #' @details see \code{\link{plot_coordination}} for documentation. \code{\link{coor.graph}} will be deprecated in future versions. #' @export coor.graph <- plot_coordination
/scratch/gouwar.j/cran-all/cranData/warbleR/R/plot_coordination.R
#' Access 'Xeno-Canto' recordings and metadata #' #' \code{query_xc} downloads recordings and metadata from \href{https://www.xeno-canto.org/}{Xeno-Canto}. #' @usage query_xc(qword, download = FALSE, X = NULL, file.name = c("Genus", "Specific_epithet"), #' parallel = 1, path = NULL, pb = TRUE) #' @param qword Character vector of length one indicating the genus, or genus and #' species, to query 'Xeno-Canto' database. For example, \emph{Phaethornis} or \emph{Phaethornis longirostris}. #' More complex queries can be done by using search terms that follow the #' xeno-canto advance query syntax. This syntax uses tags to search within a particular aspect of the recordings #' (e.g. country, location, sound type). Tags are of the form tag:searchterm'. For instance, 'type:song' #' will search for all recordings in which the sound type description contains the word 'song'. #' Several tags can be included in the same query. The query "phaethornis cnt:belize' will only return #' results for birds in the genus \emph{Phaethornis} that were recorded in Belize. Queries are case insensitive. Make sure taxonomy related tags (Genus or scientific name) are found first in multi-tag queries. See \href{https://www.xeno-canto.org/help/search}{Xeno-Canto's search help} for a full description and see examples below #' for queries using terms with more than one word. #' @param download Logical argument. If \code{FALSE} only the recording file names and #' associated metadata are downloaded. If \code{TRUE}, recordings are also downloaded to the working #' directory as .mp3 files. Default is \code{FALSE}. Note that if the recording is already in the #' working directory (as when the downloading process has been interrupted) it will be skipped. #' Hence, resuming downloading processes will not start from scratch. #' @param X Data frame with a 'Recording_ID' column and any other column listed in the file.name argument. Only the recordings listed in the data frame #' will be download (\code{download} argument is automatically set to \code{TRUE}). This can be used to select #' the recordings to be downloaded based on their attributes. #' @param file.name Character vector indicating the tags (or column names) to be included in the sound file names (if download = \code{TRUE}). Several tags can be included. If \code{NULL} only the 'Xeno-Canto' recording identification number ("Recording_ID") is used. Default is c("Genus", "Specific_epithet"). #' Note that recording id is always used (whether or not is listed by users) to avoid duplicated names. #' @param parallel Numeric. Controls whether parallel computing is applied when downloading mp3 files. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). Applied both when getting metadata and downloading files. #' @param path Character string containing the directory path where the sound files will be saved. #' If \code{NULL} (default) then the current working directory is used. #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @return If X is not provided the function returns a data frame with the following recording information: recording ID, Genus, Specific epithet, Subspecies, English name, Recordist, Country, Locality, Latitude, Longitude, Vocalization type, Audio file, License, URL, Quality, Time, Date. Sound files in .mp3 format are downloaded into the working directory if download = \code{TRUE} or if X is provided; a column indicating the names of the downloaded files is included in the output data frame. #' @export #' @name query_xc #' @details This function is slated for deprecation in future versions. We recommend exploring the advanced functionalities offered by the \href{https://github.com/maRce10/suwo}{suwo package} as an alternative solution. This function queries for avian vocalization recordings in the open-access #' online repository \href{https://www.xeno-canto.org/}{Xeno-Canto}. It can return recordings metadata #' or download the associated sound files. Complex queries can be done by using search terms that follow the #' xeno-canto advance query syntax (check "qword" argument description). #' Files are double-checked after downloading and "empty" files are re-downloaded. #' File downloading process can be interrupted and resume later as long as the working directory is the same. #' Maps of recording coordinates can be produced using #' \code{\link{map_xc}}. #' @seealso \code{\link{map_xc}} #' @examples #' \dontrun{ #' # search without downloading #' df1 <- query_xc(qword = "Phaethornis anthophilus", download = FALSE) #' View(df1) #' #' # downloading files #' query_xc(qword = "Phaethornis anthophilus", download = TRUE, path = tempdir()) #' #' # check this folder #' tempdir() #' #' ## search using xeno-canto advance query ### #' orth.pap <- query_xc(qword = "gen:orthonyx cnt:papua loc:tari", download = FALSE) #' #' # download file using the output data frame as input #' query_xc(X = orth.pap, path = tempdir()) #' #' # use quotes for queries with more than 1 word (e.g. Costa Rica),note that the #' # single quotes are used for the whole 'qword' and double quotes for the 2-word term inside #' # Phaeochroa genus in Costa Rica #' phae.cr <- query_xc(qword = 'gen:phaeochroa cnt:"costa rica"', download = FALSE) #' #' # several terms can be searched for in the same field #' # search for all female songs in sound type #' femsong <- query_xc(qword = "type:song type:female", download = FALSE) #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on nov-16-2016 (MAS) query_xc <- function(qword, download = FALSE, X = NULL, file.name = c("Genus", "Specific_epithet"), parallel = 1, path = NULL, pb = TRUE) { message2("This function is slated for deprecation in future versions. We recommend exploring the advanced functionalities offered by the suwo package (https://github.com/maRce10/suwo) as an alternative option.") #### set arguments from options # get function arguments argms <- methods::formalArgs(query_xc) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop("'path' provided does not exist") } else { path <- normalizePath(path) } # check internet connection a <- try(RCurl::getURL("www.xeno-canto.org"), silent = TRUE) if (is(a, "try-error")) stop("No connection to xeno-canto.org (check your internet connection!)") if (a == "Could not connect to the database") stop("xeno-canto.org website is apparently down") # If parallel is not numeric if (!is.numeric(parallel)) stop("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop("'parallel' should be a positive integer") # fix file name column names if (!is.null(file.name)) { file.name <- gsub(" ", "_", file.name) file.name <- tolower(file.name) } if (is.null(X) & !is.null(file.name)) { if (any(!(file.name %in% c( "recording_id", "genus", "specific_epithet", "subspecies", "english_name", "recordist", "country", "locality", "latitude", "longitude", "vocalization_type", "audio_file", "license", "url", "quality", "time", "date" )))) { stop("File name tags don't match column names in the output of this function (see documentation)") } } if (is.null(X)) { # search recs in xeno-canto (results are returned in pages with 500 recordings each) if (pb & download) { message2(x = "Obtaining recording list...") } # format query qword if (grepl("\\:", qword)) { # if using advanced search # replace first space with %20 when using full species name first_colon_pos <- gregexpr(":", qword)[[1]][1] spaces_pos <- gregexpr(" ", qword)[[1]] if (length(spaces_pos) > 1) { if (all(spaces_pos[1:2] < first_colon_pos)) { qword <- paste0(substr(qword, start = 0, stop = spaces_pos - 1), "%20", substr(qword, start = spaces_pos + 1, stop = nchar(qword))) } } # replace remaining spaces with "&" qword <- gsub(" ", "+", qword) } else { qword <- gsub(" ", "+", qword) } # initialize search q <- rjson::fromJSON(file = paste0("https://www.xeno-canto.org/api/2/recordings?query=", qword)) if (as.numeric(q$numRecordings) == 0) { message2("No recordings were found") } else { nms <- c("id", "gen", "sp", "ssp", "en", "rec", "cnt", "loc", "lat", "lng", "type", "file", "lic", "url", "q", "time", "date") ### loop over pages # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } f <- pblapply_wrblr_int(pbar = pb, X = 1:q$numPages, cl = cl, FUN = function(y) { # search for each page a <- rjson::fromJSON(file = paste0("https://www.xeno-canto.org/api/2/recordings?query=", qword, "&page=", y)) # put together as data frame d <- lapply(seq_len(length(a$recordings)), function(z) data.frame(t(unlist(a$recordings[[z]])))) d2 <- lapply(d, function(x) { if (!all(nms %in% names(x))) { dif <- setdiff(nms, names(x)) mis <- rep(NA, length(dif)) names(mis) <- dif return(cbind(x, t(mis))) } return(x) }) # determine all column names in all pages cnms <- unique(unlist(lapply(d2, names))) # add columns that are missing to each selection table d3 <- lapply(d2, function(X) { nms <- names(X) if (length(nms) != length(cnms)) { for (i in cnms[!cnms %in% nms]) { X <- data.frame(X, NA, stringsAsFactors = FALSE, check.names = FALSE) names(X)[ncol(X)] <- i } } return(X) }) e <- do.call(rbind, d3) return(e) }) # determine all column names in all pages cnms <- unique(unlist(lapply(f, names))) # add columns that are missing to each selection table f2 <- lapply(f, function(X) { nms <- names(X) if (length(nms) != length(cnms)) { for (i in cnms[!cnms %in% nms]) { X <- data.frame(X, NA, stringsAsFactors = FALSE, check.names = FALSE) names(X)[ncol(X)] <- i } } return(X) }) # save results in a single data frame results <- do.call(rbind, f2) # convert factors to characters indx <- sapply(results, is.factor) results[indx] <- lapply(results[indx], as.character) # order columns results <- results[, order(match(names(results), nms))] names(results)[match(c("id", "gen", "sp", "ssp", "en", "rec", "cnt", "loc", "lat", "lng", "alt", "type", "file", "lic", "url", "q", "length", "time", "date", "uploaded", "rmk", "bird.seen", "playback.used"), names(results))] <- c( "Recording_ID", "Genus", "Specific_epithet", "Subspecies", "English_name", "Recordist", "Country", "Locality", "Latitude", "Longitude", "Altitude", "Vocalization_type", "Audio_file", "License", "Url", "Quality", "Length", "Time", "Date", "Uploaded", "Remarks", "Bird_seen", "Playback_used" )[which(c("id", "gen", "sp", "ssp", "en", "rec", "cnt", "loc", "lat", "lng", "alt", "type", "file", "lic", "url", "q", "length", "time", "date", "uploaded", "rmk", "bird.seen", "playback.used") %in% names(results))] # rename also columns names(results) <- gsub("also", "Other_species", names(results)) # rename names(results) <- gsub("sono.", "Spectrogram_", names(results)) # remove duplicates results <- results[!duplicated(results$Recording_ID), ] if (pb) { message2(x = paste0(nrow(results), " recording(s) found!")) } } } else { # stop if X is not a data frame if (!is(X, "data.frame")) stop("X is not a data frame") # stop if the basic columns are not found if (!is.null(file.name)) { if (any(!c(file.name, "recording_id") %in% tolower(colnames(X)))) { stop(paste(paste(c(file.name, "recording_id")[!c(file.name, "recording_id") %in% tolower(colnames(X))], collapse = ", "), "column(s) not found in data frame")) } } else if (!"Recording_ID" %in% colnames(X)) { stop("Recording_ID column not found in data frame") } download <- TRUE results <- X } # download recordings if (download) { if (any(file.name == "recording_id")) file.name <- file.name[-which(file.name == "recording_id")] if (!is.null(file.name)) { if (length(which(tolower(names(results)) %in% file.name)) > 1) { fn <- apply(results[, which(tolower(names(results)) %in% file.name)], 1, paste, collapse = "-") } else { fn <- results[, which(tolower(names(results)) %in% file.name)] } results$sound.files <- paste(paste(fn, results$Recording_ID, sep = "-"), ".mp3", sep = "") } else { results$sound.files <- paste0(results$Recording_ID, ".mp3") } xcFUN <- function(results, x) { if (!file.exists(results$sound.files[x])) { download.file( url = paste("https://xeno-canto.org/", results$Recording_ID[x], "/download", sep = ""), destfile = file.path(path, results$sound.files[x]), quiet = TRUE, mode = "wb", cacheOK = TRUE, extra = getOption("download.file.extra") ) } return(NULL) } # set clusters for windows OS if (pb) { message2(x = "Downloading files...") } if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } a1 <- pblapply_wrblr_int(pbar = pb, X = 1:nrow(results), cl = cl, FUN = function(x) { xcFUN(results, x) }) if (pb) message2(x = "double-checking downloaded files") # check if some files have no data fl <- list.files(path = path, pattern = ".mp3$") size0 <- fl[file.size(file.path(path, fl)) == 0] # if so redo those files if (length(size0) > 0) { Y <- results[results$sound.files %in% size0, ] unlink(size0) # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } a1 <- pblapply_wrblr_int(pbar = pb, X = 1:nrow(Y), cl = cl, FUN = function(x) { try(xcFUN(Y, x), silent = TRUE) }) } } if (is.null(X)) { if (as.numeric(q$numRecordings) > 0) { # convert lat long to numbers results$Latitude <- as.numeric(results$Latitude) results$Longitude <- as.numeric(results$Longitude) return(droplevels(results)) } } } ############################################################################################################## #' alternative name for \code{\link{query_xc}} #' #' @keywords internal #' @details see \code{\link{query_xc}} for documentation. \code{\link{querxc}} will be deprecated in future versions. #' @export querxc <- query_xc
/scratch/gouwar.j/cran-all/cranData/warbleR/R/query_xc.R
#' An extended version of read_wave that reads several sound file formats and files from selection tables #' #' \code{read_sound_file} reads several sound file formats as well as files referenced in selection tables #' @usage read_sound_file(X, index, from = X$start[index], to = X$end[index], #' channel = X$channel[index], header = FALSE, path = NULL) #' @param X 'data.frame', 'selection_table' or 'extended_selection_table' containing columns for sound file name (sound.files), #' selection number (selec), and start and end time of signals (start and end). Alternatively, the name of a sound file or URL address to sound file can be provided. The function can read sound files in 'wav', 'mp3', 'flac' and 'wac' format. The file name can contain the directory path. #' 'top.freq' and 'bottom.freq' columns are optional. Default is \code{NULL}. #' @param index Index of the selection in 'X' that will be read. Ignored if 'X' is \code{NULL}. #' @param from Where to start reading, in seconds. Default is \code{X$start[index]}. #' @param to Where to stop reading, in seconds. Default is \code{X$end[index]}. #' @param channel Channel to be read from sound file (1 = left, 2 = right, or higher number for multichannel waves). Default is \code{X$channel[index]}. If a 'channel' column does not exist it will read the first channel. #' @param header If \code{TRUE}, only the header information of the Wave object is returned, otherwise (the default) the whole Wave object. #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. If 'X' refers to a sound file including its directory 'path' is ignored. #' @return An object of class "Wave". #' @export #' @name read_sound_file #' @details The function is a wrapper for \code{\link[tuneR]{readWave}} that read sound files, including those referenced in selection tables. It #' is also used internally by warbleR functions to read wave objects from extended selection tables (see \code{\link{selection_table}} for details). For reading 'flac' files on windows the path to the .exe is required. This can be set globally using the 'flac.path' argument in \code{\link{warbleR_options}}. Note that reading 'flac' files requires creating a temporary copy in 'wav' format, which can be particularly slow for long files. #' @examples #' \dontrun{ #' # write wave files with lower case file extension #' data(list = c("Phae.long1")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' #' # read from selection table #' read_sound_file(X = lbh_selec_table, index = 1, path = tempdir()) #' #' # from extended selection table #' library(NatureSounds) #' read_sound_file(X = lbh.est, index = 1) #' #' # read from selection table #' read_sound_file(X = lbh_selec_table, index = 1, path = tempdir()) #' #' # read WAV #' filepath <- system.file("extdata", "recording.wav", package = "bioacoustics") #' read_sound_file(filepath) #' #' # read MP3 #' filepath <- system.file("extdata", "recording.mp3", package = "bioacoustics") #' read_sound_file(filepath) #' #' # read WAC #' filepath <- system.file("extdata", "recording_20170716_230503.wac", package = "bioacoustics") #' read_sound_file(filepath, from = 0, to = 0.2) #' #' # URL file #' read_sound_file(X = "https://www.xeno-canto.org/513948/download") #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on may-7-2018 (MAS) read_sound_file <- function(X, index = NULL, from = X$start[index], to = X$end[index], channel = X$channel[index], header = FALSE, path = NULL) { # if is extended then index must be provided if (is.data.frame(X) & is.null(index)) stop2('"index" needed when a "data.frame", "selection_table", "extended_selection_table" is provided') # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X), is.character(X), is.factor(X))) stop2("X is not of a class 'data.frame', 'selection_table', 'extended_selection_table' or a sound file name") # if is not a data frame if (is.character(X) | is.factor(X)) { # if URL if (grepl("^www.|^http:|^https:", X)) { # get temporary file name temp.file <- tempfile() # download it download.file(url = X, destfile = temp.file, quiet = TRUE, mode = "wb", cacheOK = TRUE, extra = getOption("download.file.extra")) if (!file.exists(temp.file)) stop2("File couldn't be downloaded") # overwrite X X <- temp.file # extension is unknown extsn <- "unk" } else { # get extension pos <- regexpr("\\.([[:alnum:]]+)$", X) extsn <- tolower(ifelse(pos > -1L, substring(X, pos + 1L), "")) } # stop if extension not allowed if (!extsn %in% c("unk", "wav", "mp3", "wac", "flac")) stop2("File format cannot be read") if (basename(as.character(X)) != X) { filename <- X } else { # if path wasn't provided and still doesn't exist if (is.null(path)) { path <- getwd() } filename <- file.path(path, X) } if (is.na(warbleR::try_na(from))) from <- 0 if (is.na(warbleR::try_na(to))) to <- Inf if (is.na(warbleR::try_na(channel))) channel <- 1 object <- read_soundfile_wrblr_int(filename, header, from, to, extension = extsn, channel = channel) if (is(object, "try-error")) { stop2("file cannot be read") } } else { # check columns if (!all(c( "sound.files", "start", "end" ) %in% colnames(X))) { stop2(paste(paste(c("sound.files", "start", "end")[!(c( "sound.files", "start", "end" ) %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop2("NAs found in start and/or end") # if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) stop2("'start' and 'end' must be numeric") # if any start higher than end stop if (any(X$end - X$start < 0)) stop2(paste("The start is higher than the end in", length(which(X$end - X$start < 0)), "case(s)")) # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # convert attr(X, "check.results")$sound.files to character if factor if (is.factor(attr(X, "check.results")$sound.files)) { attr(X, "check.results")$sound.files <- as.character(attr(X, "check.results")$sound.files) } filename <- file.path(path, X$sound.files[index]) if (header) { if (any(is_selection_table(X), is_extended_selection_table(X))) { object <- list(sample.rate = attr(X, "check.results")$sample.rate[attr(X, "check.results")$sound.files == X$sound.files[index]][1] * 1000, channels = 1, bits = attr(X, "check.results")$bits[attr(X, "check.results")$sound.files == X$sound.files[index]][1], samples = attr(X, "check.results")$n.samples[attr(X, "check.results")$sound.files == X$sound.files[index]][1]) } else { pos <- regexpr("\\.([[:alnum:]]+)$", X$sound.files[index]) extsn <- tolower(ifelse(pos > -1L, substring(X$sound.files[index], pos + 1L), "")) object <- read_soundfile_wrblr_int(filename = filename, header = TRUE, extension = extsn) } if (any(sapply(object, length) > 1)) object <- lapply(object, "[", 1) } else { if (is_selection_table(X) | is.data.frame(X) & !is_extended_selection_table(X)) # if no extended selection table { pos <- regexpr("\\.([[:alnum:]]+)$", X$sound.files[index]) extsn <- tolower(ifelse(pos > -1L, substring(X$sound.files[index], pos + 1L), "")) object <- read_soundfile_wrblr_int(filename = filename, header = FALSE, from = from, to = to, extension = extsn, channel = channel) } else { object <- attr(X, "wave.objects")[[which(names(attr(X, "wave.objects")) == X$sound.files[index])[1]]] # if to is infinite then duration of sound file if (is.infinite(to)) to <- length(object@left) / [email protected] # if margin before != 0 and if (attr(X, "check.results")$mar.before[attr(X, "check.results")$sound.files == X$sound.files[index] & attr(X, "check.results")$selec == X$selec[index]] != 0 & attr(X, "check.results")$mar.after[attr(X, "check.results")$sound.files == X$sound.files[index] & attr(X, "check.results")$selec == X$selec[index]] != 0 & any(to < length(object@left) / [email protected], from > 0)) object <- seewave::cutw(object, from = from, to = to, output = "Wave") } } } return(object) } ### internals for reading sound files read_wave_wrblr_int <- function(filename, header = header, from = 0, to = Inf, channel = 1) { obj <- tuneR::readWave(filename = filename, header = header, from = from, to = to, units = "seconds", toWaveMC = TRUE) # Extract one channel if (!header) { obj <- Wave(obj[, channel]) } return(obj) } read_mp3_wrblr_int <- function(filename, header = FALSE, from = 0, to = Inf, channel = 1) { obj <- tuneR::readMP3(file = filename) if (from > 0 | to != Inf) obj <- seewave::cutw(wave = obj, f = [email protected], from = from, to = to, output = "Wave") if (header) { obj <- list(sample.rate = [email protected], channels = if (obj@stereo) 2 else 1, bits = obj@bit, samples = length(obj@left)) } return(obj) } read_wac_wrblr_int <- function(filename, header = FALSE, from = 0, to = Inf, channel = 1) { text_output <- testthat::capture_output_lines(obj <- bioacoustics::read_wac(file = filename)[[1]]) if (from > 0 | to != Inf) obj <- seewave::cutw(wave = obj, f = [email protected], from = from, to = to, output = "Wave") if (header) { obj <- list(sample.rate = [email protected], channels = if (obj@stereo) 2 else 1, bits = obj@bit, samples = length(obj@left)) } return(obj) } read_flac_wrblr_int <- function(filename, header = FALSE, from = 0, to = Inf, channel = 1) { # set path to flac if (is.null(getOption("warbleR")$flac.path)) { # on linox and macOS if (.Platform$OS.type == "unix") { run_flac <- "flac" if (system(paste0(run_flac, " -v --totally-silent"), ignore.stderr = TRUE) != 0) { stop2("FLAC program was not found") } } # on windows if (.Platform$OS.type == "windows") { run_flac <- paste("C:/Program Files/FLAC/", "flac", sep = "" ) if (!file.exists(run_flac)) { run_flac <- paste("C:/Program Files (x86)/FLAC/", "flac", sep = "" ) } if (!file.exists(run_flac)) { stop2("FLAC program was not found") } } warbleR_options(flac.path = "") } else { run_flac <- if (getOption("warbleR")$flac.path %in% c("", "flac")) { "flac" } else { file.path(getOption("warbleR")$flac.path, "flac") } } # create temporary file for convertin to a wav to be read at the end temp_wav <- tempfile() if (.Platform$OS.type == "unix") { system_call <- paste0(run_flac, " -d ", filename, " --output-name=", temp_wav) } if (.Platform$OS.type == "windows") { system_call <- paste(shQuote(run_flac), "-d", shQuote(filename, type = "cmd" ), sep = " ") } # make call silent system_call <- paste(system_call, "--totally-silent") # add start and end time if supplied if (from > 0) { start <- gsub("\\.", ",", paste0(floor(from / 60), ":", from - (floor(from / 60) * 60))) system_call <- paste0(system_call, " --skip=", start) } if (to != Inf) { end <- gsub("\\.", ",", paste0(floor(to / 60), ":", to - (floor(to / 60) * 60))) system_call <- paste0(system_call, " --until=", end) } # run flac out <- system(system_call, ignore.stderr = TRUE) # read temporary wav file wav <- read_wave_wrblr_int(temp_wav, header, 0, Inf, channel) # remove temporary wav file unlink(temp_wav) return(wav) } read_soundfile_wrblr_int <- function(filename, header, from = 0, to = Inf, extension = "unk", channel = 1) { if (is.null(channel) | is.function(channel)) { channel <- 1 } switch(EXPR = extension, wav = object <- read_wave_wrblr_int(filename, header, from, to, channel), mp3 = object <- read_mp3_wrblr_int(filename, header, from, to, channel), wac = object <- read_wac_wrblr_int(filename, header, from, to, channel), flac = object <- read_flac_wrblr_int(filename, header, from, to, channel), unk = { object <- try(read_wave_wrblr_int(filename, header, from, to, channel), silent = TRUE) if (is(object, "try-error")) { object <- try(read_mp3_wrblr_int(filename, header, from, to, channel), silent = TRUE) } if (is(object, "try-error")) { object <- try(read_wac_wrblr_int(filename, header, from, to, channel), silent = TRUE) } if (is(object, "try-error")) { object <- try(read_flac_wrblr_int(filename, header, from, to, channel), silent = TRUE) } } ) return(object) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/read_sound_file.R
#' A wrapper for tuneR's readWave that read sound files listed within selection tables #' #' \code{read_wave} is a wrapper for tuneR's \code{\link[tuneR]{readWave}} function that read sound files listed in data frames and selection tables #' @usage read_wave(X, index, from = X$start[index], to = X$end[index], channel = NULL, #' header = FALSE, path = NULL) #' @param X 'data.frame', 'selection_table' or 'extended_selection_table' containing columns for sound file name (sound.files), #' selection number (selec), and start and end time of signals (start and end). Alternatively, the name of a '.wav' file or URL address to a '.wav' or '.mp3' file can be provided. The file name can contain the directory path. #' 'top.freq' and 'bottom.freq' columns are optional. Default is \code{NULL}. #' @param index Index of the selection in 'X' that will be read. Ignored if 'X' is \code{NULL}. #' @param from Where to start reading, in seconds. Default is \code{X$start[index]}. #' @param to Where to stop reading, in seconds. Default is \code{X$end[index]}. \code{Inf} can be used for reading the entire sound file (when 'X' is a sound file name), #' @param channel Channel to be read from sound file (1 = left, 2 = right, or higher number for multichannel waves). If #' \code{NULL} (default) or higher than the number of channels in a wave then the first channel is used. Only applies to '.wav' files in local directories. #' @param header If \code{TRUE}, only the header information of the Wave object is returned, otherwise (the default) the whole Wave object. #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. If 'X' refers to a sound file including its directory 'path' is ignored. #' @return An object of class "Wave". #' @export #' @name read_wave #' @details The function is a wrapper for \code{\link[tuneR]{readWave}} that read sound files listed within selection tables. It #' is also used internally by warbleR functions to read wave objects from extended selection tables (see \code{\link{selection_table}} for details). #' @examples #' { #' # write wave files with lower case file extension #' data(list = c("Phae.long1")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' #' # read from selection table #' read_wave(X = lbh_selec_table, index = 1, path = tempdir()) #' #' # from extended selection table #' library(NatureSounds) #' read_wave(X = lbh.est, index = 1) #' #' # read WAV #' filepath <- system.file("extdata", "recording.wav", package = "bioacoustics") #' read_wave(filepath) #' #' # read MP3 #' filepath <- system.file("extdata", "recording.mp3", package = "bioacoustics") #' read_wave(filepath) #' #' # URL file #' read_wave(X = "https://www.xeno-canto.org/513948/download") #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on may-7-2018 (MAS) read_wave <- function(X, index, from = X$start[index], to = X$end[index], channel = NULL, header = FALSE, path = NULL) { # if is extended then index must be provided if (is_extended_selection_table(X) & missing(index)) stop('"index" needed when an extended selection table is provided') # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X), is.character(X), is.factor(X))) stop("X is not of a class 'data.frame', 'selection_table', 'extended_selection_table' or a sound file") # if is not a data frame if (is.character(X) | is.factor(X)) { # if URL if (grepl("^www.|^http:|^https:", X)) { # get temporary file name temp.file <- tempfile() # download it download.file(url = X, destfile = temp.file, quiet = TRUE, mode = "wb", cacheOK = TRUE, extra = getOption("download.file.extra")) if (!file.exists(temp.file)) stop("File couldn't be downloaded") # overwrite X X <- temp.file # extension is unknown extsn <- "unk" } else { # get extension pos <- regexpr("\\.([[:alnum:]]+)$", X) extsn <- tolower(ifelse(pos > -1L, substring(X, pos + 1L), "")) } # stop if extension not allowed if (!extsn %in% c("unk", "wav", "mp3")) stop("File format cannot be read") if (basename(as.character(X)) != X) { path <- dirname(as.character(X)) X <- basename(as.character(X)) } else # if path wasn't provided and still doesn't exist if (is.null(path)) { path <- getwd() } if (is.na(try_na(from))) from <- 0 if (is.na(try_na(to))) to <- Inf if (extsn == "wav") { read_fun <- function(X, path, header, from, to) { obj <- tuneR::readWave(filename = file.path(path, X), header = header, from = from, to = to, units = "seconds", toWaveMC = TRUE) # get a single channel if (is(obj, "WaveMC")) { obj <- if (!is.null(channel)) { Wave(obj[, if (channel > ncol(obj)) 1 else channel]) } else { Wave(obj[, 1]) } } return(obj) } } if (extsn == "mp3") read_fun <- function(X, path, header, from, to) bioacoustics::read_mp3(file = file.path(path, X), from = from, to = to) if (extsn == "unk") { read_fun <- function(X, path, header, from, to) { suppressWarnings(object <- try(tuneR::readWave(filename = file.path(path, X), header = header, units = "seconds", from = from, to = to, toWaveMC = TRUE), silent = TRUE)) if (is(object, "try-error")) { object <- try(bioacoustics::read_mp3(file = file.path(path, X), from = from, to = to), silent = TRUE) } return(object) } } object <- read_fun(X, path, header, from, to) if (is(object, "try-error")) { stop("file cannot be read (try read_sound_file() for other sound file formats)") } } else { # check columns if (!all(c( "sound.files", "start", "end" ) %in% colnames(X))) { stop(paste(paste(c("sound.files", "start", "end")[!(c( "sound.files", "start", "end" ) %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop("NAs found in start and/or end") # if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) stop("'start' and 'end' must be numeric") # if any start higher than end stop if (any(X$end - X$start < 0)) stop(paste("The start is higher than the end in", length(which(X$end - X$start < 0)), "case(s)")) # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop("'path' provided does not exist") } else { path <- normalizePath(path) } # convert attr(X, "check.results")$sound.files to character if factor if (is.factor(attr(X, "check.results")$sound.files)) { attr(X, "check.results")$sound.files <- as.character(attr(X, "check.results")$sound.files) } filename <- file.path(path, X$sound.files[index]) if (header) { if (any(is_selection_table(X), is_extended_selection_table(X))) { object <- list(sample.rate = attr(X, "check.results")$sample.rate[attr(X, "check.results")$sound.files == X$sound.files[index]][1] * 1000, channels = 1, bits = attr(X, "check.results")$bits[attr(X, "check.results")$sound.files == X$sound.files[index]][1], samples = attr(X, "check.results")$n.samples[attr(X, "check.results")$sound.files == X$sound.files[index]][1]) } else { object <- tuneR::readWave(filename = filename, header = TRUE) } if (any(sapply(object, length) > 1)) object <- lapply(object, "[", 1) } else { if (is_selection_table(X) | is.data.frame(X) & !is_extended_selection_table(X)) # if no extended selection table { object <- tuneR::readWave(filename = filename, header = FALSE, units = "seconds", from = from, to = to, toWaveMC = TRUE) # if more than 1 channel if (is(object, "WaveMC") & !is.null(X$channel)) { object <- Wave(object[, X$channel[index]]) } else { object <- Wave(object[, 1]) } } else { object <- attr(X, "wave.objects")[[which(names(attr(X, "wave.objects")) == X$sound.files[index])[1]]] # if to is inifite then duration of sound file if (is.infinite(to)) to <- length(object@left) / [email protected] if (attr(X, "check.results")$mar.before[attr(X, "check.results")$sound.files == X$sound.files[index] & attr(X, "check.results")$sound.files == X$sound.files[index] & attr(X, "check.results")$selec == X$selec[index]] != 0 & attr(X, "check.results")$mar.after[attr(X, "check.results")$sound.files == X$sound.files[index] & attr(X, "check.results")$selec == X$selec[index]] != 0 & any(to < length(object@left) / [email protected], from > 0)) object <- seewave::cutw(object, from = from, to = to, output = "Wave") } } } return(object) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/read_wave.R
#' Remove channels in wave files #' #' \code{remove_channels} remove channels in wave files #' @usage remove_channels(files = NULL, channels, path = NULL, parallel = 1, pb = TRUE) #' @param files Character vector indicating the files that will be analyzed. If not provided. Optional. #' then all wave files in the working directory (or path) will be processed. #' @param channels Numeric vector indicating the index (or channel number) for the channels that will be kept (left = 1, right = 2; 3 to inf for multichannel sound files). #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param pb Logical argument to control progress bar and messages. Default is \code{TRUE}. #' @return Sound files that have been converted are saved in the new #' folder "converted_sound_files". If `img = TRUE` then spectrogram images highlighting the silence segments #' that were removed are also saved. #' @export #' @name remove_channels #' @details The function removes channels from wave files. It works on regular and #' multichannel wave files. Converted files are saved in a new directory ("converted_sound_files") #' and original files are not modified. #' @seealso \code{\link{fix_wavs}}, \code{\link{info_wavs}}, #' @examples{ #' # save sound file examples #' data("Phae.long1") #' Phae.long1.2 <- stereo(Phae.long1, Phae.long1) #' #' writeWave(Phae.long1.2, file.path(tempdir(), "Phae.long1.2.wav")) #' #' remove_channels(channels = 1, path = tempdir()) #' #' #check this floder #' tempdir() #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on Jul-30-2018 (MAS) remove_channels <- function(files = NULL, channels, path = NULL, parallel = 1, pb = TRUE) { #### set arguments from options # get function arguments argms <- methods::formalArgs(remove_channels) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # read files fls <- list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE) # stop if files are not in working directory if (length(fls) == 0) stop2("no sound files in working directory") # subet based on file list provided (flist) if (!is.null(files)) fls <- fls[fls %in% files] if (length(fls) == 0) stop2("sound files are not in working directory") dir.create(file.path(path, "converted_sound_files")) mcwv_FUN <- function(x, channels) { wv <- tuneR::readWave(file.path(path, x), toWaveMC = TRUE) if (nchannel(wv) >= max(channels)) { wv <- wv[, channels] if (nchannel(wv) <= 2) wv <- Wave(wv) writeWave(object = wv, filename = file.path(path, "converted_sound_files", x), extensible = FALSE) a <- 0 } else { a <- 1 } return(a) } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function out_l <- pblapply_wrblr_int(pbar = pb, X = fls, cl = cl, FUN = function(x) { mcwv_FUN(x, channels) }) # make it a vector out <- unlist(out_l) if (sum(out) > 0) { warning2(x = paste(sum(out), "file(s) not processed (# channels < max(channels)")) } } ############################################################################################################## #' alternative name for \code{\link{remove_channels}} #' #' @keywords internal #' @details see \code{\link{remove_channels}} for documentation. \code{\link{rm_channels}} will be deprecated in future versions. #' @export rm_channels <- remove_channels
/scratch/gouwar.j/cran-all/cranData/warbleR/R/remove_channels.R
#' Remove silence in wave files #' #' \code{remove_silence} Removes silences in wave files #' @usage remove_silence(path = NULL, min.sil.dur = 2, img = TRUE, it = "jpeg", flim = NULL, #' files = NULL, flist = NULL, parallel = 1, pb = TRUE, downsample = TRUE) #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param min.sil.dur Numeric. Controls the minimum duration of silence segments that would be removed. #' @param img Logical argument. If \code{FALSE}, image files are not produced. Default is \code{TRUE}. #' @param it A character vector of length 1 giving the image type to be used. Currently only #' "tiff" and "jpeg" are admitted. Default is "jpeg". #' @param flim A numeric vector of length 2 indicating the highest and lowest #' frequency limits (kHz) of the spectrogram as in #' \code{\link[seewave]{spectro}}. Default is \code{NULL}. Ignored if `img = FALSE`. #' @param files character vector or factor indicating the subset of files that will be analyzed. If not provided #' then all wave files in the working directory (or path) will be processed. #' @param flist DEPRECATED. Please use 'files' instead. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param pb Logical argument to control progress bar and messages. Default is \code{TRUE}. #' @param downsample Logical indicating whether files are downsampled to a 5000 kHz sampling rate. This can be used to speed up the process, but will make the function ignore sound/noise above 2500 kHz. Default is \code{TRUE}. #' @return Sound files for which silence segments have been removed are saved in the new #' folder "silence-removed_files" in .wav format. If `img = TRUE` then spectrogram images highlighting the silence segments #' that were removed are also saved. #' @export #' @name remove_silence #' @details The function removes silence segments (i.e. segments with very low amplitude values) from wave files. #' @seealso \code{\link{fix_wavs}}, \code{\link{auto_detec}} #' @examples{ #' # save sound file examples #' data(list = c("Phae.long1", "Phae.long2","lbh_selec_table")) #' sil <- silence(samp.rate = 22500, duration = 3, xunit = "time") #' #' #' wv1 <- pastew(pastew(Phae.long1, sil, f = 22500, output = "Wave"), #' Phae.long2, f = 22500, output = "Wave") #' #' #check silence in between amplitude peaks #' env(wv1) #' #' #save wave file #' writeWave(object = wv1, filename = file.path(tempdir(), "wv1.wav"), #' extensible = FALSE) #' #' #remove silence #' # remove_silence(files = "wv1.wav", pb = FALSE, path = tempdir()) #' #' #check this floder #' tempdir() #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on mar-13-2018 (MAS) remove_silence <- function(path = NULL, min.sil.dur = 2, img = TRUE, it = "jpeg", flim = NULL, files = NULL, flist = NULL, parallel = 1, pb = TRUE, downsample = TRUE) { # flist deprecated if (!is.null(flist)) { warning2(x = "'flist' has been deprecated and will be ignored. Please use 'files' instead.") } #### set arguments from options # get function arguments argms <- methods::formalArgs(remove_silence) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) { getOption("warbleR") } else { SILLYNAME <- 0 } # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # read files wavs <- list.files( path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE ) # stop if files are not in working directory if (length(wavs) == 0) { stop2("no sound files in working directory") } # subet based on file list provided (wavs) if (!is.null(files)) { wavs <- wavs[wavs %in% files] } if (length(wavs) == 0) { stop2("selected sound files are not in working directory") } # if it argument is not "jpeg" or "tiff" if (!any(it == "jpeg", it == "tiff")) { stop2(paste("Image type", it, "not allowed")) } # if parallel is not numeric if (!is.numeric(parallel)) { stop2("'parallel' must be a numeric vector of length 1") } if (any(!(parallel %% 1 == 0), parallel < 1)) { stop2("'parallel' should be a positive integer") } wavs <- wavs[!is.na(wavs)] # stop if wavs are not in working directory if (length(wavs) == 0) { stop2("all sound files have been processed") } dir.create(file.path(path, "silence-removed_files"), showWarnings = FALSE) rm.sil.FUN <- function(fl, f = 5000, msd = min.sil.dur, flm = flim, mg = img) { # read wave wv <- warbleR::read_sound_file(X = fl, path = path) # in case flim is higher than can be due to sampling rate if (!is.null(flm)) { if (flm[2] > floor([email protected] / 2000)) { flm[2] <- floor([email protected] / 2000) } } else { flm <- c(0, floor([email protected] / 2000)) } # downsample to speed up process if (downsample) { wv1 <- tuneR::downsample(object = wv, samp.rate = f) } else { wv1 <- wv } # save temporary file temp_file_name <- paste0(tempfile(), ".wav") writeWave(wv1, temp_file_name) ad <- auto_detec( threshold = 0.06, mindur = 0.0001, ssmooth = if (length(wv1) < 1500) { 512 } else { 1500 }, parallel = 1, pb = FALSE, flist = if (downsample) { basename(temp_file_name) } else { fl }, path = if (downsample) { dirname(temp_file_name) } else { path } ) # remove the silence less than min.sil.dur ad$remove <- "no" if (nrow(ad) > 1) { for (i in 1:(nrow(ad) - 1)) { if (ad$start[i + 1] - ad$end[i] < msd) { ad$start[i + 1] <- ad$start[i] ad$remove[i] <- "yes" } } } ad <- ad[ad$remove == "no", ] if (img) { img_wrlbr_int( filename = paste0(fl, ".rm.silence.", it), path = file.path(path, "silence-removed_files"), res = 160, units = "in", width = 8.5, height = 4 ) par(mar = c(4, 4, 1, 1)) spectro_wrblr_int( wv, ovlp = 70, grid = FALSE, scale = FALSE, palette = monitoR::gray.3, axisX = TRUE, fast.spec = TRUE, flim = flm ) # label silence in spectro if (nrow(ad) > 1) { lapply(1:(nrow(ad) - 1), function(z) { # add arrow arrows( x0 = ad$end[z], y0 = flm[1] + flm[2] / 2, x1 = ad$start[z + 1], y1 = flm[1] + flm[2] / 2, code = 3, col = adjustcolor("red2", alpha.f = 0.5), lty = "solid", lwd = 4, angle = 30 ) # add silence label text( x = mean(c(ad$end[z], ad$start[z + 1])), y = flm[1] + flm[2] / 1.8, labels = "Silence", col = adjustcolor("red2", alpha.f = 0.5), pos = 3 ) }) } else { text( x = (length(wv@left) / [email protected]) / 2, y = flm[1] + flm[2] / 1.2, labels = "No silence(s) detected", col = adjustcolor("red2", alpha.f = 0.8), pos = 3 ) } dev.off() } # cut silence from file if (nrow(ad) > 1) { for (z in (nrow(ad) - 1):1) { wv <- deletew( wave = wv, from = ad$end[z], to = ad$start[z + 1], plot = FALSE, output = "Wave" ) } try(writeWave( # wrapped in try to pass checks on windows object = wv, filename = file.path(path, "silence-removed_files", fl), extensible = FALSE ), silent = TRUE) } else { file.copy( from = file.path(path, fl), to = file.path(path, "silence-removed_files", fl) ) } } if (pb) { message2("searching for silence segments in wave files:") } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function out <- pblapply_wrblr_int( pbar = pb, X = wavs, cl = cl, FUN = function(i) { rm.sil.FUN( fl = i, f = 5000, msd = min.sil.dur, flm = flim, mg = img ) } ) } ############################################################################################################## #' alternative name for \code{\link{remove_silence}} #' #' @keywords internal #' @details see \code{\link{remove_silence}} for documentation. \code{\link{rm_sil}} will be deprecated in future versions. #' @export rm_sil <- remove_silence
/scratch/gouwar.j/cran-all/cranData/warbleR/R/remove_silence.R
#' Rename wave objects and associated metadata in extended selection tables #' #' \code{rename_est_waves} rename wave objects and associated metadata in extended selection tables #' @export rename_est_waves #' @usage rename_est_waves(X, new.sound.files, new.selec = NULL) #' @param X object of class 'extended_selection_table'. #' @param new.sound.files Character vector of length equals to the number of wave objects in the extended selection table (\code{length(attr(X, "wave.objects"))}).Specifies the new names to be used for wave objects and sound file column. Note that this will rename wave objects and associated attributes and data in 'X'. #' @param new.selec Numeric or character vector of length equals to the number of rows in 'X' to specify the 'selec' column labels. Default is \code{NULL}. If not provided the 'selec' column is kept unchanged. Note that the combination of 'sound.files' and 'selec' columns must produce unique IDs for each selection (row). #' @return An extended selection table with rename sound files names in data frame and attributes. The function adds columns with the previous sound file names (and 'selec' if provided). #' @family extended selection table manipulation #' @name rename_est_waves #' @details This function allow users to change the names of 'sound.files' and 'selec' columns in extended selection tables. These names can become very long after manipulations used to produce extended tables. #' @examples{ #' data("lbh.est") #' #' # order by sound file name #' lbh.est <- lbh.est[order(lbh.est$sound.files),] #' #' # create new sound file name #' nsf <- sapply(strsplit(lbh.est$sound.files, ".wav",fixed = TRUE), "[",1) #' #' slc <- vector(length = nrow(lbh.est)) #' slc[1] <- 1 #' #' for(i in 2:length(slc)) #' if (nsf[i - 1] == nsf[i]) slc[i] <- slc[i - 1] + 1 else #' slc[i] <- 1 #' #' nsf <- paste(nsf, slc, sep = "_") #' #' # rename sound files #' Y <- rename_est_waves(X = lbh.est, new.sound.files = nsf) #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on nov-12-2019 (MAS)} rename_est_waves <- function(X, new.sound.files, new.selec = NULL) { # check length of new.sound.files if (length(new.sound.files) != length(attr(X, "wave.objects"))) stop2("length of 'new.sound.files' must be equal to the number of wave objects in 'X' (length(attr(X, 'wave.objects')))") # order check results attributes as in X attributes(X)$check.results <- attributes(X)$check.results[match(paste(X$sound.files, paste(X$selec)), paste(attributes(X)$check.results$sound.files, attributes(X)$check.results$selec)), ] # save old name X$old.sound.file.name <- attributes(X)$check.results$old.sound.file.name <- X$sound.files # old and new names in data frame new_names <- data.frame(old = names(attributes(X)$wave.objects), new = new.sound.files) # rename columns in X X$sound.files <- attributes(X)$check.results$sound.files <- sapply(X$old.sound.file.name, function(i) new_names$new[new_names$old == i]) # check and rename selec if (!is.null(new.selec)) { X$old.selec <- attributes(X)$check.results$old.selec <- X$selec X$selec <- attributes(X)$check.results$selec <- new.selec } # check that every row has a unique ID if (attributes(X)$by.song[[1]] & any(duplicated(paste(X$sound.files, X$selec)))) stop2("new.sound.files + 'selec' don't generate unique labels for each row/selection") if (!attributes(X)$by.song[[1]] & any(duplicated(new.sound.files))) stop2("new.sound.files don't have unique labels for each row/selection") # rename wave objects names(attributes(X)$wave.objects) <- sapply(names(attributes(X)$wave.objects), USE.NAMES = FALSE, function(x) { X$sound.files[X$old.sound.file.name == x][1] }) return(X) } ############################################################################################################## #' alternative name for \code{\link{rename_est_waves}} #' #' @keywords internal #' @details see \code{\link{rename_est_waves}} for documentation. \code{\link{rename_waves_est}} will be deprecated in future versions. #' @export rename_waves_est <- rename_est_waves
/scratch/gouwar.j/cran-all/cranData/warbleR/R/rename_est_waves.R
#' Resample wave objects in a extended selection table #' #' \code{resample_est} changes sampling rate and bit depth of wave objects in a extended selection table. #' @usage resample_est(X, samp.rate = 44.1, bit.depth = 16, #' avoid.clip = TRUE, pb = FALSE, parallel = 1) #' @param X object of class 'extended_selection_table' (see \code{\link{selection_table}}). #' @param samp.rate Numeric vector of length 1 with the sampling rate (in kHz) for output files. Default is \code{NULL}. #' @param bit.depth Numeric vector of length 1 with the dynamic interval (i.e. bit depth) for output files. # #' @param sox Logical to control whether \href{https://sourceforge.net/projects/sox/}{SOX} is used internally for resampling. Sox must be installed. Default is \code{FALSE}. \href{https://sourceforge.net/projects/sox/}{SOX} is a better option if having aliasing issues after resampling. #' @param avoid.clip Logical to control whether the volume is automatically #' adjusted to avoid clipping high amplitude samples when resampling. Ignored if #' '\code{sox = FALSE}. Default is \code{TRUE}. #' @param pb Logical argument to control progress bar. Default is \code{FALSE}. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @return An extended selection table with the modified wave objects. #' @export #' @name resample_est #' @details This function aims to simplify the process of homogenizing sound #' files (sampling rate and bit depth). This is a necessary step before running #' any further (bio)acoustic analysis. \href{https://sourceforge.net/projects/sox/}{SOX} must be installed. #' @examples #' \dontrun{ #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' #' # create extended selection table #' X <- selection_table( #' X = lbh_selec_table, extended = TRUE, confirm.extended = FALSE, pb = FALSE, #' path = tempdir() #' ) #' #' # resample #' Y <- resample_est(X) #' } #' @family extended selection table manipulation #' @seealso \code{\link{mp32wav}}, \code{\link{fix_wavs}} #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) #' #last modification on oct-15-2018 (MAS) resample_est <- function(X, samp.rate = 44.1, bit.depth = 16, avoid.clip = TRUE, pb = FALSE, parallel = 1) { # error message if bioacoustics is not installed # if (!requireNamespace("bioacoustics",quietly = TRUE) & !sox) # stop2("must install 'bioacoustics' to use mp32wav() when 'sox = FALSE'") # check bit.depth if (length(bit.depth) > 1) stop2("'bit.depth' should have a single value") bit.depth <- as.character(bit.depth) if (!bit.depth %in% c("1", "8", "16", "24", "32", "64", "0")) stop2('only this "bit.depth" values allowed c("1", "8", "16", "24", "32", "64", "0") \n see ?tuneR::normalize') #### set arguments from options # get function arguments argms <- methods::formalArgs(resample_est) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # set clusters for windows OS and no soz if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # if (!sox) # out <- pblapply_wrblr_int(pbar = pb, X = attributes(X)$wave.objects, cl = cl, function(x) # { # # if ([email protected] != samp.rate * 1000) { # # # filter first to avoid aliasing when downsampling # if ([email protected] > samp.rate * 1000) # x <- seewave::fir(wave = x , f = [email protected], from = 0, to = samp.rate * 1000 / 2, bandpass = TRUE, output = "Wave") # # x <- warbleR::resample(wave = x, to = samp.rate * 1000) # } # # # normalize # if (bit.depth != x@bit) # x <- tuneR::normalize(object = x, unit = bit.depth) # # return(x) # # }) else { # out <- pblapply_wrblr_int(pbar = pb, X = attributes(X)$wave.objects, FUN = function(x) { # fo saving current wave tempfile <- paste0(tempfile(), ".wav") # for writting converted wave tempfile2 <- paste0(tempfile(), ".wav") suppressWarnings(tuneR::writeWave(extensible = FALSE, object = tuneR::normalize(x, unit = bit.depth), filename = tempfile)) cll <- paste0("sox '", tempfile, "' -t wavpcm ", "-b ", bit.depth, " '", tempfile2, "' rate ", samp.rate * 1000, " dither -s") if (avoid.clip) cll <- gsub("^sox", "sox -G", cll) # if ([email protected] < samp.rate * 1000) cll <- gsub("dither -s$", "resample", cll) if (Sys.info()[1] == "Windows") cll <- gsub("'", "\"", cll) out <- suppressWarnings(system(cll, ignore.stdout = FALSE, intern = TRUE)) x <- warbleR::read_sound_file(X = basename(tempfile2), path = tempdir()) # remove files unlink(c(tempfile, tempfile2)) return(x) }) # } # replace with resampled waves attributes(X)$wave.objects <- out # fix attributes attributes(X)$check.results$sample.rate <- samp.rate attributes(X)$check.results$bits <- bit.depth attributes(X)$check.results$n.samples <- sapply(X$sound.files, function(x) length(attributes(X)$wave.objects[[which(names(attributes(X)$wave.objects) == x)]]@left)) if (any(X$top.freq > samp.rate / 2)) { X$top.freq[X$top.freq > samp.rate / 2] <- samp.rate / 2 warning2(x = "Some 'top.freq' values higher than nyquist frequency were set to samp.rate/2") } return(X) } ############################################################################################################## #' alternative name for \code{\link{resample_est}} #' #' @keywords internal #' @details see \code{\link{resample_est}} for documentation. \code{\link{resample_est_waves}} will be deprecated in future versions. #' @export resample_est_waves <- resample_est
/scratch/gouwar.j/cran-all/cranData/warbleR/R/resample_est.R
#' Alternative name for \code{lbh_selec_table} #' #' Selection table of long-billed hermit songs #' #' @description \code{selec.table} alternative name for \code{lbh_selec_table}. \code{selec.table} will be deprecated in #' future versions. #' #' @source Marcelo Araya Salas, warbleR "selec.table"
/scratch/gouwar.j/cran-all/cranData/warbleR/R/selec.table-data.R
#' Create 'selection_table' and 'extended_selection_table' objects #' #' \code{selection_table} converts data frames into an object of classes 'selection_table' or 'extended_selection_table'. #' @usage selection_table(X, max.dur = 10, path = NULL, whole.recs = FALSE, #' extended = FALSE, confirm.extended = FALSE, mar = 0.1, by.song = NULL, #' pb = TRUE, parallel = 1, verbose = TRUE, skip.error = FALSE, #' file.format = "\\\.wav$|\\\.wac$|\\\.mp3$|\\\.flac$", files = NULL, ...) #' @param X data frame with the following columns: 1) "sound.files": name of the .wav #' files, 2) "selec": unique selection identifier (within a sound file), 3) "start": start time and 4) "end": #' end time of selections. Columns for 'top.freq', 'bottom.freq' and 'channel' are optional. Note that, when 'channel' is #' not provided the first channel (i.e. left channel) would be used by default. #' Frequency parameters (including top and bottom frequency) should be provided in kHz. Alternatively, a 'selection_table' class object can be input. #' @param max.dur the maximum duration of expected for a selection (ie. end - start). If surpassed then an error message #' will be generated. Useful for detecting errors in selection tables. #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param whole.recs Logical. If \code{TRUE} the function will create a selection #' table for all sound files in the working directory (or "path") with `start = 0` #' and `end = duration_wavs()`. Default is if \code{FALSE}. Note that this will not create #' a extended selection table. If provided 'X' is ignored. #' @param extended Logical. If \code{TRUE}, the function will create an object of class 'extended_selection_table' #' which included the wave objects of the selections as an additional attribute ('wave.objects') to the data set. This is #' and self-contained format that does not require the original sound files for running most acoustic analysis in #' \code{\link{warbleR}}. This can largely facilitate the storing and sharing of (bio)acoustic data. Default #' is if \code{FALSE}. An extended selection table won't be created if there is any issue with the selection. See #' 'details'. #' @param mar Numeric vector of length 1 specifying the margins (in seconds) #' adjacent to the start and end points of the selections when creating extended #' selection tables. Default is 0.1. Ignored if 'extended' is \code{FALSE}. #' @param confirm.extended Logical. If \code{TRUE} then the size of the 'extended_selection_table' #' will be estimated and the user will be asked for confirmation (in the console) #' before proceeding. Ignored if 'extended' is \code{FALSE}. This is used to prevent #' generating objects too big to be dealt with by R. See 'details' for more information about extended selection table size. THIS ARGUMENT WILL BE DEPRECATED IN FUTURE VERSIONS. #' @param by.song Character string with the column name containing song labels. If provided a wave object containing for #' all selection belonging to a single song would be saved in the extended selection table (hence only applicable for #' extended selection tables). Note that the function assumes that song labels are not repeated within a sound file. #' If \code{NULL} (default), wave objects are created for each selection (e.g. by selection). #' Ignored if \code{extended = FALSE}. #' @param pb Logical argument to control progress bar and messages. Default is \code{TRUE}. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param verbose Logical argument to control if summary messages are printed to the console. Default is \code{TRUE}. #' @param skip.error Logical to control if errors are omitted. If so, files that could not be read will be excluded and their name printed in the console. Default is \code{FALSE}, which will return an error if some files are problematic. #' @param file.format Character string with the format of sound files. By default all sound file formats supported by warbleR are included ("\\.wav$|\\.wac$|\\.mp3$|\\.flac$"). Note that several formats can be included using regular expression syntax as in \code{\link[base]{grep}}. For instance \code{"\\.wav$|\\.mp3$"} will only include .wav and .mp3 files. Ignored if \code{whole.recs = FALSE}. #' @param files character vector indicating the set of files that will be consolidated. File names should not include the full file path. Optional. #' @param ... Additional arguments to be passed to \code{\link{check_sels}} for customizing #' checking routine. #' @return An object of class selection_table which includes the original data frame plus the following additional attributes: #' \itemize{ #' \item 1) A data frame with the output of \code{\link{check_sels}} run on the input data frame. If a extended selection table is created it will also include the original values in the input data frame for each selections. This are used by downstream warbleR functions to improve efficiency and avoid #' errors due to missing or mislabeled data, or selection out of the ranges of the original sound files. #' \item 2) A list indicating if the selection table has been created by song (see 'by.song argument). #' \item 3) If a extended selection table is created a list containing the wave objects for each selection (or song if 'by.song'). #' } #' @details This function creates and object of class 'selection_table' or 'extended_selection_table' (if \code{extended = TRUE}, see below). First, the function checks: #' \itemize{ #' \item 1) if the selections listed in the data frame correspond to .wav files #' in the working directory #' \item 2) if the sound files can be read and if so, #' \item 3) if the start and end time of the selections are found within the duration of the sound files #' } #' If no errors are found the a selection table or extended selection table will be generated. #' Note that the sound files should be in the working directory (or the directory provided in 'path'). #' This is useful for avoiding errors in downstream functions (e.g. \code{\link{spectro_analysis}}, \code{\link{cross_correlation}}, \code{\link{catalog}}, \code{\link{freq_DTW}}). Note also that corrupt files can be #' fixed using \code{\link{fix_wavs}} ('sox' must be installed to be able to run this function). #' The 'selection_table' class can be input in subsequent functions. #' #' When \code{extended = TRUE} the function will generate an object of class 'extended_selection_table' which #' will also contain the wave objects for each of the selections in the data frame. #' This transforms selection tables into self-contained objects as they no longer need the original #' sound files to run acoustic analysis. This can largely facilitate the storing and sharing of (bio)acoustic data. #' Extended selection table size will be a function of the number of selections \code{nrow(X)}, sampling rate, selection #' duration and margin duration. As a guide, a selection table #' with 1000 selections similar to the ones in 'lbh_selec_table' (mean duration ~0.15 #' seconds) at 22.5 kHz sampling rate and the default margin (\code{mar = 0.1}) #' will generate a extended selection table of ~31 MB (~310 MB for a 10000 rows #' selection table). You can check the size of the output extended selection table #' with the \code{\link[utils]{object.size}} function. Note that extended selection table created 'by.song' could be #' considerable larger. #' @seealso \code{\link{check_wavs}} #' @export #' @name selection_table #' @examples #' { #' data(list = c( #' "Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", #' "lbh_selec_table" #' )) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' #' # make selection table #' st <- selection_table(X = lbh_selec_table, path = tempdir()) #' #' is_selection_table(st) #' #' #' # make extended selection table #' st <- selection_table( #' X = lbh_selec_table, extended = TRUE, #' path = tempdir() #' ) #' #' is_extended_selection_table(st) #' #' ### make extended selection by song #' # create a song variable #' lbh_selec_table$song <- as.numeric(as.factor(lbh_selec_table$sound.files)) #' #' st <- selection_table( #' X = lbh_selec_table, extended = TRUE, #' by.song = "song", path = tempdir() #' ) #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on may-9-2018 (MAS) selection_table <- function(X, max.dur = 10, path = NULL, whole.recs = FALSE, extended = FALSE, confirm.extended = FALSE, mar = 0.1, by.song = NULL, pb = TRUE, parallel = 1, verbose = TRUE, skip.error = FALSE, file.format = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", files = NULL, ...) { #### set arguments from options # get function arguments argms <- methods::formalArgs(selection_table) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path if not provided set to working directory if (is.null(path)) path <- getwd() else if (!dir.exists(path)) stop2("'path' provided does not exist") # if by song but column not found if (!is.null(by.song)) { if (!any(names(X) == by.song)) stop2("'by.song' column not found") } # If parallel is not numeric if (!is.numeric(parallel)) stop2("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop2("'parallel' should be a positive integer") # create a selection table for a row for each full length recording if (whole.recs) { if (is.null(files)) { sound.files <- list.files(path = path, pattern = file.format, ignore.case = TRUE) } else { sound.files <- files } if (length(sound.files) == 0) stop2("No sound files were found") X <- data.frame(sound.files, selec = 1, channel = 1, start = 0, end = duration_sound_files(files = sound.files, path = path, skip.error = skip.error)$duration) if (skip.error) { # get name of problematic files error_files <- X$sound.files[is.na(X$end)] # remove them from output X X <- X[!is.na(X$end), ] } } # create error_files if not created if (!exists("error_files")) { error_files <- vector() } if (pb & verbose) { if (!extended) { message2(x = "checking selections (step 1 of 1):") } else { message2(x = "checking selections (step 1 of 2):") } } check.results <- warbleR::check_sels(X, path = path, wav.size = TRUE, pb = pb, verbose = FALSE, ...) if (any(check.results$check.res != "OK")) stop2("Not all selections can be read (use check_sels() to locate problematic selections)") X <- check.results[, names(check.results) %in% names(X)] ## Set the name for the class class(X) <- unique(append("selection_table", class(X))) check.results <- check.results[, names(check.results) %in% c("sound.files", "selec", by.song, "check.res", "duration", "min.n.sample", "sample.rate", "channels", "bits", "wav.size", "sound.file.samples")] # add wave object to extended file if (extended) { if (confirm.extended) { exp.size <- sum(round(check.results$bits * check.results$sample.rate * (check.results$duration + (mar * 2)) / 4) / 1024) message2(x = paste0("Expected 'extended_selection_table' size is ~", ifelse(round(exp.size) == 0, round(exp.size, 2), round(exp.size)), "MB (~", round(exp.size / 1024, 5), " GB) \n Do you want to proceed? (y/n): "), color = "magenta") answer <- readline(prompt = "") } else { answer <- "yeah dude!" } if (substr(answer, 1, 1) %in% c("y", "Y")) # if yes { check.results$orig.start <- X$start check.results$orig.end <- X$end check.results$mar.after <- check.results$mar.before <- rep(mar, nrow(X)) # get sound file duration dur <- duration_wavs(files = as.character(X$sound.files), path = path)$duration # reset margin signals if lower than 0 or higher than duration for (i in 1:nrow(X)) { if (X$start[i] < mar) check.results$mar.before[i] <- X$start[i] if (X$end[i] + mar > dur[i]) check.results$mar.after[i] <- dur[i] - X$end[i] } if (!is.null(by.song)) { Y <- song_analysis(X = as.data.frame(X), song_colm = by.song, pb = FALSE) Y <- Y[, names(Y) %in% c("sound.files", by.song, "start", "end")] check.results$song <- X[, by.song] # temporal column to match songs by sound file check.results$song.TEMP <- paste(X$sound.files, X[, by.song, drop = TRUE], sep = "-") Y$song.TEMP <- paste(Y$sound.files, Y[, by.song], sep = "-") Y$mar.before <- sapply(unique(Y$song.TEMP), function(x) check.results$mar.before[which.min(check.results$orig.start[check.results$song.TEMP == x])]) Y$mar.after <- sapply(unique(Y$song.TEMP), function(x) check.results$mar.after[which.max(check.results$orig.end[check.results$song.TEMP == x])]) # remove temporal column check.results$song.TEMP <- NULL } else { Y <- X Y$mar.before <- check.results$mar.before Y$mar.after <- check.results$mar.after } # save wave objects as a list attributes # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } if (pb) { message2(x = "saving wave objects into extended selection table (step 2 of 2):") } attributes(X)$wave.objects <- pblapply_wrblr_int(pbar = pb, X = 1:nrow(Y), cl = cl, FUN = function(x) warbleR::read_sound_file(X = Y, index = x, from = Y$start[x] - Y$mar.before[x], to = Y$end[x] + Y$mar.after[x], path = path, channel = if (!is.null(X$channel)) X$channel[x] else 1)) # reset for new dimensions check.results$start <- X$start <- check.results$mar.before check.results$end <- X$end <- check.results$mar.before + check.results$duration names(check.results)[names(check.results) == "sound.files"] <- "orig.sound.files" names(check.results)[names(check.results) == "selec"] <- "orig.selec" if (!is.null(by.song)) { names(attributes(X)$wave.objects) <- paste0(Y$sound.files, "-song_", Y[, by.song]) X$sound.files <- check.results$sound.files <- paste0(X$sound.files, "-song_", as.data.frame(X)[, names(X) == by.song, ]) for (i in unique(X$sound.files)) { check.results$selec[check.results$sound.files == i] <- X$selec[X$sound.files == i] <- 1:nrow(X[X$sound.files == i, drop = FALSE]) } check.results$n.samples <- NA durs <- X$end - X$start for (w in unique(X$sound.files)) { check.results$start[check.results$sound.files == w] <- X$start[X$sound.files == w] <- X$start[X$sound.files == w][which.min(check.results$orig.start[check.results$sound.files == w])] + (check.results$orig.start[check.results$sound.files == w] - min(check.results$orig.start[check.results$sound.files == w])) # add n.samples for header info check.results$n.samples[check.results$sound.files == w] <- length(attr(X, "wave.objects")[[which(names(attr(X, "wave.objects")) == w)]]@left) } check.results$end <- X$end <- X$start + durs } else { names(attributes(X)$wave.objects) <- check.results$sound.files <- X$sound.files <- paste(basename(as.character(X$sound.files)), X$selec, sep = "_") check.results$selec <- X$selec <- 1 check.results$n.samples <- as.vector(sapply(attr(X, "wave.objects"), function(x) length(x@left))) # add n.samples for header info } ## Set the name for the class class(X)[class(X) == "selection_table"] <- "extended_selection_table" } } else { check.results$n.samples <- check.results$sound.file.samples } # order check results columns check.results <- check.results[, na.omit(match(c("orig.sound.files", "orig.selec", "orig.start", "orig.end", "sound.files", "selec", "start", "end", "check.results", "duration", "sample.rate", "channels", "bits", "wav.size", "mar.before", "mar.after", "n.samples"), names(check.results)))] attributes(X)$check.results <- check.results # recalculate file size if (whole.recs) { attributes(X)$check.results$wav.size <- file.size(file.path(path, attributes(X)$check.results$sound.files)) / 1000000 } if (is_extended_selection_table(X) & !is.null(by.song)) attributes(X)$by.song <- list(by.song = TRUE, song.column = by.song) else attributes(X)$by.song <- list(by.song = FALSE, song.column = by.song) attributes(X)$call <- base::match.call() attributes(X)$warbleR.version <- packageVersion("warbleR") if (extended & confirm.extended & !is_extended_selection_table(X)) { message2(color = "silver", x = cli::style_bold("'extended_selection_table' was not created")) } if (skip.error & length(error_files) > 0) { message2(color = "silver", x = "One or more file(s) couldn't be read and were not included (run .Options$unread_files to see which files)") on.exit(options(unread_files = error_files)) } return(X) } ############################################################################################################## #' Old name for \code{\link{selection_table}} #' #' @keywords internal #' @details see \code{\link{selection_table}} for documentation #' @export make.selection.table <- selection_table ############################################################################################################## #' Class 'selection_table': double-checked frequency/time coordinates of selections #' #' Class for selections of signals in sound files #' @export #' @details An object of class \code{selection_table} created by \code{\link{selection_table}} is a list with the following elements: #' \itemize{ #' \item\code{selections}: data frame containing the frequency/time coordinates of the selections, sound file names, and any additional information #' \item \code{check.resutls}: results of the checks on data consistency using \link{check_sels} #' } #' @seealso \code{\link{selection_table}} ############################################################################################################## #' Check if object is of class "selection_table" #' #' \code{is_selection_table} Check if the object belongs to the class "selection_table" #' @usage is_selection_table(x) #' @param x R object. #' @return A logical argument indicating whether the object class is 'selection_table' #' @seealso \code{\link{selection_table}} #' @export #' @name is_selection_table #' @examples #' { #' # load data #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) #' #' is_selection_table(lbh_selec_table) #' #' # save wave files in temporary directory #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' #' st <- selection_table(lbh_selec_table, path = tempdir()) #' #' is_selection_table(st) #' #' class(st) #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on may-9-2018 (MAS) is_selection_table <- function(x) inherits(x, "selection_table") ############################################################################################################## #' Class 'extended_selection_table': selection table containing wave objects #' #' Class for selections of signals in sound files and corresponding wave objects #' @export #' @details An object of class \code{extended_selection_table} created by \code{\link{selection_table}} is a list with the following elements: #' \itemize{ #' \item \code{selections}: data frame containing the frequency/time coordinates of the selections, sound file names, and any additional information #' \item \code{check.resutls}: results of the checks on data consistency using \link{check_sels} #' \item \code{wave.objects}: list of wave objects corresponding to each selection #' \item \code{by.song}: a list with 1) a logical argument defining if the 'extended_selection_table' was created 'by song' #' and 2) the name of the song column (see \code{\link{selection_table}}) #' } #' @seealso \code{\link{selection_table}}, \code{\link{selection_table}} ############################################################################################################## #' Check if object is of class "extended_selection_table" #' #' \code{is_extended_selection_table} Check if the object belongs to the class "extended_selection_table" #' @usage is_extended_selection_table(x) #' @param x R object #' @return A logical argument indicating whether the object class is 'extended_selection_table' #' @seealso \code{\link{selection_table}}; \code{\link{is_selection_table}} #' @export #' @name is_extended_selection_table #' @examples #' { #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) #' #' is_extended_selection_table(lbh_selec_table) #' #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' #' st <- selection_table(lbh_selec_table, #' extended = TRUE, #' path = tempdir() #' ) #' #' is_extended_selection_table(st) #' #' class(st) #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on may-9-2018 (MAS) is_extended_selection_table <- function(x) inherits(x, "extended_selection_table") ############################################################################################################## #' extract method for class \code{selection_table} #' #' @param X Object of class \code{selection_table}, generated by \code{\link{selection_table}}. #' @param i, j, indices specifying elements to extract or replace. Indices are numeric or character vectors or empty #' (missing) or NULL. #' @keywords internal #' #' @export #' # function to subset extended selection table with [ `[.selection_table` <- function(X, i = NULL, j = NULL, drop = FALSE) { if (is.character(i)) i <- which(row.names(X) %in% i) if (is.character(j)) j <- which(names(X) %in% j) if (is.null(i)) i <- 1:nrow(X) if (is.null(j)) j <- seq_len(ncol(X)) Y <- as.data.frame(X)[i, j, drop = drop] if (is.data.frame(Y)) { attributes(Y)$check.results <- attributes(X)$check.results[i, , ] attributes(Y)$by.song <- attributes(X)$by.song attributes(Y)$call <- base::match.call() class(Y) <- class(X) } return(Y) } ############################################################################################################## #' extract method for class \code{extended_selection_table} #' #' @param X Object of class \code{extended_selection_table}, generated by \code{\link{selection_table}}. #' @param i, j, indices specifying elements to extract or replace. Indices are numeric or character vectors or empty #' (missing) or NULL. #' @keywords internal #' #' @export #' # function to subset extended selection table with [ `[.extended_selection_table` <- function(X, i = NULL, j = NULL, drop = FALSE) { if (is.character(i)) i <- which(row.names(X) %in% i) if (is.character(j)) j <- which(names(X) %in% j) if (is.null(i)) i <- 1:nrow(X) if (is.null(j)) j <- seq_len(ncol(X)) Y <- as.data.frame(X)[i, j, drop = drop] if (is.data.frame(Y)) { # subset wave objects in attributes attributes(Y)$wave.objects <- attributes(X)$wave.objects[names(attributes(X)$wave.objects) %in% unique(Y$sound.files)] attributes(Y)$check.results <- attributes(X)$check.results[paste(attributes(X)$check.results$sound.files, attributes(X)$check.results$selec) %in% paste(Y$sound.files, Y$selec), ] # attributes(Y)$check.results <- attributes(X)$check.results[attributes(X)$check.results$sound.files %in% Y$sound.files, ] attributes(Y)$by.song <- attributes(X)$by.song attributes(Y)$call <- base::match.call() class(Y) <- class(X) } return(Y) } ############################################################################################################# #' print method for class \code{extended_selection_table} #' #' @param x Object of class \code{extended_selection_table}, generated by \code{\link{selection_table}}. #' @keywords internal #' @param ... further arguments passed to or from other methods. Ignored when printing extended selection tables. #' @export #' print.extended_selection_table <- function(x, ...) { message2(paste("Object of class", cli::style_bold("'extended_selection_table'"))) # print call if (!is.null(attributes(x)$call)) { message2(color = "silver", x = paste("* The output of the following", "call:")) cll <- deparse(attributes(x)$call) if (length(cll) > 1) cll <- paste(cll, collapse = " ") if (nchar(as.character(cll)) > 250) { cll <- paste(substr(x = as.character(cll), start = 0, stop = 250), "...") } message2(color = "silver", x = cli::style_italic(gsub(" ", "", cll))) } message2(color = "silver", x = paste(cli::style_bold("\nContains:"), "\n* A selection table data frame with", nrow(x), "row(s) and", ncol(x), "columns:")) # define columns to show cols <- if (ncol(x) > 6) 1:6 else seq_len(ncol(x)) kntr_tab <- knitr::kable(head(x[, cols, drop = FALSE]), escape = FALSE, digits = 4, justify = "centre", format = "pipe") for (i in seq_len(length(kntr_tab))) { message2(color = "silver", x = paste0(kntr_tab[i])) } if (ncol(x) > 6) { message2(color = "silver", x = paste0("... ", ncol(x) - 6, " more column(s) (", paste(colnames(x)[7:ncol(x)], collapse = ", "), ")")) } if (nrow(x) > 6) { message2(color = "silver", x = paste0(if (ncol(x) <= 6) "..." else "", " and ", nrow(x) - 6, " more row(s)")) } message2(color = "silver", x = paste0("\n* ", length(attr(x, "wave.objects")), " wave object(s) (as attributes): ")) if (length(attr(x, "wave.objects")) <= 6) message2(color = "silver", x = paste(names(attr(x, "wave.objects")), collapse = ", ")) else message2(color = "silver", x = paste(names(attr(x, "wave.objects"))[1:6], collapse = ", ")) if (length(attr(x, "wave.objects")) > 6) message2(color = "silver", x = paste0("... and ", length(attr(x, "wave.objects")) - 6, " more")) if (length(attr(x, "wave.objects")) != length(unique(x$sound.files))) message2(color = "red", x = paste0("(warning: the number of wave objects (", length(attr(x, "wave.objects")), ") differs from the number of sound files in the \nextended selection table (", length(unique(x$sound.files)), ")- the acoustic data seems to be corrupted)")) message2(color = "silver", x = paste("\n* A data frame (check.results) with", nrow(attr(x, "check.results")), "rows generated by check_sels() (as attribute)")) if (nrow(x) != nrow(attr(x, "check.results"))) { message2(color = "red", x = paste0("(warning: the number of rows in 'check.results' (", nrow(attr(x, "check.results")), ") differs from those in the \nextended selection table (", nrow(x), ")- the metadata seems to be corrupted)")) } if (attr(x, "by.song")[[1]]) { message2(color = "silver", x = paste0(cli::style_bold("\nAdditional information:"), "\n* The selection table was created", cli::style_italic(cli::style_bold(" by song ")), "(see 'class_extended_selection_table')")) } else { message2(color = "silver", x = paste0("\nThe selection table was created", cli::style_italic(cli::style_bold(" by element ")), "(see 'class_extended_selection_table')")) } # print number of sampling rates smp.rts <- unique(attr(x, "check.results")$sample.rate) if (length(smp.rts) == 1) { message2(color = "silver", x = paste0("* ", length(smp.rts), " sampling rate(s) (in kHz): ", paste(cli::style_bold(smp.rts), collapse = "/"))) } else { message2(paste0("* ", length(smp.rts), " sampling rate(s): ", paste(cli::style_bold(smp.rts), collapse = "/")), color = "red") } # print number of sampling rates bt.dps <- unique(attr(x, "check.results")$bits) if (length(bt.dps) == 1) { message2(color = "silver", x = paste0("* ", length(bt.dps), " bit depth(s): ", paste(cli::style_bold(bt.dps), collapse = "/"))) } else { message2(paste0("* ", length(bt.dps), " bit depth(s): ", paste(cli::style_bold(bt.dps), collapse = "/")), color = "red") } # print warbleR version if (!is.null(attr(x, "warbleR.version"))) { message2(color = "silver", x = paste0("* Created by warbleR ", attr(x, "warbleR.version"))) } else { message2(color = "silver", x = "* Created by warbleR < 1.1.21") } } ############################################################################################################## #' print method for class \code{selection_table} #' #' @param x Object of class \code{selection_table}, generated by \code{\link{selection_table}}. #' @param ... further arguments passed to or from other methods. Ignored when printing selection tables. #' @keywords internal #' #' @export #' print.selection_table <- function(x, ...) { message2(paste("Object of class", cli::style_bold("'selection_table'"))) # print call if (!is.null(attributes(x)$call)) { message2(color = "silver", x = paste("* The output of the following", "call:")) cll <- paste0(deparse(attributes(x)$call)) message2(color = "silver", x = cli::style_italic(gsub(" ", "", cll))) } message2(color = "silver", x = paste(cli::style_bold("\nContains:"), "* A selection table data frame with", nrow(x), "rows and", ncol(x), "columns:")) # print data frame # define columns to show cols <- if (ncol(x) > 6) 1:6 else seq_len(ncol(x)) kntr_tab <- knitr::kable(head(x[, cols]), escape = FALSE, digits = 4, justify = "centre", format = "pipe") for (i in seq_len(length(kntr_tab))) { message2(color = "silver", x = paste0(kntr_tab[i], "")) } if (ncol(x) > 6) { message2(color = "silver", x = paste0("... ", ncol(x) - 6, " more column(s) (", paste(colnames(x)[7:ncol(x)], collapse = ", "), ")")) } if (nrow(x) > 6) message2(color = "silver", x = paste0(if (ncol(x) <= 6) "..." else "", " and ", nrow(x) - 6, " more row(s)")) message2(color = "silver", x = paste("\n* A data frame (check.results) with", nrow(attr(x, "check.results")), "rows generated by check_sels() (as attribute)")) if (nrow(x) != nrow(attr(x, "check.results"))) { message2(color = "red", x = paste0("(warning: the number of rows in 'check.results' (", nrow(attr(x, "check.results")), ") differs from those in the \nselection table (", nrow(x), ")- the metadata seems to be corrupted)")) } # print warbleR version if (!is.null(attr(x, "warbleR.version"))) { message2(color = "silver", x = paste0("created by warbleR ", attr(x, "warbleR.version"))) } else { message2(color = "silver", x = "created by warbleR < 1.1.21") } } ############################################################################################################## #' Fix extended selection tables #' #' \code{fix_extended_selection_table} fixes extended selection tables that have lost their attributes #' @usage fix_extended_selection_table(X, Y, to.by.song = FALSE) #' @param X an object of class 'selection_table' or data frame that contains columns #' for sound file name (sound.files), selection number (selec), and start and end time of signal #' (start and end). #' @param Y an object of class 'extended_selection_table' #' @param to.by.song Logical argument to control if the attributes are formatted to a match a 'by.song' extended selection table. This is required when 'X' is created by collapsing an Y by song (see 'by.song' argument in \code{\link{selection_table}}). Mostly needed internally by some warbleR functions. #' @return An extended selection table. #' @export #' @name fix_extended_selection_table #' @examples{ #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) #' #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' #' # create extended selection table #' ext_st <- selection_table(lbh_selec_table, extended = TRUE, #' path = tempdir()) #' #' # remove attributes #' st <- as.data.frame(ext_st) #' #' # check class #' class(st) #' #' # fix selection table #' st <- fix_extended_selection_table(X = st, Y = ext_st) #' #' # check class #' class(st) #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on may-14-2018 (MAS) fix_extended_selection_table <- function(X, Y, to.by.song = FALSE) { # X is new data frame and Y the original one # add wave objects if (!is_extended_selection_table(Y)) stop2("Y must be a extended selection table") attributes(X)$wave.objects <- attributes(Y)$wave.objects[names(attributes(Y)$wave.objects) %in% X$sound.files] attributes(X)$check.results <- attributes(Y)$check.results[attributes(Y)$check.results$sound.files %in% X$sound.files, ] # add additional attributes xtr.attr <- setdiff(names(attributes(Y)[!sapply(attributes(Y), is.null)]), c("names", "row.names", "check.results", "wave.objects", "dim", "dimnames")) if (length(xtr.attr) > 0) { for (i in xtr.attr) attr(X, i) <- attr(Y, i) } attributes(X)$call <- base::match.call() # fix if by.song (used internally by spectrograms()) if (to.by.song) { new_X_attr_list <- lapply(unique(X$sound.files), function(x) { sub.Y.check <- attr(Y, "check.results")[attr(Y, "check.results")$sound.files == x, ] sub.Y.check.1 <- sub.Y.check[1, ] sub.Y.check.1$selec <- X$selec[X$sound.files == x] sub.Y.check.1$start <- min(sub.Y.check$start) sub.Y.check.1$orig.start <- min(sub.Y.check$orig.start) sub.Y.check.1$end <- max(sub.Y.check$end) sub.Y.check.1$orig.end <- max(sub.Y.check$orig.end) wave <- attr(Y, "wave.objects")[[which(names(attr(Y, "wave.objects")) == x)]] sub.Y.check.1$duration <- duration(wave) sub.Y.check.1$wav.size <- round(wave@bit * ifelse(wave@stereo, 2, 1) * [email protected] * duration(wave) / 4) / 1024 sub.Y.check.1$mar.before <- sub.Y.check$mar.before[which.min(sub.Y.check$start)] sub.Y.check.1$mar.after <- sub.Y.check$mar.before[which.max(sub.Y.check$start)] sub.Y.check.1$n.samples <- length(wave) return(sub.Y.check.1) }) X_attr <- do.call(rbind, new_X_attr_list) attributes(X)$check.results <- X_attr } return(X) } ############################################################################################################## #' rbind method for class \code{selection_table} #' #' @param ... Objects of class \code{selection_table}, generated by \code{\link{selection_table}}. #' @keywords internal #' #' @export #' rbind.selection_table <- function(..., deparse.level = 1) { mcall <- list(...) X <- mcall[[1]] Y <- mcall[[2]] if (!is_selection_table(X) | !is_selection_table(Y)) stop2("both objects must be of class 'selection_table'") if (any(paste(X$sound.files, X$selec) %in% paste(Y$sound.files, Y$selec))) stop2("Some sound files/selec are found in both selection tables") cl.nms <- intersect(names(X), names(Y)) W <- rbind(as.data.frame(X[, cl.nms, drop = FALSE]), as.data.frame(Y[, cl.nms, drop = FALSE]), make.row.names = TRUE, stringsAsFactors = FALSE ) cl.nms.cr <- intersect(names(attr(X, "check.results")), names(attr(Y, "check.results"))) attr(W, "check.results") <- rbind(attr(X, "check.results")[, cl.nms.cr, drop = FALSE], attr(Y, "check.results")[, cl.nms.cr, drop = FALSE], make.row.names = TRUE, stringsAsFactors = FALSE) attr(W, "by.song") <- attr(X, "by.song") class(W) <- class(X) attributes(W)$call <- base::match.call() return(W) } ## Example # data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) # # # # writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) # writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) # writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) # writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) # # # create extended selection table # # st <- selection_table(lbh_selec_table) # st1 <- st[1:5, ] # # st2 <- st[6:10, ] # # # fix selection table # st <- rbind(X = st1, Y = st2) ############################################################################################################## #' rbind method for class \code{extended_selection_table} #' #' @param ... Objects of class \code{extended_selection_table}, generated by \code{\link{selection_table}}. #' @keywords internal #' #' @export #' rbind.extended_selection_table <- function(..., deparse.level = 1) { mcall <- list(...) X <- mcall[[1]] Y <- mcall[[2]] if (!is_extended_selection_table(X) | !is_extended_selection_table(Y)) stop2("both objects must be of class 'extended_selection_table'") if (attr(X, "by.song")[[1]] != attr(Y, "by.song")[[1]]) stop2("both objects should have been created either 'by song' or by element' (see 'by.song' argument in selection_table())") if (any(paste(X$sound.files, X$selec) %in% paste(Y$sound.files, Y$selec))) stop2("Some sound files/selec are found in both extended selection tables") waves.X <- names(attr(X, "wave.objects")) waves.Y <- names(attr(Y, "wave.objects")) if (any(waves.X %in% waves.Y)) warning2("Some wave object names are found in both extended selection tables, they are assumed to refer to the same wave object and only one copy will be kept (use rename_est_waves() to change sound file/wave object names if needed)") cl.nms <- intersect(names(X), names(Y)) W <- rbind(as.data.frame(X[, cl.nms, drop = FALSE]), as.data.frame(Y[, cl.nms, drop = FALSE]), make.row.names = TRUE) cl.nms.cr <- intersect(names(attr(X, "check.results")), names(attr(Y, "check.results"))) attr(W, "check.results") <- rbind(attr(X, "check.results")[, cl.nms.cr, drop = FALSE], attr(Y, "check.results")[, cl.nms.cr, drop = FALSE], make.row.names = TRUE) attr(W, "wave.objects") <- c(attr(X, "wave.objects"), attr(Y, "wave.objects")) attr(W, "by.song") <- attr(X, "by.song") class(W) <- class(X) # remove duplicated if any attr(W, "wave.objects") <- attr(W, "wave.objects")[!duplicated(names(attr(W, "wave.objects")))] # fix version to current version attributes(W)$warbleR.version <- packageVersion("warbleR") attributes(W)$call <- base::match.call() return(W) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/selection_table.R
#' Measure signal-to-noise ratio #' #' \code{sig2noise} measures signal-to-noise ratio across multiple files. #' @usage sig2noise(X, mar, parallel = 1, path = NULL, pb = TRUE, type = 1, eq.dur = FALSE, #' in.dB = TRUE, before = FALSE, lim.dB = TRUE, bp = NULL, wl = 10) #' @param X object of class 'selection_table', 'extended_selection_table' or any data frame with columns #' for sound file name (sound.files), selection number (selec), and start and end time of signal #' (start and end). #' @param mar numeric vector of length 1. Specifies the margins adjacent to #' the start and end points of selection over which to measure noise. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). It can also be #' set globally using the 'parallel' option (see \code{\link{warbleR_options}}). #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. It can also be #' set globally using the 'wav.path' option (see \code{\link{warbleR_options}}). #' @param pb Logical argument to control if progress bar is shown. Default is \code{TRUE}. It can also be #' set globally using the 'pb' option (see \code{\link{warbleR_options}}). #' @param type Numeric. Determine the formula to be used to calculate the signal-to-noise ratio (S = signal #' , N = background noise): #' \itemize{ #' \item \code{1}: ratio of S mean amplitude envelope to #' N mean amplitude envelope (\code{mean(env(S))/mean(env(N))}) #' \item \code{2}: ratio of S amplitude envelope RMS (root mean square) to N amplitude envelope RMS #' (\code{rms(env(S))/rms(env(N))}) #' \item \code{3}: ratio of the difference between S amplitude envelope RMS and N amplitude envelope RMS to N amplitude envelope RMS (\code{(rms(env(S)) - rms(env(N)))/rms(env(N))}) #' } #' @param eq.dur Logical. Controls whether the noise segment that is measured has the same duration #' than the signal (if \code{TRUE}, default \code{FALSE}). If \code{TRUE} then 'mar' argument is ignored. #' @param in.dB Logical. Controls whether the signal-to-noise ratio is returned in decibels (20*log10(SNR)). #' Default is \code{TRUE}. #' @param before Logical. If \code{TRUE} noise is only measured right before the signal (instead of before and after). Default is \code{FALSE}. #' @param lim.dB Logical. If \code{TRUE} the lowest signal-to-noise would be limited to -40 dB (if \code{in.dB = TRUE}). This would remove NA's that can be produced when noise segments have a higher amplitude than the signal #' itself. Default is \code{TRUE}. #' @param bp Numeric vector of length 2 giving the lower and upper limits of a frequency bandpass filter (in kHz). Default is \code{NULL}. #' @param wl A numeric vector of length 1 specifying the window length of the spectrogram for applying bandpass. Default #' is 10. Ignored if \code{bp = NULL}. It can also be #' set globally using the 'wl' option (see \code{\link{warbleR_options}}). #' Note that lower values will increase time resolution, which is more important for signal-to-noise ratio calculations. #' @return Data frame similar to \code{\link{auto_detec}} output, but also includes a new variable #' with the signal-to-noise values. #' @export #' @name sig2noise #' @details Signal-to-noise ratio (SNR) is a measure of the level of a desired signal compared to #' background noise. The function divides the mean amplitude of the signal by #' the mean amplitude of the background noise adjacent to the signal. #' A general margin to apply before and after the acoustic signal must #' be specified. Setting margins for individual signals that have been #' previously clipped from larger files may take some optimization, as #' for calls within a larger file that are irregularly separated. When #' margins overlap with another acoustic signal nearby, the signal-to-noise #' ratio (SNR) will be inaccurate. Any SNR less than or equal to one suggests #' background noise is equal to or overpowering the acoustic signal. #' \code{\link{snr_spectrograms}} can be used to troubleshoot different noise margins. #' @examples #' { #' data(list = c("Phae.long1", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) # save sound files #' #' # specifying the correct margin is important #' # use snr_spectrograms to troubleshoot margins for sound files #' sig2noise(lbh_selec_table[grep("Phae.long1", lbh_selec_table$sound.files), ], #' mar = 0.2, #' path = tempdir() #' ) #' #' # this smaller margin doesn't overlap neighboring signals #' sig2noise(lbh_selec_table[grep("Phae.long1", lbh_selec_table$sound.files), ], #' mar = 0.1, #' path = tempdir() #' ) #' } #' #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) and Grace Smith Vidaurre #' @references {Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' \href{https://en.wikipedia.org/wiki/Signal-to-noise_ratio}{Wikipedia: Signal-to-noise ratio} #' } # last modification on aug-06-2018 (MAS) sig2noise <- function(X, mar, parallel = 1, path = NULL, pb = TRUE, type = 1, eq.dur = FALSE, in.dB = TRUE, before = FALSE, lim.dB = TRUE, bp = NULL, wl = 10) { #### set arguments from options # get function arguments argms <- methods::formalArgs(sig2noise) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X))) stop2("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") if (!all(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))) { stop2(paste(paste(c("sound.files", "selec", "start", "end")[!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop2("NAs found in start and/or end") # if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) stop2("'start' and 'end' must be numeric") # if any start higher than end stop if (any(X$end - X$start <= 0)) stop2(paste("Start is higher than or equal to end in", length(which(X$end - X$start <= 0)), "case(s)")) # if any selections longer than 20 secs stop if (any(X$end - X$start > 20)) stop2(paste(length(which(X$end - X$start > 20)), "selection(s) longer than 20 sec")) if (!is_extended_selection_table(X)) { fs <- list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE) if (length(unique(X$sound.files[(X$sound.files %in% fs)])) != length(unique(X$sound.files))) { message2(paste( length(unique(X$sound.files)) - length(unique(X$sound.files[(X$sound.files %in% fs)])), "sound file(s) not found" )) } # count number of sound files in working directory and if 0 stop d <- which(X$sound.files %in% fs) if (length(d) == 0) { stop2("The sound files are not in the working directory") } else { X <- X[d, , drop = FALSE] } } else { d <- 1:nrow(X) } # If parallel is not numeric if (!is.numeric(parallel)) stop2("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop2("'parallel' should be a positive integer") # function to run over single selection snr_FUN <- function(y, mar, bp, wl, type, before, in.dB, lim.dB) { # Read sound files to get sample rate and length r <- warbleR::read_sound_file(X = X, path = path, index = y, header = TRUE) # read sample rate f <- r$sample.rate # set margin to half of signal duration if (eq.dur) mar <- (X$end[y] - X$start[y]) / 2 # reset time coordinates of signals if lower than 0 o higher than duration stn <- X$start[y] - mar enn <- X$end[y] + mar mar1 <- mar if (stn < 0) { mar1 <- mar1 + stn stn <- 0 } mar2 <- mar1 + X$end[y] - X$start[y] if (enn > r$samples / f) enn <- r$samples / f r <- warbleR::read_sound_file(X = X, path = path, index = y, from = stn, to = enn) # add band-pass frequency filter if (!is.null(bp)) { if (bp[1] == "frange") bp <- c(X$bottom.freq[y], X$top.freq[y]) r <- seewave::ffilter(r, f = f, from = bp[1] * 1000, ovlp = 0, to = bp[2] * 1000, bandpass = TRUE, wl = wl, output = "Wave" ) } # Identify the signal signal <- seewave::cutw(r, from = mar1, to = mar2, f = f) # Identify areas before and after signal over which to measure noise noise1 <- seewave::cutw(r, from = 0, to = mar1, f = f) noise2 <- seewave::cutw(r, from = mar2, to = seewave::duration(r), f = f) if (type == 1) { # Calculate mean noise amplitude if (before) { noisamp <- mean(warbleR::envelope(x = noise1)) } else { noisamp <- mean(c( warbleR::envelope(x = noise1), warbleR::envelope(x = noise2) )) } # Calculate mean signal amplitude sigamp <- mean(warbleR::envelope(signal)) } if (type %in% 2:3) { # Calculate mean noise amplitude if (before) { noisamp <- seewave::rms(warbleR::envelope(x = noise1)) } else { noisamp <- seewave::rms(c( warbleR::envelope(x = noise1), warbleR::envelope(x = noise2) )) } sigamp <- seewave::rms(warbleR::envelope(x = signal)) if (type == 3) { sigamp <- sigamp - noisamp } } # Calculate signal-to-noise ratio snr <- sigamp / noisamp # set lowest dB limit if (in.dB & lim.dB) snr[snr <= 0] <- 0.01 if (in.dB) { return(20 * log10(snr)) } else { return(snr) } } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function SNR_l <- pblapply_wrblr_int(pbar = pb, X = 1:nrow(X), cl = cl, FUN = function(y) { snr_FUN(y, mar, bp, wl, type, before, in.dB, lim.dB) }) # Add SNR data to X z <- data.frame(X, SNR = unlist(SNR_l)) # fix extended selection table if (is_extended_selection_table(X)) z <- fix_extended_selection_table(X = z, Y = X) return(z) } ############################################################################################################## #' alternative name for \code{\link{sig2noise}} #' #' @keywords internal #' @details see \code{\link{sig2noise}} for documentation. \code{\link{sig2noise}} will be deprecated in future versions. #' @export signal_2_noise <- sig2noise
/scratch/gouwar.j/cran-all/cranData/warbleR/R/sig2noise.R
#' Simulated coordinated singing events. #' #' @description \code{sim_coor_sing} contains selections of simulated interactive singing events.The simulated events use the mean #' and standard deviation of real lekking \emph{Phaethornis longirostris} (Long-billed #' Hermit hummingbird) songs and intervals between songs (e.i gaps). Three events are simulated: overlapping signals (ovlp), #' alternating signals (altern) and non-synchronized signals (uncoor). #' #' @format \describe{ #' #' \item{sim_coor_sing}{Simulated coordinated singing events that overlap and do not overlap most of the time, #' for use with \code{test_coordination}} #' #' } #' #' @usage data(sim_coor_sing) #' "sim_coor_sing"
/scratch/gouwar.j/cran-all/cranData/warbleR/R/sim_coor_sing-data.R
#' Simulate animal vocalizations #' #' \code{simulate_songs} simulate animal vocalizations in a wave object under brownian motion frequency drift. #' @usage simulate_songs(n = 1, durs = 0.2, harms = 3, harm.amps = c(1, 0.5, 0.2), am.amps = 1, #' gaps = 0.1, freqs = 5, samp.rate = 44.1, sig2 = 0.5, #' steps = 10, bgn = 0.5, seed = NULL, diff.fun = "GBM", #' fin = 0.1, fout = 0.2, shape = "linear", selec.table = FALSE, #' file.name = NULL, path = NULL, #' hrm.freqs = c(1/2, 1/3, 2/3, 1/4, 3/4, 1/5, 1/6, 1/7, 1/8, 1/9, 1/10), #' freq.range = 4) #' @param n Number of song subunits (e.g. elements). Default is 1. #' @param durs Numeric vector with the duration of subunits in seconds. It should either be a single value (which would #' be used for all subunits) or a vector of length \code{n}. #' @param harms NUmeric vector of length 1 specifying the number of harmonics to simulate. 1 indicates that only the fundamental #' frequency harmonic will be simulated. #' @param harm.amps Numeric vector with the relative amplitude of each of the harmonics (including the fundamental frequency). #' @param am.amps Numeric vector with the relative amplitude for each step (see 'step' argument) to simulate amplitude modulation (only applied to the fundamental frequency). Should have the same length as the number of steps. Default is 1 (no amplitude modulation). #' @param gaps Numeric vector with the duration of gaps (silence between subunits) in seconds. It should either be a single value #' (which would be used for all subunits) or a vector of length \code{n + 1}. #' @param freqs Numeric vector with the initial frequency of the subunits (and ending frequency if \code{diff.fun == "BB"}) in kHz. #' It should either be a single value (which would be used for all subunits) or a vector of length \code{n}. #' @param samp.rate Numeric vector of length 1. Sets the sampling frequency of the wave object (in kHz). Default is 44.1. #' @param sig2 Numeric vector defining the sigma value of the brownian motion model. It should either be a single value #' (which would be used for all subunits) or a vector of length \code{n + 1}. Higher values will produce faster #' frequency modulations. Only applied if \code{diff.fun == "GBM"}. Default is 0.1. Check the \code{\link[Sim.DiffProc]{GBM}} function from the Sim.DiffProc package #' for more details. #' @param steps Numeric vector of length 1. Controls the mean number of segments in which each song subunit is split during #' the brownian motion process. If not all subunits have the same duration, longer units will be split in more steps (although #' the average duration subunit will have the predefined number of steps). Default is 10. #' @param bgn Numeric vector of length 1 indicating the background noise level. 0 means no additional noise will 1 means #' noise at the same amplitude than the song subunits. Default is 0.5. #' @param seed Numeric vector of length 1. This allows users to get the same results in different runs (using \code{\link[base:Random]{set.seed}} internally). Default is \code{NULL}. #' @param diff.fun Character vector of length 1 controlling the function used to simulate the brownian motion process of #' frequency drift across time. Only "BB", "GBM" and "pure.tone" are accepted at this time. Check the \code{\link[Sim.DiffProc]{GBM}} function from the Sim.DiffProc package #' for more details. #' @param fin Numeric vector of length 1 setting the proportion of the sub-unit to fade-in amplitude (value between 0 and 1). #' Default is 0.1. Note that 'fin' + 'fout' cannot be higher than 1. #' @param fout Numeric vector of length 1 setting the proportion of the sub-unit to fade-out amplitude (value between 0 and 1). #' Default is 0.2. Note that 'fin' + 'fout' cannot be higher than 1. #' @param shape Character string of length 1 controlling the shape of in and out amplitude fading of the song sub-units #' ('fin' and 'fout'). "linear" (default), "exp" (exponential), and "cos" (cosine) are currently allowed. #' @param selec.table Logical. If \code{TRUE} the function returns a list with two elements: 1) a data frame containing the start/end time, and bottom/top frequency of the sub-units and 2) the wave object containing the simulated songs. If \code{FALSE} (default) no objects are returned. Regardless of the value of this argument a .wav file is always saved in the working directory. #' @param file.name Character string for naming the ".wav" file. Ignored if #' 'selec.table' is \code{FALSE}. If not provided the date-time stamp will be used. #' @param path Character string with the directory path where the sound file should be saved. Ignored if 'selec.table' is \code{FALSE}. #' If \code{NULL} (default) then the current working directory is used. #' @param hrm.freqs Numeric vector with the frequencies of the harmonics relative to the fundamental frequency. The default values are c(1/2, 1/3, 2/3, 1/4, 3/4, 1/5, 1/6, 1/7, 1/8, 1/9, 1/10). #' @param freq.range Numeric vector of length 1 with the frequency range around the simulated frequency in which signals will modulate. Default is 4 which means that sounds will range +/- 2 kHz around the target frequency. If \code{NULL} the frequency range is not constrained. #' @return A wave object containing the simulated songs. If 'selec.table' is \code{TRUE} the function saves the wave object as a '.wav' sound file in the working directory (or 'path') and returns a list including 1) a selection table with the start/end time, and bottom/top frequency of the sub-units and 2) the wave object. #' @seealso \code{\link{query_xc}} for for downloading bird vocalizations from an online repository. #' @export #' @name simulate_songs #' @details This functions uses a geometric (\code{diff.fun == "GBM"}) or Brownian bridge (\code{diff.fun == "BB"}) motion stochastic process to simulate modulation in animal vocalizations (i.e. frequency traces across time). #' The function can also simulate pure tones (\code{diff.fun == "pure.tone"}, 'sig2' is ignored). #' Several song subunits (e.g. elements) can be simulated as well as the corresponding harmonics. Modulated sounds are adjusted so the mean frequency of the frequency contour is equal to the target frequency supplied by the user. #' @examples #' \dontrun{ #' # simulate a song with 3 elements and no harmonics #' sm_sng <- simulate_songs(n = 3, harms = 1) #' #' # plot spectro #' seewave::spectro(sm_sng) #' #' # simulate a song with 5 elements and 2 extra harmonics #' sm_sng2 <- simulate_songs(n = 5, harms = 3) #' #' # plot spectrogram #' seewave::spectro(sm_sng2) #' #' # six pure tones with frequency ranging form 4 to 6 and returning selection table #' sm_sng <- simulate_songs( #' n = 6, harms = 1, seed = 1, diff.fun = "pure.tone", #' freqs = seq(4, 6, length.out = 6), selec.table = TRUE, #' path = tempdir() #' ) #' #' # plot spectro #' seewave::spectro(sm_sng$wave, flim = c(2, 8)) #' #' # selection table #' sm_sng$selec.table #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on feb-22-2018 (MAS) simulate_songs <- function(n = 1, durs = 0.2, harms = 3, harm.amps = c(1, 0.5, 0.2), am.amps = 1, gaps = 0.1, freqs = 5, samp.rate = 44.1, sig2 = 0.5, steps = 10, bgn = 0.5, seed = NULL, diff.fun = "GBM", fin = 0.1, fout = 0.2, shape = "linear", selec.table = FALSE, file.name = NULL, path = NULL, hrm.freqs = c(1 / 2, 1 / 3, 2 / 3, 1 / 4, 3 / 4, 1 / 5, 1 / 6, 1 / 7, 1 / 8, 1 / 9, 1 / 10), freq.range = 4) { # error message if wavethresh is not installed if (!requireNamespace("Sim.DiffProc", quietly = TRUE)) { stop2("must install 'Sim.DiffProc' to use this function") } # reset working directory if (selec.table) { on.exit(options(warn = .Options$warn)) #### set arguments from options # get function arguments argms <- methods::formalArgs(simulate_songs) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) { getOption("warbleR") } else { SILLYNAME <- 0 } # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop("'path' provided does not exist") } else { path <- normalizePath(path) } } if (length(durs) != n & length(durs) != 1) { stop("length of 'durs' should be 1 or equal to 'n'") } if (length(am.amps) != steps & length(am.amps) != 1) { stop("length of 'am.amps' should be 1 or equal to number of 'steps'") } if (length(harm.amps) != harms & harms > 1) { stop("length of 'harm.amps' should be equal to 'harms'") } if (length(gaps) != n + 1 & length(gaps) != 1) { stop("length of 'gaps' should be 1 or equal to 'n' + 1") } if (any(gaps <= 0)) { stop("'gaps' must be higher than 0") } if (length(durs) == 1 & n != 1) { durs <- rep(durs, n) } if (length(am.amps) == 1 & steps != 1) { am.amps <- rep(am.amps, steps) } if (length(am.amps) > 1) { am.amps <- am.amps / max(am.amps) } if (length(sig2) == 1 & n != 1) { sig2 <- rep(sig2, n) } if (length(gaps) == 1) { gaps <- rep(gaps, n + 1) } if (length(freqs) == 1 & n != 1) { freqs <- rep(freqs, n) } if (harms < 1) { stop("'harms' should at least 1") } if (harms > 10) { harms <- 10 } if (harms > 1) { harm.amps <- harm.amps / max(harm.amps) } if (!diff.fun %in% c("BB", "GBM", "pure.tone")) stop2("'diff.fun' must be 'BB', 'GBM' or 'pure.tone'") # set diffusion function if (diff.fun == "GBM") { df_fn <- Sim.DiffProc::GBM } if (diff.fun == "BB") { df_fn <- Sim.DiffProc::BB } if (!is.null(seed)) { seeds <- 1:(3 * n) + seed } # harmonics frequencies relative to fundamental hrm_freqs <- sort(1 / hrm.freqs) # simulate frequency contour and amplitude envelope of song elements and gaps frq_amp <- lapply(seq_len(n), function(x) { # number of freq values N <- round(x = steps * durs[x] / mean(durs), digits = 0) # simulate frequency modulation if (diff.fun != "pure.tone") { sng_frq <- as.vector((df_fn( N = ifelse(N < 2, 2, N), sigma = sig2[x] ) * sample(c(-1, 1), 1)) + freqs[x]) # force to be within freq.range if (!is.null(freq.range)) sng_frq <- (sng_frq - min(sng_frq)) / max(sng_frq - min(sng_frq)) * freq.range # fix frequency contour so it is centered in the is equal to target frequency sng_frq <- sng_frq + freqs[x] - (max(sng_frq) - min(sng_frq)) / 2 } else { sng_frq <- rep(freqs[x], ifelse(N < 2, 2, N)) } # patch to avoid negative numbers sng_frq <- abs(sng_frq) sng_frq[sng_frq == 0] <- 0.01 app_n <- round(durs[x] * (samp.rate * 1000), 0) sng_frq <- stats::spline(x = sng_frq, n = ifelse(app_n < 2, 2, app_n))$y frng <- range(sng_frq) sng_amp <- stats::spline(x = am.amps, n = length(sng_frq))$y * harm.amps[1] # if (fin != 0 & fout != 0 & length(unique(am.amps)) == 1) if (fin != 0 & fout != 0) { sng_amp <- fade_env_wrblr_int( nvlp = sng_amp, fin = fin, fout = fout, shape = shape ) } # add starting gap if (x == 1) { if (!is.null(seed)) { set.seed(seeds[x + n]) } gp_frq1 <- sample(1:((samp.rate * 1000) / 2), round(gaps[1] * (samp.rate * 1000), 0), replace = TRUE) sng_frq <- c(gp_frq1, sng_frq) gp_amp1 <- rep(x = 0.000001, round(gaps[1] * (samp.rate * 1000), 0)) sng_amp <- c(gp_amp1, sng_amp) } if (!is.null(seed)) { set.seed(seeds[x + (n * 2)]) } gp_frq <- sample(1:((samp.rate * 1000) / 2), round(gaps[x + 1] * (samp.rate * 1000), 0), replace = TRUE) gp_amp <- rep(x = 0.000001, round(gaps[x + 1] * (samp.rate * 1000), 0)) frq <- c(sng_frq, gp_frq) amp <- c(sng_amp, gp_amp) return(data.frame( frq, amp, bottom.freq = round(frng[1], 3), top.freq = round(frng[2], 3), subunit = x )) }) frq_amp <- do.call(rbind, frq_amp) # add noise ns <- noisew( f = (samp.rate * 1000), d = nrow(frq_amp) / (samp.rate * 1000) ) # fix noise samples to match songs while (length(ns) < nrow(frq_amp)) { ns[length(ns) + 1] <- sample(ns, 1) } while (length(ns) > nrow(frq_amp)) { ns <- ns[1:(length(ns) - 1)] } # standardize noise amplitude (range = c(0, bgn)) ns <- ns + abs(min(ns)) ns <- ns / max(ns) ns <- ns * bgn frq_amp$amp <- (frq_amp$amp + ns) * 1000 # create WAV wv <- synth2( env = frq_amp$amp, ifreq = frq_amp$frq * 1000, f = (samp.rate * 1000), plot = FALSE ) if (harms > 1) { for (i in seq_len(harms - 1)) { wv <- wv + synth2( env = frq_amp$amp / harm.amps[1] * harm.amps[i + 1], ifreq = frq_amp$frq * 1000 * hrm_freqs[i], f = (samp.rate * 1000), plot = FALSE ) } } wv <- tuneR::Wave( left = wv, samp.rate = (samp.rate * 1000), bit = 16 ) # normalize wv <- tuneR::normalize(wv, unit = "16") # create selection table and save sound file if (selec.table) { if (is.null(file.name)) { file.name <- gsub(" ", "_", paste0(format(Sys.time()), ".wav")) } else { file.name <- paste0(file.name, ".wav") } # fix name if file already exists nchr <- nchar(file.name) - 4 x <- 1 while (file.exists(file.path(path, file.name))) { file.name <- paste0(substr(file.name, 0, nchr), "_", x, ".wav") x <- x + 1 } options(warn = -1) trywrite <- try(writeWave( # wrapped in try to pass testing in windows object = wv, filename = file.path(path, file.name), extensible = FALSE ), silent = TRUE) start <- cumsum(c(gaps[1], durs[-length(durs)] + gaps[-c(1, length(gaps))])) st <- data.frame( sound.files = file.name, selec = 1:n, start, end = c(start + durs), stringsAsFactors = FALSE, bottom.freq = c(tapply( frq_amp$bottom.freq, frq_amp$subunit, mean )), top.freq = c(tapply( frq_amp$top.freq, frq_amp$subunit, mean )) ) } if (selec.table) { return(list(selec.table = st, wave = wv)) } else { return(wv) } } ############################################################################################################## #' alternative name for \code{\link{simulate_songs}} #' #' @keywords internal #' @details see \code{\link{simulate_songs}} for documentation. \code{\link{sim_songs}} will be deprecated in future versions. #' @export sim_songs <- simulate_songs
/scratch/gouwar.j/cran-all/cranData/warbleR/R/simulate_songs.R
#' Spectrograms with background noise margins #' #' \code{snr_spectrograms} creates spectrograms to visualize margins over which background noise #' will be measured by \code{\link{sig2noise}}. #' @usage snr_spectrograms(X, wl = 512, flim = NULL, wn = "hanning", ovlp = 70, #' inner.mar = c(5, 4, 4, 2), outer.mar = c(0, 0, 0, 0), picsize = 1, #' res = 100, cexlab = 1, title = TRUE, before = FALSE, eq.dur = FALSE, #' propwidth= FALSE, xl = 1, osci = FALSE, gr = FALSE, sc = FALSE, mar = 0.2, #' snrmar = 0.1, it = "jpeg", parallel = 1, path = NULL, pb = TRUE) #' @param X 'selection_table', 'extended_selection_table' or any data frame with columns #' for sound file name (sound.files), selection number (selec), and start and end time of signal #' (start and end). #' @param wl A numeric vector of length 1 specifying the window length of the spectrogram, default #' is 512. #' @param flim A numeric vector of length 2 for the frequency limit in kHz of #' the spectrogram, as in \code{\link[seewave]{spectro}}. Default is \code{NULL}. ##' @param wn Character vector of length 1 specifying window name. Default is #' "hanning". See function \code{\link[seewave]{ftwindow}} for more options. #' @param ovlp Numeric vector of length 1 specifying \% of overlap between two #' consecutive windows, as in \code{\link[seewave]{spectro}}. Default is 70. #' @param inner.mar Numeric vector with 4 elements, default is c(5,4,4,2). #' Specifies number of lines in inner plot margins where axis labels fall, #' with form c(bottom, left, top, right). See \code{\link[graphics]{par}}. #' @param outer.mar Numeric vector with 4 elements, default is c(0,0,0,0). #' Specifies number of lines in outer plot margins beyond axis labels, with #' form c(bottom, left, top, right). See \code{\link[graphics]{par}}. #' @param picsize Numeric argument of length 1, controls relative size of #' spectrogram. Default is 1. #' @param res Numeric argument of length 1 that controls image resolution. #' Default is 100 (faster) although 300 - 400 is recommended for publication/ #' presentation quality. #' @param cexlab Numeric vector of length 1 specifying relative size of axis #' labels. See \code{\link[seewave]{spectro}}. #' @param title Logical argument to add a title to individual spectrograms. #' Default is \code{TRUE}. #' @param before Logical. If \code{TRUE} noise is only measured right before the signal (instead of before and after). Default is \code{FALSE}. #' @param eq.dur Logical. Controls whether the noise segment that is measured has the same duration #' than the signal (if \code{TRUE}, default \code{FALSE}). If \code{TRUE} then 'snrmar' argument is ignored. #' @param propwidth Logical argument to scale the width of spectrogram #' proportionally to duration of the selected call. Default is \code{FALSE}. #' @param xl Numeric vector of length 1, a constant by which to scale #' spectrogram width if propwidth = \code{TRUE}. Default is 1. #' @param osci Logical argument to add an oscillogram underneath spectrogram, as #' in \code{\link[seewave]{spectro}}. Default is \code{FALSE}. #' @param gr Logical argument to add grid to spectrogram. Default is \code{FALSE}. #' @param sc Logical argument to add amplitude scale to spectrogram, default is #' \code{FALSE}. #' @param mar Numeric vector of length 1. Specifies the margins adjacent to the #' start and end points of the selections to define spectrogram limits. Default is 0.2. If snrmar #' is larger than mar, then mar is set to be equal to snrmar. #' @param snrmar Numeric vector of length 1. Specifies the margins adjacent to the start and end #' points of the selections where noise will be measured. Default is 0.1. #' @param it A character vector of length 1 giving the image type to be used. Currently only #' "tiff" and "jpeg" are admitted. Default is "jpeg". #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @return Spectrograms per selection marked with margins where background noise will be measured. #' @family spectrogram creators #' @seealso \code{\link{track_freq_contour}} for creating spectrograms to visualize #' frequency measurements by \code{\link{spectro_analysis}}, \code{\link{spectrograms}} for #' creating spectrograms #' @export #' @name snr_spectrograms #' @details This function can be used to test different margins to facilitate #' accurate SNR measurements when using \code{\link{sig2noise}} down the line. #' Setting margins for individual calls that have been previously clipped from #' larger files may take some optimization, as for calls within a #' larger file that are irregularly separated. Setting inner.mar to #' c(4,4.5,2,1) and outer.mar to c(4,2,2,1) works well when picsize = 2 or 3. #' Title font size, inner.mar and outer.mar (from \code{mar} and \code{oma} in \code{par}) don't work well #' when osci or sc = \code{TRUE}, this may take some optimization by the user. #' @examples #' \dontrun{ #' data(list = c("Phae.long1", "Phae.long2", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) # save sound.files #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' #' # make Phae.long1 and Phae.long2 spectrograms #' # snrmar needs to be smaller before moving on to sig2noise() #' #' snr_spectrograms(lbh_selec_table, #' flim = c(0, 14), inner.mar = c(4, 4.5, 2, 1), #' outer.mar = c(4, 2, 2, 1), picsize = 2, res = 300, cexlab = 2, mar = 0.2, #' snrmar = 0.1, it = "jpeg", wl = 300, path = tempdir() #' ) #' #' # make only Phae.long1 spectrograms #' # snrmar now doesn't overlap neighboring signals #' #' snr_spectrograms(lbh_selec_table[grepl(c("Phae.long1"), lbh_selec_table$sound.files), ], #' flim = c(3, 14), inner.mar = c(4, 4.5, 2, 1), outer.mar = c(4, 2, 2, 1), #' picsize = 2, res = 300, cexlab = 2, mar = 0.2, snrmar = 0.01, wl = 300, #' path = tempdir() #' ) #' #' # check this folder! #' tempdir() #' } #' @references {Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' \href{https://en.wikipedia.org/wiki/Signal-to-noise_ratio}{Wikipedia: Signal-to-noise ratio} #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) and Grace Smith Vidaurre # last modification on aug-06-2018 (MAS) snr_spectrograms <- function(X, wl = 512, flim = NULL, wn = "hanning", ovlp = 70, inner.mar = c(5, 4, 4, 2), outer.mar = c(0, 0, 0, 0), picsize = 1, res = 100, cexlab = 1, title = TRUE, before = FALSE, eq.dur = FALSE, propwidth = FALSE, xl = 1, osci = FALSE, gr = FALSE, sc = FALSE, mar = 0.2, snrmar = 0.1, it = "jpeg", parallel = 1, path = NULL, pb = TRUE) { #### set arguments from options # get function arguments argms <- methods::formalArgs(snr_spectrograms) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X))) stop2("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") if (!all(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))) { stop2(paste(paste(c("sound.files", "selec", "start", "end")[!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop2("NAs found in start and/or end") # if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) stop2("'start' and 'end' must be numeric") # if any start higher than end stop if (any(X$end - X$start <= 0)) stop2(paste("Start is higher than or equal to end in", length(which(X$end - X$start <= 0)), "case(s)")) # if it argument is not "jpeg" or "tiff" if (!any(it == "jpeg", it == "tiff")) stop2(paste("Image type", it, "not allowed")) # if any selections longer than 20 secs stop if (any(X$end - X$start > 20)) stop2(paste(length(which(X$end - X$start > 20)), "selection(s) longer than 20 sec")) options(show.error.messages = TRUE) # return warning if not all sound files were found if (!is_extended_selection_table(X)) { fs <- list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE) if (length(unique(X$sound.files[(X$sound.files %in% fs)])) != length(unique(X$sound.files))) { message2(paste( length(unique(X$sound.files)) - length(unique(X$sound.files[(X$sound.files %in% fs)])), "sound file(s) not found" )) } # count number of sound files in working directory and if 0 stop d <- which(X$sound.files %in% fs) if (length(d) == 0) { stop2("The sound files are not in the working directory") } else { X <- X[d, , drop = FALSE] } } # If parallel is not numeric if (!is.numeric(parallel)) stop2("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop2("'parallel' should be a positive integer") snrspeFUN <- function(i, X, wl, flim, ovlp, inner.mar, outer.mar, picsize, res, cexlab, xl, mar, snrmar, before, eq.dur) { # Read sound files to get sample rate and length r <- warbleR::read_sound_file(X = X, path = path, index = i, header = TRUE) f <- r$sample.rate fl <- flim # in case flim its higher than can be due to sampling rate if (is.null(fl)) { fl <- c(0, f / 2000) } if (fl[2] > f / 2000) fl[2] <- f / 2000 # set margin if eq.dur if (eq.dur) snrmar <- X$end[i] - X$start[i] # Set mar equals to snrmar if is smaller if (mar < snrmar) mar <- snrmar # reset coordinates of signals st <- X$start[i] - mar en <- X$end[i] + mar mar1 <- mar if (st < 0) { mar1 <- mar1 + st st <- 0 } mar2 <- mar1 + X$end[i] - X$start[i] if (en > r$samples / f) en <- r$samples / f r <- warbleR::read_sound_file(X = X, path = path, index = i, from = st, to = en) # Spectrogram width can be proportional to signal duration if (propwidth) pwc <- (10.16) * ((en - st) / 0.27) * xl * picsize else pwc <- (10.16) * xl * picsize img_wrlbr_int( filename = paste(X$sound.files[i], "-", X$selec[i], "-", "snr.", it, sep = ""), path = path, width = pwc, height = (10.16) * picsize, units = "cm", res = res ) # Change relative heights of rows for spectrogram when osci = TRUE if (osci == TRUE) hts <- c(3, 2) else hts <- NULL # Change relative widths of columns for spectrogram when sc = TRUE if (sc == TRUE) wts <- c(3, 1) else wts <- NULL old.par <- par(no.readonly = TRUE) # par settings which could be changed. on.exit(par(old.par)) # Change inner and outer plot margins par(mar = inner.mar) par(oma = outer.mar) # Generate spectrogram using seewave seewave::spectro(r, f = f, wl = wl, ovlp = ovlp, collevels = seq(-40, 0, 0.5), heights = hts, wn = "hanning", widths = wts, palette = seewave::reverse.gray.colors.2, osc = osci, grid = gr, scale = sc, collab = "black", cexlab = cexlab, cex.axis = 0.5 * picsize, tlab = "Time (s)", flab = "Frequency (kHz)", flim = fl, alab = "", trel = FALSE ) if (title) { title(paste(X$sound.files[i], "-", X$selec[i], "-", "snr", sep = ""), cex.main = cexlab) } # Add boxes to visualize noise region polygon(x = rep(c(mar1 - snrmar, mar1), each = 2), y = c(fl, sort(fl, decreasing = TRUE)), lty = 3, border = "#07889B", lwd = 1.3, col = adjustcolor("#07889B", alpha.f = 0.15)) text(x = mar1 - (snrmar * 0.5), y = fl[1] + fl[2] / 4, labels = "Noise", col = "#07889B", pos = 3) if (!before) { polygon(x = rep(c(mar2, mar2 + snrmar), each = 2), y = c(fl, sort(fl, decreasing = TRUE)), lty = 3, border = "#07889B", lwd = 1.3, col = adjustcolor("#07889B", alpha.f = 0.15)) text(x = mar2 + (snrmar * 0.5), y = fl[1] + fl[2] / 4, labels = "Noise", col = "#07889B", pos = 3) } dev.off() return(NULL) } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function out <- pblapply_wrblr_int(pbar = pb, X = 1:nrow(X), cl = cl, FUN = function(i) { snrspeFUN(X = X, i = i, wl = wl, flim = flim, ovlp = ovlp, inner.mar = inner.mar, outer.mar = outer.mar, picsize = picsize, res = res, cexlab = cexlab, xl = xl, mar = mar, snrmar = snrmar, before, eq.dur) }) } ############################################################################################################## #' alternative name for \code{\link{snr_spectrograms}} #' #' @keywords internal #' @details see \code{\link{snr_spectrograms}} for documentation. \code{\link{snr_spectrograms}} will be deprecated in future versions. #' @export snrspecs <- snr_spectrograms ############################################################################################################## #' alternative name for \code{\link{snr_spectrograms}} #' #' @keywords internal #' @details see \code{\link{snr_spectrograms}} for documentation. \code{\link{snr_specs}} will be deprecated in future versions. #' @export snr_specs <- snr_spectrograms
/scratch/gouwar.j/cran-all/cranData/warbleR/R/snr_spectrograms.R
#' Calculates acoustic parameters at the song level #' #' \code{song_analysis} calculates descriptive statistics of songs or other higher levels of organization in the signals. #' @usage song_analysis(X = NULL, song_colm = "song",mean_colm = NULL, min_colm = NULL, #' max_colm = NULL, elm_colm = NULL, elm_fun = NULL, sd = FALSE, parallel = 1, pb = TRUE, #' na.rm = FALSE, weight = NULL) #' @param X 'selection_table', 'extended_selection_table' (created 'by.song') or data frame with the following columns: 1) "sound.files": name of the sound #' files, 2) "selec": number of the selections, 3) "start": start time of selections, 4) "end": #' end time of selections. #' @param song_colm Character string with the column name containing song labels. #' It can be used to label any hierarchical level at which parameters need to be calculated (e.g. syllables, phrases). #' Note that #' the function assumes that song labels are not repeated within a sound file. #' @param mean_colm Numeric vector with the index of the columns that will be averaged. If \code{NULL} the mean of all numeric columns in 'X' is returned. #' @param min_colm Character vector with the name(s) of the columns for which the minimum #' value is needed. Default is \code{NULL}. #' @param max_colm Character vector with the name(s) of the columns for which the maximum #' value is needed. Default is \code{NULL}. #' @param elm_colm Character vector with the name(s) of the columns identifying the element labels (i.e. element types). If supplied 'unq.elms' and 'mean.elm.count' are returned. Default is \code{NULL}. #' @param elm_fun Function to be applied to the sequence of elements composing a song. Default is \code{NULL}. Ignored if 'elm_colm' is not supplied. The name of the column containing the function's output is "elm_fun'. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param sd Logical value indicating whether standard deviation is also returned for #' variables in which averages are reported. Default is \code{FALSE}. #' @param pb Logical argument to control progress bar and messages. Default is \code{TRUE}. #' @param na.rm Logical value indicating whether 'NA' values should be ignored for calculations. #' @param weight Character vector defining 1 or more numeric vectors to weight average #' measurements (i.e. song parameters). Names of numeric columns in 'X' can also be used. See \code{\link[stats]{weighted.mean}}. #' for more details. Default is \code{NULL} (unweighted average). #' @return A data frame similar to the input 'X' data frame, but in this case each row corresponds to a single song. The data frame contains the mean or extreme #' values for numeric columns for each song. Columns that will be averaged can be defined with #' 'mean_colm' (otherwise all numeric columns are used). Columns can be #' weighted by other columns in the data set (e.g. duration, frequency range). In addition, the function returns the following song level parameters: #' \itemize{ #' \item \code{elm.duration}: mean length of elements (in s) #' \item \code{song.duration}: length of song (in s) #' \item \code{num.elms}: number of elements (or song units) #' \item \code{start}: start time of song (in s) #' \item \code{end}: end time of song (in s) #' \item \code{bottom.freq}: lowest 'bottom.freq' from all song elements (in kHz) #' \item \code{top.freq}: highest 'top.freq' from all song elements (in kHz) #' \item \code{freq.range}: difference between song's 'top.freq' and 'bottom.freq' (in kHz) #' \item \code{song.rate}: number of elements per second (NA if only 1 element). Calculated as the number of elements in the 'song' divided by the duration of the song. In this case song duration is calculated as the time between the start of the first element and the start of the last element, which provides a rate that is less affected by the duration of individual elements. Note that this calculation is different than that from 'song.duration' above. #' \item \code{gap.duration}: average length of gaps (i.e. silences) in between elements #' (in s, NA if only 1 element) #' \item \code{elm.types}: number of element types (i.e. number of unique types, only if 'elm_colm' is supplied) #' \item \code{mean.elm.count}: mean number of times element types are found (only if 'elm_colm' is supplied) #' } #' This function assumes that song labels are not repeated within a sound file. #' #' @export #' @name song_analysis #' @details The function calculates average or extreme values of acoustic parameters of #' elements in a song or other level of organization in the signals. #' @seealso \code{\link{spectro_analysis}} #' @examples{ #' # get warbleR sound file examples #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' #' # add a 'song' column #' lbh_selec_table$song <- c("song1", "song1", "song1", "song2", #' "song2", "song3", "song3", "song3", "song4", "song4", "song4") #' #' # measure acoustic parameters #' sp <- spectro_analysis(lbh_selec_table[1:8, ], bp = c(1, 11), 300, fast = TRUE, path = tempdir()) #' #' # add song data #' sp <- merge(sp, lbh_selec_table[1:8, ], by = c("sound.files", "selec")) #' #' # caculate song-level parameters for all numeric parameters #' song_analysis(X = sp, song_colm = "song", parallel = 1, pb = TRUE) #' #' # caculate song-level parameters selecting parameters with mean_colm #' song_analysis(X = sp, song_colm = "song",mean_colm = c("dfrange", "duration"), #' parallel = 1, pb = TRUE) #' #' # caculate song-level parameters for selecting parameters with mean_colm, max_colm #' # and min_colm and weighted by duration #' song_analysis(X = sp, weight = "duration", song_colm = "song", #' mean_colm = c("dfrange", "duration"), min_colm = "mindom", max_colm = "maxdom", #' parallel = 1, pb = TRUE) #' #' # with two weights #' song_analysis(X = sp, weight = c("duration", "dfrange"), song_colm = "song", #' mean_colm = c("kurt", "sp.ent"), parallel = 1, pb = TRUE) #' #' # with two weights no progress bar #' song_analysis(X = sp, weight = c("duration", "dfrange"), song_colm = "song", #' mean_colm = c("kurt", "sp.ent"), parallel = 1, pb = FALSE) #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on may-8-2018 (MAS) song_analysis <- function(X = NULL, song_colm = "song", mean_colm = NULL, min_colm = NULL, max_colm = NULL, elm_colm = NULL, elm_fun = NULL, sd = FALSE, parallel = 1, pb = TRUE, na.rm = FALSE, weight = NULL) { #### set arguments from options # get function arguments argms <- methods::formalArgs(song_analysis) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X))) stop2("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") # if extended only by song if (is_extended_selection_table(X)) { if (!attributes(X)$by.song$by.song) stop2("extended selection tables must be created 'by.song' to be used in song.param()") } # if parallel is not numeric if (!is.numeric(parallel)) stop2("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop2("'parallel' should be a positive integer") if (!any(names(X) == song_colm)) stop2("'song_colm' not found") # check suplied column names if (!is.null(mean_colm) & !any(names(X) %in% mean_colm)) stop2("at least 1 'mean_colm' supplied not found") if (!is.null(min_colm) & !any(names(X) %in% min_colm)) stop2("at least 1 'min_colm' supplied not found") if (!is.null(max_colm) & !any(names(X) %in% max_colm)) stop2("at least 1 'max_colm' supplied not found") if (!is.null(elm_colm) & !any(names(X) == elm_colm)) stop2("'elm_colm' not found") if (!is.null(elm_colm) & !is.null(elm_fun) & if (!is.null(elm_fun)) !is.function(get(as.character(quote(elm_fun)))) else FALSE) stop2("'elm_fun' not found") if (song_colm == "sound.files") { X$song <- X$sound.files song_colm <- "song" } # stop if any song is found in more than 1 sound file # if (any(tapply(X$sound.files, X[,song_colm], function(x) length(unique(x))) > 1)) # stop2("At least 1 'song' is found in multiple sound files, which is not allowed. \n Try `tapply(X$sound.files, X$song, function(x) length(unique(x)))` to find 'problematic' songs (those higher than 1)") if (!all(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))) { stop2(paste(paste(c("sound.files", "selec", "start", "end")[!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } # if (is.null(X$duration)) X$duration <- X$end - X$start if (!any(names(X) %in% weight) & !is.null(weight)) stop2("'weight' column not found") if (!is.null(mean_colm)) { if (!all(sapply(X[, mean_colm], is.numeric))) stop2("not all columns in 'mean_colm' are numeric") } songparam.FUN <- function(Y, song_colm, mean_colm, min_colm, max_colm, weight, na.rm) { Z <- Y[1, , drop = FALSE] # set weight and calculated mean parameters if (!is.null(weight) & nrow(Y) > 1) { wts <- Y[, weight, drop = FALSE] if (length(weight) > 1) { wts <- apply(wts, 2, function(e) e / max(e, na.rm = TRUE)) wts <- apply(wts, 1, prod) } wts <- as.vector(unlist(wts)) } else { wts <- rep(1, nrow(Y)) } if (is.null(mean_colm)) { mean_colm <- names(X)[(sapply(X, is.numeric))] mean_colm <- as.vector(mean_colm[!mean_colm %in% c("selec", "channel", song_colm, "start", "end", "top.freq", "bottom.freq", min_colm, max_colm)]) mean_colm <- mean_colm[!is.na(mean_colm)] } for (u in mean_colm) Z[, u] <- stats::weighted.mean(x = as.vector(c(Y[, u, drop = TRUE])), w = wts, na.rm = na.rm) if (sd) { W <- Z for (u in mean_colm) W[, u] <- stats::sd(x = as.vector(c(Y[, u, drop = TRUE])), na.rm = na.rm) names(W) <- paste0("sd.", names(W)) } # minimums if (!is.null(min_colm)) { for (u in min_colm) Z[, u] <- min(x = as.vector(c(Y[, u, drop = TRUE])), na.rm = na.rm) } # maximums if (!is.null(max_colm)) for (u in max_colm) Z[, u] <- max(x = as.vector(c(Y[, u, drop = TRUE])), na.rm = na.rm) colm <- c(mean_colm, min_colm, max_colm) # sort columns Z <- Z[, c(names(Z) %in% c("sound.files", song_colm, colm))] Z <- Z[, match(c("sound.files", song_colm, colm), names(Z))] # add sd variables if (sd) { Z <- cbind(Z, W[, paste0("sd.", mean_colm), drop = FALSE]) } Z$num.elms <- nrow(Y) Z$start <- min(Y$start) Z$end <- max(Y$end) Z$elm.duration <- mean(Y$end - Y$start) if (!is.null(Y$bottom.freq)) { try(Z$bottom.freq <- min(Y$bottom.freq, na.rm = na.rm), silent = TRUE) try(Z$top.freq <- max(Y$top.freq, na.rm = na.rm), silent = TRUE) try(Z$freq.range <- Z$top.freq - Z$bottom.freq, silent = TRUE) } Z$song.duration <- Z$end - Z$start Z$song.rate <- if (Z$num.elms == 1) NA else Z$num.elms / (Y$start[nrow(Y)] - Y$start[1]) Z$gap.duration <- if (Z$num.elms == 1) NA else mean(Y$start[-1] - Y$end[-nrow(Y)]) if (sd) { Z$sd.gap.duration <- if (Z$num.elms == 1) NA else sd(Y$start[-1] - Y$end[-nrow(Y)]) Z$sd.elm.duration <- sd(Y$end - Y$start) } # add element parameters if (!is.null(elm_colm)) { Z$elm.types <- length(unique(Y[, elm_colm])) Z$mean.elm.count <- Z$num.elms / Z$elm.types # run element function if (!is.null(elm_fun)) { Z$......temp.name.... <- tapply(Y[, elm_colm], Y[, song_colm], elm_fun) names(Z)[names(Z) == "......temp.name...."] <- as.character(quote(elm_fun)) } } # rename columns containing min or max if (!is.null(min_colm)) { names(Z)[names(Z) %in% min_colm] <- paste0("min.", min_colm) } if (!is.null(max_colm)) { names(Z)[names(Z) %in% max_colm] <- paste0("max.", max_colm) } return(Z) } X$.....SONGX... <- paste(X$sound.files, X[, song_colm]) # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function out <- pblapply_wrblr_int(pbar = pb, X = unique(X$.....SONGX...), cl = cl, FUN = function(i) { # subset by song label Y <- X[X$.....SONGX... == i, , drop = FALSE] # order Y by start Y <- Y[order(Y$start), ] # make it a data frame just in case Y <- as.data.frame(Y) return(songparam.FUN(Y, song_colm, mean_colm, min_colm, max_colm, weight, na.rm)) }) df <- do.call(rbind, out) df <- as.data.frame(df) # rename columns rownames(df) <- 1:nrow(df) # add selec label df$selec <- 1 # reorder columns df <- sort_colms(df) return(df) } ############################################################################################################## #' alternative name for \code{\link{song_analysis}} #' #' @keywords internal #' @details see \code{\link{song_analysis}} for documentation. \code{\link{song_param}} will be deprecated in future versions. #' @export song_param <- song_analysis
/scratch/gouwar.j/cran-all/cranData/warbleR/R/song_analysis.R
#' Sort columns in a more intuitive order #' #' \code{sort_colms} sorts selection table columns in a more intuitive order. #' @usage sort_colms(X) #' @param X Data frame containing columns for sound file (sound.files), selection #' (selec), start and end time of signals ('start' and 'end') and low and high #' frequency ('bottom.freq' and 'top.freq', optional). See the example data 'lbh_selec_table'. #' @return The same data as in the input data frame but with the most relevant information #' for acoustic analysis located in the first columns. #' @details The function returns the data from the input data frame with the most relevant information #' for acoustic analysis located in the first columns. The priority order for column names is: "sound.files", "channel", "selec", "start", "end", "top.freq", and "bottom.freq". #' @export #' @name sort_colms #' @examples #' library(warbleR) #' data("selec.table") #' #' # mess column order #' selec.table <- selec.table[, sample(seq_len(ncol(selec.table)))] #' #' # check names #' names(selec.table) #' #' selec.table <- sort_colms(X = selec.table) #' #' # check names again #' names(selec.table) #' #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on mar-10-2018 sort_colms <- function(X) { if (any(duplicated(names(X)))) stop(" Duplicated column names must be fixed first") mtch <- match(c("sound.files", "channel", "selec", "start", "end", "top.freq", "bottom.freq"), names(X)) mtch <- mtch[!is.na(mtch)] X <- X[, c(mtch, setdiff(seq_len(ncol(X)), mtch))] return(X) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/sort_colms.R
#' Measure relative sound pressure level #' #' \code{sound_pressure_level} measures relative (uncalibrated) sound pressure level in signals referenced in a selection table. #' @usage sound_pressure_level(X, reference = 20, parallel = 1, path = NULL, pb = TRUE, #' type = "single", wl = 100, bp = NULL, remove.bgn = FALSE, mar = NULL, envelope = "abs") #' @param X object of class 'selection_table', 'extended_selection_table' or any data frame with columns #' for sound file name (sound.files), selection number (selec), and start and end time of signal #' (start and end). #' @param reference Numeric vector of length 1 indicating the pressure (in µPa) to be used as reference. Alternatively, a character vector with the name of a numeric column containing reference values for each row can be supplied. Default is 20 (µPa). NOT YET IMPLEMENTED. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). It can also be #' set globally using the 'parallel' option (see \code{\link{warbleR_options}}). #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. It can also be #' set globally using the 'wav.path' option (see \code{\link{warbleR_options}}). #' @param pb Logical argument to control if progress bar is shown. Default is \code{TRUE}. It can also be #' set globally using the 'pb' option (see \code{\link{warbleR_options}}). #' @param type Character string controlling how SPL is measured: #' \itemize{ #' \item \code{single}: single SPL value obtained on the entire signal. Default. #' \item \code{mean}: average of SPL values measured across the signal. #' \item \code{peak}: maximum of several SPL values measured across the signal. #' } #' @param wl A numeric vector of length 1 specifying the spectrogram window length. Default is 512. #' @param bp Numeric vector of length 2 giving the lower and upper limits of a frequency bandpass filter (in kHz). Alternatively, when set to 'freq.range', the function will use the 'bottom.freq' and 'top.freq' for each signal as the bandpass range. Default is \code{NULL} (no bandpass filter). #' @param remove.bgn Logical argument to control if SPL from background noise is excluded from the measured signal SPL. Default is \code{FALSE}. #' @param mar numeric vector of length 1. Specifies the margins adjacent to #' the start point of selection over which to measure background noise. #' @param envelope Character string vector with the method to calculate amplitude envelopes (in which SPL is measured), as in \code{\link[seewave]{env}}. Must be either 'abs' (absolute envelope, default) or 'hil' (Hilbert transformation). #' @return The object supplied in 'X' with a new variable #' with the sound pressure level values ('SPL' or 'peak.amplitude' column, see argument 'peak.amplitude') in decibels. #' @export #' @name sound_pressure_level #' @encoding UTF-8 #' @details Sound pressure level (SPL) is a logarithmic measure of the effective pressure of a sound relative to a reference, so it's a measure of sound intensity. SPL is measured as the root mean square of the amplitude vector, and as such is only a useful metric of the variation in loudness for signals within the same recording (or recorded with the same equipment and gain). #' @seealso \code{\link{sig2noise}}. #' @examples #' { #' data(list = c("Phae.long1", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) # save sound files #' #' spl <- sound_pressure_level( #' X = lbh_selec_table[grep("Phae.long1", lbh_selec_table$sound.files), ], #' parallel = 1, pb = TRUE, path = tempdir() #' ) #' } #' #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) and Grace Smith Vidaurre #' @references {Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' \href{https://en.wikipedia.org/wiki/Sound_pressure}{Wikipedia: Sound pressure level} #' } # last modification on aug-8-2022 (MAS) sound_pressure_level <- function(X, reference = 20, parallel = 1, path = NULL, pb = TRUE, type = "single", wl = 100, bp = NULL, remove.bgn = FALSE, mar = NULL, envelope = "abs") { #### set arguments from options # get function arguments argms <- methods::formalArgs(sound_pressure_level) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X))) stop2("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") if (!all(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))) { stop2(paste(paste(c("sound.files", "selec", "start", "end")[!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop2("NAs found in start and/or end") # if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) stop2("'start' and 'end' must be numeric") # if any start higher than end stop if (any(X$end - X$start <= 0)) stop2(paste("Start is higher than or equal to end in", length(which(X$end - X$start <= 0)), "case(s)")) # check sound files if not a extended selection table if (!is_extended_selection_table(X)) { fs <- list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE) if (length(unique(X$sound.files[(X$sound.files %in% fs)])) != length(unique(X$sound.files))) { message2(paste( length(unique(X$sound.files)) - length(unique(X$sound.files[(X$sound.files %in% fs)])), "sound file(s) not found" )) } # count number of sound files in working directory and if 0 stop d <- which(X$sound.files %in% fs) if (length(d) == 0) { stop2("The sound files are not in the working directory") } else { X <- X[d, , drop = FALSE] } } else { d <- 1:nrow(X) } # If parallel is not numeric if (!is.numeric(parallel)) stop2("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop2("'parallel' should be a positive integer") # need mar if remove.bgn TRUE if (remove.bgn & is.null(mar)) { stop2("'mar' must be supplied if 'remove.bgn = TRUE'") } # function to get SPL spl_FUN <- function(X, i, path, reference) { signal <- read_wave(X, index = i, path = path) if (remove.bgn) { bg.noise <- read_wave(X, index = i, path = path, from = X$start[i] - mar, to = X$start[i]) } # add band-pass frequency filter if (!is.null(bp)) { # filter to bottom and top freq range if (bp == "freq.range") { bp <- c(X$bottom.freq[i], X$top.freq[i]) } signal <- seewave::ffilter(signal, f = [email protected], from = bp[1] * 1000, ovlp = 0, to = bp[2] * 1000, bandpass = TRUE, wl = wl, output = "Wave") if (remove.bgn) { bg.noise <- seewave::ffilter(bg.noise, f = [email protected], from = bp[1] * 1000, ovlp = 0, to = bp[2] * 1000, bandpass = TRUE, wl = wl, output = "Wave") } } # only if more than 9 samples above twice wl (so it can have at least 2 segments) if ((length(signal) + 9) <= wl * 2 | type == "single") { sigamp <- seewave::rms(seewave::env(signal, envt = envelope, plot = FALSE)) } else { # sample cut points cuts <- seq(1, length(signal), by = wl) # remove last one if few samples (SPL unreliable) if (cuts[length(cuts)] - cuts[length(cuts) - 1] < 10) { cuts <- cuts[-length(cuts)] } sigamp <- sapply(2:length(cuts), function(e) { seewave::rms(seewave::env(signal[cuts[e - 1]:cuts[e]], envt = "abs", plot = FALSE)) }) } # convert to dB signaldb <- 20 * log10(sigamp) signaldb <- if (type == "peak") max(signaldb) else seewave::meandB(signaldb) # remove background SPL if (remove.bgn) { noiseamp <- seewave::rms(seewave::env(bg.noise, f = [email protected], envt = envelope, plot = FALSE)) noisedb <- 20 * log10(noiseamp) # remove noise SPL from signal SPL signaldb <- lessdB_wrblr_int(signal.noise = signaldb, noise = noisedb) } return(signaldb) } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function SPL_l <- pblapply_wrblr_int(pbar = pb, X = 1:nrow(X), cl = cl, FUN = function(i) { spl_FUN(X, i, path, reference) }) # remove reference column X$...REFERENCE_TMP <- NULL # Add SNR data to X z <- data.frame(X, SPL = unlist(SPL_l)) # rename column if peak.ampitude names(z)[ncol(z)] <- "SPL" # fix extended selection table if (is_extended_selection_table(X)) z <- fix_extended_selection_table(X = z, Y = X) return(z) }
/scratch/gouwar.j/cran-all/cranData/warbleR/R/sound_pressure_level.R
#' Measure acoustic parameters in batches of sound files #' #' \code{spectro_analysis} measures acoustic parameters on acoustic signals for which the start and end times #' are provided. #' @usage spectro_analysis(X, bp = "frange", wl = 512, wl.freq = NULL, threshold = 15, #' parallel = 1, fast = TRUE, path = NULL, pb = TRUE, ovlp = 50, #' wn = "hanning", fsmooth = 0.1, harmonicity = FALSE, nharmonics = 3, ...) #' @param X 'selection_table', 'extended_selection_table' or data frame with the following columns: 1) "sound.files": name of the sound #' files, 2) "sel": number of the selections, 3) "start": start time of selections, 4) "end": #' end time of selections. The output \code{\link{auto_detec}} can #' be used as the input data frame. #' @param bp A numeric vector of length 2 for the lower and upper limits of a #' frequency bandpass filter (in kHz) or "frange" (default) to indicate that values in bottom.freq #' and top.freq columns will be used as bandpass limits. Lower limit of #' bandpass filter is not applied to fundamental frequencies. #' @param wl A numeric vector of length 1 specifying the spectrogram window length. Default is 512. See 'wl.freq' for setting windows length independently in the frequency domain. #' @param wl.freq A numeric vector of length 1 specifying the window length of the spectrogram #' for measurements on the frequency spectrum. Default is 512. Higher values would provide #' more accurate measurements. Note that this allows to increase measurement precision independently in the time and frequency domain. If \code{NULL} (default) then the 'wl' value is used. #' @param threshold amplitude threshold (\%) for fundamental frequency and #' dominant frequency detection. Default is 15. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param fast Logical. If \code{TRUE} (default) then the peakf acoustic parameter (see below) is not computed, which #' substantially increases performance (~9 times faster). This argument will be removed in future version. #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param pb Logical argument to control progress bar and messages. Default is \code{TRUE}. #' @param ovlp Numeric vector of length 1 specifying \% of overlap between two #' consecutive windows, used for fundamental frequency (using \code{\link[seewave]{fund}} or \code{\link[tuneR]{FF}}) and dominant frequency (using \code{\link[seewave]{dfreq}}). #' Default is 50. #' @param wn Character vector of length 1 specifying window name. Default is hanning'. #' See function \code{\link[seewave]{ftwindow}} for more options. #' @param fsmooth A numeric vector of length 1 to smooth the frequency spectrum with a mean #' sliding window (in kHz) used for mean peak frequency detection. This help to average #' amplitude "hills" to minimize the effect of amplitude modulation. Default is 0.1. #' @param harmonicity Logical. If \code{TRUE} harmonicity related parameters (fundamental frequency parameters [meanfun, minfun, maxfun], hn_freq, #' hn_width, harmonics and HNR) are measured. Note that measuring these parameters #' considerably increases computing time. #' @param nharmonics Numeric vector of length 1 setting the number of harmonics to analyze. #' @param ... Additional parameters to be passed to \code{\link[soundgen]{analyze}}, which measures parameters related to harmonicity. #' @return Data frame with 'sound.files' and 'selec' as in the input data frame, plus the following acoustic parameters: #' \itemize{ #' \item \code{duration}: length of signal (in s) #' \item \code{meanfreq}: mean frequency (in kHz). Calculated as the weighted average of the frequency spectrum (i.e. weighted by the amplitude within the supplied band pass). #' \item \code{sd}: standard deviation of frequency (in kHz). Calculated as the weighted standard deviation of the frequency spectrum (i.e. weighted by the amplitude within the supplied band pass). #' \item \code{freq.median}: median frequency. The frequency at which the frequency spectrum is divided in two frequency #' intervals of equal energy (in kHz) #' \item \code{freq.Q25}: first quartile frequency. The frequency at which the frequency spectrum is divided in two #' frequency intervals of 25\% and 75\% energy respectively (in kHz) #' \item \code{freq.Q75}: third quartile frequency. The frequency at which the frequency spectrum is divided in two #' frequency intervals of 75\% and 25\% energy respectively (in kHz) #' \item \code{freq.IQR}: interquartile frequency range. Frequency range between 'freq.Q25' and 'freq.Q75' #' (in kHz) #' \item \code{time.median}: median time. The time at which the time envelope is divided in two time #' intervals of equal energy (in s) #' \item \code{time.Q25}: first quartile time. The time at which the time envelope is divided in two #'time intervals of 25\% and 75\% energy respectively (in s). See \code{\link[seewave]{acoustat}} #' \item \code{time.Q75}: third quartile time. The time at which the time envelope is divided in two #' time intervals of 75\% and 25\% energy respectively (in s). See \code{\link[seewave]{acoustat}} #' \item \code{time.IQR}: interquartile time range. Time range between 'time.Q25' and 'time.Q75' #' (in s). See \code{\link[seewave]{acoustat}} #' \item \code{skew}: skewness. Asymmetry of the frequency spectrum (see note in \code{\link[seewave]{specprop}} description) #' \item \code{kurt}: kurtosis. Peakedness of the frequency spectrum (see note in \code{\link[seewave]{specprop}} description) #' \item \code{sp.ent}: spectral entropy. Energy distribution of the frequency spectrum. Pure tone ~ 0; #' noisy ~ 1. See \code{\link[seewave]{sh}} #' \item \code{time.ent}: time entropy. Energy distribution on the time envelope. ~0 means amplitude concentrated in a specific time point, 1 means amplitude equally distributed across time. See \code{\link[seewave]{th}} #' \item \code{entropy}: spectrographic entropy. Product of time and spectral entropy \code{sp.ent * time.ent}. #' See \code{\link[seewave]{H}} #' \item \code{sfm}: spectral flatness. Similar to sp.ent (Pure tone ~ 0; #' noisy ~ 1). See \code{\link[seewave]{sfm}} #' \item \code{meandom}: average of dominant frequency measured across the spectrogram #' \item \code{mindom}: minimum of dominant frequency measured across the spectrogram #' \item \code{maxdom}: maximum of dominant frequency measured across the spectrogram #' \item \code{dfrange}: range of dominant frequency measured across the spectrogram #' \item \code{modindx}: modulation index. Calculated as the cumulative absolute #' difference between adjacent measurements of dominant frequencies divided #' by the dominant frequency range (measured on the spectrogram). 1 means the signal is not modulated. #' \item \code{startdom}: dominant frequency measurement at the start of the signal (measured on the spectrogram). #' \item \code{enddom}: dominant frequency measurement at the end of the signal(measured on the spectrogram). #' \item \code{dfslope}: slope of the change in dominant frequency (measured on the spectrogram) through time ((enddom-startdom)/duration). Units are kHz/s. #' \item \code{peakf}: peak frequency. Frequency with the highest energy. This #' parameter can take a considerable amount of time to measure. It's only #' generated if \code{fast = FALSE}. It provides a more accurate measure of peak #' frequency than 'meanpeakf' but can be more easily affected by background noise. Measured on the frequency spectrum. #' \item \code{meanpeakf}: mean peak frequency. Frequency with highest energy from the #' mean frequency spectrum (see \code{\link[seewave]{meanspec}}). Typically more consistent than peakf in the presence of noise. #' \item \code{meanfun}: average of fundamental frequency measured across the acoustic signal. Only measured if \code{harmonicity = TRUE}. #' \item \code{minfun}: minimum fundamental frequency measured across the acoustic signal. Only measured if \code{harmonicity = TRUE}. #' \item \code{maxfun}: maximum fundamental frequency measured across the acoustic signal. Only measured if \code{harmonicity = TRUE}. #' \item \code{hn_freq}: mean frequency of the 'n' upper harmonics (kHz) (see \code{\link[soundgen]{analyze}}). #' Number of harmonics is defined with the argument 'nharmonics'. Only measured if \code{harmonicity = TRUE}. #' \item \code{hn_width}: mean bandwidth of the 'n' upper harmonics (kHz) (see \code{\link[soundgen]{analyze}}). Number of harmonics is defined with the argument 'nharmonics'. Only measured if \code{harmonicity = TRUE}. #' \item \code{harmonics}: the amount of energy in upper harmonics, namely the #' ratio of total spectral power above 1.25 x F0 to the total spectral power #' below 1.25 x F0 (dB) (see \code{\link[soundgen]{analyze}}). Number of #' harmonics is defined with the argument 'nharmonics'. Only measured if \code{harmonicity = TRUE}. #' \item \code{HNR}: harmonics-to-noise ratio (dB). A measure of the harmonic content generated by \code{\link[soundgen]{getPitchAutocor}}. Only measured if \code{harmonicity = TRUE}. #' } #' @export #' @name spectro_analysis #' @details The function measures 29 acoustic parameters (if \code{fast = TRUE}) on #' each selection in the data frame. Most parameters are produced internally by #' \code{\link[seewave]{specprop}}, \code{\link[seewave]{fpeaks}}, \code{\link[seewave]{fund}}, #' and \code{\link[seewave]{dfreq}} from the package seewave and \code{\link[soundgen]{analyze}} #' from the package soundgen. NAs are produced for fundamental and dominant #' frequency measures when there are no amplitude values above the threshold. #' Additional parameters can be provided to the internal function \code{\link[soundgen]{analyze}}, which measures parameters related to harmonicity. #' @examples #' { #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' #' # measure acoustic parameters #' sp_param <- spectro_analysis(X = lbh_selec_table[1:8,], pb = FALSE, path = tempdir()) #' #' # measuring peakf #' sp_param <- spectro_analysis(X = lbh_selec_table[1:8,], pb = FALSE, fast = FALSE, path = tempdir()) #' #' \donttest{ #' # measuring harmonic-related parameters using progress bar #' sp_param <- spectro_analysis(X = lbh_selec_table[1:8,], harmonicity = TRUE, #' path = tempdir(), ovlp = 70) #' } #' } #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) and Grace Smith Vidaurre #last modification on mar-13-2018 (MAS) spectro_analysis <- function(X, bp = "frange", wl = 512, wl.freq = NULL, threshold = 15, parallel = 1, fast = TRUE, path = NULL, pb = TRUE, ovlp = 50, wn = "hanning", fsmooth = 0.1, harmonicity = FALSE, nharmonics = 3, ...) { # error message if ape is not installed if (!requireNamespace("soundgen",quietly = TRUE) & harmonicity) stop("must install 'soundgen' when harmonicity = TRUE") #### set arguments from options # get function arguments argms <- methods::formalArgs(spectro_analysis) # get warbleR options opt.argms <- if(!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) for (q in seq_len(length(opt.argms))) assign(names(opt.argms)[q], opt.argms[[q]]) #check path to working directory if (is.null(path)) path <- getwd() else if (!dir.exists(path)) stop("'path' provided does not exist") else path <- normalizePath(path) #if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X))) stop("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") if (!all(c("sound.files", "selec", "start", "end") %in% colnames(X))) stop(paste(paste(c("sound.files", "selec", "start", "end")[!(c("sound.files", "selec", "start", "end") %in% colnames(X))], collapse=", "), "column(s) not found in data frame")) #if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop("NAs found in start and/or end") #if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) stop("'start' and 'end' must be numeric") #if any start higher than end stop if (any(X$end - X$start <= 0)) stop(paste("Start is higher than or equal to end in", length(which(X$end - X$start <= 0)), "case(s)")) #if any selections longer than 20 secs warning if (any(X$end - X$start>20)) warning2(paste(length(which(X$end - X$start>20)), "selection(s) longer than 20 sec")) # bp checking if (!is.null(bp)) if (bp[1] != "frange") {if (!is.vector(bp)) stop("'bp' must be a numeric vector of length 2") else{ if (!length(bp) == 2) stop("'bp' must be a numeric vector of length 2")} } else {if (!any(names(X) == "bottom.freq") & !any(names(X) == "top.freq")) stop("'bp' = frange requires bottom.freq and top.freq columns in X") if (any(is.na(c(X$bottom.freq, X$top.freq)))) stop("NAs found in bottom.freq and/or top.freq") if (any(c(X$bottom.freq, X$top.freq) < 0)) stop("Negative values found in bottom.freq and/or top.freq") if (any(X$top.freq - X$bottom.freq < 0)) stop("top.freq should be higher than bottom.freq") } if (!is_extended_selection_table(X)){ #return warning if not all sound files were found fs <- list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE) if (length(unique(X$sound.files[(X$sound.files %in% fs)])) != length(unique(X$sound.files))) warning2(x = paste(length(unique(X$sound.files))-length(unique(X$sound.files[(X$sound.files %in% fs)])), "sound file(s) not found")) #count number of sound files in working directory and if 0 stop d <- which(X$sound.files %in% fs) if (length(d) == 0){ stop("The sound files are not in the working directory") } else { X <- X[d, ] } } # wl adjustment if (is.null(wl.freq)) wl.freq <- wl # If parallel is not numeric if (!is.numeric(parallel)) stop("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0),parallel < 1)) stop("'parallel' should be a positive integer") #create function to run within Xapply functions downstream spFUN <- function(i, X, bp, wl, threshold) { # read wave object r <- warbleR::read_sound_file(X = X, path = path, index = i) if (length(r@left) < 7) stop(paste0("too few samples in selection row ", i, ", try check_sels() to find problematic selections"), call. = FALSE) if (!is.null(bp)) if (bp[1] == "frange") bp <- c(X$bottom.freq[i], X$top.freq[i]) b <- bp #in case bp its higher than can be due to sampling rate if (b[2] > floor([email protected] / 2000)) b[2] <- floor([email protected]/2000) # add a bit above and below to ensure range limits are included bpfr <- b bpfr <- bpfr + c(-0.2, 0.2) if (bpfr[1] < 0) bpfr[1] <- 0 if (bpfr[2] > floor([email protected] / 2000)) bpfr[2] <- floor([email protected] / 2000) # freq range to measure peak freq # wl is adjusted when very short signals frng <- frd_wrblr_int(wave = r, wl = wl.freq, fsmooth = fsmooth, threshold = threshold, wn = wn, bp = bpfr, ovlp = ovlp) # soungen measurements if (harmonicity) { sg.param <- suppressMessages(try(soundgen::analyze(x = as.numeric(r@left), samplingRate = [email protected], silence = threshold / 100, overlap = ovlp, windowLength = wl / [email protected] * 1000, plot = FALSE, wn = wn, pitchCeiling = b[2] * 1000, cutFreq = b[2] * 1000, nFormants = nharmonics, SPL_measured = 0, voicedSeparate = FALSE, priorMean = NA, pitchMethods = c('dom', 'autocor'), ...), silent = TRUE)) if (!is(sg.param, "try-error")){ # fix for soundgen 2.0 if (!is.null(sg.param$detailed)){ sg.param <- sg.param$detailed } # fix harmonics energy column names(sg.param)[names(sg.param) == "harmEnergy"] <- "harmonics" names(sg.param) <- gsub("^f", "h", names(sg.param)) if (all(is.na(sg.param$pitch))) ff <- c(as.matrix(sg.param[, grep("pitch", names(sg.param))])) else ff <- sg.param$pitch sg.param[, grep("freq$|_width$", names(sg.param))] <- sg.param[, grep("freq$|_width$", names(sg.param))] / 1000 sg.param <- as.data.frame(t(apply(sg.param[, grep("harmonics|HNR$|_freq$|_width$", names(sg.param))], 2, mean, na.rm = TRUE))) ff <- ff[!is.na(ff)] if (length(ff) > 0) { meanfun<-mean(ff, na.rm = TRUE) / 1000 minfun<-min(ff, na.rm = TRUE) / 1000 maxfun<-max(ff, na.rm = TRUE) / 1000} else meanfun <- minfun <- maxfun <- NA fun.pars <- data.frame(t(c(meanfun = meanfun, minfun = minfun, maxfun = maxfun))) } else { sg.param <- data.frame(t(rep(NA, (nharmonics * 2) + 2))) names(sg.param) <- c(paste0("h", rep(1:nharmonics, each = 2), c("_freq", "_width")), "harmonics", "HNR") fun.pars <- data.frame(meanfun = NA, minfun = NA, maxfun = NA) } } #frequency spectrum analysis songspec <- suppressWarnings(seewave::spec(r, f = [email protected], plot = FALSE, wl = wl.freq, wn = wn, flim = b)) analysis <- specprop_wrblr_int(spec = songspec, f = [email protected], flim = b, plot = FALSE) #from seewave's acoustat m <- sspectro(r, f = [email protected], wl = ifelse(wl >= length(r@left), length(r@left) - 1, wl), ovlp = ovlp, wn = wn) if (!is.matrix(m)) m <- as.matrix(m) fl <- b * nrow(m) * 2000/[email protected] m <- m[(fl[1]:fl[2]) + 1, ] if (is.vector(m)) m <- t(as.matrix(m)) time <- seq(0, length(r)/[email protected], length.out = ncol(m)) t.cont <- apply(m, MARGIN = 2, FUN = sum) t.cont <- t.cont/sum(t.cont) t.cont.cum <- cumsum(t.cont) t.quartiles <- sapply(c(0.25, 0.5, 0.75), function(x) time[length(t.cont.cum[t.cont.cum <=x]) + 1]) #save parameters meanfreq <- analysis$mean/1000 sd <- analysis$sd/1000 freq.median <- analysis$median/1000 freq.Q25 <- analysis$Q25/1000 freq.Q75 <- analysis$Q75/1000 freq.IQR <- analysis$IQR/1000 time.ent <- th(cbind(time, t.cont)) time.median <- t.quartiles[2] time.Q25 <- t.quartiles[1] time.Q75 <- t.quartiles[3] time.IQR <- t.quartiles[3] - t.quartiles[1] skew <- analysis$skewness kurt <- analysis$kurtosis sp.ent <- analysis$sh entropy <- sp.ent * time.ent sfm <- analysis$sfm #Frequency with amplitude peaks if (!fast) #only if fast is TRUE peakf <- seewave::fpeaks(songspec, f = [email protected], wl = wl.freq, nmax = 3, plot = FALSE)[1, 1] else peakf <- NA #Dominant frequency parameters y <- track_harmonic(wave = r, f = [email protected], wl = if (wl >= length(r@left)) length(r@left) - 2 else wl, ovlp = ovlp, plot = FALSE, threshold = threshold, bandpass = b * 1000, fftw = TRUE, dfrq = TRUE, adjust.wl = TRUE)[, 2] #remove NAs y <- y[!is.na(y)] #remove values below and above bandpass plus half a window size y <- y[y >= b[1] & y <= b[2] & y != 0] #save results in individual objects for each measurement if (length(y) > 0) { meandom <- mean(y, na.rm = TRUE) mindom <- min(y, na.rm = TRUE) maxdom <- max(y, na.rm = TRUE) dfrange <- maxdom - mindom startdom <- y[1] enddom <- y[length(y)] if (length(y) > 1 & dfrange != 0) modindx <- sum(sapply(2:length(y), function(j) abs(y[j] - y[j - 1])))/dfrange else modindx <- 1 } else meandom <- mindom <- maxdom <- dfrange <- startdom <- enddom <- modindx <- NA duration <- (X$end[i] - X$start[i]) if (!is.na(enddom) && !is.na(startdom)) dfslope <- (enddom -startdom)/duration else dfslope <- NA # extract mean peak freq meanpeakf <- frng$meanpeakf #set to mean peak freq if length is 0 if (length(meanpeakf) == 0) meanpeakf <- NA #save results dfres <- data.frame( sound.files = X$sound.files[i], selec = X$selec[i], duration, meanfreq, sd, freq.median, freq.Q25, freq.Q75, freq.IQR, time.median, time.Q25, time.Q75, time.IQR, skew, kurt, sp.ent, time.ent, entropy, sfm, meandom, mindom, maxdom, dfrange, modindx, startdom, enddom, dfslope, meanpeakf ) # add peak freq if (!fast) dfres$peakf <- peakf # add soundgen parameters if (harmonicity) dfres <- cbind(dfres, sg.param, fun.pars) # add low high freq if (!is.null(bp)) if (bp[1] == "frange") { dfres$bottom.freq <- b[1] dfres$top.freq <- b[2] } return(dfres) } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) else cl <- parallel # run loop apply function sp <- pblapply_wrblr_int(X = 1:nrow(X), cl = cl, pbar = pb, FUN = function(i) { spFUN(X = X, i = i, bp = bp, wl = wl, threshold = threshold) }) # put results in a single data frame sp <- do.call(rbind, sp) row.names(sp) <- 1:nrow(sp) sp <- sort_colms(sp) return(sp) } ############################################################################################################## #' alternative name for \code{\link{spectro_analysis}} #' #' @keywords internal #' @details see \code{\link{spectro_analysis}} for documentation. \code{\link{specan}} will be deprecated in future versions. #' @export specan <- spectro_analysis
/scratch/gouwar.j/cran-all/cranData/warbleR/R/spectro_analysis.R
#' Spectrograms of selected signals #' #' \code{spectrograms} creates spectrograms of signals from selection tables. #' @usage spectrograms(X, wl = 512, flim = "frange", wn = "hanning", pal = reverse.gray.colors.2, #' ovlp = 70, inner.mar = c(5, 4, 4, 2), outer.mar = c(0, 0, 0, 0), picsize = 1, res = 100, #' cexlab = 1, propwidth = FALSE, xl = 1, osci = FALSE, gr = FALSE, sc = FALSE, line = TRUE, #' col = "#07889B", fill = adjustcolor("#07889B", alpha.f = 0.15), lty = 3, #' mar = 0.05, it = "jpeg", parallel = 1, path = NULL, pb = TRUE, fast.spec = FALSE, #' by.song = NULL, sel.labels = "selec", title.labels = NULL, dest.path = NULL, #' box = TRUE, axis = TRUE, ...) #' @param X 'selection_table', 'extended_selection_table' or data frame containing columns for sound file name (sound.files), #' selection number (selec), and start and end time of signals (start and end). #' 'top.freq' and 'bottom.freq' columns are optional. If using an #' 'extended_selection_table' the sound files are not required (see \code{\link{selection_table}}). #' @param wl A numeric vector of length 1 specifying the window length of the spectrogram, default #' is 512. #' @param flim A numeric vector of length 2 for the frequency limit (in kHz) of #' the spectrogram, as in \code{\link[seewave]{spectro}}. The function also #' accepts 'frange' (default) which produces spectrograms with a frequency #' limit around the range of each signal (adding a 1 kHz margin). #' @param wn Character vector of length 1 specifying window name. Default is #' "hanning". See function \code{\link[seewave]{ftwindow}} for more options. #' @param pal A color palette function to be used to assign colors in the #' plot, as in \code{\link[seewave]{spectro}}. Default is reverse.gray.colors.2. #' @param ovlp Numeric vector of length 1 specifying the percent overlap between two #' consecutive windows, as in \code{\link[seewave]{spectro}}. Default is 70. #' @param inner.mar Numeric vector with 4 elements, default is c(5,4,4,2). #' Specifies number of lines in inner plot margins where axis labels fall, #' with form c(bottom, left, top, right). See \code{\link[graphics]{par}}. #' @param outer.mar Numeric vector with 4 elements, default is c(0,0,0,0). #' Specifies number of lines in outer plot margins beyond axis labels, with #' form c(bottom, left, top, right). See \code{\link[graphics]{par}}. #' @param picsize Numeric argument of length 1. Controls relative size of #' spectrogram. Default is 1. Ignored when propwidth is \code{TRUE}. #' @param res Numeric argument of length 1. Controls image resolution. #' Default is 100 (faster) although 300 - 400 is recommended for publication/ #' presentation quality. #' @param cexlab Numeric vector of length 1 specifying the relative size of axis #' labels. See \code{\link[seewave]{spectro}}. #' @param propwidth Logical argument to scale the width of spectrogram #' proportionally to duration of the selection. Default is \code{FALSE}. #' @param xl Numeric vector of length 1. A constant by which to scale #' spectrogram width if propwidth = \code{TRUE}. Default is 1. #' @param osci Logical argument to add an oscillogram underneath spectrogram, as #' in \code{\link[seewave]{spectro}}. Default is \code{FALSE}. #' @param gr Logical argument to add grid to spectrogram. Default is \code{FALSE}. #' @param sc Logical argument to add amplitude scale to spectrogram, default is #' \code{FALSE}. #' @param line Logical argument to add lines at start and end times of selection #' (or box if bottom.freq and top.freq columns are provided). Default is \code{TRUE}. #' @param col Color of 'line'. Default is "#07889B". #' @param fill Fill color of box around selections. Default is \code{adjustcolor("#07889B", alpha.f = 0.15)}. #' @param lty Type of 'line' as in \code{\link[graphics]{par}}. Default is 1. #' @param mar Numeric vector of length 1. Specifies the margins adjacent to the start and end points of selections, #' dealineating spectrogram limits. Default is 0.05. #' @param it A character vector of length 1 giving the image type to be used. Currently only #' "tiff" and "jpeg" are admitted. Default is "jpeg". #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @param fast.spec Logical. If \code{TRUE} then image function is used internally to create spectrograms, #' which substantially increases performance (much faster), although some options become unavailable, #' as collevels, and sc (amplitude scale). This option is indicated for signals with high background noise #' levels. Palette colors \code{\link[monitoR:specCols]{gray.1}}, \code{\link[monitoR:specCols]{gray.2}}, #' \code{\link[monitoR:specCols]{gray.3}}, \code{\link[monitoR:specCols]{topo.1}} and \code{\link[monitoR:specCols]{rainbow.1}} #' (which should be imported from the package monitoR) seem to work better with 'fast' spectrograms. #' Palette colors \code{\link[monitoR:specCols]{gray.1}}, \code{\link[monitoR:specCols]{gray.2}}, \code{\link[monitoR:specCols]{gray.3}} #' offer decreasing darkness levels. #' @param by.song Character string with the column name containing song labels. If #' provide a single spectrogram containing all elements for each song will be produce. Note that #' the function assumes that each song has a unique label within a sound file. If \code{NULL} (default), spectrograms are produced for single selections. #' @param sel.labels Character string with the name of the column(s) for selection #' labeling. Default is 'selec'. Set to \code{NULL} to remove labels. #' @param title.labels Character string with the name(s) of the column(s) to use as title. Default is \code{NULL} (no title). Only sound file and song included if 'by.song' is provided. #' @param dest.path Character string containing the directory path where the image files will be saved. #' If \code{NULL} (default) then the folder containing the sound files will be used instead. #' @param box Logical to control if the box around the spectrogram is plotted (see \code{\link[graphics]{box}}). Default is \code{TRUE}. #' @param axis Logical to control if the Y and X axis are of the spectrogram are plotted (see \code{\link[graphics]{box}}). Default is \code{TRUE}. #' @param ... Additional arguments to be passed to the internal spectrogram #' creating function for customizing graphical output. The function is a modified #' version of \code{\link[seewave]{spectro}}, so it takes the same arguments. #' @return Image files containing spectrograms of the signals listed in the input data frame. #' @family spectrogram creators #' @seealso \code{\link{track_freq_contour}} for creating spectrograms to visualize #' frequency measurements by \code{\link{spectro_analysis}}, \code{\link{snr_spectrograms}} for #' creating spectrograms to optimize noise margins used in \code{\link{sig2noise}} #' @export #' @name spectrograms #' @details This function provides access to batch process of (a modified version of) the \code{\link[seewave]{spectro}} function from the 'seewave' package. The function creates spectrograms for visualization of vocalizations. #' Setting inner.mar to c(4,4.5,2,1) and outer.mar to c(4,2,2,1) works well when picsize = 2 or 3. #' Title font size, inner.mar and outer.mar (from mar and oma) don't work well when osci or sc = TRUE, #' this may take some optimization by the user. Setting 'fast' argument to TRUE significantly increases speed, although #' some options become unavailable, as collevels, and sc (amplitude scale). This option is indicated for signals with #' high background noise levels. #' @examples #' { #' # load and save data #' data(list = c("Phae.long1", "Phae.long2", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) # save sound files #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' #' # make spectrograms #' spectrograms( #' X = lbh_selec_table, flim = c(0, 11), res = 300, mar = 0.05, #' wl = 300, path = tempdir() #' ) #' #' # check this folder #' tempdir() #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) and Grace Smith Vidaurre # last modification on mar-13-2018 (MAS) spectrograms <- function(X, wl = 512, flim = "frange", wn = "hanning", pal = reverse.gray.colors.2, ovlp = 70, inner.mar = c(5, 4, 4, 2), outer.mar = c(0, 0, 0, 0), picsize = 1, res = 100, cexlab = 1, propwidth = FALSE, xl = 1, osci = FALSE, gr = FALSE, sc = FALSE, line = TRUE, col = "#07889B", fill = adjustcolor("#07889B", alpha.f = 0.15), lty = 3, mar = 0.05, it = "jpeg", parallel = 1, path = NULL, pb = TRUE, fast.spec = FALSE, by.song = NULL, sel.labels = "selec", title.labels = NULL, dest.path = NULL, box = TRUE, axis = TRUE, ...) { #### set arguments from options # get function arguments argms <- methods::formalArgs(spectrograms) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) { getOption("warbleR") } else { SILLYNAME <- 0 } # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop("'path' provided does not exist") } else { path <- normalizePath(path) } # check dest.path to working directory if (is.null(dest.path)) { dest.path <- path } else if (!dir.exists(dest.path)) { stop("'dest.path' provided does not exist") } else { dest.path <- normalizePath(dest.path) } # if X is not a data frame if (!any( is.data.frame(X), is_selection_table(X), is_extended_selection_table(X) )) { stop("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") } if (!all(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))) { stop(paste(paste( c("sound.files", "selec", "start", "end")[!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))], collapse = ", " ), "column(s) not found in data frame")) } # check song and element label if (!is.null(by.song)) { if (!any(names(X) == by.song)) { stop("'by.song' not found") } } if (!is.null(sel.labels)) { if (!any(names(X) %in% sel.labels)) { stop("'sel.labels' not found") } } # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) { stop("NAs found in start and/or end") } # if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) { stop("'start' and 'end' must be numeric") } # if any start higher than end stop if (any(X$end - X$start <= 0)) { stop(paste( "The start is higher than or equal to the end in", length(which(X$end - X$start <= 0)), "case(s)" )) } if (flim[1] != "frange") { if (!is.vector(flim)) { stop("'flim' must be a numeric vector of length 2") } else if (!length(flim) == 2) { stop("'flim' must be a numeric vector of length 2") } # add bottom and top freq if not included if (!is.null(flim[1])) { # top minus 1 kHz if (is.null(X$bottom.freq)) { X$bottom.freq <- flim[1] - 1 } # top plus 1 kHz if (is.null(X$top.freq)) { X$top.freq <- flim[2] + 1 } } else { # negative bottom so bottom line is not plotted if (is.null(X$bottom.freq)) { X$bottom.freq <- -1 } # if no top freq then make it 501 kHz (which is half the highest sampling rate (1 million) + 1) if (is.null(X$top.freq)) { X$top.freq <- 501 } } } else { if (!any(names(X) == "bottom.freq") & !any(names(X) == "top.freq")) { stop("'flim' = frange requires bottom.freq and top.freq columns in X") } if (any(is.na(c(X$bottom.freq, X$top.freq)))) { stop("NAs found in bottom.freq and/or top.freq") } if (any(c(X$bottom.freq, X$top.freq) < 0)) { stop("Negative values found in bottom.freq and/or top.freq") } if (any(X$top.freq - X$bottom.freq <= 0)) { stop("top.freq should be higher than bottom.freq") } } # if it argument is not "jpeg" or "tiff" if (!any(it == "jpeg", it == "tiff")) { stop(paste("Image type", it, "not allowed")) } # error if not title.labels character if (!is.character(title.labels) & !is.null(title.labels)) { stop("'title.labels' must be a character string") } # missing label columns if (!all(title.labels %in% colnames(X))) { stop(paste( paste(title.labels[!(title.labels %in% colnames(X))], collapse = ", "), "label column(s) not found in data frame" )) } # return warning if not all sound files were found if (!is_extended_selection_table(X)) { recs.wd <- list.files( path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE ) if (length(unique(X$sound.files[(X$sound.files %in% recs.wd)])) != length(unique(X$sound.files))) { (paste( length(unique(X$sound.files)) - length(unique(X$sound.files[(X$sound.files %in% recs.wd)])), "sound file(s) not found" )) } # count number of sound files in working directory and if 0 stop d <- which(X$sound.files %in% recs.wd) if (length(d) == 0) { stop("The sound files are not in the working directory") } else { X <- X[d, , drop = FALSE] } } if (propwidth) { picsize <- 1 } # If parallel is not numeric if (!is.numeric(parallel)) { stop("'parallel' must be a numeric vector of length 1") } if (any(!(parallel %% 1 == 0), parallel < 1)) { stop("'parallel' should be a positive integer") } # by song if (!is.null(by.song)) { Y <- X X <- song_analysis( X = Y, song_colm = by.song, pb = FALSE ) X$selec <- 1 # fix extended selection table again if (warbleR::is_extended_selection_table(Y)) { X <- fix_extended_selection_table(X, Y, to.by.song = TRUE) } } # create function to run within Xapply functions downstream specreFUN <- function(X, Y, i, mar, flim, xl, picsize, res, wl, ovlp, cexlab, by.song, sel.labels, pal, dest.path, fill) { # Read sound files, initialize frequency and time limits for spectrogram r <- warbleR::read_sound_file( X = X, path = path, index = i, header = TRUE, from = 0, to = X$end[i] + mar ) f <- r$sample.rate t <- c(X$start[i] - mar, X$end[i] + mar) mar1 <- mar mar2 <- mar1 + X$end[i] - X$start[i] if (t[1] < 0) { mar1 <- mar1 + t[1] mar2 <- mar2 + t[1] t[1] <- 0 } if (t[2] > r$samples / f) { t[2] <- r$samples / f } # add low high freq if (flim[1] == "frange") { flim <- range(c(X$bottom.freq[i], X$top.freq[i])) + c(-1, 1) } fl <- flim # in case flim its higher than can be due to sampling rate if (fl[2] >= f / 2000) { fl[2] <- ((f - 1) / 2000) } if (fl[1] < 0) { fl[1] <- 0 } # Spectrogram width can be proportional to signal duration if (propwidth) { pwc <- (10.16) * ((t[2] - t[1]) / 0.27) * xl * picsize } else { pwc <- (10.16) * xl * picsize } if (is.null(by.song)) { fn <- paste(X$sound.files[i], "-", X$selec[i], ".", it, sep = "") } else if (by.song == "sound.files") { fn <- paste(X$sound.files[i], ".", it, sep = "") } else { fn <- paste(X$sound.files[i], "-", X[i, by.song], ".", it, sep = "") } img_wrlbr_int( filename = fn, path = dest.path, width = pwc, height = (10.16) * picsize, units = "cm", res = res ) # Change relative heights of rows for spectrogram when osci = TRUE if (osci) { hts <- c(3, 2) } else { hts <- NULL } # Change relative widths of columns for spectrogram when sc = TRUE if (sc) { wts <- c(3, 1) } else { wts <- NULL } # Change inner and outer plot margins par(mar = inner.mar) par(oma = outer.mar) # Generate spectrogram using spectro_wrblr_int (modified from seewave::spectro) spectro_wrblr_int( wave = warbleR::read_sound_file( X = X, path = path, index = i, from = t[1], to = t[2] ), f = f, wl = wl, ovlp = ovlp, heights = hts, wn = "hanning", widths = wts, palette = pal, osc = osci, grid = gr, scale = sc, collab = "black", cexlab = cexlab, cex.axis = 1, flim = fl, tlab = "Time (s)", flab = "Frequency (kHz)", alab = "", trel = FALSE, fast.spec = fast.spec, box = box, axisX = axis, axisY = axis, ... ) # Add title to spectrogram if (is.null(title.labels)) { if (!is.null(by.song)) { if (by.song == "sound.files") { title(X$sound.files[i], cex.main = cexlab) } else { title(paste0(X$sound.files[i], "-", X[i, by.song]), cex.main = cexlab) } } } else { title(paste0(X[i, title.labels], collapse = " "), cex.main = cexlab) } # Plot lines to visualize selections (start and end of signal) if (line) { if (any(names(X) == "bottom.freq") & any(names(X) == "top.freq")) { if (!is.null(by.song)) { W <- Y[Y$sound.files == X$sound.files[i] & Y[, by.song, drop = TRUE] == X[i, by.song, drop = TRUE], , drop = FALSE] W$start <- W$start - X$start[i] + mar1 W$end <- W$end - X$start[i] + mar1 } else { W <- X[i, , drop = FALSE] W$start <- mar1 W$end <- mar2 } for (e in 1:nrow(W)) { # if freq columns are not provided ys <- if (is.null(W$top.freq)) { fl[c(1, 2, 2, 1)] } else { c( W$bottom.freq[e], W$top.freq[e], W$top.freq[e], W$bottom.freq[e] ) } # plot polygon polygon( x = rep(c(W$start[e], W$end[e]), each = 2), y = ys, lty = lty, border = col, col = fill, lwd = 1.2 ) if (!is.null(sel.labels)) { text( labels = paste(W[e, sel.labels], collapse = "-"), x = (W$end[e] + W$start[e]) / 2, y = if (is.null(W$top.freq)) { fl[2] - 2 * ((fl[2] - fl[1]) / 12) } else { W$top.freq[e] }, pos = 3 ) } } } } dev.off() } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function out <- pblapply_wrblr_int( pbar = pb, X = 1:nrow(X), cl = cl, FUN = function(i) { specreFUN( X, Y, i, mar, flim, xl, picsize, res, wl, ovlp, cexlab, by.song, sel.labels, pal, dest.path, fill ) } ) } ############################################################################################################## #' alternative name for \code{\link{spectrograms}} #' #' @keywords internal #' @details see \code{\link{spectrograms}} for documentation. \code{\link{specreator}} will be deprecated in future versions. #' @export specreator <- spectrograms
/scratch/gouwar.j/cran-all/cranData/warbleR/R/spectrograms.R
#' Splits sound files #' #' \code{split_sound_files} splits sound files in shorter segments #' @usage split_sound_files(path = NULL, sgmt.dur = 10, sgmts = NULL, files = NULL, #' parallel = 1, pb = TRUE, only.sels = FALSE, X = NULL) #' @param path Directory path where sound files are found. #' If \code{NULL} (default) then the current working directory is used. #' @param sgmt.dur Numeric. Duration (in s) of segments in which sound files would be split. Sound files shorter than 'sgmt.dur' won't be split. Ignored if 'sgmts' is supplied. #' @param sgmts Numeric. Number of segments in which to split each sound file. If supplied 'sgmt.dur' is ignored. #' @param files Character vector indicating the subset of files that will be split. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. Only used when #' @param only.sels Logical argument to control if only the data frame is returned (no wave files are saved). Default is \code{FALSE}. #' @param X 'selection_table' object or a data frame with columns #' for sound file name (sound.files), selection number (selec), and start and end time of signal #' (start and end). If supplied the data frame/selection table is modified to reflect the position of the selections in the new sound files. Note that some selections could split between 2 segments. To deal with this, a 'split.sels' column is added to the data frame in which those selection are labeled as 'split'. Default is \code{NULL}. #' @family data manipulation #' @seealso \code{\link{cut_sels}} #' @export #' @name split_sound_files #' @return Wave files for each segment in the working directory (if \code{only.sels = FALSE}, named as 'sound.file.name-#.wav') and a data frame in the R environment containing the name of the original sound files (org.sound.files), the name of the clips (sound.files) and the start and end of clips in the original files. Clips are saved in .wav format. If 'X' is supplied then a data frame with the position of the selections in the newly created clips is returned instead. #' @details This function aims to reduce the size of sound files in order to simplify some processes that are limited by sound file size (big files can be manipulated, e.g. \code{\link{auto_detec}}). The function keeps the original number of channels in the output clips only for 1- and 2-channel files. #' @examples #' { #' # load data and save to temporary working directory #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' #' # split files in 1 s files #' split_sound_files(sgmt.dur = 1, path = tempdir()) #' #' # Check this folder #' tempdir() #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on mar-21-2020 (MAS) split_sound_files <- function(path = NULL, sgmt.dur = 10, sgmts = NULL, files = NULL, parallel = 1, pb = TRUE, only.sels = FALSE, X = NULL) { #### set arguments from options # get function arguments argms <- methods::formalArgs(split_sound_files) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # stop if files is not a character vector if (!is.null(files) & !is.character(files)) stop2("'files' must be a character vector") if (is.null(files)) { files <- list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE) } # list .wav files in working director # stop if no wav files are found if (length(files) == 0) stop2("no sound files in working directory") if (!is.null(X)) { # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X))) stop2("X is not of a class 'data.frame' or 'selection_table'") if (is_extended_selection_table(X)) stop2("This function cannot take extended selection tables ('X' argument)") # check if all columns are found if (any(!(c("sound.files", "selec", "start", "end") %in% colnames(X)))) { stop2(paste(paste(c("sound.files", "selec", "start", "end")[!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop2("NAs found in start and/or end columns") # if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) stop2("'start' and 'end' must be numeric") # if any start higher than end stop if (any(X$end - X$start <= 0)) stop2(paste("Start is higher than or equal to end in", length(which(X$end - X$start <= 0)), "case(s)")) } # check sgmnt duration if (is.null(sgmts)) { if (!is.numeric(sgmt.dur)) stop2("'sgmt.dur' must be numeric") } else if (!is.numeric(sgmts)) stop2("'sgmts' must be numeric") # If parallel is not numeric if (!is.numeric(parallel)) stop2("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop2("'parallel' should be a positive integer") # measure wav duration wvdr <- duration_wavs(path = path, files = files) # calculate start and end of segments and output data frame split.df_l <- lapply(files, function(x) { # calculate segment limits if (is.null(sgmts)) { # if sgmnts duration is shorter than file if (sgmt.dur < wvdr$duration[wvdr$sound.files == x]) { # get start and end of segments sq <- seq(from = 0, to = wvdr$duration[wvdr$sound.files == x], by = sgmt.dur) # add end if last sq != duration if (sq[length(sq)] != wvdr$duration[wvdr$sound.files == x]) { sq <- c(sq, wvdr$duration[wvdr$sound.files == x]) } out <- data.frame(org.sound.files = x, sound.files = paste0(gsub("\\.wav$|\\.wac$|\\.mp3$|\\.flac$", "", x, ignore.case = TRUE), "-", 1:(length(sq) - 1), ".wav"), start = sq[-length(sq)], end = sq[-1], stringsAsFactors = FALSE) } else { # if segment duration is longer or equal out <- data.frame(org.sound.files = x, sound.files = x, start = 0, end = wvdr$duration[wvdr$sound.files == x], stringsAsFactors = FALSE) } } else { # get start and end of segments sq <- seq(from = 0, to = wvdr$duration[wvdr$sound.files == x], length.out = sgmts + 1) # put in data frame out <- data.frame(org.sound.files = x, sound.files = paste0(gsub("\\.wav$|\\.wac$|\\.mp3$|\\.flac$", "", x, ignore.case = TRUE), "-", 1:(length(sq) - 1), ".wav"), start = sq[-length(sq)], end = sq[-1], stringsAsFactors = FALSE) } return(out) }) # put together in a single data frame split.df <- do.call(rbind, split.df_l) # if no sound files are produced if (!only.sels) { # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # split using a loop only those shorter than segments a_l <- pblapply_wrblr_int(pbar = pb, X = which(split.df$org.sound.files != split.df$sound.files), cl = cl, FUN = function(x) { # read clip clip <- warbleR::read_sound_file(X = split.df$org.sound.files[x], from = split.df$start[x], to = split.df$end[x], path = path, channel = 1) # add second channel if stereo if (warbleR::read_sound_file(X = split.df$org.sound.files[x], path = path, header = TRUE)$channels > 1) { clip_ch2 <- warbleR::read_sound_file(X = split.df$org.sound.files[x], from = split.df$start[x], to = split.df$end[x], path = path, channel = 2) clip <- Wave(left = clip@left, right = clip_ch2@left, samp.rate = [email protected], bit = clip@bit) } # save tuneR::writeWave(extensible = FALSE, object = clip, filename = file.path(path, split.df$sound.files[x])) return(NULL) }) # make it a vector a <- unlist(a_l) } # calculate position of selection in newly created clips if (!is.null(X)) { ## cbind new file data and X to get overlapping sels # make analogous columns on both data frames split.df$new.sound.files <- split.df$sound.files split.df$sound.files <- split.df$org.sound.files split.df$bottom.freq <- split.df$top.freq <- NA X$new.sound.files <- NA # ad unique selec ID to new files split.df$selec <- paste0("new", 1:nrow(split.df)) # select columns to bind clms <- if (!is.null(X$bottom.freq) & !is.null(X$top.freq)) c("sound.files", "new.sound.files", "selec", "start", "end", "bottom.freq", "top.freq") else c("sound.files", "new.sound.files", "selec", "start", "end") # bind together ovlp.df <- rbind(X[, clms], split.df[, clms]) # add unique id for each selection ovlp.df$sel.id <- paste(ovlp.df$sound.files, ovlp.df$selec, sep = "-") X$sel.id <- paste(X$sound.files, X$selec, sep = "-") # get which selection are found in which new files ovlp.df <- warbleR::overlapping_sels(ovlp.df, indx.row = TRUE, max.ovlp = 0.0000001, pb = pb, parallel = parallel, verbose = FALSE) ovlp.df$..row <- 1:nrow(ovlp.df) # split in new files rows and selection rows new.sf.df <- ovlp.df[!is.na(ovlp.df$new.sound.files) & !is.na(ovlp.df$ovlp.sels), ] org.sls.df <- ovlp.df[is.na(ovlp.df$new.sound.files), ] # re-add other columns X$org.sound.files <- X$sound.files org.sls.df <- merge(org.sls.df, X[, setdiff(names(X), clms)], by = "sel.id") # order columns org.sls.df <- sort_colms(org.sls.df) # find time positions in new files new.sels_l <- lapply(1:nrow(new.sf.df), function(x) { Y <- new.sf.df[x, , drop = FALSE] # get those selection found within Y contained.sls <- org.sls.df[org.sls.df$..row %in% strsplit(Y$indx.row, "/")[[1]], ] # if selection were found within Y if (nrow(contained.sls) > 0) { contained.sls$sound.files <- Y$new.sound.files # get new start and end contained.sls$start <- contained.sls$start - Y$start contained.sls$end <- contained.sls$end - Y$start contained.sls$start[contained.sls$start < 0] <- 0 contained.sls$end[contained.sls$end > Y$end] <- Y$end return(contained.sls) } else { return(NULL) } }) new.sels <- do.call(rbind, new.sels_l) new.sels$..row <- new.sels$indx.row <- new.sels$ovlp.sels <- new.sels$new.sound.files <- NULL # find which selection were split in 2 or more new files new.sels$split.sels <- NA cnt.sels <- table(new.sels$sel.id) new.sels$split.sels[new.sels$sel.id %in% names(cnt.sels[cnt.sels > 1])] <- "split" new.sels$sel.id <- NULL row.names(new.sels) <- 1:nrow(new.sels) return(new.sels) } else { return(split.df) } } ############################################################################################################## #' alternative name for \code{\link{split_sound_files}} #' #' @keywords internal #' @details see \code{\link{split_sound_files}} for documentation. \code{\link{split_wavs}} will be deprecated in future versions. #' @export split_wavs <- split_sound_files
/scratch/gouwar.j/cran-all/cranData/warbleR/R/split_sound_files.R
#' Interactive view of spectrograms to tailor selections #' #' \code{tailor_sels} produces an interactive spectrographic view in #' which the start/end times and frequency range of acoustic signals listed in a data frame can be adjusted. #' @usage tailor_sels(X = NULL, wl = 512, flim = c(0,22), wn = "hanning", mar = 0.5, #' osci = TRUE, pal = reverse.gray.colors.2, ovlp = 70, auto.next = FALSE, pause = 1, #' comments = TRUE, path = NULL, frange = TRUE, fast.spec = FALSE, ext.window = TRUE, #' width = 15, height = 5, index = NULL, collevels = NULL, #' title = c("sound.files", "selec"), ts.df = NULL, col = "#E37222", #' alpha = 0.7, auto.contour = FALSE, ...) #' @param X 'selection_table', 'extended_selection_table' object or data frame with the following columns: 1) "sound.files": name of the .wav #' files, 2) "selec": number of the selections, 3) "start": start time of selections, 4) "end": #' end time of selections. Notice that, if an output file ("seltailor_output.csv") is found in the working directory it will be given priority over an input data frame. #' @param wl A numeric vector of length 1 specifying the spectrogram window length. Default is 512. #' @param flim A numeric vector of length 2 specifying the frequency limit (in kHz) of #' the spectrogram, as in the function \code{\link[seewave]{spectro}}. #' Default is c(0,22). #' @param wn A character vector of length 1 specifying the window function (by default "hanning"). #' See function \code{\link[seewave]{ftwindow}} for more options. #' @param mar Numeric vector of length 1. Specifies the margins adjacent to the #' start and end points of the selections to define spectrogram limits. Default is 0.5. #' @param osci Logical argument. If \code{TRUE} adds a oscillogram whenever the spectrograms are produced #' with higher resolution (see seltime). Default is \code{TRUE}. #' The external program must be closed before resuming analysis. Default is \code{NULL}. #' @param pal A color palette function to be used to assign colors in the #' plot, as in \code{\link[seewave]{spectro}}. Default is reverse.gray.colors.2. See Details. #' @param ovlp Numeric vector of length 1 specifying the percent overlap between two #' consecutive windows, as in \code{\link[seewave]{spectro}}. Default is 70. #' @param auto.next Logical argument to control whether the functions moves automatically to the #' next selection. The time interval before moving to the next selection is controlled by the 'pause' argument. Ignored if \code{ts.df = TRUE}. #' @param pause Numeric vector of length 1. Controls the duration of the waiting period before #' moving to the next selection (in seconds). Default is 1. #' @param comments Logical argument specifying if 'sel.comment' (when in data frame) should be included #' in the title of the spectrograms. Default is \code{TRUE}. #' @param path Character string containing the directory path where the sound files are located. #' @param frange Logical argument specifying whether limits on frequency range should be #' recorded. #' If \code{TRUE} (default) time and frequency limits are recorded. #' @param fast.spec Logical. If \code{TRUE} then image function is used internally to create spectrograms, which substantially #' increases performance (much faster), although some options become unavailable, as sc (amplitude scale). #' This option is indicated for signals with high background noise levels. Palette colors \code{\link[monitoR:specCols]{gray.1}}, \code{\link[monitoR:specCols]{gray.2}}, #' \code{\link[monitoR:specCols]{gray.3}}, \code{\link[monitoR:specCols]{topo.1}} and \code{\link[monitoR:specCols]{rainbow.1}} (which should be imported from the package monitoR) seem #' to work better with 'fast' spectrograms. Palette colors \code{\link[monitoR:specCols]{gray.1}}, \code{\link[monitoR:specCols]{gray.2}}, #' \code{\link[monitoR:specCols]{gray.3}} offer #' decreasing darkness levels. #' @param ext.window Logical. If \code{TRUE} then and external graphic window is used. Default #' dimensions can be set using the 'width' and 'height' arguments. Default is \code{TRUE}. #' @param width Numeric of length 1 controlling the width of the external graphic window. Ignored #' if \code{ext.window = FALSE}. Default is 15. #' @param height Numeric of length 1 controlling the height of the external graphic window. #' Ignored if \code{ext.window = FALSE}. Default is 5. #' @param index Numeric vector indicating which selections (rows) of 'X' should be tailored. #' Default is \code{NULL}. Ignored when the process is resumed. This can be useful when combined #' with \code{\link{filtersels}}) output (see 'index' argument in \code{\link{filtersels}}). #' @param collevels Numeric. Set of levels used to partition the amplitude range (see #' \code{\link[seewave]{spectro}}). #' @param title Character vector with the names of the columns to be included in the title for each #' selection. #' @param ts.df Optional. Data frame with frequency contour time series of signals to be tailored. If provided then #' 'autonext' is set to \code{FALSE}. Default is \code{NULL}. The data frame must include the 'sound.files' and 'selec' #' columns for the same selections included in 'X'. #' @param col Character vector defining the color of the points when 'ts.df' is provided. Default is "#E37222" (orange). #' @param alpha Numeric of length one to adjust transparency of points when adjusting frequency contours. #' @param auto.contour Logical. If \code{TRUE} contours are displayed automatically #' (without having to click on 'contour'). Note that adjusting the selection box #' (frequency/time limits) won't be available. Default is \code{FALSE}. Ignored if #' 'ts.df' is not provided. #' @param ... Additional arguments to be passed to the internal spectrogram creating function for customizing graphical output. The function is a modified version of \code{\link[seewave]{spectro}}, so it takes the same arguments. #' @return data frame similar to X with the and a .csv file saved in the working directory with start and end time of #' selections. #' @export #' @name tailor_sels #' @examples #' \dontrun{ #' data(list = c("Phae.long1", "Phae.long2", "Phae.long3", "Phae.long4", "lbh_selec_table")) #' writeWave(Phae.long1, file.path(tempdir(), "Phae.long1.wav")) #' writeWave(Phae.long2, file.path(tempdir(), "Phae.long2.wav")) #' writeWave(Phae.long3, file.path(tempdir(), "Phae.long3.wav")) #' writeWave(Phae.long4, file.path(tempdir(), "Phae.long4.wav")) #' #' tailor_sels(X = lbh_selec_table, flim = c(1, 12), wl = 300, auto.next = TRUE, path = tempdir()) #' #' # Read output .csv file #' seltailor.df <- read.csv(file.path(tempdir(), "seltailor_output.csv")) #' seltailor.df #' #' # check this directory for .csv file after stopping function #' tempdir() #' } #' @details This function produces an interactive spectrographic #' view in which users can select new time/frequency #' coordinates the selections. 4 "buttons" are provided at the upper right side of the spectrogram that #' allow to stop the analysis (stop symbol, a solid rectangle), go to the next sound file (">>"), return to the #' previous selection ("<<") or delete #' the current selection ("X"). An additional "button" to tailored frequency contour is shown #' when 'ts.df' is provided. The button contains a symbol with a 4 point contour. When a unit has been selected, the function plots #' dotted lines in the start and end of the selection in the spectrogram (or a box if #' \code{frange = TRUE}). Only the last selection is kept for each #' selection that is adjusted. The function produces a .csv file (seltailor_output.csv) #' with the same information than the input data frame, except for the new time #' coordinates, plus a new column (X$tailored) indicating if the selection #' has been tailored. The file is saved in the working directory and is updated every time the user #' moves into the next sound file (">>") or stop the process #' (stop "button"). It also return the same data frame as and object in the R environment. #' If no selection is made (by clicking on ">>") the #' original time/frequency coordinates are kept. When resuming the process (after "stop" and re-running #' the function in the same working directory), the function will continue working on the #' selections that have not been analyzed. When deleting a file (X button) an orange "X" when returning to that selection. If X is used again the selection is recovered. #' The function also displays a progress bar right on #' top of the spectrogram. The zoom can be adjusted by setting the \code{mar} argument. #' To fix contours a data.frame containing the 'sound.files' and 'selec' columns as in 'X' as well #' as the frequency values at each contour step must be provided. The function plots points corresponding to the #' time/frequency coordinates of each element of the contour. Clicking on the spectrogram will substitute the #' frequency value of the points. The contour point closest in time to the "click" will be replaced by the #' frequency value of the "click". #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on jul-5-2016 (MAS) tailor_sels <- function(X = NULL, wl = 512, flim = c(0, 22), wn = "hanning", mar = 0.5, osci = TRUE, pal = reverse.gray.colors.2, ovlp = 70, auto.next = FALSE, pause = 1, comments = TRUE, path = NULL, frange = TRUE, fast.spec = FALSE, ext.window = TRUE, width = 15, height = 5, index = NULL, collevels = NULL, title = c("sound.files", "selec"), ts.df = NULL, col = "#E37222", alpha = 0.7, auto.contour = FALSE, ...) { # reset warnings on.exit(options(warn = .Options$warn), add = TRUE) #### set arguments from options # get function arguments argms <- methods::formalArgs(tailor_sels) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # unique path for csv file csv.path <- path # no autonext if ts.df provided if (auto.next & !is.null(ts.df)) { warning2(x = "'auto.next' not available when 'ts.df' is provided") auto.next <- FALSE } # merge ts.df and X if (!is.null(ts.df)) { if (is.data.frame(ts.df)) { if (nrow(X) != nrow(ts.df)) stop2("number of rows in 'ts.df' and 'X' do not match") # fix and extract colnames from ts.df names(ts.df)[-c(1:2)] <- gsub("_|-", ".", names(ts.df)[-c(1:2)]) # get extra names other than sound.files and selec ncl <- names(ts.df)[-c(1:2)] # stop if not alls selections have contour data if (!identical(paste(ts.df$sound.files, ts.df$selec), paste(X$sound.files, X$selec))) { stop2("Not all selections in 'X' have countour data in 'ts.df'") } # add contour data to X if (is_extended_selection_table(X)) { # merge to a different object name X2 <- merge(X, ts.df, by = c("sound.files", "selec")) # and add acousitc and metadata X <- fix_extended_selection_table(X = X2, Y = X) } else { X <- merge(X, ts.df, by = c("sound.files", "selec")) } } else { # if ts.df is a list if (nrow(X) != length(ts.df)) stop2("number of rows in 'X' and length of 'ts.df' do not match") mxts <- max(sapply(ts.df, nrow)) out <- lapply(seq_len(length(ts.df)), function(x) { z <- ts.df[[x]] df <- data.frame(t(c(z$frequency, rep(NA, mxts - nrow(z)), z$absolute.time, rep(NA, mxts - nrow(z))))) colnames(df) <- paste0(colnames(df), rep(c("...FREQ", "...TIME"), each = mxts)) df$sound.files.selec <- names(ts.df)[x] return(df) }) ts.df2 <- do.call(rbind, out) X$sound.files.selec <- paste(X$sound.files, X$selec, sep = "-") X <- merge(X, ts.df2, by = c("sound.files.selec")) ncl <- names(ts.df2)[-ncol(ts.df2)] } } else { auto.contour <- FALSE } # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X))) stop2("X is not of a class 'data.frame' or 'selection_table'") # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop2("NAs found in start and/or end") # if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) stop2("'start' and 'end' must be numeric") # if any start higher than end stop if (any(X$end - X$start <= 0)) stop2(paste("Start is higher than or equal to end in", length(which(X$end - X$start <= 0)), "case(s)")) # check title columns if (any(!title %in% names(X))) stop2(paste("title column(s)", title[!title %in% names(X)], "not found")) # stop if not all sound files were found if (!is_extended_selection_table(X)) { fs <- list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE) if (length(unique(X$sound.files[(X$sound.files %in% fs)])) != length(unique(X$sound.files))) { stop2(paste( length(unique(X$sound.files)) - length(unique(X$sound.files[(X$sound.files %in% fs)])), "sound file(s) not found" )) } } else { path <- NULL } # if is extended then no path needed if (frange & !all(any(names(X) == "bottom.freq"), any(names(X) == "top.freq"))) { X$top.freq <- X$bottom.freq <- NA } # if working on a extended selection table if (!file.exists(file.path(csv.path, "seltailor_output.csv"))) { X$tailored <- "" X$tailored <- as.character(X$tailored) if (!is.null(index)) X$tailored[!1:nrow(X) %in% index] <- "y" write.csv(X[X$tailored != "delete", ], file.path(csv.path, "seltailor_output.csv"), row.names = FALSE) } else { # tell user file already existed message2(x = "'seltailor_output.csv' found in working directory, resuming tailoring ...") if (is_extended_selection_table(X)) { # read with different object name X2 <- read.csv(file.path(csv.path, "seltailor_output.csv"), stringsAsFactors = FALSE) # and add acousitc and metadata X <- fix_extended_selection_table(X = X2, Y = X) } else { X <- read.csv(file.path(csv.path, "seltailor_output.csv"), stringsAsFactors = FALSE) } # stop if all selections were analyzed if (any(is.na(X$tailored))) X$tailored[is.na(X$tailored)] <- "" if (all(any(!is.na(X$tailored)), sum(X$tailored %in% c("y", "delete")) == nrow(X))) { message2(x = "all selections have been analyzed") stop2() } # add with time series data if (!is.null(ts.df)) { if (any(!names(ts.df) %in% names(X))) { stop2("'seltailor_output.csv' file in working directory does not contain frequency contour columns") } ncl <- ncl[!ncl %in% c("sound.files", "selec")] } } dn <- 1:nrow(X) if (any(!is.na(X$tailored))) { if (length(which(X$tailored == "y")) > 0) { dn <- which(X$tailored != "y") } } # set external window function if (any(Sys.info()[1] == c("Linux", "Windows"))) extwin <- grDevices::X11 else extwin <- grDevices::quartz # start external graphic device if (ext.window) extwin(width = width, height = height) # set original number of sels to tailor org.sel.n <- nrow(X) # this first loop runs over selections h <- 1 repeat{ j <- dn[h] if (exists("prev.plot")) rm(prev.plot) rec <- warbleR::read_sound_file(X, index = j, path = path, header = TRUE) main <- do.call(paste, as.list(X[j, names(X) %in% title])) f <- rec$sample.rate # for spectro display fl <- flim # in case flim its higher than nyquist frequency if (fl[2] > f / 2000) fl[2] <- f / 2000 len <- rec$samples / f # for spectro display start <- numeric() # save results end <- numeric() # save results selcount <- 0 tlim <- c(X$start[j] - mar, X$end[j] + mar) if (tlim[1] < 0) tlim[1] <- 0 if (tlim[2] > rec$samples / f) tlim[2] <- rec$samples / f org.start <- X$start[j] # original start value # set an undivided window par(mfrow = c(1, 1), mar = c(3, 3, 1.8, 0.1)) # create spectrogram spectro_wrblr_int(warbleR::read_sound_file(X = X, index = j, path = path, from = tlim[1], to = tlim[2]), f = f, wl = wl, ovlp = ovlp, wn = wn, heights = c(3, 2), osc = osci, palette = pal, main = NULL, axisX = TRUE, grid = FALSE, collab = "black", alab = "", fftw = TRUE, colwave = "#07889B", collevels = collevels, flim = fl, scale = FALSE, axisY = TRUE, fast.spec = fast.spec, ... ) if (!osci) { mtext("Time (s)", side = 1, line = 1.8) mtext("Frequency (kHz)", side = 2, xpd = TRUE, las = 0) } # title mtext(main, side = 3, line = 0.65, xpd = NA, las = 0, font = 2, cex = 1.3, col = "#062F4F") # progress bar prct <- 1 - (sum(X$tailored == "") / org.sel.n) x2 <- prct * diff(tlim) y <- fl[2] + diff(fl) * 0.022 lines(x = c(0, x2), y = rep(y, 2), lwd = 7, col = adjustcolor("#E37222", alpha.f = 0.6), xpd = TRUE) text(x = x2 + (diff(tlim) * 0.017), y = y, xpd = TRUE, labels = paste0(floor(prct * 100), "%"), col = "#E37222", cex = 0.8) options(warn = -1) # add lines of selections on spectrogram if ((any(is.na(X$bottom.freq[j]), is.na(X$top.freq[j])))) { polygon(x = rep(c(X$start[j], X$end[j]) - tlim[1], each = 2), y = c(fl, sort(fl, decreasing = TRUE)), lty = 3, border = "#07889B", lwd = 1.2, col = adjustcolor("#07889B", alpha.f = 0.15)) } else { polygon(x = rep(c(X$start[j], X$end[j]) - tlim[1], each = 2), y = c(c(X$bottom.freq[j], X$top.freq[j]), c(X$top.freq[j], X$bottom.freq[j])), lty = 3, border = "#07889B", lwd = 1.2, col = adjustcolor("#07889B", alpha.f = 0.15)) } # add buttons xs <- grconvertX(x = c(0.94, 0.94, 0.99, 0.99), from = "npc", to = "user") labels <- c("stop", "next", "previous", "delete") if (!is.null(ts.df)) labels <- c(labels, "contour") mrg <- 0.05 cpy <- sapply(0:(length(labels) - 1), function(x) { 0.95 - (x * 3 * mrg) }) # mid position ofbuttons in c(0, 1) range ys <- c(-mrg, mrg, mrg, -mrg) grYs <- lapply(seq_len(length(cpy)), function(x) { grY <- grconvertY(y = cpy[x] - ys, from = "npc", to = "user") polygon(x = xs, y = grY, border = "#4ABDAC", col = adjustcolor("#E37222", alpha.f = 0.22), lwd = 2) # plot symbols if (labels[x] == "stop") { points(x = mean(xs), y = mean(grY), pch = 15, cex = 1.5, col = "#4ABDAC") } if (labels[x] == "next") { text(x = mean(xs), y = mean(grY), labels = ">>", cex = 1.2, font = 2, col = "#4ABDAC") } if (labels[x] == "previous") { text(x = mean(xs), y = mean(grY), labels = "<<", cex = 1.2, font = 2, col = "#4ABDAC") } if (labels[x] == "delete") { points(x = mean(xs), y = mean(grY), pch = 4, cex = 1.5, lwd = 3, col = if (X$tailored[j] != "delete") "#4ABDAC" else "#E37222") } if (labels[x] == "contour") { points(x = c(min(xs) + ((max(xs) - min(xs)) / 4.2), min(xs) + ((max(xs) - min(xs)) / 2.5), min(xs) + ((max(xs) - min(xs)) / 1.8), min(xs) + ((max(xs) - min(xs))) / 1.4), y = c(((max(grY) - min(grY)) / 2), ((max(grY) - min(grY)) / 5), ((max(grY) - min(grY)) / 3), ((max(grY) - min(grY)) / 6)) * c(-1, 1, -1, 1) + grY[c(1, 2, 4, 3)], pch = 20, col = "#4ABDAC") lines(x = c(min(xs) + ((max(xs) - min(xs)) / 4.2), min(xs) + ((max(xs) - min(xs)) / 2.5), min(xs) + ((max(xs) - min(xs)) / 1.8), min(xs) + ((max(xs) - min(xs))) / 1.4), y = c(((max(grY) - min(grY)) / 2), ((max(grY) - min(grY)) / 5), ((max(grY) - min(grY)) / 3), ((max(grY) - min(grY)) / 5)) * c(-1, 1, -1, 1) + grY[c(1, 2, 4, 3)], col = "#4ABDAC") } return(grY) }) # ask users to select what to do next (1 click) if (!auto.contour) { xy2 <- xy <- locator(n = 1, type = "n") } else { xy2 <- xy <- list(x = 0, y = 0) } # if selected is lower than 0 make it xy$x[xy$x < 0] <- 0 xy$y[xy$y < 0] <- 0 xy2$x[xy2$x < 0] <- 0 xy2$y[xy2$y < 0] <- 0 # fix freq if (!is.null(ts.df)) { if (xy$x > min(xs) & xy$x < max(xs) & xy$y > min(grYs[[5]]) & xy$y < max(grYs[[5]]) | auto.contour) { Y <- fix_cntr_wrblr_int(X, j, ending.buttons = 1:4, ncl, tlim, xs, grYs, flim = fl, col, alpha, l = !is.data.frame(ts.df)) X[, ncl] <- Y$ts.df xy <- Y$xy rm(Y) if (selcount > 0) X$tailored[j] <- "y" write.csv(X[X$tailored != "delete", ], file.path(csv.path, "seltailor_output.csv"), row.names = FALSE) } } # if delete if (xy$x > min(xs) & xy$x < max(xs) & xy$y > min(grYs[[4]]) & xy$y < max(grYs[[4]])) { # delete row if not deleted otherwise undelee if (X$tailored[j] != "delete") { X$tailored[j] <- "delete" } else { X$tailored[j] <- "y" } write.csv(X[X$tailored != "delete", ], file.path(csv.path, "seltailor_output.csv"), row.names = FALSE) if (sum(X$tailored %in% c("y", "delete")) == nrow(X)) { dev.off() # return X return(X[X$tailored != "delete", ]) # message2(x = "all selections have been analyzed") stop2(x = "all selections have been analyzed") } h <- h + 1 } # if previous if (xy$x > min(xs) & xy$x < max(xs) & xy$y > min(grYs[[3]]) & xy$y < max(grYs[[3]])) { h <- h - 1 if (h == 0) { h <- 1 message2(x = "This selection was the first one during the selection procedure (can't go further back)") } } # if next sel if (xy$x > min(xs) & xy$x < max(xs) & xy$y > min(grYs[[2]]) & xy$y < max(grYs[[2]])) { X$tailored[j] <- "y" write.csv(X[X$tailored != "delete", ], file.path(csv.path, "seltailor_output.csv"), row.names = FALSE) if (sum(X$tailored %in% c("y", "delete")) == nrow(X)) { dev.off() # return X return(X[X$tailored != "delete", ]) # message2(x = "all selections have been analyzed") stop2("all selections have been analyzed") } h <- h + 1 } # stop if (xy$x > min(xs) & xy$x < max(xs) & xy$y > min(grYs[[1]]) & xy$y < max(grYs[[1]])) { dev.off() if (selcount > 0) X$tailored[j] <- "y" write.csv(X[X$tailored != "delete", ], file.path(csv.path, "seltailor_output.csv"), row.names = FALSE) # return X return(X[X$tailored != "delete", ]) # message2(x = "Stopped by user") stop2("Stopped by user") } # while not inside buttons out <- sapply(seq_len(length(labels)), function(w) out <- !all(xy$x > min(xs) & xy$x < max(xs) & xy$y > min(grYs[[w]]) & xy$y < max(grYs[[w]]))) while (all(out)) { # select second point xy <- locator(n = 1, type = "n") # if selected is lower than 0 make it xy$x[xy$x < 0] <- 0 xy$y[xy$y < 0] <- 0 # fix freq if (!is.null(ts.df)) { if (xy$x > min(xs) & xy$x < max(xs) & xy$y > min(grYs[[5]]) & xy$y < max(grYs[[5]])) { Y <- fix_cntr_wrblr_int(X, j, ending.buttons = 1:4, ncl, tlim, xs, grYs, flim = fl, col, alpha, l = !is.data.frame(ts.df)) X[, ncl] <- Y$ts.df xy <- Y$xy rm(Y) if (selcount > 0) X$tailored[j] <- "y" write.csv(X[X$tailored != "delete", ], file.path(csv.path, "seltailor_output.csv"), row.names = FALSE) } } # if delete if (xy$x > min(xs) & xy$x < max(xs) & xy$y > min(grYs[[4]]) & xy$y < max(grYs[[4]])) { # delete row X$tailored[j] <- "delete" write.csv(X[X$tailored != "delete", ], file.path(csv.path, "seltailor_output.csv"), row.names = FALSE) if (sum(X$tailored %in% c("y", "delete")) == nrow(X)) { dev.off() # return X return(X[X$tailored != "delete", ]) # message2(x = "all selections have been analyzed") stop2(x = "all selections have been analyzed") } else { h <- h + 1 break } } # if previous if (xy$x > min(xs) & xy$x < max(xs) & xy$y > min(grYs[[3]]) & xy$y < max(grYs[[3]])) { h <- h - 1 if (h == 0) { h <- 1 message2(x = "This selection was the first one during the selection procedure (can't go further back)") } break } # if next sel if (xy$x > min(xs) & xy$x < max(xs) & xy$y > min(grYs[[2]]) & xy$y < max(grYs[[2]])) { X$tailored[j] <- "y" write.csv(X[X$tailored != "delete", ], file.path(csv.path, "seltailor_output.csv"), row.names = FALSE) if (sum(X$tailored %in% c("y", "delete")) == nrow(X)) { dev.off() # return X return(X[X$tailored != "delete", ]) options(show.error.messages = FALSE) # message2(x = "all selections have been analyzed") stop2(x = "all selections have been analyzed") } else { h <- h + 1 break } } # stop if (xy$x > min(xs) & xy$x < max(xs) & xy$y > min(grYs[[1]]) & xy$y < max(grYs[[1]])) { dev.off() if (selcount > 0) X$tailored[j] <- "y" write.csv(X[X$tailored != "delete", ], file.path(csv.path, "seltailor_output.csv"), row.names = FALSE) # return X return(X[X$tailored != "delete", ]) # message2(x = "Stopped by user") stop2(x = "Stopped by user") } if (exists("prev.plot")) xy2 <- locator(n = 1, type = "n") xy3 <- list() xy3$x <- c(xy$x, xy2$x) xy3$y <- c(xy$y, xy2$y) if (exists("prev.plot")) replayPlot(prev.plot) else prev.plot <- recordPlot() if (frange) { polygon(x = rep(sort(xy3$x), each = 2), y = c(sort(xy3$y), sort(xy3$y, decreasing = TRUE)), lty = 3, border = "#E37222", lwd = 1.2, col = adjustcolor("#EFAA7B", alpha.f = 0.15)) } else { polygon(x = rep(sort(xy3$x), each = 2), y = c(fl, sort(fl, decreasing = TRUE)), lty = 3, border = "#E37222", lwd = 1.2, col = adjustcolor("#EFAA7B", alpha.f = 0.15)) } X$start[j] <- tlim[1] + min(xy3$x) X$end[j] <- tlim[1] + max(xy3$x) X$tailored[j] <- "y" if (frange) { X$bottom.freq[j] <- min(xy3$y) if (min(xy3$y) < 0) X$bottom.freq[j] <- 0 X$top.freq[j] <- max(xy3$y) } selcount <- selcount + 1 # auto next if (auto.next) { X$start[j] <- tlim[1] + min(xy3$x) X$end[j] <- tlim[1] + max(xy3$x) # fix start if negative if (X$start[j] < 0) { X$start[j] <- 0 } # fix if higher than file duration in extended selection tables if (is_extended_selection_table(X)) { if (X$end[j] > duration(attr(X, "wave.objects")[[which(names(attr(X, "wave.objects")) == X$sound.files[j])[1]]])) { X$end[j] <- duration(attr(X, "wave.objects")[[which(names(attr(X, "wave.objects")) == X$sound.files[j])[1]]]) } } if (frange) { X$bottom.freq[j] <- min(xy3$y) if (min(xy3$y) < 0) X$bottom.freq[j] <- 0 X$top.freq[j] <- max(xy3$y) } # save selections write.csv(X[X$tailored != "delete", ], file.path(csv.path, "seltailor_output.csv"), row.names = FALSE) if (sum(X$tailored %in% c("y", "delete")) == nrow(X)) { dev.off() # return X return(X[X$tailored != "delete", ]) # message2(x = "all selections have been analyzed") stop2(x = "all selections have been analyzed") } else { Sys.sleep(pause) h <- h + 1 break } } } } } ############################################################################################################## #' alternative name for \code{\link{tailor_sels}} #' #' @keywords internal #' @details see \code{\link{tailor_sels}} for documentation. \code{\link{seltailor}} will be deprecated in future versions. #' @export seltailor <- tailor_sels
/scratch/gouwar.j/cran-all/cranData/warbleR/R/tailor_sels.R
#' Randomization test for singing coordination #' #' Monte Carlo randomization test to assess the statistical significance of overlapping or alternating singing (or any other simultaneously occurring behavior). #' @usage test_coordination(X, iterations = 1000, ovlp.method = "count", #' randomization = "keep.gaps", less.than.chance = TRUE, parallel = 1, pb = TRUE, #' rm.incomp = FALSE, cutoff = 2, rm.solo = FALSE) #' @param X Data frame containing columns for singing event (sing.event), #' individual (indiv), and start and end time of signal (start and end). #' @param iterations number of iterations for shuffling and calculation of the expected number of overlaps. Default is 1000. #' @param ovlp.method Character string defining the method to measure the amount of overlap. Three methods are available: #' \itemize{ #' \item \code{count}: count the number of overlapping signals (default) #' \item \code{time.overlap}: measure the total duration (in s) in which signals overlap #' \item \code{time.distance}: measure the time (in s) to the other individual's closest signal. This is the only method that can take more than 2 individuals. #' } #' @param randomization Character string defining the procedure for signal randomization. Three methods are available: #' \itemize{ #' \item \code{keep.gaps} the position of both signals and gaps (i.e. intervals between signals) are randomized. Default. #' \item \code{sample.gaps} gaps are simulated using a lognormal distribution with #' mean and standard deviation derived from the observed gaps. Signal position is randomized. #' \item \code{keep.song.order} only the position of gaps is randomized. #' } #' More details in Masco et al. (2015). #' @param less.than.chance Logical. If \code{TRUE} the test evaluates whether overlaps occur less often than expected by chance. #' If \code{FALSE} the opposite pattern is evaluated (whether overlaps occur more often than expected by chance). #' Default is \code{TRUE}. #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @param rm.incomp Logical. If \code{TRUE} removes the events that don't have 2 interacting individuals. Default is #' \code{FALSE}. #' @param cutoff Numeric. Determines the minimum number of signals per individual in a singing event. Events not meeting #' this criterium are removed. Default is 2. #' Note that randomization tests are not reliable with very small sample sizes. Ideally 10 or more signals per individual #' should be available in each singing event. #' @param rm.solo Logical. Controls if signals that are not alternated at the start or end of the #' sequence are removed (if \code{TRUE}). For instance, the sequence of signals A-A-A-B-A-B-A-B-B-B (in which A and B represent different individuals, as in the 'indiv' column) would be subset to #' A-B-A-B-A-B. Default is \code{FALSE}. #' @return A data frame with the following columns: #' \itemize{ #' \item \code{sing.event}: singing event ID #' \item \code{obs.overlap}: observed amount of overlap (counts or total duration, depending on overlap method, see 'ovlp.method' argument) #' \item \code{mean.random.ovlp}: mean amount of overlap expected by chance #' \item \code{p.value}: p value #' \item \code{coor.score}: coordination score (\emph{sensu} Araya-Salas et al. 2017), #' calculated as: #' \deqn{(obs.overlap - mean.random.ovlp) / mean.random.ovlp} #' Positive values indicate a tendency to overlap while negative values indicate a tendency to alternate. NA values will be returned when events cannot be randomized (e.g. too few signals). #' } #' @export #' @name test_coordination #' @details This function calculates the probability of finding an equal or more extreme amount of song overlap (higher or lower) in a coordinated singing event (or any pair-coordinated behavior). #' The function shuffles the sequences of signals and silence-between-signals for both individuals to produce #' a null distribution of overlaps expected by chance. The observed overlaps is compared to this #' expected values. The p-values are calculated as the proportion of random expected values that were lower (or higher) #' than the observed value. All procedures described in Masco et al. (2015) are implemented. In addition, either the number (\code{ovlp.method = "count"}) or the total duration (\code{ovlp.method = "time.overlap"}) in which signals overlap can be used for estimating the overall degree of overlap. The function runs one test for each singing event in the input data frame. This function assumes that there are no overlaps between signals belonging to the same individual. See Masco et al. (2015) for recommendations on randomization procedures for specific signal structures. #' @examples{ #' #load simulated singing data (see data documentation) #' data(sim_coor_sing) #' #' # set global options (this can also be set within the function call) #' warbleR_options(iterations = 100, pb = FALSE) #' #' # testing if coordination happens less than expected by chance #' test_coordination(sim_coor_sing) #' #' # testing if coordination happens more than expected by chance #' test_coordination(sim_coor_sing, less.than.chance = FALSE) #' #' # using "duration" method and "keep.song.order" as randomization procedure #' test_coordination(sim_coor_sing, ovlp.method = "time.overlap", #' randomization = "keep.song.order") #' } #' #' @references #' { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. #' Methods in Ecology and Evolution, 8(2), 184-191. #' #' Araya-Salas M., Wojczulanis-Jakubas K., Phillips E.M., Mennill D.J., Wright T.F. #' (2017) To overlap or not to overlap: context-dependent coordinated singing in #' lekking long-billed hermits. Animal Behavior 124, 57-65. #' #' Keenan EL, Odom KJ, M Araya-Salas, KG Horton, M Strimas-Mackey,MA Meatte, NI Mann,PJ Slater,JJ Price, and CN Templeton . 2020. Breeding season length predicts duet coordination and consistency in Neotropical wrens (Troglodytidae). Proceeding of the Royal Society B. 20202482. #' #' Masco, C., Allesina, S., Mennill, D. J., and Pruett-Jones, S. (2015). The Song #' Overlap Null model Generator (SONG): a new tool for distinguishing between random #' and non-random song overlap. Bioacoustics. #' #' Rivera-Caceres K, E Quiros-Guerrero E, M Araya-Salas, C Templeton & W Searcy. (2018). Early development of vocal interaction rules in a duetting songbird. Royal Society Open Science. 5, 171791. #' #' Rivera-Caceres K, E Quiros-Guerrero, M Araya-Salas & W Searcy. (2016). Neotropical wrens learn new duet as adults. Proceedings of the Royal Society B. 285, 20161819 #' } #' @author Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on apr-11-2018 (MAS) test_coordination <- function(X = NULL, iterations = 1000, ovlp.method = "count", randomization = "keep.gaps", less.than.chance = TRUE, parallel = 1, pb = TRUE, rm.incomp = FALSE, cutoff = 2, rm.solo = FALSE) { #### set arguments from options # get function arguments argms <- methods::formalArgs(test_coordination) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } if (!is.data.frame(X)) stop2("X is not a data frame") # stop if some cells are not labeled if (any(is.na(X$sing.event))) stop2("NA's in singing event names ('sing.event' column) not allowed") if (any(is.na(X$indiv))) stop2("NA's in individual names ('indiv' column) not allowed") # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop2("NAs found in start and/or end") # remove hidden levels X <- droplevels(X) # remove solo singing if (rm.solo) { rmslX <- lapply(unique(X$sing.event), function(x) { Y <- X[X$sing.event == x, ] Y <- Y[order(Y$start), ] Y_list <- split(Y, Y$indiv) fst <- max(sapply(Y_list, function(x) which(Y$start == min(x$start)))) - 1 lst <- min(sapply(Y_list, function(x) which(Y$start == max(x$start)))) - 1 if (lst > nrow(Y)) { lst <- nrow(Y) } Y <- Y[fst:lst, ] }) X <- do.call(rbind, rmslX) } # stop if some events do not have 2 individuals qw <- as.data.frame(tapply(X$sing.event, list(X$sing.event, X$indiv), length)) qw2 <- qw qw2[qw2 > 0] <- 1 indiv.cnt <- apply(qw2, 1, sum, na.rm = TRUE) sng.cnt <- apply(qw, 1, function(x) any(na.omit(x) < cutoff)) # complete singing events if (any(indiv.cnt < 2)) { if (rm.incomp) { X <- X[X$sing.event %in% names(indiv.cnt)[indiv.cnt == 2], ] warning2("Some events didn't have 2 interacting individuals and were excluded") } else { warning2("Some singing events don't have 2 interacting individuals ('indiv' column)") } } # if any more event has more than 2 individuals if (any(indiv.cnt > 2) & ovlp.method != "time.closest") { stop2("Some events have more than 2 individuals, this is only possible with ovlp.method = 'time.closest'") } # deal with cutoff value if (any(sng.cnt)) { X <- X[X$sing.event %in% names(indiv.cnt)[!sng.cnt], ] warning2("Some individuals didn't have more songs that the 'cutoff' and the events were excluded") } # if nothing was left if (nrow(X) == 0) stop2("No events left after removing incomplete events") # if iterations is not vector or length==1 stop if (any(!is.vector(iterations), !is.numeric(iterations))) { stop2("'interations' must be a numeric vector of length 1") } else { if (!length(iterations) == 1) stop2("'interations' must be a numeric vector of length 1") } # round iterations iterations <- round(iterations) # interations should be positive if (iterations < 2) stop2("'iterations' must be > 1") # if parallel is not numeric if (!is.numeric(parallel)) stop2("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop2("'parallel' should be a positive integer") # randomization function rndmFUN <- function(Y) { Y <- Y[order(Y$start), ] Y_list <- split(Y, Y$indiv) # null model # duration of signals durs <- lapply(Y_list, function(x) x$end - x$start) # duration of gaps gaps <- lapply(Y_list, function(y) { sapply(1:(nrow(y) - 1), function(x) { y$start[x + 1] - y$end[x] }) }) # randomize rnd.dfs <- lapply(1:iterations, function(x) { # randomize gaps if (randomization %in% c("keep.gaps", "keep.song.order")) { gaps <- lapply(gaps, sample) } if (randomization == "sample.gaps") { # generate gaps from lognormal distribution gaps <- lapply(gaps, function(x) { stats::rlnorm(n = length(x), meanlog = mean(log(unlist(gaps))), sdlog = stats::sd(log(unlist(gaps)))) }) } # randomize signals if (randomization %in% c("keep.gaps", "sample.gaps")) { durs <- lapply(durs, sample) } # put all back together as a sequence of signals and gaps ndfs_list <- lapply(names(Y_list), function(x) { nbt <- NULL for (i in 1:(length(durs[[x]]) - 1)) { nbt[i] <- durs[[x]][i] + gaps[[x]][i] if (i != 1) nbt[i] <- nbt[i] + nbt[i - 1] } nbt <- c(0, nbt) nbt <- nbt + min(Y_list[[x]]$start) net <- nbt + durs[[x]] ndf <- data.frame( indiv = x, start = nbt, end = net ) return(ndf) }) ndfs <- do.call(rbind, ndfs_list) ndfs <- ndfs[order(ndfs$start), ] rownames(ndfs) <- 1:nrow(ndfs) return(ndfs) }) # add observed as the first element of list dfs <- c(list(Y), rnd.dfs) return(dfs) } # counting ovlp.method countFUN <- function(Z) { # order by time and add duration Z <- Z[order(Z$start), ] Z1 <- Z[Z$indiv == unique(Z$indiv)[1], ] Z2 <- Z[Z$indiv == unique(Z$indiv)[2], ] out <- sapply(1:nrow(Z1), function(i) { # target start and end trg.strt <- Z1$start[i] trg.end <- Z1$end[i] # get the ones that overlap return(sum(Z2$end > trg.strt & Z2$start < trg.end)) }) return(sum(out)) } # time.overlap durFUN <- function(Z) { # order by time and add duration Z <- Z[order(Z$start), ] Z$duration <- Z$end - Z$start Z1 <- Z[Z$indiv == unique(Z$indiv)[1], ] Z2 <- Z[Z$indiv == unique(Z$indiv)[2], ] out <- sapply(1:nrow(Z1), function(i) { # target start and end trg.strt <- Z1$start[i] trg.end <- Z1$end[i] # get the ones that overlap Z2 <- Z2[Z2$end > trg.strt & Z2$start < trg.end, , drop = FALSE] if (nrow(Z2) > 0) # set new start and end at edges of overlaping signals { if (any(Z2$start < trg.strt)) { trg.strt <- max(Z2$end[Z2$start < trg.strt]) } if (any(Z2$end > trg.end)) { trg.end <- min(Z2$start[Z2$end > trg.end]) } # new duration no.ovlp.dur <- trg.end - trg.strt ovlp <- if (no.ovlp.dur > 0) Z1$duration[i] - no.ovlp.dur else Z1$duration[i] return(ovlp) } else { return(0) } }) return(sum(out)) } # time.distance ovlp.method closestFUN <- function(Z) { timediffs <- vapply(seq_len(nrow(Z)), function(i) { Z_others <- Z[Z$indiv != Z$indiv[i], ] timediff <- if (any(Z_others$end > Z$start[i] & Z_others$start < Z$end[i])) { 0 } else { min(abs(c(Z_others$start - Z$end[i], Z_others$end - Z$start[i]))) } return(timediff) }, FUN.VALUE = numeric(1)) return(mean(timediffs)) } # select function/ovlp.method coortestFUN <- if (ovlp.method == "count") { countFUN } else # duration kept for compatibility with previous versions if (ovlp.method %in% c("time.overlap", "duration")) { durFUN } else # time to closest call from other individuals if (ovlp.method == "time.closest") closestFUN # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function cote <- pblapply_wrblr_int(pbar = pb, X = unique(X$sing.event), cl = cl, FUN = function(h) { ovlp <- try(sapply(rndmFUN(X[X$sing.event == h, ]), coortestFUN)) if (!is(ovlp, "try-error")) { # get observed overlap (first element) obs.overlaps <- ovlp[1] # get random overlap (all except the first element) rov <- ovlp[-1] mean.random.ovlps <- mean(rov) # calculate p-value if (less.than.chance) p <- length(rov[rov <= obs.overlaps]) / iterations else p <- length(rov[rov >= obs.overlaps]) / iterations # coordination score if (obs.overlaps == 0 & mean.random.ovlps == 0) { coor.score <- 0 } else { coor.score <- round((obs.overlaps - mean.random.ovlps) / mean.random.ovlps, 3) } l <- data.frame(sing.event = h, obs.ovlp = obs.overlaps, mean.random.ovlp = mean.random.ovlps, p.value = p, coor.score) } else { l <- data.frame(sing.event = h, obs.ovlp = NA, mean.random.ovlp = NA, p.value = NA, coor.score = NA) } return(l) }) df <- do.call(rbind, cote) return(df) } ############################################################################################################## #' alternative name for \code{\link{test_coordination}} #' #' @keywords internal #' @details see \code{\link{test_coordination}} for documentation. \code{\link{coor.test}} will be deprecated in future versions. #' @export coor.test <- test_coordination
/scratch/gouwar.j/cran-all/cranData/warbleR/R/test_coordination.R
#' Spectrograms with frequency measurements #' #' \code{track_freq_contour} creates spectrograms to visualize dominant and fundamental frequency measurements (contours) #' @usage track_freq_contour(X, wl = 512, wl.freq = 512, flim = NULL, wn = "hanning", pal = #' reverse.gray.colors.2, ovlp = 70, inner.mar = c(5, 4, 4, 2), outer.mar = #' c(0, 0, 0, 0), picsize = 1, res = 100, cexlab = 1, title = TRUE, propwidth = FALSE, #' xl = 1, osci = FALSE, gr = FALSE, sc = FALSE, bp = NULL, cex = c(0.6, 1), #' threshold = 15, threshold.time = NULL, threshold.freq = NULL, contour = "both", #' col = c("#E37222B3", "#07889BB3"), pch = c(21, 24), mar = 0.05, lpos = "topright", #' it = "jpeg", parallel = 1, path = NULL, img.suffix = NULL, custom.contour = NULL, #' pb = TRUE, type = "p", leglab = c("Ffreq", "Dfreq"), col.alpha = 0.6, line = TRUE, #' fast.spec = FALSE, ff.method = "seewave", frange.detec = FALSE, fsmooth = 0.1, #' widths = c(2, 1), freq.continuity = NULL, clip.edges = 2, track.harm = FALSE, ...) #' @param X object of class 'selection_table', 'extended_selection_table' or data frame containing columns for sound file name (sound.files), #' selection number (selec), and start and end time of signal (start and end). #' The output \code{\link{auto_detec}} can also be used as the input data frame. #' @param wl A numeric vector of length 1 specifying the window length of the spectrogram, default #' is 512. #' @param wl.freq A numeric vector of length 1 specifying the window length of the spectrogram #' for measurements on the frequency spectrum. Default is 512. Higher values would provide #' more accurate measurements. #' @param flim A numeric vector of length 2 for the frequency limit of #' the spectrogram (in kHz), as in \code{\link[seewave]{spectro}}. Default is \code{NULL}. #' @param wn Character vector of length 1 specifying window name. Default is #' "hanning". See function \code{\link[seewave]{ftwindow}} for more options. #' @param pal A color palette function to be used to assign colors in the #' plot, as in \code{\link[seewave]{spectro}}. Default is reverse.gray.colors.2. #' @param ovlp Numeric vector of length 1 specifying \% of overlap between two #' consecutive windows, as in \code{\link[seewave]{spectro}}. Default is 70. #' @param inner.mar Numeric vector with 4 elements, default is c(5,4,4,2). #' Specifies number of lines in inner plot margins where axis labels fall, #' with form c(bottom, left, top, right). See \code{\link[graphics]{par}}. #' @param outer.mar Numeric vector with 4 elements, default is c(0,0,0,0). #' Specifies number of lines in outer plot margins beyond axis labels, with #' form c(bottom, left, top, right). See \code{\link[graphics]{par}}. #' @param picsize Numeric argument of length 1. Controls relative size of #' spectrogram. Default is 1. #' @param res Numeric argument of length 1. Controls image resolution. #' Default is 100 (faster) although 300 - 400 is recommended for publication/ #' presentation quality. #' @param cexlab Numeric vector of length 1 specifying the relative size of axis #' labels. See \code{\link[seewave]{spectro}}. #' @param title Logical argument to add a title to individual spectrograms. #' Default is \code{TRUE}. #' @param propwidth Logical argument to scale the width of spectrogram #' proportionally to duration of the selected call. Default is \code{FALSE}. #' @param xl Numeric vector of length 1. A constant by which to scale #' spectrogram width. Default is 1. #' @param osci Logical argument to add an oscillogram underneath spectrogram, as #' in \code{\link[seewave]{spectro}}. Default is \code{FALSE}. #' @param gr Logical argument to add grid to spectrogram. Default is \code{FALSE}. #' @param sc Logical argument to add amplitude scale to spectrogram, default is #' \code{FALSE}. #' @param bp A numeric vector of length 2 for the lower and upper limits of a #' frequency bandpass filter (in kHz) or "frange" to indicate that values in bottom.freq #' and top.freq columns will be used as bandpass limits. Default is \code{NULL}. #' @param cex Numeric vector of length 2, specifies relative size of points #' plotted for frequency measurements and legend font/points, respectively. #' See \code{\link[seewave]{spectro}}. #' @param threshold amplitude threshold (\%) for fundamental and dominant frequency detection as well as frequency range from the spectrum (see 'frange.detec'). Default is 15. WILL BE DEPRECATED. Use 'threshold.time' and 'threshold.time' instead. #' @param threshold.time amplitude threshold (\%) for the time domain. Use for fundamental and dominant frequency detection. If \code{NULL} (default) then the 'threshold' value is used. #' @param threshold.freq amplitude threshold (\%) for the frequency domain. Use for frequency range detection from the spectrum (see 'frange.detec'). If \code{NULL} (default) then the #' 'threshold' value is used. #' @param contour Character vector, one of "df", "ff" or "both", specifying whether the #' dominant or fundamental frequencies or both should be plotted. Default is "both". #' @param col Vector of length 1 or 2 specifying colors of points plotted to mark #' fundamental and dominant frequency measurements respectively (if both are plotted). Default is \code{c("#E37222B3", #' "#07889BB3")}. Extreme values (lowest and highest) are highlighted in yellow. #' @param pch Numeric vector of length 1 or 2 specifying plotting characters for #' the frequency measurements. Default is c(21, 24). #' @param mar Numeric vector of length 1. Specifies the margins adjacent to the selections #' to set spectrogram limits. Default is 0.05. #' @param lpos Character vector of length 1 or numeric vector of length 2, #' specifying position of legend. If the former, any keyword accepted by #' xy.coords can be used (see below). If the latter, the first value will be the x #' coordinate and the second value the y coordinate for the legend's position. #' Default is "topright". #' @param it A character vector of length 1 giving the image type to be used. Currently only #' "tiff" and "jpeg" are admitted. Default is "jpeg". #' @param parallel Numeric. Controls whether parallel computing is applied. #' It specifies the number of cores to be used. Default is 1 (i.e. no parallel computing). #' @param path Character string containing the directory path where the sound files are located. #' If \code{NULL} (default) then the current working directory is used. #' @param img.suffix A character vector of length 1 with a suffix (label) to add at the end of the names of #' image files. Default is \code{NULL}. #' @param custom.contour A data frame with frequency contours for exactly the same sound files and selection as in X. #' The frequency values are assumed to be equally spaced in between the start and end of the signal. The #' first 2 columns of the data frame should contain the 'sound.files' and 'selec' columns and should be #' identical to the corresponding columns in X (same order). #' @param pb Logical argument to control progress bar. Default is \code{TRUE}. #' @param type A character vector of length 1 indicating the type of frequency contour plot to be drawn. #' Possible types are "p" for points, "l" for lines and "b" for both. #' @param leglab A character vector of length 1 or 2 containing the label(s) of the frequency contour legend #' in the output image. #' @param col.alpha A numeric vector of length 1 within [0,1] indicating how transparent the lines/points should be. #' @param line Logical argument to add red lines (or box if bottom.freq and top.freq columns are provided) at start and end times of selection. Default is \code{TRUE}. #' @param fast.spec Logical. If \code{TRUE} then image function is used internally to create spectrograms, which substantially #' increases performance (much faster), although some options become unavailable, as collevels, and sc (amplitude scale). #' This option is indicated for signals with high background noise levels. Palette colors \code{\link[monitoR:specCols]{gray.1}}, \code{\link[monitoR:specCols]{gray.2}}, #' \code{\link[monitoR:specCols]{gray.3}}, \code{\link[monitoR:specCols]{topo.1}} and \code{\link[monitoR:specCols]{rainbow.1}} (which should be imported from the package monitoR) seem #' to work better with 'fast' spectrograms. Palette colors \code{\link[monitoR:specCols]{gray.1}}, \code{\link[monitoR:specCols]{gray.2}}, #' \code{\link[monitoR:specCols]{gray.3}} offer #' decreasing darkness levels. #' @param ff.method Character. Selects the method used to calculate the fundamental #' frequency. Either 'tuneR' (using \code{\link[tuneR]{FF}}) or 'seewave' (using #' \code{\link[seewave]{fund}}). Default is 'seewave'. 'tuneR' performs faster (and seems to be more accurate) than 'seewave'. #' @param frange.detec Logical. Controls whether frequency range of signal is automatically #' detected using the \code{\link{freq_range_detec}} function. If so, the range is used as the #' bandpass filter (overwriting 'bp' argument). Default is \code{FALSE}. #' @param fsmooth A numeric vector of length 1 to smooth the frequency spectrum with a mean #' sliding window (in kHz) used for frequency range detection (when \code{frange.detec = TRUE}). This help to average amplitude "hills" to minimize the effect of #' amplitude modulation. Default is 0.1. #' @param widths Numeric vector of length 2 to control the relative widths of the spectro (first element) and spectrum (second element, (when \code{frange.detec = TRUE})). #' @param freq.continuity Numeric vector of length 1 to control whether dominant frequency detections #' outliers(i.e that differ from the frequency of the detections right before and after) would be removed. Should be given in kHz. Default is \code{NULL}. #' @param clip.edges Integer vector of length 1 to control if how many 'frequency-wise discontinuous' detection would be remove at the start and end of signals (see #' 'freq.continuity' argument). Default is 2. Ignored if \code{freq.continuity = NULL}. #' @param track.harm Logical to control if \code{\link{track_harmonic}} or a modified version of \code{\link[seewave]{dfreq}} is used for dominant frequency detection. Default is \code{FALSE} (use \code{\link[seewave]{dfreq}}). #' @param ... Additional arguments to be passed to the internal spectrogram creating function for customizing graphical output. The function is a modified version of \code{\link[seewave]{spectro}}, so it takes the same arguments. #' @return Spectrograms of the signals listed in the input data frame showing the location of #' the dominant and fundamental frequencies. #' @family spectrogram creators #' @seealso \code{\link{spectrograms}} for creating spectrograms from selections, #' \code{\link{snr_spectrograms}} for creating spectrograms to #' optimize noise margins used in \code{\link{sig2noise}} #' @export #' @name track_freq_contour #' @details This function provides visualization of frequency measurements as the ones #' made by \code{\link{spectro_analysis}}, \code{\link{freq_ts}} and \code{\link{freq_DTW}}. Frequency measures can be made by the function or input by the #' user (see 'custom.contour' argument). If \code{frange = TRUE} the function uses \code{\link{freq_range_detec}} to detect the frequency range. In this case the graphical output includes a #' frequency spectrum showing the detection threshold. Extreme values (lowest and highest) are highlighted in yellow. #' Note that, unlike other warbleR functions that measure frequency contours, track_freq_contour do not interpolate frequency values. #' @examples #' { #' # load data #' data("Cryp.soui") #' writeWave(Cryp.soui, file.path(tempdir(), "Cryp.soui.wav")) # save sound files #' #' # autodetec location of signals #' ad <- auto_detec( #' threshold = 6, bp = c(1, 3), mindur = 1.2, flim = c(0, 5), #' maxdur = 3, img = FALSE, ssmooth = 600, wl = 300, flist = "Cryp.soui.wav", #' path = tempdir() #' ) #' #' # track dominant frequency graphs with freq range detection #' track_freq_contour( #' X = ad[!is.na(ad$start), ], flim = c(0, 5), ovlp = 90, #' it = "tiff", bp = c(1, 3), contour = "df", wl = 300, frange = TRUE, #' path = tempdir() #' ) #' #' # using users frequency data (custom.contour argument) #' # first get contours using freq_ts #' df <- freq_ts( #' X = ad[!is.na(ad$start), ], flim = c(0, 5), ovlp = 90, img = FALSE, #' bp = c(1, 3), wl = 300, path = tempdir() #' ) #' #' # now input the freq_ts output into track_freq_contour #' track_freq_contour( #' X = ad[!is.na(ad$start), ], custom.contour = df, flim = c(0, 5), ovlp = 90, #' it = "tiff", path = tempdir() #' ) #' #' # Check this folder #' tempdir() #' #' # track both frequencies #' track_freq_contour( #' X = ad[!is.na(ad$start), ], flim = c(0, 5), ovlp = 90, #' it = "tiff", bp = c(1, 3), contour = "both", wl = 300, path = tempdir() #' ) #' } #' #' @references { #' Araya-Salas, M., & Smith-Vidaurre, G. (2017). warbleR: An R package to streamline analysis of animal acoustic signals. Methods in Ecology and Evolution, 8(2), 184-191. #' } #' @author Grace Smith Vidaurre and Marcelo Araya-Salas (\email{marcelo.araya@@ucr.ac.cr}) # last modification on mar-13-2018 (MAS) track_freq_contour <- function(X, wl = 512, wl.freq = 512, flim = NULL, wn = "hanning", pal = reverse.gray.colors.2, ovlp = 70, inner.mar = c(5, 4, 4, 2), outer.mar = c(0, 0, 0, 0), picsize = 1, res = 100, cexlab = 1, title = TRUE, propwidth = FALSE, xl = 1, osci = FALSE, gr = FALSE, sc = FALSE, bp = NULL, cex = c(0.6, 1), threshold = 15, threshold.time = NULL, threshold.freq = NULL, contour = "both", col = c("#E37222B3", "#07889BB3"), pch = c(21, 24), mar = 0.05, lpos = "topright", it = "jpeg", parallel = 1, path = NULL, img.suffix = NULL, custom.contour = NULL, pb = TRUE, type = "p", leglab = c("Ffreq", "Dfreq"), col.alpha = 0.6, line = TRUE, fast.spec = FALSE, ff.method = "seewave", frange.detec = FALSE, fsmooth = 0.1, widths = c(2, 1), freq.continuity = NULL, clip.edges = 2, track.harm = FALSE, ...) { #### set arguments from options # get function arguments argms <- methods::formalArgs(track_freq_contour) # get warbleR options opt.argms <- if (!is.null(getOption("warbleR"))) getOption("warbleR") else SILLYNAME <- 0 # remove options not as default in call and not in function arguments opt.argms <- opt.argms[!sapply(opt.argms, is.null) & names(opt.argms) %in% argms] # get arguments set in the call call.argms <- as.list(base::match.call())[-1] # remove arguments in options that are in call opt.argms <- opt.argms[!names(opt.argms) %in% names(call.argms)] # set options left if (length(opt.argms) > 0) { for (q in seq_len(length(opt.argms))) { assign(names(opt.argms)[q], opt.argms[[q]]) } } # check path to working directory if (is.null(path)) { path <- getwd() } else if (!dir.exists(path)) { stop2("'path' provided does not exist") } else { path <- normalizePath(path) } # if X is not a data frame if (!any(is.data.frame(X), is_selection_table(X), is_extended_selection_table(X))) stop2("X is not of a class 'data.frame', 'selection_table' or 'extended_selection_table'") if (!all(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))) { stop2(paste(paste(c("sound.files", "selec", "start", "end")[!(c( "sound.files", "selec", "start", "end" ) %in% colnames(X))], collapse = ", "), "column(s) not found in data frame")) } # if there are NAs in start or end stop if (any(is.na(c(X$end, X$start)))) stop2("NAs found in start and/or end") # if end or start are not numeric stop if (any(!is(X$end, "numeric"), !is(X$start, "numeric"))) stop2("'start' and 'end' must be numeric") # if any start higher than end stop if (any(X$end - X$start <= 0)) stop2(paste("Start is higher than or equal to end in", length(which(X$end - X$start <= 0)), "case(s)")) # if any selections longer than 20 secs stop if (any(X$end - X$start > 20)) stop2(paste(length(which(X$end - X$start > 20)), "selection(s) longer than 20 sec")) # bp checking if (!is.null(bp)) { if (bp[1] != "frange") { if (!is.vector(bp)) { stop2("'bp' must be a numeric vector of length 2") } else { if (!length(bp) == 2) stop2("'bp' must be a numeric vector of length 2") } } else { if (!any(names(X) == "bottom.freq") & !any(names(X) == "top.freq")) stop2("'bp' = frange requires bottom.freq and top.freq columns in X") if (any(is.na(c(X$bottom.freq, X$top.freq)))) stop2("NAs found in bottom.freq and/or top.freq") if (any(c(X$bottom.freq, X$top.freq) < 0)) stop2("Negative values found in bottom.freq and/or top.freq") if (any(X$top.freq - X$bottom.freq < 0)) stop2("top.freq should be higher than low.f") } } # if it argument is not "jpeg" or "tiff" if (!any(it == "jpeg", it == "tiff")) stop2(paste("Image type", it, "not allowed")) # if ff.method argument if (!any(ff.method == "seewave", ff.method == "tuneR")) stop2(paste("ff.method", ff.method, "is not recognized")) # if type not l b or p if (!any(type %in% c("p", "l", "b"))) stop2(paste("Type", type, "not allowed")) # if frange.detec oscillo false if (frange.detec) osc <- FALSE # join img.suffix and it if (is.null(img.suffix)) { img.suffix2 <- paste("trackfreqs", it, sep = ".") } else { img.suffix2 <- paste(img.suffix, it, sep = ".") } # threshold adjustment if (is.null(threshold.time)) threshold.time <- threshold if (is.null(threshold.freq)) threshold.freq <- threshold # return warning if not all sound files were found if (!is_extended_selection_table(X)) { recs.wd <- list.files(path = path, pattern = "\\.wav$|\\.wac$|\\.mp3$|\\.flac$", ignore.case = TRUE) if (length(unique(X$sound.files[(X$sound.files %in% recs.wd)])) != length(unique(X$sound.files))) { message2(paste( length(unique(X$sound.files)) - length(unique(X$sound.files[(X$sound.files %in% recs.wd)])), "sound file(s) not found" )) } # count number of sound files in working directory and if 0 stop d <- which(X$sound.files %in% recs.wd) if (length(d) == 0) { stop2("The sound files are not in the working directory") } else { X <- X[d, , drop = FALSE] } } # If parallel is not numeric if (!is.numeric(parallel)) stop2("'parallel' must be a numeric vector of length 1") if (any(!(parallel %% 1 == 0), parallel < 1)) stop2("'parallel' should be a positive integer") # Compare custom.contour to X if (!is.null(custom.contour) & is.data.frame(custom.contour)) { # check if sound.files and selec columns are present and in the right order if (!identical(names(custom.contour)[1:2], c("sound.files", "selec"))) stop2("'sound.files' and/or 'selec' columns are not found in custom.contour") # check if the info in sound.files and selec columns is the same for X and custom.contour # remove custom.contour selections not in X custom.contour <- custom.contour[paste(custom.contour[, "sound.files"], custom.contour[, "selec"]) %in% paste(as.data.frame(X)[, "sound.files"], as.data.frame(X)[, "selec"]), ] # stop if not the same number of selections if (nrow(X) > nrow(custom.contour)) stop2("selection(s) in X but not in custom.contour") # order custom.contour as in X custom.contour <- custom.contour[match(paste(custom.contour[, "sound.files"], custom.contour[, "selec"]), paste(as.data.frame(X)[, "sound.files"], as.data.frame(X)[, "selec"])), ] # frange.detec <- FALSE } # adjust if only 1 pch was specfified if (length(pch) == 1) pch <- c(pch, pch) # adjust if only 1 color was specified if (length(col) == 1) col <- c(col, col) # adjust if only 1 leglab was specified if (length(leglab) == 1) leglab <- c(leglab, leglab) # make colors transparent col <- adjustcolor(c(col, "yellow", "black", "white", "red"), alpha.f = col.alpha) trackfreFUN <- function(X, i, mar, flim, xl, picsize, wl, wl.freq, cexlab, inner.mar, outer.mar, res, bp, cex, threshold.time, threshold.freq, pch, custom.contour) { # Read sound files, initialize frequency and time limits for spectrogram r <- warbleR::read_sound_file(X = X, path = path, index = i, header = TRUE) f <- r$sample.rate t <- c(X$start[i] - mar, X$end[i] + mar) # adjust margins if signal is close to start or end of sound file mar1 <- mar # adjust margin if negative if (t[1] < 0) { t[1] <- 0 mar1 <- X$start[i] } mar2 <- mar1 + X$end[i] - X$start[i] if (t[2] > r$samples / f) t[2] <- r$samples / f # read rec segment r <- warbleR::read_sound_file(X = X, path = path, index = i, from = t[1], to = t[2]) # in case bp its higher than can be due to sampling rate if (!is.null(bp)) { if (bp[1] == "frange") bp <- c(X$bottom.freq[i], X$top.freq[i]) } b <- bp if (!is.null(b)) { if (b[2] > floor([email protected] / 2000)) b[2] <- floor([email protected] / 2000) } fl <- flim # in case flim its higher than can be due to sampling rate if (!is.null(fl)) { if (fl[2] > floor(f / 2000)) fl[2] <- floor(f / 2000) } else { fl <- c(0, floor(f / 2000)) } # Spectrogram width can be proportional to signal duration if (propwidth) { pwc <- (10.16) * ((t[2] - t[1]) / 0.27) * xl * picsize } else { pwc <- (10.16) * xl * picsize } # call image function img_wrlbr_int( filename = paste0(X$sound.files[i], "-", X$selec[i], "-", img.suffix2), path = path, width = pwc, height = (10.16) * picsize, units = "cm", res = res ) # Change relative heights of rows for spectrogram when osci = TRUE if (osci == TRUE) hts <- c(3, 2) else hts <- NULL # Change relative widths of columns for spectrogram when sc = TRUE if (sc == TRUE) wts <- c(3, 1) else wts <- NULL # Change inner and outer plot margins par(mar = inner.mar) par(oma = outer.mar) # Generate spectrograms if (!frange.detec) { suppressWarnings(spectro_wrblr_int(r, f = f, wl = wl, ovlp = ovlp, heights = hts, wn = "hanning", widths = wts, palette = pal, osc = osci, grid = gr, scale = sc, collab = "black", cexlab = cexlab, cex.axis = 0.5 * picsize, flim = fl, tlab = "Time (s)", flab = "Frequency (kHz)", alab = "", fast.spec = fast.spec, ... )) if (title) { if (is.null(img.suffix)) { title(paste(X$sound.files[i], X$selec[i], sep = "-"), cex.main = cexlab) } else { title(paste(X$sound.files[i], X$selec[i], img.suffix, sep = "-"), cex.main = cexlab) } } } else { frng <- frd_wrblr_int(wave = seewave::cutw(r, from = mar1, to = mar2, output = "Wave"), wl = wl.freq, fsmooth = fsmooth, threshold = threshold.freq, wn = wn, bp = b, ovlp = ovlp) if (!all(is.na(frng$frange))) b <- as.numeric(frng$frange) # set limits for color rectangles down if (is.null(bp)) lims <- flim else lims <- bp b[is.na(b)] <- lims[is.na(b)] b <- sort(b) # split screen m <- rbind( c(0, widths[1] / sum(widths), 0, 0.93), # 1 c(widths[1] / sum(widths), 1, 0, 0.93), c(0, 1, 0.93, 1) ) # 3 invisible(close.screen(all.screens = TRUE)) split.screen(m) screen(1) par(mar = c(3.4, 3.4, 0.5, 0)) # create spectro spectro_wrblr_int2(wave = r, f = f, flim = fl, fast.spec = fast.spec, palette = pal, ovlp = ovlp, wl = wl, grid = F, tlab = "", flab = "") # add green polygon on detected frequency bands rect(xleft = 0, ybottom = b[1], xright = seewave::duration(r), ytop = b[2], col = adjustcolor("#07889B", alpha.f = 0.1), border = adjustcolor("gray", 0.1)) # add line highlighting freq range abline(h = b, col = "#07889B", lty = 3, lwd = 1) # add axis labels mtext(side = 1, text = "Time (s)", line = 2.3) mtext(side = 2, text = "Frequency (kHz)", line = 2.3) } options(warn = -1) # Calculate fundamental frequencies at each time point if (contour %in% c("both", "ff") & is.null(custom.contour)) { if (ff.method == "seewave") { ffreq1 <- seewave::fund( wave = r, wl = wl, from = mar1, to = mar2, fmax = if (!is.null(b)) b[2] * 1000 else f / 2, f = f, ovlp = ovlp, threshold = threshold.time, plot = FALSE ) } else { ff1 <- tuneR::FF(tuneR::periodogram(seewave::cutw(r, f = f, from = mar1, to = mar2, output = "Wave"), width = wl, overlap = wl * ovlp / 100), peakheight = (100 - threshold.time) / 100) / 1000 ff2 <- seq(0, X$end[i] - X$start[i], length.out = length(ff1)) ffreq1 <- cbind(ff2, ff1) } ffreq <- matrix(ffreq1[!is.na(ffreq1[, 2]), ], ncol = 2) ffreq <- matrix(ffreq[ffreq[, 2] > b[1], ], ncol = 2) if (!is.null(freq.continuity)) ffreq <- ffreq[c(0, abs(diff(ffreq[, 2]))) <= freq.continuity, ] # Plot extreme values fundamental frequency points(c(ffreq[c(which.max(ffreq[, 2]), which.min(ffreq[, 2])), 1]) + mar1, c(ffreq[c( which.max(ffreq[, 2]), which.min(ffreq[, 2]) ), 2]), col = col[3], cex = cex[1] * 1.6, pch = pch[1], lwd = 2) # Plot all fundamental frequency values if (type %in% c("p", "b")) { points(c(ffreq[, 1]) + mar1, c(ffreq[, 2]), col = col[1], cex = cex[1], pch = pch[1], bg = col[1]) } # plot lines if (type %in% c("l", "b")) { lines(ffreq[, 1] + mar1, ffreq[, 2], col = col[1], lwd = 3) } # Plot empty points at the bottom for the bins that did not detected any frequencies or out of bp if (nrow(ffreq1) > nrow(ffreq)) { points(c(ffreq1[!ffreq1[, 1] %in% ffreq[, 1], 1]) + mar1, rep(fl[1] + (fl[2] - fl[1]) * 0.04, nrow(ffreq1) - nrow(ffreq)), col = col[4], cex = cex[1] * 0.7, pch = pch[1]) } } # Calculate dominant frequency at each time point if (contour %in% c("both", "df") & is.null(custom.contour)) { dfreq1 <- track_harmonic(r, f = f, wl = wl, ovlp = 70, plot = FALSE, bandpass = if (!is.null(b)) b * 1000 else b, fftw = TRUE, threshold = threshold.time, tlim = c(mar1, mar2), dfrq = !track.harm, adjust.wl = TRUE ) dfreq <- matrix(dfreq1[!is.na(dfreq1[, 2]), ], ncol = 2) # freq continuity if (nrow(dfreq > 2) & !is.null(freq.continuity)) { indx <- sapply(1:nrow(dfreq), function(x) { # if first one if (x == 1) { if (abs(dfreq[x, 2] - dfreq[x + 1, 2]) > freq.continuity & abs(dfreq[x + 1, 2] - dfreq[x + 2, 2]) < freq.continuity) { return(FALSE) } else { return(TRUE) } } else { # if last one if (x == nrow(dfreq)) { if (abs(dfreq[x, 2] - dfreq[x - 1, 2]) > freq.continuity & abs(dfreq[x - 2, 2] - dfreq[x - 1, 2]) < freq.continuity) { return(FALSE) } else { return(TRUE) } } else { if (abs(dfreq[x, 2] - dfreq[x + 1, 2]) > freq.continuity & abs(dfreq[x, 2] - dfreq[x - 1, 2]) > freq.continuity) { return(FALSE) } else { return(TRUE) } } } }) if (nrow(dfreq) > 3 * clip.edges & any(!indx[2:clip.edges])) indx[1:(which(!indx[2:clip.edges]))] <- FALSE # turn around indx <- indx[nrow(dfreq):1] if (nrow(dfreq) > 3 * clip.edges & any(!indx[2:clip.edges])) indx[1:(which(!indx[2:clip.edges]))] <- FALSE # turn around again indx <- indx[nrow(dfreq):1] dfreq <- dfreq[indx, ] } dfreq <- as.matrix(dfreq, nrow = 2) # Plot extreme values dominant frequency points(c(dfreq[c(which.max(dfreq[, 2]), which.min(dfreq[, 2])), 1]) + mar1, c(dfreq[c( which.max(dfreq[, 2]), which.min(dfreq[, 2]) ), 2]), col = col[3], cex = cex[1] * 1.6, pch = pch[2], lwd = 2) # Plot all dominant frequency values if (type %in% c("p", "b")) { points(dfreq[, 1] + mar1, dfreq[, 2], col = col[2], cex = cex[1], pch = pch[2], bg = col[2]) } # plot lines if (type %in% c("l", "b")) { lines(dfreq[, 1] + mar1, dfreq[, 2], col = col[2], lwd = 3) } # Plot empty points at the bottom for the bins that did not detected any frequencies or out of bp if (nrow(dfreq1) > nrow(dfreq)) { points(c(dfreq1[!dfreq1[, 1] %in% dfreq[, 1], 1]) + mar1, rep(fl[1] + (fl[2] - fl[1]) * 0.02, nrow(dfreq1) - nrow(dfreq)), col = col[4], cex = cex[1] * 0.7, pch = pch[2]) } } # Use freq values provided by user if (!is.null(custom.contour)) { if (!is.data.frame(custom.contour)) { custom <- try(custom.contour[[i]], silent = TRUE) if (is(custom, "try-error")) { custom <- rep(NA, 3) freq1 <- matrix(rep(NA, 2), ncol = 2) } else { freq1 <- try(custom.contour[[i]][, 2:3], silent = TRUE) if (is(freq1, "try-error")) freq1 <- custom.contour[, 2:3, drop = FALSE] } freq <- freq1[!is.na(freq1[, 2]), , drop = FALSE] } else { custom <- custom.contour[i, 3:ncol(custom.contour)] timeaxis <- seq(from = 0, to = X$end[i] - X$start[i], length.out = length(custom)) freq1 <- cbind(timeaxis, t(custom)) freq <- freq1[!is.na(freq1[, 2]), , drop = FALSE] } # Plot extreme values dominant frequency points(c(freq[c(which.max(freq[, 2]), which.min(freq[, 2])), 1]) + mar1, c(freq[c( which.max(freq[, 2]), which.min(freq[, 2]) ), 2]), col = col[3], cex = cex[1] * 1.6, pch = pch[2], lwd = 2) # Plot all dominant frequency values if (type %in% c("p", "b")) { points(freq[, 1] + mar1, freq[, 2], col = col[2], cex = cex[1], pch = pch[2], bg = col[2]) } # plot lines if (type %in% c("l", "b")) { lines(freq[, 1] + mar1, freq[, 2], col = col[2], lwd = 3) } # Plot empty points at the bottom for the bins that did not detected any frequencies or out of bp if (nrow(freq1) > nrow(freq)) { points(c(freq1[!freq1[, 1] %in% freq[, 1], 1]) + mar1, rep(fl[1] + (fl[2] - fl[1]) * 0.02, nrow(freq1) - nrow(freq)), col = col[4], cex = cex[1] * 0.7, pch = pch[2]) } } if (line) { if (any(names(X) == "bottom.freq") & any(names(X) == "top.freq")) { if (!is.na(X$bottom.freq[i]) & !is.na(X$top.freq[i])) { if (!frange.detec) { polygon(x = rep(c(mar1, mar2), each = 2), y = c(X$bottom.freq[i], X$top.freq[i], X$top.freq[i], X$bottom.freq[i]), lty = 3, border = col[6], lwd = 1.2) } else { abline(v = c(mar1, mar2), col = col[6], lty = "dashed") } } } else { abline(v = c(mar1, mar2), col = col[6], lty = "dashed") } } ## legend # remove points for legend if (type == "l") pch <- NA if (type %in% c("l", "b")) lwd <- 3 else lwd <- NA # Adjust legend coordinates if (is.null(custom.contour)) { if (contour == "both") { legend(lpos, legend = leglab, bg = col[5], pch = pch, col = col[1:2], bty = "o", cex = cex[2], pt.bg = col[1:2], lwd = lwd ) } if (contour == "ff") { legend(lpos, legend = leglab[1], pch = pch[1], col = col[1], bty = "o", cex = cex[2], bg = col[5], pt.bg = col[1], lwd = lwd ) } if (contour == "df") { legend(lpos, legend = leglab[2], pch = pch[2], col = col[2], bty = "o", cex = cex[2], bg = col[5], pt.bg = col[2], lwd = lwd ) } } else { legend(lpos, legend = leglab[1], pch = pch[2], col = col[2], bty = "o", cex = cex[2], bg = col[5], pt.bg = col[2], lwd = lwd ) } if (frange.detec) { # second plot screen(2) z <- frng$af.mat[, 1] zf <- frng$af.mat[, 2] par(mar = c(3.4, 0, 0.5, 0.8)) plot(z, zf, type = "l", ylim = fl, yaxs = "i", xaxs = "i", yaxt = "n", xlab = "", col = "white", xaxt = "n") # add axis& labels axis(1, at = seq(0.2, 1, by = 0.4)) mtext(side = 1, text = "Amplitude (%)", line = 2.3) # fix amplitude values to close polygon (just for ploting) z3 <- c(0, z, 0) if (!is.null(bp)) zf3 <- c(b[1], zf, b[2]) else zf3 <- c(fl[1], zf, fl[2]) # addd extremes to make polygon close fine zf3 <- c(lims[1], zf, lims[2]) # plot amplitude values curve polygon(cbind(z3, zf3), col = adjustcolor("#E37222", 0.8)) # add border line points(z3, zf3, type = "l", col = adjustcolor("gray", 0.5)) # add background color rect(xleft = 0, ybottom = fl[1], xright = 1, ytop = fl[2], col = adjustcolor("#4D69FF", 0.05)) # add green polygon on detected frequency bands rect(xleft = 0, ybottom = b[1], xright = 1, ytop = b[2], col = adjustcolor("green3", 0.1), border = adjustcolor("gray", 0.2)) # add gray boxes in filtered out freq bands if (!is.null(bp)) { rect(xleft = 0, ybottom = bp[2], xright = 1, ytop = fl[2], col = adjustcolor("gray", 0.5)) rect(xleft = 0, ybottom = fl[1], xright = 1, ytop = bp[1], col = adjustcolor("gray", 0.5)) } # add line to highligh freq range abline(v = threshold.freq / 100, col = adjustcolor("blue4", 0.7), lty = 3, lwd = 2.3) abline(h = b, col = "#80C3FF", lty = 3, lwd = 1.1) if (title) { screen(3) par(mar = rep(0, 4)) plot(0.5, xlim = c(0, 1), ylim = c(0, 1), type = "n", axes = FALSE, xlab = "", ylab = "", xaxt = "n", yaxt = "n") if (is.null(img.suffix)) { text(x = 0.5, y = 0.35, labels = paste(X$sound.files[i], X$selec[i], sep = "-"), cex = cexlab, font = 2) } else { text(x = 0.5, y = 0.35, labels = paste(X$sound.files[i], X$selec[i], img.suffix, sep = "-"), cex = cexlab, font = 2) } } } invisible() dev.off() return(NULL) } # set clusters for windows OS if (Sys.info()[1] == "Windows" & parallel > 1) { cl <- parallel::makePSOCKcluster(getOption("cl.cores", parallel)) } else { cl <- parallel } # run loop apply function out <- pblapply_wrblr_int(pbar = pb, X = 1:nrow(X), cl = cl, FUN = function(i) { trackfreFUN( X = X, i = i, mar = mar, flim = flim, xl = xl, picsize = picsize, res = res, wl = wl, wl.freq = wl.freq, cexlab = cexlab, inner.mar = inner.mar, outer.mar = outer.mar, bp = bp, cex = cex, threshold.time = threshold.time, threshold.freq = threshold.freq, pch = pch, custom.contour ) }) return(NULL) } ############################################################################################################## #' alternative name for \code{\link{track_freq_contour}} #' #' @keywords internal #' @details see \code{\link{track_freq_contour}} for documentation. \code{\link{trackfreqs}} will be deprecated in future versions. #' @export trackfreqs <- track_freq_contour
/scratch/gouwar.j/cran-all/cranData/warbleR/R/track_freq_contour.R