From ac95b9eb76e3bdef8939c05e1012f363d0378e2a Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Sat, 5 Dec 2015 11:29:46 -0200 Subject: [PATCH 01/40] Start classes and methods file --- R/nicheApport-classes.R | 1 + R/nicheApport-methods.R | 60 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 R/nicheApport-classes.R create mode 100644 R/nicheApport-methods.R diff --git a/R/nicheApport-classes.R b/R/nicheApport-classes.R new file mode 100644 index 0000000..8224246 --- /dev/null +++ b/R/nicheApport-classes.R @@ -0,0 +1 @@ +setClass("fittedmodel", slots = c(Tstats = "list", sim.stats = "matrix", sim.range = "list", obs.stats = "matrix")) diff --git a/R/nicheApport-methods.R b/R/nicheApport-methods.R new file mode 100644 index 0000000..5d9cb25 --- /dev/null +++ b/R/nicheApport-methods.R @@ -0,0 +1,60 @@ +setMethod(f = "plot", signature = "fittedmodel", + definition = function(x, stat = "mean", base = NULL, ...){ + dots <- list(...) + if(!stat %in% c("mean", "variance")) + stop("'stat' parameter must be 'mean' or 'variance'") + + if(!"xlab" %in% names(dots)) dots$xlab <- "Rank abundance" + if(!"ylab" %in% names(dots)){ + if(is.null(base)) dots$ylab <- "Relative abundance" + else dots$ylab <- substitute(expression(log[b]("Relative abundance")), + list(b = base)) + } + dots$xaxt <- "n" + + if(!is.null(base)){ + do.call(plot, c(list(x = log(x@obs.stats[stat, ], base), bty = "n", + yaxt = "n"), dots)) + axis(side = 2, axTicks(2), + labels = parse(text=sprintf(paste(base, "^%d", sep = ""), + axTicks(2))), las=2) + } + else do.call(plot, c(list(x = x@obs.stats[stat, ], bty = "n"), dots)) + + axis(1, c(1, axisTicks(c(1, dim(x@obs.stats)[2]), log = FALSE, nint = 5))) + }) + +setMethod(f = "lines", signature = "fittedmodel", + definition = function(x, stat = "mean", base = NULL, range = FALSE, ...){ + dots <- list(...) + if(!stat %in% c("mean", "variance")) + stop("'stat' parameter must be 'mean' or 'variance'") + + if("lty" %in% dots) dots <- dots[names(dots) != "lty"] + if(!"col" %in% names(dots)) dots$col <- "blue" + if(!is.null(base)){ + sim.stats <- log(x@sim.stats[stat, ], base) + sim.range <- log(x@sim.range[[stat]], base) + } + else{ + sim.stats <- x@sim.stats[stat, ] + sim.range <- x@sim.range[[stat]] + } + + do.call(lines, c(list(x = sim.stats), dots)) + if(range){ + lines(sim.range["min", ], lty = 2) + lines(sim.range["max", ], lty = 2) + } + }) + +setMethod(f = "qqplot", signature = "fittedmodel", + definition = function(x, ...){ + + }) + +setMethod(f = "summary", signature = "fittedmodel", + definition = function(object, ...){ + + }) + From cd962e14b9c7a6a77d13a1272922d77ed650c140 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Sat, 5 Dec 2015 11:30:23 -0200 Subject: [PATCH 02/40] Update gitignore --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 24f4ddd..d390728 100644 --- a/.gitignore +++ b/.gitignore @@ -10,4 +10,5 @@ # RStudio project files .Rproj.user/ *.Rproj -*.Rbuildignore \ No newline at end of file +*.Rbuildignore +.Rproj.user From b676ac310b9080a68047a6ecc0adce768d25082e Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Sat, 5 Dec 2015 14:02:36 -0200 Subject: [PATCH 03/40] Update namespace --- NAMESPACE | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/NAMESPACE b/NAMESPACE index 3fbb289..de60c0a 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -3,3 +3,9 @@ export(dominanceDecay, dominancePreemp, MacArthurFraction, powerFraction, randAs # Export fitting function export(fitmodel, fitmodelCl, findPFw) + +# Export Classes +exportClasses(fittedmodel) + +# Export methods +exportMethods(plot, lines, qqplot, summary, show) \ No newline at end of file From 719200a35a02d0676237ca24f2dc9bd7fca1ca5c Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Sat, 5 Dec 2015 14:05:45 -0200 Subject: [PATCH 04/40] Create methods plot, lines, qqplot * Update method plot and create method lines to plot line of range of simulation. * Create qqplot --- R/nicheApport-methods.R | 49 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/R/nicheApport-methods.R b/R/nicheApport-methods.R index 5d9cb25..a6c462b 100644 --- a/R/nicheApport-methods.R +++ b/R/nicheApport-methods.R @@ -43,14 +43,53 @@ setMethod(f = "lines", signature = "fittedmodel", do.call(lines, c(list(x = sim.stats), dots)) if(range){ - lines(sim.range["min", ], lty = 2) - lines(sim.range["max", ], lty = 2) + do.call(lines, c(list(x = sim.range["min", ], lty = 2), dots)) + do.call(lines, c(list(x = sim.range["max", ], lty = 2), dots)) } }) setMethod(f = "qqplot", signature = "fittedmodel", - definition = function(x, ...){ + definition = function(x, stat = "mean", base = NULL, ...){ + dots <- list(...) + if(!stat %in% c("mean", "variance")) + stop("'stat' parameter must be 'mean' or 'variance'") + if(!"xlab" %in% names(dots)){ + if(is.null(base)) dots$xlab <- "Simulated abundance" + else dots$xlab <- substitute(expression(log[b]("Simulated abundance")), + list(b = base)) + } + if(!"ylab" %in% names(dots)){ + if(is.null(base)) dots$ylab <- "Observed abundance" + else dots$ylab <- substitute(expression(log[b]("Observed abundance")), + list(b = base)) + } + + if("lty" %in% dots) dots <- dots[names(dots) != "lty"] + + if(!is.null(base)){ + sim.stats <- log(x@sim.stats[stat, ], base) + sim.range <- log(x@sim.range[[stat]], base) + obs.stats <- log(x@obs.stats[stat, ], base) + } + else{ + sim.stats <- x@sim.stats[stat, ] + sim.range <- x@sim.range[[stat]] + obs.stats <- x@obs.stats[stat, ] + } + + dots$ylim <- c(min(c(sim.range["min", ], obs.stats)), + max(c(sim.range["max", ], obs.stats))) + + do.call(plot, c(list(x = sim.stats, y = sim.stats, type = "l"), dots)) + + lines(sim.stats, sim.range["min", ], lty = 2) + lines(sim.stats, sim.range["max", ], lty = 2) + + rank.fit <- rep(0, length(obs.stats)) + rank.fit[obs.stats >= sim.range["min", ] & obs.stats <= sim.range["max", ]] <- 1 + points(sim.stats[rank.fit == 0], obs.stats[rank.fit == 0], col = "#cccccc") + points(sim.stats[rank.fit == 1], obs.stats[rank.fit == 1]) }) setMethod(f = "summary", signature = "fittedmodel", @@ -58,3 +97,7 @@ setMethod(f = "summary", signature = "fittedmodel", }) +setMethod(f = "show", signature = "fittedmodel", + definition = function(object){ + + }) From c088fb9545b41bf0e07b17200e36944ce7a10f56 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Sat, 5 Dec 2015 14:08:05 -0200 Subject: [PATCH 05/40] Update to return object of fittedmodel class * Update handling ellipsis (...) * Now return object of fittedmodel class --- R/fitmodel.R | 39 +++++++++++++++++++++++++-------------- R/fitmodelCl.R | 44 ++++++++++++++++++++++++++++---------------- 2 files changed, 53 insertions(+), 30 deletions(-) diff --git a/R/fitmodel.R b/R/fitmodel.R index f57754d..6cdb3c9 100644 --- a/R/fitmodel.R +++ b/R/fitmodel.R @@ -16,6 +16,9 @@ fitmodel <- function(x, model, count, nRand = 999, ...){ stop("\n'count' must be specified") } + # Arguments in dots + dots <- list(...) + # Number of replicates and total species. n <- dim(x)[1] S <- dim(x)[2] @@ -28,12 +31,12 @@ fitmodel <- function(x, model, count, nRand = 999, ...){ for(i in 1:nRand){ sim <- matrix(nrow = n, ncol = S) for(j in 1:n){ - sim[j, ] <- do.call(model, list(N = N[j], S = S, count = count, ... = ...)) + sim[j, ] <- do.call(model, c(list(N = N[j], S = S, count = count), dots)) # Transform to relative abundance sim[j, ] <- sim[j, ] / sum(sim[j, ]) } - M[i, ] <- apply(sim, MARGIN = 2, FUN = mean) - V[i, ] <- apply(sim, MARGIN = 2, FUN = var) + M[i, ] <- apply(sim, 2, mean) + V[i, ] <- apply(sim, 2, var) } # Transform each replicate to relative abundance. @@ -42,8 +45,8 @@ fitmodel <- function(x, model, count, nRand = 999, ...){ } # Observed relative abundance mean and variance of replicates. - M0 <- apply(x, MARGIN = 2, FUN = mean) - V0 <- apply(x, MARGIN = 2, FUN = var) + M0 <- apply(x, 2, mean) + V0 <- apply(x, 2, var) # Probability that the observed mean and variance are predicted by the model. pM0 <- c() @@ -82,14 +85,22 @@ fitmodel <- function(x, model, count, nRand = 999, ...){ pvalueV <- sum(dTV > TV0) / (nRand + 1) # Simulation range for mean and variance. - rM <- apply(M, MARGIN = 2, FUN = range) - rV <- apply(V, MARGIN = 2, FUN = range) - dimnames(rM) <- list(c("min", "max"), paste("rank", 1:S, sep = "")) - rownames(rV) <- list(c("min", "max"), paste("rank", 1:S, sep = "")) + rM <- matrix(c(apply(M, 2, min), apply(M, 2, max)), nrow = 2, ncol = S, byrow = TRUE, + dimnames = list(c("min", "max"), paste("rank", 1:S, sep = ""))) + rV <- matrix(c(apply(V, 2, min), apply(V, 2, max)), nrow = 2, ncol = S, byrow = TRUE, + dimnames = list(c("min", "max"), paste("rank", 1:S, sep = ""))) - return(list(dTmean = dTM, dTvar = dTV, TMobs = TM0, TVobs = TV0, rangeM = rM, rangeV = rV, - simulations = matrix(c(apply(M, 2, mean), apply(V, 2, mean)), nrow = 2, ncol = S, byrow = TRUE, - dimnames = list(c("mean", "variance"), paste("rank", 1:S, sep = ""))), - stat = matrix(c(pvalueM, pvalueV), nrow = 2, ncol = 1, - dimnames = list(c("mean", "variance"), "p-value")))) + return(new("fittedmodel", + Tstats = list(dTmean = dTM, dTvar = dTV, TMobs = TM0, TVobs = TV0, + pvalue = matrix(c(pvalueM, pvalueV), nrow = 2, ncol = 1, + dimnames = list(c("mean", "variance"), + "p-value"))), + sim.stats = matrix(c(apply(M, 2, mean), apply(V, 2, mean)), nrow = 2, + ncol = S, byrow = TRUE, + dimnames = list(c("mean", "variance"), + paste("rank", 1:S, sep = ""))), + sim.range = list(mean = rM, variance = rV), + obs.stats = matrix(c(M0, V0), nrow = 2, ncol = S, byrow = TRUE, + dimnames = list(c("mean", "variance"), + paste("rank", 1:S, sep = ""))))) } diff --git a/R/fitmodelCl.R b/R/fitmodelCl.R index 0b347fd..21ceb08 100644 --- a/R/fitmodelCl.R +++ b/R/fitmodelCl.R @@ -16,6 +16,9 @@ fitmodelCl <- function(x, model, count, nRand = 999, nCores = 2, ...){ stop("\n'count' must be specified") } + # Arguments in dots + dots <- list(...) + # Detect numbers of cores and make a cluster nc <- detectCores() if(nc < 2) { @@ -41,27 +44,28 @@ fitmodelCl <- function(x, model, count, nRand = 999, nCores = 2, ...){ n <- dim(x)[1] S <- dim(x)[2] # Total abundance of each replicates. - N <- apply(x, MARGIN = 1, FUN = sum) + N <- apply(x, 1, sum) # Function to run in each cores fn <- function(rand, n, N, S, model, count, ...){ + dots <- list(...) clM <- matrix(nrow = rand, ncol = S) clV <- matrix(nrow = rand, ncol = S) for(i in 1:rand){ sim <- matrix(nrow = n, ncol = S) for(j in 1:n){ - sim[j, ] <- model(N = N[j], S = S, count = count, ...) + sim[j, ] <- do.call(model, c(list(N = N[j], S = S, count = count), dots)) # Transform to relative abundance sim[j, ] <- sim[j, ] / sum(sim[j, ]) } - clM[i, ] = apply(sim, MARGIN = 2, FUN = mean) - clV[i, ] = apply(sim, MARGIN = 2, FUN = var) + clM[i, ] = apply(sim, 2, mean) + clV[i, ] = apply(sim, 2, var) } return(list(M = clM, V = clV)) } # Send function to cluster - tmp <- clusterApplyLB(cl, randc, fn, n = n, N = N, S = S, model = getFunction(model), count = count, ...) + tmp <- do.call(clusterApplyLB, c(list(cl = cl, x = randc, fun = fn, n = n, N = N, S = S, model = getFunction(model), count = count), dots)) # 'nRand' means and variances of 'n' simulations to the model. M <- matrix(ncol = S) @@ -84,8 +88,8 @@ fitmodelCl <- function(x, model, count, nRand = 999, nCores = 2, ...){ } # Observed relative abundance mean and variance of replicates. - M0 <- apply(x, MARGIN = 2, FUN = mean) - V0 <- apply(x, MARGIN = 2, FUN = var) + M0 <- apply(x, 2, mean) + V0 <- apply(x, 2, var) # Probability that the observed mean and variance are predicted by the model. pM0 <- c() @@ -147,17 +151,25 @@ fitmodelCl <- function(x, model, count, nRand = 999, nCores = 2, ...){ pvalueV <- sum(dTV > TV0) / (nRand + 1) # Simulation range for mean and variance. - rM <- apply(M, MARGIN = 2, FUN = range) - rV <- apply(V, MARGIN = 2, FUN = range) - dimnames(rM) <- list(c("min", "max"), paste("rank", 1:S, sep = "")) - rownames(rV) <- list(c("min", "max"), paste("rank", 1:S, sep = "")) + rM <- matrix(c(apply(M, 2, min), apply(M, 2, max)), nrow = 2, ncol = S, byrow = TRUE, + dimnames = list(c("min", "max"), paste("rank", 1:S, sep = ""))) + rV <- matrix(c(apply(V, 2, min), apply(V, 2, max)), nrow = 2, ncol = S, byrow = TRUE, + dimnames = list(c("min", "max"), paste("rank", 1:S, sep = ""))) # Stop Cluster stopCluster(cl) - return(list(dTmean = dTM, dTvar = dTV, TMobs = TM0, TVobs = TV0, rangeM = rM, rangeV = rV, - simulations = matrix(c(apply(M, 2, mean), apply(V, 2, mean)), nrow = 2, ncol = S, byrow = TRUE, - dimnames = list(c("mean", "variance"), paste("rank", 1:S, sep = ""))), - stat = matrix(c(pvalueM, pvalueV), nrow = 2, ncol = 1, - dimnames = list(c("mean", "variance"), "p-value")))) + return(new("fittedmodel", + Tstats = list(dTmean = dTM, dTvar = dTV, TMobs = TM0, TVobs = TV0, + pvalue = matrix(c(pvalueM, pvalueV), nrow = 2, ncol = 1, + dimnames = list(c("mean", "variance"), + "p-value"))), + sim.stats = matrix(c(apply(M, 2, mean), apply(V, 2, mean)), nrow = 2, + ncol = S, byrow = TRUE, + dimnames = list(c("mean", "variance"), + paste("rank", 1:S, sep = ""))), + sim.range = list(mean = rM, variance = rV), + obs.stats = matrix(c(M0, V0), nrow = 2, ncol = S, byrow = TRUE, + dimnames = list(c("mean", "variance"), + paste("rank", 1:S, sep = ""))))) } From 25b3e2830fcafdf19077666438e721167c1d89fb Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 7 Dec 2015 02:37:24 -0200 Subject: [PATCH 06/40] Update class name and methods Remove summary methods and improove show --- NAMESPACE | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index de60c0a..65de939 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -5,7 +5,7 @@ export(dominanceDecay, dominancePreemp, MacArthurFraction, powerFraction, randAs export(fitmodel, fitmodelCl, findPFw) # Export Classes -exportClasses(fittedmodel) +exportClasses(fitmodel) # Export methods -exportMethods(plot, lines, qqplot, summary, show) \ No newline at end of file +exportMethods(plot, lines, qqplot, show) \ No newline at end of file From eb2a2f81ae5eda42fdc8d245961a9c0581e2bc00 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 7 Dec 2015 02:37:43 -0200 Subject: [PATCH 07/40] Start fitmodel class documentation --- man/fitmodel-class.Rd | 88 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 man/fitmodel-class.Rd diff --git a/man/fitmodel-class.Rd b/man/fitmodel-class.Rd new file mode 100644 index 0000000..5445583 --- /dev/null +++ b/man/fitmodel-class.Rd @@ -0,0 +1,88 @@ +\name{fitmodel-class} + +\docType{class} + +\alias{fitmodel-class} +\alias{lines,fitmodel-method} +\alias{plot,fitmodel-method} +\alias{qqplot,fitmodel-method} +\alias{show,fitmodel-method} + +\title{Class \code{"fitmodel"} from Niche Apportionment fitting} + +\description{Encapsulate results from Niche Apportionment fitting} + +\section{Objects from the Class}{ + Objects can be created by calls of the form \code{new("fitmodel", ...)}. Object results mainly from procedures executed from \code{\link{fitmodel}} or \code{\link{fitmodelCl}} call. +} + +\section{Slots}{ + \describe{ + \item{\code{call}:}{ + Object of class \code{"list"} containing: + \describe{ + \item{model}{Character containing model name.} + \item{nRepl}{Number of replicates.} + \item{nRank}{Number of ranks.} + \item{nRand}{Number of randomizations.} + \item{count}{Logical value informing if observed values are counts (discrete).} + } + } + \item{\code{Tstats}:}{ + Object of class \code{"list"} containing: + \describe{ + \item{dTmean}{Vector containing distribution of \emph{T} values for mean.} + \item{dTvar}{Vector containing distribution of \emph{T} values for variance.} + \item{TMobs}{Observed value of \emph{T} for mean.} + \item{TVobs}{Observed value of \emph{T} for variance.} + \item{pvalue}{Matrix containing p-value for mean and variance.} + } + } + \item{\code{sim.stats}:}{ + Object of class \code{"matrix"} containing mean and variance of simulations to each rank. + } + \item{\code{sim.range}:}{ + Object of class \code{"list"} containing: + \describe{ + \item{mean}{Matrix containing minimum and maximum simulation values for mean of each rank.} + \item{variance}{Matrix containing minimum and maximum simulation values for variance of each rank.} + } + } + \item{\code{obs.stats}:}{ + Object of class \code{"matrix"} containing mean and variance of replicates observed to each rank. + } + } +} + +\section{Methods}{ + \describe{ + \item{lines}{\code{signature(x = "fitmodel")}: Plot line of fitted model.} + \item{plot}{\code{signature(x = "fitmodel")}: Plot ranked abundance.} + \item{qqplot}{\code{signature(x = "fitmodel")}: Quantile-Quantile plot.} + \item{show}{\code{signature(object = "fitmodel")}: Display object.} + + The methods \code{lines}, \code{plot} and \code{qqplot} accept parameters \code{stat} and \code{base}. Further the methods \code{lines} and \code{qqplot} accept parameter \code{range}. The parameter \code{stat} inform if line must be plotted using mean (\code{"mean"}) or variance (\code{"variance"}) of model simulation. The \code{base} parameter inform the base of logarithm. If this value is different of \code{NULL}, then data are transformed to logarithm. The \code{range} parameter inform if minimum and maximum line must be plotted. + } +} + +\author{ + Mario J. Marques-Azevedo + + Maintainer: Mario J. Marques-Azevedo +} + +\examples{ + data <- matrix(nrow = 10, ncol = 40) + for(i in 1:length(data[ ,1])){ + data[i, ] <- randFraction(N = 100, S = 40, count = FALSE) + } + m1 <- fitmodelCl(x = data, model = "randFraction", count = FALSE, nRand = 99, nCores = 2) + m1 + plot(m1, base = 2) + lines(m1, base = 2, range = TRUE) + + # For qqplot + qqplot(m1, base = 2, range = TRUE) +} + +\keyword{classes} From 1e120a73c7e0eb66917cca7d035e0750d47afaff Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 7 Dec 2015 02:40:07 -0200 Subject: [PATCH 08/40] Update documentation to class/method Improove documentation and inform about class fitmodel --- man/fitmodel.Rd | 31 ++++++++++++++----------------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/man/fitmodel.Rd b/man/fitmodel.Rd index 524af3f..f804999 100644 --- a/man/fitmodel.Rd +++ b/man/fitmodel.Rd @@ -3,10 +3,10 @@ \alias{fitmodel} \alias{fitmodelCl} -\title{Fit species rank abundance distribution to data} +\title{Fitting of species rank abundance distribution to data} \description{ - Fit niche apportionment models proposed by Tokeshi (1990, 1996) using procedures proposed by Bersier & Sugihara (1997) and modified by Cassey & King (2001) and Mouillot et al. (2003). The protocol use relative abundance to fit simulated species rank abundance of particular model to observed rank abundance using Monte Carlo approach. The \code{fitmodelCl} function use parallel computation for run simulations. + Fits niche apportionment models, proposed by Tokeshi (1990, 1996), using procedures proposed by Bersier & Sugihara (1997) and modified by Cassey & King (2001) and Mouillot et al. (2003). The protocol use relative abundance to fit simulated species rank abundance of particular model to observed rank abundance using Monte Carlo approach. The \code{fitmodelCl} function use parallel computation for run simulations. } \usage{ @@ -15,7 +15,7 @@ } \arguments{ - \item{x}{Data frame or matrix with total species rank (from largest abundance to smallest) at columns and replicates at rows. See 'Details' for more information.} + \item{x}{Data frame or matrix with species ranks (ordered from largest abundance to smallest) at columns and replicates at rows. See 'Details' for more information.} \item{model}{String containing one of follow values: "dominanceDecay", "dominancePreemp", "MacArthurFraction", "powerFraction", "randAssort", "randFraction".} \item{count}{Specify if measure of abundance is number of individuals. See 'Details' for more information.} \item{nRand}{Number of simulations.} @@ -31,10 +31,10 @@ The fit use the protocol proposed by Cassey & King (2001) and ranked relative abundance recommendations by Mouillot et al. (2003), with some modifications, as the follow: \enumerate{ - \item{Run ranked relative abundance of specified model of each replicates with total abundance of replicates and total ranks (\code{S}) of all replicates (\code{n}). Calculate mean (\code{M}) and variance (\code{V}) of each rank. This procedures is repeated \code{nRand} times and result in \code{nRand} \code{M} and \code{V}.} - \item{Transform abundance of each replicates in relative abundance, maintaining the rank.} + \item{Run ranked observed abundance of specified model of each replicates, retaining the total abundance and number of ranks present in each replicate. Transform simulated abundance to relative abundance and calculate mean (\code{M}) and variance (\code{V}) of each rank for all replicates \code{n}. This procedures is repeated \code{nRand} times and result in \code{nRand} \code{M} and \code{V} for all \code{S} ranks.} + \item{Transform observed abundance of each replicates in relative abundance, retaining the rank.} \item{Calculate mean (\code{M0}) and variance (\code{V0}) of each rank for observed replicates.} - \item{Calculate the estimated p-value for mean of each rank \code{M0[S]} is in \code{nRand} simulated rank \code{M[S]}: + \item{Calculate the estimated p-value for mean of each rank \code{M0[S]} in \code{nRand} simulated rank \code{M[S]}: \code{p(M)[S] = 2 * min((bl + 1) / (nRand + 1), (bs + 1) / (nRand + 1))}, @@ -43,26 +43,20 @@ \code{T0(M0) = - 2 sum(log(p[S](M)))} and \code{T0(V0) = - 2 sum(log(p[S](V)))}.} - \item{Calculate the distribution of \code{T} of each rank as follow: for each \code{M[S]} of all \code{nRand} means simulations calculate \code{T(M)} using steps 4-5. This procedures is the same to variances \code{T(V)}.} + \item{Calculate the distribution of \emph{T} of each rank as follow: for each \code{M[S]} of all \code{nRand} means simulations calculate \code{T(M)} using steps 4-5. This procedures is the same to variances \code{T(V)}.} \item{Calculate the final estimated p-value to fit data for model as follow: \code{p-value = t / (nRand + 1)}, where \code{t} is the number of \code{T(M)} values greater than \code{T0(M0)}. The same for variance.} } - For more details see Bersier & Sugihara (1997), Cassey & King (2001) and Mouillot et al. (2003). Model fit to the observed abundance if p-value to means and variances are not significant at predetermined significance level. The observed T value (TMobs or TVobs, see 'Value' bellow) measure how well model fits to data; better fit had smaller value (Bersier & Sugihara 1997). + For more details see Bersier & Sugihara (1997), Cassey & King (2001) and Mouillot et al. (2003). Model fits to the observed abundance if p-value to means and variances are not significant at predetermined significance level (probability of found observed \emph{T} at simulated \emph{T}). The observed \emph{T} value (\code{TMobs} or \code{TVobs}, see 'Value' bellow) measure how well model fits to data; better fit had smaller value (Bersier & Sugihara 1997). - \code{fitmodelCl} use parallel computation to divide the number of simulations among the processor cores or threads that run the procedures simultaneously. When \code{nCores = 1} the function detect number of cores or threads automatically. If you inform incorrectly the number of cores or threads, the function will inform you to correct information or will recommend to use \code{fitmodel}. The overall process using parallel computation can be twice as fast, depending on the number of processor cores or threads used. + \code{fitmodelCl} use parallel computation to divide the number of simulations among the processor cores or threads and run the procedures simultaneously. When \code{nCores = 1} the function detect number of cores or threads automatically. If you inform incorrectly the number of cores or threads, the function will inform you to correct information or will recommend to use \code{fitmodel}. The overall process using parallel computation can be twice as fast, depending on the number of processor cores or threads used. } \value{ - List containing: - \item{dTmean}{Distribution of \emph{T} values for mean.} - \item{dTvar}{Distribution of \emph{T} values for variance.} - \item{TMobs}{Observed value of \emph{T} for mean.} - \item{TVobs}{Observed value of \emph{T} for variance.} - \item{simulations}{Matrix containing mean and variance of simulations to each rank.} - \item{stat}{Matrix containing p-value for mean and variance.} + An object of class \code{fitmodel}. } \references{ @@ -87,11 +81,14 @@ For models see \code{\link{dominanceDecay}}, \code{\link{dominancePreemp}}, \code{\link{MacArthurFraction}}, \code{\link{randFraction}}, \code{\link{randAssort}} and \code{\link{powerFraction}}. For fit models see \code{\link{fitmodel}}. To find best \code{w} parameter to \code{\link{powerFraction}} see \code{\link{findPFw}}. + + For class \code{fitmodel} see \link{fitmodel-class}. } \examples{ data <- matrix(nrow = 10, ncol = 40) for(i in 1:length(data[ ,1])){ data[i, ] <- randFraction(N = 100, S = 40, count = FALSE) } - fitmodelCl(x = data, model = "randFraction", count = FALSE, nRand = 99, nCores = 2) + m1 <- fitmodelCl(x = data, model = "randFraction", count = FALSE, nRand = 99, nCores = 2) + m1 } From 2ae83a402cb9d1154174a6d3d29945a65493795d Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 7 Dec 2015 02:40:37 -0200 Subject: [PATCH 09/40] Update documentation --- man/findPFw.Rd | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/man/findPFw.Rd b/man/findPFw.Rd index 48a721a..1fd1d33 100644 --- a/man/findPFw.Rd +++ b/man/findPFw.Rd @@ -26,11 +26,11 @@ \details{ The replicates in data frame or matrix \code{x} must be in rows and ranked by abundance. First rank (column 1) will be species with largest abundance, second column with second largest abundance, and so on until the species with smallest abundance. Note that this protocol do not require species identification. First rank of replicates 1, for instance, may be not the same as first rank of replicates 2. Note too that number of species may be differ among replicates. In this case, zeros must be used to the rank(s). - The fit use the protocol proposed by Cassey & King (2001) and ranked relative abundance recommendations by Mouillot et al. (2003), with some modifications. For more information of procedures consult documentation of \code{\link{fitmodel}} or \code{\link{fitmodelCl}}. + The fitting use the protocol proposed by Bersier & Sugihara (1997) and modiffied by Cassey & King (2001) and ranked relative abundance recommendations by Mouillot et al. (2003), with some modifications. For more information of procedures consult documentation of \code{\link{fitmodel}} or \code{\link{fitmodelCl}}. Observed abundance fit to the model if p-value to means and variances are not significant at predetermined significance level (probability of found observed \emph{T} at simulated \emph{T}). The observed T value (TMobs or TVobs, see 'Value' bellow) measure how well model fits to data; better fit had smaller value (Bersier & Sugihara 1997). - For more details see Bersier & Sugihara (1997), Cassey & King (2001) and Mouillot et al. (2003). Observed abundance fit to the model if p-value to means and variances are not significant at predetermined significance level. The observed T value (TMobs or TVobs, see 'Value' bellow) measure how well model fits to data; better fit had smaller value (Bersier & Sugihara 1997). + If \code{cl} is \code{TRUE} the function fit model to data calling \code{fitmodelCl} for parallel computation. This function divide the number of simulations among the processor cores or threads and run the procedures simultaneously. If \code{cl} is \code{FALSE} the function call \code{fitmodel} to fit model to data. When \code{nCores = 1} the function detect number of cores or threads automatically. If you inform incorrectly the number of cores or threads, the function will inform you to correct information or will recommend to use \code{fitmodel}. The overall process using parallel computation can be twice as fast, depending on the number of processor cores or threads used. - If \code{cl} is \code{TRUE} the function fit model to data calling \code{fitmodelCl} for parallel computation to divide the number of simulations among the processor cores or threads that run the procedures simultaneously. If \code{cl} is \code{FALSE} the function call \code{fitmodel} to fit model to data. When \code{nCores = 1} the function detect number of cores or threads automatically. If you inform incorrectly the number of cores or threads, the function will inform you to correct information or will recommend to use \code{fitmodel}. The overall process using parallel computation can be twice as fast, depending on the number of processor cores or threads used. + The \code{findPFw} function fit Power Fraction model with different \code{w} values and return information (see bellow 'Value') to choose the best \code{w}. The criteria can be the smallest values of \code{TMobs} or \code{TVobs} (Bersier & Sugihara 1997) or higher p-value (probability of found observed \emph{T} at simulated \emph{T}). } \value{ From 2ab9ef4349a7226536237b68b2b3cf4c606e647b Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 7 Dec 2015 02:42:45 -0200 Subject: [PATCH 10/40] Update class name and methods * Update class name * Update methods plot, lines and qqplot * Create method show --- R/nicheApport-classes.R | 2 +- R/nicheApport-methods.R | 64 +++++++++++++++++++++++++++++------------ 2 files changed, 46 insertions(+), 20 deletions(-) diff --git a/R/nicheApport-classes.R b/R/nicheApport-classes.R index 8224246..655cb37 100644 --- a/R/nicheApport-classes.R +++ b/R/nicheApport-classes.R @@ -1 +1 @@ -setClass("fittedmodel", slots = c(Tstats = "list", sim.stats = "matrix", sim.range = "list", obs.stats = "matrix")) +setClass("fitmodel", slots = c(call = "list", Tstats = "list", sim.stats = "matrix", sim.range = "list", obs.stats = "matrix")) diff --git a/R/nicheApport-methods.R b/R/nicheApport-methods.R index a6c462b..48d79bb 100644 --- a/R/nicheApport-methods.R +++ b/R/nicheApport-methods.R @@ -1,4 +1,4 @@ -setMethod(f = "plot", signature = "fittedmodel", +setMethod(f = "plot", signature = "fitmodel", definition = function(x, stat = "mean", base = NULL, ...){ dots <- list(...) if(!stat %in% c("mean", "variance")) @@ -10,21 +10,32 @@ setMethod(f = "plot", signature = "fittedmodel", else dots$ylab <- substitute(expression(log[b]("Relative abundance")), list(b = base)) } + + dots$yaxt <- "n" dots$xaxt <- "n" if(!is.null(base)){ - do.call(plot, c(list(x = log(x@obs.stats[stat, ], base), bty = "n", - yaxt = "n"), dots)) - axis(side = 2, axTicks(2), - labels = parse(text=sprintf(paste(base, "^%d", sep = ""), - axTicks(2))), las=2) + obs.stats <- log(x@obs.stats[stat, ], base) + yTicks <- axisTicks(range(obs.stats), log = FALSE, nint = 7) + } + else{ + obs.stats <- x@obs.stats[stat, ] + yTicks <- axisTicks(c(0, max(obs.stats)), log = FALSE, nint = 7) } - else do.call(plot, c(list(x = x@obs.stats[stat, ], bty = "n"), dots)) + + xTicks <- axisTicks(c(1, length(obs.stats)), log = FALSE, nint = 7) - axis(1, c(1, axisTicks(c(1, dim(x@obs.stats)[2]), log = FALSE, nint = 5))) + do.call(plot, c(list(x = obs.stats, bty = "n"), dots)) + + axis(1, c(1, xTicks)) + if(!is.null(base)){ + axis(side = 2, at = yTicks, las = 2, + labels = parse(text=sprintf(paste(base, "^%d", sep = ""), yTicks))) + } + else axis(2, at = yTicks, las = 2) }) -setMethod(f = "lines", signature = "fittedmodel", +setMethod(f = "lines", signature = "fitmodel", definition = function(x, stat = "mean", base = NULL, range = FALSE, ...){ dots <- list(...) if(!stat %in% c("mean", "variance")) @@ -48,8 +59,8 @@ setMethod(f = "lines", signature = "fittedmodel", } }) -setMethod(f = "qqplot", signature = "fittedmodel", - definition = function(x, stat = "mean", base = NULL, ...){ +setMethod(f = "qqplot", signature = "fitmodel", + definition = function(x, stat = "mean", base = NULL, range = FALSE, ...){ dots <- list(...) if(!stat %in% c("mean", "variance")) stop("'stat' parameter must be 'mean' or 'variance'") @@ -83,8 +94,10 @@ setMethod(f = "qqplot", signature = "fittedmodel", do.call(plot, c(list(x = sim.stats, y = sim.stats, type = "l"), dots)) - lines(sim.stats, sim.range["min", ], lty = 2) - lines(sim.stats, sim.range["max", ], lty = 2) + if(range){ + lines(sim.stats, sim.range["min", ], lty = 2) + lines(sim.stats, sim.range["max", ], lty = 2) + } rank.fit <- rep(0, length(obs.stats)) rank.fit[obs.stats >= sim.range["min", ] & obs.stats <= sim.range["max", ]] <- 1 @@ -92,12 +105,25 @@ setMethod(f = "qqplot", signature = "fittedmodel", points(sim.stats[rank.fit == 1], obs.stats[rank.fit == 1]) }) -setMethod(f = "summary", signature = "fittedmodel", - definition = function(object, ...){ - - }) - -setMethod(f = "show", signature = "fittedmodel", +setMethod(f = "show", signature = "fitmodel", definition = function(object){ + cat("Niche Apportionment fitting\n") + cat("Data type:", ifelse(object@call$count, "discrete", "continuous"), "\n") + cat("Model:", object@call$model, "\n") + cat("\t\tNumber of randomization:", object@call$nRand, "\n") + cat("\t\tNumber of ranks:", object@call$nRank, "\n") + cat("\t\tNumber of replicates:", object@call$nRepl, "\n\n") + + cat("Fitting for mean\n") + print(base::summary(object@Tstats$dTmean)) + + cat("Observed T:", object@Tstats$TMobs, "\n") + cat("P-value for Tobs greater than simulated:", + object@Tstats$pvalue[1, ], "\n\n") + cat("Fitting for variance\n") + print(base::summary(object@Tstats$dTvar)) + cat("Observed T:", object@Tstats$TVobs, "\n") + cat("P-value for Tobs greater than simulated:", + object@Tstats$pvalue[2, ], "\n") }) From 49e523798ff5ad2777a58f858a2c6f8fcded76a4 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 7 Dec 2015 02:43:19 -0200 Subject: [PATCH 11/40] Update to class fitmodel --- R/findPFw.R | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/R/findPFw.R b/R/findPFw.R index 1b44712..e71057b 100644 --- a/R/findPFw.R +++ b/R/findPFw.R @@ -18,10 +18,10 @@ findPFw <- function(x, count, ws = 0, we = 1, f = 0.01, nRand = 99, cl = TRUE, n } else { m <- fitmodel(x, model = "powerFraction", count = count, nRand = nRand, w = out$w[i]) } - out$TMobs[i] <- m$TMobs - out$TVobs[i] <- m$TVobs - out$pvalueM[i] <- m$stat[1, ] - out$pvalueV[i] <- m$stat[2, ] + out$TMobs[i] <- m@Tstats$TMobs + out$TVobs[i] <- m@Tstats$TVobs + out$pvalueM[i] <- m@Tstats$pvalue[1, ] + out$pvalueV[i] <- m@Tstats$pvalue[2, ] } return(out) } From 4f46e3ab5e0c613b0c584c083d16ff569cdc3dcc Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 7 Dec 2015 02:46:54 -0200 Subject: [PATCH 12/40] Ranks to replicates and class fitmodel * Now each simulation uses number of rank of each replicates and not more total rank. * Update class name --- R/fitmodel.R | 44 +++++++++++++++++++++------------------ R/fitmodelCl.R | 56 +++++++++++++++++++++++++++----------------------- 2 files changed, 54 insertions(+), 46 deletions(-) diff --git a/R/fitmodel.R b/R/fitmodel.R index 6cdb3c9..12af7b9 100644 --- a/R/fitmodel.R +++ b/R/fitmodel.R @@ -19,21 +19,23 @@ fitmodel <- function(x, model, count, nRand = 999, ...){ # Arguments in dots dots <- list(...) - # Number of replicates and total species. + # Number of replicates and ranks. n <- dim(x)[1] - S <- dim(x)[2] - # Total abundance of each replicates. - N <- apply(x, MARGIN = 1, FUN = sum) + Rk <- dim(x)[2] + + # Total abundance and species of each replicates. + N <- apply(x, 1, sum) + S <- apply(x > 0, 1, sum) # 'nRand' means and variances of 'n' simulations to the model. - M <- matrix(nrow = nRand, ncol = S) - V <- matrix(nrow = nRand, ncol = S) + M <- matrix(nrow = nRand, ncol = Rk) + V <- matrix(nrow = nRand, ncol = Rk) for(i in 1:nRand){ - sim <- matrix(nrow = n, ncol = S) + sim <- matrix(0, nrow = n, ncol = Rk) for(j in 1:n){ - sim[j, ] <- do.call(model, c(list(N = N[j], S = S, count = count), dots)) + sim[j,1:S[j]] <- do.call(model, c(list(N = N[j], S = S[j], count = count), dots)) # Transform to relative abundance - sim[j, ] <- sim[j, ] / sum(sim[j, ]) + sim[j,1:S[j]] <- sim[j, ] / sum(sim[j, ]) } M[i, ] <- apply(sim, 2, mean) V[i, ] <- apply(sim, 2, var) @@ -51,7 +53,7 @@ fitmodel <- function(x, model, count, nRand = 999, ...){ # Probability that the observed mean and variance are predicted by the model. pM0 <- c() pV0 <- c() - for(i in 1:S){ + for(i in 1:Rk){ # p = (b+1)/(m+1) pM0[i] <- 2 * min((sum(M[ ,i] < M0[i]) + 1) / (nRand + 1), (sum(M[ ,i] > M0[i]) + 1) / (nRand + 1)) @@ -69,7 +71,7 @@ fitmodel <- function(x, model, count, nRand = 999, ...){ for(i in 1:nRand){ pM <- c() pV <- c() - for(j in 1:S){ + for(j in 1:Rk){ # p = (b+1)/(m+1) pM[j] <- 2 * min(((sum(c(M[-i,j], M0[j]) < M[i,j]) + 1) / (nRand + 1)), ((sum(c(M[-i,j], M0[j]) > M[i,j]) + 1) / (nRand + 1))) @@ -85,22 +87,24 @@ fitmodel <- function(x, model, count, nRand = 999, ...){ pvalueV <- sum(dTV > TV0) / (nRand + 1) # Simulation range for mean and variance. - rM <- matrix(c(apply(M, 2, min), apply(M, 2, max)), nrow = 2, ncol = S, byrow = TRUE, - dimnames = list(c("min", "max"), paste("rank", 1:S, sep = ""))) - rV <- matrix(c(apply(V, 2, min), apply(V, 2, max)), nrow = 2, ncol = S, byrow = TRUE, - dimnames = list(c("min", "max"), paste("rank", 1:S, sep = ""))) + rM <- matrix(c(apply(M, 2, min), apply(M, 2, max)), nrow = 2, ncol = Rk, byrow = TRUE, + dimnames = list(c("min", "max"), paste("rank", 1:Rk, sep = ""))) + rV <- matrix(c(apply(V, 2, min), apply(V, 2, max)), nrow = 2, ncol = Rk, byrow = TRUE, + dimnames = list(c("min", "max"), paste("rank", 1:Rk, sep = ""))) - return(new("fittedmodel", + return(new("fitmodel", + call = list(model = model, nRepl = n, nRank = Rk, nRand = nRand, + count = count), Tstats = list(dTmean = dTM, dTvar = dTV, TMobs = TM0, TVobs = TV0, pvalue = matrix(c(pvalueM, pvalueV), nrow = 2, ncol = 1, dimnames = list(c("mean", "variance"), "p-value"))), sim.stats = matrix(c(apply(M, 2, mean), apply(V, 2, mean)), nrow = 2, - ncol = S, byrow = TRUE, + ncol = Rk, byrow = TRUE, dimnames = list(c("mean", "variance"), - paste("rank", 1:S, sep = ""))), + paste("rank", 1:Rk, sep = ""))), sim.range = list(mean = rM, variance = rV), - obs.stats = matrix(c(M0, V0), nrow = 2, ncol = S, byrow = TRUE, + obs.stats = matrix(c(M0, V0), nrow = 2, ncol = Rk, byrow = TRUE, dimnames = list(c("mean", "variance"), - paste("rank", 1:S, sep = ""))))) + paste("rank", 1:Rk, sep = ""))))) } diff --git a/R/fitmodelCl.R b/R/fitmodelCl.R index 21ceb08..dc6b8c3 100644 --- a/R/fitmodelCl.R +++ b/R/fitmodelCl.R @@ -34,29 +34,31 @@ fitmodelCl <- function(x, model, count, nRand = 999, nCores = 2, ...){ } cl <- makeCluster(nc) - # It partitions randomizations between cores + # Partition randomizations between cores randc <- rep(floor(nRand / nc), nc) if(sum(randc < nRand)){ randc[1:(nRand - sum(randc))] <- randc[1:(nRand - sum(randc))] + 1 } - # Number of replicates and total species + # Number of replicates and ranks. n <- dim(x)[1] - S <- dim(x)[2] - # Total abundance of each replicates. + Rk <- dim(x)[2] + + # Total abundance and species of each replicates. N <- apply(x, 1, sum) + S <- apply(x > 0, 1, sum) # Function to run in each cores - fn <- function(rand, n, N, S, model, count, ...){ + fn <- function(rand, n, N, S, Rk, model, count, ...){ dots <- list(...) - clM <- matrix(nrow = rand, ncol = S) - clV <- matrix(nrow = rand, ncol = S) + clM <- matrix(nrow = rand, ncol = Rk) + clV <- matrix(nrow = rand, ncol = Rk) for(i in 1:rand){ - sim <- matrix(nrow = n, ncol = S) + sim <- matrix(0, nrow = n, ncol = Rk) for(j in 1:n){ - sim[j, ] <- do.call(model, c(list(N = N[j], S = S, count = count), dots)) + sim[j,1:S[j]] <- do.call(model, c(list(N = N[j], S = S[j], count = count), dots)) # Transform to relative abundance - sim[j, ] <- sim[j, ] / sum(sim[j, ]) + sim[j,1:S[j]] <- sim[j, ] / sum(sim[j, ]) } clM[i, ] = apply(sim, 2, mean) clV[i, ] = apply(sim, 2, var) @@ -65,11 +67,11 @@ fitmodelCl <- function(x, model, count, nRand = 999, nCores = 2, ...){ } # Send function to cluster - tmp <- do.call(clusterApplyLB, c(list(cl = cl, x = randc, fun = fn, n = n, N = N, S = S, model = getFunction(model), count = count), dots)) + tmp <- do.call(clusterApplyLB, c(list(cl = cl, x = randc, fun = fn, n = n, N = N, S = S, Rk = Rk, model = getFunction(model), count = count), dots)) # 'nRand' means and variances of 'n' simulations to the model. - M <- matrix(ncol = S) - V <- matrix(ncol = S) + M <- matrix(ncol = Rk) + V <- matrix(ncol = Rk) # Create data frame with result of cluster M <- tmp[[1]]$M @@ -94,7 +96,7 @@ fitmodelCl <- function(x, model, count, nRand = 999, nCores = 2, ...){ # Probability that the observed mean and variance are predicted by the model. pM0 <- c() pV0 <- c() - for(i in 1:S){ + for(i in 1:Rk){ # p = (b+1)/(m+1) pM0[i] <- 2 * min((sum(M[ ,i] < M0[i]) + 1) / (nRand + 1), (sum(M[ ,i] > M0[i]) + 1) / (nRand + 1)) @@ -107,7 +109,7 @@ fitmodelCl <- function(x, model, count, nRand = 999, nCores = 2, ...){ TV0 <- -2 * sum(log(pV0)) # Function to run in cluster - fn <- function(core, rand, nRand, M, V, S){ + fn <- function(core, rand, nRand, M, V, Rk){ cldTM <- c() cldTV <- c() @@ -120,7 +122,7 @@ fitmodelCl <- function(x, model, count, nRand = 999, nCores = 2, ...){ for(i in range){ clpM <- c() clpV <- c() - for(j in 1:S){ + for(j in 1:Rk){ # p = (b+1)/(m+1) clpM[j] <- 2 * min(((sum(c(M[-i,j], M0[j]) < M[i,j]) + 1) / (nRand + 1)), ((sum(c(M[-i,j], M0[j]) > M[i,j]) + 1) / (nRand + 1))) @@ -134,7 +136,7 @@ fitmodelCl <- function(x, model, count, nRand = 999, nCores = 2, ...){ } # Send function to cluster - tmp <- clusterApplyLB(cl, seq(nc), fn, rand = randc, nRand = nRand, M = M, V = V, S = S) + tmp <- clusterApplyLB(cl, seq(nc), fn, rand = randc, nRand = nRand, M = M, V = V, Rk = Rk) # Distribution of T values. dTM <- c() @@ -151,25 +153,27 @@ fitmodelCl <- function(x, model, count, nRand = 999, nCores = 2, ...){ pvalueV <- sum(dTV > TV0) / (nRand + 1) # Simulation range for mean and variance. - rM <- matrix(c(apply(M, 2, min), apply(M, 2, max)), nrow = 2, ncol = S, byrow = TRUE, - dimnames = list(c("min", "max"), paste("rank", 1:S, sep = ""))) - rV <- matrix(c(apply(V, 2, min), apply(V, 2, max)), nrow = 2, ncol = S, byrow = TRUE, - dimnames = list(c("min", "max"), paste("rank", 1:S, sep = ""))) + rM <- matrix(c(apply(M, 2, min), apply(M, 2, max)), nrow = 2, ncol = Rk, byrow = TRUE, + dimnames = list(c("min", "max"), paste("rank", 1:Rk, sep = ""))) + rV <- matrix(c(apply(V, 2, min), apply(V, 2, max)), nrow = 2, ncol = Rk, byrow = TRUE, + dimnames = list(c("min", "max"), paste("rank", 1:Rk, sep = ""))) # Stop Cluster stopCluster(cl) - return(new("fittedmodel", + return(new("fitmodel", + call = list(model = model, nRepl = n, nRank = Rk, nRand = nRand, + count = count), Tstats = list(dTmean = dTM, dTvar = dTV, TMobs = TM0, TVobs = TV0, pvalue = matrix(c(pvalueM, pvalueV), nrow = 2, ncol = 1, dimnames = list(c("mean", "variance"), "p-value"))), sim.stats = matrix(c(apply(M, 2, mean), apply(V, 2, mean)), nrow = 2, - ncol = S, byrow = TRUE, + ncol = Rk, byrow = TRUE, dimnames = list(c("mean", "variance"), - paste("rank", 1:S, sep = ""))), + paste("rank", 1:Rk, sep = ""))), sim.range = list(mean = rM, variance = rV), - obs.stats = matrix(c(M0, V0), nrow = 2, ncol = S, byrow = TRUE, + obs.stats = matrix(c(M0, V0), nrow = 2, ncol = Rk, byrow = TRUE, dimnames = list(c("mean", "variance"), - paste("rank", 1:S, sep = ""))))) + paste("rank", 1:Rk, sep = ""))))) } From 7350746daebf9ca02194f722310b47681ade00b0 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 7 Dec 2015 12:47:27 -0200 Subject: [PATCH 13/40] Add method hist Plot histogram of simulated T values --- NAMESPACE | 2 +- R/nicheApport-methods.R | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/NAMESPACE b/NAMESPACE index 65de939..9189378 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -8,4 +8,4 @@ export(fitmodel, fitmodelCl, findPFw) exportClasses(fitmodel) # Export methods -exportMethods(plot, lines, qqplot, show) \ No newline at end of file +exportMethods(plot, lines, qqplot, hist, show) \ No newline at end of file diff --git a/R/nicheApport-methods.R b/R/nicheApport-methods.R index 48d79bb..80201db 100644 --- a/R/nicheApport-methods.R +++ b/R/nicheApport-methods.R @@ -105,6 +105,32 @@ setMethod(f = "qqplot", signature = "fitmodel", points(sim.stats[rank.fit == 1], obs.stats[rank.fit == 1]) }) +setMethod(f = "hist", signature = "fitmodel", + definition = function(x, stat = "mean", arrow.col = "blue", ...){ + dots <- list(...) + if(!stat %in% c("mean", "variance")) + stop("'stat' parameter must be 'mean' or 'variance'") + + if(!"xlab" %in% names(dots)) dots$xlab <- "T values" + if(!"main" %in% names(dots)) dots$main <- "" + + if(stat == "mean"){ + sta <- x@Tstats$dTmean + obs <- x@Tstats$TMobs + } + else { + sta <- x@Tstats$dTvar + obs <- x@Tstats$TVobs + } + + hs <- do.call(hist, c(list(x = sta, xlim = c(0, max(sta, obs * 1.3))), dots)) + arrows(x0 = obs, x1 = obs, y0 = max(hs$counts) * 0.75, lwd = 2, + y1 = min(hs$counts) * 1.1, length = 0.1, lty = 1.3, col = arrow.col) + legend("topright", cex = 0.9, bty = "n", + legend = paste("TMobs =", round(obs, 2), "\npvalue =", + round(x@Tstats$pvalue[stat, ], 2))) +}) + setMethod(f = "show", signature = "fitmodel", definition = function(object){ cat("Niche Apportionment fitting\n") From 591134550429a42d8534d49875e8f78d79538df3 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 7 Dec 2015 12:48:47 -0200 Subject: [PATCH 14/40] Add method hist, update args description --- man/fitmodel-class.Rd | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/man/fitmodel-class.Rd b/man/fitmodel-class.Rd index 5445583..8a356be 100644 --- a/man/fitmodel-class.Rd +++ b/man/fitmodel-class.Rd @@ -56,13 +56,20 @@ \section{Methods}{ \describe{ - \item{lines}{\code{signature(x = "fitmodel")}: Plot line of fitted model.} - \item{plot}{\code{signature(x = "fitmodel")}: Plot ranked abundance.} - \item{qqplot}{\code{signature(x = "fitmodel")}: Quantile-Quantile plot.} + \item{hist}{\code{signature(x = "fitmodel")}: Plot histogram of simulated \emph{T} values. Arguments are: \code{stat} and \code{arrow.col}.} + \item{lines}{\code{signature(x = "fitmodel")}: Plot line of fitted model. Arguments are: \code{stat}, \code{base} and \code{range}.} + \item{plot}{\code{signature(x = "fitmodel")}: Plot ranked abundance. Arguments are: \code{stat} and \code{base}.} + \item{qqplot}{\code{signature(x = "fitmodel")}: Quantile-Quantile plot. Arguments are: \code{stat}, \code{base} and \code{range}.} \item{show}{\code{signature(object = "fitmodel")}: Display object.} - - The methods \code{lines}, \code{plot} and \code{qqplot} accept parameters \code{stat} and \code{base}. Further the methods \code{lines} and \code{qqplot} accept parameter \code{range}. The parameter \code{stat} inform if line must be plotted using mean (\code{"mean"}) or variance (\code{"variance"}) of model simulation. The \code{base} parameter inform the base of logarithm. If this value is different of \code{NULL}, then data are transformed to logarithm. The \code{range} parameter inform if minimum and maximum line must be plotted. - } + } + + \subsection{Arguments}{ + \describe{ + \item{stat}{Inform if line must be plotted using mean (\code{"mean"}) or variance (\code{"variance"}) of model simulation.} + \item{base}{Inform the base of logarithm. If this value is different of \code{NULL}, then data are transformed to logarithm.} + \item{range}{Inform if minimum and maximum line must be plotted.} + \item{arrow.col}{Arrow color at histogram plot.} + }} } \author{ @@ -81,8 +88,11 @@ plot(m1, base = 2) lines(m1, base = 2, range = TRUE) - # For qqplot + # QQplot qqplot(m1, base = 2, range = TRUE) + + # Histogram + hist(m1) } \keyword{classes} From 5488495b1430aa6e414297be9d7a6deed244e7fc Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 7 Dec 2015 13:46:34 -0200 Subject: [PATCH 15/40] Round output of T and pvalue --- R/nicheApport-methods.R | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/R/nicheApport-methods.R b/R/nicheApport-methods.R index 80201db..4e834c1 100644 --- a/R/nicheApport-methods.R +++ b/R/nicheApport-methods.R @@ -142,14 +142,13 @@ setMethod(f = "show", signature = "fitmodel", cat("Fitting for mean\n") print(base::summary(object@Tstats$dTmean)) - - cat("Observed T:", object@Tstats$TMobs, "\n") + cat("Observed T:", round(object@Tstats$TMobs, 2), "\n") cat("P-value for Tobs greater than simulated:", - object@Tstats$pvalue[1, ], "\n\n") + round(object@Tstats$pvalue[1, ], 4), "\n\n") cat("Fitting for variance\n") print(base::summary(object@Tstats$dTvar)) - cat("Observed T:", object@Tstats$TVobs, "\n") + cat("Observed T:", round(object@Tstats$TVobs, 2), "\n") cat("P-value for Tobs greater than simulated:", - object@Tstats$pvalue[2, ], "\n") + round(object@Tstats$pvalue[2, ], 4), "\n") }) From 8ace52898105b42c897a8987695b323dedd16122 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 7 Dec 2015 14:46:32 -0200 Subject: [PATCH 16/40] Update version and news --- DESCRIPTION | 4 ++-- NEWS | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 76cabf6..cc6da4a 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -8,6 +8,6 @@ License: GPL-2 Encoding: UTF-8 Depends: parallel NeedsCompilation: no -Version: 1.0.2 -Date: 2015-12-04 +Version: 1.1.0 +Date: 2015-12-07 URL: http://mariojose.github.io/nicheApport/, https://github.com/mariojose/nicheApport diff --git a/NEWS b/NEWS index b60c124..69be926 100644 --- a/NEWS +++ b/NEWS @@ -1,3 +1,9 @@ +1.1.0 (2015-12-07) +* Update documentation +* Improve fitmode and fitmodelCl functions +* Add methods to plot rank abundance, simulated model line, qqplot of observed and simulated data and histogram of distribution of T value +* Now fitmodel and fitmodelCl return object of class 'fitmodel' + 1.0.2 (2015-12-04) * fitmodel and fitmodelCl now return simulation range * Update interpretation of p-value in help files From 0581f81c21b5ff594c52e92420902afa61de0ca9 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 7 Dec 2015 15:51:28 -0200 Subject: [PATCH 17/40] Update 'imports' and 'depends' information --- DESCRIPTION | 3 ++- NAMESPACE | 11 ++++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index cc6da4a..e926ead 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -6,7 +6,8 @@ Maintainer: Mario J. Marques-Azevedo Description: Simulate and fit, using Monte Carlo approach, rank abundance distribution to niche apportionment species abundance distributions models. License: GPL-2 Encoding: UTF-8 -Depends: parallel +Depends: parallel, methods +Imports: graphics NeedsCompilation: no Version: 1.1.0 Date: 2015-12-07 diff --git a/NAMESPACE b/NAMESPACE index 9189378..be5f9cf 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -8,4 +8,13 @@ export(fitmodel, fitmodelCl, findPFw) exportClasses(fitmodel) # Export methods -exportMethods(plot, lines, qqplot, hist, show) \ No newline at end of file +exportMethods(plot, lines, qqplot, hist, show) + +# Import function from packages +importFrom("graphics", plot, lines, hist) + +# Import packages +import( + parallel, + methods +) \ No newline at end of file From ca4040275f101aba07dcb8e29a25480986ba84be Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 7 Dec 2015 15:51:59 -0200 Subject: [PATCH 18/40] Add method hist in documentation alias --- man/fitmodel-class.Rd | 1 + 1 file changed, 1 insertion(+) diff --git a/man/fitmodel-class.Rd b/man/fitmodel-class.Rd index 8a356be..0564751 100644 --- a/man/fitmodel-class.Rd +++ b/man/fitmodel-class.Rd @@ -3,6 +3,7 @@ \docType{class} \alias{fitmodel-class} +\alias{hist,fitmodel-method} \alias{lines,fitmodel-method} \alias{plot,fitmodel-method} \alias{qqplot,fitmodel-method} From db2baeb144692974444977e70833608930068e5d Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 7 Dec 2015 15:52:43 -0200 Subject: [PATCH 19/40] Check intern functions names --- R/fitmodelCl.R | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/R/fitmodelCl.R b/R/fitmodelCl.R index dc6b8c3..64003ad 100644 --- a/R/fitmodelCl.R +++ b/R/fitmodelCl.R @@ -49,7 +49,7 @@ fitmodelCl <- function(x, model, count, nRand = 999, nCores = 2, ...){ S <- apply(x > 0, 1, sum) # Function to run in each cores - fn <- function(rand, n, N, S, Rk, model, count, ...){ + fn1 <- function(rand, n, N, S, Rk, model, count, ...){ dots <- list(...) clM <- matrix(nrow = rand, ncol = Rk) clV <- matrix(nrow = rand, ncol = Rk) @@ -67,22 +67,22 @@ fitmodelCl <- function(x, model, count, nRand = 999, nCores = 2, ...){ } # Send function to cluster - tmp <- do.call(clusterApplyLB, c(list(cl = cl, x = randc, fun = fn, n = n, N = N, S = S, Rk = Rk, model = getFunction(model), count = count), dots)) + tmp1 <- do.call(clusterApplyLB, c(list(cl = cl, x = randc, fun = fn1, n = n, N = N, S = S, Rk = Rk, model = getFunction(model), count = count), dots)) # 'nRand' means and variances of 'n' simulations to the model. M <- matrix(ncol = Rk) V <- matrix(ncol = Rk) # Create data frame with result of cluster - M <- tmp[[1]]$M - V <- tmp[[1]]$V - for(i in 2:length(tmp)){ - M <- rbind(M, tmp[[i]]$M) - V <- rbind(V, tmp[[i]]$V) + M <- tmp1[[1]]$M + V <- tmp1[[1]]$V + for(i in 2:length(tmp1)){ + M <- rbind(M, tmp1[[i]]$M) + V <- rbind(V, tmp1[[i]]$V) } - # Recycling objects names - rm(fn, tmp) + # Clear objects names + rm(fn1, tmp1) # Transform each replicate to relative abundance. for(i in 1:n){ @@ -109,7 +109,7 @@ fitmodelCl <- function(x, model, count, nRand = 999, nCores = 2, ...){ TV0 <- -2 * sum(log(pV0)) # Function to run in cluster - fn <- function(core, rand, nRand, M, V, Rk){ + fn2 <- function(core, rand, nRand, M, V, Rk){ cldTM <- c() cldTV <- c() @@ -136,18 +136,21 @@ fitmodelCl <- function(x, model, count, nRand = 999, nCores = 2, ...){ } # Send function to cluster - tmp <- clusterApplyLB(cl, seq(nc), fn, rand = randc, nRand = nRand, M = M, V = V, Rk = Rk) + tmp2 <- clusterApplyLB(cl, seq(nc), fn2, rand = randc, nRand = nRand, M = M, V = V, Rk = Rk) # Distribution of T values. dTM <- c() dTV <- c() # Create a vector with results of cluster - for(i in 1:length(tmp)){ - dTM <- c(dTM, tmp[[i]]$dTM) - dTV <- c(dTV, tmp[[i]]$dTV) + for(i in 1:length(tmp2)){ + dTM <- c(dTM, tmp2[[i]]$dTM) + dTV <- c(dTV, tmp2[[i]]$dTV) } + # Clear objects names + rm(fn2, tmp2) + # Probability that T observed is drawn from T values generated by the model. pvalueM <- sum(dTM > TM0) / (nRand + 1) pvalueV <- sum(dTV > TV0) / (nRand + 1) From b784eb2268167e95d6755224ded25393e84755b4 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 7 Dec 2015 16:14:47 -0200 Subject: [PATCH 20/40] Remove file with gpl-2 license Lincense informed at DESCRIPTION file --- LICENSE | 340 -------------------------------------------------------- 1 file changed, 340 deletions(-) delete mode 100644 LICENSE diff --git a/LICENSE b/LICENSE deleted file mode 100644 index d6a9326..0000000 --- a/LICENSE +++ /dev/null @@ -1,340 +0,0 @@ -GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - {description} - Copyright (C) {year} {fullname} - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - {signature of Ty Coon}, 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. - From 8bf8bb0ad5bfbffaef113e28474e69b64e81d2de Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Thu, 10 Dec 2015 22:40:46 -0200 Subject: [PATCH 21/40] Start vignettes --- vignettes/nicheApport.bib | 101 ++ vignettes/oikos.bst | 1574 +++++++++++++++++++++ vignettes/quick-reference-nicheApport.Rnw | 134 ++ 3 files changed, 1809 insertions(+) create mode 100644 vignettes/nicheApport.bib create mode 100644 vignettes/oikos.bst create mode 100644 vignettes/quick-reference-nicheApport.Rnw diff --git a/vignettes/nicheApport.bib b/vignettes/nicheApport.bib new file mode 100644 index 0000000..cc360ae --- /dev/null +++ b/vignettes/nicheApport.bib @@ -0,0 +1,101 @@ + +@article{bersier_species_1997, + title = {Species abundance patterns: the problem of testing stochastic models}, + volume = {66}, + issn = {0021-8790}, + shorttitle = {Species abundance patterns}, + url = {http://www.jstor.org/stable/5927}, + doi = {10.2307/5927}, + number = {5}, + urldate = {2011-11-22}, + journal = {Journal of Animal Ecology}, + author = {Bersier, Louis-Felix and Sugihara, George}, + year = {1997}, + pages = {769--774} +} + +@article{cassey_problem_2001, + title = {The problem of testing the goodness-of-fit of stochastic resource apportionment models}, + volume = {12}, + issn = {1099-095X}, + url = {http://onlinelibrary.wiley.com/doi/10.1002/env.493/abstract}, + doi = {10.1002/env.493}, + language = {en}, + number = {7}, + urldate = {2011-11-22}, + journal = {Environmetrics}, + author = {Cassey, Phillip and King, Robert A. R}, + year = {2001}, + pages = {691--698} +} + +@article{matthews_fitting_2014, + title = {Fitting and comparing competing models of the species abundance distribution: assessment and prospect}, + volume = {6}, + shorttitle = {Fitting and comparing competing models of the species abundance distribution}, + url = {http://escholarship.org/uc/item/3gz504j3}, + number = {2}, + urldate = {2014-07-10}, + journal = {Frontiers of Biogeography}, + author = {Matthews, Thomas J. and Whittaker, Robert J.}, + year = {2014}, + keywords = {Bayesian statistics, information theory, maximum entropy, species abundance distribution}, + pages = {67--82} +} + +@article{mcgill_species_2007, + title = {Species abundance distributions: moving beyond single prediction theories to integration within an ecological framework}, + volume = {10}, + issn = {1461-0248}, + url = {http://dx.doi.org/10.1111/j.1461-0248.2007.01094.x}, + doi = {10.1111/j.1461-0248.2007.01094.x}, + number = {10}, + journal = {Ecology Letters}, + author = {McGill, Brian J. and Etienne, Rampal S. and Gray, John S. and Alonso, David and Anderson, Marti J. and Benecha, Habtamu Kassa and Dornelas, Maria and Enquist, Brian J. and Green, Jessica L. and He, Fangliang and Hurlbert, Allen H. and Magurran, Anne E. and Marquet, Pablo A. and Maurer, Brian A. and Ostling, Annette and Soykan, Candan U. and Ugland, Karl Inne and White, Ethan P.}, + year = {2007}, + keywords = {review, species abundance distribution}, + pages = {995--1015} +} + +@article{mouillot_how_2003, + title = {How parasites divide resources: a test of the niche apportionment hypothesis}, + volume = {72}, + issn = {1365-2656}, + shorttitle = {How parasites divide resources}, + url = {http://onlinelibrary.wiley.com/doi/10.1046/j.1365-2656.2003.00749.x/abstract}, + doi = {10.1046/j.1365-2656.2003.00749.x}, + language = {en}, + number = {5}, + urldate = {2011-11-22}, + journal = {Journal of Animal Ecology}, + author = {Mouillot, David and George-Nascimento, Mario and Poulin, Robert}, + year = {2003}, + pages = {757--764} +} + +@article{tokeshi_niche_1990, + title = {Niche apportionment or random assortment: species abundance patterns revisited}, + volume = {59}, + issn = {00218790}, + shorttitle = {Niche apportionment or random assortment}, + url = {http://www.jstor.org/stable/5036}, + number = {3}, + journal = {Journal of Animal Ecology}, + author = {Tokeshi, Mutsunori}, + year = {1990}, + pages = {1129--1146} +} + +@article{tokeshi_power_1996, + title = {Power fraction: a new explanation of relative abundance patterns in species-rich assemblages}, + volume = {75}, + issn = {0030-1299}, + shorttitle = {Power {Fraction}}, + url = {http://www.jstor.org/stable/3545898}, + doi = {10.2307/3545898}, + number = {3}, + journal = {Oikos}, + author = {Tokeshi, Mutsunori}, + year = {1996}, + pages = {543--550} +} \ No newline at end of file diff --git a/vignettes/oikos.bst b/vignettes/oikos.bst new file mode 100644 index 0000000..cf793c7 --- /dev/null +++ b/vignettes/oikos.bst @@ -0,0 +1,1574 @@ +%% +%% This is file `oikos.bst', +%% generated with the docstrip utility. +%% +%% The original source files were: +%% +%% merlin.mbs (with options: `,ay,nat,vonx,nm-rev,ed-rev,keyxyr,dt-beg,yr-blk,yrp-per,note-yr,atit-u,jttl-rm,volp-sp,jnm-x,btit-rm,bt-rm,pre-pub,edpar,in-col,pp,ed,abr,ednx,ord,and-xcom') +%% ---------------------------------------- +%% *** Oikos *** +%% +%% Hand edited by J.Oksanen 2001: added emdash after title. +%% FIXME: Oikos does not give Publisher address. +%% +%% Hand edited by Sander Oom 2002: added replacement of repeated authors with dash +%% +%% Copyright 1994-1999 Patrick W Daly + % =============================================================== + % IMPORTANT NOTICE: + % This bibliographic style (bst) file has been generated from one or + % more master bibliographic style (mbs) files, listed above. + % + % This generated file can be redistributed and/or modified under the terms + % of the LaTeX Project Public License Distributed from CTAN + % archives in directory macros/latex/base/lppl.txt; either + % version 1 of the License, or any later version. + % =============================================================== + % Name and version information of the main mbs file: + % \ProvidesFile{merlin.mbs}[1999/05/28 3.89 (PWD)] + % For use with BibTeX version 0.99a or later + %------------------------------------------------------------------- + % This bibliography style file is intended for texts in ENGLISH + % This is an author-year citation style bibliography. As such, it is + % non-standard LaTeX, and requires a special package file to function properly. + % Such a package is natbib.sty by Patrick W. Daly + % The form of the \bibitem entries is + % \bibitem[Jones et al.(1990)]{key}... + % \bibitem[Jones et al.(1990)Jones, Baker, and Smith]{key}... + % The essential feature is that the label (the part in brackets) consists + % of the author names, as they should appear in the citation, with the year + % in parentheses following. There must be no space before the opening + % parenthesis! + % With natbib v5.3, a full list of authors may also follow the year. + % In natbib.sty, it is possible to define the type of enclosures that is + % really wanted (brackets or parentheses), but in either case, there must + % be parentheses in the label. + % The \cite command functions as follows: + % \citet{key} ==>> Jones et al. (1990) + % \citet*{key} ==>> Jones, Baker, and Smith (1990) + % \citep{key} ==>> (Jones et al., 1990) + % \citep*{key} ==>> (Jones, Baker, and Smith, 1990) + % \citep[chap. 2]{key} ==>> (Jones et al., 1990, chap. 2) + % \citep[e.g.][]{key} ==>> (e.g. Jones et al., 1990) + % \citep[e.g.][p. 32]{key} ==>> (e.g. Jones et al., p. 32) + % \citeauthor{key} ==>> Jones et al. + % \citeauthor*{key} ==>> Jones, Baker, and Smith + % \citeyear{key} ==>> 1990 + %--------------------------------------------------------------------- + +ENTRY + { address + author + booktitle + chapter + edition + editor + howpublished + institution + journal + key + month + note + number + organization + pages + publisher + school + series + title + type + volume + year + } + {} + { label extra.label sort.label short.list } + +INTEGERS { output.state before.all mid.sentence after.sentence after.block } + +FUNCTION {init.state.consts} +{ #0 'before.all := + #1 'mid.sentence := + #2 'after.sentence := + #3 'after.block := +} + +STRINGS { s t } + +FUNCTION {output.nonnull} +{ 's := + output.state mid.sentence = + { ", " * write$ } + { output.state after.block = + { add.period$ write$ + newline$ + "\newblock " write$ + } + { output.state before.all = + 'write$ + { add.period$ " " * write$ } + if$ + } + if$ + mid.sentence 'output.state := + } + if$ + s +} + +FUNCTION {output} +{ duplicate$ empty$ + 'pop$ + 'output.nonnull + if$ +} + +FUNCTION {output.check} +{ 't := + duplicate$ empty$ + { pop$ "empty " t * " in " * cite$ * warning$ } + 'output.nonnull + if$ +} + +FUNCTION {fin.entry} +{ add.period$ + write$ + newline$ +} + +FUNCTION {new.block} +{ output.state before.all = + 'skip$ + { after.block 'output.state := } + if$ +} + +FUNCTION {new.sentence} +{ output.state after.block = + 'skip$ + { output.state before.all = + 'skip$ + { after.sentence 'output.state := } + if$ + } + if$ +} + +FUNCTION {add.blank} +{ " " * before.all 'output.state := +} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% JO added this, and inserted into all formats below % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +FUNCTION {add.emdash} +{ ".~-- " * before.all 'output.state := +} + +FUNCTION {date.block} +{ + new.block +} + +FUNCTION {not} +{ { #0 } + { #1 } + if$ +} + +FUNCTION {and} +{ 'skip$ + { pop$ #0 } + if$ +} + +FUNCTION {or} +{ { pop$ #1 } + 'skip$ + if$ +} + +FUNCTION {new.block.checkb} +{ empty$ + swap$ empty$ + and + 'skip$ + 'new.block + if$ +} + +FUNCTION {field.or.null} +{ duplicate$ empty$ + { pop$ "" } + 'skip$ + if$ +} + +FUNCTION {emphasize} +{ duplicate$ empty$ + { pop$ "" } + { "{\em " swap$ * "\/}" * } + if$ +} + + +FUNCTION {capitalize} +{ "u" change.case$ "t" change.case$ } + +FUNCTION {space.word} +{ " " swap$ * " " * } + + % Here are the language-specific definitions for explicit words. + % Each function has a name bbl.xxx where xxx is the English word. + % The language selected here is ENGLISH +FUNCTION {bbl.and} +{ "and"} + +FUNCTION {bbl.etal} +{ "et~al." } + +FUNCTION {bbl.editors} +{ "eds." } + +FUNCTION {bbl.editor} +{ "ed." } + +FUNCTION {bbl.edby} +{ "edited by" } + +FUNCTION {bbl.edition} +{ "ed." } + +FUNCTION {bbl.volume} +{ "vol." } + +FUNCTION {bbl.of} +{ "of" } + +FUNCTION {bbl.number} +{ "no." } + +FUNCTION {bbl.nr} +{ "no." } + +FUNCTION {bbl.in} +{ "in" } + +FUNCTION {bbl.pages} +{ "pp." } + +FUNCTION {bbl.page} +{ "p." } + +FUNCTION {bbl.chapter} +{ "chap." } + +FUNCTION {bbl.techrep} +{ "Tech. Rep." } + +FUNCTION {bbl.mthesis} +{ "Master's thesis" } + +FUNCTION {bbl.phdthesis} +{ "Ph.D. thesis" } + +FUNCTION {bbl.first} +{ "1st" } + +FUNCTION {bbl.second} +{ "2nd" } + +FUNCTION {bbl.third} +{ "3rd" } + +FUNCTION {bbl.fourth} +{ "4th" } + +FUNCTION {bbl.fifth} +{ "5th" } + +FUNCTION {bbl.st} +{ "st" } + +FUNCTION {bbl.nd} +{ "nd" } + +FUNCTION {bbl.rd} +{ "rd" } + +FUNCTION {bbl.th} +{ "th" } + +MACRO {jan} {"Jan."} + +MACRO {feb} {"Feb."} + +MACRO {mar} {"Mar."} + +MACRO {apr} {"Apr."} + +MACRO {may} {"May"} + +MACRO {jun} {"Jun."} + +MACRO {jul} {"Jul."} + +MACRO {aug} {"Aug."} + +MACRO {sep} {"Sep."} + +MACRO {oct} {"Oct."} + +MACRO {nov} {"Nov."} + +MACRO {dec} {"Dec."} + +FUNCTION {eng.ord} +{ duplicate$ "1" swap$ * + #-2 #1 substring$ "1" = + { bbl.th * } + { duplicate$ #-1 #1 substring$ + duplicate$ "1" = + { pop$ bbl.st * } + { duplicate$ "2" = + { pop$ bbl.nd * } + { "3" = + { bbl.rd * } + { bbl.th * } + if$ + } + if$ + } + if$ + } + if$ +} + +MACRO {acmcs} {"ACM Computing Surveys"} + +MACRO {acta} {"Acta Informatica"} + +MACRO {cacm} {"Communications of the ACM"} + +MACRO {ibmjrd} {"IBM Journal of Research and Development"} + +MACRO {ibmsj} {"IBM Systems Journal"} + +MACRO {ieeese} {"IEEE Transactions on Software Engineering"} + +MACRO {ieeetc} {"IEEE Transactions on Computers"} + +MACRO {ieeetcad} + {"IEEE Transactions on Computer-Aided Design of Integrated Circuits"} + +MACRO {ipl} {"Information Processing Letters"} + +MACRO {jacm} {"Journal of the ACM"} + +MACRO {jcss} {"Journal of Computer and System Sciences"} + +MACRO {scp} {"Science of Computer Programming"} + +MACRO {sicomp} {"SIAM Journal on Computing"} + +MACRO {tocs} {"ACM Transactions on Computer Systems"} + +MACRO {tods} {"ACM Transactions on Database Systems"} + +MACRO {tog} {"ACM Transactions on Graphics"} + +MACRO {toms} {"ACM Transactions on Mathematical Software"} + +MACRO {toois} {"ACM Transactions on Office Information Systems"} + +MACRO {toplas} {"ACM Transactions on Programming Languages and Systems"} + +MACRO {tcs} {"Theoretical Computer Science"} + + +INTEGERS { nameptr namesleft numnames } + +FUNCTION {format.names} +{ 's := + "" 't := + #1 'nameptr := + s num.names$ 'numnames := + numnames 'namesleft := + { namesleft #0 > } + { s nameptr + "{vv~}{ll}{, jj}{, f.}" format.name$ + 't := + nameptr #1 > + { + namesleft #1 > + { ", " * t * } + { + s nameptr "{ll}" format.name$ duplicate$ "others" = + { 't := } + { pop$ } + if$ + t "others" = + { + " " * bbl.etal * + } + { bbl.and + space.word * t * + } + if$ + } + if$ + } + 't + if$ + nameptr #1 + 'nameptr := + namesleft #1 - 'namesleft := + } + while$ +} + +FUNCTION {format.names.ed} +{ format.names } + +FUNCTION {format.key} +{ empty$ + { key field.or.null } + { "" } + if$ +} + +FUNCTION {format.authors} +{ author empty$ + { "" } + { author format.names } + if$ +} + +FUNCTION {format.editors} +{ editor empty$ + { "" } + { editor format.names + " (" * + editor num.names$ #1 > + 'bbl.editors + 'bbl.editor + if$ + * ")" * + } + if$ +} + +FUNCTION {format.in.editors} +{ editor empty$ + { "" } + { editor format.names.ed + editor num.names$ #1 > + { " (" * bbl.editors * ")" * } + { " (" * bbl.editor * ")" * } + if$ + } + if$ +} + +FUNCTION {format.note} +{ + note empty$ + { "" } + { note #1 #1 substring$ + duplicate$ "{" = + 'skip$ + { output.state mid.sentence = + { "l" } + { "u" } + if$ + change.case$ + } + if$ + note #2 global.max$ substring$ * + } + if$ +} + +FUNCTION {format.title} +{ title empty$ + { "" } + { title + } + if$ +} + +FUNCTION {format.full.names} +{'s := + "" 't := + #1 'nameptr := + s num.names$ 'numnames := + numnames 'namesleft := + { namesleft #0 > } + { s nameptr + "{vv~}{ll}" format.name$ + 't := + nameptr #1 > + { + namesleft #1 > + { ", " * t * } + { + s nameptr "{ll}" format.name$ duplicate$ "others" = + { 't := } + { pop$ } + if$ + t "others" = + { + " " * bbl.etal * + } + { + bbl.and + space.word * t * + } + if$ + } + if$ + } + 't + if$ + nameptr #1 + 'nameptr := + namesleft #1 - 'namesleft := + } + while$ +} + +FUNCTION {author.editor.key.full} +{ author empty$ + { editor empty$ + { key empty$ + { cite$ #1 #3 substring$ } + 'key + if$ + } + { editor format.full.names } + if$ + } + { author format.full.names } + if$ +} + +FUNCTION {author.key.full} +{ author empty$ + { key empty$ + { cite$ #1 #3 substring$ } + 'key + if$ + } + { author format.full.names } + if$ +} + +FUNCTION {editor.key.full} +{ editor empty$ + { key empty$ + { cite$ #1 #3 substring$ } + 'key + if$ + } + { editor format.full.names } + if$ +} + +FUNCTION {make.full.names} +{ type$ "book" = + type$ "inbook" = + or + 'author.editor.key.full + { type$ "proceedings" = + 'editor.key.full + 'author.key.full + if$ + } + if$ +} + +FUNCTION {output.bibitem} +{ newline$ + "\bibitem[{" write$ + label write$ + ")" make.full.names duplicate$ short.list = + { pop$ } + { * } + if$ + "}]{" * write$ + cite$ write$ + "}" write$ + newline$ + "" + before.all 'output.state := +} + +FUNCTION {n.dashify} +{ + 't := + "" + { t empty$ not } + { t #1 #1 substring$ "-" = + { t #1 #2 substring$ "--" = not + { "--" * + t #2 global.max$ substring$ 't := + } + { { t #1 #1 substring$ "-" = } + { "-" * + t #2 global.max$ substring$ 't := + } + while$ + } + if$ + } + { t #1 #1 substring$ * + t #2 global.max$ substring$ 't := + } + if$ + } + while$ +} + +FUNCTION {word.in} +{ bbl.in capitalize + ":" * + " " * } + +FUNCTION {format.date} +{ year duplicate$ empty$ + { "empty year in " cite$ * "; set to ????" * warning$ + pop$ "????" } + 'skip$ + if$ + extra.label * + before.all 'output.state := + " " swap$ * +} + +FUNCTION {format.btitle} +{ title +} + +FUNCTION {tie.or.space.connect} +{ duplicate$ text.length$ #3 < + { "~" } + { " " } + if$ + swap$ * * +} + +FUNCTION {either.or.check} +{ empty$ + 'pop$ + { "can't use both " swap$ * " fields in " * cite$ * warning$ } + if$ +} + +FUNCTION {format.bvolume} +{ volume empty$ + { "" } + { bbl.volume volume tie.or.space.connect + series empty$ + 'skip$ + { bbl.of space.word * series emphasize * } + if$ + "volume and number" number either.or.check + } + if$ +} + +FUNCTION {format.number.series} +{ volume empty$ + { number empty$ + { series field.or.null } + { output.state mid.sentence = + { bbl.number } + { bbl.number capitalize } + if$ + number tie.or.space.connect + series empty$ + { "there's a number but no series in " cite$ * warning$ } + { bbl.in space.word * series * } + if$ + } + if$ + } + { "" } + if$ +} + +FUNCTION {is.num} +{ chr.to.int$ + duplicate$ "0" chr.to.int$ < not + swap$ "9" chr.to.int$ > not and +} + +FUNCTION {extract.num} +{ duplicate$ 't := + "" 's := + { t empty$ not } + { t #1 #1 substring$ + t #2 global.max$ substring$ 't := + duplicate$ is.num + { s swap$ * 's := } + { pop$ "" 't := } + if$ + } + while$ + s empty$ + 'skip$ + { pop$ s } + if$ +} + +FUNCTION {convert.edition} +{ edition extract.num "l" change.case$ 's := + s "first" = s "1" = or + { bbl.first 't := } + { s "second" = s "2" = or + { bbl.second 't := } + { s "third" = s "3" = or + { bbl.third 't := } + { s "fourth" = s "4" = or + { bbl.fourth 't := } + { s "fifth" = s "5" = or + { bbl.fifth 't := } + { s #1 #1 substring$ is.num + { s eng.ord 't := } + { edition 't := } + if$ + } + if$ + } + if$ + } + if$ + } + if$ + } + if$ + t +} + +FUNCTION {format.edition} +{ edition empty$ + { "" } + { output.state mid.sentence = + { convert.edition "l" change.case$ " " * bbl.edition * } + { convert.edition "t" change.case$ " " * bbl.edition * } + if$ + } + if$ +} + +INTEGERS { multiresult } + +FUNCTION {multi.page.check} +{ 't := + #0 'multiresult := + { multiresult not + t empty$ not + and + } + { t #1 #1 substring$ + duplicate$ "-" = + swap$ duplicate$ "," = + swap$ "+" = + or or + { #1 'multiresult := } + { t #2 global.max$ substring$ 't := } + if$ + } + while$ + multiresult +} + +FUNCTION {format.pages} +{ pages empty$ + { "" } + { pages multi.page.check + { bbl.pages pages n.dashify tie.or.space.connect } + { bbl.page pages tie.or.space.connect } + if$ + } + if$ +} + +FUNCTION {format.journal.pages} +{ pages empty$ + 'skip$ + { duplicate$ empty$ + { pop$ format.pages } + { + ": " * + pages n.dashify * + } + if$ + } + if$ +} + +FUNCTION {format.vol.num.pages} +{ volume field.or.null + number empty$ + 'skip$ + { + "(" number * ")" * * + volume empty$ + { "there's a number but no volume in " cite$ * warning$ } + 'skip$ + if$ + } + if$ + format.journal.pages +} + +FUNCTION {format.chapter.pages} +{ chapter empty$ + 'format.pages + { type empty$ + { bbl.chapter } + { type "l" change.case$ } + if$ + chapter tie.or.space.connect + pages empty$ + 'skip$ + { ", " * format.pages * } + if$ + } + if$ +} + +FUNCTION {format.in.ed.booktitle} +{ booktitle empty$ + { "" } + { editor empty$ + { word.in booktitle * } + { word.in format.in.editors * ", " * + booktitle * } + if$ + } + if$ +} + +FUNCTION {format.thesis.type} +{ type empty$ + 'skip$ + { pop$ + type "t" change.case$ + } + if$ +} + +FUNCTION {format.tr.number} +{ type empty$ + { bbl.techrep } + 'type + if$ + number empty$ + { "t" change.case$ } + { number tie.or.space.connect } + if$ +} + +FUNCTION {format.article.crossref} +{ + word.in + " \cite{" * crossref * "}" * +} + +FUNCTION {format.book.crossref} +{ volume empty$ + { "empty volume in " cite$ * "'s crossref of " * crossref * warning$ + word.in + } + { bbl.volume capitalize + volume tie.or.space.connect + bbl.of space.word * + } + if$ + " \cite{" * crossref * "}" * +} + +FUNCTION {format.incoll.inproc.crossref} +{ + word.in + " \cite{" * crossref * "}" * +} +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% Oikos does not give `address' of the `publisher' +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +FUNCTION {format.org.or.pub} +{ skip$ +% 't := +% "" +% address empty$ t empty$ and +% 'skip$ +% { +% t empty$ +% { address empty$ +% 'skip$ +% { address * } +% if$ +% } +% { t * +% address empty$ +% 'skip$ +% { ", " * address * } +% if$ +% } +% if$ +% } +% if$ +} + +FUNCTION {format.publisher.address} +{ publisher empty$ + { "empty publisher in " cite$ * warning$ + "" + } + { publisher } + if$ + format.org.or.pub +} + +FUNCTION {format.organization.address} +{ organization empty$ + { "" } + { organization } + if$ + format.org.or.pub +} + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% SO added this, to replace repeated authors in %% +%% bibliography with a dash %% +%% name.or.dash implemented in all cases below %% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +STRINGS {oldname} + +FUNCTION {name.or.dash} +{ 's := + oldname empty$ + { s 'oldname := s } + { s oldname = + { "---" } + { s 'oldname := s } + if$ + } + if$ +} + +FUNCTION {article} +{ output.bibitem + format.authors "author" output.check + author format.key output + name.or.dash + format.date "year" output.check + date.block + format.title "title" output.check + new.block + add.emdash + crossref missing$ + { journal + "journal" output.check + add.blank + format.vol.num.pages output + } + { format.article.crossref output.nonnull + format.pages output + } + if$ + new.block + format.note output + fin.entry +} + +FUNCTION {book} +{ output.bibitem + author empty$ + { format.editors "author and editor" output.check + editor format.key output + add.blank + name.or.dash + } + { format.authors output.nonnull + crossref missing$ + { "author and editor" editor either.or.check } + 'skip$ + if$ + } + if$ + format.date "year" output.check + date.block + format.btitle "title" output.check + add.emdash + crossref missing$ + { format.bvolume output + new.block + format.number.series output + new.sentence + format.publisher.address output + } + { + new.block + format.book.crossref output.nonnull + } + if$ + format.edition output + new.block + format.note output + fin.entry +} + +FUNCTION {booklet} +{ output.bibitem + format.authors output + author format.key output + name.or.dash + format.date "year" output.check + date.block + format.title "title" output.check + new.block + add.emdash + howpublished output + address output + new.block + format.note output + fin.entry +} + +FUNCTION {inbook} +{ output.bibitem + author empty$ + { format.editors "author and editor" output.check + editor format.key output + name.or.dash + } + { format.authors output.nonnull + crossref missing$ + { "author and editor" editor either.or.check } + 'skip$ + if$ + } + if$ + format.date "year" output.check + date.block + format.btitle "title" output.check + add.emdash + crossref missing$ + { + format.publisher.address output + format.bvolume output + format.chapter.pages "chapter and pages" output.check + new.block + format.number.series output + new.sentence + } + { + format.chapter.pages "chapter and pages" output.check + new.block + format.book.crossref output.nonnull + } + if$ + format.edition output + new.block + format.note output + fin.entry +} + +FUNCTION {incollection} +{ output.bibitem + format.authors "author" output.check + author format.key output + name.or.dash + format.date "year" output.check + date.block + format.title "title" output.check + new.block + add.emdash + crossref missing$ + { format.in.ed.booktitle "booktitle" output.check + new.sentence %% Added JO + format.publisher.address output + format.bvolume output + format.number.series output + format.chapter.pages output + new.sentence + format.edition output + } + { format.incoll.inproc.crossref output.nonnull + format.chapter.pages output + } + if$ + new.block + format.note output + fin.entry +} + +FUNCTION {inproceedings} +{ output.bibitem + format.authors "author" output.check + author format.key output + name.or.dash + format.date "year" output.check + date.block + format.title "title" output.check + new.block + add.emdash + crossref missing$ + { format.in.ed.booktitle "booktitle" output.check + new.sentence + publisher empty$ + { format.organization.address output } + { organization output + format.publisher.address output + } + if$ + format.bvolume output + format.number.series output + format.pages output + } + { format.incoll.inproc.crossref output.nonnull + format.pages output + } + if$ + new.block + format.note output + fin.entry +} + +FUNCTION {conference} { inproceedings } +FUNCTION {manual} +{ output.bibitem + format.authors output + author format.key output + name.or.dash + format.date "year" output.check + date.block + format.btitle "title" output.check + add.emdash + organization address new.block.checkb + organization output + address output + format.edition output + new.block + format.note output + fin.entry +} + +FUNCTION {mastersthesis} +{ output.bibitem + format.authors "author" output.check + author format.key output + name.or.dash + format.date "year" output.check + date.block + format.btitle "title" output.check + new.block + add.emdash + bbl.mthesis format.thesis.type output.nonnull + school "school" output.check + address output + new.block + format.note output + fin.entry +} + +FUNCTION {misc} +{ output.bibitem + format.authors output + author format.key output + name.or.dash + format.date "year" output.check + date.block + format.title output + new.block + add.emdash + howpublished output + new.block + format.note output + fin.entry +} + +FUNCTION {phdthesis} +{ output.bibitem + format.authors "author" output.check + author format.key output + name.or.dash + format.date "year" output.check + date.block + format.btitle "title" output.check + new.block + bbl.phdthesis format.thesis.type output.nonnull + school "school" output.check + address output + new.block + format.note output + fin.entry +} + +FUNCTION {proceedings} +{ output.bibitem + format.editors output + editor format.key output + name.or.dash + format.date "year" output.check + date.block + format.btitle "title" output.check + add.emdash + format.bvolume output + format.number.series output + new.sentence + publisher empty$ + { format.organization.address output } + { organization output + format.publisher.address output + } + if$ + new.block + format.note output + fin.entry +} + +FUNCTION {techreport} +{ output.bibitem + format.authors "author" output.check + author format.key output + name.or.dash + format.date "year" output.check + date.block + format.title "title" output.check + new.block + add.emdash + format.tr.number output.nonnull + institution "institution" output.check + address output + new.block + format.note output + fin.entry +} + +FUNCTION {unpublished} +{ output.bibitem + format.authors "author" output.check + author format.key output + name.or.dash + format.date "year" output.check + date.block + format.title "title" output.check + new.block + add.emdash + format.note "note" output.check + fin.entry +} + +FUNCTION {default.type} { misc } + +READ + +FUNCTION {sortify} +{ purify$ + "l" change.case$ +} + +INTEGERS { len } + +FUNCTION {chop.word} +{ 's := + 'len := + s #1 len substring$ = + { s len #1 + global.max$ substring$ } + 's + if$ +} + +FUNCTION {format.lab.names} +{ 's := + "" 't := + s #1 "{vv~}{ll}" format.name$ + s num.names$ duplicate$ + #2 > + { pop$ + " " * bbl.etal * + } + { #2 < + 'skip$ + { s #2 "{ff }{vv }{ll}{ jj}" format.name$ "others" = + { + " " * bbl.etal * + } + { bbl.and space.word * s #2 "{vv~}{ll}" format.name$ + * } + if$ + } + if$ + } + if$ +} + +FUNCTION {author.key.label} +{ author empty$ + { key empty$ + { cite$ #1 #3 substring$ } + 'key + if$ + } + { author format.lab.names } + if$ +} + +FUNCTION {author.editor.key.label} +{ author empty$ + { editor empty$ + { key empty$ + { cite$ #1 #3 substring$ } + 'key + if$ + } + { editor format.lab.names } + if$ + } + { author format.lab.names } + if$ +} + +FUNCTION {editor.key.label} +{ editor empty$ + { key empty$ + { cite$ #1 #3 substring$ } + 'key + if$ + } + { editor format.lab.names } + if$ +} + +FUNCTION {calc.short.authors} +{ type$ "book" = + type$ "inbook" = + or + 'author.editor.key.label + { type$ "proceedings" = + 'editor.key.label + 'author.key.label + if$ + } + if$ + 'short.list := +} + +FUNCTION {calc.label} +{ calc.short.authors + short.list + "(" + * + year duplicate$ empty$ + short.list key field.or.null = or + { pop$ "????" } + 'skip$ + if$ + * + 'label := +} + +FUNCTION {sort.format.names} +{ 's := + #1 'nameptr := + "" + s num.names$ 'numnames := + numnames 'namesleft := + { namesleft #0 > } + { s nameptr + "{ll{ }}{ f{ }}{ jj{ }}" + format.name$ 't := + nameptr #1 > + { + " " * + namesleft #1 = t "others" = and + { "zzzzz" * } + { t sortify * } + if$ + } + { t sortify * } + if$ + nameptr #1 + 'nameptr := + namesleft #1 - 'namesleft := + } + while$ +} + +FUNCTION {sort.format.title} +{ 't := + "A " #2 + "An " #3 + "The " #4 t chop.word + chop.word + chop.word + sortify + #1 global.max$ substring$ +} + +FUNCTION {author.sort} +{ author empty$ + { key empty$ + { "to sort, need author or key in " cite$ * warning$ + "" + } + { key sortify } + if$ + } + { author sort.format.names } + if$ +} + +FUNCTION {author.editor.sort} +{ author empty$ + { editor empty$ + { key empty$ + { "to sort, need author, editor, or key in " cite$ * warning$ + "" + } + { key sortify } + if$ + } + { editor sort.format.names } + if$ + } + { author sort.format.names } + if$ +} + +FUNCTION {editor.sort} +{ editor empty$ + { key empty$ + { "to sort, need editor or key in " cite$ * warning$ + "" + } + { key sortify } + if$ + } + { editor sort.format.names } + if$ +} + +FUNCTION {presort} +{ calc.label + label sortify + " " + * + type$ "book" = + type$ "inbook" = + or + 'author.editor.sort + { type$ "proceedings" = + 'editor.sort + 'author.sort + if$ + } + if$ + #1 entry.max$ substring$ + 'sort.label := + sort.label + * + " " + * + title field.or.null + sort.format.title + * + #1 entry.max$ substring$ + 'sort.key$ := +} + +ITERATE {presort} + +SORT + +STRINGS { last.label next.extra } + +INTEGERS { last.extra.num number.label } + +FUNCTION {initialize.extra.label.stuff} +{ #0 int.to.chr$ 'last.label := + "" 'next.extra := + #0 'last.extra.num := + #0 'number.label := +} + +FUNCTION {forward.pass} +{ last.label label = + { last.extra.num #1 + 'last.extra.num := + last.extra.num int.to.chr$ 'extra.label := + } + { "a" chr.to.int$ 'last.extra.num := + "" 'extra.label := + label 'last.label := + } + if$ + number.label #1 + 'number.label := +} + +FUNCTION {reverse.pass} +{ next.extra "b" = + { "a" 'extra.label := } + 'skip$ + if$ + extra.label 'next.extra := + extra.label + duplicate$ empty$ + 'skip$ + { "{\natexlab{" swap$ * "}}" * } + if$ + 'extra.label := + label extra.label * 'label := +} + +EXECUTE {initialize.extra.label.stuff} + +ITERATE {forward.pass} + +REVERSE {reverse.pass} + +FUNCTION {bib.sort.order} +{ sort.label + " " + * + year field.or.null sortify + * + " " + * + title field.or.null + sort.format.title + * + #1 entry.max$ substring$ + 'sort.key$ := +} + +ITERATE {bib.sort.order} + +SORT + +FUNCTION {begin.bib} +{ preamble$ empty$ + 'skip$ + { preamble$ write$ newline$ } + if$ + "\begin{thebibliography}{" number.label int.to.str$ * "}" * + write$ newline$ + "\expandafter\ifx\csname natexlab\endcsname\relax\def\natexlab#1{#1}\fi" + write$ newline$ +} + +EXECUTE {begin.bib} + +EXECUTE {init.state.consts} + +ITERATE {call.type$} + +FUNCTION {end.bib} +{ newline$ + "\end{thebibliography}" write$ newline$ +} + +EXECUTE {end.bib} +%% End of customized bst file +%% +%% End of file `oikos.bst'. diff --git a/vignettes/quick-reference-nicheApport.Rnw b/vignettes/quick-reference-nicheApport.Rnw new file mode 100644 index 0000000..6a1ad13 --- /dev/null +++ b/vignettes/quick-reference-nicheApport.Rnw @@ -0,0 +1,134 @@ +\documentclass[a4paper]{article} + +\usepackage[a4paper, left = 4cm, right = 4cm, top = 2cm, bottom = 2cm, includefoot]{geometry} +\usepackage[utf8]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{graphicx} +\usepackage{natbib} +\usepackage{url} +\usepackage{setspace} % Line spacing + +\title{Quick reference for \code{nicheApport} package usage} +\author{Mario J. Marques-Azevedo} +\date{December 11, 2015} + +\newcommand{\code}[1]{\texttt{#1}} % Command code + +\setlength{\parskip}{11pt} % Space between paragraphs +\setlength{\parindent}{0pt} % Remove indentation +\onehalfspacing + +\begin{document} + +\maketitle + +\section{Introduction} + +Species abundance distribution (SAD) is a basic description of ecological communities data \citep{mcgill_species_2007}. One way to represent the distribution of species abundance is to plot the ranked abundances from larger to smaller on x-axis and the abundance on y-axis (known too as MacArthur plot). Niche apportionment models were proposed to be a biological model to describe SAD \citep{tokeshi_niche_1990,tokeshi_power_1996,matthews_fitting_2014}. This models are assume that total niche are sequentially divided between species \citep{tokeshi_niche_1990,matthews_fitting_2014}. There are proposed procedures to fit niche apportionment model to data \citep{tokeshi_niche_1990,bersier_species_1997,cassey_problem_2001,mouillot_how_2003}, but no one public tool to do this. This package simulate species rank abundance distributions (RAD) and use Monte Carlo approach, proposed by \cite{bersier_species_1997,cassey_problem_2001,mouillot_how_2003} to fit model to replicates data. + +\section{Instalation} + +To install package you can do using \code{devtools} package and a stable \code{master} branch + +<>= +library(devtools) +install_github(repo = "mariojose/nicheApport", ref = "master") +@ + +or a \code{dev} branch with the news updated (before increment stable branch) + +<>= +library(devtools) +install_github(repo = "mariojose/nicheApport", ref = "dev") +@ + +\section{Models} + +The \code{nicheApport} package simulate the six models proposes by \cite{tokeshi_niche_1990,tokeshi_power_1996}: Dominance Decay, Dominance Preemption, MacArthur Fraction, Random Fraction, Random Assortment and Power Fraction. + +First load package + +<>= +library(nicheApport) +@ + +then simulate the Random Fraction model with 10 species and total abundance of 150 individuals. + +<>= +set.seed(42) +randFraction(N = 150, S = 10, count = TRUE) +@ + +Note that this run the last rank has no individual. This can happen when using counts, mainly if you choose model with high dominance like Dominance Preemption model. + +The Power Fraction model differ from other model by the \code{w} parameter. It weight niche by its abundance when procedure select fraction to divide in two new. The follow simulation run with 10 species, 300 kg of biomass (abundance) and \code{w} equal to 0.2. + +<>= +powerFraction(N = 300, S = 10, w = 0.2) +@ + +\section{Fitting} + +Fitting model to data can be ran using \code{fitmodel} or \code{fitmodelCl} functions. The last one run the fitting procedure using parallel computation. An abstract data will be created to exemplifying the fitting. This data will be 30 species and 10 replicates. + +<>= +data <- matrix(nrow = 10, ncol = 30) +for(i in 1:dim(data)[1]){ + data[i, ] <- randFraction(N = 500, S = 30, count = FALSE) +} +@ + +Now, running the fitting function and show the result of fitting (for Random Fraction and MacArthur Fraction models). + +<>= +m1 <- fitmodel(x = data, model = "randFraction", + count = FALSE, nRand = 99) +m2 <- fitmodel(x = data, model = "MacArthurFraction", + count = FALSE, nRand = 99) + +m1 +m2 +@ + +\section{Plotting} + +The rank abundance can be plotted using function \code{plot}. It will plot the observed logarithm at base 2 of the mean of each rank for all replicates. To add the simulated line of the models use function \code{lines}. The \code{range} parameter will plot minimum and maximum of the simulated values. + +<>= +plot(m1, stat = "mean", base = 2) + +lines(m1, stat = "mean", base = 2, range = TRUE, col = "blue") +lines(m2, stat = "mean", base = 2, range = TRUE, col = "red") + +legend("topright", lty = 1, col = c("blue", "red"), bty = "n", + legend = c("Random Fraction", "MacArthur Fraction")) +@ + +To confirm which rank is within simulation use \code{qqplot}. It will plot the simulated abundance against observed abundances highlighting the rank out of simulated abundances (grey colour). + +<>= +par(mfrow = c(1,2)) +qqplot(m1, stat = "mean", base = 2, range = TRUE, + main = "Random Fraction") +qqplot(m2, stat = "mean", base = 2, range = TRUE, + main = "MacArthur Fraction") +@ + +The fitting procedure calculate the \code{T} statistics to confirm with model fit to data. To plot the simulates values of \code{T} use the function \code{hist}. + +<>= +par(mfrow = c(1,2)) +hist(m1, stat = "mean", arrow.col = "blue", + main = "Random Fraction") +hist(m2, stat = "variance", arrow.col = "blue", + main = "MacArthur Fraction") +@ + +\section*{Reporting bugs} + +The package project is hosted on GitHub (\url{https://github.com/mariojose/nicheApport/}) and bugs can be reported \url{github.com/mariojose/nicheApport/issues}. Your feedbak is very important. + +\bibliographystyle{oikos} +\bibliography{nicheApport.bib} + +\end{document} From 1c94c8878bae68a4c8c1347329dbe54b457337b1 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Thu, 10 Dec 2015 22:59:40 -0200 Subject: [PATCH 22/40] Update text and grammar --- vignettes/quick-reference-nicheApport.Rnw | 24 +++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/vignettes/quick-reference-nicheApport.Rnw b/vignettes/quick-reference-nicheApport.Rnw index 6a1ad13..4ba0a5c 100644 --- a/vignettes/quick-reference-nicheApport.Rnw +++ b/vignettes/quick-reference-nicheApport.Rnw @@ -24,18 +24,18 @@ \section{Introduction} -Species abundance distribution (SAD) is a basic description of ecological communities data \citep{mcgill_species_2007}. One way to represent the distribution of species abundance is to plot the ranked abundances from larger to smaller on x-axis and the abundance on y-axis (known too as MacArthur plot). Niche apportionment models were proposed to be a biological model to describe SAD \citep{tokeshi_niche_1990,tokeshi_power_1996,matthews_fitting_2014}. This models are assume that total niche are sequentially divided between species \citep{tokeshi_niche_1990,matthews_fitting_2014}. There are proposed procedures to fit niche apportionment model to data \citep{tokeshi_niche_1990,bersier_species_1997,cassey_problem_2001,mouillot_how_2003}, but no one public tool to do this. This package simulate species rank abundance distributions (RAD) and use Monte Carlo approach, proposed by \cite{bersier_species_1997,cassey_problem_2001,mouillot_how_2003} to fit model to replicates data. +Species abundance distribution (SAD) is one of the basic description of ecological communities data \citep{mcgill_species_2007}. One way to represent the distribution of species abundance is to plot the ranked abundances from highest to lowest on x-axis and the abundance on y-axis (known too as MacArthur plot). Niche apportionment models were proposed to be a biological model to describe SAD \citep{tokeshi_niche_1990,tokeshi_power_1996,matthews_fitting_2014}. This models assume that total niche are sequentially divided between species \citep{tokeshi_niche_1990,matthews_fitting_2014}. There are proposed procedures to fit niche apportionment model to data \citep{tokeshi_niche_1990,bersier_species_1997,cassey_problem_2001,mouillot_how_2003}, but no one public tool to do this. This package simulate species rank abundance distributions (RAD) and use Monte Carlo approach, proposed by \cite{bersier_species_1997,cassey_problem_2001,mouillot_how_2003} to fit model to replicates data. \section{Instalation} -To install package you can do using \code{devtools} package and a stable \code{master} branch +The package can be installed using \code{devtools} package on R. For a stable version use the \code{master} branch <>= library(devtools) install_github(repo = "mariojose/nicheApport", ref = "master") @ -or a \code{dev} branch with the news updated (before increment stable branch) +or for a development version a \code{dev} branch. <>= library(devtools) @@ -44,9 +44,9 @@ install_github(repo = "mariojose/nicheApport", ref = "dev") \section{Models} -The \code{nicheApport} package simulate the six models proposes by \cite{tokeshi_niche_1990,tokeshi_power_1996}: Dominance Decay, Dominance Preemption, MacArthur Fraction, Random Fraction, Random Assortment and Power Fraction. +The \code{nicheApport} package simulate the six models proposed by \cite{tokeshi_niche_1990,tokeshi_power_1996}: Dominance Decay, Dominance Preemption, MacArthur Fraction, Random Fraction, Random Assortment and Power Fraction. -First load package +Before start simulation, load the package, <>= library(nicheApport) @@ -59,9 +59,9 @@ set.seed(42) randFraction(N = 150, S = 10, count = TRUE) @ -Note that this run the last rank has no individual. This can happen when using counts, mainly if you choose model with high dominance like Dominance Preemption model. +Note that in this run the last rank has no individual. This can happen when using counts, mainly if you choose a model with high dominance like Dominance Preemption model. -The Power Fraction model differ from other model by the \code{w} parameter. It weight niche by its abundance when procedure select fraction to divide in two new. The follow simulation run with 10 species, 300 kg of biomass (abundance) and \code{w} equal to 0.2. +The Power Fraction model differ from other model by the \code{w} parameter. It weight niche portion by its abundance when procedure select fraction to divide in two new. The follow simulation run with 10 species, 300 kg of biomass (abundance) and \code{w} equal to 0.2. <>= powerFraction(N = 300, S = 10, w = 0.2) @@ -69,7 +69,7 @@ powerFraction(N = 300, S = 10, w = 0.2) \section{Fitting} -Fitting model to data can be ran using \code{fitmodel} or \code{fitmodelCl} functions. The last one run the fitting procedure using parallel computation. An abstract data will be created to exemplifying the fitting. This data will be 30 species and 10 replicates. +Models can be fitted to data using \code{fitmodel} or \code{fitmodelCl} functions. The last one run the fitting procedure using parallel computation. An abstract data will be created to exemplifying the fitting. This data will have 30 species, 10 replicates and total abundance at each replicates 500 kg of biomass. <>= data <- matrix(nrow = 10, ncol = 30) @@ -78,7 +78,7 @@ for(i in 1:dim(data)[1]){ } @ -Now, running the fitting function and show the result of fitting (for Random Fraction and MacArthur Fraction models). +Now, run the fitting function and show the result of fitting (for Random Fraction and MacArthur Fraction models). <>= m1 <- fitmodel(x = data, model = "randFraction", @@ -92,7 +92,7 @@ m2 \section{Plotting} -The rank abundance can be plotted using function \code{plot}. It will plot the observed logarithm at base 2 of the mean of each rank for all replicates. To add the simulated line of the models use function \code{lines}. The \code{range} parameter will plot minimum and maximum of the simulated values. +The rank abundance can be plotted using function \code{plot}. It will plot the observed logarithm at base 2, for instance, of the mean of each rank for all replicates. To add the simulated line of the models use function \code{lines}. The \code{range} parameter will plot minimum and maximum of the simulated values. <>= plot(m1, stat = "mean", base = 2) @@ -104,7 +104,7 @@ legend("topright", lty = 1, col = c("blue", "red"), bty = "n", legend = c("Random Fraction", "MacArthur Fraction")) @ -To confirm which rank is within simulation use \code{qqplot}. It will plot the simulated abundance against observed abundances highlighting the rank out of simulated abundances (grey colour). +You can confirm which rank is within simulation checking previous plot or use \code{qqplot}. It will plot the simulated abundance against observed abundances highlighting the observed values out of simulated abundances (grey colour). <>= par(mfrow = c(1,2)) @@ -114,7 +114,7 @@ qqplot(m2, stat = "mean", base = 2, range = TRUE, main = "MacArthur Fraction") @ -The fitting procedure calculate the \code{T} statistics to confirm with model fit to data. To plot the simulates values of \code{T} use the function \code{hist}. +The fitting procedure calculate the \code{T} statistics to confirm with model fit to data. To plot the simulated values of \code{T} use the function \code{hist}. <>= par(mfrow = c(1,2)) From de189c37324911ce7b8c7182589895181c1c1dd7 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Thu, 10 Dec 2015 23:11:46 -0200 Subject: [PATCH 23/40] Update NEWS add vignettes --- NEWS | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/NEWS b/NEWS index 69be926..e214cd9 100644 --- a/NEWS +++ b/NEWS @@ -1,4 +1,5 @@ -1.1.0 (2015-12-07) +1.1.0 (next release) +* Add vignette 'Quick Reference for nicheApport' * Update documentation * Improve fitmode and fitmodelCl functions * Add methods to plot rank abundance, simulated model line, qqplot of observed and simulated data and histogram of distribution of T value From 7d3f55f9722ae9f529fd837cec8282f4d6520d5f Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Fri, 11 Dec 2015 01:23:02 -0200 Subject: [PATCH 24/40] Bug fix fitmodel to discrete data When fitting using discrete data, the transformation to relative abundance return error (number of dimension). Once all matrix are zero when assigning values, the relative is calculates only to ranks > 0. --- R/fitmodel.R | 2 +- R/fitmodelCl.R | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/R/fitmodel.R b/R/fitmodel.R index 12af7b9..53d9a8c 100644 --- a/R/fitmodel.R +++ b/R/fitmodel.R @@ -35,7 +35,7 @@ fitmodel <- function(x, model, count, nRand = 999, ...){ for(j in 1:n){ sim[j,1:S[j]] <- do.call(model, c(list(N = N[j], S = S[j], count = count), dots)) # Transform to relative abundance - sim[j,1:S[j]] <- sim[j, ] / sum(sim[j, ]) + sim[j,1:S[j]] <- sim[j,1:S[j]] / sum(sim[j,1:S[j]]) } M[i, ] <- apply(sim, 2, mean) V[i, ] <- apply(sim, 2, var) diff --git a/R/fitmodelCl.R b/R/fitmodelCl.R index 64003ad..31ca551 100644 --- a/R/fitmodelCl.R +++ b/R/fitmodelCl.R @@ -58,7 +58,7 @@ fitmodelCl <- function(x, model, count, nRand = 999, nCores = 2, ...){ for(j in 1:n){ sim[j,1:S[j]] <- do.call(model, c(list(N = N[j], S = S[j], count = count), dots)) # Transform to relative abundance - sim[j,1:S[j]] <- sim[j, ] / sum(sim[j, ]) + sim[j,1:S[j]] <- sim[j,1:S[j]] / sum(sim[j,1:S[j]]) } clM[i, ] = apply(sim, 2, mean) clV[i, ] = apply(sim, 2, var) From 06bce4af7372d39d439bc2d30fb76dea9f2986e5 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Fri, 11 Dec 2015 17:26:39 -0200 Subject: [PATCH 25/40] Update doc and add new args to plots --- man/fitmodel-class.Rd | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/man/fitmodel-class.Rd b/man/fitmodel-class.Rd index 0564751..78ff73e 100644 --- a/man/fitmodel-class.Rd +++ b/man/fitmodel-class.Rd @@ -40,17 +40,17 @@ } } \item{\code{sim.stats}:}{ - Object of class \code{"matrix"} containing mean and variance of simulations to each rank. + Object of class \code{"matrix"} containing mean and variance of simulated relative abundance of each rank. } \item{\code{sim.range}:}{ Object of class \code{"list"} containing: \describe{ - \item{mean}{Matrix containing minimum and maximum simulation values for mean of each rank.} - \item{variance}{Matrix containing minimum and maximum simulation values for variance of each rank.} + \item{mean}{Matrix containing minimum and maximum simulatated relative abundance mean of each rank.} + \item{variance}{Matrix containing minimum and maximum simulated relative abundance variance of each rank.} } } \item{\code{obs.stats}:}{ - Object of class \code{"matrix"} containing mean and variance of replicates observed to each rank. + Object of class \code{"matrix"} containing mean and variance observed relative abundance of each rank of all replicates. } } } @@ -58,18 +58,23 @@ \section{Methods}{ \describe{ \item{hist}{\code{signature(x = "fitmodel")}: Plot histogram of simulated \emph{T} values. Arguments are: \code{stat} and \code{arrow.col}.} - \item{lines}{\code{signature(x = "fitmodel")}: Plot line of fitted model. Arguments are: \code{stat}, \code{base} and \code{range}.} + \item{lines}{\code{signature(x = "fitmodel")}: Plot line of fitted model. Arguments are: \code{stat}, \code{base}, \code{range}, \code{range.lty} and \code{range.col}.} \item{plot}{\code{signature(x = "fitmodel")}: Plot ranked abundance. Arguments are: \code{stat} and \code{base}.} - \item{qqplot}{\code{signature(x = "fitmodel")}: Quantile-Quantile plot. Arguments are: \code{stat}, \code{base} and \code{range}.} + \item{qqplot}{\code{signature(x = "fitmodel")}: Quantile-Quantile plot. Arguments are: \code{stat}, \code{base}, \code{range}, \code{qqline}, \code{range.lty}, \code{range.col}, \code{in.col} and \code{out.col}.} \item{show}{\code{signature(object = "fitmodel")}: Display object.} } \subsection{Arguments}{ \describe{ - \item{stat}{Inform if line must be plotted using mean (\code{"mean"}) or variance (\code{"variance"}) of model simulation.} - \item{base}{Inform the base of logarithm. If this value is different of \code{NULL}, then data are transformed to logarithm.} - \item{range}{Inform if minimum and maximum line must be plotted.} - \item{arrow.col}{Arrow color at histogram plot.} + \item{arrow.col}{Character informing the arrow color of observed \code{T} value at histogram plot.} + \item{base}{Numeric informing the base of logarithm. If this value is different of \code{NULL}, then data are transformed to logarithm.} + \item{in.col}{Character informing the color of observed fitted values (within of simulated range).} + \item{out.col}{Character informing the color of observed non fitted values (out of simulated range).} + \item{qqline}{Logical informing if qqline must be plotted.} + \item{range}{Logical informing if minimum and maximum line must be plotted.} + \item{range.col}{Character informing the color of range plot.} + \item{range.lty}{Numerical informing the line type of range plot.} + \item{stat}{Character informing if line must be plotted using mean (\code{"mean"}) or variance (\code{"variance"}) of model simulation.} }} } From 6590eca77a2737ba27ec462d1d936f9664d25fc1 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Fri, 11 Dec 2015 17:31:03 -0200 Subject: [PATCH 26/40] Fix plot discrete data and add args to plot * When data will transfom to log, only values != 0 is transformed. With this, lines at this values will not be plotted. * Add new arguments to control colors and line type in plots (plot, line, qqplot) --- R/nicheApport-methods.R | 76 ++++++++++++++++++++++------------------- 1 file changed, 40 insertions(+), 36 deletions(-) diff --git a/R/nicheApport-methods.R b/R/nicheApport-methods.R index 4e834c1..7d7cbf7 100644 --- a/R/nicheApport-methods.R +++ b/R/nicheApport-methods.R @@ -28,39 +28,38 @@ setMethod(f = "plot", signature = "fitmodel", do.call(plot, c(list(x = obs.stats, bty = "n"), dots)) axis(1, c(1, xTicks)) - if(!is.null(base)){ - axis(side = 2, at = yTicks, las = 2, - labels = parse(text=sprintf(paste(base, "^%d", sep = ""), yTicks))) - } - else axis(2, at = yTicks, las = 2) + axis(2, at = yTicks, las = 2) }) setMethod(f = "lines", signature = "fitmodel", - definition = function(x, stat = "mean", base = NULL, range = FALSE, ...){ + definition = function(x, stat = "mean", base = NULL, range = FALSE, range.lty = 2, range.col = "black", ...){ dots <- list(...) if(!stat %in% c("mean", "variance")) stop("'stat' parameter must be 'mean' or 'variance'") - if("lty" %in% dots) dots <- dots[names(dots) != "lty"] if(!"col" %in% names(dots)) dots$col <- "blue" + + sim.sta <- x@sim.stats[stat, ] + sim.min <- x@sim.range[[stat]]["min", ] + sim.max <- x@sim.range[[stat]]["max", ] + if(!is.null(base)){ - sim.stats <- log(x@sim.stats[stat, ], base) - sim.range <- log(x@sim.range[[stat]], base) - } - else{ - sim.stats <- x@sim.stats[stat, ] - sim.range <- x@sim.range[[stat]] + sim.sta <- log(sim.sta[sim.sta > 0], base) + sim.min <- log(sim.min[sim.min > 0], base) + sim.max <- log(sim.max[sim.max > 0], base) } - do.call(lines, c(list(x = sim.stats), dots)) + do.call(lines, c(list(x = sim.sta), dots)) if(range){ - do.call(lines, c(list(x = sim.range["min", ], lty = 2), dots)) - do.call(lines, c(list(x = sim.range["max", ], lty = 2), dots)) + lines(x = sim.min, lty = range.lty, col = range.col) + lines(x = sim.max, lty = range.lty, col = range.col) } }) setMethod(f = "qqplot", signature = "fitmodel", - definition = function(x, stat = "mean", base = NULL, range = FALSE, ...){ + definition = function(x, stat = "mean", base = NULL, range = FALSE, + qqline = TRUE, range.lty = 2, range.col = "black", + in.col = "black", out.col = "grey70", ...){ dots <- list(...) if(!stat %in% c("mean", "variance")) stop("'stat' parameter must be 'mean' or 'variance'") @@ -75,34 +74,39 @@ setMethod(f = "qqplot", signature = "fitmodel", else dots$ylab <- substitute(expression(log[b]("Observed abundance")), list(b = base)) } - - if("lty" %in% dots) dots <- dots[names(dots) != "lty"] + if(!"lty" %in% names(dots)) dots$lty <- 1 + if(!"col" %in% names(dots)) dots$col <- "black" + obs.sta <- x@obs.stats[stat, ] + sim.sta <- x@sim.stats[stat, ] + sim.min <- x@sim.range[[stat]]["min", ] + sim.max <- x@sim.range[[stat]]["max", ] + if(!is.null(base)){ - sim.stats <- log(x@sim.stats[stat, ], base) - sim.range <- log(x@sim.range[[stat]], base) - obs.stats <- log(x@obs.stats[stat, ], base) - } - else{ - sim.stats <- x@sim.stats[stat, ] - sim.range <- x@sim.range[[stat]] - obs.stats <- x@obs.stats[stat, ] + obs.sta <- log(obs.sta, base) + sim.sta <- log(sim.sta[sim.sta > 0], base) + min.fil <- sim.min > 0 + max.fil <- sim.max > 0 + sim.min[min.fil] <- log(sim.min[min.fil], base) + sim.max[max.fil] <- log(sim.max[max.fil], base) } - dots$ylim <- c(min(c(sim.range["min", ], obs.stats)), - max(c(sim.range["max", ], obs.stats))) + if(range) + dots$ylim <- c(min(c(sim.min, obs.sta)), max(c(sim.max, obs.sta))) + + do.call(plot, c(list(x = sim.sta, y = sim.sta, type = "n"), dots)) - do.call(plot, c(list(x = sim.stats, y = sim.stats, type = "l"), dots)) + if(qqline) lines(x = sim.sta, y = sim.sta, lty = dots$lty, col = dots$col) if(range){ - lines(sim.stats, sim.range["min", ], lty = 2) - lines(sim.stats, sim.range["max", ], lty = 2) + lines(sim.sta[min.fil], sim.min[min.fil], lty = range.lty, col = range.col) + lines(sim.sta[max.fil], sim.max[max.fil], lty = range.lty, col = range.col) } - rank.fit <- rep(0, length(obs.stats)) - rank.fit[obs.stats >= sim.range["min", ] & obs.stats <= sim.range["max", ]] <- 1 - points(sim.stats[rank.fit == 0], obs.stats[rank.fit == 0], col = "#cccccc") - points(sim.stats[rank.fit == 1], obs.stats[rank.fit == 1]) + rank.fit <- vector("numeric", length(obs.sta)) + rank.fit[obs.sta >= sim.min & obs.sta <= sim.max] <- 1 + points(sim.sta[rank.fit == 0], obs.sta[rank.fit == 0], col = out.col) + points(sim.sta[rank.fit == 1], obs.sta[rank.fit == 1], col = in.col) }) setMethod(f = "hist", signature = "fitmodel", From 824e99c548b2ff5408361bd96b644602c358fcbd Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Fri, 11 Dec 2015 17:41:47 -0200 Subject: [PATCH 27/40] Update news --- NEWS | 2 ++ 1 file changed, 2 insertions(+) diff --git a/NEWS b/NEWS index e214cd9..6a3ed09 100644 --- a/NEWS +++ b/NEWS @@ -1,4 +1,6 @@ 1.1.0 (next release) +* Add news arguments to control plots color and line type +* Bux fix to plot and fit discrete data * Add vignette 'Quick Reference for nicheApport' * Update documentation * Improve fitmode and fitmodelCl functions From 2fa579b35b30c52bfb7b6d790bac9df1355bd47c Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Sun, 13 Dec 2015 14:09:56 -0200 Subject: [PATCH 28/40] Minimous change on code comments --- R/randAssort.R | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/R/randAssort.R b/R/randAssort.R index 7d89681..aa54081 100644 --- a/R/randAssort.R +++ b/R/randAssort.R @@ -1,16 +1,17 @@ # Random Assortment -randAssort <- function (N, S, count= FALSE){ +randAssort <- function (N, S, count = FALSE){ k <- runif(n = S, min = 0, max = 1) r <- 1 for(i in 2:S){ r[i] <- r[i - 1] * k[i] } if(count){ - # If niche of species are independent, then each species must have at least one individual + # If niche of species are independent, then each species must have at + # least one individual r <- (r / sum(r)) * (N - S) r <- floor(r) + 1 } else { r <- (r / sum(r)) * N } - return(sort(r, decreasing = TRUE)) + return(sort(r, decreasing = TRUE)) } From 66cded0d1864b397412b92a02785f233ef5319b3 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Sun, 13 Dec 2015 14:10:31 -0200 Subject: [PATCH 29/40] Minimous change on document --- man/randAssort.Rd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/man/randAssort.Rd b/man/randAssort.Rd index 43f536b..edaa9b8 100644 --- a/man/randAssort.Rd +++ b/man/randAssort.Rd @@ -19,7 +19,7 @@ } \details{ - Abundance is a measure of the amount of each species and can be represented by number of individuals or biomass, dry weight or cover (Pielou 1975). If the argument \code{count} is \code{TRUE}, than each specie will have amount of individual in accordance with model rules. Note that some species may have zero individual if model rules result in hight dominance. But, since that premise of Random Assortment is that each specie has independent abundance, than each specie will have at least one individual. If \code{count} is \code{FALSE} (default), than each species will have a fraction of total abundance. The values randomly generated to represent amount of niche to be divided follow uniform distribution. All the fraction totalize more than 1, like described in Description section. Thus, relative abundance is calculated and multiplied to total abundance informed to result a correct abundance for each rank. + Abundance is a measure of the amount of each species and can be represented by number of individuals or biomass, dry weight or cover (Pielou 1975). If the argument \code{count} is \code{TRUE}, than each specie will have amount of individual in accordance with model rules. Note that some species may have zero individual if model rules result in hight dominance. But, since that premise of Random Assortment is that each specie has independent abundance, than each specie will have at least one individual. If \code{count} is \code{FALSE} (default), than each species will have a fraction of total abundance. The values randomly generated to represent amount of niche to be divided follow uniform distribution. All the fraction totalize more than 1, like described in 'Description' section. Thus, relative abundance is calculated and multiplied to total abundance informed to result a correct abundance for each rank. } \value{ From 110d5c0104a84ddc975ce669d400d2c2f5ad25fd Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Sun, 13 Dec 2015 14:11:09 -0200 Subject: [PATCH 30/40] Minimous change on introduction --- vignettes/quick-reference-nicheApport.Rnw | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vignettes/quick-reference-nicheApport.Rnw b/vignettes/quick-reference-nicheApport.Rnw index 4ba0a5c..fd3c3d6 100644 --- a/vignettes/quick-reference-nicheApport.Rnw +++ b/vignettes/quick-reference-nicheApport.Rnw @@ -24,7 +24,7 @@ \section{Introduction} -Species abundance distribution (SAD) is one of the basic description of ecological communities data \citep{mcgill_species_2007}. One way to represent the distribution of species abundance is to plot the ranked abundances from highest to lowest on x-axis and the abundance on y-axis (known too as MacArthur plot). Niche apportionment models were proposed to be a biological model to describe SAD \citep{tokeshi_niche_1990,tokeshi_power_1996,matthews_fitting_2014}. This models assume that total niche are sequentially divided between species \citep{tokeshi_niche_1990,matthews_fitting_2014}. There are proposed procedures to fit niche apportionment model to data \citep{tokeshi_niche_1990,bersier_species_1997,cassey_problem_2001,mouillot_how_2003}, but no one public tool to do this. This package simulate species rank abundance distributions (RAD) and use Monte Carlo approach, proposed by \cite{bersier_species_1997,cassey_problem_2001,mouillot_how_2003} to fit model to replicates data. +Species abundance distribution (SAD) is one of the basic description of ecological communities data \citep{mcgill_species_2007}. One way to represent the distribution of species abundance is to plot the ranked abundances from highest to lowest on x-axis and the abundance on y-axis (known too as MacArthur plot). Niche apportionment models were proposed to be a biological model to describe SAD \citep{tokeshi_niche_1990,tokeshi_power_1996,matthews_fitting_2014}. This models assume that total niche are sequentially divided between species \citep{tokeshi_niche_1990,matthews_fitting_2014}. There are proposed procedures to fit niche apportionment model to data \citep{tokeshi_niche_1990,bersier_species_1997,cassey_problem_2001,mouillot_how_2003}, but no one open source tool to do this. This package simulate species rank abundance distributions (RAD) and use Monte Carlo approach, proposed by \cite{bersier_species_1997,cassey_problem_2001,mouillot_how_2003} to fit model to replicates data. \section{Instalation} From d600e9637d96c560893b94ea9387606c9cd0706e Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 14 Dec 2015 03:49:43 -0200 Subject: [PATCH 31/40] Improve execution time --- R/dominanceDecay.R | 24 +++++++++++++++++------- R/powerFraction.R | 17 +++++++++++++---- 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/R/dominanceDecay.R b/R/dominanceDecay.R index 25e082f..85a4a5d 100644 --- a/R/dominanceDecay.R +++ b/R/dominanceDecay.R @@ -1,13 +1,23 @@ # Dominance Decay dominanceDecay <- function (N, S, count = FALSE){ k <- runif(n = S, min = 0, max = 1) - r <- N - r[1] <- ifelse(count, floor(r[1] * k[1]), r[1] * k[1]) - r[2] <- N - r[1] - for(i in 3:S){ - r <- sort(r, decreasing = FALSE) - r[i] <- ifelse(count, floor(r[i - 1] * k[i]), r[i - 1] * k[i]) - r[i - 1] <- abs(r[i - 1] - r[i]) + if(count){ + r <- floor(N * k[1]) + r[2] <- N - r[1] + for(i in 3:S){ + r <- sort(r, decreasing = FALSE) + r[i] <- floor(r[i - 1] * k[i]) + r[i - 1] <- abs(r[i - 1] - r[i]) + } + } + else{ + r <- N * k[1] + r[2] <- N - r[1] + for(i in 3:S){ + r <- sort(r, decreasing = FALSE) + r[i] <- r[i - 1] * k[i] + r[i - 1] <- abs(r[i - 1] - r[i]) + } } return(sort(r, decreasing = TRUE)) } diff --git a/R/powerFraction.R b/R/powerFraction.R index cd0ee85..a3a919d 100644 --- a/R/powerFraction.R +++ b/R/powerFraction.R @@ -2,10 +2,19 @@ powerFraction <- function (N, S, w = 0.2, count = FALSE){ k <- runif(n = S, min = 0, max = 1) r <- N - for(i in 2:S){ - j <- sample(x = 1:(i - 1), size = 1, prob = (r ^ w)) - r[i] <- ifelse(count, floor(r[j] * k[i]), r[j] * k[i]) - r[j] <- abs(r[j] - r[i]) + if(count){ + for(i in 2:S){ + j <- sample(x = 1:(i - 1), size = 1, prob = (r ^ w)) + r[i] <- floor(r[j] * k[i]) + r[j] <- abs(r[j] - r[i]) + } + } + else{ + for(i in 2:S){ + j <- sample(x = 1:(i - 1), size = 1, prob = (r ^ w)) + r[i] <- r[j] * k[i] + r[j] <- abs(r[j] - r[i]) + } } return(sort(r, decreasing = TRUE)) } From d210acf88b1fcbed5387af9d12ed76a38f675085 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 14 Dec 2015 03:54:07 -0200 Subject: [PATCH 32/40] Update functions to call powerFraction Once randFraction and MacArthurFraction are special case of powerFraction (w=0 and w=1, respectively) the first two call the last with specific w value. --- R/MacArthurFraction.R | 9 +-------- R/randFraction.R | 9 +-------- 2 files changed, 2 insertions(+), 16 deletions(-) diff --git a/R/MacArthurFraction.R b/R/MacArthurFraction.R index e9eb30f..8d64ebb 100644 --- a/R/MacArthurFraction.R +++ b/R/MacArthurFraction.R @@ -1,11 +1,4 @@ # MacArthur Fraction MacArthurFraction <- function (N, S, count = FALSE){ - k <- runif(n = S, min = 0, max = 1) - r <- N - for(i in 2:S){ - j <- sample(x = 1:(i - 1), size = 1, prob = (r / sum(r))) - r[i] <- ifelse(count, floor(r[j] * k[i]), r[j] * k[i]) - r[j] <- abs(r[j] - r[i]) - } - return(sort(r, decreasing = TRUE)) + return(powerFraction(N = N, S = S, w = 1, count = count)) } diff --git a/R/randFraction.R b/R/randFraction.R index 7aeaa95..bf0dda6 100644 --- a/R/randFraction.R +++ b/R/randFraction.R @@ -1,11 +1,4 @@ # Random Fraction randFraction <- function (N, S, count = FALSE){ - k <- runif(n = S, min = 0, max = 1) - r <- N - for(i in 2:S){ - j <- sample(x = 1:(i - 1), size = 1, prob = (r ^ 0 / sum(r ^ 0))) - r[i] <- ifelse(count, floor(r[j] * k[i]), r[j] * k[i]) - r[j] <- abs(r[j] - r[i]) - } - return(sort(r, decreasing = TRUE)) + return(powerFraction(N = N, S = S, w = 0, count = count)) } From 6bdc83e59bfb53e9ad08a03d32e32f2df7be377c Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 14 Dec 2015 03:58:39 -0200 Subject: [PATCH 33/40] Bug fix to values 0 when using continuous * Due limit of smaller double, sum function return 0 when x > ^-16. Update procedures removing sum and add multiplication by fraction complement. * Update speed runtime --- R/dominancePreemp.R | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/R/dominancePreemp.R b/R/dominancePreemp.R index 2b81611..78bfb95 100644 --- a/R/dominancePreemp.R +++ b/R/dominancePreemp.R @@ -2,9 +2,17 @@ dominancePreemp <- function (N, S, count = FALSE){ k <- runif(n = (S - 1), min = 0.5, max = 1) r <- N - for(i in 1:(S - 1)){ - r[i] <- ifelse(count, floor(r[i] * k[i]), r[i] * k[i]) - r[i + 1] <- N - sum(r[1:i]) + if(count){ + for(i in 1:(S-1)){ + r[i + 1] <- floor(r[i] * (1 - k[i])) + r[i] <- floor(r[i] * k[i]) + } + } + else{ + for(i in 1:(S-1)){ + r[i + 1] <- r[i] * (1 - k[i]) + r[i] <- r[i] * k[i] + } } return(sort(r, decreasing = TRUE)) } From b2f5db5ddb1268c1396dda76f87da04b1acd6c4a Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 14 Dec 2015 04:04:09 -0200 Subject: [PATCH 34/40] Unit randFraction and MacArthurFraction to powerFraction doc Once randFraction and MacArthurFraction are special case of powerFraction, documentation were joined and old removed --- man/MacArthurFraction.Rd | 50 ---------------------------------------- man/powerFraction.Rd | 12 ++++++++-- man/randFraction.Rd | 50 ---------------------------------------- 3 files changed, 10 insertions(+), 102 deletions(-) delete mode 100644 man/MacArthurFraction.Rd delete mode 100644 man/randFraction.Rd diff --git a/man/MacArthurFraction.Rd b/man/MacArthurFraction.Rd deleted file mode 100644 index fd28d98..0000000 --- a/man/MacArthurFraction.Rd +++ /dev/null @@ -1,50 +0,0 @@ -\name{MacArthurFraction} - -\alias{MacArthurFraction} - -\title{MacArthur Fraction Model} - -\description{ - Simulate ranked abundance distribution for MacArthur Fraction model. The total niche is sequential and randomly divided and probability of selection of a fraction is positively related with fraction length. First, total niche is divided randomly in two fraction. Then, one of this two fraction is selected, with larger fraction having more probability of selection than smaller one, and divided again in two fraction. One of this three fraction is selected, again with probability related with fraction length, and divided again in two fraction. This procedures is repeated until all species have a fraction of total niche. -} - -\usage{ - MacArthurFraction(N, S, count = FALSE) -} - -\arguments{ - \item{N}{Total abundance. See 'Details' for more information.} - \item{S}{Number of species.} - \item{count}{Specify if measure of abundance is number of individuals. See 'Details' for more information.} -} - -\details{ - Abundance is a measure of the amount of each species and can be represented by number of individuals or biomass, dry weight or cover (Pielou 1975). If the argument \code{count} is \code{TRUE}, then each specie will have amount of individual in accordance with model rules. Note that some species may have zero individual if model rules result in hight dominance. If \code{count} is \code{FALSE} (default), then each species will have a fraction of total abundance. The values randomly generated to represent amount of niche to be divided follow uniform distribution. -} - -\value{ - A vector of ranked species abundance from the most abundant (rank 1) to the least abundant (rank \code{S}). -} - -\references{ - Pielou, E. C. 1975. Ecological diversity. Wiley, New York. - - Tokeshi, M. 1990. Niche apportionment or random assortment: species abundance patterns revisited. \emph{J. Anim. Ecol.} 59: 1129-1146. -} - -\author{ - Mario J. Marques-Azevedo - - Maintainer: Mario J. Marques-Azevedo -} - -\seealso{ - For other models see \code{\link{dominanceDecay}}, \code{\link{dominancePreemp}}, \code{\link{randFraction}}, \code{\link{randAssort}} and \code{\link{powerFraction}}. - - For fit models see \code{\link{fitmodel}} and \code{\link{fitmodelCl}} to fit using parellel computation. To find best \code{w} parameter to \code{\link{powerFraction}} see \code{\link{findPFw}}. -} - -\examples{ - set.seed(42) - MacArthurFraction(100, 10) -} diff --git a/man/powerFraction.Rd b/man/powerFraction.Rd index c18fe9d..fc4e1c3 100644 --- a/man/powerFraction.Rd +++ b/man/powerFraction.Rd @@ -1,15 +1,19 @@ \name{powerFraction} \alias{powerFraction} +\alias{MacArthurFraction} +\alias{randFraction} \title{Power Fraction Model} \description{ - Simulate a ranked abundance distribution for Power Fraction model. The total niche is sequential and randomly divided and probability \emph{p} of selection of a fraction is positively related with fraction length \emph{x} as a power function (\emph{p*x^w}, where 0 < emph{w} < 1). Fractions length or abundances are weighted by parameter \emph{w} to define probability of selection of fractions. Then, larger fractions will have more probability of being selected, weighted by their abundances by parameter \emph{w}. First, total niche is divided randomly in two fraction. Then, one of this two fraction is selected, with probability of selection of each fraction emph{p*x^w}, and divided again in two fraction. One of this three fraction is selected, again with probability \emph{p*x^w} for each fraction, and divided again in two fraction. This procedures is repeated until all species have a fraction of total niche. + Simulate a ranked abundance distribution for Power Fraction, Random Fraction and MacArthur Fraction models. The total niche is sequential and randomly divided and probability \emph{p} of selection of a fraction is related with fraction length or abundance \emph{x} by \emph{w} as a power function (\emph{p*x^w}, where 0 <= emph{w} <= 1). First, total niche is divided randomly in two fraction. Then, one of this two fraction is selected, with probability of selection of each fraction emph{p*x^w}, and divided again in two fraction. One of this three fraction is selected, again with probability \emph{p*x^w} for each fraction, and divided again in two fraction. This procedures is repeated until all species have a fraction of total niche. } \usage{ + randFraction(N, S, count = FALSE) powerFraction(N, S, w = 0.2, count = FALSE) + MacArthurFraction(N, S, count = FALSE) } \arguments{ @@ -22,7 +26,7 @@ \details{ Abundance is a measure of the amount of each species and can be represented by number of individuals or biomass, dry weight or cover (Pielou 1975). If the argument \code{count} is \code{TRUE}, then each specie will have amount of individual in accordance with model rules. Note that some species may have zero individual if model rules result in hight dominance. If \code{count} is \code{FALSE} (default), then each species will have a fraction of total abundance. The values randomly generated to represent amount of niche to be divided follow uniform distribution. - The Random Fraction and MacArthur Fraction models are special cases of Power fraction model. When \emph{w} = 0, Power Fraction correspond to Random Fraction and when \emph{w} = 1 correspond to MacArthur Fraction. Tokesh (1996) proposed this model as alternative to species-rich communities in face of other model fit well in species-poor communities. The author verified that Power Fraction with \emph{w} = 0.2 fit well to many species-rich communities analysed. + The Random Fraction and MacArthur Fraction models are special cases of Power fraction model. When \emph{w} = 0, Power Fraction correspond to Random Fraction and the probability of selection of fractions are independently of fraction length (abundance). In this case all fraction have the same probability of selection. When \emph{w} = 1, Power Fraction correspond to MacArthur Fraction and fractions have probability of selection weighted by their abundances. Values of \emph{w} between 0 and 1 (Power Fraction), the probability selection of fractions are weighted by \emph{w} as a power of their abundances (\emph{p*x^w}). Tokesh (1996) proposed this model as alternative to species-rich communities in face of other model fit well in species-poor communities. The author verified that Power Fraction with \emph{w} = 0.2 fit well to many species-rich communities analysed. The function \code{randFraction} and \code{MacArthurFraction} call \code{powerFraction} internally with respective \emph{w} value (0 and 1). } \value{ @@ -49,5 +53,9 @@ \examples{ set.seed(42) + randFraction(100, 10) + powerFraction(100, 10, w = 0.2) + + MacArthurFraction(100, 10) } diff --git a/man/randFraction.Rd b/man/randFraction.Rd deleted file mode 100644 index e600d92..0000000 --- a/man/randFraction.Rd +++ /dev/null @@ -1,50 +0,0 @@ -\name{randFraction} - -\alias{randFraction} - -\title{Random Fraction Model} - -\description{ - Simulate ranked abundance distribution for Random Fraction model. The sequential selection and division of total niche is random. First, total niche is divided randomly in two fraction. Then, one of this two fraction is selected randomly and divided randomly again in two fraction. One of this three fraction is selected and divided randomly again in two fraction and son on until all species have a fraction of total niche. -} - -\usage{ - randFraction(N, S, count = FALSE) -} - -\arguments{ - \item{N}{Total abundance. See 'Details' for more information.} - \item{S}{Number of species.} - \item{count}{Specify if measure of abundance is number of individuals. See 'Details' for more information.} -} - -\details{ - Abundance is a measure of the amount of each species and can be represented by number of individuals, biomass, dry weight or cover (Pielou 1975). If the argument \code{count} is \code{TRUE}, then each specie will have amount of individual in accordance with model rules. Note that some species may have zero individual if model rules result in hight dominance. If \code{count} is \code{FALSE} (default), than each species will have a fraction of total abundance. The values randomly generated to represent amount of niche to be divided follow uniform distribution. -} - -\value{ - A vector of ranked species abundance from the most abundant (rank 1) to the least abundant (rank \code{S}). -} - -\references{ - Pielou, E. C. 1975. Ecological diversity. Wiley, New York. - - Tokeshi, M. 1990. Niche apportionment or random assortment: species abundance patterns revisited. \emph{J. Anim. Ecol.} 59: 1129-1146. -} - -\author{ - Mario J. Marques-Azevedo - - Maintainer: Mario J. Marques-Azevedo -} - -\seealso{ - For others models see \code{\link{dominanceDecay}}, \code{\link{dominancePreemp}}, \code{\link{MacArthurFraction}}, \code{\link{randAssort}} and \code{\link{powerFraction}}. - - For fit models see \code{\link{fitmodel}} and \code{\link{fitmodelCl}} to fit using parellel computation. To find best \code{w} parameter to \code{\link{powerFraction}} see \code{\link{findPFw}}. -} - -\examples{ - set.seed(42) - randFraction(100, 10) -} From 513f827210665f4fc7c6bae73f233cad9e140aff Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 14 Dec 2015 04:09:47 -0200 Subject: [PATCH 35/40] Update NEWS file --- NEWS | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/NEWS b/NEWS index 6a3ed09..e0f1110 100644 --- a/NEWS +++ b/NEWS @@ -1,5 +1,8 @@ 1.1.0 (next release) -* Add news arguments to control plots color and line type +* Improve runtime of functions +* Joined documentation of randFraction and MacArthurFraction to powerFraction +* Bug fix to dominancePreemp that return ranks with 0 when using continuous +* Add news arguments to control plots colours and line type * Bux fix to plot and fit discrete data * Add vignette 'Quick Reference for nicheApport' * Update documentation From a717a57ea501b29f87b1be7be247084f66c2aa82 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 14 Dec 2015 04:28:45 -0200 Subject: [PATCH 36/40] Fix range.col defaults and vars call --- R/nicheApport-methods.R | 12 +++++++----- man/fitmodel-class.Rd | 2 +- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/R/nicheApport-methods.R b/R/nicheApport-methods.R index 7d7cbf7..bd9368d 100644 --- a/R/nicheApport-methods.R +++ b/R/nicheApport-methods.R @@ -32,12 +32,13 @@ setMethod(f = "plot", signature = "fitmodel", }) setMethod(f = "lines", signature = "fitmodel", - definition = function(x, stat = "mean", base = NULL, range = FALSE, range.lty = 2, range.col = "black", ...){ + definition = function(x, stat = "mean", base = NULL, range = FALSE, range.lty = 2, range.col = NULL, ...){ dots <- list(...) if(!stat %in% c("mean", "variance")) stop("'stat' parameter must be 'mean' or 'variance'") if(!"col" %in% names(dots)) dots$col <- "blue" + if(is.null(range.col)) range.col <- dots$col sim.sta <- x@sim.stats[stat, ] sim.min <- x@sim.range[[stat]]["min", ] @@ -58,7 +59,7 @@ setMethod(f = "lines", signature = "fitmodel", setMethod(f = "qqplot", signature = "fitmodel", definition = function(x, stat = "mean", base = NULL, range = FALSE, - qqline = TRUE, range.lty = 2, range.col = "black", + qqline = TRUE, range.lty = 2, range.col = NULL, in.col = "black", out.col = "grey70", ...){ dots <- list(...) if(!stat %in% c("mean", "variance")) @@ -76,17 +77,18 @@ setMethod(f = "qqplot", signature = "fitmodel", } if(!"lty" %in% names(dots)) dots$lty <- 1 if(!"col" %in% names(dots)) dots$col <- "black" + if(is.null(range.col)) range.col <- dots$col obs.sta <- x@obs.stats[stat, ] sim.sta <- x@sim.stats[stat, ] sim.min <- x@sim.range[[stat]]["min", ] sim.max <- x@sim.range[[stat]]["max", ] - + min.fil <- sim.min > 0 + max.fil <- sim.max > 0 + if(!is.null(base)){ obs.sta <- log(obs.sta, base) sim.sta <- log(sim.sta[sim.sta > 0], base) - min.fil <- sim.min > 0 - max.fil <- sim.max > 0 sim.min[min.fil] <- log(sim.min[min.fil], base) sim.max[max.fil] <- log(sim.max[max.fil], base) } diff --git a/man/fitmodel-class.Rd b/man/fitmodel-class.Rd index 78ff73e..b0f93e6 100644 --- a/man/fitmodel-class.Rd +++ b/man/fitmodel-class.Rd @@ -72,7 +72,7 @@ \item{out.col}{Character informing the color of observed non fitted values (out of simulated range).} \item{qqline}{Logical informing if qqline must be plotted.} \item{range}{Logical informing if minimum and maximum line must be plotted.} - \item{range.col}{Character informing the color of range plot.} + \item{range.col}{Character informing the color of range plot. When \code{NULL} (default) is equal to \code{col}.} \item{range.lty}{Numerical informing the line type of range plot.} \item{stat}{Character informing if line must be plotted using mean (\code{"mean"}) or variance (\code{"variance"}) of model simulation.} }} From 6350653a5ffa8989abb945ea4744aee24f573bf3 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 14 Dec 2015 15:33:53 -0200 Subject: [PATCH 37/40] Add knitr and vignette --- DESCRIPTION | 3 +++ 1 file changed, 3 insertions(+) diff --git a/DESCRIPTION b/DESCRIPTION index e926ead..01caf84 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -8,6 +8,9 @@ License: GPL-2 Encoding: UTF-8 Depends: parallel, methods Imports: graphics +Suggests: knitr +VignetteBuilder: knitr +BuildVignettes: yes NeedsCompilation: no Version: 1.1.0 Date: 2015-12-07 From a705ad64f5212c6f8e57920ad153f0dd91f94fd5 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 14 Dec 2015 15:34:27 -0200 Subject: [PATCH 38/40] Add VignetteIndexEntry --- vignettes/quick-reference-nicheApport.Rnw | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/vignettes/quick-reference-nicheApport.Rnw b/vignettes/quick-reference-nicheApport.Rnw index fd3c3d6..11ff141 100644 --- a/vignettes/quick-reference-nicheApport.Rnw +++ b/vignettes/quick-reference-nicheApport.Rnw @@ -8,9 +8,11 @@ \usepackage{url} \usepackage{setspace} % Line spacing +%\VignetteIndexEntry{Quick reference for nicheApport package usage} +%\VignetteEngine{knitr::knitr} \title{Quick reference for \code{nicheApport} package usage} \author{Mario J. Marques-Azevedo} -\date{December 11, 2015} +\date{December 14, 2015} \newcommand{\code}[1]{\texttt{#1}} % Command code @@ -20,6 +22,10 @@ \begin{document} +<>= +library(knitr) +@ + \maketitle \section{Introduction} From 0a8b0b725414f072c0b56fc979e8b296482a6b72 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 14 Dec 2015 15:39:35 -0200 Subject: [PATCH 39/40] Update release 1.1.0 data --- NEWS | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NEWS b/NEWS index e0f1110..686f412 100644 --- a/NEWS +++ b/NEWS @@ -1,4 +1,4 @@ -1.1.0 (next release) +1.1.0 (2015-12-14) * Improve runtime of functions * Joined documentation of randFraction and MacArthurFraction to powerFraction * Bug fix to dominancePreemp that return ranks with 0 when using continuous From e0277f88ac5aa673e67ed2dace08144ac336be77 Mon Sep 17 00:00:00 2001 From: "Mario J. Marques-Azevedo" Date: Mon, 14 Dec 2015 15:51:49 -0200 Subject: [PATCH 40/40] Minimous text align --- man/powerFraction.Rd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/man/powerFraction.Rd b/man/powerFraction.Rd index fc4e1c3..88ee376 100644 --- a/man/powerFraction.Rd +++ b/man/powerFraction.Rd @@ -11,7 +11,7 @@ } \usage{ - randFraction(N, S, count = FALSE) + randFraction(N, S, count = FALSE) powerFraction(N, S, w = 0.2, count = FALSE) MacArthurFraction(N, S, count = FALSE) }